@volter/browser-substrate 0.1.103 → 0.1.105

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/catalog/demand-input.json +133 -0
  2. package/dist/boot-screen.d.ts +2 -0
  3. package/dist/boot-screen.d.ts.map +1 -1
  4. package/dist/boot-screen.js +1 -1
  5. package/dist/boot-screen.js.map +1 -1
  6. package/dist/cli/archive.d.ts +1 -0
  7. package/dist/cli/archive.d.ts.map +1 -1
  8. package/dist/cli/archive.js +4 -4
  9. package/dist/cli/archive.js.map +1 -1
  10. package/dist/cli/build.d.ts +5 -1
  11. package/dist/cli/build.d.ts.map +1 -1
  12. package/dist/cli/build.js +21 -2
  13. package/dist/cli/build.js.map +1 -1
  14. package/dist/cli/cache-root.d.ts +7 -0
  15. package/dist/cli/cache-root.d.ts.map +1 -0
  16. package/dist/cli/cache-root.js +24 -0
  17. package/dist/cli/cache-root.js.map +1 -0
  18. package/dist/cli/companions.d.ts +1 -1
  19. package/dist/cli/companions.d.ts.map +1 -1
  20. package/dist/cli/companions.js +30 -16
  21. package/dist/cli/companions.js.map +1 -1
  22. package/dist/cli/dependency-plan-build.d.ts +4 -0
  23. package/dist/cli/dependency-plan-build.d.ts.map +1 -1
  24. package/dist/cli/dependency-plan-build.js +111 -30
  25. package/dist/cli/dependency-plan-build.js.map +1 -1
  26. package/dist/cli/docker-build.d.ts +1 -0
  27. package/dist/cli/docker-build.d.ts.map +1 -1
  28. package/dist/cli/docker-build.js +4 -4
  29. package/dist/cli/docker-build.js.map +1 -1
  30. package/dist/cli/dry-run.d.ts +4 -4
  31. package/dist/cli/dry-run.d.ts.map +1 -1
  32. package/dist/cli/dry-run.js +10 -9
  33. package/dist/cli/dry-run.js.map +1 -1
  34. package/dist/cli/generated-code.d.ts +2 -1
  35. package/dist/cli/generated-code.d.ts.map +1 -1
  36. package/dist/cli/generated-code.js +46 -16
  37. package/dist/cli/generated-code.js.map +1 -1
  38. package/dist/cli/host-build.d.ts +1 -0
  39. package/dist/cli/host-build.d.ts.map +1 -1
  40. package/dist/cli/host-build.js +10 -9
  41. package/dist/cli/host-build.js.map +1 -1
  42. package/dist/cli/host-managers.d.ts +3 -1
  43. package/dist/cli/host-managers.d.ts.map +1 -1
  44. package/dist/cli/host-managers.js +7 -3
  45. package/dist/cli/host-managers.js.map +1 -1
  46. package/dist/cli/image-layers.d.ts.map +1 -1
  47. package/dist/cli/image-layers.js +5 -2
  48. package/dist/cli/image-layers.js.map +1 -1
  49. package/dist/cli/main.d.ts +5 -1
  50. package/dist/cli/main.d.ts.map +1 -1
  51. package/dist/cli/main.js +97 -34
  52. package/dist/cli/main.js.map +1 -1
  53. package/dist/cli/pack-publication.d.ts +2 -2
  54. package/dist/cli/pack-publication.d.ts.map +1 -1
  55. package/dist/cli/pack-publication.js +3 -3
  56. package/dist/cli/pack-publication.js.map +1 -1
  57. package/dist/cli/package-pack.d.ts +1 -1
  58. package/dist/cli/package-pack.d.ts.map +1 -1
  59. package/dist/cli/package-pack.js +7 -4
  60. package/dist/cli/package-pack.js.map +1 -1
  61. package/dist/cli/package-packs.d.ts +1 -0
  62. package/dist/cli/package-packs.d.ts.map +1 -1
  63. package/dist/cli/package-packs.js +84 -14
  64. package/dist/cli/package-packs.js.map +1 -1
  65. package/dist/cli/plan-tarballs.d.ts +1 -0
  66. package/dist/cli/plan-tarballs.d.ts.map +1 -1
  67. package/dist/cli/plan-tarballs.js +6 -3
  68. package/dist/cli/plan-tarballs.js.map +1 -1
  69. package/dist/cli/preparation-memory.d.ts +17 -0
  70. package/dist/cli/preparation-memory.d.ts.map +1 -0
  71. package/dist/cli/preparation-memory.js +367 -0
  72. package/dist/cli/preparation-memory.js.map +1 -0
  73. package/dist/cli/project-build.d.ts +1 -0
  74. package/dist/cli/project-build.d.ts.map +1 -1
  75. package/dist/cli/project-build.js +100 -71
  76. package/dist/cli/project-build.js.map +1 -1
  77. package/dist/cli/provision-catalog.d.ts +49 -0
  78. package/dist/cli/provision-catalog.d.ts.map +1 -0
  79. package/dist/cli/provision-catalog.js +72 -0
  80. package/dist/cli/provision-catalog.js.map +1 -0
  81. package/dist/cli/provision-demand.d.ts +45 -0
  82. package/dist/cli/provision-demand.d.ts.map +1 -0
  83. package/dist/cli/provision-demand.js +208 -0
  84. package/dist/cli/provision-demand.js.map +1 -0
  85. package/dist/cli/rolldown-binding.d.ts +1 -1
  86. package/dist/cli/rolldown-binding.d.ts.map +1 -1
  87. package/dist/cli/rolldown-binding.js +8 -4
  88. package/dist/cli/rolldown-binding.js.map +1 -1
  89. package/dist/cli/serve.d.ts +3 -0
  90. package/dist/cli/serve.d.ts.map +1 -1
  91. package/dist/cli/serve.js +9 -2
  92. package/dist/cli/serve.js.map +1 -1
  93. package/dist/index.d.ts +2 -0
  94. package/dist/index.d.ts.map +1 -1
  95. package/dist/index.js +75 -31
  96. package/dist/index.js.map +1 -1
  97. package/dist/origin-reset.d.ts +4 -0
  98. package/dist/origin-reset.d.ts.map +1 -0
  99. package/dist/origin-reset.js +76 -0
  100. package/dist/origin-reset.js.map +1 -0
  101. package/dist/program-dom.d.ts +2 -0
  102. package/dist/program-dom.d.ts.map +1 -1
  103. package/dist/program-dom.js +11 -1
  104. package/dist/program-dom.js.map +1 -1
  105. package/dist/program-types.d.ts +2 -0
  106. package/dist/program-types.d.ts.map +1 -1
  107. package/dist/shell/assets/browser-opfs-filesystem-worker-CmF6UKMW.js +3 -0
  108. package/dist/shell/assets/browser-sandbox-bridge-C8nlSsT2.js +237 -0
  109. package/dist/shell/assets/{filesystem-host-DJbFuokb.js → filesystem-host-BzPlXSri.js} +1 -1
  110. package/dist/shell/assets/filesystem-host-Pq9IHKRx.js +3 -0
  111. package/dist/shell/assets/filesystem-worker-CC3pSXUP.js +5 -0
  112. package/dist/shell/assets/{fork-worker-BXY2kfdX.js → fork-worker-4YKQ4KTo.js} +1 -1
  113. package/dist/shell/assets/{node-execution-worker-7e8e0c5321ca0d10.js → node-execution-worker-3ddf5efbaa427e9d.js} +8 -8
  114. package/dist/shell/assets/{sandbox-bMeKqKBn.js → sandbox-mhFzIWaQ.js} +1 -1
  115. package/dist/shell/assets/{shell-DLIQ6jHu.js → shell-BZbhxnju.js} +763 -757
  116. package/dist/shell/assets/worker-BmHEnCyv.js +816 -0
  117. package/dist/shell/assets/{worker-program-worker-B4OcKVtV.js → worker-program-worker-DueMwljE.js} +10 -10
  118. package/dist/shell/brand/fonts/Geist-Variable.woff2 +0 -0
  119. package/dist/shell/brand/fonts/GeistMono-Variable.woff2 +0 -0
  120. package/dist/shell/brand/fonts/InstrumentSerif-Italic.woff2 +0 -0
  121. package/dist/shell/brand/fonts/InstrumentSerif-Regular.woff2 +0 -0
  122. package/dist/shell/brand/icons/app-window.svg +1 -0
  123. package/dist/shell/brand/icons/at-sign.svg +1 -0
  124. package/dist/shell/brand/icons/box.svg +1 -0
  125. package/dist/shell/brand/icons/chevron-right.svg +1 -0
  126. package/dist/shell/brand/icons/folder.svg +1 -0
  127. package/dist/shell/brand/icons/info.svg +1 -0
  128. package/dist/shell/brand/icons/key-round.svg +1 -0
  129. package/dist/shell/brand/icons/link.svg +1 -0
  130. package/dist/shell/brand/icons/monitor.svg +1 -0
  131. package/dist/shell/brand/icons/plus.svg +1 -0
  132. package/dist/shell/brand/icons/rotate-ccw.svg +1 -0
  133. package/dist/shell/brand/icons/share-2.svg +1 -0
  134. package/dist/shell/brand/icons/square-arrow-out-up-right.svg +1 -0
  135. package/dist/shell/brand/icons/terminal.svg +1 -0
  136. package/dist/shell/brand/icons/x.svg +1 -0
  137. package/dist/shell/brand/substrate.svg +1 -0
  138. package/dist/shell/brand/tokens.css +211 -0
  139. package/dist/shell/brand/wordmark.svg +1 -0
  140. package/dist/shell/index.html +5 -3
  141. package/dist/shell/node-execution-worker.js +16 -13
  142. package/dist/shell/node-host.html +2 -0
  143. package/dist/shell/python-execution-worker.js +15 -12
  144. package/dist/shell/python-host.html +2 -0
  145. package/dist/shell/python-runtime-snapshot.bin +0 -0
  146. package/dist/shell/python-runtime-snapshot.json +1 -1
  147. package/dist/shell/sandbox.html +4 -2
  148. package/dist/toolbar-styles.generated.d.ts +1 -1
  149. package/dist/toolbar-styles.generated.d.ts.map +1 -1
  150. package/dist/toolbar-styles.generated.js +1 -1
  151. package/dist/toolbar-styles.generated.js.map +1 -1
  152. package/dist/toolbar.d.ts.map +1 -1
  153. package/dist/toolbar.js +3 -1
  154. package/dist/toolbar.js.map +1 -1
  155. package/package.json +1 -1
  156. package/dist/shell/assets/browser-opfs-filesystem-worker-k2CPzPBU.js +0 -3
  157. package/dist/shell/assets/browser-sandbox-bridge-BJbQoc4f.js +0 -237
  158. package/dist/shell/assets/filesystem-host-yMcJuvmT.js +0 -3
  159. package/dist/shell/assets/filesystem-worker-BbsBhZ9p.js +0 -5
  160. package/dist/shell/assets/worker-Ce8bBwSJ.js +0 -816
@@ -1,4 +1,4 @@
1
- var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __commonJS=(cb2,mod)=>function __require2(){try{return mod||(0,cb2[__getOwnPropNames(cb2)[0]])((mod={exports:{}}).exports,mod),mod.exports}catch(e2){throw mod=0,e2}};var __copyProps=(to2,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to2,key)&&key!==except)__defProp(to2,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to2};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_sprintf=__commonJS({"../../node_modules/sprintf-js/src/sprintf.js"(exports){!(function(){"use strict";var re2={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function sprintf(key){return sprintf_format(sprintf_parse(key),arguments)}function vsprintf(fmt,argv){return sprintf.apply(null,[fmt].concat(argv||[]))}function sprintf_format(parse_tree,argv){var cursor=1,tree_length=parse_tree.length,arg,output="",i10,k10,ph2,pad,pad_character,pad_length,is_positive,sign3;for(i10=0;i10<tree_length;i10++){if(typeof parse_tree[i10]==="string"){output+=parse_tree[i10]}else if(typeof parse_tree[i10]==="object"){ph2=parse_tree[i10];if(ph2.keys){arg=argv[cursor];for(k10=0;k10<ph2.keys.length;k10++){if(arg==void 0){throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"',ph2.keys[k10],ph2.keys[k10-1]))}arg=arg[ph2.keys[k10]]}}else if(ph2.param_no){arg=argv[ph2.param_no]}else{arg=argv[cursor++]}if(re2.not_type.test(ph2.type)&&re2.not_primitive.test(ph2.type)&&arg instanceof Function){arg=arg()}if(re2.numeric_arg.test(ph2.type)&&(typeof arg!=="number"&&isNaN(arg))){throw new TypeError(sprintf("[sprintf] expecting number but found %T",arg))}if(re2.number.test(ph2.type)){is_positive=arg>=0}switch(ph2.type){case"b":arg=parseInt(arg,10).toString(2);break;case"c":arg=String.fromCharCode(parseInt(arg,10));break;case"d":case"i":arg=parseInt(arg,10);break;case"j":arg=JSON.stringify(arg,null,ph2.width?parseInt(ph2.width):0);break;case"e":arg=ph2.precision?parseFloat(arg).toExponential(ph2.precision):parseFloat(arg).toExponential();break;case"f":arg=ph2.precision?parseFloat(arg).toFixed(ph2.precision):parseFloat(arg);break;case"g":arg=ph2.precision?String(Number(arg.toPrecision(ph2.precision))):parseFloat(arg);break;case"o":arg=(parseInt(arg,10)>>>0).toString(8);break;case"s":arg=String(arg);arg=ph2.precision?arg.substring(0,ph2.precision):arg;break;case"t":arg=String(!!arg);arg=ph2.precision?arg.substring(0,ph2.precision):arg;break;case"T":arg=Object.prototype.toString.call(arg).slice(8,-1).toLowerCase();arg=ph2.precision?arg.substring(0,ph2.precision):arg;break;case"u":arg=parseInt(arg,10)>>>0;break;case"v":arg=arg.valueOf();arg=ph2.precision?arg.substring(0,ph2.precision):arg;break;case"x":arg=(parseInt(arg,10)>>>0).toString(16);break;case"X":arg=(parseInt(arg,10)>>>0).toString(16).toUpperCase();break}if(re2.json.test(ph2.type)){output+=arg}else{if(re2.number.test(ph2.type)&&(!is_positive||ph2.sign)){sign3=is_positive?"+":"-";arg=arg.toString().replace(re2.sign,"")}else{sign3=""}pad_character=ph2.pad_char?ph2.pad_char==="0"?"0":ph2.pad_char.charAt(1):" ";pad_length=ph2.width-(sign3+arg).length;pad=ph2.width?pad_length>0?pad_character.repeat(pad_length):"":"";output+=ph2.align?sign3+arg+pad:pad_character==="0"?sign3+pad+arg:pad+sign3+arg}}}return output}var sprintf_cache=Object.create(null);function sprintf_parse(fmt){if(sprintf_cache[fmt]){return sprintf_cache[fmt]}var _fmt=fmt,match2,parse_tree=[],arg_names=0;while(_fmt){if((match2=re2.text.exec(_fmt))!==null){parse_tree.push(match2[0])}else if((match2=re2.modulo.exec(_fmt))!==null){parse_tree.push("%")}else if((match2=re2.placeholder.exec(_fmt))!==null){if(match2[2]){arg_names|=1;var field_list=[],replacement_field=match2[2],field_match=[];if((field_match=re2.key.exec(replacement_field))!==null){field_list.push(field_match[1]);while((replacement_field=replacement_field.substring(field_match[0].length))!==""){if((field_match=re2.key_access.exec(replacement_field))!==null){field_list.push(field_match[1])}else if((field_match=re2.index_access.exec(replacement_field))!==null){field_list.push(field_match[1])}else{throw new SyntaxError("[sprintf] failed to parse named argument key")}}}else{throw new SyntaxError("[sprintf] failed to parse named argument key")}match2[2]=field_list}else{arg_names|=2}if(arg_names===3){throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported")}parse_tree.push({placeholder:match2[0],param_no:match2[1],keys:match2[2],sign:match2[3],pad_char:match2[4],align:match2[5],width:match2[6],precision:match2[7],type:match2[8]})}else{throw new SyntaxError("[sprintf] unexpected placeholder")}_fmt=_fmt.substring(match2[0].length)}return sprintf_cache[fmt]=parse_tree}if(typeof exports!=="undefined"){exports["sprintf"]=sprintf;exports["vsprintf"]=vsprintf}if(typeof window!=="undefined"){window["sprintf"]=sprintf;window["vsprintf"]=vsprintf;if(typeof define==="function"&&define["amd"]){define(function(){return{"sprintf":sprintf,"vsprintf":vsprintf}})}}})()}});var BROWSER_RUNTIME_CAPABILITIES=["browser.open-url","filesystem.atomic-file-replace","filesystem.private-storage","filesystem.project","media.webcodecs","network.loopback-http","network.raw-tls-relay","process.background-jobs","process.pty","process.spawn","threads.pthread"];var BROWSER_RUNTIME_PROFILE=Object.freeze({version:1,capabilities:BROWSER_RUNTIME_CAPABILITIES});var BrowserPackContractError=class extends Error{category;path;constructor(category,path3,message){super(`${path3}: ${message}`);this.name="BrowserPackContractError";this.category=category;this.path=path3}};var BROWSER_PACK_PART_MAX_BYTES=128*1024*1024;function canonicalBrowserPackJson(value){return JSON.stringify(canonical(value,"$"))}function canonical(value,path3){if(value===null||typeof value==="string"||typeof value==="boolean")return value;if(typeof value==="number"){if(!Number.isFinite(value))fail("invalid-manifest",path3,"contains a non-finite number");return value}if(Array.isArray(value))return value.map((item,index2)=>canonical(item,`${path3}[${index2}]`));if(typeof value!=="object")fail("invalid-manifest",path3,"contains an unsupported value");if(Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null)fail("invalid-manifest",path3,"must contain only plain JSON objects");const result={};for(const key of Object.keys(value).sort())result[key]=canonical(value[key],`${path3}.${key}`);return result}function fail(category,path3,message){throw new BrowserPackContractError(category,path3,message)}var BrowserPackArchiveError=class extends Error{constructor(category,message){super(message);this.category=category;this.name="BrowserPackArchiveError"}category};var TAR_BLOCK=512;var MAX_PATH_BYTES=4096;var decoder=new TextDecoder("utf-8",{fatal:true});async function extractBrowserPackArchive(bytes2,artifact,signal){if(!artifact.archive||artifact.expandedBytes===void 0||artifact.files===void 0){throw new BrowserPackArchiveError("invalid-archive","Archive bounds are missing from the pack manifest.")}cancelled(signal);let entries;if(artifact.archive==="zip")entries=await extractZip(bytes2,artifact.expandedBytes,artifact.files,signal);else{const tar=artifact.archive==="tar+gzip"?await decompress(bytes2,"gzip",tarStreamLimit(artifact.expandedBytes,artifact.files),signal):bytes2;entries=extractTar(tar,artifact.expandedBytes,artifact.files,signal)}validateTree(entries,artifact.files,artifact.expandedBytes);return entries}function extractTar(bytes2,expandedLimit,fileLimit,signal){const entries=[];const hardlinks=[];let offset2=0;let zeroBlocks=0;let longPath;let longLink;let paxPath;let paxLink;let fileBytes=0;while(offset2+TAR_BLOCK<=bytes2.byteLength){cancelled(signal);const header=bytes2.subarray(offset2,offset2+TAR_BLOCK);offset2+=TAR_BLOCK;if(header.every(byte=>byte===0)){zeroBlocks+=1;if(zeroBlocks===2)break;continue}if(zeroBlocks!==0)fail2("invalid-archive","A tar entry follows its end marker.");verifyTarChecksum(header);const size=tarNumber(header,124,12,"size");const padded=Math.ceil(size/TAR_BLOCK)*TAR_BLOCK;if(!Number.isSafeInteger(size)||offset2+padded>bytes2.byteLength)fail2("invalid-archive","A tar entry is truncated.");const data2=bytes2.subarray(offset2,offset2+size);offset2+=padded;const type2=String.fromCharCode(header[156]||48);const rawName=tarText(header,0,100);const prefix2=tarText(header,257,6).startsWith("ustar")?tarText(header,345,155):"";const headerPath=prefix2?`${prefix2}/${rawName}`:rawName;if(type2==="L"||type2==="K"){const value=decodeNullTerminated(data2);if(type2==="L")longPath=value;else longLink=value;continue}if(type2==="x"){const pax=parsePax(data2);paxPath=pax.path;paxLink=pax.linkpath;continue}if(type2==="g")fail2("unsupported-entry","Global PAX attributes are not supported in pack archives.");const effectivePath=paxPath??longPath??headerPath;const directory2=type2==="5"||effectivePath.endsWith("/");const path3=safePath(directory2?effectivePath.replace(/\/+$/u,""):effectivePath);const link2=paxLink??longLink??tarText(header,157,100);longPath=longLink=paxPath=paxLink=void 0;const mode=safeMode(tarNumber(header,100,8,"mode"),type2==="5"?493:420);if(directory2){if(size!==0)fail2("invalid-archive",`Directory ${path3} contains data.`);entries.push({path:path3,type:"directory",mode})}else if(type2==="0"||type2==="\0"||type2==="7"){fileBytes+=size;if(fileBytes>expandedLimit)fail2("expansion-limit",`Archive expands beyond ${expandedLimit} declared bytes.`);entries.push({path:path3,type:"file",mode,content:data2.slice()})}else if(type2==="2"){entries.push({path:path3,type:"symlink",mode,target:safeSymlink(path3,link2)})}else if(type2==="1"){hardlinks.push({path:path3,mode,target:safePath(link2)})}else fail2("unsupported-entry",`Tar entry ${path3} has unsupported type ${JSON.stringify(type2)}.`);if(entries.length+hardlinks.length>entryLimit(fileLimit))fail2("expansion-limit","Archive contains too many directory or file entries for its declared file count.")}if(zeroBlocks<2||offset2!==bytes2.byteLength&&bytes2.subarray(offset2).some(byte=>byte!==0)){fail2("invalid-archive","Tar archive has no complete end marker or has trailing data.")}if(longPath!==void 0||longLink!==void 0||paxPath!==void 0||paxLink!==void 0)fail2("invalid-archive","Tar archive ends after orphaned metadata.");for(const link2 of hardlinks){const target=entries.find(entry=>entry.path===link2.target&&entry.type==="file");if(!target)fail2("unsupported-entry",`Hard link ${link2.path} does not name a regular file inside the archive.`);fileBytes+=target.content.byteLength;if(fileBytes>expandedLimit)fail2("expansion-limit",`Archive expands beyond ${expandedLimit} declared bytes.`);entries.push({path:link2.path,type:"file",mode:link2.mode,content:target.content.slice()})}return entries}async function extractZip(bytes2,expandedLimit,fileLimit,signal){const end=findZipEnd(bytes2);const view=new DataView(bytes2.buffer,bytes2.byteOffset,bytes2.byteLength);if(view.getUint16(end+4,true)!==0||view.getUint16(end+6,true)!==0)fail2("unsupported-entry","Multi-disk ZIP archives are not supported.");const count=view.getUint16(end+10,true);const centralSize=view.getUint32(end+12,true);const centralOffset=view.getUint32(end+16,true);const comment=view.getUint16(end+20,true);if(view.getUint16(end+8,true)!==count||end+22+comment!==bytes2.byteLength||centralOffset+centralSize!==end)fail2("invalid-archive","ZIP central directory is invalid.");if(count>entryLimit(fileLimit))fail2("expansion-limit","ZIP contains too many directory or file entries for its declared file count.");const entries=[];const ranges=[];let cursor=centralOffset;let fileBytes=0;for(let index2=0;index2<count;index2+=1){cancelled(signal);requireRange(bytes2,cursor,46);if(view.getUint32(cursor,true)!==33639248)fail2("invalid-archive","ZIP central directory entry is invalid.");const madeBy=view.getUint16(cursor+4,true)>>>8;const flags=view.getUint16(cursor+8,true);const method=view.getUint16(cursor+10,true);const crc=view.getUint32(cursor+16,true);const compressed=view.getUint32(cursor+20,true);const size=view.getUint32(cursor+24,true);const nameLength=view.getUint16(cursor+28,true);const extraLength=view.getUint16(cursor+30,true);const commentLength=view.getUint16(cursor+32,true);const external=view.getUint32(cursor+38,true);const localOffset=view.getUint32(cursor+42,true);requireRange(bytes2,cursor+46,nameLength+extraLength+commentLength);const name=decodeName(bytes2.subarray(cursor+46,cursor+46+nameLength),flags);cursor+=46+nameLength+extraLength+commentLength;if((flags&~2048)!==0||method!==0&&method!==8)fail2("unsupported-entry",`ZIP entry ${name} uses unsupported features.`);if(localOffset>=centralOffset)fail2("invalid-archive",`ZIP entry ${name} overlaps its directory.`);requireRange(bytes2,localOffset,30);if(view.getUint32(localOffset,true)!==67324752)fail2("invalid-archive",`ZIP entry ${name} has an invalid local header.`);const localFlags=view.getUint16(localOffset+6,true);const localMethod=view.getUint16(localOffset+8,true);const localNameLength=view.getUint16(localOffset+26,true);const localExtraLength=view.getUint16(localOffset+28,true);requireRange(bytes2,localOffset+30,localNameLength+localExtraLength);const localName=decodeName(bytes2.subarray(localOffset+30,localOffset+30+localNameLength),localFlags);const dataOffset=localOffset+30+localNameLength+localExtraLength;if(localName!==name||localFlags!==flags||localMethod!==method||dataOffset+compressed>centralOffset)fail2("invalid-archive",`ZIP local and central records disagree for ${name}.`);if(view.getUint32(localOffset+14,true)!==crc||view.getUint32(localOffset+18,true)!==compressed||view.getUint32(localOffset+22,true)!==size)fail2("invalid-archive",`ZIP local sizes disagree for ${name}.`);const rangeEnd=dataOffset+compressed;if(ranges.some(([start,finish])=>localOffset<finish&&rangeEnd>start))fail2("invalid-archive",`ZIP entry ${name} overlaps another entry.`);ranges.push([localOffset,rangeEnd]);const packed=bytes2.subarray(dataOffset,rangeEnd);const directory2=name.endsWith("/");const unixType=madeBy===3?external>>>16&61440:0;if(directory2&&size!==0)fail2("invalid-archive",`ZIP directory ${name} contains data.`);if(unixType===40960&&size>MAX_PATH_BYTES)fail2("expansion-limit",`ZIP link ${name} exceeds the link target bound.`);if(!directory2&&unixType!==40960&&size>expandedLimit-fileBytes)fail2("expansion-limit",`Archive expands beyond ${expandedLimit} declared bytes.`);const data2=method===0?packed.slice():await decompress(packed,"deflate-raw",size,signal);if(data2.byteLength!==size||crc32(data2)!==crc)fail2("invalid-archive",`ZIP entry ${name} is corrupt.`);const path3=safePath(directory2?name.slice(0,-1):name);const mode=safeMode(madeBy===3?external>>>16&4095:0,directory2?493:420);if(directory2){if(size!==0||unixType!==0&&unixType!==16384)fail2("invalid-archive",`ZIP directory ${name} is invalid.`);entries.push({path:path3,type:"directory",mode})}else if(unixType===40960){entries.push({path:path3,type:"symlink",mode,target:safeSymlink(path3,decodeNullFree(data2))})}else{if(unixType!==0&&unixType!==32768)fail2("unsupported-entry",`ZIP entry ${name} is not a regular file.`);fileBytes+=data2.byteLength;if(fileBytes>expandedLimit)fail2("expansion-limit",`Archive expands beyond ${expandedLimit} declared bytes.`);entries.push({path:path3,type:"file",mode,content:data2})}}if(cursor!==end)fail2("invalid-archive","ZIP central directory length is invalid.");return entries}function validateTree(entries,expectedFiles,expectedBytes){const paths=new Map;let files=0;let bytes2=0;for(const entry of entries){if(paths.has(entry.path))fail2("invalid-archive",`Archive contains duplicate path ${entry.path}.`);paths.set(entry.path,entry);if(entry.type!=="directory")files+=1;if(entry.type==="file")bytes2+=entry.content.byteLength}for(const entry of entries){const parts=entry.path.split("/");for(let index2=1;index2<parts.length;index2+=1){const parent=paths.get(parts.slice(0,index2).join("/"));if(parent&&parent.type!=="directory")fail2("invalid-archive",`Archive path ${entry.path} descends through a non-directory.`)}}if(files!==expectedFiles)fail2("expansion-limit",`Archive contains ${files} files; manifest declares ${expectedFiles}.`);if(bytes2!==expectedBytes)fail2("expansion-limit",`Archive expands to ${bytes2} bytes; manifest declares ${expectedBytes}.`)}function safePath(value){if(value.length===0||value.startsWith("/")||value.includes("\\")||value.includes("\0"))fail2("unsafe-path",`Archive path ${JSON.stringify(value)} is unsafe.`);let encoded;try{encoded=new TextEncoder().encode(value)}catch{fail2("unsafe-path","Archive path is not valid text.")}const parts=value.split("/");if(encoded.byteLength>MAX_PATH_BYTES||parts.some(part=>part===""||part==="."||part===".."))fail2("unsafe-path",`Archive path ${JSON.stringify(value)} is unsafe.`);return value}function safeSymlink(path3,target){if(target.length===0||target.startsWith("/")||target.includes("\\")||target.includes("\0"))fail2("unsafe-path",`Link ${path3} has unsafe target ${JSON.stringify(target)}.`);const resolved=path3.split("/").slice(0,-1);for(const part of target.split("/")){if(part===""||part===".")continue;if(part===".."){if(resolved.length===0)fail2("unsafe-path",`Link ${path3} escapes the archive root.`);resolved.pop()}else resolved.push(part)}if(resolved.length===0)fail2("unsafe-path",`Link ${path3} resolves to the archive root.`);return target}function safeMode(value,fallback){return value&511||fallback}function verifyTarChecksum(header){const expected=tarNumber(header,148,8,"checksum");let sum=0;for(let index2=0;index2<header.byteLength;index2+=1)sum+=index2>=148&&index2<156?32:header[index2];if(sum!==expected)fail2("invalid-archive","Tar header checksum is invalid.")}function tarNumber(bytes2,offset2,length,field){if((bytes2[offset2]&128)!==0)fail2("unsupported-entry",`Tar ${field} uses unsupported base-256 encoding.`);const text=tarText(bytes2,offset2,length).trim();if(text==="")return 0;if(!/^[0-7]+$/u.test(text))fail2("invalid-archive",`Tar ${field} is invalid.`);const value=Number.parseInt(text,8);if(!Number.isSafeInteger(value)||value<0)fail2("invalid-archive",`Tar ${field} is outside the supported range.`);return value}function tarText(bytes2,offset2,length){const value=bytes2.subarray(offset2,offset2+length);const end=value.indexOf(0);try{return decoder.decode(end<0?value:value.subarray(0,end))}catch{fail2("invalid-archive","Tar metadata is not valid UTF-8.")}}function decodeNullTerminated(bytes2){return decodeNullFree(bytes2.subarray(0,bytes2[bytes2.byteLength-1]===0?-1:void 0))}function decodeNullFree(bytes2){try{const value=decoder.decode(bytes2);if(value.includes("\0"))fail2("invalid-archive","Archive metadata contains NUL.");return value}catch(cause){if(cause instanceof BrowserPackArchiveError)throw cause;fail2("invalid-archive","Archive metadata is not valid UTF-8.")}}function parsePax(bytes2){const result={};let cursor=0;while(cursor<bytes2.byteLength){const space=bytes2.indexOf(32,cursor);if(space<0)fail2("invalid-archive","PAX record is malformed.");const lengthText=decodeNullFree(bytes2.subarray(cursor,space));if(!/^[0-9]+$/u.test(lengthText))fail2("invalid-archive","PAX record length is invalid.");const length=Number(lengthText);if(!Number.isSafeInteger(length)||length<=0||cursor+length>bytes2.byteLength||bytes2[cursor+length-1]!==10)fail2("invalid-archive","PAX record length is invalid.");const record=decodeNullFree(bytes2.subarray(space+1,cursor+length-1));const equals=record.indexOf("=");if(equals<1)fail2("invalid-archive","PAX record is malformed.");const key=record.slice(0,equals);const value=record.slice(equals+1);if(key==="path"||key==="linkpath")result[key]=value;cursor+=length}return result}async function decompress(bytes2,format2,limit,signal){if(typeof DecompressionStream!=="function")fail2("unsupported-entry",`This browser cannot decompress ${format2} pack archives.`);const stream=new Blob([Uint8Array.from(bytes2)]).stream().pipeThrough(new DecompressionStream(format2));const reader=stream.getReader();const chunks=[];let length=0;try{for(;;){cancelled(signal);const chunk=await reader.read();if(chunk.done)break;length+=chunk.value.byteLength;if(length>limit)fail2("expansion-limit",`Archive stream exceeds its ${limit} byte expansion bound.`);chunks.push(chunk.value)}}catch(cause){if(cause instanceof BrowserPackArchiveError)throw cause;fail2("invalid-archive",`Archive decompression failed: ${cause instanceof Error?cause.message:String(cause)}`)}finally{await reader.cancel().catch(()=>void 0);reader.releaseLock()}const result=new Uint8Array(length);let offset2=0;for(const chunk of chunks){result.set(chunk,offset2);offset2+=chunk.byteLength}return result}function tarStreamLimit(expandedBytes,files){return expandedBytes+entryLimit(files)*(MAX_PATH_BYTES+TAR_BLOCK*3)+TAR_BLOCK*2}function entryLimit(files){return Math.max(16,files*16+16)}function findZipEnd(bytes2){if(bytes2.byteLength<22)fail2("invalid-archive","ZIP archive is truncated.");const view=new DataView(bytes2.buffer,bytes2.byteOffset,bytes2.byteLength);for(let offset2=bytes2.byteLength-22;offset2>=Math.max(0,bytes2.byteLength-65557);offset2-=1)if(view.getUint32(offset2,true)===101010256)return offset2;fail2("invalid-archive","ZIP end record is missing.")}function requireRange(bytes2,offset2,length){if(!Number.isSafeInteger(offset2)||!Number.isSafeInteger(length)||offset2<0||length<0||offset2+length>bytes2.byteLength)fail2("invalid-archive","ZIP archive is truncated.")}function decodeName(bytes2,flags){if((flags&2048)===0&&bytes2.some(byte=>byte>=128))fail2("unsupported-entry","ZIP entry names must use UTF-8.");return decodeNullFree(bytes2)}function crc32(bytes2){let crc=4294967295;for(const byte of bytes2){crc^=byte;for(let bit=0;bit<8;bit+=1)crc=crc>>>1^(crc&1?3988292384:0)}return(crc^4294967295)>>>0}function cancelled(signal){if(signal?.aborted)fail2("cancellation","Archive expansion was cancelled before staging.")}function fail2(category,message){throw new BrowserPackArchiveError(category,message)}var BrowserPackInstallError=class extends Error{constructor(category,message){super(message);this.category=category;this.name="BrowserPackInstallError"}category};function checkCancelled(signal){if(signal?.aborted)throw new BrowserPackInstallError("cancellation","Installation was cancelled before activation.")}var PackedBrowserPackInstallStore=class{constructor(packages2,headroom,coordinate=work=>work()){this.packages=packages2;this.headroom=headroom;this.coordinate=coordinate}packages;headroom;coordinate;async has(digest){return this.coordinate(async()=>{await this.packages.refresh();return this.packages.entries.has(this.completePath(digest))&&this.packages.entries.has(this.artifactPath(digest))})}async hasTree(digest){return this.coordinate(async()=>{await this.packages.refresh();return this.packages.entries.has(this.completePath(digest))})}async presentTrees(digests){return this.coordinate(async()=>{await this.packages.refresh();const present=new Set;for(const digest of digests)if(this.packages.entries.has(this.completePath(digest)))present.add(digest);return present})}async readArtifact(digest){return this.coordinate(async()=>{await this.packages.refresh();if(this.packages.entries.has(this.completePath(digest)))return this.packages.read(this.artifactPath(digest)).slice();if(this.packages.entries.has(legacyBrowserPackCompletePath(digest)))return this.packages.read(legacyBrowserPackArtifactPath(digest)).slice();throw new Error(`Pack artifact ${digest} is not completely staged.`)})}async stageArtifact(digest,bytes2,artifact,signal){if(await this.has(digest))return;const path3=this.artifactPath(digest);const mutations=[{operation:"mkdir",path:path3.slice(0,path3.lastIndexOf("/")),recursive:true},{operation:"mkdir",path:this.completePath(digest).slice(0,this.completePath(digest).lastIndexOf("/")),recursive:true},{operation:"write",path:path3,content:bytes2,mode:292}];if(artifact.archive){const root2=this.expandedPath(digest);const entries=await extractBrowserPackArchive(bytes2,artifact,signal);mutations.push({operation:"mkdir",path:root2,recursive:true});for(const entry of entries){const target=`${root2}/${entry.path}`;if(entry.type==="directory")mutations.push({operation:"mkdir",path:target,recursive:true,mode:entry.mode});else{mutations.push({operation:"mkdir",path:target.slice(0,target.lastIndexOf("/")),recursive:true});mutations.push({operation:"write",path:target,content:entry.type==="file"?entry.content:new TextEncoder().encode(entry.target),mode:entry.mode,...entry.type==="symlink"?{symlink:true}:{}})}}}mutations.push({operation:"write",path:this.completePath(digest),content:new Uint8Array(0),mode:292});for(let offset2=0;offset2<mutations.length;offset2+=128){checkCancelled(signal);const complete=await this.coordinate(async()=>{await this.packages.refresh();if(this.packages.entries.has(this.completePath(digest))){if(!this.packages.entries.has(path3))await this.packages.apply(mutations.slice(0,3));return true}await this.packages.apply(mutations.slice(offset2,offset2+128));return false});if(complete)return}}async stageEnvironment(lockDigest,lock){const path3=browserPackLockPath(lockDigest);await this.coordinate(async()=>{await this.packages.refresh();if(this.packages.entries.has(path3))return;await this.packages.apply([{operation:"mkdir",path:"/packages/.browser-packs/locks",recursive:true},{operation:"write",path:path3,content:new TextEncoder().encode(canonicalBrowserPackJson(lock)),mode:292}])})}async availableBytes(){return this.headroom?.()}artifactPath(digest){return browserPackArtifactPath(digest)}expandedPath(digest){return browserPackExpandedPath(digest)}completePath(digest){return browserPackCompletePath(digest)}};function browserPackObjectPath(digest){return`/packages/.browser-packs/objects/${digest.slice("sha256:".length)}`}function browserPackArtifactPath(digest){return`${browserPackObjectPath(digest)}/artifact`}function browserPackExpandedPath(digest){return`${browserPackObjectPath(digest)}/expanded`}function browserPackCompletePath(digest){return`${browserPackObjectPath(digest)}/complete`}function browserPackLockPath(digest){return`/packages/.browser-packs/locks/${digest.slice("sha256:".length)}.json`}function legacyBrowserPackArtifactPath(digest){return`/packages/.browser-packs/artifacts/${digest.slice("sha256:".length)}`}function legacyBrowserPackExpandedPath(digest){return`/packages/.browser-packs/expanded/${digest.slice("sha256:".length)}`}function legacyBrowserPackCompletePath(digest){return`/packages/.browser-packs/complete/${digest.slice("sha256:".length)}`}var INSTALL_REFUSED="EINSTALLREFUSED";var INSTALL_TRAP_RECORD="[install-trap-record]";var InstallRefusedError=class extends Error{constructor(request){super(installRefusal(request));this.request=request;this.name="InstallRefusedError"}request;code=INSTALL_REFUSED};var RECORDER=Symbol.for("browser-substrate.install-recorder");var TRAPPED=Symbol.for("browser-substrate.install-trapped");function installTrap(request){const scope4=globalThis;(scope4[TRAPPED]??=[]).push(request);scope4[RECORDER]?.(request);console.error(`[install-trap] ${request.door}: ${request.subject}`);console.info(`${INSTALL_TRAP_RECORD} ${JSON.stringify(request)}`);throw new InstallRefusedError(request)}function isInstallRefused(cause){if(typeof cause!=="object"||cause===null)return false;if(cause.code===INSTALL_REFUSED)return true;return/^REFUSED \([^)]+\): /u.test(String(cause.message??""))}function installRefusal(request){return[`REFUSED (${request.door}): ${request.subject}`,"","The tab never installs, downloads, extracts or builds a dependency, and never runs a setup step. Everything a","project uses reaches it prepared, with the image or from the catalog, and this was not. Nothing was attempted.","",...request.fix?[`To fix it: ${request.fix}`]:["To fix it, prepare the image again on a machine, from the project's folder:",""," npx @volter/browser-substrate dev"]].join("\n")}var __defProp2=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp2(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);var CHUNK=8192;function uint8ToBase64(bytes2){const parts=[];for(let i10=0;i10<bytes2.length;i10+=CHUNK){parts.push(String.fromCharCode.apply(null,Array.from(bytes2.subarray(i10,i10+CHUNK))))}return btoa(parts.join(""))}function base64ToUint8(base644){const binary=atob(base644);const bytes2=new Uint8Array(binary.length);for(let i10=0;i10<binary.length;i10++){bytes2[i10]=binary.charCodeAt(i10)}return bytes2}function uint8ToHex(bytes2){const hex=new Array(bytes2.length);for(let i10=0;i10<bytes2.length;i10++){hex[i10]=bytes2[i10].toString(16).padStart(2,"0")}return hex.join("")}function uint8ToBinaryString(bytes2){const parts=[];for(let i10=0;i10<bytes2.length;i10+=CHUNK){parts.push(String.fromCharCode.apply(null,Array.from(bytes2.subarray(i10,i10+CHUNK))))}return parts.join("")}var _encoder=new TextEncoder;var FLOW_MAX_REQUEST_BYTES=64*1024*1024;var FLOW_MAX_CHUNK_BYTES=65536;var FLOW_QUEUED_CHUNKS=4;function ownedBytes(view){const copy2=new Uint8Array(view.byteLength);copy2.set(new Uint8Array(view.buffer,view.byteOffset,view.byteLength));return copy2}var BridgeEvents=class{constructor(){__publicField(this,"listenersByEvent",new Map)}on(event,listener){const list2=this.listenersByEvent.get(event)??[];list2.push(listener);this.listenersByEvent.set(event,list2);return this}addListener(event,listener){return this.on(event,listener)}once(event,listener){const wrapped=(...args)=>{this.off(event,wrapped);listener(...args)};wrapped.listener=listener;return this.on(event,wrapped)}off(event,listener){const list2=this.listenersByEvent.get(event);if(!list2)return this;const at3=list2.findIndex(candidate=>candidate===listener||candidate.listener===listener);if(at3>=0)list2.splice(at3,1);if(list2.length===0)this.listenersByEvent.delete(event);return this}removeListener(event,listener){return this.off(event,listener)}removeAllListeners(event){if(event===void 0)this.listenersByEvent.clear();else this.listenersByEvent.delete(event);return this}listenerCount(event){var _a4;return((_a4=this.listenersByEvent.get(event))==null?void 0:_a4.length)??0}emit(event,...args){const list2=this.listenersByEvent.get(event);if(!list2||list2.length===0)return false;for(const listener of[...list2])listener(...args);return true}};var _PortBridge=class _PortBridge2 extends BridgeEvents{constructor(options={}){super();__publicField(this,"servers",new Map);__publicField(this,"baseUrl");__publicField(this,"options");__publicField(this,"messageChannel",null);__publicField(this,"serviceWorkerReady",false);__publicField(this,"keepaliveInterval",null);__publicField(this,"primaryPort",null);__publicField(this,"ownDocuments");__publicField(this,"binaryChunkPorts",new WeakSet);__publicField(this,"controlledStreams",new Map);this.options=options;if(typeof location!=="undefined"){this.baseUrl=options.baseUrl||`${location.protocol}//${location.host}`}else{this.baseUrl=options.baseUrl||"http://localhost"}}close(){if(this.keepaliveInterval!==null){clearInterval(this.keepaliveInterval);this.keepaliveInterval=null}}registerServer(server,port2,hostname2="0.0.0.0"){this.servers.set(port2,{server,port:port2,hostname:hostname2});const url2=this.getServerUrl(port2);this.emit("server-ready",port2,url2);if(this.options.onServerReady){this.options.onServerReady(port2,url2)}this.notifyServiceWorker("server-registered",{port:port2,hostname:hostname2,primary:port2===this.primaryPort})}unregisterServer(port2){this.servers.delete(port2);if(this.primaryPort===port2)this.primaryPort=null;this.notifyServiceWorker("server-unregistered",{port:port2})}setPrimaryPort(port2){const previous=this.primaryPort;this.primaryPort=port2;if(previous!==null&&previous!==port2){const entry=this.servers.get(previous);if(entry)this.notifyServiceWorker("server-registered",{port:previous,hostname:entry.hostname,primary:false})}if(port2!==null){const entry=this.servers.get(port2);this.notifyServiceWorker("server-registered",{port:port2,hostname:(entry==null?void 0:entry.hostname)??"0.0.0.0",primary:true})}}announceServers(){if(this.ownDocuments)this.notifyServiceWorker("own-documents",{paths:this.ownDocuments});for(const[port2,entry]of this.servers){this.notifyServiceWorker("server-registered",{port:port2,hostname:entry.hostname,primary:port2===this.primaryPort})}}getServerUrl(port2){return`${this.baseUrl}/__virtual__/${port2}`}getServerPorts(){return[...this.servers.keys()]}async handleRequest(port2,method,url2,headers,body){const virtualServer=this.servers.get(port2);if(!virtualServer){return{statusCode:503,statusMessage:"Service Unavailable",headers:{"Content-Type":"text/plain"},body:_encoder.encode(`No server listening on port ${port2}`)}}try{const bodyBuffer=body?this.bodyOf(new Uint8Array(body)):void 0;const named=Object.keys(headers).some(name=>name.toLowerCase()==="host");const authority=`${virtualServer.hostname&&virtualServer.hostname!=="0.0.0.0"&&virtualServer.hostname!=="::"?virtualServer.hostname:"127.0.0.1"}:${port2}`;const withHost=named?headers:{...headers,host:authority};if(virtualServer.server)return await virtualServer.server.handleRequest(method,url2,withHost,bodyBuffer);return await this.requestGuest(port2,method,url2,withHost,bodyBuffer)}catch(error){const message=error instanceof Error?error.message:"Internal Server Error";return{statusCode:500,statusMessage:"Internal Server Error",headers:{"Content-Type":"text/plain"},body:_encoder.encode(message)}}}async initServiceWorker(options){if(!("serviceWorker"in navigator)){throw new Error("Service Workers not supported")}const swUrl=(options==null?void 0:options.swUrl)??"/__sw__.js";const controllerReady=navigator.serviceWorker.controller?Promise.resolve():new Promise(resolve2=>{navigator.serviceWorker.addEventListener("controllerchange",()=>resolve2(),{once:true})});const registration=await navigator.serviceWorker.register(swUrl,{scope:"/",updateViaCache:"none"});try{await Promise.race([registration.update(),new Promise(resolve2=>setTimeout(resolve2,5e3))])}catch{}const sw2=registration.installing||registration.waiting||registration.active;if(!sw2){throw new Error("Service Worker registration failed")}await new Promise(resolve2=>{if(sw2.state==="activated"||sw2.state==="redundant"){resolve2()}else{const handler=()=>{if(sw2.state==="activated"||sw2.state==="redundant"){sw2.removeEventListener("statechange",handler);resolve2()}};sw2.addEventListener("statechange",handler)}});const controlling=sw2.state==="redundant"?registration.active:sw2;if(!controlling)throw new Error("Service Worker failed to install");if(navigator.serviceWorker.controller&&navigator.serviceWorker.controller!==controlling){await new Promise(resolve2=>{const timer=setTimeout(()=>{console.warn("tabnode: the new service worker did not take control within 10 s; starting under the one in control");done()},1e4);function done(){clearTimeout(timer);navigator.serviceWorker.removeEventListener("controllerchange",changed);resolve2()}function changed(){if(navigator.serviceWorker.controller===controlling)done()}navigator.serviceWorker.addEventListener("controllerchange",changed);changed()})}this.messageChannel=new MessageChannel;this.messageChannel.port1.onmessage=this.handleServiceWorkerMessage.bind(this);this.ownDocuments=options==null?void 0:options.ownDocuments;controlling.postMessage({type:"init",port:this.messageChannel.port2,data:{ownDocuments:this.ownDocuments??[]}},[this.messageChannel.port2]);await controllerReady;const reinit=()=>{if(navigator.serviceWorker.controller){for(const stream of[...this.controlledStreams.values()])stream.cancel();this.messageChannel=new MessageChannel;this.messageChannel.port1.onmessage=this.handleServiceWorkerMessage.bind(this);navigator.serviceWorker.controller.postMessage({type:"init",port:this.messageChannel.port2,data:{ownDocuments:this.ownDocuments??[]}},[this.messageChannel.port2]);this.announceServers()}};navigator.serviceWorker.addEventListener("controllerchange",reinit);navigator.serviceWorker.addEventListener("message",event=>{var _a4;if(((_a4=event.data)==null?void 0:_a4.type)==="sw-needs-init"){reinit()}});this.keepaliveInterval=setInterval(()=>{var _a4;(_a4=this.messageChannel)==null?void 0:_a4.port1.postMessage({type:"keepalive"})},2e4);this.serviceWorkerReady=true;this.announceServers();this.emit("sw-ready")}postChunk(port2,id2,bytes2){if(!port2)return;if(this.binaryChunkPorts.has(port2))port2.postMessage({type:"stream-chunk",id:id2,data:{chunk:bytes2}},[bytes2.buffer]);else port2.postMessage({type:"stream-chunk",id:id2,data:{chunkBase64:uint8ToBase64(bytes2)}})}async handleServiceWorkerMessage(event){var _a4,_b3,_c3;const{type:type2,id:id2,data:data2}=event.data;if(type2==="sw-capabilities"){if((data2==null?void 0:data2.binaryChunks)===1&&event.target instanceof MessagePort)this.binaryChunkPorts.add(event.target);return}_PortBridge2.DEBUG&&console.log("[ServerBridge] SW message:",type2,id2,data2==null?void 0:data2.url);if(type2==="stream-pull"||type2==="stream-cancel"){const stream=this.controlledStreams.get(id2);if(type2==="stream-pull")stream==null?void 0:stream.pull();else stream==null?void 0:stream.cancel();return}if(type2==="request"&&(data2==null?void 0:data2.flowControl)===1){const{port:port2,method,url:url2,headers,body}=data2;await this.controlledStream(id2,port2,method,url2,headers,body);return}if(type2==="request"){const{port:port2,method,url:url2,headers,body,streaming}=data2;_PortBridge2.DEBUG&&console.log("[ServerBridge] Handling request:",port2,method,url2,"streaming:",streaming);if(streaming){_PortBridge2.DEBUG&&console.log("[ServerBridge] \u{1F534} Will use streaming handler")}try{if(streaming){await this.streamToServiceWorker(id2,port2,method,url2,headers,body)}else{const response=await this.handleRequest(port2,method,url2,headers,body);_PortBridge2.DEBUG&&console.log("[ServerBridge] Response:",response.statusCode,"body length:",(_a4=response.body)==null?void 0:_a4.length);let bodyBase64="";if(response.body&&response.body.length>0){const bytes2=response.body instanceof Uint8Array?response.body:new Uint8Array(0);bodyBase64=uint8ToBase64(bytes2)}_PortBridge2.DEBUG&&console.log("[ServerBridge] Sending response to SW, body base64 length:",bodyBase64.length);(_b3=this.messageChannel)==null?void 0:_b3.port1.postMessage({type:"response",id:id2,data:{statusCode:response.statusCode,statusMessage:response.statusMessage,headers:response.headers,bodyBase64}})}}catch(error){(_c3=this.messageChannel)==null?void 0:_c3.port1.postMessage({type:"response",id:id2,error:error instanceof Error?error.message:"Unknown error"})}}}async handleStreamingRequest(port2,method,url2,headers,body,callbacks,flow){const virtualServer=this.servers.get(port2);if(!virtualServer)return false;const bodyBuffer=body?this.bodyOf(new Uint8Array(body)):void 0;if(this.isGuest(virtualServer)){const named=Object.keys(headers).some(name=>name.toLowerCase()==="host");const authority=`${virtualServer.hostname&&virtualServer.hostname!=="0.0.0.0"&&virtualServer.hostname!=="::"?virtualServer.hostname:"127.0.0.1"}:${port2}`;await this.streamGuest(port2,method,url2,named?headers:{...headers,host:authority},bodyBuffer,(statusCode,statusMessage,respHeaders)=>callbacks.start(statusCode,statusMessage,respHeaders),chunk=>callbacks.chunk(ownedBytes(chunk)),()=>callbacks.end(),flow);return true}const server=virtualServer.server;if(typeof server.handleStreamingRequest==="function"){await server.handleStreamingRequest(method,url2,headers,bodyBuffer,(statusCode,statusMessage,respHeaders)=>callbacks.start(statusCode,statusMessage,respHeaders),chunk=>callbacks.chunk(typeof chunk==="string"?_encoder.encode(chunk):ownedBytes(chunk)),()=>callbacks.end(),flow);return true}const response=await this.handleRequest(port2,method,url2,headers,body);callbacks.start(response.statusCode,response.statusMessage??"",response.headers);if(response.body){const body2=typeof response.body==="string"?_encoder.encode(response.body):response.body;callbacks.chunk(ownedBytes(body2))}callbacks.end();return true}async streamToServiceWorker(id2,port2,method,url2,headers,body){var _a4,_b3,_c3,_d3,_e3;const virtualServer=this.servers.get(port2);if(!virtualServer){(_a4=this.messageChannel)==null?void 0:_a4.port1.postMessage({type:"stream-start",id:id2,data:{statusCode:503,statusMessage:"Service Unavailable",headers:{}}});(_b3=this.messageChannel)==null?void 0:_b3.port1.postMessage({type:"stream-end",id:id2});return}if(this.isGuest(virtualServer)){const bodyBuffer=body?this.bodyOf(new Uint8Array(body)):void 0;const named=Object.keys(headers).some(name=>name.toLowerCase()==="host");const authority=`${virtualServer.hostname&&virtualServer.hostname!=="0.0.0.0"&&virtualServer.hostname!=="::"?virtualServer.hostname:"127.0.0.1"}:${port2}`;await this.streamGuest(port2,method,url2,named?headers:{...headers,host:authority},bodyBuffer,(statusCode,statusMessage,respHeaders)=>{var _a22;(_a22=this.messageChannel)==null?void 0:_a22.port1.postMessage({type:"stream-start",id:id2,data:{statusCode,statusMessage,headers:respHeaders}})},chunk=>{var _a22;const copy2=ownedBytes(chunk);(_a22=this.messageChannel)==null?void 0:_a22.port1.postMessage({type:"stream-chunk",id:id2,data:copy2.buffer},[copy2.buffer])},()=>{var _a22;(_a22=this.messageChannel)==null?void 0:_a22.port1.postMessage({type:"stream-end",id:id2})});return}const server=virtualServer.server;if(!server)return;if(typeof server.handleStreamingRequest==="function"){_PortBridge2.DEBUG&&console.log("[ServerBridge] \u{1F7E2} Server has streaming support, calling handleStreamingRequest");const bodyBuffer=body?this.bodyOf(new Uint8Array(body)):void 0;await server.handleStreamingRequest(method,url2,headers,bodyBuffer,(statusCode,statusMessage,respHeaders)=>{var _a22;_PortBridge2.DEBUG&&console.log("[ServerBridge] \u{1F7E2} onStart called, sending stream-start");(_a22=this.messageChannel)==null?void 0:_a22.port1.postMessage({type:"stream-start",id:id2,data:{statusCode,statusMessage,headers:respHeaders}})},chunk=>{var _a22;const bytes2=typeof chunk==="string"?_encoder.encode(chunk):ownedBytes(chunk);_PortBridge2.DEBUG&&console.log("[ServerBridge] \u{1F7E1} onChunk called, sending stream-chunk, size:",bytes2.byteLength);this.postChunk((_a22=this.messageChannel)==null?void 0:_a22.port1,id2,bytes2)},()=>{var _a22;_PortBridge2.DEBUG&&console.log("[ServerBridge] \u{1F7E2} onEnd called, sending stream-end");(_a22=this.messageChannel)==null?void 0:_a22.port1.postMessage({type:"stream-end",id:id2})})}else{const bodyBuffer=body?this.bodyOf(new Uint8Array(body)):void 0;const response=await server.handleRequest(method,url2,headers,bodyBuffer);(_c3=this.messageChannel)==null?void 0:_c3.port1.postMessage({type:"stream-start",id:id2,data:{statusCode:response.statusCode,statusMessage:response.statusMessage,headers:response.headers}});if(response.body&&response.body.length>0){const bytes2=response.body instanceof Uint8Array?ownedBytes(response.body):new Uint8Array(0);this.postChunk((_d3=this.messageChannel)==null?void 0:_d3.port1,id2,bytes2)}(_e3=this.messageChannel)==null?void 0:_e3.port1.postMessage({type:"stream-end",id:id2})}}notifyServiceWorker(type2,data2){if(this.serviceWorkerReady&&this.messageChannel){const flow=type2==="server-registered"?{flowControl:1,maxRequestBytes:FLOW_MAX_REQUEST_BYTES,maxChunkBytes:FLOW_MAX_CHUNK_BYTES}:{};this.messageChannel.port1.postMessage({type:type2,data:{...data2,...flow}})}}async controlledStream(id2,port2,method,url2,headers,body){const channel=this.messageChannel;const post=(type2,data2)=>{channel==null?void 0:channel.port1.postMessage({type:type2,id:id2,...data2===void 0?{}:{data:data2}})};const queue=[];const abort=new AbortController;let credits=0;let upstreamEnded=false;let finished=false;let paused=false;let pause=()=>void 0;let resume=()=>void 0;const finish=()=>{finished=true;this.controlledStreams.delete(id2)};const flush2=()=>{if(finished)return;while(credits>0&&queue.length>0){credits-=1;this.postChunk(channel==null?void 0:channel.port1,id2,queue.shift())}if(upstreamEnded&&queue.length===0){post("stream-end");finish();return}if(queue.length>=FLOW_QUEUED_CHUNKS&&!paused){paused=true;pause()}else if(queue.length<FLOW_QUEUED_CHUNKS&&paused){paused=false;resume()}};this.controlledStreams.set(id2,{pull:()=>{credits+=1;flush2()},cancel:()=>{if(finished)return;finish();queue.length=0;abort.abort()}});try{const answered=await this.handleStreamingRequest(port2,method,url2,headers,body,{start:(statusCode,statusMessage,respHeaders)=>post("stream-start",{statusCode,statusMessage,headers:respHeaders}),chunk:chunk=>{if(finished)return;for(let at3=0;at3<chunk.byteLength;at3+=FLOW_MAX_CHUNK_BYTES)queue.push(chunk.slice(at3,at3+FLOW_MAX_CHUNK_BYTES));flush2()},end:()=>{upstreamEnded=true;flush2()}},{signal:abort.signal,control:(p,r10)=>{pause=p;resume=r10}});if(!answered){post("stream-start",{statusCode:503,statusMessage:"Service Unavailable",headers:{}});post("stream-end");finish()}}catch(error){if(!finished){post("stream-error",{message:error instanceof Error?error.message:String(error)});finish()}}}createFetchHandler(){return async request=>{const url2=new URL(request.url);const match2=url2.pathname.match(/^\/__virtual__\/(\d+)(\/.*)?$/);if(!match2){throw new Error("Not a virtual server request")}const port2=parseInt(match2[1],10);const path3=match2[2]||"/";const headers={};request.headers.forEach((value,key)=>{headers[key]=value});let body;if(request.method!=="GET"&&request.method!=="HEAD"){body=await request.arrayBuffer()}const response=await this.handleRequest(port2,request.method,path3+url2.search,headers,body);const answerHeaders=new Headers;for(const[name,value]of Object.entries(response.headers)){for(const each of Array.isArray(value)?value:[value])answerHeaders.append(name,each)}return new Response(response.body,{status:response.statusCode,statusText:response.statusMessage??"",headers:answerHeaders})}}isGuest(entry){return entry.server===null}requestGuest(port2,_method,_url2,_headers2,_body){return Promise.reject(new Error(`Port ${port2} has no server in this realm.`))}streamGuest(port2,_method,_url2,_headers2,_body,_onStart,_onChunk,_onEnd,_flow){return Promise.reject(new Error(`Port ${port2} has no server in this realm.`))}bodyOf(bytes2){return bytes2}};__publicField(_PortBridge,"DEBUG",false);var PortBridge=_PortBridge;var import_sprintf_js=__toESM(require_sprintf(),1);var balanced=(a,b,str)=>{const ma2=a instanceof RegExp?maybeMatch(a,str):a;const mb2=b instanceof RegExp?maybeMatch(b,str):b;const r10=ma2!==null&&mb2!=null&&range(ma2,mb2,str);return r10&&{start:r10[0],end:r10[1],pre:str.slice(0,r10[0]),body:str.slice(r10[0]+ma2.length,r10[1]),post:str.slice(r10[1]+mb2.length)}};var maybeMatch=(reg,str)=>{const m=str.match(reg);return m?m[0]:null};var range=(a,b,str)=>{let begs,beg,left,right=void 0,result;let ai2=str.indexOf(a);let bi2=str.indexOf(b,ai2+1);let i10=ai2;if(ai2>=0&&bi2>0){if(a===b){return[ai2,bi2]}begs=[];left=str.length;while(i10>=0&&!result){if(i10===ai2){begs.push(i10);ai2=str.indexOf(a,i10+1)}else if(begs.length===1){const r10=begs.pop();if(r10!==void 0)result=[r10,bi2]}else{beg=begs.pop();if(beg!==void 0&&beg<left){left=beg;right=bi2}bi2=str.indexOf(b,i10+1)}i10=ai2<bi2&&ai2>=0?ai2:bi2}if(begs.length&&right!==void 0){result=[left,right]}}return result};var escSlash="\0SLASH"+Math.random()+"\0";var escOpen="\0OPEN"+Math.random()+"\0";var escClose="\0CLOSE"+Math.random()+"\0";var escComma="\0COMMA"+Math.random()+"\0";var escPeriod="\0PERIOD"+Math.random()+"\0";var escSlashPattern=new RegExp(escSlash,"g");var escOpenPattern=new RegExp(escOpen,"g");var escClosePattern=new RegExp(escClose,"g");var escCommaPattern=new RegExp(escComma,"g");var escPeriodPattern=new RegExp(escPeriod,"g");var slashPattern=/\\\\/g;var openPattern=/\\{/g;var closePattern=/\\}/g;var commaPattern=/\\,/g;var periodPattern=/\\\./g;var EXPANSION_MAX=1e5;var EXPANSION_MAX_LENGTH=4e6;function numeric(str){return!isNaN(str)?parseInt(str,10):str.charCodeAt(0)}function escapeBraces(str){return str.replace(slashPattern,escSlash).replace(openPattern,escOpen).replace(closePattern,escClose).replace(commaPattern,escComma).replace(periodPattern,escPeriod)}function unescapeBraces(str){return str.replace(escSlashPattern,"\\").replace(escOpenPattern,"{").replace(escClosePattern,"}").replace(escCommaPattern,",").replace(escPeriodPattern,".")}function parseCommaParts(str){if(!str){return[""]}const parts=[];const m=balanced("{","}",str);if(!m){return str.split(",")}const{pre,body,post}=m;const p=pre.split(",");p[p.length-1]+="{"+body+"}";const postParts=parseCommaParts(post);if(post.length){;p[p.length-1]+=postParts.shift();p.push.apply(p,postParts)}parts.push.apply(parts,p);return parts}function expand(str,options={}){if(!str){return[]}const{max:max2=EXPANSION_MAX,maxLength=EXPANSION_MAX_LENGTH}=options;if(str.slice(0,2)==="{}"){str="\\{\\}"+str.slice(2)}return expand_(escapeBraces(str),max2,maxLength,true).map(unescapeBraces)}function embrace(str){return"{"+str+"}"}function isPadded(el2){return/^-?0\d/.test(el2)}function lte(i10,y){return i10<=y}function gte(i10,y){return i10>=y}function combine(acc,pre,values,max2,maxLength,dropEmpties){const out=[];let length=0;for(let a=0;a<acc.length;a++){for(let v2=0;v2<values.length;v2++){if(out.length>=max2)return out;const expansion=acc[a]+pre+values[v2];if(dropEmpties&&!expansion)continue;if(length+expansion.length>maxLength)return out;out.push(expansion);length+=expansion.length}}return out}function expandSequence(body,isAlphaSequence,max2,maxLength){const n8=body.split(/\.\./);const N=[];if(n8[0]===void 0||n8[1]===void 0){return N}const x=numeric(n8[0]);const y=numeric(n8[1]);const width=Math.max(n8[0].length,n8[1].length);let incr=n8.length===3&&n8[2]!==void 0?Math.max(Math.abs(numeric(n8[2])),1):1;let test=lte;const reverse2=y<x;if(reverse2){incr*=-1;test=gte}const pad=n8.some(isPadded);let length=0;for(let i10=x;test(i10,y)&&N.length<max2;i10+=incr){let c;if(isAlphaSequence){c=String.fromCharCode(i10);if(c==="\\"){c=""}}else{c=String(i10);if(pad){const need=width-c.length;if(need>0){const z10=new Array(need+1).join("0");if(i10<0){c="-"+z10+c.slice(1)}else{c=z10+c}}}}if(length+c.length>maxLength)break;N.push(c);length+=c.length}return N}function expand_(str,max2,maxLength,isTop){let acc=[""];let dropEmpties=false;let firstGroup=true;for(;;){const m=balanced("{","}",str);if(!m){return combine(acc,str,[""],max2,maxLength,dropEmpties)}const pre=m.pre;if(/\$$/.test(pre)){acc=combine(acc,pre+"{"+m.body+"}",[""],max2,maxLength,dropEmpties&&!m.post.length);firstGroup=false;if(!m.post.length)break;str=m.post;continue}const isNumericSequence=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);const isAlphaSequence=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);const isSequence=isNumericSequence||isAlphaSequence;const isOptions=m.body.indexOf(",")>=0;if(!isSequence&&!isOptions){if(m.post.match(/,(?!,).*\}/)){str=m.pre+"{"+m.body+escClose+m.post;isTop=true;continue}return combine(acc,pre+"{"+m.body+"}"+m.post,[""],max2,maxLength,dropEmpties)}if(firstGroup){dropEmpties=isTop&&!isSequence;firstGroup=false}let values;if(isSequence){values=expandSequence(m.body,isAlphaSequence,max2,maxLength)}else{let n8=parseCommaParts(m.body);if(n8.length===1&&n8[0]!==void 0){n8=expand_(n8[0],max2,maxLength,false).map(embrace);if(n8.length===1){acc=combine(acc,pre+n8[0],[""],max2,maxLength,dropEmpties&&!m.post.length);if(!m.post.length)break;str=m.post;continue}}let dropsEmpties=dropEmpties&&!m.post.length&&!pre;for(let d=0;dropsEmpties&&d<acc.length;d++){if(acc[d]){dropsEmpties=false}}values=[];let valuesLength=0;outer:for(let j=0;j<n8.length;j++){const expanded=expand_(n8[j],max2,maxLength,false);for(let k10=0;k10<expanded.length;k10++){const v2=expanded[k10];if(dropsEmpties&&!v2)continue;if(values.length>=max2||valuesLength+v2.length>maxLength){break outer}values.push(v2);valuesLength+=v2.length}}}acc=combine(acc,pre,values,max2,maxLength,dropEmpties&&!m.post.length);if(!m.post.length)break;str=m.post}return acc}var MAX_PATTERN_LENGTH=1024*64;var assertValidPattern=pattern=>{if(typeof pattern!=="string"){throw new TypeError("invalid pattern")}if(pattern.length>MAX_PATTERN_LENGTH){throw new TypeError("pattern is too long")}};var posixClasses={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",true],"[:alpha:]":["\\p{L}\\p{Nl}",true],"[:ascii:]":["\\x00-\\x7f",false],"[:blank:]":["\\p{Zs}\\t",true],"[:cntrl:]":["\\p{Cc}",true],"[:digit:]":["\\p{Nd}",true],"[:graph:]":["\\p{Z}\\p{C}",true,true],"[:lower:]":["\\p{Ll}",true],"[:print:]":["\\p{C}",true],"[:punct:]":["\\p{P}",true],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",true],"[:upper:]":["\\p{Lu}",true],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",true],"[:xdigit:]":["A-Fa-f0-9",false]};var braceEscape=s10=>s10.replace(/[[\]\\-]/g,"\\$&");var regexpEscape=s10=>s10.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");var rangesToString=ranges=>ranges.join("");var parseClass=(glob,position)=>{const pos=position;if(glob.charAt(pos)!=="["){throw new Error("not in a brace expression")}const ranges=[];const negs=[];let i10=pos+1;let sawStart=false;let uflag=false;let escaping=false;let negate=false;let endPos=pos;let rangeStart="";WHILE:while(i10<glob.length){const c=glob.charAt(i10);if((c==="!"||c==="^")&&i10===pos+1){negate=true;i10++;continue}if(c==="]"&&sawStart&&!escaping){endPos=i10+1;break}sawStart=true;if(c==="\\"){if(!escaping){escaping=true;i10++;continue}}if(c==="["&&!escaping){for(const[cls,[unip,u,neg]]of Object.entries(posixClasses)){if(glob.startsWith(cls,i10)){if(rangeStart){return["$.",false,glob.length-pos,true]}i10+=cls.length;if(neg)negs.push(unip);else ranges.push(unip);uflag=uflag||u;continue WHILE}}}escaping=false;if(rangeStart){if(c>rangeStart){ranges.push(braceEscape(rangeStart)+"-"+braceEscape(c))}else if(c===rangeStart){ranges.push(braceEscape(c))}rangeStart="";i10++;continue}if(glob.startsWith("-]",i10+1)){ranges.push(braceEscape(c+"-"));i10+=2;continue}if(glob.startsWith("-",i10+1)){rangeStart=c;i10+=2;continue}ranges.push(braceEscape(c));i10++}if(endPos<i10){return["",false,0,false]}if(!ranges.length&&!negs.length){return["$.",false,glob.length-pos,true]}if(negs.length===0&&ranges.length===1&&/^\\?.$/.test(ranges[0])&&!negate){const r10=ranges[0].length===2?ranges[0].slice(-1):ranges[0];return[regexpEscape(r10),false,endPos-pos,false]}const sranges="["+(negate?"^":"")+rangesToString(ranges)+"]";const snegs="["+(negate?"":"^")+rangesToString(negs)+"]";const comb=ranges.length&&negs.length?"("+sranges+"|"+snegs+")":ranges.length?sranges:snegs;return[comb,uflag,endPos-pos,true]};var unescape=(s10,{windowsPathsNoEscape=false,magicalBraces=true}={})=>{if(magicalBraces){return windowsPathsNoEscape?s10.replace(/\[([^/\\])\]/g,"$1"):s10.replace(/((?!\\).|^)\[([^/\\])\]/g,"$1$2").replace(/\\([^/])/g,"$1")}return windowsPathsNoEscape?s10.replace(/\[([^/\\{}])\]/g,"$1"):s10.replace(/((?!\\).|^)\[([^/\\{}])\]/g,"$1$2").replace(/\\([^/{}])/g,"$1")};var _a;var types=new Set(["!","?","+","*","@"]);var isExtglobType=c=>types.has(c);var isExtglobAST=c=>isExtglobType(c.type);var adoptionMap=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]);var adoptionWithSpaceMap=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]);var adoptionAnyMap=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]);var usurpMap=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]);var startNoTraversal="(?!(?:^|/)\\.\\.?(?:$|/))";var startNoDot="(?!\\.)";var addPatternStart=new Set(["[","."]);var justDots=new Set(["..","."]);var reSpecials=new Set("().*{}+?[]^$\\!");var regExpEscape=s10=>s10.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");var qmark="[^/]";var star=qmark+"*?";var starNoEmpty=qmark+"+?";var ID=0;var AST=class{type;#root;#hasMagic;#uflag=false;#parts=[];#parent;#parentIndex;#negs;#filledNegs=false;#options;#toString;#emptyExt=false;id=++ID;get depth(){return(this.#parent?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#root.id,parent:this.#parent?.id,depth:this.depth,partsLength:this.#parts.length,parts:this.#parts}}constructor(type2,parent,options={}){this.type=type2;if(type2)this.#hasMagic=true;this.#parent=parent;this.#root=this.#parent?this.#parent.#root:this;this.#options=this.#root===this?options:this.#root.#options;this.#negs=this.#root===this?[]:this.#root.#negs;if(type2==="!"&&!this.#root.#filledNegs)this.#negs.push(this);this.#parentIndex=this.#parent?this.#parent.#parts.length:0}get hasMagic(){if(this.#hasMagic!==void 0)return this.#hasMagic;for(const p of this.#parts){if(typeof p==="string")continue;if(p.type||p.hasMagic)return this.#hasMagic=true}return this.#hasMagic}toString(){return this.#toString!==void 0?this.#toString:!this.type?this.#toString=this.#parts.map(p=>String(p)).join(""):this.#toString=this.type+"("+this.#parts.map(p=>String(p)).join("|")+")"}#fillNegs(){if(this!==this.#root)throw new Error("should only call on root");if(this.#filledNegs)return this;this.toString();this.#filledNegs=true;let n8;while(n8=this.#negs.pop()){if(n8.type!=="!")continue;let p=n8;let pp3=p.#parent;while(pp3){for(let i10=p.#parentIndex+1;!pp3.type&&i10<pp3.#parts.length;i10++){for(const part of n8.#parts){if(typeof part==="string"){throw new Error("string part in extglob AST??")}part.copyIn(pp3.#parts[i10])}}p=pp3;pp3=p.#parent}}return this}push(...parts){for(const p of parts){if(p==="")continue;if(typeof p!=="string"&&!(p instanceof _a&&p.#parent===this)){throw new Error("invalid part: "+p)}this.#parts.push(p)}}toJSON(){const ret=this.type===null?this.#parts.slice().map(p=>typeof p==="string"?p:p.toJSON()):[this.type,...this.#parts.map(p=>p.toJSON())];if(this.isStart()&&!this.type)ret.unshift([]);if(this.isEnd()&&(this===this.#root||this.#root.#filledNegs&&this.#parent?.type==="!")){ret.push({})}return ret}isStart(){if(this.#root===this)return true;if(!this.#parent?.isStart())return false;if(this.#parentIndex===0)return true;const p=this.#parent;for(let i10=0;i10<this.#parentIndex;i10++){const pp3=p.#parts[i10];if(!(pp3 instanceof _a&&pp3.type==="!")){return false}}return true}isEnd(){if(this.#root===this)return true;if(this.#parent?.type==="!")return true;if(!this.#parent?.isEnd())return false;if(!this.type)return this.#parent?.isEnd();const pl2=this.#parent?this.#parent.#parts.length:0;return this.#parentIndex===pl2-1}copyIn(part){if(typeof part==="string")this.push(part);else this.push(part.clone(this))}clone(parent){const c=new _a(this.type,parent);for(const p of this.#parts){c.copyIn(p)}return c}static#parseAST(str,ast,pos,opt,extDepth){const maxDepth=opt.maxExtglobRecursion??2;let escaping=false;let inBrace=false;let braceStart=-1;let braceNeg=false;if(ast.type===null){let i11=pos;let acc2="";while(i11<str.length){const c=str.charAt(i11++);if(escaping||c==="\\"){escaping=!escaping;acc2+=c;continue}if(inBrace){if(i11===braceStart+1){if(c==="^"||c==="!"){braceNeg=true}}else if(c==="]"&&!(i11===braceStart+2&&braceNeg)){inBrace=false}acc2+=c;continue}else if(c==="["){inBrace=true;braceStart=i11;braceNeg=false;acc2+=c;continue}const doRecurse=!opt.noext&&isExtglobType(c)&&str.charAt(i11)==="("&&extDepth<=maxDepth;if(doRecurse){ast.push(acc2);acc2="";const ext2=new _a(c,ast);i11=_a.#parseAST(str,ext2,i11,opt,extDepth+1);ast.push(ext2);continue}acc2+=c}ast.push(acc2);return i11}let i10=pos+1;let part=new _a(null,ast);const parts=[];let acc="";while(i10<str.length){const c=str.charAt(i10++);if(escaping||c==="\\"){escaping=!escaping;acc+=c;continue}if(inBrace){if(i10===braceStart+1){if(c==="^"||c==="!"){braceNeg=true}}else if(c==="]"&&!(i10===braceStart+2&&braceNeg)){inBrace=false}acc+=c;continue}else if(c==="["){inBrace=true;braceStart=i10;braceNeg=false;acc+=c;continue}const doRecurse=!opt.noext&&isExtglobType(c)&&str.charAt(i10)==="("&&(extDepth<=maxDepth||ast&&ast.#canAdoptType(c));if(doRecurse){const depthAdd=ast&&ast.#canAdoptType(c)?0:1;part.push(acc);acc="";const ext2=new _a(c,part);part.push(ext2);i10=_a.#parseAST(str,ext2,i10,opt,extDepth+depthAdd);continue}if(c==="|"){part.push(acc);acc="";parts.push(part);part=new _a(null,ast);continue}if(c===")"){if(acc===""&&ast.#parts.length===0){ast.#emptyExt=true}part.push(acc);acc="";ast.push(...parts,part);return i10}acc+=c}ast.type=null;ast.#hasMagic=void 0;ast.#parts=[str.substring(pos-1)];return i10}#canAdoptWithSpace(child){return this.#canAdopt(child,adoptionWithSpaceMap)}#canAdopt(child,map=adoptionMap){if(!child||typeof child!=="object"||child.type!==null||child.#parts.length!==1||this.type===null){return false}const gc2=child.#parts[0];if(!gc2||typeof gc2!=="object"||gc2.type===null){return false}return this.#canAdoptType(gc2.type,map)}#canAdoptType(c,map=adoptionAnyMap){return!!map.get(this.type)?.includes(c)}#adoptWithSpace(child,index2){const gc2=child.#parts[0];const blank=new _a(null,gc2,this.options);blank.#parts.push("");gc2.push(blank);this.#adopt(child,index2)}#adopt(child,index2){const gc2=child.#parts[0];this.#parts.splice(index2,1,...gc2.#parts);for(const p of gc2.#parts){if(typeof p==="object")p.#parent=this}this.#toString=void 0}#canUsurpType(c){const m=usurpMap.get(this.type);return!!m?.has(c)}#canUsurp(child){if(!child||typeof child!=="object"||child.type!==null||child.#parts.length!==1||this.type===null||this.#parts.length!==1){return false}const gc2=child.#parts[0];if(!gc2||typeof gc2!=="object"||gc2.type===null){return false}return this.#canUsurpType(gc2.type)}#usurp(child){const m=usurpMap.get(this.type);const gc2=child.#parts[0];const nt2=m?.get(gc2.type);if(!nt2)return false;this.#parts=gc2.#parts;for(const p of this.#parts){if(typeof p==="object"){p.#parent=this}}this.type=nt2;this.#toString=void 0;this.#emptyExt=false}static fromGlob(pattern,options={}){const ast=new _a(null,void 0,options);_a.#parseAST(pattern,ast,0,options,0);return ast}toMMPattern(){if(this!==this.#root)return this.#root.toMMPattern();const glob=this.toString();const[re2,body,hasMagic,uflag]=this.toRegExpSource();const anyMagic=hasMagic||this.#hasMagic||this.#options.nocase&&!this.#options.nocaseMagicOnly&&glob.toUpperCase()!==glob.toLowerCase();if(!anyMagic){return body}const flags=(this.#options.nocase?"i":"")+(uflag?"u":"");return Object.assign(new RegExp(`^${re2}$`,flags),{_src:re2,_glob:glob})}get options(){return this.#options}toRegExpSource(allowDot){const dot=allowDot??!!this.#options.dot;if(this.#root===this){this.#flatten();this.#fillNegs()}if(!isExtglobAST(this)){const noEmpty=this.isStart()&&this.isEnd()&&!this.#parts.some(s10=>typeof s10!=="string");const src=this.#parts.map(p=>{const[re2,_,hasMagic,uflag]=typeof p==="string"?_a.#parseGlob(p,this.#hasMagic,noEmpty):p.toRegExpSource(allowDot);this.#hasMagic=this.#hasMagic||hasMagic;this.#uflag=this.#uflag||uflag;return re2}).join("");let start2="";if(this.isStart()){if(typeof this.#parts[0]==="string"){const dotTravAllowed=this.#parts.length===1&&justDots.has(this.#parts[0]);if(!dotTravAllowed){const aps=addPatternStart;const needNoTrav=dot&&aps.has(src.charAt(0))||src.startsWith("\\.")&&aps.has(src.charAt(2))||src.startsWith("\\.\\.")&&aps.has(src.charAt(4));const needNoDot=!dot&&!allowDot&&aps.has(src.charAt(0));start2=needNoTrav?startNoTraversal:needNoDot?startNoDot:""}}}let end="";if(this.isEnd()&&this.#root.#filledNegs&&this.#parent?.type==="!"){end="(?:$|\\/)"}const final2=start2+src+end;return[final2,unescape(src),this.#hasMagic=!!this.#hasMagic,this.#uflag]}const repeated=this.type==="*"||this.type==="+";const start=this.type==="!"?"(?:(?!(?:":"(?:";let body=this.#partsToRegExp(dot);if(this.isStart()&&this.isEnd()&&!body&&this.type!=="!"){const s10=this.toString();const me=this;me.#parts=[s10];me.type=null;me.#hasMagic=void 0;return[s10,unescape(this.toString()),false,false]}let bodyDotAllowed=!repeated||allowDot||dot||!startNoDot?"":this.#partsToRegExp(true);if(bodyDotAllowed===body){bodyDotAllowed=""}if(bodyDotAllowed){body=`(?:${body})(?:${bodyDotAllowed})*?`}let final="";if(this.type==="!"&&this.#emptyExt){final=(this.isStart()&&!dot?startNoDot:"")+starNoEmpty}else{const close2=this.type==="!"?"))"+(this.isStart()&&!dot&&!allowDot?startNoDot:"")+star+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&bodyDotAllowed?")":this.type==="*"&&bodyDotAllowed?`)?`:`)${this.type}`;final=start+body+close2}return[final,unescape(body),this.#hasMagic=!!this.#hasMagic,this.#uflag]}#flatten(){if(!isExtglobAST(this)){for(const p of this.#parts){if(typeof p==="object"){p.#flatten()}}}else{let iterations=0;let done=false;do{done=true;for(let i10=0;i10<this.#parts.length;i10++){const c=this.#parts[i10];if(typeof c==="object"){c.#flatten();if(this.#canAdopt(c)){done=false;this.#adopt(c,i10)}else if(this.#canAdoptWithSpace(c)){done=false;this.#adoptWithSpace(c,i10)}else if(this.#canUsurp(c)){done=false;this.#usurp(c)}}}}while(!done&&++iterations<10)}this.#toString=void 0}#partsToRegExp(dot){return this.#parts.map(p=>{if(typeof p==="string"){throw new Error("string type in extglob ast??")}const[re2,_,_hasMagic,uflag]=p.toRegExpSource(dot);this.#uflag=this.#uflag||uflag;return re2}).filter(p=>!(this.isStart()&&this.isEnd())||!!p).join("|")}static#parseGlob(glob,hasMagic,noEmpty=false){let escaping=false;let re2="";let uflag=false;let inStar=false;for(let i10=0;i10<glob.length;i10++){const c=glob.charAt(i10);if(escaping){escaping=false;re2+=(reSpecials.has(c)?"\\":"")+c;continue}if(c==="*"){if(inStar)continue;inStar=true;re2+=noEmpty&&/^[*]+$/.test(glob)?starNoEmpty:star;hasMagic=true;continue}else{inStar=false}if(c==="\\"){if(i10===glob.length-1){re2+="\\\\"}else{escaping=true}continue}if(c==="["){const[src,needUflag,consumed,magic]=parseClass(glob,i10);if(consumed){re2+=src;uflag=uflag||needUflag;i10+=consumed-1;hasMagic=hasMagic||magic;continue}}if(c==="?"){re2+=qmark;hasMagic=true;continue}re2+=regExpEscape(c)}return[re2,unescape(glob),!!hasMagic,uflag]}};_a=AST;var escape=(s10,{windowsPathsNoEscape=false,magicalBraces=false}={})=>{if(magicalBraces){return windowsPathsNoEscape?s10.replace(/[?*()[\]{}]/g,"[$&]"):s10.replace(/[?*()[\]\\{}]/g,"\\$&")}return windowsPathsNoEscape?s10.replace(/[?*()[\]]/g,"[$&]"):s10.replace(/[?*()[\]\\]/g,"\\$&")};var minimatch=(p,pattern,options={})=>{assertValidPattern(pattern);if(!options.nocomment&&pattern.charAt(0)==="#"){return false}return new Minimatch(pattern,options).match(p)};var starDotExtRE=/^\*+([^+@!?*[(]*)$/;var starDotExtTest=ext2=>f10=>!f10.startsWith(".")&&f10.endsWith(ext2);var starDotExtTestDot=ext2=>f10=>f10.endsWith(ext2);var starDotExtTestNocase=ext2=>{ext2=ext2.toLowerCase();return f10=>!f10.startsWith(".")&&f10.toLowerCase().endsWith(ext2)};var starDotExtTestNocaseDot=ext2=>{ext2=ext2.toLowerCase();return f10=>f10.toLowerCase().endsWith(ext2)};var starDotStarRE=/^\*+\.\*+$/;var starDotStarTest=f10=>!f10.startsWith(".")&&f10.includes(".");var starDotStarTestDot=f10=>f10!=="."&&f10!==".."&&f10.includes(".");var dotStarRE=/^\.\*+$/;var dotStarTest=f10=>f10!=="."&&f10!==".."&&f10.startsWith(".");var starRE=/^\*+$/;var starTest=f10=>f10.length!==0&&!f10.startsWith(".");var starTestDot=f10=>f10.length!==0&&f10!=="."&&f10!=="..";var qmarksRE=/^\?+([^+@!?*[(]*)?$/;var qmarksTestNocase=([$02,ext2=""])=>{const noext=qmarksTestNoExt([$02]);if(!ext2)return noext;ext2=ext2.toLowerCase();return f10=>noext(f10)&&f10.toLowerCase().endsWith(ext2)};var qmarksTestNocaseDot=([$02,ext2=""])=>{const noext=qmarksTestNoExtDot([$02]);if(!ext2)return noext;ext2=ext2.toLowerCase();return f10=>noext(f10)&&f10.toLowerCase().endsWith(ext2)};var qmarksTestDot=([$02,ext2=""])=>{const noext=qmarksTestNoExtDot([$02]);return!ext2?noext:f10=>noext(f10)&&f10.endsWith(ext2)};var qmarksTest=([$02,ext2=""])=>{const noext=qmarksTestNoExt([$02]);return!ext2?noext:f10=>noext(f10)&&f10.endsWith(ext2)};var qmarksTestNoExt=([$02])=>{const len2=$02.length;return f10=>f10.length===len2&&!f10.startsWith(".")};var qmarksTestNoExtDot=([$02])=>{const len2=$02.length;return f10=>f10.length===len2&&f10!=="."&&f10!==".."};var defaultPlatform=typeof process==="object"&&process?typeof process.env==="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix";var path={win32:{sep:"\\"},posix:{sep:"/"}};var sep=defaultPlatform==="win32"?path.win32.sep:path.posix.sep;minimatch.sep=sep;var GLOBSTAR=Symbol("globstar **");minimatch.GLOBSTAR=GLOBSTAR;var qmark2="[^/]";var star2=qmark2+"*?";var twoStarDot="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";var twoStarNoDot="(?:(?!(?:\\/|^)\\.).)*?";var filter=(pattern,options={})=>p=>minimatch(p,pattern,options);minimatch.filter=filter;var ext=(a,b={})=>Object.assign({},a,b);var defaults=def=>{if(!def||typeof def!=="object"||!Object.keys(def).length){return minimatch}const orig=minimatch;const m=(p,pattern,options={})=>orig(p,pattern,ext(def,options));return Object.assign(m,{Minimatch:class Minimatch extends orig.Minimatch{constructor(pattern,options={}){super(pattern,ext(def,options))}static defaults(options){return orig.defaults(ext(def,options)).Minimatch}},AST:class AST extends orig.AST{constructor(type2,parent,options={}){super(type2,parent,ext(def,options))}static fromGlob(pattern,options={}){return orig.AST.fromGlob(pattern,ext(def,options))}},unescape:(s10,options={})=>orig.unescape(s10,ext(def,options)),escape:(s10,options={})=>orig.escape(s10,ext(def,options)),filter:(pattern,options={})=>orig.filter(pattern,ext(def,options)),defaults:options=>orig.defaults(ext(def,options)),makeRe:(pattern,options={})=>orig.makeRe(pattern,ext(def,options)),braceExpand:(pattern,options={})=>orig.braceExpand(pattern,ext(def,options)),match:(list2,pattern,options={})=>orig.match(list2,pattern,ext(def,options)),sep:orig.sep,GLOBSTAR})};minimatch.defaults=defaults;var braceExpand=(pattern,options={})=>{assertValidPattern(pattern);if(options.nobrace||!/\{(?:(?!\{).)*\}/.test(pattern)){return[pattern]}return expand(pattern,{max:options.braceExpandMax})};minimatch.braceExpand=braceExpand;var makeRe=(pattern,options={})=>new Minimatch(pattern,options).makeRe();minimatch.makeRe=makeRe;var match=(list2,pattern,options={})=>{const mm2=new Minimatch(pattern,options);list2=list2.filter(f10=>mm2.match(f10));if(mm2.options.nonull&&!list2.length){list2.push(pattern)}return list2};minimatch.match=match;var globMagic=/[?*]|[+@!]\(.*?\)|\[|\]/;var regExpEscape2=s10=>s10.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");var Minimatch=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(pattern,options={}){assertValidPattern(pattern);options=options||{};this.options=options;this.maxGlobstarRecursion=options.maxGlobstarRecursion??200;this.pattern=pattern;this.platform=options.platform||defaultPlatform;this.isWindows=this.platform==="win32";const awe="allowWindowsEscape";this.windowsPathsNoEscape=!!options.windowsPathsNoEscape||options[awe]===false;if(this.windowsPathsNoEscape){this.pattern=this.pattern.replace(/\\/g,"/")}this.preserveMultipleSlashes=!!options.preserveMultipleSlashes;this.regexp=null;this.negate=false;this.nonegate=!!options.nonegate;this.comment=false;this.empty=false;this.partial=!!options.partial;this.nocase=!!this.options.nocase;this.windowsNoMagicRoot=options.windowsNoMagicRoot!==void 0?options.windowsNoMagicRoot:!!(this.isWindows&&this.nocase);this.globSet=[];this.globParts=[];this.set=[];this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1){return true}for(const pattern of this.set){for(const part of pattern){if(typeof part!=="string")return true}}return false}debug(..._){}make(){const pattern=this.pattern;const options=this.options;if(!options.nocomment&&pattern.charAt(0)==="#"){this.comment=true;return}if(!pattern){this.empty=true;return}this.parseNegate();this.globSet=[...new Set(this.braceExpand())];if(options.debug){this.debug=(...args)=>console.error(...args)}this.debug(this.pattern,this.globSet);const rawGlobParts=this.globSet.map(s10=>this.slashSplit(s10));this.globParts=this.preprocess(rawGlobParts);this.debug(this.pattern,this.globParts);let set=this.globParts.map((s10,_,__)=>{if(this.isWindows&&this.windowsNoMagicRoot){const isUNC=s10[0]===""&&s10[1]===""&&(s10[2]==="?"||!globMagic.test(s10[2]))&&!globMagic.test(s10[3]);const isDrive=/^[a-z]:/i.test(s10[0]);if(isUNC){return[...s10.slice(0,4),...s10.slice(4).map(ss2=>this.parse(ss2))]}else if(isDrive){return[s10[0],...s10.slice(1).map(ss2=>this.parse(ss2))]}}return s10.map(ss2=>this.parse(ss2))});this.debug(this.pattern,set);this.set=set.filter(s10=>s10.indexOf(false)===-1);if(this.isWindows){for(let i10=0;i10<this.set.length;i10++){const p=this.set[i10];if(p[0]===""&&p[1]===""&&this.globParts[i10][2]==="?"&&typeof p[3]==="string"&&/^[a-z]:$/i.test(p[3])){p[2]="?"}}}this.debug(this.pattern,this.set)}preprocess(globParts){if(this.options.noglobstar){for(const partset of globParts){for(let j=0;j<partset.length;j++){if(partset[j]==="**"){partset[j]="*"}}}}const{optimizationLevel=1}=this.options;if(optimizationLevel>=2){globParts=this.firstPhasePreProcess(globParts);globParts=this.secondPhasePreProcess(globParts)}else if(optimizationLevel>=1){globParts=this.levelOneOptimize(globParts)}else{globParts=this.adjascentGlobstarOptimize(globParts)}return globParts}adjascentGlobstarOptimize(globParts){return globParts.map(parts=>{let gs2=-1;while(-1!==(gs2=parts.indexOf("**",gs2+1))){let i10=gs2;while(parts[i10+1]==="**"){i10++}if(i10!==gs2){parts.splice(gs2,i10-gs2)}}return parts})}levelOneOptimize(globParts){return globParts.map(parts=>{parts=parts.reduce((set,part)=>{const prev=set[set.length-1];if(part==="**"&&prev==="**"){return set}if(part===".."){if(prev&&prev!==".."&&prev!=="."&&prev!=="**"){set.pop();return set}}set.push(part);return set},[]);return parts.length===0?[""]:parts})}levelTwoFileOptimize(parts){if(!Array.isArray(parts)){parts=this.slashSplit(parts)}let didSomething=false;do{didSomething=false;if(!this.preserveMultipleSlashes){for(let i10=1;i10<parts.length-1;i10++){const p=parts[i10];if(i10===1&&p===""&&parts[0]==="")continue;if(p==="."||p===""){didSomething=true;parts.splice(i10,1);i10--}}if(parts[0]==="."&&parts.length===2&&(parts[1]==="."||parts[1]==="")){didSomething=true;parts.pop()}}let dd2=0;while(-1!==(dd2=parts.indexOf("..",dd2+1))){const p=parts[dd2-1];if(p&&p!=="."&&p!==".."&&p!=="**"&&!(this.isWindows&&/^[a-z]:$/i.test(p))){didSomething=true;parts.splice(dd2-1,2);dd2-=2}}}while(didSomething);return parts.length===0?[""]:parts}firstPhasePreProcess(globParts){let didSomething=false;do{didSomething=false;for(let parts of globParts){let gs2=-1;while(-1!==(gs2=parts.indexOf("**",gs2+1))){let gss=gs2;while(parts[gss+1]==="**"){gss++}if(gss>gs2){parts.splice(gs2+1,gss-gs2)}let next2=parts[gs2+1];const p=parts[gs2+2];const p22=parts[gs2+3];if(next2!=="..")continue;if(!p||p==="."||p===".."||!p22||p22==="."||p22===".."){continue}didSomething=true;parts.splice(gs2,1);const other=parts.slice(0);other[gs2]="**";globParts.push(other);gs2--}if(!this.preserveMultipleSlashes){for(let i10=1;i10<parts.length-1;i10++){const p=parts[i10];if(i10===1&&p===""&&parts[0]==="")continue;if(p==="."||p===""){didSomething=true;parts.splice(i10,1);i10--}}if(parts[0]==="."&&parts.length===2&&(parts[1]==="."||parts[1]==="")){didSomething=true;parts.pop()}}let dd2=0;while(-1!==(dd2=parts.indexOf("..",dd2+1))){const p=parts[dd2-1];if(p&&p!=="."&&p!==".."&&p!=="**"){didSomething=true;const needDot=dd2===1&&parts[dd2+1]==="**";const splin=needDot?["."]:[];parts.splice(dd2-1,2,...splin);if(parts.length===0)parts.push("");dd2-=2}}}}while(didSomething);return globParts}secondPhasePreProcess(globParts){for(let i10=0;i10<globParts.length-1;i10++){for(let j=i10+1;j<globParts.length;j++){const matched=this.partsMatch(globParts[i10],globParts[j],!this.preserveMultipleSlashes);if(matched){globParts[i10]=[];globParts[j]=matched;break}}}return globParts.filter(gs2=>gs2.length)}partsMatch(a,b,emptyGSMatch=false){let ai2=0;let bi2=0;let result=[];let which="";while(ai2<a.length&&bi2<b.length){if(a[ai2]===b[bi2]){result.push(which==="b"?b[bi2]:a[ai2]);ai2++;bi2++}else if(emptyGSMatch&&a[ai2]==="**"&&b[bi2]===a[ai2+1]){result.push(a[ai2]);ai2++}else if(emptyGSMatch&&b[bi2]==="**"&&a[ai2]===b[bi2+1]){result.push(b[bi2]);bi2++}else if(a[ai2]==="*"&&b[bi2]&&(this.options.dot||!b[bi2].startsWith("."))&&b[bi2]!=="**"){if(which==="b")return false;which="a";result.push(a[ai2]);ai2++;bi2++}else if(b[bi2]==="*"&&a[ai2]&&(this.options.dot||!a[ai2].startsWith("."))&&a[ai2]!=="**"){if(which==="a")return false;which="b";result.push(b[bi2]);ai2++;bi2++}else{return false}}return a.length===b.length&&result}parseNegate(){if(this.nonegate)return;const pattern=this.pattern;let negate=false;let negateOffset=0;for(let i10=0;i10<pattern.length&&pattern.charAt(i10)==="!";i10++){negate=!negate;negateOffset++}if(negateOffset)this.pattern=pattern.slice(negateOffset);this.negate=negate}matchOne(file2,pattern,partial=false){let fileStartIndex=0;let patternStartIndex=0;if(this.isWindows){const fileDrive=typeof file2[0]==="string"&&/^[a-z]:$/i.test(file2[0]);const fileUNC=!fileDrive&&file2[0]===""&&file2[1]===""&&file2[2]==="?"&&/^[a-z]:$/i.test(file2[3]);const patternDrive=typeof pattern[0]==="string"&&/^[a-z]:$/i.test(pattern[0]);const patternUNC=!patternDrive&&pattern[0]===""&&pattern[1]===""&&pattern[2]==="?"&&typeof pattern[3]==="string"&&/^[a-z]:$/i.test(pattern[3]);const fdi=fileUNC?3:fileDrive?0:void 0;const pdi=patternUNC?3:patternDrive?0:void 0;if(typeof fdi==="number"&&typeof pdi==="number"){const[fd2,pd2]=[file2[fdi],pattern[pdi]];if(fd2.toLowerCase()===pd2.toLowerCase()){pattern[pdi]=fd2;patternStartIndex=pdi;fileStartIndex=fdi}}}const{optimizationLevel=1}=this.options;if(optimizationLevel>=2){file2=this.levelTwoFileOptimize(file2)}if(pattern.includes(GLOBSTAR)){return this.#matchGlobstar(file2,pattern,partial,fileStartIndex,patternStartIndex)}return this.#matchOne(file2,pattern,partial,fileStartIndex,patternStartIndex)}#matchGlobstar(file2,pattern,partial,fileIndex,patternIndex){const firstgs=pattern.indexOf(GLOBSTAR,patternIndex);const lastgs=pattern.lastIndexOf(GLOBSTAR);const[head,body,tail]=partial?[pattern.slice(patternIndex,firstgs),pattern.slice(firstgs+1),[]]:[pattern.slice(patternIndex,firstgs),pattern.slice(firstgs+1,lastgs),pattern.slice(lastgs+1)];if(head.length){const fileHead=file2.slice(fileIndex,fileIndex+head.length);if(!this.#matchOne(fileHead,head,partial,0,0)){return false}fileIndex+=head.length;patternIndex+=head.length}let fileTailMatch=0;if(tail.length){if(tail.length+fileIndex>file2.length)return false;let tailStart=file2.length-tail.length;if(this.#matchOne(file2,tail,partial,tailStart,0)){fileTailMatch=tail.length}else{if(file2[file2.length-1]!==""||fileIndex+tail.length===file2.length){return false}tailStart--;if(!this.#matchOne(file2,tail,partial,tailStart,0)){return false}fileTailMatch=tail.length+1}}if(!body.length){let sawSome=!!fileTailMatch;for(let i11=fileIndex;i11<file2.length-fileTailMatch;i11++){const f10=String(file2[i11]);sawSome=true;if(f10==="."||f10===".."||!this.options.dot&&f10.startsWith(".")){return false}}return partial||sawSome}const bodySegments=[[[],0]];let currentBody=bodySegments[0];let nonGsParts=0;const nonGsPartsSums=[0];for(const b of body){if(b===GLOBSTAR){nonGsPartsSums.push(nonGsParts);currentBody=[[],0];bodySegments.push(currentBody)}else{currentBody[0].push(b);nonGsParts++}}let i10=bodySegments.length-1;const fileLength=file2.length-fileTailMatch;for(const b of bodySegments){b[1]=fileLength-(nonGsPartsSums[i10--]+b[0].length)}return!!this.#matchGlobStarBodySections(file2,bodySegments,fileIndex,0,partial,0,!!fileTailMatch)}#matchGlobStarBodySections(file2,bodySegments,fileIndex,bodyIndex,partial,globStarDepth,sawTail){const bs2=bodySegments[bodyIndex];if(!bs2){for(let i10=fileIndex;i10<file2.length;i10++){sawTail=true;const f10=file2[i10];if(f10==="."||f10===".."||!this.options.dot&&f10.startsWith(".")){return false}}return sawTail}const[body,after]=bs2;while(fileIndex<=after){const m=this.#matchOne(file2.slice(0,fileIndex+body.length),body,partial,fileIndex,0);if(m&&globStarDepth<this.maxGlobstarRecursion){const sub=this.#matchGlobStarBodySections(file2,bodySegments,fileIndex+body.length,bodyIndex+1,partial,globStarDepth+1,sawTail);if(sub!==false){return sub}}const f10=file2[fileIndex];if(f10==="."||f10===".."||!this.options.dot&&f10.startsWith(".")){return false}fileIndex++}return partial||null}#matchOne(file2,pattern,partial,fileIndex,patternIndex){let fi2;let pi2;let pl2;let fl2;for(fi2=fileIndex,pi2=patternIndex,fl2=file2.length,pl2=pattern.length;fi2<fl2&&pi2<pl2;fi2++,pi2++){this.debug("matchOne loop");let p=pattern[pi2];let f10=file2[fi2];this.debug(pattern,p,f10);if(p===false||p===GLOBSTAR){return false}let hit;if(typeof p==="string"){hit=f10===p;this.debug("string match",p,f10,hit)}else{hit=p.test(f10);this.debug("pattern match",p,f10,hit)}if(!hit)return false}if(fi2===fl2&&pi2===pl2){return true}else if(fi2===fl2){return partial}else if(pi2===pl2){return fi2===fl2-1&&file2[fi2]===""}else{throw new Error("wtf?")}}braceExpand(){return braceExpand(this.pattern,this.options)}parse(pattern){assertValidPattern(pattern);const options=this.options;if(pattern==="**")return GLOBSTAR;if(pattern==="")return"";let m;let fastTest=null;if(m=pattern.match(starRE)){fastTest=options.dot?starTestDot:starTest}else if(m=pattern.match(starDotExtRE)){fastTest=(options.nocase?options.dot?starDotExtTestNocaseDot:starDotExtTestNocase:options.dot?starDotExtTestDot:starDotExtTest)(m[1])}else if(m=pattern.match(qmarksRE)){fastTest=(options.nocase?options.dot?qmarksTestNocaseDot:qmarksTestNocase:options.dot?qmarksTestDot:qmarksTest)(m)}else if(m=pattern.match(starDotStarRE)){fastTest=options.dot?starDotStarTestDot:starDotStarTest}else if(m=pattern.match(dotStarRE)){fastTest=dotStarTest}const re2=AST.fromGlob(pattern,this.options).toMMPattern();if(fastTest&&typeof re2==="object"){Reflect.defineProperty(re2,"test",{value:fastTest})}return re2}makeRe(){if(this.regexp||this.regexp===false)return this.regexp;const set=this.set;if(!set.length){this.regexp=false;return this.regexp}const options=this.options;const twoStar=options.noglobstar?star2:options.dot?twoStarDot:twoStarNoDot;const flags=new Set(options.nocase?["i"]:[]);let re2=set.map(pattern=>{const pp3=pattern.map(p=>{if(p instanceof RegExp){for(const f10 of p.flags.split(""))flags.add(f10)}return typeof p==="string"?regExpEscape2(p):p===GLOBSTAR?GLOBSTAR:p._src});pp3.forEach((p,i10)=>{const next2=pp3[i10+1];const prev=pp3[i10-1];if(p!==GLOBSTAR||prev===GLOBSTAR){return}if(prev===void 0){if(next2!==void 0&&next2!==GLOBSTAR){pp3[i10+1]="(?:\\/|"+twoStar+"\\/)?"+next2}else{pp3[i10]=twoStar}}else if(next2===void 0){pp3[i10-1]=prev+"(?:\\/|\\/"+twoStar+")?"}else if(next2!==GLOBSTAR){pp3[i10-1]=prev+"(?:\\/|\\/"+twoStar+"\\/)"+next2;pp3[i10+1]=GLOBSTAR}});const filtered=pp3.filter(p=>p!==GLOBSTAR);if(this.partial&&filtered.length>=1){const prefixes=[];for(let i10=1;i10<=filtered.length;i10++){prefixes.push(filtered.slice(0,i10).join("/"))}return"(?:"+prefixes.join("|")+")"}return filtered.join("/")}).join("|");const[open2,close2]=set.length>1?["(?:",")"]:["",""];re2="^"+open2+re2+close2+"$";if(this.partial){re2="^(?:\\/|"+open2+re2.slice(1,-1)+close2+")$"}if(this.negate)re2="^(?!"+re2+").+$";try{this.regexp=new RegExp(re2,[...flags].join(""))}catch{this.regexp=false}return this.regexp}slashSplit(p){if(this.preserveMultipleSlashes){return p.split("/")}else if(this.isWindows&&/^\/\/[^/]+/.test(p)){return["",...p.split(/\/+/)]}else{return p.split(/\/+/)}}match(f10,partial=this.partial){this.debug("match",f10,this.pattern);if(this.comment){return false}if(this.empty){return f10===""}if(f10==="/"&&partial){return true}const options=this.options;if(this.isWindows){f10=f10.split("\\").join("/")}const ff2=this.slashSplit(f10);this.debug(this.pattern,"split",ff2);const set=this.set;this.debug(this.pattern,"set",set);let filename=ff2[ff2.length-1];if(!filename){for(let i10=ff2.length-2;!filename&&i10>=0;i10--){filename=ff2[i10]}}for(const pattern of set){let file2=ff2;if(options.matchBase&&pattern.length===1){file2=[filename]}const hit=this.matchOne(file2,pattern,partial);if(hit){if(options.flipNegate){return true}return!this.negate}}if(options.flipNegate){return false}return this.negate}static defaults(def){return minimatch.defaults(def).Minimatch}};minimatch.AST=AST;minimatch.Minimatch=Minimatch;minimatch.escape=escape;minimatch.unescape=unescape;var Z_FIXED$1=4;var Z_BINARY=0;var Z_TEXT=1;var Z_UNKNOWN$1=2;function zero$1(buf){let len2=buf.length;while(--len2>=0){buf[len2]=0}}var STORED_BLOCK=0;var STATIC_TREES=1;var DYN_TREES=2;var MIN_MATCH$1=3;var MAX_MATCH$1=258;var LENGTH_CODES$1=29;var LITERALS$1=256;var L_CODES$1=LITERALS$1+1+LENGTH_CODES$1;var D_CODES$1=30;var BL_CODES$1=19;var HEAP_SIZE$1=2*L_CODES$1+1;var MAX_BITS$1=15;var Buf_size=16;var MAX_BL_BITS=7;var END_BLOCK=256;var REP_3_6=16;var REPZ_3_10=17;var REPZ_11_138=18;var extra_lbits=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]);var extra_dbits=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]);var extra_blbits=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]);var bl_order=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);var DIST_CODE_LEN=512;var static_ltree=new Array((L_CODES$1+2)*2);zero$1(static_ltree);var static_dtree=new Array(D_CODES$1*2);zero$1(static_dtree);var _dist_code=new Array(DIST_CODE_LEN);zero$1(_dist_code);var _length_code=new Array(MAX_MATCH$1-MIN_MATCH$1+1);zero$1(_length_code);var base_length=new Array(LENGTH_CODES$1);zero$1(base_length);var base_dist=new Array(D_CODES$1);zero$1(base_dist);function StaticTreeDesc(static_tree,extra_bits,extra_base,elems,max_length){this.static_tree=static_tree;this.extra_bits=extra_bits;this.extra_base=extra_base;this.elems=elems;this.max_length=max_length;this.has_stree=static_tree&&static_tree.length}var static_l_desc;var static_d_desc;var static_bl_desc;function TreeDesc(dyn_tree,stat_desc){this.dyn_tree=dyn_tree;this.max_code=0;this.stat_desc=stat_desc}var d_code=dist=>{return dist<256?_dist_code[dist]:_dist_code[256+(dist>>>7)]};var put_short=(s10,w)=>{s10.pending_buf[s10.pending++]=w&255;s10.pending_buf[s10.pending++]=w>>>8&255};var send_bits=(s10,value,length)=>{if(s10.bi_valid>Buf_size-length){s10.bi_buf|=value<<s10.bi_valid&65535;put_short(s10,s10.bi_buf);s10.bi_buf=value>>Buf_size-s10.bi_valid;s10.bi_valid+=length-Buf_size}else{s10.bi_buf|=value<<s10.bi_valid&65535;s10.bi_valid+=length}};var send_code=(s10,c,tree2)=>{send_bits(s10,tree2[c*2],tree2[c*2+1])};var bi_reverse=(code3,len2)=>{let res=0;do{res|=code3&1;code3>>>=1;res<<=1}while(--len2>0);return res>>>1};var bi_flush=s10=>{if(s10.bi_valid===16){put_short(s10,s10.bi_buf);s10.bi_buf=0;s10.bi_valid=0}else if(s10.bi_valid>=8){s10.pending_buf[s10.pending++]=s10.bi_buf&255;s10.bi_buf>>=8;s10.bi_valid-=8}};var gen_bitlen=(s10,desc)=>{const tree2=desc.dyn_tree;const max_code=desc.max_code;const stree=desc.stat_desc.static_tree;const has_stree=desc.stat_desc.has_stree;const extra=desc.stat_desc.extra_bits;const base=desc.stat_desc.extra_base;const max_length=desc.stat_desc.max_length;let h;let n8,m;let bits;let xbits;let f10;let overflow=0;for(bits=0;bits<=MAX_BITS$1;bits++){s10.bl_count[bits]=0}tree2[s10.heap[s10.heap_max]*2+1]=0;for(h=s10.heap_max+1;h<HEAP_SIZE$1;h++){n8=s10.heap[h];bits=tree2[tree2[n8*2+1]*2+1]+1;if(bits>max_length){bits=max_length;overflow++}tree2[n8*2+1]=bits;if(n8>max_code){continue}s10.bl_count[bits]++;xbits=0;if(n8>=base){xbits=extra[n8-base]}f10=tree2[n8*2];s10.opt_len+=f10*(bits+xbits);if(has_stree){s10.static_len+=f10*(stree[n8*2+1]+xbits)}}if(overflow===0){return}do{bits=max_length-1;while(s10.bl_count[bits]===0){bits--}s10.bl_count[bits]--;s10.bl_count[bits+1]+=2;s10.bl_count[max_length]--;overflow-=2}while(overflow>0);for(bits=max_length;bits!==0;bits--){n8=s10.bl_count[bits];while(n8!==0){m=s10.heap[--h];if(m>max_code){continue}if(tree2[m*2+1]!==bits){s10.opt_len+=(bits-tree2[m*2+1])*tree2[m*2];tree2[m*2+1]=bits}n8--}}};var gen_codes=(tree2,max_code,bl_count)=>{const next_code=new Array(MAX_BITS$1+1);let code3=0;let bits;let n8;for(bits=1;bits<=MAX_BITS$1;bits++){code3=code3+bl_count[bits-1]<<1;next_code[bits]=code3}for(n8=0;n8<=max_code;n8++){let len2=tree2[n8*2+1];if(len2===0){continue}tree2[n8*2]=bi_reverse(next_code[len2]++,len2)}};var tr_static_init=()=>{let n8;let bits;let length;let code3;let dist;const bl_count=new Array(MAX_BITS$1+1);length=0;for(code3=0;code3<LENGTH_CODES$1-1;code3++){base_length[code3]=length;for(n8=0;n8<1<<extra_lbits[code3];n8++){_length_code[length++]=code3}}_length_code[length-1]=code3;dist=0;for(code3=0;code3<16;code3++){base_dist[code3]=dist;for(n8=0;n8<1<<extra_dbits[code3];n8++){_dist_code[dist++]=code3}}dist>>=7;for(;code3<D_CODES$1;code3++){base_dist[code3]=dist<<7;for(n8=0;n8<1<<extra_dbits[code3]-7;n8++){_dist_code[256+dist++]=code3}}for(bits=0;bits<=MAX_BITS$1;bits++){bl_count[bits]=0}n8=0;while(n8<=143){static_ltree[n8*2+1]=8;n8++;bl_count[8]++}while(n8<=255){static_ltree[n8*2+1]=9;n8++;bl_count[9]++}while(n8<=279){static_ltree[n8*2+1]=7;n8++;bl_count[7]++}while(n8<=287){static_ltree[n8*2+1]=8;n8++;bl_count[8]++}gen_codes(static_ltree,L_CODES$1+1,bl_count);for(n8=0;n8<D_CODES$1;n8++){static_dtree[n8*2+1]=5;static_dtree[n8*2]=bi_reverse(n8,5)}static_l_desc=new StaticTreeDesc(static_ltree,extra_lbits,LITERALS$1+1,L_CODES$1,MAX_BITS$1);static_d_desc=new StaticTreeDesc(static_dtree,extra_dbits,0,D_CODES$1,MAX_BITS$1);static_bl_desc=new StaticTreeDesc(new Array(0),extra_blbits,0,BL_CODES$1,MAX_BL_BITS)};var init_block=s10=>{let n8;for(n8=0;n8<L_CODES$1;n8++){s10.dyn_ltree[n8*2]=0}for(n8=0;n8<D_CODES$1;n8++){s10.dyn_dtree[n8*2]=0}for(n8=0;n8<BL_CODES$1;n8++){s10.bl_tree[n8*2]=0}s10.dyn_ltree[END_BLOCK*2]=1;s10.opt_len=s10.static_len=0;s10.sym_next=s10.matches=0};var bi_windup=s10=>{if(s10.bi_valid>8){put_short(s10,s10.bi_buf)}else if(s10.bi_valid>0){s10.pending_buf[s10.pending++]=s10.bi_buf}s10.bi_buf=0;s10.bi_valid=0};var smaller=(tree2,n8,m,depth4)=>{const _n2=n8*2;const _m2=m*2;return tree2[_n2]<tree2[_m2]||tree2[_n2]===tree2[_m2]&&depth4[n8]<=depth4[m]};var pqdownheap=(s10,tree2,k10)=>{const v2=s10.heap[k10];let j=k10<<1;while(j<=s10.heap_len){if(j<s10.heap_len&&smaller(tree2,s10.heap[j+1],s10.heap[j],s10.depth)){j++}if(smaller(tree2,v2,s10.heap[j],s10.depth)){break}s10.heap[k10]=s10.heap[j];k10=j;j<<=1}s10.heap[k10]=v2};var compress_block=(s10,ltree,dtree)=>{let dist;let lc2;let sx2=0;let code3;let extra;if(s10.sym_next!==0){do{dist=s10.pending_buf[s10.sym_buf+sx2++]&255;dist+=(s10.pending_buf[s10.sym_buf+sx2++]&255)<<8;lc2=s10.pending_buf[s10.sym_buf+sx2++];if(dist===0){send_code(s10,lc2,ltree)}else{code3=_length_code[lc2];send_code(s10,code3+LITERALS$1+1,ltree);extra=extra_lbits[code3];if(extra!==0){lc2-=base_length[code3];send_bits(s10,lc2,extra)}dist--;code3=d_code(dist);send_code(s10,code3,dtree);extra=extra_dbits[code3];if(extra!==0){dist-=base_dist[code3];send_bits(s10,dist,extra)}}}while(sx2<s10.sym_next)}send_code(s10,END_BLOCK,ltree)};var build_tree=(s10,desc)=>{const tree2=desc.dyn_tree;const stree=desc.stat_desc.static_tree;const has_stree=desc.stat_desc.has_stree;const elems=desc.stat_desc.elems;let n8,m;let max_code=-1;let node;s10.heap_len=0;s10.heap_max=HEAP_SIZE$1;for(n8=0;n8<elems;n8++){if(tree2[n8*2]!==0){s10.heap[++s10.heap_len]=max_code=n8;s10.depth[n8]=0}else{tree2[n8*2+1]=0}}while(s10.heap_len<2){node=s10.heap[++s10.heap_len]=max_code<2?++max_code:0;tree2[node*2]=1;s10.depth[node]=0;s10.opt_len--;if(has_stree){s10.static_len-=stree[node*2+1]}}desc.max_code=max_code;for(n8=s10.heap_len>>1;n8>=1;n8--){pqdownheap(s10,tree2,n8)}node=elems;do{n8=s10.heap[1];s10.heap[1]=s10.heap[s10.heap_len--];pqdownheap(s10,tree2,1);m=s10.heap[1];s10.heap[--s10.heap_max]=n8;s10.heap[--s10.heap_max]=m;tree2[node*2]=tree2[n8*2]+tree2[m*2];s10.depth[node]=(s10.depth[n8]>=s10.depth[m]?s10.depth[n8]:s10.depth[m])+1;tree2[n8*2+1]=tree2[m*2+1]=node;s10.heap[1]=node++;pqdownheap(s10,tree2,1)}while(s10.heap_len>=2);s10.heap[--s10.heap_max]=s10.heap[1];gen_bitlen(s10,desc);gen_codes(tree2,max_code,s10.bl_count)};var scan_tree=(s10,tree2,max_code)=>{let n8;let prevlen=-1;let curlen;let nextlen=tree2[0*2+1];let count=0;let max_count=7;let min_count=4;if(nextlen===0){max_count=138;min_count=3}tree2[(max_code+1)*2+1]=65535;for(n8=0;n8<=max_code;n8++){curlen=nextlen;nextlen=tree2[(n8+1)*2+1];if(++count<max_count&&curlen===nextlen){continue}else if(count<min_count){s10.bl_tree[curlen*2]+=count}else if(curlen!==0){if(curlen!==prevlen){s10.bl_tree[curlen*2]++}s10.bl_tree[REP_3_6*2]++}else if(count<=10){s10.bl_tree[REPZ_3_10*2]++}else{s10.bl_tree[REPZ_11_138*2]++}count=0;prevlen=curlen;if(nextlen===0){max_count=138;min_count=3}else if(curlen===nextlen){max_count=6;min_count=3}else{max_count=7;min_count=4}}};var send_tree=(s10,tree2,max_code)=>{let n8;let prevlen=-1;let curlen;let nextlen=tree2[0*2+1];let count=0;let max_count=7;let min_count=4;if(nextlen===0){max_count=138;min_count=3}for(n8=0;n8<=max_code;n8++){curlen=nextlen;nextlen=tree2[(n8+1)*2+1];if(++count<max_count&&curlen===nextlen){continue}else if(count<min_count){do{send_code(s10,curlen,s10.bl_tree)}while(--count!==0)}else if(curlen!==0){if(curlen!==prevlen){send_code(s10,curlen,s10.bl_tree);count--}send_code(s10,REP_3_6,s10.bl_tree);send_bits(s10,count-3,2)}else if(count<=10){send_code(s10,REPZ_3_10,s10.bl_tree);send_bits(s10,count-3,3)}else{send_code(s10,REPZ_11_138,s10.bl_tree);send_bits(s10,count-11,7)}count=0;prevlen=curlen;if(nextlen===0){max_count=138;min_count=3}else if(curlen===nextlen){max_count=6;min_count=3}else{max_count=7;min_count=4}}};var build_bl_tree=s10=>{let max_blindex;scan_tree(s10,s10.dyn_ltree,s10.l_desc.max_code);scan_tree(s10,s10.dyn_dtree,s10.d_desc.max_code);build_tree(s10,s10.bl_desc);for(max_blindex=BL_CODES$1-1;max_blindex>=3;max_blindex--){if(s10.bl_tree[bl_order[max_blindex]*2+1]!==0){break}}s10.opt_len+=3*(max_blindex+1)+5+5+4;return max_blindex};var send_all_trees=(s10,lcodes,dcodes,blcodes)=>{let rank3;send_bits(s10,lcodes-257,5);send_bits(s10,dcodes-1,5);send_bits(s10,blcodes-4,4);for(rank3=0;rank3<blcodes;rank3++){send_bits(s10,s10.bl_tree[bl_order[rank3]*2+1],3)}send_tree(s10,s10.dyn_ltree,lcodes-1);send_tree(s10,s10.dyn_dtree,dcodes-1)};var detect_data_type=s10=>{let block_mask=4093624447;let n8;for(n8=0;n8<=31;n8++,block_mask>>>=1){if(block_mask&1&&s10.dyn_ltree[n8*2]!==0){return Z_BINARY}}if(s10.dyn_ltree[9*2]!==0||s10.dyn_ltree[10*2]!==0||s10.dyn_ltree[13*2]!==0){return Z_TEXT}for(n8=32;n8<LITERALS$1;n8++){if(s10.dyn_ltree[n8*2]!==0){return Z_TEXT}}return Z_BINARY};var static_init_done=false;var _tr_init$1=s10=>{if(!static_init_done){tr_static_init();static_init_done=true}s10.l_desc=new TreeDesc(s10.dyn_ltree,static_l_desc);s10.d_desc=new TreeDesc(s10.dyn_dtree,static_d_desc);s10.bl_desc=new TreeDesc(s10.bl_tree,static_bl_desc);s10.bi_buf=0;s10.bi_valid=0;init_block(s10)};var _tr_stored_block$1=(s10,buf,stored_len,last)=>{send_bits(s10,(STORED_BLOCK<<1)+(last?1:0),3);bi_windup(s10);put_short(s10,stored_len);put_short(s10,~stored_len);if(stored_len){s10.pending_buf.set(s10.window.subarray(buf,buf+stored_len),s10.pending)}s10.pending+=stored_len};var _tr_align$1=s10=>{send_bits(s10,STATIC_TREES<<1,3);send_code(s10,END_BLOCK,static_ltree);bi_flush(s10)};var _tr_flush_block$1=(s10,buf,stored_len,last)=>{let opt_lenb,static_lenb;let max_blindex=0;if(s10.level>0){if(s10.strm.data_type===Z_UNKNOWN$1){s10.strm.data_type=detect_data_type(s10)}build_tree(s10,s10.l_desc);build_tree(s10,s10.d_desc);max_blindex=build_bl_tree(s10);opt_lenb=s10.opt_len+3+7>>>3;static_lenb=s10.static_len+3+7>>>3;if(static_lenb<=opt_lenb){opt_lenb=static_lenb}}else{opt_lenb=static_lenb=stored_len+5}if(stored_len+4<=opt_lenb&&buf!==-1){_tr_stored_block$1(s10,buf,stored_len,last)}else if(s10.strategy===Z_FIXED$1||static_lenb===opt_lenb){send_bits(s10,(STATIC_TREES<<1)+(last?1:0),3);compress_block(s10,static_ltree,static_dtree)}else{send_bits(s10,(DYN_TREES<<1)+(last?1:0),3);send_all_trees(s10,s10.l_desc.max_code+1,s10.d_desc.max_code+1,max_blindex+1);compress_block(s10,s10.dyn_ltree,s10.dyn_dtree)}init_block(s10);if(last){bi_windup(s10)}};var _tr_tally$1=(s10,dist,lc2)=>{s10.pending_buf[s10.sym_buf+s10.sym_next++]=dist;s10.pending_buf[s10.sym_buf+s10.sym_next++]=dist>>8;s10.pending_buf[s10.sym_buf+s10.sym_next++]=lc2;if(dist===0){s10.dyn_ltree[lc2*2]++}else{s10.matches++;dist--;s10.dyn_ltree[(_length_code[lc2]+LITERALS$1+1)*2]++;s10.dyn_dtree[d_code(dist)*2]++}return s10.sym_next===s10.sym_end};var _tr_init_1=_tr_init$1;var _tr_stored_block_1=_tr_stored_block$1;var _tr_flush_block_1=_tr_flush_block$1;var _tr_tally_1=_tr_tally$1;var _tr_align_1=_tr_align$1;var trees={_tr_init:_tr_init_1,_tr_stored_block:_tr_stored_block_1,_tr_flush_block:_tr_flush_block_1,_tr_tally:_tr_tally_1,_tr_align:_tr_align_1};var adler32=(adler,buf,len2,pos)=>{let s12=adler&65535|0,s22=adler>>>16&65535|0,n8=0;while(len2!==0){n8=len2>2e3?2e3:len2;len2-=n8;do{s12=s12+buf[pos++]|0;s22=s22+s12|0}while(--n8);s12%=65521;s22%=65521}return s12|s22<<16|0};var adler32_1=adler32;var makeTable=()=>{let c,table=[];for(var n8=0;n8<256;n8++){c=n8;for(var k10=0;k10<8;k10++){c=c&1?3988292384^c>>>1:c>>>1}table[n8]=c}return table};var crcTable=new Uint32Array(makeTable());var crc322=(crc,buf,len2,pos)=>{const t10=crcTable;const end=pos+len2;crc^=-1;for(let i10=pos;i10<end;i10++){crc=crc>>>8^t10[(crc^buf[i10])&255]}return crc^-1};var crc32_1=crc322;var messages={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"};var constants$2={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};var{_tr_init,_tr_stored_block,_tr_flush_block,_tr_tally,_tr_align}=trees;var{Z_NO_FLUSH:Z_NO_FLUSH$2,Z_PARTIAL_FLUSH,Z_FULL_FLUSH:Z_FULL_FLUSH$1,Z_FINISH:Z_FINISH$3,Z_BLOCK:Z_BLOCK$1,Z_OK:Z_OK$3,Z_STREAM_END:Z_STREAM_END$3,Z_STREAM_ERROR:Z_STREAM_ERROR$2,Z_DATA_ERROR:Z_DATA_ERROR$2,Z_BUF_ERROR:Z_BUF_ERROR$2,Z_DEFAULT_COMPRESSION:Z_DEFAULT_COMPRESSION$1,Z_FILTERED,Z_HUFFMAN_ONLY,Z_RLE,Z_FIXED,Z_DEFAULT_STRATEGY:Z_DEFAULT_STRATEGY$1,Z_UNKNOWN,Z_DEFLATED:Z_DEFLATED$2}=constants$2;var MAX_MEM_LEVEL=9;var MAX_WBITS$1=15;var DEF_MEM_LEVEL=8;var LENGTH_CODES=29;var LITERALS=256;var L_CODES=LITERALS+1+LENGTH_CODES;var D_CODES=30;var BL_CODES=19;var HEAP_SIZE=2*L_CODES+1;var MAX_BITS=15;var MIN_MATCH=3;var MAX_MATCH=258;var MIN_LOOKAHEAD=MAX_MATCH+MIN_MATCH+1;var PRESET_DICT=32;var INIT_STATE=42;var GZIP_STATE=57;var EXTRA_STATE=69;var NAME_STATE=73;var COMMENT_STATE=91;var HCRC_STATE=103;var BUSY_STATE=113;var FINISH_STATE=666;var BS_NEED_MORE=1;var BS_BLOCK_DONE=2;var BS_FINISH_STARTED=3;var BS_FINISH_DONE=4;var OS_CODE=3;var err=(strm,errorCode)=>{strm.msg=messages[errorCode];return errorCode};var rank=f10=>{return f10*2-(f10>4?9:0)};var zero=buf=>{let len2=buf.length;while(--len2>=0){buf[len2]=0}};var slide_hash=s10=>{let n8,m;let p;let wsize=s10.w_size;n8=s10.hash_size;p=n8;do{m=s10.head[--p];s10.head[p]=m>=wsize?m-wsize:0}while(--n8);n8=wsize;p=n8;do{m=s10.prev[--p];s10.prev[p]=m>=wsize?m-wsize:0}while(--n8)};var HASH=(s10,prev,data2)=>(prev<<s10.hash_shift^data2)&s10.hash_mask;var INSERT_STRING=(s10,str)=>{let h;if(s10.legacy_hash){h=s10.ins_h=HASH(s10,s10.ins_h,s10.window[str+MIN_MATCH-1])}else{const w=s10.window;const value=w[str]|w[str+1]<<8|w[str+2]<<16|w[str+3]<<24;h=s10.ins_h=Math.imul(value,66521)+66521>>>16&s10.hash_mask}const hash_head=s10.prev[str&s10.w_mask]=s10.head[h];s10.head[h]=str;return hash_head};var flush_pending=strm=>{const s10=strm.state;let len2=s10.pending;if(len2>strm.avail_out){len2=strm.avail_out}if(len2===0){return}strm.output.set(s10.pending_buf.subarray(s10.pending_out,s10.pending_out+len2),strm.next_out);strm.next_out+=len2;s10.pending_out+=len2;strm.total_out+=len2;strm.avail_out-=len2;s10.pending-=len2;if(s10.pending===0){s10.pending_out=0}};var flush_block_only=(s10,last)=>{_tr_flush_block(s10,s10.block_start>=0?s10.block_start:-1,s10.strstart-s10.block_start,last);s10.block_start=s10.strstart;flush_pending(s10.strm)};var put_byte=(s10,b)=>{s10.pending_buf[s10.pending++]=b};var putShortMSB=(s10,b)=>{s10.pending_buf[s10.pending++]=b>>>8&255;s10.pending_buf[s10.pending++]=b&255};var read_buf=(strm,buf,start,size)=>{let len2=strm.avail_in;if(len2>size){len2=size}if(len2===0){return 0}strm.avail_in-=len2;buf.set(strm.input.subarray(strm.next_in,strm.next_in+len2),start);if(strm.state.wrap===1){strm.adler=adler32_1(strm.adler,buf,len2,start)}else if(strm.state.wrap===2){strm.adler=crc32_1(strm.adler,buf,len2,start)}strm.next_in+=len2;strm.total_in+=len2;return len2};var longest_match=(s10,cur_match)=>{let chain_length=s10.max_chain_length;let scan=s10.strstart;let match2;let len2;let best_len=s10.prev_length;let nice_match=s10.nice_match;const limit=s10.strstart>s10.w_size-MIN_LOOKAHEAD?s10.strstart-(s10.w_size-MIN_LOOKAHEAD):0;const _win=s10.window;const wmask=s10.w_mask;const prev=s10.prev;const strend=s10.strstart+MAX_MATCH;let scan_end1=_win[scan+best_len-1];let scan_end=_win[scan+best_len];if(s10.prev_length>=s10.good_match){chain_length>>=2}if(nice_match>s10.lookahead){nice_match=s10.lookahead}do{match2=cur_match;if(_win[match2+best_len]!==scan_end||_win[match2+best_len-1]!==scan_end1||_win[match2]!==_win[scan]||_win[++match2]!==_win[scan+1]){continue}scan+=2;match2++;do{}while(_win[++scan]===_win[++match2]&&_win[++scan]===_win[++match2]&&_win[++scan]===_win[++match2]&&_win[++scan]===_win[++match2]&&_win[++scan]===_win[++match2]&&_win[++scan]===_win[++match2]&&_win[++scan]===_win[++match2]&&_win[++scan]===_win[++match2]&&scan<strend);len2=MAX_MATCH-(strend-scan);scan=strend-MAX_MATCH;if(len2>best_len){s10.match_start=cur_match;best_len=len2;if(len2>=nice_match){break}scan_end1=_win[scan+best_len-1];scan_end=_win[scan+best_len]}}while((cur_match=prev[cur_match&wmask])>limit&&--chain_length!==0);if(best_len<=s10.lookahead){return best_len}return s10.lookahead};var fill_window=s10=>{const _w_size=s10.w_size;let n8,more,str;do{more=s10.window_size-s10.lookahead-s10.strstart;if(s10.strstart>=_w_size+(_w_size-MIN_LOOKAHEAD)){s10.window.set(s10.window.subarray(_w_size,_w_size+_w_size-more),0);s10.match_start-=_w_size;s10.strstart-=_w_size;s10.block_start-=_w_size;if(s10.insert>s10.strstart){s10.insert=s10.strstart}slide_hash(s10);more+=_w_size}if(s10.strm.avail_in===0){break}n8=read_buf(s10.strm,s10.window,s10.strstart+s10.lookahead,more);s10.lookahead+=n8;if(!s10.legacy_hash){if(s10.lookahead+s10.insert>MIN_MATCH){str=s10.strstart-s10.insert;while(s10.insert){INSERT_STRING(s10,str);str++;s10.insert--;if(s10.lookahead+s10.insert<=MIN_MATCH){break}}}}else if(s10.lookahead+s10.insert>=MIN_MATCH){str=s10.strstart-s10.insert;s10.ins_h=s10.window[str];s10.ins_h=HASH(s10,s10.ins_h,s10.window[str+1]);while(s10.insert){INSERT_STRING(s10,str);str++;s10.insert--;if(s10.lookahead+s10.insert<MIN_MATCH){break}}}}while(s10.lookahead<MIN_LOOKAHEAD&&s10.strm.avail_in!==0)};var deflate_stored=(s10,flush2)=>{let min_block=s10.pending_buf_size-5>s10.w_size?s10.w_size:s10.pending_buf_size-5;let len2,left,have,last=0;let used=s10.strm.avail_in;do{len2=65535;have=s10.bi_valid+42>>3;if(s10.strm.avail_out<have){break}have=s10.strm.avail_out-have;left=s10.strstart-s10.block_start;if(len2>left+s10.strm.avail_in){len2=left+s10.strm.avail_in}if(len2>have){len2=have}if(len2<min_block&&(len2===0&&flush2!==Z_FINISH$3||flush2===Z_NO_FLUSH$2||len2!==left+s10.strm.avail_in)){break}last=flush2===Z_FINISH$3&&len2===left+s10.strm.avail_in?1:0;_tr_stored_block(s10,0,0,last);s10.pending_buf[s10.pending-4]=len2;s10.pending_buf[s10.pending-3]=len2>>8;s10.pending_buf[s10.pending-2]=~len2;s10.pending_buf[s10.pending-1]=~len2>>8;flush_pending(s10.strm);if(left){if(left>len2){left=len2}s10.strm.output.set(s10.window.subarray(s10.block_start,s10.block_start+left),s10.strm.next_out);s10.strm.next_out+=left;s10.strm.avail_out-=left;s10.strm.total_out+=left;s10.block_start+=left;len2-=left}if(len2){read_buf(s10.strm,s10.strm.output,s10.strm.next_out,len2);s10.strm.next_out+=len2;s10.strm.avail_out-=len2;s10.strm.total_out+=len2}}while(last===0);used-=s10.strm.avail_in;if(used){if(used>=s10.w_size){s10.matches=2;s10.window.set(s10.strm.input.subarray(s10.strm.next_in-s10.w_size,s10.strm.next_in),0);s10.strstart=s10.w_size;s10.insert=s10.strstart}else{if(s10.window_size-s10.strstart<=used){s10.strstart-=s10.w_size;s10.window.set(s10.window.subarray(s10.w_size,s10.w_size+s10.strstart),0);if(s10.matches<2){s10.matches++}if(s10.insert>s10.strstart){s10.insert=s10.strstart}}s10.window.set(s10.strm.input.subarray(s10.strm.next_in-used,s10.strm.next_in),s10.strstart);s10.strstart+=used;s10.insert+=used>s10.w_size-s10.insert?s10.w_size-s10.insert:used}s10.block_start=s10.strstart}if(s10.high_water<s10.strstart){s10.high_water=s10.strstart}if(last){return BS_FINISH_DONE}if(flush2!==Z_NO_FLUSH$2&&flush2!==Z_FINISH$3&&s10.strm.avail_in===0&&s10.strstart===s10.block_start){return BS_BLOCK_DONE}have=s10.window_size-s10.strstart;if(s10.strm.avail_in>have&&s10.block_start>=s10.w_size){s10.block_start-=s10.w_size;s10.strstart-=s10.w_size;s10.window.set(s10.window.subarray(s10.w_size,s10.w_size+s10.strstart),0);if(s10.matches<2){s10.matches++}have+=s10.w_size;if(s10.insert>s10.strstart){s10.insert=s10.strstart}}if(have>s10.strm.avail_in){have=s10.strm.avail_in}if(have){read_buf(s10.strm,s10.window,s10.strstart,have);s10.strstart+=have;s10.insert+=have>s10.w_size-s10.insert?s10.w_size-s10.insert:have}if(s10.high_water<s10.strstart){s10.high_water=s10.strstart}have=s10.bi_valid+42>>3;have=s10.pending_buf_size-have>65535?65535:s10.pending_buf_size-have;min_block=have>s10.w_size?s10.w_size:have;left=s10.strstart-s10.block_start;if(left>=min_block||(left||flush2===Z_FINISH$3)&&flush2!==Z_NO_FLUSH$2&&s10.strm.avail_in===0&&left<=have){len2=left>have?have:left;last=flush2===Z_FINISH$3&&s10.strm.avail_in===0&&len2===left?1:0;_tr_stored_block(s10,s10.block_start,len2,last);s10.block_start+=len2;flush_pending(s10.strm)}return last?BS_FINISH_STARTED:BS_NEED_MORE};var deflate_fast=(s10,flush2)=>{let hash_head;let bflush;for(;;){if(s10.lookahead<MIN_LOOKAHEAD){fill_window(s10);if(s10.lookahead<MIN_LOOKAHEAD&&flush2===Z_NO_FLUSH$2){return BS_NEED_MORE}if(s10.lookahead===0){break}}hash_head=0;if(s10.lookahead>=MIN_MATCH){hash_head=INSERT_STRING(s10,s10.strstart)}if(hash_head!==0&&s10.strstart-hash_head<=s10.w_size-MIN_LOOKAHEAD){s10.match_length=longest_match(s10,hash_head)}if(s10.match_length>=MIN_MATCH){bflush=_tr_tally(s10,s10.strstart-s10.match_start,s10.match_length-MIN_MATCH);s10.lookahead-=s10.match_length;if(s10.match_length<=s10.max_lazy_match&&s10.lookahead>=MIN_MATCH){s10.match_length--;do{s10.strstart++;hash_head=INSERT_STRING(s10,s10.strstart)}while(--s10.match_length!==0);s10.strstart++}else{s10.strstart+=s10.match_length;s10.match_length=0;if(s10.legacy_hash){s10.ins_h=s10.window[s10.strstart];s10.ins_h=HASH(s10,s10.ins_h,s10.window[s10.strstart+1])}}}else{bflush=_tr_tally(s10,0,s10.window[s10.strstart]);s10.lookahead--;s10.strstart++}if(bflush){flush_block_only(s10,false);if(s10.strm.avail_out===0){return BS_NEED_MORE}}}s10.insert=s10.strstart<MIN_MATCH-1?s10.strstart:MIN_MATCH-1;if(flush2===Z_FINISH$3){flush_block_only(s10,true);if(s10.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s10.sym_next){flush_block_only(s10,false);if(s10.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE};var deflate_slow=(s10,flush2)=>{let hash_head;let bflush;let max_insert;for(;;){if(s10.lookahead<MIN_LOOKAHEAD){fill_window(s10);if(s10.lookahead<MIN_LOOKAHEAD&&flush2===Z_NO_FLUSH$2){return BS_NEED_MORE}if(s10.lookahead===0){break}}hash_head=0;if(s10.lookahead>=MIN_MATCH){hash_head=INSERT_STRING(s10,s10.strstart)}s10.prev_length=s10.match_length;s10.prev_match=s10.match_start;s10.match_length=MIN_MATCH-1;if(hash_head!==0&&s10.prev_length<s10.max_lazy_match&&s10.strstart-hash_head<=s10.w_size-MIN_LOOKAHEAD){s10.match_length=longest_match(s10,hash_head);if(s10.match_length<=5&&(s10.strategy===Z_FILTERED||s10.match_length===MIN_MATCH&&s10.strstart-s10.match_start>4096)){s10.match_length=MIN_MATCH-1}}if(s10.prev_length>=MIN_MATCH&&s10.match_length<=s10.prev_length){max_insert=s10.strstart+s10.lookahead-MIN_MATCH;bflush=_tr_tally(s10,s10.strstart-1-s10.prev_match,s10.prev_length-MIN_MATCH);s10.lookahead-=s10.prev_length-1;s10.prev_length-=2;do{if(++s10.strstart<=max_insert){hash_head=INSERT_STRING(s10,s10.strstart)}}while(--s10.prev_length!==0);s10.match_available=0;s10.match_length=MIN_MATCH-1;s10.strstart++;if(bflush){flush_block_only(s10,false);if(s10.strm.avail_out===0){return BS_NEED_MORE}}}else if(s10.match_available){bflush=_tr_tally(s10,0,s10.window[s10.strstart-1]);if(bflush){flush_block_only(s10,false)}s10.strstart++;s10.lookahead--;if(s10.strm.avail_out===0){return BS_NEED_MORE}}else{s10.match_available=1;s10.strstart++;s10.lookahead--}}if(s10.match_available){bflush=_tr_tally(s10,0,s10.window[s10.strstart-1]);s10.match_available=0}s10.insert=s10.strstart<MIN_MATCH-1?s10.strstart:MIN_MATCH-1;if(flush2===Z_FINISH$3){flush_block_only(s10,true);if(s10.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s10.sym_next){flush_block_only(s10,false);if(s10.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE};var deflate_rle=(s10,flush2)=>{let bflush;let prev;let scan,strend;const _win=s10.window;for(;;){if(s10.lookahead<=MAX_MATCH){fill_window(s10);if(s10.lookahead<=MAX_MATCH&&flush2===Z_NO_FLUSH$2){return BS_NEED_MORE}if(s10.lookahead===0){break}}s10.match_length=0;if(s10.lookahead>=MIN_MATCH&&s10.strstart>0){scan=s10.strstart-1;prev=_win[scan];if(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]){strend=s10.strstart+MAX_MATCH;do{}while(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&scan<strend);s10.match_length=MAX_MATCH-(strend-scan);if(s10.match_length>s10.lookahead){s10.match_length=s10.lookahead}}}if(s10.match_length>=MIN_MATCH){bflush=_tr_tally(s10,1,s10.match_length-MIN_MATCH);s10.lookahead-=s10.match_length;s10.strstart+=s10.match_length;s10.match_length=0}else{bflush=_tr_tally(s10,0,s10.window[s10.strstart]);s10.lookahead--;s10.strstart++}if(bflush){flush_block_only(s10,false);if(s10.strm.avail_out===0){return BS_NEED_MORE}}}s10.insert=0;if(flush2===Z_FINISH$3){flush_block_only(s10,true);if(s10.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s10.sym_next){flush_block_only(s10,false);if(s10.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE};var deflate_huff=(s10,flush2)=>{let bflush;for(;;){if(s10.lookahead===0){fill_window(s10);if(s10.lookahead===0){if(flush2===Z_NO_FLUSH$2){return BS_NEED_MORE}break}}s10.match_length=0;bflush=_tr_tally(s10,0,s10.window[s10.strstart]);s10.lookahead--;s10.strstart++;if(bflush){flush_block_only(s10,false);if(s10.strm.avail_out===0){return BS_NEED_MORE}}}s10.insert=0;if(flush2===Z_FINISH$3){flush_block_only(s10,true);if(s10.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s10.sym_next){flush_block_only(s10,false);if(s10.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE};function Config(good_length,max_lazy,nice_length,max_chain,func){this.good_length=good_length;this.max_lazy=max_lazy;this.nice_length=nice_length;this.max_chain=max_chain;this.func=func}var configuration_table=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)];var lm_init=s10=>{s10.window_size=2*s10.w_size;zero(s10.head);s10.max_lazy_match=configuration_table[s10.level].max_lazy;s10.good_match=configuration_table[s10.level].good_length;s10.nice_match=configuration_table[s10.level].nice_length;s10.max_chain_length=configuration_table[s10.level].max_chain;s10.strstart=0;s10.block_start=0;s10.lookahead=0;s10.insert=0;s10.match_length=s10.prev_length=MIN_MATCH-1;s10.match_available=0;s10.ins_h=0};function DeflateState(){this.strm=null;this.status=0;this.pending_buf=null;this.pending_buf_size=0;this.pending_out=0;this.pending=0;this.wrap=0;this.gzhead=null;this.gzindex=0;this.method=Z_DEFLATED$2;this.last_flush=-1;this.w_size=0;this.w_bits=0;this.w_mask=0;this.window=null;this.window_size=0;this.prev=null;this.head=null;this.ins_h=0;this.legacy_hash=0;this.hash_size=0;this.hash_bits=0;this.hash_mask=0;this.hash_shift=0;this.block_start=0;this.match_length=0;this.prev_match=0;this.match_available=0;this.strstart=0;this.match_start=0;this.lookahead=0;this.prev_length=0;this.max_chain_length=0;this.max_lazy_match=0;this.level=0;this.strategy=0;this.good_match=0;this.nice_match=0;this.dyn_ltree=new Uint16Array(HEAP_SIZE*2);this.dyn_dtree=new Uint16Array((2*D_CODES+1)*2);this.bl_tree=new Uint16Array((2*BL_CODES+1)*2);zero(this.dyn_ltree);zero(this.dyn_dtree);zero(this.bl_tree);this.l_desc=null;this.d_desc=null;this.bl_desc=null;this.bl_count=new Uint16Array(MAX_BITS+1);this.heap=new Uint16Array(2*L_CODES+1);zero(this.heap);this.heap_len=0;this.heap_max=0;this.depth=new Uint16Array(2*L_CODES+1);zero(this.depth);this.sym_buf=0;this.lit_bufsize=0;this.sym_next=0;this.sym_end=0;this.opt_len=0;this.static_len=0;this.matches=0;this.insert=0;this.bi_buf=0;this.bi_valid=0}var deflateStateCheck=strm=>{if(!strm){return 1}const s10=strm.state;if(!s10||s10.strm!==strm||s10.status!==INIT_STATE&&s10.status!==GZIP_STATE&&s10.status!==EXTRA_STATE&&s10.status!==NAME_STATE&&s10.status!==COMMENT_STATE&&s10.status!==HCRC_STATE&&s10.status!==BUSY_STATE&&s10.status!==FINISH_STATE){return 1}return 0};var deflateResetKeep=strm=>{if(deflateStateCheck(strm)){return err(strm,Z_STREAM_ERROR$2)}strm.total_in=strm.total_out=0;strm.data_type=Z_UNKNOWN;const s10=strm.state;s10.pending=0;s10.pending_out=0;if(s10.wrap<0){s10.wrap=-s10.wrap}s10.status=s10.wrap===2?GZIP_STATE:s10.wrap?INIT_STATE:BUSY_STATE;strm.adler=s10.wrap===2?0:1;s10.last_flush=-2;_tr_init(s10);return Z_OK$3};var deflateReset=strm=>{const ret=deflateResetKeep(strm);if(ret===Z_OK$3){lm_init(strm.state)}return ret};var deflateSetHeader=(strm,head)=>{if(deflateStateCheck(strm)||strm.state.wrap!==2){return Z_STREAM_ERROR$2}strm.state.gzhead=head;return Z_OK$3};var deflateInit2=(strm,level,method,windowBits,memLevel,strategy,legacyHash)=>{if(!strm){return Z_STREAM_ERROR$2}let wrap2=1;if(level===Z_DEFAULT_COMPRESSION$1){level=6}if(windowBits<0){wrap2=0;windowBits=-windowBits}else if(windowBits>15){wrap2=2;windowBits-=16}if(memLevel<1||memLevel>MAX_MEM_LEVEL||method!==Z_DEFLATED$2||windowBits<8||windowBits>15||level<0||level>9||strategy<0||strategy>Z_FIXED||windowBits===8&&wrap2!==1){return err(strm,Z_STREAM_ERROR$2)}if(windowBits===8){windowBits=9}const s10=new DeflateState;strm.state=s10;s10.strm=strm;s10.status=INIT_STATE;s10.wrap=wrap2;s10.gzhead=null;s10.w_bits=windowBits;s10.w_size=1<<s10.w_bits;s10.w_mask=s10.w_size-1;s10.legacy_hash=legacyHash?1:0;s10.hash_bits=memLevel+7;if(!s10.legacy_hash&&s10.hash_bits<15){s10.hash_bits=15}s10.hash_size=1<<s10.hash_bits;s10.hash_mask=s10.hash_size-1;s10.hash_shift=~~((s10.hash_bits+MIN_MATCH-1)/MIN_MATCH);s10.window=new Uint8Array(s10.w_size*2);s10.head=new Uint16Array(s10.hash_size);s10.prev=new Uint16Array(s10.w_size);s10.lit_bufsize=1<<memLevel+6;s10.pending_buf_size=s10.lit_bufsize*4;s10.pending_buf=new Uint8Array(s10.pending_buf_size);s10.sym_buf=s10.lit_bufsize;s10.sym_end=(s10.lit_bufsize-1)*3;s10.level=level;s10.strategy=strategy;s10.method=method;return deflateReset(strm)};var deflateInit=(strm,level)=>{return deflateInit2(strm,level,Z_DEFLATED$2,MAX_WBITS$1,DEF_MEM_LEVEL,Z_DEFAULT_STRATEGY$1)};var deflate$2=(strm,flush2)=>{if(deflateStateCheck(strm)||flush2>Z_BLOCK$1||flush2<0){return strm?err(strm,Z_STREAM_ERROR$2):Z_STREAM_ERROR$2}const s10=strm.state;if(!strm.output||strm.avail_in!==0&&!strm.input||s10.status===FINISH_STATE&&flush2!==Z_FINISH$3){return err(strm,strm.avail_out===0?Z_BUF_ERROR$2:Z_STREAM_ERROR$2)}const old_flush=s10.last_flush;s10.last_flush=flush2;if(s10.pending!==0){flush_pending(strm);if(strm.avail_out===0){s10.last_flush=-1;return Z_OK$3}}else if(strm.avail_in===0&&rank(flush2)<=rank(old_flush)&&flush2!==Z_FINISH$3){return err(strm,Z_BUF_ERROR$2)}if(s10.status===FINISH_STATE&&strm.avail_in!==0){return err(strm,Z_BUF_ERROR$2)}if(s10.status===INIT_STATE&&s10.wrap===0){s10.status=BUSY_STATE}if(s10.status===INIT_STATE){let header=Z_DEFLATED$2+(s10.w_bits-8<<4)<<8;let level_flags=-1;if(s10.strategy>=Z_HUFFMAN_ONLY||s10.level<2){level_flags=0}else if(s10.level<6){level_flags=1}else if(s10.level===6){level_flags=2}else{level_flags=3}header|=level_flags<<6;if(s10.strstart!==0){header|=PRESET_DICT}header+=31-header%31;putShortMSB(s10,header);if(s10.strstart!==0){putShortMSB(s10,strm.adler>>>16);putShortMSB(s10,strm.adler&65535)}strm.adler=1;s10.status=BUSY_STATE;flush_pending(strm);if(s10.pending!==0){s10.last_flush=-1;return Z_OK$3}}if(s10.status===GZIP_STATE){strm.adler=0;put_byte(s10,31);put_byte(s10,139);put_byte(s10,8);if(!s10.gzhead){put_byte(s10,0);put_byte(s10,0);put_byte(s10,0);put_byte(s10,0);put_byte(s10,0);put_byte(s10,s10.level===9?2:s10.strategy>=Z_HUFFMAN_ONLY||s10.level<2?4:0);put_byte(s10,OS_CODE);s10.status=BUSY_STATE;flush_pending(strm);if(s10.pending!==0){s10.last_flush=-1;return Z_OK$3}}else{put_byte(s10,(s10.gzhead.text?1:0)+(s10.gzhead.hcrc?2:0)+(!s10.gzhead.extra?0:4)+(!s10.gzhead.name?0:8)+(!s10.gzhead.comment?0:16));put_byte(s10,s10.gzhead.time&255);put_byte(s10,s10.gzhead.time>>8&255);put_byte(s10,s10.gzhead.time>>16&255);put_byte(s10,s10.gzhead.time>>24&255);put_byte(s10,s10.level===9?2:s10.strategy>=Z_HUFFMAN_ONLY||s10.level<2?4:0);put_byte(s10,s10.gzhead.os&255);if(s10.gzhead.extra&&s10.gzhead.extra.length){put_byte(s10,s10.gzhead.extra.length&255);put_byte(s10,s10.gzhead.extra.length>>8&255)}if(s10.gzhead.hcrc){strm.adler=crc32_1(strm.adler,s10.pending_buf,s10.pending,0)}s10.gzindex=0;s10.status=EXTRA_STATE}}if(s10.status===EXTRA_STATE){if(s10.gzhead.extra){let beg=s10.pending;let left=(s10.gzhead.extra.length&65535)-s10.gzindex;while(s10.pending+left>s10.pending_buf_size){let copy2=s10.pending_buf_size-s10.pending;s10.pending_buf.set(s10.gzhead.extra.subarray(s10.gzindex,s10.gzindex+copy2),s10.pending);s10.pending=s10.pending_buf_size;if(s10.gzhead.hcrc&&s10.pending>beg){strm.adler=crc32_1(strm.adler,s10.pending_buf,s10.pending-beg,beg)}s10.gzindex+=copy2;flush_pending(strm);if(s10.pending!==0){s10.last_flush=-1;return Z_OK$3}beg=0;left-=copy2}let gzhead_extra=new Uint8Array(s10.gzhead.extra);s10.pending_buf.set(gzhead_extra.subarray(s10.gzindex,s10.gzindex+left),s10.pending);s10.pending+=left;if(s10.gzhead.hcrc&&s10.pending>beg){strm.adler=crc32_1(strm.adler,s10.pending_buf,s10.pending-beg,beg)}s10.gzindex=0}s10.status=NAME_STATE}if(s10.status===NAME_STATE){if(s10.gzhead.name){let beg=s10.pending;let val;do{if(s10.pending===s10.pending_buf_size){if(s10.gzhead.hcrc&&s10.pending>beg){strm.adler=crc32_1(strm.adler,s10.pending_buf,s10.pending-beg,beg)}flush_pending(strm);if(s10.pending!==0){s10.last_flush=-1;return Z_OK$3}beg=0}if(s10.gzindex<s10.gzhead.name.length){val=s10.gzhead.name.charCodeAt(s10.gzindex++)&255}else{val=0}put_byte(s10,val)}while(val!==0);if(s10.gzhead.hcrc&&s10.pending>beg){strm.adler=crc32_1(strm.adler,s10.pending_buf,s10.pending-beg,beg)}s10.gzindex=0}s10.status=COMMENT_STATE}if(s10.status===COMMENT_STATE){if(s10.gzhead.comment){let beg=s10.pending;let val;do{if(s10.pending===s10.pending_buf_size){if(s10.gzhead.hcrc&&s10.pending>beg){strm.adler=crc32_1(strm.adler,s10.pending_buf,s10.pending-beg,beg)}flush_pending(strm);if(s10.pending!==0){s10.last_flush=-1;return Z_OK$3}beg=0}if(s10.gzindex<s10.gzhead.comment.length){val=s10.gzhead.comment.charCodeAt(s10.gzindex++)&255}else{val=0}put_byte(s10,val)}while(val!==0);if(s10.gzhead.hcrc&&s10.pending>beg){strm.adler=crc32_1(strm.adler,s10.pending_buf,s10.pending-beg,beg)}}s10.status=HCRC_STATE}if(s10.status===HCRC_STATE){if(s10.gzhead.hcrc){if(s10.pending+2>s10.pending_buf_size){flush_pending(strm);if(s10.pending!==0){s10.last_flush=-1;return Z_OK$3}}put_byte(s10,strm.adler&255);put_byte(s10,strm.adler>>8&255);strm.adler=0}s10.status=BUSY_STATE;flush_pending(strm);if(s10.pending!==0){s10.last_flush=-1;return Z_OK$3}}if(strm.avail_in!==0||s10.lookahead!==0||flush2!==Z_NO_FLUSH$2&&s10.status!==FINISH_STATE){let bstate=s10.level===0?deflate_stored(s10,flush2):s10.strategy===Z_HUFFMAN_ONLY?deflate_huff(s10,flush2):s10.strategy===Z_RLE?deflate_rle(s10,flush2):configuration_table[s10.level].func(s10,flush2);if(bstate===BS_FINISH_STARTED||bstate===BS_FINISH_DONE){s10.status=FINISH_STATE}if(bstate===BS_NEED_MORE||bstate===BS_FINISH_STARTED){if(strm.avail_out===0){s10.last_flush=-1}return Z_OK$3}if(bstate===BS_BLOCK_DONE){if(flush2===Z_PARTIAL_FLUSH){_tr_align(s10)}else if(flush2!==Z_BLOCK$1){_tr_stored_block(s10,0,0,false);if(flush2===Z_FULL_FLUSH$1){zero(s10.head);if(s10.lookahead===0){s10.strstart=0;s10.block_start=0;s10.insert=0}}}flush_pending(strm);if(strm.avail_out===0){s10.last_flush=-1;return Z_OK$3}}}if(flush2!==Z_FINISH$3){return Z_OK$3}if(s10.wrap<=0){return Z_STREAM_END$3}if(s10.wrap===2){put_byte(s10,strm.adler&255);put_byte(s10,strm.adler>>8&255);put_byte(s10,strm.adler>>16&255);put_byte(s10,strm.adler>>24&255);put_byte(s10,strm.total_in&255);put_byte(s10,strm.total_in>>8&255);put_byte(s10,strm.total_in>>16&255);put_byte(s10,strm.total_in>>24&255)}else{putShortMSB(s10,strm.adler>>>16);putShortMSB(s10,strm.adler&65535)}flush_pending(strm);if(s10.wrap>0){s10.wrap=-s10.wrap}return s10.pending!==0?Z_OK$3:Z_STREAM_END$3};var deflateEnd=strm=>{if(deflateStateCheck(strm)){return Z_STREAM_ERROR$2}const status=strm.state.status;strm.state=null;return status===BUSY_STATE?err(strm,Z_DATA_ERROR$2):Z_OK$3};var deflateSetDictionary=(strm,dictionary2)=>{let dictLength=dictionary2.length;if(deflateStateCheck(strm)){return Z_STREAM_ERROR$2}const s10=strm.state;const wrap2=s10.wrap;if(wrap2===2||wrap2===1&&s10.status!==INIT_STATE||s10.lookahead){return Z_STREAM_ERROR$2}if(wrap2===1){strm.adler=adler32_1(strm.adler,dictionary2,dictLength,0)}s10.wrap=0;if(dictLength>=s10.w_size){if(wrap2===0){zero(s10.head);s10.strstart=0;s10.block_start=0;s10.insert=0}let tmpDict=new Uint8Array(s10.w_size);tmpDict.set(dictionary2.subarray(dictLength-s10.w_size,dictLength),0);dictionary2=tmpDict;dictLength=s10.w_size}const avail=strm.avail_in;const next2=strm.next_in;const input=strm.input;strm.avail_in=dictLength;strm.next_in=0;strm.input=dictionary2;fill_window(s10);while(s10.lookahead>=MIN_MATCH){let str=s10.strstart;let n8=s10.lookahead-(MIN_MATCH-1);do{INSERT_STRING(s10,str);str++}while(--n8);s10.strstart=str;s10.lookahead=MIN_MATCH-1;fill_window(s10)}s10.strstart+=s10.lookahead;s10.block_start=s10.strstart;s10.insert=s10.lookahead;s10.lookahead=0;s10.match_length=s10.prev_length=MIN_MATCH-1;s10.match_available=0;strm.next_in=next2;strm.input=input;strm.avail_in=avail;s10.wrap=wrap2;return Z_OK$3};var deflateInit_1=deflateInit;var deflateInit2_1=deflateInit2;var deflateReset_1=deflateReset;var deflateResetKeep_1=deflateResetKeep;var deflateSetHeader_1=deflateSetHeader;var deflate_2$1=deflate$2;var deflateEnd_1=deflateEnd;var deflateSetDictionary_1=deflateSetDictionary;var deflateInfo="pako deflate (from Nodeca project)";var deflate_1$2={deflateInit:deflateInit_1,deflateInit2:deflateInit2_1,deflateReset:deflateReset_1,deflateResetKeep:deflateResetKeep_1,deflateSetHeader:deflateSetHeader_1,deflate:deflate_2$1,deflateEnd:deflateEnd_1,deflateSetDictionary:deflateSetDictionary_1,deflateInfo};var _has=(obj,key)=>{return Object.prototype.hasOwnProperty.call(obj,key)};var assign=function(obj){const sources=Array.prototype.slice.call(arguments,1);while(sources.length){const source=sources.shift();if(!source){continue}if(typeof source!=="object"){throw new TypeError(source+"must be non-object")}for(const p in source){if(_has(source,p)){obj[p]=source[p]}}}return obj};var flattenChunks=chunks=>{let len2=0;for(let i10=0,l=chunks.length;i10<l;i10++){len2+=chunks[i10].length}const result=new Uint8Array(len2);for(let i10=0,pos=0,l=chunks.length;i10<l;i10++){let chunk=chunks[i10];result.set(chunk,pos);pos+=chunk.length}return result};var common={assign,flattenChunks};var STR_APPLY_UIA_OK=true;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(__){STR_APPLY_UIA_OK=false}var _utf8len=new Uint8Array(256);for(let q10=0;q10<256;q10++){_utf8len[q10]=q10>=252?6:q10>=248?5:q10>=240?4:q10>=224?3:q10>=192?2:1}_utf8len[254]=_utf8len[255]=1;var string2buf=str=>{if(typeof TextEncoder==="function"&&TextEncoder.prototype.encode){return new TextEncoder().encode(str)}let buf,c,c22,m_pos,i10,str_len=str.length,buf_len=0;for(m_pos=0;m_pos<str_len;m_pos++){c=str.charCodeAt(m_pos);if((c&64512)===55296&&m_pos+1<str_len){c22=str.charCodeAt(m_pos+1);if((c22&64512)===56320){c=65536+(c-55296<<10)+(c22-56320);m_pos++}}buf_len+=c<128?1:c<2048?2:c<65536?3:4}buf=new Uint8Array(buf_len);for(i10=0,m_pos=0;i10<buf_len;m_pos++){c=str.charCodeAt(m_pos);if((c&64512)===55296&&m_pos+1<str_len){c22=str.charCodeAt(m_pos+1);if((c22&64512)===56320){c=65536+(c-55296<<10)+(c22-56320);m_pos++}}if(c<128){buf[i10++]=c}else if(c<2048){buf[i10++]=192|c>>>6;buf[i10++]=128|c&63}else if(c<65536){buf[i10++]=224|c>>>12;buf[i10++]=128|c>>>6&63;buf[i10++]=128|c&63}else{buf[i10++]=240|c>>>18;buf[i10++]=128|c>>>12&63;buf[i10++]=128|c>>>6&63;buf[i10++]=128|c&63}}return buf};var buf2binstring=(buf,len2)=>{if(len2<65534){if(buf.subarray&&STR_APPLY_UIA_OK){return String.fromCharCode.apply(null,buf.length===len2?buf:buf.subarray(0,len2))}}let result="";for(let i10=0;i10<len2;i10++){result+=String.fromCharCode(buf[i10])}return result};var buf2string=(buf,max2)=>{const len2=max2||buf.length;if(typeof TextDecoder==="function"&&TextDecoder.prototype.decode){return new TextDecoder().decode(buf.subarray(0,max2))}let i10,out;const utf16buf=new Array(len2*2);for(out=0,i10=0;i10<len2;){let c=buf[i10++];if(c<128){utf16buf[out++]=c;continue}let c_len=_utf8len[c];if(c_len>4){utf16buf[out++]=65533;i10+=c_len-1;continue}c&=c_len===2?31:c_len===3?15:7;while(c_len>1&&i10<len2){c=c<<6|buf[i10++]&63;c_len--}if(c_len>1){utf16buf[out++]=65533;continue}if(c<65536){utf16buf[out++]=c}else{c-=65536;utf16buf[out++]=55296|c>>10&1023;utf16buf[out++]=56320|c&1023}}return buf2binstring(utf16buf,out)};var utf8border=(buf,max2)=>{max2=max2||buf.length;if(max2>buf.length){max2=buf.length}let pos=max2-1;while(pos>=0&&(buf[pos]&192)===128){pos--}if(pos<0){return max2}if(pos===0){return max2}return pos+_utf8len[buf[pos]]>max2?pos:max2};var strings={string2buf,buf2string,utf8border};function ZStream(){this.input=null;this.next_in=0;this.avail_in=0;this.total_in=0;this.output=null;this.next_out=0;this.avail_out=0;this.total_out=0;this.msg="";this.state=null;this.data_type=2;this.adler=0}var zstream=ZStream;var toString$1=Object.prototype.toString;var{Z_NO_FLUSH:Z_NO_FLUSH$1,Z_SYNC_FLUSH,Z_FULL_FLUSH,Z_FINISH:Z_FINISH$2,Z_OK:Z_OK$2,Z_STREAM_END:Z_STREAM_END$2,Z_DEFAULT_COMPRESSION,Z_DEFAULT_STRATEGY,Z_DEFLATED:Z_DEFLATED$1}=constants$2;var defaultOptions$1={level:Z_DEFAULT_COMPRESSION,method:Z_DEFLATED$1,chunkSize:16384,windowBits:15,memLevel:8,strategy:Z_DEFAULT_STRATEGY,legacyHash:true};function Deflate$1(options){this.options=common.assign({},defaultOptions$1,options||{});let opt=this.options;if(opt.raw&&opt.windowBits>0){opt.windowBits=-opt.windowBits}else if(opt.gzip&&opt.windowBits>0&&opt.windowBits<16){opt.windowBits+=16}this.err=0;this.msg="";this.ended=false;this.chunks=[];this.strm=new zstream;this.strm.avail_out=0;let status=deflate_1$2.deflateInit2(this.strm,opt.level,opt.method,opt.windowBits,opt.memLevel,opt.strategy,opt.legacyHash);if(status!==Z_OK$2){throw new Error(messages[status])}if(opt.header){deflate_1$2.deflateSetHeader(this.strm,opt.header)}if(opt.dictionary){let dict;if(typeof opt.dictionary==="string"){dict=strings.string2buf(opt.dictionary)}else if(toString$1.call(opt.dictionary)==="[object ArrayBuffer]"){dict=new Uint8Array(opt.dictionary)}else{dict=opt.dictionary}status=deflate_1$2.deflateSetDictionary(this.strm,dict);if(status!==Z_OK$2){throw new Error(messages[status])}this._dict_set=true}}Deflate$1.prototype.push=function(data2,flush_mode){const strm=this.strm;const chunkSize=this.options.chunkSize;let status,_flush_mode;if(this.ended){return false}if(flush_mode===~~flush_mode)_flush_mode=flush_mode;else _flush_mode=flush_mode===true?Z_FINISH$2:Z_NO_FLUSH$1;if(typeof data2==="string"){strm.input=strings.string2buf(data2)}else if(toString$1.call(data2)==="[object ArrayBuffer]"){strm.input=new Uint8Array(data2)}else{strm.input=data2}strm.next_in=0;strm.avail_in=strm.input.length;for(;;){if(strm.avail_out===0){strm.output=new Uint8Array(chunkSize);strm.next_out=0;strm.avail_out=chunkSize}if((_flush_mode===Z_SYNC_FLUSH||_flush_mode===Z_FULL_FLUSH)&&strm.avail_out<=6){this.onData(strm.output.subarray(0,strm.next_out));strm.avail_out=0;continue}status=deflate_1$2.deflate(strm,_flush_mode);if(status===Z_STREAM_END$2){if(strm.next_out>0){this.onData(strm.output.subarray(0,strm.next_out))}status=deflate_1$2.deflateEnd(this.strm);this.onEnd(status);this.ended=true;return status===Z_OK$2}if(strm.avail_out===0){this.onData(strm.output);continue}if(_flush_mode>0&&strm.next_out>0){this.onData(strm.output.subarray(0,strm.next_out));strm.avail_out=0;continue}if(strm.avail_in===0)break}return true};Deflate$1.prototype.onData=function(chunk){this.chunks.push(chunk)};Deflate$1.prototype.onEnd=function(status){if(status===Z_OK$2){this.result=common.flattenChunks(this.chunks)}this.chunks=[];this.err=status;this.msg=this.strm.msg};function deflate$1(input,options){const deflator=new Deflate$1(options);deflator.push(input,true);if(deflator.err){throw deflator.msg||messages[deflator.err]}return deflator.result}function deflateRaw$1(input,options){options=options||{};options.raw=true;return deflate$1(input,options)}function gzip$1(input,options){options=options||{};options.gzip=true;return deflate$1(input,options)}var Deflate_1$1=Deflate$1;var deflate_2=deflate$1;var deflateRaw_1$1=deflateRaw$1;var gzip_1$1=gzip$1;var constants$1=constants$2;var deflate_1$1={Deflate:Deflate_1$1,deflate:deflate_2,deflateRaw:deflateRaw_1$1,gzip:gzip_1$1,constants:constants$1};var BAD$1=16209;var TYPE$1=16191;var inffast=function inflate_fast(strm,start){let _in;let last;let _out;let beg;let end;let dmax;let wsize;let whave;let wnext;let s_window;let hold2;let bits;let lcode;let dcode;let lmask;let dmask;let here;let op2;let len2;let dist;let from;let from_source;let input,output;const state=strm.state;_in=strm.next_in;input=strm.input;last=_in+(strm.avail_in-5);_out=strm.next_out;output=strm.output;beg=_out-(start-strm.avail_out);end=_out+(strm.avail_out-257);dmax=state.dmax;wsize=state.wsize;whave=state.whave;wnext=state.wnext;s_window=state.window;hold2=state.hold;bits=state.bits;lcode=state.lencode;dcode=state.distcode;lmask=(1<<state.lenbits)-1;dmask=(1<<state.distbits)-1;top:do{if(bits<15){hold2+=input[_in++]<<bits;bits+=8;hold2+=input[_in++]<<bits;bits+=8}here=lcode[hold2&lmask];dolen:for(;;){op2=here>>>24;hold2>>>=op2;bits-=op2;op2=here>>>16&255;if(op2===0){output[_out++]=here&65535}else if(op2&16){len2=here&65535;op2&=15;if(op2){if(bits<op2){hold2+=input[_in++]<<bits;bits+=8}len2+=hold2&(1<<op2)-1;hold2>>>=op2;bits-=op2}if(bits<15){hold2+=input[_in++]<<bits;bits+=8;hold2+=input[_in++]<<bits;bits+=8}here=dcode[hold2&dmask];dodist:for(;;){op2=here>>>24;hold2>>>=op2;bits-=op2;op2=here>>>16&255;if(op2&16){dist=here&65535;op2&=15;if(bits<op2){hold2+=input[_in++]<<bits;bits+=8;if(bits<op2){hold2+=input[_in++]<<bits;bits+=8}}dist+=hold2&(1<<op2)-1;if(dist>dmax){strm.msg="invalid distance too far back";state.mode=BAD$1;break top}hold2>>>=op2;bits-=op2;op2=_out-beg;if(dist>op2){op2=dist-op2;if(op2>whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD$1;break top}}from=0;from_source=s_window;if(wnext===0){from+=wsize-op2;if(op2<len2){len2-=op2;do{output[_out++]=s_window[from++]}while(--op2);from=_out-dist;from_source=output}}else if(wnext<op2){from+=wsize+wnext-op2;op2-=wnext;if(op2<len2){len2-=op2;do{output[_out++]=s_window[from++]}while(--op2);from=0;if(wnext<len2){op2=wnext;len2-=op2;do{output[_out++]=s_window[from++]}while(--op2);from=_out-dist;from_source=output}}}else{from+=wnext-op2;if(op2<len2){len2-=op2;do{output[_out++]=s_window[from++]}while(--op2);from=_out-dist;from_source=output}}while(len2>2){output[_out++]=from_source[from++];output[_out++]=from_source[from++];output[_out++]=from_source[from++];len2-=3}if(len2){output[_out++]=from_source[from++];if(len2>1){output[_out++]=from_source[from++]}}}else{from=_out-dist;do{output[_out++]=output[from++];output[_out++]=output[from++];output[_out++]=output[from++];len2-=3}while(len2>2);if(len2){output[_out++]=output[from++];if(len2>1){output[_out++]=output[from++]}}}}else if((op2&64)===0){here=dcode[(here&65535)+(hold2&(1<<op2)-1)];continue dodist}else{strm.msg="invalid distance code";state.mode=BAD$1;break top}break}}else if((op2&64)===0){here=lcode[(here&65535)+(hold2&(1<<op2)-1)];continue dolen}else if(op2&32){state.mode=TYPE$1;break top}else{strm.msg="invalid literal/length code";state.mode=BAD$1;break top}break}}while(_in<last&&_out<end);len2=bits>>3;_in-=len2;bits-=len2<<3;hold2&=(1<<bits)-1;strm.next_in=_in;strm.next_out=_out;strm.avail_in=_in<last?5+(last-_in):5-(_in-last);strm.avail_out=_out<end?257+(end-_out):257-(_out-end);state.hold=hold2;state.bits=bits;return};var MAXBITS=15;var ENOUGH_LENS$1=852;var ENOUGH_DISTS$1=592;var CODES$1=0;var LENS$1=1;var DISTS$1=2;var lbase=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]);var lext=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,199,75]);var dbase=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]);var dext=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var inflate_table=(type2,lens,lens_index,codes2,table,table_index,work,opts)=>{const bits=opts.bits;let len2=0;let sym=0;let min2=0,max2=0;let root2=0;let curr=0;let drop2=0;let left=0;let used=0;let huff=0;let incr;let fill2;let low;let mask;let next2;let base=null;let match2;const count=new Uint16Array(MAXBITS+1);const offs=new Uint16Array(MAXBITS+1);let extra=null;let here_bits,here_op,here_val;for(len2=0;len2<=MAXBITS;len2++){count[len2]=0}for(sym=0;sym<codes2;sym++){count[lens[lens_index+sym]]++}root2=bits;for(max2=MAXBITS;max2>=1;max2--){if(count[max2]!==0){break}}if(root2>max2){root2=max2}if(max2===0){table[table_index++]=1<<24|64<<16|0;table[table_index++]=1<<24|64<<16|0;opts.bits=1;return 0}for(min2=1;min2<max2;min2++){if(count[min2]!==0){break}}if(root2<min2){root2=min2}left=1;for(len2=1;len2<=MAXBITS;len2++){left<<=1;left-=count[len2];if(left<0){return-1}}if(left>0&&(type2===CODES$1||max2!==1)){return-1}offs[1]=0;for(len2=1;len2<MAXBITS;len2++){offs[len2+1]=offs[len2]+count[len2]}for(sym=0;sym<codes2;sym++){if(lens[lens_index+sym]!==0){work[offs[lens[lens_index+sym]]++]=sym}}if(type2===CODES$1){base=extra=work;match2=20}else if(type2===LENS$1){base=lbase;extra=lext;match2=257}else{base=dbase;extra=dext;match2=0}huff=0;sym=0;len2=min2;next2=table_index;curr=root2;drop2=0;low=-1;used=1<<root2;mask=used-1;if(type2===LENS$1&&used>ENOUGH_LENS$1||type2===DISTS$1&&used>ENOUGH_DISTS$1){return 1}for(;;){here_bits=len2-drop2;if(work[sym]+1<match2){here_op=0;here_val=work[sym]}else if(work[sym]>=match2){here_op=extra[work[sym]-match2];here_val=base[work[sym]-match2]}else{here_op=32+64;here_val=0}incr=1<<len2-drop2;fill2=1<<curr;min2=fill2;do{fill2-=incr;table[next2+(huff>>drop2)+fill2]=here_bits<<24|here_op<<16|here_val|0}while(fill2!==0);incr=1<<len2-1;while(huff&incr){incr>>=1}if(incr!==0){huff&=incr-1;huff+=incr}else{huff=0}sym++;if(--count[len2]===0){if(len2===max2){break}len2=lens[lens_index+work[sym]]}if(len2>root2&&(huff&mask)!==low){if(drop2===0){drop2=root2}next2+=min2;curr=len2-drop2;left=1<<curr;while(curr+drop2<max2){left-=count[curr+drop2];if(left<=0){break}curr++;left<<=1}used+=1<<curr;if(type2===LENS$1&&used>ENOUGH_LENS$1||type2===DISTS$1&&used>ENOUGH_DISTS$1){return 1}low=huff&mask;table[low]=root2<<24|curr<<16|next2-table_index|0}}if(huff!==0){table[next2+huff]=len2-drop2<<24|64<<16|0}opts.bits=root2;return 0};var inftrees=inflate_table;var CODES=0;var LENS=1;var DISTS=2;var{Z_FINISH:Z_FINISH$1,Z_BLOCK,Z_TREES,Z_OK:Z_OK$1,Z_STREAM_END:Z_STREAM_END$1,Z_NEED_DICT:Z_NEED_DICT$1,Z_STREAM_ERROR:Z_STREAM_ERROR$1,Z_DATA_ERROR:Z_DATA_ERROR$1,Z_MEM_ERROR:Z_MEM_ERROR$1,Z_BUF_ERROR:Z_BUF_ERROR$1,Z_DEFLATED}=constants$2;var HEAD=16180;var FLAGS=16181;var TIME=16182;var OS=16183;var EXLEN=16184;var EXTRA=16185;var NAME=16186;var COMMENT=16187;var HCRC=16188;var DICTID=16189;var DICT=16190;var TYPE=16191;var TYPEDO=16192;var STORED=16193;var COPY_=16194;var COPY=16195;var TABLE=16196;var LENLENS=16197;var CODELENS=16198;var LEN_=16199;var LEN=16200;var LENEXT=16201;var DIST=16202;var DISTEXT=16203;var MATCH=16204;var LIT=16205;var CHECK=16206;var LENGTH=16207;var DONE=16208;var BAD=16209;var MEM=16210;var SYNC=16211;var ENOUGH_LENS=852;var ENOUGH_DISTS=592;var MAX_WBITS=15;var DEF_WBITS=MAX_WBITS;var zswap32=q10=>{return(q10>>>24&255)+(q10>>>8&65280)+((q10&65280)<<8)+((q10&255)<<24)};function InflateState(){this.strm=null;this.mode=0;this.last=false;this.wrap=0;this.havedict=false;this.flags=0;this.dmax=0;this.check=0;this.total=0;this.head=null;this.wbits=0;this.wsize=0;this.whave=0;this.wnext=0;this.window=null;this.hold=0;this.bits=0;this.length=0;this.offset=0;this.extra=0;this.lencode=null;this.distcode=null;this.lenbits=0;this.distbits=0;this.ncode=0;this.nlen=0;this.ndist=0;this.have=0;this.next=null;this.lens=new Uint16Array(320);this.work=new Uint16Array(288);this.lendyn=null;this.distdyn=null;this.sane=0;this.back=0;this.was=0}var inflateStateCheck=strm=>{if(!strm){return 1}const state=strm.state;if(!state||state.strm!==strm||state.mode<HEAD||state.mode>SYNC){return 1}return 0};var inflateResetKeep=strm=>{if(inflateStateCheck(strm)){return Z_STREAM_ERROR$1}const state=strm.state;strm.total_in=strm.total_out=state.total=0;strm.msg="";if(state.wrap){strm.adler=state.wrap&1}state.mode=HEAD;state.last=0;state.havedict=0;state.flags=-1;state.dmax=32768;state.head=null;state.hold=0;state.bits=0;state.lencode=state.lendyn=new Int32Array(ENOUGH_LENS);state.distcode=state.distdyn=new Int32Array(ENOUGH_DISTS);state.sane=1;state.back=-1;return Z_OK$1};var inflateReset=strm=>{if(inflateStateCheck(strm)){return Z_STREAM_ERROR$1}const state=strm.state;state.wsize=0;state.whave=0;state.wnext=0;return inflateResetKeep(strm)};var inflateReset2=(strm,windowBits)=>{let wrap2;if(inflateStateCheck(strm)){return Z_STREAM_ERROR$1}const state=strm.state;if(windowBits<0){wrap2=0;windowBits=-windowBits}else{wrap2=(windowBits>>4)+5;if(windowBits<48){windowBits&=15}}if(windowBits&&(windowBits<8||windowBits>15)){return Z_STREAM_ERROR$1}if(state.window!==null&&state.wbits!==windowBits){state.window=null}state.wrap=wrap2;state.wbits=windowBits;return inflateReset(strm)};var inflateInit2=(strm,windowBits)=>{if(!strm){return Z_STREAM_ERROR$1}const state=new InflateState;strm.state=state;state.strm=strm;state.window=null;state.mode=HEAD;const ret=inflateReset2(strm,windowBits);if(ret!==Z_OK$1){strm.state=null}return ret};var inflateInit=strm=>{return inflateInit2(strm,DEF_WBITS)};var virgin=true;var lenfix;var distfix;var fixedtables=state=>{if(virgin){lenfix=new Int32Array(512);distfix=new Int32Array(32);let sym=0;while(sym<144){state.lens[sym++]=8}while(sym<256){state.lens[sym++]=9}while(sym<280){state.lens[sym++]=7}while(sym<288){state.lens[sym++]=8}inftrees(LENS,state.lens,0,288,lenfix,0,state.work,{bits:9});sym=0;while(sym<32){state.lens[sym++]=5}inftrees(DISTS,state.lens,0,32,distfix,0,state.work,{bits:5});virgin=false}state.lencode=lenfix;state.lenbits=9;state.distcode=distfix;state.distbits=5};var updatewindow=(strm,src,end,copy2)=>{let dist;const state=strm.state;if(state.window===null){state.window=new Uint8Array(1<<state.wbits)}if(state.wsize===0){state.wsize=1<<state.wbits;state.wnext=0;state.whave=0}if(copy2>=state.wsize){state.window.set(src.subarray(end-state.wsize,end),0);state.wnext=0;state.whave=state.wsize}else{dist=state.wsize-state.wnext;if(dist>copy2){dist=copy2}state.window.set(src.subarray(end-copy2,end-copy2+dist),state.wnext);copy2-=dist;if(copy2){state.window.set(src.subarray(end-copy2,end),0);state.wnext=copy2;state.whave=state.wsize}else{state.wnext+=dist;if(state.wnext===state.wsize){state.wnext=0}if(state.whave<state.wsize){state.whave+=dist}}}return 0};var inflate$2=(strm,flush2)=>{let state;let input,output;let next2;let put;let have,left;let hold2;let bits;let _in,_out;let copy2;let from;let from_source;let here=0;let here_bits,here_op,here_val;let last_bits,last_op,last_val;let len2;let ret;const hbuf=new Uint8Array(4);let opts;let n8;const order=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(inflateStateCheck(strm)||!strm.output||!strm.input&&strm.avail_in!==0){return Z_STREAM_ERROR$1}state=strm.state;if(state.mode===TYPE){state.mode=TYPEDO}put=strm.next_out;output=strm.output;left=strm.avail_out;next2=strm.next_in;input=strm.input;have=strm.avail_in;hold2=state.hold;bits=state.bits;_in=have;_out=left;ret=Z_OK$1;inf_leave:for(;;){switch(state.mode){case HEAD:if(state.wrap===0){state.mode=TYPEDO;break}while(bits<16){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}if(state.wrap&2&&hold2===35615){if(state.wbits===0){state.wbits=15}state.check=0;hbuf[0]=hold2&255;hbuf[1]=hold2>>>8&255;state.check=crc32_1(state.check,hbuf,2,0);hold2=0;bits=0;state.mode=FLAGS;break}if(state.head){state.head.done=false}if(!(state.wrap&1)||(((hold2&255)<<8)+(hold2>>8))%31){strm.msg="incorrect header check";state.mode=BAD;break}if((hold2&15)!==Z_DEFLATED){strm.msg="unknown compression method";state.mode=BAD;break}hold2>>>=4;bits-=4;len2=(hold2&15)+8;if(state.wbits===0){state.wbits=len2}if(len2>15||len2>state.wbits){strm.msg="invalid window size";state.mode=BAD;break}state.dmax=1<<state.wbits;state.flags=0;strm.adler=state.check=1;state.mode=hold2&512?DICTID:TYPE;hold2=0;bits=0;break;case FLAGS:while(bits<16){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}state.flags=hold2;if((state.flags&255)!==Z_DEFLATED){strm.msg="unknown compression method";state.mode=BAD;break}if(state.flags&57344){strm.msg="unknown header flags set";state.mode=BAD;break}if(state.head){state.head.text=hold2>>8&1}if(state.flags&512&&state.wrap&4){hbuf[0]=hold2&255;hbuf[1]=hold2>>>8&255;state.check=crc32_1(state.check,hbuf,2,0)}hold2=0;bits=0;state.mode=TIME;case TIME:while(bits<32){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}if(state.head){state.head.time=hold2}if(state.flags&512&&state.wrap&4){hbuf[0]=hold2&255;hbuf[1]=hold2>>>8&255;hbuf[2]=hold2>>>16&255;hbuf[3]=hold2>>>24&255;state.check=crc32_1(state.check,hbuf,4,0)}hold2=0;bits=0;state.mode=OS;case OS:while(bits<16){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}if(state.head){state.head.xflags=hold2&255;state.head.os=hold2>>8}if(state.flags&512&&state.wrap&4){hbuf[0]=hold2&255;hbuf[1]=hold2>>>8&255;state.check=crc32_1(state.check,hbuf,2,0)}hold2=0;bits=0;state.mode=EXLEN;case EXLEN:if(state.flags&1024){while(bits<16){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}state.length=hold2;if(state.head){state.head.extra_len=hold2}if(state.flags&512&&state.wrap&4){hbuf[0]=hold2&255;hbuf[1]=hold2>>>8&255;state.check=crc32_1(state.check,hbuf,2,0)}hold2=0;bits=0}else if(state.head){state.head.extra=null}state.mode=EXTRA;case EXTRA:if(state.flags&1024){copy2=state.length;if(copy2>have){copy2=have}if(copy2){if(state.head){len2=state.head.extra_len-state.length;if(!state.head.extra){state.head.extra=new Uint8Array(state.head.extra_len)}state.head.extra.set(input.subarray(next2,next2+copy2),len2)}if(state.flags&512&&state.wrap&4){state.check=crc32_1(state.check,input,copy2,next2)}have-=copy2;next2+=copy2;state.length-=copy2}if(state.length){break inf_leave}}state.length=0;state.mode=NAME;case NAME:if(state.flags&2048){if(have===0){break inf_leave}copy2=0;do{len2=input[next2+copy2++];if(state.head&&len2&&state.length<65536){state.head.name+=String.fromCharCode(len2)}}while(len2&&copy2<have);if(state.flags&512&&state.wrap&4){state.check=crc32_1(state.check,input,copy2,next2)}have-=copy2;next2+=copy2;if(len2){break inf_leave}}else if(state.head){state.head.name=null}state.length=0;state.mode=COMMENT;case COMMENT:if(state.flags&4096){if(have===0){break inf_leave}copy2=0;do{len2=input[next2+copy2++];if(state.head&&len2&&state.length<65536){state.head.comment+=String.fromCharCode(len2)}}while(len2&&copy2<have);if(state.flags&512&&state.wrap&4){state.check=crc32_1(state.check,input,copy2,next2)}have-=copy2;next2+=copy2;if(len2){break inf_leave}}else if(state.head){state.head.comment=null}state.mode=HCRC;case HCRC:if(state.flags&512){while(bits<16){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}if(state.wrap&4&&hold2!==(state.check&65535)){strm.msg="header crc mismatch";state.mode=BAD;break}hold2=0;bits=0}if(state.head){state.head.hcrc=state.flags>>9&1;state.head.done=true}strm.adler=state.check=0;state.mode=TYPE;break;case DICTID:while(bits<32){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}strm.adler=state.check=zswap32(hold2);hold2=0;bits=0;state.mode=DICT;case DICT:if(state.havedict===0){strm.next_out=put;strm.avail_out=left;strm.next_in=next2;strm.avail_in=have;state.hold=hold2;state.bits=bits;return Z_NEED_DICT$1}strm.adler=state.check=1;state.mode=TYPE;case TYPE:if(flush2===Z_BLOCK||flush2===Z_TREES){break inf_leave}case TYPEDO:if(state.last){hold2>>>=bits&7;bits-=bits&7;state.mode=CHECK;break}while(bits<3){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}state.last=hold2&1;hold2>>>=1;bits-=1;switch(hold2&3){case 0:state.mode=STORED;break;case 1:fixedtables(state);state.mode=LEN_;if(flush2===Z_TREES){hold2>>>=2;bits-=2;break inf_leave}break;case 2:state.mode=TABLE;break;case 3:strm.msg="invalid block type";state.mode=BAD}hold2>>>=2;bits-=2;break;case STORED:hold2>>>=bits&7;bits-=bits&7;while(bits<32){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}if((hold2&65535)!==(hold2>>>16^65535)){strm.msg="invalid stored block lengths";state.mode=BAD;break}state.length=hold2&65535;hold2=0;bits=0;state.mode=COPY_;if(flush2===Z_TREES){break inf_leave}case COPY_:state.mode=COPY;case COPY:copy2=state.length;if(copy2){if(copy2>have){copy2=have}if(copy2>left){copy2=left}if(copy2===0){break inf_leave}output.set(input.subarray(next2,next2+copy2),put);have-=copy2;next2+=copy2;left-=copy2;put+=copy2;state.length-=copy2;break}state.mode=TYPE;break;case TABLE:while(bits<14){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}state.nlen=(hold2&31)+257;hold2>>>=5;bits-=5;state.ndist=(hold2&31)+1;hold2>>>=5;bits-=5;state.ncode=(hold2&15)+4;hold2>>>=4;bits-=4;if(state.nlen>286||state.ndist>30){strm.msg="too many length or distance symbols";state.mode=BAD;break}state.have=0;state.mode=LENLENS;case LENLENS:while(state.have<state.ncode){while(bits<3){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}state.lens[order[state.have++]]=hold2&7;hold2>>>=3;bits-=3}while(state.have<19){state.lens[order[state.have++]]=0}state.lencode=state.lendyn;state.lenbits=7;opts={bits:state.lenbits};ret=inftrees(CODES,state.lens,0,19,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid code lengths set";state.mode=BAD;break}state.have=0;state.mode=CODELENS;case CODELENS:while(state.have<state.nlen+state.ndist){for(;;){here=state.lencode[hold2&(1<<state.lenbits)-1];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}if(here_val<16){hold2>>>=here_bits;bits-=here_bits;state.lens[state.have++]=here_val}else{if(here_val===16){n8=here_bits+2;while(bits<n8){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}hold2>>>=here_bits;bits-=here_bits;if(state.have===0){strm.msg="invalid bit length repeat";state.mode=BAD;break}len2=state.lens[state.have-1];copy2=3+(hold2&3);hold2>>>=2;bits-=2}else if(here_val===17){n8=here_bits+3;while(bits<n8){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}hold2>>>=here_bits;bits-=here_bits;len2=0;copy2=3+(hold2&7);hold2>>>=3;bits-=3}else{n8=here_bits+7;while(bits<n8){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}hold2>>>=here_bits;bits-=here_bits;len2=0;copy2=11+(hold2&127);hold2>>>=7;bits-=7}if(state.have+copy2>state.nlen+state.ndist){strm.msg="invalid bit length repeat";state.mode=BAD;break}while(copy2--){state.lens[state.have++]=len2}}}if(state.mode===BAD){break}if(state.lens[256]===0){strm.msg="invalid code -- missing end-of-block";state.mode=BAD;break}state.lenbits=9;opts={bits:state.lenbits};ret=inftrees(LENS,state.lens,0,state.nlen,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid literal/lengths set";state.mode=BAD;break}state.distbits=6;state.distcode=state.distdyn;opts={bits:state.distbits};ret=inftrees(DISTS,state.lens,state.nlen,state.ndist,state.distcode,0,state.work,opts);state.distbits=opts.bits;if(ret){strm.msg="invalid distances set";state.mode=BAD;break}state.mode=LEN_;if(flush2===Z_TREES){break inf_leave}case LEN_:state.mode=LEN;case LEN:if(have>=6&&left>=258){strm.next_out=put;strm.avail_out=left;strm.next_in=next2;strm.avail_in=have;state.hold=hold2;state.bits=bits;inffast(strm,_out);put=strm.next_out;output=strm.output;left=strm.avail_out;next2=strm.next_in;input=strm.input;have=strm.avail_in;hold2=state.hold;bits=state.bits;if(state.mode===TYPE){state.back=-1}break}state.back=0;for(;;){here=state.lencode[hold2&(1<<state.lenbits)-1];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}if(here_op&&(here_op&240)===0){last_bits=here_bits;last_op=here_op;last_val=here_val;for(;;){here=state.lencode[last_val+((hold2&(1<<last_bits+last_op)-1)>>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}hold2>>>=last_bits;bits-=last_bits;state.back+=last_bits}hold2>>>=here_bits;bits-=here_bits;state.back+=here_bits;state.length=here_val;if(here_op===0){state.mode=LIT;break}if(here_op&32){state.back=-1;state.mode=TYPE;break}if(here_op&64){strm.msg="invalid literal/length code";state.mode=BAD;break}state.extra=here_op&15;state.mode=LENEXT;case LENEXT:if(state.extra){n8=state.extra;while(bits<n8){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}state.length+=hold2&(1<<state.extra)-1;hold2>>>=state.extra;bits-=state.extra;state.back+=state.extra}state.was=state.length;state.mode=DIST;case DIST:for(;;){here=state.distcode[hold2&(1<<state.distbits)-1];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}if((here_op&240)===0){last_bits=here_bits;last_op=here_op;last_val=here_val;for(;;){here=state.distcode[last_val+((hold2&(1<<last_bits+last_op)-1)>>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}hold2>>>=last_bits;bits-=last_bits;state.back+=last_bits}hold2>>>=here_bits;bits-=here_bits;state.back+=here_bits;if(here_op&64){strm.msg="invalid distance code";state.mode=BAD;break}state.offset=here_val;state.extra=here_op&15;state.mode=DISTEXT;case DISTEXT:if(state.extra){n8=state.extra;while(bits<n8){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}state.offset+=hold2&(1<<state.extra)-1;hold2>>>=state.extra;bits-=state.extra;state.back+=state.extra}if(state.offset>state.dmax){strm.msg="invalid distance too far back";state.mode=BAD;break}state.mode=MATCH;case MATCH:if(left===0){break inf_leave}copy2=_out-left;if(state.offset>copy2){copy2=state.offset-copy2;if(copy2>state.whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD;break}}if(copy2>state.wnext){copy2-=state.wnext;from=state.wsize-copy2}else{from=state.wnext-copy2}if(copy2>state.length){copy2=state.length}from_source=state.window}else{from_source=output;from=put-state.offset;copy2=state.length}if(copy2>left){copy2=left}left-=copy2;state.length-=copy2;do{output[put++]=from_source[from++]}while(--copy2);if(state.length===0){state.mode=LEN}break;case LIT:if(left===0){break inf_leave}output[put++]=state.length;left--;state.mode=LEN;break;case CHECK:if(state.wrap){while(bits<32){if(have===0){break inf_leave}have--;hold2|=input[next2++]<<bits;bits+=8}_out-=left;strm.total_out+=_out;state.total+=_out;if(state.wrap&4&&_out){strm.adler=state.check=state.flags?crc32_1(state.check,output,_out,put-_out):adler32_1(state.check,output,_out,put-_out)}_out=left;if(state.wrap&4&&(state.flags?hold2:zswap32(hold2))!==state.check){strm.msg="incorrect data check";state.mode=BAD;break}hold2=0;bits=0}state.mode=LENGTH;case LENGTH:if(state.wrap&&state.flags){while(bits<32){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}if(state.wrap&4&&hold2!==(state.total&4294967295)){strm.msg="incorrect length check";state.mode=BAD;break}hold2=0;bits=0}state.mode=DONE;case DONE:ret=Z_STREAM_END$1;break inf_leave;case BAD:ret=Z_DATA_ERROR$1;break inf_leave;case MEM:return Z_MEM_ERROR$1;case SYNC:default:return Z_STREAM_ERROR$1}}strm.next_out=put;strm.avail_out=left;strm.next_in=next2;strm.avail_in=have;state.hold=hold2;state.bits=bits;if(state.wsize||_out!==strm.avail_out&&state.mode<BAD&&(state.mode<CHECK||flush2!==Z_FINISH$1)){if(updatewindow(strm,strm.output,strm.next_out,_out-strm.avail_out));}_in-=strm.avail_in;_out-=strm.avail_out;strm.total_in+=_in;strm.total_out+=_out;state.total+=_out;if(state.wrap&4&&_out){strm.adler=state.check=state.flags?crc32_1(state.check,output,_out,strm.next_out-_out):adler32_1(state.check,output,_out,strm.next_out-_out)}strm.data_type=state.bits+(state.last?64:0)+(state.mode===TYPE?128:0)+(state.mode===LEN_||state.mode===COPY_?256:0);if((_in===0&&_out===0||flush2===Z_FINISH$1)&&ret===Z_OK$1){ret=Z_BUF_ERROR$1}return ret};var inflateEnd=strm=>{if(inflateStateCheck(strm)){return Z_STREAM_ERROR$1}let state=strm.state;if(state.window){state.window=null}strm.state=null;return Z_OK$1};var inflateGetHeader=(strm,head)=>{if(inflateStateCheck(strm)){return Z_STREAM_ERROR$1}const state=strm.state;if((state.wrap&2)===0){return Z_STREAM_ERROR$1}state.head=head;head.done=false;return Z_OK$1};var inflateSetDictionary=(strm,dictionary2)=>{const dictLength=dictionary2.length;let state;let dictid;let ret;if(inflateStateCheck(strm)){return Z_STREAM_ERROR$1}state=strm.state;if(state.wrap!==0&&state.mode!==DICT){return Z_STREAM_ERROR$1}if(state.mode===DICT){dictid=1;dictid=adler32_1(dictid,dictionary2,dictLength,0);if(dictid!==state.check){return Z_DATA_ERROR$1}}ret=updatewindow(strm,dictionary2,dictLength,dictLength);if(ret){state.mode=MEM;return Z_MEM_ERROR$1}state.havedict=1;return Z_OK$1};var inflateReset_1=inflateReset;var inflateReset2_1=inflateReset2;var inflateResetKeep_1=inflateResetKeep;var inflateInit_1=inflateInit;var inflateInit2_1=inflateInit2;var inflate_2$1=inflate$2;var inflateEnd_1=inflateEnd;var inflateGetHeader_1=inflateGetHeader;var inflateSetDictionary_1=inflateSetDictionary;var inflateInfo="pako inflate (from Nodeca project)";var inflate_1$2={inflateReset:inflateReset_1,inflateReset2:inflateReset2_1,inflateResetKeep:inflateResetKeep_1,inflateInit:inflateInit_1,inflateInit2:inflateInit2_1,inflate:inflate_2$1,inflateEnd:inflateEnd_1,inflateGetHeader:inflateGetHeader_1,inflateSetDictionary:inflateSetDictionary_1,inflateInfo};function GZheader(){this.text=0;this.time=0;this.xflags=0;this.os=0;this.extra=null;this.extra_len=0;this.name="";this.comment="";this.hcrc=0;this.done=false}var gzheader=GZheader;var toString=Object.prototype.toString;var{Z_NO_FLUSH,Z_FINISH,Z_OK,Z_STREAM_END,Z_NEED_DICT,Z_STREAM_ERROR,Z_DATA_ERROR,Z_MEM_ERROR,Z_BUF_ERROR}=constants$2;var defaultOptions={chunkSize:1024*64,windowBits:15,to:""};function Inflate$1(options){this.options=common.assign({},defaultOptions,options||{});const opt=this.options;if(opt.raw&&opt.windowBits>=0&&opt.windowBits<16){opt.windowBits=-opt.windowBits;if(opt.windowBits===0){opt.windowBits=-15}}if(opt.windowBits>=0&&opt.windowBits<16&&!(options&&options.windowBits)){opt.windowBits+=32}if(opt.windowBits>15&&opt.windowBits<48){if((opt.windowBits&15)===0){opt.windowBits|=15}}this.err=0;this.msg="";this.ended=false;this.chunks=[];this.strm=new zstream;this.strm.avail_out=0;let status=inflate_1$2.inflateInit2(this.strm,opt.windowBits);if(status!==Z_OK){throw new Error(messages[status])}this.header=new gzheader;inflate_1$2.inflateGetHeader(this.strm,this.header);if(opt.dictionary){if(typeof opt.dictionary==="string"){opt.dictionary=strings.string2buf(opt.dictionary)}else if(toString.call(opt.dictionary)==="[object ArrayBuffer]"){opt.dictionary=new Uint8Array(opt.dictionary)}if(opt.raw){status=inflate_1$2.inflateSetDictionary(this.strm,opt.dictionary);if(status!==Z_OK){throw new Error(messages[status])}}}}Inflate$1.prototype.push=function(data2,flush_mode){const strm=this.strm;const chunkSize=this.options.chunkSize;const dictionary2=this.options.dictionary;let status,_flush_mode,last_avail_out;if(this.ended)return false;if(flush_mode===~~flush_mode)_flush_mode=flush_mode;else _flush_mode=flush_mode===true?Z_FINISH:Z_NO_FLUSH;if(toString.call(data2)==="[object ArrayBuffer]"){strm.input=new Uint8Array(data2)}else{strm.input=data2}strm.next_in=0;strm.avail_in=strm.input.length;for(;;){if(strm.avail_out===0){strm.output=new Uint8Array(chunkSize);strm.next_out=0;strm.avail_out=chunkSize}status=inflate_1$2.inflate(strm,_flush_mode);if(status===Z_NEED_DICT&&dictionary2){status=inflate_1$2.inflateSetDictionary(strm,dictionary2);if(status===Z_OK){status=inflate_1$2.inflate(strm,_flush_mode)}else if(status===Z_DATA_ERROR){status=Z_NEED_DICT}}while(strm.avail_in>0&&status===Z_STREAM_END&&strm.state.wrap&2&&strm.state.flags!==0&&strm.input[strm.next_in]!==0){inflate_1$2.inflateReset(strm);status=inflate_1$2.inflate(strm,_flush_mode)}switch(status){case Z_STREAM_ERROR:case Z_DATA_ERROR:case Z_NEED_DICT:case Z_MEM_ERROR:this.onEnd(status);this.ended=true;return false}last_avail_out=strm.avail_out;if(strm.next_out){if(strm.avail_out===0||status===Z_STREAM_END||_flush_mode>0){if(this.options.to==="string"){let next_out_utf8=strings.utf8border(strm.output,strm.next_out);let tail=strm.next_out-next_out_utf8;let utf8str=strings.buf2string(strm.output,next_out_utf8);strm.next_out=tail;strm.avail_out=chunkSize-tail;if(tail)strm.output.set(strm.output.subarray(next_out_utf8,next_out_utf8+tail),0);this.onData(utf8str)}else{this.onData(strm.output.length===strm.next_out?strm.output:strm.output.subarray(0,strm.next_out));strm.avail_out=0;strm.next_out=0}}}if((status===Z_OK||status===Z_BUF_ERROR)&&last_avail_out===0)continue;if(status===Z_STREAM_END){status=inflate_1$2.inflateEnd(this.strm);this.onEnd(status);this.ended=true;return true}if(strm.avail_in===0){if(_flush_mode===Z_FINISH){status=inflate_1$2.inflateEnd(this.strm);this.onEnd(status===Z_OK?Z_BUF_ERROR:status);this.ended=true;return false}break}}return true};Inflate$1.prototype.onData=function(chunk){this.chunks.push(chunk)};Inflate$1.prototype.onEnd=function(status){if(status===Z_OK){if(this.options.to==="string"){this.result=this.chunks.join("")}else{this.result=common.flattenChunks(this.chunks)}}this.chunks=[];this.err=status;this.msg=this.strm.msg};function inflate$1(input,options){const inflator=new Inflate$1(options);inflator.push(input,true);if(inflator.err)throw inflator.msg||messages[inflator.err];return inflator.result}function inflateRaw$1(input,options){options=options||{};options.raw=true;return inflate$1(input,options)}var Inflate_1$1=Inflate$1;var inflate_2=inflate$1;var inflateRaw_1$1=inflateRaw$1;var ungzip$1=inflate$1;var constants=constants$2;var inflate_1$1={Inflate:Inflate_1$1,inflate:inflate_2,inflateRaw:inflateRaw_1$1,ungzip:ungzip$1,constants};var{Deflate,deflate,deflateRaw,gzip}=deflate_1$1;var{Inflate,inflate,inflateRaw,ungzip}=inflate_1$1;var Deflate_1=Deflate;var deflate_1=deflate;var deflateRaw_1=deflateRaw;var gzip_1=gzip;var Inflate_1=Inflate;var inflate_1=inflate;var inflateRaw_1=inflateRaw;var ungzip_1=ungzip;var constants_1=constants$2;var pako={Deflate:Deflate_1,deflate:deflate_1,deflateRaw:deflateRaw_1,gzip:gzip_1,Inflate:Inflate_1,inflate:inflate_1,inflateRaw:inflateRaw_1,ungzip:ungzip_1,constants:constants_1};var constants2=Object.freeze({Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1});function bytesOf(data2){if(typeof data2==="string")return new TextEncoder().encode(data2);return data2 instanceof Uint8Array?data2:new Uint8Array(data2)}function gzipSync(data2,options={}){const level=options.level??constants2.Z_DEFAULT_COMPRESSION;if(!Number.isInteger(level)||level<-1||level>9)throw new RangeError(`The value of "options.level" is out of range. It must be >= -1 and <= 9. Received ${level}`);return pako.gzip(bytesOf(data2),{level})}function gunzipSync(data2,options={}){const output=pako.ungzip(bytesOf(data2));if(options.maxOutputLength!==void 0&&output.byteLength>options.maxOutputLength){throw Object.assign(new RangeError(`Cannot create a Buffer larger than ${options.maxOutputLength} bytes`),{code:"ERR_BUFFER_TOO_LARGE"})}return output}var Diff=class{diff(oldStr,newStr,options={}){let callback;if(typeof options==="function"){callback=options;options={}}else if("callback"in options){callback=options.callback}const oldString=this.castInput(oldStr,options);const newString=this.castInput(newStr,options);const oldTokens=this.removeEmpty(this.tokenize(oldString,options));const newTokens=this.removeEmpty(this.tokenize(newString,options));return this.diffWithOptionsObj(oldTokens,newTokens,options,callback)}diffWithOptionsObj(oldTokens,newTokens,options,callback){var _a4;const done=value=>{value=this.postProcess(value,options);if(callback){setTimeout(function(){callback(value)},0);return void 0}else{return value}};const newLen=newTokens.length,oldLen=oldTokens.length;let editLength=1;let maxEditLength=newLen+oldLen;if(options.maxEditLength!=null){maxEditLength=Math.min(maxEditLength,options.maxEditLength)}const maxExecutionTime=(_a4=options.timeout)!==null&&_a4!==void 0?_a4:Infinity;const abortAfterTimestamp=Date.now()+maxExecutionTime;const bestPath=[{oldPos:-1,lastComponent:void 0}];let newPos=this.extractCommon(bestPath[0],newTokens,oldTokens,0,options);if(bestPath[0].oldPos+1>=oldLen&&newPos+1>=newLen){return done(this.buildValues(bestPath[0].lastComponent,newTokens,oldTokens))}let minDiagonalToConsider=-Infinity,maxDiagonalToConsider=Infinity;const execEditLength=()=>{for(let diagonalPath=Math.max(minDiagonalToConsider,-editLength);diagonalPath<=Math.min(maxDiagonalToConsider,editLength);diagonalPath+=2){let basePath;const removePath2=bestPath[diagonalPath-1],addPath=bestPath[diagonalPath+1];if(removePath2){bestPath[diagonalPath-1]=void 0}let canAdd=false;if(addPath){const addPathNewPos=addPath.oldPos-diagonalPath;canAdd=addPath&&0<=addPathNewPos&&addPathNewPos<newLen}const canRemove=removePath2&&removePath2.oldPos+1<oldLen;if(!canAdd&&!canRemove){bestPath[diagonalPath]=void 0;continue}if(!canRemove||canAdd&&removePath2.oldPos<addPath.oldPos){basePath=this.addToPath(addPath,true,false,0,options)}else{basePath=this.addToPath(removePath2,false,true,1,options)}newPos=this.extractCommon(basePath,newTokens,oldTokens,diagonalPath,options);if(basePath.oldPos+1>=oldLen&&newPos+1>=newLen){return done(this.buildValues(basePath.lastComponent,newTokens,oldTokens))||true}else{bestPath[diagonalPath]=basePath;if(basePath.oldPos+1>=oldLen){maxDiagonalToConsider=Math.min(maxDiagonalToConsider,diagonalPath-1)}if(newPos+1>=newLen){minDiagonalToConsider=Math.max(minDiagonalToConsider,diagonalPath+1)}}}editLength++};if(callback){(function exec(){setTimeout(function(){if(editLength>maxEditLength||Date.now()>abortAfterTimestamp){return callback(void 0)}if(!execEditLength()){exec()}},0)})()}else{while(editLength<=maxEditLength&&Date.now()<=abortAfterTimestamp){const ret=execEditLength();if(ret){return ret}}}}addToPath(path3,added,removed,oldPosInc,options){const last=path3.lastComponent;if(last&&!options.oneChangePerToken&&last.added===added&&last.removed===removed){return{oldPos:path3.oldPos+oldPosInc,lastComponent:{count:last.count+1,added,removed,previousComponent:last.previousComponent}}}else{return{oldPos:path3.oldPos+oldPosInc,lastComponent:{count:1,added,removed,previousComponent:last}}}}extractCommon(basePath,newTokens,oldTokens,diagonalPath,options){const newLen=newTokens.length,oldLen=oldTokens.length;let oldPos=basePath.oldPos,newPos=oldPos-diagonalPath,commonCount=0;while(newPos+1<newLen&&oldPos+1<oldLen&&this.equals(oldTokens[oldPos+1],newTokens[newPos+1],options)){newPos++;oldPos++;commonCount++;if(options.oneChangePerToken){basePath.lastComponent={count:1,previousComponent:basePath.lastComponent,added:false,removed:false}}}if(commonCount&&!options.oneChangePerToken){basePath.lastComponent={count:commonCount,previousComponent:basePath.lastComponent,added:false,removed:false}}basePath.oldPos=oldPos;return newPos}equals(left,right,options){if(options.comparator){return options.comparator(left,right)}else{return left===right||!!options.ignoreCase&&left.toLowerCase()===right.toLowerCase()}}removeEmpty(array){const ret=[];for(let i10=0;i10<array.length;i10++){if(array[i10]){ret.push(array[i10])}}return ret}castInput(value,options){return value}tokenize(value,options){return Array.from(value)}join(chars){return chars.join("")}postProcess(changeObjects,options){return changeObjects}get useLongestToken(){return false}buildValues(lastComponent,newTokens,oldTokens){const components=[];let nextComponent;while(lastComponent){components.push(lastComponent);nextComponent=lastComponent.previousComponent;delete lastComponent.previousComponent;lastComponent=nextComponent}components.reverse();const componentLen=components.length;let componentPos=0,newPos=0,oldPos=0;for(;componentPos<componentLen;componentPos++){const component=components[componentPos];if(!component.removed){if(!component.added&&this.useLongestToken){let value=newTokens.slice(newPos,newPos+component.count);value=value.map(function(value2,i10){const oldValue=oldTokens[oldPos+i10];return oldValue.length>value2.length?oldValue:value2});component.value=this.join(value)}else{component.value=this.join(newTokens.slice(newPos,newPos+component.count))}newPos+=component.count;if(!component.added){oldPos+=component.count}}else{component.value=this.join(oldTokens.slice(oldPos,oldPos+component.count));oldPos+=component.count}}return components}};var LineDiff=class extends Diff{constructor(){super(...arguments);this.tokenize=tokenize}equals(left,right,options){if(options.ignoreWhitespace){if(!options.newlineIsToken||!left.includes("\n")){left=left.trim()}if(!options.newlineIsToken||!right.includes("\n")){right=right.trim()}}else if(options.ignoreNewlineAtEof&&!options.newlineIsToken){if(left.endsWith("\n")){left=left.slice(0,-1)}if(right.endsWith("\n")){right=right.slice(0,-1)}}return super.equals(left,right,options)}};var lineDiff=new LineDiff;function diffLines(oldStr,newStr,options){return lineDiff.diff(oldStr,newStr,options)}function tokenize(value,options){if(options.stripTrailingCr){value=value.replace(/\r\n/g,"\n")}const retLines=[],linesAndNewlines=value.split(/(\n|\r\n)/);if(!linesAndNewlines[linesAndNewlines.length-1]){linesAndNewlines.pop()}for(let i10=0;i10<linesAndNewlines.length;i10++){const line=linesAndNewlines[i10];if(i10%2&&!options.newlineIsToken){retLines[retLines.length-1]+=line}else{retLines.push(line)}}return retLines}var INCLUDE_HEADERS={includeIndex:true,includeUnderline:true,includeFileHeaders:true};function structuredPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,options){let optionsObj;if(!options){optionsObj={}}else if(typeof options==="function"){optionsObj={callback:options}}else{optionsObj=options}if(typeof optionsObj.context==="undefined"){optionsObj.context=4}const context2=optionsObj.context;if(optionsObj.newlineIsToken){throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions")}if(!optionsObj.callback){return diffLinesResultToPatch(diffLines(oldStr,newStr,optionsObj))}else{const{callback}=optionsObj;diffLines(oldStr,newStr,Object.assign(Object.assign({},optionsObj),{callback:diff=>{const patch=diffLinesResultToPatch(diff);callback(patch)}}))}function diffLinesResultToPatch(diff){if(!diff){return}diff.push({value:"",lines:[]});function contextLines(lines){return lines.map(function(entry){return" "+entry})}const hunks=[];let oldRangeStart=0,newRangeStart=0,curRange=[],oldLine=1,newLine=1;for(let i10=0;i10<diff.length;i10++){const current3=diff[i10],lines=current3.lines||splitLines(current3.value);current3.lines=lines;if(current3.added||current3.removed){if(!oldRangeStart){const prev=diff[i10-1];oldRangeStart=oldLine;newRangeStart=newLine;if(prev){curRange=context2>0?contextLines(prev.lines.slice(-context2)):[];oldRangeStart-=curRange.length;newRangeStart-=curRange.length}}for(const line of lines){curRange.push((current3.added?"+":"-")+line)}if(current3.added){newLine+=lines.length}else{oldLine+=lines.length}}else{if(oldRangeStart){if(lines.length<=context2*2&&i10<diff.length-2){for(const line of contextLines(lines)){curRange.push(line)}}else{const contextSize=Math.min(lines.length,context2);for(const line of contextLines(lines.slice(0,contextSize))){curRange.push(line)}const hunk={oldStart:oldRangeStart,oldLines:oldLine-oldRangeStart+contextSize,newStart:newRangeStart,newLines:newLine-newRangeStart+contextSize,lines:curRange};hunks.push(hunk);oldRangeStart=0;newRangeStart=0;curRange=[]}}oldLine+=lines.length;newLine+=lines.length}}for(const hunk of hunks){for(let i10=0;i10<hunk.lines.length;i10++){if(hunk.lines[i10].endsWith("\n")){hunk.lines[i10]=hunk.lines[i10].slice(0,-1)}else{hunk.lines.splice(i10+1,0,"\");i10++}}}return{oldFileName,newFileName,oldHeader,newHeader,hunks}}}function formatPatch(patch,headerOptions){if(!headerOptions){headerOptions=INCLUDE_HEADERS}if(Array.isArray(patch)){if(patch.length>1&&!headerOptions.includeFileHeaders){throw new Error("Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)")}return patch.map(p=>formatPatch(p,headerOptions)).join("\n")}const ret=[];if(headerOptions.includeIndex&&patch.oldFileName==patch.newFileName){ret.push("Index: "+patch.oldFileName)}if(headerOptions.includeUnderline){ret.push("===================================================================")}if(headerOptions.includeFileHeaders){ret.push("--- "+patch.oldFileName+(typeof patch.oldHeader==="undefined"?"":" "+patch.oldHeader));ret.push("+++ "+patch.newFileName+(typeof patch.newHeader==="undefined"?"":" "+patch.newHeader))}for(let i10=0;i10<patch.hunks.length;i10++){const hunk=patch.hunks[i10];if(hunk.oldLines===0){hunk.oldStart-=1}if(hunk.newLines===0){hunk.newStart-=1}ret.push("@@ -"+hunk.oldStart+","+hunk.oldLines+" +"+hunk.newStart+","+hunk.newLines+" @@");for(const line of hunk.lines){ret.push(line)}}return ret.join("\n")+"\n"}function createTwoFilesPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,options){if(typeof options==="function"){options={callback:options}}if(!(options===null||options===void 0?void 0:options.callback)){const patchObj=structuredPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,options);if(!patchObj){return}return formatPatch(patchObj,options===null||options===void 0?void 0:options.headerOptions)}else{const{callback}=options;structuredPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,Object.assign(Object.assign({},options),{callback:patchObj=>{if(!patchObj){callback(void 0)}else{callback(formatPatch(patchObj,options.headerOptions))}}}))}}function splitLines(text){const hasTrailingNl=text.endsWith("\n");const result=text.split("\n").map(line=>line+"\n");if(hasTrailingNl){result.pop()}else{result.push(result.pop().slice(0,-1))}return result}function extend(destination){for(var i10=1;i10<arguments.length;i10++){var source=arguments[i10];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key))destination[key]=source[key]}}return destination}function repeat(character,count){return Array(count+1).join(character)}function trimLeadingNewlines(string){return string.replace(/^\n*/,"")}function trimTrailingNewlines(string){var indexEnd=string.length;while(indexEnd>0&&string[indexEnd-1]==="\n")indexEnd--;return string.substring(0,indexEnd)}function trimNewlines(string){return trimTrailingNewlines(trimLeadingNewlines(string))}var blockElements=["ADDRESS","ARTICLE","ASIDE","AUDIO","BLOCKQUOTE","BODY","CANVAS","CENTER","DD","DIR","DIV","DL","DT","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","FRAMESET","H1","H2","H3","H4","H5","H6","HEADER","HGROUP","HR","HTML","ISINDEX","LI","MAIN","MENU","NAV","NOFRAMES","NOSCRIPT","OL","OUTPUT","P","PRE","SECTION","TABLE","TBODY","TD","TFOOT","TH","THEAD","TR","UL"];function isBlock(node){return is(node,blockElements)}var voidElements=["AREA","BASE","BR","COL","COMMAND","EMBED","HR","IMG","INPUT","KEYGEN","LINK","META","PARAM","SOURCE","TRACK","WBR"];function isVoid(node){return is(node,voidElements)}function hasVoid(node){return has(node,voidElements)}var meaningfulWhenBlankElements=["A","TABLE","THEAD","TBODY","TFOOT","TH","TD","IFRAME","SCRIPT","AUDIO","VIDEO"];function isMeaningfulWhenBlank(node){return is(node,meaningfulWhenBlankElements)}function hasMeaningfulWhenBlank(node){return has(node,meaningfulWhenBlankElements)}function is(node,tagNames){return tagNames.indexOf(node.nodeName)>=0}function has(node,tagNames){return node.getElementsByTagName&&tagNames.some(function(tagName){return node.getElementsByTagName(tagName).length})}var markdownEscapes=[[/\\/g,"\\\\"],[/\*/g,"\\*"],[/^-/g,"\\-"],[/^\+ /g,"\\+ "],[/^(=+)/g,"\\$1"],[/^(#{1,6}) /g,"\\$1 "],[/`/g,"\\`"],[/^~~~/g,"\\~~~"],[/\[/g,"\\["],[/\]/g,"\\]"],[/^>/g,"\\>"],[/_/g,"\\_"],[/^(\d+)\. /g,"$1\\. "]];function escapeMarkdown(string){return markdownEscapes.reduce(function(accumulator,escape2){return accumulator.replace(escape2[0],escape2[1])},string)}var rules={};rules.paragraph={filter:"p",replacement:function(content){return"\n\n"+content+"\n\n"}};rules.lineBreak={filter:"br",replacement:function(content,node,options){return options.br+"\n"}};rules.heading={filter:["h1","h2","h3","h4","h5","h6"],replacement:function(content,node,options){var hLevel=Number(node.nodeName.charAt(1));if(options.headingStyle==="setext"&&hLevel<3){var underline=repeat(hLevel===1?"=":"-",content.length);return"\n\n"+content+"\n"+underline+"\n\n"}else{return"\n\n"+repeat("#",hLevel)+" "+content+"\n\n"}}};rules.blockquote={filter:"blockquote",replacement:function(content){content=trimNewlines(content).replace(/^/gm,"> ");return"\n\n"+content+"\n\n"}};rules.list={filter:["ul","ol"],replacement:function(content,node){var parent=node.parentNode;if(parent.nodeName==="LI"&&parent.lastElementChild===node){return"\n"+content}else{return"\n\n"+content+"\n\n"}}};rules.listItem={filter:"li",replacement:function(content,node,options){var prefix2=options.bulletListMarker+" ";var parent=node.parentNode;if(parent.nodeName==="OL"){var start=parent.getAttribute("start");var index2=Array.prototype.indexOf.call(parent.children,node);prefix2=(start?Number(start)+index2:index2+1)+". "}var isParagraph=/\n$/.test(content);content=trimNewlines(content)+(isParagraph?"\n":"");content=content.replace(/\n/gm,"\n"+" ".repeat(prefix2.length));return prefix2+content+(node.nextSibling?"\n":"")}};rules.indentedCodeBlock={filter:function(node,options){return options.codeBlockStyle==="indented"&&node.nodeName==="PRE"&&node.firstChild&&node.firstChild.nodeName==="CODE"},replacement:function(content,node,options){return"\n\n "+node.firstChild.textContent.replace(/\n/g,"\n ")+"\n\n"}};rules.fencedCodeBlock={filter:function(node,options){return options.codeBlockStyle==="fenced"&&node.nodeName==="PRE"&&node.firstChild&&node.firstChild.nodeName==="CODE"},replacement:function(content,node,options){var className=node.firstChild.getAttribute("class")||"";var language=(className.match(/language-(\S+)/)||[null,""])[1];var code3=node.firstChild.textContent;var fenceChar=options.fence.charAt(0);var fenceSize=3;var fenceInCodeRegex=new RegExp("^"+fenceChar+"{3,}","gm");var match2;while(match2=fenceInCodeRegex.exec(code3)){if(match2[0].length>=fenceSize){fenceSize=match2[0].length+1}}var fence=repeat(fenceChar,fenceSize);return"\n\n"+fence+language+"\n"+code3.replace(/\n$/,"")+"\n"+fence+"\n\n"}};rules.horizontalRule={filter:"hr",replacement:function(content,node,options){return"\n\n"+options.hr+"\n\n"}};rules.inlineLink={filter:function(node,options){return options.linkStyle==="inlined"&&node.nodeName==="A"&&node.getAttribute("href")},replacement:function(content,node){var href=escapeLinkDestination(node.getAttribute("href"));var title=escapeLinkTitle(cleanAttribute(node.getAttribute("title")));var titlePart=title?' "'+title+'"':"";return"["+content+"]("+href+titlePart+")"}};rules.referenceLink={filter:function(node,options){return options.linkStyle==="referenced"&&node.nodeName==="A"&&node.getAttribute("href")},replacement:function(content,node,options){var href=escapeLinkDestination(node.getAttribute("href"));var title=cleanAttribute(node.getAttribute("title"));if(title)title=' "'+escapeLinkTitle(title)+'"';var replacement;var reference;switch(options.linkReferenceStyle){case"collapsed":replacement="["+content+"][]";reference="["+content+"]: "+href+title;break;case"shortcut":replacement="["+content+"]";reference="["+content+"]: "+href+title;break;default:var id2=this.references.length+1;replacement="["+content+"]["+id2+"]";reference="["+id2+"]: "+href+title}this.references.push(reference);return replacement},references:[],append:function(options){var references="";if(this.references.length){references="\n\n"+this.references.join("\n")+"\n\n";this.references=[]}return references}};rules.emphasis={filter:["em","i"],replacement:function(content,node,options){if(!content.trim())return"";return options.emDelimiter+content+options.emDelimiter}};rules.strong={filter:["strong","b"],replacement:function(content,node,options){if(!content.trim())return"";return options.strongDelimiter+content+options.strongDelimiter}};rules.code={filter:function(node){var hasSiblings=node.previousSibling||node.nextSibling;var isCodeBlock=node.parentNode.nodeName==="PRE"&&!hasSiblings;return node.nodeName==="CODE"&&!isCodeBlock},replacement:function(content){if(!content)return"";content=content.replace(/\r?\n|\r/g," ");var extraSpace=/^`|^ .*?[^ ].* $|`$/.test(content)?" ":"";var delimiter2="`";var matches=content.match(/`+/gm)||[];while(matches.indexOf(delimiter2)!==-1)delimiter2=delimiter2+"`";return delimiter2+extraSpace+content+extraSpace+delimiter2}};rules.image={filter:"img",replacement:function(content,node){var alt=escapeMarkdown(cleanAttribute(node.getAttribute("alt")));var src=escapeLinkDestination(node.getAttribute("src")||"");var title=cleanAttribute(node.getAttribute("title"));var titlePart=title?' "'+escapeLinkTitle(title)+'"':"";return src?"!["+alt+"]("+src+titlePart+")":""}};function cleanAttribute(attribute){return attribute?attribute.replace(/(\n+\s*)+/g,"\n"):""}function escapeLinkDestination(destination){var escaped=destination.replace(/([<>()])/g,"\\$1");return escaped.indexOf(" ")>=0?"<"+escaped+">":escaped}function escapeLinkTitle(title){return title.replace(/"/g,'\\"')}function Rules(options){this.options=options;this._keep=[];this._remove=[];this.blankRule={replacement:options.blankReplacement};this.keepReplacement=options.keepReplacement;this.defaultRule={replacement:options.defaultReplacement};this.array=[];for(var key in options.rules)this.array.push(options.rules[key])}Rules.prototype={add:function(key,rule){this.array.unshift(rule)},keep:function(filter2){this._keep.unshift({filter:filter2,replacement:this.keepReplacement})},remove:function(filter2){this._remove.unshift({filter:filter2,replacement:function(){return""}})},forNode:function(node){if(node.isBlank)return this.blankRule;var rule;if(rule=findRule(this.array,node,this.options))return rule;if(rule=findRule(this._keep,node,this.options))return rule;if(rule=findRule(this._remove,node,this.options))return rule;return this.defaultRule},forEach:function(fn2){for(var i10=0;i10<this.array.length;i10++)fn2(this.array[i10],i10)}};function findRule(rules2,node,options){for(var i10=0;i10<rules2.length;i10++){var rule=rules2[i10];if(filterValue(rule,node,options))return rule}return void 0}function filterValue(rule,node,options){var filter2=rule.filter;if(typeof filter2==="string"){if(filter2===node.nodeName.toLowerCase())return true}else if(Array.isArray(filter2)){if(filter2.indexOf(node.nodeName.toLowerCase())>-1)return true}else if(typeof filter2==="function"){if(filter2.call(rule,node,options))return true}else{throw new TypeError("`filter` needs to be a string, array, or function")}}function collapseWhitespace(options){var element=options.element;var isBlock2=options.isBlock;var isVoid2=options.isVoid;var isPre=options.isPre||function(node2){return node2.nodeName==="PRE"};if(!element.firstChild||isPre(element))return;var prevText=null;var keepLeadingWs=false;var prev=null;var node=next(prev,element,isPre);while(node!==element){if(node.nodeType===3||node.nodeType===4){var text=node.data.replace(/[ \r\n\t]+/g," ");if((!prevText||/ $/.test(prevText.data))&&!keepLeadingWs&&text[0]===" "){text=text.substr(1)}if(!text){node=remove(node);continue}node.data=text;prevText=node}else if(node.nodeType===1){if(isBlock2(node)||node.nodeName==="BR"){if(prevText){prevText.data=prevText.data.replace(/ $/,"")}prevText=null;keepLeadingWs=false}else if(isVoid2(node)||isPre(node)){prevText=null;keepLeadingWs=true}else if(prevText){keepLeadingWs=false}}else{node=remove(node);continue}var nextNode=next(prev,node,isPre);prev=node;node=nextNode}if(prevText){prevText.data=prevText.data.replace(/ $/,"");if(!prevText.data){remove(prevText)}}}function remove(node){var next2=node.nextSibling||node.parentNode;node.parentNode.removeChild(node);return next2}function next(prev,current3,isPre){if(prev&&prev.parentNode===current3||isPre(current3)){return current3.nextSibling||current3.parentNode}return current3.firstChild||current3.nextSibling||current3.parentNode}var root=typeof window!=="undefined"?window:{};function canParseHTMLNatively(){var Parser3=root.DOMParser;var canParse=false;try{if(new Parser3().parseFromString("","text/html")){canParse=true}}catch(e2){}return canParse}function createHTMLParser(){var Parser3=function(){};{if(shouldUseActiveX()){Parser3.prototype.parseFromString=function(string){var doc=new window.ActiveXObject("htmlfile");doc.designMode="on";doc.open();doc.write(string);doc.close();return doc}}else{Parser3.prototype.parseFromString=function(string){var doc=document.implementation.createHTMLDocument("");doc.open();doc.write(string);doc.close();return doc}}}return Parser3}function shouldUseActiveX(){var useActiveX=false;try{document.implementation.createHTMLDocument("").open()}catch(e2){if(root.ActiveXObject)useActiveX=true}return useActiveX}var HTMLParser=canParseHTMLNatively()?root.DOMParser:createHTMLParser();function RootNode(input,options){var root2;if(typeof input==="string"){var doc=htmlParser().parseFromString('<x-turndown id="turndown-root">'+input+"</x-turndown>","text/html");root2=doc.getElementById("turndown-root")}else{root2=input.cloneNode(true)}collapseWhitespace({element:root2,isBlock,isVoid,isPre:options.preformattedCode?isPreOrCode:null});return root2}var _htmlParser;function htmlParser(){_htmlParser=_htmlParser||new HTMLParser;return _htmlParser}function isPreOrCode(node){return node.nodeName==="PRE"||node.nodeName==="CODE"}function Node(node,options){node.isBlock=isBlock(node);node.isCode=node.nodeName==="CODE"||node.parentNode.isCode;node.isBlank=isBlank(node);node.flankingWhitespace=flankingWhitespace(node,options);return node}function isBlank(node){return!isVoid(node)&&!isMeaningfulWhenBlank(node)&&/^\s*$/i.test(node.textContent)&&!hasVoid(node)&&!hasMeaningfulWhenBlank(node)}function flankingWhitespace(node,options){if(node.isBlock||options.preformattedCode&&node.isCode){return{leading:"",trailing:""}}var edges=edgeWhitespace(node.textContent);if(edges.leadingAscii&&isFlankedByWhitespace("left",node,options)){edges.leading=edges.leadingNonAscii}if(edges.trailingAscii&&isFlankedByWhitespace("right",node,options)){edges.trailing=edges.trailingNonAscii}return{leading:edges.leading,trailing:edges.trailing}}function edgeWhitespace(string){var m=string.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/);return{leading:m[1],leadingAscii:m[2],leadingNonAscii:m[3],trailing:m[4],trailingNonAscii:m[5],trailingAscii:m[6]}}function isFlankedByWhitespace(side,node,options){var sibling2;var regExp;var isFlanked;if(side==="left"){sibling2=node.previousSibling;regExp=/ $/}else{sibling2=node.nextSibling;regExp=/^ /}if(sibling2){if(sibling2.nodeType===3){isFlanked=regExp.test(sibling2.nodeValue)}else if(options.preformattedCode&&sibling2.nodeName==="CODE"){isFlanked=false}else if(sibling2.nodeType===1&&!isBlock(sibling2)){isFlanked=regExp.test(sibling2.textContent)}}return isFlanked}var reduce=Array.prototype.reduce;function TurndownService(options){if(!(this instanceof TurndownService))return new TurndownService(options);var defaults2={rules,headingStyle:"setext",hr:"* * *",bulletListMarker:"*",codeBlockStyle:"indented",fence:"```",emDelimiter:"_",strongDelimiter:"**",linkStyle:"inlined",linkReferenceStyle:"full",br:" ",preformattedCode:false,blankReplacement:function(content,node){return node.isBlock?"\n\n":""},keepReplacement:function(content,node){return node.isBlock?"\n\n"+node.outerHTML+"\n\n":node.outerHTML},defaultReplacement:function(content,node){return node.isBlock?"\n\n"+content+"\n\n":content}};this.options=extend({},defaults2,options);this.rules=new Rules(this.options)}TurndownService.prototype={turndown:function(input){if(!canConvert(input)){throw new TypeError(input+" is not a string, or an element/document/fragment node.")}if(input==="")return"";var output=process2.call(this,new RootNode(input,this.options));return postProcess.call(this,output)},use:function(plugin){if(Array.isArray(plugin)){for(var i10=0;i10<plugin.length;i10++)this.use(plugin[i10])}else if(typeof plugin==="function"){plugin(this)}else{throw new TypeError("plugin must be a Function or an Array of Functions")}return this},addRule:function(key,rule){this.rules.add(key,rule);return this},keep:function(filter2){this.rules.keep(filter2);return this},remove:function(filter2){this.rules.remove(filter2);return this},escape:function(string){return escapeMarkdown(string)}};function process2(parentNode){var self2=this;return reduce.call(parentNode.childNodes,function(output,node){node=new Node(node,self2.options);var replacement="";if(node.nodeType===3){replacement=node.isCode?node.nodeValue:self2.escape(node.nodeValue)}else if(node.nodeType===1){replacement=replacementForNode.call(self2,node)}return join(output,replacement)},"")}function postProcess(output){var self2=this;this.rules.forEach(function(rule){if(typeof rule.append==="function"){output=join(output,rule.append(self2.options))}});return output.replace(/^[\t\r\n]+/,"").replace(/[\t\r\n\s]+$/,"")}function replacementForNode(node){var rule=this.rules.forNode(node);var content=process2.call(this,node);var whitespace=node.flankingWhitespace;if(whitespace.leading||whitespace.trailing)content=content.trim();return whitespace.leading+rule.replacement(content,node,this.options)+whitespace.trailing}function join(output,replacement){var s12=trimTrailingNewlines(output);var s22=trimLeadingNewlines(replacement);var nls=Math.max(output.length-s12.length,replacement.length-s22.length);var separator="\n\n".substring(0,nls);return s12+separator+s22}function canConvert(input){return input!=null&&(typeof input==="string"||input.nodeType&&(input.nodeType===1||input.nodeType===9||input.nodeType===11))}var P7=Object.create;var Ua=Object.defineProperty;var D7=Object.getOwnPropertyDescriptor;var _7=Object.getOwnPropertyNames;var F7=Object.getPrototypeOf;var L7=Object.prototype.hasOwnProperty;var qn=(e2=>typeof __require<"u"?__require:typeof Proxy<"u"?new Proxy(e2,{get:(t10,n8)=>(typeof __require<"u"?__require:t10)[n8]}):e2)(function(e2){if(typeof __require<"u")return __require.apply(this,arguments);throw Error('Dynamic require of "'+e2+'" is not supported')});var v=(e2,t10)=>()=>(e2&&(t10=e2(e2=0)),t10);var Oi=(e2,t10)=>()=>(t10||e2((t10={exports:{}}).exports,t10),t10.exports);var ee=(e2,t10)=>{for(var n8 in t10)Ua(e2,n8,{get:t10[n8],enumerable:true})};var M7=(e2,t10,n8,r10)=>{if(t10&&typeof t10=="object"||typeof t10=="function")for(let s10 of _7(t10))!L7.call(e2,s10)&&s10!==n8&&Ua(e2,s10,{get:()=>t10[s10],enumerable:!(r10=D7(t10,s10))||r10.enumerable});return e2};var kf=(e2,t10,n8)=>(n8=e2!=null?P7(F7(e2)):{},M7(t10||!e2||!e2.__esModule?Ua(n8,"default",{value:e2,enumerable:true}):n8,e2));function Nf(){let e2=[{prop:"Function",target:globalThis,violationType:"function_constructor",strategy:"throw",reason:"Function constructor allows arbitrary code execution"},{prop:"eval",target:globalThis,violationType:"eval",strategy:"throw",reason:"eval() allows arbitrary code execution"},{prop:"setTimeout",target:globalThis,violationType:"setTimeout",strategy:"throw",reason:"setTimeout with string argument allows code execution"},{prop:"setInterval",target:globalThis,violationType:"setInterval",strategy:"throw",reason:"setInterval with string argument allows code execution"},{prop:"setImmediate",target:globalThis,violationType:"setImmediate",strategy:"throw",reason:"setImmediate could be used to escape sandbox context"},{prop:"env",target:process,violationType:"process_env",strategy:"throw",reason:"process.env could leak sensitive environment variables",allowedKeys:new Set(["NODE_V8_COVERAGE","NODE_DEBUG","NODE_DEBUG_NATIVE","NODE_COMPILE_CACHE","WATCH_REPORT_DEPENDENCIES","FORCE_COLOR","DEBUG","UNDICI_NO_FG","JEST_WORKER_ID","__MINIMATCH_TESTING_PLATFORM__","LOG_TOKENS","LOG_STREAM"])},{prop:"binding",target:process,violationType:"process_binding",strategy:"throw",reason:"process.binding provides access to native Node.js modules"},{prop:"_linkedBinding",target:process,violationType:"process_binding",strategy:"throw",reason:"process._linkedBinding provides access to native Node.js modules"},{prop:"dlopen",target:process,violationType:"process_dlopen",strategy:"throw",reason:"process.dlopen allows loading native addons"},{prop:"getBuiltinModule",target:process,violationType:"process_get_builtin_module",strategy:"throw",reason:"process.getBuiltinModule allows loading native Node.js modules (fs, child_process, vm)"},{prop:"exit",target:process,violationType:"process_exit",strategy:"throw",reason:"process.exit could terminate the interpreter"},{prop:"abort",target:process,violationType:"process_exit",strategy:"throw",reason:"process.abort could crash the interpreter"},{prop:"kill",target:process,violationType:"process_kill",strategy:"throw",reason:"process.kill could signal other processes"},{prop:"setuid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setuid could escalate privileges"},{prop:"setgid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setgid could escalate privileges"},{prop:"seteuid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.seteuid could escalate effective user privileges"},{prop:"setegid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setegid could escalate effective group privileges"},{prop:"initgroups",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.initgroups could modify supplementary group IDs"},{prop:"setgroups",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setgroups could modify supplementary group IDs"},{prop:"umask",target:process,violationType:"process_umask",strategy:"throw",reason:"process.umask could modify file creation permissions"},{prop:"argv",target:process,violationType:"process_argv",strategy:"throw",reason:"process.argv may contain secrets in CLI arguments"},{prop:"cwd",target:process,violationType:"process_chdir",strategy:"throw",reason:"process.cwd could disclose real host working directory path"},{prop:"chdir",target:process,violationType:"process_chdir",strategy:"throw",reason:"process.chdir could confuse the interpreter's CWD tracking"},{prop:"report",target:process,violationType:"process_report",strategy:"throw",reason:"process.report could disclose full environment, host paths, and system info"},{prop:"loadEnvFile",target:process,violationType:"process_env",strategy:"throw",reason:"process.loadEnvFile could load env files bypassing env proxy"},{prop:"setUncaughtExceptionCaptureCallback",target:process,violationType:"process_exception_handler",strategy:"throw",reason:"setUncaughtExceptionCaptureCallback could intercept security errors"},{prop:"send",target:process,violationType:"process_send",strategy:"throw",reason:"process.send could communicate with parent process in IPC contexts"},{prop:"channel",target:process,violationType:"process_channel",strategy:"throw",reason:"process.channel could access IPC channel to parent process"},{prop:"cpuUsage",target:process,violationType:"process_timing",strategy:"throw",reason:"process.cpuUsage could enable timing side-channel attacks"},{prop:"memoryUsage",target:process,violationType:"process_timing",strategy:"throw",reason:"process.memoryUsage could enable timing side-channel attacks"},{prop:"hrtime",target:process,violationType:"process_timing",strategy:"throw",reason:"process.hrtime could enable timing side-channel attacks"},{prop:"WeakRef",target:globalThis,violationType:"weak_ref",strategy:"throw",reason:"WeakRef could be used to leak references outside sandbox"},{prop:"FinalizationRegistry",target:globalThis,violationType:"finalization_registry",strategy:"throw",reason:"FinalizationRegistry could be used to leak references outside sandbox"},{prop:"Reflect",target:globalThis,violationType:"reflect",strategy:"freeze",reason:"Reflect provides introspection capabilities"},{prop:"Proxy",target:globalThis,violationType:"proxy",strategy:"throw",reason:"Proxy allows intercepting and modifying object behavior"},{prop:"WebAssembly",target:globalThis,violationType:"webassembly",strategy:"throw",reason:"WebAssembly allows executing arbitrary compiled code"},{prop:"SharedArrayBuffer",target:globalThis,violationType:"shared_array_buffer",strategy:"throw",reason:"SharedArrayBuffer could enable side-channel communication or timing attacks"},{prop:"Atomics",target:globalThis,violationType:"atomics",strategy:"throw",reason:"Atomics could enable side-channel communication or timing attacks"},{prop:"performance",target:globalThis,violationType:"performance_timing",strategy:"throw",reason:"performance.now() provides sub-millisecond timing for side-channel attacks"},{prop:"stdout",target:process,violationType:"process_stdout",strategy:"throw",reason:"process.stdout could bypass interpreter output to write to host stdout"},{prop:"stderr",target:process,violationType:"process_stderr",strategy:"throw",reason:"process.stderr could bypass interpreter output to write to host stderr"},{prop:"__defineGetter__",target:Object.prototype,violationType:"prototype_mutation",strategy:"throw",reason:"__defineGetter__ allows prototype pollution via getter injection"},{prop:"__defineSetter__",target:Object.prototype,violationType:"prototype_mutation",strategy:"throw",reason:"__defineSetter__ allows prototype pollution via setter injection"},{prop:"__lookupGetter__",target:Object.prototype,violationType:"prototype_mutation",strategy:"throw",reason:"__lookupGetter__ enables introspection for prototype pollution attacks"},{prop:"__lookupSetter__",target:Object.prototype,violationType:"prototype_mutation",strategy:"throw",reason:"__lookupSetter__ enables introspection for prototype pollution attacks"},{prop:"JSON",target:globalThis,violationType:"json_mutation",strategy:"freeze",reason:"Freeze JSON to prevent mutation of parsing/serialization"},{prop:"Math",target:globalThis,violationType:"math_mutation",strategy:"freeze",reason:"Freeze Math to prevent mutation of math utilities"}];try{let t10=Object.getPrototypeOf(async()=>{}).constructor;t10&&t10!==Function&&e2.push({prop:"constructor",target:Object.getPrototypeOf(async()=>{}),violationType:"async_function_constructor",strategy:"throw",reason:"AsyncFunction constructor allows arbitrary async code execution"})}catch{}try{let t10=Object.getPrototypeOf(function*(){}).constructor;t10&&t10!==Function&&e2.push({prop:"constructor",target:Object.getPrototypeOf(function*(){}),violationType:"generator_function_constructor",strategy:"throw",reason:"GeneratorFunction constructor allows arbitrary generator code execution"})}catch{}try{let t10=Object.getPrototypeOf(async function*(){}).constructor;t10&&t10!==Function&&t10!==Object.getPrototypeOf(async()=>{}).constructor&&e2.push({prop:"constructor",target:Object.getPrototypeOf(async function*(){}),violationType:"async_generator_function_constructor",strategy:"throw",reason:"AsyncGeneratorFunction constructor allows arbitrary async generator code execution"})}catch{}return e2.filter(t10=>{try{return t10.target[t10.prop]!==void 0}catch{return false}})}var If=v(()=>{"use strict"});function $f(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e2=>{let t10=Math.random()*16|0;return(e2==="x"?t10:t10&3|8).toString(16)})}function W7(e2,t10,...n8){return Le.run(e2,()=>t10(...n8))}function z7(e2){return e2===void 0?{...Ba,enabled:false}:typeof e2=="boolean"?{...Ba,enabled:e2}:{...Ba,...e2}}var rr;var Wa;var U7;var he;var Le;var B7;var Ba;var wt;var an=v(()=>{"use strict";If();rr=true;Wa=null;if(!rr)try{let{AsyncLocalStorage:e2}=qn("node:async_hooks");Wa=e2}catch{}U7=`
1
+ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __commonJS=(cb2,mod)=>function __require2(){try{return mod||(0,cb2[__getOwnPropNames(cb2)[0]])((mod={exports:{}}).exports,mod),mod.exports}catch(e2){throw mod=0,e2}};var __copyProps=(to2,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to2,key)&&key!==except)__defProp(to2,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to2};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_sprintf=__commonJS({"../../node_modules/sprintf-js/src/sprintf.js"(exports){!(function(){"use strict";var re2={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function sprintf(key){return sprintf_format(sprintf_parse(key),arguments)}function vsprintf(fmt,argv){return sprintf.apply(null,[fmt].concat(argv||[]))}function sprintf_format(parse_tree,argv){var cursor=1,tree_length=parse_tree.length,arg,output="",i10,k10,ph2,pad,pad_character,pad_length,is_positive,sign3;for(i10=0;i10<tree_length;i10++){if(typeof parse_tree[i10]==="string"){output+=parse_tree[i10]}else if(typeof parse_tree[i10]==="object"){ph2=parse_tree[i10];if(ph2.keys){arg=argv[cursor];for(k10=0;k10<ph2.keys.length;k10++){if(arg==void 0){throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"',ph2.keys[k10],ph2.keys[k10-1]))}arg=arg[ph2.keys[k10]]}}else if(ph2.param_no){arg=argv[ph2.param_no]}else{arg=argv[cursor++]}if(re2.not_type.test(ph2.type)&&re2.not_primitive.test(ph2.type)&&arg instanceof Function){arg=arg()}if(re2.numeric_arg.test(ph2.type)&&(typeof arg!=="number"&&isNaN(arg))){throw new TypeError(sprintf("[sprintf] expecting number but found %T",arg))}if(re2.number.test(ph2.type)){is_positive=arg>=0}switch(ph2.type){case"b":arg=parseInt(arg,10).toString(2);break;case"c":arg=String.fromCharCode(parseInt(arg,10));break;case"d":case"i":arg=parseInt(arg,10);break;case"j":arg=JSON.stringify(arg,null,ph2.width?parseInt(ph2.width):0);break;case"e":arg=ph2.precision?parseFloat(arg).toExponential(ph2.precision):parseFloat(arg).toExponential();break;case"f":arg=ph2.precision?parseFloat(arg).toFixed(ph2.precision):parseFloat(arg);break;case"g":arg=ph2.precision?String(Number(arg.toPrecision(ph2.precision))):parseFloat(arg);break;case"o":arg=(parseInt(arg,10)>>>0).toString(8);break;case"s":arg=String(arg);arg=ph2.precision?arg.substring(0,ph2.precision):arg;break;case"t":arg=String(!!arg);arg=ph2.precision?arg.substring(0,ph2.precision):arg;break;case"T":arg=Object.prototype.toString.call(arg).slice(8,-1).toLowerCase();arg=ph2.precision?arg.substring(0,ph2.precision):arg;break;case"u":arg=parseInt(arg,10)>>>0;break;case"v":arg=arg.valueOf();arg=ph2.precision?arg.substring(0,ph2.precision):arg;break;case"x":arg=(parseInt(arg,10)>>>0).toString(16);break;case"X":arg=(parseInt(arg,10)>>>0).toString(16).toUpperCase();break}if(re2.json.test(ph2.type)){output+=arg}else{if(re2.number.test(ph2.type)&&(!is_positive||ph2.sign)){sign3=is_positive?"+":"-";arg=arg.toString().replace(re2.sign,"")}else{sign3=""}pad_character=ph2.pad_char?ph2.pad_char==="0"?"0":ph2.pad_char.charAt(1):" ";pad_length=ph2.width-(sign3+arg).length;pad=ph2.width?pad_length>0?pad_character.repeat(pad_length):"":"";output+=ph2.align?sign3+arg+pad:pad_character==="0"?sign3+pad+arg:pad+sign3+arg}}}return output}var sprintf_cache=Object.create(null);function sprintf_parse(fmt){if(sprintf_cache[fmt]){return sprintf_cache[fmt]}var _fmt=fmt,match2,parse_tree=[],arg_names=0;while(_fmt){if((match2=re2.text.exec(_fmt))!==null){parse_tree.push(match2[0])}else if((match2=re2.modulo.exec(_fmt))!==null){parse_tree.push("%")}else if((match2=re2.placeholder.exec(_fmt))!==null){if(match2[2]){arg_names|=1;var field_list=[],replacement_field=match2[2],field_match=[];if((field_match=re2.key.exec(replacement_field))!==null){field_list.push(field_match[1]);while((replacement_field=replacement_field.substring(field_match[0].length))!==""){if((field_match=re2.key_access.exec(replacement_field))!==null){field_list.push(field_match[1])}else if((field_match=re2.index_access.exec(replacement_field))!==null){field_list.push(field_match[1])}else{throw new SyntaxError("[sprintf] failed to parse named argument key")}}}else{throw new SyntaxError("[sprintf] failed to parse named argument key")}match2[2]=field_list}else{arg_names|=2}if(arg_names===3){throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported")}parse_tree.push({placeholder:match2[0],param_no:match2[1],keys:match2[2],sign:match2[3],pad_char:match2[4],align:match2[5],width:match2[6],precision:match2[7],type:match2[8]})}else{throw new SyntaxError("[sprintf] unexpected placeholder")}_fmt=_fmt.substring(match2[0].length)}return sprintf_cache[fmt]=parse_tree}if(typeof exports!=="undefined"){exports["sprintf"]=sprintf;exports["vsprintf"]=vsprintf}if(typeof window!=="undefined"){window["sprintf"]=sprintf;window["vsprintf"]=vsprintf;if(typeof define==="function"&&define["amd"]){define(function(){return{"sprintf":sprintf,"vsprintf":vsprintf}})}}})()}});var BROWSER_RUNTIME_CAPABILITIES=["browser.open-url","filesystem.atomic-file-replace","filesystem.private-storage","filesystem.project","media.webcodecs","network.loopback-http","network.raw-tls-relay","process.background-jobs","process.pty","process.spawn","threads.pthread"];var BROWSER_RUNTIME_PROFILE=Object.freeze({version:1,capabilities:BROWSER_RUNTIME_CAPABILITIES});var BrowserPackContractError=class extends Error{category;path;constructor(category,path3,message){super(`${path3}: ${message}`);this.name="BrowserPackContractError";this.category=category;this.path=path3}};var BROWSER_PACK_PART_MAX_BYTES=128*1024*1024;function canonicalBrowserPackJson(value){return JSON.stringify(canonical(value,"$"))}function canonical(value,path3){if(value===null||typeof value==="string"||typeof value==="boolean")return value;if(typeof value==="number"){if(!Number.isFinite(value))fail("invalid-manifest",path3,"contains a non-finite number");return value}if(Array.isArray(value))return value.map((item,index2)=>canonical(item,`${path3}[${index2}]`));if(typeof value!=="object")fail("invalid-manifest",path3,"contains an unsupported value");if(Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null)fail("invalid-manifest",path3,"must contain only plain JSON objects");const result={};for(const key of Object.keys(value).sort())result[key]=canonical(value[key],`${path3}.${key}`);return result}function fail(category,path3,message){throw new BrowserPackContractError(category,path3,message)}var BrowserPackArchiveError=class extends Error{constructor(category,message){super(message);this.category=category;this.name="BrowserPackArchiveError"}category};var TAR_BLOCK=512;var MAX_PATH_BYTES=4096;var decoder=new TextDecoder("utf-8",{fatal:true});async function extractBrowserPackArchive(bytes2,artifact,signal){if(!artifact.archive||artifact.expandedBytes===void 0||artifact.files===void 0){throw new BrowserPackArchiveError("invalid-archive","Archive bounds are missing from the pack manifest.")}cancelled(signal);let entries;if(artifact.archive==="zip")entries=await extractZip(bytes2,artifact.expandedBytes,artifact.files,signal);else{const tar=artifact.archive==="tar+gzip"?await decompress(bytes2,"gzip",tarStreamLimit(artifact.expandedBytes,artifact.files),signal):bytes2;entries=extractTar(tar,artifact.expandedBytes,artifact.files,signal)}validateTree(entries,artifact.files,artifact.expandedBytes);return entries}function extractTar(bytes2,expandedLimit,fileLimit,signal){const entries=[];const hardlinks=[];let offset2=0;let zeroBlocks=0;let longPath;let longLink;let paxPath;let paxLink;let fileBytes=0;while(offset2+TAR_BLOCK<=bytes2.byteLength){cancelled(signal);const header=bytes2.subarray(offset2,offset2+TAR_BLOCK);offset2+=TAR_BLOCK;if(header.every(byte=>byte===0)){zeroBlocks+=1;if(zeroBlocks===2)break;continue}if(zeroBlocks!==0)fail2("invalid-archive","A tar entry follows its end marker.");verifyTarChecksum(header);const size=tarNumber(header,124,12,"size");const padded=Math.ceil(size/TAR_BLOCK)*TAR_BLOCK;if(!Number.isSafeInteger(size)||offset2+padded>bytes2.byteLength)fail2("invalid-archive","A tar entry is truncated.");const data2=bytes2.subarray(offset2,offset2+size);offset2+=padded;const type2=String.fromCharCode(header[156]||48);const rawName=tarText(header,0,100);const prefix2=tarText(header,257,6).startsWith("ustar")?tarText(header,345,155):"";const headerPath=prefix2?`${prefix2}/${rawName}`:rawName;if(type2==="L"||type2==="K"){const value=decodeNullTerminated(data2);if(type2==="L")longPath=value;else longLink=value;continue}if(type2==="x"){const pax=parsePax(data2);paxPath=pax.path;paxLink=pax.linkpath;continue}if(type2==="g")fail2("unsupported-entry","Global PAX attributes are not supported in pack archives.");const effectivePath=paxPath??longPath??headerPath;const directory2=type2==="5"||effectivePath.endsWith("/");const path3=safePath(directory2?effectivePath.replace(/\/+$/u,""):effectivePath);const link2=paxLink??longLink??tarText(header,157,100);longPath=longLink=paxPath=paxLink=void 0;const mode=safeMode(tarNumber(header,100,8,"mode"),type2==="5"?493:420);if(directory2){if(size!==0)fail2("invalid-archive",`Directory ${path3} contains data.`);entries.push({path:path3,type:"directory",mode})}else if(type2==="0"||type2==="\0"||type2==="7"){fileBytes+=size;if(fileBytes>expandedLimit)fail2("expansion-limit",`Archive expands beyond ${expandedLimit} declared bytes.`);entries.push({path:path3,type:"file",mode,content:data2.slice()})}else if(type2==="2"){entries.push({path:path3,type:"symlink",mode,target:safeSymlink(path3,link2)})}else if(type2==="1"){hardlinks.push({path:path3,mode,target:safePath(link2)})}else fail2("unsupported-entry",`Tar entry ${path3} has unsupported type ${JSON.stringify(type2)}.`);if(entries.length+hardlinks.length>entryLimit(fileLimit))fail2("expansion-limit","Archive contains too many directory or file entries for its declared file count.")}if(zeroBlocks<2||offset2!==bytes2.byteLength&&bytes2.subarray(offset2).some(byte=>byte!==0)){fail2("invalid-archive","Tar archive has no complete end marker or has trailing data.")}if(longPath!==void 0||longLink!==void 0||paxPath!==void 0||paxLink!==void 0)fail2("invalid-archive","Tar archive ends after orphaned metadata.");for(const link2 of hardlinks){const target=entries.find(entry=>entry.path===link2.target&&entry.type==="file");if(!target)fail2("unsupported-entry",`Hard link ${link2.path} does not name a regular file inside the archive.`);fileBytes+=target.content.byteLength;if(fileBytes>expandedLimit)fail2("expansion-limit",`Archive expands beyond ${expandedLimit} declared bytes.`);entries.push({path:link2.path,type:"file",mode:link2.mode,content:target.content.slice()})}return entries}async function extractZip(bytes2,expandedLimit,fileLimit,signal){const end=findZipEnd(bytes2);const view=new DataView(bytes2.buffer,bytes2.byteOffset,bytes2.byteLength);if(view.getUint16(end+4,true)!==0||view.getUint16(end+6,true)!==0)fail2("unsupported-entry","Multi-disk ZIP archives are not supported.");const count=view.getUint16(end+10,true);const centralSize=view.getUint32(end+12,true);const centralOffset=view.getUint32(end+16,true);const comment=view.getUint16(end+20,true);if(view.getUint16(end+8,true)!==count||end+22+comment!==bytes2.byteLength||centralOffset+centralSize!==end)fail2("invalid-archive","ZIP central directory is invalid.");if(count>entryLimit(fileLimit))fail2("expansion-limit","ZIP contains too many directory or file entries for its declared file count.");const entries=[];const ranges=[];let cursor=centralOffset;let fileBytes=0;for(let index2=0;index2<count;index2+=1){cancelled(signal);requireRange(bytes2,cursor,46);if(view.getUint32(cursor,true)!==33639248)fail2("invalid-archive","ZIP central directory entry is invalid.");const madeBy=view.getUint16(cursor+4,true)>>>8;const flags=view.getUint16(cursor+8,true);const method=view.getUint16(cursor+10,true);const crc=view.getUint32(cursor+16,true);const compressed=view.getUint32(cursor+20,true);const size=view.getUint32(cursor+24,true);const nameLength=view.getUint16(cursor+28,true);const extraLength=view.getUint16(cursor+30,true);const commentLength=view.getUint16(cursor+32,true);const external=view.getUint32(cursor+38,true);const localOffset=view.getUint32(cursor+42,true);requireRange(bytes2,cursor+46,nameLength+extraLength+commentLength);const name=decodeName(bytes2.subarray(cursor+46,cursor+46+nameLength),flags);cursor+=46+nameLength+extraLength+commentLength;if((flags&~2048)!==0||method!==0&&method!==8)fail2("unsupported-entry",`ZIP entry ${name} uses unsupported features.`);if(localOffset>=centralOffset)fail2("invalid-archive",`ZIP entry ${name} overlaps its directory.`);requireRange(bytes2,localOffset,30);if(view.getUint32(localOffset,true)!==67324752)fail2("invalid-archive",`ZIP entry ${name} has an invalid local header.`);const localFlags=view.getUint16(localOffset+6,true);const localMethod=view.getUint16(localOffset+8,true);const localNameLength=view.getUint16(localOffset+26,true);const localExtraLength=view.getUint16(localOffset+28,true);requireRange(bytes2,localOffset+30,localNameLength+localExtraLength);const localName=decodeName(bytes2.subarray(localOffset+30,localOffset+30+localNameLength),localFlags);const dataOffset=localOffset+30+localNameLength+localExtraLength;if(localName!==name||localFlags!==flags||localMethod!==method||dataOffset+compressed>centralOffset)fail2("invalid-archive",`ZIP local and central records disagree for ${name}.`);if(view.getUint32(localOffset+14,true)!==crc||view.getUint32(localOffset+18,true)!==compressed||view.getUint32(localOffset+22,true)!==size)fail2("invalid-archive",`ZIP local sizes disagree for ${name}.`);const rangeEnd=dataOffset+compressed;if(ranges.some(([start,finish])=>localOffset<finish&&rangeEnd>start))fail2("invalid-archive",`ZIP entry ${name} overlaps another entry.`);ranges.push([localOffset,rangeEnd]);const packed=bytes2.subarray(dataOffset,rangeEnd);const directory2=name.endsWith("/");const unixType=madeBy===3?external>>>16&61440:0;if(directory2&&size!==0)fail2("invalid-archive",`ZIP directory ${name} contains data.`);if(unixType===40960&&size>MAX_PATH_BYTES)fail2("expansion-limit",`ZIP link ${name} exceeds the link target bound.`);if(!directory2&&unixType!==40960&&size>expandedLimit-fileBytes)fail2("expansion-limit",`Archive expands beyond ${expandedLimit} declared bytes.`);const data2=method===0?packed.slice():await decompress(packed,"deflate-raw",size,signal);if(data2.byteLength!==size||crc32(data2)!==crc)fail2("invalid-archive",`ZIP entry ${name} is corrupt.`);const path3=safePath(directory2?name.slice(0,-1):name);const mode=safeMode(madeBy===3?external>>>16&4095:0,directory2?493:420);if(directory2){if(size!==0||unixType!==0&&unixType!==16384)fail2("invalid-archive",`ZIP directory ${name} is invalid.`);entries.push({path:path3,type:"directory",mode})}else if(unixType===40960){entries.push({path:path3,type:"symlink",mode,target:safeSymlink(path3,decodeNullFree(data2))})}else{if(unixType!==0&&unixType!==32768)fail2("unsupported-entry",`ZIP entry ${name} is not a regular file.`);fileBytes+=data2.byteLength;if(fileBytes>expandedLimit)fail2("expansion-limit",`Archive expands beyond ${expandedLimit} declared bytes.`);entries.push({path:path3,type:"file",mode,content:data2})}}if(cursor!==end)fail2("invalid-archive","ZIP central directory length is invalid.");return entries}function validateTree(entries,expectedFiles,expectedBytes){const paths=new Map;let files=0;let bytes2=0;for(const entry of entries){if(paths.has(entry.path))fail2("invalid-archive",`Archive contains duplicate path ${entry.path}.`);paths.set(entry.path,entry);if(entry.type!=="directory")files+=1;if(entry.type==="file")bytes2+=entry.content.byteLength}for(const entry of entries){const parts=entry.path.split("/");for(let index2=1;index2<parts.length;index2+=1){const parent=paths.get(parts.slice(0,index2).join("/"));if(parent&&parent.type!=="directory")fail2("invalid-archive",`Archive path ${entry.path} descends through a non-directory.`)}}if(files!==expectedFiles)fail2("expansion-limit",`Archive contains ${files} files; manifest declares ${expectedFiles}.`);if(bytes2!==expectedBytes)fail2("expansion-limit",`Archive expands to ${bytes2} bytes; manifest declares ${expectedBytes}.`)}function safePath(value){if(value.length===0||value.startsWith("/")||value.includes("\\")||value.includes("\0"))fail2("unsafe-path",`Archive path ${JSON.stringify(value)} is unsafe.`);let encoded;try{encoded=new TextEncoder().encode(value)}catch{fail2("unsafe-path","Archive path is not valid text.")}const parts=value.split("/");if(encoded.byteLength>MAX_PATH_BYTES||parts.some(part=>part===""||part==="."||part===".."))fail2("unsafe-path",`Archive path ${JSON.stringify(value)} is unsafe.`);return value}function safeSymlink(path3,target){if(target.length===0||target.startsWith("/")||target.includes("\\")||target.includes("\0"))fail2("unsafe-path",`Link ${path3} has unsafe target ${JSON.stringify(target)}.`);const resolved=path3.split("/").slice(0,-1);for(const part of target.split("/")){if(part===""||part===".")continue;if(part===".."){if(resolved.length===0)fail2("unsafe-path",`Link ${path3} escapes the archive root.`);resolved.pop()}else resolved.push(part)}if(resolved.length===0)fail2("unsafe-path",`Link ${path3} resolves to the archive root.`);return target}function safeMode(value,fallback){return value&511||fallback}function verifyTarChecksum(header){const expected=tarNumber(header,148,8,"checksum");let sum=0;for(let index2=0;index2<header.byteLength;index2+=1)sum+=index2>=148&&index2<156?32:header[index2];if(sum!==expected)fail2("invalid-archive","Tar header checksum is invalid.")}function tarNumber(bytes2,offset2,length,field){if((bytes2[offset2]&128)!==0)fail2("unsupported-entry",`Tar ${field} uses unsupported base-256 encoding.`);const text=tarText(bytes2,offset2,length).trim();if(text==="")return 0;if(!/^[0-7]+$/u.test(text))fail2("invalid-archive",`Tar ${field} is invalid.`);const value=Number.parseInt(text,8);if(!Number.isSafeInteger(value)||value<0)fail2("invalid-archive",`Tar ${field} is outside the supported range.`);return value}function tarText(bytes2,offset2,length){const value=bytes2.subarray(offset2,offset2+length);const end=value.indexOf(0);try{return decoder.decode(end<0?value:value.subarray(0,end))}catch{fail2("invalid-archive","Tar metadata is not valid UTF-8.")}}function decodeNullTerminated(bytes2){return decodeNullFree(bytes2.subarray(0,bytes2[bytes2.byteLength-1]===0?-1:void 0))}function decodeNullFree(bytes2){try{const value=decoder.decode(bytes2);if(value.includes("\0"))fail2("invalid-archive","Archive metadata contains NUL.");return value}catch(cause){if(cause instanceof BrowserPackArchiveError)throw cause;fail2("invalid-archive","Archive metadata is not valid UTF-8.")}}function parsePax(bytes2){const result={};let cursor=0;while(cursor<bytes2.byteLength){const space=bytes2.indexOf(32,cursor);if(space<0)fail2("invalid-archive","PAX record is malformed.");const lengthText=decodeNullFree(bytes2.subarray(cursor,space));if(!/^[0-9]+$/u.test(lengthText))fail2("invalid-archive","PAX record length is invalid.");const length=Number(lengthText);if(!Number.isSafeInteger(length)||length<=0||cursor+length>bytes2.byteLength||bytes2[cursor+length-1]!==10)fail2("invalid-archive","PAX record length is invalid.");const record=decodeNullFree(bytes2.subarray(space+1,cursor+length-1));const equals=record.indexOf("=");if(equals<1)fail2("invalid-archive","PAX record is malformed.");const key=record.slice(0,equals);const value=record.slice(equals+1);if(key==="path"||key==="linkpath")result[key]=value;cursor+=length}return result}async function decompress(bytes2,format2,limit,signal){if(typeof DecompressionStream!=="function")fail2("unsupported-entry",`This browser cannot decompress ${format2} pack archives.`);const stream=new Blob([Uint8Array.from(bytes2)]).stream().pipeThrough(new DecompressionStream(format2));const reader=stream.getReader();const chunks=[];let length=0;try{for(;;){cancelled(signal);const chunk=await reader.read();if(chunk.done)break;length+=chunk.value.byteLength;if(length>limit)fail2("expansion-limit",`Archive stream exceeds its ${limit} byte expansion bound.`);chunks.push(chunk.value)}}catch(cause){if(cause instanceof BrowserPackArchiveError)throw cause;fail2("invalid-archive",`Archive decompression failed: ${cause instanceof Error?cause.message:String(cause)}`)}finally{await reader.cancel().catch(()=>void 0);reader.releaseLock()}const result=new Uint8Array(length);let offset2=0;for(const chunk of chunks){result.set(chunk,offset2);offset2+=chunk.byteLength}return result}function tarStreamLimit(expandedBytes,files){return expandedBytes+entryLimit(files)*(MAX_PATH_BYTES+TAR_BLOCK*3)+TAR_BLOCK*2}function entryLimit(files){return Math.max(16,files*16+16)}function findZipEnd(bytes2){if(bytes2.byteLength<22)fail2("invalid-archive","ZIP archive is truncated.");const view=new DataView(bytes2.buffer,bytes2.byteOffset,bytes2.byteLength);for(let offset2=bytes2.byteLength-22;offset2>=Math.max(0,bytes2.byteLength-65557);offset2-=1)if(view.getUint32(offset2,true)===101010256)return offset2;fail2("invalid-archive","ZIP end record is missing.")}function requireRange(bytes2,offset2,length){if(!Number.isSafeInteger(offset2)||!Number.isSafeInteger(length)||offset2<0||length<0||offset2+length>bytes2.byteLength)fail2("invalid-archive","ZIP archive is truncated.")}function decodeName(bytes2,flags){if((flags&2048)===0&&bytes2.some(byte=>byte>=128))fail2("unsupported-entry","ZIP entry names must use UTF-8.");return decodeNullFree(bytes2)}function crc32(bytes2){let crc=4294967295;for(const byte of bytes2){crc^=byte;for(let bit=0;bit<8;bit+=1)crc=crc>>>1^(crc&1?3988292384:0)}return(crc^4294967295)>>>0}function cancelled(signal){if(signal?.aborted)fail2("cancellation","Archive expansion was cancelled before staging.")}function fail2(category,message){throw new BrowserPackArchiveError(category,message)}var BrowserPackInstallError=class extends Error{constructor(category,message){super(message);this.category=category;this.name="BrowserPackInstallError"}category};function checkCancelled(signal){if(signal?.aborted)throw new BrowserPackInstallError("cancellation","Installation was cancelled before activation.")}var PackedBrowserPackInstallStore=class{constructor(packages2,headroom,coordinate=work=>work()){this.packages=packages2;this.headroom=headroom;this.coordinate=coordinate}packages;headroom;coordinate;async has(digest){return this.coordinate(async()=>{await this.packages.refresh();return this.packages.entries.has(this.completePath(digest))&&this.packages.entries.has(this.artifactPath(digest))})}async hasTree(digest){return this.coordinate(async()=>{await this.packages.refresh();return this.packages.entries.has(this.completePath(digest))})}async presentTrees(digests){return this.coordinate(async()=>{await this.packages.refresh();const present=new Set;for(const digest of digests)if(this.packages.entries.has(this.completePath(digest)))present.add(digest);return present})}async readArtifact(digest){return this.coordinate(async()=>{await this.packages.refresh();if(this.packages.entries.has(this.completePath(digest)))return this.packages.read(this.artifactPath(digest)).slice();if(this.packages.entries.has(legacyBrowserPackCompletePath(digest)))return this.packages.read(legacyBrowserPackArtifactPath(digest)).slice();throw new Error(`Pack artifact ${digest} is not completely staged.`)})}async stageArtifact(digest,bytes2,artifact,signal){if(await this.has(digest))return;const path3=this.artifactPath(digest);const mutations=[{operation:"mkdir",path:path3.slice(0,path3.lastIndexOf("/")),recursive:true},{operation:"mkdir",path:this.completePath(digest).slice(0,this.completePath(digest).lastIndexOf("/")),recursive:true},{operation:"write",path:path3,content:bytes2,mode:292}];if(artifact.archive){const root2=this.expandedPath(digest);const entries=await extractBrowserPackArchive(bytes2,artifact,signal);mutations.push({operation:"mkdir",path:root2,recursive:true});for(const entry of entries){const target=`${root2}/${entry.path}`;if(entry.type==="directory")mutations.push({operation:"mkdir",path:target,recursive:true,mode:entry.mode});else{mutations.push({operation:"mkdir",path:target.slice(0,target.lastIndexOf("/")),recursive:true});mutations.push({operation:"write",path:target,content:entry.type==="file"?entry.content:new TextEncoder().encode(entry.target),mode:entry.mode,...entry.type==="symlink"?{symlink:true}:{}})}}}mutations.push({operation:"write",path:this.completePath(digest),content:new Uint8Array(0),mode:292});for(let offset2=0;offset2<mutations.length;offset2+=128){checkCancelled(signal);const complete=await this.coordinate(async()=>{await this.packages.refresh();if(this.packages.entries.has(this.completePath(digest))){if(!this.packages.entries.has(path3))await this.packages.apply(mutations.slice(0,3));return true}await this.packages.apply(mutations.slice(offset2,offset2+128));return false});if(complete)return}}async stageEnvironment(lockDigest,lock){const path3=browserPackLockPath(lockDigest);await this.coordinate(async()=>{await this.packages.refresh();if(this.packages.entries.has(path3))return;await this.packages.apply([{operation:"mkdir",path:"/packages/.browser-packs/locks",recursive:true},{operation:"write",path:path3,content:new TextEncoder().encode(canonicalBrowserPackJson(lock)),mode:292}])})}async availableBytes(){return this.headroom?.()}artifactPath(digest){return browserPackArtifactPath(digest)}expandedPath(digest){return browserPackExpandedPath(digest)}completePath(digest){return browserPackCompletePath(digest)}};function browserPackObjectPath(digest){return`/packages/.browser-packs/objects/${digest.slice("sha256:".length)}`}function browserPackArtifactPath(digest){return`${browserPackObjectPath(digest)}/artifact`}function browserPackExpandedPath(digest){return`${browserPackObjectPath(digest)}/expanded`}function browserPackCompletePath(digest){return`${browserPackObjectPath(digest)}/complete`}function browserPackLockPath(digest){return`/packages/.browser-packs/locks/${digest.slice("sha256:".length)}.json`}function legacyBrowserPackArtifactPath(digest){return`/packages/.browser-packs/artifacts/${digest.slice("sha256:".length)}`}function legacyBrowserPackExpandedPath(digest){return`/packages/.browser-packs/expanded/${digest.slice("sha256:".length)}`}function legacyBrowserPackCompletePath(digest){return`/packages/.browser-packs/complete/${digest.slice("sha256:".length)}`}var INSTALL_REFUSED="EINSTALLREFUSED";var INSTALL_TRAP_RECORD="[install-trap-record]";var InstallRefusedError=class extends Error{constructor(request){super(installRefusal(request));this.request=request;this.name="InstallRefusedError"}request;code=INSTALL_REFUSED};var RECORDER=Symbol.for("browser-substrate.install-recorder");var TRAPPED=Symbol.for("browser-substrate.install-trapped");function installTrap(request){const scope4=globalThis;(scope4[TRAPPED]??=[]).push(request);scope4[RECORDER]?.(request);console.error(`[install-trap] ${request.door}: ${request.subject}`);console.info(`${INSTALL_TRAP_RECORD} ${JSON.stringify(request)}`);throw new InstallRefusedError(request)}function isInstallRefused(cause){if(typeof cause!=="object"||cause===null)return false;if(cause.code===INSTALL_REFUSED)return true;return/^REFUSED \([^)]+\): /u.test(String(cause.message??""))}function installRefusal(request){return[`REFUSED (${request.door}): ${request.subject}`,"","The tab never installs, downloads, extracts or builds a dependency, and never runs a setup step. Everything a","project uses reaches it prepared, with the image or from the catalog, and this was not. Nothing was attempted.","",...request.fix?[`To fix it: ${request.fix}`]:["To fix it, prepare the image again on a machine, from the project's folder:",""," npx @volter/browser-substrate dev"]].join("\n")}var IMAGE_RANGE_WORKER_PATH="/image-range-worker.js";var IMAGE_RANGES_FILE="image-ranges.json";var PREFETCH_WORKERS=2;function validateImageRanges(candidate){const value=candidate;if(!value||value.version!==1||!Number.isSafeInteger(value.bytes)||value.bytes<0||!Array.isArray(value.parts)||value.image!==void 0&&(typeof value.image!=="string"||!/^[a-f0-9]{16,64}$/u.test(value.image))||value.parts.length>1e5)throw new Error("Invalid immutable image ranges.");let end=0;for(const part of value.parts){if(!part||part.offset!==end||!Number.isSafeInteger(part.raw)||part.raw<0||!Number.isSafeInteger(part.bytes)||part.bytes<0||part.bytes>1024*1024*1024||part.raw>1024*1024*1024||typeof part.sha256!=="string"||!/^[a-f0-9]{64}$/u.test(part.sha256)||typeof part.url!=="string"||!/^\/substrate\/[A-Za-z0-9._/-]+$/u.test(part.url)||part.url.split("/").some(segment=>segment==="."||segment===".."))throw new Error("Invalid immutable image part.");end+=part.raw;if(!Number.isSafeInteger(end))throw new Error("Immutable image ranges exceed the offset limit.")}if(end!==value.bytes)throw new Error("Immutable image ranges do not cover their reservation.");return value}var realmBlockedReads=new Map;var ImageRangeReader=class{constructor(ranges,directory2,identity,completed,receiptKey,client){this.ranges=ranges;this.directory=directory2;this.identity=identity;this.receiptKey=receiptKey;this.client=client;if(typeof Worker==="undefined"||typeof SharedArrayBuffer==="undefined"){throw new Error("This browser cannot materialize an immutable image during a synchronous read.")}this.state=new Int32Array(client?.state??new SharedArrayBuffer(ranges.parts.length*Int32Array.BYTES_PER_ELEMENT));if(this.state.length!==ranges.parts.length)throw new Error("The image reader's line has the wrong range count.");const count=ranges.parts.length;const shared=completed??new SharedArrayBuffer((2*count+1)*Int32Array.BYTES_PER_ELEMENT);if(shared.byteLength!==count*Int32Array.BYTES_PER_ELEMENT&&shared.byteLength!==(2*count+1)*Int32Array.BYTES_PER_ELEMENT){throw new Error("The image completion seed has the wrong range count.")}this.completed=new Int32Array(shared,0,count);this.firstRead=shared.byteLength>count*Int32Array.BYTES_PER_ELEMENT?new Int32Array(shared,count*Int32Array.BYTES_PER_ELEMENT,count+1):void 0;this.sharedCompletion=completed!==void 0;for(const part of ranges.parts)Object.freeze(part);Object.freeze(ranges.parts);Object.freeze(ranges)}ranges;directory;identity;receiptKey;client;worker;port;prefetchers=[];state;completed;firstRead;closed=false;ready=false;startup;cancelStartup;sharedCompletion;get completionBuffer(){return this.completed.buffer}get verifiedRanges(){return this.ranges}async initialize(){if(this.closed)throw new Error("This immutable image reader is closed.");if(this.ready)return;if(this.startup)return this.startup;let missing=false;for(let index2=0;index2<this.completed.length;index2+=1){if(Atomics.load(this.completed,index2)!==2){missing=true;break}}if(!missing){this.ready=true;this.client?.port.close();return}if(this.client){const port2=this.port=this.client.port;port2.onmessage=event=>{if(event.data?.type!=="closing"||this.port!==port2)return;port2.close();this.port=void 0;if(!this.closed)void this.startMaterializer().catch(cause=>console.warn("This process's image reader could not start its own materializer after its line closed.",cause))};port2.start();this.ready=true;return}return this.startMaterializer()}startMaterializer(){const began=Date.now();const worker2=new Worker(IMAGE_RANGE_WORKER_PATH,{type:"module",name:"immutable-image-materializer"});const viaLine=this.ready;if(!viaLine)this.worker=worker2;worker2.addEventListener("error",()=>this.fail());worker2.addEventListener("messageerror",()=>this.fail());this.startup=new Promise((resolve2,reject)=>{const cleanup=()=>{clearTimeout(timer);worker2.removeEventListener("message",acknowledge);worker2.removeEventListener("error",failed);worker2.removeEventListener("messageerror",failed);this.cancelStartup=void 0};const failed=()=>cancel(new Error("The immutable image materializer could not initialize; reload to retry."));const cancel=cause=>{cleanup();worker2.terminate();if(!viaLine){this.closed=true;this.fail()}reject(cause)};const acknowledge=event=>{if(event.data?.identity!==this.identity)return;if(event.data.type==="init-error"){cancel(new Error(`The immutable image materializer could not initialize: ${String(event.data.error)}`));return}if(event.data.type!=="ready")return;console.log(`[boot-trace] ${JSON.stringify({event:"materializer-ready",at:Date.now(),ms:Date.now()-began})}`);cleanup();this.ready=true;this.worker=worker2;resolve2()};const timer=setTimeout(()=>cancel(new Error("The immutable image materializer did not initialize within 10 seconds; reload to retry.")),1e4);this.cancelStartup=cancel;worker2.addEventListener("message",acknowledge);worker2.addEventListener("error",failed);worker2.addEventListener("messageerror",failed);try{worker2.postMessage({type:"init",ranges:this.ranges,directory:this.directory,identity:this.identity,state:this.state.buffer,completed:this.completed.buffer,sharedCompletion:this.sharedCompletion,...this.receiptKey?{receiptKey:this.receiptKey}:{}})}catch(cause){cancel(cause instanceof Error?cause:new Error(String(cause)))}});return this.startup}readDigests(){const order=this.firstRead;if(!order)return void 0;const count=this.ranges.parts.length;const read=[];for(let index2=0;index2<count;index2+=1){const sequence=Atomics.load(order,index2);const part=this.ranges.parts[index2];if(sequence>0&&part.raw>0)read.push([sequence,part.sha256])}return read.sort((left,right)=>left[0]-right[0]).map(([,digest])=>digest)}completedDigests(){const held=[];for(let index2=0;index2<this.completed.length;index2+=1){const part=this.ranges.parts[index2];if(part.raw>0&&Atomics.load(this.completed,index2)===2)held.push(part.sha256)}return held}prefetch(digests,streams2=[]){if(this.closed||!this.ready||!this.worker)return{queued:0,done:Promise.resolve()};const byDigest=new Map;for(let index2=0;index2<this.ranges.parts.length;index2+=1){const part=this.ranges.parts[index2];if(part.raw===0)continue;const held=byDigest.get(part.sha256);if(held)held.push(index2);else byDigest.set(part.sha256,[index2])}const indices=[];for(const digest of new Set(digests)){for(const index2 of byDigest.get(digest)??[])if(Atomics.load(this.completed,index2)!==2)indices.push(index2)}const helpers=streams2.length>0&&indices.length>0?Math.min(streams2.length,8):Math.min(PREFETCH_WORKERS,Math.ceil(indices.length/32));const finished=[];for(let lane=0;lane<helpers;lane+=1){const share=indices.filter((_,at3)=>at3%helpers===lane);const helper=new Worker(IMAGE_RANGE_WORKER_PATH,{type:"module",name:"immutable-image-prefetch"});this.prefetchers.push(helper);let ended2;finished.push(new Promise(resolve2=>{ended2=resolve2}));const retire=()=>{helper.terminate();this.prefetchers=this.prefetchers.filter(held=>held!==helper);ended2()};helper.addEventListener("error",retire);helper.addEventListener("messageerror",retire);helper.addEventListener("message",event=>{if(event.data?.identity!==this.identity)return;if(event.data.type==="ready")helper.postMessage(streams2.length>0?{type:"prefetch-stream",url:streams2[lane]}:{type:"prefetch",indices:share});else if(event.data.type==="prefetched"||event.data.type==="init-error")retire()});helper.postMessage({type:"init",ranges:this.ranges,directory:this.directory,identity:this.identity,state:new SharedArrayBuffer(this.state.byteLength),completed:this.completed.buffer,sharedCompletion:true,...this.receiptKey?{receiptKey:this.receiptKey}:{}})}return{queued:indices.length,done:Promise.all(finished).then(()=>void 0)}}ensure(offset2,length){if(this.closed)throw new Error("This immutable image reader is closed.");if(!this.ready)throw new Error("This immutable image reader has not finished asynchronous initialization.");if(length===0||offset2>=this.ranges.bytes)return;const end=Math.min(offset2+length,this.ranges.bytes);let low=0,high=this.ranges.parts.length;while(low<high){const mid=low+high>>>1;const part=this.ranges.parts[mid];if(part.offset+part.raw<=offset2)low=mid+1;else high=mid}for(let index2=low;index2<this.ranges.parts.length;index2+=1){const part=this.ranges.parts[index2];if(part.offset>=end)break;const order=this.firstRead;if(order&&Atomics.load(order,index2)===0)Atomics.compareExchange(order,index2,0,Atomics.add(order,this.ranges.parts.length,1)+1);if(Atomics.load(this.completed,index2)===2)continue;const materializer=this.worker??this.port;if(!materializer)throw new Error("This immutable image reader's line closed and its own materializer is still starting; retry the read.");materializer.postMessage({type:"read",index:index2});const began=performance.now();const deadline=began+3e4;while(Atomics.load(this.state,index2)===0){const left=deadline-performance.now();if(left<=0||Atomics.wait(this.state,index2,0,left)==="timed-out"){this.close();throw new Error(`The image's immutable part ${part.url} did not arrive within 30 seconds; reload to retry.`)}}const waited=performance.now()-began;const realm=realmBlockedReads.get(this.identity)??{ranges:0,ms:0};realm.ranges+=1;realm.ms+=waited;realmBlockedReads.set(this.identity,realm);console.log(`[boot-trace] ${JSON.stringify({event:"image-blocked",at:Date.now(),reader:this.identity,index:index2,range:part.sha256.slice(0,16),ms:Math.round(waited)})}`);if(Atomics.load(this.state,index2)!==2){throw new Error(`The image's immutable part ${part.url} could not be verified or stored; see the worker error and reload to retry.`)}}}lineForReader(){const materializer=this.worker??this.port;if(this.closed||!this.ready||!materializer)return void 0;const channel=new MessageChannel;const state=new SharedArrayBuffer(this.ranges.parts.length*Int32Array.BYTES_PER_ELEMENT);materializer.postMessage({type:"client",port:channel.port1,state},[channel.port1]);return{port:channel.port2,state}}fail(){for(let index2=0;index2<this.state.length;index2+=1){if(Atomics.compareExchange(this.state,index2,0,-1)===0)Atomics.notify(this.state,index2)}}close(){if(this.closed)return;this.closed=true;if(this.cancelStartup){this.cancelStartup(new Error("This immutable image reader closed during initialization."));return}this.fail();this.port?.close();const worker2=this.worker;if(worker2){worker2.postMessage({type:"closing"});setTimeout(()=>worker2.terminate(),250)}for(const helper of this.prefetchers)helper.dispatchEvent(new Event("error"));this.prefetchers=[]}};var __defProp2=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp2(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);var CHUNK=8192;function uint8ToBase64(bytes2){const parts=[];for(let i10=0;i10<bytes2.length;i10+=CHUNK){parts.push(String.fromCharCode.apply(null,Array.from(bytes2.subarray(i10,i10+CHUNK))))}return btoa(parts.join(""))}function base64ToUint8(base644){const binary=atob(base644);const bytes2=new Uint8Array(binary.length);for(let i10=0;i10<binary.length;i10++){bytes2[i10]=binary.charCodeAt(i10)}return bytes2}function uint8ToHex(bytes2){const hex=new Array(bytes2.length);for(let i10=0;i10<bytes2.length;i10++){hex[i10]=bytes2[i10].toString(16).padStart(2,"0")}return hex.join("")}function uint8ToBinaryString(bytes2){const parts=[];for(let i10=0;i10<bytes2.length;i10+=CHUNK){parts.push(String.fromCharCode.apply(null,Array.from(bytes2.subarray(i10,i10+CHUNK))))}return parts.join("")}var _encoder=new TextEncoder;var FLOW_MAX_REQUEST_BYTES=64*1024*1024;var FLOW_MAX_CHUNK_BYTES=65536;var FLOW_QUEUED_CHUNKS=4;function ownedBytes(view){const copy2=new Uint8Array(view.byteLength);copy2.set(new Uint8Array(view.buffer,view.byteOffset,view.byteLength));return copy2}var BridgeEvents=class{constructor(){__publicField(this,"listenersByEvent",new Map)}on(event,listener){const list2=this.listenersByEvent.get(event)??[];list2.push(listener);this.listenersByEvent.set(event,list2);return this}addListener(event,listener){return this.on(event,listener)}once(event,listener){const wrapped=(...args)=>{this.off(event,wrapped);listener(...args)};wrapped.listener=listener;return this.on(event,wrapped)}off(event,listener){const list2=this.listenersByEvent.get(event);if(!list2)return this;const at3=list2.findIndex(candidate=>candidate===listener||candidate.listener===listener);if(at3>=0)list2.splice(at3,1);if(list2.length===0)this.listenersByEvent.delete(event);return this}removeListener(event,listener){return this.off(event,listener)}removeAllListeners(event){if(event===void 0)this.listenersByEvent.clear();else this.listenersByEvent.delete(event);return this}listenerCount(event){var _a4;return((_a4=this.listenersByEvent.get(event))==null?void 0:_a4.length)??0}emit(event,...args){const list2=this.listenersByEvent.get(event);if(!list2||list2.length===0)return false;for(const listener of[...list2])listener(...args);return true}};var _PortBridge=class _PortBridge2 extends BridgeEvents{constructor(options={}){super();__publicField(this,"servers",new Map);__publicField(this,"baseUrl");__publicField(this,"options");__publicField(this,"messageChannel",null);__publicField(this,"serviceWorkerReady",false);__publicField(this,"keepaliveInterval",null);__publicField(this,"primaryPort",null);__publicField(this,"ownDocuments");__publicField(this,"binaryChunkPorts",new WeakSet);__publicField(this,"controlledStreams",new Map);this.options=options;if(typeof location!=="undefined"){this.baseUrl=options.baseUrl||`${location.protocol}//${location.host}`}else{this.baseUrl=options.baseUrl||"http://localhost"}}close(){if(this.keepaliveInterval!==null){clearInterval(this.keepaliveInterval);this.keepaliveInterval=null}}registerServer(server,port2,hostname2="0.0.0.0"){this.servers.set(port2,{server,port:port2,hostname:hostname2});const url2=this.getServerUrl(port2);this.emit("server-ready",port2,url2);if(this.options.onServerReady){this.options.onServerReady(port2,url2)}this.notifyServiceWorker("server-registered",{port:port2,hostname:hostname2,primary:port2===this.primaryPort})}unregisterServer(port2){this.servers.delete(port2);if(this.primaryPort===port2)this.primaryPort=null;this.notifyServiceWorker("server-unregistered",{port:port2})}setPrimaryPort(port2){const previous=this.primaryPort;this.primaryPort=port2;if(previous!==null&&previous!==port2){const entry=this.servers.get(previous);if(entry)this.notifyServiceWorker("server-registered",{port:previous,hostname:entry.hostname,primary:false})}if(port2!==null){const entry=this.servers.get(port2);this.notifyServiceWorker("server-registered",{port:port2,hostname:(entry==null?void 0:entry.hostname)??"0.0.0.0",primary:true})}}announceServers(){if(this.ownDocuments)this.notifyServiceWorker("own-documents",{paths:this.ownDocuments});for(const[port2,entry]of this.servers){this.notifyServiceWorker("server-registered",{port:port2,hostname:entry.hostname,primary:port2===this.primaryPort})}}getServerUrl(port2){return`${this.baseUrl}/__virtual__/${port2}`}getServerPorts(){return[...this.servers.keys()]}async handleRequest(port2,method,url2,headers,body){const virtualServer=this.servers.get(port2);if(!virtualServer){return{statusCode:503,statusMessage:"Service Unavailable",headers:{"Content-Type":"text/plain"},body:_encoder.encode(`No server listening on port ${port2}`)}}try{const bodyBuffer=body?this.bodyOf(new Uint8Array(body)):void 0;const named=Object.keys(headers).some(name=>name.toLowerCase()==="host");const authority=`${virtualServer.hostname&&virtualServer.hostname!=="0.0.0.0"&&virtualServer.hostname!=="::"?virtualServer.hostname:"127.0.0.1"}:${port2}`;const withHost=named?headers:{...headers,host:authority};if(virtualServer.server)return await virtualServer.server.handleRequest(method,url2,withHost,bodyBuffer);return await this.requestGuest(port2,method,url2,withHost,bodyBuffer)}catch(error){const message=error instanceof Error?error.message:"Internal Server Error";return{statusCode:500,statusMessage:"Internal Server Error",headers:{"Content-Type":"text/plain"},body:_encoder.encode(message)}}}async initServiceWorker(options){if(!("serviceWorker"in navigator)){throw new Error("Service Workers not supported")}const swUrl=(options==null?void 0:options.swUrl)??"/__sw__.js";const controllerReady=navigator.serviceWorker.controller?Promise.resolve():new Promise(resolve2=>{navigator.serviceWorker.addEventListener("controllerchange",()=>resolve2(),{once:true})});const registration=await navigator.serviceWorker.register(swUrl,{scope:"/",updateViaCache:"none"});try{await Promise.race([registration.update(),new Promise(resolve2=>setTimeout(resolve2,5e3))])}catch{}const sw2=registration.installing||registration.waiting||registration.active;if(!sw2){throw new Error("Service Worker registration failed")}await new Promise(resolve2=>{if(sw2.state==="activated"||sw2.state==="redundant"){resolve2()}else{const handler=()=>{if(sw2.state==="activated"||sw2.state==="redundant"){sw2.removeEventListener("statechange",handler);resolve2()}};sw2.addEventListener("statechange",handler)}});const controlling=sw2.state==="redundant"?registration.active:sw2;if(!controlling)throw new Error("Service Worker failed to install");if(navigator.serviceWorker.controller&&navigator.serviceWorker.controller!==controlling){await new Promise(resolve2=>{const timer=setTimeout(()=>{console.warn("tabnode: the new service worker did not take control within 10 s; starting under the one in control");done()},1e4);function done(){clearTimeout(timer);navigator.serviceWorker.removeEventListener("controllerchange",changed);resolve2()}function changed(){if(navigator.serviceWorker.controller===controlling)done()}navigator.serviceWorker.addEventListener("controllerchange",changed);changed()})}this.messageChannel=new MessageChannel;this.messageChannel.port1.onmessage=this.handleServiceWorkerMessage.bind(this);this.ownDocuments=options==null?void 0:options.ownDocuments;controlling.postMessage({type:"init",port:this.messageChannel.port2,data:{ownDocuments:this.ownDocuments??[]}},[this.messageChannel.port2]);await controllerReady;const reinit=()=>{if(navigator.serviceWorker.controller){for(const stream of[...this.controlledStreams.values()])stream.cancel();this.messageChannel=new MessageChannel;this.messageChannel.port1.onmessage=this.handleServiceWorkerMessage.bind(this);navigator.serviceWorker.controller.postMessage({type:"init",port:this.messageChannel.port2,data:{ownDocuments:this.ownDocuments??[]}},[this.messageChannel.port2]);this.announceServers()}};navigator.serviceWorker.addEventListener("controllerchange",reinit);navigator.serviceWorker.addEventListener("message",event=>{var _a4;if(((_a4=event.data)==null?void 0:_a4.type)==="sw-needs-init"){reinit()}});this.keepaliveInterval=setInterval(()=>{var _a4;(_a4=this.messageChannel)==null?void 0:_a4.port1.postMessage({type:"keepalive"})},2e4);this.serviceWorkerReady=true;this.announceServers();this.emit("sw-ready")}postChunk(port2,id2,bytes2){if(!port2)return;if(this.binaryChunkPorts.has(port2))port2.postMessage({type:"stream-chunk",id:id2,data:{chunk:bytes2}},[bytes2.buffer]);else port2.postMessage({type:"stream-chunk",id:id2,data:{chunkBase64:uint8ToBase64(bytes2)}})}async handleServiceWorkerMessage(event){var _a4,_b3,_c3;const{type:type2,id:id2,data:data2}=event.data;if(type2==="sw-capabilities"){if((data2==null?void 0:data2.binaryChunks)===1&&event.target instanceof MessagePort)this.binaryChunkPorts.add(event.target);return}_PortBridge2.DEBUG&&console.log("[ServerBridge] SW message:",type2,id2,data2==null?void 0:data2.url);if(type2==="stream-pull"||type2==="stream-cancel"){const stream=this.controlledStreams.get(id2);if(type2==="stream-pull")stream==null?void 0:stream.pull();else stream==null?void 0:stream.cancel();return}if(type2==="request"&&(data2==null?void 0:data2.flowControl)===1){const{port:port2,method,url:url2,headers,body}=data2;await this.controlledStream(id2,port2,method,url2,headers,body);return}if(type2==="request"){const{port:port2,method,url:url2,headers,body,streaming}=data2;_PortBridge2.DEBUG&&console.log("[ServerBridge] Handling request:",port2,method,url2,"streaming:",streaming);if(streaming){_PortBridge2.DEBUG&&console.log("[ServerBridge] \u{1F534} Will use streaming handler")}try{if(streaming){await this.streamToServiceWorker(id2,port2,method,url2,headers,body)}else{const response=await this.handleRequest(port2,method,url2,headers,body);_PortBridge2.DEBUG&&console.log("[ServerBridge] Response:",response.statusCode,"body length:",(_a4=response.body)==null?void 0:_a4.length);let bodyBase64="";if(response.body&&response.body.length>0){const bytes2=response.body instanceof Uint8Array?response.body:new Uint8Array(0);bodyBase64=uint8ToBase64(bytes2)}_PortBridge2.DEBUG&&console.log("[ServerBridge] Sending response to SW, body base64 length:",bodyBase64.length);(_b3=this.messageChannel)==null?void 0:_b3.port1.postMessage({type:"response",id:id2,data:{statusCode:response.statusCode,statusMessage:response.statusMessage,headers:response.headers,bodyBase64}})}}catch(error){(_c3=this.messageChannel)==null?void 0:_c3.port1.postMessage({type:"response",id:id2,error:error instanceof Error?error.message:"Unknown error"})}}}async handleStreamingRequest(port2,method,url2,headers,body,callbacks,flow){const virtualServer=this.servers.get(port2);if(!virtualServer)return false;const bodyBuffer=body?this.bodyOf(new Uint8Array(body)):void 0;if(this.isGuest(virtualServer)){const named=Object.keys(headers).some(name=>name.toLowerCase()==="host");const authority=`${virtualServer.hostname&&virtualServer.hostname!=="0.0.0.0"&&virtualServer.hostname!=="::"?virtualServer.hostname:"127.0.0.1"}:${port2}`;await this.streamGuest(port2,method,url2,named?headers:{...headers,host:authority},bodyBuffer,(statusCode,statusMessage,respHeaders)=>callbacks.start(statusCode,statusMessage,respHeaders),chunk=>callbacks.chunk(ownedBytes(chunk)),()=>callbacks.end(),flow);return true}const server=virtualServer.server;if(typeof server.handleStreamingRequest==="function"){await server.handleStreamingRequest(method,url2,headers,bodyBuffer,(statusCode,statusMessage,respHeaders)=>callbacks.start(statusCode,statusMessage,respHeaders),chunk=>callbacks.chunk(typeof chunk==="string"?_encoder.encode(chunk):ownedBytes(chunk)),()=>callbacks.end(),flow);return true}const response=await this.handleRequest(port2,method,url2,headers,body);callbacks.start(response.statusCode,response.statusMessage??"",response.headers);if(response.body){const body2=typeof response.body==="string"?_encoder.encode(response.body):response.body;callbacks.chunk(ownedBytes(body2))}callbacks.end();return true}async streamToServiceWorker(id2,port2,method,url2,headers,body){var _a4,_b3,_c3,_d3,_e3;const virtualServer=this.servers.get(port2);if(!virtualServer){(_a4=this.messageChannel)==null?void 0:_a4.port1.postMessage({type:"stream-start",id:id2,data:{statusCode:503,statusMessage:"Service Unavailable",headers:{}}});(_b3=this.messageChannel)==null?void 0:_b3.port1.postMessage({type:"stream-end",id:id2});return}if(this.isGuest(virtualServer)){const bodyBuffer=body?this.bodyOf(new Uint8Array(body)):void 0;const named=Object.keys(headers).some(name=>name.toLowerCase()==="host");const authority=`${virtualServer.hostname&&virtualServer.hostname!=="0.0.0.0"&&virtualServer.hostname!=="::"?virtualServer.hostname:"127.0.0.1"}:${port2}`;await this.streamGuest(port2,method,url2,named?headers:{...headers,host:authority},bodyBuffer,(statusCode,statusMessage,respHeaders)=>{var _a22;(_a22=this.messageChannel)==null?void 0:_a22.port1.postMessage({type:"stream-start",id:id2,data:{statusCode,statusMessage,headers:respHeaders}})},chunk=>{var _a22;const copy2=ownedBytes(chunk);(_a22=this.messageChannel)==null?void 0:_a22.port1.postMessage({type:"stream-chunk",id:id2,data:copy2.buffer},[copy2.buffer])},()=>{var _a22;(_a22=this.messageChannel)==null?void 0:_a22.port1.postMessage({type:"stream-end",id:id2})});return}const server=virtualServer.server;if(!server)return;if(typeof server.handleStreamingRequest==="function"){_PortBridge2.DEBUG&&console.log("[ServerBridge] \u{1F7E2} Server has streaming support, calling handleStreamingRequest");const bodyBuffer=body?this.bodyOf(new Uint8Array(body)):void 0;await server.handleStreamingRequest(method,url2,headers,bodyBuffer,(statusCode,statusMessage,respHeaders)=>{var _a22;_PortBridge2.DEBUG&&console.log("[ServerBridge] \u{1F7E2} onStart called, sending stream-start");(_a22=this.messageChannel)==null?void 0:_a22.port1.postMessage({type:"stream-start",id:id2,data:{statusCode,statusMessage,headers:respHeaders}})},chunk=>{var _a22;const bytes2=typeof chunk==="string"?_encoder.encode(chunk):ownedBytes(chunk);_PortBridge2.DEBUG&&console.log("[ServerBridge] \u{1F7E1} onChunk called, sending stream-chunk, size:",bytes2.byteLength);this.postChunk((_a22=this.messageChannel)==null?void 0:_a22.port1,id2,bytes2)},()=>{var _a22;_PortBridge2.DEBUG&&console.log("[ServerBridge] \u{1F7E2} onEnd called, sending stream-end");(_a22=this.messageChannel)==null?void 0:_a22.port1.postMessage({type:"stream-end",id:id2})})}else{const bodyBuffer=body?this.bodyOf(new Uint8Array(body)):void 0;const response=await server.handleRequest(method,url2,headers,bodyBuffer);(_c3=this.messageChannel)==null?void 0:_c3.port1.postMessage({type:"stream-start",id:id2,data:{statusCode:response.statusCode,statusMessage:response.statusMessage,headers:response.headers}});if(response.body&&response.body.length>0){const bytes2=response.body instanceof Uint8Array?ownedBytes(response.body):new Uint8Array(0);this.postChunk((_d3=this.messageChannel)==null?void 0:_d3.port1,id2,bytes2)}(_e3=this.messageChannel)==null?void 0:_e3.port1.postMessage({type:"stream-end",id:id2})}}notifyServiceWorker(type2,data2){if(this.serviceWorkerReady&&this.messageChannel){const flow=type2==="server-registered"?{flowControl:1,maxRequestBytes:FLOW_MAX_REQUEST_BYTES,maxChunkBytes:FLOW_MAX_CHUNK_BYTES}:{};this.messageChannel.port1.postMessage({type:type2,data:{...data2,...flow}})}}async controlledStream(id2,port2,method,url2,headers,body){const channel=this.messageChannel;const post=(type2,data2)=>{channel==null?void 0:channel.port1.postMessage({type:type2,id:id2,...data2===void 0?{}:{data:data2}})};const queue=[];const abort=new AbortController;let credits=0;let upstreamEnded=false;let finished=false;let paused=false;let pause=()=>void 0;let resume=()=>void 0;const finish=()=>{finished=true;this.controlledStreams.delete(id2)};const flush2=()=>{if(finished)return;while(credits>0&&queue.length>0){credits-=1;this.postChunk(channel==null?void 0:channel.port1,id2,queue.shift())}if(upstreamEnded&&queue.length===0){post("stream-end");finish();return}if(queue.length>=FLOW_QUEUED_CHUNKS&&!paused){paused=true;pause()}else if(queue.length<FLOW_QUEUED_CHUNKS&&paused){paused=false;resume()}};this.controlledStreams.set(id2,{pull:()=>{credits+=1;flush2()},cancel:()=>{if(finished)return;finish();queue.length=0;abort.abort()}});try{const answered=await this.handleStreamingRequest(port2,method,url2,headers,body,{start:(statusCode,statusMessage,respHeaders)=>post("stream-start",{statusCode,statusMessage,headers:respHeaders}),chunk:chunk=>{if(finished)return;for(let at3=0;at3<chunk.byteLength;at3+=FLOW_MAX_CHUNK_BYTES)queue.push(chunk.slice(at3,at3+FLOW_MAX_CHUNK_BYTES));flush2()},end:()=>{upstreamEnded=true;flush2()}},{signal:abort.signal,control:(p,r10)=>{pause=p;resume=r10}});if(!answered){post("stream-start",{statusCode:503,statusMessage:"Service Unavailable",headers:{}});post("stream-end");finish()}}catch(error){if(!finished){post("stream-error",{message:error instanceof Error?error.message:String(error)});finish()}}}createFetchHandler(){return async request=>{const url2=new URL(request.url);const match2=url2.pathname.match(/^\/__virtual__\/(\d+)(\/.*)?$/);if(!match2){throw new Error("Not a virtual server request")}const port2=parseInt(match2[1],10);const path3=match2[2]||"/";const headers={};request.headers.forEach((value,key)=>{headers[key]=value});let body;if(request.method!=="GET"&&request.method!=="HEAD"){body=await request.arrayBuffer()}const response=await this.handleRequest(port2,request.method,path3+url2.search,headers,body);const answerHeaders=new Headers;for(const[name,value]of Object.entries(response.headers)){for(const each of Array.isArray(value)?value:[value])answerHeaders.append(name,each)}return new Response(response.body,{status:response.statusCode,statusText:response.statusMessage??"",headers:answerHeaders})}}isGuest(entry){return entry.server===null}requestGuest(port2,_method,_url2,_headers2,_body){return Promise.reject(new Error(`Port ${port2} has no server in this realm.`))}streamGuest(port2,_method,_url2,_headers2,_body,_onStart,_onChunk,_onEnd,_flow){return Promise.reject(new Error(`Port ${port2} has no server in this realm.`))}bodyOf(bytes2){return bytes2}};__publicField(_PortBridge,"DEBUG",false);var PortBridge=_PortBridge;var import_sprintf_js=__toESM(require_sprintf(),1);var balanced=(a,b,str)=>{const ma2=a instanceof RegExp?maybeMatch(a,str):a;const mb2=b instanceof RegExp?maybeMatch(b,str):b;const r10=ma2!==null&&mb2!=null&&range(ma2,mb2,str);return r10&&{start:r10[0],end:r10[1],pre:str.slice(0,r10[0]),body:str.slice(r10[0]+ma2.length,r10[1]),post:str.slice(r10[1]+mb2.length)}};var maybeMatch=(reg,str)=>{const m=str.match(reg);return m?m[0]:null};var range=(a,b,str)=>{let begs,beg,left,right=void 0,result;let ai2=str.indexOf(a);let bi2=str.indexOf(b,ai2+1);let i10=ai2;if(ai2>=0&&bi2>0){if(a===b){return[ai2,bi2]}begs=[];left=str.length;while(i10>=0&&!result){if(i10===ai2){begs.push(i10);ai2=str.indexOf(a,i10+1)}else if(begs.length===1){const r10=begs.pop();if(r10!==void 0)result=[r10,bi2]}else{beg=begs.pop();if(beg!==void 0&&beg<left){left=beg;right=bi2}bi2=str.indexOf(b,i10+1)}i10=ai2<bi2&&ai2>=0?ai2:bi2}if(begs.length&&right!==void 0){result=[left,right]}}return result};var escSlash="\0SLASH"+Math.random()+"\0";var escOpen="\0OPEN"+Math.random()+"\0";var escClose="\0CLOSE"+Math.random()+"\0";var escComma="\0COMMA"+Math.random()+"\0";var escPeriod="\0PERIOD"+Math.random()+"\0";var escSlashPattern=new RegExp(escSlash,"g");var escOpenPattern=new RegExp(escOpen,"g");var escClosePattern=new RegExp(escClose,"g");var escCommaPattern=new RegExp(escComma,"g");var escPeriodPattern=new RegExp(escPeriod,"g");var slashPattern=/\\\\/g;var openPattern=/\\{/g;var closePattern=/\\}/g;var commaPattern=/\\,/g;var periodPattern=/\\\./g;var EXPANSION_MAX=1e5;var EXPANSION_MAX_LENGTH=4e6;function numeric(str){return!isNaN(str)?parseInt(str,10):str.charCodeAt(0)}function escapeBraces(str){return str.replace(slashPattern,escSlash).replace(openPattern,escOpen).replace(closePattern,escClose).replace(commaPattern,escComma).replace(periodPattern,escPeriod)}function unescapeBraces(str){return str.replace(escSlashPattern,"\\").replace(escOpenPattern,"{").replace(escClosePattern,"}").replace(escCommaPattern,",").replace(escPeriodPattern,".")}function parseCommaParts(str){if(!str){return[""]}const parts=[];const m=balanced("{","}",str);if(!m){return str.split(",")}const{pre,body,post}=m;const p=pre.split(",");p[p.length-1]+="{"+body+"}";const postParts=parseCommaParts(post);if(post.length){;p[p.length-1]+=postParts.shift();p.push.apply(p,postParts)}parts.push.apply(parts,p);return parts}function expand(str,options={}){if(!str){return[]}const{max:max2=EXPANSION_MAX,maxLength=EXPANSION_MAX_LENGTH}=options;if(str.slice(0,2)==="{}"){str="\\{\\}"+str.slice(2)}return expand_(escapeBraces(str),max2,maxLength,true).map(unescapeBraces)}function embrace(str){return"{"+str+"}"}function isPadded(el2){return/^-?0\d/.test(el2)}function lte(i10,y){return i10<=y}function gte(i10,y){return i10>=y}function combine(acc,pre,values,max2,maxLength,dropEmpties){const out=[];let length=0;for(let a=0;a<acc.length;a++){for(let v2=0;v2<values.length;v2++){if(out.length>=max2)return out;const expansion=acc[a]+pre+values[v2];if(dropEmpties&&!expansion)continue;if(length+expansion.length>maxLength)return out;out.push(expansion);length+=expansion.length}}return out}function expandSequence(body,isAlphaSequence,max2,maxLength){const n8=body.split(/\.\./);const N=[];if(n8[0]===void 0||n8[1]===void 0){return N}const x=numeric(n8[0]);const y=numeric(n8[1]);const width=Math.max(n8[0].length,n8[1].length);let incr=n8.length===3&&n8[2]!==void 0?Math.max(Math.abs(numeric(n8[2])),1):1;let test=lte;const reverse2=y<x;if(reverse2){incr*=-1;test=gte}const pad=n8.some(isPadded);let length=0;for(let i10=x;test(i10,y)&&N.length<max2;i10+=incr){let c;if(isAlphaSequence){c=String.fromCharCode(i10);if(c==="\\"){c=""}}else{c=String(i10);if(pad){const need=width-c.length;if(need>0){const z10=new Array(need+1).join("0");if(i10<0){c="-"+z10+c.slice(1)}else{c=z10+c}}}}if(length+c.length>maxLength)break;N.push(c);length+=c.length}return N}function expand_(str,max2,maxLength,isTop){let acc=[""];let dropEmpties=false;let firstGroup=true;for(;;){const m=balanced("{","}",str);if(!m){return combine(acc,str,[""],max2,maxLength,dropEmpties)}const pre=m.pre;if(/\$$/.test(pre)){acc=combine(acc,pre+"{"+m.body+"}",[""],max2,maxLength,dropEmpties&&!m.post.length);firstGroup=false;if(!m.post.length)break;str=m.post;continue}const isNumericSequence=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);const isAlphaSequence=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);const isSequence=isNumericSequence||isAlphaSequence;const isOptions=m.body.indexOf(",")>=0;if(!isSequence&&!isOptions){if(m.post.match(/,(?!,).*\}/)){str=m.pre+"{"+m.body+escClose+m.post;isTop=true;continue}return combine(acc,pre+"{"+m.body+"}"+m.post,[""],max2,maxLength,dropEmpties)}if(firstGroup){dropEmpties=isTop&&!isSequence;firstGroup=false}let values;if(isSequence){values=expandSequence(m.body,isAlphaSequence,max2,maxLength)}else{let n8=parseCommaParts(m.body);if(n8.length===1&&n8[0]!==void 0){n8=expand_(n8[0],max2,maxLength,false).map(embrace);if(n8.length===1){acc=combine(acc,pre+n8[0],[""],max2,maxLength,dropEmpties&&!m.post.length);if(!m.post.length)break;str=m.post;continue}}let dropsEmpties=dropEmpties&&!m.post.length&&!pre;for(let d=0;dropsEmpties&&d<acc.length;d++){if(acc[d]){dropsEmpties=false}}values=[];let valuesLength=0;outer:for(let j=0;j<n8.length;j++){const expanded=expand_(n8[j],max2,maxLength,false);for(let k10=0;k10<expanded.length;k10++){const v2=expanded[k10];if(dropsEmpties&&!v2)continue;if(values.length>=max2||valuesLength+v2.length>maxLength){break outer}values.push(v2);valuesLength+=v2.length}}}acc=combine(acc,pre,values,max2,maxLength,dropEmpties&&!m.post.length);if(!m.post.length)break;str=m.post}return acc}var MAX_PATTERN_LENGTH=1024*64;var assertValidPattern=pattern=>{if(typeof pattern!=="string"){throw new TypeError("invalid pattern")}if(pattern.length>MAX_PATTERN_LENGTH){throw new TypeError("pattern is too long")}};var posixClasses={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",true],"[:alpha:]":["\\p{L}\\p{Nl}",true],"[:ascii:]":["\\x00-\\x7f",false],"[:blank:]":["\\p{Zs}\\t",true],"[:cntrl:]":["\\p{Cc}",true],"[:digit:]":["\\p{Nd}",true],"[:graph:]":["\\p{Z}\\p{C}",true,true],"[:lower:]":["\\p{Ll}",true],"[:print:]":["\\p{C}",true],"[:punct:]":["\\p{P}",true],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",true],"[:upper:]":["\\p{Lu}",true],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",true],"[:xdigit:]":["A-Fa-f0-9",false]};var braceEscape=s10=>s10.replace(/[[\]\\-]/g,"\\$&");var regexpEscape=s10=>s10.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");var rangesToString=ranges=>ranges.join("");var parseClass=(glob,position)=>{const pos=position;if(glob.charAt(pos)!=="["){throw new Error("not in a brace expression")}const ranges=[];const negs=[];let i10=pos+1;let sawStart=false;let uflag=false;let escaping=false;let negate=false;let endPos=pos;let rangeStart="";WHILE:while(i10<glob.length){const c=glob.charAt(i10);if((c==="!"||c==="^")&&i10===pos+1){negate=true;i10++;continue}if(c==="]"&&sawStart&&!escaping){endPos=i10+1;break}sawStart=true;if(c==="\\"){if(!escaping){escaping=true;i10++;continue}}if(c==="["&&!escaping){for(const[cls,[unip,u,neg]]of Object.entries(posixClasses)){if(glob.startsWith(cls,i10)){if(rangeStart){return["$.",false,glob.length-pos,true]}i10+=cls.length;if(neg)negs.push(unip);else ranges.push(unip);uflag=uflag||u;continue WHILE}}}escaping=false;if(rangeStart){if(c>rangeStart){ranges.push(braceEscape(rangeStart)+"-"+braceEscape(c))}else if(c===rangeStart){ranges.push(braceEscape(c))}rangeStart="";i10++;continue}if(glob.startsWith("-]",i10+1)){ranges.push(braceEscape(c+"-"));i10+=2;continue}if(glob.startsWith("-",i10+1)){rangeStart=c;i10+=2;continue}ranges.push(braceEscape(c));i10++}if(endPos<i10){return["",false,0,false]}if(!ranges.length&&!negs.length){return["$.",false,glob.length-pos,true]}if(negs.length===0&&ranges.length===1&&/^\\?.$/.test(ranges[0])&&!negate){const r10=ranges[0].length===2?ranges[0].slice(-1):ranges[0];return[regexpEscape(r10),false,endPos-pos,false]}const sranges="["+(negate?"^":"")+rangesToString(ranges)+"]";const snegs="["+(negate?"":"^")+rangesToString(negs)+"]";const comb=ranges.length&&negs.length?"("+sranges+"|"+snegs+")":ranges.length?sranges:snegs;return[comb,uflag,endPos-pos,true]};var unescape=(s10,{windowsPathsNoEscape=false,magicalBraces=true}={})=>{if(magicalBraces){return windowsPathsNoEscape?s10.replace(/\[([^/\\])\]/g,"$1"):s10.replace(/((?!\\).|^)\[([^/\\])\]/g,"$1$2").replace(/\\([^/])/g,"$1")}return windowsPathsNoEscape?s10.replace(/\[([^/\\{}])\]/g,"$1"):s10.replace(/((?!\\).|^)\[([^/\\{}])\]/g,"$1$2").replace(/\\([^/{}])/g,"$1")};var _a;var types=new Set(["!","?","+","*","@"]);var isExtglobType=c=>types.has(c);var isExtglobAST=c=>isExtglobType(c.type);var adoptionMap=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]);var adoptionWithSpaceMap=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]);var adoptionAnyMap=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]);var usurpMap=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]);var startNoTraversal="(?!(?:^|/)\\.\\.?(?:$|/))";var startNoDot="(?!\\.)";var addPatternStart=new Set(["[","."]);var justDots=new Set(["..","."]);var reSpecials=new Set("().*{}+?[]^$\\!");var regExpEscape=s10=>s10.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");var qmark="[^/]";var star=qmark+"*?";var starNoEmpty=qmark+"+?";var ID=0;var AST=class{type;#root;#hasMagic;#uflag=false;#parts=[];#parent;#parentIndex;#negs;#filledNegs=false;#options;#toString;#emptyExt=false;id=++ID;get depth(){return(this.#parent?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#root.id,parent:this.#parent?.id,depth:this.depth,partsLength:this.#parts.length,parts:this.#parts}}constructor(type2,parent,options={}){this.type=type2;if(type2)this.#hasMagic=true;this.#parent=parent;this.#root=this.#parent?this.#parent.#root:this;this.#options=this.#root===this?options:this.#root.#options;this.#negs=this.#root===this?[]:this.#root.#negs;if(type2==="!"&&!this.#root.#filledNegs)this.#negs.push(this);this.#parentIndex=this.#parent?this.#parent.#parts.length:0}get hasMagic(){if(this.#hasMagic!==void 0)return this.#hasMagic;for(const p of this.#parts){if(typeof p==="string")continue;if(p.type||p.hasMagic)return this.#hasMagic=true}return this.#hasMagic}toString(){return this.#toString!==void 0?this.#toString:!this.type?this.#toString=this.#parts.map(p=>String(p)).join(""):this.#toString=this.type+"("+this.#parts.map(p=>String(p)).join("|")+")"}#fillNegs(){if(this!==this.#root)throw new Error("should only call on root");if(this.#filledNegs)return this;this.toString();this.#filledNegs=true;let n8;while(n8=this.#negs.pop()){if(n8.type!=="!")continue;let p=n8;let pp3=p.#parent;while(pp3){for(let i10=p.#parentIndex+1;!pp3.type&&i10<pp3.#parts.length;i10++){for(const part of n8.#parts){if(typeof part==="string"){throw new Error("string part in extglob AST??")}part.copyIn(pp3.#parts[i10])}}p=pp3;pp3=p.#parent}}return this}push(...parts){for(const p of parts){if(p==="")continue;if(typeof p!=="string"&&!(p instanceof _a&&p.#parent===this)){throw new Error("invalid part: "+p)}this.#parts.push(p)}}toJSON(){const ret=this.type===null?this.#parts.slice().map(p=>typeof p==="string"?p:p.toJSON()):[this.type,...this.#parts.map(p=>p.toJSON())];if(this.isStart()&&!this.type)ret.unshift([]);if(this.isEnd()&&(this===this.#root||this.#root.#filledNegs&&this.#parent?.type==="!")){ret.push({})}return ret}isStart(){if(this.#root===this)return true;if(!this.#parent?.isStart())return false;if(this.#parentIndex===0)return true;const p=this.#parent;for(let i10=0;i10<this.#parentIndex;i10++){const pp3=p.#parts[i10];if(!(pp3 instanceof _a&&pp3.type==="!")){return false}}return true}isEnd(){if(this.#root===this)return true;if(this.#parent?.type==="!")return true;if(!this.#parent?.isEnd())return false;if(!this.type)return this.#parent?.isEnd();const pl2=this.#parent?this.#parent.#parts.length:0;return this.#parentIndex===pl2-1}copyIn(part){if(typeof part==="string")this.push(part);else this.push(part.clone(this))}clone(parent){const c=new _a(this.type,parent);for(const p of this.#parts){c.copyIn(p)}return c}static#parseAST(str,ast,pos,opt,extDepth){const maxDepth=opt.maxExtglobRecursion??2;let escaping=false;let inBrace=false;let braceStart=-1;let braceNeg=false;if(ast.type===null){let i11=pos;let acc2="";while(i11<str.length){const c=str.charAt(i11++);if(escaping||c==="\\"){escaping=!escaping;acc2+=c;continue}if(inBrace){if(i11===braceStart+1){if(c==="^"||c==="!"){braceNeg=true}}else if(c==="]"&&!(i11===braceStart+2&&braceNeg)){inBrace=false}acc2+=c;continue}else if(c==="["){inBrace=true;braceStart=i11;braceNeg=false;acc2+=c;continue}const doRecurse=!opt.noext&&isExtglobType(c)&&str.charAt(i11)==="("&&extDepth<=maxDepth;if(doRecurse){ast.push(acc2);acc2="";const ext2=new _a(c,ast);i11=_a.#parseAST(str,ext2,i11,opt,extDepth+1);ast.push(ext2);continue}acc2+=c}ast.push(acc2);return i11}let i10=pos+1;let part=new _a(null,ast);const parts=[];let acc="";while(i10<str.length){const c=str.charAt(i10++);if(escaping||c==="\\"){escaping=!escaping;acc+=c;continue}if(inBrace){if(i10===braceStart+1){if(c==="^"||c==="!"){braceNeg=true}}else if(c==="]"&&!(i10===braceStart+2&&braceNeg)){inBrace=false}acc+=c;continue}else if(c==="["){inBrace=true;braceStart=i10;braceNeg=false;acc+=c;continue}const doRecurse=!opt.noext&&isExtglobType(c)&&str.charAt(i10)==="("&&(extDepth<=maxDepth||ast&&ast.#canAdoptType(c));if(doRecurse){const depthAdd=ast&&ast.#canAdoptType(c)?0:1;part.push(acc);acc="";const ext2=new _a(c,part);part.push(ext2);i10=_a.#parseAST(str,ext2,i10,opt,extDepth+depthAdd);continue}if(c==="|"){part.push(acc);acc="";parts.push(part);part=new _a(null,ast);continue}if(c===")"){if(acc===""&&ast.#parts.length===0){ast.#emptyExt=true}part.push(acc);acc="";ast.push(...parts,part);return i10}acc+=c}ast.type=null;ast.#hasMagic=void 0;ast.#parts=[str.substring(pos-1)];return i10}#canAdoptWithSpace(child){return this.#canAdopt(child,adoptionWithSpaceMap)}#canAdopt(child,map=adoptionMap){if(!child||typeof child!=="object"||child.type!==null||child.#parts.length!==1||this.type===null){return false}const gc2=child.#parts[0];if(!gc2||typeof gc2!=="object"||gc2.type===null){return false}return this.#canAdoptType(gc2.type,map)}#canAdoptType(c,map=adoptionAnyMap){return!!map.get(this.type)?.includes(c)}#adoptWithSpace(child,index2){const gc2=child.#parts[0];const blank=new _a(null,gc2,this.options);blank.#parts.push("");gc2.push(blank);this.#adopt(child,index2)}#adopt(child,index2){const gc2=child.#parts[0];this.#parts.splice(index2,1,...gc2.#parts);for(const p of gc2.#parts){if(typeof p==="object")p.#parent=this}this.#toString=void 0}#canUsurpType(c){const m=usurpMap.get(this.type);return!!m?.has(c)}#canUsurp(child){if(!child||typeof child!=="object"||child.type!==null||child.#parts.length!==1||this.type===null||this.#parts.length!==1){return false}const gc2=child.#parts[0];if(!gc2||typeof gc2!=="object"||gc2.type===null){return false}return this.#canUsurpType(gc2.type)}#usurp(child){const m=usurpMap.get(this.type);const gc2=child.#parts[0];const nt2=m?.get(gc2.type);if(!nt2)return false;this.#parts=gc2.#parts;for(const p of this.#parts){if(typeof p==="object"){p.#parent=this}}this.type=nt2;this.#toString=void 0;this.#emptyExt=false}static fromGlob(pattern,options={}){const ast=new _a(null,void 0,options);_a.#parseAST(pattern,ast,0,options,0);return ast}toMMPattern(){if(this!==this.#root)return this.#root.toMMPattern();const glob=this.toString();const[re2,body,hasMagic,uflag]=this.toRegExpSource();const anyMagic=hasMagic||this.#hasMagic||this.#options.nocase&&!this.#options.nocaseMagicOnly&&glob.toUpperCase()!==glob.toLowerCase();if(!anyMagic){return body}const flags=(this.#options.nocase?"i":"")+(uflag?"u":"");return Object.assign(new RegExp(`^${re2}$`,flags),{_src:re2,_glob:glob})}get options(){return this.#options}toRegExpSource(allowDot){const dot=allowDot??!!this.#options.dot;if(this.#root===this){this.#flatten();this.#fillNegs()}if(!isExtglobAST(this)){const noEmpty=this.isStart()&&this.isEnd()&&!this.#parts.some(s10=>typeof s10!=="string");const src=this.#parts.map(p=>{const[re2,_,hasMagic,uflag]=typeof p==="string"?_a.#parseGlob(p,this.#hasMagic,noEmpty):p.toRegExpSource(allowDot);this.#hasMagic=this.#hasMagic||hasMagic;this.#uflag=this.#uflag||uflag;return re2}).join("");let start2="";if(this.isStart()){if(typeof this.#parts[0]==="string"){const dotTravAllowed=this.#parts.length===1&&justDots.has(this.#parts[0]);if(!dotTravAllowed){const aps=addPatternStart;const needNoTrav=dot&&aps.has(src.charAt(0))||src.startsWith("\\.")&&aps.has(src.charAt(2))||src.startsWith("\\.\\.")&&aps.has(src.charAt(4));const needNoDot=!dot&&!allowDot&&aps.has(src.charAt(0));start2=needNoTrav?startNoTraversal:needNoDot?startNoDot:""}}}let end="";if(this.isEnd()&&this.#root.#filledNegs&&this.#parent?.type==="!"){end="(?:$|\\/)"}const final2=start2+src+end;return[final2,unescape(src),this.#hasMagic=!!this.#hasMagic,this.#uflag]}const repeated=this.type==="*"||this.type==="+";const start=this.type==="!"?"(?:(?!(?:":"(?:";let body=this.#partsToRegExp(dot);if(this.isStart()&&this.isEnd()&&!body&&this.type!=="!"){const s10=this.toString();const me=this;me.#parts=[s10];me.type=null;me.#hasMagic=void 0;return[s10,unescape(this.toString()),false,false]}let bodyDotAllowed=!repeated||allowDot||dot||!startNoDot?"":this.#partsToRegExp(true);if(bodyDotAllowed===body){bodyDotAllowed=""}if(bodyDotAllowed){body=`(?:${body})(?:${bodyDotAllowed})*?`}let final="";if(this.type==="!"&&this.#emptyExt){final=(this.isStart()&&!dot?startNoDot:"")+starNoEmpty}else{const close2=this.type==="!"?"))"+(this.isStart()&&!dot&&!allowDot?startNoDot:"")+star+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&bodyDotAllowed?")":this.type==="*"&&bodyDotAllowed?`)?`:`)${this.type}`;final=start+body+close2}return[final,unescape(body),this.#hasMagic=!!this.#hasMagic,this.#uflag]}#flatten(){if(!isExtglobAST(this)){for(const p of this.#parts){if(typeof p==="object"){p.#flatten()}}}else{let iterations=0;let done=false;do{done=true;for(let i10=0;i10<this.#parts.length;i10++){const c=this.#parts[i10];if(typeof c==="object"){c.#flatten();if(this.#canAdopt(c)){done=false;this.#adopt(c,i10)}else if(this.#canAdoptWithSpace(c)){done=false;this.#adoptWithSpace(c,i10)}else if(this.#canUsurp(c)){done=false;this.#usurp(c)}}}}while(!done&&++iterations<10)}this.#toString=void 0}#partsToRegExp(dot){return this.#parts.map(p=>{if(typeof p==="string"){throw new Error("string type in extglob ast??")}const[re2,_,_hasMagic,uflag]=p.toRegExpSource(dot);this.#uflag=this.#uflag||uflag;return re2}).filter(p=>!(this.isStart()&&this.isEnd())||!!p).join("|")}static#parseGlob(glob,hasMagic,noEmpty=false){let escaping=false;let re2="";let uflag=false;let inStar=false;for(let i10=0;i10<glob.length;i10++){const c=glob.charAt(i10);if(escaping){escaping=false;re2+=(reSpecials.has(c)?"\\":"")+c;continue}if(c==="*"){if(inStar)continue;inStar=true;re2+=noEmpty&&/^[*]+$/.test(glob)?starNoEmpty:star;hasMagic=true;continue}else{inStar=false}if(c==="\\"){if(i10===glob.length-1){re2+="\\\\"}else{escaping=true}continue}if(c==="["){const[src,needUflag,consumed,magic]=parseClass(glob,i10);if(consumed){re2+=src;uflag=uflag||needUflag;i10+=consumed-1;hasMagic=hasMagic||magic;continue}}if(c==="?"){re2+=qmark;hasMagic=true;continue}re2+=regExpEscape(c)}return[re2,unescape(glob),!!hasMagic,uflag]}};_a=AST;var escape=(s10,{windowsPathsNoEscape=false,magicalBraces=false}={})=>{if(magicalBraces){return windowsPathsNoEscape?s10.replace(/[?*()[\]{}]/g,"[$&]"):s10.replace(/[?*()[\]\\{}]/g,"\\$&")}return windowsPathsNoEscape?s10.replace(/[?*()[\]]/g,"[$&]"):s10.replace(/[?*()[\]\\]/g,"\\$&")};var minimatch=(p,pattern,options={})=>{assertValidPattern(pattern);if(!options.nocomment&&pattern.charAt(0)==="#"){return false}return new Minimatch(pattern,options).match(p)};var starDotExtRE=/^\*+([^+@!?*[(]*)$/;var starDotExtTest=ext2=>f10=>!f10.startsWith(".")&&f10.endsWith(ext2);var starDotExtTestDot=ext2=>f10=>f10.endsWith(ext2);var starDotExtTestNocase=ext2=>{ext2=ext2.toLowerCase();return f10=>!f10.startsWith(".")&&f10.toLowerCase().endsWith(ext2)};var starDotExtTestNocaseDot=ext2=>{ext2=ext2.toLowerCase();return f10=>f10.toLowerCase().endsWith(ext2)};var starDotStarRE=/^\*+\.\*+$/;var starDotStarTest=f10=>!f10.startsWith(".")&&f10.includes(".");var starDotStarTestDot=f10=>f10!=="."&&f10!==".."&&f10.includes(".");var dotStarRE=/^\.\*+$/;var dotStarTest=f10=>f10!=="."&&f10!==".."&&f10.startsWith(".");var starRE=/^\*+$/;var starTest=f10=>f10.length!==0&&!f10.startsWith(".");var starTestDot=f10=>f10.length!==0&&f10!=="."&&f10!=="..";var qmarksRE=/^\?+([^+@!?*[(]*)?$/;var qmarksTestNocase=([$02,ext2=""])=>{const noext=qmarksTestNoExt([$02]);if(!ext2)return noext;ext2=ext2.toLowerCase();return f10=>noext(f10)&&f10.toLowerCase().endsWith(ext2)};var qmarksTestNocaseDot=([$02,ext2=""])=>{const noext=qmarksTestNoExtDot([$02]);if(!ext2)return noext;ext2=ext2.toLowerCase();return f10=>noext(f10)&&f10.toLowerCase().endsWith(ext2)};var qmarksTestDot=([$02,ext2=""])=>{const noext=qmarksTestNoExtDot([$02]);return!ext2?noext:f10=>noext(f10)&&f10.endsWith(ext2)};var qmarksTest=([$02,ext2=""])=>{const noext=qmarksTestNoExt([$02]);return!ext2?noext:f10=>noext(f10)&&f10.endsWith(ext2)};var qmarksTestNoExt=([$02])=>{const len2=$02.length;return f10=>f10.length===len2&&!f10.startsWith(".")};var qmarksTestNoExtDot=([$02])=>{const len2=$02.length;return f10=>f10.length===len2&&f10!=="."&&f10!==".."};var defaultPlatform=typeof process==="object"&&process?typeof process.env==="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix";var path={win32:{sep:"\\"},posix:{sep:"/"}};var sep=defaultPlatform==="win32"?path.win32.sep:path.posix.sep;minimatch.sep=sep;var GLOBSTAR=Symbol("globstar **");minimatch.GLOBSTAR=GLOBSTAR;var qmark2="[^/]";var star2=qmark2+"*?";var twoStarDot="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";var twoStarNoDot="(?:(?!(?:\\/|^)\\.).)*?";var filter=(pattern,options={})=>p=>minimatch(p,pattern,options);minimatch.filter=filter;var ext=(a,b={})=>Object.assign({},a,b);var defaults=def=>{if(!def||typeof def!=="object"||!Object.keys(def).length){return minimatch}const orig=minimatch;const m=(p,pattern,options={})=>orig(p,pattern,ext(def,options));return Object.assign(m,{Minimatch:class Minimatch extends orig.Minimatch{constructor(pattern,options={}){super(pattern,ext(def,options))}static defaults(options){return orig.defaults(ext(def,options)).Minimatch}},AST:class AST extends orig.AST{constructor(type2,parent,options={}){super(type2,parent,ext(def,options))}static fromGlob(pattern,options={}){return orig.AST.fromGlob(pattern,ext(def,options))}},unescape:(s10,options={})=>orig.unescape(s10,ext(def,options)),escape:(s10,options={})=>orig.escape(s10,ext(def,options)),filter:(pattern,options={})=>orig.filter(pattern,ext(def,options)),defaults:options=>orig.defaults(ext(def,options)),makeRe:(pattern,options={})=>orig.makeRe(pattern,ext(def,options)),braceExpand:(pattern,options={})=>orig.braceExpand(pattern,ext(def,options)),match:(list2,pattern,options={})=>orig.match(list2,pattern,ext(def,options)),sep:orig.sep,GLOBSTAR})};minimatch.defaults=defaults;var braceExpand=(pattern,options={})=>{assertValidPattern(pattern);if(options.nobrace||!/\{(?:(?!\{).)*\}/.test(pattern)){return[pattern]}return expand(pattern,{max:options.braceExpandMax})};minimatch.braceExpand=braceExpand;var makeRe=(pattern,options={})=>new Minimatch(pattern,options).makeRe();minimatch.makeRe=makeRe;var match=(list2,pattern,options={})=>{const mm2=new Minimatch(pattern,options);list2=list2.filter(f10=>mm2.match(f10));if(mm2.options.nonull&&!list2.length){list2.push(pattern)}return list2};minimatch.match=match;var globMagic=/[?*]|[+@!]\(.*?\)|\[|\]/;var regExpEscape2=s10=>s10.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");var Minimatch=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(pattern,options={}){assertValidPattern(pattern);options=options||{};this.options=options;this.maxGlobstarRecursion=options.maxGlobstarRecursion??200;this.pattern=pattern;this.platform=options.platform||defaultPlatform;this.isWindows=this.platform==="win32";const awe="allowWindowsEscape";this.windowsPathsNoEscape=!!options.windowsPathsNoEscape||options[awe]===false;if(this.windowsPathsNoEscape){this.pattern=this.pattern.replace(/\\/g,"/")}this.preserveMultipleSlashes=!!options.preserveMultipleSlashes;this.regexp=null;this.negate=false;this.nonegate=!!options.nonegate;this.comment=false;this.empty=false;this.partial=!!options.partial;this.nocase=!!this.options.nocase;this.windowsNoMagicRoot=options.windowsNoMagicRoot!==void 0?options.windowsNoMagicRoot:!!(this.isWindows&&this.nocase);this.globSet=[];this.globParts=[];this.set=[];this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1){return true}for(const pattern of this.set){for(const part of pattern){if(typeof part!=="string")return true}}return false}debug(..._){}make(){const pattern=this.pattern;const options=this.options;if(!options.nocomment&&pattern.charAt(0)==="#"){this.comment=true;return}if(!pattern){this.empty=true;return}this.parseNegate();this.globSet=[...new Set(this.braceExpand())];if(options.debug){this.debug=(...args)=>console.error(...args)}this.debug(this.pattern,this.globSet);const rawGlobParts=this.globSet.map(s10=>this.slashSplit(s10));this.globParts=this.preprocess(rawGlobParts);this.debug(this.pattern,this.globParts);let set=this.globParts.map((s10,_,__)=>{if(this.isWindows&&this.windowsNoMagicRoot){const isUNC=s10[0]===""&&s10[1]===""&&(s10[2]==="?"||!globMagic.test(s10[2]))&&!globMagic.test(s10[3]);const isDrive=/^[a-z]:/i.test(s10[0]);if(isUNC){return[...s10.slice(0,4),...s10.slice(4).map(ss2=>this.parse(ss2))]}else if(isDrive){return[s10[0],...s10.slice(1).map(ss2=>this.parse(ss2))]}}return s10.map(ss2=>this.parse(ss2))});this.debug(this.pattern,set);this.set=set.filter(s10=>s10.indexOf(false)===-1);if(this.isWindows){for(let i10=0;i10<this.set.length;i10++){const p=this.set[i10];if(p[0]===""&&p[1]===""&&this.globParts[i10][2]==="?"&&typeof p[3]==="string"&&/^[a-z]:$/i.test(p[3])){p[2]="?"}}}this.debug(this.pattern,this.set)}preprocess(globParts){if(this.options.noglobstar){for(const partset of globParts){for(let j=0;j<partset.length;j++){if(partset[j]==="**"){partset[j]="*"}}}}const{optimizationLevel=1}=this.options;if(optimizationLevel>=2){globParts=this.firstPhasePreProcess(globParts);globParts=this.secondPhasePreProcess(globParts)}else if(optimizationLevel>=1){globParts=this.levelOneOptimize(globParts)}else{globParts=this.adjascentGlobstarOptimize(globParts)}return globParts}adjascentGlobstarOptimize(globParts){return globParts.map(parts=>{let gs2=-1;while(-1!==(gs2=parts.indexOf("**",gs2+1))){let i10=gs2;while(parts[i10+1]==="**"){i10++}if(i10!==gs2){parts.splice(gs2,i10-gs2)}}return parts})}levelOneOptimize(globParts){return globParts.map(parts=>{parts=parts.reduce((set,part)=>{const prev=set[set.length-1];if(part==="**"&&prev==="**"){return set}if(part===".."){if(prev&&prev!==".."&&prev!=="."&&prev!=="**"){set.pop();return set}}set.push(part);return set},[]);return parts.length===0?[""]:parts})}levelTwoFileOptimize(parts){if(!Array.isArray(parts)){parts=this.slashSplit(parts)}let didSomething=false;do{didSomething=false;if(!this.preserveMultipleSlashes){for(let i10=1;i10<parts.length-1;i10++){const p=parts[i10];if(i10===1&&p===""&&parts[0]==="")continue;if(p==="."||p===""){didSomething=true;parts.splice(i10,1);i10--}}if(parts[0]==="."&&parts.length===2&&(parts[1]==="."||parts[1]==="")){didSomething=true;parts.pop()}}let dd2=0;while(-1!==(dd2=parts.indexOf("..",dd2+1))){const p=parts[dd2-1];if(p&&p!=="."&&p!==".."&&p!=="**"&&!(this.isWindows&&/^[a-z]:$/i.test(p))){didSomething=true;parts.splice(dd2-1,2);dd2-=2}}}while(didSomething);return parts.length===0?[""]:parts}firstPhasePreProcess(globParts){let didSomething=false;do{didSomething=false;for(let parts of globParts){let gs2=-1;while(-1!==(gs2=parts.indexOf("**",gs2+1))){let gss=gs2;while(parts[gss+1]==="**"){gss++}if(gss>gs2){parts.splice(gs2+1,gss-gs2)}let next2=parts[gs2+1];const p=parts[gs2+2];const p22=parts[gs2+3];if(next2!=="..")continue;if(!p||p==="."||p===".."||!p22||p22==="."||p22===".."){continue}didSomething=true;parts.splice(gs2,1);const other=parts.slice(0);other[gs2]="**";globParts.push(other);gs2--}if(!this.preserveMultipleSlashes){for(let i10=1;i10<parts.length-1;i10++){const p=parts[i10];if(i10===1&&p===""&&parts[0]==="")continue;if(p==="."||p===""){didSomething=true;parts.splice(i10,1);i10--}}if(parts[0]==="."&&parts.length===2&&(parts[1]==="."||parts[1]==="")){didSomething=true;parts.pop()}}let dd2=0;while(-1!==(dd2=parts.indexOf("..",dd2+1))){const p=parts[dd2-1];if(p&&p!=="."&&p!==".."&&p!=="**"){didSomething=true;const needDot=dd2===1&&parts[dd2+1]==="**";const splin=needDot?["."]:[];parts.splice(dd2-1,2,...splin);if(parts.length===0)parts.push("");dd2-=2}}}}while(didSomething);return globParts}secondPhasePreProcess(globParts){for(let i10=0;i10<globParts.length-1;i10++){for(let j=i10+1;j<globParts.length;j++){const matched=this.partsMatch(globParts[i10],globParts[j],!this.preserveMultipleSlashes);if(matched){globParts[i10]=[];globParts[j]=matched;break}}}return globParts.filter(gs2=>gs2.length)}partsMatch(a,b,emptyGSMatch=false){let ai2=0;let bi2=0;let result=[];let which="";while(ai2<a.length&&bi2<b.length){if(a[ai2]===b[bi2]){result.push(which==="b"?b[bi2]:a[ai2]);ai2++;bi2++}else if(emptyGSMatch&&a[ai2]==="**"&&b[bi2]===a[ai2+1]){result.push(a[ai2]);ai2++}else if(emptyGSMatch&&b[bi2]==="**"&&a[ai2]===b[bi2+1]){result.push(b[bi2]);bi2++}else if(a[ai2]==="*"&&b[bi2]&&(this.options.dot||!b[bi2].startsWith("."))&&b[bi2]!=="**"){if(which==="b")return false;which="a";result.push(a[ai2]);ai2++;bi2++}else if(b[bi2]==="*"&&a[ai2]&&(this.options.dot||!a[ai2].startsWith("."))&&a[ai2]!=="**"){if(which==="a")return false;which="b";result.push(b[bi2]);ai2++;bi2++}else{return false}}return a.length===b.length&&result}parseNegate(){if(this.nonegate)return;const pattern=this.pattern;let negate=false;let negateOffset=0;for(let i10=0;i10<pattern.length&&pattern.charAt(i10)==="!";i10++){negate=!negate;negateOffset++}if(negateOffset)this.pattern=pattern.slice(negateOffset);this.negate=negate}matchOne(file2,pattern,partial=false){let fileStartIndex=0;let patternStartIndex=0;if(this.isWindows){const fileDrive=typeof file2[0]==="string"&&/^[a-z]:$/i.test(file2[0]);const fileUNC=!fileDrive&&file2[0]===""&&file2[1]===""&&file2[2]==="?"&&/^[a-z]:$/i.test(file2[3]);const patternDrive=typeof pattern[0]==="string"&&/^[a-z]:$/i.test(pattern[0]);const patternUNC=!patternDrive&&pattern[0]===""&&pattern[1]===""&&pattern[2]==="?"&&typeof pattern[3]==="string"&&/^[a-z]:$/i.test(pattern[3]);const fdi=fileUNC?3:fileDrive?0:void 0;const pdi=patternUNC?3:patternDrive?0:void 0;if(typeof fdi==="number"&&typeof pdi==="number"){const[fd2,pd2]=[file2[fdi],pattern[pdi]];if(fd2.toLowerCase()===pd2.toLowerCase()){pattern[pdi]=fd2;patternStartIndex=pdi;fileStartIndex=fdi}}}const{optimizationLevel=1}=this.options;if(optimizationLevel>=2){file2=this.levelTwoFileOptimize(file2)}if(pattern.includes(GLOBSTAR)){return this.#matchGlobstar(file2,pattern,partial,fileStartIndex,patternStartIndex)}return this.#matchOne(file2,pattern,partial,fileStartIndex,patternStartIndex)}#matchGlobstar(file2,pattern,partial,fileIndex,patternIndex){const firstgs=pattern.indexOf(GLOBSTAR,patternIndex);const lastgs=pattern.lastIndexOf(GLOBSTAR);const[head,body,tail]=partial?[pattern.slice(patternIndex,firstgs),pattern.slice(firstgs+1),[]]:[pattern.slice(patternIndex,firstgs),pattern.slice(firstgs+1,lastgs),pattern.slice(lastgs+1)];if(head.length){const fileHead=file2.slice(fileIndex,fileIndex+head.length);if(!this.#matchOne(fileHead,head,partial,0,0)){return false}fileIndex+=head.length;patternIndex+=head.length}let fileTailMatch=0;if(tail.length){if(tail.length+fileIndex>file2.length)return false;let tailStart=file2.length-tail.length;if(this.#matchOne(file2,tail,partial,tailStart,0)){fileTailMatch=tail.length}else{if(file2[file2.length-1]!==""||fileIndex+tail.length===file2.length){return false}tailStart--;if(!this.#matchOne(file2,tail,partial,tailStart,0)){return false}fileTailMatch=tail.length+1}}if(!body.length){let sawSome=!!fileTailMatch;for(let i11=fileIndex;i11<file2.length-fileTailMatch;i11++){const f10=String(file2[i11]);sawSome=true;if(f10==="."||f10===".."||!this.options.dot&&f10.startsWith(".")){return false}}return partial||sawSome}const bodySegments=[[[],0]];let currentBody=bodySegments[0];let nonGsParts=0;const nonGsPartsSums=[0];for(const b of body){if(b===GLOBSTAR){nonGsPartsSums.push(nonGsParts);currentBody=[[],0];bodySegments.push(currentBody)}else{currentBody[0].push(b);nonGsParts++}}let i10=bodySegments.length-1;const fileLength=file2.length-fileTailMatch;for(const b of bodySegments){b[1]=fileLength-(nonGsPartsSums[i10--]+b[0].length)}return!!this.#matchGlobStarBodySections(file2,bodySegments,fileIndex,0,partial,0,!!fileTailMatch)}#matchGlobStarBodySections(file2,bodySegments,fileIndex,bodyIndex,partial,globStarDepth,sawTail){const bs2=bodySegments[bodyIndex];if(!bs2){for(let i10=fileIndex;i10<file2.length;i10++){sawTail=true;const f10=file2[i10];if(f10==="."||f10===".."||!this.options.dot&&f10.startsWith(".")){return false}}return sawTail}const[body,after]=bs2;while(fileIndex<=after){const m=this.#matchOne(file2.slice(0,fileIndex+body.length),body,partial,fileIndex,0);if(m&&globStarDepth<this.maxGlobstarRecursion){const sub=this.#matchGlobStarBodySections(file2,bodySegments,fileIndex+body.length,bodyIndex+1,partial,globStarDepth+1,sawTail);if(sub!==false){return sub}}const f10=file2[fileIndex];if(f10==="."||f10===".."||!this.options.dot&&f10.startsWith(".")){return false}fileIndex++}return partial||null}#matchOne(file2,pattern,partial,fileIndex,patternIndex){let fi2;let pi2;let pl2;let fl2;for(fi2=fileIndex,pi2=patternIndex,fl2=file2.length,pl2=pattern.length;fi2<fl2&&pi2<pl2;fi2++,pi2++){this.debug("matchOne loop");let p=pattern[pi2];let f10=file2[fi2];this.debug(pattern,p,f10);if(p===false||p===GLOBSTAR){return false}let hit;if(typeof p==="string"){hit=f10===p;this.debug("string match",p,f10,hit)}else{hit=p.test(f10);this.debug("pattern match",p,f10,hit)}if(!hit)return false}if(fi2===fl2&&pi2===pl2){return true}else if(fi2===fl2){return partial}else if(pi2===pl2){return fi2===fl2-1&&file2[fi2]===""}else{throw new Error("wtf?")}}braceExpand(){return braceExpand(this.pattern,this.options)}parse(pattern){assertValidPattern(pattern);const options=this.options;if(pattern==="**")return GLOBSTAR;if(pattern==="")return"";let m;let fastTest=null;if(m=pattern.match(starRE)){fastTest=options.dot?starTestDot:starTest}else if(m=pattern.match(starDotExtRE)){fastTest=(options.nocase?options.dot?starDotExtTestNocaseDot:starDotExtTestNocase:options.dot?starDotExtTestDot:starDotExtTest)(m[1])}else if(m=pattern.match(qmarksRE)){fastTest=(options.nocase?options.dot?qmarksTestNocaseDot:qmarksTestNocase:options.dot?qmarksTestDot:qmarksTest)(m)}else if(m=pattern.match(starDotStarRE)){fastTest=options.dot?starDotStarTestDot:starDotStarTest}else if(m=pattern.match(dotStarRE)){fastTest=dotStarTest}const re2=AST.fromGlob(pattern,this.options).toMMPattern();if(fastTest&&typeof re2==="object"){Reflect.defineProperty(re2,"test",{value:fastTest})}return re2}makeRe(){if(this.regexp||this.regexp===false)return this.regexp;const set=this.set;if(!set.length){this.regexp=false;return this.regexp}const options=this.options;const twoStar=options.noglobstar?star2:options.dot?twoStarDot:twoStarNoDot;const flags=new Set(options.nocase?["i"]:[]);let re2=set.map(pattern=>{const pp3=pattern.map(p=>{if(p instanceof RegExp){for(const f10 of p.flags.split(""))flags.add(f10)}return typeof p==="string"?regExpEscape2(p):p===GLOBSTAR?GLOBSTAR:p._src});pp3.forEach((p,i10)=>{const next2=pp3[i10+1];const prev=pp3[i10-1];if(p!==GLOBSTAR||prev===GLOBSTAR){return}if(prev===void 0){if(next2!==void 0&&next2!==GLOBSTAR){pp3[i10+1]="(?:\\/|"+twoStar+"\\/)?"+next2}else{pp3[i10]=twoStar}}else if(next2===void 0){pp3[i10-1]=prev+"(?:\\/|\\/"+twoStar+")?"}else if(next2!==GLOBSTAR){pp3[i10-1]=prev+"(?:\\/|\\/"+twoStar+"\\/)"+next2;pp3[i10+1]=GLOBSTAR}});const filtered=pp3.filter(p=>p!==GLOBSTAR);if(this.partial&&filtered.length>=1){const prefixes=[];for(let i10=1;i10<=filtered.length;i10++){prefixes.push(filtered.slice(0,i10).join("/"))}return"(?:"+prefixes.join("|")+")"}return filtered.join("/")}).join("|");const[open2,close2]=set.length>1?["(?:",")"]:["",""];re2="^"+open2+re2+close2+"$";if(this.partial){re2="^(?:\\/|"+open2+re2.slice(1,-1)+close2+")$"}if(this.negate)re2="^(?!"+re2+").+$";try{this.regexp=new RegExp(re2,[...flags].join(""))}catch{this.regexp=false}return this.regexp}slashSplit(p){if(this.preserveMultipleSlashes){return p.split("/")}else if(this.isWindows&&/^\/\/[^/]+/.test(p)){return["",...p.split(/\/+/)]}else{return p.split(/\/+/)}}match(f10,partial=this.partial){this.debug("match",f10,this.pattern);if(this.comment){return false}if(this.empty){return f10===""}if(f10==="/"&&partial){return true}const options=this.options;if(this.isWindows){f10=f10.split("\\").join("/")}const ff2=this.slashSplit(f10);this.debug(this.pattern,"split",ff2);const set=this.set;this.debug(this.pattern,"set",set);let filename=ff2[ff2.length-1];if(!filename){for(let i10=ff2.length-2;!filename&&i10>=0;i10--){filename=ff2[i10]}}for(const pattern of set){let file2=ff2;if(options.matchBase&&pattern.length===1){file2=[filename]}const hit=this.matchOne(file2,pattern,partial);if(hit){if(options.flipNegate){return true}return!this.negate}}if(options.flipNegate){return false}return this.negate}static defaults(def){return minimatch.defaults(def).Minimatch}};minimatch.AST=AST;minimatch.Minimatch=Minimatch;minimatch.escape=escape;minimatch.unescape=unescape;var Z_FIXED$1=4;var Z_BINARY=0;var Z_TEXT=1;var Z_UNKNOWN$1=2;function zero$1(buf){let len2=buf.length;while(--len2>=0){buf[len2]=0}}var STORED_BLOCK=0;var STATIC_TREES=1;var DYN_TREES=2;var MIN_MATCH$1=3;var MAX_MATCH$1=258;var LENGTH_CODES$1=29;var LITERALS$1=256;var L_CODES$1=LITERALS$1+1+LENGTH_CODES$1;var D_CODES$1=30;var BL_CODES$1=19;var HEAP_SIZE$1=2*L_CODES$1+1;var MAX_BITS$1=15;var Buf_size=16;var MAX_BL_BITS=7;var END_BLOCK=256;var REP_3_6=16;var REPZ_3_10=17;var REPZ_11_138=18;var extra_lbits=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]);var extra_dbits=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]);var extra_blbits=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]);var bl_order=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);var DIST_CODE_LEN=512;var static_ltree=new Array((L_CODES$1+2)*2);zero$1(static_ltree);var static_dtree=new Array(D_CODES$1*2);zero$1(static_dtree);var _dist_code=new Array(DIST_CODE_LEN);zero$1(_dist_code);var _length_code=new Array(MAX_MATCH$1-MIN_MATCH$1+1);zero$1(_length_code);var base_length=new Array(LENGTH_CODES$1);zero$1(base_length);var base_dist=new Array(D_CODES$1);zero$1(base_dist);function StaticTreeDesc(static_tree,extra_bits,extra_base,elems,max_length){this.static_tree=static_tree;this.extra_bits=extra_bits;this.extra_base=extra_base;this.elems=elems;this.max_length=max_length;this.has_stree=static_tree&&static_tree.length}var static_l_desc;var static_d_desc;var static_bl_desc;function TreeDesc(dyn_tree,stat_desc){this.dyn_tree=dyn_tree;this.max_code=0;this.stat_desc=stat_desc}var d_code=dist=>{return dist<256?_dist_code[dist]:_dist_code[256+(dist>>>7)]};var put_short=(s10,w)=>{s10.pending_buf[s10.pending++]=w&255;s10.pending_buf[s10.pending++]=w>>>8&255};var send_bits=(s10,value,length)=>{if(s10.bi_valid>Buf_size-length){s10.bi_buf|=value<<s10.bi_valid&65535;put_short(s10,s10.bi_buf);s10.bi_buf=value>>Buf_size-s10.bi_valid;s10.bi_valid+=length-Buf_size}else{s10.bi_buf|=value<<s10.bi_valid&65535;s10.bi_valid+=length}};var send_code=(s10,c,tree2)=>{send_bits(s10,tree2[c*2],tree2[c*2+1])};var bi_reverse=(code3,len2)=>{let res=0;do{res|=code3&1;code3>>>=1;res<<=1}while(--len2>0);return res>>>1};var bi_flush=s10=>{if(s10.bi_valid===16){put_short(s10,s10.bi_buf);s10.bi_buf=0;s10.bi_valid=0}else if(s10.bi_valid>=8){s10.pending_buf[s10.pending++]=s10.bi_buf&255;s10.bi_buf>>=8;s10.bi_valid-=8}};var gen_bitlen=(s10,desc)=>{const tree2=desc.dyn_tree;const max_code=desc.max_code;const stree=desc.stat_desc.static_tree;const has_stree=desc.stat_desc.has_stree;const extra=desc.stat_desc.extra_bits;const base=desc.stat_desc.extra_base;const max_length=desc.stat_desc.max_length;let h;let n8,m;let bits;let xbits;let f10;let overflow=0;for(bits=0;bits<=MAX_BITS$1;bits++){s10.bl_count[bits]=0}tree2[s10.heap[s10.heap_max]*2+1]=0;for(h=s10.heap_max+1;h<HEAP_SIZE$1;h++){n8=s10.heap[h];bits=tree2[tree2[n8*2+1]*2+1]+1;if(bits>max_length){bits=max_length;overflow++}tree2[n8*2+1]=bits;if(n8>max_code){continue}s10.bl_count[bits]++;xbits=0;if(n8>=base){xbits=extra[n8-base]}f10=tree2[n8*2];s10.opt_len+=f10*(bits+xbits);if(has_stree){s10.static_len+=f10*(stree[n8*2+1]+xbits)}}if(overflow===0){return}do{bits=max_length-1;while(s10.bl_count[bits]===0){bits--}s10.bl_count[bits]--;s10.bl_count[bits+1]+=2;s10.bl_count[max_length]--;overflow-=2}while(overflow>0);for(bits=max_length;bits!==0;bits--){n8=s10.bl_count[bits];while(n8!==0){m=s10.heap[--h];if(m>max_code){continue}if(tree2[m*2+1]!==bits){s10.opt_len+=(bits-tree2[m*2+1])*tree2[m*2];tree2[m*2+1]=bits}n8--}}};var gen_codes=(tree2,max_code,bl_count)=>{const next_code=new Array(MAX_BITS$1+1);let code3=0;let bits;let n8;for(bits=1;bits<=MAX_BITS$1;bits++){code3=code3+bl_count[bits-1]<<1;next_code[bits]=code3}for(n8=0;n8<=max_code;n8++){let len2=tree2[n8*2+1];if(len2===0){continue}tree2[n8*2]=bi_reverse(next_code[len2]++,len2)}};var tr_static_init=()=>{let n8;let bits;let length;let code3;let dist;const bl_count=new Array(MAX_BITS$1+1);length=0;for(code3=0;code3<LENGTH_CODES$1-1;code3++){base_length[code3]=length;for(n8=0;n8<1<<extra_lbits[code3];n8++){_length_code[length++]=code3}}_length_code[length-1]=code3;dist=0;for(code3=0;code3<16;code3++){base_dist[code3]=dist;for(n8=0;n8<1<<extra_dbits[code3];n8++){_dist_code[dist++]=code3}}dist>>=7;for(;code3<D_CODES$1;code3++){base_dist[code3]=dist<<7;for(n8=0;n8<1<<extra_dbits[code3]-7;n8++){_dist_code[256+dist++]=code3}}for(bits=0;bits<=MAX_BITS$1;bits++){bl_count[bits]=0}n8=0;while(n8<=143){static_ltree[n8*2+1]=8;n8++;bl_count[8]++}while(n8<=255){static_ltree[n8*2+1]=9;n8++;bl_count[9]++}while(n8<=279){static_ltree[n8*2+1]=7;n8++;bl_count[7]++}while(n8<=287){static_ltree[n8*2+1]=8;n8++;bl_count[8]++}gen_codes(static_ltree,L_CODES$1+1,bl_count);for(n8=0;n8<D_CODES$1;n8++){static_dtree[n8*2+1]=5;static_dtree[n8*2]=bi_reverse(n8,5)}static_l_desc=new StaticTreeDesc(static_ltree,extra_lbits,LITERALS$1+1,L_CODES$1,MAX_BITS$1);static_d_desc=new StaticTreeDesc(static_dtree,extra_dbits,0,D_CODES$1,MAX_BITS$1);static_bl_desc=new StaticTreeDesc(new Array(0),extra_blbits,0,BL_CODES$1,MAX_BL_BITS)};var init_block=s10=>{let n8;for(n8=0;n8<L_CODES$1;n8++){s10.dyn_ltree[n8*2]=0}for(n8=0;n8<D_CODES$1;n8++){s10.dyn_dtree[n8*2]=0}for(n8=0;n8<BL_CODES$1;n8++){s10.bl_tree[n8*2]=0}s10.dyn_ltree[END_BLOCK*2]=1;s10.opt_len=s10.static_len=0;s10.sym_next=s10.matches=0};var bi_windup=s10=>{if(s10.bi_valid>8){put_short(s10,s10.bi_buf)}else if(s10.bi_valid>0){s10.pending_buf[s10.pending++]=s10.bi_buf}s10.bi_buf=0;s10.bi_valid=0};var smaller=(tree2,n8,m,depth4)=>{const _n2=n8*2;const _m2=m*2;return tree2[_n2]<tree2[_m2]||tree2[_n2]===tree2[_m2]&&depth4[n8]<=depth4[m]};var pqdownheap=(s10,tree2,k10)=>{const v2=s10.heap[k10];let j=k10<<1;while(j<=s10.heap_len){if(j<s10.heap_len&&smaller(tree2,s10.heap[j+1],s10.heap[j],s10.depth)){j++}if(smaller(tree2,v2,s10.heap[j],s10.depth)){break}s10.heap[k10]=s10.heap[j];k10=j;j<<=1}s10.heap[k10]=v2};var compress_block=(s10,ltree,dtree)=>{let dist;let lc2;let sx2=0;let code3;let extra;if(s10.sym_next!==0){do{dist=s10.pending_buf[s10.sym_buf+sx2++]&255;dist+=(s10.pending_buf[s10.sym_buf+sx2++]&255)<<8;lc2=s10.pending_buf[s10.sym_buf+sx2++];if(dist===0){send_code(s10,lc2,ltree)}else{code3=_length_code[lc2];send_code(s10,code3+LITERALS$1+1,ltree);extra=extra_lbits[code3];if(extra!==0){lc2-=base_length[code3];send_bits(s10,lc2,extra)}dist--;code3=d_code(dist);send_code(s10,code3,dtree);extra=extra_dbits[code3];if(extra!==0){dist-=base_dist[code3];send_bits(s10,dist,extra)}}}while(sx2<s10.sym_next)}send_code(s10,END_BLOCK,ltree)};var build_tree=(s10,desc)=>{const tree2=desc.dyn_tree;const stree=desc.stat_desc.static_tree;const has_stree=desc.stat_desc.has_stree;const elems=desc.stat_desc.elems;let n8,m;let max_code=-1;let node;s10.heap_len=0;s10.heap_max=HEAP_SIZE$1;for(n8=0;n8<elems;n8++){if(tree2[n8*2]!==0){s10.heap[++s10.heap_len]=max_code=n8;s10.depth[n8]=0}else{tree2[n8*2+1]=0}}while(s10.heap_len<2){node=s10.heap[++s10.heap_len]=max_code<2?++max_code:0;tree2[node*2]=1;s10.depth[node]=0;s10.opt_len--;if(has_stree){s10.static_len-=stree[node*2+1]}}desc.max_code=max_code;for(n8=s10.heap_len>>1;n8>=1;n8--){pqdownheap(s10,tree2,n8)}node=elems;do{n8=s10.heap[1];s10.heap[1]=s10.heap[s10.heap_len--];pqdownheap(s10,tree2,1);m=s10.heap[1];s10.heap[--s10.heap_max]=n8;s10.heap[--s10.heap_max]=m;tree2[node*2]=tree2[n8*2]+tree2[m*2];s10.depth[node]=(s10.depth[n8]>=s10.depth[m]?s10.depth[n8]:s10.depth[m])+1;tree2[n8*2+1]=tree2[m*2+1]=node;s10.heap[1]=node++;pqdownheap(s10,tree2,1)}while(s10.heap_len>=2);s10.heap[--s10.heap_max]=s10.heap[1];gen_bitlen(s10,desc);gen_codes(tree2,max_code,s10.bl_count)};var scan_tree=(s10,tree2,max_code)=>{let n8;let prevlen=-1;let curlen;let nextlen=tree2[0*2+1];let count=0;let max_count=7;let min_count=4;if(nextlen===0){max_count=138;min_count=3}tree2[(max_code+1)*2+1]=65535;for(n8=0;n8<=max_code;n8++){curlen=nextlen;nextlen=tree2[(n8+1)*2+1];if(++count<max_count&&curlen===nextlen){continue}else if(count<min_count){s10.bl_tree[curlen*2]+=count}else if(curlen!==0){if(curlen!==prevlen){s10.bl_tree[curlen*2]++}s10.bl_tree[REP_3_6*2]++}else if(count<=10){s10.bl_tree[REPZ_3_10*2]++}else{s10.bl_tree[REPZ_11_138*2]++}count=0;prevlen=curlen;if(nextlen===0){max_count=138;min_count=3}else if(curlen===nextlen){max_count=6;min_count=3}else{max_count=7;min_count=4}}};var send_tree=(s10,tree2,max_code)=>{let n8;let prevlen=-1;let curlen;let nextlen=tree2[0*2+1];let count=0;let max_count=7;let min_count=4;if(nextlen===0){max_count=138;min_count=3}for(n8=0;n8<=max_code;n8++){curlen=nextlen;nextlen=tree2[(n8+1)*2+1];if(++count<max_count&&curlen===nextlen){continue}else if(count<min_count){do{send_code(s10,curlen,s10.bl_tree)}while(--count!==0)}else if(curlen!==0){if(curlen!==prevlen){send_code(s10,curlen,s10.bl_tree);count--}send_code(s10,REP_3_6,s10.bl_tree);send_bits(s10,count-3,2)}else if(count<=10){send_code(s10,REPZ_3_10,s10.bl_tree);send_bits(s10,count-3,3)}else{send_code(s10,REPZ_11_138,s10.bl_tree);send_bits(s10,count-11,7)}count=0;prevlen=curlen;if(nextlen===0){max_count=138;min_count=3}else if(curlen===nextlen){max_count=6;min_count=3}else{max_count=7;min_count=4}}};var build_bl_tree=s10=>{let max_blindex;scan_tree(s10,s10.dyn_ltree,s10.l_desc.max_code);scan_tree(s10,s10.dyn_dtree,s10.d_desc.max_code);build_tree(s10,s10.bl_desc);for(max_blindex=BL_CODES$1-1;max_blindex>=3;max_blindex--){if(s10.bl_tree[bl_order[max_blindex]*2+1]!==0){break}}s10.opt_len+=3*(max_blindex+1)+5+5+4;return max_blindex};var send_all_trees=(s10,lcodes,dcodes,blcodes)=>{let rank3;send_bits(s10,lcodes-257,5);send_bits(s10,dcodes-1,5);send_bits(s10,blcodes-4,4);for(rank3=0;rank3<blcodes;rank3++){send_bits(s10,s10.bl_tree[bl_order[rank3]*2+1],3)}send_tree(s10,s10.dyn_ltree,lcodes-1);send_tree(s10,s10.dyn_dtree,dcodes-1)};var detect_data_type=s10=>{let block_mask=4093624447;let n8;for(n8=0;n8<=31;n8++,block_mask>>>=1){if(block_mask&1&&s10.dyn_ltree[n8*2]!==0){return Z_BINARY}}if(s10.dyn_ltree[9*2]!==0||s10.dyn_ltree[10*2]!==0||s10.dyn_ltree[13*2]!==0){return Z_TEXT}for(n8=32;n8<LITERALS$1;n8++){if(s10.dyn_ltree[n8*2]!==0){return Z_TEXT}}return Z_BINARY};var static_init_done=false;var _tr_init$1=s10=>{if(!static_init_done){tr_static_init();static_init_done=true}s10.l_desc=new TreeDesc(s10.dyn_ltree,static_l_desc);s10.d_desc=new TreeDesc(s10.dyn_dtree,static_d_desc);s10.bl_desc=new TreeDesc(s10.bl_tree,static_bl_desc);s10.bi_buf=0;s10.bi_valid=0;init_block(s10)};var _tr_stored_block$1=(s10,buf,stored_len,last)=>{send_bits(s10,(STORED_BLOCK<<1)+(last?1:0),3);bi_windup(s10);put_short(s10,stored_len);put_short(s10,~stored_len);if(stored_len){s10.pending_buf.set(s10.window.subarray(buf,buf+stored_len),s10.pending)}s10.pending+=stored_len};var _tr_align$1=s10=>{send_bits(s10,STATIC_TREES<<1,3);send_code(s10,END_BLOCK,static_ltree);bi_flush(s10)};var _tr_flush_block$1=(s10,buf,stored_len,last)=>{let opt_lenb,static_lenb;let max_blindex=0;if(s10.level>0){if(s10.strm.data_type===Z_UNKNOWN$1){s10.strm.data_type=detect_data_type(s10)}build_tree(s10,s10.l_desc);build_tree(s10,s10.d_desc);max_blindex=build_bl_tree(s10);opt_lenb=s10.opt_len+3+7>>>3;static_lenb=s10.static_len+3+7>>>3;if(static_lenb<=opt_lenb){opt_lenb=static_lenb}}else{opt_lenb=static_lenb=stored_len+5}if(stored_len+4<=opt_lenb&&buf!==-1){_tr_stored_block$1(s10,buf,stored_len,last)}else if(s10.strategy===Z_FIXED$1||static_lenb===opt_lenb){send_bits(s10,(STATIC_TREES<<1)+(last?1:0),3);compress_block(s10,static_ltree,static_dtree)}else{send_bits(s10,(DYN_TREES<<1)+(last?1:0),3);send_all_trees(s10,s10.l_desc.max_code+1,s10.d_desc.max_code+1,max_blindex+1);compress_block(s10,s10.dyn_ltree,s10.dyn_dtree)}init_block(s10);if(last){bi_windup(s10)}};var _tr_tally$1=(s10,dist,lc2)=>{s10.pending_buf[s10.sym_buf+s10.sym_next++]=dist;s10.pending_buf[s10.sym_buf+s10.sym_next++]=dist>>8;s10.pending_buf[s10.sym_buf+s10.sym_next++]=lc2;if(dist===0){s10.dyn_ltree[lc2*2]++}else{s10.matches++;dist--;s10.dyn_ltree[(_length_code[lc2]+LITERALS$1+1)*2]++;s10.dyn_dtree[d_code(dist)*2]++}return s10.sym_next===s10.sym_end};var _tr_init_1=_tr_init$1;var _tr_stored_block_1=_tr_stored_block$1;var _tr_flush_block_1=_tr_flush_block$1;var _tr_tally_1=_tr_tally$1;var _tr_align_1=_tr_align$1;var trees={_tr_init:_tr_init_1,_tr_stored_block:_tr_stored_block_1,_tr_flush_block:_tr_flush_block_1,_tr_tally:_tr_tally_1,_tr_align:_tr_align_1};var adler32=(adler,buf,len2,pos)=>{let s12=adler&65535|0,s22=adler>>>16&65535|0,n8=0;while(len2!==0){n8=len2>2e3?2e3:len2;len2-=n8;do{s12=s12+buf[pos++]|0;s22=s22+s12|0}while(--n8);s12%=65521;s22%=65521}return s12|s22<<16|0};var adler32_1=adler32;var makeTable=()=>{let c,table=[];for(var n8=0;n8<256;n8++){c=n8;for(var k10=0;k10<8;k10++){c=c&1?3988292384^c>>>1:c>>>1}table[n8]=c}return table};var crcTable=new Uint32Array(makeTable());var crc322=(crc,buf,len2,pos)=>{const t10=crcTable;const end=pos+len2;crc^=-1;for(let i10=pos;i10<end;i10++){crc=crc>>>8^t10[(crc^buf[i10])&255]}return crc^-1};var crc32_1=crc322;var messages={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"};var constants$2={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};var{_tr_init,_tr_stored_block,_tr_flush_block,_tr_tally,_tr_align}=trees;var{Z_NO_FLUSH:Z_NO_FLUSH$2,Z_PARTIAL_FLUSH,Z_FULL_FLUSH:Z_FULL_FLUSH$1,Z_FINISH:Z_FINISH$3,Z_BLOCK:Z_BLOCK$1,Z_OK:Z_OK$3,Z_STREAM_END:Z_STREAM_END$3,Z_STREAM_ERROR:Z_STREAM_ERROR$2,Z_DATA_ERROR:Z_DATA_ERROR$2,Z_BUF_ERROR:Z_BUF_ERROR$2,Z_DEFAULT_COMPRESSION:Z_DEFAULT_COMPRESSION$1,Z_FILTERED,Z_HUFFMAN_ONLY,Z_RLE,Z_FIXED,Z_DEFAULT_STRATEGY:Z_DEFAULT_STRATEGY$1,Z_UNKNOWN,Z_DEFLATED:Z_DEFLATED$2}=constants$2;var MAX_MEM_LEVEL=9;var MAX_WBITS$1=15;var DEF_MEM_LEVEL=8;var LENGTH_CODES=29;var LITERALS=256;var L_CODES=LITERALS+1+LENGTH_CODES;var D_CODES=30;var BL_CODES=19;var HEAP_SIZE=2*L_CODES+1;var MAX_BITS=15;var MIN_MATCH=3;var MAX_MATCH=258;var MIN_LOOKAHEAD=MAX_MATCH+MIN_MATCH+1;var PRESET_DICT=32;var INIT_STATE=42;var GZIP_STATE=57;var EXTRA_STATE=69;var NAME_STATE=73;var COMMENT_STATE=91;var HCRC_STATE=103;var BUSY_STATE=113;var FINISH_STATE=666;var BS_NEED_MORE=1;var BS_BLOCK_DONE=2;var BS_FINISH_STARTED=3;var BS_FINISH_DONE=4;var OS_CODE=3;var err=(strm,errorCode)=>{strm.msg=messages[errorCode];return errorCode};var rank=f10=>{return f10*2-(f10>4?9:0)};var zero=buf=>{let len2=buf.length;while(--len2>=0){buf[len2]=0}};var slide_hash=s10=>{let n8,m;let p;let wsize=s10.w_size;n8=s10.hash_size;p=n8;do{m=s10.head[--p];s10.head[p]=m>=wsize?m-wsize:0}while(--n8);n8=wsize;p=n8;do{m=s10.prev[--p];s10.prev[p]=m>=wsize?m-wsize:0}while(--n8)};var HASH=(s10,prev,data2)=>(prev<<s10.hash_shift^data2)&s10.hash_mask;var INSERT_STRING=(s10,str)=>{let h;if(s10.legacy_hash){h=s10.ins_h=HASH(s10,s10.ins_h,s10.window[str+MIN_MATCH-1])}else{const w=s10.window;const value=w[str]|w[str+1]<<8|w[str+2]<<16|w[str+3]<<24;h=s10.ins_h=Math.imul(value,66521)+66521>>>16&s10.hash_mask}const hash_head=s10.prev[str&s10.w_mask]=s10.head[h];s10.head[h]=str;return hash_head};var flush_pending=strm=>{const s10=strm.state;let len2=s10.pending;if(len2>strm.avail_out){len2=strm.avail_out}if(len2===0){return}strm.output.set(s10.pending_buf.subarray(s10.pending_out,s10.pending_out+len2),strm.next_out);strm.next_out+=len2;s10.pending_out+=len2;strm.total_out+=len2;strm.avail_out-=len2;s10.pending-=len2;if(s10.pending===0){s10.pending_out=0}};var flush_block_only=(s10,last)=>{_tr_flush_block(s10,s10.block_start>=0?s10.block_start:-1,s10.strstart-s10.block_start,last);s10.block_start=s10.strstart;flush_pending(s10.strm)};var put_byte=(s10,b)=>{s10.pending_buf[s10.pending++]=b};var putShortMSB=(s10,b)=>{s10.pending_buf[s10.pending++]=b>>>8&255;s10.pending_buf[s10.pending++]=b&255};var read_buf=(strm,buf,start,size)=>{let len2=strm.avail_in;if(len2>size){len2=size}if(len2===0){return 0}strm.avail_in-=len2;buf.set(strm.input.subarray(strm.next_in,strm.next_in+len2),start);if(strm.state.wrap===1){strm.adler=adler32_1(strm.adler,buf,len2,start)}else if(strm.state.wrap===2){strm.adler=crc32_1(strm.adler,buf,len2,start)}strm.next_in+=len2;strm.total_in+=len2;return len2};var longest_match=(s10,cur_match)=>{let chain_length=s10.max_chain_length;let scan=s10.strstart;let match2;let len2;let best_len=s10.prev_length;let nice_match=s10.nice_match;const limit=s10.strstart>s10.w_size-MIN_LOOKAHEAD?s10.strstart-(s10.w_size-MIN_LOOKAHEAD):0;const _win=s10.window;const wmask=s10.w_mask;const prev=s10.prev;const strend=s10.strstart+MAX_MATCH;let scan_end1=_win[scan+best_len-1];let scan_end=_win[scan+best_len];if(s10.prev_length>=s10.good_match){chain_length>>=2}if(nice_match>s10.lookahead){nice_match=s10.lookahead}do{match2=cur_match;if(_win[match2+best_len]!==scan_end||_win[match2+best_len-1]!==scan_end1||_win[match2]!==_win[scan]||_win[++match2]!==_win[scan+1]){continue}scan+=2;match2++;do{}while(_win[++scan]===_win[++match2]&&_win[++scan]===_win[++match2]&&_win[++scan]===_win[++match2]&&_win[++scan]===_win[++match2]&&_win[++scan]===_win[++match2]&&_win[++scan]===_win[++match2]&&_win[++scan]===_win[++match2]&&_win[++scan]===_win[++match2]&&scan<strend);len2=MAX_MATCH-(strend-scan);scan=strend-MAX_MATCH;if(len2>best_len){s10.match_start=cur_match;best_len=len2;if(len2>=nice_match){break}scan_end1=_win[scan+best_len-1];scan_end=_win[scan+best_len]}}while((cur_match=prev[cur_match&wmask])>limit&&--chain_length!==0);if(best_len<=s10.lookahead){return best_len}return s10.lookahead};var fill_window=s10=>{const _w_size=s10.w_size;let n8,more,str;do{more=s10.window_size-s10.lookahead-s10.strstart;if(s10.strstart>=_w_size+(_w_size-MIN_LOOKAHEAD)){s10.window.set(s10.window.subarray(_w_size,_w_size+_w_size-more),0);s10.match_start-=_w_size;s10.strstart-=_w_size;s10.block_start-=_w_size;if(s10.insert>s10.strstart){s10.insert=s10.strstart}slide_hash(s10);more+=_w_size}if(s10.strm.avail_in===0){break}n8=read_buf(s10.strm,s10.window,s10.strstart+s10.lookahead,more);s10.lookahead+=n8;if(!s10.legacy_hash){if(s10.lookahead+s10.insert>MIN_MATCH){str=s10.strstart-s10.insert;while(s10.insert){INSERT_STRING(s10,str);str++;s10.insert--;if(s10.lookahead+s10.insert<=MIN_MATCH){break}}}}else if(s10.lookahead+s10.insert>=MIN_MATCH){str=s10.strstart-s10.insert;s10.ins_h=s10.window[str];s10.ins_h=HASH(s10,s10.ins_h,s10.window[str+1]);while(s10.insert){INSERT_STRING(s10,str);str++;s10.insert--;if(s10.lookahead+s10.insert<MIN_MATCH){break}}}}while(s10.lookahead<MIN_LOOKAHEAD&&s10.strm.avail_in!==0)};var deflate_stored=(s10,flush2)=>{let min_block=s10.pending_buf_size-5>s10.w_size?s10.w_size:s10.pending_buf_size-5;let len2,left,have,last=0;let used=s10.strm.avail_in;do{len2=65535;have=s10.bi_valid+42>>3;if(s10.strm.avail_out<have){break}have=s10.strm.avail_out-have;left=s10.strstart-s10.block_start;if(len2>left+s10.strm.avail_in){len2=left+s10.strm.avail_in}if(len2>have){len2=have}if(len2<min_block&&(len2===0&&flush2!==Z_FINISH$3||flush2===Z_NO_FLUSH$2||len2!==left+s10.strm.avail_in)){break}last=flush2===Z_FINISH$3&&len2===left+s10.strm.avail_in?1:0;_tr_stored_block(s10,0,0,last);s10.pending_buf[s10.pending-4]=len2;s10.pending_buf[s10.pending-3]=len2>>8;s10.pending_buf[s10.pending-2]=~len2;s10.pending_buf[s10.pending-1]=~len2>>8;flush_pending(s10.strm);if(left){if(left>len2){left=len2}s10.strm.output.set(s10.window.subarray(s10.block_start,s10.block_start+left),s10.strm.next_out);s10.strm.next_out+=left;s10.strm.avail_out-=left;s10.strm.total_out+=left;s10.block_start+=left;len2-=left}if(len2){read_buf(s10.strm,s10.strm.output,s10.strm.next_out,len2);s10.strm.next_out+=len2;s10.strm.avail_out-=len2;s10.strm.total_out+=len2}}while(last===0);used-=s10.strm.avail_in;if(used){if(used>=s10.w_size){s10.matches=2;s10.window.set(s10.strm.input.subarray(s10.strm.next_in-s10.w_size,s10.strm.next_in),0);s10.strstart=s10.w_size;s10.insert=s10.strstart}else{if(s10.window_size-s10.strstart<=used){s10.strstart-=s10.w_size;s10.window.set(s10.window.subarray(s10.w_size,s10.w_size+s10.strstart),0);if(s10.matches<2){s10.matches++}if(s10.insert>s10.strstart){s10.insert=s10.strstart}}s10.window.set(s10.strm.input.subarray(s10.strm.next_in-used,s10.strm.next_in),s10.strstart);s10.strstart+=used;s10.insert+=used>s10.w_size-s10.insert?s10.w_size-s10.insert:used}s10.block_start=s10.strstart}if(s10.high_water<s10.strstart){s10.high_water=s10.strstart}if(last){return BS_FINISH_DONE}if(flush2!==Z_NO_FLUSH$2&&flush2!==Z_FINISH$3&&s10.strm.avail_in===0&&s10.strstart===s10.block_start){return BS_BLOCK_DONE}have=s10.window_size-s10.strstart;if(s10.strm.avail_in>have&&s10.block_start>=s10.w_size){s10.block_start-=s10.w_size;s10.strstart-=s10.w_size;s10.window.set(s10.window.subarray(s10.w_size,s10.w_size+s10.strstart),0);if(s10.matches<2){s10.matches++}have+=s10.w_size;if(s10.insert>s10.strstart){s10.insert=s10.strstart}}if(have>s10.strm.avail_in){have=s10.strm.avail_in}if(have){read_buf(s10.strm,s10.window,s10.strstart,have);s10.strstart+=have;s10.insert+=have>s10.w_size-s10.insert?s10.w_size-s10.insert:have}if(s10.high_water<s10.strstart){s10.high_water=s10.strstart}have=s10.bi_valid+42>>3;have=s10.pending_buf_size-have>65535?65535:s10.pending_buf_size-have;min_block=have>s10.w_size?s10.w_size:have;left=s10.strstart-s10.block_start;if(left>=min_block||(left||flush2===Z_FINISH$3)&&flush2!==Z_NO_FLUSH$2&&s10.strm.avail_in===0&&left<=have){len2=left>have?have:left;last=flush2===Z_FINISH$3&&s10.strm.avail_in===0&&len2===left?1:0;_tr_stored_block(s10,s10.block_start,len2,last);s10.block_start+=len2;flush_pending(s10.strm)}return last?BS_FINISH_STARTED:BS_NEED_MORE};var deflate_fast=(s10,flush2)=>{let hash_head;let bflush;for(;;){if(s10.lookahead<MIN_LOOKAHEAD){fill_window(s10);if(s10.lookahead<MIN_LOOKAHEAD&&flush2===Z_NO_FLUSH$2){return BS_NEED_MORE}if(s10.lookahead===0){break}}hash_head=0;if(s10.lookahead>=MIN_MATCH){hash_head=INSERT_STRING(s10,s10.strstart)}if(hash_head!==0&&s10.strstart-hash_head<=s10.w_size-MIN_LOOKAHEAD){s10.match_length=longest_match(s10,hash_head)}if(s10.match_length>=MIN_MATCH){bflush=_tr_tally(s10,s10.strstart-s10.match_start,s10.match_length-MIN_MATCH);s10.lookahead-=s10.match_length;if(s10.match_length<=s10.max_lazy_match&&s10.lookahead>=MIN_MATCH){s10.match_length--;do{s10.strstart++;hash_head=INSERT_STRING(s10,s10.strstart)}while(--s10.match_length!==0);s10.strstart++}else{s10.strstart+=s10.match_length;s10.match_length=0;if(s10.legacy_hash){s10.ins_h=s10.window[s10.strstart];s10.ins_h=HASH(s10,s10.ins_h,s10.window[s10.strstart+1])}}}else{bflush=_tr_tally(s10,0,s10.window[s10.strstart]);s10.lookahead--;s10.strstart++}if(bflush){flush_block_only(s10,false);if(s10.strm.avail_out===0){return BS_NEED_MORE}}}s10.insert=s10.strstart<MIN_MATCH-1?s10.strstart:MIN_MATCH-1;if(flush2===Z_FINISH$3){flush_block_only(s10,true);if(s10.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s10.sym_next){flush_block_only(s10,false);if(s10.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE};var deflate_slow=(s10,flush2)=>{let hash_head;let bflush;let max_insert;for(;;){if(s10.lookahead<MIN_LOOKAHEAD){fill_window(s10);if(s10.lookahead<MIN_LOOKAHEAD&&flush2===Z_NO_FLUSH$2){return BS_NEED_MORE}if(s10.lookahead===0){break}}hash_head=0;if(s10.lookahead>=MIN_MATCH){hash_head=INSERT_STRING(s10,s10.strstart)}s10.prev_length=s10.match_length;s10.prev_match=s10.match_start;s10.match_length=MIN_MATCH-1;if(hash_head!==0&&s10.prev_length<s10.max_lazy_match&&s10.strstart-hash_head<=s10.w_size-MIN_LOOKAHEAD){s10.match_length=longest_match(s10,hash_head);if(s10.match_length<=5&&(s10.strategy===Z_FILTERED||s10.match_length===MIN_MATCH&&s10.strstart-s10.match_start>4096)){s10.match_length=MIN_MATCH-1}}if(s10.prev_length>=MIN_MATCH&&s10.match_length<=s10.prev_length){max_insert=s10.strstart+s10.lookahead-MIN_MATCH;bflush=_tr_tally(s10,s10.strstart-1-s10.prev_match,s10.prev_length-MIN_MATCH);s10.lookahead-=s10.prev_length-1;s10.prev_length-=2;do{if(++s10.strstart<=max_insert){hash_head=INSERT_STRING(s10,s10.strstart)}}while(--s10.prev_length!==0);s10.match_available=0;s10.match_length=MIN_MATCH-1;s10.strstart++;if(bflush){flush_block_only(s10,false);if(s10.strm.avail_out===0){return BS_NEED_MORE}}}else if(s10.match_available){bflush=_tr_tally(s10,0,s10.window[s10.strstart-1]);if(bflush){flush_block_only(s10,false)}s10.strstart++;s10.lookahead--;if(s10.strm.avail_out===0){return BS_NEED_MORE}}else{s10.match_available=1;s10.strstart++;s10.lookahead--}}if(s10.match_available){bflush=_tr_tally(s10,0,s10.window[s10.strstart-1]);s10.match_available=0}s10.insert=s10.strstart<MIN_MATCH-1?s10.strstart:MIN_MATCH-1;if(flush2===Z_FINISH$3){flush_block_only(s10,true);if(s10.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s10.sym_next){flush_block_only(s10,false);if(s10.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE};var deflate_rle=(s10,flush2)=>{let bflush;let prev;let scan,strend;const _win=s10.window;for(;;){if(s10.lookahead<=MAX_MATCH){fill_window(s10);if(s10.lookahead<=MAX_MATCH&&flush2===Z_NO_FLUSH$2){return BS_NEED_MORE}if(s10.lookahead===0){break}}s10.match_length=0;if(s10.lookahead>=MIN_MATCH&&s10.strstart>0){scan=s10.strstart-1;prev=_win[scan];if(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]){strend=s10.strstart+MAX_MATCH;do{}while(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&scan<strend);s10.match_length=MAX_MATCH-(strend-scan);if(s10.match_length>s10.lookahead){s10.match_length=s10.lookahead}}}if(s10.match_length>=MIN_MATCH){bflush=_tr_tally(s10,1,s10.match_length-MIN_MATCH);s10.lookahead-=s10.match_length;s10.strstart+=s10.match_length;s10.match_length=0}else{bflush=_tr_tally(s10,0,s10.window[s10.strstart]);s10.lookahead--;s10.strstart++}if(bflush){flush_block_only(s10,false);if(s10.strm.avail_out===0){return BS_NEED_MORE}}}s10.insert=0;if(flush2===Z_FINISH$3){flush_block_only(s10,true);if(s10.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s10.sym_next){flush_block_only(s10,false);if(s10.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE};var deflate_huff=(s10,flush2)=>{let bflush;for(;;){if(s10.lookahead===0){fill_window(s10);if(s10.lookahead===0){if(flush2===Z_NO_FLUSH$2){return BS_NEED_MORE}break}}s10.match_length=0;bflush=_tr_tally(s10,0,s10.window[s10.strstart]);s10.lookahead--;s10.strstart++;if(bflush){flush_block_only(s10,false);if(s10.strm.avail_out===0){return BS_NEED_MORE}}}s10.insert=0;if(flush2===Z_FINISH$3){flush_block_only(s10,true);if(s10.strm.avail_out===0){return BS_FINISH_STARTED}return BS_FINISH_DONE}if(s10.sym_next){flush_block_only(s10,false);if(s10.strm.avail_out===0){return BS_NEED_MORE}}return BS_BLOCK_DONE};function Config(good_length,max_lazy,nice_length,max_chain,func){this.good_length=good_length;this.max_lazy=max_lazy;this.nice_length=nice_length;this.max_chain=max_chain;this.func=func}var configuration_table=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)];var lm_init=s10=>{s10.window_size=2*s10.w_size;zero(s10.head);s10.max_lazy_match=configuration_table[s10.level].max_lazy;s10.good_match=configuration_table[s10.level].good_length;s10.nice_match=configuration_table[s10.level].nice_length;s10.max_chain_length=configuration_table[s10.level].max_chain;s10.strstart=0;s10.block_start=0;s10.lookahead=0;s10.insert=0;s10.match_length=s10.prev_length=MIN_MATCH-1;s10.match_available=0;s10.ins_h=0};function DeflateState(){this.strm=null;this.status=0;this.pending_buf=null;this.pending_buf_size=0;this.pending_out=0;this.pending=0;this.wrap=0;this.gzhead=null;this.gzindex=0;this.method=Z_DEFLATED$2;this.last_flush=-1;this.w_size=0;this.w_bits=0;this.w_mask=0;this.window=null;this.window_size=0;this.prev=null;this.head=null;this.ins_h=0;this.legacy_hash=0;this.hash_size=0;this.hash_bits=0;this.hash_mask=0;this.hash_shift=0;this.block_start=0;this.match_length=0;this.prev_match=0;this.match_available=0;this.strstart=0;this.match_start=0;this.lookahead=0;this.prev_length=0;this.max_chain_length=0;this.max_lazy_match=0;this.level=0;this.strategy=0;this.good_match=0;this.nice_match=0;this.dyn_ltree=new Uint16Array(HEAP_SIZE*2);this.dyn_dtree=new Uint16Array((2*D_CODES+1)*2);this.bl_tree=new Uint16Array((2*BL_CODES+1)*2);zero(this.dyn_ltree);zero(this.dyn_dtree);zero(this.bl_tree);this.l_desc=null;this.d_desc=null;this.bl_desc=null;this.bl_count=new Uint16Array(MAX_BITS+1);this.heap=new Uint16Array(2*L_CODES+1);zero(this.heap);this.heap_len=0;this.heap_max=0;this.depth=new Uint16Array(2*L_CODES+1);zero(this.depth);this.sym_buf=0;this.lit_bufsize=0;this.sym_next=0;this.sym_end=0;this.opt_len=0;this.static_len=0;this.matches=0;this.insert=0;this.bi_buf=0;this.bi_valid=0}var deflateStateCheck=strm=>{if(!strm){return 1}const s10=strm.state;if(!s10||s10.strm!==strm||s10.status!==INIT_STATE&&s10.status!==GZIP_STATE&&s10.status!==EXTRA_STATE&&s10.status!==NAME_STATE&&s10.status!==COMMENT_STATE&&s10.status!==HCRC_STATE&&s10.status!==BUSY_STATE&&s10.status!==FINISH_STATE){return 1}return 0};var deflateResetKeep=strm=>{if(deflateStateCheck(strm)){return err(strm,Z_STREAM_ERROR$2)}strm.total_in=strm.total_out=0;strm.data_type=Z_UNKNOWN;const s10=strm.state;s10.pending=0;s10.pending_out=0;if(s10.wrap<0){s10.wrap=-s10.wrap}s10.status=s10.wrap===2?GZIP_STATE:s10.wrap?INIT_STATE:BUSY_STATE;strm.adler=s10.wrap===2?0:1;s10.last_flush=-2;_tr_init(s10);return Z_OK$3};var deflateReset=strm=>{const ret=deflateResetKeep(strm);if(ret===Z_OK$3){lm_init(strm.state)}return ret};var deflateSetHeader=(strm,head)=>{if(deflateStateCheck(strm)||strm.state.wrap!==2){return Z_STREAM_ERROR$2}strm.state.gzhead=head;return Z_OK$3};var deflateInit2=(strm,level,method,windowBits,memLevel,strategy,legacyHash)=>{if(!strm){return Z_STREAM_ERROR$2}let wrap2=1;if(level===Z_DEFAULT_COMPRESSION$1){level=6}if(windowBits<0){wrap2=0;windowBits=-windowBits}else if(windowBits>15){wrap2=2;windowBits-=16}if(memLevel<1||memLevel>MAX_MEM_LEVEL||method!==Z_DEFLATED$2||windowBits<8||windowBits>15||level<0||level>9||strategy<0||strategy>Z_FIXED||windowBits===8&&wrap2!==1){return err(strm,Z_STREAM_ERROR$2)}if(windowBits===8){windowBits=9}const s10=new DeflateState;strm.state=s10;s10.strm=strm;s10.status=INIT_STATE;s10.wrap=wrap2;s10.gzhead=null;s10.w_bits=windowBits;s10.w_size=1<<s10.w_bits;s10.w_mask=s10.w_size-1;s10.legacy_hash=legacyHash?1:0;s10.hash_bits=memLevel+7;if(!s10.legacy_hash&&s10.hash_bits<15){s10.hash_bits=15}s10.hash_size=1<<s10.hash_bits;s10.hash_mask=s10.hash_size-1;s10.hash_shift=~~((s10.hash_bits+MIN_MATCH-1)/MIN_MATCH);s10.window=new Uint8Array(s10.w_size*2);s10.head=new Uint16Array(s10.hash_size);s10.prev=new Uint16Array(s10.w_size);s10.lit_bufsize=1<<memLevel+6;s10.pending_buf_size=s10.lit_bufsize*4;s10.pending_buf=new Uint8Array(s10.pending_buf_size);s10.sym_buf=s10.lit_bufsize;s10.sym_end=(s10.lit_bufsize-1)*3;s10.level=level;s10.strategy=strategy;s10.method=method;return deflateReset(strm)};var deflateInit=(strm,level)=>{return deflateInit2(strm,level,Z_DEFLATED$2,MAX_WBITS$1,DEF_MEM_LEVEL,Z_DEFAULT_STRATEGY$1)};var deflate$2=(strm,flush2)=>{if(deflateStateCheck(strm)||flush2>Z_BLOCK$1||flush2<0){return strm?err(strm,Z_STREAM_ERROR$2):Z_STREAM_ERROR$2}const s10=strm.state;if(!strm.output||strm.avail_in!==0&&!strm.input||s10.status===FINISH_STATE&&flush2!==Z_FINISH$3){return err(strm,strm.avail_out===0?Z_BUF_ERROR$2:Z_STREAM_ERROR$2)}const old_flush=s10.last_flush;s10.last_flush=flush2;if(s10.pending!==0){flush_pending(strm);if(strm.avail_out===0){s10.last_flush=-1;return Z_OK$3}}else if(strm.avail_in===0&&rank(flush2)<=rank(old_flush)&&flush2!==Z_FINISH$3){return err(strm,Z_BUF_ERROR$2)}if(s10.status===FINISH_STATE&&strm.avail_in!==0){return err(strm,Z_BUF_ERROR$2)}if(s10.status===INIT_STATE&&s10.wrap===0){s10.status=BUSY_STATE}if(s10.status===INIT_STATE){let header=Z_DEFLATED$2+(s10.w_bits-8<<4)<<8;let level_flags=-1;if(s10.strategy>=Z_HUFFMAN_ONLY||s10.level<2){level_flags=0}else if(s10.level<6){level_flags=1}else if(s10.level===6){level_flags=2}else{level_flags=3}header|=level_flags<<6;if(s10.strstart!==0){header|=PRESET_DICT}header+=31-header%31;putShortMSB(s10,header);if(s10.strstart!==0){putShortMSB(s10,strm.adler>>>16);putShortMSB(s10,strm.adler&65535)}strm.adler=1;s10.status=BUSY_STATE;flush_pending(strm);if(s10.pending!==0){s10.last_flush=-1;return Z_OK$3}}if(s10.status===GZIP_STATE){strm.adler=0;put_byte(s10,31);put_byte(s10,139);put_byte(s10,8);if(!s10.gzhead){put_byte(s10,0);put_byte(s10,0);put_byte(s10,0);put_byte(s10,0);put_byte(s10,0);put_byte(s10,s10.level===9?2:s10.strategy>=Z_HUFFMAN_ONLY||s10.level<2?4:0);put_byte(s10,OS_CODE);s10.status=BUSY_STATE;flush_pending(strm);if(s10.pending!==0){s10.last_flush=-1;return Z_OK$3}}else{put_byte(s10,(s10.gzhead.text?1:0)+(s10.gzhead.hcrc?2:0)+(!s10.gzhead.extra?0:4)+(!s10.gzhead.name?0:8)+(!s10.gzhead.comment?0:16));put_byte(s10,s10.gzhead.time&255);put_byte(s10,s10.gzhead.time>>8&255);put_byte(s10,s10.gzhead.time>>16&255);put_byte(s10,s10.gzhead.time>>24&255);put_byte(s10,s10.level===9?2:s10.strategy>=Z_HUFFMAN_ONLY||s10.level<2?4:0);put_byte(s10,s10.gzhead.os&255);if(s10.gzhead.extra&&s10.gzhead.extra.length){put_byte(s10,s10.gzhead.extra.length&255);put_byte(s10,s10.gzhead.extra.length>>8&255)}if(s10.gzhead.hcrc){strm.adler=crc32_1(strm.adler,s10.pending_buf,s10.pending,0)}s10.gzindex=0;s10.status=EXTRA_STATE}}if(s10.status===EXTRA_STATE){if(s10.gzhead.extra){let beg=s10.pending;let left=(s10.gzhead.extra.length&65535)-s10.gzindex;while(s10.pending+left>s10.pending_buf_size){let copy2=s10.pending_buf_size-s10.pending;s10.pending_buf.set(s10.gzhead.extra.subarray(s10.gzindex,s10.gzindex+copy2),s10.pending);s10.pending=s10.pending_buf_size;if(s10.gzhead.hcrc&&s10.pending>beg){strm.adler=crc32_1(strm.adler,s10.pending_buf,s10.pending-beg,beg)}s10.gzindex+=copy2;flush_pending(strm);if(s10.pending!==0){s10.last_flush=-1;return Z_OK$3}beg=0;left-=copy2}let gzhead_extra=new Uint8Array(s10.gzhead.extra);s10.pending_buf.set(gzhead_extra.subarray(s10.gzindex,s10.gzindex+left),s10.pending);s10.pending+=left;if(s10.gzhead.hcrc&&s10.pending>beg){strm.adler=crc32_1(strm.adler,s10.pending_buf,s10.pending-beg,beg)}s10.gzindex=0}s10.status=NAME_STATE}if(s10.status===NAME_STATE){if(s10.gzhead.name){let beg=s10.pending;let val;do{if(s10.pending===s10.pending_buf_size){if(s10.gzhead.hcrc&&s10.pending>beg){strm.adler=crc32_1(strm.adler,s10.pending_buf,s10.pending-beg,beg)}flush_pending(strm);if(s10.pending!==0){s10.last_flush=-1;return Z_OK$3}beg=0}if(s10.gzindex<s10.gzhead.name.length){val=s10.gzhead.name.charCodeAt(s10.gzindex++)&255}else{val=0}put_byte(s10,val)}while(val!==0);if(s10.gzhead.hcrc&&s10.pending>beg){strm.adler=crc32_1(strm.adler,s10.pending_buf,s10.pending-beg,beg)}s10.gzindex=0}s10.status=COMMENT_STATE}if(s10.status===COMMENT_STATE){if(s10.gzhead.comment){let beg=s10.pending;let val;do{if(s10.pending===s10.pending_buf_size){if(s10.gzhead.hcrc&&s10.pending>beg){strm.adler=crc32_1(strm.adler,s10.pending_buf,s10.pending-beg,beg)}flush_pending(strm);if(s10.pending!==0){s10.last_flush=-1;return Z_OK$3}beg=0}if(s10.gzindex<s10.gzhead.comment.length){val=s10.gzhead.comment.charCodeAt(s10.gzindex++)&255}else{val=0}put_byte(s10,val)}while(val!==0);if(s10.gzhead.hcrc&&s10.pending>beg){strm.adler=crc32_1(strm.adler,s10.pending_buf,s10.pending-beg,beg)}}s10.status=HCRC_STATE}if(s10.status===HCRC_STATE){if(s10.gzhead.hcrc){if(s10.pending+2>s10.pending_buf_size){flush_pending(strm);if(s10.pending!==0){s10.last_flush=-1;return Z_OK$3}}put_byte(s10,strm.adler&255);put_byte(s10,strm.adler>>8&255);strm.adler=0}s10.status=BUSY_STATE;flush_pending(strm);if(s10.pending!==0){s10.last_flush=-1;return Z_OK$3}}if(strm.avail_in!==0||s10.lookahead!==0||flush2!==Z_NO_FLUSH$2&&s10.status!==FINISH_STATE){let bstate=s10.level===0?deflate_stored(s10,flush2):s10.strategy===Z_HUFFMAN_ONLY?deflate_huff(s10,flush2):s10.strategy===Z_RLE?deflate_rle(s10,flush2):configuration_table[s10.level].func(s10,flush2);if(bstate===BS_FINISH_STARTED||bstate===BS_FINISH_DONE){s10.status=FINISH_STATE}if(bstate===BS_NEED_MORE||bstate===BS_FINISH_STARTED){if(strm.avail_out===0){s10.last_flush=-1}return Z_OK$3}if(bstate===BS_BLOCK_DONE){if(flush2===Z_PARTIAL_FLUSH){_tr_align(s10)}else if(flush2!==Z_BLOCK$1){_tr_stored_block(s10,0,0,false);if(flush2===Z_FULL_FLUSH$1){zero(s10.head);if(s10.lookahead===0){s10.strstart=0;s10.block_start=0;s10.insert=0}}}flush_pending(strm);if(strm.avail_out===0){s10.last_flush=-1;return Z_OK$3}}}if(flush2!==Z_FINISH$3){return Z_OK$3}if(s10.wrap<=0){return Z_STREAM_END$3}if(s10.wrap===2){put_byte(s10,strm.adler&255);put_byte(s10,strm.adler>>8&255);put_byte(s10,strm.adler>>16&255);put_byte(s10,strm.adler>>24&255);put_byte(s10,strm.total_in&255);put_byte(s10,strm.total_in>>8&255);put_byte(s10,strm.total_in>>16&255);put_byte(s10,strm.total_in>>24&255)}else{putShortMSB(s10,strm.adler>>>16);putShortMSB(s10,strm.adler&65535)}flush_pending(strm);if(s10.wrap>0){s10.wrap=-s10.wrap}return s10.pending!==0?Z_OK$3:Z_STREAM_END$3};var deflateEnd=strm=>{if(deflateStateCheck(strm)){return Z_STREAM_ERROR$2}const status=strm.state.status;strm.state=null;return status===BUSY_STATE?err(strm,Z_DATA_ERROR$2):Z_OK$3};var deflateSetDictionary=(strm,dictionary2)=>{let dictLength=dictionary2.length;if(deflateStateCheck(strm)){return Z_STREAM_ERROR$2}const s10=strm.state;const wrap2=s10.wrap;if(wrap2===2||wrap2===1&&s10.status!==INIT_STATE||s10.lookahead){return Z_STREAM_ERROR$2}if(wrap2===1){strm.adler=adler32_1(strm.adler,dictionary2,dictLength,0)}s10.wrap=0;if(dictLength>=s10.w_size){if(wrap2===0){zero(s10.head);s10.strstart=0;s10.block_start=0;s10.insert=0}let tmpDict=new Uint8Array(s10.w_size);tmpDict.set(dictionary2.subarray(dictLength-s10.w_size,dictLength),0);dictionary2=tmpDict;dictLength=s10.w_size}const avail=strm.avail_in;const next2=strm.next_in;const input=strm.input;strm.avail_in=dictLength;strm.next_in=0;strm.input=dictionary2;fill_window(s10);while(s10.lookahead>=MIN_MATCH){let str=s10.strstart;let n8=s10.lookahead-(MIN_MATCH-1);do{INSERT_STRING(s10,str);str++}while(--n8);s10.strstart=str;s10.lookahead=MIN_MATCH-1;fill_window(s10)}s10.strstart+=s10.lookahead;s10.block_start=s10.strstart;s10.insert=s10.lookahead;s10.lookahead=0;s10.match_length=s10.prev_length=MIN_MATCH-1;s10.match_available=0;strm.next_in=next2;strm.input=input;strm.avail_in=avail;s10.wrap=wrap2;return Z_OK$3};var deflateInit_1=deflateInit;var deflateInit2_1=deflateInit2;var deflateReset_1=deflateReset;var deflateResetKeep_1=deflateResetKeep;var deflateSetHeader_1=deflateSetHeader;var deflate_2$1=deflate$2;var deflateEnd_1=deflateEnd;var deflateSetDictionary_1=deflateSetDictionary;var deflateInfo="pako deflate (from Nodeca project)";var deflate_1$2={deflateInit:deflateInit_1,deflateInit2:deflateInit2_1,deflateReset:deflateReset_1,deflateResetKeep:deflateResetKeep_1,deflateSetHeader:deflateSetHeader_1,deflate:deflate_2$1,deflateEnd:deflateEnd_1,deflateSetDictionary:deflateSetDictionary_1,deflateInfo};var _has=(obj,key)=>{return Object.prototype.hasOwnProperty.call(obj,key)};var assign=function(obj){const sources=Array.prototype.slice.call(arguments,1);while(sources.length){const source=sources.shift();if(!source){continue}if(typeof source!=="object"){throw new TypeError(source+"must be non-object")}for(const p in source){if(_has(source,p)){obj[p]=source[p]}}}return obj};var flattenChunks=chunks=>{let len2=0;for(let i10=0,l=chunks.length;i10<l;i10++){len2+=chunks[i10].length}const result=new Uint8Array(len2);for(let i10=0,pos=0,l=chunks.length;i10<l;i10++){let chunk=chunks[i10];result.set(chunk,pos);pos+=chunk.length}return result};var common={assign,flattenChunks};var STR_APPLY_UIA_OK=true;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(__){STR_APPLY_UIA_OK=false}var _utf8len=new Uint8Array(256);for(let q10=0;q10<256;q10++){_utf8len[q10]=q10>=252?6:q10>=248?5:q10>=240?4:q10>=224?3:q10>=192?2:1}_utf8len[254]=_utf8len[255]=1;var string2buf=str=>{if(typeof TextEncoder==="function"&&TextEncoder.prototype.encode){return new TextEncoder().encode(str)}let buf,c,c22,m_pos,i10,str_len=str.length,buf_len=0;for(m_pos=0;m_pos<str_len;m_pos++){c=str.charCodeAt(m_pos);if((c&64512)===55296&&m_pos+1<str_len){c22=str.charCodeAt(m_pos+1);if((c22&64512)===56320){c=65536+(c-55296<<10)+(c22-56320);m_pos++}}buf_len+=c<128?1:c<2048?2:c<65536?3:4}buf=new Uint8Array(buf_len);for(i10=0,m_pos=0;i10<buf_len;m_pos++){c=str.charCodeAt(m_pos);if((c&64512)===55296&&m_pos+1<str_len){c22=str.charCodeAt(m_pos+1);if((c22&64512)===56320){c=65536+(c-55296<<10)+(c22-56320);m_pos++}}if(c<128){buf[i10++]=c}else if(c<2048){buf[i10++]=192|c>>>6;buf[i10++]=128|c&63}else if(c<65536){buf[i10++]=224|c>>>12;buf[i10++]=128|c>>>6&63;buf[i10++]=128|c&63}else{buf[i10++]=240|c>>>18;buf[i10++]=128|c>>>12&63;buf[i10++]=128|c>>>6&63;buf[i10++]=128|c&63}}return buf};var buf2binstring=(buf,len2)=>{if(len2<65534){if(buf.subarray&&STR_APPLY_UIA_OK){return String.fromCharCode.apply(null,buf.length===len2?buf:buf.subarray(0,len2))}}let result="";for(let i10=0;i10<len2;i10++){result+=String.fromCharCode(buf[i10])}return result};var buf2string=(buf,max2)=>{const len2=max2||buf.length;if(typeof TextDecoder==="function"&&TextDecoder.prototype.decode){return new TextDecoder().decode(buf.subarray(0,max2))}let i10,out;const utf16buf=new Array(len2*2);for(out=0,i10=0;i10<len2;){let c=buf[i10++];if(c<128){utf16buf[out++]=c;continue}let c_len=_utf8len[c];if(c_len>4){utf16buf[out++]=65533;i10+=c_len-1;continue}c&=c_len===2?31:c_len===3?15:7;while(c_len>1&&i10<len2){c=c<<6|buf[i10++]&63;c_len--}if(c_len>1){utf16buf[out++]=65533;continue}if(c<65536){utf16buf[out++]=c}else{c-=65536;utf16buf[out++]=55296|c>>10&1023;utf16buf[out++]=56320|c&1023}}return buf2binstring(utf16buf,out)};var utf8border=(buf,max2)=>{max2=max2||buf.length;if(max2>buf.length){max2=buf.length}let pos=max2-1;while(pos>=0&&(buf[pos]&192)===128){pos--}if(pos<0){return max2}if(pos===0){return max2}return pos+_utf8len[buf[pos]]>max2?pos:max2};var strings={string2buf,buf2string,utf8border};function ZStream(){this.input=null;this.next_in=0;this.avail_in=0;this.total_in=0;this.output=null;this.next_out=0;this.avail_out=0;this.total_out=0;this.msg="";this.state=null;this.data_type=2;this.adler=0}var zstream=ZStream;var toString$1=Object.prototype.toString;var{Z_NO_FLUSH:Z_NO_FLUSH$1,Z_SYNC_FLUSH,Z_FULL_FLUSH,Z_FINISH:Z_FINISH$2,Z_OK:Z_OK$2,Z_STREAM_END:Z_STREAM_END$2,Z_DEFAULT_COMPRESSION,Z_DEFAULT_STRATEGY,Z_DEFLATED:Z_DEFLATED$1}=constants$2;var defaultOptions$1={level:Z_DEFAULT_COMPRESSION,method:Z_DEFLATED$1,chunkSize:16384,windowBits:15,memLevel:8,strategy:Z_DEFAULT_STRATEGY,legacyHash:true};function Deflate$1(options){this.options=common.assign({},defaultOptions$1,options||{});let opt=this.options;if(opt.raw&&opt.windowBits>0){opt.windowBits=-opt.windowBits}else if(opt.gzip&&opt.windowBits>0&&opt.windowBits<16){opt.windowBits+=16}this.err=0;this.msg="";this.ended=false;this.chunks=[];this.strm=new zstream;this.strm.avail_out=0;let status=deflate_1$2.deflateInit2(this.strm,opt.level,opt.method,opt.windowBits,opt.memLevel,opt.strategy,opt.legacyHash);if(status!==Z_OK$2){throw new Error(messages[status])}if(opt.header){deflate_1$2.deflateSetHeader(this.strm,opt.header)}if(opt.dictionary){let dict;if(typeof opt.dictionary==="string"){dict=strings.string2buf(opt.dictionary)}else if(toString$1.call(opt.dictionary)==="[object ArrayBuffer]"){dict=new Uint8Array(opt.dictionary)}else{dict=opt.dictionary}status=deflate_1$2.deflateSetDictionary(this.strm,dict);if(status!==Z_OK$2){throw new Error(messages[status])}this._dict_set=true}}Deflate$1.prototype.push=function(data2,flush_mode){const strm=this.strm;const chunkSize=this.options.chunkSize;let status,_flush_mode;if(this.ended){return false}if(flush_mode===~~flush_mode)_flush_mode=flush_mode;else _flush_mode=flush_mode===true?Z_FINISH$2:Z_NO_FLUSH$1;if(typeof data2==="string"){strm.input=strings.string2buf(data2)}else if(toString$1.call(data2)==="[object ArrayBuffer]"){strm.input=new Uint8Array(data2)}else{strm.input=data2}strm.next_in=0;strm.avail_in=strm.input.length;for(;;){if(strm.avail_out===0){strm.output=new Uint8Array(chunkSize);strm.next_out=0;strm.avail_out=chunkSize}if((_flush_mode===Z_SYNC_FLUSH||_flush_mode===Z_FULL_FLUSH)&&strm.avail_out<=6){this.onData(strm.output.subarray(0,strm.next_out));strm.avail_out=0;continue}status=deflate_1$2.deflate(strm,_flush_mode);if(status===Z_STREAM_END$2){if(strm.next_out>0){this.onData(strm.output.subarray(0,strm.next_out))}status=deflate_1$2.deflateEnd(this.strm);this.onEnd(status);this.ended=true;return status===Z_OK$2}if(strm.avail_out===0){this.onData(strm.output);continue}if(_flush_mode>0&&strm.next_out>0){this.onData(strm.output.subarray(0,strm.next_out));strm.avail_out=0;continue}if(strm.avail_in===0)break}return true};Deflate$1.prototype.onData=function(chunk){this.chunks.push(chunk)};Deflate$1.prototype.onEnd=function(status){if(status===Z_OK$2){this.result=common.flattenChunks(this.chunks)}this.chunks=[];this.err=status;this.msg=this.strm.msg};function deflate$1(input,options){const deflator=new Deflate$1(options);deflator.push(input,true);if(deflator.err){throw deflator.msg||messages[deflator.err]}return deflator.result}function deflateRaw$1(input,options){options=options||{};options.raw=true;return deflate$1(input,options)}function gzip$1(input,options){options=options||{};options.gzip=true;return deflate$1(input,options)}var Deflate_1$1=Deflate$1;var deflate_2=deflate$1;var deflateRaw_1$1=deflateRaw$1;var gzip_1$1=gzip$1;var constants$1=constants$2;var deflate_1$1={Deflate:Deflate_1$1,deflate:deflate_2,deflateRaw:deflateRaw_1$1,gzip:gzip_1$1,constants:constants$1};var BAD$1=16209;var TYPE$1=16191;var inffast=function inflate_fast(strm,start){let _in;let last;let _out;let beg;let end;let dmax;let wsize;let whave;let wnext;let s_window;let hold2;let bits;let lcode;let dcode;let lmask;let dmask;let here;let op2;let len2;let dist;let from;let from_source;let input,output;const state=strm.state;_in=strm.next_in;input=strm.input;last=_in+(strm.avail_in-5);_out=strm.next_out;output=strm.output;beg=_out-(start-strm.avail_out);end=_out+(strm.avail_out-257);dmax=state.dmax;wsize=state.wsize;whave=state.whave;wnext=state.wnext;s_window=state.window;hold2=state.hold;bits=state.bits;lcode=state.lencode;dcode=state.distcode;lmask=(1<<state.lenbits)-1;dmask=(1<<state.distbits)-1;top:do{if(bits<15){hold2+=input[_in++]<<bits;bits+=8;hold2+=input[_in++]<<bits;bits+=8}here=lcode[hold2&lmask];dolen:for(;;){op2=here>>>24;hold2>>>=op2;bits-=op2;op2=here>>>16&255;if(op2===0){output[_out++]=here&65535}else if(op2&16){len2=here&65535;op2&=15;if(op2){if(bits<op2){hold2+=input[_in++]<<bits;bits+=8}len2+=hold2&(1<<op2)-1;hold2>>>=op2;bits-=op2}if(bits<15){hold2+=input[_in++]<<bits;bits+=8;hold2+=input[_in++]<<bits;bits+=8}here=dcode[hold2&dmask];dodist:for(;;){op2=here>>>24;hold2>>>=op2;bits-=op2;op2=here>>>16&255;if(op2&16){dist=here&65535;op2&=15;if(bits<op2){hold2+=input[_in++]<<bits;bits+=8;if(bits<op2){hold2+=input[_in++]<<bits;bits+=8}}dist+=hold2&(1<<op2)-1;if(dist>dmax){strm.msg="invalid distance too far back";state.mode=BAD$1;break top}hold2>>>=op2;bits-=op2;op2=_out-beg;if(dist>op2){op2=dist-op2;if(op2>whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD$1;break top}}from=0;from_source=s_window;if(wnext===0){from+=wsize-op2;if(op2<len2){len2-=op2;do{output[_out++]=s_window[from++]}while(--op2);from=_out-dist;from_source=output}}else if(wnext<op2){from+=wsize+wnext-op2;op2-=wnext;if(op2<len2){len2-=op2;do{output[_out++]=s_window[from++]}while(--op2);from=0;if(wnext<len2){op2=wnext;len2-=op2;do{output[_out++]=s_window[from++]}while(--op2);from=_out-dist;from_source=output}}}else{from+=wnext-op2;if(op2<len2){len2-=op2;do{output[_out++]=s_window[from++]}while(--op2);from=_out-dist;from_source=output}}while(len2>2){output[_out++]=from_source[from++];output[_out++]=from_source[from++];output[_out++]=from_source[from++];len2-=3}if(len2){output[_out++]=from_source[from++];if(len2>1){output[_out++]=from_source[from++]}}}else{from=_out-dist;do{output[_out++]=output[from++];output[_out++]=output[from++];output[_out++]=output[from++];len2-=3}while(len2>2);if(len2){output[_out++]=output[from++];if(len2>1){output[_out++]=output[from++]}}}}else if((op2&64)===0){here=dcode[(here&65535)+(hold2&(1<<op2)-1)];continue dodist}else{strm.msg="invalid distance code";state.mode=BAD$1;break top}break}}else if((op2&64)===0){here=lcode[(here&65535)+(hold2&(1<<op2)-1)];continue dolen}else if(op2&32){state.mode=TYPE$1;break top}else{strm.msg="invalid literal/length code";state.mode=BAD$1;break top}break}}while(_in<last&&_out<end);len2=bits>>3;_in-=len2;bits-=len2<<3;hold2&=(1<<bits)-1;strm.next_in=_in;strm.next_out=_out;strm.avail_in=_in<last?5+(last-_in):5-(_in-last);strm.avail_out=_out<end?257+(end-_out):257-(_out-end);state.hold=hold2;state.bits=bits;return};var MAXBITS=15;var ENOUGH_LENS$1=852;var ENOUGH_DISTS$1=592;var CODES$1=0;var LENS$1=1;var DISTS$1=2;var lbase=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]);var lext=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,199,75]);var dbase=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]);var dext=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var inflate_table=(type2,lens,lens_index,codes2,table,table_index,work,opts)=>{const bits=opts.bits;let len2=0;let sym=0;let min2=0,max2=0;let root2=0;let curr=0;let drop2=0;let left=0;let used=0;let huff=0;let incr;let fill2;let low;let mask;let next2;let base=null;let match2;const count=new Uint16Array(MAXBITS+1);const offs=new Uint16Array(MAXBITS+1);let extra=null;let here_bits,here_op,here_val;for(len2=0;len2<=MAXBITS;len2++){count[len2]=0}for(sym=0;sym<codes2;sym++){count[lens[lens_index+sym]]++}root2=bits;for(max2=MAXBITS;max2>=1;max2--){if(count[max2]!==0){break}}if(root2>max2){root2=max2}if(max2===0){table[table_index++]=1<<24|64<<16|0;table[table_index++]=1<<24|64<<16|0;opts.bits=1;return 0}for(min2=1;min2<max2;min2++){if(count[min2]!==0){break}}if(root2<min2){root2=min2}left=1;for(len2=1;len2<=MAXBITS;len2++){left<<=1;left-=count[len2];if(left<0){return-1}}if(left>0&&(type2===CODES$1||max2!==1)){return-1}offs[1]=0;for(len2=1;len2<MAXBITS;len2++){offs[len2+1]=offs[len2]+count[len2]}for(sym=0;sym<codes2;sym++){if(lens[lens_index+sym]!==0){work[offs[lens[lens_index+sym]]++]=sym}}if(type2===CODES$1){base=extra=work;match2=20}else if(type2===LENS$1){base=lbase;extra=lext;match2=257}else{base=dbase;extra=dext;match2=0}huff=0;sym=0;len2=min2;next2=table_index;curr=root2;drop2=0;low=-1;used=1<<root2;mask=used-1;if(type2===LENS$1&&used>ENOUGH_LENS$1||type2===DISTS$1&&used>ENOUGH_DISTS$1){return 1}for(;;){here_bits=len2-drop2;if(work[sym]+1<match2){here_op=0;here_val=work[sym]}else if(work[sym]>=match2){here_op=extra[work[sym]-match2];here_val=base[work[sym]-match2]}else{here_op=32+64;here_val=0}incr=1<<len2-drop2;fill2=1<<curr;min2=fill2;do{fill2-=incr;table[next2+(huff>>drop2)+fill2]=here_bits<<24|here_op<<16|here_val|0}while(fill2!==0);incr=1<<len2-1;while(huff&incr){incr>>=1}if(incr!==0){huff&=incr-1;huff+=incr}else{huff=0}sym++;if(--count[len2]===0){if(len2===max2){break}len2=lens[lens_index+work[sym]]}if(len2>root2&&(huff&mask)!==low){if(drop2===0){drop2=root2}next2+=min2;curr=len2-drop2;left=1<<curr;while(curr+drop2<max2){left-=count[curr+drop2];if(left<=0){break}curr++;left<<=1}used+=1<<curr;if(type2===LENS$1&&used>ENOUGH_LENS$1||type2===DISTS$1&&used>ENOUGH_DISTS$1){return 1}low=huff&mask;table[low]=root2<<24|curr<<16|next2-table_index|0}}if(huff!==0){table[next2+huff]=len2-drop2<<24|64<<16|0}opts.bits=root2;return 0};var inftrees=inflate_table;var CODES=0;var LENS=1;var DISTS=2;var{Z_FINISH:Z_FINISH$1,Z_BLOCK,Z_TREES,Z_OK:Z_OK$1,Z_STREAM_END:Z_STREAM_END$1,Z_NEED_DICT:Z_NEED_DICT$1,Z_STREAM_ERROR:Z_STREAM_ERROR$1,Z_DATA_ERROR:Z_DATA_ERROR$1,Z_MEM_ERROR:Z_MEM_ERROR$1,Z_BUF_ERROR:Z_BUF_ERROR$1,Z_DEFLATED}=constants$2;var HEAD=16180;var FLAGS=16181;var TIME=16182;var OS=16183;var EXLEN=16184;var EXTRA=16185;var NAME=16186;var COMMENT=16187;var HCRC=16188;var DICTID=16189;var DICT=16190;var TYPE=16191;var TYPEDO=16192;var STORED=16193;var COPY_=16194;var COPY=16195;var TABLE=16196;var LENLENS=16197;var CODELENS=16198;var LEN_=16199;var LEN=16200;var LENEXT=16201;var DIST=16202;var DISTEXT=16203;var MATCH=16204;var LIT=16205;var CHECK=16206;var LENGTH=16207;var DONE=16208;var BAD=16209;var MEM=16210;var SYNC=16211;var ENOUGH_LENS=852;var ENOUGH_DISTS=592;var MAX_WBITS=15;var DEF_WBITS=MAX_WBITS;var zswap32=q10=>{return(q10>>>24&255)+(q10>>>8&65280)+((q10&65280)<<8)+((q10&255)<<24)};function InflateState(){this.strm=null;this.mode=0;this.last=false;this.wrap=0;this.havedict=false;this.flags=0;this.dmax=0;this.check=0;this.total=0;this.head=null;this.wbits=0;this.wsize=0;this.whave=0;this.wnext=0;this.window=null;this.hold=0;this.bits=0;this.length=0;this.offset=0;this.extra=0;this.lencode=null;this.distcode=null;this.lenbits=0;this.distbits=0;this.ncode=0;this.nlen=0;this.ndist=0;this.have=0;this.next=null;this.lens=new Uint16Array(320);this.work=new Uint16Array(288);this.lendyn=null;this.distdyn=null;this.sane=0;this.back=0;this.was=0}var inflateStateCheck=strm=>{if(!strm){return 1}const state=strm.state;if(!state||state.strm!==strm||state.mode<HEAD||state.mode>SYNC){return 1}return 0};var inflateResetKeep=strm=>{if(inflateStateCheck(strm)){return Z_STREAM_ERROR$1}const state=strm.state;strm.total_in=strm.total_out=state.total=0;strm.msg="";if(state.wrap){strm.adler=state.wrap&1}state.mode=HEAD;state.last=0;state.havedict=0;state.flags=-1;state.dmax=32768;state.head=null;state.hold=0;state.bits=0;state.lencode=state.lendyn=new Int32Array(ENOUGH_LENS);state.distcode=state.distdyn=new Int32Array(ENOUGH_DISTS);state.sane=1;state.back=-1;return Z_OK$1};var inflateReset=strm=>{if(inflateStateCheck(strm)){return Z_STREAM_ERROR$1}const state=strm.state;state.wsize=0;state.whave=0;state.wnext=0;return inflateResetKeep(strm)};var inflateReset2=(strm,windowBits)=>{let wrap2;if(inflateStateCheck(strm)){return Z_STREAM_ERROR$1}const state=strm.state;if(windowBits<0){wrap2=0;windowBits=-windowBits}else{wrap2=(windowBits>>4)+5;if(windowBits<48){windowBits&=15}}if(windowBits&&(windowBits<8||windowBits>15)){return Z_STREAM_ERROR$1}if(state.window!==null&&state.wbits!==windowBits){state.window=null}state.wrap=wrap2;state.wbits=windowBits;return inflateReset(strm)};var inflateInit2=(strm,windowBits)=>{if(!strm){return Z_STREAM_ERROR$1}const state=new InflateState;strm.state=state;state.strm=strm;state.window=null;state.mode=HEAD;const ret=inflateReset2(strm,windowBits);if(ret!==Z_OK$1){strm.state=null}return ret};var inflateInit=strm=>{return inflateInit2(strm,DEF_WBITS)};var virgin=true;var lenfix;var distfix;var fixedtables=state=>{if(virgin){lenfix=new Int32Array(512);distfix=new Int32Array(32);let sym=0;while(sym<144){state.lens[sym++]=8}while(sym<256){state.lens[sym++]=9}while(sym<280){state.lens[sym++]=7}while(sym<288){state.lens[sym++]=8}inftrees(LENS,state.lens,0,288,lenfix,0,state.work,{bits:9});sym=0;while(sym<32){state.lens[sym++]=5}inftrees(DISTS,state.lens,0,32,distfix,0,state.work,{bits:5});virgin=false}state.lencode=lenfix;state.lenbits=9;state.distcode=distfix;state.distbits=5};var updatewindow=(strm,src,end,copy2)=>{let dist;const state=strm.state;if(state.window===null){state.window=new Uint8Array(1<<state.wbits)}if(state.wsize===0){state.wsize=1<<state.wbits;state.wnext=0;state.whave=0}if(copy2>=state.wsize){state.window.set(src.subarray(end-state.wsize,end),0);state.wnext=0;state.whave=state.wsize}else{dist=state.wsize-state.wnext;if(dist>copy2){dist=copy2}state.window.set(src.subarray(end-copy2,end-copy2+dist),state.wnext);copy2-=dist;if(copy2){state.window.set(src.subarray(end-copy2,end),0);state.wnext=copy2;state.whave=state.wsize}else{state.wnext+=dist;if(state.wnext===state.wsize){state.wnext=0}if(state.whave<state.wsize){state.whave+=dist}}}return 0};var inflate$2=(strm,flush2)=>{let state;let input,output;let next2;let put;let have,left;let hold2;let bits;let _in,_out;let copy2;let from;let from_source;let here=0;let here_bits,here_op,here_val;let last_bits,last_op,last_val;let len2;let ret;const hbuf=new Uint8Array(4);let opts;let n8;const order=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(inflateStateCheck(strm)||!strm.output||!strm.input&&strm.avail_in!==0){return Z_STREAM_ERROR$1}state=strm.state;if(state.mode===TYPE){state.mode=TYPEDO}put=strm.next_out;output=strm.output;left=strm.avail_out;next2=strm.next_in;input=strm.input;have=strm.avail_in;hold2=state.hold;bits=state.bits;_in=have;_out=left;ret=Z_OK$1;inf_leave:for(;;){switch(state.mode){case HEAD:if(state.wrap===0){state.mode=TYPEDO;break}while(bits<16){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}if(state.wrap&2&&hold2===35615){if(state.wbits===0){state.wbits=15}state.check=0;hbuf[0]=hold2&255;hbuf[1]=hold2>>>8&255;state.check=crc32_1(state.check,hbuf,2,0);hold2=0;bits=0;state.mode=FLAGS;break}if(state.head){state.head.done=false}if(!(state.wrap&1)||(((hold2&255)<<8)+(hold2>>8))%31){strm.msg="incorrect header check";state.mode=BAD;break}if((hold2&15)!==Z_DEFLATED){strm.msg="unknown compression method";state.mode=BAD;break}hold2>>>=4;bits-=4;len2=(hold2&15)+8;if(state.wbits===0){state.wbits=len2}if(len2>15||len2>state.wbits){strm.msg="invalid window size";state.mode=BAD;break}state.dmax=1<<state.wbits;state.flags=0;strm.adler=state.check=1;state.mode=hold2&512?DICTID:TYPE;hold2=0;bits=0;break;case FLAGS:while(bits<16){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}state.flags=hold2;if((state.flags&255)!==Z_DEFLATED){strm.msg="unknown compression method";state.mode=BAD;break}if(state.flags&57344){strm.msg="unknown header flags set";state.mode=BAD;break}if(state.head){state.head.text=hold2>>8&1}if(state.flags&512&&state.wrap&4){hbuf[0]=hold2&255;hbuf[1]=hold2>>>8&255;state.check=crc32_1(state.check,hbuf,2,0)}hold2=0;bits=0;state.mode=TIME;case TIME:while(bits<32){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}if(state.head){state.head.time=hold2}if(state.flags&512&&state.wrap&4){hbuf[0]=hold2&255;hbuf[1]=hold2>>>8&255;hbuf[2]=hold2>>>16&255;hbuf[3]=hold2>>>24&255;state.check=crc32_1(state.check,hbuf,4,0)}hold2=0;bits=0;state.mode=OS;case OS:while(bits<16){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}if(state.head){state.head.xflags=hold2&255;state.head.os=hold2>>8}if(state.flags&512&&state.wrap&4){hbuf[0]=hold2&255;hbuf[1]=hold2>>>8&255;state.check=crc32_1(state.check,hbuf,2,0)}hold2=0;bits=0;state.mode=EXLEN;case EXLEN:if(state.flags&1024){while(bits<16){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}state.length=hold2;if(state.head){state.head.extra_len=hold2}if(state.flags&512&&state.wrap&4){hbuf[0]=hold2&255;hbuf[1]=hold2>>>8&255;state.check=crc32_1(state.check,hbuf,2,0)}hold2=0;bits=0}else if(state.head){state.head.extra=null}state.mode=EXTRA;case EXTRA:if(state.flags&1024){copy2=state.length;if(copy2>have){copy2=have}if(copy2){if(state.head){len2=state.head.extra_len-state.length;if(!state.head.extra){state.head.extra=new Uint8Array(state.head.extra_len)}state.head.extra.set(input.subarray(next2,next2+copy2),len2)}if(state.flags&512&&state.wrap&4){state.check=crc32_1(state.check,input,copy2,next2)}have-=copy2;next2+=copy2;state.length-=copy2}if(state.length){break inf_leave}}state.length=0;state.mode=NAME;case NAME:if(state.flags&2048){if(have===0){break inf_leave}copy2=0;do{len2=input[next2+copy2++];if(state.head&&len2&&state.length<65536){state.head.name+=String.fromCharCode(len2)}}while(len2&&copy2<have);if(state.flags&512&&state.wrap&4){state.check=crc32_1(state.check,input,copy2,next2)}have-=copy2;next2+=copy2;if(len2){break inf_leave}}else if(state.head){state.head.name=null}state.length=0;state.mode=COMMENT;case COMMENT:if(state.flags&4096){if(have===0){break inf_leave}copy2=0;do{len2=input[next2+copy2++];if(state.head&&len2&&state.length<65536){state.head.comment+=String.fromCharCode(len2)}}while(len2&&copy2<have);if(state.flags&512&&state.wrap&4){state.check=crc32_1(state.check,input,copy2,next2)}have-=copy2;next2+=copy2;if(len2){break inf_leave}}else if(state.head){state.head.comment=null}state.mode=HCRC;case HCRC:if(state.flags&512){while(bits<16){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}if(state.wrap&4&&hold2!==(state.check&65535)){strm.msg="header crc mismatch";state.mode=BAD;break}hold2=0;bits=0}if(state.head){state.head.hcrc=state.flags>>9&1;state.head.done=true}strm.adler=state.check=0;state.mode=TYPE;break;case DICTID:while(bits<32){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}strm.adler=state.check=zswap32(hold2);hold2=0;bits=0;state.mode=DICT;case DICT:if(state.havedict===0){strm.next_out=put;strm.avail_out=left;strm.next_in=next2;strm.avail_in=have;state.hold=hold2;state.bits=bits;return Z_NEED_DICT$1}strm.adler=state.check=1;state.mode=TYPE;case TYPE:if(flush2===Z_BLOCK||flush2===Z_TREES){break inf_leave}case TYPEDO:if(state.last){hold2>>>=bits&7;bits-=bits&7;state.mode=CHECK;break}while(bits<3){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}state.last=hold2&1;hold2>>>=1;bits-=1;switch(hold2&3){case 0:state.mode=STORED;break;case 1:fixedtables(state);state.mode=LEN_;if(flush2===Z_TREES){hold2>>>=2;bits-=2;break inf_leave}break;case 2:state.mode=TABLE;break;case 3:strm.msg="invalid block type";state.mode=BAD}hold2>>>=2;bits-=2;break;case STORED:hold2>>>=bits&7;bits-=bits&7;while(bits<32){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}if((hold2&65535)!==(hold2>>>16^65535)){strm.msg="invalid stored block lengths";state.mode=BAD;break}state.length=hold2&65535;hold2=0;bits=0;state.mode=COPY_;if(flush2===Z_TREES){break inf_leave}case COPY_:state.mode=COPY;case COPY:copy2=state.length;if(copy2){if(copy2>have){copy2=have}if(copy2>left){copy2=left}if(copy2===0){break inf_leave}output.set(input.subarray(next2,next2+copy2),put);have-=copy2;next2+=copy2;left-=copy2;put+=copy2;state.length-=copy2;break}state.mode=TYPE;break;case TABLE:while(bits<14){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}state.nlen=(hold2&31)+257;hold2>>>=5;bits-=5;state.ndist=(hold2&31)+1;hold2>>>=5;bits-=5;state.ncode=(hold2&15)+4;hold2>>>=4;bits-=4;if(state.nlen>286||state.ndist>30){strm.msg="too many length or distance symbols";state.mode=BAD;break}state.have=0;state.mode=LENLENS;case LENLENS:while(state.have<state.ncode){while(bits<3){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}state.lens[order[state.have++]]=hold2&7;hold2>>>=3;bits-=3}while(state.have<19){state.lens[order[state.have++]]=0}state.lencode=state.lendyn;state.lenbits=7;opts={bits:state.lenbits};ret=inftrees(CODES,state.lens,0,19,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid code lengths set";state.mode=BAD;break}state.have=0;state.mode=CODELENS;case CODELENS:while(state.have<state.nlen+state.ndist){for(;;){here=state.lencode[hold2&(1<<state.lenbits)-1];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}if(here_val<16){hold2>>>=here_bits;bits-=here_bits;state.lens[state.have++]=here_val}else{if(here_val===16){n8=here_bits+2;while(bits<n8){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}hold2>>>=here_bits;bits-=here_bits;if(state.have===0){strm.msg="invalid bit length repeat";state.mode=BAD;break}len2=state.lens[state.have-1];copy2=3+(hold2&3);hold2>>>=2;bits-=2}else if(here_val===17){n8=here_bits+3;while(bits<n8){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}hold2>>>=here_bits;bits-=here_bits;len2=0;copy2=3+(hold2&7);hold2>>>=3;bits-=3}else{n8=here_bits+7;while(bits<n8){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}hold2>>>=here_bits;bits-=here_bits;len2=0;copy2=11+(hold2&127);hold2>>>=7;bits-=7}if(state.have+copy2>state.nlen+state.ndist){strm.msg="invalid bit length repeat";state.mode=BAD;break}while(copy2--){state.lens[state.have++]=len2}}}if(state.mode===BAD){break}if(state.lens[256]===0){strm.msg="invalid code -- missing end-of-block";state.mode=BAD;break}state.lenbits=9;opts={bits:state.lenbits};ret=inftrees(LENS,state.lens,0,state.nlen,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid literal/lengths set";state.mode=BAD;break}state.distbits=6;state.distcode=state.distdyn;opts={bits:state.distbits};ret=inftrees(DISTS,state.lens,state.nlen,state.ndist,state.distcode,0,state.work,opts);state.distbits=opts.bits;if(ret){strm.msg="invalid distances set";state.mode=BAD;break}state.mode=LEN_;if(flush2===Z_TREES){break inf_leave}case LEN_:state.mode=LEN;case LEN:if(have>=6&&left>=258){strm.next_out=put;strm.avail_out=left;strm.next_in=next2;strm.avail_in=have;state.hold=hold2;state.bits=bits;inffast(strm,_out);put=strm.next_out;output=strm.output;left=strm.avail_out;next2=strm.next_in;input=strm.input;have=strm.avail_in;hold2=state.hold;bits=state.bits;if(state.mode===TYPE){state.back=-1}break}state.back=0;for(;;){here=state.lencode[hold2&(1<<state.lenbits)-1];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}if(here_op&&(here_op&240)===0){last_bits=here_bits;last_op=here_op;last_val=here_val;for(;;){here=state.lencode[last_val+((hold2&(1<<last_bits+last_op)-1)>>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}hold2>>>=last_bits;bits-=last_bits;state.back+=last_bits}hold2>>>=here_bits;bits-=here_bits;state.back+=here_bits;state.length=here_val;if(here_op===0){state.mode=LIT;break}if(here_op&32){state.back=-1;state.mode=TYPE;break}if(here_op&64){strm.msg="invalid literal/length code";state.mode=BAD;break}state.extra=here_op&15;state.mode=LENEXT;case LENEXT:if(state.extra){n8=state.extra;while(bits<n8){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}state.length+=hold2&(1<<state.extra)-1;hold2>>>=state.extra;bits-=state.extra;state.back+=state.extra}state.was=state.length;state.mode=DIST;case DIST:for(;;){here=state.distcode[hold2&(1<<state.distbits)-1];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}if((here_op&240)===0){last_bits=here_bits;last_op=here_op;last_val=here_val;for(;;){here=state.distcode[last_val+((hold2&(1<<last_bits+last_op)-1)>>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}hold2>>>=last_bits;bits-=last_bits;state.back+=last_bits}hold2>>>=here_bits;bits-=here_bits;state.back+=here_bits;if(here_op&64){strm.msg="invalid distance code";state.mode=BAD;break}state.offset=here_val;state.extra=here_op&15;state.mode=DISTEXT;case DISTEXT:if(state.extra){n8=state.extra;while(bits<n8){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}state.offset+=hold2&(1<<state.extra)-1;hold2>>>=state.extra;bits-=state.extra;state.back+=state.extra}if(state.offset>state.dmax){strm.msg="invalid distance too far back";state.mode=BAD;break}state.mode=MATCH;case MATCH:if(left===0){break inf_leave}copy2=_out-left;if(state.offset>copy2){copy2=state.offset-copy2;if(copy2>state.whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD;break}}if(copy2>state.wnext){copy2-=state.wnext;from=state.wsize-copy2}else{from=state.wnext-copy2}if(copy2>state.length){copy2=state.length}from_source=state.window}else{from_source=output;from=put-state.offset;copy2=state.length}if(copy2>left){copy2=left}left-=copy2;state.length-=copy2;do{output[put++]=from_source[from++]}while(--copy2);if(state.length===0){state.mode=LEN}break;case LIT:if(left===0){break inf_leave}output[put++]=state.length;left--;state.mode=LEN;break;case CHECK:if(state.wrap){while(bits<32){if(have===0){break inf_leave}have--;hold2|=input[next2++]<<bits;bits+=8}_out-=left;strm.total_out+=_out;state.total+=_out;if(state.wrap&4&&_out){strm.adler=state.check=state.flags?crc32_1(state.check,output,_out,put-_out):adler32_1(state.check,output,_out,put-_out)}_out=left;if(state.wrap&4&&(state.flags?hold2:zswap32(hold2))!==state.check){strm.msg="incorrect data check";state.mode=BAD;break}hold2=0;bits=0}state.mode=LENGTH;case LENGTH:if(state.wrap&&state.flags){while(bits<32){if(have===0){break inf_leave}have--;hold2+=input[next2++]<<bits;bits+=8}if(state.wrap&4&&hold2!==(state.total&4294967295)){strm.msg="incorrect length check";state.mode=BAD;break}hold2=0;bits=0}state.mode=DONE;case DONE:ret=Z_STREAM_END$1;break inf_leave;case BAD:ret=Z_DATA_ERROR$1;break inf_leave;case MEM:return Z_MEM_ERROR$1;case SYNC:default:return Z_STREAM_ERROR$1}}strm.next_out=put;strm.avail_out=left;strm.next_in=next2;strm.avail_in=have;state.hold=hold2;state.bits=bits;if(state.wsize||_out!==strm.avail_out&&state.mode<BAD&&(state.mode<CHECK||flush2!==Z_FINISH$1)){if(updatewindow(strm,strm.output,strm.next_out,_out-strm.avail_out));}_in-=strm.avail_in;_out-=strm.avail_out;strm.total_in+=_in;strm.total_out+=_out;state.total+=_out;if(state.wrap&4&&_out){strm.adler=state.check=state.flags?crc32_1(state.check,output,_out,strm.next_out-_out):adler32_1(state.check,output,_out,strm.next_out-_out)}strm.data_type=state.bits+(state.last?64:0)+(state.mode===TYPE?128:0)+(state.mode===LEN_||state.mode===COPY_?256:0);if((_in===0&&_out===0||flush2===Z_FINISH$1)&&ret===Z_OK$1){ret=Z_BUF_ERROR$1}return ret};var inflateEnd=strm=>{if(inflateStateCheck(strm)){return Z_STREAM_ERROR$1}let state=strm.state;if(state.window){state.window=null}strm.state=null;return Z_OK$1};var inflateGetHeader=(strm,head)=>{if(inflateStateCheck(strm)){return Z_STREAM_ERROR$1}const state=strm.state;if((state.wrap&2)===0){return Z_STREAM_ERROR$1}state.head=head;head.done=false;return Z_OK$1};var inflateSetDictionary=(strm,dictionary2)=>{const dictLength=dictionary2.length;let state;let dictid;let ret;if(inflateStateCheck(strm)){return Z_STREAM_ERROR$1}state=strm.state;if(state.wrap!==0&&state.mode!==DICT){return Z_STREAM_ERROR$1}if(state.mode===DICT){dictid=1;dictid=adler32_1(dictid,dictionary2,dictLength,0);if(dictid!==state.check){return Z_DATA_ERROR$1}}ret=updatewindow(strm,dictionary2,dictLength,dictLength);if(ret){state.mode=MEM;return Z_MEM_ERROR$1}state.havedict=1;return Z_OK$1};var inflateReset_1=inflateReset;var inflateReset2_1=inflateReset2;var inflateResetKeep_1=inflateResetKeep;var inflateInit_1=inflateInit;var inflateInit2_1=inflateInit2;var inflate_2$1=inflate$2;var inflateEnd_1=inflateEnd;var inflateGetHeader_1=inflateGetHeader;var inflateSetDictionary_1=inflateSetDictionary;var inflateInfo="pako inflate (from Nodeca project)";var inflate_1$2={inflateReset:inflateReset_1,inflateReset2:inflateReset2_1,inflateResetKeep:inflateResetKeep_1,inflateInit:inflateInit_1,inflateInit2:inflateInit2_1,inflate:inflate_2$1,inflateEnd:inflateEnd_1,inflateGetHeader:inflateGetHeader_1,inflateSetDictionary:inflateSetDictionary_1,inflateInfo};function GZheader(){this.text=0;this.time=0;this.xflags=0;this.os=0;this.extra=null;this.extra_len=0;this.name="";this.comment="";this.hcrc=0;this.done=false}var gzheader=GZheader;var toString=Object.prototype.toString;var{Z_NO_FLUSH,Z_FINISH,Z_OK,Z_STREAM_END,Z_NEED_DICT,Z_STREAM_ERROR,Z_DATA_ERROR,Z_MEM_ERROR,Z_BUF_ERROR}=constants$2;var defaultOptions={chunkSize:1024*64,windowBits:15,to:""};function Inflate$1(options){this.options=common.assign({},defaultOptions,options||{});const opt=this.options;if(opt.raw&&opt.windowBits>=0&&opt.windowBits<16){opt.windowBits=-opt.windowBits;if(opt.windowBits===0){opt.windowBits=-15}}if(opt.windowBits>=0&&opt.windowBits<16&&!(options&&options.windowBits)){opt.windowBits+=32}if(opt.windowBits>15&&opt.windowBits<48){if((opt.windowBits&15)===0){opt.windowBits|=15}}this.err=0;this.msg="";this.ended=false;this.chunks=[];this.strm=new zstream;this.strm.avail_out=0;let status=inflate_1$2.inflateInit2(this.strm,opt.windowBits);if(status!==Z_OK){throw new Error(messages[status])}this.header=new gzheader;inflate_1$2.inflateGetHeader(this.strm,this.header);if(opt.dictionary){if(typeof opt.dictionary==="string"){opt.dictionary=strings.string2buf(opt.dictionary)}else if(toString.call(opt.dictionary)==="[object ArrayBuffer]"){opt.dictionary=new Uint8Array(opt.dictionary)}if(opt.raw){status=inflate_1$2.inflateSetDictionary(this.strm,opt.dictionary);if(status!==Z_OK){throw new Error(messages[status])}}}}Inflate$1.prototype.push=function(data2,flush_mode){const strm=this.strm;const chunkSize=this.options.chunkSize;const dictionary2=this.options.dictionary;let status,_flush_mode,last_avail_out;if(this.ended)return false;if(flush_mode===~~flush_mode)_flush_mode=flush_mode;else _flush_mode=flush_mode===true?Z_FINISH:Z_NO_FLUSH;if(toString.call(data2)==="[object ArrayBuffer]"){strm.input=new Uint8Array(data2)}else{strm.input=data2}strm.next_in=0;strm.avail_in=strm.input.length;for(;;){if(strm.avail_out===0){strm.output=new Uint8Array(chunkSize);strm.next_out=0;strm.avail_out=chunkSize}status=inflate_1$2.inflate(strm,_flush_mode);if(status===Z_NEED_DICT&&dictionary2){status=inflate_1$2.inflateSetDictionary(strm,dictionary2);if(status===Z_OK){status=inflate_1$2.inflate(strm,_flush_mode)}else if(status===Z_DATA_ERROR){status=Z_NEED_DICT}}while(strm.avail_in>0&&status===Z_STREAM_END&&strm.state.wrap&2&&strm.state.flags!==0&&strm.input[strm.next_in]!==0){inflate_1$2.inflateReset(strm);status=inflate_1$2.inflate(strm,_flush_mode)}switch(status){case Z_STREAM_ERROR:case Z_DATA_ERROR:case Z_NEED_DICT:case Z_MEM_ERROR:this.onEnd(status);this.ended=true;return false}last_avail_out=strm.avail_out;if(strm.next_out){if(strm.avail_out===0||status===Z_STREAM_END||_flush_mode>0){if(this.options.to==="string"){let next_out_utf8=strings.utf8border(strm.output,strm.next_out);let tail=strm.next_out-next_out_utf8;let utf8str=strings.buf2string(strm.output,next_out_utf8);strm.next_out=tail;strm.avail_out=chunkSize-tail;if(tail)strm.output.set(strm.output.subarray(next_out_utf8,next_out_utf8+tail),0);this.onData(utf8str)}else{this.onData(strm.output.length===strm.next_out?strm.output:strm.output.subarray(0,strm.next_out));strm.avail_out=0;strm.next_out=0}}}if((status===Z_OK||status===Z_BUF_ERROR)&&last_avail_out===0)continue;if(status===Z_STREAM_END){status=inflate_1$2.inflateEnd(this.strm);this.onEnd(status);this.ended=true;return true}if(strm.avail_in===0){if(_flush_mode===Z_FINISH){status=inflate_1$2.inflateEnd(this.strm);this.onEnd(status===Z_OK?Z_BUF_ERROR:status);this.ended=true;return false}break}}return true};Inflate$1.prototype.onData=function(chunk){this.chunks.push(chunk)};Inflate$1.prototype.onEnd=function(status){if(status===Z_OK){if(this.options.to==="string"){this.result=this.chunks.join("")}else{this.result=common.flattenChunks(this.chunks)}}this.chunks=[];this.err=status;this.msg=this.strm.msg};function inflate$1(input,options){const inflator=new Inflate$1(options);inflator.push(input,true);if(inflator.err)throw inflator.msg||messages[inflator.err];return inflator.result}function inflateRaw$1(input,options){options=options||{};options.raw=true;return inflate$1(input,options)}var Inflate_1$1=Inflate$1;var inflate_2=inflate$1;var inflateRaw_1$1=inflateRaw$1;var ungzip$1=inflate$1;var constants=constants$2;var inflate_1$1={Inflate:Inflate_1$1,inflate:inflate_2,inflateRaw:inflateRaw_1$1,ungzip:ungzip$1,constants};var{Deflate,deflate,deflateRaw,gzip}=deflate_1$1;var{Inflate,inflate,inflateRaw,ungzip}=inflate_1$1;var Deflate_1=Deflate;var deflate_1=deflate;var deflateRaw_1=deflateRaw;var gzip_1=gzip;var Inflate_1=Inflate;var inflate_1=inflate;var inflateRaw_1=inflateRaw;var ungzip_1=ungzip;var constants_1=constants$2;var pako={Deflate:Deflate_1,deflate:deflate_1,deflateRaw:deflateRaw_1,gzip:gzip_1,Inflate:Inflate_1,inflate:inflate_1,inflateRaw:inflateRaw_1,ungzip:ungzip_1,constants:constants_1};var constants2=Object.freeze({Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1});function bytesOf(data2){if(typeof data2==="string")return new TextEncoder().encode(data2);return data2 instanceof Uint8Array?data2:new Uint8Array(data2)}function gzipSync(data2,options={}){const level=options.level??constants2.Z_DEFAULT_COMPRESSION;if(!Number.isInteger(level)||level<-1||level>9)throw new RangeError(`The value of "options.level" is out of range. It must be >= -1 and <= 9. Received ${level}`);return pako.gzip(bytesOf(data2),{level})}function gunzipSync(data2,options={}){const output=pako.ungzip(bytesOf(data2));if(options.maxOutputLength!==void 0&&output.byteLength>options.maxOutputLength){throw Object.assign(new RangeError(`Cannot create a Buffer larger than ${options.maxOutputLength} bytes`),{code:"ERR_BUFFER_TOO_LARGE"})}return output}var Diff=class{diff(oldStr,newStr,options={}){let callback;if(typeof options==="function"){callback=options;options={}}else if("callback"in options){callback=options.callback}const oldString=this.castInput(oldStr,options);const newString=this.castInput(newStr,options);const oldTokens=this.removeEmpty(this.tokenize(oldString,options));const newTokens=this.removeEmpty(this.tokenize(newString,options));return this.diffWithOptionsObj(oldTokens,newTokens,options,callback)}diffWithOptionsObj(oldTokens,newTokens,options,callback){var _a4;const done=value=>{value=this.postProcess(value,options);if(callback){setTimeout(function(){callback(value)},0);return void 0}else{return value}};const newLen=newTokens.length,oldLen=oldTokens.length;let editLength=1;let maxEditLength=newLen+oldLen;if(options.maxEditLength!=null){maxEditLength=Math.min(maxEditLength,options.maxEditLength)}const maxExecutionTime=(_a4=options.timeout)!==null&&_a4!==void 0?_a4:Infinity;const abortAfterTimestamp=Date.now()+maxExecutionTime;const bestPath=[{oldPos:-1,lastComponent:void 0}];let newPos=this.extractCommon(bestPath[0],newTokens,oldTokens,0,options);if(bestPath[0].oldPos+1>=oldLen&&newPos+1>=newLen){return done(this.buildValues(bestPath[0].lastComponent,newTokens,oldTokens))}let minDiagonalToConsider=-Infinity,maxDiagonalToConsider=Infinity;const execEditLength=()=>{for(let diagonalPath=Math.max(minDiagonalToConsider,-editLength);diagonalPath<=Math.min(maxDiagonalToConsider,editLength);diagonalPath+=2){let basePath;const removePath2=bestPath[diagonalPath-1],addPath=bestPath[diagonalPath+1];if(removePath2){bestPath[diagonalPath-1]=void 0}let canAdd=false;if(addPath){const addPathNewPos=addPath.oldPos-diagonalPath;canAdd=addPath&&0<=addPathNewPos&&addPathNewPos<newLen}const canRemove=removePath2&&removePath2.oldPos+1<oldLen;if(!canAdd&&!canRemove){bestPath[diagonalPath]=void 0;continue}if(!canRemove||canAdd&&removePath2.oldPos<addPath.oldPos){basePath=this.addToPath(addPath,true,false,0,options)}else{basePath=this.addToPath(removePath2,false,true,1,options)}newPos=this.extractCommon(basePath,newTokens,oldTokens,diagonalPath,options);if(basePath.oldPos+1>=oldLen&&newPos+1>=newLen){return done(this.buildValues(basePath.lastComponent,newTokens,oldTokens))||true}else{bestPath[diagonalPath]=basePath;if(basePath.oldPos+1>=oldLen){maxDiagonalToConsider=Math.min(maxDiagonalToConsider,diagonalPath-1)}if(newPos+1>=newLen){minDiagonalToConsider=Math.max(minDiagonalToConsider,diagonalPath+1)}}}editLength++};if(callback){(function exec(){setTimeout(function(){if(editLength>maxEditLength||Date.now()>abortAfterTimestamp){return callback(void 0)}if(!execEditLength()){exec()}},0)})()}else{while(editLength<=maxEditLength&&Date.now()<=abortAfterTimestamp){const ret=execEditLength();if(ret){return ret}}}}addToPath(path3,added,removed,oldPosInc,options){const last=path3.lastComponent;if(last&&!options.oneChangePerToken&&last.added===added&&last.removed===removed){return{oldPos:path3.oldPos+oldPosInc,lastComponent:{count:last.count+1,added,removed,previousComponent:last.previousComponent}}}else{return{oldPos:path3.oldPos+oldPosInc,lastComponent:{count:1,added,removed,previousComponent:last}}}}extractCommon(basePath,newTokens,oldTokens,diagonalPath,options){const newLen=newTokens.length,oldLen=oldTokens.length;let oldPos=basePath.oldPos,newPos=oldPos-diagonalPath,commonCount=0;while(newPos+1<newLen&&oldPos+1<oldLen&&this.equals(oldTokens[oldPos+1],newTokens[newPos+1],options)){newPos++;oldPos++;commonCount++;if(options.oneChangePerToken){basePath.lastComponent={count:1,previousComponent:basePath.lastComponent,added:false,removed:false}}}if(commonCount&&!options.oneChangePerToken){basePath.lastComponent={count:commonCount,previousComponent:basePath.lastComponent,added:false,removed:false}}basePath.oldPos=oldPos;return newPos}equals(left,right,options){if(options.comparator){return options.comparator(left,right)}else{return left===right||!!options.ignoreCase&&left.toLowerCase()===right.toLowerCase()}}removeEmpty(array){const ret=[];for(let i10=0;i10<array.length;i10++){if(array[i10]){ret.push(array[i10])}}return ret}castInput(value,options){return value}tokenize(value,options){return Array.from(value)}join(chars){return chars.join("")}postProcess(changeObjects,options){return changeObjects}get useLongestToken(){return false}buildValues(lastComponent,newTokens,oldTokens){const components=[];let nextComponent;while(lastComponent){components.push(lastComponent);nextComponent=lastComponent.previousComponent;delete lastComponent.previousComponent;lastComponent=nextComponent}components.reverse();const componentLen=components.length;let componentPos=0,newPos=0,oldPos=0;for(;componentPos<componentLen;componentPos++){const component=components[componentPos];if(!component.removed){if(!component.added&&this.useLongestToken){let value=newTokens.slice(newPos,newPos+component.count);value=value.map(function(value2,i10){const oldValue=oldTokens[oldPos+i10];return oldValue.length>value2.length?oldValue:value2});component.value=this.join(value)}else{component.value=this.join(newTokens.slice(newPos,newPos+component.count))}newPos+=component.count;if(!component.added){oldPos+=component.count}}else{component.value=this.join(oldTokens.slice(oldPos,oldPos+component.count));oldPos+=component.count}}return components}};var LineDiff=class extends Diff{constructor(){super(...arguments);this.tokenize=tokenize}equals(left,right,options){if(options.ignoreWhitespace){if(!options.newlineIsToken||!left.includes("\n")){left=left.trim()}if(!options.newlineIsToken||!right.includes("\n")){right=right.trim()}}else if(options.ignoreNewlineAtEof&&!options.newlineIsToken){if(left.endsWith("\n")){left=left.slice(0,-1)}if(right.endsWith("\n")){right=right.slice(0,-1)}}return super.equals(left,right,options)}};var lineDiff=new LineDiff;function diffLines(oldStr,newStr,options){return lineDiff.diff(oldStr,newStr,options)}function tokenize(value,options){if(options.stripTrailingCr){value=value.replace(/\r\n/g,"\n")}const retLines=[],linesAndNewlines=value.split(/(\n|\r\n)/);if(!linesAndNewlines[linesAndNewlines.length-1]){linesAndNewlines.pop()}for(let i10=0;i10<linesAndNewlines.length;i10++){const line=linesAndNewlines[i10];if(i10%2&&!options.newlineIsToken){retLines[retLines.length-1]+=line}else{retLines.push(line)}}return retLines}var INCLUDE_HEADERS={includeIndex:true,includeUnderline:true,includeFileHeaders:true};function structuredPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,options){let optionsObj;if(!options){optionsObj={}}else if(typeof options==="function"){optionsObj={callback:options}}else{optionsObj=options}if(typeof optionsObj.context==="undefined"){optionsObj.context=4}const context2=optionsObj.context;if(optionsObj.newlineIsToken){throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions")}if(!optionsObj.callback){return diffLinesResultToPatch(diffLines(oldStr,newStr,optionsObj))}else{const{callback}=optionsObj;diffLines(oldStr,newStr,Object.assign(Object.assign({},optionsObj),{callback:diff=>{const patch=diffLinesResultToPatch(diff);callback(patch)}}))}function diffLinesResultToPatch(diff){if(!diff){return}diff.push({value:"",lines:[]});function contextLines(lines){return lines.map(function(entry){return" "+entry})}const hunks=[];let oldRangeStart=0,newRangeStart=0,curRange=[],oldLine=1,newLine=1;for(let i10=0;i10<diff.length;i10++){const current3=diff[i10],lines=current3.lines||splitLines(current3.value);current3.lines=lines;if(current3.added||current3.removed){if(!oldRangeStart){const prev=diff[i10-1];oldRangeStart=oldLine;newRangeStart=newLine;if(prev){curRange=context2>0?contextLines(prev.lines.slice(-context2)):[];oldRangeStart-=curRange.length;newRangeStart-=curRange.length}}for(const line of lines){curRange.push((current3.added?"+":"-")+line)}if(current3.added){newLine+=lines.length}else{oldLine+=lines.length}}else{if(oldRangeStart){if(lines.length<=context2*2&&i10<diff.length-2){for(const line of contextLines(lines)){curRange.push(line)}}else{const contextSize=Math.min(lines.length,context2);for(const line of contextLines(lines.slice(0,contextSize))){curRange.push(line)}const hunk={oldStart:oldRangeStart,oldLines:oldLine-oldRangeStart+contextSize,newStart:newRangeStart,newLines:newLine-newRangeStart+contextSize,lines:curRange};hunks.push(hunk);oldRangeStart=0;newRangeStart=0;curRange=[]}}oldLine+=lines.length;newLine+=lines.length}}for(const hunk of hunks){for(let i10=0;i10<hunk.lines.length;i10++){if(hunk.lines[i10].endsWith("\n")){hunk.lines[i10]=hunk.lines[i10].slice(0,-1)}else{hunk.lines.splice(i10+1,0,"\");i10++}}}return{oldFileName,newFileName,oldHeader,newHeader,hunks}}}function formatPatch(patch,headerOptions){if(!headerOptions){headerOptions=INCLUDE_HEADERS}if(Array.isArray(patch)){if(patch.length>1&&!headerOptions.includeFileHeaders){throw new Error("Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)")}return patch.map(p=>formatPatch(p,headerOptions)).join("\n")}const ret=[];if(headerOptions.includeIndex&&patch.oldFileName==patch.newFileName){ret.push("Index: "+patch.oldFileName)}if(headerOptions.includeUnderline){ret.push("===================================================================")}if(headerOptions.includeFileHeaders){ret.push("--- "+patch.oldFileName+(typeof patch.oldHeader==="undefined"?"":" "+patch.oldHeader));ret.push("+++ "+patch.newFileName+(typeof patch.newHeader==="undefined"?"":" "+patch.newHeader))}for(let i10=0;i10<patch.hunks.length;i10++){const hunk=patch.hunks[i10];if(hunk.oldLines===0){hunk.oldStart-=1}if(hunk.newLines===0){hunk.newStart-=1}ret.push("@@ -"+hunk.oldStart+","+hunk.oldLines+" +"+hunk.newStart+","+hunk.newLines+" @@");for(const line of hunk.lines){ret.push(line)}}return ret.join("\n")+"\n"}function createTwoFilesPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,options){if(typeof options==="function"){options={callback:options}}if(!(options===null||options===void 0?void 0:options.callback)){const patchObj=structuredPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,options);if(!patchObj){return}return formatPatch(patchObj,options===null||options===void 0?void 0:options.headerOptions)}else{const{callback}=options;structuredPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,Object.assign(Object.assign({},options),{callback:patchObj=>{if(!patchObj){callback(void 0)}else{callback(formatPatch(patchObj,options.headerOptions))}}}))}}function splitLines(text){const hasTrailingNl=text.endsWith("\n");const result=text.split("\n").map(line=>line+"\n");if(hasTrailingNl){result.pop()}else{result.push(result.pop().slice(0,-1))}return result}function extend(destination){for(var i10=1;i10<arguments.length;i10++){var source=arguments[i10];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key))destination[key]=source[key]}}return destination}function repeat(character,count){return Array(count+1).join(character)}function trimLeadingNewlines(string){return string.replace(/^\n*/,"")}function trimTrailingNewlines(string){var indexEnd=string.length;while(indexEnd>0&&string[indexEnd-1]==="\n")indexEnd--;return string.substring(0,indexEnd)}function trimNewlines(string){return trimTrailingNewlines(trimLeadingNewlines(string))}var blockElements=["ADDRESS","ARTICLE","ASIDE","AUDIO","BLOCKQUOTE","BODY","CANVAS","CENTER","DD","DIR","DIV","DL","DT","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","FRAMESET","H1","H2","H3","H4","H5","H6","HEADER","HGROUP","HR","HTML","ISINDEX","LI","MAIN","MENU","NAV","NOFRAMES","NOSCRIPT","OL","OUTPUT","P","PRE","SECTION","TABLE","TBODY","TD","TFOOT","TH","THEAD","TR","UL"];function isBlock(node){return is(node,blockElements)}var voidElements=["AREA","BASE","BR","COL","COMMAND","EMBED","HR","IMG","INPUT","KEYGEN","LINK","META","PARAM","SOURCE","TRACK","WBR"];function isVoid(node){return is(node,voidElements)}function hasVoid(node){return has(node,voidElements)}var meaningfulWhenBlankElements=["A","TABLE","THEAD","TBODY","TFOOT","TH","TD","IFRAME","SCRIPT","AUDIO","VIDEO"];function isMeaningfulWhenBlank(node){return is(node,meaningfulWhenBlankElements)}function hasMeaningfulWhenBlank(node){return has(node,meaningfulWhenBlankElements)}function is(node,tagNames){return tagNames.indexOf(node.nodeName)>=0}function has(node,tagNames){return node.getElementsByTagName&&tagNames.some(function(tagName){return node.getElementsByTagName(tagName).length})}var markdownEscapes=[[/\\/g,"\\\\"],[/\*/g,"\\*"],[/^-/g,"\\-"],[/^\+ /g,"\\+ "],[/^(=+)/g,"\\$1"],[/^(#{1,6}) /g,"\\$1 "],[/`/g,"\\`"],[/^~~~/g,"\\~~~"],[/\[/g,"\\["],[/\]/g,"\\]"],[/^>/g,"\\>"],[/_/g,"\\_"],[/^(\d+)\. /g,"$1\\. "]];function escapeMarkdown(string){return markdownEscapes.reduce(function(accumulator,escape2){return accumulator.replace(escape2[0],escape2[1])},string)}var rules={};rules.paragraph={filter:"p",replacement:function(content){return"\n\n"+content+"\n\n"}};rules.lineBreak={filter:"br",replacement:function(content,node,options){return options.br+"\n"}};rules.heading={filter:["h1","h2","h3","h4","h5","h6"],replacement:function(content,node,options){var hLevel=Number(node.nodeName.charAt(1));if(options.headingStyle==="setext"&&hLevel<3){var underline=repeat(hLevel===1?"=":"-",content.length);return"\n\n"+content+"\n"+underline+"\n\n"}else{return"\n\n"+repeat("#",hLevel)+" "+content+"\n\n"}}};rules.blockquote={filter:"blockquote",replacement:function(content){content=trimNewlines(content).replace(/^/gm,"> ");return"\n\n"+content+"\n\n"}};rules.list={filter:["ul","ol"],replacement:function(content,node){var parent=node.parentNode;if(parent.nodeName==="LI"&&parent.lastElementChild===node){return"\n"+content}else{return"\n\n"+content+"\n\n"}}};rules.listItem={filter:"li",replacement:function(content,node,options){var prefix2=options.bulletListMarker+" ";var parent=node.parentNode;if(parent.nodeName==="OL"){var start=parent.getAttribute("start");var index2=Array.prototype.indexOf.call(parent.children,node);prefix2=(start?Number(start)+index2:index2+1)+". "}var isParagraph=/\n$/.test(content);content=trimNewlines(content)+(isParagraph?"\n":"");content=content.replace(/\n/gm,"\n"+" ".repeat(prefix2.length));return prefix2+content+(node.nextSibling?"\n":"")}};rules.indentedCodeBlock={filter:function(node,options){return options.codeBlockStyle==="indented"&&node.nodeName==="PRE"&&node.firstChild&&node.firstChild.nodeName==="CODE"},replacement:function(content,node,options){return"\n\n "+node.firstChild.textContent.replace(/\n/g,"\n ")+"\n\n"}};rules.fencedCodeBlock={filter:function(node,options){return options.codeBlockStyle==="fenced"&&node.nodeName==="PRE"&&node.firstChild&&node.firstChild.nodeName==="CODE"},replacement:function(content,node,options){var className=node.firstChild.getAttribute("class")||"";var language=(className.match(/language-(\S+)/)||[null,""])[1];var code3=node.firstChild.textContent;var fenceChar=options.fence.charAt(0);var fenceSize=3;var fenceInCodeRegex=new RegExp("^"+fenceChar+"{3,}","gm");var match2;while(match2=fenceInCodeRegex.exec(code3)){if(match2[0].length>=fenceSize){fenceSize=match2[0].length+1}}var fence=repeat(fenceChar,fenceSize);return"\n\n"+fence+language+"\n"+code3.replace(/\n$/,"")+"\n"+fence+"\n\n"}};rules.horizontalRule={filter:"hr",replacement:function(content,node,options){return"\n\n"+options.hr+"\n\n"}};rules.inlineLink={filter:function(node,options){return options.linkStyle==="inlined"&&node.nodeName==="A"&&node.getAttribute("href")},replacement:function(content,node){var href=escapeLinkDestination(node.getAttribute("href"));var title=escapeLinkTitle(cleanAttribute(node.getAttribute("title")));var titlePart=title?' "'+title+'"':"";return"["+content+"]("+href+titlePart+")"}};rules.referenceLink={filter:function(node,options){return options.linkStyle==="referenced"&&node.nodeName==="A"&&node.getAttribute("href")},replacement:function(content,node,options){var href=escapeLinkDestination(node.getAttribute("href"));var title=cleanAttribute(node.getAttribute("title"));if(title)title=' "'+escapeLinkTitle(title)+'"';var replacement;var reference;switch(options.linkReferenceStyle){case"collapsed":replacement="["+content+"][]";reference="["+content+"]: "+href+title;break;case"shortcut":replacement="["+content+"]";reference="["+content+"]: "+href+title;break;default:var id2=this.references.length+1;replacement="["+content+"]["+id2+"]";reference="["+id2+"]: "+href+title}this.references.push(reference);return replacement},references:[],append:function(options){var references="";if(this.references.length){references="\n\n"+this.references.join("\n")+"\n\n";this.references=[]}return references}};rules.emphasis={filter:["em","i"],replacement:function(content,node,options){if(!content.trim())return"";return options.emDelimiter+content+options.emDelimiter}};rules.strong={filter:["strong","b"],replacement:function(content,node,options){if(!content.trim())return"";return options.strongDelimiter+content+options.strongDelimiter}};rules.code={filter:function(node){var hasSiblings=node.previousSibling||node.nextSibling;var isCodeBlock=node.parentNode.nodeName==="PRE"&&!hasSiblings;return node.nodeName==="CODE"&&!isCodeBlock},replacement:function(content){if(!content)return"";content=content.replace(/\r?\n|\r/g," ");var extraSpace=/^`|^ .*?[^ ].* $|`$/.test(content)?" ":"";var delimiter2="`";var matches=content.match(/`+/gm)||[];while(matches.indexOf(delimiter2)!==-1)delimiter2=delimiter2+"`";return delimiter2+extraSpace+content+extraSpace+delimiter2}};rules.image={filter:"img",replacement:function(content,node){var alt=escapeMarkdown(cleanAttribute(node.getAttribute("alt")));var src=escapeLinkDestination(node.getAttribute("src")||"");var title=cleanAttribute(node.getAttribute("title"));var titlePart=title?' "'+escapeLinkTitle(title)+'"':"";return src?"!["+alt+"]("+src+titlePart+")":""}};function cleanAttribute(attribute){return attribute?attribute.replace(/(\n+\s*)+/g,"\n"):""}function escapeLinkDestination(destination){var escaped=destination.replace(/([<>()])/g,"\\$1");return escaped.indexOf(" ")>=0?"<"+escaped+">":escaped}function escapeLinkTitle(title){return title.replace(/"/g,'\\"')}function Rules(options){this.options=options;this._keep=[];this._remove=[];this.blankRule={replacement:options.blankReplacement};this.keepReplacement=options.keepReplacement;this.defaultRule={replacement:options.defaultReplacement};this.array=[];for(var key in options.rules)this.array.push(options.rules[key])}Rules.prototype={add:function(key,rule){this.array.unshift(rule)},keep:function(filter2){this._keep.unshift({filter:filter2,replacement:this.keepReplacement})},remove:function(filter2){this._remove.unshift({filter:filter2,replacement:function(){return""}})},forNode:function(node){if(node.isBlank)return this.blankRule;var rule;if(rule=findRule(this.array,node,this.options))return rule;if(rule=findRule(this._keep,node,this.options))return rule;if(rule=findRule(this._remove,node,this.options))return rule;return this.defaultRule},forEach:function(fn2){for(var i10=0;i10<this.array.length;i10++)fn2(this.array[i10],i10)}};function findRule(rules2,node,options){for(var i10=0;i10<rules2.length;i10++){var rule=rules2[i10];if(filterValue(rule,node,options))return rule}return void 0}function filterValue(rule,node,options){var filter2=rule.filter;if(typeof filter2==="string"){if(filter2===node.nodeName.toLowerCase())return true}else if(Array.isArray(filter2)){if(filter2.indexOf(node.nodeName.toLowerCase())>-1)return true}else if(typeof filter2==="function"){if(filter2.call(rule,node,options))return true}else{throw new TypeError("`filter` needs to be a string, array, or function")}}function collapseWhitespace(options){var element=options.element;var isBlock2=options.isBlock;var isVoid2=options.isVoid;var isPre=options.isPre||function(node2){return node2.nodeName==="PRE"};if(!element.firstChild||isPre(element))return;var prevText=null;var keepLeadingWs=false;var prev=null;var node=next(prev,element,isPre);while(node!==element){if(node.nodeType===3||node.nodeType===4){var text=node.data.replace(/[ \r\n\t]+/g," ");if((!prevText||/ $/.test(prevText.data))&&!keepLeadingWs&&text[0]===" "){text=text.substr(1)}if(!text){node=remove(node);continue}node.data=text;prevText=node}else if(node.nodeType===1){if(isBlock2(node)||node.nodeName==="BR"){if(prevText){prevText.data=prevText.data.replace(/ $/,"")}prevText=null;keepLeadingWs=false}else if(isVoid2(node)||isPre(node)){prevText=null;keepLeadingWs=true}else if(prevText){keepLeadingWs=false}}else{node=remove(node);continue}var nextNode=next(prev,node,isPre);prev=node;node=nextNode}if(prevText){prevText.data=prevText.data.replace(/ $/,"");if(!prevText.data){remove(prevText)}}}function remove(node){var next2=node.nextSibling||node.parentNode;node.parentNode.removeChild(node);return next2}function next(prev,current3,isPre){if(prev&&prev.parentNode===current3||isPre(current3)){return current3.nextSibling||current3.parentNode}return current3.firstChild||current3.nextSibling||current3.parentNode}var root=typeof window!=="undefined"?window:{};function canParseHTMLNatively(){var Parser3=root.DOMParser;var canParse=false;try{if(new Parser3().parseFromString("","text/html")){canParse=true}}catch(e2){}return canParse}function createHTMLParser(){var Parser3=function(){};{if(shouldUseActiveX()){Parser3.prototype.parseFromString=function(string){var doc=new window.ActiveXObject("htmlfile");doc.designMode="on";doc.open();doc.write(string);doc.close();return doc}}else{Parser3.prototype.parseFromString=function(string){var doc=document.implementation.createHTMLDocument("");doc.open();doc.write(string);doc.close();return doc}}}return Parser3}function shouldUseActiveX(){var useActiveX=false;try{document.implementation.createHTMLDocument("").open()}catch(e2){if(root.ActiveXObject)useActiveX=true}return useActiveX}var HTMLParser=canParseHTMLNatively()?root.DOMParser:createHTMLParser();function RootNode(input,options){var root2;if(typeof input==="string"){var doc=htmlParser().parseFromString('<x-turndown id="turndown-root">'+input+"</x-turndown>","text/html");root2=doc.getElementById("turndown-root")}else{root2=input.cloneNode(true)}collapseWhitespace({element:root2,isBlock,isVoid,isPre:options.preformattedCode?isPreOrCode:null});return root2}var _htmlParser;function htmlParser(){_htmlParser=_htmlParser||new HTMLParser;return _htmlParser}function isPreOrCode(node){return node.nodeName==="PRE"||node.nodeName==="CODE"}function Node(node,options){node.isBlock=isBlock(node);node.isCode=node.nodeName==="CODE"||node.parentNode.isCode;node.isBlank=isBlank(node);node.flankingWhitespace=flankingWhitespace(node,options);return node}function isBlank(node){return!isVoid(node)&&!isMeaningfulWhenBlank(node)&&/^\s*$/i.test(node.textContent)&&!hasVoid(node)&&!hasMeaningfulWhenBlank(node)}function flankingWhitespace(node,options){if(node.isBlock||options.preformattedCode&&node.isCode){return{leading:"",trailing:""}}var edges=edgeWhitespace(node.textContent);if(edges.leadingAscii&&isFlankedByWhitespace("left",node,options)){edges.leading=edges.leadingNonAscii}if(edges.trailingAscii&&isFlankedByWhitespace("right",node,options)){edges.trailing=edges.trailingNonAscii}return{leading:edges.leading,trailing:edges.trailing}}function edgeWhitespace(string){var m=string.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/);return{leading:m[1],leadingAscii:m[2],leadingNonAscii:m[3],trailing:m[4],trailingNonAscii:m[5],trailingAscii:m[6]}}function isFlankedByWhitespace(side,node,options){var sibling2;var regExp;var isFlanked;if(side==="left"){sibling2=node.previousSibling;regExp=/ $/}else{sibling2=node.nextSibling;regExp=/^ /}if(sibling2){if(sibling2.nodeType===3){isFlanked=regExp.test(sibling2.nodeValue)}else if(options.preformattedCode&&sibling2.nodeName==="CODE"){isFlanked=false}else if(sibling2.nodeType===1&&!isBlock(sibling2)){isFlanked=regExp.test(sibling2.textContent)}}return isFlanked}var reduce=Array.prototype.reduce;function TurndownService(options){if(!(this instanceof TurndownService))return new TurndownService(options);var defaults2={rules,headingStyle:"setext",hr:"* * *",bulletListMarker:"*",codeBlockStyle:"indented",fence:"```",emDelimiter:"_",strongDelimiter:"**",linkStyle:"inlined",linkReferenceStyle:"full",br:" ",preformattedCode:false,blankReplacement:function(content,node){return node.isBlock?"\n\n":""},keepReplacement:function(content,node){return node.isBlock?"\n\n"+node.outerHTML+"\n\n":node.outerHTML},defaultReplacement:function(content,node){return node.isBlock?"\n\n"+content+"\n\n":content}};this.options=extend({},defaults2,options);this.rules=new Rules(this.options)}TurndownService.prototype={turndown:function(input){if(!canConvert(input)){throw new TypeError(input+" is not a string, or an element/document/fragment node.")}if(input==="")return"";var output=process2.call(this,new RootNode(input,this.options));return postProcess.call(this,output)},use:function(plugin){if(Array.isArray(plugin)){for(var i10=0;i10<plugin.length;i10++)this.use(plugin[i10])}else if(typeof plugin==="function"){plugin(this)}else{throw new TypeError("plugin must be a Function or an Array of Functions")}return this},addRule:function(key,rule){this.rules.add(key,rule);return this},keep:function(filter2){this.rules.keep(filter2);return this},remove:function(filter2){this.rules.remove(filter2);return this},escape:function(string){return escapeMarkdown(string)}};function process2(parentNode){var self2=this;return reduce.call(parentNode.childNodes,function(output,node){node=new Node(node,self2.options);var replacement="";if(node.nodeType===3){replacement=node.isCode?node.nodeValue:self2.escape(node.nodeValue)}else if(node.nodeType===1){replacement=replacementForNode.call(self2,node)}return join(output,replacement)},"")}function postProcess(output){var self2=this;this.rules.forEach(function(rule){if(typeof rule.append==="function"){output=join(output,rule.append(self2.options))}});return output.replace(/^[\t\r\n]+/,"").replace(/[\t\r\n\s]+$/,"")}function replacementForNode(node){var rule=this.rules.forNode(node);var content=process2.call(this,node);var whitespace=node.flankingWhitespace;if(whitespace.leading||whitespace.trailing)content=content.trim();return whitespace.leading+rule.replacement(content,node,this.options)+whitespace.trailing}function join(output,replacement){var s12=trimTrailingNewlines(output);var s22=trimLeadingNewlines(replacement);var nls=Math.max(output.length-s12.length,replacement.length-s22.length);var separator="\n\n".substring(0,nls);return s12+separator+s22}function canConvert(input){return input!=null&&(typeof input==="string"||input.nodeType&&(input.nodeType===1||input.nodeType===9||input.nodeType===11))}var P7=Object.create;var Ua=Object.defineProperty;var D7=Object.getOwnPropertyDescriptor;var _7=Object.getOwnPropertyNames;var F7=Object.getPrototypeOf;var L7=Object.prototype.hasOwnProperty;var qn=(e2=>typeof __require<"u"?__require:typeof Proxy<"u"?new Proxy(e2,{get:(t10,n8)=>(typeof __require<"u"?__require:t10)[n8]}):e2)(function(e2){if(typeof __require<"u")return __require.apply(this,arguments);throw Error('Dynamic require of "'+e2+'" is not supported')});var v=(e2,t10)=>()=>(e2&&(t10=e2(e2=0)),t10);var Oi=(e2,t10)=>()=>(t10||e2((t10={exports:{}}).exports,t10),t10.exports);var ee=(e2,t10)=>{for(var n8 in t10)Ua(e2,n8,{get:t10[n8],enumerable:true})};var M7=(e2,t10,n8,r10)=>{if(t10&&typeof t10=="object"||typeof t10=="function")for(let s10 of _7(t10))!L7.call(e2,s10)&&s10!==n8&&Ua(e2,s10,{get:()=>t10[s10],enumerable:!(r10=D7(t10,s10))||r10.enumerable});return e2};var kf=(e2,t10,n8)=>(n8=e2!=null?P7(F7(e2)):{},M7(t10||!e2||!e2.__esModule?Ua(n8,"default",{value:e2,enumerable:true}):n8,e2));function Nf(){let e2=[{prop:"Function",target:globalThis,violationType:"function_constructor",strategy:"throw",reason:"Function constructor allows arbitrary code execution"},{prop:"eval",target:globalThis,violationType:"eval",strategy:"throw",reason:"eval() allows arbitrary code execution"},{prop:"setTimeout",target:globalThis,violationType:"setTimeout",strategy:"throw",reason:"setTimeout with string argument allows code execution"},{prop:"setInterval",target:globalThis,violationType:"setInterval",strategy:"throw",reason:"setInterval with string argument allows code execution"},{prop:"setImmediate",target:globalThis,violationType:"setImmediate",strategy:"throw",reason:"setImmediate could be used to escape sandbox context"},{prop:"env",target:process,violationType:"process_env",strategy:"throw",reason:"process.env could leak sensitive environment variables",allowedKeys:new Set(["NODE_V8_COVERAGE","NODE_DEBUG","NODE_DEBUG_NATIVE","NODE_COMPILE_CACHE","WATCH_REPORT_DEPENDENCIES","FORCE_COLOR","DEBUG","UNDICI_NO_FG","JEST_WORKER_ID","__MINIMATCH_TESTING_PLATFORM__","LOG_TOKENS","LOG_STREAM"])},{prop:"binding",target:process,violationType:"process_binding",strategy:"throw",reason:"process.binding provides access to native Node.js modules"},{prop:"_linkedBinding",target:process,violationType:"process_binding",strategy:"throw",reason:"process._linkedBinding provides access to native Node.js modules"},{prop:"dlopen",target:process,violationType:"process_dlopen",strategy:"throw",reason:"process.dlopen allows loading native addons"},{prop:"getBuiltinModule",target:process,violationType:"process_get_builtin_module",strategy:"throw",reason:"process.getBuiltinModule allows loading native Node.js modules (fs, child_process, vm)"},{prop:"exit",target:process,violationType:"process_exit",strategy:"throw",reason:"process.exit could terminate the interpreter"},{prop:"abort",target:process,violationType:"process_exit",strategy:"throw",reason:"process.abort could crash the interpreter"},{prop:"kill",target:process,violationType:"process_kill",strategy:"throw",reason:"process.kill could signal other processes"},{prop:"setuid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setuid could escalate privileges"},{prop:"setgid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setgid could escalate privileges"},{prop:"seteuid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.seteuid could escalate effective user privileges"},{prop:"setegid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setegid could escalate effective group privileges"},{prop:"initgroups",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.initgroups could modify supplementary group IDs"},{prop:"setgroups",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setgroups could modify supplementary group IDs"},{prop:"umask",target:process,violationType:"process_umask",strategy:"throw",reason:"process.umask could modify file creation permissions"},{prop:"argv",target:process,violationType:"process_argv",strategy:"throw",reason:"process.argv may contain secrets in CLI arguments"},{prop:"cwd",target:process,violationType:"process_chdir",strategy:"throw",reason:"process.cwd could disclose real host working directory path"},{prop:"chdir",target:process,violationType:"process_chdir",strategy:"throw",reason:"process.chdir could confuse the interpreter's CWD tracking"},{prop:"report",target:process,violationType:"process_report",strategy:"throw",reason:"process.report could disclose full environment, host paths, and system info"},{prop:"loadEnvFile",target:process,violationType:"process_env",strategy:"throw",reason:"process.loadEnvFile could load env files bypassing env proxy"},{prop:"setUncaughtExceptionCaptureCallback",target:process,violationType:"process_exception_handler",strategy:"throw",reason:"setUncaughtExceptionCaptureCallback could intercept security errors"},{prop:"send",target:process,violationType:"process_send",strategy:"throw",reason:"process.send could communicate with parent process in IPC contexts"},{prop:"channel",target:process,violationType:"process_channel",strategy:"throw",reason:"process.channel could access IPC channel to parent process"},{prop:"cpuUsage",target:process,violationType:"process_timing",strategy:"throw",reason:"process.cpuUsage could enable timing side-channel attacks"},{prop:"memoryUsage",target:process,violationType:"process_timing",strategy:"throw",reason:"process.memoryUsage could enable timing side-channel attacks"},{prop:"hrtime",target:process,violationType:"process_timing",strategy:"throw",reason:"process.hrtime could enable timing side-channel attacks"},{prop:"WeakRef",target:globalThis,violationType:"weak_ref",strategy:"throw",reason:"WeakRef could be used to leak references outside sandbox"},{prop:"FinalizationRegistry",target:globalThis,violationType:"finalization_registry",strategy:"throw",reason:"FinalizationRegistry could be used to leak references outside sandbox"},{prop:"Reflect",target:globalThis,violationType:"reflect",strategy:"freeze",reason:"Reflect provides introspection capabilities"},{prop:"Proxy",target:globalThis,violationType:"proxy",strategy:"throw",reason:"Proxy allows intercepting and modifying object behavior"},{prop:"WebAssembly",target:globalThis,violationType:"webassembly",strategy:"throw",reason:"WebAssembly allows executing arbitrary compiled code"},{prop:"SharedArrayBuffer",target:globalThis,violationType:"shared_array_buffer",strategy:"throw",reason:"SharedArrayBuffer could enable side-channel communication or timing attacks"},{prop:"Atomics",target:globalThis,violationType:"atomics",strategy:"throw",reason:"Atomics could enable side-channel communication or timing attacks"},{prop:"performance",target:globalThis,violationType:"performance_timing",strategy:"throw",reason:"performance.now() provides sub-millisecond timing for side-channel attacks"},{prop:"stdout",target:process,violationType:"process_stdout",strategy:"throw",reason:"process.stdout could bypass interpreter output to write to host stdout"},{prop:"stderr",target:process,violationType:"process_stderr",strategy:"throw",reason:"process.stderr could bypass interpreter output to write to host stderr"},{prop:"__defineGetter__",target:Object.prototype,violationType:"prototype_mutation",strategy:"throw",reason:"__defineGetter__ allows prototype pollution via getter injection"},{prop:"__defineSetter__",target:Object.prototype,violationType:"prototype_mutation",strategy:"throw",reason:"__defineSetter__ allows prototype pollution via setter injection"},{prop:"__lookupGetter__",target:Object.prototype,violationType:"prototype_mutation",strategy:"throw",reason:"__lookupGetter__ enables introspection for prototype pollution attacks"},{prop:"__lookupSetter__",target:Object.prototype,violationType:"prototype_mutation",strategy:"throw",reason:"__lookupSetter__ enables introspection for prototype pollution attacks"},{prop:"JSON",target:globalThis,violationType:"json_mutation",strategy:"freeze",reason:"Freeze JSON to prevent mutation of parsing/serialization"},{prop:"Math",target:globalThis,violationType:"math_mutation",strategy:"freeze",reason:"Freeze Math to prevent mutation of math utilities"}];try{let t10=Object.getPrototypeOf(async()=>{}).constructor;t10&&t10!==Function&&e2.push({prop:"constructor",target:Object.getPrototypeOf(async()=>{}),violationType:"async_function_constructor",strategy:"throw",reason:"AsyncFunction constructor allows arbitrary async code execution"})}catch{}try{let t10=Object.getPrototypeOf(function*(){}).constructor;t10&&t10!==Function&&e2.push({prop:"constructor",target:Object.getPrototypeOf(function*(){}),violationType:"generator_function_constructor",strategy:"throw",reason:"GeneratorFunction constructor allows arbitrary generator code execution"})}catch{}try{let t10=Object.getPrototypeOf(async function*(){}).constructor;t10&&t10!==Function&&t10!==Object.getPrototypeOf(async()=>{}).constructor&&e2.push({prop:"constructor",target:Object.getPrototypeOf(async function*(){}),violationType:"async_generator_function_constructor",strategy:"throw",reason:"AsyncGeneratorFunction constructor allows arbitrary async generator code execution"})}catch{}return e2.filter(t10=>{try{return t10.target[t10.prop]!==void 0}catch{return false}})}var If=v(()=>{"use strict"});function $f(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e2=>{let t10=Math.random()*16|0;return(e2==="x"?t10:t10&3|8).toString(16)})}function W7(e2,t10,...n8){return Le.run(e2,()=>t10(...n8))}function z7(e2){return e2===void 0?{...Ba,enabled:false}:typeof e2=="boolean"?{...Ba,enabled:e2}:{...Ba,...e2}}var rr;var Wa;var U7;var he;var Le;var B7;var Ba;var wt;var an=v(()=>{"use strict";If();rr=true;Wa=null;if(!rr)try{let{AsyncLocalStorage:e2}=qn("node:async_hooks");Wa=e2}catch{}U7=`
2
2
 
3
3
  This is a defense-in-depth measure and indicates a bug in just-bash. Please report this at security@vercel.com`,he=class extends Error{violation;constructor(t10,n8){super(t10+U7),this.violation=n8,this.name="SecurityViolationError"}},Le=!rr&&Wa?new Wa:null,B7=1e3;Ba={enabled:true,auditMode:false};wt=class e2{static instance=null;static importHooksRegistered=false;static trustedExecutionDepth=new Map;config;refCount=0;patchFailures=[];activeExecutionIds=new Set;contextCache=new Map;originalDescriptors=[];violations=[];activationTime=0;totalActiveTimeMs=0;constructor(t10){this.config=t10}static getInstance(t10){let n8=z7(t10);if(!e2.instance)e2.instance=new e2(n8);else{let r10=e2.instance.config;if(n8.enabled!==r10.enabled||n8.auditMode!==r10.auditMode)throw new Error(`DefenseInDepthBox config conflict: requested {enabled: ${n8.enabled}, auditMode: ${n8.auditMode}} but singleton already has {enabled: ${r10.enabled}, auditMode: ${r10.auditMode}}. All Bash instances must use the same defense-in-depth security settings, or call DefenseInDepthBox.resetInstance() between incompatible configurations.`)}return e2.instance}static resetInstance(){e2.instance&&(e2.instance.forceDeactivate(),e2.instance=null),e2.trustedExecutionDepth.clear()}static isInSandboxedContext(){return Le?Le?.getStore()?.sandboxActive===true:false}static getCurrentExecutionId(){if(Le)return Le?.getStore()?.executionId}static enterTrustedScope(t10){let n8=e2.trustedExecutionDepth.get(t10)??0;e2.trustedExecutionDepth.set(t10,n8+1)}static leaveTrustedScope(t10){let n8=e2.trustedExecutionDepth.get(t10);if(n8){if(n8===1){e2.trustedExecutionDepth.delete(t10);return}e2.trustedExecutionDepth.set(t10,n8-1)}}static isTrustedScopeActive(t10){return t10?(e2.trustedExecutionDepth.get(t10)??0)>0:false}isExecutionIdActive(t10){return this.activeExecutionIds.has(t10)}getCachedContext(t10){let n8=this.contextCache.get(t10);return n8||(n8={sandboxActive:true,executionId:t10},this.contextCache.set(t10,n8)),n8}getPreferredActiveExecutionId(){if(this.activeExecutionIds.size!==0)for(let t10 of this.activeExecutionIds)return t10}static bindCurrentContext(t10){if(!Le)return t10;let n8=e2.instance,r10=Le.getStore(),s10=r10?.sandboxActive===true?r10.executionId:n8?.getPreferredActiveExecutionId();if(!s10)return t10;let i10=n8?.getCachedContext(s10)??{sandboxActive:true,executionId:s10};return((...o10)=>{let a=e2.instance;if(!(a&&!a.isExecutionIdActive(s10)&&(a.recordViolation("bound_callback_after_deactivate","bound callback","Bound callback blocked after originating execution was deactivated"),!a.config.auditMode)))return W7(i10,t10,...o10)})}isEnabled(){return this.config.enabled===true&&Le!==null&&!rr}updateConfig(t10){this.config={...this.config,...t10}}activate(){if(rr||!this.config.enabled||!Le){let r10=$f(),s10=false;return{run:i10=>s10?Promise.reject(new Error("DefenseInDepthBox handle is deactivated and cannot run new work")):i10(),deactivate:()=>{s10=true},executionId:r10}}this.refCount++,this.refCount===1&&(this.applyPatches(),this.activationTime=Date.now());let t10=$f(),n8=false;return{run:r10=>n8?Promise.reject(new Error("DefenseInDepthBox handle is deactivated and cannot run new work")):(this.activeExecutionIds.add(t10),Le.run({sandboxActive:true,executionId:t10},r10)),deactivate:()=>{n8||(n8=true,this.activeExecutionIds.delete(t10),this.contextCache.delete(t10),this.refCount--,this.refCount===0&&(this.restorePatches(),this.totalActiveTimeMs+=Date.now()-this.activationTime),this.refCount<0&&(this.refCount=0))},executionId:t10}}forceDeactivate(){this.refCount>0&&(this.restorePatches(),this.totalActiveTimeMs+=Date.now()-this.activationTime),this.activeExecutionIds.clear(),this.contextCache.clear(),this.refCount=0}isActive(){return this.refCount>0}getStats(){return{violationsBlocked:this.violations.length,violations:[...this.violations],activeTimeMs:this.totalActiveTimeMs+(this.refCount>0?Date.now()-this.activationTime:0),refCount:this.refCount}}getPatchFailures(){return[...this.patchFailures]}clearViolations(){this.violations=[]}getPathForTarget(t10,n8){return t10===globalThis?`globalThis.${n8}`:t10===process?`process.${n8}`:t10===Error?`Error.${n8}`:t10===Function.prototype?`Function.prototype.${n8}`:t10===Object.prototype?`Object.prototype.${n8}`:`<object>.${n8}`}static runTrusted(t10){if(!Le)return t10();let n8=Le.getStore();if(!n8)return t10();let{executionId:r10}=n8;return Le.run({...n8,trusted:true},()=>{e2.enterTrustedScope(r10);try{let s10=t10();return typeof s10=="object"&&s10!==null&&"finally"in s10&&typeof s10.finally=="function"?s10.finally(()=>{e2.leaveTrustedScope(r10)}):(e2.leaveTrustedScope(r10),s10)}catch(s10){throw e2.leaveTrustedScope(r10),s10}})}static async runTrustedAsync(t10){if(!Le)return t10();let n8=Le.getStore();if(!n8)return t10();let{executionId:r10}=n8;return Le.run({...n8,trusted:true},async()=>{e2.enterTrustedScope(r10);try{return await t10()}finally{e2.leaveTrustedScope(r10)}})}shouldBlock(){if(rr||this.config.auditMode||!Le)return false;let t10=Le?.getStore();return!(t10?.sandboxActive!==true||t10.trusted||e2.isTrustedScopeActive(t10.executionId))}recordViolation(t10,n8,r10){let s10={timestamp:Date.now(),type:t10,message:r10,path:n8,stack:new Error().stack,executionId:Le?.getStore()?.executionId};if(this.violations.length<B7&&this.violations.push(s10),this.config.onViolation)try{this.config.onViolation(s10)}catch(i10){console.debug("[DefenseInDepthBox] onViolation callback threw:",i10 instanceof Error?i10.message:i10)}return s10}createBlockingProxy(t10,n8,r10){let s10=this;return new Proxy(t10,{apply(i10,o10,a){if(s10.shouldBlock()){let l=`${n8} is blocked during script execution`,c=s10.recordViolation(r10,n8,l);throw new he(l,c)}return s10.config.auditMode&&Le?.getStore()?.sandboxActive===true&&s10.recordViolation(r10,n8,`${n8} called (audit mode)`),Reflect.apply(i10,o10,a)},construct(i10,o10,a){if(s10.shouldBlock()){let l=`${n8} constructor is blocked during script execution`,c=s10.recordViolation(r10,n8,l);throw new he(l,c)}return s10.config.auditMode&&Le?.getStore()?.sandboxActive===true&&s10.recordViolation(r10,n8,`${n8} constructor called (audit mode)`),Reflect.construct(i10,o10,a)}})}createBlockingObjectProxy(t10,n8,r10,s10){let i10=this;return new Proxy(t10,{get(o10,a,l){if(i10.shouldBlock()){if(s10&&typeof a=="string"&&s10.has(a))return Reflect.get(o10,a,l);let c=`${n8}.${String(a)}`,u=`${c} is blocked during script execution`,f10=i10.recordViolation(r10,c,u);throw new he(u,f10)}if(i10.config.auditMode&&Le?.getStore()?.sandboxActive===true){let c=`${n8}.${String(a)}`;i10.recordViolation(r10,c,`${c} accessed (audit mode)`)}return Reflect.get(o10,a,l)},set(o10,a,l,c){if(i10.shouldBlock()){let u=`${n8}.${String(a)}`,f10=`${u} modification is blocked during script execution`,p=i10.recordViolation(r10,u,f10);throw new he(f10,p)}return Reflect.set(o10,a,l,c)},ownKeys(o10){if(i10.shouldBlock()){let a=`${n8} enumeration is blocked during script execution`,l=i10.recordViolation(r10,n8,a);throw new he(a,l)}return Reflect.ownKeys(o10)},getOwnPropertyDescriptor(o10,a){if(i10.shouldBlock()){let l=`${n8}.${String(a)}`,c=`${l} descriptor access is blocked during script execution`,u=i10.recordViolation(r10,l,c);throw new he(c,u)}return Reflect.getOwnPropertyDescriptor(o10,a)},has(o10,a){if(i10.shouldBlock()){let l=`${n8}.${String(a)}`,c=`${l} existence check is blocked during script execution`,u=i10.recordViolation(r10,l,c);throw new he(c,u)}return Reflect.has(o10,a)},deleteProperty(o10,a){if(i10.shouldBlock()){let l=`${n8}.${String(a)}`,c=`${l} deletion is blocked during script execution`,u=i10.recordViolation(r10,l,c);throw new he(c,u)}return Reflect.deleteProperty(o10,a)},setPrototypeOf(o10,a){if(i10.shouldBlock()){let l=`${n8} setPrototypeOf is blocked during script execution`,c=i10.recordViolation(r10,n8,l);throw new he(l,c)}return Reflect.setPrototypeOf(o10,a)},defineProperty(o10,a,l){if(i10.shouldBlock()){let c=`${n8}.${String(a)}`,u=`${c} defineProperty is blocked during script execution`,f10=i10.recordViolation(r10,c,u);throw new he(u,f10)}return Reflect.defineProperty(o10,a,l)}})}applyPatches(){this.patchFailures=[];let t10=Nf(),n8=new Set(["process_send","process_channel","process_stdout","process_stderr"]);for(let i10 of t10)n8.has(i10.violationType)||this.applyPatch(i10);this.protectConstructorChain(),this.protectErrorPrepareStackTrace(),this.protectPromiseThen(),this.protectDynamicImport(),this.protectModuleLoad(),this.protectModuleResolveFilename(),this.protectProcessMainModule(),this.protectProcessExecPath(),this.lockWellKnownSymbols(),this.protectProxyRevocable();let r10=["Function.prototype.constructor","Module._load"],s10=this.patchFailures.filter(i10=>r10.includes(i10));if(s10.length>0)throw this.restorePatches(),new Error(`DefenseInDepthBox: critical patches failed: ${s10.join(", ")}`)}protectConstructorChain(){this.patchPrototypeConstructor(Function.prototype,"Function.prototype.constructor","function_constructor");try{let t10=Object.getPrototypeOf(async()=>{}).constructor;t10&&t10!==Function&&this.patchPrototypeConstructor(t10.prototype,"AsyncFunction.prototype.constructor","async_function_constructor")}catch(t10){this.patchFailures.push("AsyncFunction.prototype.constructor"),console.debug("[DefenseInDepthBox] Could not patch AsyncFunction.prototype.constructor:",t10 instanceof Error?t10.message:t10)}try{let t10=Object.getPrototypeOf(function*(){}).constructor;t10&&t10!==Function&&this.patchPrototypeConstructor(t10.prototype,"GeneratorFunction.prototype.constructor","generator_function_constructor")}catch(t10){this.patchFailures.push("GeneratorFunction.prototype.constructor"),console.debug("[DefenseInDepthBox] Could not patch GeneratorFunction.prototype.constructor:",t10 instanceof Error?t10.message:t10)}try{let t10=Object.getPrototypeOf(async function*(){}).constructor,n8=Object.getPrototypeOf(async()=>{}).constructor;t10&&t10!==Function&&t10!==n8&&this.patchPrototypeConstructor(t10.prototype,"AsyncGeneratorFunction.prototype.constructor","async_generator_function_constructor")}catch(t10){this.patchFailures.push("AsyncGeneratorFunction.prototype.constructor"),console.debug("[DefenseInDepthBox] Could not patch AsyncGeneratorFunction.prototype.constructor:",t10 instanceof Error?t10.message:t10)}}protectErrorPrepareStackTrace(){let t10=this;try{let n8=Object.getOwnPropertyDescriptor(Error,"prepareStackTrace");this.originalDescriptors.push({target:Error,prop:"prepareStackTrace",descriptor:n8});let r10=n8?.value;Object.defineProperty(Error,"prepareStackTrace",{get(){return r10},set(s10){if(t10.shouldBlock()){let i10="Error.prepareStackTrace modification is blocked during script execution",o10=t10.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace",i10);throw new he(i10,o10)}t10.config.auditMode&&Le?.getStore()?.sandboxActive===true&&t10.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace","Error.prepareStackTrace set (audit mode)"),r10=s10},configurable:true})}catch(n8){this.patchFailures.push("Error.prepareStackTrace"),console.debug("[DefenseInDepthBox] Could not protect Error.prepareStackTrace:",n8 instanceof Error?n8.message:n8)}}protectPromiseThen(){let t10=this;try{let i10=function(...o10){return Le.run(this.captured,()=>{if(!this.box.isExecutionIdActive(this.executionId)){if(this.box.recordViolation("promise_then_after_deactivate","Promise.then","Promise.then callback is blocked after defense deactivation"),this.box.config.auditMode)return Reflect.apply(this.cb,void 0,o10);if(this.kind==="fulfilled")return o10[0];throw o10[0]}return Reflect.apply(this.cb,void 0,o10)})};var n8=i10;let r10=Object.getOwnPropertyDescriptor(Promise.prototype,"then");this.originalDescriptors.push({target:Promise.prototype,prop:"then",descriptor:r10});let s10=r10?.value;if(typeof s10!="function")return;Object.defineProperty(Promise.prototype,"then",{value:function(a,l){if(!Le)return Reflect.apply(s10,this,[a,l]);let c=Le.getStore(),u=c?.sandboxActive===true&&c.trusted!==true?c.executionId:void 0;if(!u)return Reflect.apply(s10,this,[a,l]);let f10=t10.getCachedContext(u),p=(h,d)=>typeof h!="function"?h:i10.bind({box:t10,executionId:u,captured:f10,cb:h,kind:d});return Reflect.apply(s10,this,[p(a,"fulfilled"),p(l,"rejected")])},writable:true,configurable:true})}catch(r10){this.patchFailures.push("Promise.prototype.then"),console.debug("[DefenseInDepthBox] Could not protect Promise.prototype.then:",r10 instanceof Error?r10.message:r10)}}patchPrototypeConstructor(t10,n8,r10){let s10=this;try{let i10=Object.getOwnPropertyDescriptor(t10,"constructor");this.originalDescriptors.push({target:t10,prop:"constructor",descriptor:i10});let o10=i10?.value;Object.defineProperty(t10,"constructor",{get(){if(s10.shouldBlock()){let a=`${n8} access is blocked during script execution`,l=s10.recordViolation(r10,n8,a);throw new he(a,l)}return s10.config.auditMode&&Le?.getStore()?.sandboxActive===true&&s10.recordViolation(r10,n8,`${n8} accessed (audit mode)`),o10},set(a){if(s10.shouldBlock()){let l=`${n8} modification is blocked during script execution`,c=s10.recordViolation(r10,n8,l);throw new he(l,c)}Object.defineProperty(this,"constructor",{value:a,writable:true,configurable:true})},configurable:true})}catch(i10){this.patchFailures.push(n8),console.debug(`[DefenseInDepthBox] Could not patch ${n8}:`,i10 instanceof Error?i10.message:i10)}}protectProcessMainModule(){if(typeof process>"u")return;let t10=this;try{let n8=Object.getOwnPropertyDescriptor(process,"mainModule");this.originalDescriptors.push({target:process,prop:"mainModule",descriptor:n8});let r10=n8?.value;r10!==void 0&&Object.defineProperty(process,"mainModule",{get(){if(t10.shouldBlock()){let s10="process.mainModule access is blocked during script execution",i10=t10.recordViolation("process_main_module","process.mainModule",s10);throw new he(s10,i10)}return t10.config.auditMode&&Le?.getStore()?.sandboxActive===true&&t10.recordViolation("process_main_module","process.mainModule","process.mainModule accessed (audit mode)"),r10},set(s10){if(t10.shouldBlock()){let i10="process.mainModule modification is blocked during script execution",o10=t10.recordViolation("process_main_module","process.mainModule",i10);throw new he(i10,o10)}Object.defineProperty(process,"mainModule",{value:s10,writable:true,configurable:true})},configurable:true})}catch(n8){this.patchFailures.push("process.mainModule"),console.debug("[DefenseInDepthBox] Could not protect process.mainModule:",n8 instanceof Error?n8.message:n8)}}protectProcessExecPath(){if(typeof process>"u")return;let t10=this;try{let n8=Object.getOwnPropertyDescriptor(process,"execPath");this.originalDescriptors.push({target:process,prop:"execPath",descriptor:n8});let r10=n8?.value??process.execPath;Object.defineProperty(process,"execPath",{get(){if(t10.shouldBlock()){let s10="process.execPath access is blocked during script execution",i10=t10.recordViolation("process_exec_path","process.execPath",s10);throw new he(s10,i10)}return t10.config.auditMode&&Le?.getStore()?.sandboxActive===true&&t10.recordViolation("process_exec_path","process.execPath","process.execPath accessed (audit mode)"),r10},set(s10){if(t10.shouldBlock()){let i10="process.execPath modification is blocked during script execution",o10=t10.recordViolation("process_exec_path","process.execPath",i10);throw new he(i10,o10)}Object.defineProperty(process,"execPath",{value:s10,writable:true,configurable:true})},configurable:true})}catch(n8){this.patchFailures.push("process.execPath"),console.debug("[DefenseInDepthBox] Could not protect process.execPath:",n8 instanceof Error?n8.message:n8)}}lockWellKnownSymbols(){let t10=(n8,r10)=>{try{let s10=Object.getOwnPropertyDescriptor(n8,r10);if(s10?.configurable){if("value"in s10){Object.defineProperty(n8,r10,{...s10,configurable:false,writable:false});return}Object.defineProperty(n8,r10,{...s10,configurable:false})}}catch{}};for(let n8 of[Array,Map,Set,RegExp,Promise])t10(n8,Symbol.species);for(let n8 of[Array.prototype,String.prototype,Map.prototype,Set.prototype])t10(n8,Symbol.iterator);t10(Symbol.prototype,Symbol.toPrimitive),t10(Date.prototype,Symbol.toPrimitive);for(let n8 of[Symbol.match,Symbol.matchAll,Symbol.replace,Symbol.search,Symbol.split])t10(RegExp.prototype,n8);t10(Function.prototype,Symbol.hasInstance),t10(Array.prototype,Symbol.unscopables);for(let n8 of[Map.prototype,Set.prototype,Promise.prototype,ArrayBuffer.prototype])t10(n8,Symbol.toStringTag);try{let n8=Object.getOwnPropertyDescriptor(Error,"stackTraceLimit");this.originalDescriptors.push({target:Error,prop:"stackTraceLimit",descriptor:n8}),Object.defineProperty(Error,"stackTraceLimit",{value:Error.stackTraceLimit,writable:false,configurable:true})}catch{}}protectProxyRevocable(){let t10=this;try{let n8=Proxy.revocable;if(typeof n8!="function")return;let r10=Object.getOwnPropertyDescriptor(Proxy,"revocable");this.originalDescriptors.push({target:Proxy,prop:"revocable",descriptor:r10}),Object.defineProperty(Proxy,"revocable",{value:function(i10,o10){if(t10.shouldBlock()){let a="Proxy.revocable is blocked during script execution",l=t10.recordViolation("proxy","Proxy.revocable",a);throw new he(a,l)}return t10.config.auditMode&&Le?.getStore()?.sandboxActive===true&&t10.recordViolation("proxy","Proxy.revocable","Proxy.revocable called (audit mode)"),n8(i10,o10)},writable:false,configurable:true})}catch(n8){this.patchFailures.push("Proxy.revocable"),console.debug("[DefenseInDepthBox] Could not protect Proxy.revocable:",n8 instanceof Error?n8.message:n8)}}protectDynamicImport(){if(!(rr||e2.importHooksRegistered))try{let t10=this,n8=qn("node:module"),r10=new Set;for(let o10 of n8.builtinModules??[]){let a=o10.startsWith("node:")?o10.slice(5):o10;r10.add(a);let l=a.indexOf("/");l>0&&r10.add(a.slice(0,l))}let s10=o10=>{if(o10.startsWith("./")||o10.startsWith("../")||o10.startsWith("/")||o10.startsWith("file:")||o10.startsWith("data:")||o10.startsWith("blob:")||o10.startsWith("http:")||o10.startsWith("https:"))return false;let a=o10.startsWith("node:")?o10.slice(5):o10;if(!a)return false;if(typeof n8.isBuiltin=="function"&&n8.isBuiltin(a)||r10.has(a))return true;let l=a.indexOf("/");return l>0&&r10.has(a.slice(0,l))},i10=()=>{let o10=Le?.getStore();return t10.config.auditMode===true&&o10?.sandboxActive===true&&o10.trusted!==true&&!e2.isTrustedScopeActive(o10.executionId)};if(typeof n8.registerHooks=="function"){n8.registerHooks({resolve(o10,a,l){if(o10.startsWith("data:")||o10.startsWith("blob:"))throw new Error(`dynamic import of ${o10.startsWith("data:")?"data:":"blob:"} URLs is blocked by defense-in-depth`);if(s10(o10)){let c=`import(${o10})`,u=`dynamic import of Node.js builtin '${o10}' is blocked during script execution`;if(t10.shouldBlock()){let f10=t10.recordViolation("dynamic_import_builtin",c,u);throw new he(u,f10)}i10()&&t10.recordViolation("dynamic_import_builtin",c,`dynamic import of Node.js builtin '${o10}' called (audit mode)`)}return l(o10,a)}}),e2.importHooksRegistered=true;return}if(typeof n8.register=="function"){let o10=["export async function resolve(specifier, context, nextResolve) {",' if (specifier.startsWith("data:") || specifier.startsWith("blob:")) {',' throw new Error("dynamic import of " + (specifier.startsWith("data:") ? "data:" : "blob:") + " URLs is blocked by defense-in-depth");'," }"," return nextResolve(specifier, context);","}"].join(`
4
4
  `);n8.register(`data:text/javascript,${encodeURIComponent(o10)}`),e2.importHooksRegistered=true}}catch(t10){console.debug("[DefenseInDepthBox] Could not register import() hooks:",t10 instanceof Error?t10.message:t10)}}protectModuleLoad(){if(!rr)try{let t10=null;if(typeof process<"u"){let o10=process.mainModule;o10&&typeof o10=="object"&&(t10=o10.constructor)}if(!t10&&typeof qn<"u"&&typeof qn.main<"u"&&(t10=qn.main.constructor),!t10||typeof t10._load!="function")return;let n8=t10._load,r10=Object.getOwnPropertyDescriptor(t10,"_load");this.originalDescriptors.push({target:t10,prop:"_load",descriptor:r10});let i10=this.createBlockingProxy(n8,"Module._load","module_load");Object.defineProperty(t10,"_load",{value:i10,writable:true,configurable:true})}catch(t10){this.patchFailures.push("Module._load"),console.debug("[DefenseInDepthBox] Could not protect Module._load:",t10 instanceof Error?t10.message:t10)}}protectModuleResolveFilename(){if(!rr)try{let t10=null;if(typeof process<"u"){let o10=process.mainModule;o10&&typeof o10=="object"&&(t10=o10.constructor)}if(!t10&&typeof qn<"u"&&typeof qn.main<"u"&&(t10=qn.main.constructor),!t10||typeof t10._resolveFilename!="function")return;let n8=t10._resolveFilename,r10=Object.getOwnPropertyDescriptor(t10,"_resolveFilename");this.originalDescriptors.push({target:t10,prop:"_resolveFilename",descriptor:r10});let i10=this.createBlockingProxy(n8,"Module._resolveFilename","module_resolve_filename");Object.defineProperty(t10,"_resolveFilename",{value:i10,writable:true,configurable:true})}catch(t10){this.patchFailures.push("Module._resolveFilename"),console.debug("[DefenseInDepthBox] Could not protect Module._resolveFilename:",t10 instanceof Error?t10.message:t10)}}applyPatch(t10){let{target:n8,prop:r10,violationType:s10,strategy:i10}=t10;try{let o10=n8[r10];if(o10===void 0)return;let a=Object.getOwnPropertyDescriptor(n8,r10);if(this.originalDescriptors.push({target:n8,prop:r10,descriptor:a}),i10==="freeze")typeof o10=="object"&&o10!==null&&Object.freeze(o10);else{let l=this.getPathForTarget(n8,r10),c=typeof o10=="function"?this.createBlockingProxy(o10,l,s10):this.createBlockingObjectProxy(o10,l,s10,t10.allowedKeys);Object.defineProperty(n8,r10,{value:c,writable:true,configurable:true})}}catch(o10){let a=this.getPathForTarget(n8,r10);this.patchFailures.push(a),console.debug(`[DefenseInDepthBox] Could not patch ${a}:`,o10 instanceof Error?o10.message:o10)}}restorePatches(){for(let t10=this.originalDescriptors.length-1;t10>=0;t10--){let{target:n8,prop:r10,descriptor:s10}=this.originalDescriptors[t10];try{s10?Object.defineProperty(n8,r10,s10):delete n8[r10]}catch(i10){let o10=this.getPathForTarget(n8,r10);console.debug(`[DefenseInDepthBox] Could not restore ${o10}:`,i10 instanceof Error?i10.message:i10)}}this.originalDescriptors=[]}}});function G7(e2){return typeof e2!="function"?e2:wt.bindCurrentContext(e2)}var H7;var j7;var Bv;var Wv;var Sr;var Qr;var zs=v(()=>{"use strict";an();H7=globalThis.setTimeout.bind(globalThis),j7=globalThis.clearTimeout.bind(globalThis),Bv=globalThis.setInterval.bind(globalThis),Wv=globalThis.clearInterval.bind(globalThis);Sr=((e2,t10,...n8)=>H7(G7(e2),t10,...n8)),Qr=j7});var Of={};ee(Of,{echoCommand:()=>q7,flagsForFuzzing:()=>Z7});function V7(e2){let t10="",n8=0;for(;n8<e2.length;)if(e2[n8]==="\\"){if(n8+1>=e2.length){t10+="\\";break}let r10=e2[n8+1];switch(r10){case"\\":t10+="\\",n8+=2;break;case"n":t10+=`
@@ -5889,8 +5889,8 @@ while (true) {
5889
5889
  }
5890
5890
  }`)(require2,consoleWrapper,process22,buffer2);replGen.next();return{eval(code22){const transformed=code22.replace(/^\s*(const|let)\s+/gm,"var ");const exprResult=replGen.next("("+transformed+")").value;if(!exprResult.error){replGen.next();return exprResult.value}replGen.next();const stmtResult=replGen.next(transformed).value;if(stmtResult.error){replGen.next();throw stmtResult.error}replGen.next();return stmtResult.value}}}};function execute(code22,vfs2,options){const runtime=new Runtime(vfs2,options);return runtime.execute(code22)}forGuestRealm(()=>{if(typeof globalThis.setImmediate==="undefined"){takeFromHost(globalThis,"setImmediate",(fn2,...args)=>setTimeout(fn2,0,...args));takeFromHost(globalThis,"clearImmediate",id2=>clearTimeout(id2))}});forGuestRealm(()=>{if(typeof globalThis.Request==="function"&&!globalThis.Request.__substrateHeaderGuard){const Native=globalThis.Request;const kept=new WeakMap;class NodeRequest extends Native{constructor(input,init){init=withNodeRequestBody(init);super(input,init);rememberRequestBodySource(this,input,init);const asked=new Headers((init==null?void 0:init.headers)??(input instanceof Native?input.headers:void 0));const headers=new Headers(super.headers);asked.forEach((value,name)=>{if(!headers.has(name))headers.set(name,value)});kept.set(this,headers)}get headers(){return kept.get(this)??super.headers}clone(){const copy2=super.clone();rememberRequestBodySource(copy2,this);return new NodeRequest(copy2,{headers:this.headers})}}Object.defineProperty(NodeRequest,"__substrateHeaderGuard",{value:true});Object.defineProperty(NodeRequest,"name",{value:"Request",configurable:true});takeFromHost(globalThis,"Request",NodeRequest)}});forGuestRealm(()=>{installNodeResponse(globalThis)});forGuestRealm(()=>{const kIsClosedPromise=Symbol.for("nodejs.webstream.isClosedPromise");const Native=globalThis.ReadableStream;if(typeof Native!=="function"||Native.__substrateClosedPromise)return;const Tracked=new Proxy(Native,{construct(target,args,newTarget){let resolve2;let reject;const promise=new Promise((yes,no2)=>{resolve2=yes;reject=no2});promise.then(void 0,()=>{});const source=args[0];const track=controller=>{const close2=controller.close;const error=controller.error;if(typeof close2==="function")controller.close=function(...rest){const result=close2.apply(this,rest);resolve2();return result};if(typeof error==="function")controller.error=function(...rest){reject(rest[0]);return error.apply(this,rest)}};const failed=cause=>{reject(cause);throw cause};const wrapped=Object.create(source??null);wrapped.start=controller=>{var _a22;track(controller);try{return(_a22=source==null?void 0:source.start)==null?void 0:_a22.call(source,controller)}catch(cause){return failed(cause)}};if(typeof(source==null?void 0:source.pull)==="function"){const pull=source.pull;wrapped.pull=controller=>{try{return Promise.resolve(pull.call(source,controller)).catch(failed)}catch(cause){return failed(cause)}}}wrapped.cancel=reason=>{var _a22;resolve2();return(_a22=source==null?void 0:source.cancel)==null?void 0:_a22.call(source,reason)};const stream=Reflect.construct(target,[wrapped,...args.slice(1)],newTarget===Tracked?target:newTarget);Object.defineProperty(stream,kIsClosedPromise,{value:{promise,resolve:resolve2,reject},configurable:true});return stream}});Object.defineProperty(Tracked,"__substrateClosedPromise",{value:true});takeFromHost(globalThis,"ReadableStream",Tracked)});forGuestRealm(__substrateStackTracePolyfill);forGuestRealm(__substrateCallSiteFileNames);forGuestRealm(__substrateTextDecoderPolyfill);function __substrateTextDecoderPolyfill(){const OriginalTextDecoder=globalThis.TextDecoder;if(OriginalTextDecoder.__substrateBinaryEncodings)return;class PolyfillTextDecoder{constructor(encoding="utf-8",options){__publicField2(this,"encoding");__publicField2(this,"decoder",null);this.encoding=encoding.toLowerCase();const validTextEncodings=["utf-8","utf8","utf-16le","utf-16be","utf-16","ascii","iso-8859-1","latin1","windows-1252"];if(validTextEncodings.includes(this.encoding)){try{this.decoder=new OriginalTextDecoder(encoding,options)}catch{this.decoder=new OriginalTextDecoder("utf-8",options)}}}decode(input,options){if(this.decoder){return this.decoder.decode(input,options)}if(!input)return"";const bytes2=input instanceof ArrayBuffer?new Uint8Array(input):new Uint8Array(input.buffer,input.byteOffset,input.byteLength);if(this.encoding==="base64"){return uint8ToBase64(bytes2)}if(this.encoding==="base64url"){return uint8ToBase64(bytes2).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}if(this.encoding==="hex"){return uint8ToHex(bytes2)}return new OriginalTextDecoder("utf-8").decode(input,options)}get fatal(){var _a22;return((_a22=this.decoder)==null?void 0:_a22.fatal)??false}get ignoreBOM(){var _a22;return((_a22=this.decoder)==null?void 0:_a22.ignoreBOM)??false}}Object.defineProperty(PolyfillTextDecoder,"__substrateBinaryEncodings",{value:true});takeFromHost(globalThis,"TextDecoder",PolyfillTextDecoder)}function __substrateStackTracePolyfill(){if(typeof Error.captureStackTrace==="function")return;if(Error.stackTraceLimit===void 0){takeFromHost(Error,"stackTraceLimit",10)}function parseStack(stack){if(!stack)return[];const frames=[];const lines=stack.split("\n");for(const raw of lines){const line=raw.trim();if(!line||line.startsWith("Error")||line.startsWith("TypeError"))continue;let fn2="",file2="",lineNo=0,colNo=0;const safariMatch=line.match(/^(.*)@(.*?):(\d+):(\d+)$/);if(safariMatch){fn2=safariMatch[1]||"";file2=safariMatch[2];lineNo=parseInt(safariMatch[3],10);colNo=parseInt(safariMatch[4],10);frames.push({fn:fn2,file:file2,line:lineNo,col:colNo});continue}const chromeMatch=line.match(/^at\s+(?:(.+?)\s+\()?(.*?):(\d+):(\d+)\)?$/);if(chromeMatch){fn2=chromeMatch[1]||"";file2=chromeMatch[2];lineNo=parseInt(chromeMatch[3],10);colNo=parseInt(chromeMatch[4],10);frames.push({fn:fn2,file:file2,line:lineNo,col:colNo});continue}}return frames}function createCallSite(frame){return{getFileName:()=>frame.file||null,getLineNumber:()=>frame.line||null,getColumnNumber:()=>frame.col||null,getFunctionName:()=>frame.fn||null,getMethodName:()=>frame.fn||null,getTypeName:()=>null,getThis:()=>void 0,getFunction:()=>void 0,getEvalOrigin:()=>void 0,isNative:()=>false,isConstructor:()=>false,isToplevel:()=>!frame.fn,isEval:()=>false,toString:()=>frame.fn?`${frame.fn} (${frame.file}:${frame.line}:${frame.col})`:`${frame.file}:${frame.line}:${frame.col}`}}function buildCallSites(stack,constructorOpt){const frames=parseStack(stack);let startIdx=0;if(constructorOpt&&constructorOpt.name){for(let i22=0;i22<frames.length;i22++){if(frames[i22].fn===constructorOpt.name){startIdx=i22+1;break}}}return frames.slice(startIdx).map(createCallSite)}const stackSymbol=Symbol("rawStack");defineOnHost(Error.prototype,"stack",{get(){const rawStack=this[stackSymbol];if(rawStack!==void 0&&typeof Error.prepareStackTrace==="function"){const callSites=buildCallSites(rawStack);try{return Error.prepareStackTrace(this,callSites)}catch{return rawStack}}return rawStack},set(value){this[stackSymbol]=value},configurable:true,enumerable:false});const captureStackTrace=function(target,constructorOpt){const savedPrepare=Error.prepareStackTrace;Error.prepareStackTrace=void 0;const err22=new Error;const rawStack=err22.stack||"";Error.prepareStackTrace=savedPrepare;if(typeof savedPrepare==="function"){const callSites=buildCallSites(rawStack,constructorOpt);try{target.stack=savedPrepare(target,callSites)}catch(e2){console.warn("[tabnode] Error.prepareStackTrace threw:",e2);target.stack=rawStack}}else{target.stack=rawStack}};takeFromHost(Error,"captureStackTrace",captureStackTrace)}function __substrateCallSiteFileNames(){var _a22;if(typeof Error.captureStackTrace!=="function")return;const held=Object.getOwnPropertyDescriptor(Error,"prepareStackTrace");if((_a22=held==null?void 0:held.get)==null?void 0:_a22.__substrateNamesFrames)return;if(held!==void 0&&held.configurable===false)return;const named=site=>new Proxy(site,{get(target,key){if(key==="getFileName")return()=>{var _a32;return target.getFileName()??(((_a32=target.getScriptNameOrSourceURL)==null?void 0:_a32.call(target))||null)};const value=Reflect.get(target,key);return typeof value==="function"?value.bind(target):value}});let guestPrepare=held&&!held.get&&!held.set?held.value:void 0;const namers=new WeakMap;const guests=new WeakMap;const namerFor=prepare=>{let namer=namers.get(prepare);if(!namer){namer=(error,sites)=>prepare(error,sites.map(named));namers.set(prepare,namer);guests.set(namer,prepare)}return namer};const overridingFor=guest=>{const known=typeof guest==="function"?overridings.get(guest):overridingNone;if(known)return known;const overriding=(error,sites)=>{const override=error!==null&&typeof error==="object"?stackOverrides.get(error):void 0;if(override){stackOverrides.delete(error);return override(error,sites.map(named))}if(typeof guest==="function")return namerFor(guest)(error,sites);return`${Error.prototype.toString.call(error)}${sites.map(site=>`
5891
5891
  at ${String(site)}`).join("")}`};guests.set(overriding,guest);if(typeof guest==="function")overridings.set(guest,overriding);else overridingNone=overriding;return overriding};const overridings=new WeakMap;let overridingNone;const get2=()=>stackOverrides.size>0?overridingFor(guestPrepare):typeof guestPrepare==="function"?namerFor(guestPrepare):guestPrepare;get2.__substrateNamesFrames=true;defineOnHost(Error,"prepareStackTrace",{get:get2,set(prepare){guestPrepare=typeof prepare==="function"&&guests.has(prepare)?guests.get(prepare):prepare},configurable:true,enumerable:false})}var WorkerRuntime=class{constructor(vfs2,options={}){__publicField2(this,"worker");__publicField2(this,"workerApi");__publicField2(this,"vfs");__publicField2(this,"options");__publicField2(this,"initialized");__publicField2(this,"changeListener",null);__publicField2(this,"deleteListener",null);this.vfs=vfs2;this.options=options;this.worker=new Worker("/assets/runtime-worker-CFd3N-Xm.js",{type:"module"});this.workerApi=wrap(this.worker);this.initialized=this.initWorker();this.setupVFSListeners()}async initWorker(){const snapshot=this.vfs.toSnapshot();const workerOptions2={cwd:this.options.cwd,env:this.options.env};await this.workerApi.init(snapshot,workerOptions2);if(this.options.onConsole){await this.workerApi.setConsoleCallback(proxy(this.options.onConsole))}console.log("[WorkerRuntime] Worker initialized")}setupVFSListeners(){this.changeListener=(path22,content)=>{this.workerApi.syncFile(path22,content)};this.vfs.on("change",this.changeListener);this.deleteListener=path22=>{this.workerApi.syncFile(path22,null)};this.vfs.on("delete",this.deleteListener)}async execute(code22,filename){await this.initialized;return this.workerApi.execute(code22,filename)}async runFile(filename){await this.initialized;return this.workerApi.runFile(filename)}clearCache(){this.workerApi.clearCache()}getVFS(){return this.vfs}terminate(){if(this.changeListener){this.vfs.off("change",this.changeListener)}if(this.deleteListener){this.vfs.off("delete",this.deleteListener)}this.worker.terminate();console.log("[WorkerRuntime] Worker terminated")}};function isWorkerAvailable(){return typeof Worker!=="undefined"}var AsyncRuntimeWrapper=class{constructor(vfs2,options={}){__publicField2(this,"runtime");this.runtime=new Runtime(vfs2,options)}async execute(code22,filename){return Promise.resolve(this.runtime.execute(code22,filename))}async runFile(filename){return Promise.resolve(this.runtime.runFile(filename))}clearCache(){this.runtime.clearCache()}getVFS(){return this.runtime.getVFS()}getSyncRuntime(){return this.runtime}};async function createRuntime(vfs2,options={}){const{useWorker=false,...runtimeOptions}=options;const shouldUseWorker=useWorker===true||useWorker==="auto"?isWorkerAvailable():false;if(shouldUseWorker){const workerRuntime=new WorkerRuntime(vfs2,runtimeOptions);await workerRuntime.execute("/* worker ready check */","/__worker_init__.js");return workerRuntime}return new AsyncRuntimeWrapper(vfs2,runtimeOptions)}var DuplexStreamHandle=class extends LibuvStreamWrap{constructor(transport2){super();__publicField2(this,"pendingWrite");this.transport=transport2;transport2.pause();transport2.on("data",chunk=>{transport2.pause();this.receive(chunk)});transport2.on("end",()=>this.receiveEof());transport2.on("error",()=>{var _a22;(_a22=this.pendingWrite)==null?void 0:_a22.call(this,UV_ECONNRESET);this.receiveError(UV_ECONNRESET)});transport2.on("close",()=>{var _a22;(_a22=this.pendingWrite)==null?void 0:_a22.call(this,UV_ECONNRESET);this.receiveEof()})}readStop(){this.transport.pause();return super.readStop()}flushInbound(){super.flushInbound();if(this.reading&&!this.closed&&!this.inboundEof)this.transport.resume()}dispatchWrite(req,buffer2){if(this.closed)return UV_EBADF;streamBaseState[kBytesWritten]=buffer2.byteLength;streamBaseState[kLastWriteWasAsync]=1;this.writeQueueSize=buffer2.byteLength;let offset2=0;let complete=false;const finish=status=>{if(complete)return;complete=true;this.pendingWrite=void 0;this.writeQueueSize=0;queueMicrotask(()=>{var _a22;return(_a22=req.oncomplete)==null?void 0:_a22.call(req,status)})};this.pendingWrite=finish;const next2=()=>{if(complete)return;if(this.closed){finish(UV_EBADF);return}if(offset2===buffer2.byteLength){finish(0);return}const bytes2=buffer2.slice(offset2,offset2+64*1024);offset2+=bytes2.byteLength;this.transport.write(bytes2,error=>{if(error){finish(UV_ECONNRESET);return}this.bytesWritten+=bytes2.byteLength;this.writeQueueSize-=bytes2.byteLength;next2()})};queueMicrotask(next2);return 0}shutdown(req){if(this.closed)return UV_EBADF;this.transport.end(()=>{var _a22;return(_a22=req.oncomplete)==null?void 0:_a22.call(req,0)});return 0}onCloseHandle(){var _a22;(_a22=this.pendingWrite)==null?void 0:_a22.call(this,UV_EBADF);this.transport.destroy()}getsockname(){return UV_ENOTSUP}getpeername(){return UV_ENOTSUP}setNoDelay(){return 0}setKeepAlive(){return 0}};var unsupported=detail=>Object.assign(new Error(`HTTP transport does not support ${detail}.`),{code:"ERR_HTTP_TRANSPORT_UNSUPPORTED"});var local=host2=>host2==="localhost"||host2==="::1"||host2==="[::1]"||/^127\./u.test(host2);var tlsOptions=["ca","cert","key","pfx","passphrase","ciphers","secureContext","checkServerIdentity","minVersion","maxVersion","secureProtocol","secureOptions","session","ALPNProtocols","pskCallback"];function installHttpClientTransport(factory,transportOptions={}){const installed22=new WeakMap;const live2=new Set;const collected=new FinalizationRegistry(ref2=>live2.delete(ref2));const install22=(Agent,protocol,require2)=>{const prototype=Agent.prototype;if(installed22.has(prototype))return;const original=prototype.createConnection;const connect2=function(options,callback){var _a22;const host2=String(options.hostname??options.host??"localhost").toLowerCase();const hostPort=local(host2)&&!options.socketPath&&((_a22=transportOptions.hostPorts)==null?void 0:_a22.call(transportOptions).has(Number(options.port??(protocol==="https:"?443:80))));if(!hostPort&&(protocol==="http:"&&(local(host2)||options.socketPath)||protocol==="https:"&&local(host2)&&!options.socketPath)){return original.call(this,options,callback)}try{if(options.socketPath||options.localAddress||options.localPort||options.lookup||options.family)throw unsupported("custom socket routing");if(protocol==="https:"&&(tlsOptions.some(key=>options[key]!==void 0)||options.rejectUnauthorized===false||options.servername!==void 0&&options.servername!==host2))throw unsupported("custom TLS options");const authority=new URL(`${protocol}//${host2.includes(":")&&!host2.startsWith("[")?`[${host2}]`:host2}:${options.port??(protocol==="https:"?443:80)}`);return connection(authority,factory(),require2)}catch(cause){queueMicrotask(()=>callback(cause instanceof Error?cause:new Error(String(cause))));return void 0}};prototype.createConnection=connect2;installed22.set(prototype,{original,connect:connect2});const ref2=new WeakRef(prototype);live2.add(ref2);collected.register(prototype,ref2,ref2)};install22(httpModule.Agent,"http:");install22(httpsModule.Agent,"https:");const unsubscribe=onNodeLibLoaded((name,value,require2)=>{if(name==="_http_agent")install22(value.Agent,"http:",require2);if(name==="https")install22(value.Agent,"https:",require2)});return()=>{unsubscribe();for(const ref2 of live2){const prototype=ref2.deref();const held=prototype&&installed22.get(prototype);if(prototype&&held&&prototype.createConnection===held.connect)prototype.createConnection=held.original;collected.unregister(ref2)}live2.clear()}}function connection(origin,exchange2,require2){const streams2=require2?require2("stream"):streamModule;const net=require2?require2("net"):netModule;const http=require2?require2("http"):httpModule;const pair=streams2.duplexPair({highWaterMark:64*1024});const client=new net.Socket({handle:new DuplexStreamHandle(pair[0]),readable:true,writable:true});const peer=new net.Socket({handle:new DuplexStreamHandle(pair[1]),readable:true,writable:true});peer.unref();const controller=new AbortController;let reader;const fail3=cause=>{const error=cause instanceof Error?cause:new Error(String(cause));controller.abort(error);client.destroy(error);peer.destroy()};client.once("close",()=>{controller.abort(new Error("HTTP client connection closed."));void(reader==null?void 0:reader.cancel(controller.signal.reason).catch(()=>{}));peer.destroy()});peer.on("error",fail3);const server=http.createServer({maxHeaderSize:32*1024,requestTimeout:0,headersTimeout:0},(request,response)=>{void(async()=>{var _a22,_b22;if(!request.url.startsWith("/")||request.url.startsWith("//"))throw unsupported("absolute-form request targets");const url2=new URL(request.url,origin);if(url2.origin!==origin.origin)throw unsupported("a request target that changes origin");const headers=[];const connectionHeaders=new Set;for(let i22=0;i22<request.rawHeaders.length;i22+=2){const name=request.rawHeaders[i22],value=request.rawHeaders[i22+1];const lower=name.toLowerCase();if(["expect","upgrade","trailer","te"].includes(lower))throw unsupported(`${lower} headers`);if(lower==="host"){if(value.toLowerCase()!==origin.host)throw unsupported("a Host header different from the destination");continue}if(lower==="connection")for(const token of value.split(","))connectionHeaders.add(token.trim().toLowerCase());headers.push([name,value])}const outgoing=headers.filter(([name])=>!["connection","keep-alive","transfer-encoding"].includes(name.toLowerCase())&&!connectionHeaders.has(name.toLowerCase()));const carriesBody=request.headers["transfer-encoding"]!==void 0||Number(request.headers["content-length"]??0)>0;const Readable2=streams2.Readable;const body=carriesBody?Readable2.toWeb(request,{strategy:{highWaterMark:64*1024,size:chunk=>chunk.byteLength}}):void 0;if(!carriesBody)request.resume();const result=await exchange2({url:url2.href,method:request.method,headers:outgoing,...body?{body}:{},signal:controller.signal,profile:"server-http"});if(controller.signal.aborted){await((_a22=result.body)==null?void 0:_a22.cancel(controller.signal.reason));return}response.shouldKeepAlive=false;response.sendDate=false;response.writeHead(result.status,result.statusText,result.headers.flat());reader=(_b22=result.body)==null?void 0:_b22.getReader();try{for(;;){controller.signal.throwIfAborted();const next2=reader?await reader.read():{done:true,value:void 0};if(next2.done)break;if(!response.write(next2.value))await new Promise((resolve2,reject)=>{const abort=()=>{response.removeListener("drain",drain);reject(controller.signal.reason)};const drain=()=>{controller.signal.removeEventListener("abort",abort);resolve2()};response.once("drain",drain);controller.signal.addEventListener("abort",abort,{once:true});if(controller.signal.aborted)abort()})}response.end()}catch(cause){await(reader==null?void 0:reader.cancel(cause).catch(()=>{}));throw cause}finally{reader==null?void 0:reader.releaseLock();reader=void 0}})().catch(fail3)});for(const name of["connect","upgrade","checkContinue","checkExpectation"])server.on(name,()=>fail3(unsupported(name)));server.on("clientError",fail3);server.emit("connection",peer);return client}var DEFAULT_REGISTRY="https://registry.npmjs.org";var Registry=class{constructor(options={}){__publicField2(this,"registryUrl");__publicField2(this,"registryScopes");__publicField2(this,"cache");this.registryUrl=options.registry||DEFAULT_REGISTRY;this.registryScopes=options.registryScopes;this.cache=options.cache||new Map}registryFor(packageName){const scopes2=this.registryScopes??globalThis.__browserRuntimeRegistryScopes;if(scopes2&&typeof packageName==="string"){const scope4=packageName.startsWith("@")&&packageName.includes("/")?packageName.slice(0,packageName.indexOf("/")):packageName;const url2=scopes2[scope4]??scopes2[packageName];if(typeof url2==="string"&&url2!=="")return url2.endsWith("/")?url2.slice(0,-1):url2}return this.registryUrl}async getPackageManifest(packageName){if(this.cache.has(packageName)){return this.cache.get(packageName)}const __docs=globalThis.__browserRuntimeLockfileManifests;const __doc=__docs instanceof Map?__docs.get(packageName):void 0;if(__doc){const __tarball=`${this.registryFor(packageName)}/${encodePackageName(packageName)}/-/${packageName.slice(packageName.lastIndexOf("/")+1)}-${__doc.version}.tgz`;const __manifest={"dist-tags":{latest:__doc.version},versions:{[__doc.version]:{name:packageName,version:__doc.version,dist:{tarball:__tarball},dependencies:__doc.dependencies,...__doc.peerDependencies?{peerDependencies:__doc.peerDependencies,peerDependenciesMeta:__doc.peerDependenciesMeta||{}}:{},...__doc.optionalDependencies?{optionalDependencies:__doc.optionalDependencies}:{}}}};this.cache.set(packageName,__manifest);return __manifest}const __pins=globalThis.__browserRuntimeLockfilePins;const __pin=__pins instanceof Map?__pins.get(packageName):void 0;if(typeof __pin==="string"){const pinnedUrl=`${this.registryFor(packageName)}/${encodePackageName(packageName)}/${__pin}`;const pinnedResponse=await fetch(pinnedUrl,{headers:{Accept:"application/json"}});if(pinnedResponse.ok){const versionData=await pinnedResponse.json();if(versionData&&versionData.dist&&versionData.dist.tarball){const pinnedManifest={"dist-tags":{latest:__pin},versions:{[__pin]:versionData}};this.cache.set(packageName,pinnedManifest);return pinnedManifest}}}const url2=`${this.registryFor(packageName)}/${encodePackageName(packageName)}`;const response=await fetch(url2,{headers:{Accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8"}});if(!response.ok){if(response.status===404){throw new Error(`Package not found: ${packageName}`)}throw new Error(`Failed to fetch package ${packageName}: ${response.status}`)}const manifest=await response.json();this.cache.set(packageName,manifest);return manifest}async getPackageVersion(packageName,version2){const manifest=await this.getPackageManifest(packageName);if(manifest["dist-tags"][version2]){version2=manifest["dist-tags"][version2]}const versionData=manifest.versions[version2];if(!versionData){throw new Error(`Version ${version2} not found for package ${packageName}`)}return versionData}async getLatestVersion(packageName){const manifest=await this.getPackageManifest(packageName);return manifest["dist-tags"].latest}async getVersions(packageName){const manifest=await this.getPackageManifest(packageName);return Object.keys(manifest.versions)}async downloadTarball(tarballUrl){const response=await fetch(tarballUrl);if(!response.ok){throw new Error(`Failed to download tarball: ${response.status}`)}return response.arrayBuffer()}clearCache(){this.cache.clear()}};function encodePackageName(name){return name.replace("/","%2f")}new Registry;function parseVersion(version2){const match2=version2.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(!match2)return null;return{major:parseInt(match2[1],10),minor:parseInt(match2[2],10),patch:parseInt(match2[3],10),prerelease:match2[4]}}function compareVersions(a,b){const parsedA=parseVersion(a);const parsedB=parseVersion(b);if(!parsedA||!parsedB){return a.localeCompare(b)}if(parsedA.major!==parsedB.major){return parsedA.major-parsedB.major}if(parsedA.minor!==parsedB.minor){return parsedA.minor-parsedB.minor}if(parsedA.patch!==parsedB.patch){return parsedA.patch-parsedB.patch}if(parsedA.prerelease&&!parsedB.prerelease)return-1;if(!parsedA.prerelease&&parsedB.prerelease)return 1;if(parsedA.prerelease&&parsedB.prerelease){return parsedA.prerelease.localeCompare(parsedB.prerelease)}return 0}function satisfies(version2,range22){const parsed=parseVersion(version2);if(!parsed)return false;if(parsed.prerelease&&!range22.includes("-")){return false}range22=range22.trim();range22=range22.replace(/^=\s*/,"").replace(/^v(?=\d)/,"");range22=range22.replace(/(>=|<=|>|<|=)\s*(\d+)(\.\d+)?(?![.\d])/g,(__m,__op,__major,__minor)=>__op+" "+__major+(__minor===void 0?".0.0":__minor+".0"));const __browserRuntimePartialRange=range22.match(/^([~^])(\d+)(?:\.(\d+))?(?:\.(\d+))?$/);if(__browserRuntimePartialRange){const operator=__browserRuntimePartialRange[1];const major=Number(__browserRuntimePartialRange[2]);const hasMinor=__browserRuntimePartialRange[3]!==void 0;const hasPatch=__browserRuntimePartialRange[4]!==void 0;const minor=Number(__browserRuntimePartialRange[3]??0);const patch=Number(__browserRuntimePartialRange[4]??0);const lower=major+"."+minor+"."+patch;let upper;if(operator==="~"){upper=hasMinor?major+"."+(minor+1)+".0":major+1+".0.0"}else if(major>0||!hasMinor){upper=major+1+".0.0"}else if(minor>0||!hasPatch){upper="0."+(minor+1)+".0"}else{upper="0.0."+(patch+1)}return compareVersions(version2,lower)>=0&&compareVersions(version2,upper)<0}if(/^\d+\.\d+\.\d+/.test(range22)&&!range22.includes(" ")){const rangeMatch=range22.match(/^(\d+\.\d+\.\d+(?:-[^\s]+)?)/);if(rangeMatch){return compareVersions(version2,rangeMatch[1])===0}}if(range22==="*"||range22==="latest"||range22===""){return true}if(range22.includes("||")){return range22.split("||").some(r10=>satisfies(version2,r10.trim()))}if(range22.includes(" - ")){const[min2,max2]=range22.split(" - ").map(s10=>s10.trim());return compareVersions(version2,min2)>=0&&compareVersions(version2,max2)<=0}const operatorMatches=range22.match(/(>=|<=|>|<|=)?\s*(\d+\.\d+\.\d+(?:-[^\s]*)?)/g);if(operatorMatches&&operatorMatches.length>1){return operatorMatches.every(match2=>{const m=match2.match(/^(>=|<=|>|<|=)?\s*(\d+\.\d+\.\d+(?:-[^\s]*)?)$/);if(!m)return true;const op2=m[1]||"=";const ver=m[2];switch(op2){case">=":return compareVersions(version2,ver)>=0;case"<=":return compareVersions(version2,ver)<=0;case">":return compareVersions(version2,ver)>0;case"<":return compareVersions(version2,ver)<0;case"=":return compareVersions(version2,ver)===0;default:return compareVersions(version2,ver)===0}})}if(range22.startsWith("^")){const base=range22.slice(1);const baseParsed=parseVersion(base);if(!baseParsed)return false;if(parsed.major!==baseParsed.major){return false}if(baseParsed.major===0){if(baseParsed.minor!==0&&parsed.minor!==baseParsed.minor){return false}if(baseParsed.minor===0&&parsed.minor!==0){return false}}return compareVersions(version2,base)>=0}if(range22.startsWith("~")){const base=range22.slice(1);const baseParsed=parseVersion(base);if(!baseParsed)return false;if(parsed.major!==baseParsed.major||parsed.minor!==baseParsed.minor){return false}return compareVersions(version2,base)>=0}if(range22.startsWith(">=")){const base=range22.slice(2).trim();return compareVersions(version2,base)>=0}if(range22.startsWith(">")){const base=range22.slice(1).trim();return compareVersions(version2,base)>0}if(range22.startsWith("<=")){const base=range22.slice(2).trim();return compareVersions(version2,base)<=0}if(range22.startsWith("<")){const base=range22.slice(1).trim();return compareVersions(version2,base)<0}if(range22.includes("x")||range22.includes("X")||/^\d+$/.test(range22)||/^\d+\.\d+$/.test(range22)){const parts=range22.replace(/[xX]/g,"").split(".").filter(Boolean);if(parts.length===1){return parsed.major===parseInt(parts[0],10)}if(parts.length===2){return parsed.major===parseInt(parts[0],10)&&parsed.minor===parseInt(parts[1],10)}}if(range22.includes(" ")){const conditions=range22.split(/\s+/).filter(Boolean);return conditions.every(r10=>satisfies(version2,r10))}return compareVersions(version2,range22)===0}function findBestVersion(versions,range22){const sorted=[...versions].sort((a,b)=>compareVersions(b,a));for(const version2 of sorted){if(satisfies(version2,range22)){return version2}}return null}async function resolveDependencies(packageName,versionRange="latest",options={}){const registry=options.registry||new Registry;const context2={registry,resolved:new Map,resolving:new Set,options};await resolvePackage(packageName,versionRange,context2);context2.resolved.__nested=context2.nested;return context2.resolved}async function resolveFromPackageJson(packageJson,options={}){const registry=options.registry||new Registry;const context2={registry,resolved:new Map,resolving:new Set,options};const deps={...packageJson.dependencies};if(options.includeDev&&packageJson.devDependencies){Object.assign(deps,packageJson.devDependencies)}const __pins=globalThis.__browserRuntimeLockfilePins;if(__pins instanceof Map&&__pins.size>0){const __names=[...__pins.keys()];for(let __index=0;__index<__names.length;__index+=32){await Promise.all(__names.slice(__index,__index+32).map(name3=>registry.getPackageManifest(name3).catch(()=>void 0)))}}context2.rootDeps=new Map;for(const[name,range22]of Object.entries(deps)){await resolvePackage(name,range22,context2,void 0,"choose")}for(const[name,range22]of Object.entries(deps)){await resolvePackage(name,range22,context2,void 0,"descend")}context2.resolved.__nested=context2.nested;return context2.resolved}async function __browserRuntimeNest(packageName,versionRange,context2,parentKey,registryName=packageName){const records=globalThis.__browserRuntimeLockfileRecords;const versions=records instanceof Map?records.get(packageName):void 0;if(!versions)return;const candidates=[...versions.keys()].filter(version22=>satisfies(version22,versionRange)).sort((a,b)=>compareVersions(b,a));const version2=candidates[0];if(!version2)return;const nestedKey=parentKey?`${parentKey}/node_modules/${packageName}`:packageName;context2.nested??(context2.nested=new Map);if(context2.nested.has(nestedKey)||context2.resolving.has(nestedKey))return;context2.resolving.add(nestedKey);try{const doc=versions.get(version2);const tarballUrl=doc.resolved||`${context2.registry.registryFor(registryName)}/${encodePackageName(registryName)}/-/${registryName.slice(registryName.lastIndexOf("/")+1)}-${version2}.tgz`;context2.nested.set(nestedKey,{name:packageName,version:version2,tarballUrl,dependencies:doc.dependencies||{}});const deps={};if(doc.peerDependencies){const meta=doc.peerDependenciesMeta||{};for(const[name2,range22]of Object.entries(doc.peerDependencies)){if(!(meta[name2]&&meta[name2].optional))deps[name2]=range22}}Object.assign(deps,doc.dependencies);if(context2.options.includeOptional&&doc.optionalDependencies)Object.assign(deps,doc.optionalDependencies);for(const[depName,depRange]of Object.entries(deps)){await resolvePackage(depName,depRange,context2,nestedKey)}}finally{context2.resolving.delete(nestedKey)}}async function resolvePackage(packageName,versionRange,context2,__parent,phase){var _a22,_b22,_c22;if(phase==="descend"){const chosen=(_a22=context2.rootDeps)==null?void 0:_a22.get(packageName);if(!chosen)return;context2.rootDeps.delete(packageName);await descendInto(packageName,chosen,context2);return}let __registryName=packageName;if(typeof versionRange==="string"&&versionRange.startsWith("npm:")){const __spec=versionRange.slice(4);const __at=__spec.lastIndexOf("@");__registryName=__at>0?__spec.slice(0,__at):__spec;versionRange=__at>0?__spec.slice(__at+1):"latest"}const{registry,resolved,resolving,options}=context2;const key=`${packageName}@${versionRange}`;if(resolving.has(key)){return}if(resolved.has(packageName)){const existing=resolved.get(packageName);if(satisfies(existing.version,versionRange)){return}await __browserRuntimeNest(packageName,versionRange,context2,__parent,typeof __registryName==="string"?__registryName:packageName);return}resolving.add(key);try{(_b22=options.onProgress)==null?void 0:_b22.call(options,`Resolving ${packageName}@${versionRange}`);const manifest=await registry.getPackageManifest(__registryName);const versions=Object.keys(manifest.versions);let targetVersion;const __pinned=globalThis.__browserRuntimeLockfilePins;const __pin=__pinned instanceof Map?__pinned.get(__registryName):void 0;if(typeof __pin==="string"&&manifest.versions[__pin]){const versionData2=manifest.versions[__pin];const resolvedPackage2={name:packageName,version:__pin,tarballUrl:versionData2.dist.tarball,dependencies:versionData2.dependencies||{}};resolved.set(packageName,resolvedPackage2);const deps2={};if(versionData2.peerDependencies){const meta2=versionData2.peerDependenciesMeta||{};for(const[name3,range22]of Object.entries(versionData2.peerDependencies)){if(!(meta2[name3]==null?void 0:meta2[name3].optional))deps2[name3]=range22}}Object.assign(deps2,versionData2.dependencies);if(options.includeOptional&&versionData2.optionalDependencies){Object.assign(deps2,versionData2.optionalDependencies)}if(phase==="choose")context2.rootDeps.set(packageName,deps2);else await descendInto(packageName,deps2,context2);if(!satisfies(__pin,versionRange))await __browserRuntimeNest(packageName,versionRange,context2,__parent,__registryName);return}if(versionRange==="latest"||versionRange==="*"){targetVersion=manifest["dist-tags"].latest}else if(manifest["dist-tags"][versionRange]){targetVersion=manifest["dist-tags"][versionRange]}else{const best=findBestVersion(versions,versionRange);if(!best){throw new Error(`No matching version found for ${packageName}@${versionRange}`)}targetVersion=best}const versionData=manifest.versions[targetVersion];const resolvedPackage={name:packageName,version:targetVersion,tarballUrl:versionData.dist.tarball,dependencies:versionData.dependencies||{}};resolved.set(packageName,resolvedPackage);const deps={};if(versionData.peerDependencies){const meta=versionData.peerDependenciesMeta||{};for(const[name,range22]of Object.entries(versionData.peerDependencies)){if(!((_c22=meta[name])==null?void 0:_c22.optional)){deps[name]=range22}}}Object.assign(deps,versionData.dependencies);if(options.includeOptional&&versionData.optionalDependencies){Object.assign(deps,versionData.optionalDependencies)}if(phase==="choose")context2.rootDeps.set(packageName,deps);else await descendInto(packageName,deps,context2)}finally{resolving.delete(key)}}async function descendInto(packageName,deps,context2){const depEntries=Object.entries(deps);if(depEntries.length===0)return;const CONCURRENCY=8;for(let i22=0;i22<depEntries.length;i22+=CONCURRENCY){const batch=depEntries.slice(i22,i22+CONCURRENCY);await Promise.all(batch.map(([depName,depRange])=>resolvePackage(depName,depRange,context2,packageName)))}}function*parseTar(data2){new TextDecoder;let offset2=0;let __nextName;while(offset2<data2.length-512){const header=data2.slice(offset2,offset2+512);offset2+=512;if(header.every(b=>b===0)){break}const name=parseString(header,0,100);const mode=parseOctal(header,100,8);const size=parseOctal(header,124,12);const typeFlag=String.fromCharCode(header[156]);const linkName=parseString(header,157,100);const prefix2=parseString(header,345,155);if(!name){continue}const fullName=__nextName!==void 0?__nextName:prefix2?`${prefix2}/${name}`:name;__nextName=void 0;let type2;switch(typeFlag){case"0":case"\0":case"":type2="file";break;case"5":type2="directory";break;case"1":case"2":type2="symlink";break;default:type2="unknown"}let content;const __payload=size>0?Math.ceil(size/512)*512:0;if(typeFlag==="x"||typeFlag==="L"){const __text=new TextDecoder().decode(data2.slice(offset2,offset2+size));offset2+=__payload;if(typeFlag==="L"){__nextName=__text.replace(/\0+$/,"")}else{for(const __line of __text.split("\n")){const __match=/^\d+ path=(.*)$/.exec(__line);if(__match)__nextName=__match[1]}}continue}if(type2==="file"){content=size>0?data2.slice(offset2,offset2+size):new Uint8Array(0)}offset2+=__payload;yield{name:fullName,type:type2,size,mode,content,linkTarget:type2==="symlink"?linkName:void 0}}}function parseString(data2,offset2,length){const bytes2=data2.slice(offset2,offset2+length);const nullIndex=bytes2.indexOf(0);const actualBytes=nullIndex>=0?bytes2.slice(0,nullIndex):bytes2;return new TextDecoder().decode(actualBytes)}function parseOctal(data2,offset2,length){const str=parseString(data2,offset2,length).trim();return parseInt(str,8)||0}function decompress2(data2){const input=data2 instanceof Uint8Array?data2:new Uint8Array(data2);return pako.inflate(input)}function extractTarball(tarballData,vfs2,destPath,options={}){const{stripComponents=1,filter:filter2,onProgress}=options;onProgress==null?void 0:onProgress("Decompressing...");const tarData=decompress2(tarballData);const extractedFiles=[];for(const entry of parseTar(tarData)){if(entry.type!=="file"&&entry.type!=="directory"){continue}let entryPath=entry.name;if(stripComponents>0){const parts=entryPath.split("/").filter(Boolean);if(parts.length<=stripComponents){continue}entryPath=parts.slice(stripComponents).join("/")}if(filter2&&!filter2(entryPath)){continue}const fullPath=join2(destPath,entryPath);if(entry.type==="directory"){vfs2.mkdirSync(fullPath,{recursive:true})}else if(entry.type==="file"&&entry.content){const parentDir=dirname(fullPath);vfs2.mkdirSync(parentDir,{recursive:true});vfs2.writeFileSync(fullPath,entry.content);extractedFiles.push(fullPath)}}onProgress==null?void 0:onProgress(`Extracted ${extractedFiles.length} files`);return extractedFiles}globalThis[Symbol.for("@volter/browser-runtime/package-extract")]=extractTarball;async function __browserRuntimeInstallPool(items,size,work){let next2=0;await Promise.all(Array.from({length:Math.min(size,items.length)},async()=>{for(;;){const index2=next2++;if(index2>=items.length)return;await work(items[index2])}}))}async function downloadAndExtract(url2,vfs2,destPath,options={}){const{onProgress}=options;onProgress==null?void 0:onProgress(`Downloading ${url2}...`);const response=await fetch(url2);if(!response.ok){throw new Error(`Failed to download tarball: ${response.status}`)}const data2=await response.arrayBuffer();return extractTarball(data2,vfs2,destPath,options)}var isBrowser=typeof window!=="undefined";var NODE_DYNAMIC_IMPORT_BUILTINS=["stream/web","fs/promises","stream/promises","stream/consumers","timers/promises","dns/promises","readline/promises","path/posix","path/win32","util/types","assert/strict","assert","buffer","constants","child_process","cluster","crypto","dgram","dns","events","fs","http","http2","https","net","os","path","perf_hooks","querystring","readline","stream","string_decoder","timers","tls","url","util","v8","vm","worker_threads","zlib","async_hooks","inspector","module"];function lowerDynamicBuiltinImports(code22){let lowered=code22.replace(/\bimport\s*\(\s*["']node:([^"']+)["']\s*\)/g,'Promise.resolve(require("node:$1"))');for(const builtin of NODE_DYNAMIC_IMPORT_BUILTINS){const pattern=new RegExp(`\\bimport\\s*\\(\\s*["']${builtin}["']\\s*\\)`,"g");lowered=lowered.replace(pattern,`Promise.resolve(require("${builtin}"))`)}return lowered}async function initTransformer(){if(getEsbuildInstance())return;if(!isBrowser){console.log("[transform] Skipping esbuild init (not in browser)");return}if(window.__esbuild){console.log("[transform] Reusing existing esbuild instance");return}if(window.__esbuildInitPromise){return window.__esbuildInitPromise}window.__esbuildInitPromise=(async()=>{try{console.log("[transform] Loading esbuild-wasm...");const mod=await import(ESBUILD_WASM_ESM_CDN);const esbuildMod=mod.default||mod;try{await esbuildMod.initialize({wasmURL:ESBUILD_WASM_BINARY_CDN});console.log("[transform] esbuild-wasm initialized")}catch(initError){if(initError instanceof Error&&initError.message.includes('Cannot call "initialize" more than once')){console.log("[transform] esbuild-wasm already initialized, reusing")}else{throw initError}}window.__esbuild=esbuildMod}catch(error){console.error("[transform] Failed to initialize esbuild:",error);window.__esbuildInitPromise=void 0;throw error}})();return window.__esbuildInitPromise}function isTransformerReady(){if(getEsbuildInstance())return true;if(!isBrowser)return true;return window.__esbuild!==void 0}async function transformFile(code22,filename){if(!getEsbuildInstance()&&!isBrowser){return code22}if(!getEsbuildInstance()&&!window.__esbuild){await initTransformer()}const esbuild2=getEsbuildInstance()??window.__esbuild;if(!esbuild2){throw new Error("esbuild not initialized")}let loader="js";if(filename.endsWith(".jsx"))loader="jsx";else if(filename.endsWith(".ts"))loader="ts";else if(filename.endsWith(".tsx"))loader="tsx";else if(filename.endsWith(".mjs"))loader="js";try{const result=await esbuild2.transform(code22,{loader,format:"cjs",target:"esnext",platform:"neutral",define:{"import.meta.url":"import_meta.url","import.meta.dirname":"import_meta.dirname","import.meta.filename":"import_meta.filename","import.meta":"import_meta"}});const transformed=lowerDynamicBuiltinImports(result.code);return transformed}catch(error){const errorMsg=error instanceof Error?error.message:String(error);if(errorMsg.includes("Top-level await")){console.log(`[transform] Skipping ${filename} (has top-level await, likely CLI entry point)`);return code22}console.warn(`[transform] Failed to transform ${filename}:`,error);return code22}}function needsTransform(filename,code22){if(filename.endsWith(".mjs")){return true}if(filename.endsWith(".cjs")){return false}const hasImport=/\bimport\s+[\w{*'"]/m.test(code22);const hasExport=/\bexport\s+(?:default|const|let|var|function|class|{|\*)/m.test(code22);const hasImportMeta=/\bimport\.meta\b/.test(code22);return hasImport||hasExport||hasImportMeta}function hasDynamicNodeImports(code22){if(/\bimport\s*\(\s*["']node:/.test(code22)){return true}const names2=NODE_DYNAMIC_IMPORT_BUILTINS.map(name=>name.replace("/","\\/")).join("|");return new RegExp(`\\bimport\\s*\\(\\s*["'](?:${names2})["']\\s*\\)`).test(code22)}function patchDynamicImports(code22){return lowerDynamicBuiltinImports(code22)}async function transformPackage(vfs2,pkgPath,onProgress){let transformedCount=0;const jsFiles=findJsFiles(vfs2,pkgPath);onProgress==null?void 0:onProgress(` Transforming ${jsFiles.length} files in ${pkgPath}...`);const BATCH_SIZE=10;for(let i22=0;i22<jsFiles.length;i22+=BATCH_SIZE){const batch=jsFiles.slice(i22,i22+BATCH_SIZE);await Promise.all(batch.map(async filePath=>{try{const code22=vfs2.readFileSync(filePath,"utf8");if(needsTransform(filePath,code22)){const transformed=await transformFile(code22,filePath);vfs2.writeFileSync(filePath,transformed);transformedCount++}else if(hasDynamicNodeImports(code22)){const patched=patchDynamicImports(code22);vfs2.writeFileSync(filePath,patched);transformedCount++}}catch(error){console.warn(`[transform] Skipping ${filePath}:`,error)}}))}return transformedCount}function findJsFiles(vfs2,dir){const files=[];try{const entries=vfs2.readdirSync(dir);for(const entry of entries){const fullPath=dir+"/"+entry;try{const stat2=vfs2.statSync(fullPath);if(stat2.isDirectory()){if(entry!=="node_modules"){files.push(...findJsFiles(vfs2,fullPath))}}else if(entry.endsWith(".js")||entry.endsWith(".mjs")||entry.endsWith(".jsx")){files.push(fullPath)}}catch{}}}catch{}return files}var installTransformEnabled=false;function setInstallTransformEnabled(enabled){installTransformEnabled=enabled}function normalizeBin(pkgName,bin){if(!bin)return{};if(typeof bin==="string"){const cmdName=pkgName.includes("/")?pkgName.split("/").pop():pkgName;return{[cmdName]:bin}}return bin}var PackageManager=class{constructor(vfs2,options={}){__publicField2(this,"vfs");__publicField2(this,"registry");__publicField2(this,"cwd");this.vfs=vfs2;this.registry=new Registry(options);this.cwd=options.cwd||"/"}async install(packageSpec,options={}){const{onProgress}=options;const{name,version:version2}=parsePackageSpec(packageSpec);onProgress==null?void 0:onProgress(`Resolving ${name}@${version2||"latest"}...`);const resolved=await resolveDependencies(name,version2||"latest",{registry:this.registry,includeDev:options.includeDev,includeOptional:options.includeOptional,onProgress});const added=await this.installResolved(resolved,options);if(options.save||options.saveDev){const pkgToAdd=resolved.get(name);if(pkgToAdd){await this.updatePackageJson(name,`^${pkgToAdd.version}`,options.saveDev||false)}}onProgress==null?void 0:onProgress(`Installed ${resolved.size} packages`);return{installed:resolved,added}}async installFromPackageJson(options={}){var _a22;const{onProgress}=options;const pkgJsonPath=join2(this.cwd,"package.json");if(!this.vfs.existsSync(pkgJsonPath)){throw new Error("No package.json found")}const pkgJson=((_a22=this.vfs[Symbol.for("@volter/browser-node/workspace-install-manifests")])==null?void 0:_a22.get(this.cwd))??JSON.parse(this.vfs.readFileSync(pkgJsonPath,"utf8"));onProgress==null?void 0:onProgress("Resolving dependencies...");const resolved=await resolveFromPackageJson(pkgJson,{registry:this.registry,includeDev:options.includeDev,includeOptional:options.includeOptional,onProgress});const added=await this.installResolved(resolved,options);onProgress==null?void 0:onProgress(`Installed ${resolved.size} packages`);return{installed:resolved,added}}async installResolved(resolved,options){const{onProgress}=options;const added=[];const nodeModulesPath=join2(this.cwd,"node_modules");this.vfs.mkdirSync(nodeModulesPath,{recursive:true});const toInstall=[];for(const[name,pkg]of resolved){const pkgPath=join2(nodeModulesPath,name);const existingPkgJson=join2(pkgPath,"package.json");if(this.vfs.existsSync(existingPkgJson)){try{const existing=JSON.parse(this.vfs.readFileSync(existingPkgJson,"utf8"));if(existing.version===pkg.version){onProgress==null?void 0:onProgress(`Skipping ${name}@${pkg.version} (already installed)`);continue}}catch{}}toInstall.push({name,pkg,pkgPath})}for(const[nestedKey,pkg]of resolved.__nested instanceof Map?resolved.__nested:[]){toInstall.push({name:pkg.name,pkg,pkgPath:join2(nodeModulesPath,nestedKey)})}const shouldTransform=installTransformEnabled;if(shouldTransform&&!isTransformerReady()){onProgress==null?void 0:onProgress("Initializing ESM transformer...");await initTransformer()}const CONCURRENCY=16;onProgress==null?void 0:onProgress(`Installing ${toInstall.length} packages...`);await __browserRuntimeInstallPool(toInstall,CONCURRENCY,async({name,pkg,pkgPath})=>{onProgress==null?void 0:onProgress(` Downloading ${name}@${pkg.version}...`);const __installHook=globalThis[Symbol.for("@volter/browser-runtime/package-install")];if(!(__installHook&&await __installHook(name,pkg,pkgPath,this.vfs))){await downloadAndExtract(pkg.tarballUrl,this.vfs,pkgPath,{stripComponents:1})}if(shouldTransform){try{const count=await transformPackage(this.vfs,pkgPath,onProgress);if(count>0){onProgress==null?void 0:onProgress(` Transformed ${count} files in ${name}`)}}catch(transformError){onProgress==null?void 0:onProgress(` Warning: Transform failed for ${name}: ${transformError}`)}}try{const pkgJsonPath=join2(pkgPath,"package.json");if(this.vfs.existsSync(pkgJsonPath)){const pkgJson=JSON.parse(this.vfs.readFileSync(pkgJsonPath,"utf8"));const binEntries=normalizeBin(name,pkgJson.bin);const binDir=join2(pkgPath.slice(0,pkgPath.lastIndexOf("/node_modules/")+"/node_modules".length),".bin");for(const[cmdName,entryPath]of Object.entries(binEntries)){this.vfs.mkdirSync(binDir,{recursive:true});const targetPath=join2(pkgPath,entryPath);this.vfs.writeFileSync(join2(binDir,cmdName),`node "${targetPath}" "$@"
5892
- `)}}}catch{}added.push(name)});await this.writeLockfile(resolved);return added}async writeLockfile(resolved){const lockfile={};for(const[name,pkg]of resolved){lockfile[name]={version:pkg.version,resolved:pkg.tarballUrl}}const lockfilePath=join2(this.cwd,"node_modules",".package-lock.json");this.vfs.writeFileSync(lockfilePath,JSON.stringify(lockfile,null,2))}async updatePackageJson(packageName,version2,isDev){const pkgJsonPath=join2(this.cwd,"package.json");let pkgJson={};if(this.vfs.existsSync(pkgJsonPath)){pkgJson=JSON.parse(this.vfs.readFileSync(pkgJsonPath,"utf8"))}const field=isDev?"devDependencies":"dependencies";if(!pkgJson[field]){pkgJson[field]={}}pkgJson[field][packageName]=version2;this.vfs.writeFileSync(pkgJsonPath,JSON.stringify(pkgJson,null,2))}list(){const nodeModulesPath=join2(this.cwd,"node_modules");if(!this.vfs.existsSync(nodeModulesPath)){return{}}const packages2={};const entries=this.vfs.readdirSync(nodeModulesPath);for(const entry of entries){if(entry.startsWith("."))continue;if(entry.startsWith("@")){const scopePath=join2(nodeModulesPath,entry);const scopedPkgs=this.vfs.readdirSync(scopePath);for(const scopedPkg of scopedPkgs){const pkgJsonPath=join2(scopePath,scopedPkg,"package.json");if(this.vfs.existsSync(pkgJsonPath)){const pkgJson=JSON.parse(this.vfs.readFileSync(pkgJsonPath,"utf8"));packages2[`${entry}/${scopedPkg}`]=pkgJson.version}}}else{const pkgJsonPath=join2(nodeModulesPath,entry,"package.json");if(this.vfs.existsSync(pkgJsonPath)){const pkgJson=JSON.parse(this.vfs.readFileSync(pkgJsonPath,"utf8"));packages2[entry]=pkgJson.version}}}return packages2}};function parsePackageSpec(spec){if(spec.startsWith("@")){const slashIndex=spec.indexOf("/");if(slashIndex===-1){throw new Error(`Invalid package spec: ${spec}`)}const afterSlash=spec.slice(slashIndex+1);const atIndex2=afterSlash.indexOf("@");if(atIndex2===-1){return{name:spec}}return{name:spec.slice(0,slashIndex+1+atIndex2),version:afterSlash.slice(atIndex2+1)}}const atIndex=spec.indexOf("@");if(atIndex===-1){return{name:spec}}return{name:spec.slice(0,atIndex),version:spec.slice(atIndex+1)}}async function install(packageSpec,vfs2,options){const pm=new PackageManager(vfs2);return pm.install(packageSpec,options)}var index=Object.freeze(Object.defineProperty({__proto__:null,PackageManager,Registry,install,parsePackageSpec,setInstallTransformEnabled},Symbol.toStringTag,{value:"Module"}));function __listening(port2){return listenerOnPort(port2)!==void 0}function requestHead(method,url2,headers,body){const lines=[`${method.toUpperCase()} ${url2} HTTP/1.1`];let hasLength=false;let hasEncoding=false;for(const[name,value]of Object.entries(headers)){const lower=name.toLowerCase();if(lower==="content-length")hasLength=true;if(lower==="transfer-encoding")hasEncoding=true;if(lower==="connection")continue;lines.push(`${name}: ${value}`)}if(!hasLength&&!hasEncoding)lines.push(`Content-Length: ${body?body.length:0}`);lines.push("Connection: close","","");return lines.join("\r\n")}function responseParser(collected,onHead,onChunk){const parser=new HTTPParser;parser.initialize(HTTPParser.RESPONSE,null,0,0);parser[HTTPParser.kOnHeadersComplete]=(_major,_minor,headers,_method,_url2,statusCode,statusMessage,upgrade)=>{if(collected.complete)return 0;collected.statusCode=statusCode;collected.statusMessage=statusMessage;collected.upgrade=upgrade;for(let index2=0;index2+1<headers.length;index2+=2){const name=headers[index2].toLowerCase();const value=headers[index2+1];collected.headers[name]=collected.headers[name]===void 0?value:`${collected.headers[name]}, ${value}`}onHead==null?void 0:onHead();return 0};parser[HTTPParser.kOnBody]=chunk=>{if(collected.complete)return;if(onChunk)onChunk(chunk);else collected.chunks.push(chunk)};parser[HTTPParser.kOnMessageComplete]=()=>{if(collected.complete)return collected.upgrade?0:-1;collected.complete=true;if(collected.upgrade)return 0;parser.pause();return-1};return parser}function emptyCollected(){return{statusCode:0,statusMessage:"",headers:{},chunks:[],complete:false,upgrade:false}}function ownedConcat(chunks){let total=0;for(const chunk of chunks)total+=chunk.byteLength;const joined=new Uint8Array(total);let at22=0;for(const chunk of chunks){joined.set(new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength),at22);at22+=chunk.byteLength}return joined}function serviceUnavailable(port2){return{statusCode:503,statusMessage:"Service Unavailable",headers:{"Content-Type":"text/plain"},body:ownedConcat([Buffer$9.from(`No server listening on port ${port2}`)])}}function __requestOverLoopback(port2,method,url2,headers,body){if(!__listening(port2))return Promise.resolve(serviceUnavailable(port2));return new Promise(resolve2=>{const collected=emptyCollected();const parser=responseParser(collected);let settled=false;const answer2=()=>{if(settled)return;settled=true;parser.free();resolve2({statusCode:collected.statusCode||502,statusMessage:collected.statusMessage,headers:collected.headers,body:ownedConcat(collected.chunks)})};const socket=netModule.connect({port:port2,host:"127.0.0.1"});socket.on("data",chunk=>{if(settled)return;const read=parser.execute(chunk);if(read instanceof Error){socket.destroy();answer2()}else if(collected.complete){socket.destroy();answer2()}});socket.on("end",()=>{if(!settled){parser.finish()}answer2()});socket.on("close",answer2);socket.on("error",()=>{if(settled)return;settled=true;parser.free();resolve2(serviceUnavailable(port2))});socket.write(requestHead(method,url2,headers,body));if(body&&body.length>0)socket.write(body)})}function __streamOverLoopback(port2,method,url2,headers,body,onStart,onChunk,onEnd,flow){if(!__listening(port2)){onStart(503,"Service Unavailable",{"Content-Type":"text/plain"});onEnd();return Promise.resolve()}return new Promise(resolve2=>{var _a22;const collected=emptyCollected();let started2=false;let ended2=false;const finish=()=>{if(ended2)return;ended2=true;parser.free();onEnd();resolve2()};const parser=responseParser(collected,()=>{started2=true;onStart(collected.statusCode,collected.statusMessage,collected.headers)},chunk=>onChunk(chunk));const socket=netModule.connect({port:port2,host:"127.0.0.1"});(_a22=flow==null?void 0:flow.control)==null?void 0:_a22.call(flow,()=>socket.pause(),()=>socket.resume());if(flow==null?void 0:flow.signal){if(flow.signal.aborted){socket.destroy();finish();return}flow.signal.addEventListener("abort",()=>{socket.destroy();finish()},{once:true})}socket.on("data",chunk=>{if(ended2)return;const read=parser.execute(chunk);if(read instanceof Error){socket.destroy();finish()}else if(collected.complete){socket.destroy();finish()}});socket.on("end",()=>{if(!ended2){parser.finish()}finish()});socket.on("close",finish);socket.on("error",()=>{if(!started2)onStart(503,"Service Unavailable",{"Content-Type":"text/plain"});finish()});socket.write(requestHead(method,url2,headers,body));if(body&&body.length>0)socket.write(body)})}function __upgradeOverLoopback(port2,method,url2,headers){if(!__listening(port2)){return Promise.resolve({statusCode:503,statusMessage:"Service Unavailable",headers:{},socket:null})}return new Promise(resolve2=>{const collected=emptyCollected();let settled=false;const parser=responseParser(collected);const socket=netModule.connect({port:port2,host:"127.0.0.1"});const fail3=()=>{if(settled)return;settled=true;parser.free();resolve2({statusCode:collected.statusCode||502,statusMessage:collected.statusMessage,headers:collected.headers,socket:null})};socket.on("data",chunk=>{if(settled)return;const read=parser.execute(chunk);if(read instanceof Error){socket.destroy();fail3();return}if(collected.upgrade||collected.statusCode===101){settled=true;parser.free();const consumed=typeof read==="number"?read:chunk.length;const rest=chunk.subarray(consumed);if(rest.length>0)socket.unshift(rest);resolve2({statusCode:collected.statusCode,statusMessage:collected.statusMessage,headers:collected.headers,socket});return}if(collected.complete){socket.destroy();fail3()}});socket.on("error",fail3);socket.on("close",fail3);const upgradeHeaders={...headers,Connection:"Upgrade"};const lines=[`${method.toUpperCase()} ${url2} HTTP/1.1`];for(const[name,value]of Object.entries(upgradeHeaders)){if(name.toLowerCase()==="connection")continue;lines.push(`${name}: ${value}`)}lines.push("Connection: Upgrade","","");socket.write(lines.join("\r\n"))})}var _encoder2=new TextEncoder;function guestListeningServer(port2,address){const hostname2=address;return{listening:true,address:()=>({port:port2,address:hostname2,family:hostname2.includes(":")?"IPv6":"IPv4"}),handleRequest:(method,url2,headers,body)=>__requestOverLoopback(port2,method,url2,headers,typeof body==="string"?Buffer$9.from(body):body)}}var __substrateUpgradeSockets=new Map;function __substrateFrame(opcode,payload,masked){const length=payload.length;const header=[128|opcode];if(length<126)header.push(128|length);else if(length<65536)header.push(128|126,length>>8,length&255);else header.push(128|127,0,0,0,0,length>>>24&255,length>>>16&255,length>>>8&255,length&255);const mask=[Math.random()*256|0,Math.random()*256|0,Math.random()*256|0,Math.random()*256|0];const out=new Uint8Array(header.length+mask.length+length);out.set(header,0);out.set(mask,header.length);for(let index2=0;index2<length;index2+=1)out[header.length+mask.length+index2]=payload[index2]^mask[index2&3];return out}function __substrateParseFrames(state,chunk,onFrame){const joined=state.pending.length?new Uint8Array([...state.pending,...chunk]):chunk;let offset2=0;for(;;){if(joined.length-offset2<2)break;const b02=joined[offset2],b12=joined[offset2+1];const fin=(b02&128)!==0,opcode=b02&15,masked=(b12&128)!==0;let length=b12&127,at22=offset2+2;if(length===126){if(joined.length-at22<2)break;length=joined[at22]<<8|joined[at22+1];at22+=2}else if(length===127){if(joined.length-at22<8)break;length=0;for(let index2=0;index2<8;index2+=1)length=length*256+joined[at22+index2];at22+=8}let mask;if(masked){if(joined.length-at22<4)break;mask=joined.subarray(at22,at22+4);at22+=4}if(joined.length-at22<length)break;const payload=joined.slice(at22,at22+length);if(mask)for(let index2=0;index2<length;index2+=1)payload[index2]^=mask[index2&3];offset2=at22+length;if(opcode===0&&state.fragments){state.fragments.parts.push(payload);if(fin){const parts=state.fragments.parts;const total=parts.reduce((sum,part)=>sum+part.length,0);const whole=new Uint8Array(total);let cursor=0;for(const part of parts){whole.set(part,cursor);cursor+=part.length}const op2=state.fragments.opcode;state.fragments=null;onFrame(op2,whole)}}else if(!fin&&(opcode===1||opcode===2))state.fragments={opcode,parts:[payload]};else onFrame(opcode,payload)}state.pending=joined.slice(offset2)}function __substrateUpgradeSocket(entry,socket){const end=socket;const bridge={push:frame=>{socket.write(frame)},destroy:()=>{socket.destroy()},get destroyed(){return socket.destroyed},onData:listener=>{socket.on("data",listener)}};let closed=false;const state={pending:new Uint8Array(0),fragments:null};const decoder22=new TextDecoder;const finish=(code22,reason)=>{if(closed)return;closed=true;__substrateUpgradeSockets.delete(entry.clientId);entry.channel.postMessage({type:"close",targetClient:entry.clientId,code:code22,reason})};const receive2=frame=>{if(!bridge.destroyed)bridge.push(frame)};bridge.onData(chunk=>{const bytes2=chunk;__substrateParseFrames(state,bytes2,(opcode,payload)=>{if(opcode===1)entry.channel.postMessage({type:"message",targetClient:entry.clientId,payload:decoder22.decode(payload)});else if(opcode===2)entry.channel.postMessage({type:"message",targetClient:entry.clientId,payload:payload.buffer.slice(payload.byteOffset,payload.byteOffset+payload.byteLength)});else if(opcode===8){const code22=payload.length>=2?payload[0]<<8|payload[1]:1005;finish(code22===1005?1e3:code22,payload.length>2?decoder22.decode(payload.subarray(2)):"");end.destroy()}else if(opcode===9)receive2(__substrateFrame(10,payload))})});end.on("close",()=>{finish(1e3,"");bridge.destroy()});end.deliver=payload=>{if(closed||end.destroyed)return;const bytes2=typeof payload==="string"?_encoder2.encode(payload):new Uint8Array(payload);receive2(__substrateFrame(typeof payload==="string"?1:2,bytes2))};end.disconnect=(code22,reason)=>{if(closed||end.destroyed)return;const text=_encoder2.encode(reason||"");const payload=new Uint8Array(2+text.length);payload[0]=code22>>8;payload[1]=code22&255;payload.set(text,2);receive2(__substrateFrame(8,payload));setTimeout(()=>{finish(code22,reason||"");end.destroy()},50)};return end}function __substrateRawUpgradeSocket(entry,socket){const end=socket;const bridge={push:data2=>{socket.write(data2)},destroy:()=>{socket.destroy()},end:()=>{socket.end()},get destroyed(){return socket.destroyed},onData:listener=>{socket.on("data",listener)}};let closed=false;const finish=(code22,reason)=>{if(closed)return;closed=true;__substrateUpgradeSockets.delete(entry.clientId);entry.channel.postMessage({type:"close",targetClient:entry.clientId,code:code22,reason})};bridge.onData(chunk=>{if(closed)return;entry.channel.postMessage({type:"message",targetClient:entry.clientId,payload:chunk.buffer.slice(chunk.byteOffset,chunk.byteOffset+chunk.byteLength)})});end.on("close",()=>{finish(1e3,"");bridge.destroy()});end.deliver=payload=>{if(closed||end.destroyed||bridge.destroyed)return;bridge.push(typeof payload==="string"?_encoder2.encode(payload):new Uint8Array(payload))};end.disconnect=(code22,reason)=>{if(closed||end.destroyed)return;bridge.end();finish(code22,reason||"");end.destroy()};return end}function __substrateListenForUpgrades(bridge){var _a22;if(typeof BroadcastChannel==="undefined")return null;const channel=new BroadcastChannel("vite-ws-channel");(_a22=channel.unref)==null?void 0:_a22.call(channel);channel.addEventListener("message",event=>{const data2=event.data;if(!data2||typeof data2!=="object")return;if(data2.type==="connect"){let url2;try{url2=new URL(data2.url)}catch{return}const port2=Number(url2.port);if(!__listening(port2))return;const record={clientId:data2.clientId,channel};const raw=data2.framing==="none";const key=uint8ToBase64(crypto.getRandomValues(new Uint8Array(16)));const protocols=Array.isArray(data2.protocols)?data2.protocols:[];void __upgradeOverLoopback(port2,"GET",url2.pathname+url2.search,{Host:typeof data2.host==="string"&&/^(?:\[[0-9a-f:.]+\]|[a-z0-9.-]+)(?::[0-9]{1,5})?$/iu.test(data2.host)?data2.host:url2.host,Upgrade:"websocket","Sec-WebSocket-Version":"13","Sec-WebSocket-Key":key,...protocols.length?{"Sec-WebSocket-Protocol":protocols.join(", ")}:{},...typeof data2.origin==="string"&&/^https?:\/\/[^/]+$/u.test(data2.origin)?{Origin:data2.origin}:{}}).then(result=>{if(result.statusCode!==101||!result.socket){channel.postMessage({type:"close",targetClient:data2.clientId,code:1006,reason:"upgrade refused"});return}const socket=raw?__substrateRawUpgradeSocket(record,result.socket):__substrateUpgradeSocket(record,result.socket);__substrateUpgradeSockets.set(data2.clientId,socket);channel.postMessage({type:"connected",targetClient:data2.clientId,protocol:result.headers["sec-websocket-protocol"]??(raw?protocols[0]??"":"")})})}else if(data2.type==="message"){const socket=__substrateUpgradeSockets.get(data2.clientId);if(socket)socket.deliver(data2.payload)}else if(data2.type==="disconnect"){const socket=__substrateUpgradeSockets.get(data2.clientId);if(socket)socket.disconnect(typeof data2.code==="number"?data2.code:1e3,typeof data2.reason==="string"?data2.reason:"")}});return channel}var ServerBridge=class extends PortBridge{constructor(options={}){super(options);__publicField2(this,"upgradeChannel",null);__publicField2(this,"guestServers",new WeakSet);this.watchGuestPorts();this.upgradeChannel=__substrateListenForUpgrades()}watchGuestPorts(){setPortWatchers((port2,address)=>{if(this.servers.has(port2))return;const hostname2=address||"0.0.0.0";const server=guestListeningServer(port2,hostname2);this.guestServers.add(server);this.registerServer(server,port2,hostname2)},port2=>{const entry=this.servers.get(port2);if(entry&&(entry.server===null||this.guestServers.has(entry.server))){if(entry.server)entry.server.listening=false;this.unregisterServer(port2)}})}close(){if(this.upgradeChannel){try{this.upgradeChannel.close()}catch{}this.upgradeChannel=null}super.close()}isGuest(entry){return entry.server===null||this.guestServers.has(entry.server)}requestGuest(port2,method,url2,headers,body){return __requestOverLoopback(port2,method,url2,headers,body)}streamGuest(port2,method,url2,headers,body,onStart,onChunk,onEnd,flow){return __streamOverLoopback(port2,method,url2,headers,body,onStart,onChunk,onEnd,flow)}bodyOf(bytes2){return Buffer$9.from(bytes2)}};var globalBridge=null;function getServerBridge(options){if(!globalBridge){globalBridge=new ServerBridge(options)}return globalBridge}function resetServerBridge(){globalBridge=null}var scopes=new WeakMap;var liveScopes=new Set;var NativeStreamScope=class{constructor(limits,emit2,ownerPid){__publicField2(this,"entries",new Map);__publicField2(this,"descriptors",new Map);__publicField2(this,"writes",new Map);__publicField2(this,"connects",new Map);__publicField2(this,"nextId",1);__publicField2(this,"pendingWriteBytes",0);__publicField2(this,"disposed",false);__publicField2(this,"limits");this.emit=emit2;this.ownerPid=ownerPid;if([limits.maxHandles,limits.maxReadChunkBytes,limits.maxQueuedBytes,limits.maxQueuedHandles,limits.maxPendingWriteBytes].some(value=>!Number.isSafeInteger(value)||value<1)||limits.maxReadChunkBytes>2147483647||limits.maxReadChunkBytes>limits.maxQueuedBytes||limits.maxReadChunkBytes>limits.maxPendingWriteBytes)throw new Error("Invalid native stream resource limits.");this.limits=Object.freeze({...limits});liveScopes.add(this)}handles(){var _a22;if(this.disposed)return[];const pid=(_a22=this.ownerPid)==null?void 0:_a22.call(this);return[...this.entries.values()].map(({handle,descriptor})=>({...pid!==void 0?{pid}:{},id:descriptor.id,kind:descriptor.kind,listening:!!handle.listening}))}entry(id2){return this.disposed?void 0:this.entries.get(id2)}publish(event){if(this.disposed)return;try{this.emit(event)}catch(cause){try{this.dispose()}catch(cleanup){throw new AggregateError([cause,cleanup],"Native stream event delivery and cleanup failed.")}throw cause}}claim(handle){if(this.disposed||!Number.isSafeInteger(this.nextId)||this.entries.size>=this.limits.maxHandles||scopes.has(handle))return void 0;const descriptor={id:this.nextId++,kind:handle instanceof TCP?"tcp":"pipe",type:handle.type};const entry={handle,descriptor};this.entries.set(descriptor.id,entry);scopes.set(handle,this);__adoptHandle(handle,null);handle.onconnection=(status,accepted)=>{const incoming2=status===0?this.claim(accepted):void 0;if(status===0&&!incoming2)accepted.close();this.publish({type:"connection",id:descriptor.id,status:status||(incoming2?0:UV_EMFILE),...incoming2?{handle:incoming2}:{}})};handle.onread=buffer2=>{const count=streamBaseState[kReadBytesOrError];const offset2=streamBaseState[kArrayBufferOffset];handle.readStop();const sent=handle.pendingHandle;handle.pendingHandle=null;let incoming2;if(sent!=null){if((sent instanceof TCP||sent instanceof Pipe)&&!sent.listening)incoming2=this.claim(sent);if(!incoming2){if(sent instanceof LibuvStreamWrap&&!scopes.has(sent)&&!sent.listening)sent.close();this.publish({type:"read",id:descriptor.id,status:UV_ENOTSUP});this.close(descriptor.id);return}}const bytes2=count>0?(buffer2?new Uint8Array(buffer2,offset2,count):entry.buffer.subarray(0,count)).slice():void 0;this.publish({type:"read",id:descriptor.id,status:count,...bytes2?{bytes:bytes2}:{},...incoming2?{handle:incoming2}:{}})};return{...descriptor}}call(operation){var _a22,_b22;if(this.disposed)return{status:UV_EBADF};if(operation.operation==="fdType"){if(!Number.isInteger(operation.fd)||operation.fd<0)return{status:UV_EINVAL};const id2=this.descriptors.get(operation.fd);const entry2=id2===void 0?void 0:this.entry(id2);return entry2?{status:0,handleType:entry2.descriptor.kind==="tcp"?"TCP":"PIPE"}:{status:UV_EBADF}}if(operation.operation==="create"){if(this.entries.size>=this.limits.maxHandles)return{status:UV_EMFILE};if(operation.kind!=="tcp"&&operation.kind!=="pipe"||!Number.isInteger(operation.type)||operation.type<0||operation.type>(operation.kind==="pipe"?2:1))return{status:UV_EINVAL};const handle2=operation.kind==="tcp"?new TCP(operation.type):new Pipe(operation.type);const descriptor=this.claim(handle2);if(!descriptor){handle2.close();return{status:UV_EMFILE}}return{status:0,handle:descriptor}}const entry=this.entry(operation.id);if(!entry)return{status:UV_EBADF};const handle=entry.handle;switch(operation.operation){case"duplicate":{if(handle.listening)return{status:UV_ENOTSUP};if(this.entries.size>=this.limits.maxHandles)return{status:UV_EMFILE};const copy2=handle.duplicate();const descriptor=this.claim(copy2);if(!descriptor){copy2.close();return{status:UV_EMFILE}}return{status:0,handle:descriptor}}case"pair":{const other=(_a22=this.entry(operation.peer))==null?void 0:_a22.handle;if(!other||handle.peer||other.peer||handle.listening||other.listening||other===handle)return{status:UV_EINVAL};LibuvStreamWrap.pair(handle,other);return{status:0}}case"bind":{if(typeof operation.address!=="string")return{status:UV_EINVAL};if(handle instanceof Pipe)return{status:handle.bind(operation.address)};if(!Number.isInteger(operation.port)||operation.port<0||operation.port>65535)return{status:UV_EINVAL};return{status:operation.ipv6?handle.bind6(operation.address,operation.port,operation.flags):handle.bind(operation.address,operation.port,operation.flags)}}case"listen":return{status:Number.isInteger(operation.backlog)&&operation.backlog>=0?handle.listen(operation.backlog):UV_EINVAL};case"connect":{if(this.connects.has(operation.id))return{status:UV_EALREADY};if(typeof operation.address!=="string"||!Number.isSafeInteger(operation.request)||operation.request<1)return{status:UV_EINVAL};if(handle instanceof TCP&&(!Number.isInteger(operation.port)||operation.port<1||operation.port>65535))return{status:UV_EINVAL};this.connects.set(operation.id,operation.request);const request=handle instanceof TCP?new TCPConnectWrap:new PipeConnectWrap;request.oncomplete=status2=>{if(this.connects.get(operation.id)!==operation.request)return;this.connects.delete(operation.id);this.publish({type:"connect",id:operation.id,request:operation.request,status:status2})};const status=handle instanceof TCP?operation.ipv6?handle.connect6(request,operation.address,operation.port):handle.connect(request,operation.address,operation.port):handle.connect(request,operation.address);if(status!==0)this.connects.delete(operation.id);return{status}}case"open":{const inherited=this.descriptors.get(operation.fd);const held=inherited===void 0?void 0:this.entry(inherited);if(!held||held.descriptor.kind!==entry.descriptor.kind||handle.peer||handle.listening)return{status:UV_EBADF};if(held!==entry){if(handle instanceof TCP&&held.handle instanceof TCP){const local2={},remote={};if(held.handle.getsockname(local2)===0&&held.handle.getpeername(remote)===0)handle.adoptNames(local2,remote)}handle.takeOverFrom(held.handle);this.entries.delete(inherited);scopes.delete(held.handle);held.handle.close();this.descriptors.set(operation.fd,operation.id)}return{status:0}}case"readStart":entry.buffer??(entry.buffer=new Uint8Array(this.limits.maxReadChunkBytes));handle.useUserBuffer(entry.buffer);return{status:handle.readStart()};case"readStop":return{status:handle.readStop()};case"ref":handle.ref();return{status:0};case"unref":handle.unref();return{status:0};case"getsockname":case"getpeername":{if(!(handle instanceof TCP))return{status:UV_ENOTSUP};const address={};const status=handle[operation.operation](address);return{status,...status===0?{address}:{}}}case"shutdown":{if(!Number.isSafeInteger(operation.request)||operation.request<1)return{status:UV_EINVAL};if(this.writes.has(operation.id))return{status:UV_EBUSY};const request=new ShutdownWrap;request.oncomplete=status=>this.publish({type:"shutdown",id:operation.id,request:operation.request,status});return{status:handle.shutdown(request)}}case"reset":if(!Number.isSafeInteger(operation.request)||operation.request<1)return{status:UV_EINVAL};if(!(handle instanceof TCP))return{status:UV_ENOTSUP};(_b22=this.writes.get(operation.id))==null?void 0:_b22(UV_ECANCELED);return this.close(operation.id,operation.request,true);case"close":if(!Number.isSafeInteger(operation.request)||operation.request<1)return{status:UV_EINVAL};return this.close(operation.id,operation.request)}}write(id2,bytes2,sentId){var _a22,_b22;const handle=(_a22=this.entry(id2))==null?void 0:_a22.handle;if(!handle)return Promise.resolve(UV_EBADF);if(this.writes.has(id2))return Promise.resolve(UV_EBUSY);if(bytes2.byteLength>this.limits.maxReadChunkBytes||this.pendingWriteBytes+bytes2.byteLength>this.limits.maxPendingWriteBytes)return Promise.resolve(UV_ENOBUFS);const sent=sentId===void 0?void 0:(_b22=this.entry(sentId))==null?void 0:_b22.handle;if(sentId!==void 0&&!sent)return Promise.resolve(UV_EBADF);if(sent&&(!(handle instanceof Pipe)||sent.listening||bytes2.byteLength===0))return Promise.resolve(UV_ENOTSUP);const owned=new Uint8Array(bytes2.byteLength);owned.set(bytes2);const retained=sent==null?void 0:sent.duplicate();if(retained)__adoptHandle(retained,null);this.pendingWriteBytes+=owned.byteLength;return new Promise((resolve2,reject)=>{let ended2=false;let unsubscribe=()=>{};const finish=(status,failure)=>{if(ended2)return;ended2=true;unsubscribe();this.writes.delete(id2);this.pendingWriteBytes-=owned.byteLength;try{retained==null?void 0:retained.close()}catch(cause){reject(cause);return}if(failure!==void 0)reject(failure);else resolve2(status)};const attempt=()=>{if(ended2)return;if(handle.closed||this.disposed){finish(UV_ECANCELED);return}if(!handle.peer){finish(UV_EPIPE);return}if(handle.peerQueuedBytes+owned.byteLength>this.limits.maxQueuedBytes)return;if(retained&&handle.peerQueuedHandles>=this.limits.maxQueuedHandles)return;try{finish(handle.writeBuffer(new WriteWrap,owned,retained))}catch(cause){finish(UV_ECANCELED,cause)}};this.writes.set(id2,finish);unsubscribe=handle.onPeerReadCapacity(attempt);attempt()})}inherit(fd2,source,id2){var _a22;if(this.disposed||!Number.isInteger(fd2)||fd2<0||this.descriptors.has(fd2))return{status:UV_EINVAL};if(this.entries.size>=this.limits.maxHandles)return{status:UV_EMFILE};const handle=(_a22=source.entry(id2))==null?void 0:_a22.handle;if(!handle)return{status:UV_EBADF};if(handle.listening)return{status:UV_ENOTSUP};const copy2=handle.duplicate();const descriptor=this.claim(copy2);if(!descriptor){copy2.close();return{status:UV_EMFILE}}this.descriptors.set(fd2,descriptor.id);return{status:0,handle:descriptor}}close(id2,request,reset2=false){var _a22;const entry=this.entries.get(id2);if(!entry)return{status:UV_EBADF};(_a22=this.writes.get(id2))==null?void 0:_a22(UV_ECANCELED);const connecting=this.connects.get(id2);this.connects.delete(id2);if(connecting!==void 0)this.publish({type:"connect",id:id2,request:connecting,status:UV_ECANCELED});this.entries.delete(id2);scopes.delete(entry.handle);for(const[fd2,held]of this.descriptors)if(held===id2)this.descriptors.delete(fd2);const complete=request===void 0?void 0:()=>this.publish({type:"close",id:id2,request,status:0});if(reset2)entry.handle.reset(complete);else entry.handle.close(complete);return{status:0}}dispose(){if(this.disposed)return;this.disposed=true;liveScopes.delete(this);const failures=[];for(const id2 of[...this.entries.keys()]){try{this.close(id2)}catch(cause){failures.push(cause)}}if(failures.length)throw new AggregateError(failures,"Native stream scope cleanup failed.")}};function nativeStreamOwnerPid(handle){var _a22,_b22;return(_b22=(_a22=scopes.get(handle))==null?void 0:_a22.ownerPid)==null?void 0:_b22.call(_a22)}function nativeStreamHandles(){return[...liveScopes].flatMap(scope4=>scope4.handles())}var __nextRunName=1;function createContainer(options){const vfs2=options&&options.vfs||new VirtualFS;const runtime=new Runtime(vfs2,options);const npmManager=new PackageManager(vfs2);const serverBridge=new ServerBridge({baseUrl:options==null?void 0:options.baseUrl,onServerReady:options==null?void 0:options.onServerReady});return{vfs:vfs2,runtime,npm:npmManager,serverBridge,execute:(code22,filename)=>runtime.execute(code22,filename),runFile:filename=>runtime.runFile(filename),run:(command,runOptions)=>{var _a22;if((_a22=runOptions==null?void 0:runOptions.signal)==null?void 0:_a22.aborted){return Promise.resolve({stdout:"",stderr:"",exitCode:130})}const processToken=typeof(runOptions==null?void 0:runOptions.processToken)==="string"&&runOptions.processToken.length>0?runOptions.processToken:`run-${__nextRunName++}`;registerRunStreams(processToken,{onStdout:runOptions==null?void 0:runOptions.onStdout,onStderr:runOptions==null?void 0:runOptions.onStderr,signal:runOptions==null?void 0:runOptions.signal,held:(runOptions==null?void 0:runOptions.held)===true,stdinStream:runOptions==null?void 0:runOptions.stdinStream,stdinOpen:(runOptions==null?void 0:runOptions.stdinStream)!==void 0,terminal:runOptions==null?void 0:runOptions.terminal});return new Promise(resolve2=>{runCommand(command,{cwd:runOptions==null?void 0:runOptions.cwd,env:runOptions==null?void 0:runOptions.env,stdin:typeof(runOptions==null?void 0:runOptions.stdin)==="string"?runOptions.stdin:void 0,processToken,vfs:vfs2},(error,stdout,stderr)=>{var _a32;releaseRunStreams(processToken);const terminatedBy=__takeTermination(processToken);resolve2({stdout:String(stdout),stderr:String(stderr),exitCode:((_a32=runOptions==null?void 0:runOptions.signal)==null?void 0:_a32.aborted)?143:error?error.code??1:0,...terminatedBy?{signal:terminatedBy}:{}})})})},pendingTimers:token=>{var _a22;return((_a22=__runFor(token))==null?void 0:_a22.pendingTimers())??0},processPorts:token=>__ownedServerPorts(token),portPid:port2=>{var _a22;const listener=listenerOnPort(port2);if(!listener)return void 0;return((_a22=runPid(ownerOf(listener)))==null?void 0:_a22.pid)??nativeStreamOwnerPid(listener)},streamHandles:()=>nativeStreamHandles(),signalProcess:(token,signal)=>__signalOwnedProcess(token,signal),stopProcess:token=>{const known=__runFor(token)!==void 0||__ownedServerPorts(token).length>0;__releaseOwnedServers(token,false);__releaseOwnedHandles(token);__stopOwnedProcess(token);return known},sendInput:(data2,token)=>sendStdin(data2,token),currentProcessToken:()=>__currentProcessToken(),runPid:token=>runPid(token===void 0?__currentProcessToken():token),processByPid,listenNet:(port2,onConnection)=>{const server=new Server(onConnection);server.listen(port2);__adoptHandle(server._handle,null);return()=>{server.close()}},createREPL:()=>runtime.createREPL(),on:(event,listener)=>{serverBridge.on(event,listener)}}}if(!Object.getOwnPropertyDescriptor(globalThis,"Buffer")){Object.defineProperty(globalThis,"Buffer",{configurable:true,enumerable:false,get:()=>bufferModule.Buffer})}function normalizeProcessFilesystemPolicy(value){if(!value||typeof value!=="object"||Object.keys(value).some(key=>key!=="writableRoots")||!Array.isArray(value.writableRoots)||value.writableRoots.length>128){throw new TypeError("Invalid process filesystem policy: expected up to 128 writableRoots.")}const roots=[...new Set(Array.from(value.writableRoots,absolutePolicyPath))].sort();return Object.freeze({writableRoots:Object.freeze(roots.filter(root2=>!roots.some(other=>other!==root2&&within(root2,other))))})}function intersectProcessFilesystemPolicies(parent,child){const inherited=normalizeProcessFilesystemPolicy(parent);if(child===void 0)return inherited;const requested=normalizeProcessFilesystemPolicy(child);return normalizeProcessFilesystemPolicy({writableRoots:inherited.writableRoots.flatMap(left=>requested.writableRoots.flatMap(right=>within(left,right)?[left]:within(right,left)?[right]:[]))})}function createProcessFilesystemMutationGuard(filesystem,requested){const policy=normalizeProcessFilesystemPolicy(requested);const permitted=path3=>policy.writableRoots.some(root2=>within(path3,root2));return input=>{const path3=absolutePolicyPath(input);if(!permitted(path3))deny(path3);let current3="";for(const part of path3.split("/").filter(Boolean)){current3+=`/${part}`;try{if(filesystem.lstatSync(current3).isSymbolicLink())deny(path3)}catch(error){if(error.code!=="ENOENT")throw error;if(!permitted(current3))deny(current3)}}return path3}}function absolutePolicyPath(path3){if(typeof path3!=="string"||!path3.startsWith("/")||path3.includes("\0")||path3.length>8192){throw new TypeError("Filesystem policy paths must be absolute paths without NUL bytes.")}const parts=[];for(const part of path3.split("/")){if(part==="..")parts.pop();else if(part&&part!==".")parts.push(part)}return`/${parts.join("/")}`}function within(path3,root2){return root2==="/"||path3===root2||path3.startsWith(`${root2}/`)}function deny(path3){throw Object.assign(new Error(`EACCES: process filesystem policy denies mutation of '${path3}'`),{code:"EACCES",path:path3})}async function forwardBrowserProcessInput(input,receive2,signal){signal.throwIfAborted();const iterator=input[Symbol.asyncIterator]();let finished=false;let rejectCancellation;const cancellation=new Promise((_resolve,reject)=>{rejectCancellation=reject});void cancellation.catch(()=>void 0);const abort=()=>rejectCancellation(signal.reason??new DOMException("Process input was cancelled.","AbortError"));signal.addEventListener("abort",abort,{once:true});try{for(;;){signal.throwIfAborted();const next2=await Promise.race([iterator.next(),cancellation]);signal.throwIfAborted();if(next2.done){finished=true;return}await Promise.race([Promise.resolve(receive2(next2.value)),cancellation])}}finally{signal.removeEventListener("abort",abort);if(!finished)void Promise.resolve().then(()=>iterator.return?.()).catch(()=>void 0)}}var BrowserProcessInputPipe=class{queued;ended=false;reading=false;failure;wake;write(bytes2){if(this.ended)return Promise.reject(this.failure??new Error("Process input is closed."));if(this.queued)return Promise.reject(new Error("Wait for the previous process input chunk to be consumed."));const consumed=new Promise((resolve2,reject)=>{this.queued={bytes:Uint8Array.from(bytes2),resolve:resolve2,reject}});this.notify();return consumed}end(){this.ended=true;this.notify()}cancel(cause=new DOMException("Process input was cancelled.","AbortError")){this.failure=cause;this.ended=true;this.queued?.reject(cause);this.queued=void 0;this.notify()}notify(){const wake=this.wake;this.wake=void 0;wake?.()}async*[Symbol.asyncIterator](){if(this.reading)throw new Error("Process input already has a reader.");this.reading=true;try{for(;;){if(this.failure!==void 0)throw this.failure;const next2=this.queued;if(next2){this.queued=void 0;next2.resolve();yield next2.bytes}else if(this.ended)return;else await new Promise(resolve2=>{this.wake=resolve2})}}finally{this.cancel()}}};function parseCommandWords(command){const words=[];let word="";let quote2="";let escaped=false;for(const character of command.trim()){if(escaped){word+=character;escaped=false;continue}if(character==="\\"&&quote2!=="'"){escaped=true;continue}if(quote2){if(character===quote2)quote2="";else word+=character;continue}if(character==="'"||character==='"'){quote2=character;continue}if(/\s/u.test(character)){if(word){words.push(word);word=""}continue}if(/[|&;<>]/u.test(character))throw new Error("Shell operators require the shell runtime.");word+=character}if(escaped||quote2)throw new Error("Unterminated command quoting.");if(word)words.push(word);return words}function renderCommand(argv){return argv.map(value=>/^[A-Za-z0-9_./:@%+=,-]+$/u.test(value)?value:`'${value.replaceAll("'",`'\\''`)}'`).join(" ")}var PageNetSocketImpl=class{constructor(id2,post,onClosed){this.id=id2;this.post=post;this.onClosed=onClosed}id;post;onClosed;listeners=new Map;ended=false;outstanding=0;drainWaiters=[];on(event,listener){const list2=this.listeners.get(event)??[];list2.push(listener);this.listeners.set(event,list2);return this}write(chunk,done){if(this.ended)return false;const buffer2=Uint8Array.from(chunk).buffer;this.outstanding+=1;this.post({type:"net-data",socket:this.id,chunk:buffer2},[buffer2]);done?.();return true}taken(){this.outstanding=Math.max(0,this.outstanding-1);for(const waiter of[...this.drainWaiters]){if(this.outstanding>=waiter.below)continue;this.drainWaiters.splice(this.drainWaiters.indexOf(waiter),1);waiter.resume()}}drained(below){if(this.ended||this.outstanding<below)return Promise.resolve();return new Promise(resume=>this.drainWaiters.push({below,resume}))}end(){if(!this.ended){this.post({type:"net-end",socket:this.id});this.finish()}return this}destroy(){return this.end()}receive(chunk){if(this.ended)return;for(const listener of this.listeners.get("data")??[])listener(chunk)}finish(){if(this.ended)return;this.ended=true;this.onClosed();for(const waiter of this.drainWaiters.splice(0))waiter.resume();const listeners=[...this.listeners.get("end")??[],...this.listeners.get("close")??[]];this.listeners.clear();for(const listener of listeners)listener(void 0)}};var STATE=0;var STATUS=1;var PID=2;var PPID=3;var IDLE=0;var REQUEST=1;var WRITING=2;var DONE3=3;var CLOSED=4;var TIMEOUT_MS=3e4;var STREAM_REPLY_BYTES=4096;function serveNodeProcessRegistry(limits,ownerPid){if(limits)limits=Object.freeze({...limits});const streams2=limits?new NativeStreamScope(limits,event=>{const transfer2=event.type==="read"&&event.bytes?[event.bytes.buffer]:[];port1.postMessage({operation:"stream-event",event},transfer2)},ownerPid):void 0;const registry=createProcessRegistryScope();const{port1,port2}=new MessageChannel;const shared=new SharedArrayBuffer(4*Int32Array.BYTES_PER_ELEMENT);const control=new Int32Array(shared);const reply=limits?new SharedArrayBuffer(STREAM_REPLY_BYTES):void 0;const encoder7=new TextEncoder;let disposed=false;const dispose=()=>{if(disposed)return;disposed=true;Atomics.store(control,STATE,CLOSED);Atomics.notify(control,STATE);try{port1.postMessage({operation:"closed"})}finally{try{streams2?.dispose()}finally{registry.dispose();port1.onmessage=null;port1.onmessageerror=null;port1.close();port2.close()}}};port1.onmessage=({data:data2})=>{if(disposed)return;if(!data2||typeof data2!=="object"){dispose();return}if(data2.operation==="close"){dispose();return}if(data2.operation==="stream-write"){if(!streams2||!limits||!Number.isSafeInteger(data2.request)||data2.request<1||!Number.isSafeInteger(data2.id)||data2.id<1||data2.handle!==void 0&&(!Number.isSafeInteger(data2.handle)||data2.handle<1)||!(data2.bytes instanceof Uint8Array)||data2.bytes.byteLength>limits.maxReadChunkBytes){dispose();return}try{void streams2.write(data2.id,data2.bytes,data2.handle).then(status2=>{if(!disposed)port1.postMessage({operation:"stream-written",request:data2.request,status:status2})}).catch(()=>dispose())}catch{dispose()}return}if(data2.operation==="stream-post"){const call=data2.call;const closing=call?.operation==="close"||call?.operation==="reset"||call?.operation==="shutdown";if(!streams2||call?.operation!=="readStart"&&!closing||!Number.isSafeInteger(call.id)||call.id<1||closing&&(!Number.isSafeInteger(call.request)||call.request<1)){dispose();return}try{const{status:status2}=streams2.call(call);if(status2!==0){port1.postMessage({operation:"stream-event",event:closing?{type:call.operation==="shutdown"?"shutdown":"close",id:call.id,request:call.request,status:status2}:{type:"read",id:call.id,status:status2}})}}catch{dispose()}return}if(Atomics.compareExchange(control,STATE,REQUEST,WRITING)!==REQUEST)return;let identity;let replyLength=0;let status=0;try{switch(data2.operation){case"allocate":identity={pid:registry.allocate(),ppid:0};break;case"publish":if(typeof data2.token!=="string")throw new Error("Invalid process token.");registry.publish(data2.token,{pid:data2.pid,ppid:data2.ppid,...data2.argv!==void 0?{argv:data2.argv}:{},...data2.cwd!==void 0?{cwd:data2.cwd}:{},...data2.startedAt!==void 0?{startedAt:data2.startedAt}:{}});break;case"forget":if(typeof data2.token!=="string")throw new Error("Invalid process token.");registry.forget(data2.token);break;case"lookup":identity=registry.lookup(data2.pid);break;case"signal":if(!Number.isSafeInteger(data2.pid)||typeof data2.signal!=="string"||!/^SIG[A-Z0-9]{1,12}$/u.test(data2.signal)){throw new Error("Invalid process signal.")}identity=registry.signal(data2.pid,data2.signal)?{pid:data2.pid,ppid:0}:void 0;break;case"stream-call":{if(!streams2||!reply)throw new Error("Native stream transport was not granted.");const result=streams2.call(data2.call);const bytes2=encoder7.encode(JSON.stringify(result));if(bytes2.byteLength>reply.byteLength)throw new Error("Native stream reply exceeds its bound.");new Uint8Array(reply).set(bytes2);replyLength=bytes2.byteLength;break}default:throw new Error("Unknown process registry operation.")}}catch{if(data2.operation==="stream-call"){dispose();return}status=1}Atomics.store(control,STATUS,status);Atomics.store(control,PID,data2.operation==="stream-call"?replyLength:identity?.pid??0);Atomics.store(control,PPID,identity?.ppid??0);if(Atomics.compareExchange(control,STATE,WRITING,DONE3)===WRITING)Atomics.notify(control,STATE);else dispose()};port1.onmessageerror=dispose;port1.start();return{registry,channel:{port:port2,control:shared,...reply&&limits?{streams:{reply,limits}}:{}},...streams2?{streams:streams2}:{},dispose}}function exchange(channel,request,read){const control=new Int32Array(channel.control);if(Atomics.compareExchange(control,STATE,IDLE,REQUEST)!==IDLE)throw new Error("Process owner channel is unavailable.");let result;let status;try{channel.port.postMessage(request);const deadline=performance.now()+TIMEOUT_MS;for(;;){const state=Atomics.load(control,STATE);if(state===DONE3)break;if(state===CLOSED)throw new Error("Process owner stopped.");const remaining=deadline-performance.now();if(remaining<=0)throw new Error("Process owner did not answer within 30 seconds.");Atomics.wait(control,STATE,state,remaining)}status=Atomics.load(control,STATUS);result=read(control);if(Atomics.compareExchange(control,STATE,DONE3,IDLE)!==DONE3)throw new Error("Process owner stopped.")}catch(cause){Atomics.store(control,STATE,CLOSED);try{channel.port.postMessage({operation:"close"})}finally{channel.port.close()}throw cause}if(status!==0)throw new Error("Process owner refused an invalid or unowned identity.");return result}var NodeProcessRegistryClient=class{constructor(channel){this.channel=channel;if(channel.streams)this.streams=this.native=new NodeNativeStreamClient(channel)}channel;streams;native;allocate(){return this.call({operation:"allocate"}).pid}publish(token,identity){this.call({operation:"publish",token,...identity})}forget(token){this.call({operation:"forget",token})}lookup(pid){return this.call({operation:"lookup",pid})}signal(pid,signal){return this.call({operation:"signal",pid,signal})!==void 0}call(request){try{return exchange(this.channel,request,control=>{const pid=Atomics.load(control,PID);return pid===0?void 0:{pid,ppid:Atomics.load(control,PPID)}})}catch(cause){if(Atomics.load(new Int32Array(this.channel.control),STATE)===CLOSED)this.native?.dispose();throw cause}}};var NodeNativeStreamClient=class{constructor(channel){this.channel=channel;if(!channel.streams)throw new Error("Native stream transport was not granted.");this.metadata=channel.streams;this.limits=Object.freeze({...channel.streams.limits});channel.port.addEventListener("message",this.receive);channel.port.addEventListener("messageerror",this.failed);channel.port.start()}channel;limits;listeners=new Set;pending=new Map;writing=new Set;queued=[];pendingBytes=0;nextRequest=1;stopped=false;metadata;call(operation){try{return exchange(this.channel,{operation:"stream-call",call:operation},control=>{const length=Atomics.load(control,PID);if(length<1||length>this.metadata.reply.byteLength)throw new Error("Invalid native stream reply length.");const bytes2=new Uint8Array(this.metadata.reply,0,length).slice();return JSON.parse(new TextDecoder().decode(bytes2))})}catch(cause){this.dispose();throw cause}}post(operation){if(this.stopped||Atomics.load(new Int32Array(this.channel.control),STATE)===CLOSED){this.dispose();throw new Error("Native stream owner stopped.")}this.channel.port.postMessage({operation:"stream-post",call:operation})}write(id2,bytes2,handle){if(this.stopped||Atomics.load(new Int32Array(this.channel.control),STATE)===CLOSED){this.dispose();return Promise.reject(new Error("Native stream owner stopped."))}if(this.writing.has(id2)||this.pending.size>=this.limits.maxHandles||bytes2.byteLength>this.limits.maxReadChunkBytes||!Number.isSafeInteger(this.nextRequest))return Promise.reject(new Error("Native stream write exceeds its transport limits."));const request=this.nextRequest++;return new Promise((resolve2,reject)=>{this.pending.set(request,{id:id2,bytes:bytes2.byteLength,resolve:resolve2,reject});this.writing.add(id2);this.queued.push({request,id:id2,bytes:bytes2,...handle===void 0?{}:{handle}});this.flushWrites()})}flushWrites(){while(!this.stopped&&this.queued.length){const next2=this.queued[0];if(this.pendingBytes+next2.bytes.byteLength>this.limits.maxPendingWriteBytes)return;this.queued.shift();const owned=new Uint8Array(next2.bytes.byteLength);owned.set(next2.bytes);this.pendingBytes+=owned.byteLength;try{this.channel.port.postMessage({operation:"stream-write",request:next2.request,id:next2.id,bytes:owned,...next2.handle===void 0?{}:{handle:next2.handle}},[owned.buffer])}catch{this.dispose()}}}onEvent(listener){if(this.stopped)throw new Error("Native stream owner stopped.");this.listeners.add(listener);return()=>{this.listeners.delete(listener)}}receive=({data:data2})=>{if(data2.operation==="closed"){this.dispose();return}if(data2.operation==="stream-event"){for(const listener of[...this.listeners])listener(data2.event)}else if(data2.operation==="stream-written"){const write=this.pending.get(data2.request);if(!write){this.dispose();return}this.pending.delete(data2.request);this.writing.delete(write.id);this.pendingBytes-=write.bytes;this.flushWrites();write.resolve(data2.status)}};failed=()=>{this.dispose()};dispose(){if(this.stopped)return;this.stopped=true;Atomics.store(new Int32Array(this.channel.control),STATE,CLOSED);try{this.channel.port.postMessage({operation:"close"})}finally{this.channel.port.removeEventListener("message",this.receive);this.channel.port.removeEventListener("messageerror",this.failed);this.channel.port.close();const cause=new Error("Native stream owner stopped.");for(const write of this.pending.values())write.reject(cause);this.pending.clear();this.queued.length=0;this.writing.clear();this.pendingBytes=0;const listeners=[...this.listeners];this.listeners.clear();const failures=[];for(const listener of listeners){try{listener({type:"closed"})}catch(error){failures.push(error)}}if(failures.length)throw new AggregateError(failures,"Native stream close delivery failed.")}}};var maximumChunk=64*1024;function validDescriptorNumber(fd2){return typeof fd2==="number"&&Number.isInteger(fd2)&&fd2>=3&&fd2<=63}var CrossOriginChildProcesses=class{constructor(run,send2){this.run=run;this.send=send2}run;send;children=new Map;disposed=false;receive(message){if(!["child-run","child-abort","child-stdin","child-stdin-end","child-resize","child-fd","child-fd-end"].includes(message.type))return false;if(this.disposed)return true;if(message.type==="child-run"){if(!Number.isSafeInteger(message.id)||message.id<1||this.children.has(message.id)){throw new Error("Invalid or duplicate child process identity.")}if(message.descriptors!==void 0&&(!Array.isArray(message.descriptors)||!message.descriptors.every(validDescriptorNumber)||new Set(message.descriptors).size!==message.descriptors.length)){throw new Error("Child process descriptors must be distinct integers from 3 through 63.")}void this.start(message).catch(cause=>console.error("Child process transport failed.",cause));return true}if(!("id"in message)||typeof message.id!=="number")return true;const child=this.children.get(message.id);if(!child)return true;if(message.type==="child-abort"){child.controller.abort();child.input?.cancel();for(const input of child.descriptors.values())input.cancel()}else if(message.type==="child-fd"||message.type==="child-fd-end"){const input=validDescriptorNumber(message.fd)?child.descriptors.get(message.fd):void 0;if(!input){child.controller.abort(new Error("Child process has no such descriptor."));return true}if(message.type==="child-fd-end"){input.end();return true}if(!(message.bytes instanceof ArrayBuffer)||message.bytes.byteLength>maximumChunk){const cause=new Error("Child process descriptor chunks must be at most 64 KiB.");child.controller.abort(cause);input.cancel(cause);return true}const fd2=message.fd;void input.write(new Uint8Array(message.bytes)).then(()=>{if(!this.disposed&&this.children.get(message.id)===child)this.send({type:"child-fd-consumed",id:message.id,fd:fd2})}).catch(cause=>{child.controller.abort(cause)})}else if(message.type==="child-stdin"){if(!child.input){child.controller.abort(new Error("Child process has no live input."));return true}if(message.bytes.byteLength>64*1024){const cause=new Error("Child process input chunks must be at most 64 KiB.");child.controller.abort(cause);child.input.cancel(cause);return true}void child.input.write(new Uint8Array(message.bytes)).then(()=>{if(!this.disposed&&this.children.get(message.id)===child)this.send({type:"child-input-consumed",id:message.id})}).catch(cause=>{if(!this.disposed&&this.children.get(message.id)===child)child.controller.abort(cause)})}else if(message.type==="child-stdin-end")child.input?.end();else if(message.type==="child-resize"&&child.terminal){child.terminal.columns=message.columns;child.terminal.rows=message.rows;for(const resize of[...child.resizes]){try{resize(message.columns,message.rows)}catch(cause){child.controller.abort(cause)}}}return true}detach(){this.close(false)}dispose(){this.close(true)}close(abort){if(this.disposed)return;this.disposed=true;for(const child of this.children.values()){if(abort){child.controller.abort();child.input?.cancel();for(const input of child.descriptors.values())input.cancel()}else{child.input?.end();for(const input of child.descriptors.values())input.end()}child.resizes.clear()}this.children.clear()}async start(message){const child={controller:new AbortController,resizes:new Set,descriptors:new Map((message.descriptors??[]).map(fd2=>[fd2,new BrowserProcessInputPipe])),...message.liveStdin?{input:new BrowserProcessInputPipe}:{}};if(message.terminal)child.terminal={...message.terminal,onResize:listener=>{child.resizes.add(listener);return()=>{child.resizes.delete(listener)}}};this.children.set(message.id,child);const descriptors={};for(const[fd2,input]of child.descriptors)descriptors[fd2]=this.descriptor(message.id,fd2,input,child);try{const result=await this.run(message,{...message.cwd!==void 0?{cwd:message.cwd}:{},...message.env!==void 0?{env:message.env}:{},...message.executablePath!==void 0?{executablePath:message.executablePath}:{},...message.filesystemPolicy!==void 0?{filesystemPolicy:message.filesystemPolicy}:{},...message.stdin!==void 0?{stdin:message.stdin}:{},...child.input?{stdinStream:child.input}:{},...child.terminal?{terminal:child.terminal}:{},...child.descriptors.size>0?{descriptors}:{},signal:child.controller.signal,onStdout:chunk=>{if(!this.disposed)this.send({type:"child-output",id:message.id,stream:"stdout",chunk})},onStderr:chunk=>{if(!this.disposed)this.send({type:"child-output",id:message.id,stream:"stderr",chunk})}});if(!this.disposed)this.send({type:"child-result",id:message.id,stdout:result.stdout,stderr:result.stderr,exitCode:result.exitCode,...result.signal?{signal:result.signal}:{}})}catch(cause){if(!this.disposed){try{this.send({type:"child-error",id:message.id,error:cause instanceof Error?cause.message:String(cause)})}catch(failure){console.error("Child process result transport failed.",failure)}}}finally{child.input?.cancel();for(const input of child.descriptors.values())input.cancel();child.resizes.clear();this.children.delete(message.id)}}descriptor(id2,fd2,input,child){let closed=false;const live2=()=>!closed&&!this.disposed&&this.children.get(id2)===child;return{input,write:bytes2=>{for(let offset2=0;offset2<bytes2.byteLength&&live2();offset2+=maximumChunk){const chunk=Uint8Array.from(bytes2.subarray(offset2,offset2+maximumChunk)).buffer;this.send({type:"child-fd-output",id:id2,fd:fd2,bytes:chunk},[chunk])}},end:()=>{if(!live2())return;closed=true;this.send({type:"child-fd-close",id:id2,fd:fd2})}}}};var STAT_FIELDS=["mode","mtimeMs","atimeMs","ctimeMs","birthtimeMs","nlink","uid","gid","dev","ino","rdev","blksize","blocks"];var STATE2=0;var OPERATION=1;var STATUS2=2;var INPUT_LENGTH=3;var OUTPUT_LENGTH=4;var TOTAL_LENGTH=5;var CONTROL_WORDS=8;var DEFAULT_PAYLOAD_BYTES=4*1024*1024;var REQUEST_TIMEOUT_MS=3e4;var encoder2=new TextEncoder;var decoder3=new TextDecoder;function createBrowserFilesystemChannel(payloadBytes=DEFAULT_PAYLOAD_BYTES){const{port1,port2}=new MessageChannel;const control=new SharedArrayBuffer(CONTROL_WORDS*Int32Array.BYTES_PER_ELEMENT);const payload=new SharedArrayBuffer(payloadBytes);return{holder:{port:port1,control,payload},reader:{port:port2,control,payload}}}function serveBrowserFilesystemChannel(filesystem,channel){const control=new Int32Array(channel.control);const payload=new Uint8Array(channel.payload);let staged=null;channel.port.onmessage=event=>{const requestId2=event.data;if(Atomics.load(control,STATE2)!==requestId2)return;let status=0;let output=new Uint8Array;let total=0;try{const operation=Atomics.load(control,OPERATION);const inputLength=Atomics.load(control,INPUT_LENGTH);const input=JSON.parse(decoder3.decode(payload.slice(0,inputLength)));if(operation===1){output=encoder2.encode(JSON.stringify(filesystem.existsSync(input.path)))}else if(operation===2||operation===13){if(operation===13&&!filesystem.lstatSync){throw Object.assign(new Error("The filesystem holder does not support lstat."),{code:"ENOTSUP"})}const stat2=input.throwIfNoEntry===false?operation===13?filesystem.lstatSync(input.path,{throwIfNoEntry:false}):filesystem.statSync(input.path,{throwIfNoEntry:false}):operation===13?filesystem.lstatSync(input.path):filesystem.statSync(input.path);if(stat2===void 0)output=encoder2.encode("null");else{const metadata=Object.fromEntries(STAT_FIELDS.filter(key=>stat2[key]!==void 0).map(key=>[key,stat2[key]]));output=encoder2.encode(JSON.stringify({...metadata,file:stat2.isFile(),directory:stat2.isDirectory(),symlink:stat2.isSymbolicLink?.()??false,size:stat2.size,mode:stat2.mode??420,mtimeMs:stat2.mtimeMs??0}))}}else if(operation===14&&filesystem.readlinkSync){output=encoder2.encode(JSON.stringify(filesystem.readlinkSync(input.path)))}else if(operation===15&&filesystem.symlinkSync&&typeof input.target==="string"){filesystem.symlinkSync(input.target,input.path)}else if(operation===4){output=encoder2.encode(JSON.stringify(filesystem.readdirSync(input.path)))}else if(operation===3){const bytes2=filesystem.readFileSync(input.path);total=bytes2.byteLength;const offset2=input.offset??0;output=bytes2.subarray(offset2,Math.min(total,offset2+payload.byteLength))}else if(operation===5){output=encoder2.encode(JSON.stringify(filesystem.realpathSync?.(input.path)??input.path))}else if(operation===6&&filesystem.writeFileSync){if(!Number.isSafeInteger(input.bytes)||input.bytes<0||inputLength+input.bytes>payload.byteLength)throw new Error("Invalid filesystem write length.");const piece=payload.slice(inputLength,inputLength+input.bytes);if(input.total===void 0){filesystem.writeFileSync(input.path,piece)}else{const offset2=input.offset??0;if(!Number.isSafeInteger(input.total)||input.total<0||offset2+piece.byteLength>input.total)throw new Error("Invalid filesystem write piece.");if(offset2===0)staged={path:input.path,bytes:new Uint8Array(input.total),received:0};if(!staged||staged.path!==input.path||staged.bytes.byteLength!==input.total||staged.received!==offset2){staged=null;throw new Error(`The filesystem channel received a write piece of ${input.path} out of order.`)}staged.bytes.set(piece,offset2);staged.received+=piece.byteLength;if(staged.received===input.total){const whole=staged.bytes;staged=null;filesystem.writeFileSync(input.path,whole)}}}else if(operation===16&&(filesystem.appendFileSync||filesystem.writeFileSync)){if(!Number.isSafeInteger(input.bytes)||input.bytes<0||inputLength+input.bytes>payload.byteLength)throw new Error("Invalid filesystem append length.");const piece=payload.slice(inputLength,inputLength+input.bytes);if(filesystem.appendFileSync)filesystem.appendFileSync(input.path,piece);else{const existing=filesystem.existsSync(input.path)?filesystem.readFileSync(input.path):new Uint8Array(0);const whole=new Uint8Array(existing.byteLength+piece.byteLength);whole.set(existing,0);whole.set(piece,existing.byteLength);filesystem.writeFileSync(input.path,whole)}}else if(operation===17&&(filesystem.writeAtSync||filesystem.writeFileSync)){if(!Number.isSafeInteger(input.bytes)||input.bytes<0||inputLength+input.bytes>payload.byteLength)throw new Error("Invalid filesystem write length.");if(!Number.isSafeInteger(input.position)||input.position<0)throw new Error("Invalid filesystem write position.");const piece=payload.slice(inputLength,inputLength+input.bytes);if(filesystem.writeAtSync)filesystem.writeAtSync(input.path,piece,input.position);else if(piece.byteLength===0&&filesystem.existsSync(input.path)){}else{const existing=filesystem.existsSync(input.path)?filesystem.readFileSync(input.path):new Uint8Array(0);const whole=new Uint8Array(Math.max(existing.byteLength,input.position+piece.byteLength));whole.set(existing,0);whole.set(piece,input.position);filesystem.writeFileSync(input.path,whole)}}else if(operation===7&&filesystem.mkdirSync){filesystem.mkdirSync(input.path,{recursive:input.recursive===true})}else if(operation===8&&filesystem.unlinkSync){filesystem.unlinkSync(input.path)}else if(operation===9&&filesystem.rmdirSync){filesystem.rmdirSync(input.path)}else if(operation===10&&filesystem.renameSync&&typeof input.to==="string"){filesystem.renameSync(input.path,input.to)}else if(operation===11&&filesystem.chmodSync&&Number.isInteger(input.mode)){filesystem.chmodSync(input.path,input.mode)}else if(operation===12&&filesystem.utimesSync&&Number.isFinite(input.atime)&&Number.isFinite(input.mtime)){filesystem.utimesSync(input.path,input.atimeDate?new Date(input.atime):input.atime,input.mtimeDate?new Date(input.mtime):input.mtime)}else{throw new Error(`Unsupported filesystem channel operation ${operation}.`)}if(output.byteLength>payload.byteLength)throw new Error("The filesystem channel answer exceeds its buffer.")}catch(cause){const error=cause;const message=cause instanceof Error?cause.message:String(cause);status=2;output=encoder2.encode(JSON.stringify({message,...typeof error?.code==="string"?{code:error.code}:{},...typeof error?.path==="string"?{path:error.path}:{}}));if(output.byteLength>payload.byteLength){status=1;output=encoder2.encode(message).subarray(0,payload.byteLength)}}if(Atomics.compareExchange(control,STATE2,requestId2,-requestId2)!==requestId2)return;payload.set(output);Atomics.store(control,STATUS2,status);Atomics.store(control,OUTPUT_LENGTH,output.byteLength);Atomics.store(control,TOTAL_LENGTH,total);Atomics.store(control,STATE2,requestId2+1);Atomics.notify(control,STATE2)};channel.port.start();return()=>{channel.port.onmessage=null;channel.port.close()}}var BrowserFilesystemChannelClient=class{constructor(channel){this.channel=channel;this.control=new Int32Array(channel.control);this.payload=new Uint8Array(channel.payload)}channel;control;payload;nextRequestId=1;existsSync(path3){return JSON.parse(decoder3.decode(this.call(1,{path:path3}).output))}statSync(path3,options){return this.stat(path3,2,options?.throwIfNoEntry!==false)}lstatSync(path3,options){return this.stat(path3,13,options?.throwIfNoEntry!==false)}stat(path3,operation,throwIfNoEntry){let bytes2;try{bytes2=this.call(operation,{path:path3,...throwIfNoEntry?{}:{throwIfNoEntry:false}}).output}catch(cause){if(!throwIfNoEntry&&cause.code==="ENOENT")return void 0;throw cause}const stat2=JSON.parse(decoder3.decode(bytes2));if(stat2===null){if(!throwIfNoEntry)return void 0;throw new Error("The filesystem holder returned absence for a throwing stat.")}return{...Object.fromEntries(STAT_FIELDS.filter(key=>stat2[key]!==void 0).map(key=>[key,stat2[key]])),isFile:()=>stat2.file,isDirectory:()=>stat2.directory,isSymbolicLink:()=>stat2.symlink===true,size:stat2.size,mode:stat2.mode,mtimeMs:stat2.mtimeMs,mtime:new Date(stat2.mtimeMs)}}readlinkSync(path3){return JSON.parse(decoder3.decode(this.call(14,{path:path3}).output))}symlinkSync(target,path3){this.call(15,{path:path3,target})}readdirSync(path3){return JSON.parse(decoder3.decode(this.call(4,{path:path3}).output))}realpathSync(path3){return JSON.parse(decoder3.decode(this.call(5,{path:path3}).output))}writeFileSync(path3,value){const bytes2=typeof value==="string"?encoder2.encode(value):value;const room=this.payload.byteLength-encoder2.encode(JSON.stringify({path:path3,bytes:bytes2.byteLength,offset:bytes2.byteLength,total:bytes2.byteLength})).byteLength;if(bytes2.byteLength<=room){this.call(6,{path:path3,bytes:bytes2.byteLength},bytes2);return}for(let offset2=0;offset2<bytes2.byteLength;offset2+=room){const piece=bytes2.subarray(offset2,Math.min(bytes2.byteLength,offset2+room));this.call(6,{path:path3,bytes:piece.byteLength,offset:offset2,total:bytes2.byteLength},piece)}}appendFileSync(path3,value){const bytes2=typeof value==="string"?encoder2.encode(value):value;const room=this.payload.byteLength-encoder2.encode(JSON.stringify({path:path3,bytes:bytes2.byteLength})).byteLength;if(bytes2.byteLength===0){this.call(16,{path:path3,bytes:0},bytes2);return}for(let offset2=0;offset2<bytes2.byteLength;offset2+=room){const piece=bytes2.subarray(offset2,Math.min(bytes2.byteLength,offset2+room));this.call(16,{path:path3,bytes:piece.byteLength},piece)}}writeAtSync(path3,value,position){const room=this.payload.byteLength-encoder2.encode(JSON.stringify({path:path3,position:position+value.byteLength,bytes:value.byteLength})).byteLength;if(value.byteLength===0){this.call(17,{path:path3,position,bytes:0},value);return}for(let offset2=0;offset2<value.byteLength;offset2+=room){const piece=value.subarray(offset2,Math.min(value.byteLength,offset2+room));this.call(17,{path:path3,position:position+offset2,bytes:piece.byteLength},piece)}}mkdirSync(path3,options){this.call(7,{path:path3,recursive:options?.recursive===true})}unlinkSync(path3){this.call(8,{path:path3})}rmdirSync(path3){this.call(9,{path:path3})}renameSync(path3,to2){this.call(10,{path:path3,to:to2})}chmodSync(path3,mode){this.call(11,{path:path3,mode})}utimesSync(path3,atime,mtime){this.call(12,{path:path3,atime:typeof atime==="number"?atime:Number(atime),mtime:typeof mtime==="number"?mtime:Number(mtime),atimeDate:typeof atime!=="number",mtimeDate:typeof mtime!=="number"})}readFileSync(path3,encoding){const first=this.call(3,{path:path3});let bytes2;if(first.output.byteLength>=first.total){bytes2=first.output}else{bytes2=new Uint8Array(first.total);bytes2.set(first.output,0);for(let offset2=first.output.byteLength;offset2<first.total;){const piece=this.call(3,{path:path3,offset:offset2});if(piece.output.byteLength===0)throw new Error(`The filesystem channel returned a short read of ${path3}.`);bytes2.set(piece.output,offset2);offset2+=piece.output.byteLength}}return encoding?decoder3.decode(bytes2):bytes2}call(operation,input,bytes2){const encoded=encoder2.encode(JSON.stringify(input));if(encoded.byteLength+(bytes2?.byteLength??0)>this.payload.byteLength)throw new Error("The filesystem channel request exceeds its buffer.");if(Atomics.load(this.control,STATE2)!==0)throw new Error("The filesystem channel is answering another request.");const requestId2=this.nextRequestId;this.nextRequestId=requestId2>=1073741821?1:requestId2+2;this.payload.set(encoded);if(bytes2)this.payload.set(bytes2,encoded.byteLength);Atomics.store(this.control,OPERATION,operation);Atomics.store(this.control,INPUT_LENGTH,encoded.byteLength);Atomics.store(this.control,STATE2,requestId2);this.channel.port.postMessage(requestId2);const deadline=Date.now()+REQUEST_TIMEOUT_MS;for(;;){const state=Atomics.load(this.control,STATE2);if(state===requestId2+1)break;if(state!==requestId2&&state!==-requestId2)throw new Error(`The filesystem channel is in state ${state} for request ${requestId2}.`);const remaining=Math.max(0,deadline-Date.now());if(remaining===0&&state===requestId2&&Atomics.compareExchange(this.control,STATE2,requestId2,0)===requestId2){throw new Error(`The filesystem holder did not answer within ${REQUEST_TIMEOUT_MS} ms.`)}Atomics.wait(this.control,STATE2,state,state===-requestId2?void 0:remaining)}const status=Atomics.load(this.control,STATUS2);const length=Atomics.load(this.control,OUTPUT_LENGTH);const total=Atomics.load(this.control,TOTAL_LENGTH);const output=this.payload.slice(0,length);Atomics.store(this.control,STATE2,0);if(status===2){const error=JSON.parse(decoder3.decode(output));throw Object.assign(new Error(error.message),error)}if(status!==0)throw new Error(decoder3.decode(output));return{output,total}}};function createConfinedNodeFilesystem(filesystem,policy){const writable=createProcessFilesystemMutationGuard(filesystem,policy);const view=new VirtualFS;Object.defineProperty(view,Symbol.for("@volter/browser-node/assert-filesystem-mutation"),{value:writable});const descriptors={existsSync:path3=>filesystem.existsSync(path3),statSync:(path3,options)=>filesystem.statSync(path3,options),lstatSync:(path3,options)=>filesystem.lstatSync(path3,options),readdirSync:path3=>filesystem.readdirSync(path3),realpathSync:path3=>filesystem.realpathSync(path3),readlinkSync:path3=>filesystem.readlinkSync(path3),accessSync:(path3,mode)=>filesystem.accessSync((mode??0)&2?writable(path3):path3,mode),readFileSync:(path3,encoding)=>{const bytes2=new Uint8Array(filesystem.readFileSync(path3));return encoding?new TextDecoder().decode(bytes2):bytes2},writeFileSync:(path3,bytes2)=>filesystem.writeFileSync(writable(path3),typeof bytes2==="string"?bytes2:new Uint8Array(bytes2)),appendFileSync:(path3,bytes2)=>filesystem.appendFileSync(writable(path3),typeof bytes2==="string"?bytes2:new Uint8Array(bytes2)),writeAtSync:(path3,bytes2,position)=>filesystem.writeAtSync(writable(path3),new Uint8Array(bytes2),position),mkdirSync:(path3,options)=>{if(options?.recursive&&filesystem.existsSync(path3)&&filesystem.lstatSync(path3).isDirectory()&&!filesystem.lstatSync(path3).isSymbolicLink())return;filesystem.mkdirSync(writable(path3),options)},unlinkSync:path3=>filesystem.unlinkSync(writable(path3)),rmdirSync:path3=>filesystem.rmdirSync(writable(path3)),renameSync:(from,to2)=>{const source=writable(from);const destination=writable(to2);filesystem.renameSync(source,destination)},chmodSync:(path3,mode)=>{const target=writable(path3);const change=Reflect.get(filesystem,"chmodSync");if(!change)unsupported2("chmod");change.call(filesystem,target,mode)},utimesSync:(path3,atime,mtime)=>{const target=writable(path3);const change=Reflect.get(filesystem,"utimesSync");if(!change)unsupported2("utimes");change.call(filesystem,target,atime,mtime)},symlinkSync:()=>unsupported2("symlink"),linkSync:()=>unsupported2("link"),toSnapshot:()=>structuredClone(filesystem.toSnapshot()),watch:filesystem.watch.bind(filesystem),on:(event,listener)=>{filesystem.on(event,listener);return view},off:(event,listener)=>{filesystem.off(event,listener);return view}};for(const[name,value]of Object.entries(descriptors)){Object.defineProperty(view,name,{value,configurable:false,writable:false})}return view}function unsupported2(operation){throw Object.assign(new Error(`Node filesystem does not support ${operation}.`),{code:"ENOTSUP"})}var MAGIC=2019846480;var HEADER_WORDS=6;var RECORD_WORDS=6;var RECORD_NUMBERS=3;var PATH_OFFSET=0;var PATH_LENGTH=1;var FLAGS3=2;var MODE=3;var CHILD_START=4;var CHILD_COUNT=5;var MTIME=0;var OFFSET=1;var LENGTH3=2;var HAS_ENTRY=1;var HAS_CHILDREN=2;var PACKED=4;var ASCII2=32;var TYPE_SHIFT=3;var TYPES=["file","directory","symlink"];var LONE_SURROGATE=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;var encoder3=new TextEncoder;var decoder4=new TextDecoder;function hashPath(path3){let hash3=2166136261;for(let index2=0;index2<path3.length;index2+=1){hash3^=path3.charCodeAt(index2);hash3=Math.imul(hash3,16777619)}return hash3>>>0}function encodeSharedIndex(entries,children){const paths=[...entries.keys()];for(const path3 of paths)if(LONE_SURROGATE.test(path3))throw new Error("A path in the store is not well-formed UTF-16.");const at3=new Map;for(let index2=0;index2<paths.length;index2+=1)at3.set(paths[index2],index2);for(const parent of children.keys())if(!at3.has(parent)){at3.set(parent,paths.length);paths.push(parent)}const count=paths.length;const encoded=new Map;const byteLengths=new Uint32Array(count);let stringBytes=0;for(let index2=0;index2<count;index2+=1){const path3=paths[index2];let ascii=true;for(let unit=0;unit<path3.length;unit+=1)if(path3.charCodeAt(unit)>=128){ascii=false;break}if(!ascii)encoded.set(index2,encoder3.encode(path3));byteLengths[index2]=ascii?path3.length:encoded.get(index2).length;stringBytes+=byteLengths[index2]}let childTotal=0;for(const names2 of children.values())childTotal+=names2.size;let tableSize=1;while(tableSize<count*2)tableSize<<=1;const recordsAt=HEADER_WORDS*4;const numbersAt=align(recordsAt+count*RECORD_WORDS*4,8);const tableAt=numbersAt+count*RECORD_NUMBERS*8;const childListAt=tableAt+tableSize*4;const stringsAt=childListAt+childTotal*4;const buffer2=new SharedArrayBuffer(align(stringsAt+stringBytes,8));const header=new Uint32Array(buffer2,0,HEADER_WORDS);header.set([MAGIC,count,tableSize,childTotal,stringBytes,entries.size]);const records=new Uint32Array(buffer2,recordsAt,count*RECORD_WORDS);const numbers=new Float64Array(buffer2,numbersAt,count*RECORD_NUMBERS);const table=new Uint32Array(buffer2,tableAt,tableSize);const childList=new Uint32Array(buffer2,childListAt,childTotal);const strings2=new Uint8Array(buffer2,stringsAt,stringBytes);let stringCursor=0;let childCursor=0;for(let index2=0;index2<count;index2+=1){const path3=paths[index2];const word=index2*RECORD_WORDS;const other=encoded.get(index2);if(other)strings2.set(other,stringCursor);else for(let unit=0;unit<path3.length;unit+=1)strings2[stringCursor+unit]=path3.charCodeAt(unit);const length=byteLengths[index2];records[word+PATH_OFFSET]=stringCursor;records[word+PATH_LENGTH]=length;stringCursor+=length;let flags=other?0:ASCII2;const entry=entries.get(path3);if(entry){flags|=HAS_ENTRY|TYPES.indexOf(entry.type)<<TYPE_SHIFT;if(entry.pack)flags|=PACKED;records[word+MODE]=entry.mode;const number=index2*RECORD_NUMBERS;numbers[number+MTIME]=entry.mtimeMs;numbers[number+OFFSET]=entry.offset;numbers[number+LENGTH3]=entry.length}const names2=children.get(path3);if(names2){flags|=HAS_CHILDREN;records[word+CHILD_START]=childCursor;records[word+CHILD_COUNT]=names2.size;for(const name of names2){const child=at3.get(`${path3}/${name}`);if(child===void 0)throw new Error(`The store's children name ${path3}/${name}, which its index does not hold.`);childList[childCursor++]=child}}records[word+FLAGS3]=flags;let slot=hashPath(path3)&tableSize-1;while(table[slot]!==0)slot=slot+1&tableSize-1;table[slot]=index2+1}if(childCursor!==childTotal)throw new Error("The shared index's children did not add up.");return buffer2}function align(value,to2){return Math.ceil(value/to2)*to2}var SharedIndex=class{buffer;count;entryCount;records;numbers;table;childList;strings;mask;constructor(buffer2){const header=new Uint32Array(buffer2,0,HEADER_WORDS);if(header[0]!==MAGIC)throw new Error("Not a shared store index.");const[,count,tableSize,childTotal,stringBytes,entryCount]=header;this.buffer=buffer2;this.count=count;this.entryCount=entryCount;const recordsAt=HEADER_WORDS*4;const numbersAt=align(recordsAt+count*RECORD_WORDS*4,8);const tableAt=numbersAt+count*RECORD_NUMBERS*8;const childListAt=tableAt+tableSize*4;const stringsAt=childListAt+childTotal*4;this.records=new Uint32Array(buffer2,recordsAt,count*RECORD_WORDS);this.numbers=new Float64Array(buffer2,numbersAt,count*RECORD_NUMBERS);this.table=new Uint32Array(buffer2,tableAt,tableSize);this.childList=new Uint32Array(buffer2,childListAt,childTotal);this.strings=new Uint8Array(buffer2,stringsAt,stringBytes);this.mask=tableSize-1}find(path3){let slot=hashPath(path3)&this.mask;for(;;){const held=this.table[slot];if(held===0)return-1;if(this.pathIs(held-1,path3))return held-1;slot=slot+1&this.mask}}entry(record){const word=record*RECORD_WORDS;const flags=this.records[word+FLAGS3];if(!(flags&HAS_ENTRY))return void 0;const number=record*RECORD_NUMBERS;const entry={type:TYPES[flags>>>TYPE_SHIFT&3],mode:this.records[word+MODE],mtimeMs:this.numbers[number+MTIME],offset:this.numbers[number+OFFSET],length:this.numbers[number+LENGTH3]};if(flags&PACKED)entry.pack="packages";return entry}typeAt(record){const flags=this.records[record*RECORD_WORDS+FLAGS3];return flags&HAS_ENTRY?TYPES[flags>>>TYPE_SHIFT&3]:void 0}hasEntry(record){return(this.records[record*RECORD_WORDS+FLAGS3]&HAS_ENTRY)!==0}childNames(record){const word=record*RECORD_WORDS;if(!(this.records[word+FLAGS3]&HAS_CHILDREN))return void 0;const start=this.records[word+CHILD_START];const skip=this.records[word+PATH_LENGTH]+1;const names2=[];for(let index2=0;index2<this.records[word+CHILD_COUNT];index2+=1){const child=this.childList[start+index2]*RECORD_WORDS;names2.push(this.decode(this.records[child+PATH_OFFSET]+skip,this.records[child+PATH_LENGTH]-skip,(this.records[child+FLAGS3]&ASCII2)!==0))}return names2}path(record){const word=record*RECORD_WORDS;return this.decode(this.records[word+PATH_OFFSET],this.records[word+PATH_LENGTH],(this.records[word+FLAGS3]&ASCII2)!==0)}decode(start,length,ascii){if(!ascii)return decoder4.decode(this.strings.slice(start,start+length));let text="";for(let at3=start,end=start+length;at3<end;at3+=4096){text+=String.fromCharCode.apply(null,this.strings.subarray(at3,Math.min(end,at3+4096)))}return text}pathIs(record,path3){const word=record*RECORD_WORDS;const start=this.records[word+PATH_OFFSET];const length=this.records[word+PATH_LENGTH];if(!(this.records[word+FLAGS3]&ASCII2))return this.path(record)===path3;if(length!==path3.length)return false;for(let index2=0;index2<length;index2+=1)if(this.strings[start+index2]!==path3.charCodeAt(index2))return false;return true}};var DELETED=Symbol("deleted");function sameIndexEntry(left,right){return left===right||!!left&&!!right&&left.type===right.type&&left.offset===right.offset&&left.length===right.length&&left.pack===right.pack&&left.mode===right.mode&&left.mtimeMs===right.mtimeMs&&left.capacity===right.capacity}var OverlaidIndex=class{constructor(base){this.base=base}base;overlay=new Map;delta=0;get[Symbol.toStringTag](){return"Map"}get size(){return this.base.entryCount+this.delta}get(path3){const over=this.overlay.get(path3);if(over!==void 0)return over===DELETED?void 0:over;const record=this.base.find(path3);return record<0?void 0:this.base.entry(record)}typeOf(path3){const over=this.overlay.get(path3);if(over!==void 0)return over===DELETED?void 0:over.type;const record=this.base.find(path3);return record<0?void 0:this.base.typeAt(record)}has(path3){const over=this.overlay.get(path3);if(over!==void 0)return over!==DELETED;const record=this.base.find(path3);return record>=0&&this.base.hasEntry(record)}set(path3,entry){if(!this.has(path3))this.delta+=1;const record=this.base.find(path3);if(record>=0&&sameIndexEntry(this.base.entry(record),entry))this.overlay.delete(path3);else this.overlay.set(path3,entry);return this}delete(path3){if(!this.has(path3))return false;const record=this.base.find(path3);if(record>=0&&this.base.hasEntry(record))this.overlay.set(path3,DELETED);else this.overlay.delete(path3);this.delta-=1;return true}clear(){throw new Error("A reader's index is not cleared; it is replaced.")}*entries(){for(const[path3,entry]of this.overlay)if(entry!==DELETED)yield[path3,entry];for(let record=0;record<this.base.count;record+=1){if(!this.base.hasEntry(record))continue;const path3=this.base.path(record);if(this.overlay.has(path3))continue;yield[path3,this.base.entry(record)]}}*keys(){for(const[path3]of this.entries())yield path3}*values(){for(const[,entry]of this.entries())yield entry}[Symbol.iterator](){return this.entries()}forEach(callback,thisArg){for(const[path3,entry]of this.entries())callback.call(thisArg,entry,path3,this)}*changed(){for(const[path3,entry]of this.overlay)if(entry!==DELETED)yield[path3,entry]}*changes(){for(const[path3,entry]of this.overlay)yield[path3,entry===DELETED?null:entry]}get overlaid(){return this.overlay.size}boundedChanges(){if(this.overlay.size>65536)return void 0;const changes=[];let bytes2=0;for(const[path3,entry]of this.changes()){bytes2+=path3.length*2+128;if(bytes2>8*1024*1024)return void 0;changes.push([path3,entry])}return changes}};var OverlaidChildren=class{constructor(base){this.base=base}base;overlay=new Map;get(path3){const over=this.overlay.get(path3);if(over!==void 0)return over===DELETED?void 0:over;const record=this.base.find(path3);const names2=record<0?void 0:this.base.childNames(record);return names2?new Set(names2):void 0}mutable(path3){const over=this.overlay.get(path3);if(over!==void 0&&over!==DELETED)return over;const names2=new Set(over===DELETED?[]:this.get(path3)??[]);this.overlay.set(path3,names2);return names2}delete(path3){this.overlay.set(path3,DELETED)}};var STORE_BASE_DIRECTORY="supercode-browser-filesystems";var PACKAGES_STORE="packages";var STORE_STATE_FILE="state.json";var IMAGE_RANGE_WORKER_PATH="/image-range-worker.js";var IMAGE_RANGES_FILE="image-ranges.json";var PREFETCH_WORKERS=2;function validateImageRanges(candidate){const value=candidate;if(!value||value.version!==1||!Number.isSafeInteger(value.bytes)||value.bytes<0||!Array.isArray(value.parts)||value.image!==void 0&&(typeof value.image!=="string"||!/^[a-f0-9]{16,64}$/u.test(value.image))||value.parts.length>1e5)throw new Error("Invalid immutable image ranges.");let end=0;for(const part of value.parts){if(!part||part.offset!==end||!Number.isSafeInteger(part.raw)||part.raw<0||!Number.isSafeInteger(part.bytes)||part.bytes<0||part.bytes>1024*1024*1024||part.raw>1024*1024*1024||typeof part.sha256!=="string"||!/^[a-f0-9]{64}$/u.test(part.sha256)||typeof part.url!=="string"||!/^\/substrate\/[A-Za-z0-9._/-]+$/u.test(part.url)||part.url.split("/").some(segment=>segment==="."||segment===".."))throw new Error("Invalid immutable image part.");end+=part.raw;if(!Number.isSafeInteger(end))throw new Error("Immutable image ranges exceed the offset limit.")}if(end!==value.bytes)throw new Error("Immutable image ranges do not cover their reservation.");return value}var ImageRangeReader=class{constructor(ranges,directory2,identity,completed,receiptKey,client){this.ranges=ranges;this.directory=directory2;this.identity=identity;this.receiptKey=receiptKey;this.client=client;if(typeof Worker==="undefined"||typeof SharedArrayBuffer==="undefined"){throw new Error("This browser cannot materialize an immutable image during a synchronous read.")}this.state=new Int32Array(client?.state??new SharedArrayBuffer(ranges.parts.length*Int32Array.BYTES_PER_ELEMENT));if(this.state.length!==ranges.parts.length)throw new Error("The image reader's line has the wrong range count.");const count=ranges.parts.length;const shared=completed??new SharedArrayBuffer((2*count+1)*Int32Array.BYTES_PER_ELEMENT);if(shared.byteLength!==count*Int32Array.BYTES_PER_ELEMENT&&shared.byteLength!==(2*count+1)*Int32Array.BYTES_PER_ELEMENT){throw new Error("The image completion seed has the wrong range count.")}this.completed=new Int32Array(shared,0,count);this.firstRead=shared.byteLength>count*Int32Array.BYTES_PER_ELEMENT?new Int32Array(shared,count*Int32Array.BYTES_PER_ELEMENT,count+1):void 0;this.sharedCompletion=completed!==void 0;for(const part of ranges.parts)Object.freeze(part);Object.freeze(ranges.parts);Object.freeze(ranges)}ranges;directory;identity;receiptKey;client;worker;port;prefetchers=[];state;completed;firstRead;closed=false;ready=false;startup;cancelStartup;sharedCompletion;blocked={ranges:0,ms:0};get completionBuffer(){return this.completed.buffer}get verifiedRanges(){return this.ranges}async initialize(){if(this.closed)throw new Error("This immutable image reader is closed.");if(this.ready)return;if(this.startup)return this.startup;let missing=false;for(let index2=0;index2<this.completed.length;index2+=1){if(Atomics.load(this.completed,index2)!==2){missing=true;break}}if(!missing){this.ready=true;this.client?.port.close();return}if(this.client){const port2=this.port=this.client.port;port2.onmessage=event=>{if(event.data?.type!=="closing"||this.port!==port2)return;port2.close();this.port=void 0;if(!this.closed)void this.startMaterializer().catch(cause=>console.warn("This process's image reader could not start its own materializer after its line closed.",cause))};port2.start();this.ready=true;return}return this.startMaterializer()}startMaterializer(){const began=Date.now();const worker2=new Worker(IMAGE_RANGE_WORKER_PATH,{type:"module",name:"immutable-image-materializer"});const viaLine=this.ready;if(!viaLine)this.worker=worker2;worker2.addEventListener("error",()=>this.fail());worker2.addEventListener("messageerror",()=>this.fail());this.startup=new Promise((resolve2,reject)=>{const cleanup=()=>{clearTimeout(timer);worker2.removeEventListener("message",acknowledge);worker2.removeEventListener("error",failed);worker2.removeEventListener("messageerror",failed);this.cancelStartup=void 0};const failed=()=>cancel(new Error("The immutable image materializer could not initialize; reload to retry."));const cancel=cause=>{cleanup();worker2.terminate();if(!viaLine){this.closed=true;this.fail()}reject(cause)};const acknowledge=event=>{if(event.data?.identity!==this.identity)return;if(event.data.type==="init-error"){cancel(new Error(`The immutable image materializer could not initialize: ${String(event.data.error)}`));return}if(event.data.type!=="ready")return;console.log(`[boot-trace] ${JSON.stringify({event:"materializer-ready",at:Date.now(),ms:Date.now()-began})}`);cleanup();this.ready=true;this.worker=worker2;resolve2()};const timer=setTimeout(()=>cancel(new Error("The immutable image materializer did not initialize within 10 seconds; reload to retry.")),1e4);this.cancelStartup=cancel;worker2.addEventListener("message",acknowledge);worker2.addEventListener("error",failed);worker2.addEventListener("messageerror",failed);try{worker2.postMessage({type:"init",ranges:this.ranges,directory:this.directory,identity:this.identity,state:this.state.buffer,completed:this.completed.buffer,sharedCompletion:this.sharedCompletion,...this.receiptKey?{receiptKey:this.receiptKey}:{}})}catch(cause){cancel(cause instanceof Error?cause:new Error(String(cause)))}});return this.startup}readDigests(){const order=this.firstRead;if(!order)return void 0;const count=this.ranges.parts.length;const read=[];for(let index2=0;index2<count;index2+=1){const sequence=Atomics.load(order,index2);const part=this.ranges.parts[index2];if(sequence>0&&part.raw>0)read.push([sequence,part.sha256])}return read.sort((left,right)=>left[0]-right[0]).map(([,digest])=>digest)}completedDigests(){const held=[];for(let index2=0;index2<this.completed.length;index2+=1){const part=this.ranges.parts[index2];if(part.raw>0&&Atomics.load(this.completed,index2)===2)held.push(part.sha256)}return held}prefetch(digests,streams2=[]){if(this.closed||!this.ready||!this.worker)return{queued:0,done:Promise.resolve()};const byDigest=new Map;for(let index2=0;index2<this.ranges.parts.length;index2+=1){const part=this.ranges.parts[index2];if(part.raw===0)continue;const held=byDigest.get(part.sha256);if(held)held.push(index2);else byDigest.set(part.sha256,[index2])}const indices=[];for(const digest of new Set(digests)){for(const index2 of byDigest.get(digest)??[])if(Atomics.load(this.completed,index2)!==2)indices.push(index2)}const helpers=streams2.length>0&&indices.length>0?Math.min(streams2.length,8):Math.min(PREFETCH_WORKERS,Math.ceil(indices.length/32));const finished=[];for(let lane=0;lane<helpers;lane+=1){const share=indices.filter((_,at3)=>at3%helpers===lane);const helper=new Worker(IMAGE_RANGE_WORKER_PATH,{type:"module",name:"immutable-image-prefetch"});this.prefetchers.push(helper);let ended2;finished.push(new Promise(resolve2=>{ended2=resolve2}));const retire=()=>{helper.terminate();this.prefetchers=this.prefetchers.filter(held=>held!==helper);ended2()};helper.addEventListener("error",retire);helper.addEventListener("messageerror",retire);helper.addEventListener("message",event=>{if(event.data?.identity!==this.identity)return;if(event.data.type==="ready")helper.postMessage(streams2.length>0?{type:"prefetch-stream",url:streams2[lane]}:{type:"prefetch",indices:share});else if(event.data.type==="prefetched"||event.data.type==="init-error")retire()});helper.postMessage({type:"init",ranges:this.ranges,directory:this.directory,identity:this.identity,state:new SharedArrayBuffer(this.state.byteLength),completed:this.completed.buffer,sharedCompletion:true,...this.receiptKey?{receiptKey:this.receiptKey}:{}})}return{queued:indices.length,done:Promise.all(finished).then(()=>void 0)}}get blockedReads(){return{...this.blocked}}ensure(offset2,length){if(this.closed)throw new Error("This immutable image reader is closed.");if(!this.ready)throw new Error("This immutable image reader has not finished asynchronous initialization.");if(length===0||offset2>=this.ranges.bytes)return;const end=Math.min(offset2+length,this.ranges.bytes);let low=0,high=this.ranges.parts.length;while(low<high){const mid=low+high>>>1;const part=this.ranges.parts[mid];if(part.offset+part.raw<=offset2)low=mid+1;else high=mid}for(let index2=low;index2<this.ranges.parts.length;index2+=1){const part=this.ranges.parts[index2];if(part.offset>=end)break;const order=this.firstRead;if(order&&Atomics.load(order,index2)===0)Atomics.compareExchange(order,index2,0,Atomics.add(order,this.ranges.parts.length,1)+1);if(Atomics.load(this.completed,index2)===2)continue;const materializer=this.worker??this.port;if(!materializer)throw new Error("This immutable image reader's line closed and its own materializer is still starting; retry the read.");materializer.postMessage({type:"read",index:index2});const began=performance.now();const deadline=began+3e4;while(Atomics.load(this.state,index2)===0){const left=deadline-performance.now();if(left<=0||Atomics.wait(this.state,index2,0,left)==="timed-out"){this.close();throw new Error(`The image's immutable part ${part.url} did not arrive within 30 seconds; reload to retry.`)}}this.blocked.ranges+=1;this.blocked.ms+=performance.now()-began;if(Atomics.load(this.state,index2)!==2){throw new Error(`The image's immutable part ${part.url} could not be verified or stored; see the worker error and reload to retry.`)}}}lineForReader(){const materializer=this.worker??this.port;if(this.closed||!this.ready||!materializer)return void 0;const channel=new MessageChannel;const state=new SharedArrayBuffer(this.ranges.parts.length*Int32Array.BYTES_PER_ELEMENT);materializer.postMessage({type:"client",port:channel.port1,state},[channel.port1]);return{port:channel.port2,state}}fail(){for(let index2=0;index2<this.state.length;index2+=1){if(Atomics.compareExchange(this.state,index2,0,-1)===0)Atomics.notify(this.state,index2)}}close(){if(this.closed)return;this.closed=true;if(this.cancelStartup){this.cancelStartup(new Error("This immutable image reader closed during initialization."));return}this.fail();this.port?.close();const worker2=this.worker;if(worker2){worker2.postMessage({type:"closing"});setTimeout(()=>worker2.terminate(),250)}for(const helper of this.prefetchers)helper.dispatchEvent(new Event("error"));this.prefetchers=[]}};var PACKAGES_ROOT="/packages";var BROWSER_PACK_RETENTION_ROOT="/opt/.browser-packs";var PACKAGES_LOCK="supercode-browser-packages";var PACKAGES_OPEN_LOCK="supercode-browser-packages-open";var encoder4=new TextEncoder;var decoder5=new TextDecoder("utf-8",{fatal:true});var BASE_DIRECTORY=STORE_BASE_DIRECTORY;var TREE_STORE_PREFIX="host-tree.";var GENERATIONS_DIRECTORY="generations";var STAGING_DIRECTORY="atomic-staging";var STATE_FILE=STORE_STATE_FILE;var INDEX_FILE="index.json";var LOG_FILE="index-log.bin";var PACK_FILE="pack.bin";var RECORD_HEADER_BYTES=8;var MAX_RECORD_BYTES=64*1024*1024;var MAX_FILE_BYTES=1024*1024*1024;var MAX_WORKSPACE_BYTES=4*1024*1024*1024;var PROJECT_ROOTS=["/workspace","/home","/opt"];var STORE_CLOCK_EPOCH=0;var STORE_CLOCK_LOG=1;var MAX_ENTRIES=1e6;var MAX_LOG_BYTES=8*1024*1024;var FLUSH_WINDOW_MS=250;var COMPACTION_FLOOR_BYTES=64*1024*1024;var SESSION_COMPACTION_BYTES=256*1024*1024;var COPY_BUFFER_BYTES=4*1024*1024;var DIRECTORY_MODE=493;var FILE_MODE=420;function createPackStore(environment,options={}){const maximumBytes=options.limits?.maxBytes??MAX_WORKSPACE_BYTES;const maximumEntries=options.limits?.maxEntries??MAX_ENTRIES;if(!Number.isSafeInteger(maximumBytes)||maximumBytes<1||maximumBytes>MAX_WORKSPACE_BYTES||!Number.isSafeInteger(maximumEntries)||maximumEntries<1||maximumEntries>MAX_ENTRIES){throw new Error("Invalid OPFS workspace limits.")}let project;let shared=false;let readOnly=false;let extentsOnly=false;let generationHandle;let linked=0;let linkedBytes=0;let releaseLock;let projectId;let generation;let entries=new Map;let children=new LocalChildren;let packAccess;let imageRangesDigest;let imageReader;let deferredImage;let receivedImageCompletion;let receivedImageLine;let generationInitializedAt=0;let logAccess;let immutableReadEnd=0;const readAhead=new Map;const READ_AHEAD_BYTES=256*1024;const READ_AHEAD_BLOCKS=32;let packBytes=0;let flushTimer;let lastFlushAt=-Infinity;let flushes=0;let flushMs=0;let logBytes=0;let liveBytes=0;let deadBytes=0;let rewrites=0;let rewrittenBytes=0;let mutationUndo;let bytesUndo;let mutationFailure;let initializing=false;let openingController;let checkpointTail=Promise.resolve();let activeStorageOperations=0;let closing=false;let rewritingGeneration=false;let clockView;let transitions=0;let clockRetired=false;function publishLog(){if(!clockView||clockRetired)return;if(logBytes>2147483647){retireClock();return}Atomics.store(clockView,STORE_CLOCK_LOG,logBytes)}function retireClock(){if(!clockView||clockRetired)return;clockRetired=true;if((Atomics.load(clockView,STORE_CLOCK_EPOCH)&1)===0)Atomics.add(clockView,STORE_CLOCK_EPOCH,1)}function beginTransition(){transitions+=1;if(transitions===1&&clockView&&!clockRetired)Atomics.add(clockView,STORE_CLOCK_EPOCH,1)}function endTransition(){transitions-=1;if(transitions>0||!clockView||clockRetired)return;publishLog();if(!clockRetired)Atomics.add(clockView,STORE_CLOCK_EPOCH,1)}function clock(){if(readOnly)throw new Error("A store open for reading follows its owner's clock; it has none of its own.");if(!clockView){clockView=new Int32Array(new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT));clockView[STORE_CLOCK_EPOCH]=transitions>0||clockRetired?1:0;publishLog()}return clockView.buffer}let seedCache;const SEED_REPLAY_BYTES=8*1024*1024;let startedFromSeed=false;function readerSeed(options2){if(readOnly||!clockView||!generation||initializing||transitions>0||clockRetired||closing)return void 0;const epoch=Atomics.load(clockView,STORE_CLOCK_EPOCH);if(epoch&1)return void 0;if(options2?.overlays&&entries instanceof OverlaidIndex){const changes=entries.boundedChanges();if(changes){return withImageCompletion({generation,index:entries.base.buffer,changes,packBytes,logBytes,epoch,liveBytes,linked,linkedBytes})}}if(seedCache&&seedCache.generation===generation&&seedCache.epoch===epoch&&logBytes>=seedCache.logBytes&&logBytes-seedCache.logBytes<=(options2?.current?0:SEED_REPLAY_BYTES))return withImageCompletion(seedCache);let index2;try{index2=encodeSharedIndex(entries,childrenMap())}catch(cause){console.warn(`[pack-store] no reader seed: ${cause instanceof Error?cause.message:String(cause)}`);return void 0}seedCache={generation,index:index2,packBytes,logBytes,epoch,liveBytes,linked,linkedBytes};standOnSeed(index2);return withImageCompletion(seedCache)}function withImageCompletion(seed){const packagesImage=options.packages?.imageCompletionSeed();return packagesImage?{...seed,packagesImage}:seed}function imageCompletionSeed(){if(!imageReader||!imageRangesDigest||!generation||initializing||transitions>0||closing)return void 0;return{generation,rangesDigest:imageRangesDigest,completed:imageReader.completionBuffer,...imageReader.receiptKey?{metadata:{ranges:imageReader.verifiedRanges,receiptKey:imageReader.receiptKey}}:{}}}function standOnSeed(index2){const roomy=[];if(entries instanceof OverlaidIndex){for(const[path3,entry]of entries.changed())if(entry.capacity!==void 0)roomy.push([path3,entry])}else{for(const[path3,entry]of entries)if(entry.capacity!==void 0)roomy.push([path3,entry])}const base=new SharedIndex(index2);entries=new OverlaidIndex(base);children=new OverlaidChildren(base);for(const[path3,entry]of roomy)entries.set(path3,entry)}function childrenMap(){if(children instanceof LocalChildren)return children.map;const derived=new Map;for(const path3 of entries.keys()){const parent=parentPath(path3);if(parent===path3)continue;let names2=derived.get(parent);if(!names2){names2=new Set;derived.set(parent,names2)}names2.add(path3.slice(parent.length+1))}return derived}function follow(){if(!readOnly||extentsOnly||closing||!logAccess)return;replayLog(logBytes)}async function ownStorageOperation(operation){if(closing)throw new Error("This OPFS workspace is closing.");activeStorageOperations+=1;let failure;let failed=false;try{return await operation()}catch(cause){failed=true;failure=cause;throw cause}finally{activeStorageOperations-=1;if(closing&&activeStorageOperations===0){try{closeStorage()}catch(cause){if(failed)throw new AggregateError([failure,cause],"OPFS operation and deferred close both failed.");throw cause}}}}async function rewriteGeneration(operation){assertWritable();if(activeStorageOperations!==0)return Promise.reject(new Error("Wait for the current OPFS storage operation before replacing its generation."));rewritingGeneration=true;return ownStorageOperation(async()=>{try{return await operation()}finally{rewritingGeneration=false}})}function read(path3){if(closing)throw new Error("This OPFS workspace is closing.");const entry=entries.get(path3);if(!entry||entry.type==="directory")throw new Error(`OPFS workspace file does not exist: ${path3}`);return readEntry(entry)}function readRange(path3,offset2,length){if(closing)throw new Error("This OPFS workspace is closing.");const entry=entries.get(path3);if(!entry||entry.type==="directory")throw new Error(`OPFS workspace file does not exist: ${path3}`);const start=Math.min(Math.max(0,offset2),entry.length);const count=Math.min(Math.max(0,length),entry.length-start);if(entry.pack){const packages2=options.packages;if(!packages2)throw new Error("This store has no shared package store to read from.");return packages2.readExtent(entry.offset+start,count)}return readExtent(entry.offset+start,count)}function readEntry(entry){if(entry.pack){const packages2=options.packages;if(!packages2)throw new Error("This store has no shared package store to read from.");return packages2.readExtent(entry.offset,entry.length)}return readExtent(entry.offset,entry.length)}function readExtent(offset2,length){if(closing)throw new Error("This OPFS workspace is closing.");const access=packAccess;if(!access)throw new Error("OPFS filesystem worker is not initialized.");const value=new Uint8Array(length);if(length>0&&length<=READ_AHEAD_BYTES&&offset2>=0&&offset2+length<=immutableReadEnd){let copied=0;while(copied<length){const position=offset2+copied;const start=Math.floor(position/READ_AHEAD_BYTES)*READ_AHEAD_BYTES;let block=readAhead.get(start);if(!block){block=new Uint8Array(Math.min(READ_AHEAD_BYTES,immutableReadEnd-start));imageReader?.ensure(start,block.byteLength);if(access.read(block,{at:start})!==block.byteLength)throw new Error("An OPFS package range could not be read completely.")}readAhead.delete(start);readAhead.set(start,block);if(readAhead.size>READ_AHEAD_BLOCKS)readAhead.delete(readAhead.keys().next().value);const from=position-start;const count=Math.min(length-copied,block.byteLength-from);value.set(block.subarray(from,from+count),copied);copied+=count}return value}imageReader?.ensure(offset2,length);if(length>0&&access.read(value,{at:offset2})!==length){throw new Error("An OPFS workspace file could not be read completely.")}return value}async function initialize2(requestedProjectId,openOptions={}){if(closing&&project||!project&&activeStorageOperations!==0)throw new Error("Wait for this OPFS workspace to finish closing before opening it again.");if(initializing)throw new Error("This OPFS store is already opening a workspace.");if(project){if(projectId!==validProjectId(requestedProjectId))throw new Error("Close this OPFS store before opening another workspace.");return entries.size>0}initializing=true;closing=false;const opening=new AbortController;openingController=opening;try{entries=new Map;children=new LocalChildren;generation=void 0;imageRangesDigest=void 0;generationHandle=void 0;mutationUndo=void 0;mutationFailure=void 0;packBytes=logBytes=liveBytes=deadBytes=linked=linkedBytes=0;checkpointPrefix=void 0;rewrites=rewrittenBytes=flushes=flushMs=0;lastFlushAt=-Infinity;projectId=validProjectId(requestedProjectId);readOnly=openOptions.readOnly===true;receivedImageCompletion=readOnly?openOptions.imageCompletion:void 0;receivedImageLine=readOnly?openOptions.imageLine:void 0;extentsOnly=readOnly&&openOptions.extentsOnly===true;shared=openOptions.shared===true||readOnly;if(!shared)await acquireSessionLock(opening.signal);opening.signal.throwIfAborted();const root2=await storageRoot();opening.signal.throwIfAborted();try{const base=await root2.getDirectoryHandle(BASE_DIRECTORY,{create:!readOnly});opening.signal.throwIfAborted();project=await base.getDirectoryHandle(projectId,{create:!readOnly})}catch(cause){opening.signal.throwIfAborted();if(readOnly&&notFound(cause))return false;throw cause}opening.signal.throwIfAborted();let state=readStorageState(await readJson2(project,STATE_FILE));opening.signal.throwIfAborted();if(!state&&readOnly){await assertNoUncommittedGenerations();return false}if(!state&&shared){await environment.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive",signal:opening.signal},async()=>{opening.signal.throwIfAborted();state=readStorageState(await readJson2(project,STATE_FILE));opening.signal.throwIfAborted();if(!state){await assertNoUncommittedGenerations();await writeGeneration({files:[],pack:new ArrayBuffer(0)});await writeSweepMark(project)}});opening.signal.throwIfAborted();if(!state){generationHandle=await generationDirectory(generation,false);opening.signal.throwIfAborted();return false}}if(!state){await assertNoUncommittedGenerations();opening.signal.throwIfAborted();return false}const openCommitted=async state2=>{let directory2;try{directory2=await generationDirectory(state2.generation,false)}catch(cause){opening.signal.throwIfAborted();if(!notFound(cause))throw cause;throw new Error("The committed OPFS workspace generation is missing. Stored generations were retained.",{cause})}opening.signal.throwIfAborted();generation=state2.generation;generationInitializedAt=state2.initializedAt;imageRangesDigest=state2.imageRanges;generationHandle=directory2;if(extentsOnly){if(projectId===PACKAGES_STORE&&environment.navigator.locks){await environment.navigator.locks.request(PACKAGES_LOCK,{mode:"shared",signal:opening.signal},async()=>{await openGenerationHandles(directory2);immutableReadEnd=packAccess.getSize()})}else await openGenerationHandles(directory2);opening.signal.throwIfAborted();return true}const seed=readOnly?openOptions.seed:void 0;if(seed&&seed.generation===state2.generation){const base=new SharedIndex(seed.index);entries=new OverlaidIndex(base);children=new OverlaidChildren(base);packBytes=seed.packBytes;if(seed.changes)applyIndexRecord({packBytes:seed.packBytes,changes:seed.changes});await openGenerationHandles(directory2);opening.signal.throwIfAborted();logBytes=seed.logBytes;({liveBytes,linked,linkedBytes}=seed);deadBytes=Math.max(0,packBytes-liveBytes);startedFromSeed=true;return entries.size>0}const retained=!readOnly?await readRetainedIndex(directory2):void 0;opening.signal.throwIfAborted();if(retained){const base=new SharedIndex(retained.index);entries=new OverlaidIndex(base);children=new OverlaidChildren(base);({packBytes,liveBytes,linked,linkedBytes}=retained);const epoch=Atomics.load(new Int32Array(clock()),STORE_CLOCK_EPOCH);seedCache={generation,index:retained.index,packBytes,liveBytes,linked,linkedBytes,logBytes:0,epoch}}else{entries=readIndex(await readJson2(directory2,INDEX_FILE));opening.signal.throwIfAborted();rebuildChildren();packBytes=indexPackBytes(entries)}await openGenerationHandles(directory2);opening.signal.throwIfAborted();const represented=retained?await verifiedJournalPrefix(retained):0;opening.signal.throwIfAborted();if(represented){checkpointPrefix={generation,bytes:represented};if(seedCache)seedCache.logBytes=represented}replayLog(represented,!!retained);if(retained)deadBytes=Math.max(0,packBytes-liveBytes);else measureBytes();assertWorkspaceQuota();if(shared&&!readOnly&&!retained&&entries.size>=1e4){flushStorage();await writeIndexAtomically(directory2,entries,{access:logAccess,bytes:logBytes,packBytes})}if(!shared){packAccess.truncate(packBytes);await removeEntry(project,STAGING_DIRECTORY,true);await discardGenerations(generation);opening.signal.throwIfAborted();if(deadBytes>COMPACTION_FLOOR_BYTES&&deadBytes>liveBytes)await compact()}opening.signal.throwIfAborted();return entries.size>0};if(shared&&!readOnly){return await environment.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive",signal:opening.signal},async()=>{state=readStorageState(await readJson2(project,STATE_FILE));if(!state)throw new Error("The committed package store state is missing. Stored data was retained.");return openCommitted(state)})}return await openCommitted(state)}catch(cause){const failures=[cause];try{closeGenerationHandles()}catch(error){failures.push(error)}try{releaseLock?.()}catch(error){failures.push(error)}releaseLock=void 0;project=void 0;if(failures.length>1)throw new AggregateError(failures,"OPFS workspace open and cleanup failed.");throw cause}finally{initializing=false;openingController=void 0}}function refresh(options2){return ownStorageOperation(()=>refreshStorage(options2?.whole===true))}async function refreshStorage(whole=false){if(extentsOnly)throw new Error("A store opened for its extents alone has no index to follow.");if(readOnly&&project){const state=readStorageState(await readJson2(project,STATE_FILE));if(!state)throw new Error("The committed OPFS workspace state is missing. Stored data was retained.");if(state.generation!==generation||whole){const directory2=await generationDirectory(state.generation,false);const index2=readIndex(await readJson2(directory2,INDEX_FILE));packBytes=indexPackBytes(index2);if(state.generation!==generation){generation=state.generation;generationInitializedAt=state.initializedAt;imageRangesDigest=state.imageRanges;await openGenerationHandles(directory2)}generation=state.generation;generationHandle=directory2;entries=index2;rebuildChildren();replayLog();measureBytes();return}}const access=logAccess;if(!access||!generationHandle)return;const size=access.getSize();let reread=false;if(size<logBytes){entries=readIndex(await readJson2(generationHandle,INDEX_FILE));rebuildChildren();packBytes=indexPackBytes(entries);logBytes=0;reread=true}const before=logBytes;replayLog(logBytes);if(reread||logBytes!==before)measureBytes()}async function storageRoot(){let last;for(let attempt=0;attempt<10;attempt+=1){openingController?.signal.throwIfAborted();try{return await environment.navigator.storage.getDirectory()}catch(cause){last=cause;await new Promise(resolve2=>setTimeout(resolve2,200))}}throw last instanceof Error?last:new Error("This browser workspace's storage is unavailable.")}const OPEN_ATTEMPT_MS=1e4;async function openSyncAccess(handle,name){let refusal;const signal=openingController?.signal;for(let attempt=0;attempt<2;attempt+=1){signal?.throwIfAborted();const pending=handle.createSyncAccessHandle({mode:"readwrite-unsafe"});let timer;let abort;let claimed=false;try{const cancelled2=new Promise((_resolve,reject)=>{abort=()=>reject(signal?.reason??new DOMException("Workspace open was cancelled.","AbortError"));signal?.addEventListener("abort",abort,{once:true});if(signal?.aborted)abort()});const opened=await Promise.race([pending.then(access=>({access})).catch(cause=>{refusal=cause;return void 0}),new Promise(resolve2=>{timer=setTimeout(()=>resolve2(void 0),OPEN_ATTEMPT_MS)}),cancelled2]);signal?.throwIfAborted();if(opened){claimed=true;return opened.access}}finally{if(timer!==void 0)clearTimeout(timer);if(abort)signal?.removeEventListener("abort",abort);if(!claimed)void pending.then(access=>access.close(),()=>void 0).catch(cause=>console.error("Late workspace handle cleanup failed.",cause))}if(refusal instanceof TypeError){throw new Error(`This browser cannot share a workspace's files between pages: its file access handles have no readwrite-unsafe mode (Chrome 121 or newer has one). ${refusal.message}`)}await new Promise(resolve2=>setTimeout(resolve2,500))}const reason=refusal instanceof Error?` (${refusal.message})`:"";throw new Error(`This browser workspace's ${name} is held by another page${reason}.`)}async function openGenerationHandles(directory2){closeGenerationHandles();const pack=await directory2.getFileHandle(PACK_FILE);packAccess=await openSyncAccess(pack,"store");try{if(packAccess.getSize()<packBytes)throw new Error("The committed OPFS workspace pack is incomplete. Stored data was retained.");const log=await directory2.getFileHandle(LOG_FILE);logAccess=await openSyncAccess(log,"record of changes");logBytes=logAccess.getSize();if(imageRangesDigest){const supplied=receivedImageCompletion;const completion=supplied&&supplied.generation===generation&&supplied.rangesDigest===imageRangesDigest?supplied:void 0;let ranges;let receiptKey;if(completion?.metadata){ranges=validateImageRanges(completion.metadata.ranges);receiptKey=completion.metadata.receiptKey;if(!/^[a-f0-9]{64}$/u.test(receiptKey))throw new Error("The owner's immutable receipt key is invalid.")}else{const file2=await(await directory2.getFileHandle(IMAGE_RANGES_FILE)).getFile();const bytes2=new Uint8Array(await file2.arrayBuffer());if(await indexDigest(bytes2)!==imageRangesDigest)throw new Error("The committed immutable image ranges have changed. Stored data was retained.");ranges=validateImageRanges(JSON.parse(decoder5.decode(bytes2)));receiptKey=await indexDigest(encoder4.encode(JSON.stringify(ranges)))}if(ranges.bytes>packAccess.getSize())throw new Error("The immutable image reservation is incomplete. Stored data was retained.");const line=completion?receivedImageLine:void 0;if(!line)receivedImageLine?.port.close();receivedImageLine=void 0;imageReader=new ImageRangeReader(ranges,directory2,`${projectId}.${generation}`,completion?.completed,receiptKey,line);await imageReader.initialize();deferredImage=ranges.image}}catch(cause){closeGenerationHandles();throw cause}}function closeGenerationHandles(){imageReader?.close();imageReader=void 0;deferredImage=void 0;const pack=packAccess,log=logAccess;packAccess=void 0;logAccess=void 0;logBytes=0;immutableReadEnd=0;readAhead.clear();try{pack?.close()}finally{log?.close()}}function replayLog(from=0,measureChanges=false){const access=logAccess;if(!access)throw new Error("OPFS filesystem worker is not initialized.");const size=access.getSize();if(size<=from){logBytes=size;return}const buffer2=new Uint8Array(size-from);if(access.read(buffer2,{at:from})!==buffer2.byteLength)throw new Error("The OPFS workspace index log could not be read.");const packSize=packAccess?.getSize()??Infinity;const view=new DataView(buffer2.buffer);let offset2=0;const end=buffer2.byteLength;while(offset2+RECORD_HEADER_BYTES<=end){const length=view.getUint32(offset2,true);const checksum=view.getUint32(offset2+4,true);const start=offset2+RECORD_HEADER_BYTES;if(length===0||length>MAX_RECORD_BYTES||start+length>end)break;const body=buffer2.subarray(start,start+length);if(fingerprint2(body)!==checksum)break;let record;try{record=readIndexRecord(JSON.parse(decoder5.decode(body)))}catch{break}if(record.packBytes>packSize)break;applyIndexRecord(record,measureChanges);offset2=start+length}if(offset2!==end&&!shared)access.truncate(from+offset2);logBytes=from+offset2}function applyIndexRecord(record,measureChanges=false){for(const[path3,entry]of record.changes){const previous=entries.get(path3);if(entry&&sameIndexEntry(previous,entry)){attach(path3);continue}if(measureChanges){if(previous?.pack){linked-=1;linkedBytes-=previous.length}else if(previous)liveBytes-=previous.length;if(entry?.pack){linked+=1;linkedBytes+=entry.length}else if(entry)liveBytes+=entry.length}if(entry===null){entries.delete(path3);detach(path3)}else{entries.set(path3,entry);attach(path3)}}packBytes=Math.max(packBytes,record.packBytes)}function measureBytes(){liveBytes=0;linked=0;linkedBytes=0;for(const entry of entries.values()){if(entry.pack){linked+=1;linkedBytes+=entry.length}else liveBytes+=entry.length}deadBytes=Math.max(0,packBytes-liveBytes)}function indexPackBytes(index2){let end=0;for(const entry of index2.values())if(!entry.pack)end=Math.max(end,entry.offset+entry.length);return end}const SESSION_LOCK_WAIT_MS=5e3;async function acquireSessionLock(signal){if(!environment.navigator.locks)return;if(!projectId)throw new Error("OPFS filesystem project is not initialized.");const controller=new AbortController;const timer=setTimeout(()=>controller.abort(),SESSION_LOCK_WAIT_MS);try{await new Promise((resolve2,reject)=>{void environment.navigator.locks.request(`supercode-browser-filesystem-${projectId}`,{mode:"exclusive",signal:signal?AbortSignal.any([signal,controller.signal]):controller.signal},async()=>{clearTimeout(timer);resolve2();await new Promise(release2=>{releaseLock=release2})}).catch(()=>reject(signal?.aborted?signal.reason:new Error("This browser workspace is already open in another tab.")))})}finally{clearTimeout(timer)}}function validProjectId(value){if(typeof value!=="string"||!/^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/u.test(value)){throw new Error("OPFS filesystem projectId is invalid.")}return value}async function projectDirectory(){if(!project)throw new Error("OPFS filesystem worker is not initialized.");return project}async function generationDirectory(name,create2){const root2=await(await projectDirectory()).getDirectoryHandle(GENERATIONS_DIRECTORY,{create:create2});return root2.getDirectoryHandle(name,{create:create2})}async function assertNoUncommittedGenerations(){let directory2;try{directory2=await(await projectDirectory()).getDirectoryHandle(GENERATIONS_DIRECTORY)}catch(cause){if(notFound(cause))return;throw cause}for await(const _entry of directory2.entries()){throw new Error("OPFS workspace state is missing but stored generations exist. Stored data was retained.")}}async function discardGenerations(retain2){const directory2=await projectDirectory();let root2;try{root2=await directory2.getDirectoryHandle(GENERATIONS_DIRECTORY)}catch(cause){if(notFound(cause))return;throw cause}for await(const[name]of root2.entries()){if(name!==retain2)await removeGenerationQuietly(root2,name)}}function assertWritable(){if(closing)throw new Error("This OPFS workspace is closing.");if(rewritingGeneration)throw new Error("This OPFS workspace is replacing its generation; wait for that operation before writing.");if(readOnly)throw new Error("This store is open for reading; its owner writes it.");if(mutationFailure)throw mutationFailure}async function applyMutations(mutations){applyNow(mutations)}let checkpointPending=false;let maintenanceDeferrals=0;let checkpointPrefix;let compactingLive=false;function maintain(){if(maintenanceDeferrals>0)return;const represented=checkpointPrefix&&checkpointPrefix.generation===generation&&checkpointPrefix.bytes<=logBytes?checkpointPrefix.bytes:0;if(logBytes-represented>MAX_LOG_BYTES&&!checkpointPending){checkpointPending=true;const operation=shared?environment.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive"},async()=>{if(!project||closing)return;await refreshStorage();const prefix2=checkpointPrefix;const represented2=prefix2&&prefix2.generation===generation&&prefix2.bytes<=logBytes?prefix2.bytes:0;if(logBytes-represented2>MAX_LOG_BYTES)await checkpoint()}):checkpoint();void operation.catch(cause=>console.error("The workspace's log could not be checkpointed; it is replayed at the next open.",cause)).finally(()=>{checkpointPending=false})}if(!shared&&!compactingLive&&deadBytes>SESSION_COMPACTION_BYTES&&deadBytes>liveBytes){compactingLive=true;void ownStorageOperation(compactWhileWriting).catch(cause=>console.error("The workspace could not be compacted; it keeps its generation.",cause)).finally(()=>{compactingLive=false})}}async function deferMaintenance(operation){assertWritable();maintenanceDeferrals+=1;try{return await operation()}finally{maintenanceDeferrals-=1;if(maintenanceDeferrals===0&&!closing&&project)maintain()}}function applyMutation(mutation,changes){const path3=requiredPath(mutation.path);if(mutation.operation==="write"){if(entries.get(path3)?.type==="directory")throw new Error(`OPFS write target is a directory: ${path3}`);if(!(mutation.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const value=mutation.content;if(value.byteLength>MAX_FILE_BYTES)throw new Error(`${path3} is ${value.byteLength} bytes; an OPFS workspace file holds at most ${MAX_FILE_BYTES}.`);assertBounds(path3,value.byteLength);createParents(path3,changes);const offset2=appendPack(value);setEntry(path3,{type:mutation.symlink?"symlink":"file",mode:mutation.mode??entries.get(path3)?.mode??FILE_MODE,mtimeMs:mutation.mtimeMs??Date.now(),offset:offset2,length:value.byteLength},changes);return}if(mutation.operation==="append"){const previous=entries.get(path3);if(previous&&previous.type!=="file")throw new Error(`OPFS append target is not a file: ${path3}`);if(!(mutation.content instanceof Uint8Array))throw new Error("OPFS append requires file content.");const added=mutation.content;const length=(previous?.length??0)+added.byteLength;if(length>MAX_FILE_BYTES)throw new Error(`${path3} is ${length} bytes; an OPFS workspace file holds at most ${MAX_FILE_BYTES}.`);assertBounds(path3,length);createParents(path3,changes);const mode=mutation.mode??previous?.mode??FILE_MODE;const mtimeMs=mutation.mtimeMs??Date.now();const room=previous&&!previous.pack?previous.capacity??previous.length:0;if(projectId!==PACKAGES_STORE&&previous&&!previous.pack&&previous.length>0&&(length<=room||previous.offset+room===packBytes)){writePackAt(previous.offset+previous.length,added);setEntry(path3,{...previous,mode,mtimeMs,length,capacity:Math.max(room,length)},changes);deadBytes-=Math.max(previous.length,previous.capacity??0);rewrites-=1;rewrittenBytes-=previous.length;return}const whole=new Uint8Array(length);if(previous&&previous.length>0)whole.set(readEntry(previous),0);whole.set(added,length-added.byteLength);const offset2=appendPack(whole);const capacity=Math.min(MAX_FILE_BYTES,Math.max(length,length*2,64*1024));if(capacity>length)reservePack(offset2+capacity);setEntry(path3,{type:"file",mode,mtimeMs,offset:offset2,length,capacity},changes);return}if(mutation.operation==="write-at"){const previous=entries.get(path3);if(previous&&previous.type!=="file")throw new Error(`OPFS write target is not a file: ${path3}`);if(!(mutation.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const bytes2=mutation.content;const position=mutation.position;const held=previous?.length??0;if(bytes2.byteLength===0&&previous)return;const length=bytes2.byteLength===0?held:Math.max(held,position+bytes2.byteLength);if(length>MAX_FILE_BYTES)throw new Error(`${path3} is ${length} bytes; an OPFS workspace file holds at most ${MAX_FILE_BYTES}.`);assertBounds(path3,length);createParents(path3,changes);const mode=mutation.mode??previous?.mode??FILE_MODE;const mtimeMs=mutation.mtimeMs??Date.now();const room=previous&&!previous.pack?previous.capacity??previous.length:0;if(projectId!==PACKAGES_STORE&&previous&&!previous.pack&&held>0&&(length<=room||previous.offset+room===packBytes)){if(position>held)writePackAt(previous.offset+held,new Uint8Array(position-held));if(bytesUndo&&position<held){const end=Math.min(held,position+bytes2.byteLength);bytesUndo.push([previous.offset+position,readExtent(previous.offset+position,end-position)])}writePackAt(previous.offset+position,bytes2);setEntry(path3,{...previous,mode,mtimeMs,length,capacity:Math.max(room,length)},changes);if(length!==held){deadBytes-=Math.max(previous.length,previous.capacity??0);rewrites-=1;rewrittenBytes-=previous.length}return}const whole=new Uint8Array(length);if(previous&&held>0)whole.set(readEntry(previous),0);if(bytes2.byteLength>0)whole.set(bytes2,position);const offset2=appendPack(whole);const capacity=Math.min(MAX_FILE_BYTES,Math.max(length,length*2,64*1024));if(capacity>length)reservePack(offset2+capacity);setEntry(path3,{type:"file",mode,mtimeMs,offset:offset2,length,capacity},changes);return}if(mutation.operation==="mkdir"){createParents(path3,changes);const existing=entries.get(path3);if(existing&&existing.type!=="directory")throw new Error(`OPFS path is a file: ${path3}`);setEntry(path3,{type:"directory",mode:mutation.mode??existing?.mode??DIRECTORY_MODE,mtimeMs:mutation.mtimeMs??existing?.mtimeMs??Date.now(),offset:0,length:0},changes);return}if(mutation.operation==="remove"){removeTree3(path3,changes);if(storeRoots().includes(path3)){setEntry(path3,{type:"directory",mode:DIRECTORY_MODE,mtimeMs:Date.now(),offset:0,length:0},changes)}return}if(mutation.operation==="link"){linkShared(path3,sharedPath(mutation.source),changes);return}if(mutation.operation==="rename"){renameTree(path3,requiredPath(mutation.destination),changes);return}const entry=entries.get(path3);if(!entry)throw new Error(`OPFS metadata target does not exist: ${path3}`);setEntry(path3,{...entry,mode:mutation.mode??entry.mode,mtimeMs:mutation.mtimeMs??entry.mtimeMs},changes)}function setEntry(path3,entry,changes){const previous=entries.get(path3);if(mutationUndo&&!mutationUndo.has(path3))mutationUndo.set(path3,previous);const sameExtent=previous!==void 0&&previous.type===entry.type&&previous.offset===entry.offset&&previous.length===entry.length&&previous.pack===entry.pack;if(previous&&!sameExtent){forget(previous,path3);if(previous.type!=="directory"&&entry.type!=="directory"&&previous.length>0&&!previous.pack){rewrites+=1;rewrittenBytes+=previous.length}}entries.set(path3,entry);attach(path3);if(!sameExtent){if(entry.pack){linked+=1;linkedBytes+=entry.length}else liveBytes+=entry.length}changes.push([path3,entry])}function attach(path3){const parent=parentPath(path3);if(parent===path3)return;children.mutable(parent).add(path3.slice(parent.length+1))}function detach(path3){const parent=parentPath(path3);if(children.get(parent)?.has(path3.slice(parent.length+1)))children.mutable(parent).delete(path3.slice(parent.length+1));children.delete(path3)}function rebuildChildren(){children=new LocalChildren;for(const path3 of entries.keys())attach(path3)}function descendants(prefix2){const found=[];const visit=path3=>{const entry=entries.get(path3);if(!entry)return;found.push([path3,entry]);const names2=children.get(path3);if(names2)for(const name of names2)visit(`${path3}/${name}`)};visit(prefix2);return found}function forget(previous,path3){if(previous.pack){linked-=1;linkedBytes-=previous.length;return}liveBytes-=previous.length;deadBytes+=Math.max(previous.length,previous.capacity??0)}function deleteEntry(path3,changes){const previous=entries.get(path3);if(!previous)return;if(mutationUndo&&!mutationUndo.has(path3))mutationUndo.set(path3,previous);entries.delete(path3);detach(path3);forget(previous,path3);changes.push([path3,null])}function linkShared(path3,source,changes){const packages2=options.packages;if(!packages2)throw new Error("This store has no shared package store to link from.");const prefix2=sharedPath(source);const files=packages2.descendants(prefix2);if(files.length===0)throw new Error(`The shared package store does not hold ${source}.`);createParents(path3,changes);removeTree3(path3,changes);assertEntryCount(entries.size+files.length);for(const[candidate,entry]of files){const target=candidate===prefix2?path3:`${path3}${candidate.slice(prefix2.length)}`;setEntry(target,entry.type==="directory"?{type:"directory",mode:entry.mode,mtimeMs:entry.mtimeMs,offset:0,length:0}:{type:entry.type,mode:entry.mode,mtimeMs:entry.mtimeMs,offset:entry.offset,length:entry.length,pack:PACKAGES_STORE},changes)}}function createParents(path3,changes){const above=parentPath(path3);if(above!==path3&&entries.get(above)?.type==="directory"){assertEntryCount(entries.size+(entries.has(path3)?0:1));return}const missing=[];let current3=rootOf(path3)??storeRoots()[0];if(!entries.has(current3))missing.push(current3);if(path3!==current3){for(const segment of segmentsOf(relativePath3(parentPath(path3)))){current3=`${current3}/${segment}`;const existing=entries.get(current3);if(existing&&existing.type!=="directory")throw new Error(`OPFS path parent is a file: ${current3}`);if(!existing)missing.push(current3)}}assertEntryCount(entries.size+missing.length+(entries.has(path3)?0:1));const now=Date.now();for(const directory2 of missing){setEntry(directory2,{type:"directory",mode:DIRECTORY_MODE,mtimeMs:now,offset:0,length:0},changes)}}function removeTree3(path3,changes){for(const[candidate]of descendants(path3))deleteEntry(candidate,changes)}function renameTree(source,destination,changes){if(source===destination)return;if(destination.startsWith(`${source}/`))throw new Error("An OPFS rename cannot move a directory into itself.");const moved=descendants(source);if(moved.length===0){if(entries.has(destination))return;throw new Error(`OPFS rename source does not exist: ${source}`)}createParents(destination,changes);removeTree3(destination,changes);for(const[path3]of moved)deleteEntry(path3,changes);for(const[path3,entry]of moved)setEntry(`${destination}${path3.slice(source.length)}`,entry,changes);assertEntryCount(entries.size)}function sharedPath(value){if(typeof value!=="string"||!value.startsWith(`${PACKAGES_ROOT}/`)||value.includes("\0")||value.length>4096){throw new Error("Invalid shared store path.")}segmentsOf(value.slice(PACKAGES_ROOT.length+1));return value}function storeRoots(){return projectId===PACKAGES_STORE?[PACKAGES_ROOT]:PROJECT_ROOTS}function rootOf(path3){return storeRoots().find(root2=>path3===root2||path3.startsWith(`${root2}/`))}function assertBounds(path3,bytes2){const previous=entries.get(path3);const replaced=previous&&!previous.pack?previous.length:0;if(liveBytes-replaced+bytes2>maximumBytes){throw new Error(`OPFS workspace exceeds its byte limit: writing ${path3} (${bytes2} bytes) would take the project's own files past ${maximumBytes} bytes.`)}}function assertEntryCount(count){if(count>maximumEntries)throw new Error("OPFS workspace exceeds its entry limit.")}function assertWorkspaceQuota(){assertEntryCount(entries.size);if(liveBytes>maximumBytes)throw new Error(`OPFS workspace exceeds its byte limit: the project's own files hold ${liveBytes} bytes, past ${maximumBytes}.`)}function writePackAt(offset2,value){const access=packAccess;if(!access)throw new Error("OPFS filesystem worker is not initialized.");let written=0;while(written<value.byteLength){const count=access.write(value.subarray(written),{at:offset2+written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}packBytes=Math.max(packBytes,offset2+value.byteLength)}function reservePack(end){const access=packAccess;if(!access)throw new Error("OPFS filesystem worker is not initialized.");if(end<=packBytes)return;access.truncate(end);packBytes=end}function appendPack(value){const access=packAccess;if(!access)throw new Error("OPFS filesystem worker is not initialized.");const offset2=packBytes;let written=0;while(written<value.byteLength){const count=access.write(value.subarray(written),{at:offset2+written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}packBytes=offset2+value.byteLength;return offset2}function assertStored(log){const pack=packAccess;if(pack.getSize()>=packBytes&&log.getSize()>=logBytes)return;pack.flush();log.flush();const packSize=pack.getSize(),logSize=log.getSize();if(packSize>=packBytes&&logSize>=logBytes)return;throw Object.assign(new Error(`This browser is keeping less than the tab wrote (the store's pack holds ${packSize} of ${packBytes} bytes, its log ${logSize} of ${logBytes}): its storage is full, as a private window's is well below its quota.`),{name:"QuotaExceededError",code:"ENOSPC"})}function commit(changes,options2={}){const access=logAccess;if(!access||!packAccess)throw new Error("OPFS filesystem worker is not initialized.");if(changes.length===0)return;const body=encoder4.encode(JSON.stringify({packBytes,changes}));if(body.byteLength>MAX_RECORD_BYTES)throw new Error("An OPFS workspace index record exceeds its size limit.");const record=new Uint8Array(RECORD_HEADER_BYTES+body.byteLength);const view=new DataView(record.buffer);view.setUint32(0,body.byteLength,true);view.setUint32(4,fingerprint2(body),true);record.set(body,RECORD_HEADER_BYTES);let written=0;while(written<record.byteLength){const count=access.write(record.subarray(written),{at:logBytes+written});if(count<=0)throw new Error("The OPFS workspace index log could not be written completely.");written+=count}logBytes+=record.byteLength;assertStored(access);if(options2.publish!==false)publishLog();if(performance.now()-lastFlushAt>=FLUSH_WINDOW_MS)flushStorage();else if(flushTimer===void 0)flushTimer=setTimeout(flushStorage,FLUSH_WINDOW_MS)}function flushStorage(){if(flushTimer!==void 0){clearTimeout(flushTimer);flushTimer=void 0}if(mutationFailure)throw mutationFailure;const startedAt=performance.now();packAccess?.flush();logAccess?.flush();lastFlushAt=performance.now();flushes+=1;flushMs+=lastFlushAt-startedAt}function checkpoint(){const previous=checkpointTail;const operation=ownStorageOperation(()=>previous.catch(()=>void 0).then(checkpointStorage));checkpointTail=operation;return operation}async function checkpointStorage(){assertWritable();if(!generation)return;const checkpointGeneration=generation;const access=logAccess;const directory2=await generationDirectory(checkpointGeneration,false);if(!access||access!==logAccess||checkpointGeneration!==generation){throw new Error("OPFS workspace changed generations before its checkpoint could start.")}flushStorage();const checkpointBytes=logBytes;await writeIndexAtomically(directory2,entries,{access,bytes:checkpointBytes,packBytes});if(checkpointGeneration===generation)checkpointPrefix={generation:checkpointGeneration,bytes:checkpointBytes};if(access===logAccess&&checkpointGeneration===generation&&checkpointBytes===logBytes){beginTransition();try{access.truncate(0);access.flush();logBytes=0;checkpointPrefix={generation:checkpointGeneration,bytes:0}}finally{endTransition()}}}function writeGeneration(snapshot){return rewriteGeneration(()=>writeGenerationContents(validateSnapshot(snapshot)))}async function writeGenerationContents(snapshot){const next2=crypto.randomUUID();const directory2=await generationDirectory(next2,true);const handle=await directory2.getFileHandle(PACK_FILE,{create:true});const access=await openSyncAccess(handle,"store");const index2=new Map;let cursor=0;try{for(const entry of snapshot.files){let offset2=0;let length=0;if(entry.type!=="directory"){const value=new Uint8Array(snapshot.pack,entry.offset??0,entry.length??0);offset2=cursor;length=value.byteLength;let written=0;while(written<length){const count=access.write(value.subarray(written),{at:offset2+written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}cursor+=length}index2.set(entry.path,{type:entry.type,mode:entry.mode??(entry.type==="directory"?DIRECTORY_MODE:FILE_MODE),mtimeMs:entry.mtimeMs??Date.now(),offset:offset2,length})}for(const root2 of storeRoots()){if(!index2.has(root2))index2.set(root2,{type:"directory",mode:DIRECTORY_MODE,mtimeMs:Date.now(),offset:0,length:0})}assertEntryCount(index2.size);access.truncate(cursor);access.flush()}finally{access.close()}const prepared=await writeIndexAtomically(directory2,index2);await commitGeneration(next2,directory2,index2,cursor,prepared)}async function compact(){await retain(()=>true)}async function compactWhileWriting(){let transitioning=false;let named=false;let stayed=false;try{await compactWhileWritingIn(()=>{transitioning=true},()=>{named=true},()=>{stayed=true})}finally{if(transitioning&&(named||stayed))endTransition();else if(transitioning)retireClock()}}async function compactWhileWritingIn(began,named,stayed){const next2=crypto.randomUUID();const directory2=await generationDirectory(next2,true);const pack=await openSyncAccess(await directory2.getFileHandle(PACK_FILE,{create:true}),"store");let log;let switched=false;try{log=await openSyncAccess(await directory2.getFileHandle(LOG_FILE,{create:true}),"record of changes");log.truncate(0);const buffer2=new Uint8Array(COPY_BUFFER_BYTES);let cursor=0;const copy2=entry=>{if(entry.pack)return{...entry};if(entry.type==="directory"||entry.length===0)return{...entry,offset:0,length:0};const source=packAccess;if(!source)throw new Error("OPFS filesystem worker is not initialized.");const offset2=cursor;let copied=0;while(copied<entry.length){const span=Math.min(buffer2.byteLength,entry.length-copied);const chunk=buffer2.subarray(0,span);imageReader?.ensure(entry.offset+copied,span);if(source.read(chunk,{at:entry.offset+copied})!==span)throw new Error("An OPFS workspace file could not be read completely.");let written=0;while(written<span){const count=pack.write(chunk.subarray(written),{at:offset2+copied+written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}copied+=span}cursor+=entry.length;const{capacity:_room,...extent}=entry;return{...extent,offset:offset2}};const copies=new Map;let sliceStart=performance.now();for(const[path3,entry]of[...entries]){if(closing||rewritingGeneration)return;if(entries.get(path3)!==entry)continue;copies.set(entry,copy2(entry));if(performance.now()-sliceStart>8){await new Promise(resolve2=>setTimeout(resolve2,0));sliceStart=performance.now()}}if(closing||rewritingGeneration||!packAccess||!logAccess)return;beginTransition();began();const index2=new Map;for(const[path3,entry]of entries)index2.set(path3,copies.get(entry)??copy2(entry));pack.truncate(cursor);pack.flush();log.flush();flushStorage();const previous={pack:packAccess,log:logAccess};packAccess=pack;logAccess=log;logBytes=0;entries=index2;rebuildChildren();packBytes=cursor;generation=next2;generationHandle=directory2;measureBytes();switched=true;const document2=new Map(index2);try{previous.pack.close()}finally{previous.log.close()}try{await writeIndexAtomically(directory2,document2);const state={storageVersion:4,generation:next2,initializedAt:Date.now()};await writeJsonAtomically(await projectDirectory(),STATE_FILE,state)}catch(cause){mutationFailure=new Error("The workspace moved to a compacted generation it could not record; it takes no more writes, which its next open would discard.",{cause});throw mutationFailure}named();await discardGenerations(next2)}finally{if(!switched){stayed();try{pack.close()}finally{log?.close()}await removeGenerationQuietly(await(await projectDirectory()).getDirectoryHandle(GENERATIONS_DIRECTORY),next2)}}}async function remapLinks(moved){assertWritable();beginTransition();try{await remapLinksIn(moved)}finally{endTransition()}}async function remapLinksIn(moved){let changed=false;for(const[path3,entry]of entries){if(!entry.pack||entry.length===0)continue;const offset2=moved.get(entry.offset);if(offset2===void 0)throw new Error(`The shared store no longer holds the bytes of ${path3}.`);if(offset2===entry.offset)continue;entries.set(path3,{...entry,offset:offset2});changed=true}if(changed)await checkpoint()}function retain(keep){return rewriteGeneration(()=>retainGeneration(keep))}async function retainGeneration(keep){const source=packAccess;if(!source)throw new Error("OPFS filesystem worker is not initialized.");const moved=new Map;const next2=crypto.randomUUID();const directory2=await generationDirectory(next2,true);const handle=await directory2.getFileHandle(PACK_FILE,{create:true});const access=await openSyncAccess(handle,"store");const index2=new Map;const buffer2=new Uint8Array(COPY_BUFFER_BYTES);let cursor=0;try{for(const[path3,entry]of entries){if(!keep(path3,entry))continue;if(entry.pack){index2.set(path3,{...entry});continue}if(entry.type==="directory"||entry.length===0){index2.set(path3,{...entry,offset:0,length:0});continue}const offset2=cursor;moved.set(entry.offset,offset2);let copied=0;while(copied<entry.length){const span=Math.min(buffer2.byteLength,entry.length-copied);const chunk=buffer2.subarray(0,span);imageReader?.ensure(entry.offset+copied,span);if(source.read(chunk,{at:entry.offset+copied})!==span){throw new Error("An OPFS workspace file could not be read completely.")}let written=0;while(written<span){const count=access.write(chunk.subarray(written),{at:offset2+copied+written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}copied+=span}cursor+=entry.length;const{capacity:_room,...extent}=entry;index2.set(path3,{...extent,offset:offset2,length:entry.length})}access.truncate(cursor);access.flush()}finally{access.close()}const prepared=await writeIndexAtomically(directory2,index2);await commitGeneration(next2,directory2,index2,cursor,prepared);return moved}async function commitGeneration(name,directory2,index2,bytes2,prepared,rangesDigest){beginTransition();try{await commitGenerationIn(name,directory2,index2,bytes2,prepared,rangesDigest)}finally{endTransition()}}async function commitGenerationIn(name,directory2,index2,bytes2,prepared,rangesDigest){const journal=await directory2.getFileHandle(LOG_FILE,{create:true});const journalAccess=await openSyncAccess(journal,"record of changes");try{journalAccess.truncate(0);journalAccess.flush()}finally{journalAccess.close()}const state={storageVersion:rangesDigest?5:4,generation:name,initializedAt:Date.now(),...rangesDigest?{imageRanges:rangesDigest}:{}};await writeJsonAtomically(await projectDirectory(),STATE_FILE,state);closeGenerationHandles();generation=name;generationInitializedAt=state.initializedAt;imageRangesDigest=rangesDigest;if(prepared){const base=new SharedIndex(prepared.index);entries=new OverlaidIndex(base);children=new OverlaidChildren(base);seedCache=void 0}else{entries=index2;rebuildChildren()}packBytes=bytes2;generationHandle=directory2;await openGenerationHandles(directory2);if(prepared){({liveBytes,linked,linkedBytes}=prepared);deadBytes=Math.max(0,packBytes-liveBytes)}else measureBytes();if(!shared)await discardGenerations(name)}async function installPreparedImage(prepared,json,binary,suppliedRanges,verified=false){assertWritable();if(!shared||projectId!==PACKAGES_STORE)throw new Error("Only the shared package store can reserve immutable image extents.");if(packBytes!==0||[...entries.values()].some(entry=>entry.type!=="directory"))return false;const ranges=validateImageRanges(suppliedRanges);if(ranges.bytes!==prepared.packBytes||prepared.entries>MAX_ENTRIES||prepared.liveBytes>prepared.packBytes||json.byteLength!==prepared.json.raw||binary.byteLength!==prepared.binary.raw||!await matchesDigest(json,prepared.json.sha256,verified)||!await matchesDigest(binary,prepared.binary.sha256,verified)){throw new Error("The image's prepared metadata does not match its document.")}const newline=json.subarray(0,4096).indexOf(10);if(newline<0)throw new Error("The prepared index has no bounded retained header.");const retained=JSON.parse(`${decoder5.decode(json.subarray(0,newline-1))}}`);const measures={packBytes:prepared.packBytes,liveBytes:prepared.liveBytes,linked:0,linkedBytes:0};const header=retained.retainedIndex;if(header.version!==1||header.digest!==await retainedIndexDigestOf(prepared.binary.sha256,measures)||header.packBytes!==measures.packBytes||header.liveBytes!==measures.liveBytes||header.linked!==0||header.linkedBytes!==0){throw new Error("The prepared index's retained measures are inconsistent.")}const index2=new SharedArrayBuffer(binary.byteLength);new Uint8Array(index2).set(binary);if(new SharedIndex(index2).entryCount!==prepared.entries)throw new Error("The prepared index has the wrong number of entries.");return rewriteGeneration(async()=>{const name=crypto.randomUUID();const directory2=await generationDirectory(name,true);const pack=await directory2.getFileHandle(PACK_FILE,{create:true});const access=await openSyncAccess(pack,"immutable image reservation");try{access.truncate(prepared.packBytes);access.flush()}finally{access.close()}const rangeBytes=encoder4.encode(JSON.stringify(ranges));await writeBytesAtomically(directory2,IMAGE_RANGES_FILE,rangeBytes);await writeBytesAtomically(directory2,RETAINED_INDEX_FILE,binary);await writeBytesAtomically(directory2,INDEX_FILE,json);await commitGeneration(name,directory2,new Map,prepared.packBytes,{index:index2,...measures},await indexDigest(rangeBytes));return true})}async function installPreparedProject(prepared,json,binary,verified=false,imageInstalled){assertWritable();if(shared||!options.packages||!imageInstalled&&!options.packages.deferredImage)throw new Error("Prepared project paths require a verified shared image.");if(packBytes!==0||[...entries.values()].some(entry=>entry.type!=="directory"))return false;if(json.byteLength!==prepared.json.raw||binary.byteLength!==prepared.binary.raw||!await matchesDigest(json,prepared.json.sha256,verified)||!await matchesDigest(binary,prepared.binary.sha256,verified)){throw new Error("The image's prepared project does not match its descriptor.")}const newline=json.subarray(0,4096).indexOf(10);if(newline<0)throw new Error("The prepared project has no bounded retained header.");const header=JSON.parse(`${decoder5.decode(json.subarray(0,newline-1))}}`).retainedIndex;const measures={packBytes:0,liveBytes:0,linked:prepared.linked,linkedBytes:prepared.linkedBytes};if(header.version!==1||header.digest!==await retainedIndexDigestOf(prepared.binary.sha256,measures)||header.packBytes!==0||header.liveBytes!==0||header.linked!==prepared.linked||header.linkedBytes!==prepared.linkedBytes){throw new Error("The prepared project's retained measures are inconsistent.")}const index2=new SharedArrayBuffer(binary.byteLength);new Uint8Array(index2).set(binary);if(new SharedIndex(index2).entryCount!==prepared.entries||prepared.entries>maximumEntries)throw new Error("The prepared project has invalid entry bounds.");return rewriteGeneration(async()=>{const name=crypto.randomUUID();const directory2=await generationDirectory(name,true);const pack=await directory2.getFileHandle(PACK_FILE,{create:true});const access=await openSyncAccess(pack,"prepared project");try{access.truncate(0);access.flush()}finally{access.close()}await writeBytesAtomically(directory2,RETAINED_INDEX_FILE,binary);await writeBytesAtomically(directory2,INDEX_FILE,json);if(imageInstalled&&!await imageInstalled)return false;if(!options.packages?.deferredImage)throw new Error("Prepared project paths require a verified shared image.");await commitGeneration(name,directory2,new Map,0,{index:index2,...measures});return true})}async function readSnapshot(){if(closing)throw new Error("This OPFS workspace is closing.");if(!packAccess)throw new Error("OPFS filesystem worker is not initialized.");const files=[];const paths=[...entries.keys()].sort((left,right)=>depth4(left)-depth4(right)||(left<right?-1:1));let total=0;for(const entry of entries.values())if(entry.type!=="directory")total+=entry.length;const pack=new ArrayBuffer(total);const view=new Uint8Array(pack);let cursor=0;for(const path3 of paths){const entry=entries.get(path3);if(entry.type==="directory"){files.push({path:path3,type:"directory",mode:entry.mode,mtimeMs:entry.mtimeMs});continue}if(entry.length>0)view.set(readEntry(entry),cursor);files.push({path:path3,type:entry.type,offset:cursor,length:entry.length,mode:entry.mode,mtimeMs:entry.mtimeMs});cursor+=entry.length}for(const root2 of[...storeRoots()].reverse()){if(!entries.has(root2))files.unshift({path:root2,type:"directory",mode:DIRECTORY_MODE,mtimeMs:Date.now()})}return validateSnapshot({files,pack})}async function writeJsonAtomically(directory2,name,value){await writeBytesAtomically(directory2,name,encoder4.encode(JSON.stringify(value)))}async function writeBytesAtomically(directory2,name,bytes2){const staging=await(await projectDirectory()).getDirectoryHandle(STAGING_DIRECTORY,{create:true});const temporaryName=crypto.randomUUID();const handle=await staging.getFileHandle(temporaryName,{create:true});const access=await openSyncAccess(handle,"index");try{let written=0;while(written<bytes2.byteLength){const count=access.write(bytes2.subarray(written),{at:written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}access.truncate(bytes2.byteLength);access.flush()}finally{access.close()}try{await handle.move(directory2,name)}finally{await removeEntry(staging,temporaryName,false)}}const RETAINED_INDEX_FILE="index.shared";async function indexDigest(bytes2){const hash3=await crypto.subtle.digest("SHA-256",bytes2);return Array.from(new Uint8Array(hash3),byte=>byte.toString(16).padStart(2,"0")).join("")}async function matchesDigest(bytes2,digest,verified){return verified||await indexDigest(bytes2)===digest}function retainedIndexDigestOf(binaryDigest,measures){const{packBytes:packBytes2,liveBytes:liveBytes2,linked:linked2,linkedBytes:linkedBytes2,journalPrefix}=measures;return indexDigest(encoder4.encode(`${JSON.stringify({packBytes:packBytes2,liveBytes:liveBytes2,linked:linked2,linkedBytes:linkedBytes2,...journalPrefix?{journalPrefix}:{}})}:${binaryDigest}`))}async function retainedIndexDigest(bytes2,measures){const{packBytes:packBytes2,liveBytes:liveBytes2,linked:linked2,linkedBytes:linkedBytes2,journalPrefix}=measures;return indexDigest(encoder4.encode(`${JSON.stringify({packBytes:packBytes2,liveBytes:liveBytes2,linked:linked2,linkedBytes:linkedBytes2,...journalPrefix?{journalPrefix}:{}})}:${await indexDigest(bytes2)}`))}async function writeIndexAtomically(directory2,index2,journal){const document2=indexDocument(index2);if(typeof SharedArrayBuffer==="undefined"||index2.size<1e4){await writeJsonAtomically(directory2,INDEX_FILE,document2);return}const snapshot=new Map(document2.entries);const names2=new Map;const measure={packBytes:journal?.packBytes??0,liveBytes:0,linked:0,linkedBytes:0};for(const[path3,entry]of snapshot){const parent=parentPath(path3);if(parent!==path3){let children2=names2.get(parent);if(!children2){children2=new Set;names2.set(parent,children2)}children2.add(path3.slice(parent.length+1))}if(entry.pack){measure.linked+=1;measure.linkedBytes+=entry.length}else{measure.liveBytes+=entry.length;measure.packBytes=Math.max(measure.packBytes,entry.offset+entry.length)}}let encoded;try{encoded=encodeSharedIndex(snapshot,names2)}catch{await writeJsonAtomically(directory2,INDEX_FILE,document2);return}const json=JSON.stringify(document2.entries);const prefixBytes=journal?new Uint8Array(journal.bytes):void 0;if(prefixBytes&&journal.access.read(prefixBytes,{at:0})!==prefixBytes.byteLength){throw new Error("The checkpoint's journal prefix could not be read completely.")}const journalPrefix=prefixBytes?{bytes:prefixBytes.byteLength,digest:await indexDigest(prefixBytes)}:void 0;const bytes2=new Uint8Array(encoded).slice();const retained={version:journalPrefix?2:1,digest:await retainedIndexDigest(bytes2,{...measure,...journalPrefix?{journalPrefix}:{}}),...measure,...journalPrefix?{journalPrefix}:{}};try{await writeBytesAtomically(directory2,RETAINED_INDEX_FILE,bytes2)}catch{await writeJsonAtomically(directory2,INDEX_FILE,{entries:JSON.parse(json)});return}await writeBytesAtomically(directory2,INDEX_FILE,encoder4.encode(`{"retainedIndex":${JSON.stringify(retained)},
5893
- "entries":${json}}`));return{index:encoded,...measure}}async function readRetainedIndex(directory2){if(typeof SharedArrayBuffer==="undefined")return void 0;try{const handle=await directory2.getFileHandle(INDEX_FILE);const access=await openSyncAccess(handle,"index");let prefix2;try{const bytes3=new Uint8Array(Math.min(512,access.getSize()));const count=access.read(bytes3,{at:0});prefix2=decoder5.decode(bytes3.subarray(0,count))}finally{access.close()}const firstLine=prefix2.split("\n",1)[0];if(!firstLine.startsWith('{"retainedIndex":')||!firstLine.endsWith(","))return void 0;const retained=JSON.parse(firstLine.slice(0,-1)+"}").retainedIndex;if(retained.version!==1&&retained.version!==2||!/^[a-f0-9]{64}$/u.test(retained.digest)||![retained.packBytes,retained.liveBytes,retained.linked,retained.linkedBytes].every(n8=>Number.isSafeInteger(n8)&&n8>=0))return void 0;if(retained.version===1&&retained.journalPrefix!==void 0)return void 0;if(retained.version===2&&(!retained.journalPrefix||!Number.isSafeInteger(retained.journalPrefix.bytes)||retained.journalPrefix.bytes<0||!/^[a-f0-9]{64}$/u.test(retained.journalPrefix.digest)))return void 0;const binary=await directory2.getFileHandle(RETAINED_INDEX_FILE);const reader=await openSyncAccess(binary,"index");let bytes2;try{const size=reader.getSize();if(size>256*1024*1024)return void 0;bytes2=new Uint8Array(size);if(reader.read(bytes2,{at:0})!==size)return void 0}finally{reader.close()}if(await retainedIndexDigest(bytes2,retained)!==retained.digest)return void 0;const index2=new SharedArrayBuffer(bytes2.byteLength);new Uint8Array(index2).set(bytes2);const base=new SharedIndex(index2);assertEntryCount(base.entryCount);return{...retained,index:index2}}catch{return void 0}}async function verifiedJournalPrefix(retained){const prefix2=retained.journalPrefix;if(!prefix2||!logAccess||!packAccess||prefix2.bytes>logAccess.getSize()||retained.packBytes>packAccess.getSize())return 0;const bytes2=new Uint8Array(prefix2.bytes);if(logAccess.read(bytes2,{at:0})!==bytes2.byteLength)return 0;return await indexDigest(bytes2)===prefix2.digest?prefix2.bytes:0}async function readJson2(directory2,name){let handle;try{handle=await directory2.getFileHandle(name)}catch(cause){if(notFound(cause))return;throw cause}let text;if(readOnly){text=await(await handle.getFile()).text();try{return JSON.parse(text)}catch(cause){throw new Error(`Invalid OPFS workspace metadata (${name}). Stored data was retained.`,{cause})}}const access=await openSyncAccess(handle,"index");try{const size=access.getSize();const value=new Uint8Array(size);if(size>0&&access.read(value,{at:0})!==size){throw new Error("An OPFS workspace file could not be read completely.")}text=decoder5.decode(value)}finally{access.close()}try{return JSON.parse(text)}catch(cause){throw new Error(`Invalid OPFS workspace metadata (${name}). Stored data was retained.`,{cause})}}async function removeEntry(directory2,name,recursive){try{await directory2.removeEntry(name,{recursive})}catch(cause){if(!notFound(cause))throw cause}}async function removeGenerationQuietly(root2,name){try{await root2.removeEntry(name,{recursive:true})}catch{}}function validateMutation(candidate){if(!candidate||typeof candidate!=="object"||Array.isArray(candidate))throw new Error("Invalid OPFS filesystem mutation.");if(candidate.operation!=="write"&&candidate.operation!=="append"&&candidate.operation!=="write-at"&&candidate.operation!=="mkdir"&&candidate.operation!=="remove"&&candidate.operation!=="rename"&&candidate.operation!=="metadata"&&candidate.operation!=="link"){throw new Error("Invalid OPFS filesystem mutation.")}requiredPath(candidate.path);if(candidate.operation==="rename")requiredPath(candidate.destination);if((candidate.operation==="write"||candidate.operation==="append"||candidate.operation==="write-at")&&!(candidate.content instanceof Uint8Array)){throw new Error("Invalid OPFS file content.")}if(candidate.operation==="write-at"&&(!Number.isSafeInteger(candidate.position)||candidate.position<0)){throw new Error("Invalid OPFS write position.")}validateEntryMetadata(candidate);return candidate}function validateMutationBatch(candidate){if(!Array.isArray(candidate)||candidate.length===0||candidate.length>128){throw new Error("Invalid OPFS filesystem mutation batch.")}return candidate.map(mutation=>validateMutation(mutation))}function validateSnapshot(candidate){if(!candidate||!Array.isArray(candidate.files)||candidate.files.length>maximumEntries||!(candidate.pack instanceof ArrayBuffer)){throw new Error("Invalid OPFS workspace snapshot.")}const paths=new Set;const types3=new Map(storeRoots().map(root2=>[root2,"directory"]));let bytes2=0;for(const entry of candidate.files){if(!entry||typeof entry!=="object")throw new Error("Invalid OPFS workspace snapshot entry.");requiredPath(entry.path);if(entry.type!=="file"&&entry.type!=="directory"&&entry.type!=="symlink"||paths.has(entry.path)){throw new Error("Invalid or duplicate OPFS workspace entry.")}paths.add(entry.path);types3.set(entry.path,entry.type);if(storeRoots().includes(entry.path)&&entry.type!=="directory")throw new Error("The OPFS workspace root must be a directory.");if(entry.type!=="directory"){const offset2=entry.offset??0;const length=entry.length??0;if(!Number.isSafeInteger(offset2)||!Number.isSafeInteger(length)||offset2<0||length<0||length>MAX_FILE_BYTES||offset2+length>candidate.pack.byteLength){throw new Error("Invalid OPFS workspace file.")}bytes2+=length;if(bytes2>maximumBytes)throw new Error("OPFS workspace exceeds its byte limit.")}else if((entry.offset??0)!==0||(entry.length??0)!==0){throw new Error("An OPFS workspace directory cannot contain file bytes.")}validateEntryMetadata(entry)}assertEntryCount(types3.size);for(const entry of candidate.files){if(!storeRoots().includes(entry.path)&&types3.get(parentPath(entry.path))!=="directory"){throw new Error(`An OPFS workspace snapshot has no directory parent for ${entry.path}.`)}}return candidate}function validateEntryMetadata(value){if(value.mode!==void 0&&(!Number.isSafeInteger(value.mode)||value.mode<0||value.mode>4095)){throw new Error("Invalid OPFS file mode.")}if(value.mtimeMs!==void 0&&(typeof value.mtimeMs!=="number"||!Number.isFinite(value.mtimeMs)||value.mtimeMs<0)){throw new Error("Invalid OPFS modification time.")}}function indexDocument(index2){return{entries:[...index2]}}function readIndex(value){const index2=new Map;if(value===void 0)throw new Error("The committed OPFS workspace index is missing. Stored data was retained.");if(!value||typeof value!=="object"||!Array.isArray(value.entries)){throw new Error("Invalid OPFS workspace index.")}const rows=value.entries;assertEntryCount(rows.length);for(const row of rows){if(!Array.isArray(row)||row.length!==2)throw new Error("Invalid OPFS workspace index entry.");const path3=requiredPath(row[0]);if(index2.has(path3))throw new Error("Duplicate OPFS workspace index entry.");index2.set(path3,readIndexEntry(row[1]))}return index2}function readIndexEntry(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Invalid OPFS workspace index entry.");const candidate=value;if(candidate.type!=="file"&&candidate.type!=="directory"&&candidate.type!=="symlink")throw new Error("Invalid OPFS workspace index entry.");validateEntryMetadata(candidate);if(candidate.mode===void 0||candidate.mtimeMs===void 0)throw new Error("Invalid OPFS workspace index entry.");if(!Number.isSafeInteger(candidate.offset)||candidate.offset<0||!Number.isSafeInteger(candidate.length)||candidate.length<0||candidate.length>MAX_FILE_BYTES){throw new Error("Invalid OPFS workspace index extent.")}if(candidate.pack!==void 0&&candidate.pack!==PACKAGES_STORE)throw new Error("Invalid OPFS workspace index entry.");return{type:candidate.type,mode:candidate.mode,mtimeMs:candidate.mtimeMs,offset:candidate.offset,length:candidate.length,...candidate.pack?{pack:candidate.pack}:{}}}function readIndexRecord(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Invalid OPFS workspace index record.");const candidate=value;if(!Number.isSafeInteger(candidate.packBytes)||candidate.packBytes<0||!Array.isArray(candidate.changes)){throw new Error("Invalid OPFS workspace index record.")}const changes=[];for(const row of candidate.changes){if(!Array.isArray(row)||row.length!==2)throw new Error("Invalid OPFS workspace index record.");changes.push([requiredPath(row[0]),row[1]===null?null:readIndexEntry(row[1])])}return{packBytes:candidate.packBytes,changes}}function readStorageState(value){if(value===void 0)return;if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Invalid OPFS workspace state. Stored data was retained.");const candidate=value;if(candidate.storageVersion!==4&&candidate.storageVersion!==5||candidate.storageVersion===5&&(typeof candidate.imageRanges!=="string"||!/^[a-f0-9]{64}$/u.test(candidate.imageRanges))||candidate.storageVersion===4&&candidate.imageRanges!==void 0||typeof candidate.generation!=="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(candidate.generation)||typeof candidate.initializedAt!=="number"||!Number.isFinite(candidate.initializedAt)){throw new Error("Invalid or unsupported OPFS workspace state. Stored data was retained.")}return candidate}function requiredPath(value){if(typeof value!=="string"||rootOf(value)===void 0||value.includes("\0")||value.length>4096){throw new Error("Invalid OPFS workspace path.")}relativePath3(value);return value}function relativePath3(path3){const root2=rootOf(path3);if(root2===void 0)throw new Error("Invalid OPFS workspace path.");const relative3=path3===root2?"":path3.slice(root2.length+1);segmentsOf(relative3);return relative3}function segmentsOf(relative3){const segments=relative3===""?[]:relative3.split("/");if(segments.some(segment=>!segment||segment==="."||segment===".."||segment.includes("\0"))){throw new Error("Invalid OPFS workspace path segment.")}return segments}function parentPath(path3){const parent=path3.slice(0,path3.lastIndexOf("/"));return parent===""||rootOf(parent)===void 0?rootOf(path3)??path3:parent}function depth4(path3){let segments=1;for(let index2=0;index2<path3.length;index2+=1)if(path3.charCodeAt(index2)===47)segments+=1;return segments}function notFound(cause){return cause instanceof DOMException&&cause.name==="NotFoundError"}function fingerprint2(value){let hash3=2166136261;for(let index2=0;index2<value.byteLength;index2+=1){hash3^=value[index2];hash3=Math.imul(hash3,16777619)}return hash3>>>0}if(typeof addEventListener==="function")addEventListener("close",()=>{packAccess?.flush();logAccess?.flush();closeGenerationHandles();releaseLock?.()});function applyNow(mutations,options2={}){assertWritable();if(mutationUndo)throw new Error("An OPFS mutation batch cannot be nested.");for(const mutation of mutations)validateMutation(mutation);if(!mutations.length)return[];return runBatch(changes=>{for(const mutation of mutations)applyMutation(mutation,changes)},options2)}function applyExtentsNow(bytes2,files,options2={}){assertWritable();if(mutationUndo)throw new Error("An OPFS mutation batch cannot be nested.");for(const file2 of files){requiredPath(file2.path);if(file2.type!=="file"&&file2.type!=="directory"&&file2.type!=="symlink")throw new Error(`OPFS extent ${file2.path} has no valid type.`);if(file2.type==="directory")continue;const{offset:offset2,length}=file2;if(offset2===void 0||length===void 0||!Number.isSafeInteger(offset2)||!Number.isSafeInteger(length)||offset2<0||length<0||offset2+length>bytes2.byteLength)throw new Error(`OPFS extent ${file2.path} lies outside its bytes.`);if(length>MAX_FILE_BYTES)throw new Error(`${file2.path} is ${length} bytes; an OPFS workspace file holds at most ${MAX_FILE_BYTES}.`)}if(!files.length)return[];return runBatch(changes=>{const base=bytes2.byteLength>0?appendPack(bytes2):packBytes;for(const file2 of files){const path3=requiredPath(file2.path);createParents(path3,changes);const existing=entries.get(path3);if(file2.type==="directory"){if(existing&&existing.type!=="directory")throw new Error(`OPFS path is a file: ${path3}`);setEntry(path3,{type:"directory",mode:file2.mode,mtimeMs:file2.mtimeMs,offset:0,length:0},changes);continue}if(existing?.type==="directory")throw new Error(`OPFS write target is a directory: ${path3}`);assertBounds(path3,file2.length);setEntry(path3,{type:file2.type,mode:file2.mode,mtimeMs:file2.mtimeMs,offset:base+file2.offset,length:file2.length},changes)}},options2)}function runBatch(apply,options2){if(!packAccess||!logAccess)throw new Error("OPFS filesystem worker is not initialized.");const before={packBytes,logBytes,liveBytes,deadBytes,rewrites,rewrittenBytes,linked,linkedBytes};const undo=new Map;mutationUndo=undo;const overwritten=[];bytesUndo=overwritten;const changes=[];try{apply(changes);assertWorkspaceQuota();commit(changes,{publish:!options2.durable});if(options2.durable){flushStorage();publishLog()}maintain();return changes}catch(cause){const published=clockView!==void 0&&!clockRetired&&Atomics.load(clockView,STORE_CLOCK_LOG)!==before.logBytes;if(published)beginTransition();for(const[path3,entry]of undo){if(entry===void 0)entries.delete(path3);else entries.set(path3,entry)}rebuildChildren();try{for(let index2=overwritten.length-1;index2>=0;index2-=1)writePackAt(overwritten[index2][0],overwritten[index2][1])}catch(restoreCause){cause=new AggregateError([cause,restoreCause],"OPFS could not restore bytes a failed batch wrote over.")}({packBytes,logBytes,liveBytes,deadBytes,rewrites,rewrittenBytes,linked,linkedBytes}=before);if(flushTimer!==void 0){clearTimeout(flushTimer);flushTimer=void 0}try{logAccess.truncate(logBytes);logAccess.flush();packAccess.truncate(packBytes);packAccess.flush()}catch(rollbackCause){retireClock();mutationFailure=new AggregateError([cause,rollbackCause],"OPFS could not roll back a failed batch; reopen this workspace before writing again.");throw mutationFailure}if(published)endTransition();throw cause}finally{mutationUndo=void 0;bytesUndo=void 0}}function close2(){if(initializing){openingController?.abort(new DOMException("The workspace was closed while opening.","AbortError"));return}if(closing)return;closing=true;if(activeStorageOperations!==0)return;closeStorage()}function closeStorage(){retireClock();try{flushStorage()}finally{try{closeGenerationHandles()}finally{const release2=releaseLock;releaseLock=void 0;project=void 0;try{release2?.()}finally{if(options.ownsPackages)options.packages?.close()}}}}return{initialize:initialize2,opened:()=>project!==void 0&&!closing,stats:()=>({entries:entries.size,liveBytes,deadBytes,packBytes,rewrites,rewrittenBytes,linked,linkedBytes,flushes,flushMs}),applyNow,applyExtentsNow,close:close2,readExtent,descendants,retain,remapLinks,childrenOf:path3=>[...children.get(path3)??[]].sort(),refresh,follow,clock,readerSeed,imageCompletionSeed,imageLine:()=>imageReader?.lineForReader()??options.packages?.imageLine(),imageStartupSet:()=>imageReader?.readDigests()??imageReader?.completedDigests()??[],prefetchImage:(digests,streams2)=>imageReader?.prefetch(digests,streams2)??{queued:0,done:Promise.resolve()},imageBlockedReads:()=>{const own=imageReader?.blockedReads??{ranges:0,ms:0};const linked2=options.packages?.imageBlockedReads()??{ranges:0,ms:0};return{ranges:own.ranges+linked2.ranges,ms:own.ms+linked2.ms}},seeded:()=>startedFromSeed,get logBytes(){return logBytes},checkpoint,deferMaintenance,installPreparedImage,installPreparedProject,get deferredImage(){return deferredImage},get imagePlacedAt(){return project&&imageRangesDigest?generationInitializedAt:void 0},get entries(){return entries},get packBytes(){return packBytes},read,readRange,snapshot:readSnapshot,replace:writeGeneration,apply:applyMutations,flush:()=>{if(closing||!project)throw new Error("This OPFS workspace is not open.");if(rewritingGeneration)throw new Error("Wait for the OPFS generation replacement before flushing it.");flushStorage()},validateSnapshot,validateMutationBatch}}async function openPackReader(environment,projectId,seed,imageLine){const packages2=createPackStore(environment);await packages2.initialize(PACKAGES_STORE,{readOnly:true,extentsOnly:true,...seed?.packagesImage?{imageCompletion:seed.packagesImage,...imageLine?{imageLine}:{}}:{}});const project=createPackStore(environment,{packages:packages2,ownsPackages:true});let opened;try{opened=await project.initialize(projectId,{readOnly:true,...seed?{seed}:{}})}catch(cause){project.close();packages2.close();throw cause}if(!opened&&!project.opened()){packages2.close();return void 0}return project}var SWEEP_COMPACTION_BYTES=64*1024*1024;var SWEEP_INTERVAL_MS=24*60*60*1e3;var SWEEP_MARK_FILE="sweep.json";var SWEEP_GRACE_MS=14*24*60*60*1e3;async function sweepSharedPackages(environment,progress){const locks=environment.navigator.locks;if(!locks)return void 0;return locks.request(PACKAGES_OPEN_LOCK,{mode:"exclusive",ifAvailable:true},async lock=>{if(!lock)return void 0;const root2=await environment.navigator.storage.getDirectory();let base;try{base=await root2.getDirectoryHandle(BASE_DIRECTORY)}catch{return void 0}let packagesDirectory;try{packagesDirectory=await base.getDirectoryHandle(PACKAGES_STORE)}catch{return void 0}const lastSweep=await readSweepMark(packagesDirectory);if(lastSweep!==void 0&&Date.now()-lastSweep<SWEEP_INTERVAL_MS)return void 0;const projectIds=[];for await(const[name,handle]of base.entries()){if(handle.kind==="directory"&&name!==PACKAGES_STORE&&name!==STAGING_DIRECTORY&&!name.startsWith(TREE_STORE_PREFIX))projectIds.push(name)}const shared=createPackStore(environment);if(!await shared.initialize(PACKAGES_STORE,{shared:true})){shared.close();return void 0}const projects=[];const referenced=new Set;try{for(const[index2,id2]of projectIds.entries()){progress?.(`sweeping the origin's packages, project ${index2+1} of ${projectIds.length}`);const project=createPackStore(environment,{packages:shared});try{const opened=await project.initialize(id2);if(!opened&&!project.opened()){project.close();continue}}catch{project.close();continue}for(const entry of project.entries.values())if(entry.pack&&entry.length>0)referenced.add(entry.offset);projects.push(project)}const kept=new Set;const now=Date.now();for(const[path3,entry]of shared.entries){const unit=unitOf(path3);if(unit===void 0)continue;const linked=entry.type!=="directory"&&entry.length>0&&referenced.has(entry.offset);const recent=path3===`${PACKAGES_ROOT}/${unit}`&&now-Math.max(entry.mtimeMs,shared.imagePlacedAt??0)<SWEEP_GRACE_MS;if(linked||recent)kept.add(unit)}let packagesDropped=0;let bytesDropped=0;const units=new Set;for(const[path3,entry]of shared.entries){const unit=unitOf(path3);if(unit===void 0)continue;units.add(unit);if(!kept.has(unit)&&entry.type!=="directory")bytesDropped+=entry.length}if([...units].some(unit=>!kept.has(unit)&&unit!==".layers"&&unit!==".layers-deferred")){kept.delete(".layers");kept.delete(".layers-deferred")}for(const unit of units)if(!kept.has(unit))packagesDropped+=1;const keep=path3=>{const unit=unitOf(path3);return unit===void 0||kept.has(unit)};let compacted=false;if(packagesDropped>0){if(bytesDropped>=SWEEP_COMPACTION_BYTES||bytesDropped*4>=shared.packBytes){progress?.("sweeping the origin's packages, compacting");const moved=await shared.retain(keep);for(const project of projects)await project.remapLinks(moved);compacted=true}else{const removals=[];for(const unit of units)if(!kept.has(unit))removals.push({operation:"remove",path:`${PACKAGES_ROOT}/${unit}`});for(let offset2=0;offset2<removals.length;offset2+=128)await shared.apply(removals.slice(offset2,offset2+128))}}await writeSweepMark(packagesDirectory);return{projects:projects.length,packagesKept:kept.size,packagesDropped,bytesDropped,compacted}}finally{for(const project of projects)project.close();shared.close()}})}async function readSweepMark(directory2){try{const file2=await(await directory2.getFileHandle(SWEEP_MARK_FILE)).getFile();const mark=JSON.parse(await file2.text());return typeof mark.at==="number"&&Number.isFinite(mark.at)?mark.at:void 0}catch{return void 0}}async function writeSweepMark(directory2){const handle=await directory2.getFileHandle(SWEEP_MARK_FILE,{create:true});const writable=await handle.createWritable();await writable.write(JSON.stringify({at:Date.now()}));await writable.close()}function unitOf(path3){if(!path3.startsWith(`${PACKAGES_ROOT}/`))return void 0;const parts=path3.slice(PACKAGES_ROOT.length+1).split("/");if(parts[0]===".modules")return parts.length>=4?parts.slice(0,4).join("/"):void 0;if(parts[0]===".programs")return parts.length>=2?parts.slice(0,2).join("/"):void 0;if(parts[0]===".browser-packs"){if(parts[1]==="objects"&&parts.length>=3)return parts.slice(0,3).join("/");if(parts[1]==="locks"&&parts.length>=3)return parts.slice(0,3).join("/");return void 0}const packageLength=parts[0]?.startsWith("@")?2:1;return parts.length>=packageLength?parts.slice(0,packageLength).join("/"):void 0}var LocalChildren=class{map=new Map;get(path3){return this.map.get(path3)}mutable(path3){let names2=this.map.get(path3);if(!names2){names2=new Set;this.map.set(path3,names2)}return names2}delete(path3){this.map.delete(path3)}};function storeImportMutations(store,tree2,inside){const root2=normalize2(tree2.root);if(root2!==tree2.root||root2.includes("\0")||root2.includes("\\")||root2.length>4096)throw new Error("Invalid workspace import root.");if(!inside(root2))return false;if(!Array.isArray(tree2.entries)||!tree2.entries.length||tree2.entries.length>5e4)throw new Error("Invalid workspace import entry count.");const incoming2=new Map;let bytes2=0;for(const entry of tree2.entries){if(!entry||typeof entry.path!=="string"||normalize2(entry.path)!==entry.path||entry.path.includes("\0")||entry.path.includes("\\")||entry.path.length>4096||entry.path!==root2&&!entry.path.startsWith(`${root2}/`)||incoming2.has(entry.path)||entry.type!=="file"&&entry.type!=="directory"||!Number.isInteger(entry.mode)||entry.mode<0||entry.mode>4095||!Number.isFinite(entry.mtimeMs)||entry.mtimeMs<0)throw new Error("Invalid workspace import entry.");if(entry.type==="file"){if(!(entry.bytes instanceof Uint8Array))throw new Error("Workspace import file has no bytes.");bytes2+=entry.bytes.byteLength;if(bytes2>128*1024*1024)throw new Error("Workspace import exceeds its byte limit.")}incoming2.set(entry.path,entry)}if(incoming2.get(root2)?.type!=="directory")throw new Error("Workspace import has no root directory.");for(const entry of incoming2.values()){if(entry.path!==root2&&incoming2.get(parentOf(entry.path))?.type!=="directory"){throw new Error(`Workspace import has no parent directory for ${entry.path}.`)}const current3=store.entries.get(entry.path);if(!tree2.replace&&current3&&current3.type!==entry.type)throw new Error(`Workspace import conflicts with ${entry.path}.`)}const heldRoot=store.entries.get(root2);if(tree2.requireEmpty&&heldRoot&&(heldRoot.type!=="directory"||store.childrenOf(root2).length>0)){throw new Error(`Workspace import target is not empty: ${root2}`)}const mutations=tree2.replace?[{operation:"remove",path:root2}]:[];for(const entry of[...incoming2.values()].sort((left,right)=>depth(left.path)-depth(right.path))){mutations.push(entry.type==="directory"?{operation:"mkdir",path:entry.path,mode:entry.mode,mtimeMs:entry.mtimeMs}:{operation:"write",path:entry.path,content:entry.bytes,mode:entry.mode,mtimeMs:entry.mtimeMs})}return mutations}function normalize2(path3){if(path3.startsWith("/")&&(path3.length===1||!path3.endsWith("/"))&&!path3.includes("//")&&!path3.includes("/./")&&!path3.includes("/../")&&!path3.endsWith("/.")&&!path3.endsWith("/.."))return path3;const parts=[];for(const part of`/${path3}`.split("/")){if(!part||part===".")continue;if(part==="..")parts.pop();else parts.push(part)}return`/${parts.join("/")}`}function parentOf(path3){const at3=path3.lastIndexOf("/");return at3<=0?"/":path3.slice(0,at3)}function depth(path3){let segments=1;for(let index2=0;index2<path3.length;index2+=1)if(path3.charCodeAt(index2)===47)segments+=1;return segments}var DIRECTORY_MODE2=493;var FILE_MODE2=420;var PackedVirtualFS=class extends VirtualFS{storeRoots;store;changeListeners=new Set;deleteListeners=new Set;storeWatchers=new Map;textDecoder=new TextDecoder;textEncoder=new TextEncoder;constructor(store,roots=PROJECT_ROOTS,options={}){super();this.store=store;this.storeRoots=typeof roots==="string"?[roots]:roots;if(options.reader===true)return;for(const root2 of this.storeRoots){if(store.entries.has(root2))continue;try{store.applyNow([{operation:"mkdir",path:root2,mode:DIRECTORY_MODE2,mtimeMs:Date.now()}])}catch{}}}on(event,listener){if(event==="change")this.changeListeners.add(listener);else if(event==="delete")this.deleteListeners.add(listener);super.on(event,listener);return this}off(event,listener){if(event==="change")this.changeListeners.delete(listener);else if(event==="delete")this.deleteListeners.delete(listener);super.off(event,listener);return this}existsSync(path3){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized))return super.existsSync(normalized);return this.store.entries.has(normalized)}statSync(path3,options){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized))return super.statSync(normalized,options);const entry=this.store.entries.get(normalized);if(!entry){if(options?.throwIfNoEntry===false)return void 0;throw nodeError("ENOENT","stat",normalized)}return statsOf(entry)}lstatSync(path3,options){const normalized=normalize3(path3);const resolved=this.packedResolve(normalized,true);if(!this.packedInside(resolved))return super.lstatSync(resolved,options);const entry=this.store.entries.get(resolved);if(!entry){if(options?.throwIfNoEntry===false)return void 0;throw nodeError("ENOENT","lstat",resolved)}return statsOf(entry)}readFileSync(path3,encoding){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized))return encoding?super.readFileSync(normalized,encoding):super.readFileSync(normalized);const entry=this.store.entries.get(normalized);if(!entry)throw nodeError("ENOENT","open",normalized);if(entry.type!=="file")throw nodeError("EISDIR","read",normalized);const bytes2=this.store.read(normalized);return encoding?this.textDecoder.decode(bytes2):bytes2}readdirSync(path3){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized))return super.readdirSync(normalized);const entry=this.store.entries.get(normalized);if(!entry)throw nodeError("ENOENT","scandir",normalized);if(entry.type!=="directory")throw nodeError("ENOTDIR","scandir",normalized);return this.store.childrenOf(normalized)}holds(path3,keepLast=false){return this.packedInside(this.packedResolve(normalize3(path3),keepLast))}realpathSync(path3){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized))return super.realpathSync(normalized);if(!this.store.entries.has(normalized))throw nodeError("ENOENT","realpath",normalized);return normalized}accessSync(path3,mode){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized)){super.accessSync(normalized,mode);return}if(!this.store.entries.has(normalized))throw nodeError("ENOENT","access",normalized)}symlinkSync(target,path3){const normalized=this.packedResolve(normalize3(path3),true);if(!this.packedInside(normalized)){super.symlinkSync(target,normalized);return}const parent=this.store.entries.get(parentOf2(normalized));if(!parent||parent.type!=="directory")throw nodeError("ENOENT","symlink",normalized);if(this.store.entries.has(normalized))throw nodeError("EEXIST","symlink",normalized);this.packedApply([{operation:"write",path:normalized,content:this.textEncoder.encode(String(target)),symlink:true,mode:511,mtimeMs:Date.now()}])}readlinkSync(path3){const normalized=this.packedResolve(normalize3(path3),true);if(!this.packedInside(normalized))return super.readlinkSync(normalized);const entry=this.store.entries.get(normalized);if(!entry)throw nodeError("ENOENT","readlink",normalized);if(entry.type!=="symlink")throw nodeError("EINVAL","readlink",normalized);return this.textDecoder.decode(this.store.read(normalized))}writeFileSync(path3,data2){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized)){super.writeFileSync(path3,data2);return}const existing=this.store.entries.get(normalized);if(existing?.type==="directory")throw nodeError("EISDIR","open",normalized);const content=typeof data2==="string"?this.textEncoder.encode(data2):data2;this.packedAppeared(this.packedApply([{operation:"write",path:normalized,content,mode:existing?.mode??FILE_MODE2,mtimeMs:Date.now()}]));this.packedChanged(normalized,typeof data2==="string"?data2:void 0,existing===void 0?"rename":"change")}appendFileSync(path3,data2){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized)){super.appendFileSync(path3,data2);return}const existing=this.store.entries.get(normalized);if(existing?.type==="directory")throw nodeError("EISDIR","open",normalized);const content=typeof data2==="string"?this.textEncoder.encode(data2):data2;this.packedAppeared(this.packedApply([{operation:"append",path:normalized,content,mode:existing?.mode??FILE_MODE2,mtimeMs:Date.now()}]));this.packedChanged(normalized,void 0,existing===void 0?"rename":"change")}writeAtSync(path3,data2,position){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized)){super.writeAtSync(path3,data2,position);return}const existing=this.store.entries.get(normalized);if(existing?.type==="directory")throw nodeError("EISDIR","open",normalized);this.packedAppeared(this.packedApply([{operation:"write-at",path:normalized,content:data2,position,mode:existing?.mode??FILE_MODE2,mtimeMs:Date.now()}]));this.packedChanged(normalized,void 0,existing===void 0?"rename":"change")}mkdirSync(path3,options){const normalized=this.packedResolve(normalize3(path3),true);if(!this.packedInside(normalized)){super.mkdirSync(path3,options);return}const existing=this.store.entries.get(normalized);if(existing){if(options?.recursive&&existing.type==="directory")return;throw nodeError("EEXIST","mkdir",normalized)}if(!options?.recursive){const parent=parentOf2(normalized);const above=this.store.entries.get(parent);if(!above&&this.packedInside(parent))throw nodeError("ENOENT","mkdir",normalized);if(above&&above.type!=="directory")throw nodeError("ENOTDIR","mkdir",normalized)}this.packedAppeared(this.packedApply([{operation:"mkdir",path:normalized,mode:DIRECTORY_MODE2,mtimeMs:Date.now()}]))}unlinkSync(path3){const normalized=this.packedResolve(normalize3(path3),true);if(!this.packedInside(normalized)){super.unlinkSync(path3);return}const entry=this.store.entries.get(normalized);if(!entry)throw nodeError("ENOENT","unlink",normalized);if(entry.type==="directory")throw nodeError("EISDIR","unlink",normalized);this.packedApply([{operation:"remove",path:normalized,recursive:false}]);this.packedDeleted(normalized)}rmdirSync(path3){const normalized=normalize3(path3);if(!this.packedInside(normalized)){super.rmdirSync(path3);return}const entry=this.store.entries.get(normalized);if(!entry)throw nodeError("ENOENT","rmdir",normalized);if(entry.type!=="directory")throw nodeError("ENOTDIR","rmdir",normalized);if(this.store.childrenOf(normalized).length>0)throw nodeError("ENOTEMPTY","rmdir",normalized);this.packedApply([{operation:"remove",path:normalized,recursive:true}]);this.packedDeleted(normalized)}linkShared(source,path3){this.linkSharedBatch([{source,path:path3}])}linkSharedBatch(links){const mutations=links.map(({source,path:path3})=>{const normalized=normalize3(path3);if(!this.packedInside(normalized))throw new Error(`A shared path can only be linked inside ${this.storeRoots.join(" or ")}.`);return{operation:"link",path:normalized,source}});const startedAt=performance.now();const changes=this.store.applyNow(mutations);const indexedAt=performance.now();this.linkTiming.indexMs+=indexedAt-startedAt;for(const[changed,entry]of changes){if(entry===null){this.packedDeleted(changed);continue}if(entry.type==="file")this.packedChanged(changed,void 0)}this.linkTiming.announceMs+=performance.now()-indexedAt}linkTiming={indexMs:0,announceMs:0};chmodSync(path3,mode){const normalized=normalize3(path3);if(!this.packedInside(normalized))return;if(!this.store.entries.has(normalized))throw nodeError("ENOENT","chmod",normalized);this.packedApply([{operation:"metadata",path:normalized,mode:mode&4095}])}utimesSync(path3,_atime,mtime){const normalized=normalize3(path3);if(!this.packedInside(normalized))return;if(!this.store.entries.has(normalized))throw nodeError("ENOENT","utimes",normalized);this.packedApply([{operation:"metadata",path:normalized,mtimeMs:typeof mtime==="number"?mtime:mtime.getTime()}])}renameSync(oldPath,newPath){const source=normalize3(oldPath);const destination=normalize3(newPath);const sourceInside=this.packedInside(source);const destinationInside=this.packedInside(destination);if(!sourceInside&&!destinationInside){super.renameSync(oldPath,newPath);return}if(sourceInside&&destinationInside){if(!this.store.entries.has(source))throw nodeError("ENOENT","rename",source);const moved=[source];for(let index2=0;index2<moved.length;index2+=1){const path3=moved[index2];if(this.store.entries.get(path3)?.type!=="directory")continue;for(const name of this.store.childrenOf(path3))moved.push(`${path3}/${name}`)}this.packedApply([{operation:"rename",path:source,destination}]);for(const path3 of moved)this.packedDeleted(path3);for(const path3 of moved)this.packedChanged(`${destination}${path3.slice(source.length)}`,void 0);return}this.packedCopyTree(source,destination);this.packedRemoveTree(source)}copyFileSync(src,dest){this.writeFileSync(dest,this.readFileSync(src))}watchedPaths(){const paths=[];for(const[path3,set]of this.storeWatchers)if(set.size>0)paths.push({path:path3,recursive:[...set].some(entry=>entry.recursive)});const overlay=this.watchers;for(const[path3,set]of overlay??[]){const live2=[...set].filter(entry=>!entry.closed);if(live2.length>0)paths.push({path:path3,recursive:live2.some(entry=>entry.recursive===true)})}return paths}watch(filename,optionsOrListener,listener){const normalized=normalize3(filename);const inside=this.packedInside(normalized);const above=this.storeRoots.some(root2=>normalized==="/"||root2.startsWith(normalized+"/"));if(!inside&&!above)return super.watch(filename,optionsOrListener,listener);const overlay=inside?void 0:super.watch(filename,optionsOrListener,listener);const options=typeof optionsOrListener==="function"?{}:optionsOrListener??{};const actual=typeof optionsOrListener==="function"?optionsOrListener:listener;const entry={listener:actual??(()=>void 0),recursive:options.recursive??false};let set=this.storeWatchers.get(normalized);if(!set){set=new Set;this.storeWatchers.set(normalized,set)}set.add(entry);const watcher={close:()=>{set.delete(entry);overlay?.close()},ref(){overlay?.ref();return this},unref(){overlay?.unref();return this}};return watcher}toSnapshot(){const base=super.toSnapshot();const files=base.files.filter(entry=>!this.packedInside(entry.path));const paths=[...this.store.entries.keys()].sort((left,right)=>depth2(left)-depth2(right)||(left<right?-1:1));for(const path3 of paths){const entry=this.store.entries.get(path3);const metadata={mode:entry.mode&4095,mtimeMs:entry.mtimeMs};if(entry.type==="directory")files.push({path:path3,type:"directory",...metadata});else if(entry.type==="symlink")files.push({path:path3,type:"symlink",target:this.textDecoder.decode(this.store.read(path3)),...metadata});else files.push({path:path3,type:"file",content:base642(this.store.read(path3)),...metadata})}return{...base,files}}packedInside(path3){return this.storeRoots.some(root2=>path3===root2||path3.startsWith(`${root2}/`))}typeOf(path3){const entries=this.store.entries;return entries.typeOf?entries.typeOf(path3):entries.get(path3)?.type}packedResolve(path3,keepLast=false){if(!this.packedInside(path3))return path3;const direct=this.typeOf(path3);if(direct?direct!=="symlink"||keepLast:this.typeOf(parentOf2(path3))==="directory")return path3;let current3=path3;for(let hops=0;hops<40;hops+=1){const parts=current3.split("/").filter(Boolean);let prefix2="";let followed=false;for(let index2=0;index2<parts.length;index2+=1){prefix2=`${prefix2}/${parts[index2]}`;if(!this.packedInside(prefix2))return current3;if(keepLast&&index2===parts.length-1)break;const type2=this.typeOf(prefix2);if(!type2)return current3;if(type2!=="symlink")continue;const target=this.textDecoder.decode(this.store.read(prefix2));const base=target.startsWith("/")?target:`${parentOf2(prefix2)}/${target}`;current3=normalize3(`${base}/${parts.slice(index2+1).join("/")}`.replace(/\/$/u,""));followed=true;break}if(!followed)return current3}throw nodeError("ELOOP","stat",path3)}packedApply(mutations,options){return this.store.applyNow(mutations,options)}applyBatch(mutations){for(const mutation of mutations){if(typeof mutation.path!=="string"||!this.packedInside(normalize3(mutation.path))){throw new Error(`A batch can only be applied inside ${this.storeRoots.join(" or ")}.`)}}const changes=this.packedApply(mutations);for(const[path3,entry]of changes){if(entry===null)this.packedDeleted(path3);else if(entry.type==="file")this.packedChanged(path3,void 0)}}importTree(tree2){const mutations=storeImportMutations(this.store,tree2,path3=>this.packedInside(path3));if(!mutations)return false;const changes=this.packedApply(mutations,{durable:true});for(const[path3,entry]of changes){try{if(entry===null)this.packedDeleted(path3);else if(entry.type==="file")this.packedChanged(path3,void 0)}catch(cause){console.error("Workspace import observer failed.",cause)}}return true}packedAppeared(changes){for(const[path3,entry]of changes)if(entry!==null&&entry.type==="directory")this.packedNotifyWatchers(path3,"rename")}packedChanged(path3,text,event="change"){for(const listener of this.changeListeners)listener(path3,text??"");this.packedNotifyWatchers(path3,event)}packedDeleted(path3){for(const listener of this.deleteListeners)listener(path3);this.packedNotifyWatchers(path3,"rename")}packedNotifyWatchers(path3,event){for(const[watched,set]of this.storeWatchers){if(path3!==watched&&watched!=="/"&&!path3.startsWith(`${watched}/`))continue;const relative3=path3===watched?path3.slice(path3.lastIndexOf("/")+1):path3.slice(watched==="/"?1:watched.length+1);for(const entry of set){if(path3!==watched&&!entry.recursive&&relative3.includes("/"))continue;entry.listener(event,relative3)}}}packedCopyTree(source,destination){const stat2=this.statSync(source);if(stat2.isDirectory()){this.mkdirSync(destination,{recursive:true});for(const name of this.readdirSync(source))this.packedCopyTree(`${source}/${name}`,`${destination}/${name}`);return}this.writeFileSync(destination,this.readFileSync(source))}packedRemoveTree(path3){const stat2=this.statSync(path3);if(stat2.isDirectory()){for(const name of this.readdirSync(path3))this.packedRemoveTree(`${path3}/${name}`);this.rmdirSync(path3);return}this.unlinkSync(path3)}};function statsOf(entry){const isFile2=entry.type==="file";const isLink=entry.type==="symlink";const when=new Date(entry.mtimeMs);return{isFile:()=>isFile2,isDirectory:()=>entry.type==="directory",isSymbolicLink:()=>isLink,isBlockDevice:()=>false,isCharacterDevice:()=>false,isFIFO:()=>false,isSocket:()=>false,size:entry.type==="directory"?0:entry.length,mode:(isFile2?32768:isLink?40960:16384)|entry.mode,mtime:when,atime:when,ctime:when,birthtime:when,mtimeMs:entry.mtimeMs,atimeMs:entry.mtimeMs,ctimeMs:entry.mtimeMs,birthtimeMs:entry.mtimeMs,nlink:1,uid:0,gid:0,dev:0,ino:0,rdev:0,blksize:4096,blocks:Math.ceil((isFile2?entry.length:0)/512)}}function nodeError(code3,syscall,path3){const messages3={ENOENT:"no such file or directory",ENOTDIR:"not a directory",EISDIR:"is a directory",EEXIST:"file already exists",ENOTEMPTY:"directory not empty",EINVAL:"invalid argument",ELOOP:"too many symbolic links encountered"};const errno={ENOENT:-2,ENOTDIR:-20,EISDIR:-21,EEXIST:-17,ENOTEMPTY:-39,EINVAL:-22,ELOOP:-40};return Object.assign(new Error(`${code3}: ${messages3[code3]}, ${syscall} '${path3}'`),{code:code3,errno:errno[code3],syscall,path:path3})}function normalize3(path3){if(path3.startsWith("/")&&(path3.length===1||!path3.endsWith("/"))&&!path3.includes("//")&&!path3.includes("/./")&&!path3.includes("/../")&&!path3.endsWith("/.")&&!path3.endsWith("/.."))return path3;const parts=[];for(const part of`/${path3}`.split("/")){if(!part||part===".")continue;if(part==="..")parts.pop();else parts.push(part)}return`/${parts.join("/")}`}function parentOf2(path3){const at3=path3.lastIndexOf("/");return at3<=0?"/":path3.slice(0,at3)}function base642(value){let binary="";for(let offset2=0;offset2<value.byteLength;offset2+=32768){binary+=String.fromCharCode(...value.subarray(offset2,Math.min(value.byteLength,offset2+32768)))}return btoa(binary)}function depth2(path3){let segments=1;for(let index2=0;index2<path3.length;index2+=1)if(path3.charCodeAt(index2)===47)segments+=1;return segments}function storeReads(grant){const{opening,clock:buffer2}=grant;const clock=new Int32Array(buffer2);let reader;let local2;let synced=-1;void opening.then(opened=>{if(!opened)return;reader=opened;local2=new PackedVirtualFS(opened,PROJECT_ROOTS,{reader:true});const openedAt=grant.openedAt;if((openedAt&1)===0&&Atomics.load(clock,STORE_CLOCK_EPOCH)===openedAt)synced=openedAt},()=>void 0);let resyncing=false;let retryAt=0;const resync=epoch=>{if(resyncing||!reader||performance.now()<retryAt)return;resyncing=true;reader.refresh({whole:true}).then(()=>{if(Atomics.load(clock,STORE_CLOCK_EPOCH)===epoch)synced=epoch},()=>{retryAt=performance.now()+1e3}).finally(()=>{resyncing=false})};return(path3,keepLast,read)=>{if(!reader||!local2)return void 0;const epoch=Atomics.load(clock,STORE_CLOCK_EPOCH);if(resyncing)return void 0;if(epoch!==synced){if((epoch&1)===0)resync(epoch);return void 0}const published=Atomics.load(clock,STORE_CLOCK_LOG);if(reader.logBytes<published){try{reader.follow()}catch{return void 0}if(reader.logBytes<published)return void 0}let value;try{if(!local2.holds(path3,keepLast))return void 0;value=read(local2)}catch(cause){if(Atomics.load(clock,STORE_CLOCK_EPOCH)!==epoch||typeof cause?.code!=="string")return void 0;throw cause}if(Atomics.load(clock,STORE_CLOCK_EPOCH)!==epoch)return void 0;return{value}}}function validateNodePreparedFiles(files,limits){if(!Number.isSafeInteger(limits.maxBytes)||limits.maxBytes<1||!Number.isSafeInteger(limits.maxEntries)||limits.maxEntries<1||!Array.isArray(files)||files.length>limits.maxEntries)throw new Error("Invalid Node prepared-file limits or count.");const paths=new Map([["/","directory"]]);const encoder7=new TextEncoder;let bytes2=1;for(const file2 of files){if(!file2||typeof file2.path!=="string"||file2.path.length>limits.maxBytes||!file2.path.startsWith("/")||file2.path.endsWith("/")||file2.path.includes("\0")||file2.path.slice(1).split("/").some(part=>!part||part==="."||part==="..")||!(file2.bytes instanceof Uint8Array)||paths.has(file2.path))throw new Error("Invalid Node prepared file.");let parent="";for(const part of file2.path.slice(1).split("/").slice(0,-1)){parent+=`/${part}`;if(paths.get(parent)==="file")throw new Error("Node prepared file conflicts with a directory.");if(!paths.has(parent)){paths.set(parent,"directory");bytes2+=encoder7.encode(parent).byteLength}}paths.set(file2.path,"file");bytes2+=encoder7.encode(file2.path).byteLength+file2.bytes.byteLength;if(paths.size>limits.maxEntries)throw new Error("Node prepared files exceed their entry limit.");if(bytes2>limits.maxBytes)throw new Error("Node prepared files exceed their byte limit.")}}function captureNodePreparedFiles(filesystem,limits){validateNodePreparedFiles([],limits);const paths=["/"];const files=[];const encoder7=new TextEncoder;let entries=0,bytes2=0;while(paths.length){const path3=paths.pop();if(++entries>limits.maxEntries)throw new Error("Node prepared files exceed their entry limit.");const stat2=filesystem.lstatSync(path3);bytes2+=encoder7.encode(path3).byteLength;if(stat2.isFile()){bytes2+=stat2.size;files.push(path3)}else if(stat2.isDirectory()){const names2=filesystem.readdirSync(path3);if(entries+paths.length+names2.length>limits.maxEntries)throw new Error("Node prepared files exceed their entry limit.");for(const name of names2)paths.push(`${path3==="/"?"":path3}/${name}`)}else throw new Error("Node prepared files cannot contain symbolic links.");if(bytes2>limits.maxBytes)throw new Error("Node prepared files exceed their byte limit.")}return files.map(path3=>({path:path3,bytes:Uint8Array.from(filesystem.readFileSync(path3))}))}function nodeInvocationFilesystem(channel,policy,prepared,store){const client=new BrowserFilesystemChannelClient(channel);const shared=new VirtualFS;for(const method of["existsSync","statSync","lstatSync","readFileSync","readdirSync","realpathSync","readlinkSync","symlinkSync","writeFileSync","appendFileSync","writeAtSync","mkdirSync","unlinkSync","rmdirSync","renameSync","chmodSync","utimesSync"]){Reflect.set(shared,method,client[method].bind(client))}Reflect.set(shared,"accessSync",path3=>{client.statSync(path3)});if(store){const attempt=storeReads(store);for(const method of["existsSync","statSync","lstatSync","readFileSync","readdirSync","realpathSync","readlinkSync","accessSync"]){const owner2=Reflect.get(shared,method);const keepLast=method==="lstatSync"||method==="readlinkSync";Reflect.set(shared,method,(path3,...args)=>{const answer2=attempt(path3,keepLast,local2=>Reflect.get(local2,method).call(local2,path3,...args));return answer2?answer2.value:owner2(path3,...args)})}}const runtimeFiles=new VirtualFS;if(prepared){validateNodePreparedFiles(prepared.files,prepared.limits);for(const{path:path3,bytes:bytes2}of prepared.files){runtimeFiles.mkdirSync(path3.slice(0,path3.lastIndexOf("/"))||"/",{recursive:true});runtimeFiles.writeFileSync(path3,bytes2)}}const merged=new VirtualFS;const owner=path3=>{if(!runtimeFiles.existsSync(path3))return shared;if(runtimeFiles.statSync(path3).isDirectory()&&shared.existsSync(path3))return shared;return runtimeFiles};const mutationOwner=path3=>{const filesystem=owner(path3);if(filesystem===runtimeFiles)throw Object.assign(new Error(`EACCES: private runtime file '${path3}' is read-only`),{code:"EACCES"});return filesystem};for(const method of["statSync","lstatSync","readFileSync","realpathSync","readlinkSync","accessSync","writeFileSync","appendFileSync","writeAtSync","mkdirSync","unlinkSync","rmdirSync","chmodSync","utimesSync"]){Reflect.set(merged,method,(path3,...args)=>{const mutating=["writeFileSync","appendFileSync","writeAtSync","mkdirSync","unlinkSync","rmdirSync","chmodSync","utimesSync"].includes(method)||method==="accessSync"&&(Number(args[0]??0)&2)!==0;const filesystem=mutating?mutationOwner(path3):owner(path3);const action=Reflect.get(filesystem,method);if(!action)throw Object.assign(new Error(`Unsupported filesystem operation ${method}.`),{code:"ENOTSUP"});return action.call(filesystem,path3,...args)})}Reflect.set(merged,"existsSync",path3=>runtimeFiles.existsSync(path3)||shared.existsSync(path3));Reflect.set(merged,"readdirSync",path3=>[...new Set([...runtimeFiles.existsSync(path3)?runtimeFiles.readdirSync(path3):[],...shared.existsSync(path3)?shared.readdirSync(path3):[]])].sort());Reflect.set(merged,"renameSync",(from,to2)=>{const filesystem=mutationOwner(from);if(filesystem!==mutationOwner(to2))throw Object.assign(new Error("Cannot rename across runtime and project files."),{code:"EXDEV"});filesystem.renameSync(from,to2)});Reflect.set(merged,"symlinkSync",(target,path3)=>mutationOwner(path3).symlinkSync(target,path3));const listeners={change:new Set,delete:new Set};const watchers=new Set;const normalize4=path3=>{const parts=[];for(const part of path3.split("/")){if(part==="..")parts.pop();else if(part&&part!==".")parts.push(part)}return"/"+parts.join("/")};Reflect.set(merged,"on",(event,listener)=>{listeners[event].add(listener);return merged});Reflect.set(merged,"off",(event,listener)=>{listeners[event].delete(listener);return merged});Reflect.set(merged,"watch",((path3,optionsOrListener,listener)=>{const options=typeof optionsOrListener==="object"?optionsOrListener:{};const entry={path:normalize4(path3),directory:merged.statSync(path3).isDirectory(),recursive:options?.recursive===true,persistent:options?.persistent!==false,listener:typeof optionsOrListener==="function"?optionsOrListener:listener};watchers.add(entry);return{close(){watchers.delete(entry)},ref(){entry.persistent=true;return this},unref(){entry.persistent=false;return this}}}));return{guest:policy?createConfinedNodeFilesystem(merged,policy):merged,runtimeFiles,notify(event,changedPath){const path3=normalize4(changedPath);let content="";if(event==="change"&&listeners.change.size&&merged.existsSync(path3)&&merged.statSync(path3).isFile())content=merged.readFileSync(path3,"utf8");for(const listener of listeners[event])listener(path3,content)},notifyWatch(event,changedPath){const path3=normalize4(changedPath);for(const watcher of watchers){const relative3=path3.slice(watcher.path==="/"?1:watcher.path.length+1);const inside=watcher.directory&&(watcher.path==="/"||path3.startsWith(watcher.path+"/"));if(path3===watcher.path||inside&&(watcher.recursive||!relative3.includes("/"))){watcher.listener?.(event,inside?relative3:path3.split("/").pop())}}}}}var TAILWIND_RUNTIME_DIRECTORY="/tmp/browser-runtime-tailwind";var TAILWIND_VITE_PATH=`${TAILWIND_RUNTIME_DIRECTORY}/vite.cjs`;var STAND_IN_PATHS={"@tailwindcss/vite":TAILWIND_VITE_PATH};function ensureTailwindStandIn(filesystem){if(filesystem.existsSync(TAILWIND_VITE_PATH))return;filesystem.mkdirSync(TAILWIND_RUNTIME_DIRECTORY,{recursive:true});filesystem.writeFileSync(TAILWIND_VITE_PATH,TAILWIND_VITE_SOURCE)}var TAILWIND_VITE_SOURCE=String.raw`"use strict";
5892
+ `)}}}catch{}added.push(name)});await this.writeLockfile(resolved);return added}async writeLockfile(resolved){const lockfile={};for(const[name,pkg]of resolved){lockfile[name]={version:pkg.version,resolved:pkg.tarballUrl}}const lockfilePath=join2(this.cwd,"node_modules",".package-lock.json");this.vfs.writeFileSync(lockfilePath,JSON.stringify(lockfile,null,2))}async updatePackageJson(packageName,version2,isDev){const pkgJsonPath=join2(this.cwd,"package.json");let pkgJson={};if(this.vfs.existsSync(pkgJsonPath)){pkgJson=JSON.parse(this.vfs.readFileSync(pkgJsonPath,"utf8"))}const field=isDev?"devDependencies":"dependencies";if(!pkgJson[field]){pkgJson[field]={}}pkgJson[field][packageName]=version2;this.vfs.writeFileSync(pkgJsonPath,JSON.stringify(pkgJson,null,2))}list(){const nodeModulesPath=join2(this.cwd,"node_modules");if(!this.vfs.existsSync(nodeModulesPath)){return{}}const packages2={};const entries=this.vfs.readdirSync(nodeModulesPath);for(const entry of entries){if(entry.startsWith("."))continue;if(entry.startsWith("@")){const scopePath=join2(nodeModulesPath,entry);const scopedPkgs=this.vfs.readdirSync(scopePath);for(const scopedPkg of scopedPkgs){const pkgJsonPath=join2(scopePath,scopedPkg,"package.json");if(this.vfs.existsSync(pkgJsonPath)){const pkgJson=JSON.parse(this.vfs.readFileSync(pkgJsonPath,"utf8"));packages2[`${entry}/${scopedPkg}`]=pkgJson.version}}}else{const pkgJsonPath=join2(nodeModulesPath,entry,"package.json");if(this.vfs.existsSync(pkgJsonPath)){const pkgJson=JSON.parse(this.vfs.readFileSync(pkgJsonPath,"utf8"));packages2[entry]=pkgJson.version}}}return packages2}};function parsePackageSpec(spec){if(spec.startsWith("@")){const slashIndex=spec.indexOf("/");if(slashIndex===-1){throw new Error(`Invalid package spec: ${spec}`)}const afterSlash=spec.slice(slashIndex+1);const atIndex2=afterSlash.indexOf("@");if(atIndex2===-1){return{name:spec}}return{name:spec.slice(0,slashIndex+1+atIndex2),version:afterSlash.slice(atIndex2+1)}}const atIndex=spec.indexOf("@");if(atIndex===-1){return{name:spec}}return{name:spec.slice(0,atIndex),version:spec.slice(atIndex+1)}}async function install(packageSpec,vfs2,options){const pm=new PackageManager(vfs2);return pm.install(packageSpec,options)}var index=Object.freeze(Object.defineProperty({__proto__:null,PackageManager,Registry,install,parsePackageSpec,setInstallTransformEnabled},Symbol.toStringTag,{value:"Module"}));function __listening(port2){return listenerOnPort(port2)!==void 0}function requestHead(method,url2,headers,body){const lines=[`${method.toUpperCase()} ${url2} HTTP/1.1`];let hasLength=false;let hasEncoding=false;for(const[name,value]of Object.entries(headers)){const lower=name.toLowerCase();if(lower==="content-length")hasLength=true;if(lower==="transfer-encoding")hasEncoding=true;if(lower==="connection")continue;lines.push(`${name}: ${value}`)}if(!hasLength&&!hasEncoding)lines.push(`Content-Length: ${body?body.length:0}`);lines.push("Connection: close","","");return lines.join("\r\n")}function responseParser(collected,onHead,onChunk){const parser=new HTTPParser;parser.initialize(HTTPParser.RESPONSE,null,0,0);parser[HTTPParser.kOnHeadersComplete]=(_major,_minor,headers,_method,_url2,statusCode,statusMessage,upgrade)=>{if(collected.complete)return 0;collected.statusCode=statusCode;collected.statusMessage=statusMessage;collected.upgrade=upgrade;for(let index2=0;index2+1<headers.length;index2+=2){const name=headers[index2].toLowerCase();const value=headers[index2+1];collected.headers[name]=collected.headers[name]===void 0?value:`${collected.headers[name]}, ${value}`}onHead==null?void 0:onHead();return 0};parser[HTTPParser.kOnBody]=chunk=>{if(collected.complete)return;if(onChunk)onChunk(chunk);else collected.chunks.push(chunk)};parser[HTTPParser.kOnMessageComplete]=()=>{if(collected.complete)return collected.upgrade?0:-1;collected.complete=true;if(collected.upgrade)return 0;parser.pause();return-1};return parser}function emptyCollected(){return{statusCode:0,statusMessage:"",headers:{},chunks:[],complete:false,upgrade:false}}function ownedConcat(chunks){let total=0;for(const chunk of chunks)total+=chunk.byteLength;const joined=new Uint8Array(total);let at22=0;for(const chunk of chunks){joined.set(new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength),at22);at22+=chunk.byteLength}return joined}function serviceUnavailable(port2){return{statusCode:503,statusMessage:"Service Unavailable",headers:{"Content-Type":"text/plain"},body:ownedConcat([Buffer$9.from(`No server listening on port ${port2}`)])}}function __requestOverLoopback(port2,method,url2,headers,body){if(!__listening(port2))return Promise.resolve(serviceUnavailable(port2));return new Promise(resolve2=>{const collected=emptyCollected();const parser=responseParser(collected);let settled=false;const answer2=()=>{if(settled)return;settled=true;parser.free();resolve2({statusCode:collected.statusCode||502,statusMessage:collected.statusMessage,headers:collected.headers,body:ownedConcat(collected.chunks)})};const socket=netModule.connect({port:port2,host:"127.0.0.1"});socket.on("data",chunk=>{if(settled)return;const read=parser.execute(chunk);if(read instanceof Error){socket.destroy();answer2()}else if(collected.complete){socket.destroy();answer2()}});socket.on("end",()=>{if(!settled){parser.finish()}answer2()});socket.on("close",answer2);socket.on("error",()=>{if(settled)return;settled=true;parser.free();resolve2(serviceUnavailable(port2))});socket.write(requestHead(method,url2,headers,body));if(body&&body.length>0)socket.write(body)})}function __streamOverLoopback(port2,method,url2,headers,body,onStart,onChunk,onEnd,flow){if(!__listening(port2)){onStart(503,"Service Unavailable",{"Content-Type":"text/plain"});onEnd();return Promise.resolve()}return new Promise(resolve2=>{var _a22;const collected=emptyCollected();let started2=false;let ended2=false;const finish=()=>{if(ended2)return;ended2=true;parser.free();onEnd();resolve2()};const parser=responseParser(collected,()=>{started2=true;onStart(collected.statusCode,collected.statusMessage,collected.headers)},chunk=>onChunk(chunk));const socket=netModule.connect({port:port2,host:"127.0.0.1"});(_a22=flow==null?void 0:flow.control)==null?void 0:_a22.call(flow,()=>socket.pause(),()=>socket.resume());if(flow==null?void 0:flow.signal){if(flow.signal.aborted){socket.destroy();finish();return}flow.signal.addEventListener("abort",()=>{socket.destroy();finish()},{once:true})}socket.on("data",chunk=>{if(ended2)return;const read=parser.execute(chunk);if(read instanceof Error){socket.destroy();finish()}else if(collected.complete){socket.destroy();finish()}});socket.on("end",()=>{if(!ended2){parser.finish()}finish()});socket.on("close",finish);socket.on("error",()=>{if(!started2)onStart(503,"Service Unavailable",{"Content-Type":"text/plain"});finish()});socket.write(requestHead(method,url2,headers,body));if(body&&body.length>0)socket.write(body)})}function __upgradeOverLoopback(port2,method,url2,headers){if(!__listening(port2)){return Promise.resolve({statusCode:503,statusMessage:"Service Unavailable",headers:{},socket:null})}return new Promise(resolve2=>{const collected=emptyCollected();let settled=false;const parser=responseParser(collected);const socket=netModule.connect({port:port2,host:"127.0.0.1"});const fail3=()=>{if(settled)return;settled=true;parser.free();resolve2({statusCode:collected.statusCode||502,statusMessage:collected.statusMessage,headers:collected.headers,socket:null})};socket.on("data",chunk=>{if(settled)return;const read=parser.execute(chunk);if(read instanceof Error){socket.destroy();fail3();return}if(collected.upgrade||collected.statusCode===101){settled=true;parser.free();const consumed=typeof read==="number"?read:chunk.length;const rest=chunk.subarray(consumed);if(rest.length>0)socket.unshift(rest);resolve2({statusCode:collected.statusCode,statusMessage:collected.statusMessage,headers:collected.headers,socket});return}if(collected.complete){socket.destroy();fail3()}});socket.on("error",fail3);socket.on("close",fail3);const upgradeHeaders={...headers,Connection:"Upgrade"};const lines=[`${method.toUpperCase()} ${url2} HTTP/1.1`];for(const[name,value]of Object.entries(upgradeHeaders)){if(name.toLowerCase()==="connection")continue;lines.push(`${name}: ${value}`)}lines.push("Connection: Upgrade","","");socket.write(lines.join("\r\n"))})}var _encoder2=new TextEncoder;function guestListeningServer(port2,address){const hostname2=address;return{listening:true,address:()=>({port:port2,address:hostname2,family:hostname2.includes(":")?"IPv6":"IPv4"}),handleRequest:(method,url2,headers,body)=>__requestOverLoopback(port2,method,url2,headers,typeof body==="string"?Buffer$9.from(body):body)}}var __substrateUpgradeSockets=new Map;function __substrateFrame(opcode,payload,masked){const length=payload.length;const header=[128|opcode];if(length<126)header.push(128|length);else if(length<65536)header.push(128|126,length>>8,length&255);else header.push(128|127,0,0,0,0,length>>>24&255,length>>>16&255,length>>>8&255,length&255);const mask=[Math.random()*256|0,Math.random()*256|0,Math.random()*256|0,Math.random()*256|0];const out=new Uint8Array(header.length+mask.length+length);out.set(header,0);out.set(mask,header.length);for(let index2=0;index2<length;index2+=1)out[header.length+mask.length+index2]=payload[index2]^mask[index2&3];return out}function __substrateParseFrames(state,chunk,onFrame){const joined=state.pending.length?new Uint8Array([...state.pending,...chunk]):chunk;let offset2=0;for(;;){if(joined.length-offset2<2)break;const b02=joined[offset2],b12=joined[offset2+1];const fin=(b02&128)!==0,opcode=b02&15,masked=(b12&128)!==0;let length=b12&127,at22=offset2+2;if(length===126){if(joined.length-at22<2)break;length=joined[at22]<<8|joined[at22+1];at22+=2}else if(length===127){if(joined.length-at22<8)break;length=0;for(let index2=0;index2<8;index2+=1)length=length*256+joined[at22+index2];at22+=8}let mask;if(masked){if(joined.length-at22<4)break;mask=joined.subarray(at22,at22+4);at22+=4}if(joined.length-at22<length)break;const payload=joined.slice(at22,at22+length);if(mask)for(let index2=0;index2<length;index2+=1)payload[index2]^=mask[index2&3];offset2=at22+length;if(opcode===0&&state.fragments){state.fragments.parts.push(payload);if(fin){const parts=state.fragments.parts;const total=parts.reduce((sum,part)=>sum+part.length,0);const whole=new Uint8Array(total);let cursor=0;for(const part of parts){whole.set(part,cursor);cursor+=part.length}const op2=state.fragments.opcode;state.fragments=null;onFrame(op2,whole)}}else if(!fin&&(opcode===1||opcode===2))state.fragments={opcode,parts:[payload]};else onFrame(opcode,payload)}state.pending=joined.slice(offset2)}function __substrateUpgradeSocket(entry,socket){const end=socket;const bridge={push:frame=>{socket.write(frame)},destroy:()=>{socket.destroy()},get destroyed(){return socket.destroyed},onData:listener=>{socket.on("data",listener)}};let closed=false;const state={pending:new Uint8Array(0),fragments:null};const decoder22=new TextDecoder;const finish=(code22,reason)=>{if(closed)return;closed=true;__substrateUpgradeSockets.delete(entry.clientId);entry.channel.postMessage({type:"close",targetClient:entry.clientId,code:code22,reason})};const receive2=frame=>{if(!bridge.destroyed)bridge.push(frame)};bridge.onData(chunk=>{const bytes2=chunk;__substrateParseFrames(state,bytes2,(opcode,payload)=>{if(opcode===1)entry.channel.postMessage({type:"message",targetClient:entry.clientId,payload:decoder22.decode(payload)});else if(opcode===2)entry.channel.postMessage({type:"message",targetClient:entry.clientId,payload:payload.buffer.slice(payload.byteOffset,payload.byteOffset+payload.byteLength)});else if(opcode===8){const code22=payload.length>=2?payload[0]<<8|payload[1]:1005;finish(code22===1005?1e3:code22,payload.length>2?decoder22.decode(payload.subarray(2)):"");end.destroy()}else if(opcode===9)receive2(__substrateFrame(10,payload))})});end.on("close",()=>{finish(1e3,"");bridge.destroy()});end.deliver=payload=>{if(closed||end.destroyed)return;const bytes2=typeof payload==="string"?_encoder2.encode(payload):new Uint8Array(payload);receive2(__substrateFrame(typeof payload==="string"?1:2,bytes2))};end.disconnect=(code22,reason)=>{if(closed||end.destroyed)return;const text=_encoder2.encode(reason||"");const payload=new Uint8Array(2+text.length);payload[0]=code22>>8;payload[1]=code22&255;payload.set(text,2);receive2(__substrateFrame(8,payload));setTimeout(()=>{finish(code22,reason||"");end.destroy()},50)};return end}function __substrateRawUpgradeSocket(entry,socket){const end=socket;const bridge={push:data2=>{socket.write(data2)},destroy:()=>{socket.destroy()},end:()=>{socket.end()},get destroyed(){return socket.destroyed},onData:listener=>{socket.on("data",listener)}};let closed=false;const finish=(code22,reason)=>{if(closed)return;closed=true;__substrateUpgradeSockets.delete(entry.clientId);entry.channel.postMessage({type:"close",targetClient:entry.clientId,code:code22,reason})};bridge.onData(chunk=>{if(closed)return;entry.channel.postMessage({type:"message",targetClient:entry.clientId,payload:chunk.buffer.slice(chunk.byteOffset,chunk.byteOffset+chunk.byteLength)})});end.on("close",()=>{finish(1e3,"");bridge.destroy()});end.deliver=payload=>{if(closed||end.destroyed||bridge.destroyed)return;bridge.push(typeof payload==="string"?_encoder2.encode(payload):new Uint8Array(payload))};end.disconnect=(code22,reason)=>{if(closed||end.destroyed)return;bridge.end();finish(code22,reason||"");end.destroy()};return end}function __substrateListenForUpgrades(bridge){var _a22;if(typeof BroadcastChannel==="undefined")return null;const channel=new BroadcastChannel("vite-ws-channel");(_a22=channel.unref)==null?void 0:_a22.call(channel);channel.addEventListener("message",event=>{const data2=event.data;if(!data2||typeof data2!=="object")return;if(data2.type==="connect"){let url2;try{url2=new URL(data2.url)}catch{return}const port2=Number(url2.port);if(!__listening(port2))return;const record={clientId:data2.clientId,channel};const raw=data2.framing==="none";const key=uint8ToBase64(crypto.getRandomValues(new Uint8Array(16)));const protocols=Array.isArray(data2.protocols)?data2.protocols:[];void __upgradeOverLoopback(port2,"GET",url2.pathname+url2.search,{Host:typeof data2.host==="string"&&/^(?:\[[0-9a-f:.]+\]|[a-z0-9.-]+)(?::[0-9]{1,5})?$/iu.test(data2.host)?data2.host:url2.host,Upgrade:"websocket","Sec-WebSocket-Version":"13","Sec-WebSocket-Key":key,...protocols.length?{"Sec-WebSocket-Protocol":protocols.join(", ")}:{},...typeof data2.origin==="string"&&/^https?:\/\/[^/]+$/u.test(data2.origin)?{Origin:data2.origin}:{}}).then(result=>{if(result.statusCode!==101||!result.socket){channel.postMessage({type:"close",targetClient:data2.clientId,code:1006,reason:"upgrade refused"});return}const socket=raw?__substrateRawUpgradeSocket(record,result.socket):__substrateUpgradeSocket(record,result.socket);__substrateUpgradeSockets.set(data2.clientId,socket);channel.postMessage({type:"connected",targetClient:data2.clientId,protocol:result.headers["sec-websocket-protocol"]??(raw?protocols[0]??"":"")})})}else if(data2.type==="message"){const socket=__substrateUpgradeSockets.get(data2.clientId);if(socket)socket.deliver(data2.payload)}else if(data2.type==="disconnect"){const socket=__substrateUpgradeSockets.get(data2.clientId);if(socket)socket.disconnect(typeof data2.code==="number"?data2.code:1e3,typeof data2.reason==="string"?data2.reason:"")}});return channel}var ServerBridge=class extends PortBridge{constructor(options={}){super(options);__publicField2(this,"upgradeChannel",null);__publicField2(this,"guestServers",new WeakSet);this.watchGuestPorts();this.upgradeChannel=__substrateListenForUpgrades()}watchGuestPorts(){setPortWatchers((port2,address)=>{if(this.servers.has(port2))return;const hostname2=address||"0.0.0.0";const server=guestListeningServer(port2,hostname2);this.guestServers.add(server);this.registerServer(server,port2,hostname2)},port2=>{const entry=this.servers.get(port2);if(entry&&(entry.server===null||this.guestServers.has(entry.server))){if(entry.server)entry.server.listening=false;this.unregisterServer(port2)}})}close(){if(this.upgradeChannel){try{this.upgradeChannel.close()}catch{}this.upgradeChannel=null}super.close()}isGuest(entry){return entry.server===null||this.guestServers.has(entry.server)}requestGuest(port2,method,url2,headers,body){return __requestOverLoopback(port2,method,url2,headers,body)}streamGuest(port2,method,url2,headers,body,onStart,onChunk,onEnd,flow){return __streamOverLoopback(port2,method,url2,headers,body,onStart,onChunk,onEnd,flow)}bodyOf(bytes2){return Buffer$9.from(bytes2)}};var globalBridge=null;function getServerBridge(options){if(!globalBridge){globalBridge=new ServerBridge(options)}return globalBridge}function resetServerBridge(){globalBridge=null}var scopes=new WeakMap;var liveScopes=new Set;var NativeStreamScope=class{constructor(limits,emit2,ownerPid){__publicField2(this,"entries",new Map);__publicField2(this,"descriptors",new Map);__publicField2(this,"writes",new Map);__publicField2(this,"connects",new Map);__publicField2(this,"nextId",1);__publicField2(this,"pendingWriteBytes",0);__publicField2(this,"disposed",false);__publicField2(this,"limits");this.emit=emit2;this.ownerPid=ownerPid;if([limits.maxHandles,limits.maxReadChunkBytes,limits.maxQueuedBytes,limits.maxQueuedHandles,limits.maxPendingWriteBytes].some(value=>!Number.isSafeInteger(value)||value<1)||limits.maxReadChunkBytes>2147483647||limits.maxReadChunkBytes>limits.maxQueuedBytes||limits.maxReadChunkBytes>limits.maxPendingWriteBytes)throw new Error("Invalid native stream resource limits.");this.limits=Object.freeze({...limits});liveScopes.add(this)}handles(){var _a22;if(this.disposed)return[];const pid=(_a22=this.ownerPid)==null?void 0:_a22.call(this);return[...this.entries.values()].map(({handle,descriptor})=>({...pid!==void 0?{pid}:{},id:descriptor.id,kind:descriptor.kind,listening:!!handle.listening}))}entry(id2){return this.disposed?void 0:this.entries.get(id2)}publish(event){if(this.disposed)return;try{this.emit(event)}catch(cause){try{this.dispose()}catch(cleanup){throw new AggregateError([cause,cleanup],"Native stream event delivery and cleanup failed.")}throw cause}}claim(handle){if(this.disposed||!Number.isSafeInteger(this.nextId)||this.entries.size>=this.limits.maxHandles||scopes.has(handle))return void 0;const descriptor={id:this.nextId++,kind:handle instanceof TCP?"tcp":"pipe",type:handle.type};const entry={handle,descriptor};this.entries.set(descriptor.id,entry);scopes.set(handle,this);__adoptHandle(handle,null);handle.onconnection=(status,accepted)=>{const incoming2=status===0?this.claim(accepted):void 0;if(status===0&&!incoming2)accepted.close();this.publish({type:"connection",id:descriptor.id,status:status||(incoming2?0:UV_EMFILE),...incoming2?{handle:incoming2}:{}})};handle.onread=buffer2=>{const count=streamBaseState[kReadBytesOrError];const offset2=streamBaseState[kArrayBufferOffset];handle.readStop();const sent=handle.pendingHandle;handle.pendingHandle=null;let incoming2;if(sent!=null){if((sent instanceof TCP||sent instanceof Pipe)&&!sent.listening)incoming2=this.claim(sent);if(!incoming2){if(sent instanceof LibuvStreamWrap&&!scopes.has(sent)&&!sent.listening)sent.close();this.publish({type:"read",id:descriptor.id,status:UV_ENOTSUP});this.close(descriptor.id);return}}const bytes2=count>0?(buffer2?new Uint8Array(buffer2,offset2,count):entry.buffer.subarray(0,count)).slice():void 0;this.publish({type:"read",id:descriptor.id,status:count,...bytes2?{bytes:bytes2}:{},...incoming2?{handle:incoming2}:{}})};return{...descriptor}}call(operation){var _a22,_b22;if(this.disposed)return{status:UV_EBADF};if(operation.operation==="fdType"){if(!Number.isInteger(operation.fd)||operation.fd<0)return{status:UV_EINVAL};const id2=this.descriptors.get(operation.fd);const entry2=id2===void 0?void 0:this.entry(id2);return entry2?{status:0,handleType:entry2.descriptor.kind==="tcp"?"TCP":"PIPE"}:{status:UV_EBADF}}if(operation.operation==="create"){if(this.entries.size>=this.limits.maxHandles)return{status:UV_EMFILE};if(operation.kind!=="tcp"&&operation.kind!=="pipe"||!Number.isInteger(operation.type)||operation.type<0||operation.type>(operation.kind==="pipe"?2:1))return{status:UV_EINVAL};const handle2=operation.kind==="tcp"?new TCP(operation.type):new Pipe(operation.type);const descriptor=this.claim(handle2);if(!descriptor){handle2.close();return{status:UV_EMFILE}}return{status:0,handle:descriptor}}const entry=this.entry(operation.id);if(!entry)return{status:UV_EBADF};const handle=entry.handle;switch(operation.operation){case"duplicate":{if(handle.listening)return{status:UV_ENOTSUP};if(this.entries.size>=this.limits.maxHandles)return{status:UV_EMFILE};const copy2=handle.duplicate();const descriptor=this.claim(copy2);if(!descriptor){copy2.close();return{status:UV_EMFILE}}return{status:0,handle:descriptor}}case"pair":{const other=(_a22=this.entry(operation.peer))==null?void 0:_a22.handle;if(!other||handle.peer||other.peer||handle.listening||other.listening||other===handle)return{status:UV_EINVAL};LibuvStreamWrap.pair(handle,other);return{status:0}}case"bind":{if(typeof operation.address!=="string")return{status:UV_EINVAL};if(handle instanceof Pipe)return{status:handle.bind(operation.address)};if(!Number.isInteger(operation.port)||operation.port<0||operation.port>65535)return{status:UV_EINVAL};return{status:operation.ipv6?handle.bind6(operation.address,operation.port,operation.flags):handle.bind(operation.address,operation.port,operation.flags)}}case"listen":return{status:Number.isInteger(operation.backlog)&&operation.backlog>=0?handle.listen(operation.backlog):UV_EINVAL};case"connect":{if(this.connects.has(operation.id))return{status:UV_EALREADY};if(typeof operation.address!=="string"||!Number.isSafeInteger(operation.request)||operation.request<1)return{status:UV_EINVAL};if(handle instanceof TCP&&(!Number.isInteger(operation.port)||operation.port<1||operation.port>65535))return{status:UV_EINVAL};this.connects.set(operation.id,operation.request);const request=handle instanceof TCP?new TCPConnectWrap:new PipeConnectWrap;request.oncomplete=status2=>{if(this.connects.get(operation.id)!==operation.request)return;this.connects.delete(operation.id);this.publish({type:"connect",id:operation.id,request:operation.request,status:status2})};const status=handle instanceof TCP?operation.ipv6?handle.connect6(request,operation.address,operation.port):handle.connect(request,operation.address,operation.port):handle.connect(request,operation.address);if(status!==0)this.connects.delete(operation.id);return{status}}case"open":{const inherited=this.descriptors.get(operation.fd);const held=inherited===void 0?void 0:this.entry(inherited);if(!held||held.descriptor.kind!==entry.descriptor.kind||handle.peer||handle.listening)return{status:UV_EBADF};if(held!==entry){if(handle instanceof TCP&&held.handle instanceof TCP){const local2={},remote={};if(held.handle.getsockname(local2)===0&&held.handle.getpeername(remote)===0)handle.adoptNames(local2,remote)}handle.takeOverFrom(held.handle);this.entries.delete(inherited);scopes.delete(held.handle);held.handle.close();this.descriptors.set(operation.fd,operation.id)}return{status:0}}case"readStart":entry.buffer??(entry.buffer=new Uint8Array(this.limits.maxReadChunkBytes));handle.useUserBuffer(entry.buffer);return{status:handle.readStart()};case"readStop":return{status:handle.readStop()};case"ref":handle.ref();return{status:0};case"unref":handle.unref();return{status:0};case"getsockname":case"getpeername":{if(!(handle instanceof TCP))return{status:UV_ENOTSUP};const address={};const status=handle[operation.operation](address);return{status,...status===0?{address}:{}}}case"shutdown":{if(!Number.isSafeInteger(operation.request)||operation.request<1)return{status:UV_EINVAL};if(this.writes.has(operation.id))return{status:UV_EBUSY};const request=new ShutdownWrap;request.oncomplete=status=>this.publish({type:"shutdown",id:operation.id,request:operation.request,status});return{status:handle.shutdown(request)}}case"reset":if(!Number.isSafeInteger(operation.request)||operation.request<1)return{status:UV_EINVAL};if(!(handle instanceof TCP))return{status:UV_ENOTSUP};(_b22=this.writes.get(operation.id))==null?void 0:_b22(UV_ECANCELED);return this.close(operation.id,operation.request,true);case"close":if(!Number.isSafeInteger(operation.request)||operation.request<1)return{status:UV_EINVAL};return this.close(operation.id,operation.request)}}write(id2,bytes2,sentId){var _a22,_b22;const handle=(_a22=this.entry(id2))==null?void 0:_a22.handle;if(!handle)return Promise.resolve(UV_EBADF);if(this.writes.has(id2))return Promise.resolve(UV_EBUSY);if(bytes2.byteLength>this.limits.maxReadChunkBytes||this.pendingWriteBytes+bytes2.byteLength>this.limits.maxPendingWriteBytes)return Promise.resolve(UV_ENOBUFS);const sent=sentId===void 0?void 0:(_b22=this.entry(sentId))==null?void 0:_b22.handle;if(sentId!==void 0&&!sent)return Promise.resolve(UV_EBADF);if(sent&&(!(handle instanceof Pipe)||sent.listening||bytes2.byteLength===0))return Promise.resolve(UV_ENOTSUP);const owned=new Uint8Array(bytes2.byteLength);owned.set(bytes2);const retained=sent==null?void 0:sent.duplicate();if(retained)__adoptHandle(retained,null);this.pendingWriteBytes+=owned.byteLength;return new Promise((resolve2,reject)=>{let ended2=false;let unsubscribe=()=>{};const finish=(status,failure)=>{if(ended2)return;ended2=true;unsubscribe();this.writes.delete(id2);this.pendingWriteBytes-=owned.byteLength;try{retained==null?void 0:retained.close()}catch(cause){reject(cause);return}if(failure!==void 0)reject(failure);else resolve2(status)};const attempt=()=>{if(ended2)return;if(handle.closed||this.disposed){finish(UV_ECANCELED);return}if(!handle.peer){finish(UV_EPIPE);return}if(handle.peerQueuedBytes+owned.byteLength>this.limits.maxQueuedBytes)return;if(retained&&handle.peerQueuedHandles>=this.limits.maxQueuedHandles)return;try{finish(handle.writeBuffer(new WriteWrap,owned,retained))}catch(cause){finish(UV_ECANCELED,cause)}};this.writes.set(id2,finish);unsubscribe=handle.onPeerReadCapacity(attempt);attempt()})}inherit(fd2,source,id2){var _a22;if(this.disposed||!Number.isInteger(fd2)||fd2<0||this.descriptors.has(fd2))return{status:UV_EINVAL};if(this.entries.size>=this.limits.maxHandles)return{status:UV_EMFILE};const handle=(_a22=source.entry(id2))==null?void 0:_a22.handle;if(!handle)return{status:UV_EBADF};if(handle.listening)return{status:UV_ENOTSUP};const copy2=handle.duplicate();const descriptor=this.claim(copy2);if(!descriptor){copy2.close();return{status:UV_EMFILE}}this.descriptors.set(fd2,descriptor.id);return{status:0,handle:descriptor}}close(id2,request,reset2=false){var _a22;const entry=this.entries.get(id2);if(!entry)return{status:UV_EBADF};(_a22=this.writes.get(id2))==null?void 0:_a22(UV_ECANCELED);const connecting=this.connects.get(id2);this.connects.delete(id2);if(connecting!==void 0)this.publish({type:"connect",id:id2,request:connecting,status:UV_ECANCELED});this.entries.delete(id2);scopes.delete(entry.handle);for(const[fd2,held]of this.descriptors)if(held===id2)this.descriptors.delete(fd2);const complete=request===void 0?void 0:()=>this.publish({type:"close",id:id2,request,status:0});if(reset2)entry.handle.reset(complete);else entry.handle.close(complete);return{status:0}}dispose(){if(this.disposed)return;this.disposed=true;liveScopes.delete(this);const failures=[];for(const id2 of[...this.entries.keys()]){try{this.close(id2)}catch(cause){failures.push(cause)}}if(failures.length)throw new AggregateError(failures,"Native stream scope cleanup failed.")}};function nativeStreamOwnerPid(handle){var _a22,_b22;return(_b22=(_a22=scopes.get(handle))==null?void 0:_a22.ownerPid)==null?void 0:_b22.call(_a22)}function nativeStreamHandles(){return[...liveScopes].flatMap(scope4=>scope4.handles())}var __nextRunName=1;function createContainer(options){const vfs2=options&&options.vfs||new VirtualFS;const runtime=new Runtime(vfs2,options);const npmManager=new PackageManager(vfs2);const serverBridge=new ServerBridge({baseUrl:options==null?void 0:options.baseUrl,onServerReady:options==null?void 0:options.onServerReady});return{vfs:vfs2,runtime,npm:npmManager,serverBridge,execute:(code22,filename)=>runtime.execute(code22,filename),runFile:filename=>runtime.runFile(filename),run:(command,runOptions)=>{var _a22;if((_a22=runOptions==null?void 0:runOptions.signal)==null?void 0:_a22.aborted){return Promise.resolve({stdout:"",stderr:"",exitCode:130})}const processToken=typeof(runOptions==null?void 0:runOptions.processToken)==="string"&&runOptions.processToken.length>0?runOptions.processToken:`run-${__nextRunName++}`;registerRunStreams(processToken,{onStdout:runOptions==null?void 0:runOptions.onStdout,onStderr:runOptions==null?void 0:runOptions.onStderr,signal:runOptions==null?void 0:runOptions.signal,held:(runOptions==null?void 0:runOptions.held)===true,stdinStream:runOptions==null?void 0:runOptions.stdinStream,stdinOpen:(runOptions==null?void 0:runOptions.stdinStream)!==void 0,terminal:runOptions==null?void 0:runOptions.terminal});return new Promise(resolve2=>{runCommand(command,{cwd:runOptions==null?void 0:runOptions.cwd,env:runOptions==null?void 0:runOptions.env,stdin:typeof(runOptions==null?void 0:runOptions.stdin)==="string"?runOptions.stdin:void 0,processToken,vfs:vfs2},(error,stdout,stderr)=>{var _a32;releaseRunStreams(processToken);const terminatedBy=__takeTermination(processToken);resolve2({stdout:String(stdout),stderr:String(stderr),exitCode:((_a32=runOptions==null?void 0:runOptions.signal)==null?void 0:_a32.aborted)?143:error?error.code??1:0,...terminatedBy?{signal:terminatedBy}:{}})})})},pendingTimers:token=>{var _a22;return((_a22=__runFor(token))==null?void 0:_a22.pendingTimers())??0},processPorts:token=>__ownedServerPorts(token),portPid:port2=>{var _a22;const listener=listenerOnPort(port2);if(!listener)return void 0;return((_a22=runPid(ownerOf(listener)))==null?void 0:_a22.pid)??nativeStreamOwnerPid(listener)},streamHandles:()=>nativeStreamHandles(),signalProcess:(token,signal)=>__signalOwnedProcess(token,signal),stopProcess:token=>{const known=__runFor(token)!==void 0||__ownedServerPorts(token).length>0;__releaseOwnedServers(token,false);__releaseOwnedHandles(token);__stopOwnedProcess(token);return known},sendInput:(data2,token)=>sendStdin(data2,token),currentProcessToken:()=>__currentProcessToken(),runPid:token=>runPid(token===void 0?__currentProcessToken():token),processByPid,listenNet:(port2,onConnection)=>{const server=new Server(onConnection);server.listen(port2);__adoptHandle(server._handle,null);return()=>{server.close()}},createREPL:()=>runtime.createREPL(),on:(event,listener)=>{serverBridge.on(event,listener)}}}if(!Object.getOwnPropertyDescriptor(globalThis,"Buffer")){Object.defineProperty(globalThis,"Buffer",{configurable:true,enumerable:false,get:()=>bufferModule.Buffer})}function normalizeProcessFilesystemPolicy(value){if(!value||typeof value!=="object"||Object.keys(value).some(key=>key!=="writableRoots")||!Array.isArray(value.writableRoots)||value.writableRoots.length>128){throw new TypeError("Invalid process filesystem policy: expected up to 128 writableRoots.")}const roots=[...new Set(Array.from(value.writableRoots,absolutePolicyPath))].sort();return Object.freeze({writableRoots:Object.freeze(roots.filter(root2=>!roots.some(other=>other!==root2&&within(root2,other))))})}function intersectProcessFilesystemPolicies(parent,child){const inherited=normalizeProcessFilesystemPolicy(parent);if(child===void 0)return inherited;const requested=normalizeProcessFilesystemPolicy(child);return normalizeProcessFilesystemPolicy({writableRoots:inherited.writableRoots.flatMap(left=>requested.writableRoots.flatMap(right=>within(left,right)?[left]:within(right,left)?[right]:[]))})}function createProcessFilesystemMutationGuard(filesystem,requested){const policy=normalizeProcessFilesystemPolicy(requested);const permitted=path3=>policy.writableRoots.some(root2=>within(path3,root2));return input=>{const path3=absolutePolicyPath(input);if(!permitted(path3))deny(path3);let current3="";for(const part of path3.split("/").filter(Boolean)){current3+=`/${part}`;try{if(filesystem.lstatSync(current3).isSymbolicLink())deny(path3)}catch(error){if(error.code!=="ENOENT")throw error;if(!permitted(current3))deny(current3)}}return path3}}function absolutePolicyPath(path3){if(typeof path3!=="string"||!path3.startsWith("/")||path3.includes("\0")||path3.length>8192){throw new TypeError("Filesystem policy paths must be absolute paths without NUL bytes.")}const parts=[];for(const part of path3.split("/")){if(part==="..")parts.pop();else if(part&&part!==".")parts.push(part)}return`/${parts.join("/")}`}function within(path3,root2){return root2==="/"||path3===root2||path3.startsWith(`${root2}/`)}function deny(path3){throw Object.assign(new Error(`EACCES: process filesystem policy denies mutation of '${path3}'`),{code:"EACCES",path:path3})}async function forwardBrowserProcessInput(input,receive2,signal){signal.throwIfAborted();const iterator=input[Symbol.asyncIterator]();let finished=false;let rejectCancellation;const cancellation=new Promise((_resolve,reject)=>{rejectCancellation=reject});void cancellation.catch(()=>void 0);const abort=()=>rejectCancellation(signal.reason??new DOMException("Process input was cancelled.","AbortError"));signal.addEventListener("abort",abort,{once:true});try{for(;;){signal.throwIfAborted();const next2=await Promise.race([iterator.next(),cancellation]);signal.throwIfAborted();if(next2.done){finished=true;return}await Promise.race([Promise.resolve(receive2(next2.value)),cancellation])}}finally{signal.removeEventListener("abort",abort);if(!finished)void Promise.resolve().then(()=>iterator.return?.()).catch(()=>void 0)}}var BrowserProcessInputPipe=class{queued;ended=false;reading=false;failure;wake;write(bytes2){if(this.ended)return Promise.reject(this.failure??new Error("Process input is closed."));if(this.queued)return Promise.reject(new Error("Wait for the previous process input chunk to be consumed."));const consumed=new Promise((resolve2,reject)=>{this.queued={bytes:Uint8Array.from(bytes2),resolve:resolve2,reject}});this.notify();return consumed}end(){this.ended=true;this.notify()}cancel(cause=new DOMException("Process input was cancelled.","AbortError")){this.failure=cause;this.ended=true;this.queued?.reject(cause);this.queued=void 0;this.notify()}notify(){const wake=this.wake;this.wake=void 0;wake?.()}async*[Symbol.asyncIterator](){if(this.reading)throw new Error("Process input already has a reader.");this.reading=true;try{for(;;){if(this.failure!==void 0)throw this.failure;const next2=this.queued;if(next2){this.queued=void 0;next2.resolve();yield next2.bytes}else if(this.ended)return;else await new Promise(resolve2=>{this.wake=resolve2})}}finally{this.cancel()}}};function parseCommandWords(command){const words=[];let word="";let quote2="";let escaped=false;for(const character of command.trim()){if(escaped){word+=character;escaped=false;continue}if(character==="\\"&&quote2!=="'"){escaped=true;continue}if(quote2){if(character===quote2)quote2="";else word+=character;continue}if(character==="'"||character==='"'){quote2=character;continue}if(/\s/u.test(character)){if(word){words.push(word);word=""}continue}if(/[|&;<>]/u.test(character))throw new Error("Shell operators require the shell runtime.");word+=character}if(escaped||quote2)throw new Error("Unterminated command quoting.");if(word)words.push(word);return words}function renderCommand(argv){return argv.map(value=>/^[A-Za-z0-9_./:@%+=,-]+$/u.test(value)?value:`'${value.replaceAll("'",`'\\''`)}'`).join(" ")}var PageNetSocketImpl=class{constructor(id2,post,onClosed){this.id=id2;this.post=post;this.onClosed=onClosed}id;post;onClosed;listeners=new Map;ended=false;outstanding=0;drainWaiters=[];on(event,listener){const list2=this.listeners.get(event)??[];list2.push(listener);this.listeners.set(event,list2);return this}write(chunk,done){if(this.ended)return false;const buffer2=Uint8Array.from(chunk).buffer;this.outstanding+=1;this.post({type:"net-data",socket:this.id,chunk:buffer2},[buffer2]);done?.();return true}taken(){this.outstanding=Math.max(0,this.outstanding-1);for(const waiter of[...this.drainWaiters]){if(this.outstanding>=waiter.below)continue;this.drainWaiters.splice(this.drainWaiters.indexOf(waiter),1);waiter.resume()}}drained(below){if(this.ended||this.outstanding<below)return Promise.resolve();return new Promise(resume=>this.drainWaiters.push({below,resume}))}end(){if(!this.ended){this.post({type:"net-end",socket:this.id});this.finish()}return this}destroy(){return this.end()}receive(chunk){if(this.ended)return;for(const listener of this.listeners.get("data")??[])listener(chunk)}finish(){if(this.ended)return;this.ended=true;this.onClosed();for(const waiter of this.drainWaiters.splice(0))waiter.resume();const listeners=[...this.listeners.get("end")??[],...this.listeners.get("close")??[]];this.listeners.clear();for(const listener of listeners)listener(void 0)}};var STATE=0;var STATUS=1;var PID=2;var PPID=3;var IDLE=0;var REQUEST=1;var WRITING=2;var DONE3=3;var CLOSED=4;var TIMEOUT_MS=3e4;var STREAM_REPLY_BYTES=4096;function serveNodeProcessRegistry(limits,ownerPid){if(limits)limits=Object.freeze({...limits});const streams2=limits?new NativeStreamScope(limits,event=>{const transfer2=event.type==="read"&&event.bytes?[event.bytes.buffer]:[];port1.postMessage({operation:"stream-event",event},transfer2)},ownerPid):void 0;const registry=createProcessRegistryScope();const{port1,port2}=new MessageChannel;const shared=new SharedArrayBuffer(4*Int32Array.BYTES_PER_ELEMENT);const control=new Int32Array(shared);const reply=limits?new SharedArrayBuffer(STREAM_REPLY_BYTES):void 0;const encoder7=new TextEncoder;let disposed=false;const dispose=()=>{if(disposed)return;disposed=true;Atomics.store(control,STATE,CLOSED);Atomics.notify(control,STATE);try{port1.postMessage({operation:"closed"})}finally{try{streams2?.dispose()}finally{registry.dispose();port1.onmessage=null;port1.onmessageerror=null;port1.close();port2.close()}}};port1.onmessage=({data:data2})=>{if(disposed)return;if(!data2||typeof data2!=="object"){dispose();return}if(data2.operation==="close"){dispose();return}if(data2.operation==="stream-write"){if(!streams2||!limits||!Number.isSafeInteger(data2.request)||data2.request<1||!Number.isSafeInteger(data2.id)||data2.id<1||data2.handle!==void 0&&(!Number.isSafeInteger(data2.handle)||data2.handle<1)||!(data2.bytes instanceof Uint8Array)||data2.bytes.byteLength>limits.maxReadChunkBytes){dispose();return}try{void streams2.write(data2.id,data2.bytes,data2.handle).then(status2=>{if(!disposed)port1.postMessage({operation:"stream-written",request:data2.request,status:status2})}).catch(()=>dispose())}catch{dispose()}return}if(data2.operation==="stream-post"){const call=data2.call;const closing=call?.operation==="close"||call?.operation==="reset"||call?.operation==="shutdown";if(!streams2||call?.operation!=="readStart"&&!closing||!Number.isSafeInteger(call.id)||call.id<1||closing&&(!Number.isSafeInteger(call.request)||call.request<1)){dispose();return}try{const{status:status2}=streams2.call(call);if(status2!==0){port1.postMessage({operation:"stream-event",event:closing?{type:call.operation==="shutdown"?"shutdown":"close",id:call.id,request:call.request,status:status2}:{type:"read",id:call.id,status:status2}})}}catch{dispose()}return}if(Atomics.compareExchange(control,STATE,REQUEST,WRITING)!==REQUEST)return;let identity;let replyLength=0;let status=0;try{switch(data2.operation){case"allocate":identity={pid:registry.allocate(),ppid:0};break;case"publish":if(typeof data2.token!=="string")throw new Error("Invalid process token.");registry.publish(data2.token,{pid:data2.pid,ppid:data2.ppid,...data2.argv!==void 0?{argv:data2.argv}:{},...data2.cwd!==void 0?{cwd:data2.cwd}:{},...data2.startedAt!==void 0?{startedAt:data2.startedAt}:{}});break;case"forget":if(typeof data2.token!=="string")throw new Error("Invalid process token.");registry.forget(data2.token);break;case"lookup":identity=registry.lookup(data2.pid);break;case"signal":if(!Number.isSafeInteger(data2.pid)||typeof data2.signal!=="string"||!/^SIG[A-Z0-9]{1,12}$/u.test(data2.signal)){throw new Error("Invalid process signal.")}identity=registry.signal(data2.pid,data2.signal)?{pid:data2.pid,ppid:0}:void 0;break;case"stream-call":{if(!streams2||!reply)throw new Error("Native stream transport was not granted.");const result=streams2.call(data2.call);const bytes2=encoder7.encode(JSON.stringify(result));if(bytes2.byteLength>reply.byteLength)throw new Error("Native stream reply exceeds its bound.");new Uint8Array(reply).set(bytes2);replyLength=bytes2.byteLength;break}default:throw new Error("Unknown process registry operation.")}}catch{if(data2.operation==="stream-call"){dispose();return}status=1}Atomics.store(control,STATUS,status);Atomics.store(control,PID,data2.operation==="stream-call"?replyLength:identity?.pid??0);Atomics.store(control,PPID,identity?.ppid??0);if(Atomics.compareExchange(control,STATE,WRITING,DONE3)===WRITING)Atomics.notify(control,STATE);else dispose()};port1.onmessageerror=dispose;port1.start();return{registry,channel:{port:port2,control:shared,...reply&&limits?{streams:{reply,limits}}:{}},...streams2?{streams:streams2}:{},dispose}}function exchange(channel,request,read){const control=new Int32Array(channel.control);if(Atomics.compareExchange(control,STATE,IDLE,REQUEST)!==IDLE)throw new Error("Process owner channel is unavailable.");let result;let status;try{channel.port.postMessage(request);const deadline=performance.now()+TIMEOUT_MS;for(;;){const state=Atomics.load(control,STATE);if(state===DONE3)break;if(state===CLOSED)throw new Error("Process owner stopped.");const remaining=deadline-performance.now();if(remaining<=0)throw new Error("Process owner did not answer within 30 seconds.");Atomics.wait(control,STATE,state,remaining)}status=Atomics.load(control,STATUS);result=read(control);if(Atomics.compareExchange(control,STATE,DONE3,IDLE)!==DONE3)throw new Error("Process owner stopped.")}catch(cause){Atomics.store(control,STATE,CLOSED);try{channel.port.postMessage({operation:"close"})}finally{channel.port.close()}throw cause}if(status!==0)throw new Error("Process owner refused an invalid or unowned identity.");return result}var NodeProcessRegistryClient=class{constructor(channel){this.channel=channel;if(channel.streams)this.streams=this.native=new NodeNativeStreamClient(channel)}channel;streams;native;allocate(){return this.call({operation:"allocate"}).pid}publish(token,identity){this.call({operation:"publish",token,...identity})}forget(token){this.call({operation:"forget",token})}lookup(pid){return this.call({operation:"lookup",pid})}signal(pid,signal){return this.call({operation:"signal",pid,signal})!==void 0}call(request){try{return exchange(this.channel,request,control=>{const pid=Atomics.load(control,PID);return pid===0?void 0:{pid,ppid:Atomics.load(control,PPID)}})}catch(cause){if(Atomics.load(new Int32Array(this.channel.control),STATE)===CLOSED)this.native?.dispose();throw cause}}};var NodeNativeStreamClient=class{constructor(channel){this.channel=channel;if(!channel.streams)throw new Error("Native stream transport was not granted.");this.metadata=channel.streams;this.limits=Object.freeze({...channel.streams.limits});channel.port.addEventListener("message",this.receive);channel.port.addEventListener("messageerror",this.failed);channel.port.start()}channel;limits;listeners=new Set;pending=new Map;writing=new Set;queued=[];pendingBytes=0;nextRequest=1;stopped=false;metadata;call(operation){try{return exchange(this.channel,{operation:"stream-call",call:operation},control=>{const length=Atomics.load(control,PID);if(length<1||length>this.metadata.reply.byteLength)throw new Error("Invalid native stream reply length.");const bytes2=new Uint8Array(this.metadata.reply,0,length).slice();return JSON.parse(new TextDecoder().decode(bytes2))})}catch(cause){this.dispose();throw cause}}post(operation){if(this.stopped||Atomics.load(new Int32Array(this.channel.control),STATE)===CLOSED){this.dispose();throw new Error("Native stream owner stopped.")}this.channel.port.postMessage({operation:"stream-post",call:operation})}write(id2,bytes2,handle){if(this.stopped||Atomics.load(new Int32Array(this.channel.control),STATE)===CLOSED){this.dispose();return Promise.reject(new Error("Native stream owner stopped."))}if(this.writing.has(id2)||this.pending.size>=this.limits.maxHandles||bytes2.byteLength>this.limits.maxReadChunkBytes||!Number.isSafeInteger(this.nextRequest))return Promise.reject(new Error("Native stream write exceeds its transport limits."));const request=this.nextRequest++;return new Promise((resolve2,reject)=>{this.pending.set(request,{id:id2,bytes:bytes2.byteLength,resolve:resolve2,reject});this.writing.add(id2);this.queued.push({request,id:id2,bytes:bytes2,...handle===void 0?{}:{handle}});this.flushWrites()})}flushWrites(){while(!this.stopped&&this.queued.length){const next2=this.queued[0];if(this.pendingBytes+next2.bytes.byteLength>this.limits.maxPendingWriteBytes)return;this.queued.shift();const owned=new Uint8Array(next2.bytes.byteLength);owned.set(next2.bytes);this.pendingBytes+=owned.byteLength;try{this.channel.port.postMessage({operation:"stream-write",request:next2.request,id:next2.id,bytes:owned,...next2.handle===void 0?{}:{handle:next2.handle}},[owned.buffer])}catch{this.dispose()}}}onEvent(listener){if(this.stopped)throw new Error("Native stream owner stopped.");this.listeners.add(listener);return()=>{this.listeners.delete(listener)}}receive=({data:data2})=>{if(data2.operation==="closed"){this.dispose();return}if(data2.operation==="stream-event"){for(const listener of[...this.listeners])listener(data2.event)}else if(data2.operation==="stream-written"){const write=this.pending.get(data2.request);if(!write){this.dispose();return}this.pending.delete(data2.request);this.writing.delete(write.id);this.pendingBytes-=write.bytes;this.flushWrites();write.resolve(data2.status)}};failed=()=>{this.dispose()};dispose(){if(this.stopped)return;this.stopped=true;Atomics.store(new Int32Array(this.channel.control),STATE,CLOSED);try{this.channel.port.postMessage({operation:"close"})}finally{this.channel.port.removeEventListener("message",this.receive);this.channel.port.removeEventListener("messageerror",this.failed);this.channel.port.close();const cause=new Error("Native stream owner stopped.");for(const write of this.pending.values())write.reject(cause);this.pending.clear();this.queued.length=0;this.writing.clear();this.pendingBytes=0;const listeners=[...this.listeners];this.listeners.clear();const failures=[];for(const listener of listeners){try{listener({type:"closed"})}catch(error){failures.push(error)}}if(failures.length)throw new AggregateError(failures,"Native stream close delivery failed.")}}};var maximumChunk=64*1024;function validDescriptorNumber(fd2){return typeof fd2==="number"&&Number.isInteger(fd2)&&fd2>=3&&fd2<=63}var CrossOriginChildProcesses=class{constructor(run,send2){this.run=run;this.send=send2}run;send;children=new Map;disposed=false;receive(message){if(!["child-run","child-abort","child-stdin","child-stdin-end","child-resize","child-fd","child-fd-end"].includes(message.type))return false;if(this.disposed)return true;if(message.type==="child-run"){if(!Number.isSafeInteger(message.id)||message.id<1||this.children.has(message.id)){throw new Error("Invalid or duplicate child process identity.")}if(message.descriptors!==void 0&&(!Array.isArray(message.descriptors)||!message.descriptors.every(validDescriptorNumber)||new Set(message.descriptors).size!==message.descriptors.length)){throw new Error("Child process descriptors must be distinct integers from 3 through 63.")}void this.start(message).catch(cause=>console.error("Child process transport failed.",cause));return true}if(!("id"in message)||typeof message.id!=="number")return true;const child=this.children.get(message.id);if(!child)return true;if(message.type==="child-abort"){child.controller.abort();child.input?.cancel();for(const input of child.descriptors.values())input.cancel()}else if(message.type==="child-fd"||message.type==="child-fd-end"){const input=validDescriptorNumber(message.fd)?child.descriptors.get(message.fd):void 0;if(!input){child.controller.abort(new Error("Child process has no such descriptor."));return true}if(message.type==="child-fd-end"){input.end();return true}if(!(message.bytes instanceof ArrayBuffer)||message.bytes.byteLength>maximumChunk){const cause=new Error("Child process descriptor chunks must be at most 64 KiB.");child.controller.abort(cause);input.cancel(cause);return true}const fd2=message.fd;void input.write(new Uint8Array(message.bytes)).then(()=>{if(!this.disposed&&this.children.get(message.id)===child)this.send({type:"child-fd-consumed",id:message.id,fd:fd2})}).catch(cause=>{child.controller.abort(cause)})}else if(message.type==="child-stdin"){if(!child.input){child.controller.abort(new Error("Child process has no live input."));return true}if(message.bytes.byteLength>64*1024){const cause=new Error("Child process input chunks must be at most 64 KiB.");child.controller.abort(cause);child.input.cancel(cause);return true}void child.input.write(new Uint8Array(message.bytes)).then(()=>{if(!this.disposed&&this.children.get(message.id)===child)this.send({type:"child-input-consumed",id:message.id})}).catch(cause=>{if(!this.disposed&&this.children.get(message.id)===child)child.controller.abort(cause)})}else if(message.type==="child-stdin-end")child.input?.end();else if(message.type==="child-resize"&&child.terminal){child.terminal.columns=message.columns;child.terminal.rows=message.rows;for(const resize of[...child.resizes]){try{resize(message.columns,message.rows)}catch(cause){child.controller.abort(cause)}}}return true}detach(){this.close(false)}dispose(){this.close(true)}close(abort){if(this.disposed)return;this.disposed=true;for(const child of this.children.values()){if(abort){child.controller.abort();child.input?.cancel();for(const input of child.descriptors.values())input.cancel()}else{child.input?.end();for(const input of child.descriptors.values())input.end()}child.resizes.clear()}this.children.clear()}async start(message){const child={controller:new AbortController,resizes:new Set,descriptors:new Map((message.descriptors??[]).map(fd2=>[fd2,new BrowserProcessInputPipe])),...message.liveStdin?{input:new BrowserProcessInputPipe}:{}};if(message.terminal)child.terminal={...message.terminal,onResize:listener=>{child.resizes.add(listener);return()=>{child.resizes.delete(listener)}}};this.children.set(message.id,child);const descriptors={};for(const[fd2,input]of child.descriptors)descriptors[fd2]=this.descriptor(message.id,fd2,input,child);try{const result=await this.run(message,{...message.cwd!==void 0?{cwd:message.cwd}:{},...message.env!==void 0?{env:message.env}:{},...message.executablePath!==void 0?{executablePath:message.executablePath}:{},...message.filesystemPolicy!==void 0?{filesystemPolicy:message.filesystemPolicy}:{},...message.stdin!==void 0?{stdin:message.stdin}:{},...child.input?{stdinStream:child.input}:{},...child.terminal?{terminal:child.terminal}:{},...child.descriptors.size>0?{descriptors}:{},signal:child.controller.signal,onStdout:chunk=>{if(!this.disposed)this.send({type:"child-output",id:message.id,stream:"stdout",chunk})},onStderr:chunk=>{if(!this.disposed)this.send({type:"child-output",id:message.id,stream:"stderr",chunk})}});if(!this.disposed)this.send({type:"child-result",id:message.id,stdout:result.stdout,stderr:result.stderr,exitCode:result.exitCode,...result.signal?{signal:result.signal}:{}})}catch(cause){if(!this.disposed){try{this.send({type:"child-error",id:message.id,error:cause instanceof Error?cause.message:String(cause)})}catch(failure){console.error("Child process result transport failed.",failure)}}}finally{child.input?.cancel();for(const input of child.descriptors.values())input.cancel();child.resizes.clear();this.children.delete(message.id)}}descriptor(id2,fd2,input,child){let closed=false;const live2=()=>!closed&&!this.disposed&&this.children.get(id2)===child;return{input,write:bytes2=>{for(let offset2=0;offset2<bytes2.byteLength&&live2();offset2+=maximumChunk){const chunk=Uint8Array.from(bytes2.subarray(offset2,offset2+maximumChunk)).buffer;this.send({type:"child-fd-output",id:id2,fd:fd2,bytes:chunk},[chunk])}},end:()=>{if(!live2())return;closed=true;this.send({type:"child-fd-close",id:id2,fd:fd2})}}}};var STAT_FIELDS=["mode","mtimeMs","atimeMs","ctimeMs","birthtimeMs","nlink","uid","gid","dev","ino","rdev","blksize","blocks"];var STATE2=0;var OPERATION=1;var STATUS2=2;var INPUT_LENGTH=3;var OUTPUT_LENGTH=4;var TOTAL_LENGTH=5;var CONTROL_WORDS=8;var DEFAULT_PAYLOAD_BYTES=4*1024*1024;var REQUEST_TIMEOUT_MS=3e4;var encoder2=new TextEncoder;var decoder3=new TextDecoder;function createBrowserFilesystemChannel(payloadBytes=DEFAULT_PAYLOAD_BYTES){const{port1,port2}=new MessageChannel;const control=new SharedArrayBuffer(CONTROL_WORDS*Int32Array.BYTES_PER_ELEMENT);const payload=new SharedArrayBuffer(payloadBytes);return{holder:{port:port1,control,payload},reader:{port:port2,control,payload}}}function serveBrowserFilesystemChannel(filesystem,channel){const control=new Int32Array(channel.control);const payload=new Uint8Array(channel.payload);let staged=null;channel.port.onmessage=event=>{const requestId2=event.data;if(Atomics.load(control,STATE2)!==requestId2)return;let status=0;let output=new Uint8Array;let total=0;try{const operation=Atomics.load(control,OPERATION);const inputLength=Atomics.load(control,INPUT_LENGTH);const input=JSON.parse(decoder3.decode(payload.slice(0,inputLength)));if(operation===1){output=encoder2.encode(JSON.stringify(filesystem.existsSync(input.path)))}else if(operation===2||operation===13){if(operation===13&&!filesystem.lstatSync){throw Object.assign(new Error("The filesystem holder does not support lstat."),{code:"ENOTSUP"})}const stat2=input.throwIfNoEntry===false?operation===13?filesystem.lstatSync(input.path,{throwIfNoEntry:false}):filesystem.statSync(input.path,{throwIfNoEntry:false}):operation===13?filesystem.lstatSync(input.path):filesystem.statSync(input.path);if(stat2===void 0)output=encoder2.encode("null");else{const metadata=Object.fromEntries(STAT_FIELDS.filter(key=>stat2[key]!==void 0).map(key=>[key,stat2[key]]));output=encoder2.encode(JSON.stringify({...metadata,file:stat2.isFile(),directory:stat2.isDirectory(),symlink:stat2.isSymbolicLink?.()??false,size:stat2.size,mode:stat2.mode??420,mtimeMs:stat2.mtimeMs??0}))}}else if(operation===14&&filesystem.readlinkSync){output=encoder2.encode(JSON.stringify(filesystem.readlinkSync(input.path)))}else if(operation===15&&filesystem.symlinkSync&&typeof input.target==="string"){filesystem.symlinkSync(input.target,input.path)}else if(operation===4){output=encoder2.encode(JSON.stringify(filesystem.readdirSync(input.path)))}else if(operation===3){const bytes2=filesystem.readFileSync(input.path);total=bytes2.byteLength;const offset2=input.offset??0;output=bytes2.subarray(offset2,Math.min(total,offset2+payload.byteLength))}else if(operation===5){output=encoder2.encode(JSON.stringify(filesystem.realpathSync?.(input.path)??input.path))}else if(operation===6&&filesystem.writeFileSync){if(!Number.isSafeInteger(input.bytes)||input.bytes<0||inputLength+input.bytes>payload.byteLength)throw new Error("Invalid filesystem write length.");const piece=payload.slice(inputLength,inputLength+input.bytes);if(input.total===void 0){filesystem.writeFileSync(input.path,piece)}else{const offset2=input.offset??0;if(!Number.isSafeInteger(input.total)||input.total<0||offset2+piece.byteLength>input.total)throw new Error("Invalid filesystem write piece.");if(offset2===0)staged={path:input.path,bytes:new Uint8Array(input.total),received:0};if(!staged||staged.path!==input.path||staged.bytes.byteLength!==input.total||staged.received!==offset2){staged=null;throw new Error(`The filesystem channel received a write piece of ${input.path} out of order.`)}staged.bytes.set(piece,offset2);staged.received+=piece.byteLength;if(staged.received===input.total){const whole=staged.bytes;staged=null;filesystem.writeFileSync(input.path,whole)}}}else if(operation===16&&(filesystem.appendFileSync||filesystem.writeFileSync)){if(!Number.isSafeInteger(input.bytes)||input.bytes<0||inputLength+input.bytes>payload.byteLength)throw new Error("Invalid filesystem append length.");const piece=payload.slice(inputLength,inputLength+input.bytes);if(filesystem.appendFileSync)filesystem.appendFileSync(input.path,piece);else{const existing=filesystem.existsSync(input.path)?filesystem.readFileSync(input.path):new Uint8Array(0);const whole=new Uint8Array(existing.byteLength+piece.byteLength);whole.set(existing,0);whole.set(piece,existing.byteLength);filesystem.writeFileSync(input.path,whole)}}else if(operation===17&&(filesystem.writeAtSync||filesystem.writeFileSync)){if(!Number.isSafeInteger(input.bytes)||input.bytes<0||inputLength+input.bytes>payload.byteLength)throw new Error("Invalid filesystem write length.");if(!Number.isSafeInteger(input.position)||input.position<0)throw new Error("Invalid filesystem write position.");const piece=payload.slice(inputLength,inputLength+input.bytes);if(filesystem.writeAtSync)filesystem.writeAtSync(input.path,piece,input.position);else if(piece.byteLength===0&&filesystem.existsSync(input.path)){}else{const existing=filesystem.existsSync(input.path)?filesystem.readFileSync(input.path):new Uint8Array(0);const whole=new Uint8Array(Math.max(existing.byteLength,input.position+piece.byteLength));whole.set(existing,0);whole.set(piece,input.position);filesystem.writeFileSync(input.path,whole)}}else if(operation===7&&filesystem.mkdirSync){filesystem.mkdirSync(input.path,{recursive:input.recursive===true})}else if(operation===8&&filesystem.unlinkSync){filesystem.unlinkSync(input.path)}else if(operation===9&&filesystem.rmdirSync){filesystem.rmdirSync(input.path)}else if(operation===10&&filesystem.renameSync&&typeof input.to==="string"){filesystem.renameSync(input.path,input.to)}else if(operation===11&&filesystem.chmodSync&&Number.isInteger(input.mode)){filesystem.chmodSync(input.path,input.mode)}else if(operation===12&&filesystem.utimesSync&&Number.isFinite(input.atime)&&Number.isFinite(input.mtime)){filesystem.utimesSync(input.path,input.atimeDate?new Date(input.atime):input.atime,input.mtimeDate?new Date(input.mtime):input.mtime)}else{throw new Error(`Unsupported filesystem channel operation ${operation}.`)}if(output.byteLength>payload.byteLength)throw new Error("The filesystem channel answer exceeds its buffer.")}catch(cause){const error=cause;const message=cause instanceof Error?cause.message:String(cause);status=2;output=encoder2.encode(JSON.stringify({message,...typeof error?.code==="string"?{code:error.code}:{},...typeof error?.path==="string"?{path:error.path}:{}}));if(output.byteLength>payload.byteLength){status=1;output=encoder2.encode(message).subarray(0,payload.byteLength)}}if(Atomics.compareExchange(control,STATE2,requestId2,-requestId2)!==requestId2)return;payload.set(output);Atomics.store(control,STATUS2,status);Atomics.store(control,OUTPUT_LENGTH,output.byteLength);Atomics.store(control,TOTAL_LENGTH,total);Atomics.store(control,STATE2,requestId2+1);Atomics.notify(control,STATE2)};channel.port.start();return()=>{channel.port.onmessage=null;channel.port.close()}}var BrowserFilesystemChannelClient=class{constructor(channel){this.channel=channel;this.control=new Int32Array(channel.control);this.payload=new Uint8Array(channel.payload)}channel;control;payload;nextRequestId=1;existsSync(path3){return JSON.parse(decoder3.decode(this.call(1,{path:path3}).output))}statSync(path3,options){return this.stat(path3,2,options?.throwIfNoEntry!==false)}lstatSync(path3,options){return this.stat(path3,13,options?.throwIfNoEntry!==false)}stat(path3,operation,throwIfNoEntry){let bytes2;try{bytes2=this.call(operation,{path:path3,...throwIfNoEntry?{}:{throwIfNoEntry:false}}).output}catch(cause){if(!throwIfNoEntry&&cause.code==="ENOENT")return void 0;throw cause}const stat2=JSON.parse(decoder3.decode(bytes2));if(stat2===null){if(!throwIfNoEntry)return void 0;throw new Error("The filesystem holder returned absence for a throwing stat.")}return{...Object.fromEntries(STAT_FIELDS.filter(key=>stat2[key]!==void 0).map(key=>[key,stat2[key]])),isFile:()=>stat2.file,isDirectory:()=>stat2.directory,isSymbolicLink:()=>stat2.symlink===true,size:stat2.size,mode:stat2.mode,mtimeMs:stat2.mtimeMs,mtime:new Date(stat2.mtimeMs)}}readlinkSync(path3){return JSON.parse(decoder3.decode(this.call(14,{path:path3}).output))}symlinkSync(target,path3){this.call(15,{path:path3,target})}readdirSync(path3){return JSON.parse(decoder3.decode(this.call(4,{path:path3}).output))}realpathSync(path3){return JSON.parse(decoder3.decode(this.call(5,{path:path3}).output))}writeFileSync(path3,value){const bytes2=typeof value==="string"?encoder2.encode(value):value;const room=this.payload.byteLength-encoder2.encode(JSON.stringify({path:path3,bytes:bytes2.byteLength,offset:bytes2.byteLength,total:bytes2.byteLength})).byteLength;if(bytes2.byteLength<=room){this.call(6,{path:path3,bytes:bytes2.byteLength},bytes2);return}for(let offset2=0;offset2<bytes2.byteLength;offset2+=room){const piece=bytes2.subarray(offset2,Math.min(bytes2.byteLength,offset2+room));this.call(6,{path:path3,bytes:piece.byteLength,offset:offset2,total:bytes2.byteLength},piece)}}appendFileSync(path3,value){const bytes2=typeof value==="string"?encoder2.encode(value):value;const room=this.payload.byteLength-encoder2.encode(JSON.stringify({path:path3,bytes:bytes2.byteLength})).byteLength;if(bytes2.byteLength===0){this.call(16,{path:path3,bytes:0},bytes2);return}for(let offset2=0;offset2<bytes2.byteLength;offset2+=room){const piece=bytes2.subarray(offset2,Math.min(bytes2.byteLength,offset2+room));this.call(16,{path:path3,bytes:piece.byteLength},piece)}}writeAtSync(path3,value,position){const room=this.payload.byteLength-encoder2.encode(JSON.stringify({path:path3,position:position+value.byteLength,bytes:value.byteLength})).byteLength;if(value.byteLength===0){this.call(17,{path:path3,position,bytes:0},value);return}for(let offset2=0;offset2<value.byteLength;offset2+=room){const piece=value.subarray(offset2,Math.min(value.byteLength,offset2+room));this.call(17,{path:path3,position:position+offset2,bytes:piece.byteLength},piece)}}mkdirSync(path3,options){this.call(7,{path:path3,recursive:options?.recursive===true})}unlinkSync(path3){this.call(8,{path:path3})}rmdirSync(path3){this.call(9,{path:path3})}renameSync(path3,to2){this.call(10,{path:path3,to:to2})}chmodSync(path3,mode){this.call(11,{path:path3,mode})}utimesSync(path3,atime,mtime){this.call(12,{path:path3,atime:typeof atime==="number"?atime:Number(atime),mtime:typeof mtime==="number"?mtime:Number(mtime),atimeDate:typeof atime!=="number",mtimeDate:typeof mtime!=="number"})}readFileSync(path3,encoding){const first=this.call(3,{path:path3});let bytes2;if(first.output.byteLength>=first.total){bytes2=first.output}else{bytes2=new Uint8Array(first.total);bytes2.set(first.output,0);for(let offset2=first.output.byteLength;offset2<first.total;){const piece=this.call(3,{path:path3,offset:offset2});if(piece.output.byteLength===0)throw new Error(`The filesystem channel returned a short read of ${path3}.`);bytes2.set(piece.output,offset2);offset2+=piece.output.byteLength}}return encoding?decoder3.decode(bytes2):bytes2}call(operation,input,bytes2){const encoded=encoder2.encode(JSON.stringify(input));if(encoded.byteLength+(bytes2?.byteLength??0)>this.payload.byteLength)throw new Error("The filesystem channel request exceeds its buffer.");if(Atomics.load(this.control,STATE2)!==0)throw new Error("The filesystem channel is answering another request.");const requestId2=this.nextRequestId;this.nextRequestId=requestId2>=1073741821?1:requestId2+2;this.payload.set(encoded);if(bytes2)this.payload.set(bytes2,encoded.byteLength);Atomics.store(this.control,OPERATION,operation);Atomics.store(this.control,INPUT_LENGTH,encoded.byteLength);Atomics.store(this.control,STATE2,requestId2);this.channel.port.postMessage(requestId2);const deadline=Date.now()+REQUEST_TIMEOUT_MS;for(;;){const state=Atomics.load(this.control,STATE2);if(state===requestId2+1)break;if(state!==requestId2&&state!==-requestId2)throw new Error(`The filesystem channel is in state ${state} for request ${requestId2}.`);const remaining=Math.max(0,deadline-Date.now());if(remaining===0&&state===requestId2&&Atomics.compareExchange(this.control,STATE2,requestId2,0)===requestId2){throw new Error(`The filesystem holder did not answer within ${REQUEST_TIMEOUT_MS} ms.`)}Atomics.wait(this.control,STATE2,state,state===-requestId2?void 0:remaining)}const status=Atomics.load(this.control,STATUS2);const length=Atomics.load(this.control,OUTPUT_LENGTH);const total=Atomics.load(this.control,TOTAL_LENGTH);const output=this.payload.slice(0,length);Atomics.store(this.control,STATE2,0);if(status===2){const error=JSON.parse(decoder3.decode(output));throw Object.assign(new Error(error.message),error)}if(status!==0)throw new Error(decoder3.decode(output));return{output,total}}};function createConfinedNodeFilesystem(filesystem,policy){const writable=createProcessFilesystemMutationGuard(filesystem,policy);const view=new VirtualFS;Object.defineProperty(view,Symbol.for("@volter/browser-node/assert-filesystem-mutation"),{value:writable});const descriptors={existsSync:path3=>filesystem.existsSync(path3),statSync:(path3,options)=>filesystem.statSync(path3,options),lstatSync:(path3,options)=>filesystem.lstatSync(path3,options),readdirSync:path3=>filesystem.readdirSync(path3),realpathSync:path3=>filesystem.realpathSync(path3),readlinkSync:path3=>filesystem.readlinkSync(path3),accessSync:(path3,mode)=>filesystem.accessSync((mode??0)&2?writable(path3):path3,mode),readFileSync:(path3,encoding)=>{const bytes2=new Uint8Array(filesystem.readFileSync(path3));return encoding?new TextDecoder().decode(bytes2):bytes2},writeFileSync:(path3,bytes2)=>filesystem.writeFileSync(writable(path3),typeof bytes2==="string"?bytes2:new Uint8Array(bytes2)),appendFileSync:(path3,bytes2)=>filesystem.appendFileSync(writable(path3),typeof bytes2==="string"?bytes2:new Uint8Array(bytes2)),writeAtSync:(path3,bytes2,position)=>filesystem.writeAtSync(writable(path3),new Uint8Array(bytes2),position),mkdirSync:(path3,options)=>{if(options?.recursive&&filesystem.existsSync(path3)&&filesystem.lstatSync(path3).isDirectory()&&!filesystem.lstatSync(path3).isSymbolicLink())return;filesystem.mkdirSync(writable(path3),options)},unlinkSync:path3=>filesystem.unlinkSync(writable(path3)),rmdirSync:path3=>filesystem.rmdirSync(writable(path3)),renameSync:(from,to2)=>{const source=writable(from);const destination=writable(to2);filesystem.renameSync(source,destination)},chmodSync:(path3,mode)=>{const target=writable(path3);const change=Reflect.get(filesystem,"chmodSync");if(!change)unsupported2("chmod");change.call(filesystem,target,mode)},utimesSync:(path3,atime,mtime)=>{const target=writable(path3);const change=Reflect.get(filesystem,"utimesSync");if(!change)unsupported2("utimes");change.call(filesystem,target,atime,mtime)},symlinkSync:()=>unsupported2("symlink"),linkSync:()=>unsupported2("link"),toSnapshot:()=>structuredClone(filesystem.toSnapshot()),watch:filesystem.watch.bind(filesystem),on:(event,listener)=>{filesystem.on(event,listener);return view},off:(event,listener)=>{filesystem.off(event,listener);return view}};for(const[name,value]of Object.entries(descriptors)){Object.defineProperty(view,name,{value,configurable:false,writable:false})}return view}function unsupported2(operation){throw Object.assign(new Error(`Node filesystem does not support ${operation}.`),{code:"ENOTSUP"})}var MAGIC=2019846480;var HEADER_WORDS=6;var RECORD_WORDS=6;var RECORD_NUMBERS=3;var PATH_OFFSET=0;var PATH_LENGTH=1;var FLAGS3=2;var MODE=3;var CHILD_START=4;var CHILD_COUNT=5;var MTIME=0;var OFFSET=1;var LENGTH3=2;var HAS_ENTRY=1;var HAS_CHILDREN=2;var PACKED=4;var ASCII2=32;var TYPE_SHIFT=3;var TYPES=["file","directory","symlink"];var LONE_SURROGATE=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;var encoder3=new TextEncoder;var decoder4=new TextDecoder;function hashPath(path3){let hash3=2166136261;for(let index2=0;index2<path3.length;index2+=1){hash3^=path3.charCodeAt(index2);hash3=Math.imul(hash3,16777619)}return hash3>>>0}function encodeSharedIndex(entries,children){const paths=[...entries.keys()];for(const path3 of paths)if(LONE_SURROGATE.test(path3))throw new Error("A path in the store is not well-formed UTF-16.");const at3=new Map;for(let index2=0;index2<paths.length;index2+=1)at3.set(paths[index2],index2);for(const parent of children.keys())if(!at3.has(parent)){at3.set(parent,paths.length);paths.push(parent)}const count=paths.length;const encoded=new Map;const byteLengths=new Uint32Array(count);let stringBytes=0;for(let index2=0;index2<count;index2+=1){const path3=paths[index2];let ascii=true;for(let unit=0;unit<path3.length;unit+=1)if(path3.charCodeAt(unit)>=128){ascii=false;break}if(!ascii)encoded.set(index2,encoder3.encode(path3));byteLengths[index2]=ascii?path3.length:encoded.get(index2).length;stringBytes+=byteLengths[index2]}let childTotal=0;for(const names2 of children.values())childTotal+=names2.size;let tableSize=1;while(tableSize<count*2)tableSize<<=1;const recordsAt=HEADER_WORDS*4;const numbersAt=align(recordsAt+count*RECORD_WORDS*4,8);const tableAt=numbersAt+count*RECORD_NUMBERS*8;const childListAt=tableAt+tableSize*4;const stringsAt=childListAt+childTotal*4;const buffer2=new SharedArrayBuffer(align(stringsAt+stringBytes,8));const header=new Uint32Array(buffer2,0,HEADER_WORDS);header.set([MAGIC,count,tableSize,childTotal,stringBytes,entries.size]);const records=new Uint32Array(buffer2,recordsAt,count*RECORD_WORDS);const numbers=new Float64Array(buffer2,numbersAt,count*RECORD_NUMBERS);const table=new Uint32Array(buffer2,tableAt,tableSize);const childList=new Uint32Array(buffer2,childListAt,childTotal);const strings2=new Uint8Array(buffer2,stringsAt,stringBytes);let stringCursor=0;let childCursor=0;for(let index2=0;index2<count;index2+=1){const path3=paths[index2];const word=index2*RECORD_WORDS;const other=encoded.get(index2);if(other)strings2.set(other,stringCursor);else for(let unit=0;unit<path3.length;unit+=1)strings2[stringCursor+unit]=path3.charCodeAt(unit);const length=byteLengths[index2];records[word+PATH_OFFSET]=stringCursor;records[word+PATH_LENGTH]=length;stringCursor+=length;let flags=other?0:ASCII2;const entry=entries.get(path3);if(entry){flags|=HAS_ENTRY|TYPES.indexOf(entry.type)<<TYPE_SHIFT;if(entry.pack)flags|=PACKED;records[word+MODE]=entry.mode;const number=index2*RECORD_NUMBERS;numbers[number+MTIME]=entry.mtimeMs;numbers[number+OFFSET]=entry.offset;numbers[number+LENGTH3]=entry.length}const names2=children.get(path3);if(names2){flags|=HAS_CHILDREN;records[word+CHILD_START]=childCursor;records[word+CHILD_COUNT]=names2.size;for(const name of names2){const child=at3.get(`${path3}/${name}`);if(child===void 0)throw new Error(`The store's children name ${path3}/${name}, which its index does not hold.`);childList[childCursor++]=child}}records[word+FLAGS3]=flags;let slot=hashPath(path3)&tableSize-1;while(table[slot]!==0)slot=slot+1&tableSize-1;table[slot]=index2+1}if(childCursor!==childTotal)throw new Error("The shared index's children did not add up.");return buffer2}function align(value,to2){return Math.ceil(value/to2)*to2}var SharedIndex=class{buffer;count;entryCount;records;numbers;table;childList;strings;mask;constructor(buffer2){const header=new Uint32Array(buffer2,0,HEADER_WORDS);if(header[0]!==MAGIC)throw new Error("Not a shared store index.");const[,count,tableSize,childTotal,stringBytes,entryCount]=header;this.buffer=buffer2;this.count=count;this.entryCount=entryCount;const recordsAt=HEADER_WORDS*4;const numbersAt=align(recordsAt+count*RECORD_WORDS*4,8);const tableAt=numbersAt+count*RECORD_NUMBERS*8;const childListAt=tableAt+tableSize*4;const stringsAt=childListAt+childTotal*4;this.records=new Uint32Array(buffer2,recordsAt,count*RECORD_WORDS);this.numbers=new Float64Array(buffer2,numbersAt,count*RECORD_NUMBERS);this.table=new Uint32Array(buffer2,tableAt,tableSize);this.childList=new Uint32Array(buffer2,childListAt,childTotal);this.strings=new Uint8Array(buffer2,stringsAt,stringBytes);this.mask=tableSize-1}find(path3){let slot=hashPath(path3)&this.mask;for(;;){const held=this.table[slot];if(held===0)return-1;if(this.pathIs(held-1,path3))return held-1;slot=slot+1&this.mask}}entry(record){const word=record*RECORD_WORDS;const flags=this.records[word+FLAGS3];if(!(flags&HAS_ENTRY))return void 0;const number=record*RECORD_NUMBERS;const entry={type:TYPES[flags>>>TYPE_SHIFT&3],mode:this.records[word+MODE],mtimeMs:this.numbers[number+MTIME],offset:this.numbers[number+OFFSET],length:this.numbers[number+LENGTH3]};if(flags&PACKED)entry.pack="packages";return entry}typeAt(record){const flags=this.records[record*RECORD_WORDS+FLAGS3];return flags&HAS_ENTRY?TYPES[flags>>>TYPE_SHIFT&3]:void 0}hasEntry(record){return(this.records[record*RECORD_WORDS+FLAGS3]&HAS_ENTRY)!==0}childNames(record){const word=record*RECORD_WORDS;if(!(this.records[word+FLAGS3]&HAS_CHILDREN))return void 0;const start=this.records[word+CHILD_START];const skip=this.records[word+PATH_LENGTH]+1;const names2=[];for(let index2=0;index2<this.records[word+CHILD_COUNT];index2+=1){const child=this.childList[start+index2]*RECORD_WORDS;names2.push(this.decode(this.records[child+PATH_OFFSET]+skip,this.records[child+PATH_LENGTH]-skip,(this.records[child+FLAGS3]&ASCII2)!==0))}return names2}path(record){const word=record*RECORD_WORDS;return this.decode(this.records[word+PATH_OFFSET],this.records[word+PATH_LENGTH],(this.records[word+FLAGS3]&ASCII2)!==0)}decode(start,length,ascii){if(!ascii)return decoder4.decode(this.strings.slice(start,start+length));let text="";for(let at3=start,end=start+length;at3<end;at3+=4096){text+=String.fromCharCode.apply(null,this.strings.subarray(at3,Math.min(end,at3+4096)))}return text}pathIs(record,path3){const word=record*RECORD_WORDS;const start=this.records[word+PATH_OFFSET];const length=this.records[word+PATH_LENGTH];if(!(this.records[word+FLAGS3]&ASCII2))return this.path(record)===path3;if(length!==path3.length)return false;for(let index2=0;index2<length;index2+=1)if(this.strings[start+index2]!==path3.charCodeAt(index2))return false;return true}};var DELETED=Symbol("deleted");function sameIndexEntry(left,right){return left===right||!!left&&!!right&&left.type===right.type&&left.offset===right.offset&&left.length===right.length&&left.pack===right.pack&&left.mode===right.mode&&left.mtimeMs===right.mtimeMs&&left.capacity===right.capacity}var OverlaidIndex=class{constructor(base){this.base=base}base;overlay=new Map;delta=0;get[Symbol.toStringTag](){return"Map"}get size(){return this.base.entryCount+this.delta}get(path3){const over=this.overlay.get(path3);if(over!==void 0)return over===DELETED?void 0:over;const record=this.base.find(path3);return record<0?void 0:this.base.entry(record)}typeOf(path3){const over=this.overlay.get(path3);if(over!==void 0)return over===DELETED?void 0:over.type;const record=this.base.find(path3);return record<0?void 0:this.base.typeAt(record)}has(path3){const over=this.overlay.get(path3);if(over!==void 0)return over!==DELETED;const record=this.base.find(path3);return record>=0&&this.base.hasEntry(record)}set(path3,entry){if(!this.has(path3))this.delta+=1;const record=this.base.find(path3);if(record>=0&&sameIndexEntry(this.base.entry(record),entry))this.overlay.delete(path3);else this.overlay.set(path3,entry);return this}delete(path3){if(!this.has(path3))return false;const record=this.base.find(path3);if(record>=0&&this.base.hasEntry(record))this.overlay.set(path3,DELETED);else this.overlay.delete(path3);this.delta-=1;return true}clear(){throw new Error("A reader's index is not cleared; it is replaced.")}*entries(){for(const[path3,entry]of this.overlay)if(entry!==DELETED)yield[path3,entry];for(let record=0;record<this.base.count;record+=1){if(!this.base.hasEntry(record))continue;const path3=this.base.path(record);if(this.overlay.has(path3))continue;yield[path3,this.base.entry(record)]}}*keys(){for(const[path3]of this.entries())yield path3}*values(){for(const[,entry]of this.entries())yield entry}[Symbol.iterator](){return this.entries()}forEach(callback,thisArg){for(const[path3,entry]of this.entries())callback.call(thisArg,entry,path3,this)}*changed(){for(const[path3,entry]of this.overlay)if(entry!==DELETED)yield[path3,entry]}*changes(){for(const[path3,entry]of this.overlay)yield[path3,entry===DELETED?null:entry]}get overlaid(){return this.overlay.size}boundedChanges(){if(this.overlay.size>65536)return void 0;const changes=[];let bytes2=0;for(const[path3,entry]of this.changes()){bytes2+=path3.length*2+128;if(bytes2>8*1024*1024)return void 0;changes.push([path3,entry])}return changes}};var OverlaidChildren=class{constructor(base){this.base=base}base;overlay=new Map;get(path3){const over=this.overlay.get(path3);if(over!==void 0)return over===DELETED?void 0:over;const record=this.base.find(path3);const names2=record<0?void 0:this.base.childNames(record);return names2?new Set(names2):void 0}mutable(path3){const over=this.overlay.get(path3);if(over!==void 0&&over!==DELETED)return over;const names2=new Set(over===DELETED?[]:this.get(path3)??[]);this.overlay.set(path3,names2);return names2}delete(path3){this.overlay.set(path3,DELETED)}};var STORE_BASE_DIRECTORY="supercode-browser-filesystems";var PACKAGES_STORE="packages";var STORE_STATE_FILE="state.json";var PACKAGES_ROOT="/packages";var BROWSER_PACK_RETENTION_ROOT="/opt/.browser-packs";var PACKAGES_LOCK="supercode-browser-packages";var PACKAGES_OPEN_LOCK="supercode-browser-packages-open";var encoder4=new TextEncoder;var decoder5=new TextDecoder("utf-8",{fatal:true});var BASE_DIRECTORY=STORE_BASE_DIRECTORY;var TREE_STORE_PREFIX="host-tree.";var GENERATIONS_DIRECTORY="generations";var STAGING_DIRECTORY="atomic-staging";var STATE_FILE=STORE_STATE_FILE;var INDEX_FILE="index.json";var LOG_FILE="index-log.bin";var PACK_FILE="pack.bin";var RECORD_HEADER_BYTES=8;var MAX_RECORD_BYTES=64*1024*1024;var MAX_FILE_BYTES=1024*1024*1024;var MAX_WORKSPACE_BYTES=4*1024*1024*1024;var PROJECT_ROOTS=["/workspace","/home","/opt"];var STORE_CLOCK_EPOCH=0;var STORE_CLOCK_LOG=1;var MAX_ENTRIES=1e6;var MAX_LOG_BYTES=8*1024*1024;var FLUSH_WINDOW_MS=250;var COMPACTION_FLOOR_BYTES=64*1024*1024;var SESSION_COMPACTION_BYTES=256*1024*1024;var COPY_BUFFER_BYTES=4*1024*1024;var DIRECTORY_MODE=493;var FILE_MODE=420;function createPackStore(environment,options={}){const maximumBytes=options.limits?.maxBytes??MAX_WORKSPACE_BYTES;const maximumEntries=options.limits?.maxEntries??MAX_ENTRIES;if(!Number.isSafeInteger(maximumBytes)||maximumBytes<1||maximumBytes>MAX_WORKSPACE_BYTES||!Number.isSafeInteger(maximumEntries)||maximumEntries<1||maximumEntries>MAX_ENTRIES){throw new Error("Invalid OPFS workspace limits.")}let project;let shared=false;let readOnly=false;let extentsOnly=false;let generationHandle;let linked=0;let linkedBytes=0;let releaseLock;let projectId;let generation;let entries=new Map;let children=new LocalChildren;let packAccess;let imageRangesDigest;let imageReader;let deferredImage;let receivedImageCompletion;let receivedImageLine;let generationInitializedAt=0;let logAccess;let immutableReadEnd=0;const readAhead=new Map;const READ_AHEAD_BYTES=256*1024;const READ_AHEAD_BLOCKS=32;let packBytes=0;let flushTimer;let lastFlushAt=-Infinity;let flushes=0;let flushMs=0;let logBytes=0;let liveBytes=0;let deadBytes=0;let rewrites=0;let rewrittenBytes=0;let mutationUndo;let bytesUndo;let mutationFailure;let initializing=false;let openingController;let checkpointTail=Promise.resolve();let activeStorageOperations=0;let closing=false;let rewritingGeneration=false;let clockView;let transitions=0;let clockRetired=false;function publishLog(){if(!clockView||clockRetired)return;if(logBytes>2147483647){retireClock();return}Atomics.store(clockView,STORE_CLOCK_LOG,logBytes)}function retireClock(){if(!clockView||clockRetired)return;clockRetired=true;if((Atomics.load(clockView,STORE_CLOCK_EPOCH)&1)===0)Atomics.add(clockView,STORE_CLOCK_EPOCH,1)}function beginTransition(){transitions+=1;if(transitions===1&&clockView&&!clockRetired)Atomics.add(clockView,STORE_CLOCK_EPOCH,1)}function endTransition(){transitions-=1;if(transitions>0||!clockView||clockRetired)return;publishLog();if(!clockRetired)Atomics.add(clockView,STORE_CLOCK_EPOCH,1)}function clock(){if(readOnly)throw new Error("A store open for reading follows its owner's clock; it has none of its own.");if(!clockView){clockView=new Int32Array(new SharedArrayBuffer(2*Int32Array.BYTES_PER_ELEMENT));clockView[STORE_CLOCK_EPOCH]=transitions>0||clockRetired?1:0;publishLog()}return clockView.buffer}let seedCache;const SEED_REPLAY_BYTES=8*1024*1024;let startedFromSeed=false;function readerSeed(options2){if(readOnly||!clockView||!generation||initializing||transitions>0||clockRetired||closing)return void 0;const epoch=Atomics.load(clockView,STORE_CLOCK_EPOCH);if(epoch&1)return void 0;if(options2?.overlays&&entries instanceof OverlaidIndex){const changes=entries.boundedChanges();if(changes){return withImageCompletion({generation,index:entries.base.buffer,changes,packBytes,logBytes,epoch,liveBytes,linked,linkedBytes})}}if(seedCache&&seedCache.generation===generation&&seedCache.epoch===epoch&&logBytes>=seedCache.logBytes&&logBytes-seedCache.logBytes<=(options2?.current?0:SEED_REPLAY_BYTES))return withImageCompletion(seedCache);let index2;try{index2=encodeSharedIndex(entries,childrenMap())}catch(cause){console.warn(`[pack-store] no reader seed: ${cause instanceof Error?cause.message:String(cause)}`);return void 0}seedCache={generation,index:index2,packBytes,logBytes,epoch,liveBytes,linked,linkedBytes};standOnSeed(index2);return withImageCompletion(seedCache)}function withImageCompletion(seed){const packagesImage=options.packages?.imageCompletionSeed();return packagesImage?{...seed,packagesImage}:seed}function imageCompletionSeed(){if(!imageReader||!imageRangesDigest||!generation||initializing||transitions>0||closing)return void 0;return{generation,rangesDigest:imageRangesDigest,completed:imageReader.completionBuffer,...imageReader.receiptKey?{metadata:{ranges:imageReader.verifiedRanges,receiptKey:imageReader.receiptKey}}:{}}}function standOnSeed(index2){const roomy=[];if(entries instanceof OverlaidIndex){for(const[path3,entry]of entries.changed())if(entry.capacity!==void 0)roomy.push([path3,entry])}else{for(const[path3,entry]of entries)if(entry.capacity!==void 0)roomy.push([path3,entry])}const base=new SharedIndex(index2);entries=new OverlaidIndex(base);children=new OverlaidChildren(base);for(const[path3,entry]of roomy)entries.set(path3,entry)}function childrenMap(){if(children instanceof LocalChildren)return children.map;const derived=new Map;for(const path3 of entries.keys()){const parent=parentPath(path3);if(parent===path3)continue;let names2=derived.get(parent);if(!names2){names2=new Set;derived.set(parent,names2)}names2.add(path3.slice(parent.length+1))}return derived}function follow(){if(!readOnly||extentsOnly||closing||!logAccess)return;replayLog(logBytes)}async function ownStorageOperation(operation){if(closing)throw new Error("This OPFS workspace is closing.");activeStorageOperations+=1;let failure;let failed=false;try{return await operation()}catch(cause){failed=true;failure=cause;throw cause}finally{activeStorageOperations-=1;if(closing&&activeStorageOperations===0){try{closeStorage()}catch(cause){if(failed)throw new AggregateError([failure,cause],"OPFS operation and deferred close both failed.");throw cause}}}}async function rewriteGeneration(operation){assertWritable();if(activeStorageOperations!==0)return Promise.reject(new Error("Wait for the current OPFS storage operation before replacing its generation."));rewritingGeneration=true;return ownStorageOperation(async()=>{try{return await operation()}finally{rewritingGeneration=false}})}function read(path3){if(closing)throw new Error("This OPFS workspace is closing.");const entry=entries.get(path3);if(!entry||entry.type==="directory")throw new Error(`OPFS workspace file does not exist: ${path3}`);return readEntry(entry)}function readRange(path3,offset2,length){if(closing)throw new Error("This OPFS workspace is closing.");const entry=entries.get(path3);if(!entry||entry.type==="directory")throw new Error(`OPFS workspace file does not exist: ${path3}`);const start=Math.min(Math.max(0,offset2),entry.length);const count=Math.min(Math.max(0,length),entry.length-start);if(entry.pack){const packages2=options.packages;if(!packages2)throw new Error("This store has no shared package store to read from.");return packages2.readExtent(entry.offset+start,count)}return readExtent(entry.offset+start,count)}function readEntry(entry){if(entry.pack){const packages2=options.packages;if(!packages2)throw new Error("This store has no shared package store to read from.");return packages2.readExtent(entry.offset,entry.length)}return readExtent(entry.offset,entry.length)}function readExtent(offset2,length){if(closing)throw new Error("This OPFS workspace is closing.");const access=packAccess;if(!access)throw new Error("OPFS filesystem worker is not initialized.");const value=new Uint8Array(length);if(length>0&&length<=READ_AHEAD_BYTES&&offset2>=0&&offset2+length<=immutableReadEnd){let copied=0;while(copied<length){const position=offset2+copied;const start=Math.floor(position/READ_AHEAD_BYTES)*READ_AHEAD_BYTES;let block=readAhead.get(start);if(!block){block=new Uint8Array(Math.min(READ_AHEAD_BYTES,immutableReadEnd-start));imageReader?.ensure(start,block.byteLength);if(access.read(block,{at:start})!==block.byteLength)throw new Error("An OPFS package range could not be read completely.")}readAhead.delete(start);readAhead.set(start,block);if(readAhead.size>READ_AHEAD_BLOCKS)readAhead.delete(readAhead.keys().next().value);const from=position-start;const count=Math.min(length-copied,block.byteLength-from);value.set(block.subarray(from,from+count),copied);copied+=count}return value}imageReader?.ensure(offset2,length);if(length>0&&access.read(value,{at:offset2})!==length){throw new Error("An OPFS workspace file could not be read completely.")}return value}async function initialize2(requestedProjectId,openOptions={}){if(closing&&project||!project&&activeStorageOperations!==0)throw new Error("Wait for this OPFS workspace to finish closing before opening it again.");if(initializing)throw new Error("This OPFS store is already opening a workspace.");if(project){if(projectId!==validProjectId(requestedProjectId))throw new Error("Close this OPFS store before opening another workspace.");return entries.size>0}initializing=true;closing=false;const opening=new AbortController;openingController=opening;try{entries=new Map;children=new LocalChildren;generation=void 0;imageRangesDigest=void 0;generationHandle=void 0;mutationUndo=void 0;mutationFailure=void 0;packBytes=logBytes=liveBytes=deadBytes=linked=linkedBytes=0;checkpointPrefix=void 0;rewrites=rewrittenBytes=flushes=flushMs=0;lastFlushAt=-Infinity;projectId=validProjectId(requestedProjectId);readOnly=openOptions.readOnly===true;receivedImageCompletion=readOnly?openOptions.imageCompletion:void 0;receivedImageLine=readOnly?openOptions.imageLine:void 0;extentsOnly=readOnly&&openOptions.extentsOnly===true;shared=openOptions.shared===true||readOnly;if(!shared)await acquireSessionLock(opening.signal);opening.signal.throwIfAborted();const root2=await storageRoot();opening.signal.throwIfAborted();try{const base=await root2.getDirectoryHandle(BASE_DIRECTORY,{create:!readOnly});opening.signal.throwIfAborted();project=await base.getDirectoryHandle(projectId,{create:!readOnly})}catch(cause){opening.signal.throwIfAborted();if(readOnly&&notFound(cause))return false;throw cause}opening.signal.throwIfAborted();let state=readStorageState(await readJson2(project,STATE_FILE));opening.signal.throwIfAborted();if(!state&&readOnly){await assertNoUncommittedGenerations();return false}if(!state&&shared){await environment.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive",signal:opening.signal},async()=>{opening.signal.throwIfAborted();state=readStorageState(await readJson2(project,STATE_FILE));opening.signal.throwIfAborted();if(!state){await assertNoUncommittedGenerations();await writeGeneration({files:[],pack:new ArrayBuffer(0)});await writeSweepMark(project)}});opening.signal.throwIfAborted();if(!state){generationHandle=await generationDirectory(generation,false);opening.signal.throwIfAborted();return false}}if(!state){await assertNoUncommittedGenerations();opening.signal.throwIfAborted();return false}const openCommitted=async state2=>{let directory2;try{directory2=await generationDirectory(state2.generation,false)}catch(cause){opening.signal.throwIfAborted();if(!notFound(cause))throw cause;throw new Error("The committed OPFS workspace generation is missing. Stored generations were retained.",{cause})}opening.signal.throwIfAborted();generation=state2.generation;generationInitializedAt=state2.initializedAt;imageRangesDigest=state2.imageRanges;generationHandle=directory2;if(extentsOnly){if(projectId===PACKAGES_STORE&&environment.navigator.locks){await environment.navigator.locks.request(PACKAGES_LOCK,{mode:"shared",signal:opening.signal},async()=>{await openGenerationHandles(directory2);immutableReadEnd=packAccess.getSize()})}else await openGenerationHandles(directory2);opening.signal.throwIfAborted();return true}const seed=readOnly?openOptions.seed:void 0;if(seed&&seed.generation===state2.generation){const base=new SharedIndex(seed.index);entries=new OverlaidIndex(base);children=new OverlaidChildren(base);packBytes=seed.packBytes;if(seed.changes)applyIndexRecord({packBytes:seed.packBytes,changes:seed.changes});await openGenerationHandles(directory2);opening.signal.throwIfAborted();logBytes=seed.logBytes;({liveBytes,linked,linkedBytes}=seed);deadBytes=Math.max(0,packBytes-liveBytes);startedFromSeed=true;return entries.size>0}const retained=!readOnly?await readRetainedIndex(directory2):void 0;opening.signal.throwIfAborted();if(retained){const base=new SharedIndex(retained.index);entries=new OverlaidIndex(base);children=new OverlaidChildren(base);({packBytes,liveBytes,linked,linkedBytes}=retained);const epoch=Atomics.load(new Int32Array(clock()),STORE_CLOCK_EPOCH);seedCache={generation,index:retained.index,packBytes,liveBytes,linked,linkedBytes,logBytes:0,epoch}}else{entries=readIndex(await readJson2(directory2,INDEX_FILE));opening.signal.throwIfAborted();rebuildChildren();packBytes=indexPackBytes(entries)}await openGenerationHandles(directory2);opening.signal.throwIfAborted();const represented=retained?await verifiedJournalPrefix(retained):0;opening.signal.throwIfAborted();if(represented){checkpointPrefix={generation,bytes:represented};if(seedCache)seedCache.logBytes=represented}replayLog(represented,!!retained);if(retained)deadBytes=Math.max(0,packBytes-liveBytes);else measureBytes();assertWorkspaceQuota();if(shared&&!readOnly&&!retained&&entries.size>=1e4){flushStorage();await writeIndexAtomically(directory2,entries,{access:logAccess,bytes:logBytes,packBytes})}if(!shared){packAccess.truncate(packBytes);await removeEntry(project,STAGING_DIRECTORY,true);await discardGenerations(generation);opening.signal.throwIfAborted();if(deadBytes>COMPACTION_FLOOR_BYTES&&deadBytes>liveBytes)await compact()}opening.signal.throwIfAborted();return entries.size>0};if(shared&&!readOnly){return await environment.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive",signal:opening.signal},async()=>{state=readStorageState(await readJson2(project,STATE_FILE));if(!state)throw new Error("The committed package store state is missing. Stored data was retained.");return openCommitted(state)})}return await openCommitted(state)}catch(cause){const failures=[cause];try{closeGenerationHandles()}catch(error){failures.push(error)}try{releaseLock?.()}catch(error){failures.push(error)}releaseLock=void 0;project=void 0;if(failures.length>1)throw new AggregateError(failures,"OPFS workspace open and cleanup failed.");throw cause}finally{initializing=false;openingController=void 0}}function refresh(options2){return ownStorageOperation(()=>refreshStorage(options2?.whole===true))}async function refreshStorage(whole=false){if(extentsOnly)throw new Error("A store opened for its extents alone has no index to follow.");if(readOnly&&project){const state=readStorageState(await readJson2(project,STATE_FILE));if(!state)throw new Error("The committed OPFS workspace state is missing. Stored data was retained.");if(state.generation!==generation||whole){const directory2=await generationDirectory(state.generation,false);const index2=readIndex(await readJson2(directory2,INDEX_FILE));packBytes=indexPackBytes(index2);if(state.generation!==generation){generation=state.generation;generationInitializedAt=state.initializedAt;imageRangesDigest=state.imageRanges;await openGenerationHandles(directory2)}generation=state.generation;generationHandle=directory2;entries=index2;rebuildChildren();replayLog();measureBytes();return}}const access=logAccess;if(!access||!generationHandle)return;const size=access.getSize();let reread=false;if(size<logBytes){entries=readIndex(await readJson2(generationHandle,INDEX_FILE));rebuildChildren();packBytes=indexPackBytes(entries);logBytes=0;reread=true}const before=logBytes;replayLog(logBytes);if(reread||logBytes!==before)measureBytes()}async function storageRoot(){let last;for(let attempt=0;attempt<10;attempt+=1){openingController?.signal.throwIfAborted();try{return await environment.navigator.storage.getDirectory()}catch(cause){last=cause;await new Promise(resolve2=>setTimeout(resolve2,200))}}throw last instanceof Error?last:new Error("This browser workspace's storage is unavailable.")}const OPEN_ATTEMPT_MS=1e4;async function openSyncAccess(handle,name){let refusal;const signal=openingController?.signal;for(let attempt=0;attempt<2;attempt+=1){signal?.throwIfAborted();const pending=handle.createSyncAccessHandle({mode:"readwrite-unsafe"});let timer;let abort;let claimed=false;try{const cancelled2=new Promise((_resolve,reject)=>{abort=()=>reject(signal?.reason??new DOMException("Workspace open was cancelled.","AbortError"));signal?.addEventListener("abort",abort,{once:true});if(signal?.aborted)abort()});const opened=await Promise.race([pending.then(access=>({access})).catch(cause=>{refusal=cause;return void 0}),new Promise(resolve2=>{timer=setTimeout(()=>resolve2(void 0),OPEN_ATTEMPT_MS)}),cancelled2]);signal?.throwIfAborted();if(opened){claimed=true;return opened.access}}finally{if(timer!==void 0)clearTimeout(timer);if(abort)signal?.removeEventListener("abort",abort);if(!claimed)void pending.then(access=>access.close(),()=>void 0).catch(cause=>console.error("Late workspace handle cleanup failed.",cause))}if(refusal instanceof TypeError){throw new Error(`This browser cannot share a workspace's files between pages: its file access handles have no readwrite-unsafe mode (Chrome 121 or newer has one). ${refusal.message}`)}await new Promise(resolve2=>setTimeout(resolve2,500))}const reason=refusal instanceof Error?` (${refusal.message})`:"";throw new Error(`This browser workspace's ${name} is held by another page${reason}.`)}async function openGenerationHandles(directory2){closeGenerationHandles();const pack=await directory2.getFileHandle(PACK_FILE);packAccess=await openSyncAccess(pack,"store");try{if(packAccess.getSize()<packBytes)throw new Error("The committed OPFS workspace pack is incomplete. Stored data was retained.");const log=await directory2.getFileHandle(LOG_FILE);logAccess=await openSyncAccess(log,"record of changes");logBytes=logAccess.getSize();if(imageRangesDigest){const supplied=receivedImageCompletion;const completion=supplied&&supplied.generation===generation&&supplied.rangesDigest===imageRangesDigest?supplied:void 0;let ranges;let receiptKey;if(completion?.metadata){ranges=validateImageRanges(completion.metadata.ranges);receiptKey=completion.metadata.receiptKey;if(!/^[a-f0-9]{64}$/u.test(receiptKey))throw new Error("The owner's immutable receipt key is invalid.")}else{const file2=await(await directory2.getFileHandle(IMAGE_RANGES_FILE)).getFile();const bytes2=new Uint8Array(await file2.arrayBuffer());if(await indexDigest(bytes2)!==imageRangesDigest)throw new Error("The committed immutable image ranges have changed. Stored data was retained.");ranges=validateImageRanges(JSON.parse(decoder5.decode(bytes2)));receiptKey=await indexDigest(encoder4.encode(JSON.stringify(ranges)))}if(ranges.bytes>packAccess.getSize())throw new Error("The immutable image reservation is incomplete. Stored data was retained.");const line=completion?receivedImageLine:void 0;if(!line)receivedImageLine?.port.close();receivedImageLine=void 0;imageReader=new ImageRangeReader(ranges,directory2,`${projectId}.${generation}`,completion?.completed,receiptKey,line);console.log(`[boot-trace] ${JSON.stringify({event:"image-reader-open",at:Date.now(),reader:`${projectId}.${generation}`,offered:supplied!==void 0,shared:completion!==void 0,...supplied&&!completion?{offeredGeneration:supplied.generation,generation,rangesMatch:supplied.rangesDigest===imageRangesDigest}:{}})}`);await imageReader.initialize();deferredImage=ranges.image}}catch(cause){closeGenerationHandles();throw cause}}function closeGenerationHandles(){imageReader?.close();imageReader=void 0;deferredImage=void 0;const pack=packAccess,log=logAccess;packAccess=void 0;logAccess=void 0;logBytes=0;immutableReadEnd=0;readAhead.clear();try{pack?.close()}finally{log?.close()}}function replayLog(from=0,measureChanges=false){const access=logAccess;if(!access)throw new Error("OPFS filesystem worker is not initialized.");const size=access.getSize();if(size<=from){logBytes=size;return}const buffer2=new Uint8Array(size-from);if(access.read(buffer2,{at:from})!==buffer2.byteLength)throw new Error("The OPFS workspace index log could not be read.");const packSize=packAccess?.getSize()??Infinity;const view=new DataView(buffer2.buffer);let offset2=0;const end=buffer2.byteLength;while(offset2+RECORD_HEADER_BYTES<=end){const length=view.getUint32(offset2,true);const checksum=view.getUint32(offset2+4,true);const start=offset2+RECORD_HEADER_BYTES;if(length===0||length>MAX_RECORD_BYTES||start+length>end)break;const body=buffer2.subarray(start,start+length);if(fingerprint2(body)!==checksum)break;let record;try{record=readIndexRecord(JSON.parse(decoder5.decode(body)))}catch{break}if(record.packBytes>packSize)break;applyIndexRecord(record,measureChanges);offset2=start+length}if(offset2!==end&&!shared)access.truncate(from+offset2);logBytes=from+offset2}function applyIndexRecord(record,measureChanges=false){for(const[path3,entry]of record.changes){const previous=entries.get(path3);if(entry&&sameIndexEntry(previous,entry)){attach(path3);continue}if(measureChanges){if(previous?.pack){linked-=1;linkedBytes-=previous.length}else if(previous)liveBytes-=previous.length;if(entry?.pack){linked+=1;linkedBytes+=entry.length}else if(entry)liveBytes+=entry.length}if(entry===null){entries.delete(path3);detach(path3)}else{entries.set(path3,entry);attach(path3)}}packBytes=Math.max(packBytes,record.packBytes)}function measureBytes(){liveBytes=0;linked=0;linkedBytes=0;for(const entry of entries.values()){if(entry.pack){linked+=1;linkedBytes+=entry.length}else liveBytes+=entry.length}deadBytes=Math.max(0,packBytes-liveBytes)}function indexPackBytes(index2){let end=0;for(const entry of index2.values())if(!entry.pack)end=Math.max(end,entry.offset+entry.length);return end}const SESSION_LOCK_WAIT_MS=5e3;async function acquireSessionLock(signal){if(!environment.navigator.locks)return;if(!projectId)throw new Error("OPFS filesystem project is not initialized.");const controller=new AbortController;const timer=setTimeout(()=>controller.abort(),SESSION_LOCK_WAIT_MS);try{await new Promise((resolve2,reject)=>{void environment.navigator.locks.request(`supercode-browser-filesystem-${projectId}`,{mode:"exclusive",signal:signal?AbortSignal.any([signal,controller.signal]):controller.signal},async()=>{clearTimeout(timer);resolve2();await new Promise(release2=>{releaseLock=release2})}).catch(()=>reject(signal?.aborted?signal.reason:new Error("This browser workspace is already open in another tab.")))})}finally{clearTimeout(timer)}}function validProjectId(value){if(typeof value!=="string"||!/^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/u.test(value)){throw new Error("OPFS filesystem projectId is invalid.")}return value}async function projectDirectory(){if(!project)throw new Error("OPFS filesystem worker is not initialized.");return project}async function generationDirectory(name,create2){const root2=await(await projectDirectory()).getDirectoryHandle(GENERATIONS_DIRECTORY,{create:create2});return root2.getDirectoryHandle(name,{create:create2})}async function assertNoUncommittedGenerations(){let directory2;try{directory2=await(await projectDirectory()).getDirectoryHandle(GENERATIONS_DIRECTORY)}catch(cause){if(notFound(cause))return;throw cause}for await(const _entry of directory2.entries()){throw new Error("OPFS workspace state is missing but stored generations exist. Stored data was retained.")}}async function discardGenerations(retain2){const directory2=await projectDirectory();let root2;try{root2=await directory2.getDirectoryHandle(GENERATIONS_DIRECTORY)}catch(cause){if(notFound(cause))return;throw cause}for await(const[name]of root2.entries()){if(name!==retain2)await removeGenerationQuietly(root2,name)}}function assertWritable(){if(closing)throw new Error("This OPFS workspace is closing.");if(rewritingGeneration)throw new Error("This OPFS workspace is replacing its generation; wait for that operation before writing.");if(readOnly)throw new Error("This store is open for reading; its owner writes it.");if(mutationFailure)throw mutationFailure}async function applyMutations(mutations){applyNow(mutations)}let checkpointPending=false;let maintenanceDeferrals=0;let checkpointPrefix;let compactingLive=false;function maintain(){if(maintenanceDeferrals>0)return;const represented=checkpointPrefix&&checkpointPrefix.generation===generation&&checkpointPrefix.bytes<=logBytes?checkpointPrefix.bytes:0;if(logBytes-represented>MAX_LOG_BYTES&&!checkpointPending){checkpointPending=true;const operation=shared?environment.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive"},async()=>{if(!project||closing)return;await refreshStorage();const prefix2=checkpointPrefix;const represented2=prefix2&&prefix2.generation===generation&&prefix2.bytes<=logBytes?prefix2.bytes:0;if(logBytes-represented2>MAX_LOG_BYTES)await checkpoint()}):checkpoint();void operation.catch(cause=>console.error("The workspace's log could not be checkpointed; it is replayed at the next open.",cause)).finally(()=>{checkpointPending=false})}if(!shared&&!compactingLive&&deadBytes>SESSION_COMPACTION_BYTES&&deadBytes>liveBytes){compactingLive=true;void ownStorageOperation(compactWhileWriting).catch(cause=>console.error("The workspace could not be compacted; it keeps its generation.",cause)).finally(()=>{compactingLive=false})}}async function deferMaintenance(operation){assertWritable();maintenanceDeferrals+=1;try{return await operation()}finally{maintenanceDeferrals-=1;if(maintenanceDeferrals===0&&!closing&&project)maintain()}}function applyMutation(mutation,changes){const path3=requiredPath(mutation.path);if(mutation.operation==="write"){if(entries.get(path3)?.type==="directory")throw new Error(`OPFS write target is a directory: ${path3}`);if(!(mutation.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const value=mutation.content;if(value.byteLength>MAX_FILE_BYTES)throw new Error(`${path3} is ${value.byteLength} bytes; an OPFS workspace file holds at most ${MAX_FILE_BYTES}.`);assertBounds(path3,value.byteLength);createParents(path3,changes);const offset2=appendPack(value);setEntry(path3,{type:mutation.symlink?"symlink":"file",mode:mutation.mode??entries.get(path3)?.mode??FILE_MODE,mtimeMs:mutation.mtimeMs??Date.now(),offset:offset2,length:value.byteLength},changes);return}if(mutation.operation==="append"){const previous=entries.get(path3);if(previous&&previous.type!=="file")throw new Error(`OPFS append target is not a file: ${path3}`);if(!(mutation.content instanceof Uint8Array))throw new Error("OPFS append requires file content.");const added=mutation.content;const length=(previous?.length??0)+added.byteLength;if(length>MAX_FILE_BYTES)throw new Error(`${path3} is ${length} bytes; an OPFS workspace file holds at most ${MAX_FILE_BYTES}.`);assertBounds(path3,length);createParents(path3,changes);const mode=mutation.mode??previous?.mode??FILE_MODE;const mtimeMs=mutation.mtimeMs??Date.now();const room=previous&&!previous.pack?previous.capacity??previous.length:0;if(projectId!==PACKAGES_STORE&&previous&&!previous.pack&&previous.length>0&&(length<=room||previous.offset+room===packBytes)){writePackAt(previous.offset+previous.length,added);setEntry(path3,{...previous,mode,mtimeMs,length,capacity:Math.max(room,length)},changes);deadBytes-=Math.max(previous.length,previous.capacity??0);rewrites-=1;rewrittenBytes-=previous.length;return}const whole=new Uint8Array(length);if(previous&&previous.length>0)whole.set(readEntry(previous),0);whole.set(added,length-added.byteLength);const offset2=appendPack(whole);const capacity=Math.min(MAX_FILE_BYTES,Math.max(length,length*2,64*1024));if(capacity>length)reservePack(offset2+capacity);setEntry(path3,{type:"file",mode,mtimeMs,offset:offset2,length,capacity},changes);return}if(mutation.operation==="write-at"){const previous=entries.get(path3);if(previous&&previous.type!=="file")throw new Error(`OPFS write target is not a file: ${path3}`);if(!(mutation.content instanceof Uint8Array))throw new Error("OPFS write requires file content.");const bytes2=mutation.content;const position=mutation.position;const held=previous?.length??0;if(bytes2.byteLength===0&&previous)return;const length=bytes2.byteLength===0?held:Math.max(held,position+bytes2.byteLength);if(length>MAX_FILE_BYTES)throw new Error(`${path3} is ${length} bytes; an OPFS workspace file holds at most ${MAX_FILE_BYTES}.`);assertBounds(path3,length);createParents(path3,changes);const mode=mutation.mode??previous?.mode??FILE_MODE;const mtimeMs=mutation.mtimeMs??Date.now();const room=previous&&!previous.pack?previous.capacity??previous.length:0;if(projectId!==PACKAGES_STORE&&previous&&!previous.pack&&held>0&&(length<=room||previous.offset+room===packBytes)){if(position>held)writePackAt(previous.offset+held,new Uint8Array(position-held));if(bytesUndo&&position<held){const end=Math.min(held,position+bytes2.byteLength);bytesUndo.push([previous.offset+position,readExtent(previous.offset+position,end-position)])}writePackAt(previous.offset+position,bytes2);setEntry(path3,{...previous,mode,mtimeMs,length,capacity:Math.max(room,length)},changes);if(length!==held){deadBytes-=Math.max(previous.length,previous.capacity??0);rewrites-=1;rewrittenBytes-=previous.length}return}const whole=new Uint8Array(length);if(previous&&held>0)whole.set(readEntry(previous),0);if(bytes2.byteLength>0)whole.set(bytes2,position);const offset2=appendPack(whole);const capacity=Math.min(MAX_FILE_BYTES,Math.max(length,length*2,64*1024));if(capacity>length)reservePack(offset2+capacity);setEntry(path3,{type:"file",mode,mtimeMs,offset:offset2,length,capacity},changes);return}if(mutation.operation==="mkdir"){createParents(path3,changes);const existing=entries.get(path3);if(existing&&existing.type!=="directory")throw new Error(`OPFS path is a file: ${path3}`);setEntry(path3,{type:"directory",mode:mutation.mode??existing?.mode??DIRECTORY_MODE,mtimeMs:mutation.mtimeMs??existing?.mtimeMs??Date.now(),offset:0,length:0},changes);return}if(mutation.operation==="remove"){removeTree3(path3,changes);if(storeRoots().includes(path3)){setEntry(path3,{type:"directory",mode:DIRECTORY_MODE,mtimeMs:Date.now(),offset:0,length:0},changes)}return}if(mutation.operation==="link"){linkShared(path3,sharedPath(mutation.source),changes);return}if(mutation.operation==="rename"){renameTree(path3,requiredPath(mutation.destination),changes);return}const entry=entries.get(path3);if(!entry)throw new Error(`OPFS metadata target does not exist: ${path3}`);setEntry(path3,{...entry,mode:mutation.mode??entry.mode,mtimeMs:mutation.mtimeMs??entry.mtimeMs},changes)}function setEntry(path3,entry,changes){const previous=entries.get(path3);if(mutationUndo&&!mutationUndo.has(path3))mutationUndo.set(path3,previous);const sameExtent=previous!==void 0&&previous.type===entry.type&&previous.offset===entry.offset&&previous.length===entry.length&&previous.pack===entry.pack;if(previous&&!sameExtent){forget(previous,path3);if(previous.type!=="directory"&&entry.type!=="directory"&&previous.length>0&&!previous.pack){rewrites+=1;rewrittenBytes+=previous.length}}entries.set(path3,entry);attach(path3);if(!sameExtent){if(entry.pack){linked+=1;linkedBytes+=entry.length}else liveBytes+=entry.length}changes.push([path3,entry])}function attach(path3){const parent=parentPath(path3);if(parent===path3)return;children.mutable(parent).add(path3.slice(parent.length+1))}function detach(path3){const parent=parentPath(path3);if(children.get(parent)?.has(path3.slice(parent.length+1)))children.mutable(parent).delete(path3.slice(parent.length+1));children.delete(path3)}function rebuildChildren(){children=new LocalChildren;for(const path3 of entries.keys())attach(path3)}function descendants(prefix2){const found=[];const visit=path3=>{const entry=entries.get(path3);if(!entry)return;found.push([path3,entry]);const names2=children.get(path3);if(names2)for(const name of names2)visit(`${path3}/${name}`)};visit(prefix2);return found}function forget(previous,path3){if(previous.pack){linked-=1;linkedBytes-=previous.length;return}liveBytes-=previous.length;deadBytes+=Math.max(previous.length,previous.capacity??0)}function deleteEntry(path3,changes){const previous=entries.get(path3);if(!previous)return;if(mutationUndo&&!mutationUndo.has(path3))mutationUndo.set(path3,previous);entries.delete(path3);detach(path3);forget(previous,path3);changes.push([path3,null])}function linkShared(path3,source,changes){const packages2=options.packages;if(!packages2)throw new Error("This store has no shared package store to link from.");const prefix2=sharedPath(source);const files=packages2.descendants(prefix2);if(files.length===0)throw new Error(`The shared package store does not hold ${source}.`);createParents(path3,changes);removeTree3(path3,changes);assertEntryCount(entries.size+files.length);for(const[candidate,entry]of files){const target=candidate===prefix2?path3:`${path3}${candidate.slice(prefix2.length)}`;setEntry(target,entry.type==="directory"?{type:"directory",mode:entry.mode,mtimeMs:entry.mtimeMs,offset:0,length:0}:{type:entry.type,mode:entry.mode,mtimeMs:entry.mtimeMs,offset:entry.offset,length:entry.length,pack:PACKAGES_STORE},changes)}}function createParents(path3,changes){const above=parentPath(path3);if(above!==path3&&entries.get(above)?.type==="directory"){assertEntryCount(entries.size+(entries.has(path3)?0:1));return}const missing=[];let current3=rootOf(path3)??storeRoots()[0];if(!entries.has(current3))missing.push(current3);if(path3!==current3){for(const segment of segmentsOf(relativePath3(parentPath(path3)))){current3=`${current3}/${segment}`;const existing=entries.get(current3);if(existing&&existing.type!=="directory")throw new Error(`OPFS path parent is a file: ${current3}`);if(!existing)missing.push(current3)}}assertEntryCount(entries.size+missing.length+(entries.has(path3)?0:1));const now=Date.now();for(const directory2 of missing){setEntry(directory2,{type:"directory",mode:DIRECTORY_MODE,mtimeMs:now,offset:0,length:0},changes)}}function removeTree3(path3,changes){for(const[candidate]of descendants(path3))deleteEntry(candidate,changes)}function renameTree(source,destination,changes){if(source===destination)return;if(destination.startsWith(`${source}/`))throw new Error("An OPFS rename cannot move a directory into itself.");const moved=descendants(source);if(moved.length===0){if(entries.has(destination))return;throw new Error(`OPFS rename source does not exist: ${source}`)}createParents(destination,changes);removeTree3(destination,changes);for(const[path3]of moved)deleteEntry(path3,changes);for(const[path3,entry]of moved)setEntry(`${destination}${path3.slice(source.length)}`,entry,changes);assertEntryCount(entries.size)}function sharedPath(value){if(typeof value!=="string"||!value.startsWith(`${PACKAGES_ROOT}/`)||value.includes("\0")||value.length>4096){throw new Error("Invalid shared store path.")}segmentsOf(value.slice(PACKAGES_ROOT.length+1));return value}function storeRoots(){return projectId===PACKAGES_STORE?[PACKAGES_ROOT]:PROJECT_ROOTS}function rootOf(path3){return storeRoots().find(root2=>path3===root2||path3.startsWith(`${root2}/`))}function assertBounds(path3,bytes2){const previous=entries.get(path3);const replaced=previous&&!previous.pack?previous.length:0;if(liveBytes-replaced+bytes2>maximumBytes){throw new Error(`OPFS workspace exceeds its byte limit: writing ${path3} (${bytes2} bytes) would take the project's own files past ${maximumBytes} bytes.`)}}function assertEntryCount(count){if(count>maximumEntries)throw new Error("OPFS workspace exceeds its entry limit.")}function assertWorkspaceQuota(){assertEntryCount(entries.size);if(liveBytes>maximumBytes)throw new Error(`OPFS workspace exceeds its byte limit: the project's own files hold ${liveBytes} bytes, past ${maximumBytes}.`)}function writePackAt(offset2,value){const access=packAccess;if(!access)throw new Error("OPFS filesystem worker is not initialized.");let written=0;while(written<value.byteLength){const count=access.write(value.subarray(written),{at:offset2+written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}packBytes=Math.max(packBytes,offset2+value.byteLength)}function reservePack(end){const access=packAccess;if(!access)throw new Error("OPFS filesystem worker is not initialized.");if(end<=packBytes)return;access.truncate(end);packBytes=end}function appendPack(value){const access=packAccess;if(!access)throw new Error("OPFS filesystem worker is not initialized.");const offset2=packBytes;let written=0;while(written<value.byteLength){const count=access.write(value.subarray(written),{at:offset2+written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}packBytes=offset2+value.byteLength;return offset2}function assertStored(log){const pack=packAccess;if(pack.getSize()>=packBytes&&log.getSize()>=logBytes)return;pack.flush();log.flush();const packSize=pack.getSize(),logSize=log.getSize();if(packSize>=packBytes&&logSize>=logBytes)return;throw Object.assign(new Error(`This browser is keeping less than the tab wrote (the store's pack holds ${packSize} of ${packBytes} bytes, its log ${logSize} of ${logBytes}): its storage is full, as a private window's is well below its quota.`),{name:"QuotaExceededError",code:"ENOSPC"})}function commit(changes,options2={}){const access=logAccess;if(!access||!packAccess)throw new Error("OPFS filesystem worker is not initialized.");if(changes.length===0)return;const body=encoder4.encode(JSON.stringify({packBytes,changes}));if(body.byteLength>MAX_RECORD_BYTES)throw new Error("An OPFS workspace index record exceeds its size limit.");const record=new Uint8Array(RECORD_HEADER_BYTES+body.byteLength);const view=new DataView(record.buffer);view.setUint32(0,body.byteLength,true);view.setUint32(4,fingerprint2(body),true);record.set(body,RECORD_HEADER_BYTES);let written=0;while(written<record.byteLength){const count=access.write(record.subarray(written),{at:logBytes+written});if(count<=0)throw new Error("The OPFS workspace index log could not be written completely.");written+=count}logBytes+=record.byteLength;assertStored(access);if(options2.publish!==false)publishLog();if(performance.now()-lastFlushAt>=FLUSH_WINDOW_MS)flushStorage();else if(flushTimer===void 0)flushTimer=setTimeout(flushStorage,FLUSH_WINDOW_MS)}function flushStorage(){if(flushTimer!==void 0){clearTimeout(flushTimer);flushTimer=void 0}if(mutationFailure)throw mutationFailure;const startedAt=performance.now();packAccess?.flush();logAccess?.flush();lastFlushAt=performance.now();flushes+=1;flushMs+=lastFlushAt-startedAt}function checkpoint(){const previous=checkpointTail;const operation=ownStorageOperation(()=>previous.catch(()=>void 0).then(checkpointStorage));checkpointTail=operation;return operation}async function checkpointStorage(){assertWritable();if(!generation)return;const checkpointGeneration=generation;const access=logAccess;const directory2=await generationDirectory(checkpointGeneration,false);if(!access||access!==logAccess||checkpointGeneration!==generation){throw new Error("OPFS workspace changed generations before its checkpoint could start.")}flushStorage();const checkpointBytes=logBytes;await writeIndexAtomically(directory2,entries,{access,bytes:checkpointBytes,packBytes});if(checkpointGeneration===generation)checkpointPrefix={generation:checkpointGeneration,bytes:checkpointBytes};if(access===logAccess&&checkpointGeneration===generation&&checkpointBytes===logBytes){beginTransition();try{access.truncate(0);access.flush();logBytes=0;checkpointPrefix={generation:checkpointGeneration,bytes:0}}finally{endTransition()}}}function writeGeneration(snapshot){return rewriteGeneration(()=>writeGenerationContents(validateSnapshot(snapshot)))}async function writeGenerationContents(snapshot){const next2=crypto.randomUUID();const directory2=await generationDirectory(next2,true);const handle=await directory2.getFileHandle(PACK_FILE,{create:true});const access=await openSyncAccess(handle,"store");const index2=new Map;let cursor=0;try{for(const entry of snapshot.files){let offset2=0;let length=0;if(entry.type!=="directory"){const value=new Uint8Array(snapshot.pack,entry.offset??0,entry.length??0);offset2=cursor;length=value.byteLength;let written=0;while(written<length){const count=access.write(value.subarray(written),{at:offset2+written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}cursor+=length}index2.set(entry.path,{type:entry.type,mode:entry.mode??(entry.type==="directory"?DIRECTORY_MODE:FILE_MODE),mtimeMs:entry.mtimeMs??Date.now(),offset:offset2,length})}for(const root2 of storeRoots()){if(!index2.has(root2))index2.set(root2,{type:"directory",mode:DIRECTORY_MODE,mtimeMs:Date.now(),offset:0,length:0})}assertEntryCount(index2.size);access.truncate(cursor);access.flush()}finally{access.close()}const prepared=await writeIndexAtomically(directory2,index2);await commitGeneration(next2,directory2,index2,cursor,prepared)}async function compact(){await retain(()=>true)}async function compactWhileWriting(){let transitioning=false;let named=false;let stayed=false;try{await compactWhileWritingIn(()=>{transitioning=true},()=>{named=true},()=>{stayed=true})}finally{if(transitioning&&(named||stayed))endTransition();else if(transitioning)retireClock()}}async function compactWhileWritingIn(began,named,stayed){const next2=crypto.randomUUID();const directory2=await generationDirectory(next2,true);const pack=await openSyncAccess(await directory2.getFileHandle(PACK_FILE,{create:true}),"store");let log;let switched=false;try{log=await openSyncAccess(await directory2.getFileHandle(LOG_FILE,{create:true}),"record of changes");log.truncate(0);const buffer2=new Uint8Array(COPY_BUFFER_BYTES);let cursor=0;const copy2=entry=>{if(entry.pack)return{...entry};if(entry.type==="directory"||entry.length===0)return{...entry,offset:0,length:0};const source=packAccess;if(!source)throw new Error("OPFS filesystem worker is not initialized.");const offset2=cursor;let copied=0;while(copied<entry.length){const span=Math.min(buffer2.byteLength,entry.length-copied);const chunk=buffer2.subarray(0,span);imageReader?.ensure(entry.offset+copied,span);if(source.read(chunk,{at:entry.offset+copied})!==span)throw new Error("An OPFS workspace file could not be read completely.");let written=0;while(written<span){const count=pack.write(chunk.subarray(written),{at:offset2+copied+written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}copied+=span}cursor+=entry.length;const{capacity:_room,...extent}=entry;return{...extent,offset:offset2}};const copies=new Map;let sliceStart=performance.now();for(const[path3,entry]of[...entries]){if(closing||rewritingGeneration)return;if(entries.get(path3)!==entry)continue;copies.set(entry,copy2(entry));if(performance.now()-sliceStart>8){await new Promise(resolve2=>setTimeout(resolve2,0));sliceStart=performance.now()}}if(closing||rewritingGeneration||!packAccess||!logAccess)return;beginTransition();began();const index2=new Map;for(const[path3,entry]of entries)index2.set(path3,copies.get(entry)??copy2(entry));pack.truncate(cursor);pack.flush();log.flush();flushStorage();const previous={pack:packAccess,log:logAccess};packAccess=pack;logAccess=log;logBytes=0;entries=index2;rebuildChildren();packBytes=cursor;generation=next2;generationHandle=directory2;measureBytes();switched=true;const document2=new Map(index2);try{previous.pack.close()}finally{previous.log.close()}try{await writeIndexAtomically(directory2,document2);const state={storageVersion:4,generation:next2,initializedAt:Date.now()};await writeJsonAtomically(await projectDirectory(),STATE_FILE,state)}catch(cause){mutationFailure=new Error("The workspace moved to a compacted generation it could not record; it takes no more writes, which its next open would discard.",{cause});throw mutationFailure}named();await discardGenerations(next2)}finally{if(!switched){stayed();try{pack.close()}finally{log?.close()}await removeGenerationQuietly(await(await projectDirectory()).getDirectoryHandle(GENERATIONS_DIRECTORY),next2)}}}async function remapLinks(moved){assertWritable();beginTransition();try{await remapLinksIn(moved)}finally{endTransition()}}async function remapLinksIn(moved){let changed=false;for(const[path3,entry]of entries){if(!entry.pack||entry.length===0)continue;const offset2=moved.get(entry.offset);if(offset2===void 0)throw new Error(`The shared store no longer holds the bytes of ${path3}.`);if(offset2===entry.offset)continue;entries.set(path3,{...entry,offset:offset2});changed=true}if(changed)await checkpoint()}function retain(keep){return rewriteGeneration(()=>retainGeneration(keep))}async function retainGeneration(keep){const source=packAccess;if(!source)throw new Error("OPFS filesystem worker is not initialized.");const moved=new Map;const next2=crypto.randomUUID();const directory2=await generationDirectory(next2,true);const handle=await directory2.getFileHandle(PACK_FILE,{create:true});const access=await openSyncAccess(handle,"store");const index2=new Map;const buffer2=new Uint8Array(COPY_BUFFER_BYTES);let cursor=0;try{for(const[path3,entry]of entries){if(!keep(path3,entry))continue;if(entry.pack){index2.set(path3,{...entry});continue}if(entry.type==="directory"||entry.length===0){index2.set(path3,{...entry,offset:0,length:0});continue}const offset2=cursor;moved.set(entry.offset,offset2);let copied=0;while(copied<entry.length){const span=Math.min(buffer2.byteLength,entry.length-copied);const chunk=buffer2.subarray(0,span);imageReader?.ensure(entry.offset+copied,span);if(source.read(chunk,{at:entry.offset+copied})!==span){throw new Error("An OPFS workspace file could not be read completely.")}let written=0;while(written<span){const count=access.write(chunk.subarray(written),{at:offset2+copied+written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}copied+=span}cursor+=entry.length;const{capacity:_room,...extent}=entry;index2.set(path3,{...extent,offset:offset2,length:entry.length})}access.truncate(cursor);access.flush()}finally{access.close()}const prepared=await writeIndexAtomically(directory2,index2);await commitGeneration(next2,directory2,index2,cursor,prepared);return moved}async function commitGeneration(name,directory2,index2,bytes2,prepared,rangesDigest){beginTransition();try{await commitGenerationIn(name,directory2,index2,bytes2,prepared,rangesDigest)}finally{endTransition()}}async function commitGenerationIn(name,directory2,index2,bytes2,prepared,rangesDigest){const journal=await directory2.getFileHandle(LOG_FILE,{create:true});const journalAccess=await openSyncAccess(journal,"record of changes");try{journalAccess.truncate(0);journalAccess.flush()}finally{journalAccess.close()}const state={storageVersion:rangesDigest?5:4,generation:name,initializedAt:Date.now(),...rangesDigest?{imageRanges:rangesDigest}:{}};await writeJsonAtomically(await projectDirectory(),STATE_FILE,state);closeGenerationHandles();generation=name;generationInitializedAt=state.initializedAt;imageRangesDigest=rangesDigest;if(prepared){const base=new SharedIndex(prepared.index);entries=new OverlaidIndex(base);children=new OverlaidChildren(base);seedCache=void 0}else{entries=index2;rebuildChildren()}packBytes=bytes2;generationHandle=directory2;await openGenerationHandles(directory2);if(prepared){({liveBytes,linked,linkedBytes}=prepared);deadBytes=Math.max(0,packBytes-liveBytes)}else measureBytes();if(!shared)await discardGenerations(name)}async function installPreparedImage(prepared,json,binary,suppliedRanges,verified=false){assertWritable();if(!shared||projectId!==PACKAGES_STORE)throw new Error("Only the shared package store can reserve immutable image extents.");if(packBytes!==0||[...entries.values()].some(entry=>entry.type!=="directory"))return false;const ranges=validateImageRanges(suppliedRanges);if(ranges.bytes!==prepared.packBytes||prepared.entries>MAX_ENTRIES||prepared.liveBytes>prepared.packBytes||json.byteLength!==prepared.json.raw||binary.byteLength!==prepared.binary.raw||!await matchesDigest(json,prepared.json.sha256,verified)||!await matchesDigest(binary,prepared.binary.sha256,verified)){throw new Error("The image's prepared metadata does not match its document.")}const newline=json.subarray(0,4096).indexOf(10);if(newline<0)throw new Error("The prepared index has no bounded retained header.");const retained=JSON.parse(`${decoder5.decode(json.subarray(0,newline-1))}}`);const measures={packBytes:prepared.packBytes,liveBytes:prepared.liveBytes,linked:0,linkedBytes:0};const header=retained.retainedIndex;if(header.version!==1||header.digest!==await retainedIndexDigestOf(prepared.binary.sha256,measures)||header.packBytes!==measures.packBytes||header.liveBytes!==measures.liveBytes||header.linked!==0||header.linkedBytes!==0){throw new Error("The prepared index's retained measures are inconsistent.")}const index2=new SharedArrayBuffer(binary.byteLength);new Uint8Array(index2).set(binary);if(new SharedIndex(index2).entryCount!==prepared.entries)throw new Error("The prepared index has the wrong number of entries.");return rewriteGeneration(async()=>{const name=crypto.randomUUID();const directory2=await generationDirectory(name,true);const pack=await directory2.getFileHandle(PACK_FILE,{create:true});const access=await openSyncAccess(pack,"immutable image reservation");try{access.truncate(prepared.packBytes);access.flush()}finally{access.close()}const rangeBytes=encoder4.encode(JSON.stringify(ranges));await writeBytesAtomically(directory2,IMAGE_RANGES_FILE,rangeBytes);await writeBytesAtomically(directory2,RETAINED_INDEX_FILE,binary);await writeBytesAtomically(directory2,INDEX_FILE,json);await commitGeneration(name,directory2,new Map,prepared.packBytes,{index:index2,...measures},await indexDigest(rangeBytes));return true})}async function installPreparedProject(prepared,json,binary,verified=false,imageInstalled){assertWritable();if(shared||!options.packages||!imageInstalled&&!options.packages.deferredImage)throw new Error("Prepared project paths require a verified shared image.");if(packBytes!==0||[...entries.values()].some(entry=>entry.type!=="directory"))return false;if(json.byteLength!==prepared.json.raw||binary.byteLength!==prepared.binary.raw||!await matchesDigest(json,prepared.json.sha256,verified)||!await matchesDigest(binary,prepared.binary.sha256,verified)){throw new Error("The image's prepared project does not match its descriptor.")}const newline=json.subarray(0,4096).indexOf(10);if(newline<0)throw new Error("The prepared project has no bounded retained header.");const header=JSON.parse(`${decoder5.decode(json.subarray(0,newline-1))}}`).retainedIndex;const measures={packBytes:0,liveBytes:0,linked:prepared.linked,linkedBytes:prepared.linkedBytes};if(header.version!==1||header.digest!==await retainedIndexDigestOf(prepared.binary.sha256,measures)||header.packBytes!==0||header.liveBytes!==0||header.linked!==prepared.linked||header.linkedBytes!==prepared.linkedBytes){throw new Error("The prepared project's retained measures are inconsistent.")}const index2=new SharedArrayBuffer(binary.byteLength);new Uint8Array(index2).set(binary);if(new SharedIndex(index2).entryCount!==prepared.entries||prepared.entries>maximumEntries)throw new Error("The prepared project has invalid entry bounds.");return rewriteGeneration(async()=>{const name=crypto.randomUUID();const directory2=await generationDirectory(name,true);const pack=await directory2.getFileHandle(PACK_FILE,{create:true});const access=await openSyncAccess(pack,"prepared project");try{access.truncate(0);access.flush()}finally{access.close()}await writeBytesAtomically(directory2,RETAINED_INDEX_FILE,binary);await writeBytesAtomically(directory2,INDEX_FILE,json);if(imageInstalled&&!await imageInstalled)return false;if(!options.packages?.deferredImage)throw new Error("Prepared project paths require a verified shared image.");await commitGeneration(name,directory2,new Map,0,{index:index2,...measures});return true})}async function readSnapshot(){if(closing)throw new Error("This OPFS workspace is closing.");if(!packAccess)throw new Error("OPFS filesystem worker is not initialized.");const files=[];const paths=[...entries.keys()].sort((left,right)=>depth4(left)-depth4(right)||(left<right?-1:1));let total=0;for(const entry of entries.values())if(entry.type!=="directory")total+=entry.length;const pack=new ArrayBuffer(total);const view=new Uint8Array(pack);let cursor=0;for(const path3 of paths){const entry=entries.get(path3);if(entry.type==="directory"){files.push({path:path3,type:"directory",mode:entry.mode,mtimeMs:entry.mtimeMs});continue}if(entry.length>0)view.set(readEntry(entry),cursor);files.push({path:path3,type:entry.type,offset:cursor,length:entry.length,mode:entry.mode,mtimeMs:entry.mtimeMs});cursor+=entry.length}for(const root2 of[...storeRoots()].reverse()){if(!entries.has(root2))files.unshift({path:root2,type:"directory",mode:DIRECTORY_MODE,mtimeMs:Date.now()})}return validateSnapshot({files,pack})}async function writeJsonAtomically(directory2,name,value){await writeBytesAtomically(directory2,name,encoder4.encode(JSON.stringify(value)))}async function writeBytesAtomically(directory2,name,bytes2){const staging=await(await projectDirectory()).getDirectoryHandle(STAGING_DIRECTORY,{create:true});const temporaryName=crypto.randomUUID();const handle=await staging.getFileHandle(temporaryName,{create:true});const access=await openSyncAccess(handle,"index");try{let written=0;while(written<bytes2.byteLength){const count=access.write(bytes2.subarray(written),{at:written});if(count<=0)throw new Error("An OPFS workspace file could not be written completely.");written+=count}access.truncate(bytes2.byteLength);access.flush()}finally{access.close()}try{await handle.move(directory2,name)}finally{await removeEntry(staging,temporaryName,false)}}const RETAINED_INDEX_FILE="index.shared";async function indexDigest(bytes2){const hash3=await crypto.subtle.digest("SHA-256",bytes2);return Array.from(new Uint8Array(hash3),byte=>byte.toString(16).padStart(2,"0")).join("")}async function matchesDigest(bytes2,digest,verified){return verified||await indexDigest(bytes2)===digest}function retainedIndexDigestOf(binaryDigest,measures){const{packBytes:packBytes2,liveBytes:liveBytes2,linked:linked2,linkedBytes:linkedBytes2,journalPrefix}=measures;return indexDigest(encoder4.encode(`${JSON.stringify({packBytes:packBytes2,liveBytes:liveBytes2,linked:linked2,linkedBytes:linkedBytes2,...journalPrefix?{journalPrefix}:{}})}:${binaryDigest}`))}async function retainedIndexDigest(bytes2,measures){const{packBytes:packBytes2,liveBytes:liveBytes2,linked:linked2,linkedBytes:linkedBytes2,journalPrefix}=measures;return indexDigest(encoder4.encode(`${JSON.stringify({packBytes:packBytes2,liveBytes:liveBytes2,linked:linked2,linkedBytes:linkedBytes2,...journalPrefix?{journalPrefix}:{}})}:${await indexDigest(bytes2)}`))}async function writeIndexAtomically(directory2,index2,journal){const document2=indexDocument(index2);if(typeof SharedArrayBuffer==="undefined"||index2.size<1e4){await writeJsonAtomically(directory2,INDEX_FILE,document2);return}const snapshot=new Map(document2.entries);const names2=new Map;const measure={packBytes:journal?.packBytes??0,liveBytes:0,linked:0,linkedBytes:0};for(const[path3,entry]of snapshot){const parent=parentPath(path3);if(parent!==path3){let children2=names2.get(parent);if(!children2){children2=new Set;names2.set(parent,children2)}children2.add(path3.slice(parent.length+1))}if(entry.pack){measure.linked+=1;measure.linkedBytes+=entry.length}else{measure.liveBytes+=entry.length;measure.packBytes=Math.max(measure.packBytes,entry.offset+entry.length)}}let encoded;try{encoded=encodeSharedIndex(snapshot,names2)}catch{await writeJsonAtomically(directory2,INDEX_FILE,document2);return}const json=JSON.stringify(document2.entries);const prefixBytes=journal?new Uint8Array(journal.bytes):void 0;if(prefixBytes&&journal.access.read(prefixBytes,{at:0})!==prefixBytes.byteLength){throw new Error("The checkpoint's journal prefix could not be read completely.")}const journalPrefix=prefixBytes?{bytes:prefixBytes.byteLength,digest:await indexDigest(prefixBytes)}:void 0;const bytes2=new Uint8Array(encoded).slice();const retained={version:journalPrefix?2:1,digest:await retainedIndexDigest(bytes2,{...measure,...journalPrefix?{journalPrefix}:{}}),...measure,...journalPrefix?{journalPrefix}:{}};try{await writeBytesAtomically(directory2,RETAINED_INDEX_FILE,bytes2)}catch{await writeJsonAtomically(directory2,INDEX_FILE,{entries:JSON.parse(json)});return}await writeBytesAtomically(directory2,INDEX_FILE,encoder4.encode(`{"retainedIndex":${JSON.stringify(retained)},
5893
+ "entries":${json}}`));return{index:encoded,...measure}}async function readRetainedIndex(directory2){if(typeof SharedArrayBuffer==="undefined")return void 0;try{const handle=await directory2.getFileHandle(INDEX_FILE);const access=await openSyncAccess(handle,"index");let prefix2;try{const bytes3=new Uint8Array(Math.min(512,access.getSize()));const count=access.read(bytes3,{at:0});prefix2=decoder5.decode(bytes3.subarray(0,count))}finally{access.close()}const firstLine=prefix2.split("\n",1)[0];if(!firstLine.startsWith('{"retainedIndex":')||!firstLine.endsWith(","))return void 0;const retained=JSON.parse(firstLine.slice(0,-1)+"}").retainedIndex;if(retained.version!==1&&retained.version!==2||!/^[a-f0-9]{64}$/u.test(retained.digest)||![retained.packBytes,retained.liveBytes,retained.linked,retained.linkedBytes].every(n8=>Number.isSafeInteger(n8)&&n8>=0))return void 0;if(retained.version===1&&retained.journalPrefix!==void 0)return void 0;if(retained.version===2&&(!retained.journalPrefix||!Number.isSafeInteger(retained.journalPrefix.bytes)||retained.journalPrefix.bytes<0||!/^[a-f0-9]{64}$/u.test(retained.journalPrefix.digest)))return void 0;const binary=await directory2.getFileHandle(RETAINED_INDEX_FILE);const reader=await openSyncAccess(binary,"index");let bytes2;try{const size=reader.getSize();if(size>256*1024*1024)return void 0;bytes2=new Uint8Array(size);if(reader.read(bytes2,{at:0})!==size)return void 0}finally{reader.close()}if(await retainedIndexDigest(bytes2,retained)!==retained.digest)return void 0;const index2=new SharedArrayBuffer(bytes2.byteLength);new Uint8Array(index2).set(bytes2);const base=new SharedIndex(index2);assertEntryCount(base.entryCount);return{...retained,index:index2}}catch{return void 0}}async function verifiedJournalPrefix(retained){const prefix2=retained.journalPrefix;if(!prefix2||!logAccess||!packAccess||prefix2.bytes>logAccess.getSize()||retained.packBytes>packAccess.getSize())return 0;const bytes2=new Uint8Array(prefix2.bytes);if(logAccess.read(bytes2,{at:0})!==bytes2.byteLength)return 0;return await indexDigest(bytes2)===prefix2.digest?prefix2.bytes:0}async function readJson2(directory2,name){let handle;try{handle=await directory2.getFileHandle(name)}catch(cause){if(notFound(cause))return;throw cause}let text;if(readOnly){text=await(await handle.getFile()).text();try{return JSON.parse(text)}catch(cause){throw new Error(`Invalid OPFS workspace metadata (${name}). Stored data was retained.`,{cause})}}const access=await openSyncAccess(handle,"index");try{const size=access.getSize();const value=new Uint8Array(size);if(size>0&&access.read(value,{at:0})!==size){throw new Error("An OPFS workspace file could not be read completely.")}text=decoder5.decode(value)}finally{access.close()}try{return JSON.parse(text)}catch(cause){throw new Error(`Invalid OPFS workspace metadata (${name}). Stored data was retained.`,{cause})}}async function removeEntry(directory2,name,recursive){try{await directory2.removeEntry(name,{recursive})}catch(cause){if(!notFound(cause))throw cause}}async function removeGenerationQuietly(root2,name){try{await root2.removeEntry(name,{recursive:true})}catch{}}function validateMutation(candidate){if(!candidate||typeof candidate!=="object"||Array.isArray(candidate))throw new Error("Invalid OPFS filesystem mutation.");if(candidate.operation!=="write"&&candidate.operation!=="append"&&candidate.operation!=="write-at"&&candidate.operation!=="mkdir"&&candidate.operation!=="remove"&&candidate.operation!=="rename"&&candidate.operation!=="metadata"&&candidate.operation!=="link"){throw new Error("Invalid OPFS filesystem mutation.")}requiredPath(candidate.path);if(candidate.operation==="rename")requiredPath(candidate.destination);if((candidate.operation==="write"||candidate.operation==="append"||candidate.operation==="write-at")&&!(candidate.content instanceof Uint8Array)){throw new Error("Invalid OPFS file content.")}if(candidate.operation==="write-at"&&(!Number.isSafeInteger(candidate.position)||candidate.position<0)){throw new Error("Invalid OPFS write position.")}validateEntryMetadata(candidate);return candidate}function validateMutationBatch(candidate){if(!Array.isArray(candidate)||candidate.length===0||candidate.length>128){throw new Error("Invalid OPFS filesystem mutation batch.")}return candidate.map(mutation=>validateMutation(mutation))}function validateSnapshot(candidate){if(!candidate||!Array.isArray(candidate.files)||candidate.files.length>maximumEntries||!(candidate.pack instanceof ArrayBuffer)){throw new Error("Invalid OPFS workspace snapshot.")}const paths=new Set;const types3=new Map(storeRoots().map(root2=>[root2,"directory"]));let bytes2=0;for(const entry of candidate.files){if(!entry||typeof entry!=="object")throw new Error("Invalid OPFS workspace snapshot entry.");requiredPath(entry.path);if(entry.type!=="file"&&entry.type!=="directory"&&entry.type!=="symlink"||paths.has(entry.path)){throw new Error("Invalid or duplicate OPFS workspace entry.")}paths.add(entry.path);types3.set(entry.path,entry.type);if(storeRoots().includes(entry.path)&&entry.type!=="directory")throw new Error("The OPFS workspace root must be a directory.");if(entry.type!=="directory"){const offset2=entry.offset??0;const length=entry.length??0;if(!Number.isSafeInteger(offset2)||!Number.isSafeInteger(length)||offset2<0||length<0||length>MAX_FILE_BYTES||offset2+length>candidate.pack.byteLength){throw new Error("Invalid OPFS workspace file.")}bytes2+=length;if(bytes2>maximumBytes)throw new Error("OPFS workspace exceeds its byte limit.")}else if((entry.offset??0)!==0||(entry.length??0)!==0){throw new Error("An OPFS workspace directory cannot contain file bytes.")}validateEntryMetadata(entry)}assertEntryCount(types3.size);for(const entry of candidate.files){if(!storeRoots().includes(entry.path)&&types3.get(parentPath(entry.path))!=="directory"){throw new Error(`An OPFS workspace snapshot has no directory parent for ${entry.path}.`)}}return candidate}function validateEntryMetadata(value){if(value.mode!==void 0&&(!Number.isSafeInteger(value.mode)||value.mode<0||value.mode>4095)){throw new Error("Invalid OPFS file mode.")}if(value.mtimeMs!==void 0&&(typeof value.mtimeMs!=="number"||!Number.isFinite(value.mtimeMs)||value.mtimeMs<0)){throw new Error("Invalid OPFS modification time.")}}function indexDocument(index2){return{entries:[...index2]}}function readIndex(value){const index2=new Map;if(value===void 0)throw new Error("The committed OPFS workspace index is missing. Stored data was retained.");if(!value||typeof value!=="object"||!Array.isArray(value.entries)){throw new Error("Invalid OPFS workspace index.")}const rows=value.entries;assertEntryCount(rows.length);for(const row of rows){if(!Array.isArray(row)||row.length!==2)throw new Error("Invalid OPFS workspace index entry.");const path3=requiredPath(row[0]);if(index2.has(path3))throw new Error("Duplicate OPFS workspace index entry.");index2.set(path3,readIndexEntry(row[1]))}return index2}function readIndexEntry(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Invalid OPFS workspace index entry.");const candidate=value;if(candidate.type!=="file"&&candidate.type!=="directory"&&candidate.type!=="symlink")throw new Error("Invalid OPFS workspace index entry.");validateEntryMetadata(candidate);if(candidate.mode===void 0||candidate.mtimeMs===void 0)throw new Error("Invalid OPFS workspace index entry.");if(!Number.isSafeInteger(candidate.offset)||candidate.offset<0||!Number.isSafeInteger(candidate.length)||candidate.length<0||candidate.length>MAX_FILE_BYTES){throw new Error("Invalid OPFS workspace index extent.")}if(candidate.pack!==void 0&&candidate.pack!==PACKAGES_STORE)throw new Error("Invalid OPFS workspace index entry.");return{type:candidate.type,mode:candidate.mode,mtimeMs:candidate.mtimeMs,offset:candidate.offset,length:candidate.length,...candidate.pack?{pack:candidate.pack}:{}}}function readIndexRecord(value){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Invalid OPFS workspace index record.");const candidate=value;if(!Number.isSafeInteger(candidate.packBytes)||candidate.packBytes<0||!Array.isArray(candidate.changes)){throw new Error("Invalid OPFS workspace index record.")}const changes=[];for(const row of candidate.changes){if(!Array.isArray(row)||row.length!==2)throw new Error("Invalid OPFS workspace index record.");changes.push([requiredPath(row[0]),row[1]===null?null:readIndexEntry(row[1])])}return{packBytes:candidate.packBytes,changes}}function readStorageState(value){if(value===void 0)return;if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Invalid OPFS workspace state. Stored data was retained.");const candidate=value;if(candidate.storageVersion!==4&&candidate.storageVersion!==5||candidate.storageVersion===5&&(typeof candidate.imageRanges!=="string"||!/^[a-f0-9]{64}$/u.test(candidate.imageRanges))||candidate.storageVersion===4&&candidate.imageRanges!==void 0||typeof candidate.generation!=="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(candidate.generation)||typeof candidate.initializedAt!=="number"||!Number.isFinite(candidate.initializedAt)){throw new Error("Invalid or unsupported OPFS workspace state. Stored data was retained.")}return candidate}function requiredPath(value){if(typeof value!=="string"||rootOf(value)===void 0||value.includes("\0")||value.length>4096){throw new Error("Invalid OPFS workspace path.")}relativePath3(value);return value}function relativePath3(path3){const root2=rootOf(path3);if(root2===void 0)throw new Error("Invalid OPFS workspace path.");const relative3=path3===root2?"":path3.slice(root2.length+1);segmentsOf(relative3);return relative3}function segmentsOf(relative3){const segments=relative3===""?[]:relative3.split("/");if(segments.some(segment=>!segment||segment==="."||segment===".."||segment.includes("\0"))){throw new Error("Invalid OPFS workspace path segment.")}return segments}function parentPath(path3){const parent=path3.slice(0,path3.lastIndexOf("/"));return parent===""||rootOf(parent)===void 0?rootOf(path3)??path3:parent}function depth4(path3){let segments=1;for(let index2=0;index2<path3.length;index2+=1)if(path3.charCodeAt(index2)===47)segments+=1;return segments}function notFound(cause){return cause instanceof DOMException&&cause.name==="NotFoundError"}function fingerprint2(value){let hash3=2166136261;for(let index2=0;index2<value.byteLength;index2+=1){hash3^=value[index2];hash3=Math.imul(hash3,16777619)}return hash3>>>0}if(typeof addEventListener==="function")addEventListener("close",()=>{packAccess?.flush();logAccess?.flush();closeGenerationHandles();releaseLock?.()});function applyNow(mutations,options2={}){assertWritable();if(mutationUndo)throw new Error("An OPFS mutation batch cannot be nested.");for(const mutation of mutations)validateMutation(mutation);if(!mutations.length)return[];return runBatch(changes=>{for(const mutation of mutations)applyMutation(mutation,changes)},options2)}function applyExtentsNow(bytes2,files,options2={}){assertWritable();if(mutationUndo)throw new Error("An OPFS mutation batch cannot be nested.");for(const file2 of files){requiredPath(file2.path);if(file2.type!=="file"&&file2.type!=="directory"&&file2.type!=="symlink")throw new Error(`OPFS extent ${file2.path} has no valid type.`);if(file2.type==="directory")continue;const{offset:offset2,length}=file2;if(offset2===void 0||length===void 0||!Number.isSafeInteger(offset2)||!Number.isSafeInteger(length)||offset2<0||length<0||offset2+length>bytes2.byteLength)throw new Error(`OPFS extent ${file2.path} lies outside its bytes.`);if(length>MAX_FILE_BYTES)throw new Error(`${file2.path} is ${length} bytes; an OPFS workspace file holds at most ${MAX_FILE_BYTES}.`)}if(!files.length)return[];return runBatch(changes=>{const base=bytes2.byteLength>0?appendPack(bytes2):packBytes;for(const file2 of files){const path3=requiredPath(file2.path);createParents(path3,changes);const existing=entries.get(path3);if(file2.type==="directory"){if(existing&&existing.type!=="directory")throw new Error(`OPFS path is a file: ${path3}`);setEntry(path3,{type:"directory",mode:file2.mode,mtimeMs:file2.mtimeMs,offset:0,length:0},changes);continue}if(existing?.type==="directory")throw new Error(`OPFS write target is a directory: ${path3}`);assertBounds(path3,file2.length);setEntry(path3,{type:file2.type,mode:file2.mode,mtimeMs:file2.mtimeMs,offset:base+file2.offset,length:file2.length},changes)}},options2)}function runBatch(apply,options2){if(!packAccess||!logAccess)throw new Error("OPFS filesystem worker is not initialized.");const before={packBytes,logBytes,liveBytes,deadBytes,rewrites,rewrittenBytes,linked,linkedBytes};const undo=new Map;mutationUndo=undo;const overwritten=[];bytesUndo=overwritten;const changes=[];try{apply(changes);assertWorkspaceQuota();commit(changes,{publish:!options2.durable});if(options2.durable){flushStorage();publishLog()}maintain();return changes}catch(cause){const published=clockView!==void 0&&!clockRetired&&Atomics.load(clockView,STORE_CLOCK_LOG)!==before.logBytes;if(published)beginTransition();for(const[path3,entry]of undo){if(entry===void 0)entries.delete(path3);else entries.set(path3,entry)}rebuildChildren();try{for(let index2=overwritten.length-1;index2>=0;index2-=1)writePackAt(overwritten[index2][0],overwritten[index2][1])}catch(restoreCause){cause=new AggregateError([cause,restoreCause],"OPFS could not restore bytes a failed batch wrote over.")}({packBytes,logBytes,liveBytes,deadBytes,rewrites,rewrittenBytes,linked,linkedBytes}=before);if(flushTimer!==void 0){clearTimeout(flushTimer);flushTimer=void 0}try{logAccess.truncate(logBytes);logAccess.flush();packAccess.truncate(packBytes);packAccess.flush()}catch(rollbackCause){retireClock();mutationFailure=new AggregateError([cause,rollbackCause],"OPFS could not roll back a failed batch; reopen this workspace before writing again.");throw mutationFailure}if(published)endTransition();throw cause}finally{mutationUndo=void 0;bytesUndo=void 0}}function close2(){if(initializing){openingController?.abort(new DOMException("The workspace was closed while opening.","AbortError"));return}if(closing)return;closing=true;if(activeStorageOperations!==0)return;closeStorage()}function closeStorage(){retireClock();try{flushStorage()}finally{try{closeGenerationHandles()}finally{const release2=releaseLock;releaseLock=void 0;project=void 0;try{release2?.()}finally{if(options.ownsPackages)options.packages?.close()}}}}return{initialize:initialize2,opened:()=>project!==void 0&&!closing,stats:()=>({entries:entries.size,liveBytes,deadBytes,packBytes,rewrites,rewrittenBytes,linked,linkedBytes,flushes,flushMs}),applyNow,applyExtentsNow,close:close2,readExtent,descendants,retain,remapLinks,childrenOf:path3=>[...children.get(path3)??[]].sort(),refresh,follow,clock,readerSeed,imageCompletionSeed,imageLine:()=>imageReader?.lineForReader()??options.packages?.imageLine(),imageStartupSet:()=>imageReader?.readDigests()??imageReader?.completedDigests()??[],prefetchImage:(digests,streams2)=>imageReader?.prefetch(digests,streams2)??{queued:0,done:Promise.resolve()},seeded:()=>startedFromSeed,get logBytes(){return logBytes},checkpoint,deferMaintenance,installPreparedImage,installPreparedProject,get deferredImage(){return deferredImage},get imagePlacedAt(){return project&&imageRangesDigest?generationInitializedAt:void 0},get entries(){return entries},get packBytes(){return packBytes},read,readRange,snapshot:readSnapshot,replace:writeGeneration,apply:applyMutations,flush:()=>{if(closing||!project)throw new Error("This OPFS workspace is not open.");if(rewritingGeneration)throw new Error("Wait for the OPFS generation replacement before flushing it.");flushStorage()},validateSnapshot,validateMutationBatch}}async function openPackReader(environment,projectId,seed,imageLine){const packages2=createPackStore(environment);await packages2.initialize(PACKAGES_STORE,{readOnly:true,extentsOnly:true,...seed?.packagesImage?{imageCompletion:seed.packagesImage,...imageLine?{imageLine}:{}}:{}});const project=createPackStore(environment,{packages:packages2,ownsPackages:true});let opened;try{opened=await project.initialize(projectId,{readOnly:true,...seed?{seed}:{}})}catch(cause){project.close();packages2.close();throw cause}if(!opened&&!project.opened()){packages2.close();return void 0}return project}var SWEEP_COMPACTION_BYTES=64*1024*1024;var SWEEP_INTERVAL_MS=24*60*60*1e3;var SWEEP_MARK_FILE="sweep.json";var SWEEP_GRACE_MS=14*24*60*60*1e3;async function sweepSharedPackages(environment,progress){const locks=environment.navigator.locks;if(!locks)return void 0;return locks.request(PACKAGES_OPEN_LOCK,{mode:"exclusive",ifAvailable:true},async lock=>{if(!lock)return void 0;const root2=await environment.navigator.storage.getDirectory();let base;try{base=await root2.getDirectoryHandle(BASE_DIRECTORY)}catch{return void 0}let packagesDirectory;try{packagesDirectory=await base.getDirectoryHandle(PACKAGES_STORE)}catch{return void 0}const lastSweep=await readSweepMark(packagesDirectory);if(lastSweep!==void 0&&Date.now()-lastSweep<SWEEP_INTERVAL_MS)return void 0;const projectIds=[];for await(const[name,handle]of base.entries()){if(handle.kind==="directory"&&name!==PACKAGES_STORE&&name!==STAGING_DIRECTORY&&!name.startsWith(TREE_STORE_PREFIX))projectIds.push(name)}const shared=createPackStore(environment);if(!await shared.initialize(PACKAGES_STORE,{shared:true})){shared.close();return void 0}const projects=[];const referenced=new Set;try{for(const[index2,id2]of projectIds.entries()){progress?.(`sweeping the origin's packages, project ${index2+1} of ${projectIds.length}`);const project=createPackStore(environment,{packages:shared});try{const opened=await project.initialize(id2);if(!opened&&!project.opened()){project.close();continue}}catch{project.close();continue}for(const entry of project.entries.values())if(entry.pack&&entry.length>0)referenced.add(entry.offset);projects.push(project)}const kept=new Set;const now=Date.now();for(const[path3,entry]of shared.entries){const unit=unitOf(path3);if(unit===void 0)continue;const linked=entry.type!=="directory"&&entry.length>0&&referenced.has(entry.offset);const recent=path3===`${PACKAGES_ROOT}/${unit}`&&now-Math.max(entry.mtimeMs,shared.imagePlacedAt??0)<SWEEP_GRACE_MS;if(linked||recent)kept.add(unit)}let packagesDropped=0;let bytesDropped=0;const units=new Set;for(const[path3,entry]of shared.entries){const unit=unitOf(path3);if(unit===void 0)continue;units.add(unit);if(!kept.has(unit)&&entry.type!=="directory")bytesDropped+=entry.length}if([...units].some(unit=>!kept.has(unit)&&unit!==".layers"&&unit!==".layers-deferred")){kept.delete(".layers");kept.delete(".layers-deferred")}for(const unit of units)if(!kept.has(unit))packagesDropped+=1;const keep=path3=>{const unit=unitOf(path3);return unit===void 0||kept.has(unit)};let compacted=false;if(packagesDropped>0){if(bytesDropped>=SWEEP_COMPACTION_BYTES||bytesDropped*4>=shared.packBytes){progress?.("sweeping the origin's packages, compacting");const moved=await shared.retain(keep);for(const project of projects)await project.remapLinks(moved);compacted=true}else{const removals=[];for(const unit of units)if(!kept.has(unit))removals.push({operation:"remove",path:`${PACKAGES_ROOT}/${unit}`});for(let offset2=0;offset2<removals.length;offset2+=128)await shared.apply(removals.slice(offset2,offset2+128))}}await writeSweepMark(packagesDirectory);return{projects:projects.length,packagesKept:kept.size,packagesDropped,bytesDropped,compacted}}finally{for(const project of projects)project.close();shared.close()}})}async function readSweepMark(directory2){try{const file2=await(await directory2.getFileHandle(SWEEP_MARK_FILE)).getFile();const mark=JSON.parse(await file2.text());return typeof mark.at==="number"&&Number.isFinite(mark.at)?mark.at:void 0}catch{return void 0}}async function writeSweepMark(directory2){const handle=await directory2.getFileHandle(SWEEP_MARK_FILE,{create:true});const writable=await handle.createWritable();await writable.write(JSON.stringify({at:Date.now()}));await writable.close()}function unitOf(path3){if(!path3.startsWith(`${PACKAGES_ROOT}/`))return void 0;const parts=path3.slice(PACKAGES_ROOT.length+1).split("/");if(parts[0]===".modules")return parts.length>=4?parts.slice(0,4).join("/"):void 0;if(parts[0]===".programs")return parts.length>=2?parts.slice(0,2).join("/"):void 0;if(parts[0]===".browser-packs"){if(parts[1]==="objects"&&parts.length>=3)return parts.slice(0,3).join("/");if(parts[1]==="locks"&&parts.length>=3)return parts.slice(0,3).join("/");return void 0}const packageLength=parts[0]?.startsWith("@")?2:1;return parts.length>=packageLength?parts.slice(0,packageLength).join("/"):void 0}var LocalChildren=class{map=new Map;get(path3){return this.map.get(path3)}mutable(path3){let names2=this.map.get(path3);if(!names2){names2=new Set;this.map.set(path3,names2)}return names2}delete(path3){this.map.delete(path3)}};function storeImportMutations(store,tree2,inside){const root2=normalize2(tree2.root);if(root2!==tree2.root||root2.includes("\0")||root2.includes("\\")||root2.length>4096)throw new Error("Invalid workspace import root.");if(!inside(root2))return false;if(!Array.isArray(tree2.entries)||!tree2.entries.length||tree2.entries.length>5e4)throw new Error("Invalid workspace import entry count.");const incoming2=new Map;let bytes2=0;for(const entry of tree2.entries){if(!entry||typeof entry.path!=="string"||normalize2(entry.path)!==entry.path||entry.path.includes("\0")||entry.path.includes("\\")||entry.path.length>4096||entry.path!==root2&&!entry.path.startsWith(`${root2}/`)||incoming2.has(entry.path)||entry.type!=="file"&&entry.type!=="directory"||!Number.isInteger(entry.mode)||entry.mode<0||entry.mode>4095||!Number.isFinite(entry.mtimeMs)||entry.mtimeMs<0)throw new Error("Invalid workspace import entry.");if(entry.type==="file"){if(!(entry.bytes instanceof Uint8Array))throw new Error("Workspace import file has no bytes.");bytes2+=entry.bytes.byteLength;if(bytes2>128*1024*1024)throw new Error("Workspace import exceeds its byte limit.")}incoming2.set(entry.path,entry)}if(incoming2.get(root2)?.type!=="directory")throw new Error("Workspace import has no root directory.");for(const entry of incoming2.values()){if(entry.path!==root2&&incoming2.get(parentOf(entry.path))?.type!=="directory"){throw new Error(`Workspace import has no parent directory for ${entry.path}.`)}const current3=store.entries.get(entry.path);if(!tree2.replace&&current3&&current3.type!==entry.type)throw new Error(`Workspace import conflicts with ${entry.path}.`)}const heldRoot=store.entries.get(root2);if(tree2.requireEmpty&&heldRoot&&(heldRoot.type!=="directory"||store.childrenOf(root2).length>0)){throw new Error(`Workspace import target is not empty: ${root2}`)}const mutations=tree2.replace?[{operation:"remove",path:root2}]:[];for(const entry of[...incoming2.values()].sort((left,right)=>depth(left.path)-depth(right.path))){mutations.push(entry.type==="directory"?{operation:"mkdir",path:entry.path,mode:entry.mode,mtimeMs:entry.mtimeMs}:{operation:"write",path:entry.path,content:entry.bytes,mode:entry.mode,mtimeMs:entry.mtimeMs})}return mutations}function normalize2(path3){if(path3.startsWith("/")&&(path3.length===1||!path3.endsWith("/"))&&!path3.includes("//")&&!path3.includes("/./")&&!path3.includes("/../")&&!path3.endsWith("/.")&&!path3.endsWith("/.."))return path3;const parts=[];for(const part of`/${path3}`.split("/")){if(!part||part===".")continue;if(part==="..")parts.pop();else parts.push(part)}return`/${parts.join("/")}`}function parentOf(path3){const at3=path3.lastIndexOf("/");return at3<=0?"/":path3.slice(0,at3)}function depth(path3){let segments=1;for(let index2=0;index2<path3.length;index2+=1)if(path3.charCodeAt(index2)===47)segments+=1;return segments}var DIRECTORY_MODE2=493;var FILE_MODE2=420;var PackedVirtualFS=class extends VirtualFS{storeRoots;store;changeListeners=new Set;deleteListeners=new Set;storeWatchers=new Map;textDecoder=new TextDecoder;textEncoder=new TextEncoder;constructor(store,roots=PROJECT_ROOTS,options={}){super();this.store=store;this.storeRoots=typeof roots==="string"?[roots]:roots;if(options.reader===true)return;for(const root2 of this.storeRoots){if(store.entries.has(root2))continue;try{store.applyNow([{operation:"mkdir",path:root2,mode:DIRECTORY_MODE2,mtimeMs:Date.now()}])}catch{}}}on(event,listener){if(event==="change")this.changeListeners.add(listener);else if(event==="delete")this.deleteListeners.add(listener);super.on(event,listener);return this}off(event,listener){if(event==="change")this.changeListeners.delete(listener);else if(event==="delete")this.deleteListeners.delete(listener);super.off(event,listener);return this}existsSync(path3){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized))return super.existsSync(normalized);return this.store.entries.has(normalized)}statSync(path3,options){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized))return super.statSync(normalized,options);const entry=this.store.entries.get(normalized);if(!entry){if(options?.throwIfNoEntry===false)return void 0;throw nodeError("ENOENT","stat",normalized)}return statsOf(entry)}lstatSync(path3,options){const normalized=normalize3(path3);const resolved=this.packedResolve(normalized,true);if(!this.packedInside(resolved))return super.lstatSync(resolved,options);const entry=this.store.entries.get(resolved);if(!entry){if(options?.throwIfNoEntry===false)return void 0;throw nodeError("ENOENT","lstat",resolved)}return statsOf(entry)}readFileSync(path3,encoding){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized))return encoding?super.readFileSync(normalized,encoding):super.readFileSync(normalized);const entry=this.store.entries.get(normalized);if(!entry)throw nodeError("ENOENT","open",normalized);if(entry.type!=="file")throw nodeError("EISDIR","read",normalized);const bytes2=this.store.read(normalized);return encoding?this.textDecoder.decode(bytes2):bytes2}readdirSync(path3){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized))return super.readdirSync(normalized);const entry=this.store.entries.get(normalized);if(!entry)throw nodeError("ENOENT","scandir",normalized);if(entry.type!=="directory")throw nodeError("ENOTDIR","scandir",normalized);return this.store.childrenOf(normalized)}holds(path3,keepLast=false){return this.packedInside(this.packedResolve(normalize3(path3),keepLast))}realpathSync(path3){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized))return super.realpathSync(normalized);if(!this.store.entries.has(normalized))throw nodeError("ENOENT","realpath",normalized);return normalized}accessSync(path3,mode){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized)){super.accessSync(normalized,mode);return}if(!this.store.entries.has(normalized))throw nodeError("ENOENT","access",normalized)}symlinkSync(target,path3){const normalized=this.packedResolve(normalize3(path3),true);if(!this.packedInside(normalized)){super.symlinkSync(target,normalized);return}const parent=this.store.entries.get(parentOf2(normalized));if(!parent||parent.type!=="directory")throw nodeError("ENOENT","symlink",normalized);if(this.store.entries.has(normalized))throw nodeError("EEXIST","symlink",normalized);this.packedApply([{operation:"write",path:normalized,content:this.textEncoder.encode(String(target)),symlink:true,mode:511,mtimeMs:Date.now()}])}readlinkSync(path3){const normalized=this.packedResolve(normalize3(path3),true);if(!this.packedInside(normalized))return super.readlinkSync(normalized);const entry=this.store.entries.get(normalized);if(!entry)throw nodeError("ENOENT","readlink",normalized);if(entry.type!=="symlink")throw nodeError("EINVAL","readlink",normalized);return this.textDecoder.decode(this.store.read(normalized))}writeFileSync(path3,data2){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized)){super.writeFileSync(path3,data2);return}const existing=this.store.entries.get(normalized);if(existing?.type==="directory")throw nodeError("EISDIR","open",normalized);const content=typeof data2==="string"?this.textEncoder.encode(data2):data2;this.packedAppeared(this.packedApply([{operation:"write",path:normalized,content,mode:existing?.mode??FILE_MODE2,mtimeMs:Date.now()}]));this.packedChanged(normalized,typeof data2==="string"?data2:void 0,existing===void 0?"rename":"change")}appendFileSync(path3,data2){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized)){super.appendFileSync(path3,data2);return}const existing=this.store.entries.get(normalized);if(existing?.type==="directory")throw nodeError("EISDIR","open",normalized);const content=typeof data2==="string"?this.textEncoder.encode(data2):data2;this.packedAppeared(this.packedApply([{operation:"append",path:normalized,content,mode:existing?.mode??FILE_MODE2,mtimeMs:Date.now()}]));this.packedChanged(normalized,void 0,existing===void 0?"rename":"change")}writeAtSync(path3,data2,position){const normalized=this.packedResolve(normalize3(path3));if(!this.packedInside(normalized)){super.writeAtSync(path3,data2,position);return}const existing=this.store.entries.get(normalized);if(existing?.type==="directory")throw nodeError("EISDIR","open",normalized);this.packedAppeared(this.packedApply([{operation:"write-at",path:normalized,content:data2,position,mode:existing?.mode??FILE_MODE2,mtimeMs:Date.now()}]));this.packedChanged(normalized,void 0,existing===void 0?"rename":"change")}mkdirSync(path3,options){const normalized=this.packedResolve(normalize3(path3),true);if(!this.packedInside(normalized)){super.mkdirSync(path3,options);return}const existing=this.store.entries.get(normalized);if(existing){if(options?.recursive&&existing.type==="directory")return;throw nodeError("EEXIST","mkdir",normalized)}if(!options?.recursive){const parent=parentOf2(normalized);const above=this.store.entries.get(parent);if(!above&&this.packedInside(parent))throw nodeError("ENOENT","mkdir",normalized);if(above&&above.type!=="directory")throw nodeError("ENOTDIR","mkdir",normalized)}this.packedAppeared(this.packedApply([{operation:"mkdir",path:normalized,mode:DIRECTORY_MODE2,mtimeMs:Date.now()}]))}unlinkSync(path3){const normalized=this.packedResolve(normalize3(path3),true);if(!this.packedInside(normalized)){super.unlinkSync(path3);return}const entry=this.store.entries.get(normalized);if(!entry)throw nodeError("ENOENT","unlink",normalized);if(entry.type==="directory")throw nodeError("EISDIR","unlink",normalized);this.packedApply([{operation:"remove",path:normalized,recursive:false}]);this.packedDeleted(normalized)}rmdirSync(path3){const normalized=normalize3(path3);if(!this.packedInside(normalized)){super.rmdirSync(path3);return}const entry=this.store.entries.get(normalized);if(!entry)throw nodeError("ENOENT","rmdir",normalized);if(entry.type!=="directory")throw nodeError("ENOTDIR","rmdir",normalized);if(this.store.childrenOf(normalized).length>0)throw nodeError("ENOTEMPTY","rmdir",normalized);this.packedApply([{operation:"remove",path:normalized,recursive:true}]);this.packedDeleted(normalized)}linkShared(source,path3){this.linkSharedBatch([{source,path:path3}])}linkSharedBatch(links){const mutations=links.map(({source,path:path3})=>{const normalized=normalize3(path3);if(!this.packedInside(normalized))throw new Error(`A shared path can only be linked inside ${this.storeRoots.join(" or ")}.`);return{operation:"link",path:normalized,source}});const startedAt=performance.now();const changes=this.store.applyNow(mutations);const indexedAt=performance.now();this.linkTiming.indexMs+=indexedAt-startedAt;for(const[changed,entry]of changes){if(entry===null){this.packedDeleted(changed);continue}if(entry.type==="file")this.packedChanged(changed,void 0)}this.linkTiming.announceMs+=performance.now()-indexedAt}linkTiming={indexMs:0,announceMs:0};chmodSync(path3,mode){const normalized=normalize3(path3);if(!this.packedInside(normalized))return;if(!this.store.entries.has(normalized))throw nodeError("ENOENT","chmod",normalized);this.packedApply([{operation:"metadata",path:normalized,mode:mode&4095}])}utimesSync(path3,_atime,mtime){const normalized=normalize3(path3);if(!this.packedInside(normalized))return;if(!this.store.entries.has(normalized))throw nodeError("ENOENT","utimes",normalized);this.packedApply([{operation:"metadata",path:normalized,mtimeMs:typeof mtime==="number"?mtime:mtime.getTime()}])}renameSync(oldPath,newPath){const source=normalize3(oldPath);const destination=normalize3(newPath);const sourceInside=this.packedInside(source);const destinationInside=this.packedInside(destination);if(!sourceInside&&!destinationInside){super.renameSync(oldPath,newPath);return}if(sourceInside&&destinationInside){if(!this.store.entries.has(source))throw nodeError("ENOENT","rename",source);const moved=[source];for(let index2=0;index2<moved.length;index2+=1){const path3=moved[index2];if(this.store.entries.get(path3)?.type!=="directory")continue;for(const name of this.store.childrenOf(path3))moved.push(`${path3}/${name}`)}this.packedApply([{operation:"rename",path:source,destination}]);for(const path3 of moved)this.packedDeleted(path3);for(const path3 of moved)this.packedChanged(`${destination}${path3.slice(source.length)}`,void 0);return}this.packedCopyTree(source,destination);this.packedRemoveTree(source)}copyFileSync(src,dest){this.writeFileSync(dest,this.readFileSync(src))}watchedPaths(){const paths=[];for(const[path3,set]of this.storeWatchers)if(set.size>0)paths.push({path:path3,recursive:[...set].some(entry=>entry.recursive)});const overlay=this.watchers;for(const[path3,set]of overlay??[]){const live2=[...set].filter(entry=>!entry.closed);if(live2.length>0)paths.push({path:path3,recursive:live2.some(entry=>entry.recursive===true)})}return paths}watch(filename,optionsOrListener,listener){const normalized=normalize3(filename);const inside=this.packedInside(normalized);const above=this.storeRoots.some(root2=>normalized==="/"||root2.startsWith(normalized+"/"));if(!inside&&!above)return super.watch(filename,optionsOrListener,listener);const overlay=inside?void 0:super.watch(filename,optionsOrListener,listener);const options=typeof optionsOrListener==="function"?{}:optionsOrListener??{};const actual=typeof optionsOrListener==="function"?optionsOrListener:listener;const entry={listener:actual??(()=>void 0),recursive:options.recursive??false};let set=this.storeWatchers.get(normalized);if(!set){set=new Set;this.storeWatchers.set(normalized,set)}set.add(entry);const watcher={close:()=>{set.delete(entry);overlay?.close()},ref(){overlay?.ref();return this},unref(){overlay?.unref();return this}};return watcher}toSnapshot(){const base=super.toSnapshot();const files=base.files.filter(entry=>!this.packedInside(entry.path));const paths=[...this.store.entries.keys()].sort((left,right)=>depth2(left)-depth2(right)||(left<right?-1:1));for(const path3 of paths){const entry=this.store.entries.get(path3);const metadata={mode:entry.mode&4095,mtimeMs:entry.mtimeMs};if(entry.type==="directory")files.push({path:path3,type:"directory",...metadata});else if(entry.type==="symlink")files.push({path:path3,type:"symlink",target:this.textDecoder.decode(this.store.read(path3)),...metadata});else files.push({path:path3,type:"file",content:base642(this.store.read(path3)),...metadata})}return{...base,files}}packedInside(path3){return this.storeRoots.some(root2=>path3===root2||path3.startsWith(`${root2}/`))}typeOf(path3){const entries=this.store.entries;return entries.typeOf?entries.typeOf(path3):entries.get(path3)?.type}packedResolve(path3,keepLast=false){if(!this.packedInside(path3))return path3;const direct=this.typeOf(path3);if(direct?direct!=="symlink"||keepLast:this.typeOf(parentOf2(path3))==="directory")return path3;let current3=path3;for(let hops=0;hops<40;hops+=1){const parts=current3.split("/").filter(Boolean);let prefix2="";let followed=false;for(let index2=0;index2<parts.length;index2+=1){prefix2=`${prefix2}/${parts[index2]}`;if(!this.packedInside(prefix2))return current3;if(keepLast&&index2===parts.length-1)break;const type2=this.typeOf(prefix2);if(!type2)return current3;if(type2!=="symlink")continue;const target=this.textDecoder.decode(this.store.read(prefix2));const base=target.startsWith("/")?target:`${parentOf2(prefix2)}/${target}`;current3=normalize3(`${base}/${parts.slice(index2+1).join("/")}`.replace(/\/$/u,""));followed=true;break}if(!followed)return current3}throw nodeError("ELOOP","stat",path3)}packedApply(mutations,options){return this.store.applyNow(mutations,options)}applyBatch(mutations){for(const mutation of mutations){if(typeof mutation.path!=="string"||!this.packedInside(normalize3(mutation.path))){throw new Error(`A batch can only be applied inside ${this.storeRoots.join(" or ")}.`)}}const changes=this.packedApply(mutations);for(const[path3,entry]of changes){if(entry===null)this.packedDeleted(path3);else if(entry.type==="file")this.packedChanged(path3,void 0)}}importTree(tree2){const mutations=storeImportMutations(this.store,tree2,path3=>this.packedInside(path3));if(!mutations)return false;const changes=this.packedApply(mutations,{durable:true});for(const[path3,entry]of changes){try{if(entry===null)this.packedDeleted(path3);else if(entry.type==="file")this.packedChanged(path3,void 0)}catch(cause){console.error("Workspace import observer failed.",cause)}}return true}packedAppeared(changes){for(const[path3,entry]of changes)if(entry!==null&&entry.type==="directory")this.packedNotifyWatchers(path3,"rename")}packedChanged(path3,text,event="change"){for(const listener of this.changeListeners)listener(path3,text??"");this.packedNotifyWatchers(path3,event)}packedDeleted(path3){for(const listener of this.deleteListeners)listener(path3);this.packedNotifyWatchers(path3,"rename")}packedNotifyWatchers(path3,event){for(const[watched,set]of this.storeWatchers){if(path3!==watched&&watched!=="/"&&!path3.startsWith(`${watched}/`))continue;const relative3=path3===watched?path3.slice(path3.lastIndexOf("/")+1):path3.slice(watched==="/"?1:watched.length+1);for(const entry of set){if(path3!==watched&&!entry.recursive&&relative3.includes("/"))continue;entry.listener(event,relative3)}}}packedCopyTree(source,destination){const stat2=this.statSync(source);if(stat2.isDirectory()){this.mkdirSync(destination,{recursive:true});for(const name of this.readdirSync(source))this.packedCopyTree(`${source}/${name}`,`${destination}/${name}`);return}this.writeFileSync(destination,this.readFileSync(source))}packedRemoveTree(path3){const stat2=this.statSync(path3);if(stat2.isDirectory()){for(const name of this.readdirSync(path3))this.packedRemoveTree(`${path3}/${name}`);this.rmdirSync(path3);return}this.unlinkSync(path3)}};function statsOf(entry){const isFile2=entry.type==="file";const isLink=entry.type==="symlink";const when=new Date(entry.mtimeMs);return{isFile:()=>isFile2,isDirectory:()=>entry.type==="directory",isSymbolicLink:()=>isLink,isBlockDevice:()=>false,isCharacterDevice:()=>false,isFIFO:()=>false,isSocket:()=>false,size:entry.type==="directory"?0:entry.length,mode:(isFile2?32768:isLink?40960:16384)|entry.mode,mtime:when,atime:when,ctime:when,birthtime:when,mtimeMs:entry.mtimeMs,atimeMs:entry.mtimeMs,ctimeMs:entry.mtimeMs,birthtimeMs:entry.mtimeMs,nlink:1,uid:0,gid:0,dev:0,ino:0,rdev:0,blksize:4096,blocks:Math.ceil((isFile2?entry.length:0)/512)}}function nodeError(code3,syscall,path3){const messages3={ENOENT:"no such file or directory",ENOTDIR:"not a directory",EISDIR:"is a directory",EEXIST:"file already exists",ENOTEMPTY:"directory not empty",EINVAL:"invalid argument",ELOOP:"too many symbolic links encountered"};const errno={ENOENT:-2,ENOTDIR:-20,EISDIR:-21,EEXIST:-17,ENOTEMPTY:-39,EINVAL:-22,ELOOP:-40};return Object.assign(new Error(`${code3}: ${messages3[code3]}, ${syscall} '${path3}'`),{code:code3,errno:errno[code3],syscall,path:path3})}function normalize3(path3){if(path3.startsWith("/")&&(path3.length===1||!path3.endsWith("/"))&&!path3.includes("//")&&!path3.includes("/./")&&!path3.includes("/../")&&!path3.endsWith("/.")&&!path3.endsWith("/.."))return path3;const parts=[];for(const part of`/${path3}`.split("/")){if(!part||part===".")continue;if(part==="..")parts.pop();else parts.push(part)}return`/${parts.join("/")}`}function parentOf2(path3){const at3=path3.lastIndexOf("/");return at3<=0?"/":path3.slice(0,at3)}function base642(value){let binary="";for(let offset2=0;offset2<value.byteLength;offset2+=32768){binary+=String.fromCharCode(...value.subarray(offset2,Math.min(value.byteLength,offset2+32768)))}return btoa(binary)}function depth2(path3){let segments=1;for(let index2=0;index2<path3.length;index2+=1)if(path3.charCodeAt(index2)===47)segments+=1;return segments}function storeReads(grant){const{opening,clock:buffer2}=grant;const clock=new Int32Array(buffer2);let reader;let local2;let synced=-1;void opening.then(opened=>{if(!opened)return;reader=opened;local2=new PackedVirtualFS(opened,PROJECT_ROOTS,{reader:true});const openedAt=grant.openedAt;if((openedAt&1)===0&&Atomics.load(clock,STORE_CLOCK_EPOCH)===openedAt)synced=openedAt},()=>void 0);let resyncing=false;let retryAt=0;const resync=epoch=>{if(resyncing||!reader||performance.now()<retryAt)return;resyncing=true;reader.refresh({whole:true}).then(()=>{if(Atomics.load(clock,STORE_CLOCK_EPOCH)===epoch)synced=epoch},()=>{retryAt=performance.now()+1e3}).finally(()=>{resyncing=false})};return(path3,keepLast,read)=>{if(!reader||!local2)return void 0;const epoch=Atomics.load(clock,STORE_CLOCK_EPOCH);if(resyncing)return void 0;if(epoch!==synced){if((epoch&1)===0)resync(epoch);return void 0}const published=Atomics.load(clock,STORE_CLOCK_LOG);if(reader.logBytes<published){try{reader.follow()}catch{return void 0}if(reader.logBytes<published)return void 0}let value;try{if(!local2.holds(path3,keepLast))return void 0;value=read(local2)}catch(cause){if(Atomics.load(clock,STORE_CLOCK_EPOCH)!==epoch||typeof cause?.code!=="string")return void 0;throw cause}if(Atomics.load(clock,STORE_CLOCK_EPOCH)!==epoch)return void 0;return{value}}}function validateNodePreparedFiles(files,limits){if(!Number.isSafeInteger(limits.maxBytes)||limits.maxBytes<1||!Number.isSafeInteger(limits.maxEntries)||limits.maxEntries<1||!Array.isArray(files)||files.length>limits.maxEntries)throw new Error("Invalid Node prepared-file limits or count.");const paths=new Map([["/","directory"]]);const encoder7=new TextEncoder;let bytes2=1;for(const file2 of files){if(!file2||typeof file2.path!=="string"||file2.path.length>limits.maxBytes||!file2.path.startsWith("/")||file2.path.endsWith("/")||file2.path.includes("\0")||file2.path.slice(1).split("/").some(part=>!part||part==="."||part==="..")||!(file2.bytes instanceof Uint8Array)||paths.has(file2.path))throw new Error("Invalid Node prepared file.");let parent="";for(const part of file2.path.slice(1).split("/").slice(0,-1)){parent+=`/${part}`;if(paths.get(parent)==="file")throw new Error("Node prepared file conflicts with a directory.");if(!paths.has(parent)){paths.set(parent,"directory");bytes2+=encoder7.encode(parent).byteLength}}paths.set(file2.path,"file");bytes2+=encoder7.encode(file2.path).byteLength+file2.bytes.byteLength;if(paths.size>limits.maxEntries)throw new Error("Node prepared files exceed their entry limit.");if(bytes2>limits.maxBytes)throw new Error("Node prepared files exceed their byte limit.")}}function captureNodePreparedFiles(filesystem,limits){validateNodePreparedFiles([],limits);const paths=["/"];const files=[];const encoder7=new TextEncoder;let entries=0,bytes2=0;while(paths.length){const path3=paths.pop();if(++entries>limits.maxEntries)throw new Error("Node prepared files exceed their entry limit.");const stat2=filesystem.lstatSync(path3);bytes2+=encoder7.encode(path3).byteLength;if(stat2.isFile()){bytes2+=stat2.size;files.push(path3)}else if(stat2.isDirectory()){const names2=filesystem.readdirSync(path3);if(entries+paths.length+names2.length>limits.maxEntries)throw new Error("Node prepared files exceed their entry limit.");for(const name of names2)paths.push(`${path3==="/"?"":path3}/${name}`)}else throw new Error("Node prepared files cannot contain symbolic links.");if(bytes2>limits.maxBytes)throw new Error("Node prepared files exceed their byte limit.")}return files.map(path3=>({path:path3,bytes:Uint8Array.from(filesystem.readFileSync(path3))}))}function nodeInvocationFilesystem(channel,policy,prepared,store){const client=new BrowserFilesystemChannelClient(channel);const shared=new VirtualFS;for(const method of["existsSync","statSync","lstatSync","readFileSync","readdirSync","realpathSync","readlinkSync","symlinkSync","writeFileSync","appendFileSync","writeAtSync","mkdirSync","unlinkSync","rmdirSync","renameSync","chmodSync","utimesSync"]){Reflect.set(shared,method,client[method].bind(client))}Reflect.set(shared,"accessSync",path3=>{client.statSync(path3)});if(store){const attempt=storeReads(store);for(const method of["existsSync","statSync","lstatSync","readFileSync","readdirSync","realpathSync","readlinkSync","accessSync"]){const owner2=Reflect.get(shared,method);const keepLast=method==="lstatSync"||method==="readlinkSync";Reflect.set(shared,method,(path3,...args)=>{const answer2=attempt(path3,keepLast,local2=>Reflect.get(local2,method).call(local2,path3,...args));return answer2?answer2.value:owner2(path3,...args)})}}const runtimeFiles=new VirtualFS;if(prepared){validateNodePreparedFiles(prepared.files,prepared.limits);for(const{path:path3,bytes:bytes2}of prepared.files){runtimeFiles.mkdirSync(path3.slice(0,path3.lastIndexOf("/"))||"/",{recursive:true});runtimeFiles.writeFileSync(path3,bytes2)}}const merged=new VirtualFS;const owner=path3=>{if(!runtimeFiles.existsSync(path3))return shared;if(runtimeFiles.statSync(path3).isDirectory()&&shared.existsSync(path3))return shared;return runtimeFiles};const mutationOwner=path3=>{const filesystem=owner(path3);if(filesystem===runtimeFiles)throw Object.assign(new Error(`EACCES: private runtime file '${path3}' is read-only`),{code:"EACCES"});return filesystem};for(const method of["statSync","lstatSync","readFileSync","realpathSync","readlinkSync","accessSync","writeFileSync","appendFileSync","writeAtSync","mkdirSync","unlinkSync","rmdirSync","chmodSync","utimesSync"]){Reflect.set(merged,method,(path3,...args)=>{const mutating=["writeFileSync","appendFileSync","writeAtSync","mkdirSync","unlinkSync","rmdirSync","chmodSync","utimesSync"].includes(method)||method==="accessSync"&&(Number(args[0]??0)&2)!==0;const filesystem=mutating?mutationOwner(path3):owner(path3);const action=Reflect.get(filesystem,method);if(!action)throw Object.assign(new Error(`Unsupported filesystem operation ${method}.`),{code:"ENOTSUP"});return action.call(filesystem,path3,...args)})}Reflect.set(merged,"existsSync",path3=>runtimeFiles.existsSync(path3)||shared.existsSync(path3));Reflect.set(merged,"readdirSync",path3=>[...new Set([...runtimeFiles.existsSync(path3)?runtimeFiles.readdirSync(path3):[],...shared.existsSync(path3)?shared.readdirSync(path3):[]])].sort());Reflect.set(merged,"renameSync",(from,to2)=>{const filesystem=mutationOwner(from);if(filesystem!==mutationOwner(to2))throw Object.assign(new Error("Cannot rename across runtime and project files."),{code:"EXDEV"});filesystem.renameSync(from,to2)});Reflect.set(merged,"symlinkSync",(target,path3)=>mutationOwner(path3).symlinkSync(target,path3));const listeners={change:new Set,delete:new Set};const watchers=new Set;const normalize4=path3=>{const parts=[];for(const part of path3.split("/")){if(part==="..")parts.pop();else if(part&&part!==".")parts.push(part)}return"/"+parts.join("/")};Reflect.set(merged,"on",(event,listener)=>{listeners[event].add(listener);return merged});Reflect.set(merged,"off",(event,listener)=>{listeners[event].delete(listener);return merged});Reflect.set(merged,"watch",((path3,optionsOrListener,listener)=>{const options=typeof optionsOrListener==="object"?optionsOrListener:{};const entry={path:normalize4(path3),directory:merged.statSync(path3).isDirectory(),recursive:options?.recursive===true,persistent:options?.persistent!==false,listener:typeof optionsOrListener==="function"?optionsOrListener:listener};watchers.add(entry);return{close(){watchers.delete(entry)},ref(){entry.persistent=true;return this},unref(){entry.persistent=false;return this}}}));return{guest:policy?createConfinedNodeFilesystem(merged,policy):merged,runtimeFiles,notify(event,changedPath){const path3=normalize4(changedPath);let content="";if(event==="change"&&listeners.change.size&&merged.existsSync(path3)&&merged.statSync(path3).isFile())content=merged.readFileSync(path3,"utf8");for(const listener of listeners[event])listener(path3,content)},notifyWatch(event,changedPath){const path3=normalize4(changedPath);for(const watcher of watchers){const relative3=path3.slice(watcher.path==="/"?1:watcher.path.length+1);const inside=watcher.directory&&(watcher.path==="/"||path3.startsWith(watcher.path+"/"));if(path3===watcher.path||inside&&(watcher.recursive||!relative3.includes("/"))){watcher.listener?.(event,inside?relative3:path3.split("/").pop())}}}}}var TAILWIND_RUNTIME_DIRECTORY="/tmp/browser-runtime-tailwind";var TAILWIND_VITE_PATH=`${TAILWIND_RUNTIME_DIRECTORY}/vite.cjs`;var STAND_IN_PATHS={"@tailwindcss/vite":TAILWIND_VITE_PATH};function ensureTailwindStandIn(filesystem){if(filesystem.existsSync(TAILWIND_VITE_PATH))return;filesystem.mkdirSync(TAILWIND_RUNTIME_DIRECTORY,{recursive:true});filesystem.writeFileSync(TAILWIND_VITE_PATH,TAILWIND_VITE_SOURCE)}var TAILWIND_VITE_SOURCE=String.raw`"use strict";
5894
5894
  const fs = require("fs");
5895
5895
  const path = require("path");
5896
5896
 
@@ -6405,8 +6405,8 @@ ${declarations}`)}function absoluteChunkImports(code3){return code3.replace(/(["
6405
6405
  ${pack.header?.hasDefault?`export { default } from ${from};
6406
6406
  `:""}`;vfs2.writeFileSync(target,code3);outputs[relativeTo(cwd,target)]={imports:[{path:relativeTo(cwd,pack.file),kind:"import-statement"}],exports:[...pack.header?.exports??[],...pack.header?.hasDefault?["default"]:[]],entryPoint:relativeTo(cwd,file2),inputs:{},bytes:code3.length}}return{errors:[],warnings:[],metafile:{inputs:{},outputs},outputFiles:void 0,mangleCache:void 0}}var importPattern=/(\b(?:from|import)\s*\(?\s*)(["'])([^"'\n]+)\2/gu;function besideNeighbors(code3,neighbors,required=new Set){const beside=new Set(neighbors);if(beside.size===0&&required.size===0)return code3;return code3.replace(importPattern,(match2,lead,quote2,specifier)=>{const name=specifier.startsWith(REQUIRE_ROUTE)?specifier.slice(REQUIRE_ROUTE.length):void 0;if(name!==void 0)return required.has(name)?`${lead}${quote2}./${packFileName(name)}${quote2}`:match2;return beside.has(specifier)?`${lead}${quote2}./${packFileName(specifier)}${quote2}`:match2})}var MAX_VIRTUAL_WEBSOCKET_FRAME_BYTES=32*1024*1024;var CHANNEL_NAME="vite-ws-channel";function createVirtualWebSocketRelay(deliver2){const channel=new BroadcastChannel(CHANNEL_NAME);const listener=event=>{const data2=event.data;if(data2&&typeof data2==="object"&&typeof data2.targetClient==="string")deliver2(data2)};channel.addEventListener("message",listener);return{receive:message=>channel.postMessage(message),close:()=>{channel.removeEventListener("message",listener);channel.close()}}}function typeStripperFrom(glue){return{strip:(code3,filename)=>glue.transformSync(code3,{mode:"transform",filename,deprecatedTsModuleAsError:true,transform:{verbatimModuleSyntax:true,nativeClassProperties:true,noEmptyExport:true,importNotUsedAsValues:"preserve"}}).code}}var quote=word=>`'${word.replace(/'/gu,"'\\''")}'`;function parseWorkspaceCommand(argv){const result={recursive:false,parallel:false,bail:true,ifPresent:false,failIfNoMatch:false,concurrency:4,filters:[],root:false,argv:[]};const args=argv.slice(1);const prefix2=[];let i10=0;for(;i10<args.length;i10++){const arg=args[i10];if(arg==="-r"||arg==="--recursive")result.recursive=true;else if(arg==="--parallel")result.parallel=true;else if(arg==="--no-bail")result.bail=false;else if(arg==="--if-present")result.ifPresent=true;else if(arg==="--fail-if-no-match")result.failIfNoMatch=true;else if(arg==="-w"||arg==="--workspace-root")result.root=true;else if(arg==="--stream"){}else if(arg==="--filter"||arg==="-F"||arg==="-C"||arg==="--dir"||arg==="--workspace-concurrency"){const value=args[++i10];if(value===void 0)throw new Error(`${arg} requires a value.`);if(arg==="--filter"||arg==="-F")result.filters.push(value);else if(arg==="--workspace-concurrency")result.concurrency=Number(value);else result.directory=value}else if(arg.startsWith("--filter="))result.filters.push(arg.slice(9));else if(arg.startsWith("--dir="))result.directory=arg.slice(6);else if(arg.startsWith("--workspace-concurrency="))result.concurrency=Number(arg.slice(24));else if(!prefix2.length&&(arg==="run"||arg==="run-script"||arg==="exec"))prefix2.push(arg);else if(arg==="--"){i10++;break}else if(arg.startsWith("-"))throw new Error(`Unsupported pnpm workspace option: ${arg}`);else break}if(!Number.isInteger(result.concurrency)||result.concurrency<1||result.concurrency>64)throw new Error("Workspace concurrency must be an integer from 1 to 64.");result.argv=[...prefix2,...args.slice(i10)];return result}function selectWorkspacePackages(workspace,filters,cwd=workspace.root){const select=filter2=>{let dependencies=false,dependents=false,onlyRelated=false;if(filter2.startsWith("...")){dependents=true;filter2=filter2.slice(3);if(filter2.startsWith("^")){onlyRelated=true;filter2=filter2.slice(1)}}if(filter2.endsWith("...")){dependencies=true;filter2=filter2.slice(0,-3);if(filter2.endsWith("^")){onlyRelated=true;filter2=filter2.slice(0,-1)}}if(dependencies&&dependents)throw new Error("Combined dependency/dependent filters are not supported.");if(filter2===".")filter2="{.}";const directory2=/^\{([^{}]+)\}$/u.exec(filter2)?.[1]??(filter2.startsWith("./")?filter2.slice(2):void 0);let matches=workspace.packages.filter(pkg=>directory2!==void 0?workspaceGlob(normalizeWorkspacePath(directory2.startsWith("/")?directory2:`${cwd}/${directory2}`),pkg.path):filter2==="*"||workspaceGlob(filter2,pkg.name));if(directory2===void 0&&!filter2.includes("/")&&!filter2.startsWith("@")){const scoped=workspace.packages.filter(pkg=>pkg.name.startsWith("@")&&workspaceGlob(filter2,pkg.name.split("/").at(-1)));if(filter2.includes("*")||filter2.includes("?"))matches=[...new Set([...matches,...scoped])];else if(!matches.length&&scoped.length===1)matches=scoped}const names3=new Set(matches.map(pkg=>pkg.name));let changed=true;while(changed){changed=false;for(const pkg of workspace.packages){if(dependencies&&names3.has(pkg.name)){for(const name of pkg.dependencies)if(!names3.has(name)){names3.add(name);changed=true}}if(dependents&&pkg.dependencies.some(name=>names3.has(name))&&!names3.has(pkg.name)){names3.add(pkg.name);changed=true}}}if(onlyRelated)matches.forEach(pkg=>names3.delete(pkg.name));return names3};const positive=filters.filter(filter2=>!filter2.startsWith("!"));const names2=positive.length?new Set(positive.flatMap(filter2=>[...select(filter2)])):new Set(workspace.packages.map(pkg=>pkg.name));for(const filter2 of filters.filter(filter3=>filter3.startsWith("!")))for(const name of select(filter2.slice(1)))names2.delete(name);return workspace.packages.filter(pkg=>names2.has(pkg.name))}function pnpmWorkspaceRunner(fs2,run,fallback,install3){return async(argv,options)=>{let workspace;try{const parsed=parseWorkspaceCommand(argv);const cwd=parsed.directory?normalizeWorkspacePath(`${parsed.directory.startsWith("/")?"":(options.cwd??"/")+"/"}${parsed.directory}`):normalizeWorkspacePath(options.cwd??"/");workspace=discoverPnpmWorkspace(fs2,cwd);if(!workspace)return fallback(argv,options);const[command="install",...rest]=parsed.argv;if(["install","i","add","update","up","upgrade","remove","rm","uninstall","un","import","fetch","rebuild","rb","dedupe","link","ln","unlink"].includes(command)){const filters=[...parsed.filters];const argv2=[];for(let index2=0;index2<rest.length;index2+=1){const arg=rest[index2];if(arg==="--filter"||arg==="-F"){const value=rest[++index2];if(value===void 0)throw new Error(`${arg} requires a value.`);filters.push(value)}else if(arg.startsWith("--filter="))filters.push(arg.slice(9));else argv2.push(arg)}return await install3(workspace,argv2,{...options,cwd},filters)}configureWorkspaceLinks(fs2,workspace);const exec=command==="exec";const explicit=exec||command==="run"||command==="run-script";const script=explicit?rest[0]:command;const arguments_=explicit?rest.slice(1):rest;if(!script)throw new Error(exec?"pnpm exec requires a command.":"pnpm run requires a script name.");const forwarded=arguments_.length&&arguments_[0]!=="--"?["--",...arguments_]:arguments_;const currentPackage=workspace.packages.filter(pkg=>cwd===pkg.path||cwd.startsWith(`${pkg.path==="/"?"":pkg.path}/`)).sort((left,right)=>right.path.length-left.path.length)[0];let selected=parsed.filters.length?selectWorkspacePackages(workspace,parsed.filters,cwd):parsed.recursive?workspace.packages.filter(pkg=>pkg.relative!=="."):workspace.packages.filter(pkg=>parsed.root?pkg.path===workspace.root:pkg===currentPackage);if(!selected.length){const message="No workspace projects matched.\n";options.onStderr?.(message);return{stdout:"",stderr:message,exitCode:parsed.failIfNoMatch?1:0}}const recursive=parsed.recursive||parsed.filters.length>0;if(!exec&&!recursive&&!parsed.ifPresent&&!selected[0]?.manifest.scripts?.[script])throw new Error(`${selected[0]?.name}: missing script ${script}.`);if(!exec)selected=selected.filter(pkg=>typeof pkg.manifest.scripts?.[script]==="string");if(!selected.length&&!parsed.ifPresent)throw new Error(`No selected workspace package has script ${script}.`);if(!parsed.parallel)selected=orderWorkspacePackages(selected);const controller=new AbortController;const abort=()=>controller.abort(options.signal?.reason);if(options.signal?.aborted)abort();else options.signal?.addEventListener("abort",abort,{once:true});const results=new Map;const active2=new Map;const pending=[...selected];let firstFailure=0;try{while(pending.length||active2.size){if(controller.signal.aborted)pending.length=0;for(let i10=0;i10<pending.length&&!controller.signal.aborted&&active2.size<(parsed.parallel?selected.length:parsed.concurrency);){const pkg=pending[i10];const waiting=!parsed.parallel&&pkg.dependencies.some(name=>selected.some(candidate=>candidate.name===name)&&!results.has(name));if(waiting){i10++;continue}pending.splice(i10,1);const task=(async()=>{let result;try{const commandWords=exec?[script,...arguments_]:["npm","run",script,...forwarded];result=await run(commandWords.map(quote).join(" "),{...options,cwd:pkg.path,signal:controller.signal,env:{...options.env,INIT_CWD:options.env?.INIT_CWD??cwd,...exec?{PNPM_PACKAGE_NAME:pkg.name}:{}}})}catch(cause){const message=`${pkg.name}: ${cause instanceof Error?cause.message:String(cause)}
6407
6407
  `;options.onStderr?.(message);result={stdout:"",stderr:message,exitCode:controller.signal.aborted?130:1}}results.set(pkg.name,result);if(result.exitCode!==0&&!firstFailure){firstFailure=result.exitCode;if(parsed.bail)controller.abort(new Error(`${pkg.name}: ${script} failed.`))}})().finally(()=>{active2.delete(pkg.name)});active2.set(pkg.name,task)}if(active2.size)await Promise.race(active2.values());else if(pending.length)throw new Error("Workspace scheduler has unresolved dependencies.")}}catch(cause){controller.abort(cause);await Promise.allSettled(active2.values());throw cause}finally{options.signal?.removeEventListener("abort",abort)}return{stdout:[...results.values()].map(result=>result.stdout).join(""),stderr:[...results.values()].map(result=>result.stderr).join(""),exitCode:firstFailure||(controller.signal.aborted?130:0)}}catch(cause){const message=`pnpm: ${cause instanceof Error?cause.message:String(cause)}
6408
- `;options.onStderr?.(message);return{stdout:"",stderr:message,exitCode:2}}}}var ROLLDOWN_BROWSER_VERSION="1.2.8";var modulesSymbol=Symbol.for("@volter/browser-node/rolldown-modules");var RolldownRuntime=class{constructor(fs2,moduleUrl){this.fs=fs2;this.moduleUrl=moduleUrl;if(Reflect.has(fs2,modulesSymbol))throw new Error("This filesystem already owns a Rolldown runtime.");Reflect.set(fs2,modulesSymbol,this.modules)}fs;moduleUrl;binding;disposed=false;warned=new Set;modules=new Map;pending=0;get pendingWork(){return this.pending}async prepare(cwd){if(this.disposed)throw new Error("The Rolldown runtime is disposed.");let directory2=cwd;for(;;){const root2=`${directory2==="/"?"":directory2}/node_modules/rolldown`;const manifest=`${root2}/package.json`;const clearRoot=()=>{for(const path3 of this.modules.keys())if(path3.startsWith(`${root2}/`)||path3.startsWith("pkg:rolldown@"))this.modules.delete(path3);let real;try{real=this.fs.realpathSync?.(root2)}catch{real=void 0}if(real&&real!==root2){for(const path3 of this.modules.keys())if(path3.startsWith(`${real}/`))this.modules.delete(path3)}};if(this.fs.existsSync(manifest)){const pkg=JSON.parse(this.fs.readFileSync(manifest,"utf8"));const binding2=await(this.binding??=this.load());if(this.disposed)throw new Error("The Rolldown runtime is disposed.");if(pkg.version!==(binding2.version??ROLLDOWN_BROWSER_VERSION)){if(!this.warned.has(pkg.version)){this.warned.add(pkg.version);console.warn(`[rolldown] ${root2} is rolldown ${pkg.version}; the page's binding is ${binding2.version??ROLLDOWN_BROWSER_VERSION}, so rolldown will look for its own.`)}}if(pkg.version===(binding2.version??ROLLDOWN_BROWSER_VERSION)){const entries=new Map;for(const[name,module]of Object.entries(binding2.modules)){const key=name==="rolldown"?".":`.${name.slice("rolldown".length)}`;const views=new WeakMap;const view=process3=>{let value=views.get(process3);if(!value){value=this.moduleView(name,module,process3);views.set(process3,value)}return value};for(const entry of exportPaths(pkg.exports?.[key])){if(!entry.startsWith("./")||entry.endsWith(".d.ts")||entry.endsWith(".d.mts"))continue;entries.set(`${root2}/${entry.slice(2)}`,view);entries.set(`pkg:rolldown@${pkg.version}/${entry.slice(2)}`,view)}}clearRoot();for(const[path3,view]of entries)this.modules.set(path3,view);let real;try{real=this.fs.realpathSync?.(root2)}catch{real=void 0}if(real&&real!==root2)for(const[path3,view]of entries)this.modules.set(`${real}${path3.slice(root2.length)}`,view)}else clearRoot()}else clearRoot();if(directory2==="/")break;directory2=directory2.slice(0,directory2.lastIndexOf("/"))||"/"}}moduleView(name,module,process3){const view={...module};for(const[key,value]of Object.entries(module)){if(typeof value!=="function")continue;view[key]=new Proxy(value,{apply:(target,receiver,args)=>{if(name==="rolldown"&&["rolldown","build","watch"].includes(key)||name==="rolldown/experimental"&&["scan","dev"].includes(key)){const withCwd2=input=>{if(Array.isArray(input))return input.map(withCwd2);if(input!==void 0&&(!input||typeof input!=="object"))return input;const options=input;return{...options,cwd:options?.cwd??process3.cwd()}};args[0]=withCwd2(args[0])}return this.hold(Reflect.apply(target,receiver,args))}})}return view}hold(result){if(!result||typeof result.then!=="function")return result;this.pending+=1;return Promise.resolve(result).then(value=>{if(!value||typeof value!=="object"||typeof Reflect.get(value,"generate")!=="function"||typeof Reflect.get(value,"write")!=="function")return value;for(const key of["generate","write","close"]){const method=Reflect.get(value,key);if(typeof method!=="function")continue;Object.defineProperty(value,key,{configurable:true,writable:true,value:(...args)=>this.hold(Reflect.apply(method,value,args))})}return value}).finally(()=>{this.pending-=1})}async load(){try{const factory=await import(this.moduleUrl);return await factory.createRolldown(this.fs)}catch(error){this.binding=void 0;throw error}}async dispose(){this.disposed=true;this.modules.clear();Reflect.deleteProperty(this.fs,modulesSymbol);const binding2=await this.binding;await binding2?.dispose();this.binding=void 0}};function exportPaths(value){if(typeof value==="string")return[value];if(!value||typeof value!=="object")return[];return Object.entries(value).filter(([key])=>key!=="types").flatMap(([,child])=>exportPaths(child))}var installationQueue=Promise.resolve();function serializedInstallation(work){const result=installationQueue.then(work,work);installationQueue=result.then(()=>void 0,()=>void 0);return result}var childProcessExecutorSymbol=Symbol.for("@volter/browser-runtime/child-process-executor");var EXPORTABLE_NAME=/^[A-Za-z_][A-Za-z0-9_]*$/u;var SHELL_OWNED_NAMES=new Set(["SHELLOPTS","BASHOPTS","BASH_VERSINFO","EUID","PPID","UID"]);function refuseInstall(door,subject,options){let refusal;try{installTrap({door,subject,detail:{cwd:options.cwd??"/"},fix:"add what it installs to the project's dependencies (package.json and its lockfile), then prepare the image again with `npx @volter/browser-substrate dev`: the image then carries each as a pack."})}catch(cause){refusal=cause}const text=`${refusal instanceof Error?refusal.message:String(refusal)}
6409
- `;options.onStderr?.(text);return{stdout:"",stderr:text,exitCode:2}}function scriptPath(cwd,inherited){const bins=[];for(let directory2=cwd;;directory2=directory2.slice(0,directory2.lastIndexOf("/"))||"/"){bins.push(`${directory2==="/"?"":directory2}/node_modules/.bin`);if(directory2==="/")break}return[...new Set([...bins,...(inherited??"/usr/local/bin:/usr/bin:/bin").split(":").filter(Boolean)])].join(":")}var NPM_VALUED_OPTIONS=new Set(["-w","--workspace","--prefix","-C","--registry","--cache","--userconfig","--scope","--tag","--loglevel"]);function npmCommandOf(argv){for(let index2=1;index2<argv.length;index2++){const word=argv[index2];if(NPM_VALUED_OPTIONS.has(word)){index2++;continue}if(word.startsWith("-"))continue;return{command:word,rest:argv.slice(index2+1)}}return{command:void 0,rest:[]}}function firstOperand(words){for(let index2=0;index2<words.length;index2++){const word=words[index2];if(word==="--")return words[index2+1];if(NPM_VALUED_OPTIONS.has(word)){index2++;continue}if(!word.startsWith("-"))return word}return void 0}var NPM_INSTALLS=new Set(["install","i","add","in","ins","inst","insta","instal","isnt","isnta","isntal","isntall","ci","clean-install","install-clean","ic","isntall-clean","install-test","it","install-ci-test","cit","clean-install-test","sit","update","up","upgrade","udpate","rebuild","rb","dedupe","ddp"]);var TabnodeToolchain=class{constructor(container2,options={},webSockets){this.container=container2;this.options=options;this.webSockets=webSockets;ensureFsAppend(container2);if(options.registryScopes)Reflect.set(globalThis,"__browserRuntimeRegistryScopes",{...options.registryScopes});if(!Reflect.get(globalThis,MODULE_STAND_INS))installModuleStandIns(container2.vfs,[new PrismaClientStandIn]);if(options.rolldownModuleUrl)this.rolldown=new RolldownRuntime(container2.vfs,options.rolldownModuleUrl);if(options.bundler){this.bundler=new BrowserBundler(container2.vfs,options.bundler);esbuildShim.useHost(this.bundler);this.bundler.prebundle=vitePrebundleAssembler(container2.vfs,options.moduleCache)}}container;options;webSockets;nodeFetchDepth=0;heldChildren=new Set;originalFetch;hadOriginalChildProcessExecutor=false;originalChildProcessExecutor;bundler;rolldown;register(registry){registry.registerProgram("node",(argv,options)=>this.runNode(argv,options));const run=(command,options)=>{if(!this.options.runShellCommand)throw new Error("Workspace commands require the runtime shell.");return this.options.runShellCommand(command,options)};registry.registerProgram("pnpm",pnpmWorkspaceRunner(this.container.vfs,run,packageManagerAliasRunner("pnpm",run),(workspace,argv,options,filters)=>serializedInstallation(()=>this.installPnpmWorkspace(workspace,argv,options,filters))));registry.registerProgram("npm",(argv,options)=>this.runNpm(argv,options));registry.registerProgram("vite",(argv,options)=>this.runVite(argv,options));registry.registerProgram("npx",(argv,options)=>{const rest=[...argv.slice(1)];while(rest.length>0&&rest[0].startsWith("-")){const flag=rest.shift();if(flag==="--")break;if((flag==="--package"||flag==="-p"||flag==="--call"||flag==="-c")&&rest.length>0)rest.shift()}const name=rest[0];const bin=name?this.installedBin(name,normalizeAbsolutePath(options.cwd??"/")):void 0;if(bin)return bin(rest,options);const stderr=`npx: ${name??"nothing"} is not installed in this project; the tab runs what the install put in node_modules/.bin and fetches nothing to run a command.
6408
+ `;options.onStderr?.(message);return{stdout:"",stderr:message,exitCode:2}}}}var ROLLDOWN_BROWSER_VERSION="1.2.8";var ROLLDOWN_BROWSER_SUBPATHS=["experimental","utils","plugins","filter","parseAst"];var modulesSymbol=Symbol.for("@volter/browser-node/rolldown-modules");var pendingSymbol=Symbol.for("substrate.pending");var RolldownRuntime=class{constructor(fs2,moduleUrl,version2=ROLLDOWN_BROWSER_VERSION){this.fs=fs2;this.moduleUrl=moduleUrl;this.version=version2;if(Reflect.has(fs2,modulesSymbol))throw new Error("This filesystem already owns a Rolldown runtime.");Reflect.set(fs2,modulesSymbol,this.modules)}fs;moduleUrl;version;binding;disposed=false;warned=new Set;modules=new Map;views=new WeakMap;pending=0;get pendingWork(){return this.pending}async prepare(cwd){if(this.disposed)throw new Error("The Rolldown runtime is disposed.");let directory2=cwd;for(;;){const root2=`${directory2==="/"?"":directory2}/node_modules/rolldown`;const manifest=`${root2}/package.json`;const clearRoot=()=>{for(const path3 of this.modules.keys())if(path3.startsWith(`${root2}/`)||path3.startsWith("pkg:rolldown@"))this.modules.delete(path3);let real;try{real=this.fs.realpathSync?.(root2)}catch{real=void 0}if(real&&real!==root2){for(const path3 of this.modules.keys())if(path3.startsWith(`${real}/`))this.modules.delete(path3)}};if(this.fs.existsSync(manifest)){const pkg=JSON.parse(this.fs.readFileSync(manifest,"utf8"));if(pkg.version!==this.version){if(!this.warned.has(pkg.version)){this.warned.add(pkg.version);console.warn(`[rolldown] ${root2} is rolldown ${pkg.version}; the page's binding is ${this.version}, so rolldown will look for its own.`)}}if(pkg.version===this.version){const entries=new Map;for(const name of["rolldown",...ROLLDOWN_BROWSER_SUBPATHS.map(subpath=>`rolldown/${subpath}`)]){const key=name==="rolldown"?".":`.${name.slice("rolldown".length)}`;const view=process3=>this.moduleOnUse(name,process3);for(const entry of exportPaths(pkg.exports?.[key])){if(!entry.startsWith("./")||entry.endsWith(".d.ts")||entry.endsWith(".d.mts"))continue;entries.set(`${root2}/${entry.slice(2)}`,view);entries.set(`pkg:rolldown@${pkg.version}/${entry.slice(2)}`,view)}}clearRoot();for(const[path3,view]of entries)this.modules.set(path3,view);let real;try{real=this.fs.realpathSync?.(root2)}catch{real=void 0}if(real&&real!==root2)for(const[path3,view]of entries)this.modules.set(`${real}${path3.slice(root2.length)}`,view)}else clearRoot()}else clearRoot();if(directory2==="/")break;directory2=directory2.slice(0,directory2.lastIndexOf("/"))||"/"}}moduleOnUse(name,process3){if(this.disposed)throw new Error("The Rolldown runtime is disposed.");if(typeof globalThis.Worker!=="function"){throw new Error("Rolldown cannot initialize here: nested web workers require broker-delegated authority (ROADMAP W77). Use a host-prepared production build.")}let views=this.views.get(process3);if(!views){views=new Map;this.views.set(process3,views)}const cached=views.get(name);if(cached)return cached;const exports={};let ready=false;let failure;const access=()=>{if(failure!==void 0)throw failure;if(!ready)throw Object.assign(new Error(`Cannot synchronously use ${name} while its WASM module is initializing; import it asynchronously.`),{code:"ERR_REQUIRE_ASYNC_MODULE"})};const view=new Proxy(exports,{get:(target,key,receiver)=>{if(key==="then"&&!ready)return void 0;if(key!==pendingSymbol)access();return Reflect.get(target,key,receiver)},ownKeys:target=>{access();return Reflect.ownKeys(target)}});this.pending+=1;const pending=(this.binding??=this.load()).then(binding2=>{if(this.disposed)throw new Error("The Rolldown runtime is disposed.");const module=binding2.modules[name];if(!module)throw new Error(`The prepared Rolldown ${this.version} binding carries no ${name} export.`);Object.defineProperties(exports,Object.getOwnPropertyDescriptors(this.moduleView(name,module,process3)));ready=true}).catch(cause=>{failure=cause;throw cause}).finally(()=>{this.pending-=1;Reflect.deleteProperty(exports,pendingSymbol)});Object.defineProperty(exports,pendingSymbol,{value:pending,configurable:true});views.set(name,view);return view}moduleView(name,module,process3){const view={...module};for(const[key,value]of Object.entries(module)){if(typeof value!=="function")continue;view[key]=new Proxy(value,{apply:(target,receiver,args)=>{if(name==="rolldown"&&["rolldown","build","watch"].includes(key)||name==="rolldown/experimental"&&["scan","dev"].includes(key)){const withCwd2=input=>{if(Array.isArray(input))return input.map(withCwd2);if(input!==void 0&&(!input||typeof input!=="object"))return input;const options=input;return{...options,cwd:options?.cwd??process3.cwd()}};args[0]=withCwd2(args[0])}return this.hold(Reflect.apply(target,receiver,args))}})}return view}hold(result){if(!result||typeof result.then!=="function")return result;this.pending+=1;return Promise.resolve(result).then(value=>{if(!value||typeof value!=="object"||typeof Reflect.get(value,"generate")!=="function"||typeof Reflect.get(value,"write")!=="function")return value;for(const key of["generate","write","close"]){const method=Reflect.get(value,key);if(typeof method!=="function")continue;Object.defineProperty(value,key,{configurable:true,writable:true,value:(...args)=>this.hold(Reflect.apply(method,value,args))})}return value}).finally(()=>{this.pending-=1})}async load(){try{const factory=await import(this.moduleUrl);if((factory.version??this.version)!==this.version)throw new Error(`Prepared Rolldown factory is ${factory.version}; the image selected ${this.version}.`);return await factory.createRolldown(this.fs)}catch(error){this.binding=void 0;throw error}}async dispose(){this.disposed=true;this.modules.clear();Reflect.deleteProperty(this.fs,modulesSymbol);const binding2=await this.binding;await binding2?.dispose();this.binding=void 0}};function exportPaths(value){if(typeof value==="string")return[value];if(!value||typeof value!=="object")return[];return Object.entries(value).filter(([key])=>key!=="types").flatMap(([,child])=>exportPaths(child))}var installationQueue=Promise.resolve();function serializedInstallation(work){const result=installationQueue.then(work,work);installationQueue=result.then(()=>void 0,()=>void 0);return result}var childProcessExecutorSymbol=Symbol.for("@volter/browser-runtime/child-process-executor");var EXPORTABLE_NAME=/^[A-Za-z_][A-Za-z0-9_]*$/u;var SHELL_OWNED_NAMES=new Set(["SHELLOPTS","BASHOPTS","BASH_VERSINFO","EUID","PPID","UID"]);function refuseInstall(door,subject,options){let refusal;try{installTrap({door,subject,detail:{cwd:options.cwd??"/"},fix:"add what it installs to the project's dependencies (package.json and its lockfile), then prepare the image again with `npx @volter/browser-substrate dev`: the image then carries each as a pack."})}catch(cause){refusal=cause}const text=`${refusal instanceof Error?refusal.message:String(refusal)}
6409
+ `;options.onStderr?.(text);return{stdout:"",stderr:text,exitCode:2}}function scriptPath(cwd,inherited){const bins=[];for(let directory2=cwd;;directory2=directory2.slice(0,directory2.lastIndexOf("/"))||"/"){bins.push(`${directory2==="/"?"":directory2}/node_modules/.bin`);if(directory2==="/")break}return[...new Set([...bins,...(inherited??"/usr/local/bin:/usr/bin:/bin").split(":").filter(Boolean)])].join(":")}var NPM_VALUED_OPTIONS=new Set(["-w","--workspace","--prefix","-C","--registry","--cache","--userconfig","--scope","--tag","--loglevel"]);function npmCommandOf(argv){for(let index2=1;index2<argv.length;index2++){const word=argv[index2];if(NPM_VALUED_OPTIONS.has(word)){index2++;continue}if(word.startsWith("-"))continue;return{command:word,rest:argv.slice(index2+1)}}return{command:void 0,rest:[]}}function firstOperand(words){for(let index2=0;index2<words.length;index2++){const word=words[index2];if(word==="--")return words[index2+1];if(NPM_VALUED_OPTIONS.has(word)){index2++;continue}if(!word.startsWith("-"))return word}return void 0}var NPM_INSTALLS=new Set(["install","i","add","in","ins","inst","insta","instal","isnt","isnta","isntal","isntall","ci","clean-install","install-clean","ic","isntall-clean","install-test","it","install-ci-test","cit","clean-install-test","sit","update","up","upgrade","udpate","rebuild","rb","dedupe","ddp"]);var TabnodeToolchain=class{constructor(container2,options={},webSockets){this.container=container2;this.options=options;this.webSockets=webSockets;ensureFsAppend(container2);if(options.registryScopes)Reflect.set(globalThis,"__browserRuntimeRegistryScopes",{...options.registryScopes});if(!Reflect.get(globalThis,MODULE_STAND_INS))installModuleStandIns(container2.vfs,[new PrismaClientStandIn]);if(options.rolldownModuleUrl)this.rolldown=new RolldownRuntime(container2.vfs,options.rolldownModuleUrl,options.rolldownVersion);if(options.bundler){this.bundler=new BrowserBundler(container2.vfs,options.bundler);esbuildShim.useHost(this.bundler);this.bundler.prebundle=vitePrebundleAssembler(container2.vfs,options.moduleCache)}}container;options;webSockets;nodeFetchDepth=0;heldChildren=new Set;originalFetch;hadOriginalChildProcessExecutor=false;originalChildProcessExecutor;bundler;rolldown;register(registry){registry.registerProgram("node",(argv,options)=>this.runNode(argv,options));const run=(command,options)=>{if(!this.options.runShellCommand)throw new Error("Workspace commands require the runtime shell.");return this.options.runShellCommand(command,options)};registry.registerProgram("pnpm",pnpmWorkspaceRunner(this.container.vfs,run,packageManagerAliasRunner("pnpm",run),(workspace,argv,options,filters)=>serializedInstallation(()=>this.installPnpmWorkspace(workspace,argv,options,filters))));registry.registerProgram("npm",(argv,options)=>this.runNpm(argv,options));registry.registerProgram("vite",(argv,options)=>this.runVite(argv,options));registry.registerProgram("npx",(argv,options)=>{const rest=[...argv.slice(1)];while(rest.length>0&&rest[0].startsWith("-")){const flag=rest.shift();if(flag==="--")break;if((flag==="--package"||flag==="-p"||flag==="--call"||flag==="-c")&&rest.length>0)rest.shift()}const name=rest[0];const bin=name?this.installedBin(name,normalizeAbsolutePath(options.cwd??"/")):void 0;if(bin)return bin(rest,options);const stderr=`npx: ${name??"nothing"} is not installed in this project; the tab runs what the install put in node_modules/.bin and fetches nothing to run a command.
6410
6410
  `;options.onStderr?.(stderr);return Promise.resolve({stdout:"",stderr,exitCode:1})});registry.registerProgram("next",(argv,options)=>this.runNext(argv,options));registry.registerProgram("prisma",(argv,options)=>{if(argv[1]==="generate"){const line="prisma generate: the generated client is answered from the schema by the runtime; nothing to write.\n";options.onStdout?.(line);return Promise.resolve({stdout:line,stderr:"",exitCode:0})}const bin=this.installedBin("prisma",normalizeAbsolutePath(options.cwd??"/"));return bin?bin(argv,options):this.runContainer(argv,options)});registry.registerCommandResolver?.((name,cwd)=>this.installedBin(name,cwd))}nextGeneration(cwd){let directory2=normalizeAbsolutePath(cwd);for(;;){const manifest=`${directory2==="/"?"":directory2}/node_modules/next/package.json`;if(this.container.vfs.existsSync(manifest)){try{const version2=JSON.parse(this.container.vfs.readFileSync(manifest,"utf8")).version;return typeof version2==="string"?Number.parseInt(version2,10)||0:0}catch{return 0}}if(directory2==="/")return 0;directory2=directory2.slice(0,directory2.lastIndexOf("/"))||"/"}}installedBin(name,cwd){if(!/^[A-Za-z0-9][\w.-]*$/u.test(name))return void 0;let directory2=normalizeAbsolutePath(cwd);for(;;){const stub=`${directory2==="/"?"":directory2}/node_modules/.bin/${name}`;if(this.container.vfs.existsSync(stub)){const target=/^node "([^"]+)"/u.exec(this.container.vfs.readFileSync(stub,"utf8"))?.[1];if(target&&this.container.vfs.existsSync(target)){return(argv,options)=>this.runNode(["node",target,...argv.slice(1)],options)}}if(directory2==="/")return void 0;directory2=directory2.slice(0,directory2.lastIndexOf("/"))||"/"}}async dispose(){this.bundler?.dispose();await this.rolldown?.dispose()}async runNode(argv,options){if(argv[1]==="--version"||argv[1]==="-v"){return{stdout:"v18.0.0-browser\n",stderr:"",exitCode:0}}if(options.env?.[BUN_ENVIRONMENT_FLAG])this.ensureBunRuntime();this.ensureStandIns();const preloaded=nodePreloads(argv,options.env??{});argv=preloaded.argv;const preloads=preloaded.preloads;let codeIndex=-1;let printIndex=-1;for(let index2=1;index2<argv.length;index2+=1){const value=argv[index2];if(!value.startsWith("-"))break;if(value==="-e"||value==="--eval"){codeIndex=index2;break}if(value==="-p"||value==="--print"){codeIndex=index2;printIndex=index2;break}}if(codeIndex<0)return this.runNodeFile(argv,options,preloads);const source=argv[codeIndex+1];if(source===void 0){return{stdout:"",stderr:`node: ${argv[codeIndex]} requires an argument
6411
6411
  `,exitCode:9}}const sequence=globalThis.crypto.randomUUID();const completionMarker=`__browser_runtime_node_eval_${sequence}__`;const environment=JSON.stringify(options.env??{});const bootstrap=`Object.assign(process.env, ${environment});
6412
6412
  ${preloadLines(preloads)}`;const program=bootstrap+(printIndex>=0?`console.log(${source});
@@ -6420,10 +6420,10 @@ ${preloadLines(preloads)}`;const program=bootstrap+(printIndex>=0?`console.log($
6420
6420
  > ${label} ${phase}
6421
6421
  > ${command}
6422
6422
 
6423
- `;if(phaseHeading)options.onStderr?.(phaseHeading);const result2=await this.options.runShellCommand(command,{...options,env:{...options.env,npm_lifecycle_event:phase,npm_package_name:manifest.name??"",npm_package_version:manifest.version??"",PATH:scriptPath(cwd,options.env?.PATH)}});stdout+=result2.stdout;stderr+=phaseHeading+result2.stderr;if(result2.exitCode!==0)return{...result2,stdout,stderr}}return{stdout,stderr,exitCode:0}}let scriptArgv;try{scriptArgv=parseCommandWords(script)}catch{return this.runContainer(argv,options)}if(scriptArgv[0]!=="vite"&&!(scriptArgv[0]==="next"&&scriptArgv[1]==="dev"))return this.runContainer(argv,options);if(separator>=0)scriptArgv.push(...argv.slice(separator+1));options.onStderr?.(heading);const result=scriptArgv[0]==="next"?await this.runNext(scriptArgv,options):await this.runVite(scriptArgv,options);return{...result,stderr:`${heading}${result.stderr}`}}ensureBunRuntime(){const vfs2=this.container.vfs;if(vfs2.existsSync(BUN_GLOBALS_PATH)&&vfs2.existsSync(BUN_BUILD_PATH))return;vfs2.mkdirSync(BUN_RUNTIME_DIRECTORY,{recursive:true});vfs2.writeFileSync(BUN_GLOBALS_PATH,BUN_GLOBALS_SOURCE);vfs2.writeFileSync(BUN_BUILD_PATH,BUN_BUILD_SOURCE)}ensureStandIns(){const vfs2=this.container.vfs;Reflect.set(globalThis,"__browserRuntimeStandInPaths",STAND_IN_PATHS);if(!Reflect.get(globalThis,MODULE_STAND_INS))installModuleStandIns(vfs2,[new PrismaClientStandIn]);ensureTailwindStandIn(vfs2);ensureNativeStandIns(vfs2)}async runNodeFile(argv,options,preloads=[]){const target=argv[1];if(!target||target.startsWith("-")){return this.runContainer(argv,options)}const cwd=normalizeAbsolutePath(options.cwd??"/");const targetPath=normalizeAbsolutePath(target.startsWith("/")?target:`${cwd}/${target}`);if(!this.container.vfs.existsSync(targetPath))return this.runContainer(argv,options);if(preloads.length===0&&!options.env?.[BUN_ENVIRONMENT_FLAG]){return this.runNodeContainer(argv,options)}const executablePath=targetPath;const temporaryDirectory=preloads.length>0?cwd:"/tmp/browser-runtime-node-entry";const temporaryPath=`${temporaryDirectory==="/"?"":temporaryDirectory}/${preloads.length>0?".browser-runtime-node-entry-":""}${globalThis.crypto.randomUUID()}.cjs`;const runtimeFiles=this.options.runtimeFiles??this.container.vfs;runtimeFiles.mkdirSync(temporaryDirectory,{recursive:true});runtimeFiles.writeFileSync(temporaryPath,[`Object.assign(process.env, ${JSON.stringify(options.env??{})});`,`process.argv = ${JSON.stringify(["node",targetPath,...argv.slice(2)])};`,...options.env?.[BUN_ENVIRONMENT_FLAG]?[`require(${JSON.stringify(BUN_GLOBALS_PATH)});`]:[],...preloads.length>0?[preloadLines(preloads)]:[],`require("module")._load(${JSON.stringify(executablePath)}, null, true);`,""].join("\n"));try{return await this.runNodeContainer(["node",temporaryPath],options)}finally{if(runtimeFiles.existsSync(temporaryPath))runtimeFiles.unlinkSync(temporaryPath)}}runNext(argv,options){const cli=this.installedBin("next",normalizeAbsolutePath(options.cwd??"/"));if(!cli)return Promise.resolve({stdout:"",stderr:"next: the project has no next installed to run it.\n",exitCode:1});let args=[...argv];if(args[1]==="dev"){const turbo=args.some(arg=>arg==="--turbopack"||arg==="--turbo");args=args.filter(arg=>arg!=="--turbopack"&&arg!=="--turbo");if(this.nextGeneration(normalizeAbsolutePath(options.cwd??"/"))>=16&&!args.includes("--webpack"))args.push("--webpack");if(turbo)options.onStderr?.("next dev: Turbopack is a native binary the tab cannot run; bundling with webpack.\n")}return cli(args,options)}runVite(argv,options){const cli=this.installedBin("vite",normalizeAbsolutePath(options.cwd??"/"));if(cli)return cli(argv,options);return Promise.resolve({stdout:"",stderr:"vite: the project has no vite installed to run it.\n",exitCode:1})}runContainer(argv,options){const environment=Object.entries({...this.vendorSeams(options.cwd),...options.env??{}}).filter(([name])=>EXPORTABLE_NAME.test(name)&&!SHELL_OWNED_NAMES.has(name)).map(([name,value])=>`${name}=${renderCommand([value])}`);const command=[...environment,renderCommand(argv)].join(" ");return this.container.run(command,options)}vendorSeams(cwd){const seams={};const vfs2=this.container.vfs;let directory2=cwd&&cwd.startsWith("/")?cwd:"/workspace/app";for(;;){if(vfs2.existsSync(`${directory2}/node_modules/lightningcss/pkg/package.json`)){seams.CSS_TRANSFORMER_WASM="1";break}if(directory2==="/"||directory2==="")break;directory2=directory2.slice(0,directory2.lastIndexOf("/"))||"/"}return seams}async runNodeContainer(argv,options){if(nodeProcessHostInstalled())options={...options,held:false};options={...options,env:{...this.vendorSeams(options.cwd),...options.env??{}}};try{await this.rolldown?.prepare(normalizeAbsolutePath(options.cwd??"/"))}catch(error){const stderr=`Rolldown initialization failed: ${error instanceof Error?error.message:String(error)}
6423
+ `;if(phaseHeading)options.onStderr?.(phaseHeading);const result2=await this.options.runShellCommand(command,{...options,env:{...options.env,npm_lifecycle_event:phase,npm_package_name:manifest.name??"",npm_package_version:manifest.version??"",PATH:scriptPath(cwd,options.env?.PATH)}});stdout+=result2.stdout;stderr+=phaseHeading+result2.stderr;if(result2.exitCode!==0)return{...result2,stdout,stderr}}return{stdout,stderr,exitCode:0}}let scriptArgv;try{scriptArgv=parseCommandWords(script)}catch{return this.runContainer(argv,options)}if(scriptArgv[0]!=="vite"&&!(scriptArgv[0]==="next"&&scriptArgv[1]==="dev"))return this.runContainer(argv,options);if(separator>=0)scriptArgv.push(...argv.slice(separator+1));options.onStderr?.(heading);const result=scriptArgv[0]==="next"?await this.runNext(scriptArgv,options):await this.runVite(scriptArgv,options);return{...result,stderr:`${heading}${result.stderr}`}}ensureBunRuntime(){const vfs2=this.container.vfs;if(vfs2.existsSync(BUN_GLOBALS_PATH)&&vfs2.existsSync(BUN_BUILD_PATH))return;vfs2.mkdirSync(BUN_RUNTIME_DIRECTORY,{recursive:true});vfs2.writeFileSync(BUN_GLOBALS_PATH,BUN_GLOBALS_SOURCE);vfs2.writeFileSync(BUN_BUILD_PATH,BUN_BUILD_SOURCE)}ensureStandIns(){const vfs2=this.container.vfs;Reflect.set(globalThis,"__browserRuntimeStandInPaths",STAND_IN_PATHS);if(!Reflect.get(globalThis,MODULE_STAND_INS))installModuleStandIns(vfs2,[new PrismaClientStandIn]);ensureTailwindStandIn(vfs2);ensureNativeStandIns(vfs2)}async runNodeFile(argv,options,preloads=[]){const target=argv[1];if(!target||target.startsWith("-")){return this.runContainer(argv,options)}const cwd=normalizeAbsolutePath(options.cwd??"/");const targetPath=normalizeAbsolutePath(target.startsWith("/")?target:`${cwd}/${target}`);if(!this.container.vfs.existsSync(targetPath))return this.runContainer(argv,options);if(preloads.length===0&&!options.env?.[BUN_ENVIRONMENT_FLAG]){return this.runNodeContainer(argv,options)}const executablePath=targetPath;const temporaryDirectory=preloads.length>0?cwd:"/tmp/browser-runtime-node-entry";const temporaryPath=`${temporaryDirectory==="/"?"":temporaryDirectory}/${preloads.length>0?".browser-runtime-node-entry-":""}${globalThis.crypto.randomUUID()}.cjs`;const runtimeFiles=this.options.runtimeFiles??this.container.vfs;runtimeFiles.mkdirSync(temporaryDirectory,{recursive:true});runtimeFiles.writeFileSync(temporaryPath,[`Object.assign(process.env, ${JSON.stringify(options.env??{})});`,`process.argv = ${JSON.stringify(["node",targetPath,...argv.slice(2)])};`,...options.env?.[BUN_ENVIRONMENT_FLAG]?[`require(${JSON.stringify(BUN_GLOBALS_PATH)});`]:[],...preloads.length>0?[preloadLines(preloads)]:[],`require("module")._load(${JSON.stringify(executablePath)}, null, true);`,""].join("\n"));try{return await this.runNodeContainer(["node",temporaryPath],options)}finally{if(runtimeFiles.existsSync(temporaryPath))runtimeFiles.unlinkSync(temporaryPath)}}runNext(argv,options){const cli=this.installedBin("next",normalizeAbsolutePath(options.cwd??"/"));if(!cli)return Promise.resolve({stdout:"",stderr:"next: the project has no next installed to run it.\n",exitCode:1});let args=[...argv];if(args[1]==="dev"){const turbo=args.some(arg=>arg==="--turbopack"||arg==="--turbo");args=args.filter(arg=>arg!=="--turbopack"&&arg!=="--turbo");if(this.nextGeneration(normalizeAbsolutePath(options.cwd??"/"))>=16&&!args.includes("--webpack"))args.push("--webpack");if(turbo)options.onStderr?.("next dev: Turbopack is a native binary the tab cannot run; bundling with webpack.\n")}return cli(args,options)}runVite(argv,options){const cli=this.installedBin("vite",normalizeAbsolutePath(options.cwd??"/"));if(cli)return cli(argv,options);return Promise.resolve({stdout:"",stderr:"vite: the project has no vite installed to run it.\n",exitCode:1})}runContainer(argv,options){const environment=Object.entries({...this.vendorSeams(options.cwd),...options.env??{}}).filter(([name])=>EXPORTABLE_NAME.test(name)&&!SHELL_OWNED_NAMES.has(name)).map(([name,value])=>`${name}=${renderCommand([value])}`);const command=[...environment,renderCommand(argv)].join(" ");return this.container.run(command,options)}vendorSeams(cwd){const seams={};const vfs2=this.container.vfs;let directory2=cwd&&cwd.startsWith("/")?cwd:"/workspace/app";for(;;){if(vfs2.existsSync(`${directory2}/node_modules/lightningcss/pkg/package.json`)){seams.CSS_TRANSFORMER_WASM="1";break}if(directory2==="/"||directory2==="")break;directory2=directory2.slice(0,directory2.lastIndexOf("/"))||"/"}return seams}async runNodeContainer(argv,options){if(nodeProcessHostInstalled())options={...options,held:false};options={...options,env:{...this.vendorSeams(options.cwd),...options.env??{}}};try{await this.rolldown?.prepare(normalizeAbsolutePath(options.cwd??"/"))}catch(error){const stderr=`Rolldown metadata registration failed: ${error instanceof Error?error.message:String(error)}
6424
6424
  `;options.onStderr?.(stderr);return{stdout:"",stderr,exitCode:1}}const portsBeforeLaunch=new Set(this.container.serverBridge.getServerPorts());if(!this.container.isolated&&this.nodeFetchDepth===0){this.originalFetch=globalThis.fetch.bind(globalThis);globalThis.fetch=this.loopbackFetch;this.hadOriginalChildProcessExecutor=Reflect.has(globalThis,childProcessExecutorSymbol);this.originalChildProcessExecutor=Reflect.get(globalThis,childProcessExecutorSymbol);const childProcessRunner=this.options.runChildProcessCommand??this.options.runShellCommand;if(childProcessRunner){Reflect.set(globalThis,childProcessExecutorSymbol,{bypass:0,...options.signal?{parentSignal:options.signal}:{},run:async(command,runOptions)=>{const hold2=runOptions.hold??{value:true};this.heldChildren.add(hold2);try{return await childProcessRunner(command,runOptions)}finally{this.heldChildren.delete(hold2)}}})}}const namedToken=options.processToken;const processToken=typeof namedToken==="string"?namedToken:globalThis.crypto.randomUUID();const owner=this.container;const pendingTimers=()=>owner.pendingTimers?.(processToken)??0;const heldBuilds=()=>(Reflect.get(globalThis,"__browserRuntimeHeldWork")?.count??0)+(this.rolldown?.pendingWork??0);const bridgeChildren=()=>Reflect.get(globalThis,childProcessExecutorSymbol)?.pending?.(processToken)??0;const executionController=options.signal?new AbortController:void 0;const stopOnKill=()=>{executionController?.abort();owner.stopProcess?.(processToken)};options.signal?.addEventListener("abort",stopOnKill,{once:true});if(!this.container.isolated)this.nodeFetchDepth+=1;try{let lastOutputAt;const liveStdin=options.stdinStream;let stdinOpen=liveStdin!==void 0;const heldStdin=liveStdin===void 0?void 0:(async function*(){try{for await(const chunk of liveStdin)yield chunk}finally{stdinOpen=false;lastOutputAt=Date.now()}})();const containerOptions=(({signal:_signal,onStdout,onStderr,...rest})=>({...rest,processToken,...heldStdin?{stdinStream:heldStdin}:{},...executionController?{signal:executionController.signal}:{},...onStdout?{onStdout:chunk=>{lastOutputAt=Date.now();onStdout(chunk)}}:{},...onStderr?{onStderr:chunk=>{lastOutputAt=Date.now();onStderr(chunk)}}:{}}))(options);const childProcessBridge=this.container.isolated?void 0:Reflect.get(globalThis,childProcessExecutorSymbol);if(childProcessBridge)childProcessBridge.bypass+=1;const launchedAt=Date.now();const execution=this.runContainer(argv,containerOptions);await nextTask();const portsOwned=()=>owner.processPorts?.(processToken)??this.container.serverBridge.getServerPorts().filter(port2=>!portsBeforeLaunch.has(port2));let ownedPorts=portsOwned();if(options.held!==true)return await execution;const holdSignal=options.signal??new AbortController().signal;if(ownedPorts.length===0){let settled;void execution.then(result2=>{settled=result2});let lastTickAt=Date.now();let quietSince=lastTickAt;while(!holdSignal.aborted){ownedPorts=portsOwned();if(ownedPorts.length>0)break;const now=Date.now();if(now-lastTickAt>150)quietSince=now;lastTickAt=now;const idle=now-Math.max(lastOutputAt??launchedAt,quietSince)>=500;const working=!settled&&stdinOpen||pendingTimers()>0||[...this.heldChildren].some(hold2=>hold2.value)||bridgeChildren()>0||heldBuilds()>0;if(working)quietSince=now;if(settled&&!working&&(liveStdin===void 0||idle))break;if(!settled&&executionController&&!working&&idle){break}await delay(50)}if(ownedPorts.length===0)ownedPorts=portsOwned();if(ownedPorts.length===0){const idleStop2=!settled&&executionController!==void 0&&!holdSignal.aborted;if(!settled)executionController?.abort();const result2=settled??await execution;return holdSignal.aborted?{...result2,exitCode:143}:idleStop2&&result2.exitCode===143?{...result2,exitCode:0}:result2}}while(!holdSignal.aborted&&(owner.processPorts?portsOwned().length>0:ownedPorts.some(port2=>this.container.serverBridge.getServerPorts().includes(port2)))){await delay(50)}if(holdSignal.aborted&&!owner.processPorts){for(const port2 of ownedPorts){if(this.container.serverBridge.getServerPorts().includes(port2)){this.container.serverBridge.unregisterServer(port2)}}}const idleStop=executionController!==void 0&&!holdSignal.aborted;executionController?.abort();const result=await execution;return holdSignal.aborted?{...result,exitCode:143}:idleStop&&result.exitCode===143?{...result,exitCode:0}:result}finally{if(owner.processPorts?.(processToken).length===0)owner.stopProcess?.(processToken);options.signal?.removeEventListener("abort",stopOnKill);if(!this.container.isolated)this.nodeFetchDepth-=1;if(!this.container.isolated&&this.nodeFetchDepth===0){if(this.originalFetch)globalThis.fetch=this.originalFetch;this.originalFetch=void 0;if(this.hadOriginalChildProcessExecutor){Reflect.set(globalThis,childProcessExecutorSymbol,this.originalChildProcessExecutor)}else{Reflect.deleteProperty(globalThis,childProcessExecutorSymbol)}this.hadOriginalChildProcessExecutor=false;this.originalChildProcessExecutor=void 0}}}loopbackFetch=async(input,init)=>{const request=new Request(input,init);const url2=new URL(request.url);const port2=url2.port?Number(url2.port):url2.protocol==="http:"?80:443;const local2=(url2.protocol==="http:"||url2.protocol==="https:")&&(url2.hostname==="127.0.0.1"||url2.hostname==="localhost"||url2.hostname.endsWith(".localhost")||url2.hostname==="[::1]");if(!local2){if(url2.protocol!=="https:")throw new Error("Browser Node external requests require HTTPS.");this.options.authorizeExternalRequest?.(url2);if(!this.originalFetch)throw new Error("Browser fetch is unavailable.");return this.originalFetch(input,init)}if(!this.container.serverBridge.getServerPorts().includes(port2)){const here=globalThis.location;if(here?.host&&url2.host===here.host&&this.originalFetch)return this.originalFetch(input,init);throw new Error(`Virtual loopback port ${port2} is not listening (${url2.href}; this page is ${here?.host??"unknown"}).`)}const headers={};request.headers.forEach((value,name)=>{headers[name]=value});headers.host=url2.host;const body=request.method==="GET"||request.method==="HEAD"?void 0:await request.arrayBuffer();const response=await this.container.serverBridge.handleRequest(port2,request.method,`${url2.pathname}${url2.search}`,headers,body);const responseHeaders=new Headers;for(const[name,value]of Object.entries(response.headers)){for(const item of Array.isArray(value)?value:[value])responseHeaders.append(name,item)}const bodyForbidden=request.method==="HEAD"||[204,205,304].includes(response.statusCode);const responseBody=!bodyForbidden&&response.body?Uint8Array.from(response.body):null;return new Response(responseBody,{status:response.statusCode,statusText:response.statusMessage??"",headers:responseHeaders})}};function nextTask(){return delay(0)}function delay(milliseconds){const nativeSetTimeout=globalThis.__browserRuntimeNativeSetTimeout??globalThis.setTimeout;return new Promise(resolve2=>nativeSetTimeout.call(globalThis,resolve2,milliseconds))}function normalizeAbsolutePath(value){const parts=[];for(const part of`/${value}`.split("/")){if(!part||part===".")continue;if(part==="..")parts.pop();else parts.push(part)}return`/${parts.join("/")}`}function ensureFsAppend(container2){const shim=container2.runtime?.fsShim;if(!shim||typeof shim.writeFileSync!=="function"||typeof shim.appendFileSync==="function")return;const encoder7=new TextEncoder;const bytes2=value=>typeof value==="string"?encoder7.encode(value):value;const appendSync=(path3,data2,options)=>{let existing=new Uint8Array(0);try{existing=bytes2(shim.readFileSync(path3))}catch{}const next2=bytes2(data2);const joined=new Uint8Array(existing.length+next2.length);joined.set(existing);joined.set(next2,existing.length);shim.writeFileSync(path3,joined,options)};shim.appendFileSync=appendSync;shim.appendFile=(path3,data2,optionsOrCallback,callback)=>{const done=typeof optionsOrCallback==="function"?optionsOrCallback:callback;try{appendSync(path3,data2,typeof optionsOrCallback==="function"?void 0:optionsOrCallback);done?.(null)}catch(error){done?.(error)}};if(shim.promises&&typeof shim.promises==="object"){shim.promises.appendFile=async(path3,data2,options)=>appendSync(path3,data2,options)}}function nodePreloads(argv,env){const preloads=[];const take=(words,strip)=>{const kept=[];for(let index2=0;index2<words.length;index2+=1){const word=words[index2];if(word==="--require"||word==="-r"||word==="--import"){const name=words[index2+1];if(name!==void 0){preloads.push(name);index2+=1}continue}const inline=/^--(?:require|import)=(.+)$/u.exec(word);if(inline){preloads.push(inline[1]);continue}if(strip&&!word.startsWith("-")){kept.push(...words.slice(index2));break}kept.push(word)}return kept};const nodeOptions=env.NODE_OPTIONS?.match(/(?:[^\s"]+|"[^"]*")+/gu)?.map(word=>word.replace(/^"|"$/gu,""))??[];take(nodeOptions,false);const[program,...rest]=argv;return{argv:[program,...take(rest,true)],preloads}}function preloadLines(preloads){return preloads.map(name=>`require(${JSON.stringify(name)});`).join("\n")+(preloads.length>0?"\n":"")}function networkProgram(command){const unquote=word=>word.replace(/^(['"])([\s\S]*)\1$/u,"$2");const words=command.trim().split(/\s+/u).map(unquote);let index2=words[0]==="env"?1:0;while(index2<words.length&&/^[A-Za-z_][A-Za-z0-9_]*=/u.test(words[index2]))index2+=1;const executable=words[index2]?.split("/").at(-1)??"node";return/^[A-Za-z0-9._+-]{1,64}$/u.test(executable)?executable:"node"}function programFromCommand(command,executablePath){return networkProgram(executablePath??command)}function programOfPid(pid,runs2,pidOf){for(const[id2,run]of runs2){if(pidOf(String(id2))?.pid===pid)return run.program}return void 0}function inheritedProgram(ppid,runs2,pidOf,processByPid2){const seen=new Set;let current3=ppid;while(current3>0&&!seen.has(current3)){seen.add(current3);const named=programOfPid(current3,runs2,pidOf);if(named)return named;current3=processByPid2(current3)?.ppid??0}return void 0}function owningRun(token,runs2,pidOf,processByPid2){const ids=pidOf(token);if(!ids)return void 0;const runOfPid=pid=>{for(const id2 of runs2.keys())if(pidOf(String(id2))?.pid===pid)return id2;return void 0};const own=runOfPid(ids.pid);if(own!==void 0)return own;const seen=new Set;let current3=ids.ppid;while(current3>0&&!seen.has(current3)){seen.add(current3);const named=runOfPid(current3);if(named!==void 0)return named;current3=processByPid2(current3)?.ppid??0}return void 0}function networkProgramNow(runs2,token,pidOf,processByPid2){const activePrograms=[...new Set([...runs2.values()].map(run=>run.program))];const ids=pidOf(token);if(ids){const own=programOfPid(ids.pid,runs2,pidOf);const program=own??inheritedProgram(ids.ppid,runs2,pidOf,processByPid2);if(program){return{program,attributed:true,activePrograms,...own===void 0?{pid:ids.pid}:{}}}}if(token!==null){const owned=runs2.get(Number(token));if(owned)return{program:owned.program,attributed:true,activePrograms}}let latest;for(const run of runs2.values())if(!latest||run.startedAt>latest.startedAt)latest=run;return{program:latest?.program??"node",attributed:false,activePrograms}}function tabnodeContainerView(container2,vfs2,overrides={}){return new Proxy(container2,{get(target,key){if(key==="vfs")return vfs2;if(key in overrides)return overrides[key];const value=Reflect.get(target,key);return typeof value==="function"?value.bind(target):value}})}var scope3=self;console.log("[boot-trace]",JSON.stringify({event:"worker-module-ready",at:Date.now()}));scope3.addEventListener("error",event=>{const error=event.error;console.error(`[node worker] uncaught: ${event.message} at ${event.filename||"<generated>"}:${event.lineno}:${event.colno}
6425
- ${error?.stack??"(no stack)"}`)});scope3.addEventListener("unhandledrejection",event=>{const reason=event.reason;console.error(`[node worker] unhandled rejection: ${reason?.stack??String(reason)}`)});var executorSymbol=Symbol.for("@volter/browser-runtime/child-process-executor");var port;var container;var packStore;var packStoreProjectId;async function openStoreReads(grant){const clock=new Int32Array(grant.clock);const before=Atomics.load(clock,STORE_CLOCK_EPOCH);let openedAt=before;const began=Date.now();const opening=openPackReader({navigator:scope3.navigator},grant.projectId,grant.seed,grant.imageLine).then(reader=>{if(reader?.seeded()&&grant.seed)openedAt=grant.seed.epoch;processReader=reader;return reader}).catch(cause=>{console.warn(`This process reads the project's files through their owner: its own reader did not open (${cause instanceof Error?cause.message:String(cause)}).`);return void 0});await Promise.race([opening,new Promise(resolve2=>setTimeout(resolve2,STORE_OPEN_BUDGET_MS))]);console.log(`[boot-trace] ${JSON.stringify({event:"store-open",at:Date.now(),ms:Date.now()-began,opened:processReader!==void 0})}`);return{opening,clock:grant.clock,get openedAt(){return openedAt}}}var STORE_OPEN_BUDGET_MS=1500;function storeReadsFor(filesystem){const active2=container;if(!packStore||!packStoreProjectId||!active2||filesystem!==active2.vfs||!(filesystem instanceof PackedVirtualFS))return{};const store=packStore,projectId=packStoreProjectId;return{storeReads:()=>{if(packStore!==store)return void 0;const clock=store.clock();const seed=store.readerSeed({overlays:true});const imageLine=seed?.packagesImage?store.imageLine():void 0;return{projectId,clock,...seed?{seed}:{},...imageLine?{imageLine}:{}}}}}var storeWriteFailure;function reportStoreWriteFailure(){const failure=storeWriteFailure;if(!failure)return;storeWriteFailure=void 0;throw failure}var packages;var packagesFilesystem;var processReader;var imageBlocked=()=>{const blocked=(processReader??packages)?.imageBlockedReads();return blocked&&blocked.ranges>0?{ranges:blocked.ranges,ms:Math.round(blocked.ms)}:void 0};var releasePackagesOpen;var initializationStarted=false;var workerDisposing=false;var portStreams=new Map;var childInputSupported=false;var releaseProject;var bundler;var threads;var workerOptions={};function configureNodeExecutionWorker(options){workerOptions=options}var toolchain;var invocationPolicy;var invocationFiles;var executionConfiguration;var confinedRuns=new Map;var nodeProcesses=new NodeProcessSupervisor;var rootRuntimeFiles;var programs=new Map;var commandResolver;function routeCommand2(command,cwd){if(!toolchain)return void 0;let argv;try{argv=parseCommandWords(command)}catch{return void 0}const env={};while(argv.length){const assignment=/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/su.exec(argv[0]);if(!assignment)break;env[assignment[1]]=assignment[2];argv.shift()}if(argv[0]==="/usr/bin/env"&&argv.length>1)argv.shift();let name=argv[0];if(name===void 0)return void 0;if(name.startsWith("/")&&!programs.has(name)){const basename2=name.slice(name.lastIndexOf("/")+1);if(programs.has(basename2)){name=basename2;argv[0]=basename2}}const runner2=programs.get(name)??commandResolver?.(name,cwd);return runner2?{argv,runner:runner2,env}:void 0}async function runCommand2(command,options){const links=splitShellChain(command);if(links.length===1)return runOneCommand(command,options);let stdout="";let stderr="";let exitCode=0;for(const link2 of links){if(!chainContinues(link2.operator,exitCode))continue;const result=await runOneCommand(link2.command,options);stdout+=result.stdout;stderr+=result.stderr;exitCode=result.exitCode}return{stdout,stderr,exitCode}}function runOneCommand(command,options){assertWorkerActive();options.signal?.throwIfAborted();const shellLine=shellCommandLine(command);if(shellLine!==void 0){const{executablePath:_shell,...lineOptions}=options;return runCommand2(shellLine,lineOptions)}const routed=routeCommand2(command,options.cwd??"/");if(routed)return routed.runner(routed.argv,{...options,env:{...options.env,...routed.env}});return engineRun(requiredContainer(),command,options)}function engineRun(active2,command,options){const bridge=Reflect.get(globalThis,executorSymbol);if(bridge)bridge.bypass+=1;return active2.run(command,options)}function toolchainContainer(active2){return tabnodeContainerView(active2,active2.vfs,{isolated:true,run:(command,options)=>engineRun(active2,command,options)})}var sharedModuleCache;var moduleCacheAnswers=new Map;var nextModuleCacheRequest=1;function askOwnerModuleCache(message){const id2=nextModuleCacheRequest++;return new Promise((resolve2,reject)=>{moduleCacheAnswers.set(id2,{resolve:resolve2,reject});send({...message,id:id2})})}var ownerModuleCache={link:(key,target)=>askOwnerModuleCache({type:"module-cache-link",key,target}),keep:async(key,code3,target)=>{await askOwnerModuleCache({type:"module-cache-keep",key,code:code3,target})}};function moduleCacheOption(vfs2){const moduleCache=projectModuleCache(vfs2);return moduleCache?{moduleCache}:{}}function projectModuleCache(vfs2){if(invocationFiles&&!packages)return ownerModuleCache;if(!packages||!packagesFilesystem||!(vfs2 instanceof PackedVirtualFS))return void 0;sharedModuleCache??=moduleCacheOver(packages,packagesFilesystem,vfs2);return sharedModuleCache}function installToolchain(active2,options){const moduleCache=projectModuleCache(active2.vfs);toolchain=new TabnodeToolchain(toolchainContainer(active2),{...invocationFiles?{runtimeFiles:invocationFiles.runtimeFiles}:rootRuntimeFiles?{runtimeFiles:rootRuntimeFiles}:{},...options.rolldownModuleUrl?{rolldownModuleUrl:new URL(options.rolldownModuleUrl,scope3.location.href).href}:{},...options.standIns?{standIns:{...options.standIns}}:{},...moduleCache?{moduleCache}:{},...options.browserImports?{browserImports:options.browserImports}:{},...options.defaultVitePort!==void 0?{defaultVitePort:options.defaultVitePort}:{},...options.registryScopes?{registryScopes:options.registryScopes}:{},runShellCommand:runCommand2,runChildProcessCommand:runCommand2,authorizeExternalRequest:()=>void 0});toolchain.register({registerProgram:(name,runner2)=>{programs.set(name,runner2)},registerCommandResolver:resolver=>{commandResolver=resolver}});for(const manager of PACKAGE_MANAGER_ALIASES.filter(manager2=>manager2!=="pnpm"))programs.set(manager,packageManagerAliasRunner(manager,runCommand2));if(options.standIns)void fetchPrismaSchemaParser(active2.vfs,options.standIns)}var suppressFilesystemEvents=false;var importingFilesystemRoot;var activeRuns=new Map;function beginRun(id2,command,extra){console.log(`[boot-trace] ${JSON.stringify({event:"run-start",at:Date.now(),id:id2,program:programFromCommand(command,extra.executablePath)})}`);const{executablePath,...rest}=extra;activeRuns.set(id2,{...rest,program:programFromCommand(command,executablePath),command,startedAt:Date.now()})}function enginePids(){if(!container)return void 0;const engine=container;if(typeof engine.runPid!=="function"||typeof engine.processByPid!=="function")return void 0;return{token:()=>engine.currentProcessToken(),runPid:engine.runPid,processByPid:engine.processByPid}}function attributionNow(){const engine=enginePids();return networkProgramNow(activeRuns,engine?.token()??container?.currentProcessToken()??null,token=>engine?.runPid(token),pid=>engine?.processByPid(pid))}var nextFetchId=1;var pendingFetches=new Map;var responseStreams=new Map;var fetchAbortCleanup=new Map;var fetchActivities=new Map;function pullFetch(id2){const owned=fetchActivities.get(id2);try{if(owned)owned.pulls.push(owned.activity.hold());send({type:"fetch-pull",id:id2})}catch(cause){owned?.cancel();throw cause}}var filesystemForwardingScheduled=false;var settleEngineInitialized;var initialized=new Promise((resolve2,reject)=>{settleEngineInitialized={resolve:resolve2,reject}});void initialized.catch(()=>void 0);publishEngineInitialized(initialized);scope3.addEventListener("message",event=>{if(receiveNodeThread(event))return;if(port||event.data.type!=="attach"||!(event.data.port instanceof MessagePort))return;console.log("[boot-trace]",JSON.stringify({event:"worker-attach-received",at:Date.now()}));port=event.data.port;port.addEventListener("message",message=>void receive(message.data));port.start();send({type:"attached"})});async function receive(message){if(message.type==="module-cache-answer"){const waiter=moduleCacheAnswers.get(message.id);moduleCacheAnswers.delete(message.id);if(message.error)waiter?.reject(new Error(message.error));else waiter?.resolve(message.linked);return}try{if(message.type==="dispose"){if(!workerDisposing)await disposeWorker();return}assertWorkerActive();if(message.type==="init-confined"){if(initializationStarted)throw new Error("Browser Node host initialization has already started.");initializationStarted=true;childInputSupported=message.childInputVersion===1;const processRegistry2=new NodeProcessRegistryClient(message.processRegistry);installProcessRegistry(processRegistry2,message.initialProcess);if(processRegistry2.streams)installNativeStreamTransport(processRegistry2.streams);if(message.nodeProcess){if(!message.initialProcess||message.initialProcess.token!=="1"||!processRegistry2.streams){throw new Error("Node process execution requires its admitted run and native stream channel.")}installNodeEntryBridge(message.initialProcess.token,message.nodeProcess)}if(message.filesystemPolicy===void 0&&!message.nodeProcess)throw new Error("An ordinary Node realm requires process admission.");invocationPolicy=message.filesystemPolicy===void 0?void 0:normalizeProcessFilesystemPolicy(message.filesystemPolicy);if(message.preparedFiles&&!message.nodeProcess)throw new Error("Prepared entries require Node process admission.");const files=nodeInvocationFilesystem(message.filesystem,invocationPolicy,message.nodeProcess?{files:message.preparedFiles??[],limits:message.nodeProcess}:void 0,message.storeReads?await openStoreReads(message.storeReads):void 0);invocationFiles=files;container=createContainer({...message.options,vfs:files.guest});installPortForwarding();if(message.bundler)installBundler(container.vfs,message.bundler);threads=installNodeThreadHost(container.vfs,message.bundler);installToolchain(container,message.toolchain??{});installNetworkBroker();installChildProcessBridge();restrictNodeWorkerAuthority();send({type:"initialized",id:message.id,filesystemPolicyVersion:1,processRegistryVersion:1,...processRegistry2.streams?{nativeStreamVersion:1}:{},...message.nodeProcess?{nodeProcessVersion:1}:{},...typeof container?.signalProcess==="function"?{signalVersion:1}:{},inputBytesVersion:1,store:{opened:false,index:[]}});return}if(message.type==="init"){if(initializationStarted)throw new Error("Browser Node host initialization has already started.");initializationStarted=true;nodeProcesses.prepareWorkers(scope3.location.href);childInputSupported=message.childInputVersion===1;executionConfiguration={options:message.options,...message.bundler?{bundler:message.bundler}:{},...message.toolchain?{toolchain:message.toolchain}:{}};{const handoff2=takeStoreHandoff();const held=handoff2?.held??await holdProjectStores({projectId:String(message.store.projectId),...message.store.limits?{limits:message.store.limits}:{},report:work=>send({type:"initializing",id:message.id,work}),disposing:()=>workerDisposing});releaseProject=held.releaseProject;releasePackagesOpen=held.releasePackagesOpen;packages=held.shared;installPackageStore(held.shared);const store=held.store;packStore=store;for(const plan of held.preparedPlans??[])preparedProjectPlans.set(plan.root,plan.key);packStoreProjectId=String(message.store.projectId);const opened=held.opened;const{startedAt,phases}=held;const phase=(name,since)=>{phases.push(`${name} ${Math.round(performance.now()-since)} ms`);return performance.now()};const at3=performance.now();container=createContainer({...message.options,vfs:new PackedVirtualFS(store)});for(const entry of handoff2?.overlay??[]){if(entry.type==="directory"){if(!container.vfs.existsSync(entry.path))container.vfs.mkdirSync(entry.path,{recursive:true})}else container.vfs.writeFileSync(entry.path,entry.bytes)}{const active3=container;mountContainerProc(active3.vfs,ownerProcessTable,()=>active3.serverBridge.getServerPorts().map(port2=>{const pid=active3.portPid(port2);return{port:port2,...pid?{pid}:{}}}),()=>active3.streamHandles())}phase("engine",at3);console.log(`[worker] started in ${Math.round(performance.now()-startedAt)} ms: ${phases.join(", ")}`);if(message.toolchain?.typeStripperModuleUrl)await installTypeStripper(new URL(message.toolchain.typeStripperModuleUrl,scope3.location.href).href);webSocketRelay=createVirtualWebSocketRelay(relayed=>send({type:"ws",message:relayed}));if(message.bundler)installBundler(container.vfs,message.bundler);threads=installNodeThreadHost(container.vfs,message.bundler,{projectId:String(message.store.projectId),flush:()=>store.flush()});installFilesystemForwarding(container.vfs);installRootNodeEntryBridge();if(message.toolchain)installToolchain(container,message.toolchain);installNetworkBroker();installChildProcessBridge();const index2=[];let sharedIndex;if(!handoff2){if(message.sharedPageIndexVersion===1){store.clock();const seed=store.readerSeed({current:true});if(seed)sharedIndex={buffer:seed.index,roots:PROJECT_ROOTS,bytes:seed.liveBytes+seed.linkedBytes}}if(!sharedIndex)for(const[path3,entry]of store.entries)index2.push([path3,entry.type,entry.length,entry.mode,entry.mtimeMs])}send({type:"initialized",id:message.id,filesystemPolicyVersion:1,inputBytesVersion:1,store:{opened,index:index2,...sharedIndex?{sharedIndex}:{},treeImport:true,limitsVersion:1,entryReadVersion:1}});settleEngineInitialized?.resolve();return}}if(message.type==="fetch-response-start"){const pending=pendingFetches.get(message.id);if(!pending)return;pendingFetches.delete(message.id);try{const id2=message.id;const body=pending.method==="HEAD"||[204,205,304].includes(message.status)?null:new ReadableStream({start(controller){responseStreams.set(id2,controller)},pull(){pullFetch(id2)},cancel(){responseStreams.delete(id2);fetchAbortCleanup.get(id2)?.();fetchAbortCleanup.delete(id2);try{send({type:"fetch-abort",id:id2})}catch{}}},{highWaterMark:0});fetchActivities.get(id2)?.headersDone();pending.resolve({body,status:message.status,statusText:message.statusText,headers:message.headers});if(body===null)pullFetch(id2)}catch(cause){fetchAbortCleanup.get(message.id)?.();fetchAbortCleanup.delete(message.id);try{send({type:"fetch-abort",id:message.id})}catch{}pending.reject(cause instanceof Error?cause:new Error(String(cause)))}return}if(message.type==="fetch-response-chunk"){fetchActivities.get(message.id)?.pulls.shift()?.();responseStreams.get(message.id)?.enqueue(new Uint8Array(message.body));return}if(message.type==="fetch-response-end"){const stream=responseStreams.get(message.id);responseStreams.delete(message.id);fetchAbortCleanup.get(message.id)?.();fetchAbortCleanup.delete(message.id);stream?.close();return}if(message.type==="fetch-response"||message.type==="fetch-error"){const pending=pendingFetches.get(message.id);if(message.type==="fetch-error"){if(pending){pendingFetches.delete(message.id);pending.reject(new Error(message.error))}const stream=responseStreams.get(message.id);responseStreams.delete(message.id);fetchAbortCleanup.get(message.id)?.();fetchAbortCleanup.delete(message.id);stream?.error(new Error(message.error))}else if(!pending)return;else{pendingFetches.delete(message.id);fetchAbortCleanup.get(message.id)?.();fetchAbortCleanup.delete(message.id);try{pending.resolve({body:pending.method==="HEAD"||[204,205,304].includes(message.status)?null:new ReadableStream({start(controller){controller.enqueue(new Uint8Array(message.body));controller.close()}}),status:message.status,statusText:message.statusText,headers:message.headers})}catch(cause){pending.reject(cause instanceof Error?cause:new Error(String(cause)))}}return}if(message.type==="apply-layers"){try{const result=await applyImageLayers(message.url,message.digest,(parts,total)=>send({type:"applying-layers",id:message.id,parts,total}),message.prepared);send({type:"layers-applied",id:message.id,...result})}catch(cause){send({type:"layers-applied",id:message.id,parts:0,units:0,bytes:0,skipped:false,error:cause instanceof Error?cause.message:String(cause)})}return}if(message.type==="link-program"){try{send({type:"linked-program",id:message.id,...await linkImageProgram(message.source,message.target)})}catch(cause){send({type:"linked-program",id:message.id,linked:false,files:0,error:cause instanceof Error?cause.message:String(cause)})}return}if(message.type==="link-packages"){try{if(!linkPlan)throw new Error("The origin's package store is not open.");const result=await linkPlan(message.root,message.plan,(linked,total,waiting)=>send({type:"linking-packages",id:message.id,linked,total,...waiting?{waiting}:{}}));send({type:"linked-packages",id:message.id,...result})}catch(cause){const described=cause instanceof Error?cause.message?`${cause.name==="Error"?"":`${cause.name}: `}${cause.message}`:cause.name:String(cause);send({type:"linked-packages",id:message.id,linked:0,fetched:0,fromStore:0,error:described})}return}if(message.type==="pack-store-abort"){packStoreOperations.get(message.id)?.abort();return}if(message.type==="pack-store"){const controller=new AbortController;packStoreOperations.set(message.id,controller);try{await answerPackStore(message,controller.signal,{packages,project:packStore,linkShared:(source,target)=>{const vfs2=requiredContainer().vfs;if(!(vfs2 instanceof PackedVirtualFS))throw new Error("The live pack needs the worker's packed filesystem.");vfs2.linkShared(source,target)},send})}finally{packStoreOperations.delete(message.id)}return}if(message.type==="image-file"){const pending=pendingImageFiles.get(message.id);pendingImageFiles.delete(message.id);if(!pending)return;if(message.error!==void 0||message.bytes===void 0)pending.reject(new Error(`The image's file could not be read: ${message.error??"the page answered without it"}`));else pending.resolve({bytes:new Uint8Array(message.bytes),inflated:message.inflated===true});return}if(message.type==="image-pack"){const pending=pendingImagePacks.get(message.id);pendingImagePacks.delete(message.id);if(!pending)return;if(message.error!==void 0||message.text===void 0)pending.reject(new Error(message.error??"the page answered without the pack"));else pending.resolve(message.text);return}if(message.type==="image-packs-expected"){imagePacksKnown??=new Promise(resolve2=>{settleImagePacksKnown=resolve2});return}if(message.type==="image-packs-abandoned"){settleImagePacksKnown?.();imagePacksKnown=settleImagePacksKnown=void 0;return}if(message.type==="image-packs"){try{const packs=readImagePacks(message.keys);settleImagePacksKnown?.();imagePacksKnown=settleImagePacksKnown=void 0;if(message.bodies?.length)await linkPreparedBodies(message.bodies);send({type:"image-packs-read",id:message.id,packs})}catch(cause){send({type:"image-packs-read",id:message.id,packs:0,error:cause instanceof Error?cause.message:String(cause)})}finally{settleImagePacksKnown?.();imagePacksKnown=settleImagePacksKnown=void 0}return}if(message.type==="ws"){webSocketRelay?.receive(message.message);return}if(message.type==="watched-paths"){const vfs2=container?.vfs;const paths=typeof vfs2?.watchedPaths==="function"?vfs2.watchedPaths():vfs2?.watchers?[...vfs2.watchers.entries()].filter(([,entries])=>[...entries].some(entry=>!entry.closed)).map(([path3,entries])=>({path:path3,recursive:[...entries].some(entry=>!entry.closed&&entry.recursive===true)})):[];send({type:"watched-paths",id:message.id,paths});return}if(message.type==="store-stats"){const account=installAccounting();send({type:"store-stats",id:message.id,stats:packStore?{...packStore.stats(),...account?{install:account}:{}}:null});return}if(message.type==="image-startup-set"){send({type:"image-startup-set",id:message.id,ranges:packages?.imageStartupSet()??[]});return}if(message.type==="image-prefetch"){const startedAt=performance.now();const prefetch=packages?.prefetchImage(message.ranges,message.streams)??{queued:0,done:Promise.resolve()};send({type:"image-prefetch",id:message.id,queued:prefetch.queued});if(prefetch.queued>0)void prefetch.done.then(()=>send({type:"image-prefetched",id:message.id,ms:Math.round(performance.now()-startedAt)}));return}if(message.type==="profile-probe"){send({type:"profile-pong",id:message.id});return}if(message.type==="host-ports"){hostPorts=new Set(message.ports.filter(candidate=>Number.isInteger(candidate)&&candidate>0&&candidate<65536));for(const listener of hostPortListeners)listener(hostPorts);return}if(message.type==="listen-net"||message.type==="unlisten-net"||message.type==="net-data"||message.type==="net-end"){handleNetMessage(message);return}if(message.type==="child-input-consumed"){const pending=pendingChildInput.get(message.id);pendingChildInput.delete(message.id);pending?.resolve();return}if(message.type==="child-fd-consumed"){const key=childFdKey(message.id,message.fd);const pending=pendingChildFdInput.get(key);pendingChildFdInput.delete(key);pending?.resolve();return}if(message.type==="child-fd-output"||message.type==="child-fd-close"){const pending=pendingChildren.get(message.id);const descriptor=validChildFd(message.fd)?pending?.descriptors?.[message.fd]:void 0;if(!pending||!descriptor)return;if(message.type==="child-fd-close"){descriptor.end();return}if(!(message.bytes instanceof ArrayBuffer)||message.bytes.byteLength>childChunkBytes){pendingChildren.delete(message.id);try{send({type:"child-abort",id:message.id})}catch{}pending.reject(new Error("Child process descriptor chunks must be at most 64 KiB."));return}descriptor.write(new Uint8Array(message.bytes));return}if(message.type==="child-output"||message.type==="child-result"||message.type==="child-error"){const pending=pendingChildren.get(message.id);if(!pending)return;if(message.type==="child-output"){if(message.stream==="stdout")pending.onStdout?.(message.chunk);else pending.onStderr?.(message.chunk);return}console.log(`[boot-trace] ${JSON.stringify({event:message.type,at:Date.now(),id:message.id,owner:pending.owner})}`);pendingChildren.delete(message.id);if(message.type==="child-error")pending.reject(new Error(message.error));else pending.resolve({stdout:message.stdout,stderr:message.stderr,exitCode:message.exitCode,...message.signal?{signal:message.signal}:{}});return}const active2=requiredContainer();if(message.type==="fs-watch-event"){invocationFiles?.notifyWatch(message.event,message.path);return}if(message.type==="fs-event"){invocationFiles?.notify(message.event,message.path);return}if(message.type==="run"&&message.filesystemPolicy&&!invocationPolicy){if(!executionConfiguration)throw new Error("Confined Node execution has no worker configuration.");const configuration=executionConfiguration;const policy=normalizeProcessFilesystemPolicy(message.filesystemPolicy);const controller=new AbortController;confinedRuns.set(message.id,controller);beginRun(message.id,message.command,{controller,...message.cwd?{cwd:message.cwd}:{},...message.executablePath?{executablePath:message.executablePath}:{}});const liveStdin=message.liveStdin?openLiveStdin(message.id):void 0;const terminal=message.terminal?openTerminal(message.id,message.terminal):void 0;void nodeProcesses.run(message.command,{...message.cwd?{cwd:message.cwd}:{},...message.env?{env:message.env}:{},...message.stdin!==void 0?{stdin:message.stdin}:{},...liveStdin?{stdinStream:liveStdin}:{},...terminal?{terminal}:{},signal:controller.signal,onStdout:chunk=>send({type:"output",id:message.id,stream:"stdout",chunk}),onStderr:chunk=>send({type:"output",id:message.id,stream:"stderr",chunk})},{filesystem:active2.vfs,...storeReadsFor(active2.vfs),policy,workerUrl:scope3.location.href,configuration,serverBridge:active2.serverBridge,net:pageNetHost,hostPorts:hostPortsHost,...moduleCacheOption(active2.vfs),runChild:(command,options,argv)=>requestChild(command,options,message.id,argv),http:request=>brokerHttpOnce(request,{program:programFromCommand(message.command,message.executablePath),attributed:true,activePrograms:[programFromCommand(message.command,message.executablePath)]})}).then(async result=>{await packStore?.flush();flushFilesystemForwarding();sendResult(message.id,result)}).catch(cause=>{flushFilesystemForwarding();sendError(message.id,cause)}).finally(()=>{confinedRuns.delete(message.id);activeRuns.delete(message.id);liveStdins.get(message.id)?.close(true);liveStdins.delete(message.id);terminals.delete(message.id)});return}if(message.type==="run"){const chain=splitShellChain(message.command).length>1;const routed=chain?void 0:routeCommand2(message.command,message.cwd??"/");const controller=new AbortController;beginRun(message.id,message.command,{...controller?{controller}:{},...message.cwd?{cwd:message.cwd}:{},...message.executablePath?{executablePath:message.executablePath}:{}});launchPorts.set(message.id,new Set(vfsServerBridge().getServerPorts()));if(message.interactive)heldRuns.add(message.id);const liveStdin=message.liveStdin?openLiveStdin(message.id):void 0;const terminal=message.terminal?openTerminal(message.id,message.terminal):void 0;const runOptions={...message.cwd?{cwd:message.cwd}:{},...message.env?{env:message.env}:{},...controller?{signal:controller.signal}:{},held:message.interactive,...{processToken:String(message.id)},...message.stdin!==void 0?{stdin:message.stdin}:{},...liveStdin?{stdinStream:liveStdin}:{},...terminal?{terminal}:{},onStdout:chunk=>send({type:"output",id:message.id,stream:"stdout",chunk}),onStderr:chunk=>send({type:"output",id:message.id,stream:"stderr",chunk})};const running=chain?runCommand2(message.command,runOptions):routed?routed.runner(routed.argv,{...runOptions,env:{...runOptions.env,...routed.env}}):engineRun(active2,message.command,runOptions);void running.then(async result=>{console.log(`[boot-trace] ${JSON.stringify({event:"body-return",at:Date.now(),id:message.id,exitCode:result.exitCode,ports:runPorts(message.id),imageBlocked:imageBlocked()})}`);await workSettled(message.id,message.interactive);flushFilesystemForwarding();const aborted=activeRuns.get(message.id)?.controller?.signal.aborted===true;sendResult(message.id,aborted&&result.exitCode===0?{...result,exitCode:143}:result)},cause=>{flushFilesystemForwarding();sendError(message.id,cause)}).finally(()=>{liveStdins.get(message.id)?.close(true);liveStdins.delete(message.id);terminals.delete(message.id);activeRuns.delete(message.id);launchPorts.delete(message.id);heldRuns.delete(message.id)})}else if(message.type==="stdin"){if(message.id!==void 0){const input=liveStdins.get(message.id);if(message.bytes&&input){const id2=message.id;void input.write(new Uint8Array(message.bytes)).then(()=>send({type:"stdin-consumed",id:id2})).catch(cause=>{activeRuns.get(id2)?.controller?.abort(cause);if(!workerDisposing)sendError(id2,cause)})}else if(input)input.push(message.data);else if(message.data!==void 0)active2.sendInput(message.data,String(message.id))}else active2.sendInput(message.data)}else if(message.type==="stdin-end"){liveStdins.get(message.id)?.close();liveStdins.delete(message.id)}else if(message.type==="resize"){terminals.get(message.id)?.resize(message.columns,message.rows)}else if(message.type==="signal"){active2.signalProcess?.(String(message.id),message.signal)}else if(message.type==="abort"){if(heldRuns.has(message.id))closeRunServers(message.id);confinedRuns.get(message.id)?.abort();for(const[childId,child]of pendingChildren){if(child.owner===message.id)send({type:"child-abort",id:childId})}active2.stopProcess?.(String(message.id));liveStdins.get(message.id)?.close(true);liveStdins.delete(message.id);terminals.delete(message.id);activeRuns.get(message.id)?.controller?.abort()}else if(message.type==="fs-apply"){suppressFilesystemEvents=true;try{for(const operation of message.operations){try{applyStoreOperation(active2.vfs,operation)}catch(cause){storeWriteFailure??=cause instanceof Error?cause:new Error(String(cause));const paths=operation.op==="rename"?[operation.from,operation.to]:[operation.path];for(const path3 of paths)queueIndexForwarding(storeEntryOf(active2.vfs,path3));console.error(`The workspace refused ${operation.op} ${paths.join(" -> ")}: ${cause instanceof Error?cause.message:String(cause)}`)}}}finally{suppressFilesystemEvents=false}}else if(message.type==="fs-import"){reportStoreWriteFailure();if(!(active2.vfs instanceof PackedVirtualFS)||!packStore){send({type:"fs-imported",id:message.id,applied:false,changes:[]});return}flushFilesystemForwarding();const root2=normalizeStorePath2(message.tree.root);importingFilesystemRoot=root2;suppressFilesystemEvents=true;let applied;try{applied=active2.vfs.importTree(message.tree)}finally{suppressFilesystemEvents=false;importingFilesystemRoot=void 0}const changes=[];if(applied){changes.push([root2,null]);for(const[path3,entry]of packStore.descendants(root2)){changes.push([path3,entry.type,entry.type==="file"?entry.length:0,entry.mode,entry.mtimeMs])}}send({type:"fs-imported",id:message.id,applied,changes})}else if(message.type==="fs-read"){try{const bytes2=Uint8Array.from(active2.vfs.readFileSync(message.path));const body=bytes2.buffer.slice(bytes2.byteOffset,bytes2.byteOffset+bytes2.byteLength);send({type:"fs-read-result",id:message.id,bytes:body},[body])}catch(cause){sendError(message.id,cause)}}else if(message.type==="fs-entry"){reportStoreWriteFailure();const path3=normalizeStorePath2(message.path);flushFilesystemForwarding();if(!active2.vfs.existsSync(path3)){send({type:"fs-entry-result",id:message.id})}else{const stat2=active2.vfs.statSync(path3);const metadata={path:path3,mode:stat2.mode&4095,mtimeMs:stat2.mtimeMs};if(stat2.isDirectory()){send({type:"fs-entry-result",id:message.id,entry:{...metadata,type:"directory"}})}else{const bytes2=Uint8Array.from(active2.vfs.readFileSync(path3));send({type:"fs-entry-result",id:message.id,entry:{...metadata,type:"file",bytes:bytes2}},[bytes2.buffer])}}}else if(message.type==="fs-flush"){reportStoreWriteFailure();packStore?.flush();send({type:"fs-flushed",id:message.id})}else if(message.type==="port-stream-request"){const stream={abort:new AbortController,pause:()=>void 0,resume:()=>void 0};portStreams.set(message.id,stream);try{const answered=await active2.serverBridge.handleStreamingRequest(message.port,message.method,message.url,message.headers,message.body,{start:(statusCode,statusMessage,headers)=>send({type:"port-stream-head",id:message.id,statusCode,statusMessage,headers}),chunk:chunk=>{const body=Uint8Array.from(chunk).buffer;send({type:"port-stream-chunk",id:message.id,body},[body])},end:()=>send({type:"port-stream-end",id:message.id})},{signal:stream.abort.signal,control:(pause,resume)=>{stream.pause=pause;stream.resume=resume}});if(!answered){send({type:"port-stream-head",id:message.id,statusCode:503,statusMessage:"Service Unavailable",headers:{}});send({type:"port-stream-end",id:message.id})}}finally{portStreams.delete(message.id)}}else if(message.type==="port-stream-control"){const stream=portStreams.get(message.id);if(message.action==="pause")stream?.pause();else if(message.action==="resume")stream?.resume();else stream?.abort.abort()}else if(message.type==="request"){const response=await active2.serverBridge.handleRequest(message.port,message.method,message.url,message.headers,message.body);const bytes2=response.body?Uint8Array.from(response.body):new Uint8Array;const body=bytes2.buffer.slice(bytes2.byteOffset,bytes2.byteOffset+bytes2.byteLength);send({type:"response",id:message.id,statusCode:response.statusCode,statusMessage:response.statusMessage??"",headers:response.headers,body},[body])}}catch(cause){if(message.type==="init")settleEngineInitialized?.reject(cause);if("id"in message&&typeof message.id==="number")sendError(message.id,cause)}}function assertWorkerActive(){if(workerDisposing)throw new Error("Browser Node host is disposed.")}async function disposeWorker(){workerDisposing=true;const reapedProcesses=nodeProcesses.dispose();const failures=[];const release2=operation=>{try{operation()}catch(cause){failures.push(cause)}};for(const controller of confinedRuns.values())release2(()=>controller.abort());confinedRuns.clear();for(const socket of netSockets.values())release2(()=>socket.destroy());netSockets.clear();for(const unlisten of netListeners.values())release2(unlisten);netListeners.clear();netListenerChanges.clear();for(const controller of packStoreOperations.values())controller.abort();packStoreOperations.clear();for(const run of activeRuns.values())release2(()=>run.controller?.abort());for(const input of liveStdins.values())release2(()=>input.close(true));liveStdins.clear();terminals.clear();for(const pending of pendingChildren.values())pending.reject(new Error("Browser Node host was disposed."));pendingChildren.clear();for(const pending of pendingFetches.values())pending.reject(new Error("Browser Node host was disposed."));pendingFetches.clear();for(const stream of responseStreams.values())stream.error(new Error("Browser Node host was disposed."));responseStreams.clear();for(const cleanup of fetchAbortCleanup.values())cleanup();fetchAbortCleanup.clear();await reapedProcesses;release2(()=>threads?.dispose());threads=void 0;try{await toolchain?.dispose()}catch(cause){failures.push(cause)}toolchain=void 0;release2(()=>bundler?.dispose());bundler=void 0;release2(()=>packStore?.close());packStore=void 0;release2(()=>packages?.close());packages=void 0;release2(()=>releasePackagesOpen?.());releasePackagesOpen=void 0;release2(()=>releaseProject?.());releaseProject=void 0;activeRuns.clear();release2(()=>port?.close());if(failures.length)console.error("Browser Node worker cleanup failed.",new AggregateError(failures));scope3.close()}function installBundler(vfs2,options){bundler=new BrowserBundler(vfs2,options);const shim=esbuildShim;shim.setModuleURL(new URL(options.esbuildModuleUrl,scope3.location.href).href);shim.setWasmURL(new URL(options.esbuildWasmUrl,scope3.location.href).href);if(options.rollupModuleUrl)Reflect.set(globalThis,"__browserRuntimeRollupUrl",new URL(options.rollupModuleUrl,scope3.location.href).href);Reflect.set(globalThis,"__browserRuntimeRollupFs",rollupFsOver(requiredContainer().vfs));bundler.prebundle=vitePrebundleAssembler(vfs2,projectModuleCache(vfs2));shim.useHost(bundler)}function normalizeStorePath2(path3){const parts=[];for(const part of path3.split("/")){if(!part||part===".")continue;if(part==="..")parts.pop();else parts.push(part)}return`/${parts.join("/")}`}var installAccount={packages:0,linkedFromStore:0,downloadMs:0,downloadBytes:0,lockWaitMs:0,extractMs:0,extractHelpers:0,applyMs:0,linkMs:0,announceMs:0,sharedFlushes:0,sharedFlushMs:0,elapsedMs:0,lastAt:0};var packStoreOperations=new Map;function installAccounting(){if(installAccount.packages===0)return void 0;const{firstAt,lastAt,...account}=installAccount;return{...account,elapsedMs:firstAt===void 0?0:Math.round(lastAt-firstAt)}}function installPackageStore(shared){const sharedFilesystem=new PackedVirtualFS(shared,PACKAGES_ROOT);packagesFilesystem=sharedFilesystem;const making=new Map;const ensure=async(key,tarballUrl,integrity,pack)=>{try{return await make(key,tarballUrl,integrity,pack)}finally{making.delete(key)}};const make=async(key,tarballUrl,integrity,pack)=>{const startedAt=performance.now();installAccount.firstAt??=startedAt;if(!pack){installTrap({door:"package extraction",subject:`${key} has no pack; the tab would download and extract ${tarballUrl}`,detail:{key,tarball:tarballUrl,...integrity?{integrity}:{}}})}const digest=pack.artifact.digest;const store=livePackStore(shared);let fetched=false;if(!await store.hasTree(digest)){making.set(key,"receiving");const bytes2=await imageFile(pack.url);const actual=`sha256:${[...new Uint8Array(await crypto.subtle.digest("SHA-256",bytes2))].map(byte=>byte.toString(16).padStart(2,"0")).join("")}`;if(actual!==digest||bytes2.byteLength!==pack.artifact.bytes){installTrap({door:"image pack",subject:`${key}'s pack at ${pack.url} is not the artifact the plan names (${bytes2.byteLength} bytes, ${actual}; the plan names ${pack.artifact.bytes} bytes, ${digest})`,detail:{key}})}installAccount.downloadBytes+=bytes2.byteLength;installAccount.downloadMs+=performance.now()-startedAt;making.set(key,"storing");const stagedAt=performance.now();await store.stageArtifact(digest,bytes2,pack.artifact);installAccount.extractMs+=performance.now()-stagedAt;fetched=true}return{home:browserPackExpandedPath(digest),fetched}};const link2=(vfs2,home,path3,fromStore)=>{if(fromStore)installAccount.linkedFromStore+=1;const linkStartedAt=performance.now();const announcedBefore=vfs2.linkTiming.announceMs;vfs2.linkShared(home,path3);installAccount.linkMs+=performance.now()-linkStartedAt;installAccount.announceMs+=vfs2.linkTiming.announceMs-announcedBefore;installAccount.packages+=1;installAccount.lastAt=performance.now()};const hook=async(name,pkg,pkgPath,vfs2)=>{if(!(vfs2 instanceof PackedVirtualFS))return false;const ensured=await ensure(`${name}@${pkg.version}`,pkg.tarballUrl);if(!ensured)return false;link2(vfs2,ensured.home,pkgPath,!ensured.fetched);return true};Reflect.set(globalThis,Symbol.for("@volter/browser-runtime/package-install"),hook);linkPlan=async(root2,plan,progress)=>{const vfs2=requiredContainer().vfs;if(!(vfs2 instanceof PackedVirtualFS))throw new Error("The image's dependency plan needs the worker's store.");const at3=path3=>`${root2==="/"?"":root2}/${path3}`;const phases={};let phaseAt=performance.now();const phase=name=>{const now=performance.now();phases[name]=Math.round(now-phaseAt);phaseAt=now};const total=plan.links.length;let linked=0;let fetched=0;let fromStore=0;let lastReported=performance.now();const checkedAt=performance.now();installAccount.firstAt??=checkedAt;const prelinked=plan.key!==void 0&&preparedProjectPlans.get(root2)===plan.key;if(prelinked)preparedProjectPlans.delete(root2);const held=prelinked?new Set:await livePackStore(shared).presentTrees(plan.packages.flatMap(entry=>entry.pack?[entry.pack.artifact.digest]:[]));installAccount.lockWaitMs+=performance.now()-checkedAt;const homes=new Map;const homeOf=index2=>{let pending=homes.get(index2);if(!pending){const entry=plan.packages[index2];const digest=entry.pack?.artifact.digest;if(digest!==void 0&&held.has(digest)){fromStore+=1;pending=Promise.resolve({home:browserPackExpandedPath(digest),fetched:false});homes.set(index2,pending);return pending}pending=ensure(`${entry.name}@${entry.version}`,entry.tarball,entry.integrity,entry.pack).then(ensured=>{if(!ensured)throw new Error(`${entry.name}@${entry.version}: this thread cannot fetch packages into the store.`);if(ensured.fetched)fetched+=1;else fromStore+=1;return ensured});homes.set(index2,pending)}return pending};const links=[...plan.links].sort((left,right)=>depth3(left.path)-depth3(right.path)||left.path.localeCompare(right.path));const platformFits=new Map;const fitsPlatform=(index2,home)=>{let fits=platformFits.get(index2);if(fits!==void 0)return fits;if(plan.packages[index2]?.placed){platformFits.set(index2,true);return true}const prepared=plan.packages[index2]?.linuxX64;if(prepared!==void 0){platformFits.set(index2,prepared);return prepared}fits=true;try{const store=packagesFilesystem&&packagesFilesystem.existsSync(`${home}/package.json`)?packagesFilesystem:vfs2;const manifest=JSON.parse(store.readFileSync(`${home}/package.json`,"utf8"));const allows=(field,value)=>{if(!Array.isArray(field)||field.length===0)return true;const names2=field.filter(item=>typeof item==="string");const denied=names2.filter(name=>name.startsWith("!")).map(name=>name.slice(1));const allowed=names2.filter(name=>!name.startsWith("!"));if(denied.includes(value))return false;return allowed.length===0||allowed.includes(value)};fits=allows(manifest.os,"linux")&&allows(manifest.cpu,"x64")}catch{}platformFits.set(index2,fits);return fits};const place=async entry=>{const{home,fetched:wasFetched}=await homeOf(entry.package);if(!fitsPlatform(entry.package,home)){const stale=at3(entry.path);try{if(vfs2.existsSync(stale))removeTree2(vfs2,stale)}catch{}}else{link2(vfs2,home,at3(entry.path),!wasFetched)}linked+=1;if(performance.now()-lastReported>500){lastReported=performance.now();progress(linked,total)}};const nested=path3=>{const at4=path3.lastIndexOf("node_modules/");const rest=(at4<0?path3:path3.slice(at4+"node_modules/".length)).split("/").filter(Boolean);const nameLength=rest[0]?.startsWith("@")?2:1;return rest.length>nameLength};const first=links.filter(entry=>!nested(entry.path));const later=links.filter(entry=>nested(entry.path));const concurrency=16;let next2=0;let stopped2=false;let linkedAtLastLook=-1;const watch2=setInterval(()=>{if(linked!==linkedAtLastLook){linkedAtLastLook=linked;return}progress(linked,total,[...making].map(([key,stage])=>`${key} ${stage}`))},STALL_REPORT_MS);try{const placed=await Promise.allSettled(Array.from({length:prelinked?0:Math.min(concurrency,first.length)},async()=>{while(!stopped2){const index2=next2++;if(index2>=first.length)return;try{await place(first[index2])}catch(cause){stopped2=true;throw cause}}}));const failures=placed.filter(result=>result.status==="rejected").map(result=>result.reason);if(failures.length===1)throw failures[0];if(failures.length>1)throw new AggregateError(failures,"Package placement failed.");if(prelinked){linked=total;fromStore=new Set(plan.links.filter(entry=>plan.packages[entry.package]?.placed||plan.packages[entry.package]?.linuxX64!==false).map(entry=>entry.package)).size}else for(const entry of later)await place(entry)}finally{clearInterval(watch2)}phase(prelinked?"prelinkedMs":"linksMs");for(const bin of plan.bins){const path3=at3(bin.path);const directory2=path3.slice(0,path3.lastIndexOf("/"));if(!vfs2.existsSync(directory2))vfs2.mkdirSync(directory2,{recursive:true});vfs2.writeFileSync(path3,`node "${at3(bin.target)}" "$@"
6426
- `)}for(const entry of plan.entries??[]){const path3=at3(entry.path);const directory2=path3.slice(0,path3.lastIndexOf("/"));if(!vfs2.existsSync(directory2))vfs2.mkdirSync(directory2,{recursive:true});vfs2.writeFileSync(path3,entry.content)}phase("binsMs");if(plan.aliases.length>0)configurePlanAliases(vfs2,root2,plan.aliases);const workspace=discoverPnpmWorkspace(vfs2,root2);if(workspace)configureWorkspaceLinks(vfs2,workspace);phase("aliasesMs");console.log(`[boot-trace] ${JSON.stringify({event:"link-plan",at:Date.now(),root:root2,links:total,bins:plan.bins.length,entries:plan.entries?.length??0,aliases:plan.aliases.length,...phases})}`);progress(linked,total);return{linked,fetched,fromStore}}}function removeTree2(vfs2,path3){const stats=vfs2.lstatSync(path3);if(stats.isDirectory()&&!stats.isSymbolicLink()){for(const name of vfs2.readdirSync(path3))removeTree2(vfs2,`${path3}/${name}`);vfs2.rmdirSync(path3)}else{vfs2.unlinkSync(path3)}}var STALL_REPORT_MS=15e3;var linkPlan;var preparedProjectPlans=new Map;async function linkImageProgram(source,target){if(!packages)throw new Error("The origin's package store is not open.");const shared=packages;const vfs2=requiredContainer().vfs;if(!(vfs2 instanceof PackedVirtualFS))throw new Error("A program is linked into the worker's packed filesystem.");if(!source.startsWith("/packages/.programs/"))throw new Error(`${source} is not a program's tree in the shared store.`);return scope3.navigator.locks.request(PACKAGES_LOCK,{mode:"shared"},async()=>{await shared.refresh();if(!shared.entries.has(`${source}/${PROGRAM_ARCHIVE_RECEIPT}`))return{linked:false,files:0};vfs2.linkShared(source,target);return{linked:true,files:shared.descendants(source).length}})}var imagePacks=new Set;var imagePacksKnown;var settleImagePacksKnown;var fetchingPacks=new Map;var PREPARED_BODY_LINK_BATCH=512;function readImagePacks(keys){imagePacks.clear();for(const key of keys)if(typeof key==="string")imagePacks.add(key);return imagePacks.size}async function linkPreparedBodies(keys){const vfs2=container?.vfs;if(!packages||!packagesFilesystem||!(vfs2 instanceof PackedVirtualFS))return;const shared=packages;const sharedFilesystem=packagesFilesystem;if(!vfs2.existsSync(PREPARED_MODULES_DIR))vfs2.mkdirSync(PREPARED_MODULES_DIR,{recursive:true});const present=new Set(vfs2.readdirSync(PREPARED_MODULES_DIR).map(String));const missing=keys.filter(key=>!present.has(key));if(missing.length===0)return;const startedAt=performance.now();let linked=0;let fetched=0;const held=missing.filter(key=>shared.entries.has(`${PACKAGES_ROOT}/.prepared/${key}`));const absent=missing.filter(key=>!shared.entries.has(`${PACKAGES_ROOT}/.prepared/${key}`));for(let offset2=0;offset2<held.length;offset2+=PREPARED_BODY_LINK_BATCH){const batch=held.slice(offset2,offset2+PREPARED_BODY_LINK_BATCH);vfs2.linkSharedBatch(batch.map(key=>({source:`${PACKAGES_ROOT}/.prepared/${key}`,path:`${PREPARED_MODULES_DIR}/${key}`})));linked+=batch.length}let next2=0;await Promise.all(Array.from({length:Math.min(8,absent.length)},async()=>{while(next2<absent.length){const key=absent[next2++];const source=`${PACKAGES_ROOT}/.prepared/${key}`;try{if(!shared.entries.has(source)){const body=await imagePack(key);await scope3.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive"},async()=>{await shared.refresh();if(!shared.entries.has(source))sharedFilesystem.writeFileSync(source,body);if(shared.logBytes>8*1024*1024)await shared.checkpoint()});fetched+=1}vfs2.linkShared(source,`${PREPARED_MODULES_DIR}/${key}`);linked+=1}catch(cause){console.warn(`[modules] the image's prepared body ${key} could not be linked (${cause instanceof Error?cause.message:String(cause)}); the engine prepares that module itself.`)}}}));console.log(`[modules] ${linked} of ${missing.length} prepared bodies linked from the origin's store in ${Math.round(performance.now()-startedAt)} ms (${fetched} fetched from the image)`)}async function applyImageLayers(url2,digest,progress,compact){if(!packages)throw new Error("The origin's package store is not open.");const shared=packages;const applied=imageLayersAppliedPath(digest);const deferred=imageLayersDeferredPath(digest);await scope3.navigator.locks.request(PACKAGES_LOCK,{mode:"shared"},()=>shared.refresh());if(shared.entries.has(applied)||shared.entries.has(deferred)||shared.deferredImage===digest)return{parts:0,units:0,bytes:0,skipped:true};if(compact&&shared.packBytes===0&&new URL(url2).origin===scope3.location.origin){const text2=await imageFile(compact.url);const named2=Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",text2)),byte=>byte.toString(16).padStart(2,"0")).join("");if(named2!==compact.digest)throw new Error("The prepared image descriptor is not the one its manifest names.");const descriptor=JSON.parse(new TextDecoder().decode(text2));if(descriptor.kind!=="browser-substrate-prepared-layers"||descriptor.version!==1||!Number.isSafeInteger(descriptor.units)||descriptor.units<0){throw new Error("Malformed prepared image descriptor.")}const prepared=validatePreparedImageIndex(descriptor.prepared);progress(0,2);const metadata=async file2=>{const answer2=await imageFileAnswer(new URL(file2.url,url2).href,file2);if(answer2.inflated)return answer2.bytes;if(answer2.bytes.byteLength!==file2.bytes)throw new Error("The image's metadata has the wrong served size.");return inflateLayerPart(answer2.bytes,file2.raw)};const[json,binary]=await Promise.all([metadata(prepared.json),metadata(prepared.binary)]);const ranges={...prepared.ranges,image:digest};const installed3=await scope3.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive"},async()=>{await shared.refresh();if(shared.entries.has(deferred))return true;if(!await shared.installPreparedImage(prepared,json,binary,ranges))return false;shared.applyNow([{operation:"write",path:deferred,content:new Uint8Array(0),mode:292}],{durable:true});return true});if(installed3){progress(2,2);return{parts:0,units:descriptor.units,bytes:prepared.json.bytes+prepared.binary.bytes,skipped:false}}}const text=await imageFile(url2);const named=[...new Uint8Array(await crypto.subtle.digest("SHA-256",text))].map(byte=>byte.toString(16).padStart(2,"0")).join("");if(!named.startsWith(digest))throw new Error(`The image's layers document at ${url2} is not the one its manifest names.`);const document2=validateImageLayers(JSON.parse(new TextDecoder().decode(text)));const needed=document2.parts.filter(part=>part.units.some(unit=>!shared.entries.has(unit.marker)));let parts=0,units=0,bytes2=0,next2=0;let failed=false;const placedAt=Date.now();progress(0,needed.length);await shared.deferMaintenance(async()=>{const results=await Promise.allSettled(Array.from({length:Math.min(LAYER_PARTS_AT_ONCE,needed.length)},async()=>{while(next2<needed.length&&!failed){const part=needed[next2++];try{const answer2=await imageFileAnswer(new URL(part.url,url2).href,{bytes:part.bytes,raw:part.raw,sha256:part.sha256});let raw=answer2.bytes;if(!answer2.inflated){if(raw.byteLength!==part.bytes)throw new Error(`The image's layer part ${part.url} is ${raw.byteLength} bytes; its document says ${part.bytes}.`);raw=await inflateLayerPart(raw,part.raw);const actual=[...new Uint8Array(await crypto.subtle.digest("SHA-256",raw))].map(byte=>byte.toString(16).padStart(2,"0")).join("");if(actual!==part.sha256)throw new Error(`The image's layer part ${part.url} is not the part its document names.`)}else if(raw.byteLength!==part.raw)throw new Error(`The image's layer part ${part.url} came inflated to ${raw.byteLength} bytes; its document says ${part.raw}.`);await scope3.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive"},async()=>{await shared.refresh();const files=[];const slices=[];let size=0;for(const unit of part.units){if(shared.entries.has(unit.marker))continue;let start=Infinity,end=0;for(const[,type2,,offset2,length]of unit.files)if(type2!=="d"){start=Math.min(start,offset2);end=Math.max(end,offset2+length)}if(start===Infinity)start=end=0;const base=size-start;let marked=false;for(const[relative3,type2,mode,offset2,length]of unit.files){const path3=imageLayerPath(unit,relative3);if(path3===unit.marker)marked=true;files.push(type2==="d"?{path:path3,type:"directory",mode,mtimeMs:placedAt}:{path:path3,type:type2==="l"?"symlink":"file",mode,mtimeMs:placedAt,offset:base+offset2,length})}if(!marked)files.push({path:unit.marker,type:"file",mode:292,mtimeMs:placedAt,offset:0,length:0});slices.push(raw.subarray(start,end));size+=end-start;units+=1}if(files.length===0)return;const bytes3=slices.length===1?slices[0]:new Uint8Array(size);if(slices.length>1){let cursor=0;for(const slice of slices){bytes3.set(slice,cursor);cursor+=slice.byteLength}}shared.applyExtentsNow(bytes3,files)});parts+=1;bytes2+=part.bytes;progress(parts,needed.length)}catch(cause){failed=true;throw cause}}}));const rejected=results.find(result=>result.status==="rejected");if(rejected)throw rejected.reason;await scope3.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive"},async()=>{await shared.refresh();if(!shared.entries.has(applied))shared.applyNow([{operation:"write",path:applied,content:new Uint8Array(0),mode:292}]);if(shared.logBytes>0)await shared.checkpoint()})});return{parts,units,bytes:bytes2,skipped:false}}var LAYER_PARTS_AT_ONCE=6;async function inflateLayerPart(served,raw){const reader=new Blob([served]).stream().pipeThrough(new DecompressionStream("gzip")).getReader();const out=new Uint8Array(raw);let offset2=0;for(;;){const{done,value}=await reader.read();if(done)break;if(offset2+value.byteLength>raw)throw new Error("An image layer part inflates past its raw size.");out.set(value,offset2);offset2+=value.byteLength}if(offset2!==raw)throw new Error("An image layer part inflates short of its raw size.");return out}var nextImagePackRead=1;var pendingImagePacks=new Map;var pendingImageFiles=new Map;var nextImageFileRead=1;async function imageFile(url2){return(await imageFileAnswer(url2)).bytes}function imageFileAnswer(url2,part){const id2=nextImageFileRead++;return new Promise((resolve2,reject)=>{pendingImageFiles.set(id2,{resolve:resolve2,reject});send({type:"image-file-read",id:id2,url:url2,...part?{part}:{}})})}function imagePack(key){const id2=nextImagePackRead++;return new Promise((resolve2,reject)=>{pendingImagePacks.set(id2,{resolve:resolve2,reject});send({type:"image-pack-read",id:id2,key})})}function moduleCacheOver(shared,sharedFilesystem,project){const home=key=>`${PACKAGES_ROOT}/.modules/${key}`;const keepShared=async(source,code3)=>{await scope3.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive"},async()=>{await shared.refresh();if(!shared.entries.has(source))sharedFilesystem.writeFileSync(source,code3);else{const now=new Date;sharedFilesystem.utimesSync(source,now,now)}if(shared.logBytes>8*1024*1024){console.warn(`[modules] the shared store checkpoints at ${Math.round(shared.logBytes/1024)} KiB of log, after ${source}`);await shared.checkpoint()}})};const fromImage=(key,source)=>{let pending=fetchingPacks.get(key);if(pending)return pending;pending=(async()=>{try{await keepShared(source,await imagePack(key));return true}catch(cause){if(isInstallRefused(cause))throw cause;const message=cause instanceof Error?cause.message:String(cause);if(/\b4\d\d\b|not found|no pack/iu.test(message))installTrap({door:"image pack",subject:`the image names a pack for ${key} its origin cannot give: ${message}`,detail:{key}});throw new Error(`The image's pack for ${key} could not be read this time (${message}); reloading the page tries again.`)}finally{fetchingPacks.delete(key)}})();fetchingPacks.set(key,pending);return pending};const reportedMisses=new Set;const reportMiss=(key,carried)=>{if(reportedMisses.has(key))return;reportedMisses.add(key);console.log(carried?`[modules] this tab's store has no pack at ${key}; fetching the one the image's index names.`:`[modules] neither this tab's store nor the image has a pack at ${key}; the tab builds it.`)};return{link:async(key,target)=>{const source=home(key);let fetched=false;if(!shared.entries.has(source)&&imagePacksKnown)await imagePacksKnown;if(!shared.entries.has(source)){reportMiss(key,imagePacks.has(key));if(!imagePacks.has(key))return false;if(!await fromImage(key,source))return false;fetched=true}project.linkShared(source,target);if(!project.existsSync(target)){console.warn(`[modules] linked ${key} to ${target} and it is not there: fetched ${fetched}, shared holds ${shared.entries.has(source)}, the project's parent ${project.existsSync(target.slice(0,target.lastIndexOf("/")))}`)}return true},keep:async(key,code3,target)=>{const source=home(key);await keepShared(source,code3);project.linkShared(source,target)}}}function requiredContainer(){if(!container)throw new Error("Browser Node host is not initialized.");return container}function installFilesystemForwarding(vfs2){const suppressed=path3=>{if(!suppressFilesystemEvents)return false;if(importingFilesystemRoot===void 0)return true;const normalized=normalizeStorePath2(path3);return normalized===importingFilesystemRoot||normalized.startsWith(`${importingFilesystemRoot==="/"?"":importingFilesystemRoot}/`)};vfs2.on("change",path3=>{if(suppressed(path3)||!vfs2.existsSync(path3))return;const stat2=vfs2.statSync(path3);queueIndexForwarding([path3,stat2.isDirectory()?"directory":"file",stat2.isDirectory()?0:stat2.size,stat2.mode&4095,stat2.mtimeMs])});vfs2.on("delete",path3=>{if(!suppressed(path3))queueIndexForwarding([path3,null])});installPortForwarding()}function installPortForwarding(){const bridge=vfsServerBridge();const register=bridge.registerServer.bind(bridge);const unregister=bridge.unregisterServer.bind(bridge);bridge.registerServer=((server,serverPort,hostname2)=>{console.log(`[boot-trace] ${JSON.stringify({event:"port-register",at:Date.now(),port:serverPort,token:container?.currentProcessToken()})}`);register(server,serverPort,hostname2);if(netListeners.has(serverPort))return;send({type:"port",action:"open",port:serverPort,...hostname2?{hostname:hostname2}:{}})});bridge.unregisterServer=(serverPort=>{console.log(`[boot-trace] ${JSON.stringify({event:"port-unregister",at:Date.now(),port:serverPort,token:container?.currentProcessToken()})}`);unregister(serverPort);if(netListeners.has(serverPort))return;send({type:"port",action:"close",port:serverPort})})}var pendingIndexForwarding=[];function queueIndexForwarding(change){pendingIndexForwarding.push(change);if(filesystemForwardingScheduled)return;filesystemForwardingScheduled=true;queueMicrotask(flushFilesystemForwarding)}function storeEntryOf(vfs2,path3){if(!vfs2.existsSync(path3))return[path3,null];const stat2=vfs2.lstatSync(path3);const type2=stat2.isDirectory()?"directory":stat2.isSymbolicLink()?"symlink":"file";return[path3,type2,type2==="file"?stat2.size:0,stat2.mode&4095,stat2.mtimeMs]}function applyStoreOperation(vfs2,operation){const withModes=vfs2;if(operation.op==="write"){writeFile(vfs2,operation.path,new Uint8Array(operation.bytes));if(operation.mode!==void 0)withModes.chmodSync?.(operation.path,operation.mode);withModes.utimesSync?.(operation.path,new Date(operation.mtimeMs),new Date(operation.mtimeMs))}else if(operation.op==="mkdir"){if(!vfs2.existsSync(operation.path))vfs2.mkdirSync(operation.path,{recursive:true})}else if(operation.op==="remove"){removePath(vfs2,operation.path)}else if(operation.op==="rename"){vfs2.renameSync(operation.from,operation.to)}else if(operation.op==="chmod"){withModes.chmodSync?.(operation.path,operation.mode)}else if(operation.op==="utimes"){withModes.utimesSync?.(operation.path,new Date(operation.mtimeMs),new Date(operation.mtimeMs))}}function flushFilesystemForwarding(){filesystemForwardingScheduled=false;const changes=pendingIndexForwarding.splice(0);for(let offset2=0;offset2<changes.length;offset2+=4096){send({type:"fs-index",changes:changes.slice(offset2,offset2+4096)})}}function vfsServerBridge(){return requiredContainer().serverBridge}var netListeners=new Map;var netSockets=new Map;var netListenerChanges=new Set;var nextNetSocket=1;var pageNetHost={ports:()=>netListeners.keys(),subscribe:listener=>{netListenerChanges.add(listener);return()=>{netListenerChanges.delete(listener)}},connect:(port2,socket)=>{if(!netListeners.has(port2)){socket.destroy();return}forwardNetSocket(port2,socket)}};function forwardNetSocket(port2,socket){const id2=nextNetSocket++;netSockets.set(id2,socket);socket.on("data",chunk=>{if(!netSockets.has(id2))return;const buffer2=Uint8Array.from(chunk).buffer;send({type:"net-guest-data",socket:id2,chunk:buffer2},[buffer2])});const close2=()=>{if(!netSockets.delete(id2))return;send({type:"net-guest-end",socket:id2})};socket.on("end",close2);socket.on("close",close2);socket.on("error",()=>void 0);send({type:"net-connect",port:port2,socket:id2})}function handleNetMessage(message){if(message.type==="listen-net"){const host2=requiredContainer();if(!host2.listenNet)return;netListeners.get(message.port)?.();netListeners.set(message.port,()=>{});try{const unlisten=host2.listenNet(message.port,socket2=>forwardNetSocket(message.port,socket2));netListeners.set(message.port,unlisten)}catch(error){netListeners.delete(message.port);throw error}for(const listener of netListenerChanges)listener(message.port,true);return}if(message.type==="unlisten-net"){netListeners.get(message.port)?.();netListeners.delete(message.port);for(const listener of netListenerChanges)listener(message.port,false);return}const socket=netSockets.get(message.socket);if(!socket)return;if(message.type==="net-data")socket.write(new Uint8Array(message.chunk),()=>send({type:"net-taken",socket:message.socket}));else{socket.end();netSockets.delete(message.socket)}}var pendingChildren=new Map;var pendingChildInput=new Map;var pendingChildFdInput=new Map;var childFdKey=(id2,fd2)=>`${id2}:${fd2}`;var childChunkBytes=64*1024;function validChildFd(fd2){return typeof fd2==="number"&&Number.isInteger(fd2)&&fd2>=3&&fd2<=63}function childDescriptorNumbers(descriptors){if(descriptors===void 0)return void 0;const fds=Object.keys(descriptors).map(Number);if(!fds.every(validChildFd))throw new Error("Child process descriptors must be integers from 3 through 63.");return fds.length>0?fds.sort((left,right)=>left-right):void 0}var nextChildId=1;var launchPorts=new Map;var heldRuns=new Set;function runPorts(id2){const before=launchPorts.get(id2);if(!before)return[];return vfsServerBridge().getServerPorts().filter(port2=>!before.has(port2))}function closeRunServers(id2){const bridge=vfsServerBridge();for(const port2 of runPorts(id2)){const entry=bridge.servers?.get(port2);try{entry?.server?.close?.()}catch{}try{bridge.unregisterServer(port2)}catch{}}}async function workSettled(id2,held=false){const token=String(id2);const engine=container;const nativeSetTimeout=globalThis.__browserRuntimeNativeSetTimeout??setTimeout;const tick=()=>new Promise(resolve2=>nativeSetTimeout.call(globalThis,resolve2,50));const ports2=()=>Math.max(engine?.processPorts?.(token).length??0,runPorts(id2).length);if(held&&activeRuns.has(id2)){const deadline=Date.now()+500;while(Date.now()<deadline&&ports2()===0&&activeRuns.has(id2))await tick()}const owned=()=>{const timers=engine?.pendingTimers?.(token)??0;if(timers>0)return true;if(held&&ports2()>0)return true;return[...pendingChildren.values()].some(child=>child.owner===id2&&child.hold?.value!==false)};while(owned()&&activeRuns.has(id2))await tick()}function spawnedArgv(options){const given=options.__browserRuntimeSpawnArgs;if(!Array.isArray(given)||given.length===0)return void 0;return given.every(word=>typeof word==="string")?[...given]:void 0}function requestChild(command,options,fixedOwner,fixedArgv,nodeProcess){return new Promise((resolve2,reject)=>{assertWorkerActive();options.signal?.throwIfAborted();const descriptorFds=childDescriptorNumbers(options.descriptors);if(!childInputSupported&&(options.stdin!==void 0||options.stdinStream||options.terminal||options.executablePath!==void 0||descriptorFds)){throw new Error("The holder did not negotiate child-process input and terminal support.")}const id2=nextChildId++;const inputController=new AbortController;let removeResize;let inputFailure;const token=container?.currentProcessToken()??null;let owner=fixedOwner??(token===null?null:Number(token));if(owner!==null&&!activeRuns.has(owner)){const engine=enginePids();owner=(engine?owningRun(token,activeRuns,engine.runPid,engine.processByPid):void 0)??null}if(owner===null){let latest;for(const[id3,run]of activeRuns)if(!latest||run.startedAt>latest.startedAt)latest={id:id3,startedAt:run.startedAt};owner=latest?.id??null}const rejectFdInputs=cause=>{for(const fd2 of descriptorFds??[]){const key=childFdKey(id2,fd2);const input=pendingChildFdInput.get(key);pendingChildFdInput.delete(key);input?.reject(cause)}};const abort=()=>{inputController.abort(options.signal?.reason);const input=pendingChildInput.get(id2);pendingChildInput.delete(id2);input?.reject(inputController.signal.reason);rejectFdInputs(inputController.signal.reason);if(!pendingChildren.has(id2))return;try{send({type:"child-abort",id:id2})}catch(cause){const pending=pendingChildren.get(id2);pendingChildren.delete(id2);pending?.reject(cause instanceof Error?cause:new Error(String(cause)))}};const cleanup=()=>{options.signal?.removeEventListener("abort",abort);inputController.abort();const input=pendingChildInput.get(id2);pendingChildInput.delete(id2);input?.reject(new DOMException("The child process stopped.","AbortError"));rejectFdInputs(new DOMException("The child process stopped.","AbortError"));try{removeResize?.()}catch(cause){console.error("Child terminal subscription cleanup failed.",cause)}removeResize=void 0};console.log(`[boot-trace] ${JSON.stringify({event:"child-start",at:Date.now(),id:id2,owner,token,program:programFromCommand(command),imageBlocked:imageBlocked()})}`);pendingChildren.set(id2,{owner,...options.hold?{hold:options.hold}:{},...options.onStdout?{onStdout:options.onStdout}:{},...options.onStderr?{onStderr:options.onStderr}:{},...descriptorFds&&options.descriptors?{descriptors:options.descriptors}:{},resolve:result=>{cleanup();if(inputFailure)reject(inputFailure);else resolve2(result)},reject:cause=>{cleanup();reject(inputFailure??cause)}});options.signal?.addEventListener("abort",abort,{once:true});const parentCwd=owner!==null?activeRuns.get(owner)?.cwd??"/":"/";const cwd=options.cwd===void 0?parentCwd:options.cwd.startsWith("/")?options.cwd:`${parentCwd.replace(/\/$/u,"")}/${options.cwd}`.replace(/\/\.\//gu,"/");const argv=fixedArgv?[...fixedArgv]:spawnedArgv(options);try{send({type:"child-run",...options.filesystemPolicy?{filesystemPolicy:options.filesystemPolicy}:{},id:id2,owner,command,...argv?{argv}:{},...nodeProcess?{nodeProcess}:{},cwd,...options.executablePath!==void 0?{executablePath:options.executablePath}:{},...options.stdin!==void 0?{stdin:options.stdin}:{},...options.stdinStream?{liveStdin:true}:{},...options.terminal?{terminal:{columns:options.terminal.columns,rows:options.terminal.rows}}:{},...options.env?{env:{...options.env}}:{},...descriptorFds?{descriptors:descriptorFds}:{}});if(options.stdinStream){void forwardBrowserProcessInput(options.stdinStream,async chunk=>{for(let offset2=0;offset2<chunk.byteLength;offset2+=64*1024){inputController.signal.throwIfAborted();const bytes2=Uint8Array.from(chunk.subarray(offset2,offset2+64*1024)).buffer;await new Promise((resolve3,reject2)=>{pendingChildInput.set(id2,{resolve:resolve3,reject:reject2});try{send({type:"child-stdin",id:id2,bytes:bytes2},[bytes2])}catch(cause){pendingChildInput.delete(id2);reject2(cause)}})}},inputController.signal).then(()=>{if(pendingChildren.has(id2)&&!inputController.signal.aborted)send({type:"child-stdin-end",id:id2})}).catch(cause=>{if(inputController.signal.aborted||!pendingChildren.has(id2))return;inputFailure=cause instanceof Error?cause:new Error(String(cause));abort()})}for(const fd2 of descriptorFds??[]){const key=childFdKey(id2,fd2);void forwardBrowserProcessInput(options.descriptors[fd2].input,async chunk=>{for(let offset2=0;offset2<chunk.byteLength;offset2+=childChunkBytes){inputController.signal.throwIfAborted();const bytes2=Uint8Array.from(chunk.subarray(offset2,offset2+childChunkBytes)).buffer;await new Promise((resolve3,reject2)=>{pendingChildFdInput.set(key,{resolve:resolve3,reject:reject2});try{send({type:"child-fd",id:id2,fd:fd2,bytes:bytes2},[bytes2])}catch(cause){pendingChildFdInput.delete(key);reject2(cause)}})}},inputController.signal).then(()=>{if(pendingChildren.has(id2)&&!inputController.signal.aborted)send({type:"child-fd-end",id:id2,fd:fd2})}).catch(cause=>{if(inputController.signal.aborted||!pendingChildren.has(id2))return;inputFailure=cause instanceof Error?cause:new Error(String(cause));abort()})}removeResize=options.terminal?.onResize?.((columns,rows)=>{if(pendingChildren.has(id2)&&!inputController.signal.aborted)send({type:"child-resize",id:id2,columns,rows})})}catch(cause){try{send({type:"child-abort",id:id2})}catch{}const pending=pendingChildren.get(id2);pendingChildren.delete(id2);pending?.reject(cause instanceof Error?cause:new Error(String(cause)))}})}function installChildProcessBridge(){const pending=token=>{const owner=Number(token);let count=0;for(const child of pendingChildren.values())if(child.owner===owner&&child.hold?.value!==false)count+=1;return count};Reflect.set(globalThis,executorSymbol,{bypass:0,run:requestChild,pending})}function installRootNodeEntryBridge(){const preparedLimits=Object.freeze({maxBytes:4*1024*1024,maxEntries:1024});const streamLimits=Object.freeze({maxHandles:1024,maxReadChunkBytes:64*1024,maxQueuedBytes:64*1024,maxQueuedHandles:16,maxPendingWriteBytes:1024*1024});const runtimeFiles=new VirtualFS;rootRuntimeFiles=runtimeFiles;const registry=ownerProcessRegistryScope();installNodeProcessHost({run:launch=>{const active2=requiredContainer();if(launch.inherited.length)throw new Error("A store-owner Node launch cannot inherit guest stream descriptors.");if(!executionConfiguration)throw new Error("Node process execution has no worker configuration.");const engine=enginePids();const owner=activeRuns.has(Number(launch.token))?Number(launch.token):engine?owningRun(launch.token,activeRuns,engine.runPid,engine.processByPid):void 0;if(owner===void 0)throw new Error("Node process execution has no owning command.");const attribution=networkProgramNow(activeRuns,launch.token,token=>engine?.runPid(token),pid=>engine?.processByPid(pid));const streams2=launch.streams;return nodeProcesses.run(renderCommand(["node",...launch.argv]),{cwd:launch.cwd,env:launch.env,...launch.stdin!==void 0?{stdin:launch.stdin}:{},...launch.stdinStream?{stdinStream:launch.stdinStream}:{},...streams2?.signal?{signal:streams2.signal}:{},...streams2?.terminal?{terminal:streams2.terminal}:{},...streams2?.onStdout?{onStdout:streams2.onStdout}:{},...streams2?.onStderr?{onStderr:streams2.onStderr}:{}},{filesystem:launch.filesystem,...storeReadsFor(launch.filesystem),workerUrl:scope3.location.href,configuration:executionConfiguration,...moduleCacheOption(active2.vfs),processAdmission:{source:registry,token:launch.token},nativeStreams:{limits:streamLimits,inherited:[]},nodeProcess:{preparedLimits},preparedFiles:captureNodePreparedFiles(runtimeFiles,preparedLimits),serverBridge:active2.serverBridge,net:pageNetHost,hostPorts:hostPortsHost,runChild:(command,options,argv)=>requestChild(command,options,owner,argv),http:request=>brokerHttpOnce(request,attribution)})}})}function installNodeEntryBridge(localToken2,preparedLimits){installNodeProcessHost({run:launch=>{const argv=["node",...launch.argv];const streams2=launch.streams;return requestChild(renderCommand(argv),{cwd:launch.cwd,env:launch.env,hold:{value:false},...launch.stdin!==void 0?{stdin:launch.stdin}:{},...launch.stdinStream?{stdinStream:launch.stdinStream}:{},...streams2?.signal?{signal:streams2.signal}:{},...streams2?.terminal?{terminal:streams2.terminal}:{},...streams2?.onStdout?{onStdout:streams2.onStdout}:{},...streams2?.onStderr?{onStderr:streams2.onStderr}:{},...invocationPolicy?{filesystemPolicy:invocationPolicy}:{}},Number(localToken2),argv,{token:launch.token,inherited:launch.inherited.map(({fd:fd2,handle})=>({fd:fd2,id:handle.id})),preparedFiles:invocationFiles?captureNodePreparedFiles(invocationFiles.runtimeFiles,preparedLimits):[]})}},localToken2)}async function brokerHttpOnce(request,attribution,context2){assertWorkerActive();request.signal.throwIfAborted();const id2=nextFetchId++;const headers=request.headers;assertWorkerActive();request.signal.throwIfAborted();const result=new Promise((resolve2,reject)=>pendingFetches.set(id2,{method:request.method,resolve:resolve2,reject}));const abort=()=>{const pending=pendingFetches.get(id2);if(pending){pendingFetches.delete(id2);pending.reject(request.signal.reason??new DOMException("The request was cancelled.","AbortError"))}else{const stream=responseStreams.get(id2);if(!stream&&!fetchActivities.has(id2))return;responseStreams.delete(id2);stream?.error(request.signal.reason??new DOMException("The request was cancelled.","AbortError"))}try{send({type:"fetch-abort",id:id2})}catch{}fetchAbortCleanup.get(id2)?.();fetchAbortCleanup.delete(id2)};if(context2){try{const activity2=context2.begin(abort);fetchActivities.set(id2,{activity:activity2,headersDone:activity2.hold(),pulls:[],cancel:abort})}catch(cause){pendingFetches.delete(id2);throw cause}}request.signal.addEventListener("abort",abort,{once:true});fetchAbortCleanup.set(id2,()=>{request.signal.removeEventListener("abort",abort);fetchActivities.get(id2)?.activity.release();fetchActivities.delete(id2)});try{const body=request.body;send({type:"fetch",id:id2,program:attribution.program,attributed:attribution.attributed,activePrograms:attribution.activePrograms,...attribution.pid!==void 0?{pid:attribution.pid}:{},url:request.url,method:request.method,headers,...request.profile?{profile:request.profile}:{},...body?{body}:{}},body instanceof ReadableStream?[body]:[])}catch(cause){pendingFetches.get(id2)?.reject(cause instanceof Error?cause:new Error(String(cause)));pendingFetches.delete(id2);fetchAbortCleanup.get(id2)?.();fetchAbortCleanup.delete(id2)}if(request.signal.aborted)abort();return result}async function brokerFetch(input,init,fixedAttribution,context2){let request=new Request(input,init);const attribution=fixedAttribution??attributionNow();let body=request.body??void 0;if(body&&requestHasStaticBody(request)){let stopped2=false;const activity2=context2?.begin(()=>{stopped2=true});const done=activity2?.hold();try{body=await request.blob();request.signal.throwIfAborted();if(stopped2)throw new DOMException("The requesting process has ended.","AbortError")}finally{done?.();activity2?.release()}}for(let redirects=0;;redirects++){const result=await brokerHttpOnce({url:request.url,method:request.method,headers:[...request.headers.entries()],...body?{body}:{},signal:request.signal},attribution,context2);const response=new Response(result.body,{status:result.status,statusText:result.statusText,headers:result.headers});if(![301,302,303,307,308].includes(response.status))return response;if(request.redirect==="manual")return response;if(request.redirect==="error"){await response.body?.cancel().catch(()=>void 0);throw new TypeError("Redirects are disabled for this request.")}if(redirects>=20){await response.body?.cancel().catch(()=>void 0);throw new TypeError("Too many redirects.")}const location2=response.headers.get("location");if(!location2)return response;const nextUrl=new URL(location2,request.url);let method=request.method;const headers=new Headers(request.headers);if(response.status===303&&method!=="HEAD"||(response.status===301||response.status===302)&&method==="POST"){method="GET";body=void 0;for(const name of["content-encoding","content-language","content-length","content-location","content-type"])headers.delete(name)}else if(body instanceof ReadableStream){await response.body?.cancel().catch(()=>void 0);throw new TypeError("A streamed request body cannot be replayed across a redirect.")}if(new URL(request.url).origin!==nextUrl.origin){for(const name of["authorization","cookie","proxy-authorization"])headers.delete(name)}await response.body?.cancel().catch(()=>void 0);request=new Request(nextUrl,{method,headers,...body?{body}:{},redirect:request.redirect,signal:request.signal})}}var hostPorts=new Set;var hostPortListeners=new Set;var hostPortsHost={current:()=>hostPorts,subscribe:listener=>{hostPortListeners.add(listener);return()=>{hostPortListeners.delete(listener)}}};var RefusedWebSocket=class extends EventTarget{static CONNECTING=0;static OPEN=1;static CLOSING=2;static CLOSED=3;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;url;protocol="";extensions="";bufferedAmount=0;binaryType="blob";readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;constructor(url2,_protocols){super();this.url=new URL(url2).href;queueMicrotask(()=>{if(this.readyState===3)return;this.readyState=3;const error=Object.assign(new Event("error"),{message:`WebSocket to ${this.url} refused: a sandboxed program has no WebSocket egress.`});this.onerror?.(error);this.dispatchEvent(error);const close2=new CloseEvent("close",{code:1006,reason:"",wasClean:false});this.onclose?.(close2);this.dispatchEvent(close2)})}send(){throw new DOMException("The WebSocket is not open.","InvalidStateError")}close(){this.readyState=3}};function installNetworkBroker(){installFetchTransport((input,init,context2)=>brokerFetch(input,init,attributionNow(),context2));installHttpClientTransport(()=>{const attribution=attributionNow();return request=>brokerHttpOnce(request,attribution)},{hostPorts:()=>hostPorts});Object.defineProperty(globalThis,"fetch",{value:brokerFetch,configurable:false,writable:false});for(const name of["XMLHttpRequest","EventSource","BroadcastChannel","SharedWorker"]){try{Object.defineProperty(globalThis,name,{value:void 0,configurable:false,writable:false})}catch{}}try{Object.defineProperty(globalThis,"WebSocket",{value:RefusedWebSocket,configurable:false,writable:false})}catch{}Reflect.set(globalThis,executorSymbol,void 0)}var liveStdins=new Map;async function installTypeStripper(url2){const glue=await import(url2);globalThis.__substrateStripTypes=typeStripperFrom(glue.default).strip}var webSocketRelay;function openLiveStdin(id2){const encoder7=new TextEncoder;const queue=[];let closed=false;let wake;const notify=()=>{const resolve2=wake;wake=void 0;resolve2?.()};const stdin={push:data2=>{if(closed)return;queue.push({bytes:encoder7.encode(data2)});notify()},write:bytes2=>{if(closed)return Promise.reject(new Error("Process input is closed."));if(bytes2.byteLength>64*1024||queue.some(entry=>entry.consumed))return Promise.reject(new Error("Process input requires consumed chunks of at most 64 KiB."));const consumed=new Promise((resolve2,reject)=>{queue.push({bytes:Uint8Array.from(bytes2),consumed:{resolve:resolve2,reject}})});notify();return consumed},close:(discard=false)=>{closed=true;if(discard)for(const entry of queue.splice(0))entry.consumed?.reject(new DOMException("Process input was cancelled.","AbortError"));notify()},async*[Symbol.asyncIterator](){for(;;){if(queue.length>0){const entry=queue.shift();entry.consumed?.resolve();yield entry.bytes;continue}if(closed)return;await new Promise(resolve2=>{wake=resolve2})}}};liveStdins.set(id2,stdin);return stdin}var terminals=new Map;function openTerminal(id2,size){const listeners=new Set;const terminal={columns:size.columns,rows:size.rows,onResize:listener=>{listeners.add(listener);return()=>{listeners.delete(listener)}},resize:(columns,rows)=>{terminal.columns=columns;terminal.rows=rows;for(const listener of listeners)listener(columns,rows)}};terminals.set(id2,terminal);return terminal}function writeFile(vfs2,path3,bytes2){const parent=path3.slice(0,path3.lastIndexOf("/"))||"/";if(parent!=="/"&&!vfs2.existsSync(parent))vfs2.mkdirSync(parent,{recursive:true});vfs2.writeFileSync(path3,bytes2)}function removePath(vfs2,path3){if(!vfs2.existsSync(path3))return;if(vfs2.statSync(path3).isFile()){vfs2.unlinkSync(path3);return}for(const name of vfs2.readdirSync(path3))removePath(vfs2,`${path3==="/"?"":path3}/${name}`);if(path3!=="/")vfs2.rmdirSync(path3)}function sendResult(id2,result){console.log(`[boot-trace] ${JSON.stringify({event:"run-result",at:Date.now(),id:id2,exitCode:result.exitCode})}`);const signal=result.signal;send({type:"result",id:id2,stdout:result.stdout,stderr:result.stderr,exitCode:result.exitCode,...typeof signal==="string"?{signal}:{}})}function sendError(id2,cause){const error=cause instanceof Error?cause:new Error(String(cause));send({type:"error",id:id2,error:error.message,...error.stack?{stack:error.stack}:{}})}function send(message,transfer2=[]){port?.postMessage(message,transfer2)}async function fetchPrismaSchemaParser(vfs2,urls){try{const[glue,wasm2]=await Promise.all([fetch(new URL(urls.prismaSchemaModuleUrl,scope3.location.href).href).then(response=>{if(!response.ok)throw new Error(`${response.status}`);return response.text()}),fetch(new URL(urls.prismaSchemaWasmUrl,scope3.location.href).href).then(response=>{if(!response.ok)throw new Error(`${response.status}`);return response.arrayBuffer()})]);vfs2.mkdirSync(PRISMA_SCHEMA_DIRECTORY,{recursive:true});vfs2.writeFileSync(`${PRISMA_SCHEMA_DIRECTORY}/prisma_schema_build.js`,glue);vfs2.writeFileSync(`${PRISMA_SCHEMA_DIRECTORY}/prisma_schema_build_bg.wasm`,new Uint8Array(wasm2))}catch(cause){console.warn(`[stand-ins] Prisma's schema parser did not reach the runtime: ${cause instanceof Error?cause.message:String(cause)}`)}}function depth3(path3){let segments=1;for(let index2=0;index2<path3.length;index2+=1)if(path3.charCodeAt(index2)===47)segments+=1;return segments}configureNodeExecutionWorker({});
6425
+ ${error?.stack??"(no stack)"}`)});scope3.addEventListener("unhandledrejection",event=>{const reason=event.reason;console.error(`[node worker] unhandled rejection: ${reason?.stack??String(reason)}`)});var executorSymbol=Symbol.for("@volter/browser-runtime/child-process-executor");var port;var container;var packStore;var packStoreProjectId;async function openStoreReads(grant){const clock=new Int32Array(grant.clock);const before=Atomics.load(clock,STORE_CLOCK_EPOCH);let openedAt=before;const began=Date.now();const opening=openPackReader({navigator:scope3.navigator},grant.projectId,grant.seed,grant.imageLine).then(reader=>{if(reader?.seeded()&&grant.seed)openedAt=grant.seed.epoch;processReader=reader;return reader}).catch(cause=>{console.warn(`This process reads the project's files through their owner: its own reader did not open (${cause instanceof Error?cause.message:String(cause)}).`);return void 0});await Promise.race([opening,new Promise(resolve2=>setTimeout(resolve2,STORE_OPEN_BUDGET_MS))]);console.log(`[boot-trace] ${JSON.stringify({event:"store-open",at:Date.now(),ms:Date.now()-began,opened:processReader!==void 0})}`);return{opening,clock:grant.clock,get openedAt(){return openedAt}}}var STORE_OPEN_BUDGET_MS=1500;function storeReadsFor(filesystem){const active2=container;if(!packStore||!packStoreProjectId||!active2||filesystem!==active2.vfs||!(filesystem instanceof PackedVirtualFS))return{};const store=packStore,projectId=packStoreProjectId;return{storeReads:()=>{if(packStore!==store)return void 0;const clock=store.clock();const seed=store.readerSeed({overlays:true});const imageLine=seed?.packagesImage?store.imageLine():void 0;return{projectId,clock,...seed?{seed}:{},...imageLine?{imageLine}:{}}}}}var storeWriteFailure;function reportStoreWriteFailure(){const failure=storeWriteFailure;if(!failure)return;storeWriteFailure=void 0;throw failure}var packages;var packagesFilesystem;var processReader;var imageBlocked=()=>realmBlockedReads.size===0?void 0:Object.fromEntries([...realmBlockedReads].map(([reader,{ranges,ms:ms2}])=>[reader,{ranges,ms:Math.round(ms2)}]));var releasePackagesOpen;var initializationStarted=false;var workerDisposing=false;var portStreams=new Map;var childInputSupported=false;var releaseProject;var bundler;var threads;var workerOptions={};function configureNodeExecutionWorker(options){workerOptions=options}var toolchain;var invocationPolicy;var invocationFiles;var executionConfiguration;var confinedRuns=new Map;var nodeProcesses=new NodeProcessSupervisor;var rootRuntimeFiles;var programs=new Map;var commandResolver;function routeCommand2(command,cwd){if(!toolchain)return void 0;let argv;try{argv=parseCommandWords(command)}catch{return void 0}const env={};while(argv.length){const assignment=/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/su.exec(argv[0]);if(!assignment)break;env[assignment[1]]=assignment[2];argv.shift()}if(argv[0]==="/usr/bin/env"&&argv.length>1)argv.shift();let name=argv[0];if(name===void 0)return void 0;if(name.startsWith("/")&&!programs.has(name)){const basename2=name.slice(name.lastIndexOf("/")+1);if(programs.has(basename2)){name=basename2;argv[0]=basename2}}const runner2=programs.get(name)??commandResolver?.(name,cwd);return runner2?{argv,runner:runner2,env}:void 0}async function runCommand2(command,options){const links=splitShellChain(command);if(links.length===1)return runOneCommand(command,options);let stdout="";let stderr="";let exitCode=0;for(const link2 of links){if(!chainContinues(link2.operator,exitCode))continue;const result=await runOneCommand(link2.command,options);stdout+=result.stdout;stderr+=result.stderr;exitCode=result.exitCode}return{stdout,stderr,exitCode}}function runOneCommand(command,options){assertWorkerActive();options.signal?.throwIfAborted();const shellLine=shellCommandLine(command);if(shellLine!==void 0){const{executablePath:_shell,...lineOptions}=options;return runCommand2(shellLine,lineOptions)}const routed=routeCommand2(command,options.cwd??"/");if(routed)return routed.runner(routed.argv,{...options,env:{...options.env,...routed.env}});return engineRun(requiredContainer(),command,options)}function engineRun(active2,command,options){const bridge=Reflect.get(globalThis,executorSymbol);if(bridge)bridge.bypass+=1;return active2.run(command,options)}function toolchainContainer(active2){return tabnodeContainerView(active2,active2.vfs,{isolated:true,run:(command,options)=>engineRun(active2,command,options)})}var sharedModuleCache;var moduleCacheAnswers=new Map;var nextModuleCacheRequest=1;function askOwnerModuleCache(message){const id2=nextModuleCacheRequest++;return new Promise((resolve2,reject)=>{moduleCacheAnswers.set(id2,{resolve:resolve2,reject});send({...message,id:id2})})}var ownerModuleCache={link:(key,target)=>askOwnerModuleCache({type:"module-cache-link",key,target}),keep:async(key,code3,target)=>{await askOwnerModuleCache({type:"module-cache-keep",key,code:code3,target})}};function moduleCacheOption(vfs2){const moduleCache=projectModuleCache(vfs2);return moduleCache?{moduleCache}:{}}function projectModuleCache(vfs2){if(invocationFiles&&!packages)return ownerModuleCache;if(!packages||!packagesFilesystem||!(vfs2 instanceof PackedVirtualFS))return void 0;sharedModuleCache??=moduleCacheOver(packages,packagesFilesystem,vfs2);return sharedModuleCache}function installToolchain(active2,options){const moduleCache=projectModuleCache(active2.vfs);toolchain=new TabnodeToolchain(toolchainContainer(active2),{...invocationFiles?{runtimeFiles:invocationFiles.runtimeFiles}:rootRuntimeFiles?{runtimeFiles:rootRuntimeFiles}:{},...options.rolldownModuleUrl?{rolldownModuleUrl:new URL(options.rolldownModuleUrl,scope3.location.href).href}:{},...options.rolldownVersion?{rolldownVersion:options.rolldownVersion}:{},...options.standIns?{standIns:{...options.standIns}}:{},...moduleCache?{moduleCache}:{},...options.browserImports?{browserImports:options.browserImports}:{},...options.defaultVitePort!==void 0?{defaultVitePort:options.defaultVitePort}:{},...options.registryScopes?{registryScopes:options.registryScopes}:{},runShellCommand:runCommand2,runChildProcessCommand:runCommand2,authorizeExternalRequest:()=>void 0});toolchain.register({registerProgram:(name,runner2)=>{programs.set(name,runner2)},registerCommandResolver:resolver=>{commandResolver=resolver}});for(const manager of PACKAGE_MANAGER_ALIASES.filter(manager2=>manager2!=="pnpm"))programs.set(manager,packageManagerAliasRunner(manager,runCommand2));if(options.standIns)void fetchPrismaSchemaParser(active2.vfs,options.standIns)}var suppressFilesystemEvents=false;var importingFilesystemRoot;var activeRuns=new Map;function beginRun(id2,command,extra){console.log(`[boot-trace] ${JSON.stringify({event:"run-start",at:Date.now(),id:id2,program:programFromCommand(command,extra.executablePath)})}`);const{executablePath,...rest}=extra;activeRuns.set(id2,{...rest,program:programFromCommand(command,executablePath),command,startedAt:Date.now()})}function enginePids(){if(!container)return void 0;const engine=container;if(typeof engine.runPid!=="function"||typeof engine.processByPid!=="function")return void 0;return{token:()=>engine.currentProcessToken(),runPid:engine.runPid,processByPid:engine.processByPid}}function attributionNow(){const engine=enginePids();return networkProgramNow(activeRuns,engine?.token()??container?.currentProcessToken()??null,token=>engine?.runPid(token),pid=>engine?.processByPid(pid))}var nextFetchId=1;var pendingFetches=new Map;var responseStreams=new Map;var fetchAbortCleanup=new Map;var fetchActivities=new Map;function pullFetch(id2){const owned=fetchActivities.get(id2);try{if(owned)owned.pulls.push(owned.activity.hold());send({type:"fetch-pull",id:id2})}catch(cause){owned?.cancel();throw cause}}var filesystemForwardingScheduled=false;var settleEngineInitialized;var initialized=new Promise((resolve2,reject)=>{settleEngineInitialized={resolve:resolve2,reject}});void initialized.catch(()=>void 0);publishEngineInitialized(initialized);scope3.addEventListener("message",event=>{if(receiveNodeThread(event))return;if(port||event.data.type!=="attach"||!(event.data.port instanceof MessagePort))return;console.log("[boot-trace]",JSON.stringify({event:"worker-attach-received",at:Date.now()}));port=event.data.port;port.addEventListener("message",message=>void receive(message.data));port.start();send({type:"attached"})});async function receive(message){if(message.type==="module-cache-answer"){const waiter=moduleCacheAnswers.get(message.id);moduleCacheAnswers.delete(message.id);if(message.error)waiter?.reject(new Error(message.error));else waiter?.resolve(message.linked);return}try{if(message.type==="dispose"){if(!workerDisposing)await disposeWorker();return}assertWorkerActive();if(message.type==="init-confined"){if(initializationStarted)throw new Error("Browser Node host initialization has already started.");initializationStarted=true;childInputSupported=message.childInputVersion===1;const processRegistry2=new NodeProcessRegistryClient(message.processRegistry);installProcessRegistry(processRegistry2,message.initialProcess);if(processRegistry2.streams)installNativeStreamTransport(processRegistry2.streams);if(message.nodeProcess){if(!message.initialProcess||message.initialProcess.token!=="1"||!processRegistry2.streams){throw new Error("Node process execution requires its admitted run and native stream channel.")}installNodeEntryBridge(message.initialProcess.token,message.nodeProcess)}if(message.filesystemPolicy===void 0&&!message.nodeProcess)throw new Error("An ordinary Node realm requires process admission.");invocationPolicy=message.filesystemPolicy===void 0?void 0:normalizeProcessFilesystemPolicy(message.filesystemPolicy);if(message.preparedFiles&&!message.nodeProcess)throw new Error("Prepared entries require Node process admission.");const files=nodeInvocationFilesystem(message.filesystem,invocationPolicy,message.nodeProcess?{files:message.preparedFiles??[],limits:message.nodeProcess}:void 0,message.storeReads?await openStoreReads(message.storeReads):void 0);invocationFiles=files;container=createContainer({...message.options,vfs:files.guest});installPortForwarding();if(message.bundler)installBundler(container.vfs,message.bundler);threads=installNodeThreadHost(container.vfs,message.bundler);installToolchain(container,message.toolchain??{});installNetworkBroker();installChildProcessBridge();restrictNodeWorkerAuthority();send({type:"initialized",id:message.id,filesystemPolicyVersion:1,processRegistryVersion:1,...processRegistry2.streams?{nativeStreamVersion:1}:{},...message.nodeProcess?{nodeProcessVersion:1}:{},...typeof container?.signalProcess==="function"?{signalVersion:1}:{},inputBytesVersion:1,store:{opened:false,index:[]}});return}if(message.type==="init"){if(initializationStarted)throw new Error("Browser Node host initialization has already started.");initializationStarted=true;nodeProcesses.prepareWorkers(scope3.location.href);childInputSupported=message.childInputVersion===1;executionConfiguration={options:message.options,...message.bundler?{bundler:message.bundler}:{},...message.toolchain?{toolchain:message.toolchain}:{}};{const handoff2=takeStoreHandoff();const held=handoff2?.held??await holdProjectStores({projectId:String(message.store.projectId),...message.store.limits?{limits:message.store.limits}:{},report:work=>send({type:"initializing",id:message.id,work}),disposing:()=>workerDisposing});releaseProject=held.releaseProject;releasePackagesOpen=held.releasePackagesOpen;packages=held.shared;installPackageStore(held.shared);const store=held.store;packStore=store;for(const plan of held.preparedPlans??[])preparedProjectPlans.set(plan.root,plan.key);packStoreProjectId=String(message.store.projectId);const opened=held.opened;const{startedAt,phases}=held;const phase=(name,since)=>{phases.push(`${name} ${Math.round(performance.now()-since)} ms`);return performance.now()};const at3=performance.now();container=createContainer({...message.options,vfs:new PackedVirtualFS(store)});for(const entry of handoff2?.overlay??[]){if(entry.type==="directory"){if(!container.vfs.existsSync(entry.path))container.vfs.mkdirSync(entry.path,{recursive:true})}else container.vfs.writeFileSync(entry.path,entry.bytes)}{const active3=container;mountContainerProc(active3.vfs,ownerProcessTable,()=>active3.serverBridge.getServerPorts().map(port2=>{const pid=active3.portPid(port2);return{port:port2,...pid?{pid}:{}}}),()=>active3.streamHandles())}phase("engine",at3);console.log(`[worker] started in ${Math.round(performance.now()-startedAt)} ms: ${phases.join(", ")}`);if(message.toolchain?.typeStripperModuleUrl)await installTypeStripper(new URL(message.toolchain.typeStripperModuleUrl,scope3.location.href).href);webSocketRelay=createVirtualWebSocketRelay(relayed=>send({type:"ws",message:relayed}));if(message.bundler)installBundler(container.vfs,message.bundler);threads=installNodeThreadHost(container.vfs,message.bundler,{projectId:String(message.store.projectId),flush:()=>store.flush()});installFilesystemForwarding(container.vfs);installRootNodeEntryBridge();if(message.toolchain)installToolchain(container,message.toolchain);installNetworkBroker();installChildProcessBridge();const index2=[];let sharedIndex;if(!handoff2){if(message.sharedPageIndexVersion===1){store.clock();const seed=store.readerSeed({current:true});if(seed)sharedIndex={buffer:seed.index,roots:PROJECT_ROOTS,bytes:seed.liveBytes+seed.linkedBytes}}if(!sharedIndex)for(const[path3,entry]of store.entries)index2.push([path3,entry.type,entry.length,entry.mode,entry.mtimeMs])}send({type:"initialized",id:message.id,filesystemPolicyVersion:1,inputBytesVersion:1,store:{opened,index:index2,...sharedIndex?{sharedIndex}:{},treeImport:true,limitsVersion:1,entryReadVersion:1}});settleEngineInitialized?.resolve();return}}if(message.type==="fetch-response-start"){const pending=pendingFetches.get(message.id);if(!pending)return;pendingFetches.delete(message.id);try{const id2=message.id;const body=pending.method==="HEAD"||[204,205,304].includes(message.status)?null:new ReadableStream({start(controller){responseStreams.set(id2,controller)},pull(){pullFetch(id2)},cancel(){responseStreams.delete(id2);fetchAbortCleanup.get(id2)?.();fetchAbortCleanup.delete(id2);try{send({type:"fetch-abort",id:id2})}catch{}}},{highWaterMark:0});fetchActivities.get(id2)?.headersDone();pending.resolve({body,status:message.status,statusText:message.statusText,headers:message.headers});if(body===null)pullFetch(id2)}catch(cause){fetchAbortCleanup.get(message.id)?.();fetchAbortCleanup.delete(message.id);try{send({type:"fetch-abort",id:message.id})}catch{}pending.reject(cause instanceof Error?cause:new Error(String(cause)))}return}if(message.type==="fetch-response-chunk"){fetchActivities.get(message.id)?.pulls.shift()?.();responseStreams.get(message.id)?.enqueue(new Uint8Array(message.body));return}if(message.type==="fetch-response-end"){const stream=responseStreams.get(message.id);responseStreams.delete(message.id);fetchAbortCleanup.get(message.id)?.();fetchAbortCleanup.delete(message.id);stream?.close();return}if(message.type==="fetch-response"||message.type==="fetch-error"){const pending=pendingFetches.get(message.id);if(message.type==="fetch-error"){if(pending){pendingFetches.delete(message.id);pending.reject(new Error(message.error))}const stream=responseStreams.get(message.id);responseStreams.delete(message.id);fetchAbortCleanup.get(message.id)?.();fetchAbortCleanup.delete(message.id);stream?.error(new Error(message.error))}else if(!pending)return;else{pendingFetches.delete(message.id);fetchAbortCleanup.get(message.id)?.();fetchAbortCleanup.delete(message.id);try{pending.resolve({body:pending.method==="HEAD"||[204,205,304].includes(message.status)?null:new ReadableStream({start(controller){controller.enqueue(new Uint8Array(message.body));controller.close()}}),status:message.status,statusText:message.statusText,headers:message.headers})}catch(cause){pending.reject(cause instanceof Error?cause:new Error(String(cause)))}}return}if(message.type==="apply-layers"){try{const result=await applyImageLayers(message.url,message.digest,(parts,total)=>send({type:"applying-layers",id:message.id,parts,total}),message.prepared);send({type:"layers-applied",id:message.id,...result})}catch(cause){send({type:"layers-applied",id:message.id,parts:0,units:0,bytes:0,skipped:false,error:cause instanceof Error?cause.message:String(cause)})}return}if(message.type==="link-program"){try{send({type:"linked-program",id:message.id,...await linkImageProgram(message.source,message.target)})}catch(cause){send({type:"linked-program",id:message.id,linked:false,files:0,error:cause instanceof Error?cause.message:String(cause)})}return}if(message.type==="link-packages"){try{if(!linkPlan)throw new Error("The origin's package store is not open.");const result=await linkPlan(message.root,message.plan,(linked,total,waiting)=>send({type:"linking-packages",id:message.id,linked,total,...waiting?{waiting}:{}}));send({type:"linked-packages",id:message.id,...result})}catch(cause){const described=cause instanceof Error?cause.message?`${cause.name==="Error"?"":`${cause.name}: `}${cause.message}`:cause.name:String(cause);send({type:"linked-packages",id:message.id,linked:0,fetched:0,fromStore:0,error:described})}return}if(message.type==="pack-store-abort"){packStoreOperations.get(message.id)?.abort();return}if(message.type==="pack-store"){const controller=new AbortController;packStoreOperations.set(message.id,controller);try{await answerPackStore(message,controller.signal,{packages,project:packStore,linkShared:(source,target)=>{const vfs2=requiredContainer().vfs;if(!(vfs2 instanceof PackedVirtualFS))throw new Error("The live pack needs the worker's packed filesystem.");vfs2.linkShared(source,target)},send})}finally{packStoreOperations.delete(message.id)}return}if(message.type==="image-file"){const pending=pendingImageFiles.get(message.id);pendingImageFiles.delete(message.id);if(!pending)return;if(message.error!==void 0||message.bytes===void 0)pending.reject(new Error(`The image's file could not be read: ${message.error??"the page answered without it"}`));else pending.resolve({bytes:new Uint8Array(message.bytes),inflated:message.inflated===true});return}if(message.type==="image-pack"){const pending=pendingImagePacks.get(message.id);pendingImagePacks.delete(message.id);if(!pending)return;if(message.error!==void 0||message.text===void 0)pending.reject(new Error(message.error??"the page answered without the pack"));else pending.resolve(message.text);return}if(message.type==="image-packs-expected"){imagePacksKnown??=new Promise(resolve2=>{settleImagePacksKnown=resolve2});return}if(message.type==="image-packs-abandoned"){settleImagePacksKnown?.();imagePacksKnown=settleImagePacksKnown=void 0;return}if(message.type==="image-packs"){try{const packs=readImagePacks(message.keys);settleImagePacksKnown?.();imagePacksKnown=settleImagePacksKnown=void 0;if(message.bodies?.length)await linkPreparedBodies(message.bodies);send({type:"image-packs-read",id:message.id,packs})}catch(cause){send({type:"image-packs-read",id:message.id,packs:0,error:cause instanceof Error?cause.message:String(cause)})}finally{settleImagePacksKnown?.();imagePacksKnown=settleImagePacksKnown=void 0}return}if(message.type==="ws"){webSocketRelay?.receive(message.message);return}if(message.type==="watched-paths"){const vfs2=container?.vfs;const paths=typeof vfs2?.watchedPaths==="function"?vfs2.watchedPaths():vfs2?.watchers?[...vfs2.watchers.entries()].filter(([,entries])=>[...entries].some(entry=>!entry.closed)).map(([path3,entries])=>({path:path3,recursive:[...entries].some(entry=>!entry.closed&&entry.recursive===true)})):[];send({type:"watched-paths",id:message.id,paths});return}if(message.type==="store-stats"){const account=installAccounting();send({type:"store-stats",id:message.id,stats:packStore?{...packStore.stats(),...account?{install:account}:{}}:null});return}if(message.type==="image-startup-set"){send({type:"image-startup-set",id:message.id,ranges:packages?.imageStartupSet()??[]});return}if(message.type==="image-prefetch"){const startedAt=performance.now();const prefetch=packages?.prefetchImage(message.ranges,message.streams)??{queued:0,done:Promise.resolve()};send({type:"image-prefetch",id:message.id,queued:prefetch.queued});if(prefetch.queued>0)void prefetch.done.then(()=>send({type:"image-prefetched",id:message.id,ms:Math.round(performance.now()-startedAt)}));return}if(message.type==="profile-probe"){send({type:"profile-pong",id:message.id});return}if(message.type==="host-ports"){hostPorts=new Set(message.ports.filter(candidate=>Number.isInteger(candidate)&&candidate>0&&candidate<65536));for(const listener of hostPortListeners)listener(hostPorts);return}if(message.type==="listen-net"||message.type==="unlisten-net"||message.type==="net-data"||message.type==="net-end"){handleNetMessage(message);return}if(message.type==="child-input-consumed"){const pending=pendingChildInput.get(message.id);pendingChildInput.delete(message.id);pending?.resolve();return}if(message.type==="child-fd-consumed"){const key=childFdKey(message.id,message.fd);const pending=pendingChildFdInput.get(key);pendingChildFdInput.delete(key);pending?.resolve();return}if(message.type==="child-fd-output"||message.type==="child-fd-close"){const pending=pendingChildren.get(message.id);const descriptor=validChildFd(message.fd)?pending?.descriptors?.[message.fd]:void 0;if(!pending||!descriptor)return;if(message.type==="child-fd-close"){descriptor.end();return}if(!(message.bytes instanceof ArrayBuffer)||message.bytes.byteLength>childChunkBytes){pendingChildren.delete(message.id);try{send({type:"child-abort",id:message.id})}catch{}pending.reject(new Error("Child process descriptor chunks must be at most 64 KiB."));return}descriptor.write(new Uint8Array(message.bytes));return}if(message.type==="child-output"||message.type==="child-result"||message.type==="child-error"){const pending=pendingChildren.get(message.id);if(!pending)return;if(message.type==="child-output"){if(message.stream==="stdout")pending.onStdout?.(message.chunk);else pending.onStderr?.(message.chunk);return}console.log(`[boot-trace] ${JSON.stringify({event:message.type,at:Date.now(),id:message.id,owner:pending.owner})}`);pendingChildren.delete(message.id);if(message.type==="child-error")pending.reject(new Error(message.error));else pending.resolve({stdout:message.stdout,stderr:message.stderr,exitCode:message.exitCode,...message.signal?{signal:message.signal}:{}});return}const active2=requiredContainer();if(message.type==="fs-watch-event"){invocationFiles?.notifyWatch(message.event,message.path);return}if(message.type==="fs-event"){invocationFiles?.notify(message.event,message.path);return}if(message.type==="run"&&message.filesystemPolicy&&!invocationPolicy){if(!executionConfiguration)throw new Error("Confined Node execution has no worker configuration.");const configuration=executionConfiguration;const policy=normalizeProcessFilesystemPolicy(message.filesystemPolicy);const controller=new AbortController;confinedRuns.set(message.id,controller);beginRun(message.id,message.command,{controller,...message.cwd?{cwd:message.cwd}:{},...message.executablePath?{executablePath:message.executablePath}:{}});const liveStdin=message.liveStdin?openLiveStdin(message.id):void 0;const terminal=message.terminal?openTerminal(message.id,message.terminal):void 0;void nodeProcesses.run(message.command,{...message.cwd?{cwd:message.cwd}:{},...message.env?{env:message.env}:{},...message.stdin!==void 0?{stdin:message.stdin}:{},...liveStdin?{stdinStream:liveStdin}:{},...terminal?{terminal}:{},signal:controller.signal,onStdout:chunk=>send({type:"output",id:message.id,stream:"stdout",chunk}),onStderr:chunk=>send({type:"output",id:message.id,stream:"stderr",chunk})},{filesystem:active2.vfs,...storeReadsFor(active2.vfs),policy,workerUrl:scope3.location.href,configuration,serverBridge:active2.serverBridge,net:pageNetHost,hostPorts:hostPortsHost,...moduleCacheOption(active2.vfs),runChild:(command,options,argv)=>requestChild(command,options,message.id,argv),http:request=>brokerHttpOnce(request,{program:programFromCommand(message.command,message.executablePath),attributed:true,activePrograms:[programFromCommand(message.command,message.executablePath)]})}).then(async result=>{await packStore?.flush();flushFilesystemForwarding();sendResult(message.id,result)}).catch(cause=>{flushFilesystemForwarding();sendError(message.id,cause)}).finally(()=>{confinedRuns.delete(message.id);activeRuns.delete(message.id);liveStdins.get(message.id)?.close(true);liveStdins.delete(message.id);terminals.delete(message.id)});return}if(message.type==="run"){const chain=splitShellChain(message.command).length>1;const routed=chain?void 0:routeCommand2(message.command,message.cwd??"/");const controller=new AbortController;beginRun(message.id,message.command,{...controller?{controller}:{},...message.cwd?{cwd:message.cwd}:{},...message.executablePath?{executablePath:message.executablePath}:{}});launchPorts.set(message.id,new Set(vfsServerBridge().getServerPorts()));if(message.interactive)heldRuns.add(message.id);const liveStdin=message.liveStdin?openLiveStdin(message.id):void 0;const terminal=message.terminal?openTerminal(message.id,message.terminal):void 0;const runOptions={...message.cwd?{cwd:message.cwd}:{},...message.env?{env:message.env}:{},...controller?{signal:controller.signal}:{},held:message.interactive,...{processToken:String(message.id)},...message.stdin!==void 0?{stdin:message.stdin}:{},...liveStdin?{stdinStream:liveStdin}:{},...terminal?{terminal}:{},onStdout:chunk=>send({type:"output",id:message.id,stream:"stdout",chunk}),onStderr:chunk=>send({type:"output",id:message.id,stream:"stderr",chunk})};const running=chain?runCommand2(message.command,runOptions):routed?routed.runner(routed.argv,{...runOptions,env:{...runOptions.env,...routed.env}}):engineRun(active2,message.command,runOptions);void running.then(async result=>{console.log(`[boot-trace] ${JSON.stringify({event:"body-return",at:Date.now(),id:message.id,exitCode:result.exitCode,ports:runPorts(message.id),imageBlocked:imageBlocked()})}`);await workSettled(message.id,message.interactive);flushFilesystemForwarding();const aborted=activeRuns.get(message.id)?.controller?.signal.aborted===true;sendResult(message.id,aborted&&result.exitCode===0?{...result,exitCode:143}:result)},cause=>{flushFilesystemForwarding();sendError(message.id,cause)}).finally(()=>{liveStdins.get(message.id)?.close(true);liveStdins.delete(message.id);terminals.delete(message.id);activeRuns.delete(message.id);launchPorts.delete(message.id);heldRuns.delete(message.id)})}else if(message.type==="stdin"){if(message.id!==void 0){const input=liveStdins.get(message.id);if(message.bytes&&input){const id2=message.id;void input.write(new Uint8Array(message.bytes)).then(()=>send({type:"stdin-consumed",id:id2})).catch(cause=>{activeRuns.get(id2)?.controller?.abort(cause);if(!workerDisposing)sendError(id2,cause)})}else if(input)input.push(message.data);else if(message.data!==void 0)active2.sendInput(message.data,String(message.id))}else active2.sendInput(message.data)}else if(message.type==="stdin-end"){liveStdins.get(message.id)?.close();liveStdins.delete(message.id)}else if(message.type==="resize"){terminals.get(message.id)?.resize(message.columns,message.rows)}else if(message.type==="signal"){active2.signalProcess?.(String(message.id),message.signal)}else if(message.type==="abort"){if(heldRuns.has(message.id))closeRunServers(message.id);confinedRuns.get(message.id)?.abort();for(const[childId,child]of pendingChildren){if(child.owner===message.id)send({type:"child-abort",id:childId})}active2.stopProcess?.(String(message.id));liveStdins.get(message.id)?.close(true);liveStdins.delete(message.id);terminals.delete(message.id);activeRuns.get(message.id)?.controller?.abort()}else if(message.type==="fs-apply"){suppressFilesystemEvents=true;try{for(const operation of message.operations){try{applyStoreOperation(active2.vfs,operation)}catch(cause){storeWriteFailure??=cause instanceof Error?cause:new Error(String(cause));const paths=operation.op==="rename"?[operation.from,operation.to]:[operation.path];for(const path3 of paths)queueIndexForwarding(storeEntryOf(active2.vfs,path3));console.error(`The workspace refused ${operation.op} ${paths.join(" -> ")}: ${cause instanceof Error?cause.message:String(cause)}`)}}}finally{suppressFilesystemEvents=false}}else if(message.type==="fs-import"){reportStoreWriteFailure();if(!(active2.vfs instanceof PackedVirtualFS)||!packStore){send({type:"fs-imported",id:message.id,applied:false,changes:[]});return}flushFilesystemForwarding();const root2=normalizeStorePath2(message.tree.root);importingFilesystemRoot=root2;suppressFilesystemEvents=true;let applied;try{applied=active2.vfs.importTree(message.tree)}finally{suppressFilesystemEvents=false;importingFilesystemRoot=void 0}const changes=[];if(applied){changes.push([root2,null]);for(const[path3,entry]of packStore.descendants(root2)){changes.push([path3,entry.type,entry.type==="file"?entry.length:0,entry.mode,entry.mtimeMs])}}send({type:"fs-imported",id:message.id,applied,changes})}else if(message.type==="fs-read"){try{const bytes2=Uint8Array.from(active2.vfs.readFileSync(message.path));const body=bytes2.buffer.slice(bytes2.byteOffset,bytes2.byteOffset+bytes2.byteLength);send({type:"fs-read-result",id:message.id,bytes:body},[body])}catch(cause){sendError(message.id,cause)}}else if(message.type==="fs-entry"){reportStoreWriteFailure();const path3=normalizeStorePath2(message.path);flushFilesystemForwarding();if(!active2.vfs.existsSync(path3)){send({type:"fs-entry-result",id:message.id})}else{const stat2=active2.vfs.statSync(path3);const metadata={path:path3,mode:stat2.mode&4095,mtimeMs:stat2.mtimeMs};if(stat2.isDirectory()){send({type:"fs-entry-result",id:message.id,entry:{...metadata,type:"directory"}})}else{const bytes2=Uint8Array.from(active2.vfs.readFileSync(path3));send({type:"fs-entry-result",id:message.id,entry:{...metadata,type:"file",bytes:bytes2}},[bytes2.buffer])}}}else if(message.type==="fs-flush"){reportStoreWriteFailure();packStore?.flush();send({type:"fs-flushed",id:message.id})}else if(message.type==="port-stream-request"){const stream={abort:new AbortController,pause:()=>void 0,resume:()=>void 0};portStreams.set(message.id,stream);try{const answered=await active2.serverBridge.handleStreamingRequest(message.port,message.method,message.url,message.headers,message.body,{start:(statusCode,statusMessage,headers)=>send({type:"port-stream-head",id:message.id,statusCode,statusMessage,headers}),chunk:chunk=>{const body=Uint8Array.from(chunk).buffer;send({type:"port-stream-chunk",id:message.id,body},[body])},end:()=>send({type:"port-stream-end",id:message.id})},{signal:stream.abort.signal,control:(pause,resume)=>{stream.pause=pause;stream.resume=resume}});if(!answered){send({type:"port-stream-head",id:message.id,statusCode:503,statusMessage:"Service Unavailable",headers:{}});send({type:"port-stream-end",id:message.id})}}finally{portStreams.delete(message.id)}}else if(message.type==="port-stream-control"){const stream=portStreams.get(message.id);if(message.action==="pause")stream?.pause();else if(message.action==="resume")stream?.resume();else stream?.abort.abort()}else if(message.type==="request"){const response=await active2.serverBridge.handleRequest(message.port,message.method,message.url,message.headers,message.body);const bytes2=response.body?Uint8Array.from(response.body):new Uint8Array;const body=bytes2.buffer.slice(bytes2.byteOffset,bytes2.byteOffset+bytes2.byteLength);send({type:"response",id:message.id,statusCode:response.statusCode,statusMessage:response.statusMessage??"",headers:response.headers,body},[body])}}catch(cause){if(message.type==="init")settleEngineInitialized?.reject(cause);if("id"in message&&typeof message.id==="number")sendError(message.id,cause)}}function assertWorkerActive(){if(workerDisposing)throw new Error("Browser Node host is disposed.")}async function disposeWorker(){workerDisposing=true;const reapedProcesses=nodeProcesses.dispose();const failures=[];const release2=operation=>{try{operation()}catch(cause){failures.push(cause)}};for(const controller of confinedRuns.values())release2(()=>controller.abort());confinedRuns.clear();for(const socket of netSockets.values())release2(()=>socket.destroy());netSockets.clear();for(const unlisten of netListeners.values())release2(unlisten);netListeners.clear();netListenerChanges.clear();for(const controller of packStoreOperations.values())controller.abort();packStoreOperations.clear();for(const run of activeRuns.values())release2(()=>run.controller?.abort());for(const input of liveStdins.values())release2(()=>input.close(true));liveStdins.clear();terminals.clear();for(const pending of pendingChildren.values())pending.reject(new Error("Browser Node host was disposed."));pendingChildren.clear();for(const pending of pendingFetches.values())pending.reject(new Error("Browser Node host was disposed."));pendingFetches.clear();for(const stream of responseStreams.values())stream.error(new Error("Browser Node host was disposed."));responseStreams.clear();for(const cleanup of fetchAbortCleanup.values())cleanup();fetchAbortCleanup.clear();await reapedProcesses;release2(()=>threads?.dispose());threads=void 0;try{await toolchain?.dispose()}catch(cause){failures.push(cause)}toolchain=void 0;release2(()=>bundler?.dispose());bundler=void 0;release2(()=>packStore?.close());packStore=void 0;release2(()=>packages?.close());packages=void 0;release2(()=>releasePackagesOpen?.());releasePackagesOpen=void 0;release2(()=>releaseProject?.());releaseProject=void 0;activeRuns.clear();release2(()=>port?.close());if(failures.length)console.error("Browser Node worker cleanup failed.",new AggregateError(failures));scope3.close()}function installBundler(vfs2,options){bundler=new BrowserBundler(vfs2,options);const shim=esbuildShim;shim.setModuleURL(new URL(options.esbuildModuleUrl,scope3.location.href).href);shim.setWasmURL(new URL(options.esbuildWasmUrl,scope3.location.href).href);if(options.rollupModuleUrl)Reflect.set(globalThis,"__browserRuntimeRollupUrl",new URL(options.rollupModuleUrl,scope3.location.href).href);Reflect.set(globalThis,"__browserRuntimeRollupFs",rollupFsOver(requiredContainer().vfs));bundler.prebundle=vitePrebundleAssembler(vfs2,projectModuleCache(vfs2));shim.useHost(bundler)}function normalizeStorePath2(path3){const parts=[];for(const part of path3.split("/")){if(!part||part===".")continue;if(part==="..")parts.pop();else parts.push(part)}return`/${parts.join("/")}`}var installAccount={packages:0,linkedFromStore:0,downloadMs:0,downloadBytes:0,lockWaitMs:0,extractMs:0,extractHelpers:0,applyMs:0,linkMs:0,announceMs:0,sharedFlushes:0,sharedFlushMs:0,elapsedMs:0,lastAt:0};var packStoreOperations=new Map;function installAccounting(){if(installAccount.packages===0)return void 0;const{firstAt,lastAt,...account}=installAccount;return{...account,elapsedMs:firstAt===void 0?0:Math.round(lastAt-firstAt)}}function installPackageStore(shared){const sharedFilesystem=new PackedVirtualFS(shared,PACKAGES_ROOT);packagesFilesystem=sharedFilesystem;const making=new Map;const ensure=async(key,tarballUrl,integrity,pack)=>{try{return await make(key,tarballUrl,integrity,pack)}finally{making.delete(key)}};const make=async(key,tarballUrl,integrity,pack)=>{const startedAt=performance.now();installAccount.firstAt??=startedAt;if(!pack){installTrap({door:"package extraction",subject:`${key} has no pack; the tab would download and extract ${tarballUrl}`,detail:{key,tarball:tarballUrl,...integrity?{integrity}:{}}})}const digest=pack.artifact.digest;const store=livePackStore(shared);let fetched=false;if(!await store.hasTree(digest)){making.set(key,"receiving");const bytes2=await imageFile(pack.url);const actual=`sha256:${[...new Uint8Array(await crypto.subtle.digest("SHA-256",bytes2))].map(byte=>byte.toString(16).padStart(2,"0")).join("")}`;if(actual!==digest||bytes2.byteLength!==pack.artifact.bytes){installTrap({door:"image pack",subject:`${key}'s pack at ${pack.url} is not the artifact the plan names (${bytes2.byteLength} bytes, ${actual}; the plan names ${pack.artifact.bytes} bytes, ${digest})`,detail:{key}})}installAccount.downloadBytes+=bytes2.byteLength;installAccount.downloadMs+=performance.now()-startedAt;making.set(key,"storing");const stagedAt=performance.now();await store.stageArtifact(digest,bytes2,pack.artifact);installAccount.extractMs+=performance.now()-stagedAt;fetched=true}return{home:browserPackExpandedPath(digest),fetched}};const link2=(vfs2,home,path3,fromStore)=>{if(fromStore)installAccount.linkedFromStore+=1;const linkStartedAt=performance.now();const announcedBefore=vfs2.linkTiming.announceMs;vfs2.linkShared(home,path3);installAccount.linkMs+=performance.now()-linkStartedAt;installAccount.announceMs+=vfs2.linkTiming.announceMs-announcedBefore;installAccount.packages+=1;installAccount.lastAt=performance.now()};const hook=async(name,pkg,pkgPath,vfs2)=>{if(!(vfs2 instanceof PackedVirtualFS))return false;const ensured=await ensure(`${name}@${pkg.version}`,pkg.tarballUrl);if(!ensured)return false;link2(vfs2,ensured.home,pkgPath,!ensured.fetched);return true};Reflect.set(globalThis,Symbol.for("@volter/browser-runtime/package-install"),hook);linkPlan=async(root2,plan,progress)=>{const vfs2=requiredContainer().vfs;if(!(vfs2 instanceof PackedVirtualFS))throw new Error("The image's dependency plan needs the worker's store.");const at3=path3=>`${root2==="/"?"":root2}/${path3}`;const phases={};let phaseAt=performance.now();const phase=name=>{const now=performance.now();phases[name]=Math.round(now-phaseAt);phaseAt=now};const total=plan.links.length;let linked=0;let fetched=0;let fromStore=0;let lastReported=performance.now();const checkedAt=performance.now();installAccount.firstAt??=checkedAt;const prelinked=plan.key!==void 0&&preparedProjectPlans.get(root2)===plan.key;if(prelinked)preparedProjectPlans.delete(root2);const held=prelinked?new Set:await livePackStore(shared).presentTrees(plan.packages.flatMap(entry=>entry.pack?[entry.pack.artifact.digest]:[]));installAccount.lockWaitMs+=performance.now()-checkedAt;const homes=new Map;const homeOf=index2=>{let pending=homes.get(index2);if(!pending){const entry=plan.packages[index2];const digest=entry.pack?.artifact.digest;if(digest!==void 0&&held.has(digest)){fromStore+=1;pending=Promise.resolve({home:browserPackExpandedPath(digest),fetched:false});homes.set(index2,pending);return pending}pending=ensure(`${entry.name}@${entry.version}`,entry.tarball,entry.integrity,entry.pack).then(ensured=>{if(!ensured)throw new Error(`${entry.name}@${entry.version}: this thread cannot fetch packages into the store.`);if(ensured.fetched)fetched+=1;else fromStore+=1;return ensured});homes.set(index2,pending)}return pending};const links=[...plan.links].sort((left,right)=>depth3(left.path)-depth3(right.path)||left.path.localeCompare(right.path));const platformFits=new Map;const fitsPlatform=(index2,home)=>{let fits=platformFits.get(index2);if(fits!==void 0)return fits;if(plan.packages[index2]?.placed){platformFits.set(index2,true);return true}const prepared=plan.packages[index2]?.linuxX64;if(prepared!==void 0){platformFits.set(index2,prepared);return prepared}fits=true;try{const store=packagesFilesystem&&packagesFilesystem.existsSync(`${home}/package.json`)?packagesFilesystem:vfs2;const manifest=JSON.parse(store.readFileSync(`${home}/package.json`,"utf8"));const allows=(field,value)=>{if(!Array.isArray(field)||field.length===0)return true;const names2=field.filter(item=>typeof item==="string");const denied=names2.filter(name=>name.startsWith("!")).map(name=>name.slice(1));const allowed=names2.filter(name=>!name.startsWith("!"));if(denied.includes(value))return false;return allowed.length===0||allowed.includes(value)};fits=allows(manifest.os,"linux")&&allows(manifest.cpu,"x64")}catch{}platformFits.set(index2,fits);return fits};const place=async entry=>{const{home,fetched:wasFetched}=await homeOf(entry.package);if(!fitsPlatform(entry.package,home)){const stale=at3(entry.path);try{if(vfs2.existsSync(stale))removeTree2(vfs2,stale)}catch{}}else{link2(vfs2,home,at3(entry.path),!wasFetched)}linked+=1;if(performance.now()-lastReported>500){lastReported=performance.now();progress(linked,total)}};const nested=path3=>{const at4=path3.lastIndexOf("node_modules/");const rest=(at4<0?path3:path3.slice(at4+"node_modules/".length)).split("/").filter(Boolean);const nameLength=rest[0]?.startsWith("@")?2:1;return rest.length>nameLength};const first=links.filter(entry=>!nested(entry.path));const later=links.filter(entry=>nested(entry.path));const concurrency=16;let next2=0;let stopped2=false;let linkedAtLastLook=-1;const watch2=setInterval(()=>{if(linked!==linkedAtLastLook){linkedAtLastLook=linked;return}progress(linked,total,[...making].map(([key,stage])=>`${key} ${stage}`))},STALL_REPORT_MS);try{const placed=await Promise.allSettled(Array.from({length:prelinked?0:Math.min(concurrency,first.length)},async()=>{while(!stopped2){const index2=next2++;if(index2>=first.length)return;try{await place(first[index2])}catch(cause){stopped2=true;throw cause}}}));const failures=placed.filter(result=>result.status==="rejected").map(result=>result.reason);if(failures.length===1)throw failures[0];if(failures.length>1)throw new AggregateError(failures,"Package placement failed.");if(prelinked){linked=total;fromStore=new Set(plan.links.filter(entry=>plan.packages[entry.package]?.placed||plan.packages[entry.package]?.linuxX64!==false).map(entry=>entry.package)).size}else for(const entry of later)await place(entry)}finally{clearInterval(watch2)}phase(prelinked?"prelinkedMs":"linksMs");for(const bin of plan.bins){const path3=at3(bin.path);const directory2=path3.slice(0,path3.lastIndexOf("/"));if(!vfs2.existsSync(directory2))vfs2.mkdirSync(directory2,{recursive:true});vfs2.writeFileSync(path3,`node "${at3(bin.target)}" "$@"
6426
+ `)}for(const entry of plan.entries??[]){const path3=at3(entry.path);const directory2=path3.slice(0,path3.lastIndexOf("/"));if(!vfs2.existsSync(directory2))vfs2.mkdirSync(directory2,{recursive:true});vfs2.writeFileSync(path3,entry.content)}phase("binsMs");if(plan.aliases.length>0)configurePlanAliases(vfs2,root2,plan.aliases);const workspace=discoverPnpmWorkspace(vfs2,root2);if(workspace)configureWorkspaceLinks(vfs2,workspace);phase("aliasesMs");console.log(`[boot-trace] ${JSON.stringify({event:"link-plan",at:Date.now(),root:root2,links:total,bins:plan.bins.length,entries:plan.entries?.length??0,aliases:plan.aliases.length,...phases})}`);progress(linked,total);return{linked,fetched,fromStore}}}function removeTree2(vfs2,path3){const stats=vfs2.lstatSync(path3);if(stats.isDirectory()&&!stats.isSymbolicLink()){for(const name of vfs2.readdirSync(path3))removeTree2(vfs2,`${path3}/${name}`);vfs2.rmdirSync(path3)}else{vfs2.unlinkSync(path3)}}var STALL_REPORT_MS=15e3;var linkPlan;var preparedProjectPlans=new Map;async function linkImageProgram(source,target){if(!packages)throw new Error("The origin's package store is not open.");const shared=packages;const vfs2=requiredContainer().vfs;if(!(vfs2 instanceof PackedVirtualFS))throw new Error("A program is linked into the worker's packed filesystem.");if(!source.startsWith("/packages/.programs/"))throw new Error(`${source} is not a program's tree in the shared store.`);return scope3.navigator.locks.request(PACKAGES_LOCK,{mode:"shared"},async()=>{await shared.refresh();if(!shared.entries.has(`${source}/${PROGRAM_ARCHIVE_RECEIPT}`))return{linked:false,files:0};vfs2.linkShared(source,target);return{linked:true,files:shared.descendants(source).length}})}var imagePacks=new Set;var imagePacksKnown;var settleImagePacksKnown;var fetchingPacks=new Map;var PREPARED_BODY_LINK_BATCH=512;function readImagePacks(keys){imagePacks.clear();for(const key of keys)if(typeof key==="string")imagePacks.add(key);return imagePacks.size}async function linkPreparedBodies(keys){const vfs2=container?.vfs;if(!packages||!packagesFilesystem||!(vfs2 instanceof PackedVirtualFS))return;const shared=packages;const sharedFilesystem=packagesFilesystem;if(!vfs2.existsSync(PREPARED_MODULES_DIR))vfs2.mkdirSync(PREPARED_MODULES_DIR,{recursive:true});const present=new Set(vfs2.readdirSync(PREPARED_MODULES_DIR).map(String));const missing=keys.filter(key=>!present.has(key));if(missing.length===0)return;const startedAt=performance.now();let linked=0;let fetched=0;const held=missing.filter(key=>shared.entries.has(`${PACKAGES_ROOT}/.prepared/${key}`));const absent=missing.filter(key=>!shared.entries.has(`${PACKAGES_ROOT}/.prepared/${key}`));for(let offset2=0;offset2<held.length;offset2+=PREPARED_BODY_LINK_BATCH){const batch=held.slice(offset2,offset2+PREPARED_BODY_LINK_BATCH);vfs2.linkSharedBatch(batch.map(key=>({source:`${PACKAGES_ROOT}/.prepared/${key}`,path:`${PREPARED_MODULES_DIR}/${key}`})));linked+=batch.length}let next2=0;await Promise.all(Array.from({length:Math.min(8,absent.length)},async()=>{while(next2<absent.length){const key=absent[next2++];const source=`${PACKAGES_ROOT}/.prepared/${key}`;try{if(!shared.entries.has(source)){const body=await imagePack(key);await scope3.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive"},async()=>{await shared.refresh();if(!shared.entries.has(source))sharedFilesystem.writeFileSync(source,body);if(shared.logBytes>8*1024*1024)await shared.checkpoint()});fetched+=1}vfs2.linkShared(source,`${PREPARED_MODULES_DIR}/${key}`);linked+=1}catch(cause){console.warn(`[modules] the image's prepared body ${key} could not be linked (${cause instanceof Error?cause.message:String(cause)}); the engine prepares that module itself.`)}}}));console.log(`[modules] ${linked} of ${missing.length} prepared bodies linked from the origin's store in ${Math.round(performance.now()-startedAt)} ms (${fetched} fetched from the image)`)}async function applyImageLayers(url2,digest,progress,compact){if(!packages)throw new Error("The origin's package store is not open.");const shared=packages;const applied=imageLayersAppliedPath(digest);const deferred=imageLayersDeferredPath(digest);await scope3.navigator.locks.request(PACKAGES_LOCK,{mode:"shared"},()=>shared.refresh());if(shared.entries.has(applied)||shared.entries.has(deferred)||shared.deferredImage===digest)return{parts:0,units:0,bytes:0,skipped:true};if(compact&&shared.packBytes===0&&new URL(url2).origin===scope3.location.origin){const text2=await imageFile(compact.url);const named2=Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",text2)),byte=>byte.toString(16).padStart(2,"0")).join("");if(named2!==compact.digest)throw new Error("The prepared image descriptor is not the one its manifest names.");const descriptor=JSON.parse(new TextDecoder().decode(text2));if(descriptor.kind!=="browser-substrate-prepared-layers"||descriptor.version!==1||!Number.isSafeInteger(descriptor.units)||descriptor.units<0){throw new Error("Malformed prepared image descriptor.")}const prepared=validatePreparedImageIndex(descriptor.prepared);progress(0,2);const metadata=async file2=>{const answer2=await imageFileAnswer(new URL(file2.url,url2).href,file2);if(answer2.inflated)return answer2.bytes;if(answer2.bytes.byteLength!==file2.bytes)throw new Error("The image's metadata has the wrong served size.");return inflateLayerPart(answer2.bytes,file2.raw)};const[json,binary]=await Promise.all([metadata(prepared.json),metadata(prepared.binary)]);const ranges={...prepared.ranges,image:digest};const installed3=await scope3.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive"},async()=>{await shared.refresh();if(shared.entries.has(deferred))return true;if(!await shared.installPreparedImage(prepared,json,binary,ranges))return false;shared.applyNow([{operation:"write",path:deferred,content:new Uint8Array(0),mode:292}],{durable:true});return true});if(installed3){progress(2,2);return{parts:0,units:descriptor.units,bytes:prepared.json.bytes+prepared.binary.bytes,skipped:false}}}const text=await imageFile(url2);const named=[...new Uint8Array(await crypto.subtle.digest("SHA-256",text))].map(byte=>byte.toString(16).padStart(2,"0")).join("");if(!named.startsWith(digest))throw new Error(`The image's layers document at ${url2} is not the one its manifest names.`);const document2=validateImageLayers(JSON.parse(new TextDecoder().decode(text)));const needed=document2.parts.filter(part=>part.units.some(unit=>!shared.entries.has(unit.marker)));let parts=0,units=0,bytes2=0,next2=0;let failed=false;const placedAt=Date.now();progress(0,needed.length);await shared.deferMaintenance(async()=>{const results=await Promise.allSettled(Array.from({length:Math.min(LAYER_PARTS_AT_ONCE,needed.length)},async()=>{while(next2<needed.length&&!failed){const part=needed[next2++];try{const answer2=await imageFileAnswer(new URL(part.url,url2).href,{bytes:part.bytes,raw:part.raw,sha256:part.sha256});let raw=answer2.bytes;if(!answer2.inflated){if(raw.byteLength!==part.bytes)throw new Error(`The image's layer part ${part.url} is ${raw.byteLength} bytes; its document says ${part.bytes}.`);raw=await inflateLayerPart(raw,part.raw);const actual=[...new Uint8Array(await crypto.subtle.digest("SHA-256",raw))].map(byte=>byte.toString(16).padStart(2,"0")).join("");if(actual!==part.sha256)throw new Error(`The image's layer part ${part.url} is not the part its document names.`)}else if(raw.byteLength!==part.raw)throw new Error(`The image's layer part ${part.url} came inflated to ${raw.byteLength} bytes; its document says ${part.raw}.`);await scope3.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive"},async()=>{await shared.refresh();const files=[];const slices=[];let size=0;for(const unit of part.units){if(shared.entries.has(unit.marker))continue;let start=Infinity,end=0;for(const[,type2,,offset2,length]of unit.files)if(type2!=="d"){start=Math.min(start,offset2);end=Math.max(end,offset2+length)}if(start===Infinity)start=end=0;const base=size-start;let marked=false;for(const[relative3,type2,mode,offset2,length]of unit.files){const path3=imageLayerPath(unit,relative3);if(path3===unit.marker)marked=true;files.push(type2==="d"?{path:path3,type:"directory",mode,mtimeMs:placedAt}:{path:path3,type:type2==="l"?"symlink":"file",mode,mtimeMs:placedAt,offset:base+offset2,length})}if(!marked)files.push({path:unit.marker,type:"file",mode:292,mtimeMs:placedAt,offset:0,length:0});slices.push(raw.subarray(start,end));size+=end-start;units+=1}if(files.length===0)return;const bytes3=slices.length===1?slices[0]:new Uint8Array(size);if(slices.length>1){let cursor=0;for(const slice of slices){bytes3.set(slice,cursor);cursor+=slice.byteLength}}shared.applyExtentsNow(bytes3,files)});parts+=1;bytes2+=part.bytes;progress(parts,needed.length)}catch(cause){failed=true;throw cause}}}));const rejected=results.find(result=>result.status==="rejected");if(rejected)throw rejected.reason;await scope3.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive"},async()=>{await shared.refresh();if(!shared.entries.has(applied))shared.applyNow([{operation:"write",path:applied,content:new Uint8Array(0),mode:292}]);if(shared.logBytes>0)await shared.checkpoint()})});return{parts,units,bytes:bytes2,skipped:false}}var LAYER_PARTS_AT_ONCE=6;async function inflateLayerPart(served,raw){const reader=new Blob([served]).stream().pipeThrough(new DecompressionStream("gzip")).getReader();const out=new Uint8Array(raw);let offset2=0;for(;;){const{done,value}=await reader.read();if(done)break;if(offset2+value.byteLength>raw)throw new Error("An image layer part inflates past its raw size.");out.set(value,offset2);offset2+=value.byteLength}if(offset2!==raw)throw new Error("An image layer part inflates short of its raw size.");return out}var nextImagePackRead=1;var pendingImagePacks=new Map;var pendingImageFiles=new Map;var nextImageFileRead=1;async function imageFile(url2){return(await imageFileAnswer(url2)).bytes}function imageFileAnswer(url2,part){const id2=nextImageFileRead++;return new Promise((resolve2,reject)=>{pendingImageFiles.set(id2,{resolve:resolve2,reject});send({type:"image-file-read",id:id2,url:url2,...part?{part}:{}})})}function imagePack(key){const id2=nextImagePackRead++;return new Promise((resolve2,reject)=>{pendingImagePacks.set(id2,{resolve:resolve2,reject});send({type:"image-pack-read",id:id2,key})})}function moduleCacheOver(shared,sharedFilesystem,project){const home=key=>`${PACKAGES_ROOT}/.modules/${key}`;const keepShared=async(source,code3)=>{await scope3.navigator.locks.request(PACKAGES_LOCK,{mode:"exclusive"},async()=>{await shared.refresh();if(!shared.entries.has(source))sharedFilesystem.writeFileSync(source,code3);else{const now=new Date;sharedFilesystem.utimesSync(source,now,now)}if(shared.logBytes>8*1024*1024){console.warn(`[modules] the shared store checkpoints at ${Math.round(shared.logBytes/1024)} KiB of log, after ${source}`);await shared.checkpoint()}})};const fromImage=(key,source)=>{let pending=fetchingPacks.get(key);if(pending)return pending;pending=(async()=>{try{await keepShared(source,await imagePack(key));return true}catch(cause){if(isInstallRefused(cause))throw cause;const message=cause instanceof Error?cause.message:String(cause);if(/\b4\d\d\b|not found|no pack/iu.test(message))installTrap({door:"image pack",subject:`the image names a pack for ${key} its origin cannot give: ${message}`,detail:{key}});throw new Error(`The image's pack for ${key} could not be read this time (${message}); reloading the page tries again.`)}finally{fetchingPacks.delete(key)}})();fetchingPacks.set(key,pending);return pending};const reportedMisses=new Set;const reportMiss=(key,carried)=>{if(reportedMisses.has(key))return;reportedMisses.add(key);console.log(carried?`[modules] this tab's store has no pack at ${key}; fetching the one the image's index names.`:`[modules] neither this tab's store nor the image has a pack at ${key}; the tab builds it.`)};return{link:async(key,target)=>{const source=home(key);let fetched=false;if(!shared.entries.has(source)&&imagePacksKnown)await imagePacksKnown;if(!shared.entries.has(source)){reportMiss(key,imagePacks.has(key));if(!imagePacks.has(key))return false;if(!await fromImage(key,source))return false;fetched=true}project.linkShared(source,target);if(!project.existsSync(target)){console.warn(`[modules] linked ${key} to ${target} and it is not there: fetched ${fetched}, shared holds ${shared.entries.has(source)}, the project's parent ${project.existsSync(target.slice(0,target.lastIndexOf("/")))}`)}return true},keep:async(key,code3,target)=>{const source=home(key);await keepShared(source,code3);project.linkShared(source,target)}}}function requiredContainer(){if(!container)throw new Error("Browser Node host is not initialized.");return container}function installFilesystemForwarding(vfs2){const suppressed=path3=>{if(!suppressFilesystemEvents)return false;if(importingFilesystemRoot===void 0)return true;const normalized=normalizeStorePath2(path3);return normalized===importingFilesystemRoot||normalized.startsWith(`${importingFilesystemRoot==="/"?"":importingFilesystemRoot}/`)};vfs2.on("change",path3=>{if(suppressed(path3)||!vfs2.existsSync(path3))return;const stat2=vfs2.statSync(path3);queueIndexForwarding([path3,stat2.isDirectory()?"directory":"file",stat2.isDirectory()?0:stat2.size,stat2.mode&4095,stat2.mtimeMs])});vfs2.on("delete",path3=>{if(!suppressed(path3))queueIndexForwarding([path3,null])});installPortForwarding()}function installPortForwarding(){const bridge=vfsServerBridge();const register=bridge.registerServer.bind(bridge);const unregister=bridge.unregisterServer.bind(bridge);bridge.registerServer=((server,serverPort,hostname2)=>{console.log(`[boot-trace] ${JSON.stringify({event:"port-register",at:Date.now(),port:serverPort,token:container?.currentProcessToken(),imageBlocked:imageBlocked()})}`);register(server,serverPort,hostname2);if(netListeners.has(serverPort))return;send({type:"port",action:"open",port:serverPort,...hostname2?{hostname:hostname2}:{}})});bridge.unregisterServer=(serverPort=>{console.log(`[boot-trace] ${JSON.stringify({event:"port-unregister",at:Date.now(),port:serverPort,token:container?.currentProcessToken(),imageBlocked:imageBlocked()})}`);unregister(serverPort);if(netListeners.has(serverPort))return;send({type:"port",action:"close",port:serverPort})})}var pendingIndexForwarding=[];function queueIndexForwarding(change){pendingIndexForwarding.push(change);if(filesystemForwardingScheduled)return;filesystemForwardingScheduled=true;queueMicrotask(flushFilesystemForwarding)}function storeEntryOf(vfs2,path3){if(!vfs2.existsSync(path3))return[path3,null];const stat2=vfs2.lstatSync(path3);const type2=stat2.isDirectory()?"directory":stat2.isSymbolicLink()?"symlink":"file";return[path3,type2,type2==="file"?stat2.size:0,stat2.mode&4095,stat2.mtimeMs]}function applyStoreOperation(vfs2,operation){const withModes=vfs2;if(operation.op==="write"){writeFile(vfs2,operation.path,new Uint8Array(operation.bytes));if(operation.mode!==void 0)withModes.chmodSync?.(operation.path,operation.mode);withModes.utimesSync?.(operation.path,new Date(operation.mtimeMs),new Date(operation.mtimeMs))}else if(operation.op==="mkdir"){if(!vfs2.existsSync(operation.path))vfs2.mkdirSync(operation.path,{recursive:true})}else if(operation.op==="remove"){removePath(vfs2,operation.path)}else if(operation.op==="rename"){vfs2.renameSync(operation.from,operation.to)}else if(operation.op==="chmod"){withModes.chmodSync?.(operation.path,operation.mode)}else if(operation.op==="utimes"){withModes.utimesSync?.(operation.path,new Date(operation.mtimeMs),new Date(operation.mtimeMs))}}function flushFilesystemForwarding(){filesystemForwardingScheduled=false;const changes=pendingIndexForwarding.splice(0);for(let offset2=0;offset2<changes.length;offset2+=4096){send({type:"fs-index",changes:changes.slice(offset2,offset2+4096)})}}function vfsServerBridge(){return requiredContainer().serverBridge}var netListeners=new Map;var netSockets=new Map;var netListenerChanges=new Set;var nextNetSocket=1;var pageNetHost={ports:()=>netListeners.keys(),subscribe:listener=>{netListenerChanges.add(listener);return()=>{netListenerChanges.delete(listener)}},connect:(port2,socket)=>{if(!netListeners.has(port2)){socket.destroy();return}forwardNetSocket(port2,socket)}};function forwardNetSocket(port2,socket){const id2=nextNetSocket++;netSockets.set(id2,socket);socket.on("data",chunk=>{if(!netSockets.has(id2))return;const buffer2=Uint8Array.from(chunk).buffer;send({type:"net-guest-data",socket:id2,chunk:buffer2},[buffer2])});const close2=()=>{if(!netSockets.delete(id2))return;send({type:"net-guest-end",socket:id2})};socket.on("end",close2);socket.on("close",close2);socket.on("error",()=>void 0);send({type:"net-connect",port:port2,socket:id2})}function handleNetMessage(message){if(message.type==="listen-net"){const host2=requiredContainer();if(!host2.listenNet)return;netListeners.get(message.port)?.();netListeners.set(message.port,()=>{});try{const unlisten=host2.listenNet(message.port,socket2=>forwardNetSocket(message.port,socket2));netListeners.set(message.port,unlisten)}catch(error){netListeners.delete(message.port);throw error}for(const listener of netListenerChanges)listener(message.port,true);return}if(message.type==="unlisten-net"){netListeners.get(message.port)?.();netListeners.delete(message.port);for(const listener of netListenerChanges)listener(message.port,false);return}const socket=netSockets.get(message.socket);if(!socket)return;if(message.type==="net-data")socket.write(new Uint8Array(message.chunk),()=>send({type:"net-taken",socket:message.socket}));else{socket.end();netSockets.delete(message.socket)}}var pendingChildren=new Map;var pendingChildInput=new Map;var pendingChildFdInput=new Map;var childFdKey=(id2,fd2)=>`${id2}:${fd2}`;var childChunkBytes=64*1024;function validChildFd(fd2){return typeof fd2==="number"&&Number.isInteger(fd2)&&fd2>=3&&fd2<=63}function childDescriptorNumbers(descriptors){if(descriptors===void 0)return void 0;const fds=Object.keys(descriptors).map(Number);if(!fds.every(validChildFd))throw new Error("Child process descriptors must be integers from 3 through 63.");return fds.length>0?fds.sort((left,right)=>left-right):void 0}var nextChildId=1;var launchPorts=new Map;var heldRuns=new Set;function runPorts(id2){const before=launchPorts.get(id2);if(!before)return[];return vfsServerBridge().getServerPorts().filter(port2=>!before.has(port2))}function closeRunServers(id2){const bridge=vfsServerBridge();for(const port2 of runPorts(id2)){const entry=bridge.servers?.get(port2);try{entry?.server?.close?.()}catch{}try{bridge.unregisterServer(port2)}catch{}}}async function workSettled(id2,held=false){const token=String(id2);const engine=container;const nativeSetTimeout=globalThis.__browserRuntimeNativeSetTimeout??setTimeout;const tick=()=>new Promise(resolve2=>nativeSetTimeout.call(globalThis,resolve2,50));const ports2=()=>Math.max(engine?.processPorts?.(token).length??0,runPorts(id2).length);if(held&&activeRuns.has(id2)){const deadline=Date.now()+500;while(Date.now()<deadline&&ports2()===0&&activeRuns.has(id2))await tick()}const owned=()=>{const timers=engine?.pendingTimers?.(token)??0;if(timers>0)return true;if(held&&ports2()>0)return true;return[...pendingChildren.values()].some(child=>child.owner===id2&&child.hold?.value!==false)};while(owned()&&activeRuns.has(id2))await tick()}function spawnedArgv(options){const given=options.__browserRuntimeSpawnArgs;if(!Array.isArray(given)||given.length===0)return void 0;return given.every(word=>typeof word==="string")?[...given]:void 0}function requestChild(command,options,fixedOwner,fixedArgv,nodeProcess){return new Promise((resolve2,reject)=>{assertWorkerActive();options.signal?.throwIfAborted();const descriptorFds=childDescriptorNumbers(options.descriptors);if(!childInputSupported&&(options.stdin!==void 0||options.stdinStream||options.terminal||options.executablePath!==void 0||descriptorFds)){throw new Error("The holder did not negotiate child-process input and terminal support.")}const id2=nextChildId++;const inputController=new AbortController;let removeResize;let inputFailure;const token=container?.currentProcessToken()??null;let owner=fixedOwner??(token===null?null:Number(token));if(owner!==null&&!activeRuns.has(owner)){const engine=enginePids();owner=(engine?owningRun(token,activeRuns,engine.runPid,engine.processByPid):void 0)??null}if(owner===null){let latest;for(const[id3,run]of activeRuns)if(!latest||run.startedAt>latest.startedAt)latest={id:id3,startedAt:run.startedAt};owner=latest?.id??null}const rejectFdInputs=cause=>{for(const fd2 of descriptorFds??[]){const key=childFdKey(id2,fd2);const input=pendingChildFdInput.get(key);pendingChildFdInput.delete(key);input?.reject(cause)}};const abort=()=>{inputController.abort(options.signal?.reason);const input=pendingChildInput.get(id2);pendingChildInput.delete(id2);input?.reject(inputController.signal.reason);rejectFdInputs(inputController.signal.reason);if(!pendingChildren.has(id2))return;try{send({type:"child-abort",id:id2})}catch(cause){const pending=pendingChildren.get(id2);pendingChildren.delete(id2);pending?.reject(cause instanceof Error?cause:new Error(String(cause)))}};const cleanup=()=>{options.signal?.removeEventListener("abort",abort);inputController.abort();const input=pendingChildInput.get(id2);pendingChildInput.delete(id2);input?.reject(new DOMException("The child process stopped.","AbortError"));rejectFdInputs(new DOMException("The child process stopped.","AbortError"));try{removeResize?.()}catch(cause){console.error("Child terminal subscription cleanup failed.",cause)}removeResize=void 0};console.log(`[boot-trace] ${JSON.stringify({event:"child-start",at:Date.now(),id:id2,owner,token,program:programFromCommand(command),imageBlocked:imageBlocked()})}`);pendingChildren.set(id2,{owner,...options.hold?{hold:options.hold}:{},...options.onStdout?{onStdout:options.onStdout}:{},...options.onStderr?{onStderr:options.onStderr}:{},...descriptorFds&&options.descriptors?{descriptors:options.descriptors}:{},resolve:result=>{cleanup();if(inputFailure)reject(inputFailure);else resolve2(result)},reject:cause=>{cleanup();reject(inputFailure??cause)}});options.signal?.addEventListener("abort",abort,{once:true});const parentCwd=owner!==null?activeRuns.get(owner)?.cwd??"/":"/";const cwd=options.cwd===void 0?parentCwd:options.cwd.startsWith("/")?options.cwd:`${parentCwd.replace(/\/$/u,"")}/${options.cwd}`.replace(/\/\.\//gu,"/");const argv=fixedArgv?[...fixedArgv]:spawnedArgv(options);try{send({type:"child-run",...options.filesystemPolicy?{filesystemPolicy:options.filesystemPolicy}:{},id:id2,owner,command,...argv?{argv}:{},...nodeProcess?{nodeProcess}:{},cwd,...options.executablePath!==void 0?{executablePath:options.executablePath}:{},...options.stdin!==void 0?{stdin:options.stdin}:{},...options.stdinStream?{liveStdin:true}:{},...options.terminal?{terminal:{columns:options.terminal.columns,rows:options.terminal.rows}}:{},...options.env?{env:{...options.env}}:{},...descriptorFds?{descriptors:descriptorFds}:{}});if(options.stdinStream){void forwardBrowserProcessInput(options.stdinStream,async chunk=>{for(let offset2=0;offset2<chunk.byteLength;offset2+=64*1024){inputController.signal.throwIfAborted();const bytes2=Uint8Array.from(chunk.subarray(offset2,offset2+64*1024)).buffer;await new Promise((resolve3,reject2)=>{pendingChildInput.set(id2,{resolve:resolve3,reject:reject2});try{send({type:"child-stdin",id:id2,bytes:bytes2},[bytes2])}catch(cause){pendingChildInput.delete(id2);reject2(cause)}})}},inputController.signal).then(()=>{if(pendingChildren.has(id2)&&!inputController.signal.aborted)send({type:"child-stdin-end",id:id2})}).catch(cause=>{if(inputController.signal.aborted||!pendingChildren.has(id2))return;inputFailure=cause instanceof Error?cause:new Error(String(cause));abort()})}for(const fd2 of descriptorFds??[]){const key=childFdKey(id2,fd2);void forwardBrowserProcessInput(options.descriptors[fd2].input,async chunk=>{for(let offset2=0;offset2<chunk.byteLength;offset2+=childChunkBytes){inputController.signal.throwIfAborted();const bytes2=Uint8Array.from(chunk.subarray(offset2,offset2+childChunkBytes)).buffer;await new Promise((resolve3,reject2)=>{pendingChildFdInput.set(key,{resolve:resolve3,reject:reject2});try{send({type:"child-fd",id:id2,fd:fd2,bytes:bytes2},[bytes2])}catch(cause){pendingChildFdInput.delete(key);reject2(cause)}})}},inputController.signal).then(()=>{if(pendingChildren.has(id2)&&!inputController.signal.aborted)send({type:"child-fd-end",id:id2,fd:fd2})}).catch(cause=>{if(inputController.signal.aborted||!pendingChildren.has(id2))return;inputFailure=cause instanceof Error?cause:new Error(String(cause));abort()})}removeResize=options.terminal?.onResize?.((columns,rows)=>{if(pendingChildren.has(id2)&&!inputController.signal.aborted)send({type:"child-resize",id:id2,columns,rows})})}catch(cause){try{send({type:"child-abort",id:id2})}catch{}const pending=pendingChildren.get(id2);pendingChildren.delete(id2);pending?.reject(cause instanceof Error?cause:new Error(String(cause)))}})}function installChildProcessBridge(){const pending=token=>{const owner=Number(token);let count=0;for(const child of pendingChildren.values())if(child.owner===owner&&child.hold?.value!==false)count+=1;return count};Reflect.set(globalThis,executorSymbol,{bypass:0,run:requestChild,pending})}function installRootNodeEntryBridge(){const preparedLimits=Object.freeze({maxBytes:4*1024*1024,maxEntries:1024});const streamLimits=Object.freeze({maxHandles:1024,maxReadChunkBytes:64*1024,maxQueuedBytes:64*1024,maxQueuedHandles:16,maxPendingWriteBytes:1024*1024});const runtimeFiles=new VirtualFS;rootRuntimeFiles=runtimeFiles;const registry=ownerProcessRegistryScope();installNodeProcessHost({run:launch=>{const active2=requiredContainer();if(launch.inherited.length)throw new Error("A store-owner Node launch cannot inherit guest stream descriptors.");if(!executionConfiguration)throw new Error("Node process execution has no worker configuration.");const engine=enginePids();const owner=activeRuns.has(Number(launch.token))?Number(launch.token):engine?owningRun(launch.token,activeRuns,engine.runPid,engine.processByPid):void 0;if(owner===void 0)throw new Error("Node process execution has no owning command.");const attribution=networkProgramNow(activeRuns,launch.token,token=>engine?.runPid(token),pid=>engine?.processByPid(pid));const streams2=launch.streams;return nodeProcesses.run(renderCommand(["node",...launch.argv]),{cwd:launch.cwd,env:launch.env,...launch.stdin!==void 0?{stdin:launch.stdin}:{},...launch.stdinStream?{stdinStream:launch.stdinStream}:{},...streams2?.signal?{signal:streams2.signal}:{},...streams2?.terminal?{terminal:streams2.terminal}:{},...streams2?.onStdout?{onStdout:streams2.onStdout}:{},...streams2?.onStderr?{onStderr:streams2.onStderr}:{}},{filesystem:launch.filesystem,...storeReadsFor(launch.filesystem),workerUrl:scope3.location.href,configuration:executionConfiguration,...moduleCacheOption(active2.vfs),processAdmission:{source:registry,token:launch.token},nativeStreams:{limits:streamLimits,inherited:[]},nodeProcess:{preparedLimits},preparedFiles:captureNodePreparedFiles(runtimeFiles,preparedLimits),serverBridge:active2.serverBridge,net:pageNetHost,hostPorts:hostPortsHost,runChild:(command,options,argv)=>requestChild(command,options,owner,argv),http:request=>brokerHttpOnce(request,attribution)})}})}function installNodeEntryBridge(localToken2,preparedLimits){installNodeProcessHost({run:launch=>{const argv=["node",...launch.argv];const streams2=launch.streams;return requestChild(renderCommand(argv),{cwd:launch.cwd,env:launch.env,hold:{value:false},...launch.stdin!==void 0?{stdin:launch.stdin}:{},...launch.stdinStream?{stdinStream:launch.stdinStream}:{},...streams2?.signal?{signal:streams2.signal}:{},...streams2?.terminal?{terminal:streams2.terminal}:{},...streams2?.onStdout?{onStdout:streams2.onStdout}:{},...streams2?.onStderr?{onStderr:streams2.onStderr}:{},...invocationPolicy?{filesystemPolicy:invocationPolicy}:{}},Number(localToken2),argv,{token:launch.token,inherited:launch.inherited.map(({fd:fd2,handle})=>({fd:fd2,id:handle.id})),preparedFiles:invocationFiles?captureNodePreparedFiles(invocationFiles.runtimeFiles,preparedLimits):[]})}},localToken2)}async function brokerHttpOnce(request,attribution,context2){assertWorkerActive();request.signal.throwIfAborted();const id2=nextFetchId++;const headers=request.headers;assertWorkerActive();request.signal.throwIfAborted();const result=new Promise((resolve2,reject)=>pendingFetches.set(id2,{method:request.method,resolve:resolve2,reject}));const abort=()=>{const pending=pendingFetches.get(id2);if(pending){pendingFetches.delete(id2);pending.reject(request.signal.reason??new DOMException("The request was cancelled.","AbortError"))}else{const stream=responseStreams.get(id2);if(!stream&&!fetchActivities.has(id2))return;responseStreams.delete(id2);stream?.error(request.signal.reason??new DOMException("The request was cancelled.","AbortError"))}try{send({type:"fetch-abort",id:id2})}catch{}fetchAbortCleanup.get(id2)?.();fetchAbortCleanup.delete(id2)};if(context2){try{const activity2=context2.begin(abort);fetchActivities.set(id2,{activity:activity2,headersDone:activity2.hold(),pulls:[],cancel:abort})}catch(cause){pendingFetches.delete(id2);throw cause}}request.signal.addEventListener("abort",abort,{once:true});fetchAbortCleanup.set(id2,()=>{request.signal.removeEventListener("abort",abort);fetchActivities.get(id2)?.activity.release();fetchActivities.delete(id2)});try{const body=request.body;send({type:"fetch",id:id2,program:attribution.program,attributed:attribution.attributed,activePrograms:attribution.activePrograms,...attribution.pid!==void 0?{pid:attribution.pid}:{},url:request.url,method:request.method,headers,...request.profile?{profile:request.profile}:{},...body?{body}:{}},body instanceof ReadableStream?[body]:[])}catch(cause){pendingFetches.get(id2)?.reject(cause instanceof Error?cause:new Error(String(cause)));pendingFetches.delete(id2);fetchAbortCleanup.get(id2)?.();fetchAbortCleanup.delete(id2)}if(request.signal.aborted)abort();return result}async function brokerFetch(input,init,fixedAttribution,context2){let request=new Request(input,init);const attribution=fixedAttribution??attributionNow();let body=request.body??void 0;if(body&&requestHasStaticBody(request)){let stopped2=false;const activity2=context2?.begin(()=>{stopped2=true});const done=activity2?.hold();try{body=await request.blob();request.signal.throwIfAborted();if(stopped2)throw new DOMException("The requesting process has ended.","AbortError")}finally{done?.();activity2?.release()}}for(let redirects=0;;redirects++){const result=await brokerHttpOnce({url:request.url,method:request.method,headers:[...request.headers.entries()],...body?{body}:{},signal:request.signal},attribution,context2);const response=new Response(result.body,{status:result.status,statusText:result.statusText,headers:result.headers});if(![301,302,303,307,308].includes(response.status))return response;if(request.redirect==="manual")return response;if(request.redirect==="error"){await response.body?.cancel().catch(()=>void 0);throw new TypeError("Redirects are disabled for this request.")}if(redirects>=20){await response.body?.cancel().catch(()=>void 0);throw new TypeError("Too many redirects.")}const location2=response.headers.get("location");if(!location2)return response;const nextUrl=new URL(location2,request.url);let method=request.method;const headers=new Headers(request.headers);if(response.status===303&&method!=="HEAD"||(response.status===301||response.status===302)&&method==="POST"){method="GET";body=void 0;for(const name of["content-encoding","content-language","content-length","content-location","content-type"])headers.delete(name)}else if(body instanceof ReadableStream){await response.body?.cancel().catch(()=>void 0);throw new TypeError("A streamed request body cannot be replayed across a redirect.")}if(new URL(request.url).origin!==nextUrl.origin){for(const name of["authorization","cookie","proxy-authorization"])headers.delete(name)}await response.body?.cancel().catch(()=>void 0);request=new Request(nextUrl,{method,headers,...body?{body}:{},redirect:request.redirect,signal:request.signal})}}var hostPorts=new Set;var hostPortListeners=new Set;var hostPortsHost={current:()=>hostPorts,subscribe:listener=>{hostPortListeners.add(listener);return()=>{hostPortListeners.delete(listener)}}};var RefusedWebSocket=class extends EventTarget{static CONNECTING=0;static OPEN=1;static CLOSING=2;static CLOSED=3;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;url;protocol="";extensions="";bufferedAmount=0;binaryType="blob";readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;constructor(url2,_protocols){super();this.url=new URL(url2).href;queueMicrotask(()=>{if(this.readyState===3)return;this.readyState=3;const error=Object.assign(new Event("error"),{message:`WebSocket to ${this.url} refused: a sandboxed program has no WebSocket egress.`});this.onerror?.(error);this.dispatchEvent(error);const close2=new CloseEvent("close",{code:1006,reason:"",wasClean:false});this.onclose?.(close2);this.dispatchEvent(close2)})}send(){throw new DOMException("The WebSocket is not open.","InvalidStateError")}close(){this.readyState=3}};function installNetworkBroker(){installFetchTransport((input,init,context2)=>brokerFetch(input,init,attributionNow(),context2));installHttpClientTransport(()=>{const attribution=attributionNow();return request=>brokerHttpOnce(request,attribution)},{hostPorts:()=>hostPorts});Object.defineProperty(globalThis,"fetch",{value:brokerFetch,configurable:false,writable:false});for(const name of["XMLHttpRequest","EventSource","BroadcastChannel","SharedWorker"]){try{Object.defineProperty(globalThis,name,{value:void 0,configurable:false,writable:false})}catch{}}try{Object.defineProperty(globalThis,"WebSocket",{value:RefusedWebSocket,configurable:false,writable:false})}catch{}Reflect.set(globalThis,executorSymbol,void 0)}var liveStdins=new Map;async function installTypeStripper(url2){const glue=await import(url2);globalThis.__substrateStripTypes=typeStripperFrom(glue.default).strip}var webSocketRelay;function openLiveStdin(id2){const encoder7=new TextEncoder;const queue=[];let closed=false;let wake;const notify=()=>{const resolve2=wake;wake=void 0;resolve2?.()};const stdin={push:data2=>{if(closed)return;queue.push({bytes:encoder7.encode(data2)});notify()},write:bytes2=>{if(closed)return Promise.reject(new Error("Process input is closed."));if(bytes2.byteLength>64*1024||queue.some(entry=>entry.consumed))return Promise.reject(new Error("Process input requires consumed chunks of at most 64 KiB."));const consumed=new Promise((resolve2,reject)=>{queue.push({bytes:Uint8Array.from(bytes2),consumed:{resolve:resolve2,reject}})});notify();return consumed},close:(discard=false)=>{closed=true;if(discard)for(const entry of queue.splice(0))entry.consumed?.reject(new DOMException("Process input was cancelled.","AbortError"));notify()},async*[Symbol.asyncIterator](){for(;;){if(queue.length>0){const entry=queue.shift();entry.consumed?.resolve();yield entry.bytes;continue}if(closed)return;await new Promise(resolve2=>{wake=resolve2})}}};liveStdins.set(id2,stdin);return stdin}var terminals=new Map;function openTerminal(id2,size){const listeners=new Set;const terminal={columns:size.columns,rows:size.rows,onResize:listener=>{listeners.add(listener);return()=>{listeners.delete(listener)}},resize:(columns,rows)=>{terminal.columns=columns;terminal.rows=rows;for(const listener of listeners)listener(columns,rows)}};terminals.set(id2,terminal);return terminal}function writeFile(vfs2,path3,bytes2){const parent=path3.slice(0,path3.lastIndexOf("/"))||"/";if(parent!=="/"&&!vfs2.existsSync(parent))vfs2.mkdirSync(parent,{recursive:true});vfs2.writeFileSync(path3,bytes2)}function removePath(vfs2,path3){if(!vfs2.existsSync(path3))return;if(vfs2.statSync(path3).isFile()){vfs2.unlinkSync(path3);return}for(const name of vfs2.readdirSync(path3))removePath(vfs2,`${path3==="/"?"":path3}/${name}`);if(path3!=="/")vfs2.rmdirSync(path3)}function sendResult(id2,result){console.log(`[boot-trace] ${JSON.stringify({event:"run-result",at:Date.now(),id:id2,exitCode:result.exitCode,imageBlocked:imageBlocked()})}`);const signal=result.signal;send({type:"result",id:id2,stdout:result.stdout,stderr:result.stderr,exitCode:result.exitCode,...typeof signal==="string"?{signal}:{}})}function sendError(id2,cause){const error=cause instanceof Error?cause:new Error(String(cause));send({type:"error",id:id2,error:error.message,...error.stack?{stack:error.stack}:{}})}function send(message,transfer2=[]){port?.postMessage(message,transfer2)}async function fetchPrismaSchemaParser(vfs2,urls){try{const[glue,wasm2]=await Promise.all([fetch(new URL(urls.prismaSchemaModuleUrl,scope3.location.href).href).then(response=>{if(!response.ok)throw new Error(`${response.status}`);return response.text()}),fetch(new URL(urls.prismaSchemaWasmUrl,scope3.location.href).href).then(response=>{if(!response.ok)throw new Error(`${response.status}`);return response.arrayBuffer()})]);vfs2.mkdirSync(PRISMA_SCHEMA_DIRECTORY,{recursive:true});vfs2.writeFileSync(`${PRISMA_SCHEMA_DIRECTORY}/prisma_schema_build.js`,glue);vfs2.writeFileSync(`${PRISMA_SCHEMA_DIRECTORY}/prisma_schema_build_bg.wasm`,new Uint8Array(wasm2))}catch(cause){console.warn(`[stand-ins] Prisma's schema parser did not reach the runtime: ${cause instanceof Error?cause.message:String(cause)}`)}}function depth3(path3){let segments=1;for(let index2=0;index2<path3.length;index2+=1)if(path3.charCodeAt(index2)===47)segments+=1;return segments}configureNodeExecutionWorker({});
6427
6427
  /*! Bundled license information:
6428
6428
 
6429
6429
  pako/dist/pako.esm.mjs: