just-bash 3.2.0 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +65 -0
- package/README.md +47 -0
- package/dist/ast/types.d.ts +4 -1
- package/dist/bin/chunks/{chunk-QF7PPON7.js → chunk-5SR55TXB.js} +10 -10
- package/dist/bin/{shell/chunks/chunk-TL4JI2SL.js → chunks/chunk-6UK23ZFT.js} +17 -18
- package/dist/bin/chunks/{chunk-XBB73LFB.js → chunk-CMTQFWZK.js} +2 -2
- package/dist/bin/chunks/{chunk-YMELOXDK.js → chunk-D5G3L4PR.js} +8 -8
- package/dist/bin/chunks/{chunk-PRKSLEHG.js → chunk-DKIOFM35.js} +1 -1
- package/dist/bin/chunks/chunk-IJIJAQBT.js +12 -0
- package/dist/bin/{shell/chunks/chunk-NQQ3X7MZ.js → chunks/chunk-KXWWWQZK.js} +1 -1
- package/dist/bin/chunks/{chunk-3HUI54BW.js → chunk-TROO33BG.js} +1 -1
- package/dist/bin/chunks/chunk-USMDLXMM.js +21 -0
- package/dist/bin/{shell/chunks/chunk-JQER3HUP.js → chunks/chunk-XAVWLYZR.js} +1 -1
- package/dist/bin/chunks/{echo-4OUEL7QB.js → echo-NYDCCFWB.js} +1 -1
- package/dist/bin/chunks/{flag-coverage-WGSE667D.js → flag-coverage-EB3DK32J.js} +1 -1
- package/dist/bin/chunks/{grep-CMT2H2S7.js → grep-73YHJEX4.js} +1 -1
- package/dist/bin/{shell/chunks/jq-ACCMBTSD.js → chunks/jq-AO5GTPN4.js} +1 -1
- package/dist/bin/chunks/js-exec-worker.js +56 -20
- package/dist/bin/{shell/chunks/printf-F2KOCULO.js → chunks/printf-CNXNRQ3I.js} +1 -1
- package/dist/bin/chunks/python3-N252MJV6.js +14 -0
- package/dist/bin/{shell/chunks/rg-JRKJ6I4X.js → chunks/rg-OGGL3RIE.js} +1 -1
- package/dist/bin/chunks/{sqlite3-ZXF6BGDW.js → sqlite3-FEUFATVW.js} +1 -1
- package/dist/bin/chunks/worker.js +17 -1
- package/dist/bin/chunks/{xan-D6US4ZGL.js → xan-Q52EBQYW.js} +1 -1
- package/dist/bin/chunks/{yq-EYV7HLKK.js → yq-UA5NX5RT.js} +1 -1
- package/dist/bin/just-bash.js +391 -389
- package/dist/bin/shell/chunks/{chunk-QF7PPON7.js → chunk-5SR55TXB.js} +10 -10
- package/dist/bin/{chunks/chunk-TL4JI2SL.js → shell/chunks/chunk-6UK23ZFT.js} +17 -18
- package/dist/bin/shell/chunks/{chunk-XBB73LFB.js → chunk-CMTQFWZK.js} +2 -2
- package/dist/bin/shell/chunks/{chunk-YMELOXDK.js → chunk-D5G3L4PR.js} +8 -8
- package/dist/bin/shell/chunks/{chunk-PRKSLEHG.js → chunk-DKIOFM35.js} +1 -1
- package/dist/bin/shell/chunks/chunk-IJIJAQBT.js +12 -0
- package/dist/bin/{chunks/chunk-NQQ3X7MZ.js → shell/chunks/chunk-KXWWWQZK.js} +1 -1
- package/dist/bin/shell/chunks/{chunk-3HUI54BW.js → chunk-TROO33BG.js} +1 -1
- package/dist/bin/shell/chunks/chunk-USMDLXMM.js +21 -0
- package/dist/bin/{chunks/chunk-JQER3HUP.js → shell/chunks/chunk-XAVWLYZR.js} +1 -1
- package/dist/bin/shell/chunks/{echo-4OUEL7QB.js → echo-NYDCCFWB.js} +1 -1
- package/dist/bin/shell/chunks/{flag-coverage-WGSE667D.js → flag-coverage-EB3DK32J.js} +1 -1
- package/dist/bin/shell/chunks/{grep-CMT2H2S7.js → grep-73YHJEX4.js} +1 -1
- package/dist/bin/{chunks/jq-ACCMBTSD.js → shell/chunks/jq-AO5GTPN4.js} +1 -1
- package/dist/bin/{chunks/printf-F2KOCULO.js → shell/chunks/printf-CNXNRQ3I.js} +1 -1
- package/dist/bin/shell/chunks/python3-N252MJV6.js +14 -0
- package/dist/bin/{chunks/rg-JRKJ6I4X.js → shell/chunks/rg-OGGL3RIE.js} +1 -1
- package/dist/bin/shell/chunks/{sqlite3-ZXF6BGDW.js → sqlite3-FEUFATVW.js} +1 -1
- package/dist/bin/shell/chunks/{xan-D6US4ZGL.js → xan-Q52EBQYW.js} +1 -1
- package/dist/bin/shell/chunks/{yq-EYV7HLKK.js → yq-UA5NX5RT.js} +1 -1
- package/dist/bin/shell/shell.js +396 -394
- package/dist/bundle/browser.js +836 -823
- package/dist/bundle/chunks/{chunk-RAHPENCM.js → chunk-3ZBJCAAR.js} +1 -1
- package/dist/bundle/chunks/{chunk-AMLHAS2N.js → chunk-4AKAIZPW.js} +9 -9
- package/dist/bundle/chunks/{chunk-6SHYIICL.js → chunk-AGH5UJJI.js} +2 -2
- package/dist/bundle/chunks/{chunk-NOPXHH6G.js → chunk-EZDB7TGH.js} +1 -1
- package/dist/bundle/chunks/chunk-FC5NW7U4.js +11 -0
- package/dist/bundle/chunks/{chunk-5KGKXQF6.js → chunk-FHFPWM4W.js} +1 -1
- package/dist/bundle/chunks/chunk-H3PXMIY3.js +20 -0
- package/dist/bundle/chunks/{chunk-EWWPEE2G.js → chunk-IHGFM3FN.js} +17 -18
- package/dist/bundle/chunks/{chunk-65Z4QURM.js → chunk-J5G3ZBEK.js} +8 -8
- package/dist/bundle/chunks/{chunk-WENIVVEE.js → chunk-LTCWFMCI.js} +1 -1
- package/dist/bundle/chunks/{echo-HZOVZAPR.js → echo-PLLZYM2L.js} +1 -1
- package/dist/bundle/chunks/{flag-coverage-THYQHOT3.js → flag-coverage-UV7GI2DF.js} +1 -1
- package/dist/bundle/chunks/{grep-S6SNTIHZ.js → grep-UDCQDUQK.js} +1 -1
- package/dist/bundle/chunks/{jq-D6N4QCAJ.js → jq-B5324QOX.js} +1 -1
- package/dist/bundle/chunks/js-exec-worker.js +56 -20
- package/dist/bundle/chunks/{printf-QHD2JRWQ.js → printf-V42QCPHL.js} +1 -1
- package/dist/bundle/chunks/python3-ETPBGJP3.js +13 -0
- package/dist/bundle/chunks/{rg-OUJZ5DH6.js → rg-XCX2J2RF.js} +1 -1
- package/dist/bundle/chunks/{sqlite3-WWZJZW37.js → sqlite3-ZTQJIC3G.js} +1 -1
- package/dist/bundle/chunks/worker.js +17 -1
- package/dist/bundle/chunks/{xan-KKPV2TJ3.js → xan-EGU5VRRP.js} +1 -1
- package/dist/bundle/chunks/{yq-ZGB3W46S.js → yq-FMWLA3S2.js} +1 -1
- package/dist/bundle/index.cjs +1026 -1014
- package/dist/bundle/index.js +391 -389
- package/dist/commands/python3/worker.d.ts +1 -0
- package/dist/commands/query-engine/evaluator.d.ts +8 -0
- package/dist/fs/read-write-fs/read-write-fs.d.ts +42 -1
- package/dist/interpreter/builtin-dispatch.d.ts +9 -2
- package/dist/interpreter/builtins/eval.d.ts +7 -1
- package/dist/interpreter/control-flow.d.ts +1 -1
- package/dist/interpreter/fd-table.d.ts +130 -0
- package/dist/interpreter/functions.d.ts +3 -1
- package/dist/interpreter/helpers/word-matching.d.ts +0 -10
- package/dist/interpreter/interpreter.d.ts +7 -0
- package/dist/interpreter/numeric-fd-redirects.d.ts +8 -0
- package/dist/interpreter/process-substitution.d.ts +62 -0
- package/dist/interpreter/redirections.d.ts +33 -37
- package/dist/interpreter/subshell-group.d.ts +10 -2
- package/dist/interpreter/types.d.ts +38 -1
- package/dist/network/dns-pin.d.ts +11 -0
- package/dist/parser/expansion-parser.d.ts +3 -1
- package/dist/parser/lexer.d.ts +7 -9
- package/dist/parser/parser-substitution.d.ts +13 -4
- package/dist/parser/parser.d.ts +18 -4
- package/dist/parser/types.d.ts +6 -0
- package/dist/parser/word-parser.d.ts +2 -0
- package/dist/types.d.ts +6 -0
- package/package.json +1 -1
- package/dist/bin/chunks/chunk-P6NPCASY.js +0 -11
- package/dist/bin/chunks/chunk-WYTPLN2M.js +0 -11
- package/dist/bin/chunks/python3-AYUQQRCR.js +0 -14
- package/dist/bin/shell/chunks/chunk-P6NPCASY.js +0 -11
- package/dist/bin/shell/chunks/chunk-WYTPLN2M.js +0 -11
- package/dist/bin/shell/chunks/python3-AYUQQRCR.js +0 -14
- package/dist/bundle/chunks/chunk-VECGTAPW.js +0 -10
- package/dist/bundle/chunks/chunk-YOUUMJLJ.js +0 -10
- package/dist/bundle/chunks/python3-QDNG2UXX.js +0 -13
package/dist/bundle/index.js
CHANGED
|
@@ -1,239 +1,273 @@
|
|
|
1
1
|
import{createRequire} from"node:module";const require=createRequire(import.meta.url);
|
|
2
|
-
import{a as xt,b as Pt,c as nt}from"./chunks/chunk-WNH3HOQA.js";import{a as pr}from"./chunks/chunk-BRJERIF4.js";import{c as Ms,e as Ta}from"./chunks/chunk-KIGPB52X.js";import{a as dr,b as hr,c as Tn,d as Ln}from"./chunks/chunk-K3XJ2WT4.js";import{a as Lt}from"./chunks/chunk-J2OBOJ64.js";import{a as Ls}from"./chunks/chunk-L2UW7DWF.js";import{a as Tt,b as Ke,c as Fn}from"./chunks/chunk-DLL7UR66.js";import{a as Wn,b as _a}from"./chunks/chunk-AI5LSBJC.js";import{a as ye}from"./chunks/chunk-XVL654YD.js";import{a as Ct,b as Ie}from"./chunks/chunk-UBTKJ6MG.js";import"./chunks/chunk-6D3WD6YU.js";import{c as It,d as hn}from"./chunks/chunk-AH7VTVWU.js";import"./chunks/chunk-STHBFACM.js";import{a as B,b as vt,c as F,d as pn,e as _t,f as At,g as mn}from"./chunks/chunk-YUSFCOM7.js";import{a as Ia,b as Ze,c as He,d as Me,e as et,f as Be,g as H,h as oe,i as Qe,j as Rt,k as gr,l as P,m as We,n as Ot,o as wr,p as tt}from"./chunks/chunk-EFORKKSH.js";import{a as M,b as Mn,c as Bn,d as ju,e as Dt,f as _s,g as mr,h as Gu,i as yr,j as Ts,k as Zu,l as Hu}from"./chunks/chunk-GN6CQ3J4.js";import{a as ht}from"./chunks/chunk-FOCWZZDE.js";import{a as St}from"./chunks/chunk-W5DWRFSU.js";import{a as Is}from"./chunks/chunk-NCUTH6QL.js";var en=[{name:"echo",load:async()=>(await import("./chunks/echo-HZOVZAPR.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-636HYSH4.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-QHD2JRWQ.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-R5CQLZQM.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-WDDKK2P3.js")).mkdirCommand},{name:"rmdir",load:async()=>(await import("./chunks/rmdir-WZKAT6M5.js")).rmdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-W4DF6Z4T.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-JQ4GDKDD.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-FKTQRFYJ.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-XSJA2FNL.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-VYDFOFNO.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-4CIOYX5Q.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-76BPYV5F.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-IY6QKK2P.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-UCOA3VQC.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-G3W6PNG3.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-RUR7HE5O.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-MLNSW25G.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-S6SNTIHZ.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-S6SNTIHZ.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-S6SNTIHZ.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-OUJZ5DH6.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-TZIPJOGL.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-IPNBFNH2.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-PV2NEQHF.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-OVOW532K.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-DTWKU2MC.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-RWPUW5FY.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-ZU3EODNI.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-3KPFH3J4.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-EPOS3MFH.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-RFXH2GNX.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-QJBPHRFJ.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-2BPPGGSM.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-YD5BWFH4.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-WTD7Q2EF.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-KNDNAFPT.js")).split},{name:"column",load:async()=>(await import("./chunks/column-LKMDIDCH.js")).column},{name:"join",load:async()=>(await import("./chunks/join-KQ4Z5OD4.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-OOWSWHRQ.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-DWWMZFO5.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-SJZQ5W65.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-Z2ZMOOW2.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-7OOL2MH6.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-PR3M44X6.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-VUUMB47B.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-VUUMB47B.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-T5TO5GWK.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-T5TO5GWK.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-3N762S3K.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-L7TJHOJT.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-QUBPEGGU.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-QUBPEGGU.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-KPIUNI6K.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-HIEWVHJ2.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-HIEWVHJ2.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-D6N4QCAJ.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-OXGTKKDA.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-CSARC7WF.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-FN2DXAEE.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-VPYWSKDR.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-SYQCWBMZ.js")).timeoutCommand},{name:"time",load:async()=>(await import("./chunks/time-NERE2JJ2.js")).timeCommand},{name:"seq",load:async()=>(await import("./chunks/seq-5R2GKXC6.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-SHRJJ4PX.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-JEDX55KS.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-BLPZJ6MP.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-VJZ4PHQ4.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-YC4YEI4P.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-NUF6QEX4.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-QDDMBDU7.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-UWVKETYW.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-YXC4HBTR.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-CESD3CQR.js")).hostname},{name:"whoami",load:async()=>(await import("./chunks/whoami-KR6E7UIR.js")).whoami},{name:"od",load:async()=>(await import("./chunks/od-YXD2NNIU.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-BTI6CWY4.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-BTI6CWY4.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-BTI6CWY4.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(en.push({name:"tar",load:async()=>(await import("./chunks/tar-GLX6QUHW.js")).tarCommand}),en.push({name:"yq",load:async()=>(await import("./chunks/yq-ZGB3W46S.js")).yqCommand}),en.push({name:"xan",load:async()=>(await import("./chunks/xan-KKPV2TJ3.js")).xanCommand}),en.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-WWZJZW37.js")).sqlite3Command}));var Er=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Er.push({name:"python3",load:async()=>(await import("./chunks/python3-QDNG2UXX.js")).python3Command}),Er.push({name:"python",load:async()=>(await import("./chunks/python3-QDNG2UXX.js")).pythonCommand}));var br=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(br.push({name:"js-exec",load:async()=>(await import("./chunks/js-exec-PNUEDFT5.js")).jsExecCommand}),br.push({name:"node",load:async()=>(await import("./chunks/js-exec-PNUEDFT5.js")).nodeStubCommand}));var Ma=[{name:"curl",load:async()=>(await import("./chunks/curl-DEHFBW27.js")).curlCommand}],La=new Map;function Sr(e){return{name:e.name,async execute(t,n){let r=La.get(e.name);if(r||(r=await Ie.runTrustedAsync(()=>e.load()),La.set(e.name,r)),n.coverage&&(typeof __BROWSER__>"u"||!__BROWSER__)){let{emitFlagCoverage:s}=await import("./chunks/flag-coverage-THYQHOT3.js");s(n.coverage,e.name,t)}return r.execute(t,n)}}}function Qu(){return en.map(e=>e.name)}function Ku(){return Ma.map(e=>e.name)}function Ba(e){return(e?en.filter(n=>e.includes(n.name)):en).map(Sr)}function Wa(){return Ma.map(Sr)}function Xu(){return Er.map(e=>e.name)}function Fa(){return Er.map(Sr)}function Yu(){return br.map(e=>e.name)}function Va(){return br.map(Sr)}var za=new WeakMap,qa=new WeakSet;function vr(e){let t=za.get(e);return t===void 0&&(t=Object.freeze(Object.create(null)),za.set(e,t),qa.add(t)),t}function Ua(e){return qa.has(e)}var ja={maxSourceBytes:67108864,maxExecDepth:64,maxCallDepth:100,maxCommandCount:1e5,maxLoopIterations:1e5,maxAwkIterations:1e5,maxSedIterations:1e5,maxJqIterations:1e7,maxQueryTokens:1e5,maxQueryDepth:1e3,maxQueryElements:1e6,maxAwkParserTokens:1e5,maxAwkParserDepth:256,maxAwkParserOperations:1e6,maxCsvRows:1e6,maxCsvCells:1e7,maxWorkUnits:1e8,maxTraversalEntries:1e6,maxTraversalDepth:1e3,maxTraversalWork:1e6,maxLiveBytes:536870912,maxInputBytes:536870912,maxFileSystemBytes:1073741824,maxDatabaseBytes:1073741824,maxDatabaseResultBytes:268435456,maxArchiveBytes:1073741824,maxArchiveCompressedBytes:536870912,maxArchiveEntryBytes:536870912,maxArchiveEntries:1e6,maxWorkerMessageBytes:67108864,maxExecutionTimeMs:36e5,maxExtensionCleanupTimeMs:100,maxSqliteTimeoutMs:3e4,maxPythonTimeoutMs:3e4,maxJsTimeoutMs:3e4,maxGlobOperations:1e6,maxStringLength:67108864,maxArrayElements:1e6,maxHeredocSize:67108864,maxSubstitutionDepth:50,maxBraceExpansionResults:1e5,maxOutputSize:268435456,maxFileDescriptors:4096,maxSourceDepth:100},Ju={...ja,maxSourceBytes:8*1024*1024,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3,maxPythonTimeoutMs:1e4,maxJsTimeoutMs:1e4,maxExtensionCleanupTimeMs:25,maxGlobOperations:1e5,maxStringLength:10*1024*1024,maxArrayElements:1e5,maxHeredocSize:10*1024*1024,maxBraceExpansionResults:1e4,maxOutputSize:10*1024*1024,maxFileDescriptors:1024,maxQueryTokens:25e3,maxQueryDepth:256,maxQueryElements:1e5,maxAwkParserTokens:25e3,maxAwkParserDepth:128,maxAwkParserOperations:1e5,maxCsvRows:1e5,maxCsvCells:1e6,maxWorkUnits:1e5,maxTraversalEntries:1e5,maxTraversalDepth:256,maxTraversalWork:1e5,maxLiveBytes:64*1024*1024,maxInputBytes:32*1024*1024,maxFileSystemBytes:128*1024*1024,maxDatabaseBytes:64*1024*1024,maxDatabaseResultBytes:16*1024*1024,maxArchiveBytes:128*1024*1024,maxArchiveCompressedBytes:64*1024*1024,maxArchiveEntryBytes:64*1024*1024,maxArchiveEntries:1e5,maxWorkerMessageBytes:16*1024*1024,maxExecutionTimeMs:3e4};function Ar(e,t="normal"){if(t!=="normal"&&t!=="hardened")throw new RangeError('executionLimitProfile must be "normal" or "hardened"');let n=t==="hardened"?Ju:ja;if(!e)return{...n};let r={maxSourceBytes:e.maxSourceBytes??n.maxSourceBytes,maxExecDepth:e.maxExecDepth??n.maxExecDepth,maxCallDepth:e.maxCallDepth??n.maxCallDepth,maxCommandCount:e.maxCommandCount??n.maxCommandCount,maxLoopIterations:e.maxLoopIterations??n.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??n.maxAwkIterations,maxSedIterations:e.maxSedIterations??n.maxSedIterations,maxJqIterations:e.maxJqIterations??n.maxJqIterations,maxQueryTokens:e.maxQueryTokens??n.maxQueryTokens,maxQueryDepth:e.maxQueryDepth??n.maxQueryDepth,maxQueryElements:e.maxQueryElements??n.maxQueryElements,maxAwkParserTokens:e.maxAwkParserTokens??n.maxAwkParserTokens,maxAwkParserDepth:e.maxAwkParserDepth??n.maxAwkParserDepth,maxAwkParserOperations:e.maxAwkParserOperations??n.maxAwkParserOperations,maxCsvRows:e.maxCsvRows??n.maxCsvRows,maxCsvCells:e.maxCsvCells??n.maxCsvCells,maxWorkUnits:e.maxWorkUnits??n.maxWorkUnits,maxTraversalEntries:e.maxTraversalEntries??n.maxTraversalEntries,maxTraversalDepth:e.maxTraversalDepth??n.maxTraversalDepth,maxTraversalWork:e.maxTraversalWork??n.maxTraversalWork,maxLiveBytes:e.maxLiveBytes??n.maxLiveBytes,maxInputBytes:e.maxInputBytes??n.maxInputBytes,maxFileSystemBytes:e.maxFileSystemBytes??n.maxFileSystemBytes,maxDatabaseBytes:e.maxDatabaseBytes??n.maxDatabaseBytes,maxDatabaseResultBytes:e.maxDatabaseResultBytes??n.maxDatabaseResultBytes,maxArchiveBytes:e.maxArchiveBytes??n.maxArchiveBytes,maxArchiveCompressedBytes:e.maxArchiveCompressedBytes??n.maxArchiveCompressedBytes,maxArchiveEntryBytes:e.maxArchiveEntryBytes??n.maxArchiveEntryBytes,maxArchiveEntries:e.maxArchiveEntries??n.maxArchiveEntries,maxWorkerMessageBytes:e.maxWorkerMessageBytes??n.maxWorkerMessageBytes,maxExecutionTimeMs:e.maxExecutionTimeMs??n.maxExecutionTimeMs,maxExtensionCleanupTimeMs:e.maxExtensionCleanupTimeMs??n.maxExtensionCleanupTimeMs,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??n.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??n.maxPythonTimeoutMs,maxJsTimeoutMs:e.maxJsTimeoutMs??n.maxJsTimeoutMs,maxGlobOperations:e.maxGlobOperations??n.maxGlobOperations,maxStringLength:e.maxStringLength??n.maxStringLength,maxArrayElements:e.maxArrayElements??n.maxArrayElements,maxHeredocSize:e.maxHeredocSize??n.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??n.maxSubstitutionDepth,maxBraceExpansionResults:e.maxBraceExpansionResults??n.maxBraceExpansionResults,maxOutputSize:e.maxOutputSize??n.maxOutputSize,maxFileDescriptors:e.maxFileDescriptors??n.maxFileDescriptors,maxSourceDepth:e.maxSourceDepth??n.maxSourceDepth};for(let s of Object.keys(r)){let i=r[s];if(i!==Number.POSITIVE_INFINITY&&(!Number.isSafeInteger(i)||i<0))throw new RangeError(`${s} must be a non-negative safe integer or positive Infinity`)}return r}function ef(e){let{executionLimits:t,executionLimitProfile:n,fs:r,stdin:s=_s,...i}=e;return{fs:r,fsIdentity:i.fsIdentity??vr(r),cwd:"/",env:new Map,stdin:s,limits:Ar(t,n),...i}}function Ga(e){return"load"in e&&typeof e.load=="function"}function tf(e,t,n={}){return{name:e,trusted:n.trusted!==!1,execute:t}}function Za(e){let t=null,n=null;return{name:e.name,trusted:e.trusted!==!1,async execute(r,s){if(!t){let a=n;a||(a=e.load().then(o=>(t=o,o)),n=a);try{t=await a}catch(o){throw n===a&&(n=null),o}}let i=t;if(!i)throw new Error(`Failed to load command: ${e.name}`);return i.execute(r,s)}}}var Ha=Object.freeze(Object.create(null)),xr=class{limits;signal;commandCount=0;workUnits=0;liveBytes=0;inputBytes=0;outputBytes=0;countersByKind=new Map;bytesByKind=new Map;depthByKind=new Map;cleanupCallbacks=[];poisoned;closed=!1;startedAt=Date.now();get remainingLiveBytes(){return Math.max(0,this.limits.maxLiveBytes-this.liveBytes)}get outputBytesUsed(){return this.outputBytes}constructor(t,n=void 0){this.limits=t,this.signal=n}fail(t){throw this.poisoned??=t,this.poisoned}poisonAfterAbort(t){this.poisoned??=t}assertUsable(){if(this.poisoned)throw this.poisoned;if(this.closed)throw new Error("execution budget is already closed");this.throwIfAborted()}chargeCommand(){return this.consume("commands",1,"execution")}consumeWork(t=1,n="execution"){return this.consume("work",t,n)}consumeLimited(t,n,r,s=t){this.assertUsable();let i=this.countersByKind.get(t)??0;return(!Number.isSafeInteger(n)||n<0||!Number.isSafeInteger(r)||r<0||n>r-i)&&this.fail(new P(`${s}: ${t} work limit exceeded (${r})`,"iterations")),n>this.limits.maxWorkUnits-this.workUnits&&this.fail(new P(`${s}: aggregate work limit exceeded (${this.limits.maxWorkUnits})`,"iterations")),this.countersByKind.set(t,i+n),this.workUnits+=n,i+n}consumeInput(t,n="execution"){return this.assertUsable(),(!Number.isSafeInteger(t)||t<0||t>this.limits.maxInputBytes-this.inputBytes)&&this.fail(new P(`${n}: aggregate input size limit exceeded (${this.limits.maxInputBytes} bytes)`,"string_length")),this.inputBytes+=t,this.inputBytes}consume(t,n=1,r=t){this.assertUsable();let s=this.countersByKind.get(t)??0,i=t==="commands"?this.commandCount:this.workUnits,a=t==="commands"?this.limits.maxCommandCount:this.limits.maxWorkUnits;(!Number.isSafeInteger(n)||n<0||n>a-i)&&this.fail(new P(t==="commands"?`too many commands executed (>${a}), increase executionLimits.maxCommandCount`:`${r}: ${t} work limit exceeded (${a})`,t==="commands"?"commands":"iterations"));let o=i+n;return t==="commands"?this.commandCount=o:this.workUnits=o,this.countersByKind.set(t,s+n),o}reserveBytes(t,n,r){this.assertUsable();let s=typeof t=="string"?t:"live",i=typeof t=="string"?n:t,a=typeof t=="string"?r??s:n??"execution";(!Number.isSafeInteger(i)||i<0||i>this.limits.maxLiveBytes-this.liveBytes)&&this.fail(new P(`${a}: live byte limit exceeded (${this.limits.maxLiveBytes} bytes)`,"string_length")),this.liveBytes+=i,this.bytesByKind.set(s,(this.bytesByKind.get(s)??0)+i);let o=!1;return{release:()=>{if(o)return;o=!0,this.liveBytes-=i;let l=(this.bytesByKind.get(s)??i)-i;l<=0?this.bytesByKind.delete(s):this.bytesByKind.set(s,l)}}}appendOutput(t,n,r="execution",s=0,i="text"){this.assertUsable();let a=i==="bytes"?n.length:M(n);(!Number.isSafeInteger(s)||s<0||s>a)&&this.fail(new P(`${r}: invalid ${t} accounting`,"output_size"));let o=a-s;return o>this.limits.maxOutputSize-this.outputBytes&&this.fail(new P(`${r}: total output size exceeded (>${this.limits.maxOutputSize} bytes), increase executionLimits.maxOutputSize`,"output_size")),this.outputBytes+=o,a}accountResult(t,n="execution",r=Number.POSITIVE_INFINITY){let s=t.internalOutputAccounting,i=Math.min(s?.stdout??0,r),a=Math.min(s?.stderr??0,Math.max(0,r-i)),o=this.appendOutput("stdout",t.stdout,n,i,t.stdoutKind==="bytes"||t.stdoutEncoding==="binary"?"bytes":"text"),l=this.appendOutput("stderr",t.stderr,n,a);return Object.isExtensible(t)?(t.internalOutputAccounting={stdout:o,stderr:l},t):o===0&&l===0?t:{...t,internalOutputAccounting:{stdout:o,stderr:l}}}relinquishOutput(t,n,r){this.assertUsable(),r!==Ha&&this.fail(new P(`${n}: unauthorized output accounting release`,"output_size")),(!Number.isSafeInteger(t)||t<0||t>this.outputBytes)&&this.fail(new P(`${n}: invalid output accounting release`,"output_size")),this.outputBytes-=t}enterDepth(t,n=this.limits.maxCallDepth,r){this.assertUsable();let s=typeof n=="number"?n:this.limits.maxCallDepth,i=typeof n=="string"?n:r??t,a=this.depthByKind.get(t)??0;a>=s&&this.fail(new P(`${i}: maximum depth (${s}) exceeded`,"recursion")),this.depthByKind.set(t,a+1);let o=!1;return{release:()=>{if(o)return;o=!0;let l=(this.depthByKind.get(t)??1)-1;l<=0?this.depthByKind.delete(t):this.depthByKind.set(t,l)}}}throwIfAborted(t="execution"){this.signal?.aborted&&this.fail(new We("",`bash: ${t} aborted
|
|
3
|
-
`)),Date.now()-this.startedAt>this.limits.maxExecutionTimeMs&&this.fail(new
|
|
4
|
-
`))}remainingTimeMs(){return Math.max(0,this.limits.maxExecutionTimeMs-(Date.now()-this.startedAt))}registerCleanup(t){this.assertUsable(),this.cleanupCallbacks.push(t);let n=!0;return()=>{if(!n)return;n=!1;let r=this.cleanupCallbacks.indexOf(t);r>=0&&this.cleanupCallbacks.splice(r,1)}}async close(){if(this.closed)return;this.closed=!0;let t=[],n=Date.now()+this.limits.maxExtensionCleanupTimeMs;for(let r=this.cleanupCallbacks.length-1;r>=0;r--)try{let s=n-Date.now();if(s<=0){t.push(new Error("execution cleanup grace period exceeded"));break}let i,a=await Promise.race([Promise.resolve().then(this.cleanupCallbacks[r]).then(()=>({ok:!0}),o=>({ok:!1,error:o})),new Promise(o=>{i=Tn(()=>o({ok:!1,error:new Error("execution cleanup grace period exceeded")}),s)})]);if(Ln(i),!a.ok&&(t.push(a.error),Date.now()>=n))break}catch(s){t.push(s)}if(this.cleanupCallbacks.length=0,this.depthByKind.clear(),this.bytesByKind.clear(),this.liveBytes=0,t.length>0)throw new AggregateError(t,"execution cleanup failed")}assertExecDepth(t){this.assertUsable(),t>this.limits.maxExecDepth&&this.fail(new P(`maximum nested execution depth (${this.limits.maxExecDepth}) exceeded`,"recursion"))}};function Qa(e){let t=Object.create(null);return Object.defineProperties(t,{remainingLiveBytes:{enumerable:!0,get:()=>e.remainingLiveBytes},consumeWork:{enumerable:!0,value:e.consumeWork.bind(e)},consumeLimited:{enumerable:!0,value:e.consumeLimited.bind(e)},consumeInput:{enumerable:!0,value:e.consumeInput.bind(e)},reserveBytes:{enumerable:!0,value:e.reserveBytes.bind(e)},enterDepth:{enumerable:!0,value:e.enterDepth.bind(e)},throwIfAborted:{enumerable:!0,value:e.throwIfAborted.bind(e)},remainingTimeMs:{enumerable:!0,value:e.remainingTimeMs.bind(e)},registerCleanup:{enumerable:!0,value:e.registerCleanup.bind(e)}}),Object.freeze(t)}function Ka(e,t,n="pipeline"){e.relinquishOutput(t,n,Ha)}var tn=new TextEncoder;function nf(e){return typeof e=="object"&&e!==null&&!(e instanceof Uint8Array)&&"content"in e}var $t=class{data=new Map;entryIdentities=new WeakMap;nextEntryIdentity=1;maxTotalBytes;retainedBytes=0;contentReferences=new WeakMap;materializedContent(t){return t?.type==="file"&&"content"in t?t.content:null}storedByteLength(t){return t===null?0:t instanceof Uint8Array?t.byteLength:M(t)}wouldReleaseBytes(t){let n=this.materializedContent(t);return n===null?0:n instanceof Uint8Array?this.contentReferences.get(n)===1?n.byteLength:0:this.storedByteLength(n)}assertCanAllocate(t,n){let r=this.wouldReleaseBytes(this.data.get(t));if(!Number.isSafeInteger(n)||n<0||n>this.maxTotalBytes-this.retainedBytes+r)throw new Error(`ENOSPC: in-memory filesystem byte limit exceeded (${this.maxTotalBytes} bytes)`)}setEntry(t,n){let r=this.data.get(t),s=this.materializedContent(r),i=this.materializedContent(n);if(s===i){this.data.set(t,n);return}let a=this.wouldReleaseBytes(r),o=i instanceof Uint8Array?this.contentReferences.has(i)?0:i.byteLength:this.storedByteLength(i);if(o>this.maxTotalBytes-this.retainedBytes+a)throw new Error(`ENOSPC: in-memory filesystem byte limit exceeded (${this.maxTotalBytes} bytes)`);if(s instanceof Uint8Array){let l=this.contentReferences.get(s)??0;l<=1?this.contentReferences.delete(s):this.contentReferences.set(s,l-1)}i instanceof Uint8Array&&this.contentReferences.set(i,(this.contentReferences.get(i)??0)+1),this.retainedBytes+=o-a,this.data.set(t,n)}deleteEntry(t){let n=this.data.get(t);if(!n)return!1;let r=this.materializedContent(n),s=this.wouldReleaseBytes(n);if(r instanceof Uint8Array){let i=this.contentReferences.get(r)??0;i<=1?this.contentReferences.delete(r):this.contentReferences.set(r,i-1)}return this.retainedBytes-=s,this.data.delete(t)}contentByteLength(t,n){if(t instanceof Uint8Array)return t.byteLength;if(n==="hex")return Math.floor(t.length/2);if(n==="base64"){let r=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.max(0,Math.floor(t.length*3/4)-r)}return n==="binary"||n==="latin1"?t.length:M(t)}identityFor(t){let n=this.entryIdentities.get(t);return n||(n=`memfs:${this.nextEntryIdentity++}`,this.entryIdentities.set(t,n)),n}constructor(t,n={}){if(this.maxTotalBytes=n.maxTotalBytes??1024*1024*1024,!Number.isSafeInteger(this.maxTotalBytes)||this.maxTotalBytes<0)throw new Error("InMemoryFs: invalid maxTotalBytes");if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),t)for(let[r,s]of Object.entries(t))typeof s=="function"?this.writeFileLazy(r,s):nf(s)?this.writeFileSync(r,s.content,void 0,{mode:s.mode,mtime:s.mtime}):this.writeFileSync(r,s)}ensureParentDirs(t){let n=pn(t);n!=="/"&&(this.data.has(n)||(this.ensureParentDirs(n),this.data.set(n,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(t,n,r,s){F(t,"write");let i=B(t);this.ensureParentDirs(i);let a=nt(r);this.assertCanAllocate(i,this.contentByteLength(n,a));let o=xt(n,a);this.setEntry(i,{type:"file",content:o,mode:s?.mode??420,mtime:s?.mtime??new Date})}writeFileLazy(t,n,r){F(t,"write");let s=B(t);this.ensureParentDirs(s),this.setEntry(s,{type:"file",lazy:n,mode:r?.mode??420,mtime:r?.mtime??new Date})}async materializeLazy(t,n){let r=await n.lazy(),s=typeof r=="string"?tn.encode(r):r,i={type:"file",content:s,mode:n.mode,mtime:n.mtime};return this.assertCanAllocate(t,s.byteLength),this.setEntry(t,i),i}async readFile(t,n){let r=await this.readFileBuffer(t),s=nt(n);return Pt(r,s)}async readFileBytes(t){let n=await this.readFileBuffer(t);return Pt(n,"binary")}async readFileBuffer(t){F(t,"open");let n=this.resolvePathWithSymlinks(t),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if("lazy"in r){let s=await this.materializeLazy(n,r);return s.content instanceof Uint8Array?s.content:tn.encode(s.content)}return r.content instanceof Uint8Array?r.content:tn.encode(r.content)}async writeFile(t,n,r){this.writeFileSync(t,n,r)}async appendFile(t,n,r){F(t,"append");let s=B(t),i=this.data.get(s);if(i&&i.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${t}'`);let a=nt(r),o=this.contentByteLength(n,a);if(i?.type==="file"){let l=i;"lazy"in l&&(l=await this.materializeLazy(s,l));let c="content"in l&&l.content instanceof Uint8Array?l.content:tn.encode("content"in l?l.content:"");this.assertCanAllocate(s,c.byteLength+o);let u=xt(n,a),f=new Uint8Array(c.length+u.length);f.set(c),f.set(u,c.length),this.setEntry(s,{type:"file",content:f,mode:l.mode,mtime:new Date})}else this.writeFileSync(t,n,r)}async exists(t){if(t.includes("\0"))return!1;try{let n=this.resolvePathWithSymlinks(t);return this.data.has(n)}catch{return!1}}async stat(t){F(t,"stat");let n=this.resolvePathWithSymlinks(t),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);r.type==="file"&&"lazy"in r&&(r=await this.materializeLazy(n,r));let s=0;return r.type==="file"&&"content"in r&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=tn.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date,identity:this.identityFor(r)}}async lstat(t){F(t,"lstat");let n=this.resolveIntermediateSymlinks(t),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};r.type==="file"&&"lazy"in r&&(r=await this.materializeLazy(n,r));let s=0;return r.type==="file"&&"content"in r&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=tn.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date,identity:this.identityFor(r)}}resolveIntermediateSymlinks(t){let n=B(t);if(n==="/")return"/";let r=n.slice(1).split("/");if(r.length<=1)return n;let s="",i=new Set;for(let a=0;a<r.length-1;a++){let o=r[a];s=`${s}/${o}`;let l=this.data.get(s),c=0,u=40;for(;l&&l.type==="symlink"&&c<u;){if(i.has(s))throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`);i.add(s),s=mn(s,l.target),l=this.data.get(s),c++}if(c>=u)throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`)}return`${s}/${r[r.length-1]}`}resolvePathWithSymlinks(t){let n=B(t);if(n==="/")return"/";let r=n.slice(1).split("/"),s="",i=new Set;for(let a of r){s=`${s}/${a}`;let o=this.data.get(s),l=0,c=40;for(;o&&o.type==="symlink"&&l<c;){if(i.has(s))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);i.add(s),s=mn(s,o.target),o=this.data.get(s),l++}if(l>=c)throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`)}return s}async mkdir(t,n){this.mkdirSync(t,n)}mkdirSync(t,n){F(t,"mkdir");let r=B(t);if(this.data.has(r)){if(this.data.get(r)?.type==="file")throw new Error(`EEXIST: file already exists, mkdir '${t}'`);if(!n?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${t}'`);return}let s=pn(r);if(s!=="/"&&!this.data.has(s))if(n?.recursive)this.mkdirSync(s,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.data.set(r,{type:"directory",mode:493,mtime:new Date})}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){F(t,"scandir");let n=B(t),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let s=new Set;for(;r&&r.type==="symlink";){if(s.has(n))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);s.add(n),n=mn(n,r.target),r=this.data.get(n)}if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);if(r.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);let i=n==="/"?"/":`${n}/`,a=new Map;for(let[o,l]of this.data.entries())if(o!==n&&o.startsWith(i)){let c=o.slice(i.length),u=c.split("/")[0];u&&!c.includes("/",u.length)&&!a.has(u)&&a.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}return Array.from(a.values()).sort((o,l)=>o.name<l.name?-1:o.name>l.name?1:0)}async rm(t,n){F(t,"rm");let r=B(t),s=this.data.get(r);if(!s){if(n?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}if(s.type==="directory"){let i=await this.readdir(r);if(i.length>0){if(!n?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let a of i){let o=At(r,a);await this.rm(o,n)}}}this.deleteEntry(r)}async cp(t,n,r){F(t,"cp"),F(n,"cp");let s=B(t),i=B(n),a=this.data.get(s);if(!a)throw new Error(`ENOENT: no such file or directory, cp '${t}'`);if(a.type==="file")if(this.ensureParentDirs(i),"content"in a){let o=a.content instanceof Uint8Array?a.content.byteLength:tn.encode(a.content).byteLength;this.assertCanAllocate(i,o);let l=a.content instanceof Uint8Array?new Uint8Array(a.content):a.content;this.setEntry(i,{...a,content:l})}else this.setEntry(i,{...a});else if(a.type==="symlink")this.ensureParentDirs(i),this.data.set(i,{...a});else if(a.type==="directory"){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);if(vt(s,i))throw new Error(`EINVAL: cannot copy '${t}' into itself, '${n}'`);await this.mkdir(i,{recursive:!0});let o=await this.readdir(s);for(let l of o){let c=At(s,l),u=At(i,l);await this.cp(c,u,r)}}}async mv(t,n){F(t,"mv"),F(n,"mv");let r=B(t),s=B(n);if(r===s)return;let i=this.data.get(r);if(!i)throw new Error(`ENOENT: no such file or directory, mv '${t}'`);if(i.type==="directory"&&vt(r,s))throw new Error(`EINVAL: cannot move '${t}' into itself, '${n}'`);if(i.type==="directory"){await this.mkdir(s,{recursive:!0});let a=await this.readdir(r);for(let o of a)await this.mv(At(r,o),At(s,o));this.deleteEntry(r);return}this.ensureParentDirs(s),this.setEntry(s,i),this.deleteEntry(r)}getAllPaths(){return Array.from(this.data.keys())}resolvePath(t,n){return _t(t,n)}async chmod(t,n){F(t,"chmod");let r=B(t),s=this.data.get(r);if(!s)throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);s.mode=n}async symlink(t,n){F(n,"symlink");let r=B(n);if(this.data.has(r))throw new Error(`EEXIST: file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:t,mode:511,mtime:new Date})}async link(t,n){F(t,"link"),F(n,"link");let r=B(t),s=B(n),i=this.data.get(r);if(!i)throw new Error(`ENOENT: no such file or directory, link '${t}'`);if(i.type!=="file")throw new Error(`EPERM: operation not permitted, link '${t}'`);if(this.data.has(s))throw new Error(`EEXIST: file already exists, link '${n}'`);let a=i;"lazy"in a&&(a=await this.materializeLazy(r,a)),this.ensureParentDirs(s);let o={type:"file",content:a.content,mode:a.mode,mtime:a.mtime};this.entryIdentities.set(o,this.identityFor(a)),this.setEntry(s,o)}async readlink(t){F(t,"readlink");let n=B(t),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return r.target}async realpath(t){F(t,"realpath");let n=this.resolvePathWithSymlinks(t);if(!this.data.has(n))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return n}async utimes(t,n,r){F(t,"utimes");let s=B(t),i=this.resolvePathWithSymlinks(s),a=this.data.get(i);if(!a)throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);a.mtime=r}};var Xa="5.1.0(1)-release",Ya="Linux version 5.15.0-generic (just-bash) #1 SMP PREEMPT";function Ws(e){let{pid:t,ppid:n,uid:r,gid:s}=e;return`Name: bash
|
|
2
|
+
import{a as Rt,b as Ot,c as it}from"./chunks/chunk-WNH3HOQA.js";import{a as Nr}from"./chunks/chunk-BRJERIF4.js";import{c as ei,e as ma}from"./chunks/chunk-KIGPB52X.js";import{a as $r,b as Cr,c as Yn,d as Jn}from"./chunks/chunk-K3XJ2WT4.js";import{a as Vt}from"./chunks/chunk-J2OBOJ64.js";import{a as Js}from"./chunks/chunk-L2UW7DWF.js";import{a as Wt,b as Xe,c as nr}from"./chunks/chunk-DLL7UR66.js";import{a as tr,b as ha}from"./chunks/chunk-AI5LSBJC.js";import{a as ge}from"./chunks/chunk-XVL654YD.js";import{a as _t,b as Le}from"./chunks/chunk-UBTKJ6MG.js";import"./chunks/chunk-6D3WD6YU.js";import{c as Ft,d as Pn}from"./chunks/chunk-AH7VTVWU.js";import"./chunks/chunk-STHBFACM.js";import{a as W,b as Ct,c as V,d as xn,e as Bt,f as Nt,g as $n}from"./chunks/chunk-YUSFCOM7.js";import{a as kn,b as He,c as Qe,d as _e,e as We,f as Ve,g as j,h as ce,i as Ke,j as Lt,k as Rr,l as x,m as ze,n as Mt,o as Or,p as st}from"./chunks/chunk-EFORKKSH.js";import{a as B,b as er,c as cn,d as Wf,e as Tt,f as Xs,g as vn,h as Vf,i as xt,j as Ys,k as zf,l as Uf}from"./chunks/chunk-GN6CQ3J4.js";import{a as wt}from"./chunks/chunk-FOCWZZDE.js";import{a as $t}from"./chunks/chunk-W5DWRFSU.js";import{a as Ks}from"./chunks/chunk-NCUTH6QL.js";var un=[{name:"echo",load:async()=>(await import("./chunks/echo-PLLZYM2L.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-636HYSH4.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-V42QCPHL.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-R5CQLZQM.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-WDDKK2P3.js")).mkdirCommand},{name:"rmdir",load:async()=>(await import("./chunks/rmdir-WZKAT6M5.js")).rmdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-W4DF6Z4T.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-JQ4GDKDD.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-FKTQRFYJ.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-XSJA2FNL.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-VYDFOFNO.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-4CIOYX5Q.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-76BPYV5F.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-IY6QKK2P.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-UCOA3VQC.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-G3W6PNG3.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-RUR7HE5O.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-MLNSW25G.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-UDCQDUQK.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-UDCQDUQK.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-UDCQDUQK.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-XCX2J2RF.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-TZIPJOGL.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-IPNBFNH2.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-PV2NEQHF.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-OVOW532K.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-DTWKU2MC.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-RWPUW5FY.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-ZU3EODNI.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-3KPFH3J4.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-EPOS3MFH.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-RFXH2GNX.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-QJBPHRFJ.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-2BPPGGSM.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-YD5BWFH4.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-WTD7Q2EF.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-KNDNAFPT.js")).split},{name:"column",load:async()=>(await import("./chunks/column-LKMDIDCH.js")).column},{name:"join",load:async()=>(await import("./chunks/join-KQ4Z5OD4.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-OOWSWHRQ.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-DWWMZFO5.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-SJZQ5W65.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-Z2ZMOOW2.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-7OOL2MH6.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-PR3M44X6.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-VUUMB47B.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-VUUMB47B.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-T5TO5GWK.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-T5TO5GWK.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-3N762S3K.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-L7TJHOJT.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-QUBPEGGU.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-QUBPEGGU.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-KPIUNI6K.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-HIEWVHJ2.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-HIEWVHJ2.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-B5324QOX.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-OXGTKKDA.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-CSARC7WF.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-FN2DXAEE.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-VPYWSKDR.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-SYQCWBMZ.js")).timeoutCommand},{name:"time",load:async()=>(await import("./chunks/time-NERE2JJ2.js")).timeCommand},{name:"seq",load:async()=>(await import("./chunks/seq-5R2GKXC6.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-SHRJJ4PX.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-JEDX55KS.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-BLPZJ6MP.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-VJZ4PHQ4.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-YC4YEI4P.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-NUF6QEX4.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-QDDMBDU7.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-UWVKETYW.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-YXC4HBTR.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-CESD3CQR.js")).hostname},{name:"whoami",load:async()=>(await import("./chunks/whoami-KR6E7UIR.js")).whoami},{name:"od",load:async()=>(await import("./chunks/od-YXD2NNIU.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-BTI6CWY4.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-BTI6CWY4.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-BTI6CWY4.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(un.push({name:"tar",load:async()=>(await import("./chunks/tar-GLX6QUHW.js")).tarCommand}),un.push({name:"yq",load:async()=>(await import("./chunks/yq-FMWLA3S2.js")).yqCommand}),un.push({name:"xan",load:async()=>(await import("./chunks/xan-EGU5VRRP.js")).xanCommand}),un.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-ZTQJIC3G.js")).sqlite3Command}));var Dr=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Dr.push({name:"python3",load:async()=>(await import("./chunks/python3-ETPBGJP3.js")).python3Command}),Dr.push({name:"python",load:async()=>(await import("./chunks/python3-ETPBGJP3.js")).pythonCommand}));var Ir=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Ir.push({name:"js-exec",load:async()=>(await import("./chunks/js-exec-PNUEDFT5.js")).jsExecCommand}),Ir.push({name:"node",load:async()=>(await import("./chunks/js-exec-PNUEDFT5.js")).nodeStubCommand}));var ga=[{name:"curl",load:async()=>(await import("./chunks/curl-DEHFBW27.js")).curlCommand}],ya=new Map;function _r(e){return{name:e.name,async execute(t,n){let r=ya.get(e.name);if(r||(r=await Le.runTrustedAsync(()=>e.load()),ya.set(e.name,r)),n.coverage&&(typeof __BROWSER__>"u"||!__BROWSER__)){let{emitFlagCoverage:s}=await import("./chunks/flag-coverage-UV7GI2DF.js");s(n.coverage,e.name,t)}return r.execute(t,n)}}}function qf(){return un.map(e=>e.name)}function jf(){return ga.map(e=>e.name)}function wa(e){return(e?un.filter(n=>e.includes(n.name)):un).map(_r)}function Ea(){return ga.map(_r)}function Gf(){return Dr.map(e=>e.name)}function ba(){return Dr.map(_r)}function Zf(){return Ir.map(e=>e.name)}function Sa(){return Ir.map(_r)}var Aa=new WeakMap,va=new WeakSet;function Tr(e){let t=Aa.get(e);return t===void 0&&(t=Object.freeze(Object.create(null)),Aa.set(e,t),va.add(t)),t}function ka(e){return va.has(e)}var Pa={maxSourceBytes:67108864,maxExecDepth:64,maxCallDepth:100,maxCommandCount:1e5,maxLoopIterations:1e5,maxAwkIterations:1e5,maxSedIterations:1e5,maxJqIterations:1e7,maxQueryTokens:1e5,maxQueryDepth:1e3,maxQueryElements:1e6,maxAwkParserTokens:1e5,maxAwkParserDepth:256,maxAwkParserOperations:1e6,maxCsvRows:1e6,maxCsvCells:1e7,maxWorkUnits:1e8,maxTraversalEntries:1e6,maxTraversalDepth:1e3,maxTraversalWork:1e6,maxLiveBytes:536870912,maxInputBytes:536870912,maxFileSystemBytes:1073741824,maxDatabaseBytes:1073741824,maxDatabaseResultBytes:268435456,maxArchiveBytes:1073741824,maxArchiveCompressedBytes:536870912,maxArchiveEntryBytes:536870912,maxArchiveEntries:1e6,maxWorkerMessageBytes:67108864,maxExecutionTimeMs:36e5,maxExtensionCleanupTimeMs:100,maxSqliteTimeoutMs:3e4,maxPythonTimeoutMs:3e4,maxJsTimeoutMs:3e4,maxGlobOperations:1e6,maxStringLength:67108864,maxArrayElements:1e6,maxHeredocSize:67108864,maxSubstitutionDepth:50,maxBraceExpansionResults:1e5,maxOutputSize:268435456,maxFileDescriptors:4096,maxSourceDepth:100},Hf={...Pa,maxSourceBytes:8*1024*1024,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3,maxPythonTimeoutMs:1e4,maxJsTimeoutMs:1e4,maxExtensionCleanupTimeMs:25,maxGlobOperations:1e5,maxStringLength:10*1024*1024,maxArrayElements:1e5,maxHeredocSize:10*1024*1024,maxBraceExpansionResults:1e4,maxOutputSize:10*1024*1024,maxFileDescriptors:1024,maxQueryTokens:25e3,maxQueryDepth:256,maxQueryElements:1e5,maxAwkParserTokens:25e3,maxAwkParserDepth:128,maxAwkParserOperations:1e5,maxCsvRows:1e5,maxCsvCells:1e6,maxWorkUnits:1e5,maxTraversalEntries:1e5,maxTraversalDepth:256,maxTraversalWork:1e5,maxLiveBytes:64*1024*1024,maxInputBytes:32*1024*1024,maxFileSystemBytes:128*1024*1024,maxDatabaseBytes:64*1024*1024,maxDatabaseResultBytes:16*1024*1024,maxArchiveBytes:128*1024*1024,maxArchiveCompressedBytes:64*1024*1024,maxArchiveEntryBytes:64*1024*1024,maxArchiveEntries:1e5,maxWorkerMessageBytes:16*1024*1024,maxExecutionTimeMs:3e4};function Lr(e,t="normal"){if(t!=="normal"&&t!=="hardened")throw new RangeError('executionLimitProfile must be "normal" or "hardened"');let n=t==="hardened"?Hf:Pa;if(!e)return{...n};let r={maxSourceBytes:e.maxSourceBytes??n.maxSourceBytes,maxExecDepth:e.maxExecDepth??n.maxExecDepth,maxCallDepth:e.maxCallDepth??n.maxCallDepth,maxCommandCount:e.maxCommandCount??n.maxCommandCount,maxLoopIterations:e.maxLoopIterations??n.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??n.maxAwkIterations,maxSedIterations:e.maxSedIterations??n.maxSedIterations,maxJqIterations:e.maxJqIterations??n.maxJqIterations,maxQueryTokens:e.maxQueryTokens??n.maxQueryTokens,maxQueryDepth:e.maxQueryDepth??n.maxQueryDepth,maxQueryElements:e.maxQueryElements??n.maxQueryElements,maxAwkParserTokens:e.maxAwkParserTokens??n.maxAwkParserTokens,maxAwkParserDepth:e.maxAwkParserDepth??n.maxAwkParserDepth,maxAwkParserOperations:e.maxAwkParserOperations??n.maxAwkParserOperations,maxCsvRows:e.maxCsvRows??n.maxCsvRows,maxCsvCells:e.maxCsvCells??n.maxCsvCells,maxWorkUnits:e.maxWorkUnits??n.maxWorkUnits,maxTraversalEntries:e.maxTraversalEntries??n.maxTraversalEntries,maxTraversalDepth:e.maxTraversalDepth??n.maxTraversalDepth,maxTraversalWork:e.maxTraversalWork??n.maxTraversalWork,maxLiveBytes:e.maxLiveBytes??n.maxLiveBytes,maxInputBytes:e.maxInputBytes??n.maxInputBytes,maxFileSystemBytes:e.maxFileSystemBytes??n.maxFileSystemBytes,maxDatabaseBytes:e.maxDatabaseBytes??n.maxDatabaseBytes,maxDatabaseResultBytes:e.maxDatabaseResultBytes??n.maxDatabaseResultBytes,maxArchiveBytes:e.maxArchiveBytes??n.maxArchiveBytes,maxArchiveCompressedBytes:e.maxArchiveCompressedBytes??n.maxArchiveCompressedBytes,maxArchiveEntryBytes:e.maxArchiveEntryBytes??n.maxArchiveEntryBytes,maxArchiveEntries:e.maxArchiveEntries??n.maxArchiveEntries,maxWorkerMessageBytes:e.maxWorkerMessageBytes??n.maxWorkerMessageBytes,maxExecutionTimeMs:e.maxExecutionTimeMs??n.maxExecutionTimeMs,maxExtensionCleanupTimeMs:e.maxExtensionCleanupTimeMs??n.maxExtensionCleanupTimeMs,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??n.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??n.maxPythonTimeoutMs,maxJsTimeoutMs:e.maxJsTimeoutMs??n.maxJsTimeoutMs,maxGlobOperations:e.maxGlobOperations??n.maxGlobOperations,maxStringLength:e.maxStringLength??n.maxStringLength,maxArrayElements:e.maxArrayElements??n.maxArrayElements,maxHeredocSize:e.maxHeredocSize??n.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??n.maxSubstitutionDepth,maxBraceExpansionResults:e.maxBraceExpansionResults??n.maxBraceExpansionResults,maxOutputSize:e.maxOutputSize??n.maxOutputSize,maxFileDescriptors:e.maxFileDescriptors??n.maxFileDescriptors,maxSourceDepth:e.maxSourceDepth??n.maxSourceDepth};for(let s of Object.keys(r)){let i=r[s];if(i!==Number.POSITIVE_INFINITY&&(!Number.isSafeInteger(i)||i<0))throw new RangeError(`${s} must be a non-negative safe integer or positive Infinity`)}return r}function Qf(e){let{executionLimits:t,executionLimitProfile:n,fs:r,stdin:s=Xs,...i}=e;return{fs:r,fsIdentity:i.fsIdentity??Tr(r),cwd:"/",env:new Map,stdin:s,limits:Lr(t,n),...i}}function xa(e){return"load"in e&&typeof e.load=="function"}function Kf(e,t,n={}){return{name:e,trusted:n.trusted!==!1,execute:t}}function $a(e){let t=null,n=null;return{name:e.name,trusted:e.trusted!==!1,async execute(r,s){if(!t){let o=n;o||(o=e.load().then(a=>(t=a,a)),n=o);try{t=await o}catch(a){throw n===o&&(n=null),a}}let i=t;if(!i)throw new Error(`Failed to load command: ${e.name}`);return i.execute(r,s)}}}var Ca=Object.freeze(Object.create(null)),Mr=class{limits;signal;commandCount=0;workUnits=0;liveBytes=0;inputBytes=0;outputBytes=0;countersByKind=new Map;bytesByKind=new Map;depthByKind=new Map;cleanupCallbacks=[];poisoned;closed=!1;startedAt=Date.now();get remainingLiveBytes(){return Math.max(0,this.limits.maxLiveBytes-this.liveBytes)}get outputBytesUsed(){return this.outputBytes}constructor(t,n=void 0){this.limits=t,this.signal=n}fail(t){throw this.poisoned??=t,this.poisoned}poisonAfterAbort(t){this.poisoned??=t}assertUsable(){if(this.poisoned)throw this.poisoned;if(this.closed)throw new Error("execution budget is already closed");this.throwIfAborted()}chargeCommand(){return this.consume("commands",1,"execution")}consumeWork(t=1,n="execution"){return this.consume("work",t,n)}consumeLimited(t,n,r,s=t){this.assertUsable();let i=this.countersByKind.get(t)??0;return(!Number.isSafeInteger(n)||n<0||!Number.isSafeInteger(r)||r<0||n>r-i)&&this.fail(new x(`${s}: ${t} work limit exceeded (${r})`,"iterations")),n>this.limits.maxWorkUnits-this.workUnits&&this.fail(new x(`${s}: aggregate work limit exceeded (${this.limits.maxWorkUnits})`,"iterations")),this.countersByKind.set(t,i+n),this.workUnits+=n,i+n}consumeInput(t,n="execution"){return this.assertUsable(),(!Number.isSafeInteger(t)||t<0||t>this.limits.maxInputBytes-this.inputBytes)&&this.fail(new x(`${n}: aggregate input size limit exceeded (${this.limits.maxInputBytes} bytes)`,"string_length")),this.inputBytes+=t,this.inputBytes}consume(t,n=1,r=t){this.assertUsable();let s=this.countersByKind.get(t)??0,i=t==="commands"?this.commandCount:this.workUnits,o=t==="commands"?this.limits.maxCommandCount:this.limits.maxWorkUnits;(!Number.isSafeInteger(n)||n<0||n>o-i)&&this.fail(new x(t==="commands"?`too many commands executed (>${o}), increase executionLimits.maxCommandCount`:`${r}: ${t} work limit exceeded (${o})`,t==="commands"?"commands":"iterations"));let a=i+n;return t==="commands"?this.commandCount=a:this.workUnits=a,this.countersByKind.set(t,s+n),a}reserveBytes(t,n,r){this.assertUsable();let s=typeof t=="string"?t:"live",i=typeof t=="string"?n:t,o=typeof t=="string"?r??s:n??"execution";(!Number.isSafeInteger(i)||i<0||i>this.limits.maxLiveBytes-this.liveBytes)&&this.fail(new x(`${o}: live byte limit exceeded (${this.limits.maxLiveBytes} bytes)`,"string_length")),this.liveBytes+=i,this.bytesByKind.set(s,(this.bytesByKind.get(s)??0)+i);let a=!1;return{release:()=>{if(a)return;a=!0,this.liveBytes-=i;let l=(this.bytesByKind.get(s)??i)-i;l<=0?this.bytesByKind.delete(s):this.bytesByKind.set(s,l)}}}appendOutput(t,n,r="execution",s=0,i="text"){this.assertUsable();let o=i==="bytes"?n.length:B(n);(!Number.isSafeInteger(s)||s<0||s>o)&&this.fail(new x(`${r}: invalid ${t} accounting`,"output_size"));let a=o-s;return a>this.limits.maxOutputSize-this.outputBytes&&this.fail(new x(`${r}: total output size exceeded (>${this.limits.maxOutputSize} bytes), increase executionLimits.maxOutputSize`,"output_size")),this.outputBytes+=a,o}accountResult(t,n="execution",r=Number.POSITIVE_INFINITY){let s=t.internalOutputAccounting,i=Math.min(s?.stdout??0,r),o=Math.min(s?.stderr??0,Math.max(0,r-i)),a=this.appendOutput("stdout",t.stdout,n,i,t.stdoutKind==="bytes"||t.stdoutEncoding==="binary"?"bytes":"text"),l=this.appendOutput("stderr",t.stderr,n,o);return Object.isExtensible(t)?(t.internalOutputAccounting={stdout:a,stderr:l},t):a===0&&l===0?t:{...t,internalOutputAccounting:{stdout:a,stderr:l}}}relinquishOutput(t,n,r){this.assertUsable(),r!==Ca&&this.fail(new x(`${n}: unauthorized output accounting release`,"output_size")),(!Number.isSafeInteger(t)||t<0||t>this.outputBytes)&&this.fail(new x(`${n}: invalid output accounting release`,"output_size")),this.outputBytes-=t}enterDepth(t,n=this.limits.maxCallDepth,r){this.assertUsable();let s=typeof n=="number"?n:this.limits.maxCallDepth,i=typeof n=="string"?n:r??t,o=this.depthByKind.get(t)??0;o>=s&&this.fail(new x(`${i}: maximum depth (${s}) exceeded`,"recursion")),this.depthByKind.set(t,o+1);let a=!1;return{release:()=>{if(a)return;a=!0;let l=(this.depthByKind.get(t)??1)-1;l<=0?this.depthByKind.delete(t):this.depthByKind.set(t,l)}}}throwIfAborted(t="execution"){this.signal?.aborted&&this.fail(new ze("",`bash: ${t} aborted
|
|
3
|
+
`)),Date.now()-this.startedAt>this.limits.maxExecutionTimeMs&&this.fail(new ze("",`bash: ${t} exceeded execution deadline (${this.limits.maxExecutionTimeMs}ms)
|
|
4
|
+
`))}remainingTimeMs(){return Math.max(0,this.limits.maxExecutionTimeMs-(Date.now()-this.startedAt))}registerCleanup(t){this.assertUsable(),this.cleanupCallbacks.push(t);let n=!0;return()=>{if(!n)return;n=!1;let r=this.cleanupCallbacks.indexOf(t);r>=0&&this.cleanupCallbacks.splice(r,1)}}async close(){if(this.closed)return;this.closed=!0;let t=[],n=Date.now()+this.limits.maxExtensionCleanupTimeMs;for(let r=this.cleanupCallbacks.length-1;r>=0;r--)try{let s=n-Date.now();if(s<=0){t.push(new Error("execution cleanup grace period exceeded"));break}let i,o=await Promise.race([Promise.resolve().then(this.cleanupCallbacks[r]).then(()=>({ok:!0}),a=>({ok:!1,error:a})),new Promise(a=>{i=Yn(()=>a({ok:!1,error:new Error("execution cleanup grace period exceeded")}),s)})]);if(Jn(i),!o.ok&&(t.push(o.error),Date.now()>=n))break}catch(s){t.push(s)}if(this.cleanupCallbacks.length=0,this.depthByKind.clear(),this.bytesByKind.clear(),this.liveBytes=0,t.length>0)throw new AggregateError(t,"execution cleanup failed")}assertExecDepth(t){this.assertUsable(),t>this.limits.maxExecDepth&&this.fail(new x(`maximum nested execution depth (${this.limits.maxExecDepth}) exceeded`,"recursion"))}};function Na(e){let t=Object.create(null);return Object.defineProperties(t,{remainingLiveBytes:{enumerable:!0,get:()=>e.remainingLiveBytes},consumeWork:{enumerable:!0,value:e.consumeWork.bind(e)},consumeLimited:{enumerable:!0,value:e.consumeLimited.bind(e)},consumeInput:{enumerable:!0,value:e.consumeInput.bind(e)},reserveBytes:{enumerable:!0,value:e.reserveBytes.bind(e)},enterDepth:{enumerable:!0,value:e.enterDepth.bind(e)},throwIfAborted:{enumerable:!0,value:e.throwIfAborted.bind(e)},remainingTimeMs:{enumerable:!0,value:e.remainingTimeMs.bind(e)},registerCleanup:{enumerable:!0,value:e.registerCleanup.bind(e)}}),Object.freeze(t)}function Ra(e,t,n="pipeline"){e.relinquishOutput(t,n,Ca)}var fn=new TextEncoder;function Xf(e){return typeof e=="object"&&e!==null&&!(e instanceof Uint8Array)&&"content"in e}var ft=class{data=new Map;entryIdentities=new WeakMap;nextEntryIdentity=1;maxTotalBytes;retainedBytes=0;contentReferences=new WeakMap;materializedContent(t){return t?.type==="file"&&"content"in t?t.content:null}storedByteLength(t){return t===null?0:t instanceof Uint8Array?t.byteLength:B(t)}wouldReleaseBytes(t){let n=this.materializedContent(t);return n===null?0:n instanceof Uint8Array?this.contentReferences.get(n)===1?n.byteLength:0:this.storedByteLength(n)}assertCanAllocate(t,n){let r=this.wouldReleaseBytes(this.data.get(t));if(!Number.isSafeInteger(n)||n<0||n>this.maxTotalBytes-this.retainedBytes+r)throw new Error(`ENOSPC: in-memory filesystem byte limit exceeded (${this.maxTotalBytes} bytes)`)}setEntry(t,n){let r=this.data.get(t),s=this.materializedContent(r),i=this.materializedContent(n);if(s===i){this.data.set(t,n);return}let o=this.wouldReleaseBytes(r),a=i instanceof Uint8Array?this.contentReferences.has(i)?0:i.byteLength:this.storedByteLength(i);if(a>this.maxTotalBytes-this.retainedBytes+o)throw new Error(`ENOSPC: in-memory filesystem byte limit exceeded (${this.maxTotalBytes} bytes)`);if(s instanceof Uint8Array){let l=this.contentReferences.get(s)??0;l<=1?this.contentReferences.delete(s):this.contentReferences.set(s,l-1)}i instanceof Uint8Array&&this.contentReferences.set(i,(this.contentReferences.get(i)??0)+1),this.retainedBytes+=a-o,this.data.set(t,n)}deleteEntry(t){let n=this.data.get(t);if(!n)return!1;let r=this.materializedContent(n),s=this.wouldReleaseBytes(n);if(r instanceof Uint8Array){let i=this.contentReferences.get(r)??0;i<=1?this.contentReferences.delete(r):this.contentReferences.set(r,i-1)}return this.retainedBytes-=s,this.data.delete(t)}contentByteLength(t,n){if(t instanceof Uint8Array)return t.byteLength;if(n==="hex")return Math.floor(t.length/2);if(n==="base64"){let r=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.max(0,Math.floor(t.length*3/4)-r)}return n==="binary"||n==="latin1"?t.length:B(t)}identityFor(t){let n=this.entryIdentities.get(t);return n||(n=`memfs:${this.nextEntryIdentity++}`,this.entryIdentities.set(t,n)),n}constructor(t,n={}){if(this.maxTotalBytes=n.maxTotalBytes??1024*1024*1024,!Number.isSafeInteger(this.maxTotalBytes)||this.maxTotalBytes<0)throw new Error("InMemoryFs: invalid maxTotalBytes");if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),t)for(let[r,s]of Object.entries(t))typeof s=="function"?this.writeFileLazy(r,s):Xf(s)?this.writeFileSync(r,s.content,void 0,{mode:s.mode,mtime:s.mtime}):this.writeFileSync(r,s)}ensureParentDirs(t){let n=xn(t);n!=="/"&&(this.data.has(n)||(this.ensureParentDirs(n),this.data.set(n,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(t,n,r,s){V(t,"write");let i=W(t);this.ensureParentDirs(i);let o=it(r);this.assertCanAllocate(i,this.contentByteLength(n,o));let a=Rt(n,o);this.setEntry(i,{type:"file",content:a,mode:s?.mode??420,mtime:s?.mtime??new Date})}writeFileLazy(t,n,r){V(t,"write");let s=W(t);this.ensureParentDirs(s),this.setEntry(s,{type:"file",lazy:n,mode:r?.mode??420,mtime:r?.mtime??new Date})}async materializeLazy(t,n){let r=await n.lazy(),s=typeof r=="string"?fn.encode(r):r,i={type:"file",content:s,mode:n.mode,mtime:n.mtime};return this.assertCanAllocate(t,s.byteLength),this.setEntry(t,i),i}async readFile(t,n){let r=await this.readFileBuffer(t),s=it(n);return Ot(r,s)}async readFileBytes(t){let n=await this.readFileBuffer(t);return Ot(n,"binary")}async readFileBuffer(t){V(t,"open");let n=this.resolvePathWithSymlinks(t),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if("lazy"in r){let s=await this.materializeLazy(n,r);return s.content instanceof Uint8Array?s.content:fn.encode(s.content)}return r.content instanceof Uint8Array?r.content:fn.encode(r.content)}async writeFile(t,n,r){this.writeFileSync(t,n,r)}async appendFile(t,n,r){V(t,"append");let s=W(t),i=this.data.get(s);if(i&&i.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${t}'`);let o=it(r),a=this.contentByteLength(n,o);if(i?.type==="file"){let l=i;"lazy"in l&&(l=await this.materializeLazy(s,l));let c="content"in l&&l.content instanceof Uint8Array?l.content:fn.encode("content"in l?l.content:"");this.assertCanAllocate(s,c.byteLength+a);let u=Rt(n,o),f=new Uint8Array(c.length+u.length);f.set(c),f.set(u,c.length),this.setEntry(s,{type:"file",content:f,mode:l.mode,mtime:new Date})}else this.writeFileSync(t,n,r)}async exists(t){if(t.includes("\0"))return!1;try{let n=this.resolvePathWithSymlinks(t);return this.data.has(n)}catch{return!1}}async stat(t){V(t,"stat");let n=this.resolvePathWithSymlinks(t),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);r.type==="file"&&"lazy"in r&&(r=await this.materializeLazy(n,r));let s=0;return r.type==="file"&&"content"in r&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=fn.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date,identity:this.identityFor(r)}}async lstat(t){V(t,"lstat");let n=this.resolveIntermediateSymlinks(t),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};r.type==="file"&&"lazy"in r&&(r=await this.materializeLazy(n,r));let s=0;return r.type==="file"&&"content"in r&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=fn.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date,identity:this.identityFor(r)}}resolveIntermediateSymlinks(t){let n=W(t);if(n==="/")return"/";let r=n.slice(1).split("/");if(r.length<=1)return n;let s="",i=new Set;for(let o=0;o<r.length-1;o++){let a=r[o];s=`${s}/${a}`;let l=this.data.get(s),c=0,u=40;for(;l&&l.type==="symlink"&&c<u;){if(i.has(s))throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`);i.add(s),s=$n(s,l.target),l=this.data.get(s),c++}if(c>=u)throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`)}return`${s}/${r[r.length-1]}`}resolvePathWithSymlinks(t){let n=W(t);if(n==="/")return"/";let r=n.slice(1).split("/"),s="",i=new Set;for(let o of r){s=`${s}/${o}`;let a=this.data.get(s),l=0,c=40;for(;a&&a.type==="symlink"&&l<c;){if(i.has(s))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);i.add(s),s=$n(s,a.target),a=this.data.get(s),l++}if(l>=c)throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`)}return s}async mkdir(t,n){this.mkdirSync(t,n)}mkdirSync(t,n){V(t,"mkdir");let r=W(t);if(this.data.has(r)){if(this.data.get(r)?.type==="file")throw new Error(`EEXIST: file already exists, mkdir '${t}'`);if(!n?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${t}'`);return}let s=xn(r);if(s!=="/"&&!this.data.has(s))if(n?.recursive)this.mkdirSync(s,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.data.set(r,{type:"directory",mode:493,mtime:new Date})}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){V(t,"scandir");let n=W(t),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let s=new Set;for(;r&&r.type==="symlink";){if(s.has(n))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);s.add(n),n=$n(n,r.target),r=this.data.get(n)}if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);if(r.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);let i=n==="/"?"/":`${n}/`,o=new Map;for(let[a,l]of this.data.entries())if(a!==n&&a.startsWith(i)){let c=a.slice(i.length),u=c.split("/")[0];u&&!c.includes("/",u.length)&&!o.has(u)&&o.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}return Array.from(o.values()).sort((a,l)=>a.name<l.name?-1:a.name>l.name?1:0)}async rm(t,n){V(t,"rm");let r=W(t),s=this.data.get(r);if(!s){if(n?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}if(s.type==="directory"){let i=await this.readdir(r);if(i.length>0){if(!n?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let o of i){let a=Nt(r,o);await this.rm(a,n)}}}this.deleteEntry(r)}async cp(t,n,r){V(t,"cp"),V(n,"cp");let s=W(t),i=W(n),o=this.data.get(s);if(!o)throw new Error(`ENOENT: no such file or directory, cp '${t}'`);if(o.type==="file")if(this.ensureParentDirs(i),"content"in o){let a=o.content instanceof Uint8Array?o.content.byteLength:fn.encode(o.content).byteLength;this.assertCanAllocate(i,a);let l=o.content instanceof Uint8Array?new Uint8Array(o.content):o.content;this.setEntry(i,{...o,content:l})}else this.setEntry(i,{...o});else if(o.type==="symlink")this.ensureParentDirs(i),this.data.set(i,{...o});else if(o.type==="directory"){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);if(Ct(s,i))throw new Error(`EINVAL: cannot copy '${t}' into itself, '${n}'`);await this.mkdir(i,{recursive:!0});let a=await this.readdir(s);for(let l of a){let c=Nt(s,l),u=Nt(i,l);await this.cp(c,u,r)}}}async mv(t,n){V(t,"mv"),V(n,"mv");let r=W(t),s=W(n);if(r===s)return;let i=this.data.get(r);if(!i)throw new Error(`ENOENT: no such file or directory, mv '${t}'`);if(i.type==="directory"&&Ct(r,s))throw new Error(`EINVAL: cannot move '${t}' into itself, '${n}'`);if(i.type==="directory"){await this.mkdir(s,{recursive:!0});let o=await this.readdir(r);for(let a of o)await this.mv(Nt(r,a),Nt(s,a));this.deleteEntry(r);return}this.ensureParentDirs(s),this.setEntry(s,i),this.deleteEntry(r)}getAllPaths(){return Array.from(this.data.keys())}resolvePath(t,n){return Bt(t,n)}async chmod(t,n){V(t,"chmod");let r=W(t),s=this.data.get(r);if(!s)throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);s.mode=n}async symlink(t,n){V(n,"symlink");let r=W(n);if(this.data.has(r))throw new Error(`EEXIST: file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:t,mode:511,mtime:new Date})}async link(t,n){V(t,"link"),V(n,"link");let r=W(t),s=W(n),i=this.data.get(r);if(!i)throw new Error(`ENOENT: no such file or directory, link '${t}'`);if(i.type!=="file")throw new Error(`EPERM: operation not permitted, link '${t}'`);if(this.data.has(s))throw new Error(`EEXIST: file already exists, link '${n}'`);let o=i;"lazy"in o&&(o=await this.materializeLazy(r,o)),this.ensureParentDirs(s);let a={type:"file",content:o.content,mode:o.mode,mtime:o.mtime};this.entryIdentities.set(a,this.identityFor(o)),this.setEntry(s,a)}async readlink(t){V(t,"readlink");let n=W(t),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return r.target}async realpath(t){V(t,"realpath");let n=this.resolvePathWithSymlinks(t);if(!this.data.has(n))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return n}async utimes(t,n,r){V(t,"utimes");let s=W(t),i=this.resolvePathWithSymlinks(s),o=this.data.get(i);if(!o)throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);o.mtime=r}};var Oa="5.1.0(1)-release",Da="Linux version 5.15.0-generic (just-bash) #1 SMP PREEMPT";function ni(e){let{pid:t,ppid:n,uid:r,gid:s}=e;return`Name: bash
|
|
5
5
|
State: R (running)
|
|
6
6
|
Pid: ${t}
|
|
7
7
|
PPid: ${n}
|
|
8
8
|
Uid: ${r} ${r} ${r} ${r}
|
|
9
9
|
Gid: ${s} ${s} ${s} ${s}
|
|
10
|
-
`}function
|
|
10
|
+
`}function Yf(e){let t=e;return typeof t.mkdirSync=="function"&&typeof t.writeFileSync=="function"}function Jf(e,t){e.mkdirSync("/bin",{recursive:!0}),e.mkdirSync("/usr/bin",{recursive:!0}),t&&(e.mkdirSync("/home/user",{recursive:!0}),e.mkdirSync("/tmp",{recursive:!0}))}function ed(e){e.mkdirSync("/dev",{recursive:!0}),e.mkdirSync("/dev/fd",{recursive:!0}),e.writeFileSync("/dev/null",""),e.writeFileSync("/dev/zero",new Uint8Array(0)),e.writeFileSync("/dev/stdin",""),e.writeFileSync("/dev/stdout",""),e.writeFileSync("/dev/stderr","")}function td(e,t){e.mkdirSync("/proc/self/fd",{recursive:!0}),e.writeFileSync("/proc/version",`${Da}
|
|
11
11
|
`),e.writeFileSync("/proc/self/exe","/bin/bash"),e.writeFileSync("/proc/self/cmdline","bash\0"),e.writeFileSync("/proc/self/comm",`bash
|
|
12
|
-
`),e.writeFileLazy?e.writeFileLazy("/proc/self/status",()=>
|
|
13
|
-
`||
|
|
14
|
-
|
|
15
|
-
`&&
|
|
12
|
+
`),e.writeFileLazy?e.writeFileLazy("/proc/self/status",()=>ni(t)):e.writeFileSync("/proc/self/status",ni(t)),e.writeFileSync("/proc/self/fd/0","/dev/stdin"),e.writeFileSync("/proc/self/fd/1","/dev/stdout"),e.writeFileSync("/proc/self/fd/2","/dev/stderr")}function Ia(e,t,n={pid:1,ppid:0,uid:1e3,gid:1e3}){Yf(e)&&(Jf(e,t),ed(e),td(e,n))}function Me(e){return{kind:e.kind,elements:new Map(e.elements)}}function ot(e){return new Map(Array.from(e??[],([t,n])=>[t,Me(n)]))}function Pe(e,t){return e.state.arrays?.get(t)}function rr(e,t,n="indexed"){e.state.arrays??=new Map;let r=e.state.arrays.get(t);return r||(r={kind:n,elements:new Map},e.state.arrays.set(t,r)),r}function zt(e,t,n){let r=rr(e,t,n);return r.kind=n,r}function Ce(e,t){return e.state.arrays?.has(t)??!1}function le(e,t,n){return Pe(e,t)?.elements.get(String(n))}function Ut(e,t,n){return Pe(e,t)?.elements.has(String(n))??!1}function G(e,t,n,r,s){let i=rr(e,t,s),o=String(n);if(!i.elements.has(o)&&i.elements.size>=e.limits.maxArrayElements)throw new x(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");if(B(r)>e.limits.maxStringLength)throw new x(`array value string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");i.elements.set(o,r)}function dn(e,t,n,r=!1){let s=new Set(r?[]:Pe(e,t)?.elements.keys()??[]);for(let i of n)if(s.add(String(i)),s.size>e.limits.maxArrayElements)throw new x(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements")}function pn(e,t,n){return Pe(e,t)?.elements.delete(String(n))??!1}function sr(e,t){e.state.arrays?.delete(t),e.state.associativeArrays?.delete(t)}function ve(e,t){return Array.from(Pe(e,t)?.elements.keys()??[]).filter(r=>/^(0|[1-9]\d*)$/.test(r)).map(Number).sort((r,s)=>r-s)}function Ee(e,t){rr(e,t,e.state.associativeArrays?.has(t)?"associative":"indexed").elements.clear()}function Et(e,t){return Array.from(Pe(e,t)?.elements.keys()??[]).sort()}function Br(e){return e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function ri(e){if(e.parts.length<2)return null;let t=e.parts[0],n=e.parts[1];if(t.type!=="Glob"||!t.pattern.startsWith("["))return null;let r,s=n,i=1;if(n.type==="Literal"&&n.value.startsWith("]")){let f=n.value.slice(1);if(f.startsWith("+=")||f.startsWith("="))r=t.pattern.slice(1);else if(f===""){if(e.parts.length<3)return null;let d=e.parts[2];if(d.type!=="Literal"||!d.value.startsWith("=")&&!d.value.startsWith("+="))return null;r=t.pattern.slice(1),s=d,i=2}else return null}else if(t.pattern==="["&&(n.type==="DoubleQuoted"||n.type==="SingleQuoted")){if(e.parts.length<3)return null;let f=e.parts[2];if(f.type!=="Literal"||!f.value.startsWith("]=")&&!f.value.startsWith("]+="))return null;if(n.type==="SingleQuoted")r=n.value;else{r="";for(let d of n.parts)(d.type==="Literal"||d.type==="Escaped")&&(r+=d.value)}s=f,i=2}else if(t.pattern.endsWith("]")){if(n.type!=="Literal"||!n.value.startsWith("=")&&!n.value.startsWith("+="))return null;r=t.pattern.slice(1,-1)}else return null;r=Br(r);let o;if(s.type!=="Literal")return null;s.value.startsWith("]=")||s.value.startsWith("]+=")?o=s.value.slice(1):o=s.value;let a=o.startsWith("+=");if(!a&&!o.startsWith("="))return null;let l=[],c=a?2:1,u=o.slice(c);u&&l.push({type:"Literal",value:u});for(let f=i+1;f<e.parts.length;f++){let d=e.parts[f];d.type==="BraceExpansion"?l.push({type:"Literal",value:nd(d)}):l.push(d)}return{key:r,valueParts:l,append:a}}function nd(e){return`{${e.items.map(n=>{if(n.type==="Range"){let r=n.startStr??String(n.start),s=n.endStr??String(n.end),i=`${r}..${s}`;return n.step&&(i+=`..${n.step}`),i}return Nn(n.word)}).join(",")}}`}function Nn(e){let t="";for(let n of e.parts)switch(n.type){case"Literal":t+=n.value;break;case"Glob":t+=n.pattern;break;case"SingleQuoted":t+=n.value;break;case"DoubleQuoted":for(let r of n.parts)(r.type==="Literal"||r.type==="Escaped")&&(t+=r.value);break;case"Escaped":t+=n.value;break;case"BraceExpansion":t+="{",t+=n.items.map(r=>r.type==="Range"?`${r.startStr}..${r.endStr}${r.step?`..${r.step}`:""}`:Nn(r.word)).join(","),t+="}";break;case"TildeExpansion":t+="~",n.user&&(t+=n.user);break}return t}var rd=["allexport","errexit","noglob","noclobber","noexec","nounset","pipefail","posix","verbose","xtrace"],sd=["braceexpand","hashall","interactive-comments"];function si(e){let t=[],n=[...sd.map(r=>({name:r,enabled:!0})),...rd.map(r=>({name:r,enabled:e[r]}))].sort((r,s)=>r.name.localeCompare(s.name));for(let r of n)r.enabled&&t.push(r.name);return t.join(":")}function Rn(e){e.state.env.set("SHELLOPTS",si(e.state.options))}var id=["dotglob","expand_aliases","extglob","failglob","globskipdots","globstar","lastpipe","nocaseglob","nocasematch","nullglob","xpg_echo"];function ii(e){let t=[];for(let n of id)e[n]&&t.push(n);return t.join(":")}function oi(e){e.state.env.set("BASHOPTS",ii(e.state.shoptOptions))}var M={script(e){return{type:"Script",statements:e}},statement(e,t=[],n=!1,r,s){let i={type:"Statement",pipelines:e,operators:t,background:n};return r&&(i.deferredError=r),s!==void 0&&(i.sourceText=s),i},pipeline(e,t=!1,n=!1,r=!1,s){return{type:"Pipeline",commands:e,negated:t,timed:n,timePosix:r,pipeStderr:s}},simpleCommand(e,t=[],n=[],r=[]){return{type:"SimpleCommand",name:e,args:t,assignments:n,redirections:r}},word(e){return{type:"Word",parts:e}},literal(e){return{type:"Literal",value:e}},singleQuoted(e){return{type:"SingleQuoted",value:e}},doubleQuoted(e){return{type:"DoubleQuoted",parts:e}},escaped(e){return{type:"Escaped",value:e}},parameterExpansion(e,t=null){return{type:"ParameterExpansion",parameter:e,operation:t}},commandSubstitution(e,t=!1){return{type:"CommandSubstitution",body:e,legacy:t}},arithmeticExpansion(e){return{type:"ArithmeticExpansion",expression:e}},processSubstitution(e,t){return{type:"ProcessSubstitution",body:e,direction:t}},assignment(e,t,n=!1,r=null){return{type:"Assignment",name:e,value:t,append:n,array:r}},redirection(e,t,n=null,r){let s={type:"Redirection",fd:n,operator:e,target:t};return r&&(s.fdVariable=r),s},hereDoc(e,t,n=!1,r=!1,s){let i={type:"HereDoc",delimiter:e,content:t,stripTabs:n,quoted:r};return s!==void 0&&(i.terminated=s),i},ifNode(e,t=null,n=[]){return{type:"If",clauses:e,elseBody:t,redirections:n}},forNode(e,t,n,r=[]){return{type:"For",variable:e,words:t,body:n,redirections:r}},whileNode(e,t,n=[]){return{type:"While",condition:e,body:t,redirections:n}},untilNode(e,t,n=[]){return{type:"Until",condition:e,body:t,redirections:n}},caseNode(e,t,n=[]){return{type:"Case",word:e,items:t,redirections:n}},caseItem(e,t,n=";;"){return{type:"CaseItem",patterns:e,body:t,terminator:n}},subshell(e,t=[]){return{type:"Subshell",body:e,redirections:t}},group(e,t=[]){return{type:"Group",body:e,redirections:t}},functionDef(e,t,n=[],r){return{type:"FunctionDef",name:e,body:t,redirections:n,sourceFile:r}},conditionalCommand(e,t=[],n){return{type:"ConditionalCommand",expression:e,redirections:t,line:n}},arithmeticCommand(e,t=[],n){return{type:"ArithmeticCommand",expression:e,redirections:t,line:n}}};function _a(e,t){let n=e.length,r=t+3,s=2,i=!1,o=!1;for(;r<n&&s>0;){let a=e[r];if(i){a==="'"&&(i=!1),r++;continue}if(o){if(a==="\\"){r+=2;continue}a==='"'&&(o=!1),r++;continue}if(a==="'"){i=!0,r++;continue}if(a==='"'){o=!0,r++;continue}if(a==="\\"){r+=2;continue}if(a==="("){s++,r++;continue}if(a===")"){if(s--,s===1){let l=r+1;return!(l<n&&e[l]===")")}if(s===0)return!1;r++;continue}if(s===1&&(a==="|"&&r+1<n&&e[r+1]==="|"||a==="&"&&r+1<n&&e[r+1]==="&"||a==="|"&&r+1<n&&e[r+1]!=="|"))return!0;r++}return!1}function Wr(e,t){let n="",r=t,s=0,i=!1,o,a=l=>l===" "||l===" "||l===`
|
|
13
|
+
`||l===";"||l==="&"||l==="|"||l==="<"||l===">"||l==="("||l===")";for(;r<e.length;){let l=e[r];if(l==="'"){let c=s>0;for(c||(i=!0),c&&(n+=l),r++;r<e.length&&e[r]!=="'";)n+=e[r],r++;r<e.length?(c&&(n+=e[r]),r++):o=l;continue}if(l==='"'){let c=s>0;for(c||(i=!0),c&&(n+=l),r++;r<e.length&&e[r]!=='"';){if(e[r]==="\\"&&r+1<e.length){if(c){n+=e.slice(r,r+2),r+=2;continue}let u=e[r+1];if(u==="$"||u==="`"||u==='"'||u==="\\"||u===`
|
|
14
|
+
`){r+=2,u!==`
|
|
15
|
+
`&&(n+=u);continue}}n+=e[r],r++}r<e.length?(c&&(n+=e[r]),r++):o=l;continue}if(l==="\\"&&r+1<e.length){if(s>0){n+=e.slice(r,r+2),r+=2;continue}i=!0;let c=e[r+1];c!==`
|
|
16
|
+
`&&(n+=c),r+=2;continue}if(s===0&&(l==="$"||l==="<"||l===">")&&e[r+1]==="("){n+=`${l}(`,s=1,r+=2;continue}if(s===0&&a(l))break;s>0&&(l==="("?s++:l===")"&&s--),n+=l,r++}return{delim:n,endPos:r,quoted:i,unclosedQuote:o,unclosedSubstitution:s>0}}function od(e,t,n){let r=t+1;for(let{delim:s,stripTabs:i}of n)for(;;){if(r>=e.length)return e.length;let o=e.indexOf(`
|
|
17
|
+
`,r);o===-1&&(o=e.length);let a=e.slice(r,o);if(i&&(a=a.replace(/^\t+/,"")),a===s){r=o+1;break}if(o>=e.length)return e.length;r=o+1}return Math.min(r,e.length)}function Ta(e,t,n){let r=1,s=t,i=!1,o=!1,a=0,l=!1,c="",u=[],f=0;for(;s<e.length&&r>0;){let d=e[s];if(i)d==="'"&&(i=!1);else if(o)d==="\\"&&s+1<e.length?s++:d==='"'&&(o=!1);else{if(d==="("&&e[s+1]==="("?f++:d===")"&&e[s+1]===")"&&f>0&&f--,f===0&&d==="<"&&e[s+1]==="<"&&e[s+2]!=="<"){let p=s+2,h=!1;for(e[p]==="-"&&(h=!0,p++);e[p]===" "||e[p]===" ";)p++;let{delim:m,endPos:E,unclosedQuote:b,unclosedSubstitution:g}=Wr(e,p);if(b&&n(`unexpected EOF while looking for matching \`${b}'`),g&&n("unexpected EOF while looking for matching `)'"),m.length>0){u.push({delim:m,stripTabs:h}),c="",s=E;continue}}if(d===`
|
|
18
|
+
`&&u.length>0){let p=od(e,s,u);u.length=0,c="",s=p;continue}d==="'"?(i=!0,c=""):d==='"'?(o=!0,c=""):d==="\\"&&s+1<e.length?(s++,c=""):/[a-zA-Z_]/.test(d)?c+=d:(c==="case"?(a++,l=!1):c==="in"&&a>0?l=!0:c==="esac"&&a>0&&(a--,l=!1),c="",d==="("?s>0&&e[s-1]==="$"?r++:l||r++:d===")"?l?l=!1:r--:d===";"&&a>0&&s+1<e.length&&e[s+1]===";"&&(l=!0))}r>0&&s++}return r>0&&n("unexpected EOF while looking for matching `)'"),s}function La(e,t,n,r){let s=t+2,i=Ta(e,s,r),o=e.slice(s,i),l=n().parse(o);return{part:M.commandSubstitution(l,!1),endIndex:i+1}}function Ma(e,t,n,r){let s=e[t]==="<"?"input":"output",i=t+2,o=Ta(e,i,r),a=n().parse(e.slice(i,o));return{part:M.processSubstitution(a,s),endIndex:o+1}}function Fa(e,t,n,r,s){let o=t+1,a="";for(;o<e.length&&e[o]!=="`";)if(e[o]==="\\"){let u=e[o+1];u==="$"||u==="`"||u==="\\"||u===`
|
|
16
19
|
`||n&&u==='"'?(u!==`
|
|
17
|
-
`&&(
|
|
18
|
-
`||e===";"||e==="&"||e==="|"||e==="("||e===")"||e==="<"||e===">"}var
|
|
19
|
-
`)r+=2,i++,s=1;else break}this.pos=r,this.column=s,this.line=i}nextToken(){let t=this.input,n=this.pos,r=this.line,s=this.column,i=t[n],
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
20
|
+
`&&(a+=u),o+=2):(a+=e[o],o++)}else a+=e[o],o++;o>=e.length&&s("unexpected EOF while looking for matching ``'");let c=r().parse(a);return{part:M.commandSubstitution(c,!0),endIndex:o+1}}var ad=10485760,w;(function(e){e.EOF="EOF",e.NEWLINE="NEWLINE",e.SEMICOLON="SEMICOLON",e.AMP="AMP",e.PIPE="PIPE",e.PIPE_AMP="PIPE_AMP",e.AND_AND="AND_AND",e.OR_OR="OR_OR",e.BANG="BANG",e.LESS="LESS",e.GREAT="GREAT",e.DLESS="DLESS",e.DGREAT="DGREAT",e.LESSAND="LESSAND",e.GREATAND="GREATAND",e.LESSGREAT="LESSGREAT",e.DLESSDASH="DLESSDASH",e.CLOBBER="CLOBBER",e.TLESS="TLESS",e.AND_GREAT="AND_GREAT",e.AND_DGREAT="AND_DGREAT",e.LPAREN="LPAREN",e.RPAREN="RPAREN",e.LBRACE="LBRACE",e.RBRACE="RBRACE",e.DSEMI="DSEMI",e.SEMI_AND="SEMI_AND",e.SEMI_SEMI_AND="SEMI_SEMI_AND",e.DBRACK_START="DBRACK_START",e.DBRACK_END="DBRACK_END",e.DPAREN_START="DPAREN_START",e.DPAREN_END="DPAREN_END",e.IF="IF",e.THEN="THEN",e.ELSE="ELSE",e.ELIF="ELIF",e.FI="FI",e.FOR="FOR",e.WHILE="WHILE",e.UNTIL="UNTIL",e.DO="DO",e.DONE="DONE",e.CASE="CASE",e.ESAC="ESAC",e.IN="IN",e.FUNCTION="FUNCTION",e.SELECT="SELECT",e.TIME="TIME",e.COPROC="COPROC",e.WORD="WORD",e.NAME="NAME",e.NUMBER="NUMBER",e.ASSIGNMENT_WORD="ASSIGNMENT_WORD",e.FD_VARIABLE="FD_VARIABLE",e.COMMENT="COMMENT",e.HEREDOC_CONTENT="HEREDOC_CONTENT"})(w||(w={}));var Ye=class extends Error{line;column;constructor(t,n,r){super(`line ${n}: ${t}`),this.line=n,this.column=r,this.name="LexerError"}},ai=new Map([["if",w.IF],["then",w.THEN],["else",w.ELSE],["elif",w.ELIF],["fi",w.FI],["for",w.FOR],["while",w.WHILE],["until",w.UNTIL],["do",w.DO],["done",w.DONE],["case",w.CASE],["esac",w.ESAC],["in",w.IN],["function",w.FUNCTION],["select",w.SELECT],["time",w.TIME],["coproc",w.COPROC]]),ld=new Set(ai.values());function li(e){return ld.has(e)}function Ba(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return!1;let n=e.slice(t[0].length);if(n===""||n==="+")return!0;if(n[0]==="["){let r=0,s=0;for(;s<n.length;s++)if(n[s]==="[")r++;else if(n[s]==="]"&&(r--,r===0))break;if(r!==0||s>=n.length)return!1;let i=n.slice(s+1);return i===""||i==="+"}return!1}function Wa(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r==="[")t++;else if(r==="]")t--;else{if(t===0&&r==="=")return n;if(t===0&&r==="+"&&e[n+1]==="=")return n+1}}return-1}var cd=[[";",";","&",w.SEMI_SEMI_AND],["<","<","<",w.TLESS],["&",">",">",w.AND_DGREAT]],ud=[["[","[",w.DBRACK_START],["]","]",w.DBRACK_END],["(","(",w.DPAREN_START],[")",")",w.DPAREN_END],["&","&",w.AND_AND],["|","|",w.OR_OR],[";",";",w.DSEMI],[";","&",w.SEMI_AND],["|","&",w.PIPE_AMP],[">",">",w.DGREAT],["<","&",w.LESSAND],[">","&",w.GREATAND],["<",">",w.LESSGREAT],[">","|",w.CLOBBER],["&",">",w.AND_GREAT]],fd=new Map([["|",w.PIPE],["&",w.AMP],[";",w.SEMICOLON],["(",w.LPAREN],[")",w.RPAREN],["<",w.LESS],[">",w.GREAT]]);function dd(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function Va(e){return e===" "||e===" "||e===`
|
|
21
|
+
`||e===";"||e==="&"||e==="|"||e==="("||e===")"||e==="<"||e===">"}var Vr=class{input;pos=0;line=1;column=1;tokens=[];pendingHeredocs=[];pendingHeredocDelimiterMode;dparenDepth=0;maxHeredocSize;constructor(t,n){this.input=t,this.maxHeredocSize=n?.maxHeredocSize??ad}tokenize(){let n=this.input.length,r=this.tokens,s=this.pendingHeredocs;for(;this.pos<n;){if(s.length>0&&r.length>0&&r[r.length-1].type===w.NEWLINE){this.readHeredocContent();continue}if(this.skipWhitespace(),this.pos>=n)break;let i=this.nextToken();i&&r.push(i)}return s.length>0&&this.readHeredocContent(),r.push({type:w.EOF,value:"",start:this.pos,end:this.pos,line:this.line,column:this.column}),r}skipWhitespace(){let t=this.input,n=t.length,r=this.pos,s=this.column,i=this.line;for(;r<n;){let o=t[r];if(o===" "||o===" ")r++,s++;else if(o==="\\"&&t[r+1]===`
|
|
22
|
+
`)r+=2,i++,s=1;else break}this.pos=r,this.column=s,this.line=i}nextToken(){let t=this.input,n=this.pos,r=this.line,s=this.column,i=t[n],o=t[n+1],a=t[n+2],l=this.pendingHeredocDelimiterMode;if(this.pendingHeredocDelimiterMode=void 0,l!==void 0&&i!==`
|
|
23
|
+
`&&!(i==="#"&&this.dparenDepth===0))return this.readHeredocDelimiterToken(n,r,s,l);if(i==="#"&&this.dparenDepth===0)return this.readComment(n,r,s);if(i===`
|
|
24
|
+
`)return this.pos=n+1,this.line++,this.column=1,{type:w.NEWLINE,value:`
|
|
25
|
+
`,start:n,end:n+1,line:r,column:s};if(i==="<"&&o==="<"&&a==="-")return this.pos=n+3,this.column=s+3,this.pendingHeredocDelimiterMode=!0,this.makeToken(w.DLESSDASH,"<<-",n,r,s);for(let[u,f,d,p]of cd)if(i===u&&o===f&&a===d)return this.pos=n+3,this.column=s+3,this.makeToken(p,u+f+d,n,r,s);if(i==="<"&&o==="<")return this.pos=n+2,this.column=s+2,this.pendingHeredocDelimiterMode=!1,this.makeToken(w.DLESS,"<<",n,r,s);if(i==="("&&o==="("){let u=this.tokens[this.tokens.length-1];return this.dparenDepth===0&&u?.end===n&&(u.type===w.LESS||u.type===w.GREAT)?(this.pos=n+1,this.column=s+1,this.makeToken(w.LPAREN,"(",n,r,s)):this.dparenDepth>0?(this.pos=n+1,this.column=s+1,this.dparenDepth++,this.makeToken(w.LPAREN,"(",n,r,s)):this.looksLikeNestedSubshells(n+2)||this.dparenClosesWithSpacedParens(n+2)?(this.pos=n+1,this.column=s+1,this.makeToken(w.LPAREN,"(",n,r,s)):(this.pos=n+2,this.column=s+2,this.dparenDepth=1,this.makeToken(w.DPAREN_START,"((",n,r,s))}if(i===")"&&o===")")return this.dparenDepth===1?(this.pos=n+2,this.column=s+2,this.dparenDepth=0,this.makeToken(w.DPAREN_END,"))",n,r,s)):this.dparenDepth>1?(this.pos=n+1,this.column=s+1,this.dparenDepth--,this.makeToken(w.RPAREN,")",n,r,s)):(this.pos=n+1,this.column=s+1,this.makeToken(w.RPAREN,")",n,r,s));for(let[u,f,d]of ud)if(!(u==="("&&f==="("||u===")"&&f===")")&&!(this.dparenDepth>0&&u===";"&&(d===w.DSEMI||d===w.SEMI_AND||d===w.SEMI_SEMI_AND))&&i===u&&o===f){if(d===w.DBRACK_START||d===w.DBRACK_END){let p=t[n+2];if(p!==void 0&&p!==" "&&p!==" "&&p!==`
|
|
26
|
+
`&&p!==";"&&p!=="&"&&p!=="|"&&p!=="("&&p!==")"&&p!=="<"&&p!==">")break}return this.pos=n+2,this.column=s+2,this.makeToken(d,u+f,n,r,s)}if(i==="("&&this.dparenDepth>0)return this.pos=n+1,this.column=s+1,this.dparenDepth++,this.makeToken(w.LPAREN,"(",n,r,s);if(i===")"&&this.dparenDepth>1)return this.pos=n+1,this.column=s+1,this.dparenDepth--,this.makeToken(w.RPAREN,")",n,r,s);let c=fd.get(i);if(c!==void 0)return this.pos=n+1,this.column=s+1,this.makeToken(c,i,n,r,s);if(i==="{"){let u=this.scanFdVariable(n);return u!==null?(this.pos=u.end,this.column=s+(u.end-n),{type:w.FD_VARIABLE,value:u.varname,start:n,end:u.end,line:r,column:s}):o==="}"?(this.pos=n+2,this.column=s+2,{type:w.WORD,value:"{}",start:n,end:n+2,line:r,column:s,quoted:!1,singleQuoted:!1}):this.scanBraceExpansion(n)!==null?this.readWordWithBraceExpansion(n,r,s):this.scanLiteralBraceWord(n)!==null?this.readWordWithBraceExpansion(n,r,s):o!==void 0&&o!==" "&&o!==" "&&o!==`
|
|
27
|
+
`?this.readWord(n,r,s):(this.pos=n+1,this.column=s+1,this.makeToken(w.LBRACE,"{",n,r,s))}return i==="}"?this.isWordCharFollowing(n+1)?this.readWord(n,r,s):(this.pos=n+1,this.column=s+1,this.makeToken(w.RBRACE,"}",n,r,s)):i==="!"?o==="="?(this.pos=n+2,this.column=s+2,this.makeToken(w.WORD,"!=",n,r,s)):(this.pos=n+1,this.column=s+1,this.makeToken(w.BANG,"!",n,r,s)):this.readWord(n,r,s)}looksLikeNestedSubshells(t){let n=this.input,r=n.length,s=t;for(;s<r&&(n[s]===" "||n[s]===" ");)s++;if(s>=r)return!1;let i=n[s];if(i==="(")return this.looksLikeNestedSubshells(s+1);let o=/[a-zA-Z_]/.test(i),a=i==="!"||i==="[";if(!o&&!a)return!1;let l=s;for(;l<r&&/[a-zA-Z0-9_\-.]/.test(n[l]);)l++;if(l===s)return a;let c=l;for(;c<r&&(n[c]===" "||n[c]===" ");)c++;if(c>=r)return!1;let u=n[c];if(u==="="&&n[c+1]!=="="||u===`
|
|
24
28
|
`||l===c&&/[+\-*/%<>&|^!~?:]/.test(u)&&u!=="-"||u===")"&&n[c+1]===")")return!1;if(c>l&&(u==="-"||u==='"'||u==="'"||u==="$"||/[a-zA-Z_/.]/.test(u))){let f=c;for(;f<r&&n[f]!==`
|
|
25
|
-
`;){if(n[f]===")")return!0;f++}return!1}if(u===")"){let f=c+1;for(;f<r&&(n[f]===" "||n[f]===" ");)f++;if(n[f]==="|"&&n[f+1]==="|"||n[f]==="&"&&n[f+1]==="&"||n[f]===";"||n[f]==="|"&&n[f+1]!=="|")return!0}return!1}makeToken(t,n,r,s,i){return{type:t,value:n,start:r,end:this.pos,line:s,column:i}}readComment(t,n,r){let s=this.input,i=s.length,
|
|
26
|
-
`;)
|
|
27
|
-
`||
|
|
28
|
-
`||
|
|
29
|
-
`)break;u+=
|
|
30
|
-
`||
|
|
31
|
-
`){
|
|
29
|
+
`;){if(n[f]===")")return!0;f++}return!1}if(u===")"){let f=c+1;for(;f<r&&(n[f]===" "||n[f]===" ");)f++;if(n[f]==="|"&&n[f+1]==="|"||n[f]==="&"&&n[f+1]==="&"||n[f]===";"||n[f]==="|"&&n[f+1]!=="|")return!0}return!1}makeToken(t,n,r,s,i){return{type:t,value:n,start:r,end:this.pos,line:s,column:i}}readComment(t,n,r){let s=this.input,i=s.length,o=this.pos;for(;o<i&&s[o]!==`
|
|
30
|
+
`;)o++;let a=s.slice(t,o);return this.pos=o,this.column=r+(o-t),{type:w.COMMENT,value:a,start:t,end:o,line:n,column:r}}readWord(t,n,r){let s=this.input,i=s.length,o=this.pos,a=o;for(;o<i;){let y=s[o];if(y===" "||y===" "||y===`
|
|
31
|
+
`||y===";"||y==="&"||y==="|"||y==="("||y===")"||y==="<"||y===">"||y==="'"||y==='"'||y==="\\"||y==="$"||y==="`"||y==="{"||y==="}"||y==="~"||y==="*"||y==="?"||y==="[")break;o++}if(o>a){let y=s[o];if(!(y==="("&&o>a&&"@*+?!".includes(s[o-1]))){if(o>=i||y===" "||y===" "||y===`
|
|
32
|
+
`||y===";"||y==="&"||y==="|"||y==="("||y===")"||y==="<"||y===">"){let S=s.slice(a,o);this.pos=o,this.column=r+(o-a);let v=ai.get(S);if(v!==void 0)return{type:v,value:S,start:t,end:o,line:n,column:r};let k=Wa(S);return k>0&&Ba(S.slice(0,k))?{type:w.ASSIGNMENT_WORD,value:S,start:t,end:o,line:n,column:r}:/^[0-9]+$/.test(S)?{type:w.NUMBER,value:S,start:t,end:o,line:n,column:r}:/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(S)?{type:w.NAME,value:S,start:t,end:o,line:n,column:r,quoted:!1,singleQuoted:!1}:{type:w.WORD,value:S,start:t,end:o,line:n,column:r,quoted:!1,singleQuoted:!1}}}}o=this.pos;let l=this.column,c=this.line,u="",f=!1,d=!1,p=!1,h=!1,m=s[o]==='"'||s[o]==="'",E=!1,b=0;for(;o<i;){let y=s[o];if(!p&&!h){if(y==="("&&u.length>0&&"@*+?!".includes(u[u.length-1])){let S=this.scanExtglobPattern(o);if(S!==null){u+=S.content,o=S.end,l+=S.content.length;continue}}if(y==="["&&b===0){if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)){let S=o+1<i?s[o+1]:"";if(S==="^"||S==="!"){u+=y,o++,l++;continue}b=1,u+=y,o++,l++;continue}}else if(y==="["&&b>0){u.length>0&&u[u.length-1]!=="\\"&&b++,u+=y,o++,l++;continue}else if(y==="]"&&b>0){u.length>0&&u[u.length-1]!=="\\"&&b--,u+=y,o++,l++;continue}if(b>0){if(y===`
|
|
33
|
+
`)break;u+=y,o++,l++;continue}if(y===" "||y===" "||y===`
|
|
34
|
+
`||y===";"||y==="&"||y==="|"||y==="("||y===")"||y==="<"||y===">")break}if(y==="$"&&o+1<i&&s[o+1]==="'"&&!p&&!h){for(u+="$'",o+=2,l+=2;o<i&&s[o]!=="'";)s[o]==="\\"&&o+1<i?(u+=s[o]+s[o+1],o+=2,l+=2):(u+=s[o],o++,l++);o<i&&(u+="'",o++,l++);continue}if(y==="$"&&o+1<i&&s[o+1]==='"'&&!p&&!h){o++,l++,h=!0,f=!0,u===""&&(m=!0),o++,l++;continue}if(y==="'"&&!h){if(p)if(p=!1,!m||E)u+=y;else{let S=o+1<i?s[o+1]:"";S&&!Va(S)&&S!=="'"&&(S==='"'?(E=!0,u+=y,d=!1,f=!1):(E=!0,u+=y))}else p=!0,m&&!E?(d=!0,f=!0):u+=y;o++,l++;continue}if(y==='"'&&!p){if(h)if(h=!1,!m||E)u+=y;else{let S=o+1<i?s[o+1]:"";S&&!Va(S)&&S!=='"'&&(S==="'"?(E=!0,u+=y,d=!1,f=!1):(E=!0,u+=y))}else h=!0,m&&!E?f=!0:u+=y;o++,l++;continue}if(y==="\\"&&!p&&o+1<i){let S=s[o+1];if(S===`
|
|
35
|
+
`){o+=2,c++,l=1;continue}if(h){if(S==='"'||S==="\\"||S==="$"||S==="`"||S===`
|
|
32
36
|
`){if(S===`
|
|
33
|
-
`){
|
|
34
|
-
`&&
|
|
35
|
-
`,
|
|
36
|
-
`?(c++,l=0):l++,
|
|
37
|
-
`;)
|
|
38
|
-
`&&(c++,l=0,
|
|
39
|
-
`&&(c++,l=0),
|
|
40
|
-
`){
|
|
41
|
-
`&&(c++,l=0),
|
|
42
|
-
`&&(c++,l=0),
|
|
43
|
-
`?(c++,l=1):l++}if(this.pos=
|
|
44
|
-
`;)a+=this.input[this.pos],this.pos++,this.column++;
|
|
45
|
-
|
|
46
|
-
`&&(i
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
`||
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
37
|
+
`){o+=2,l=1,c++;continue}u+=y+S,o+=2,l+=2;continue}}else{u+=y+S,o+=2,l+=2;continue}}if(y==="$"&&o+1<i&&s[o+1]==="("&&!p){u+=y,o++,l++,u+=s[o],o++,l++;let S=1,v=!1,k=!1,A=0,$=!1,N="",P=[],C=s[o]==="("&&!this.dollarDparenIsSubshell(o),O=C?1:0;for(;S>0&&o<i;){let U=s[o];if(u+=U,v)U==="'"&&(v=!1);else if(k)U==="\\"&&o+1<i?(u+=s[o+1],o++,l++):U==='"'&&(k=!1);else{if(U==="("&&s[o+1]==="("?O++:U===")"&&s[o+1]===")"&&O>0&&O--,O===0&&U==="<"&&s[o+1]==="<"&&s[o+2]!=="<"){let X=o+2,R=!1;for(s[X]==="-"&&(R=!0,X++);s[X]===" "||s[X]===" ";)X++;let{delim:z,endPos:q,unclosedQuote:_,unclosedSubstitution:T}=Wr(s,X);if(_)throw new Ye(`unexpected EOF while looking for matching \`${_}'`,c,l);if(T)throw new Ye("unexpected EOF while looking for matching `)'",c,l);if(z.length>0){u+=s.slice(o+1,q),l+=q-o,P.push({delim:z,stripTabs:R}),o=q;continue}}if(U===`
|
|
38
|
+
`&&P.length>0){c++,l=0;let X=o+1;for(let{delim:R,stripTabs:z}of P)for(;!(X>=i);){let q=s.indexOf(`
|
|
39
|
+
`,X);q===-1&&(q=i);let _=s.slice(X,q),T=z?_.replace(/^\t+/,""):_;u+=s.slice(X,Math.min(q+1,i)),q<i&&c++;let F=q>=i;if(X=q+1,T===R||F)break}P.length=0,l=0,o=Math.min(X,i);continue}if(U==="'")v=!0,N="";else if(U==='"')k=!0,N="";else if(U==="\\"&&o+1<i)u+=s[o+1],o++,l++,N="";else if(U==="$"&&o+1<i&&s[o+1]==="{"){o++,l++,u+=s[o],o++,l++;let X=1,R=!1,z=!1;for(;X>0&&o<i;){let q=s[o];if(q==="\\"&&o+1<i&&!R){u+=q,o++,l++,u+=s[o],o++,l++;continue}u+=q,R?q==="'"&&(R=!1):z?q==='"'&&(z=!1):q==="'"?R=!0:q==='"'?z=!0:q==="{"?X++:q==="}"&&X--,q===`
|
|
40
|
+
`?(c++,l=0):l++,o++}N="";continue}else if(U==="#"&&!C&&(N===""||/\s/.test(s[o-1]||""))){for(;o+1<i&&s[o+1]!==`
|
|
41
|
+
`;)o++,l++,u+=s[o];N=""}else/[a-zA-Z_]/.test(U)?N+=U:(N==="case"?(A++,$=!1):N==="in"&&A>0?$=!0:N==="esac"&&A>0&&(A--,$=!1),N="",U==="("?o>0&&s[o-1]==="$"?S++:$||S++:U===")"?$?$=!1:S--:U===";"&&A>0&&(o+1<i&&s[o+1]===";"||o+1<i&&s[o+1]==="&")&&($=!0))}U===`
|
|
42
|
+
`&&(c++,l=0,N=""),o++,l++}continue}if(y==="$"&&o+1<i&&s[o+1]==="["&&!p){u+=y,o++,l++,u+=s[o],o++,l++;let S=1;for(;S>0&&o<i;){let v=s[o];u+=v,v==="["?S++:v==="]"?S--:v===`
|
|
43
|
+
`&&(c++,l=0),o++,l++}continue}if(y==="$"&&o+1<i&&s[o+1]==="{"&&!p){u+=y,o++,l++,u+=s[o],o++,l++;let S=1,v=!1,k=!1,A=c,$=l,N=c,P=l;for(;S>0&&o<i;){let C=s[o];if(C==="\\"&&o+1<i&&s[o+1]===`
|
|
44
|
+
`){o+=2,c++,l=1;continue}if(C==="\\"&&o+1<i&&!v){u+=C,o++,l++,u+=s[o],o++,l++;continue}u+=C,v?C==="'"&&(v=!1):k?C==='"'&&(k=!1):C==="'"?(v=!0,A=c,$=l):C==='"'?(k=!0,N=c,P=l):C==="{"?S++:C==="}"&&S--,C===`
|
|
45
|
+
`&&(c++,l=0),o++,l++}if(v)throw new Ye("unexpected EOF while looking for matching `''",A,$);if(k)throw new Ye("unexpected EOF while looking for matching `\"'",N,P);continue}if(y==="$"&&o+1<i&&!p){let S=s[o+1];if(S==="#"||S==="?"||S==="$"||S==="!"||S==="@"||S==="*"||S==="-"||S>="0"&&S<="9"){u+=y+S,o+=2,l+=2;continue}}if(y==="`"&&!p){for(u+=y,o++,l++;o<i&&s[o]!=="`";){let S=s[o];u+=S,S==="\\"&&o+1<i&&(u+=s[o+1],o++,l++),S===`
|
|
46
|
+
`&&(c++,l=0),o++,l++}o<i&&(u+=s[o],o++,l++);continue}u+=y,o++,y===`
|
|
47
|
+
`?(c++,l=1):l++}if(this.pos=o,this.column=l,this.line=c,E&&m&&(u=s[t]+u,f=!1,d=!1),p||h){let y=p?"'":'"';throw new Ye(`unexpected EOF while looking for matching \`${y}'`,n,r)}if(!m&&u.length>=2){if(u[0]==="'"&&u[u.length-1]==="'"){let y=u.slice(1,-1);!y.includes("'")&&!y.includes('"')&&(u=y,f=!0,d=!0)}else if(u[0]==='"'&&u[u.length-1]==='"'){let y=u.slice(1,-1),S=!1;for(let v=0;v<y.length;v++){if(y[v]==='"'){S=!0;break}y[v]==="\\"&&v+1<y.length&&v++}S||(u=y,f=!0,d=!1)}}if(u==="")return{type:w.WORD,value:"",start:t,end:o,line:n,column:r,quoted:f,singleQuoted:d};let g=ai.get(u);if(!f&&g!==void 0)return{type:g,value:u,start:t,end:o,line:n,column:r};if(!m){let y=Wa(u);if(y>0&&Ba(u.slice(0,y)))return{type:w.ASSIGNMENT_WORD,value:u,start:t,end:o,line:n,column:r,quoted:f,singleQuoted:d}}return/^[0-9]+$/.test(u)?{type:w.NUMBER,value:u,start:t,end:o,line:n,column:r}:dd(u)?{type:w.NAME,value:u,start:t,end:o,line:n,column:r,quoted:f,singleQuoted:d}:{type:w.WORD,value:u,start:t,end:o,line:n,column:r,quoted:f,singleQuoted:d}}readHeredocContent(){for(;this.pendingHeredocs.length>0;){let t=this.pendingHeredocs.shift();if(!t)break;let n=this.pos,r=this.line,s=this.column,i="",o=!1;for(;this.pos<this.input.length;){let a="",l="",c="";for(;;){for(a="";this.pos<this.input.length&&this.input[this.pos]!==`
|
|
48
|
+
`;)a+=this.input[this.pos],this.pos++,this.column++;let f=0;for(let d=a.length-1;a[d]==="\\";d-=1)f+=1;if(c+=a,t.quoted||f%2===0||this.pos+1>=this.input.length)break;c=c.slice(0,-1),l+=`${a}
|
|
49
|
+
`,this.pos++,this.line++,this.column=1}if((t.stripTabs?c.replace(/^\t+/,""):c)===t.delimiter){o=!0,this.pos<this.input.length&&this.input[this.pos]===`
|
|
50
|
+
`&&(this.pos++,this.line++,this.column=1);break}if(i+=l,i+=a,this.pos<this.input.length&&this.input[this.pos]===`
|
|
51
|
+
`?(i+=`
|
|
52
|
+
`,this.pos++,this.line++,this.column=1):a.length>0&&(i+=`
|
|
53
|
+
`),i.length>this.maxHeredocSize)throw new Ye(`Heredoc size limit exceeded (${this.maxHeredocSize} bytes)`,r,s)}this.tokens.push({type:w.HEREDOC_CONTENT,value:i,start:n,end:this.pos,line:r,column:s,heredocTerminated:o})}}readHeredocDelimiterToken(t,n,r,s){let i=this.input,{delim:o,endPos:a,quoted:l,unclosedQuote:c,unclosedSubstitution:u}=Wr(i,t);if(c)throw new Ye(`unexpected EOF while looking for matching \`${c}'`,n,r);if(u)throw new Ye("unexpected EOF while looking for matching `)'",n,r);if(a===t)throw new Ye("Expected here-document delimiter",n,r);let f=n,d=r;for(let p=t;p<a;p++)i[p]===`
|
|
54
|
+
`?(f+=1,d=1):d+=1;return this.pos=a,this.line=f,this.column=d,this.pendingHeredocs.push({delimiter:o,stripTabs:s,quoted:l}),{type:w.WORD,value:i.slice(t,a),start:t,end:a,line:n,column:r,quoted:l,heredocDelimiter:o}}isWordCharFollowing(t){if(t>=this.input.length)return!1;let n=this.input[t];return!(n===" "||n===" "||n===`
|
|
55
|
+
`||n===";"||n==="&"||n==="|"||n==="("||n===")"||n==="<"||n===">")}readWordWithBraceExpansion(t,n,r){let s=this.input,i=s.length,o=t,a=r;for(;o<i;){let c=s[o];if(c===" "||c===" "||c===`
|
|
56
|
+
`||c===";"||c==="&"||c==="|"||c==="("||c===")"||c==="<"||c===">")break;if(c==="{"){if(this.scanBraceExpansion(o)!==null){let f=1;for(o++,a++;o<i&&f>0;)s[o]==="{"?f++:s[o]==="}"&&f--,o++,a++;continue}o++,a++;continue}if(c==="}"){o++,a++;continue}if(c==="$"&&o+1<i&&s[o+1]==="("){o++,a++,o++,a++;let u=1;for(;u>0&&o<i;)s[o]==="("?u++:s[o]===")"&&u--,o++,a++;continue}if(c==="$"&&o+1<i&&s[o+1]==="{"){o++,a++,o++,a++;let u=1;for(;u>0&&o<i;)s[o]==="{"?u++:s[o]==="}"&&u--,o++,a++;continue}if(c==="`"){for(o++,a++;o<i&&s[o]!=="`";)s[o]==="\\"&&o+1<i?(o+=2,a+=2):(o++,a++);o<i&&(o++,a++);continue}o++,a++}let l=s.slice(t,o);return this.pos=o,this.column=a,{type:w.WORD,value:l,start:t,end:o,line:n,column:r,quoted:!1,singleQuoted:!1}}scanBraceExpansion(t){let n=this.input,r=n.length,s=t+1,i=1,o=!1,a=!1;for(;s<r&&i>0;){let l=n[s];if(l==="{")i++,s++;else if(l==="}")i--,s++;else if(l===","&&i===1)o=!0,s++;else if(l==="."&&s+1<r&&n[s+1]===".")a=!0,s+=2;else{if(l===" "||l===" "||l===`
|
|
57
|
+
`||l===";"||l==="&"||l==="|")return null;s++}}return i===0&&(o||a)?n.slice(t,s):null}scanLiteralBraceWord(t){let n=this.input,r=n.length,s=t+1,i=1;for(;s<r&&i>0;){let o=n[s];if(o==="{")i++,s++;else if(o==="}"){if(i--,i===0)return n.slice(t,s+1);s++}else{if(o===" "||o===" "||o===`
|
|
58
|
+
`||o===";"||o==="&"||o==="|")return null;s++}}return null}scanExtglobPattern(t){let n=this.input,r=n.length,s=t+1,i=1;for(;s<r&&i>0;){let o=n[s];if(o==="\\"&&s+1<r){s+=2;continue}if("@*+?!".includes(o)&&s+1<r&&n[s+1]==="("){s++,i++,s++;continue}if(o==="(")i++,s++;else if(o===")")i--,s++;else{if(o===`
|
|
59
|
+
`)return null;s++}}return i===0?{content:n.slice(t,s),end:s}:null}scanFdVariable(t){let n=this.input,r=n.length,s=t+1,i=s;for(;s<r;){let u=n[s];if(s===i){if(!(u>="a"&&u<="z"||u>="A"&&u<="Z"||u==="_"))return null}else if(!(u>="a"&&u<="z"||u>="A"&&u<="Z"||u>="0"&&u<="9"||u==="_"))break;s++}if(s===i)return null;let o=n.slice(i,s);if(s>=r||n[s]!=="}"||(s++,s>=r))return null;let a=n[s],l=s+1<r?n[s+1]:"";return a===">"||a==="<"||a==="&"&&(l===">"||l==="<")?{varname:o,end:s}:null}dollarDparenIsSubshell(t){let n=this.input,r=n.length,s=t+1,i=2,o=!1,a=!1,l=!1;for(;s<r&&i>0;){let c=n[s];if(o){c==="'"&&(o=!1),c===`
|
|
60
|
+
`&&(l=!0),s++;continue}if(a){if(c==="\\"){s+=2;continue}c==='"'&&(a=!1),c===`
|
|
61
|
+
`&&(l=!0),s++;continue}if(c==="'"){o=!0,s++;continue}if(c==='"'){a=!0,s++;continue}if(c==="\\"){s+=2;continue}if(c===`
|
|
55
62
|
`&&(l=!0),c==="("){i++,s++;continue}if(c===")"){if(i--,i===1){let u=s+1;if(u<r&&n[u]===")")return!1;let f=u,d=!1;for(;f<r&&(n[f]===" "||n[f]===" "||n[f]===`
|
|
56
|
-
`);)d=!0,f++;if(d&&f<r&&n[f]===")"||l)return!0}if(i===0)return!1;s++;continue}s++}return!1}dparenClosesWithSpacedParens(t){let n=this.input,r=n.length,s=t,i=2,
|
|
57
|
-
`);)f=!0,u++;if(f&&u<r&&n[u]===")")return!0}if(i===0)return!1;s++;continue}if(i===1&&(l==="|"&&s+1<r&&n[s+1]==="|"||l==="&"&&s+1<r&&n[s+1]==="&"||l==="|"&&s+1<r&&n[s+1]!=="|"))return!0;s++}return!1}};var
|
|
58
|
-
`){t+=2;continue}if(/\s/.test(e[t])){t++;continue}break}return t}var
|
|
59
|
-
`;break;case"t":r+=" ";break;case"r":r+="\r";break;case"\\":r+="\\";break;case"'":r+="'";break;default:r+=i}n+=2}else r+=e[n],n++;e[n]==="'"&&n++;let s=Number.parseInt(r,10);return{expr:{type:"ArithNumber",value:Number.isNaN(s)?0:s},pos:n}}function po(e,t){if(e.slice(t,t+2)!=='$"')return null;let n=t+2,r="";for(;n<e.length&&e[n]!=='"';)e[n]==="\\"&&n+1<e.length?(r+=e[n+1],n+=2):(r+=e[n],n++);e[n]==='"'&&n++;let s=Number.parseInt(r,10);return{expr:{type:"ArithNumber",value:Number.isNaN(s)?0:s},pos:n}}function Ef(e){let t="",n=0;for(;n<e.length;)if(e[n]==='"'){for(n++;n<e.length&&e[n]!=='"';)e[n]==="\\"&&n+1<e.length?(t+=e[n+1],n+=2):(t+=e[n],n++);n<e.length&&n++}else t+=e[n],n++;return t}function re(e,t){let n=Ef(t),{expr:r,pos:s}=En(e,n,0),i=pe(n,s);if(i<n.length){let a=t.slice(i).trim();if(a)return{type:"ArithmeticExpression",originalText:t,expression:{type:"ArithSyntaxError",errorToken:a,message:`${a}: syntax error: invalid arithmetic operator (error token is "${a}")`}}}return{type:"ArithmeticExpression",expression:r,originalText:t}}function Ve(e,t){return{expr:{type:"ArithSyntaxError",errorToken:e,message:`syntax error: operand expected (error token is "${e}")`},pos:t}}function ze(e,t){return pe(e,t)>=e.length}function En(e,t,n){return bf(e,t,n)}function sn(e,t,n){return e.withDepth(()=>En(e,t,n))}function bf(e,t,n){let{expr:r,pos:s}=jn(e,t,n);for(s=pe(t,s);t[s]===",";){if(s++,ze(t,s))return Ve(",",s);let{expr:a,pos:o}=jn(e,t,s);r={type:"ArithBinary",operator:",",left:r,right:a},s=pe(t,o)}return{expr:r,pos:s}}function jn(e,t,n){let{expr:r,pos:s}=Sf(e,t,n);if(s=pe(t,s),t[s]==="?"){s++;let{expr:i,pos:a}=sn(e,t,s);if(s=pe(t,a),t[s]===":"){s++;let{expr:o,pos:l}=sn(e,t,s);return{expr:{type:"ArithTernary",condition:r,consequent:i,alternate:o},pos:l}}}return{expr:r,pos:s}}function Sf(e,t,n){let{expr:r,pos:s}=mo(e,t,n);for(;s=pe(t,s),t.slice(s,s+2)==="||";){if(s+=2,ze(t,s))return Ve("||",s);let{expr:a,pos:o}=mo(e,t,s);r={type:"ArithBinary",operator:"||",left:r,right:a},s=o}return{expr:r,pos:s}}function mo(e,t,n){let{expr:r,pos:s}=yo(e,t,n);for(;s=pe(t,s),t.slice(s,s+2)==="&&";){if(s+=2,ze(t,s))return Ve("&&",s);let{expr:a,pos:o}=yo(e,t,s);r={type:"ArithBinary",operator:"&&",left:r,right:a},s=o}return{expr:r,pos:s}}function yo(e,t,n){let{expr:r,pos:s}=go(e,t,n);for(;s=pe(t,s),t[s]==="|"&&t[s+1]!=="|";){if(s++,ze(t,s))return Ve("|",s);let{expr:a,pos:o}=go(e,t,s);r={type:"ArithBinary",operator:"|",left:r,right:a},s=o}return{expr:r,pos:s}}function go(e,t,n){let{expr:r,pos:s}=wo(e,t,n);for(;s=pe(t,s),t[s]==="^";){if(s++,ze(t,s))return Ve("^",s);let{expr:a,pos:o}=wo(e,t,s);r={type:"ArithBinary",operator:"^",left:r,right:a},s=o}return{expr:r,pos:s}}function wo(e,t,n){let{expr:r,pos:s}=Eo(e,t,n);for(;s=pe(t,s),t[s]==="&"&&t[s+1]!=="&";){if(s++,ze(t,s))return Ve("&",s);let{expr:a,pos:o}=Eo(e,t,s);r={type:"ArithBinary",operator:"&",left:r,right:a},s=o}return{expr:r,pos:s}}function Eo(e,t,n){let{expr:r,pos:s}=bo(e,t,n);for(;s=pe(t,s),t.slice(s,s+2)==="=="||t.slice(s,s+2)==="!=";){let i=t.slice(s,s+2);if(s+=2,ze(t,s))return Ve(i,s);let{expr:a,pos:o}=bo(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:a},s=o}return{expr:r,pos:s}}function bo(e,t,n){let{expr:r,pos:s}=Gs(e,t,n);for(;;)if(s=pe(t,s),t.slice(s,s+2)==="<="||t.slice(s,s+2)===">="){let i=t.slice(s,s+2);if(s+=2,ze(t,s))return Ve(i,s);let{expr:a,pos:o}=Gs(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:a},s=o}else if(t[s]==="<"||t[s]===">"){let i=t[s];if(s++,ze(t,s))return Ve(i,s);let{expr:a,pos:o}=Gs(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:a},s=o}else break;return{expr:r,pos:s}}function Gs(e,t,n){let{expr:r,pos:s}=So(e,t,n);for(;s=pe(t,s),t.slice(s,s+2)==="<<"||t.slice(s,s+2)===">>";){let i=t.slice(s,s+2);if(s+=2,ze(t,s))return Ve(i,s);let{expr:a,pos:o}=So(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:a},s=o}return{expr:r,pos:s}}function So(e,t,n){let{expr:r,pos:s}=vo(e,t,n);for(;s=pe(t,s),(t[s]==="+"||t[s]==="-")&&t[s+1]!==t[s];){let i=t[s];if(s++,ze(t,s))return Ve(i,s);let{expr:a,pos:o}=vo(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:a},s=o}return{expr:r,pos:s}}function vo(e,t,n){let{expr:r,pos:s}=Dr(e,t,n);for(;;)if(s=pe(t,s),t[s]==="*"&&t[s+1]!=="*"){if(s++,ze(t,s))return Ve("*",s);let{expr:a,pos:o}=Dr(e,t,s);r={type:"ArithBinary",operator:"*",left:r,right:a},s=o}else if(t[s]==="/"||t[s]==="%"){let i=t[s];if(s++,ze(t,s))return Ve(i,s);let{expr:a,pos:o}=Dr(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:a},s=o}else break;return{expr:r,pos:s}}function Dr(e,t,n){let{expr:r,pos:s}=Zs(e,t,n),i=pe(t,s);if(t.slice(i,i+2)==="**"){if(i+=2,ze(t,i))return Ve("**",i);let{expr:o,pos:l}=e.withDepth(()=>Dr(e,t,i));return{expr:{type:"ArithBinary",operator:"**",left:r,right:o},pos:l}}return{expr:r,pos:s}}function Zs(e,t,n){let r=pe(t,n);if(t.slice(r,r+2)==="++"||t.slice(r,r+2)==="--"){let s=t.slice(r,r+2);r+=2;let{expr:i,pos:a}=e.withDepth(()=>Zs(e,t,r));return{expr:{type:"ArithUnary",operator:s,operand:i,prefix:!0},pos:a}}if(t[r]==="+"||t[r]==="-"||t[r]==="!"||t[r]==="~"){let s=t[r];r++;let{expr:i,pos:a}=e.withDepth(()=>Zs(e,t,r));return{expr:{type:"ArithUnary",operator:s,operand:i,prefix:!0},pos:a}}return Af(e,t,r)}function vf(e,t){let n=e[t];return n==="$"||n==="`"}function Af(e,t,n){let{expr:r,pos:s}=Ao(e,t,n,!1),i=[r];for(;vf(t,s);){let{expr:o,pos:l}=Ao(e,t,s,!0);i.push(o),s=l}i.length>1&&(r={type:"ArithConcat",parts:i});let a;if(t[s]==="["&&r.type==="ArithConcat"){s++;let{expr:o,pos:l}=sn(e,t,s);a=o,s=l,t[s]==="]"&&s++}if(a&&r.type==="ArithConcat"&&(r={type:"ArithDynamicElement",nameExpr:r,subscript:a},a=void 0),s=pe(t,s),r.type==="ArithConcat"||r.type==="ArithVariable"||r.type==="ArithDynamicElement"){for(let o of Cr)if(t.slice(s,s+o.length)===o&&t.slice(s,s+o.length+1)!=="=="){s+=o.length;let{expr:l,pos:c}=e.withDepth(()=>jn(e,t,s));return r.type==="ArithDynamicElement"?{expr:{type:"ArithDynamicAssignment",operator:o,target:r.nameExpr,subscript:r.subscript,value:l},pos:c}:r.type==="ArithConcat"?{expr:{type:"ArithDynamicAssignment",operator:o,target:r,value:l},pos:c}:{expr:{type:"ArithAssignment",operator:o,variable:r.name,value:l},pos:c}}}if(t.slice(s,s+2)==="++"||t.slice(s,s+2)==="--"){let o=t.slice(s,s+2);return s+=2,{expr:{type:"ArithUnary",operator:o,operand:r,prefix:!1},pos:s}}return{expr:r,pos:s}}function Ao(e,t,n,r=!1){let s=pe(t,n),i=fo(sn,e,t,s);if(i)return i;let a=ho(t,s);if(a)return a;let o=po(t,s);if(o)return o;if(t.slice(s,s+2)==="$("&&t[s+2]!=="("){s+=2;let c=1,u=s;for(;s<t.length&&c>0;)t[s]==="("?c++:t[s]===")"&&c--,c>0&&s++;let f=t.slice(u,s);return s++,{expr:{type:"ArithCommandSubst",command:f},pos:s}}if(t[s]==="`"){s++;let c=s;for(;s<t.length&&t[s]!=="`";)s++;let u=t.slice(c,s);return t[s]==="`"&&s++,{expr:{type:"ArithCommandSubst",command:u},pos:s}}if(t[s]==="("){s++;let{expr:c,pos:u}=sn(e,t,s);return s=pe(t,u),t[s]===")"&&s++,{expr:{type:"ArithGroup",expression:c},pos:s}}if(t[s]==="'"){s++;let c="";for(;s<t.length&&t[s]!=="'";)c+=t[s],s++;t[s]==="'"&&s++;let u=Number.parseInt(c,10);return{expr:{type:"ArithSingleQuote",content:c,value:Number.isNaN(u)?0:u},pos:s}}if(t[s]==='"'){s++;let c="";for(;s<t.length&&t[s]!=='"';)t[s]==="\\"&&s+1<t.length?(c+=t[s+1],s+=2):(c+=t[s],s++);t[s]==='"'&&s++;let u=c.trim();if(!u)return{expr:{type:"ArithNumber",value:0},pos:s};let{expr:f}=sn(e,u,0);return{expr:f,pos:s}}if(/[0-9]/.test(t[s])){let c="",u=!1,f=!1;for(;s<t.length;){let h=t[s];if(u)if(/[0-9a-zA-Z@_]/.test(h))c+=h,s++;else break;else if(h==="#")u=!0,c+=h,s++;else if(c==="0"&&(h==="x"||h==="X")&&s+1<t.length&&/[0-9a-fA-F]/.test(t[s+1]))f=!0,c+=h,s++;else if(f&&/[0-9a-fA-F]/.test(h))c+=h,s++;else if(!f&&/[0-9]/.test(h))c+=h,s++;else break}if(s<t.length&&/[a-zA-Z_]/.test(t[s])){let h=c;for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)h+=t[s],s++;return{expr:{type:"ArithSyntaxError",errorToken:h,message:`${h}: value too great for base (error token is "${h}")`},pos:s}}if(t[s]==="."&&/[0-9]/.test(t[s+1]))throw new oe(`${c}.${t[s+1]}...: syntax error: invalid arithmetic operator`);if(t[s]==="["){let h=t.slice(s).trim();return{expr:{type:"ArithNumberSubscript",number:c,errorToken:h},pos:t.length}}return{expr:{type:"ArithNumber",value:Un(c)},pos:s}}if(t[s]==="$"&&t[s+1]==="{"){let c=s+2,u=1,f=c;for(;f<t.length&&u>0;)t[f]==="{"?u++:t[f]==="}"&&u--,u>0&&f++;let d=t.slice(c,f),h=f+1;if(t[h]==="#"){let p=h+1;for(;p<t.length&&/[0-9a-zA-Z@_]/.test(t[p]);)p++;let m=t.slice(h+1,p);return{expr:{type:"ArithDynamicBase",baseExpr:d,value:m},pos:p}}if(/[0-9]/.test(t[h])||t[h]==="x"||t[h]==="X"){let p=h;if(t[h]==="x"||t[h]==="X")for(p++;p<t.length&&/[0-9a-fA-F]/.test(t[p]);)p++;else for(;p<t.length&&/[0-9]/.test(t[p]);)p++;let m=t.slice(h,p);return{expr:{type:"ArithDynamicNumber",prefix:d,suffix:m},pos:p}}return s=h,{expr:{type:"ArithBracedExpansion",content:d},pos:s}}if(t[s]==="$"&&s+1<t.length&&/[0-9]/.test(t[s+1])){s++;let c="";for(;s<t.length&&/[0-9]/.test(t[s]);)c+=t[s],s++;return{expr:{type:"ArithVariable",name:c,hasDollarPrefix:!0},pos:s}}if(t[s]==="$"&&s+1<t.length&&/[*@#?\-!$]/.test(t[s+1])){let c=t[s+1];return s+=2,{expr:{type:"ArithSpecialVar",name:c},pos:s}}let l=!1;if(t[s]==="$"&&s+1<t.length&&/[a-zA-Z_]/.test(t[s+1])&&(l=!0,s++),s<t.length&&/[a-zA-Z_]/.test(t[s])){let c="";for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)c+=t[s],s++;if(t[s]==="["&&!r){s++;let u;if(t[s]==="'"||t[s]==='"'){let d=t[s];for(s++,u="";s<t.length&&t[s]!==d;)u+=t[s],s++;t[s]===d&&s++,s=pe(t,s),t[s]==="]"&&s++}let f;if(u===void 0){let{expr:d,pos:h}=sn(e,t,s);f=d,s=h,t[s]==="]"&&s++}if(s=pe(t,s),t[s]==="["&&f)return{expr:{type:"ArithDoubleSubscript",array:c,index:f},pos:s};if(!r){for(let d of Cr)if(t.slice(s,s+d.length)===d&&t.slice(s,s+d.length+1)!=="=="){s+=d.length;let{expr:h,pos:p}=e.withDepth(()=>jn(e,t,s));return{expr:{type:"ArithAssignment",operator:d,variable:c,subscript:f,stringKey:u,value:h},pos:p}}}return{expr:{type:"ArithArrayElement",array:c,index:f,stringKey:u},pos:s}}if(s=pe(t,s),!r){for(let u of Cr)if(t.slice(s,s+u.length)===u&&t.slice(s,s+u.length+1)!=="=="){s+=u.length;let{expr:f,pos:d}=e.withDepth(()=>jn(e,t,s));return{expr:{type:"ArithAssignment",operator:u,variable:c,value:f},pos:d}}}return{expr:{type:"ArithVariable",name:c,hasDollarPrefix:l},pos:s}}if(t[s]==="#"){let c=s+1;for(;c<t.length&&t[c]!==`
|
|
60
|
-
`;)c++;let u=t.slice(s,c).trim()||"#";return{expr:{type:"ArithSyntaxError",errorToken:u,message:`${u}: syntax error: invalid arithmetic operator (error token is "${u}")`},pos:t.length}}return{expr:{type:"ArithNumber",value:0},pos:s}}function
|
|
61
|
-
`,s+=2;break;case"t":r+=" ",s+=2;break;case"r":r+="\r",s+=2;break;case"\\":r+="\\",s+=2;break;case"'":r+="'",s+=2;break;case'"':r+='"',s+=2;break;case"a":r+="\x07",s+=2;break;case"b":r+="\b",s+=2;break;case"e":case"E":r+="\x1B",s+=2;break;case"f":r+="\f",s+=2;break;case"v":r+="\v",s+=2;break;case"x":{let o=[],l=s;for(;l+1<t.length&&t[l]==="\\"&&t[l+1]==="x";){let c=t.slice(l+2,l+4),u=parseInt(c,16);if(!Number.isNaN(u)&&c.length>0)o.push(u),l+=2+c.length;else break}o.length>0?(r+=xf(o),s=l):(r+="\\x",s+=2);break}case"u":{let o=t.slice(s+2,s+6),l=parseInt(o,16);Number.isNaN(l)?(r+="\\u",s+=2):(r+=String.fromCharCode(l),s+=6);break}case"c":{if(s+2<t.length){let l=t[s+2].charCodeAt(0)&31;r+=String.fromCharCode(l),s+=3}else r+="\\c",s+=2;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let o="",l=s+1;for(;l<t.length&&l<s+4&&/[0-7]/.test(t[l]);)o+=t[l],l++;let c=parseInt(o,8);r+=String.fromCharCode(c),s=l;break}default:r+=i,s++}else r+=i,s++}return s<t.length&&t[s]==="'"&&s++,{part:L.literal(r),endIndex:s}}function Qs(e,t){let n=t.trim();return n===""?{type:"ArithmeticExpression",expression:{type:"ArithNumber",value:0}}:re(e,n)}function Po(e){let t=[],n="",r=0;for(let s=0;s<e.length;s++){let i=e[s];i==="{"?(r++,n+=i):i==="}"?(r--,n+=i):i===","&&r===0?(t.push(n),n=""):n+=i}return t.push(n),t}function Do(e,t,n,r){let s=Hs(e,t,n,"{","}");if(s===-1)return null;let i=t.slice(n+1,s),a=i.match(/^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/);if(a)return{part:{type:"BraceExpansion",items:[{type:"Range",start:Number.parseInt(a[1],10),end:Number.parseInt(a[2],10),step:a[3]?Number.parseInt(a[3],10):void 0,startStr:a[1],endStr:a[2]}]},endIndex:s+1};let o=i.match(/^([a-zA-Z])\.\.([a-zA-Z])(?:\.\.(-?\d+))?$/);return o?{part:{type:"BraceExpansion",items:[{type:"Range",start:o[1],end:o[2],step:o[3]?Number.parseInt(o[3],10):void 0}]},endIndex:s+1}:i.includes(",")&&r?{part:{type:"BraceExpansion",items:Po(i).map(u=>e.withDepth(()=>({type:"Word",word:L.word(r(e,u,!1,!1,!1))})))},endIndex:s+1}:i.includes(",")?{part:{type:"BraceExpansion",items:Po(i).map(u=>({type:"Word",word:L.word([L.literal(u)])}))},endIndex:s+1}:null}function Ks(e,t){let n="";for(let r of t.parts)switch(r.type){case"Literal":n+=r.value;break;case"SingleQuoted":n+=`'${r.value}'`;break;case"Escaped":n+=r.value;break;case"DoubleQuoted":n+='"';for(let s of r.parts)s.type==="Literal"||s.type==="Escaped"?n+=s.value:s.type==="ParameterExpansion"&&(n+=`\${${s.parameter}}`);n+='"';break;case"ParameterExpansion":n+=`\${${r.parameter}}`;break;case"Glob":n+=r.pattern;break;case"TildeExpansion":n+="~",r.user&&(n+=r.user);break;case"BraceExpansion":{n+="{";let s=[];for(let i of r.items)if(i.type==="Range"){let a=i.startStr??String(i.start),o=i.endStr??String(i.end);i.step!==void 0?s.push(`${a}..${o}..${i.step}`):s.push(`${a}..${o}`)}else s.push(Ks(e,i.word));s.length===1&&r.items[0].type==="Range"?n+=s[0]:n+=s.join(","),n+="}";break}default:n+=r.type}return n}function Ro(e,t){return{[y.LESS]:"<",[y.GREAT]:">",[y.DGREAT]:">>",[y.LESSAND]:"<&",[y.GREATAND]:">&",[y.LESSGREAT]:"<>",[y.CLOBBER]:">|",[y.TLESS]:"<<<",[y.AND_GREAT]:"&>",[y.AND_DGREAT]:"&>>",[y.DLESS]:"<",[y.DLESSDASH]:"<"}[t]||">"}function Rr(e){let t=e.current(),n=t.type;if(n===y.NUMBER){let r=e.peek(1);return t.end!==r.start?!1:co.has(r.type)}if(n===y.FD_VARIABLE){let r=e.peek(1);return uo.has(r.type)}return lo.has(n)}function Or(e){let t=null,n;e.check(y.NUMBER)?t=Number.parseInt(e.advance().value,10):e.check(y.FD_VARIABLE)&&(n=e.advance().value);let r=e.advance(),s=Ro(e,r.type);if(r.type===y.DLESS||r.type===y.DLESSDASH)return $f(e,s,t,r.type===y.DLESSDASH);e.isWord()||e.error("Expected redirection target");let i=e.parseWord();return L.redirection(s,i,t,n)}function $f(e,t,n,r){e.isWord()||e.error("Expected here-document delimiter");let s=e.advance(),i=s.value,a=s.quoted||!1;(i.startsWith("'")&&i.endsWith("'")||i.startsWith('"')&&i.endsWith('"'))&&(i=i.slice(1,-1));let o=L.redirection(r?"<<-":"<<",L.hereDoc(i,L.word([]),r,a),n);return e.addPendingHeredoc(o,i,r,a),o}function Io(e){let t=e.current().line,n=[],r=null,s=[],i=[];for(;e.check(y.ASSIGNMENT_WORD)||Rr(e);)e.checkIterationLimit(),e.check(y.ASSIGNMENT_WORD)?n.push(kf(e)):i.push(Or(e));if(e.isWord())r=e.parseWord();else if(n.length>0&&(e.check(y.DBRACK_START)||e.check(y.DPAREN_START))){let o=e.advance();r=L.word([L.literal(o.value)])}for(;(!e.isStatementEnd()||e.check(y.RBRACE))&&!e.check(y.PIPE,y.PIPE_AMP);)if(e.checkIterationLimit(),Rr(e))i.push(Or(e));else if(e.check(y.RBRACE)){let o=e.advance();s.push(e.parseWordFromString(o.value,!1,!1))}else if(e.check(y.LBRACE)){let o=e.advance();s.push(e.parseWordFromString(o.value,!1,!1))}else if(e.check(y.DBRACK_END)){let o=e.advance();s.push(e.parseWordFromString(o.value,!1,!1))}else if(e.isWord())s.push(e.parseWord());else if(e.check(y.ASSIGNMENT_WORD)){let o=e.advance(),l=o.value,c=l.endsWith("="),u=l.endsWith("=(");if((c||u)&&(u||e.check(y.LPAREN))){let f=u?l.slice(0,-2):l.slice(0,-1);u||e.expect(y.LPAREN);let d=Xs(e);e.expect(y.RPAREN);let h=d.map(m=>Ks(e,m)),p=`${f}=(${h.join(" ")})`;s.push(e.parseWordFromString(p,!1,!1,!0))}else s.push(e.parseWordFromString(l,o.quoted,o.singleQuoted,!0))}else if(e.check(y.LPAREN))e.error("syntax error near unexpected token `('");else break;let a=L.simpleCommand(r,s,n,i);return a.line=t,a}function kf(e){let t=e.expect(y.ASSIGNMENT_WORD),n=t.value,r=n.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);r||e.error(`Invalid assignment: ${n}`);let s=r[0],i,a=s.length;if(n[a]==="["){let f=0,d=a+1;for(;a<n.length;a++)if(n[a]==="[")f++;else if(n[a]==="]"&&(f--,f===0))break;f!==0&&e.error(`Invalid assignment: ${n}`),i=n.slice(d,a),a++}let o=n[a]==="+";o&&a++,n[a]!=="="&&e.error(`Invalid assignment: ${n}`),a++;let l=n.slice(a);if(l==="("){let f=Xs(e);e.expect(y.RPAREN);let d=i!==void 0?`${s}[${i}]`:s;return L.assignment(d,null,o,f)}if(l===""&&e.check(y.LPAREN)){let f=e.current();if(t.end===f.start){e.advance();let d=Xs(e);e.expect(y.RPAREN);let h=i!==void 0?`${s}[${i}]`:s;return L.assignment(h,null,o,d)}}let c=l?e.parseWordFromString(l,t.quoted,t.singleQuoted,!0):null,u=i!==void 0?`${s}[${i}]`:s;return L.assignment(u,c,o,null)}var Nf=new Set([y.AMP,y.PIPE,y.PIPE_AMP,y.SEMICOLON,y.AND_AND,y.OR_OR,y.DSEMI,y.SEMI_AND,y.SEMI_SEMI_AND]);function Xs(e){let t=[];for(e.skipNewlines();!e.check(y.RPAREN,y.EOF);)e.checkIterationLimit(),e.isWord()?t.push(e.parseWord()):Nf.has(e.current().type)?e.error(`syntax error near unexpected token \`${e.current().value}'`):e.advance(),e.skipNewlines();return t}function Ys(e,t){e.expect(y.IF);let n=[],r=e.parseCompoundList();e.expect(y.THEN);let s=e.parseCompoundList();if(s.length===0){let o=e.check(y.FI)?"fi":e.check(y.ELSE)?"else":e.check(y.ELIF)?"elif":"fi";e.error(`syntax error near unexpected token \`${o}'`)}for(n.push({condition:r,body:s});e.check(y.ELIF);){e.advance();let o=e.parseCompoundList();e.expect(y.THEN);let l=e.parseCompoundList();if(l.length===0){let c=e.check(y.FI)?"fi":e.check(y.ELSE)?"else":e.check(y.ELIF)?"elif":"fi";e.error(`syntax error near unexpected token \`${c}'`)}n.push({condition:o,body:l})}let i=null;e.check(y.ELSE)&&(e.advance(),i=e.parseCompoundList(),i.length===0&&e.error("syntax error near unexpected token `fi'")),e.expect(y.FI);let a=t?.skipRedirections?[]:e.parseOptionalRedirections();return L.ifNode(n,i,a)}function Js(e,t){let n=e.expect(y.FOR);if(e.check(y.DPAREN_START))return Df(e,t,n.line);e.isWord()||e.error("Expected variable name in for loop");let s=e.advance().value,i=null;if(e.skipNewlines(),e.check(y.IN))for(e.advance(),i=[];!e.check(y.SEMICOLON,y.NEWLINE,y.DO,y.EOF)&&e.isWord();)i.push(e.parseWord());e.check(y.SEMICOLON)&&e.advance(),e.skipNewlines(),e.expect(y.DO);let a=e.parseCompoundList();e.expect(y.DONE);let o=t?.skipRedirections?[]:e.parseOptionalRedirections();return L.forNode(s,i,a,o)}function Df(e,t,n){e.expect(y.DPAREN_START);let r=null,s=null,i=null,a=["","",""],o=0,l=0;for(;!e.check(y.DPAREN_END,y.EOF);){let f=e.advance();if(f.type===y.SEMICOLON&&l===0){if(o++,o>2)break}else f.value==="("&&l++,f.value===")"&&l--,a[o]+=f.value}e.expect(y.DPAREN_END),a[0].trim()&&(r=re(e,a[0].trim())),a[1].trim()&&(s=re(e,a[1].trim())),a[2].trim()&&(i=re(e,a[2].trim())),e.skipNewlines(),e.check(y.SEMICOLON)&&e.advance(),e.skipNewlines();let c;e.check(y.LBRACE)?(e.advance(),c=e.parseCompoundList(),e.expect(y.RBRACE)):(e.expect(y.DO),c=e.parseCompoundList(),e.expect(y.DONE));let u=t?.skipRedirections?[]:e.parseOptionalRedirections();return{type:"CStyleFor",init:r,condition:s,update:i,body:c,redirections:u,line:n}}function ei(e,t){e.expect(y.WHILE);let n=e.parseCompoundList();e.expect(y.DO);let r=e.parseCompoundList();r.length===0&&e.error("syntax error near unexpected token `done'"),e.expect(y.DONE);let s=t?.skipRedirections?[]:e.parseOptionalRedirections();return L.whileNode(n,r,s)}function ti(e,t){e.expect(y.UNTIL);let n=e.parseCompoundList();e.expect(y.DO);let r=e.parseCompoundList();r.length===0&&e.error("syntax error near unexpected token `done'"),e.expect(y.DONE);let s=t?.skipRedirections?[]:e.parseOptionalRedirections();return L.untilNode(n,r,s)}function ni(e,t){e.expect(y.CASE),e.isWord()||e.error("Expected word after 'case'");let n=e.parseWord();e.skipNewlines(),e.expect(y.IN),e.skipNewlines();let r=[];for(;!e.check(y.ESAC,y.EOF);){e.checkIterationLimit();let i=e.getPos(),a=Rf(e);if(a&&r.push(a),e.skipNewlines(),e.getPos()===i&&!a)break}e.expect(y.ESAC);let s=t?.skipRedirections?[]:e.parseOptionalRedirections();return L.caseNode(n,r,s)}function Rf(e){e.check(y.LPAREN)&&e.advance();let t=[];for(;e.isWord()&&(t.push(e.parseWord()),e.check(y.PIPE));)e.advance();if(t.length===0)return null;e.expect(y.RPAREN),e.skipNewlines();let n=[];for(;!e.check(y.DSEMI,y.SEMI_AND,y.SEMI_SEMI_AND,y.ESAC,y.EOF);){e.checkIterationLimit(),e.isWord()&&e.peek(1).type===y.RPAREN&&e.error("syntax error near unexpected token `)'"),e.check(y.LPAREN)&&e.peek(1).type===y.WORD&&e.error(`syntax error near unexpected token \`${e.peek(1).value}'`);let s=e.getPos(),i=e.parseStatement();if(i&&n.push(i),e.skipSeparators(!1),e.getPos()===s&&!i)break}let r=";;";return e.check(y.DSEMI)?(e.advance(),r=";;"):e.check(y.SEMI_AND)?(e.advance(),r=";&"):e.check(y.SEMI_SEMI_AND)&&(e.advance(),r=";;&"),L.caseItem(t,n,r)}function ri(e,t){e.expect(y.LPAREN);let n=e.parseCompoundList();e.expect(y.RPAREN);let r=t?.skipRedirections?[]:e.parseOptionalRedirections();return L.subshell(n,r)}function si(e,t){e.expect(y.LBRACE);let n=e.parseCompoundList();e.expect(y.RBRACE);let r=t?.skipRedirections?[]:e.parseOptionalRedirections();return L.group(n,r)}var If=["-a","-b","-c","-d","-e","-f","-g","-h","-k","-p","-r","-s","-t","-u","-w","-x","-G","-L","-N","-O","-S","-z","-n","-o","-v","-R"],_f=["==","!=","=~","<",">","-eq","-ne","-lt","-le","-gt","-ge","-nt","-ot","-ef"];function _o(e){return e.isWord()||e.check(y.LBRACE)||e.check(y.RBRACE)||e.check(y.ASSIGNMENT_WORD)}function To(e){if(e.check(y.BANG)&&e.peek(1).type===y.LPAREN){e.advance(),e.advance();let t=1,n="!(";for(;t>0&&!e.check(y.EOF);)if(e.check(y.LPAREN))t++,n+="(",e.advance();else if(e.check(y.RPAREN))t--,t>0&&(n+=")"),e.advance();else if(e.isWord())n+=e.advance().value;else if(e.check(y.PIPE))n+="|",e.advance();else break;return n+=")",e.parseWordFromString(n,!1,!1,!1,!1,!0)}return e.parseWordNoBraceExpansion()}function ai(e){return e.skipNewlines(),Tf(e)}function Tf(e){let t=Lo(e);for(e.skipNewlines();e.check(y.OR_OR);){e.advance(),e.skipNewlines();let n=Lo(e);t={type:"CondOr",left:t,right:n},e.skipNewlines()}return t}function Lo(e){let t=ii(e);for(e.skipNewlines();e.check(y.AND_AND);){e.advance(),e.skipNewlines();let n=ii(e);t={type:"CondAnd",left:t,right:n},e.skipNewlines()}return t}function ii(e){return e.skipNewlines(),e.check(y.BANG)?(e.advance(),e.skipNewlines(),{type:"CondNot",operand:e.withDepth(()=>ii(e))}):Lf(e)}function Lf(e){if(e.check(y.LPAREN)){e.advance();let t=e.withDepth(()=>ai(e));return e.expect(y.RPAREN),{type:"CondGroup",expression:t}}if(_o(e)){let t=e.current(),n=t.value;if(If.includes(n)&&!t.quoted){if(e.advance(),e.check(y.DBRACK_END)&&e.error(`Expected operand after ${n}`),_o(e)){let i=e.parseWordNoBraceExpansion();return{type:"CondUnary",operator:n,operand:i}}let s=e.current();e.error(`unexpected argument \`${s.value}' to conditional unary operator`)}let r=e.parseWordNoBraceExpansion();if(e.isWord()&&_f.includes(e.current().value)){let s=e.advance().value,i;return s==="=~"?i=Mf(e):s==="=="||s==="!="?i=To(e):i=e.parseWordNoBraceExpansion(),{type:"CondBinary",operator:s,left:r,right:i}}if(e.check(y.LESS)){e.advance();let s=e.parseWordNoBraceExpansion();return{type:"CondBinary",operator:"<",left:r,right:s}}if(e.check(y.GREAT)){e.advance();let s=e.parseWordNoBraceExpansion();return{type:"CondBinary",operator:">",left:r,right:s}}if(e.isWord()&&e.current().value==="="){e.advance();let s=To(e);return{type:"CondBinary",operator:"==",left:r,right:s}}return{type:"CondWord",word:r}}e.error("Expected conditional expression")}function Mf(e){let t=[],n=0,r=-1,s=e.getInput(),i=()=>e.check(y.DBRACK_END)||e.check(y.AND_AND)||e.check(y.OR_OR)||e.check(y.NEWLINE)||e.check(y.EOF);for(;!i();){let a=e.current(),o=r>=0&&a.start>r;if(n===0&&o)break;if(n>0&&o){let l=s.slice(r,a.start);t.push({type:"Literal",value:l})}if(e.isWord()||e.check(y.ASSIGNMENT_WORD)){let l=e.parseWordForRegex();t.push(...l.parts),r=e.peek(-1).end}else if(e.check(y.LPAREN)){let l=e.advance();t.push({type:"Literal",value:"("}),n++,r=l.end}else if(e.check(y.DPAREN_START)){let l=e.advance();t.push({type:"Literal",value:"(("}),n+=2,r=l.end}else if(e.check(y.DPAREN_END))if(n>=2){let l=e.advance();t.push({type:"Literal",value:"))"}),n-=2,r=l.end}else{if(n===1)break;break}else if(e.check(y.RPAREN))if(n>0){let l=e.advance();t.push({type:"Literal",value:")"}),n--,r=l.end}else break;else if(e.check(y.PIPE)){let l=e.advance();t.push({type:"Literal",value:"|"}),r=l.end}else if(e.check(y.SEMICOLON))if(n>0){let l=e.advance();t.push({type:"Literal",value:";"}),r=l.end}else break;else if(n>0&&e.check(y.LESS)){let l=e.advance();t.push({type:"Literal",value:"<"}),r=l.end}else if(n>0&&e.check(y.GREAT)){let l=e.advance();t.push({type:"Literal",value:">"}),r=l.end}else if(n>0&&e.check(y.DGREAT)){let l=e.advance();t.push({type:"Literal",value:">>"}),r=l.end}else if(n>0&&e.check(y.DLESS)){let l=e.advance();t.push({type:"Literal",value:"<<"}),r=l.end}else if(n>0&&e.check(y.LESSAND)){let l=e.advance();t.push({type:"Literal",value:"<&"}),r=l.end}else if(n>0&&e.check(y.GREATAND)){let l=e.advance();t.push({type:"Literal",value:">&"}),r=l.end}else if(n>0&&e.check(y.LESSGREAT)){let l=e.advance();t.push({type:"Literal",value:"<>"}),r=l.end}else if(n>0&&e.check(y.CLOBBER)){let l=e.advance();t.push({type:"Literal",value:">|"}),r=l.end}else if(n>0&&e.check(y.TLESS)){let l=e.advance();t.push({type:"Literal",value:"<<<"}),r=l.end}else if(n>0&&e.check(y.AMP)){let l=e.advance();t.push({type:"Literal",value:"&"}),r=l.end}else if(n>0&&e.check(y.LBRACE)){let l=e.advance();t.push({type:"Literal",value:"{"}),r=l.end}else if(n>0&&e.check(y.RBRACE)){let l=e.advance();t.push({type:"Literal",value:"}"}),r=l.end}else break}return t.length===0&&e.error("Expected regex pattern after =~"),{type:"Word",parts:t}}function Gn(e){return e.length>0?e:[L.literal("")]}function Wf(e,t){let n=1,r=t+1;for(;r<e.length&&n>0;){let s=e[r];if(s==="\\"){r+=2;continue}if("@*+?!".includes(s)&&r+1<e.length&&e[r+1]==="("){r++,n++,r++;continue}if(s==="(")n++;else if(s===")"&&(n--,n===0))return r;r++}return-1}function Ff(e,t,n){let r=n+1,s=t[r];if("@*#?$!-0123456789".includes(s))return{part:L.parameterExpansion(s),endIndex:r+1};let i="";for(;r<t.length&&/[a-zA-Z0-9_]/.test(t[r]);)i+=t[r],r++;return{part:L.parameterExpansion(i),endIndex:r}}function Vf(e,t,n,r=!1){let s=n+2,i=!1;t[s]==="!"&&(i=!0,s++);let a=!1;t[s]==="#"&&!/[}:#%/^,]/.test(t[s+1]||"}")&&(a=!0,s++);let o="",l=t[s];if(/[@*#?$!-]/.test(l)&&!/[a-zA-Z0-9_]/.test(t[s+1]||""))o=l,s++;else for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)o+=t[s],s++;if(t[s]==="["){let u=Hs(e,t,s,"[","]");if(o+=t.slice(s,u+1),s=u+1,t[s]==="["){let f=1,d=s;for(;d<t.length&&f>0;)t[d]==="{"?f++:t[d]==="}"&&f--,f>0&&d++;let h=t.slice(n+2,d);return{part:L.parameterExpansion("",{type:"BadSubstitution",text:h}),endIndex:d+1}}}if(o===""&&!i&&!a&&t[s]!=="}"){let u=1,f=s;for(;f<t.length&&u>0;)t[f]==="{"?u++:t[f]==="}"&&u--,u>0&&f++;if(u>0)throw new xe("unexpected EOF while looking for matching '}'",0,0);let d=t.slice(n+2,f);return{part:L.parameterExpansion("",{type:"BadSubstitution",text:d}),endIndex:f+1}}let c=null;if(i){let u=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(u)if(s<t.length&&t[s]!=="}"&&/[:=\-+?#%/^,@]/.test(t[s])){let f=oi(e,t,s,o,r);f.operation?(c={type:"Indirection",innerOp:f.operation},s=f.endIndex):(c={type:"ArrayKeys",array:u[1],star:u[2]==="*"},o="")}else c={type:"ArrayKeys",array:u[1],star:u[2]==="*"},o="";else if(t[s]==="*"||t[s]==="@"&&!/[QPaAEKkuUL]/.test(t[s+1]||"")){let f=t[s];s++,c={type:"VarNamePrefix",prefix:o,star:f==="*"},o=""}else if(s<t.length&&t[s]!=="}"&&/[:=\-+?#%/^,@]/.test(t[s])){let f=oi(e,t,s,o,r);f.operation?(c={type:"Indirection",innerOp:f.operation},s=f.endIndex):c={type:"Indirection"}}else c={type:"Indirection"}}else if(a)if(t[s]===":")for(c={type:"LengthSliceError"};s<t.length&&t[s]!=="}";)s++;else t[s]!=="}"&&/[-+=?]/.test(t[s])?e.error(`\${#${o}${t.slice(s,t.indexOf("}",s))}}: bad substitution`):t[s]==="/"?e.error(`\${#${o}${t.slice(s,t.indexOf("}",s))}}: bad substitution`):c={type:"Length"};if(!c&&s<t.length&&t[s]!=="}"){let u=oi(e,t,s,o,r);c=u.operation,s=u.endIndex}if(s<t.length&&t[s]!=="}"){let u=t[s];if(!/[:\-+=?#%/^,@[]/.test(u)){let f=s;for(;f<t.length&&t[f]!=="}";)f++;let d=t.slice(n,f+1);e.error(`\${${d.slice(2,-1)}}: bad substitution`)}}for(;s<t.length&&t[s]!=="}";)s++;if(s>=t.length)throw new xe("unexpected EOF while looking for matching '}'",0,0);return{part:L.parameterExpansion(o,c),endIndex:s+1}}function oi(e,t,n,r,s=!1){let i=n,a=t[i],o=t[i+1]||"";if(a===":"){let l=o;if("-=?+".includes(l)){i+=2;let b=an(e,t,i),g=t.slice(i,b),w=e.withDepth(()=>Ft(e,g,!1,!1,!0,!1,s,!1,!1,!0)),S=L.word(Gn(w));if(l==="-")return{operation:{type:"DefaultValue",word:S,checkEmpty:!0},endIndex:b};if(l==="=")return{operation:{type:"AssignDefault",word:S,checkEmpty:!0},endIndex:b};if(l==="?")return{operation:{type:"ErrorIfUnset",word:S,checkEmpty:!0},endIndex:b};if(l==="+")return{operation:{type:"UseAlternative",word:S,checkEmpty:!0},endIndex:b}}i++;let c=an(e,t,i),u=t.slice(i,c),f=-1,d=0,h=0;for(let E=0;E<u.length;E++){let b=u[E];if(b==="("||b==="[")d++;else if(b===")"||b==="]")d--;else if(b==="?"&&d===0)h++;else if(b===":"&&d===0)if(h>0)h--;else{f=E;break}}let p=f>=0?u.slice(0,f):u,m=f>=0?u.slice(f+1):null;return{operation:{type:"Substring",offset:Qs(e,p),length:m!==null?Qs(e,m):null},endIndex:c}}if("-=?+".includes(a)){i++;let l=an(e,t,i),c=t.slice(i,l),u=e.withDepth(()=>Ft(e,c,!1,!1,!0,!1,s,!1,!1,!0)),f=L.word(Gn(u));if(a==="-")return{operation:{type:"DefaultValue",word:f,checkEmpty:!1},endIndex:l};if(a==="=")return{operation:{type:"AssignDefault",word:f,checkEmpty:!1},endIndex:l};if(a==="?")return{operation:{type:"ErrorIfUnset",word:c?f:null,checkEmpty:!1},endIndex:l};if(a==="+")return{operation:{type:"UseAlternative",word:f,checkEmpty:!1},endIndex:l}}if(a==="#"||a==="%"){let l=o===a,c=a==="#"?"prefix":"suffix";i+=l?2:1;let u=an(e,t,i),f=t.slice(i,u),d=e.withDepth(()=>Ft(e,f,!1,!1,!1));return{operation:{type:"PatternRemoval",pattern:L.word(Gn(d)),side:c,greedy:l},endIndex:u}}if(a==="/"){let l=o==="/";i+=l?2:1;let c=null;t[i]==="#"?(c="start",i++):t[i]==="%"&&(c="end",i++);let u;c!==null&&(t[i]==="/"||t[i]==="}")?u=i:u=ko(e,t,i);let f=t.slice(i,u),d=e.withDepth(()=>Ft(e,f,!1,!1,!1)),h=L.word(Gn(d)),p=null,m=u;if(t[u]==="/"){let E=u+1,b=an(e,t,E),g=t.slice(E,b),w=e.withDepth(()=>Ft(e,g,!1,!1,!1));p=L.word(Gn(w)),m=b}return{operation:{type:"PatternReplacement",pattern:h,replacement:p,all:l,anchor:c},endIndex:m}}if(a==="^"||a===","){let l=o===a,c=a==="^"?"upper":"lower";i+=l?2:1;let u=an(e,t,i),f=t.slice(i,u),d=f?L.word([L.literal(f)]):null;return{operation:{type:"CaseModification",direction:c,all:l,pattern:d},endIndex:u}}return a==="@"&&/[QPaAEKkuUL]/.test(o)?{operation:{type:"Transform",operator:o},endIndex:i+2}:{operation:null,endIndex:i}}function li(e,t,n,r=!1){let s=n+1;if(s>=t.length)return{part:L.literal("$"),endIndex:s};let i=t[s];if(i==="("&&t[s+1]==="(")return e.isDollarDparenSubshell(t,n)?e.parseCommandSubstitution(t,n):e.parseArithmeticExpansion(t,n);if(i==="["){let a=1,o=s+1;for(;o<t.length&&a>0;)t[o]==="["?a++:t[o]==="]"&&a--,a>0&&o++;if(a===0){let l=t.slice(s+1,o),c=re(e,l);return{part:L.arithmeticExpansion(c),endIndex:o+1}}}return i==="("?e.parseCommandSubstitution(t,n):i==="{"?Vf(e,t,n,r):/[a-zA-Z_0-9@*#?$!-]/.test(i)?Ff(e,t,n):{part:L.literal("$"),endIndex:s}}function Mo(e,t){let n=[],r=0,s="",i=()=>{s&&(n.push(L.literal(s)),s="")};for(;r<t.length;){let a=t[r];if(a==="\\"&&r+1<t.length){let o=t[r+1];if(o==="$"||o==="`"||o==='"'||o==="\\"){s+=o,r+=2;continue}s+=a,r++;continue}if(a==="$"){i();let{part:o,endIndex:l}=li(e,t,r,!0);o&&n.push(o),r=l;continue}if(a==="`"){i();let{part:o,endIndex:l}=e.parseBacktickSubstitution(t,r,!0);n.push(o),r=l;continue}s+=a,r++}return i(),n}function zf(e,t,n){let r=[],s=n,i="",a=()=>{i&&(r.push(L.literal(i)),i="")};for(;s<t.length&&t[s]!=='"';){let o=t[s];if(o==="\\"&&s+1<t.length){let l=t[s+1];if('"\\$`\n'.includes(l)){i+=l,s+=2;continue}i+=o,s++;continue}if(o==="$"){a();let{part:l,endIndex:c}=li(e,t,s,!0);l&&r.push(l),s=c;continue}if(o==="`"){a();let{part:l,endIndex:c}=e.parseBacktickSubstitution(t,s,!0);r.push(l),s=c;continue}i+=o,s++}return a(),{part:L.doubleQuoted(r),endIndex:s}}function Ft(e,t,n=!1,r=!1,s=!1,i=!1,a=!1,o=!1,l=!1,c=!1){if(r)return[L.singleQuoted(t)];if(n){let p=Mo(e,t);return[L.doubleQuoted(p)]}if(t.length>=2&&t[0]==='"'&&t[t.length-1]==='"'){let p=t.slice(1,-1),m=!1;for(let E=0;E<p.length;E++){if(p[E]==='"'){m=!0;break}p[E]==="\\"&&E+1<p.length&&E++}if(!m){let E=Mo(e,p);return[L.doubleQuoted(E)]}}let u=[],f=0,d="",h=()=>{d&&(u.push(L.literal(d)),d="")};for(;f<t.length;){let p=t[f];if(p==="\\"&&f+1<t.length){let m=t[f+1];if(l){h(),u.push(L.escaped(m)),f+=2;continue}let E=i?m==="$"||m==="`"||m===`
|
|
62
|
-
|
|
63
|
-
`||c&&m==="}",b=a?"*?[]\\".includes(m):"*?[]\\(){}.^+".includes(m);E?d+=m:b?(h(),u.push(L.escaped(m))):d+=`\\${m}`,f+=2;continue}if(p==="'"&&!a&&!i){h();let m=t.indexOf("'",f+1);if(m===-1){d+=t.slice(f);break}u.push(L.singleQuoted(t.slice(f+1,m))),f=m+1;continue}if(p==='"'&&!i){h();let{part:m,endIndex:E}=zf(e,t,f+1);u.push(m),f=E+1;continue}if(p==="$"&&t[f+1]==="'"){h();let{part:m,endIndex:E}=Co(e,t,f+2);u.push(m),f=E;continue}if(p==="$"){h();let{part:m,endIndex:E}=li(e,t,f);m&&u.push(m),f=E;continue}if(p==="`"){h();let{part:m,endIndex:E}=e.parseBacktickSubstitution(t,f);u.push(m),f=E;continue}if(p==="~"){let m=f>0?t[f-1]:"";if(f===0||m==="="||s&&m===":"){let b=$o(e,t,f),g=t[b];if(g===void 0||g==="/"||g===":"){h();let w=t.slice(f+1,b)||null;u.push({type:"TildeExpansion",user:w}),f=b;continue}}}if("@*+?!".includes(p)&&f+1<t.length&&t[f+1]==="("){let m=Wf(t,f+1);if(m!==-1){h();let E=t.slice(f,m+1);u.push({type:"Glob",pattern:E}),f=m+1;continue}}if(p==="*"||p==="?"||p==="["){h();let{pattern:m,endIndex:E}=No(e,t,f);u.push({type:"Glob",pattern:m}),f=E;continue}if(p==="{"&&!s&&!o&&!i){let m=Do(e,t,f,Ft);if(m){h(),u.push(m.part),f=m.endIndex;continue}}d+=p,f++}return h(),u}var U=class e{tokens=[];pos=0;pendingHeredocs=[];parseBudget;ownsParseBudget;_input="";constructor(t){this.parseBudget=t??new Nr,this.ownsParseBudget=t===void 0}getInput(){return this._input}checkIterationLimit(){let t=this.current();this.parseBudget.chargeIteration(t?.line??1,t?.column??1)}enterDepth(){let t=this.current();return this.parseBudget.enter(t?.line??1,t?.column??1)}withDepth(t){let n=this.enterDepth();try{return t()}finally{n()}}parse(t,n){this.ownsParseBudget&&this.parseBudget.reset();let r=this.ownsParseBudget?void 0:this.enterDepth();try{if(t.length>js)throw new xe(`Input too large: ${t.length} bytes exceeds limit of ${js}`,1,1);this._input=t;let s=new kr(t,n);if(this.tokens=s.tokenize(),this.tokens.length>qn)throw new xe(`Too many tokens: ${this.tokens.length} exceeds limit of ${qn}`,1,1);return this.pos=0,this.pendingHeredocs=[],this.parseBudget.chargeTokens(this.tokens.length),this.parseScript()}finally{r?.()}}parseTokens(t){this.ownsParseBudget&&this.parseBudget.reset();let n=this.ownsParseBudget?void 0:this.enterDepth();try{return this.tokens=t,this.pos=0,this.pendingHeredocs=[],this.parseBudget.chargeTokens(t.length),this.parseScript()}finally{n?.()}}current(){return this.tokens[this.pos]||this.tokens[this.tokens.length-1]}peek(t=0){return this.tokens[this.pos+t]||this.tokens[this.tokens.length-1]}advance(){let t=this.current();return this.pos<this.tokens.length-1&&this.pos++,t}getPos(){return this.pos}check(t,n,r,s,...i){let a=this.tokens[this.pos]?.type;return a===t||n!==void 0&&a===n||r!==void 0&&a===r||s!==void 0&&a===s?!0:i.length>0?i.includes(a):!1}expect(t,n){if(this.check(t))return this.advance();let r=this.current();throw new xe(n||`Expected ${t}, got ${r.type}`,r.line,r.column,r)}error(t){let n=this.current();throw new xe(t,n.line,n.column,n)}skipNewlines(){for(;this.check(y.NEWLINE,y.COMMENT);)this.check(y.NEWLINE)?(this.advance(),this.processHeredocs()):this.advance()}skipSeparators(t=!0){for(;;){if(this.check(y.NEWLINE)){this.advance(),this.processHeredocs();continue}if(this.check(y.SEMICOLON,y.COMMENT)){this.advance();continue}if(t&&this.check(y.DSEMI,y.SEMI_AND,y.SEMI_SEMI_AND)){this.advance();continue}break}}addPendingHeredoc(t,n,r,s){this.pendingHeredocs.push({redirect:t,delimiter:n,stripTabs:r,quoted:s})}processHeredocs(){for(let t of this.pendingHeredocs)if(this.check(y.HEREDOC_CONTENT)){let n=this.advance(),r;t.quoted?r=L.word([L.literal(n.value)]):r=this.parseWordFromString(n.value,!1,!1,!1,!0),t.redirect.target=L.hereDoc(t.delimiter,r,t.stripTabs,t.quoted)}this.pendingHeredocs=[]}isStatementEnd(){return this.check(y.EOF,y.NEWLINE,y.SEMICOLON,y.AMP,y.AND_AND,y.OR_OR,y.RPAREN,y.RBRACE,y.DSEMI,y.SEMI_AND,y.SEMI_SEMI_AND)}isCommandStart(){let t=this.current().type;return t===y.WORD||t===y.NAME||t===y.NUMBER||t===y.ASSIGNMENT_WORD||t===y.IF||t===y.FOR||t===y.WHILE||t===y.UNTIL||t===y.CASE||t===y.LPAREN||t===y.LBRACE||t===y.DPAREN_START||t===y.DBRACK_START||t===y.FUNCTION||t===y.BANG||t===y.TIME||t===y.IN||t===y.LESS||t===y.GREAT||t===y.DLESS||t===y.DGREAT||t===y.LESSAND||t===y.GREATAND||t===y.LESSGREAT||t===y.DLESSDASH||t===y.CLOBBER||t===y.TLESS||t===y.AND_GREAT||t===y.AND_DGREAT}parseScript(){let t=[],r=0;for(this.skipNewlines();!this.check(y.EOF);){r++,r>1e4&&this.error("Parser stuck: too many iterations (>10000)");let s=this.checkUnexpectedToken();if(s){t.push(s),this.skipSeparators(!1);continue}let i=this.pos,a=this.parseStatement();a&&t.push(a),this.skipSeparators(!1),this.check(y.DSEMI,y.SEMI_AND,y.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${this.current().value}'`),this.pos===i&&!this.check(y.EOF)&&this.advance()}return L.script(t)}checkUnexpectedToken(){let t=this.current().type,n=this.current().value;if((t===y.DO||t===y.DONE||t===y.THEN||t===y.ELSE||t===y.ELIF||t===y.FI||t===y.ESAC)&&this.error(`syntax error near unexpected token \`${n}'`),t===y.RBRACE||t===y.RPAREN){let r=`syntax error near unexpected token \`${n}'`;return this.advance(),L.statement([L.pipeline([L.simpleCommand(null,[],[],[])])],[],!1,{message:r,token:n})}return(t===y.DSEMI||t===y.SEMI_AND||t===y.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${n}'`),t===y.SEMICOLON&&this.error(`syntax error near unexpected token \`${n}'`),(t===y.PIPE||t===y.PIPE_AMP)&&this.error(`syntax error near unexpected token \`${n}'`),null}parseStatement(){if(this.skipNewlines(),!this.isCommandStart())return null;let t=this.current().start,n=[],r=[],s=!1,i=this.parsePipeline();for(n.push(i);this.check(y.AND_AND,y.OR_OR);){let l=this.advance();r.push(l.type===y.AND_AND?"&&":"||"),this.skipNewlines();let c=this.parsePipeline();n.push(c)}this.check(y.AMP)&&(this.advance(),s=!0);let a=this.pos>0?this.tokens[this.pos-1].end:t,o=this._input.slice(t,a);return L.statement(n,r,s,void 0,o)}parsePipeline(){let t=!1,n=!1;this.check(y.TIME)&&(this.advance(),t=!0,this.check(y.WORD,y.NAME)&&this.current().value==="-p"&&(this.advance(),n=!0));let r=0;for(;this.check(y.BANG);)this.advance(),r++;let s=r%2===1,i=[],a=[],o=this.parseCommand();for(i.push(o);this.check(y.PIPE,y.PIPE_AMP);){let l=this.advance();this.skipNewlines(),a.push(l.type===y.PIPE_AMP);let c=this.parseCommand();i.push(c)}return L.pipeline(i,s,t,n,a.length>0?a:void 0)}parseCommand(){return this.check(y.IF)?Ys(this):this.check(y.FOR)?Js(this):this.check(y.WHILE)?ei(this):this.check(y.UNTIL)?ti(this):this.check(y.CASE)?ni(this):this.check(y.LPAREN)?ri(this):this.check(y.LBRACE)?si(this):this.check(y.DPAREN_START)?this.dparenClosesWithSpacedParens()?this.parseNestedSubshellsFromDparen():this.parseArithmeticCommand():this.check(y.DBRACK_START)?this.parseConditionalCommand():this.check(y.FUNCTION)?this.parseFunctionDef():this.check(y.NAME,y.WORD)&&this.peek(1).type===y.LPAREN&&this.peek(2).type===y.RPAREN?this.parseFunctionDef():Io(this)}dparenClosesWithSpacedParens(){let t=1,n=1;for(;n<this.tokens.length-this.pos;){let r=this.peek(n);if(r.type===y.EOF)return!1;if(r.type===y.DPAREN_START||r.type===y.LPAREN)t++;else if(r.type===y.DPAREN_END){if(t-=2,t<=0)return!1}else if(r.type===y.RPAREN&&(t--,t===0&&this.peek(n+1).type===y.RPAREN))return!0;n++}return!1}parseNestedSubshellsFromDparen(){this.advance();let t=this.parseCompoundList();this.expect(y.RPAREN),this.expect(y.RPAREN);let n=this.parseOptionalRedirections(),r=L.subshell(t,[]);return L.subshell([L.statement([L.pipeline([r],!1,!1,!1)])],n)}isWord(){let t=this.current().type;return t===y.WORD||t===y.NAME||t===y.NUMBER||t===y.IF||t===y.FOR||t===y.WHILE||t===y.UNTIL||t===y.CASE||t===y.FUNCTION||t===y.ELSE||t===y.ELIF||t===y.FI||t===y.THEN||t===y.DO||t===y.DONE||t===y.ESAC||t===y.IN||t===y.SELECT||t===y.TIME||t===y.COPROC||t===y.BANG}parseWord(){let t=this.advance();return this.parseWordFromString(t.value,t.quoted,t.singleQuoted)}parseWordNoBraceExpansion(){let t=this.advance();return this.parseWordFromString(t.value,t.quoted,t.singleQuoted,!1,!1,!0)}parseWordForRegex(){let t=this.advance();return this.parseWordFromString(t.value,t.quoted,t.singleQuoted,!1,!1,!0,!0)}parseWordFromString(t,n=!1,r=!1,s=!1,i=!1,a=!1,o=!1){let l=Ft(this,t,n,r,s,i,!1,a,o);return L.word(l)}parseCommandSubstitution(t,n){return to(t,n,()=>new e(this.parseBudget),r=>this.error(r))}parseBacktickSubstitution(t,n,r=!1){return no(t,n,r,()=>new e(this.parseBudget),s=>this.error(s))}isDollarDparenSubshell(t,n){return eo(t,n)}parseArithmeticExpansion(t,n){let r=n+3,s=1,i=0,a=r;for(;a<t.length-1&&s>0;)t[a]==="$"&&t[a+1]==="("?t[a+2]==="("?(s++,a+=3):(i++,a+=2):t[a]==="("&&t[a+1]==="("?(s++,a+=2):t[a]===")"&&t[a+1]===")"?i>0?(i--,a++):(s--,s>0&&(a+=2)):t[a]==="("?(i++,a++):(t[a]===")"&&i>0&&i--,a++);let o=t.slice(r,a),l=this.parseArithmeticExpression(o);return{part:L.arithmeticExpansion(l),endIndex:a+2}}parseArithmeticCommand(){let t=this.expect(y.DPAREN_START),n="",r=1,s=0,i=!1,a=!1;for(;r>0&&!this.check(y.EOF);){if(i){if(i=!1,s>0){s--,n+=")";continue}if(this.check(y.RPAREN)){r--,a=!0,this.advance();continue}if(this.check(y.DPAREN_END)){r--,a=!0;continue}n+=")";continue}if(this.check(y.DPAREN_START))r++,n+="((",this.advance();else if(this.check(y.DPAREN_END))s>=2?(s-=2,n+="))",this.advance()):s===1?(s--,n+=")",i=!0,this.advance()):(r--,a=!0,r>0&&(n+="))"),this.advance());else if(this.check(y.LPAREN))s++,n+="(",this.advance();else if(this.check(y.RPAREN))s>0&&s--,n+=")",this.advance();else{let c=this.current().value,u=n.length>0?n[n.length-1]:"";n.length>0&&!n.endsWith(" ")&&!(c==="="&&/[|&^+\-*/%<>]$/.test(n))&&!(c==="<"&&u==="<")&&!(c===">"&&u===">")&&(n+=" "),n+=c,this.advance()}}a||this.expect(y.DPAREN_END);let o=this.parseArithmeticExpression(n.trim()),l=this.parseOptionalRedirections();return L.arithmeticCommand(o,l,t.line)}parseConditionalCommand(){let t=this.expect(y.DBRACK_START),n=ai(this);this.expect(y.DBRACK_END);let r=this.parseOptionalRedirections();return L.conditionalCommand(n,r,t.line)}parseFunctionDef(){let t;if(this.check(y.FUNCTION)){if(this.advance(),this.check(y.NAME)||this.check(y.WORD))t=this.advance().value;else{let s=this.current();throw new xe("Expected function name",s.line,s.column,s)}this.check(y.LPAREN)&&(this.advance(),this.expect(y.RPAREN))}else t=this.advance().value,t.includes("$")&&this.error(`\`${t}': not a valid identifier`),this.expect(y.LPAREN),this.expect(y.RPAREN);this.skipNewlines();let n=this.parseCompoundCommandBody({forFunctionBody:!0}),r=this.parseOptionalRedirections();return L.functionDef(t,n,r)}parseCompoundCommandBody(t){let n=t?.forFunctionBody;if(this.check(y.LBRACE))return si(this,{skipRedirections:n});if(this.check(y.LPAREN))return ri(this,{skipRedirections:n});if(this.check(y.IF))return Ys(this,{skipRedirections:n});if(this.check(y.FOR))return Js(this,{skipRedirections:n});if(this.check(y.WHILE))return ei(this,{skipRedirections:n});if(this.check(y.UNTIL))return ti(this,{skipRedirections:n});if(this.check(y.CASE))return ni(this,{skipRedirections:n});this.error("Expected compound command for function body")}parseCompoundList(){let t=this.enterDepth();try{let n=[];for(this.skipNewlines();!this.check(y.EOF,y.FI,y.ELSE,y.ELIF,y.THEN,y.DO,y.DONE,y.ESAC,y.RPAREN,y.RBRACE,y.DSEMI,y.SEMI_AND,y.SEMI_SEMI_AND)&&this.isCommandStart();){this.checkIterationLimit();let r=this.pos,s=this.parseStatement();if(s&&n.push(s),this.skipSeparators(),this.pos===r&&!s)break}return n}finally{t()}}parseOptionalRedirections(){let t=[];for(;Rr(this);){this.checkIterationLimit();let n=this.pos;if(t.push(Or(this)),this.pos===n)break}return t}parseArithmeticExpression(t){return re(this,t)}};function qe(e,t){return new U().parse(e,t)}var Uf="BASH_ALIAS_";function Ir(e,t,n,r){let s=M(t);if(s>n-r.value)throw new P(`alias expansion exceeds string length limit (${n} bytes)`,"string_length");return r.value+=s,e+t}function Bo(e){return e.parts.length!==1?!1:e.parts[0].type==="Literal"}function Wo(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type==="Literal"?t.value:null}function Fo(e,t){return e.env.get(`${Uf}${t}`)}function zo(e,t,n){return qo(e,t,n)}function qo(e,t,n,r=!0){if(!t.name||!Bo(t.name))return t;let s=Wo(t.name);if(!s)return t;let i=Fo(e,s);if(!i||n.has(s))return t;try{n.add(s);let a=new U,o={value:0},l=Ir("",i,e.limits.maxStringLength,o),c=i.endsWith(" ");if(!c)for(let h of t.args){let p=Uo(h);l=Ir(l,` ${p}`,e.limits.maxStringLength,o)}let u;try{u=a.parse(l)}catch(h){if(h instanceof xe)throw h;return t}if(u.statements.length!==1||u.statements[0].pipelines.length!==1||u.statements[0].pipelines[0].commands.length!==1)return Vo(e,t,i);let f=u.statements[0].pipelines[0].commands[0];if(f.type!=="SimpleCommand")return Vo(e,t,i);let d={...f,assignments:[...t.assignments,...f.assignments],redirections:[...f.redirections,...t.redirections],line:t.line};if(c&&t.args.length>0){d={...d,args:[...d.args,...t.args]};let h=1;for(;r&&d.args.length>0;){let p=d.args[0];if(!Bo(p))break;let m=Wo(p),E=m?Fo(e,m):null;if(!E)break;if(h>=e.limits.maxCallDepth)throw new P(`alias expansion depth limit exceeded (${e.limits.maxCallDepth})`,"recursion");h++;let b={type:"SimpleCommand",name:p,args:d.args.slice(1),assignments:[],redirections:[]},g=qo(e,b,n,!1);if(g===b||(d={...d,name:g.name,args:[...g.args]},!E.endsWith(" ")))break}}return d}catch(a){throw n.delete(s),a}}function Vo(e,t,n){let r={value:0},s=Ir("",n,e.limits.maxStringLength,r);for(let c of t.args){let u=Uo(c);s=Ir(s,` ${u}`,e.limits.maxStringLength,r)}let i=new U,a=i.parseWordFromString("eval",!1,!1),o=0;for(let c of s)c==="'"&&o++;if(r.value+2+o*3>e.limits.maxStringLength)throw new P(`alias expansion exceeds string length limit (${e.limits.maxStringLength} bytes)`,"string_length");let l=i.parseWordFromString(`'${s.replace(/'/g,"'\\''")}'`,!1,!1);return{type:"SimpleCommand",name:a,args:[l],assignments:t.assignments,redirections:t.redirections,line:t.line}}function Uo(e){let t="";for(let n of e.parts)switch(n.type){case"Literal":t+=n.value.replace(/([\s"'$`\\*?[\]{}()<>|&;#!])/g,"\\$1");break;case"SingleQuoted":t+=`'${n.value}'`;break;case"DoubleQuoted":t+=`"${n.parts.map(r=>r.type==="Literal"?r.value:`$${r.type}`).join("")}"`;break;case"ParameterExpansion":t+=`\${${n.parameter}}`;break;case"CommandSubstitution":t+="$(...)";break;case"ArithmeticExpansion":t+=`$((${n.expression}))`;break;case"Glob":t+=n.pattern;break;default:break}return t}var jf=new Map([["alnum","a-zA-Z0-9"],["alpha","a-zA-Z"],["ascii","\\x00-\\x7F"],["blank"," \\t"],["cntrl","\\x00-\\x1F\\x7F"],["digit","0-9"],["graph","!-~"],["lower","a-z"],["print"," -~"],["punct","!-/:-@\\[-`{-~"],["space"," \\t\\n\\r\\f\\v"],["upper","A-Z"],["word","a-zA-Z0-9_"],["xdigit","0-9a-fA-F"]]);function ci(e){return jf.get(e)??""}function jo(e){let t=[],n="",r=0;for(;r<e.length;){let s=e[r];if(s==="["){for(n+=s,r++,r<e.length&&(e[r]==="!"||e[r]==="^")&&(n+=e[r],r++),r<e.length&&e[r]==="]"&&(n+=e[r],r++);r<e.length&&e[r]!=="]";){if(e[r]==="["&&r+1<e.length&&e[r+1]===":"){let i=e.indexOf(":]",r+2);if(i!==-1){n+=e.slice(r,i+2),r=i+2;continue}}if(e[r]==="\\"&&r+1<e.length){n+=e[r]+e[r+1],r+=2;continue}n+=e[r],r++}r<e.length&&e[r]==="]"&&(n+=e[r],r++)}else s===":"?(n!==""&&t.push(n),n="",r++):s==="\\"&&r+1<e.length?(n+=s+e[r+1],r+=2):(n+=s,r++)}return n!==""&&t.push(n),t}function Go(e){let t="^";for(let n=0;n<e.length;n++){let r=e[n];if(r==="*")t+="[^/]*";else if(r==="?")t+="[^/]";else if(r==="["){let s=n+1,i="[";s<e.length&&(e[s]==="^"||e[s]==="!")&&(i+="^",s++),s<e.length&&e[s]==="]"&&(i+="\\]",s++);let a=s;for(;a<e.length;){if(e[a]==="\\"&&a+1<e.length){a+=2;continue}if(e[a]==="["&&a+1<e.length&&e[a+1]===":"){let l=e.indexOf(":]",a+2);if(l!==-1){a=l+2;continue}}if(e[a]==="]")break;a++}let o=s;for(;s<e.length&&e[s]!=="]";){if(e[s]==="["&&s+1<e.length&&e[s+1]===":"){let l=e.indexOf(":]",s+2);if(l!==-1){let c=e.slice(s+2,l),u=ci(c);i+=u,s=l+2;continue}}if(e[s]==="\\"&&s+1<e.length){i+=`\\${e[s+1]}`,s+=2;continue}if(e[s]==="-"){let l=s===o,c=s+1===a;l||c?i+="\\-":i+="-"}else i+=e[s];s++}i+="]",t+=i,n=s}else if(r==="\\"&&n+1<e.length){let s=e[n+1];/[.+^${}()|\\*?[\]]/.test(s)?t+=`\\${s}`:t+=s,n++}else/[.+^${}()|]/.test(r)?t+=`\\${r}`:t+=r}return t+="$",ye(t)}function ui(e,t){let n=1,r=t+1;for(;r<e.length&&n>0;){let s=e[r];if(s==="\\"){r+=2;continue}if(s==="(")n++;else if(s===")"&&(n--,n===0))return r;r++}return-1}function fi(e){let t=[],n="",r=0,s=!1,i=0;for(;i<e.length;){let a=e[i];if(a==="'"&&!s){s=!0,n+="\0QUOTE_START\0",i++;continue}if(a==="'"&&s){s=!1,n+="\0QUOTE_END\0",i++;continue}if(s){n+=a,i++;continue}if(a==="\\"){n+=a,i+1<e.length?(n+=e[i+1],i+=2):i++;continue}a==="("?(r++,n+=a):a===")"?(r--,n+=a):a==="|"&&r===0?(t.push(n),n=""):n+=a,i++}return t.push(n),t}var Zo=5,Vt=class{fs;cwd;globignorePatterns=[];hasGlobignore=!1;globstar=!1;nullglob=!1;failglob=!1;dotglob=!1;extglob=!1;globskipdots=!0;ops={count:0};maxOps;consumeOperation;constructor(t,n,r,s){this.fs=t,this.cwd=n,typeof s=="boolean"?(this.globstar=s,this.maxOps=1e5):s?(this.globstar=s.globstar??!1,this.nullglob=s.nullglob??!1,this.failglob=s.failglob??!1,this.dotglob=s.dotglob??!1,this.extglob=s.extglob??!1,this.globskipdots=s.globskipdots??!0,this.maxOps=s.maxGlobOperations??1e5,this.consumeOperation=s.consumeOperation):this.maxOps=1e5;let i=r?.get("GLOBIGNORE");i!==void 0&&i!==""&&(this.hasGlobignore=!0,this.globignorePatterns=jo(i))}checkOpsLimit(){if(++this.ops.count>this.maxOps)throw new P(`Glob operation limit exceeded (${this.maxOps})`,"glob_operations");this.consumeOperation?.()}hasNullglob(){return this.nullglob}hasFailglob(){return this.failglob}filterGlobignore(t){return!this.hasGlobignore&&!this.globskipdots?t:t.filter(n=>{let r=n.split("/").pop()||n;if((this.hasGlobignore||this.globskipdots)&&(r==="."||r===".."))return!1;if(this.hasGlobignore){for(let s of this.globignorePatterns)if(this.matchGlobignorePattern(n,s))return!1}return!0})}matchGlobignorePattern(t,n){return Go(n).test(t)}isGlobPattern(t){return!!(t.includes("*")||t.includes("?")||/\[.*\]/.test(t)||this.extglob&&/[@*+?!]\(/.test(t))}async expandArgs(t,n){let r=t.map((a,o)=>(n?.[o]??!1)||!this.isGlobPattern(a)?null:this.expand(a)),s=await Promise.all(r.map(a=>a||Promise.resolve(null))),i=[];for(let a=0;a<t.length;a++){let o=s[a];o===null?i.push(t[a]):o.length>0?i.push(...o):i.push(t[a])}return i}async expand(t){if(this.globstar){let r=t.split("/"),s=0;for(let i of r)if(i==="**"&&(s++,s>Zo))throw new P(`Glob pattern has too many ** segments (max ${Zo})`,"glob_operations")}let n;if(t.includes("**")&&this.globstar&&this.isGlobstarValid(t))n=await this.expandRecursive(t);else{let r=t.replace(/\*\*+/g,"*");n=await this.expandSimple(r)}return this.filterGlobignore(n)}isGlobstarValid(t){let n=t.split("/");for(let r of n)if(r.includes("**")&&r!=="**")return!1;return!0}hasGlobChars(t){return!!(t.includes("*")||t.includes("?")||/\[.*\]/.test(t)||this.extglob&&/[@*+?!]\(/.test(t))}async expandSimple(t){let n=t.startsWith("/"),r=t.split("/").filter(c=>c!==""),s=-1;for(let c=0;c<r.length;c++)if(this.hasGlobChars(r[c])){s=c;break}if(s===-1)return[t];let i,a;if(s===0)n?(i="/",a="/"):(i=this.cwd,a="");else{let c=r.slice(0,s);n?(i=`/${c.join("/")}`,a=`/${c.join("/")}`):(i=this.fs.resolvePath(this.cwd,c.join("/")),a=c.join("/"))}let o=r.slice(s);return(await this.expandSegments(i,a,o)).sort()}async expandSegments(t,n,r){if(this.checkOpsLimit(),r.length===0)return[n];let[s,...i]=r,a=[];try{if(this.fs.readdirWithFileTypes){this.checkOpsLimit();let o=await this.fs.readdirWithFileTypes(t),l=[],c=[...o],u=this.dotglob||this.hasGlobignore;if(s.startsWith(".")||this.dotglob){let d=o.some(p=>p.name==="."),h=o.some(p=>p.name==="..");d||c.push({name:".",isFile:!1,isDirectory:!0,isSymbolicLink:!1}),h||c.push({name:"..",isFile:!1,isDirectory:!0,isSymbolicLink:!1})}for(let d of c)if(!(d.name.startsWith(".")&&!s.startsWith(".")&&!u)&&this.matchPattern(d.name,s)){let h=t==="/"?`/${d.name}`:`${t}/${d.name}`,p;n===""?p=d.name:n==="/"?p=`/${d.name}`:p=`${n}/${d.name}`,i.length===0?l.push(Promise.resolve([p])):d.isDirectory&&l.push(this.expandSegments(h,p,i))}let f=await Promise.all(l);for(let d of f)a.push(...d)}else{this.checkOpsLimit();let o=await this.fs.readdir(t),l=[],c=[...o],u=this.dotglob||this.hasGlobignore;(s.startsWith(".")||this.dotglob)&&(o.includes(".")||c.push("."),o.includes("..")||c.push(".."));for(let d of c)if(!(d.startsWith(".")&&!s.startsWith(".")&&!u)&&this.matchPattern(d,s)){let h=t==="/"?`/${d}`:`${t}/${d}`,p;n===""?p=d:n==="/"?p=`/${d}`:p=`${n}/${d}`,i.length===0?l.push(Promise.resolve([p])):l.push((async()=>{try{if(this.checkOpsLimit(),(await this.fs.stat(h)).isDirectory)return this.expandSegments(h,p,i)}catch(m){if(m instanceof P)throw m}return[]})())}let f=await Promise.all(l);for(let d of f)a.push(...d)}}catch(o){if(o instanceof P)throw o}return a}async expandRecursive(t){let n=[],r=t.indexOf("**"),s=t.slice(0,r).replace(/\/$/,"")||".",a=t.slice(r+2).replace(/^\//,"");return a.includes("**")&&this.isGlobstarValid(a)?(await this.walkDirectoryMultiGlobstar(s,a,n),[...new Set(n)].sort()):(await this.walkDirectory(s,a,n),n.sort())}async walkDirectoryMultiGlobstar(t,n,r){this.checkOpsLimit();let s=this.fs.resolvePath(this.cwd,t);try{this.checkOpsLimit();let i=this.fs.readdirWithFileTypes?await this.fs.readdirWithFileTypes(s):null;if(i){let a=[];for(let c of i){let u=t==="."?c.name:`${t}/${c.name}`;c.isDirectory&&a.push(u)}let o=t==="."?n:`${t}/${n}`,l=await this.expandRecursive(o);r.push(...l);for(let c=0;c<a.length;c+=100){let u=a.slice(c,c+100);await Promise.all(u.map(f=>this.walkDirectoryMultiGlobstar(f,n,r)))}}else{this.checkOpsLimit();let a=await this.fs.readdir(s),o=[];for(let u of a){let f=t==="."?u:`${t}/${u}`,d=this.fs.resolvePath(this.cwd,f);try{this.checkOpsLimit(),(await this.fs.stat(d)).isDirectory&&o.push(f)}catch(h){if(h instanceof P)throw h}}let l=t==="."?n:`${t}/${n}`,c=await this.expandRecursive(l);r.push(...c);for(let u=0;u<o.length;u+=100){let f=o.slice(u,u+100);await Promise.all(f.map(d=>this.walkDirectoryMultiGlobstar(d,n,r)))}}}catch(i){if(i instanceof P)throw i}}async walkDirectory(t,n,r){this.checkOpsLimit();let s=this.fs.resolvePath(this.cwd,t);try{if(this.fs.readdirWithFileTypes){this.checkOpsLimit();let i=await this.fs.readdirWithFileTypes(s),a=[],o=[];for(let l of i){let c=t==="."?l.name:`${t}/${l.name}`;l.isDirectory?o.push(c):n&&this.matchPattern(l.name,n)&&a.push(c)}r.push(...a);for(let l=0;l<o.length;l+=100){let c=o.slice(l,l+100);await Promise.all(c.map(u=>this.walkDirectory(u,n,r)))}}else{this.checkOpsLimit();let i=await this.fs.readdir(s),a=[];for(let l=0;l<i.length;l+=100){let c=i.slice(l,l+100),u=await Promise.all(c.map(async f=>{let d=t==="."?f:`${t}/${f}`,h=this.fs.resolvePath(this.cwd,d);try{this.checkOpsLimit();let p=await this.fs.stat(h);return{name:f,path:d,isDirectory:p.isDirectory}}catch(p){if(p instanceof P)throw p;return null}}));a.push(...u.filter(f=>f!==null))}for(let l of a)!l.isDirectory&&n&&this.matchPattern(l.name,n)&&r.push(l.path);let o=a.filter(l=>l.isDirectory);for(let l=0;l<o.length;l+=100){let c=o.slice(l,l+100);await Promise.all(c.map(u=>this.walkDirectory(u.path,n,r)))}}}catch(i){if(i instanceof P)throw i}}matchPattern(t,n){return this.patternToRegex(n).test(t)}patternToRegex(t){let n=this.patternToRegexStr(t);return ye(`^${n}$`)}patternToRegexStr(t){let n="",r=!1;for(let s=0;s<t.length;s++){if(t.slice(s,s+13)==="\0QUOTE_START\0"){r=!0,s+=12;continue}if(t.slice(s,s+11)==="\0QUOTE_END\0"){r=!1,s+=10;continue}let i=t[s];if(r){/[.+^${}()|\\*?[\]]/.test(i)?n+=`\\${i}`:n+=i;continue}if(this.extglob&&(i==="@"||i==="*"||i==="+"||i==="?"||i==="!")&&s+1<t.length&&t[s+1]==="("){let a=ui(t,s+1);if(a!==-1){let o=t.slice(s+2,a),l=fi(o),c=l.map(f=>this.patternToRegexStr(f)),u=c.length>0?c.join("|"):"(?:)";if(i==="@")n+=`(?:${u})`;else if(i==="*")n+=`(?:${u})*`;else if(i==="+")n+=`(?:${u})+`;else if(i==="?")n+=`(?:${u})?`;else if(i==="!")if(a<t.length-1){let d=l.map(p=>this.computePatternLength(p));if(d.every(p=>p!==null)&&d.every(p=>p===d[0])&&d[0]!==null){let p=d[0];if(p===0)n+="(?:.+)";else{let m=[];p>0&&m.push(`.{0,${p-1}}`),m.push(`.{${p+1},}`),m.push(`(?!(?:${u})).{${p}}`),n+=`(?:${m.join("|")})`}}else n+=`(?:(?!(?:${u})).)*?`}else n+=`(?!(?:${u})$).*`;s=a;continue}}if(i==="*")n+=".*";else if(i==="?")n+=".";else if(i==="["){let a=s+1,o="[";a<t.length&&(t[a]==="^"||t[a]==="!")&&(o+="^",a++),a<t.length&&t[a]==="]"&&(o+="\\]",a++);let l=a;for(;l<t.length;){if(t[l]==="\\"&&l+1<t.length){l+=2;continue}if(t[l]==="["&&l+1<t.length&&t[l+1]===":"){let u=t.indexOf(":]",l+2);if(u!==-1){l=u+2;continue}}if(t[l]==="]")break;l++}let c=a;for(;a<t.length&&t[a]!=="]";){if(t[a]==="["&&a+1<t.length&&t[a+1]===":"){let u=t.indexOf(":]",a+2);if(u!==-1){let f=t.slice(a+2,u),d=ci(f);o+=d,a=u+2;continue}}if(t[a]==="\\"&&a+1<t.length){o+=`\\${t[a+1]}`,a+=2;continue}if(t[a]==="-"){let u=a===c,f=a+1===l;u||f?o+="\\-":o+="-"}else o+=t[a];a++}o+="]",n+=o,s=a}else if(i==="\\"&&s+1<t.length){let a=t[s+1];/[.+^${}()|\\*?[\]]/.test(a)?n+=`\\${a}`:n+=a,s++}else/[.+^${}()|]/.test(i)?n+=`\\${i}`:n+=i}return n}computePatternLength(t){let n=0,r=0,s=!1;for(;r<t.length;){if(t.slice(r,r+13)==="\0QUOTE_START\0"){s=!0,r+=13;continue}if(t.slice(r,r+11)==="\0QUOTE_END\0"){s=!1,r+=11;continue}let i=t[r];if(s){n+=1,r++;continue}if((i==="@"||i==="*"||i==="+"||i==="?"||i==="!")&&r+1<t.length&&t[r+1]==="("){let a=ui(t,r+1);if(a!==-1){if(i==="@"){let o=t.slice(r+2,a),c=fi(o).map(u=>this.computePatternLength(u));if(c.every(u=>u!==null)&&c.every(u=>u===c[0])){n+=c[0],r=a+1;continue}return null}return null}}if(i==="*")return null;if(i==="?"){n+=1,r++;continue}if(i==="["){let a=t.indexOf("]",r+1);if(a!==-1){n+=1,r=a+1;continue}n+=1,r++;continue}if(i==="\\"){n+=1,r+=2;continue}n+=1,r++}return n}};function di(e){for(let t=0;t<e.length;t++){if(e[t]==="\\"){t++;continue}if(e[t]==="$"){let n=e[t+1];if(n==="{"||n&&/[a-zA-Z_]/.test(n))return!0}}return!1}function Gf(e){if(!e.operation)return!1;let t=e.operation,n;if((t.type==="DefaultValue"||t.type==="AssignDefault"||t.type==="UseAlternative"||t.type==="ErrorIfUnset")&&(n=t.word?.parts),!n)return!1;for(let r of n)if(r.type==="DoubleQuoted"||r.type==="SingleQuoted")return!0;return!1}function Ho(e){if(!e.operation)return!1;let t=e.operation,n;if((t.type==="DefaultValue"||t.type==="AssignDefault"||t.type==="UseAlternative"||t.type==="ErrorIfUnset")&&(n=t.word?.parts),!n||n.length===0)return!1;for(let r of n)if(r.type!=="DoubleQuoted"&&r.type!=="SingleQuoted")return!1;return!0}function Zn(e){let t=!1,n=!1,r=!1,s=!1,i=!1,a=!1,o=!1;for(let l of e){if((l.type==="SingleQuoted"||l.type==="DoubleQuoted")&&(t=!0,l.type==="DoubleQuoted"))for(let c of l.parts)c.type==="ParameterExpansion"&&(c.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/)&&(!c.operation||c.operation.type==="PatternRemoval"||c.operation.type==="PatternReplacement")&&(s=!0),(c.operation?.type==="VarNamePrefix"||c.operation?.type==="ArrayKeys")&&(a=!0),c.operation?.type==="Indirection"&&(o=!0));l.type==="CommandSubstitution"&&(n=!0),l.type==="ParameterExpansion"&&(i=!0,(l.parameter==="@"||l.parameter==="*")&&(r=!0),Gf(l)&&(t=!0),(l.operation?.type==="VarNamePrefix"||l.operation?.type==="ArrayKeys")&&(a=!0),l.operation?.type==="Indirection"&&(o=!0)),l.type==="Glob"&&di(l.pattern)&&(i=!0)}return{hasQuoted:t,hasCommandSub:n,hasArrayVar:r,hasArrayAtExpansion:s,hasParamExpansion:i,hasVarNamePrefixExpansion:a,hasIndirection:o}}var Zf=`
|
|
64
|
-
|
|
65
|
-
`)return!1;return!0}function Qo(e){let t=!1,n=[];for(let r of e.split(""))r==="-"?t=!0:/[\\^$.*+?()[\]{}|]/.test(r)?n.push(`\\${r}`):r===" "?n.push("\\t"):r===`
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
`,""):ae(e,a,p)||""}let u=ae(e,a,c);if(u!==void 0)return u;if(c===0){let f=e.state.env.get(a);if(f!==void 0)return f}if(n&&e.state.options.nounset)throw new Be(`${a}[${c}]`);return""}if(/^[1-9][0-9]*$/.test(t)){let a=e.state.env.get(t);if(a===void 0&&n&&e.state.options.nounset)throw new Be(t);return a||""}if(le(e,t)){let a=Te(e,t);if(a===void 0)return"";if(a!==t)return await ie(e,a,n,r);let o=e.state.env.get(t);if((o===void 0||o==="")&&n&&e.state.options.nounset)throw new Be(t);return o||""}let i=e.state.env.get(t);if(i!==void 0)return e.state.tempEnvBindings?.some(a=>a.has(t))&&(e.state.accessedTempEnvVars=e.state.accessedTempEnvVars||new Set,e.state.accessedTempEnvVars.add(t)),i;if(at(e,t)){let a=ae(e,t,0);if(a!==void 0)return a;if(n&&e.state.options.nounset)throw new Be(t);return""}if(n&&e.state.options.nounset)throw new Be(t);return""}async function gt(e,t){if(new Set(["?","$","#","_","-","0","PPID","UID","EUID","RANDOM","SECONDS","BASH_VERSION","!","BASHPID","LINENO"]).has(t))return!0;if(t==="@"||t==="*")return Number.parseInt(e.state.env.get("#")||"0",10)>0;if(t==="PWD"||t==="OLDPWD")return e.state.env.has(t);let r=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(r){let s=r[1],i=r[2];if(le(e,s)){let l=Te(e,s);if(l&&l!==s){if(l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/))return!1;s=l}}if(i==="@"||i==="*")return j(e,s).length>0?!0:e.state.env.has(s);if(e.state.associativeArrays?.has(s)){let l=el(e,$r(i));return Bt(e,s,l)}let o;if(/^-?\d+$/.test(i))o=Number.parseInt(i,10);else try{let l=new U,c=re(l,i);o=await K(e,c.expression)}catch{let l=e.state.env.get(i);o=l?Number.parseInt(l,10):0,Number.isNaN(o)&&(o=0)}if(o<0){let l=j(e,s);if(l.length===0)return!1;let u=Math.max(...l.map(([f])=>typeof f=="number"?f:0))+1+o;return u<0?!1:Bt(e,s,u)}return Bt(e,s,o)}if(le(e,t)){let s=Te(e,t);return s===void 0||s===t?e.state.env.has(t):gt(e,s)}return e.state.env.has(t)?!0:at(e,t)?Bt(e,t,0):!1}async function tl(e,t){let n="",r=0;for(;r<t.length;){if(t[r]==="$"){if(t[r+1]==="{"){let s=1,i=r+2;for(;i<t.length&&s>0;)t[i]==="{"?s++:t[i]==="}"&&s--,i++;n+=t.slice(r,i),r=i;continue}if(t[r+1]==="("){let s=1,i=r+2;for(;i<t.length&&s>0;)t[i]==="("?s++:t[i]===")"&&s--,i++;n+=t.slice(r,i),r=i;continue}if(/[a-zA-Z_]/.test(t[r+1]||"")){let s=r+1;for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)s++;let i=t.slice(r+1,s),a=await ie(e,i);n+=a,r=s;continue}if(/[0-9]/.test(t[r+1]||"")){let s=r+1;for(;s<t.length&&/[0-9]/.test(t[s]);)s++;let i=t.slice(r+1,s),a=await ie(e,i);n+=a,r=s;continue}if(/[*@#?\-!$]/.test(t[r+1]||"")){let s=t[r+1],i=await ie(e,s);n+=i,r+=2;continue}}if(t[r]==='"'){for(n+='"',r++;r<t.length&&t[r]!=='"';)if(t[r]==="$"&&/[a-zA-Z_]/.test(t[r+1]||"")){let s=r+1;for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)s++;let i=t.slice(r+1,s),a=await ie(e,i);n+=a,r=s}else t[r]==="\\"?(n+=t[r],r++,r<t.length&&(n+=t[r],r++)):(n+=t[r],r++);r<t.length&&(n+='"',r++);continue}n+=t[r],r++}return n}async function gi(e,t){let n=t,r=t.startsWith('"')&&t.endsWith('"'),s=t.startsWith("'")&&t.endsWith("'");if((r||s)&&(n=t.slice(1,-1)),s)return n;let i="",a=0;for(;a<n.length;)if(n[a]==="$")if(n[a+1]==="("){let o=1,l=a+2;for(;l<n.length&&o>0;)n[l]==="("&&n[l-1]==="$"||n[l]==="("?o++:n[l]===")"&&o--,l++;let c=n.slice(a+2,l-1);if(e.execFn){let u=await e.execFn(c,{signal:e.state.signal});i+=u.stdout.replace(/\n+$/,""),u.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+u.stderr)}a=l}else if(n[a+1]==="{"){let o=1,l=a+2;for(;l<n.length&&o>0;)n[l]==="{"?o++:n[l]==="}"&&o--,l++;let c=n.slice(a+2,l-1),u=await ie(e,c);i+=u,a=l}else if(/[a-zA-Z_]/.test(n[a+1]||"")){let o=a+1;for(;o<n.length&&/[a-zA-Z0-9_]/.test(n[o]);)o++;let l=n.slice(a+1,o),c=await ie(e,l);i+=c,a=o}else i+=n[a],a++;else if(n[a]==="`"){let o=a+1;for(;o<n.length&&n[o]!=="`";)o++;let l=n.slice(a+1,o);if(e.execFn){let c=await e.execFn(l,{signal:e.state.signal});i+=c.stdout.replace(/\n+$/,""),c.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+c.stderr)}a=o+1}else i+=n[a],a++;return i}var Hn=1e4,wi={maxResults:Hn,maxStringBytes:10*1024*1024};function Br(e,t,n,r){if(e.length>=n.maxResults)return!1;let s=M(t);if(s>n.maxStringBytes-r.value)throw new P(`brace expansion string limit exceeded (${n.maxStringBytes} bytes)`,"string_length");return e.push(t),r.value+=s,!0}function Xf(e,t,n,r,s,i=wi){let a=n??1;a===0&&(a=1);let o=Math.abs(a),l=[],c=0;if(r?.match(/^-?0\d/)&&(c=Math.max(c,r.replace(/^-/,"").length)),s?.match(/^-?0\d/)&&(c=Math.max(c,s.replace(/^-/,"").length)),c>i.maxStringBytes)throw new P(`brace expansion padding limit exceeded (${i.maxStringBytes} bytes)`,"string_length");let u={value:0},f=d=>{if(c>0){let h=d<0,p=String(Math.abs(d)).padStart(c,"0");return h?`-${p}`:p}return String(d)};if(e<=t)for(let d=e,h=0;d<=t&&h<Hn&&Br(l,f(d),i,u);d+=o,h++);else for(let d=e,h=0;d>=t&&h<Hn&&Br(l,f(d),i,u);d-=o,h++);return l}function Yf(e,t,n,r=wi){let s=n??1;s===0&&(s=1);let i=e.charCodeAt(0),a=t.charCodeAt(0),o=Math.abs(s),l=e>="A"&&e<="Z",c=e>="a"&&e<="z",u=t>="A"&&t<="Z",f=t>="a"&&t<="z";if(l&&f||c&&u){let p=n!==void 0?`..${n}`:"";throw new gr(`{${e}..${t}${p}}: invalid sequence`)}let d=[],h={value:0};if(i<=a)for(let p=i,m=0;p<=a&&m<Hn&&Br(d,String.fromCharCode(p),r,h);p+=o,m++);else for(let p=i,m=0;p>=a&&m<Hn&&Br(d,String.fromCharCode(p),r,h);p-=o,m++);return d}function Ei(e,t,n,r,s,i=wi){let a=n!==void 0?`..${n}`:"";return typeof e=="number"&&typeof t=="number"?{expanded:Xf(e,t,n,r,s,i),literal:`{${e}..${t}${a}}`}:typeof e=="string"&&typeof t=="string"?{expanded:Yf(e,t,n,i),literal:`{${e}..${t}${a}}`}:{expanded:null,literal:`{${e}..${t}${a}}`}}function nl(e){if(e.statements.length!==1)return null;let t=e.statements[0];if(t.operators.length!==0||t.pipelines.length!==1)return null;let n=t.pipelines[0];if(n.negated||n.commands.length!==1)return null;let r=n.commands[0];if(r.type!=="SimpleCommand")return null;let s=r;if(s.name!==null||s.args.length!==0||s.assignments.length!==0||s.redirections.length!==1)return null;let i=s.redirections[0];return i.operator!=="<"||i.target.type!=="Word"?null:{target:i.target}}function wt(e,t){return!!(/[*?[]/.test(e)||t&&/[@*+?!]\(/.test(e))}function bi(e){let t="",n=0;for(;n<e.length;)e[n]==="\\"&&n+1<e.length?(t+=e[n+1],n+=2):(t+=e[n],n++);return t}function Xe(e){return e.replace(/([*?[\]\\()|])/g,"\\$1")}function Qn(e){return e.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&")}function te(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function X(e,t,n=!1){let r="",s=0;for(;s<e.length;){let i=e[s];if(n&&(i==="@"||i==="*"||i==="+"||i==="?"||i==="!")&&s+1<e.length&&e[s+1]==="("){let a=Jf(e,s+1);if(a!==-1){let o=e.slice(s+2,a),c=ed(o).map(f=>X(f,t,n)),u=c.length>0?c.join("|"):"(?:)";i==="@"?r+=`(?:${u})`:i==="*"?r+=`(?:${u})*`:i==="+"?r+=`(?:${u})+`:i==="?"?r+=`(?:${u})?`:i==="!"&&(r+=`(?!(?:${u})$).*`),s=a+1;continue}}if(i==="\\")if(s+1<e.length){let a=e[s+1];/[\\^$.|+(){}[\]*?]/.test(a)?r+=`\\${a}`:r+=a,s+=2}else r+="\\\\",s++;else if(i==="*")r+=t?".*":".*?",s++;else if(i==="?")r+=".",s++;else if(i==="["){let a=td(e,s);if(a===-1)r+="\\[",s++;else{let o=e.slice(s+1,a);r+=nd(o),s=a+1}}else/[\^$.|+(){}]/.test(i)?(r+=`\\${i}`,s++):(r+=i,s++)}return r}function Jf(e,t){let n=1,r=t+1;for(;r<e.length&&n>0;){let s=e[r];if(s==="\\"){r+=2;continue}if(s==="(")n++;else if(s===")"&&(n--,n===0))return r;r++}return-1}function ed(e){let t=[],n="",r=0,s=0;for(;s<e.length;){let i=e[s];if(i==="\\"){n+=i,s+1<e.length?(n+=e[s+1],s+=2):s++;continue}i==="("?(r++,n+=i):i===")"?(r--,n+=i):i==="|"&&r===0?(t.push(n),n=""):n+=i,s++}return t.push(n),t}function td(e,t){let n=t+1;for(n<e.length&&e[n]==="^"&&n++,n<e.length&&e[n]==="]"&&n++;n<e.length;){if(e[n]==="\\"&&n+1<e.length){n+=2;continue}if(e[n]==="]")return n;if(e[n]==="'"){let r=e.indexOf("'",n+1);if(r!==-1){n=r+1;continue}}if(e[n]==="["&&n+1<e.length&&e[n+1]===":"){let r=e.indexOf(":]",n+2);if(r!==-1){n=r+2;continue}}n++}return-1}function nd(e){let t="[",n=0;for((e[0]==="^"||e[0]==="!")&&(t+="^",n++);n<e.length;){if(e[n]==="'"){let s=e.indexOf("'",n+1);if(s!==-1){let i=e.slice(n+1,s);for(let a of i)a==="\\"?t+="\\\\":a==="]"?t+="\\]":a==="^"&&t==="["?t+="\\^":t+=a;n=s+1;continue}}if(e[n]==="["&&n+1<e.length&&e[n+1]===":"){let s=e.indexOf(":]",n+2);if(s!==-1){let i=e.slice(n+2,s);t+=sd(i),n=s+2;continue}}let r=e[n];r==="\\"?n+1<e.length?(t+=`\\${e[n+1]}`,n+=2):(t+="\\\\",n++):r==="-"&&n>0&&n<e.length-1?(t+="-",n++):r==="^"&&n===0?(t+="^",n++):(r==="]"&&n===0?t+="\\]":t+=r,n++)}return t+="]",t}var rd=new Map([["alnum","a-zA-Z0-9"],["alpha","a-zA-Z"],["ascii","\\x00-\\x7F"],["blank"," \\t"],["cntrl","\\x00-\\x1F\\x7F"],["digit","0-9"],["graph","!-~"],["lower","a-z"],["print"," -~"],["punct","!-/:-@\\[-`{-~"],["space"," \\t\\n\\r\\f\\v"],["upper","A-Z"],["word","a-zA-Z0-9_"],["xdigit","0-9A-Fa-f"]]);function sd(e){return rd.get(e)??""}function ot(e,t,n,r,s){if(r==="prefix")return e.executionScope.consumeLimited("pattern-removal",Math.max(1,t.length),e.limits.maxGlobOperations,"pattern removal"),ye(`^${n}`,"s").replace(t,"");let i=ye(`${n}$`,"s");if(s)return e.executionScope.consumeLimited("pattern-removal",Math.max(1,t.length),e.limits.maxGlobOperations,"pattern removal"),i.replace(t,"");e.executionScope.consumeLimited("pattern-removal",Math.max(1,t.length),e.limits.maxGlobOperations,"pattern removal");let a=ye(`^(?:.*)(${n})$`,"s").exec(t);if(!a)return t;let o=a[1]??"";return t.slice(0,t.length-o.length)}function bn(e,t){let n=new Set;for(let r of e.state.env.keys())r.startsWith(t)&&n.add(r);for(let r of e.state.arrays?.keys()??[])r.startsWith(t)&&n.add(r);return[...n].sort()}function Wr(e,t,n,r,s){let i=new hn(e.limits.maxStringLength,"pattern replacement",()=>new P(`pattern replacement: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length"));n.lastIndex=0;let a=0,o=n.exec(t);for(;o!==null&&(e.executionScope.consumeLimited("pattern_operations",1,e.limits.maxGlobOperations,"pattern replacement"),!(s&&o[0].length===0&&o.index===t.length||(i.append(t.slice(a,o.index)),i.append(r),a=o.index+o[0].length,!s)));)o[0].length===0&&(a++,n.lastIndex<=o.index&&(n.lastIndex=o.index+1)),o=n.exec(t);return i.append(t.slice(a)),n.lastIndex=0,i.build()}function rl(e){let t=[],n=0;return{append(r){let s=M(r);if(s>e-n)throw new P(`prompt expansion exceeds string length limit (${e} bytes)`,"string_length");r&&t.push(r),n+=s},build:()=>t.join("")}}function id(e,t,n){let r=(a,o=2)=>String(a).padStart(o,"0");if(e===""){let a=r(t.getHours()),o=r(t.getMinutes()),l=r(t.getSeconds());return`${a}:${o}:${l}`}let s=rl(n),i=0;for(;i<e.length;)if(e[i]==="%"){if(i+1>=e.length){s.append("%"),i++;continue}let a=e[i+1];switch(a){case"H":s.append(r(t.getHours()));break;case"M":s.append(r(t.getMinutes()));break;case"S":s.append(r(t.getSeconds()));break;case"d":s.append(r(t.getDate()));break;case"m":s.append(r(t.getMonth()+1));break;case"Y":s.append(String(t.getFullYear()));break;case"y":s.append(r(t.getFullYear()%100));break;case"I":{let o=t.getHours()%12;o===0&&(o=12),s.append(r(o));break}case"p":s.append(t.getHours()<12?"AM":"PM");break;case"P":s.append(t.getHours()<12?"am":"pm");break;case"%":s.append("%");break;case"a":{let o=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];s.append(o[t.getDay()]);break}case"b":{let o=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];s.append(o[t.getMonth()]);break}default:s.append(`%${a}`)}i+=2}else s.append(e[i]),i++;return s.build()}function Kn(e,t){let n=rl(e.limits.maxStringLength),r=0,s=e.state.env.get("USER")||e.state.env.get("LOGNAME")||"user",i=e.state.env.get("HOSTNAME")||"localhost",a=i.split(".")[0],o=e.state.env.get("PWD")||"/",l=e.state.env.get("HOME")||"/",c=o.startsWith(l)?`~${o.slice(l.length)}`:o,u=o.split("/").pop()||o,f=new Date,d=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],h=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],p=e.state.env.get("__COMMAND_NUMBER")||"1";for(;r<t.length;){let m=t[r];if(m==="\\"){if(r+1>=t.length){n.append("\\"),r++;continue}let E=t[r+1];if(E>="0"&&E<="7"){let b="",g=r+1;for(;g<t.length&&g<r+4&&t[g]>="0"&&t[g]<="7";)b+=t[g],g++;let w=Number.parseInt(b,8)%256;n.append(String.fromCharCode(w)),r=g;continue}switch(E){case"\\":n.append("\\"),r+=2;break;case"a":n.append("\x07"),r+=2;break;case"e":n.append("\x1B"),r+=2;break;case"n":n.append(`
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"'":return"'";case'"':return'"';case"?":return"?";default:return l}});case"K":case"k":return r?"":zt(n);case"u":return n.charAt(0).toUpperCase()+n.slice(1);case"U":return n.toUpperCase();case"L":return n.toLowerCase();default:return n}}async function pl(e,t,n,r,s,i,a=!1){if(e.coverage?.hit("bash:expansion:indirection"),le(e,t))return ln(e,t)||"";let o=/^[a-zA-Z_][a-zA-Z0-9_]*\[([@*])\]$/.test(t);if(r){if(s.innerOp?.type==="UseAlternative")return"";throw new Qe(`\${!${t}}`)}let l=n;if(o&&(l===""||l.includes(" ")))throw new Qe(`\${!${t}}`);let c=l.match(/^[a-zA-Z_][a-zA-Z0-9_]*\[(.+)\]$/);if(c&&c[1].includes("~"))throw new Qe(`\${!${t}}`);if(s.innerOp){let u={type:"ParameterExpansion",parameter:l,operation:s.innerOp};return i(e,u,a)}return await ie(e,l)}function ml(e,t){e.coverage?.hit("bash:expansion:array_keys");let r=j(e,t.array).map(([s])=>String(s));return t.star?r.join(Z(e.state.env)):r.join(" ")}function yl(e,t){e.coverage?.hit("bash:expansion:var_name_prefix");let n=bn(e,t.prefix);return t.star?n.join(Z(e.state.env)):n.join(" ")}function gl(e,t,n,r){let s=Number.parseInt(e.state.env.get("#")||"0",10),i=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(t==="*")return{isEmpty:s===0,effectiveValue:n};if(t==="@")return{isEmpty:s===0||s===1&&e.state.env.get("1")==="",effectiveValue:n};if(i){let[,a,o]=i,l=j(e,a);if(l.length===0)return{isEmpty:!0,effectiveValue:""};if(o==="*"){let c=Z(e.state.env),u=l.map(([,f])=>f).join(c);return{isEmpty:r?u==="":!1,effectiveValue:u}}return{isEmpty:l.length===1&&l.every(([,c])=>c===""),effectiveValue:l.map(([,c])=>c).join(" ")}}return{isEmpty:n==="",effectiveValue:n}}function wl(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="\\"&&t+1<e.length){t+=2;continue}if(n==="'"){let r=e.indexOf("'",t+1);if(r!==-1){t=r+1;continue}}if(n==="$"&&t+1<e.length&&e[t+1]==="("||n==="`")return!0;t++}return!1}function El(e,t){let n=1,r=t,s=!1,i=!1;for(;r<e.length&&n>0;){let a=e[r];if(a==="\\"&&!s&&r+1<e.length){r+=2;continue}if(a==="'"&&!i){s=!s,r++;continue}if(a==='"'&&!s){i=!i,r++;continue}if(!s&&!i){if(a==="(")n++;else if(a===")"&&(n--,n===0))return r}r++}return-1}async function Vr(e,t){let n=new U,r;try{r=n.parse(t)}catch{return""}let s=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let i=new Map(e.state.env),a=pt(e.state.arrays),o=e.state.cwd,l=e.state.suppressVerbose;e.state.suppressVerbose=!0;try{let c=await e.executeScript(r),u=c.exitCode;return e.state.env=i,e.state.arrays=a,e.state.cwd=o,e.state.suppressVerbose=l,e.state.lastExitCode=u,e.state.env.set("?",String(u)),c.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+c.stderr),e.state.bashPid=s,c.stdout.replace(/\n+$/,"")}catch(c){if(e.state.env=i,e.state.arrays=a,e.state.cwd=o,e.state.bashPid=s,e.state.suppressVerbose=l,c instanceof P)throw c;return c instanceof H?(e.state.lastExitCode=c.exitCode,e.state.env.set("?",String(c.exitCode)),c.stdout?.replace(/\n+$/,"")??""):""}}function Si(e,t){let n="",r=0;for(;r<t.length;){let s=t[r];if(s==="'"){let i=t.indexOf("'",r+1);if(i!==-1){let a=t.slice(r+1,i);n+=Xe(a),r=i+1;continue}}if(s==='"'){let i=-1,a=r+1;for(;a<t.length;){if(t[a]==="\\"){a+=2;continue}if(t[a]==='"'){i=a;break}a++}if(i!==-1){let o=t.slice(r+1,i),l=ad(e,o);n+=Xe(l),r=i+1;continue}}if(s==="$"&&r+1<t.length){let i=t[r+1];if(i==="{"){let a=t.indexOf("}",r+2);if(a!==-1){let o=t.slice(r+2,a);n+=e.state.env.get(o)??"",r=a+1;continue}}else if(/[a-zA-Z_]/.test(i)){let a=r+1;for(;a<t.length&&/[a-zA-Z0-9_]/.test(t[a]);)a++;let o=t.slice(r+1,a);n+=e.state.env.get(o)??"",r=a;continue}}if(s==="\\"&&r+1<t.length){n+=s+t[r+1],r+=2;continue}n+=s,r++}return n}function ad(e,t){let n="",r=0;for(;r<t.length;){let s=t[r];if(s==="\\"&&r+1<t.length){let i=t[r+1];if(i==="$"||i==="`"||i==="\\"||i==='"'){n+=i,r+=2;continue}n+=s,r++;continue}if(s==="$"&&r+1<t.length){let i=t[r+1];if(i==="{"){let a=t.indexOf("}",r+2);if(a!==-1){let o=t.slice(r+2,a);n+=e.state.env.get(o)??"",r=a+1;continue}}else if(/[a-zA-Z_]/.test(i)){let a=r+1;for(;a<t.length&&/[a-zA-Z0-9_]/.test(t[a]);)a++;let o=t.slice(r+1,a);n+=e.state.env.get(o)??"",r=a;continue}}n+=s,r++}return n}async function bl(e,t){let n="",r=0;for(;r<t.length;){let s=t[r];if(s==="'"){let i=t.indexOf("'",r+1);if(i!==-1){let a=t.slice(r+1,i);n+=Xe(a),r=i+1;continue}}if(s==='"'){let i=-1,a=r+1;for(;a<t.length;){if(t[a]==="\\"){a+=2;continue}if(t[a]==='"'){i=a;break}a++}if(i!==-1){let o=t.slice(r+1,i),l=await od(e,o);n+=Xe(l),r=i+1;continue}}if(s==="$"&&r+1<t.length&&t[r+1]==="("){let i=El(t,r+2);if(i!==-1){let a=t.slice(r+2,i),o=await Vr(e,a);n+=o,r=i+1;continue}}if(s==="`"){let i=t.indexOf("`",r+1);if(i!==-1){let a=t.slice(r+1,i),o=await Vr(e,a);n+=o,r=i+1;continue}}if(s==="$"&&r+1<t.length){let i=t[r+1];if(i==="{"){let a=t.indexOf("}",r+2);if(a!==-1){let o=t.slice(r+2,a);n+=e.state.env.get(o)??"",r=a+1;continue}}else if(/[a-zA-Z_]/.test(i)){let a=r+1;for(;a<t.length&&/[a-zA-Z0-9_]/.test(t[a]);)a++;let o=t.slice(r+1,a);n+=e.state.env.get(o)??"",r=a;continue}}if(s==="\\"&&r+1<t.length){n+=s+t[r+1],r+=2;continue}n+=s,r++}return n}async function od(e,t){let n="",r=0;for(;r<t.length;){let s=t[r];if(s==="\\"&&r+1<t.length){let i=t[r+1];if(i==="$"||i==="`"||i==="\\"||i==='"'){n+=i,r+=2;continue}n+=s,r++;continue}if(s==="$"&&r+1<t.length&&t[r+1]==="("){let i=El(t,r+2);if(i!==-1){let a=t.slice(r+2,i),o=await Vr(e,a);n+=o,r=i+1;continue}}if(s==="`"){let i=t.indexOf("`",r+1);if(i!==-1){let a=t.slice(r+1,i),o=await Vr(e,a);n+=o,r=i+1;continue}}if(s==="$"&&r+1<t.length){let i=t[r+1];if(i==="{"){let a=t.indexOf("}",r+2);if(a!==-1){let o=t.slice(r+2,a);n+=e.state.env.get(o)??"",r=a+1;continue}}else if(/[a-zA-Z_]/.test(i)){let a=r+1;for(;a<t.length&&/[a-zA-Z0-9_]/.test(t[a]);)a++;let o=t.slice(r+1,a);n+=e.state.env.get(o)??"",r=a;continue}}n+=s,r++}return n}function vi(e,t){if(!t.startsWith("~"))return t;e.coverage?.hit("bash:expansion:tilde");let n=e.state.env.get("HOME")!==void 0?e.state.env.get("HOME"):"/home/user";if(t==="~"||t.startsWith("~/"))return n+t.slice(1);let r=1;for(;r<t.length&&/[a-zA-Z0-9_-]/.test(t[r]);)r++;let s=t.slice(1,r),i=t.slice(r);return i!==""&&!i.startsWith("/")?t:s==="root"?`/root${i}`:t}function Ut(e,t){return t.split(":").map(n=>vi(e,n)).join(":")}function De(e,t,n,r){if(e.length>n-t.length)throw new P(`${r} element limit exceeded (${n})`,"array_elements");for(let s of t)e.push(s)}async function ld(e,t,n,r){let s="";for(let i of t.parts)if(i.type==="Glob")s+=X(i.pattern,!0,e.state.shoptOptions.extglob);else if(i.type==="Literal")s+=X(i.value,!0,e.state.shoptOptions.extglob);else if(i.type==="SingleQuoted"||i.type==="Escaped")s+=te(i.value);else if(i.type==="DoubleQuoted"){let a=await n(e,i.parts);s+=te(a)}else if(i.type==="ParameterExpansion"){let a=await r(e,i);s+=X(a,!0,e.state.shoptOptions.extglob)}else{let a=await r(e,i);s+=te(a)}return s}async function Sl(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0];if(s.parts.length!==1||s.parts[0].type!=="ParameterExpansion"||s.parts[0].operation?.type!=="PatternReplacement")return null;let i=s.parts[0],a=i.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!a)return null;let o=a[1],l=a[2]==="*",c=i.operation,u=j(e,o),f=u.map(([,E])=>E);if(u.length===0){let E=e.state.env.get(o);E!==void 0&&f.push(E)}if(f.length===0)return{values:[],quoted:!0};let d="";c.pattern&&(d=await ld(e,c.pattern,n,r));let h=c.replacement?await n(e,c.replacement.parts):"",p=d;c.anchor==="start"?p=`^${d}`:c.anchor==="end"&&(p=`${d}$`);let m=[];try{let E=ye(p,c.all?"g":"");for(let b of f)m.push(E.replace(b,h))}catch{m.push(...f)}if(l){let E=Z(e.state.env);return{values:[m.join(E)],quoted:!0}}return{values:m,quoted:!0}}async function vl(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0];if(s.parts.length!==1||s.parts[0].type!=="ParameterExpansion"||s.parts[0].operation?.type!=="PatternRemoval")return null;let i=s.parts[0],a=i.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!a)return null;let o=a[1],l=a[2]==="*",c=i.operation,u=j(e,o),f=u.map(([,m])=>m);if(u.length===0){let m=e.state.env.get(o);m!==void 0&&f.push(m)}if(f.length===0)return{values:[],quoted:!0};let d="",h=e.state.shoptOptions.extglob;if(c.pattern)for(let m of c.pattern.parts)if(m.type==="Glob")d+=X(m.pattern,c.greedy,h);else if(m.type==="Literal")d+=X(m.value,c.greedy,h);else if(m.type==="SingleQuoted"||m.type==="Escaped")d+=te(m.value);else if(m.type==="DoubleQuoted"){let E=await n(e,m.parts);d+=te(E)}else if(m.type==="ParameterExpansion"){let E=await r(e,m);d+=X(E,c.greedy,h)}else{let E=await r(e,m);d+=te(E)}let p=[];for(let m of f)p.push(ot(e,m,d,c.side,c.greedy));if(l){let m=Z(e.state.env);return{values:[p.join(m)],quoted:!0}}return{values:p,quoted:!0}}async function Al(e,t){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!=="ParameterExpansion"||n.parts[0].operation?.type!=="DefaultValue"&&n.parts[0].operation?.type!=="UseAlternative"&&n.parts[0].operation?.type!=="AssignDefault")return null;let r=n.parts[0],s=r.operation,i=r.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/),a,o=!1;if(i){let l=i[1];o=i[2]==="*";let c=j(e,l),u=c.length>0||e.state.env.has(l),f=c.length===0||c.length===1&&c.every(([,h])=>h===""),d=s.checkEmpty??!1;if(s.type==="UseAlternative"?a=u&&!(d&&f):a=!u||d&&f,!a){if(c.length>0){let p=c.map(([,m])=>m);if(o){let m=Z(e.state.env);return{values:[p.join(m)],quoted:!0}}return{values:p,quoted:!0}}let h=e.state.env.get(l);return h!==void 0?{values:[h],quoted:!0}:{values:[],quoted:!0}}}else{let l=r.parameter,c=await gt(e,l),u=await ie(e,l),f=u==="",d=s.checkEmpty??!1;if(s.type==="UseAlternative"?a=c&&!(d&&f):a=!c||d&&f,!a)return{values:[u],quoted:!0}}if(a&&s.word){let l=s.word.parts,c=null,u=!1;for(let f of l)if(f.type==="ParameterExpansion"&&!f.operation){let d=f.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(d){c=d[1],u=d[2]==="*";break}}if(c){let f=j(e,c);if(f.length>0){let h=f.map(([,p])=>p);if(u||o){let p=Z(e.state.env);return{values:[h.join(p)],quoted:!0}}return{values:h,quoted:!0}}let d=e.state.env.get(c);return d!==void 0?{values:[d],quoted:!0}:{values:[],quoted:!0}}}return null}async function xl(e,t,n,r,s){if(!n||t.length!==1||t[0].type!=="DoubleQuoted")return null;let i=t[0],a=-1,o="",l=!1,c=null;for(let m=0;m<i.parts.length;m++){let E=i.parts[m];if(E.type==="ParameterExpansion"&&(E.operation?.type==="PatternRemoval"||E.operation?.type==="PatternReplacement")){let b=E.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(b){a=m,o=b[1],l=b[2]==="*",c=E.operation;break}}}if(a===-1||a===0&&a===i.parts.length-1)return null;let u="";for(let m=0;m<a;m++)u+=await r(e,i.parts[m]);let f="";for(let m=a+1;m<i.parts.length;m++)f+=await r(e,i.parts[m]);let d=j(e,o),h=d.map(([,m])=>m);if(d.length===0){let m=e.state.env.get(o);if(m!==void 0)h=[m];else{if(l)return{values:[u+f],quoted:!0};let E=u+f;return{values:E?[E]:[],quoted:!0}}}if(c?.type==="PatternRemoval"){let m=c,E="",b=e.state.shoptOptions.extglob;if(m.pattern)for(let g of m.pattern.parts)if(g.type==="Glob")E+=X(g.pattern,m.greedy,b);else if(g.type==="Literal")E+=X(g.value,m.greedy,b);else if(g.type==="SingleQuoted"||g.type==="Escaped")E+=te(g.value);else if(g.type==="DoubleQuoted"){let w=await s(e,g.parts);E+=te(w)}else if(g.type==="ParameterExpansion"){let w=await r(e,g);E+=X(w,m.greedy,b)}else{let w=await r(e,g);E+=te(w)}h=h.map(g=>ot(e,g,E,m.side,m.greedy))}else if(c?.type==="PatternReplacement"){let m=c,E="";if(m.pattern)for(let w of m.pattern.parts)if(w.type==="Glob")E+=X(w.pattern,!0,e.state.shoptOptions.extglob);else if(w.type==="Literal")E+=X(w.value,!0,e.state.shoptOptions.extglob);else if(w.type==="SingleQuoted"||w.type==="Escaped")E+=te(w.value);else if(w.type==="DoubleQuoted"){let S=await s(e,w.parts);E+=te(S)}else if(w.type==="ParameterExpansion"){let S=await r(e,w);E+=X(S,!0,e.state.shoptOptions.extglob)}else{let S=await r(e,w);E+=te(S)}let b=m.replacement?await s(e,m.replacement.parts):"",g=E;m.anchor==="start"?g=`^${E}`:m.anchor==="end"&&(g=`${E}$`);try{let w=ye(g,m.all?"g":"");h=h.map(S=>w.replace(S,b))}catch{}}if(l){let m=Z(e.state.env);return{values:[u+h.join(m)+f],quoted:!0}}return h.length===1?{values:[u+h[0]+f],quoted:!0}:{values:[u+h[0],...h.slice(1,-1),h[h.length-1]+f],quoted:!0}}async function Pl(e,t,n,r){if(!n||t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0],i=-1,a="",o=!1;for(let h=0;h<s.parts.length;h++){let p=s.parts[h];if(p.type==="ParameterExpansion"&&!p.operation){let m=p.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(m){i=h,a=m[1],o=m[2]==="*";break}}}if(i===-1)return null;let l="";for(let h=0;h<i;h++)l+=await r(e,s.parts[h]);let c="";for(let h=i+1;h<s.parts.length;h++)c+=await r(e,s.parts[h]);let u=j(e,a),f=u.map(([,h])=>h);if(u.length===0){let h=e.state.env.get(a);if(h!==void 0)return{values:[l+h+c],quoted:!0};if(o)return{values:[l+c],quoted:!0};let p=l+c;return{values:p?[p]:[],quoted:!0}}if(o){let h=Z(e.state.env);return{values:[l+f.join(h)+c],quoted:!0}}return f.length===1?{values:[l+f[0]+c],quoted:!0}:{values:[l+f[0],...f.slice(1,-1),f[f.length-1]+c],quoted:!0}}async function $l(e,t,n){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let r=t[0];if(r.parts.length!==1||r.parts[0].type!=="ParameterExpansion"||r.parts[0].operation?.type!=="Substring")return null;let s=r.parts[0],i=s.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!i)return null;let a=i[1],o=i[2]==="*",l=s.operation;if(e.state.associativeArrays?.has(a))throw new H(1,"",`bash: \${${a}[@]: 0: 3}: bad substitution
|
|
76
|
-
`);let c=l.offset?await n(e,l.offset.expression):0,u=l.length?await n(e,l.length.expression):void 0,f=j(e,a);if(f.length>e.limits.maxArrayElements)throw new P(`array transform element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let d=0;if(c<0){if(f.length>0){let p=f[f.length-1][0],E=(typeof p=="number"?p:0)+1+c;if(E<0)return{values:[],quoted:!0};d=f.findIndex(([b])=>typeof b=="number"&&b>=E),d<0&&(d=f.length)}}else d=f.findIndex(([p])=>typeof p=="number"&&p>=c),d<0&&(d=f.length);let h;if(u!==void 0){if(u<0)throw new oe(`${a}[@]: substring expression < 0`);h=f.slice(d,d+u).map(([,p])=>p)}else h=f.slice(d).map(([,p])=>p);if(h.length===0)return{values:[],quoted:!0};if(o){let p=Z(e.state.env);return{values:[h.join(p)],quoted:!0}}return{values:h,quoted:!0}}function kl(e,t){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!=="ParameterExpansion"||n.parts[0].operation?.type!=="Transform")return null;let r=n.parts[0],s=r.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!s)return null;let i=s[1],a=s[2]==="*",o=r.operation,l=j(e,i);if(l.length===0){let d=e.state.env.get(i);if(d!==void 0){let h;switch(o.operator){case"a":h="";break;case"P":h=Kn(e,d);break;case"Q":h=zt(d);break;default:h=d}if(M(h)>e.limits.maxStringLength)throw new P(`array transform string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[h],quoted:!0}}return a?{values:[""],quoted:!0}:{values:[],quoted:!0}}let c=qt(e,i),u=[],f=0;for(let[,d]of l){let h;switch(o.operator){case"a":h=c;break;case"P":h=Kn(e,d);break;case"Q":h=zt(d);break;case"u":h=d.charAt(0).toUpperCase()+d.slice(1);break;case"U":h=d.toUpperCase();break;case"L":h=d.toLowerCase();break;default:h=d}let p=M(h);if(p>e.limits.maxStringLength-f)throw new P(`array transform string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");u.push(h),f+=p}if(a){let d=Z(e.state.env);if(Math.max(0,u.length-1)*M(d)>e.limits.maxStringLength-f)throw new P(`array transform string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[u.join(d)],quoted:!0}}return{values:u,quoted:!0}}function Nl(e,t){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!=="ParameterExpansion")return null;let r=n.parts[0];if(r.operation)return null;let s=r.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(@)\]$/);if(!s)return null;let i=s[1];if(le(e,i)){let l=ln(e,i);if(l?.endsWith("[@]")||l?.endsWith("[*]"))return{values:[],quoted:!0}}let a=j(e,i);if(a.length>0)return{values:a.map(([,l])=>l),quoted:!0};let o=e.state.env.get(i);return o!==void 0?{values:[o],quoted:!0}:{values:[],quoted:!0}}function Cl(e,t){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!=="ParameterExpansion"||n.parts[0].operation)return null;let s=n.parts[0].parameter;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)||!le(e,s))return null;let i=ln(e,s);if(!i)return null;let a=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(@)\]$/);if(!a)return null;let o=a[1],l=j(e,o);if(l.length>0)return{values:l.map(([,u])=>u),quoted:!0};let c=e.state.env.get(o);return c!==void 0?{values:[c],quoted:!0}:{values:[],quoted:!0}}async function Dl(e,t,n,r,s){if(!n||t.length!==1||t[0].type!=="DoubleQuoted")return null;let i=t[0];if(i.parts.length!==1||i.parts[0].type!=="ParameterExpansion"||i.parts[0].operation?.type!=="Indirection")return null;let a=i.parts[0],o=a.operation,l=await ie(e,a.parameter),c=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!c){if(!o.innerOp&&(l==="@"||l==="*")){let p=Number.parseInt(e.state.env.get("#")||"0",10),m=[];for(let E=1;E<=p;E++)m.push(e.state.env.get(String(E))||"");return l==="*"?{values:[m.join(Z(e.state.env))],quoted:!0}:{values:m,quoted:!0}}return null}let u=c[1],f=c[2]==="*",d=j(e,u);if(o.innerOp){if(o.innerOp.type==="Substring")return cd(e,d,u,f,o.innerOp);if(o.innerOp.type==="DefaultValue"||o.innerOp.type==="UseAlternative"||o.innerOp.type==="AssignDefault"||o.innerOp.type==="ErrorIfUnset")return ud(e,d,u,f,o.innerOp,s);if(o.innerOp.type==="Transform"&&o.innerOp.operator==="a"){let m=qt(e,u),E=d.map(()=>m);return f?{values:[E.join(Z(e.state.env))],quoted:!0}:{values:E,quoted:!0}}let p=[];for(let[,m]of d){let E={type:"ParameterExpansion",parameter:"_indirect_elem_",operation:o.innerOp},b=e.state.env.get("_indirect_elem_");e.state.env.set("_indirect_elem_",m);try{let g=await r(e,E,!0);p.push(g)}finally{b!==void 0?e.state.env.set("_indirect_elem_",b):e.state.env.delete("_indirect_elem_")}}return f?{values:[p.join(Z(e.state.env))],quoted:!0}:{values:p,quoted:!0}}if(d.length>0){let p=d.map(([,m])=>m);return f?{values:[p.join(Z(e.state.env))],quoted:!0}:{values:p,quoted:!0}}let h=e.state.env.get(u);return h!==void 0?{values:[h],quoted:!0}:{values:[],quoted:!0}}async function cd(e,t,n,r,s){let i=s.offset?await K(e,s.offset.expression):0,a=s.length?await K(e,s.length.expression):void 0,o=0;if(i<0){if(t.length>0){let u=t[t.length-1][0],d=(typeof u=="number"?u:0)+1+i;if(d<0)return{values:[],quoted:!0};if(o=t.findIndex(([h])=>typeof h=="number"&&h>=d),o<0)return{values:[],quoted:!0}}}else if(o=t.findIndex(([u])=>typeof u=="number"&&u>=i),o<0)return{values:[],quoted:!0};let l;if(a!==void 0){if(a<0)throw new oe(`${n}[@]: substring expression < 0`);l=t.slice(o,o+a)}else l=t.slice(o);let c=l.map(([,u])=>u);return r?{values:[c.join(Z(e.state.env))],quoted:!0}:{values:c,quoted:!0}}async function ud(e,t,n,r,s,i){let a=s.checkEmpty??!1,o=t.map(([,u])=>u),l=t.length===0,c=t.length===0;if(s.type==="UseAlternative")return!c&&!(a&&l)&&s.word?{values:[await i(e,s.word.parts,!0)],quoted:!0}:{values:[],quoted:!0};if(s.type==="DefaultValue")return(c||a&&l)&&s.word?{values:[await i(e,s.word.parts,!0)],quoted:!0}:r?{values:[o.join(Z(e.state.env))],quoted:!0}:{values:o,quoted:!0};if(s.type==="AssignDefault"){if((c||a&&l)&&s.word){let f=await i(e,s.word.parts,!0);return q(e,n,0,f),{values:[f],quoted:!0}}return r?{values:[o.join(Z(e.state.env))],quoted:!0}:{values:o,quoted:!0}}return r?{values:[o.join(Z(e.state.env))],quoted:!0}:{values:o,quoted:!0}}async function Rl(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="UseAlternative"&&t[0].operation?.type!=="DefaultValue")return null;let n=t[0],r=n.operation,s=r?.word;if(!s||s.parts.length!==1||s.parts[0].type!=="DoubleQuoted")return null;let i=s.parts[0];if(i.parts.length!==1||i.parts[0].type!=="ParameterExpansion"||i.parts[0].operation?.type!=="Indirection")return null;let a=i.parts[0],l=(await ie(e,a.parameter)).match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!l)return null;let c=await gt(e,n.parameter),u=await ie(e,n.parameter)==="",f=r.checkEmpty??!1,d;if(r.type==="UseAlternative"?d=c&&!(f&&u):d=!c||f&&u,d){let h=l[1],p=l[2]==="*",m=j(e,h);if(m.length>0){let b=m.map(([,g])=>g);return p?{values:[b.join(Z(e.state.env))],quoted:!0}:{values:b,quoted:!0}}let E=e.state.env.get(h);return E!==void 0?{values:[E],quoted:!0}:{values:[],quoted:!0}}return{values:[],quoted:!1}}async function Ol(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="Indirection")return null;let n=t[0],s=n.operation.innerOp;if(!s||s.type!=="UseAlternative"&&s.type!=="DefaultValue")return null;let i=s.word;if(!i||i.parts.length!==1||i.parts[0].type!=="DoubleQuoted")return null;let a=i.parts[0];if(a.parts.length!==1||a.parts[0].type!=="ParameterExpansion"||a.parts[0].operation?.type!=="Indirection")return null;let o=a.parts[0],c=(await ie(e,o.parameter)).match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!c)return null;let u=await ie(e,n.parameter),f=await gt(e,n.parameter),d=u==="",h=s.checkEmpty??!1,p;if(s.type==="UseAlternative"?p=f&&!(h&&d):p=!f||h&&d,p){let m=c[1],E=c[2]==="*",b=j(e,m);if(b.length>0){let w=b.map(([,S])=>S);return E?{values:[w.join(Z(e.state.env))],quoted:!0}:{values:w,quoted:!0}}let g=e.state.env.get(m);return g!==void 0?{values:[g],quoted:!0}:{values:[],quoted:!0}}return{values:[],quoted:!1}}function Il(e){let t=Number.parseInt(e.state.env.get("#")||"0",10);if(t>e.limits.maxArrayElements)throw new P(`positional parameter element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let n=[],r=0;for(let s=1;s<=t;s++){let i=e.state.env.get(String(s))||"",a=M(i);if(a>e.limits.maxStringLength-r)throw new P(`positional parameter string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");n.push(i),r+=a}return n}function zr(e,t,n){if(M(t)>n-M(e))throw new P(`positional expansion string limit exceeded (${n} bytes)`,"string_length");return e+t}function Ai(e,t,n,r){if(e.length>=r.limits.maxArrayElements)throw new P(`positional expansion element limit exceeded (${r.limits.maxArrayElements})`,"array_elements");let s=M(t);if(s>r.limits.maxStringLength-n.value)throw new P(`positional expansion string limit exceeded (${r.limits.maxStringLength} bytes)`,"string_length");e.push(t),n.value+=s}async function _l(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0],i=-1,a=!1;for(let g=0;g<s.parts.length;g++){let w=s.parts[g];if(w.type==="ParameterExpansion"&&(w.parameter==="@"||w.parameter==="*")&&w.operation?.type==="Substring"){i=g,a=w.parameter==="*";break}}if(i===-1)return null;let l=s.parts[i].operation,c=l.offset?await n(e,l.offset.expression):0,u=l.length?await n(e,l.length.expression):void 0,f=Number.parseInt(e.state.env.get("#")||"0",10),d=[];for(let g=1;g<=f;g++)d.push(e.state.env.get(String(g))||"");let h=e.state.env.get("0")||"bash",p;if(c<=0){let g=[h,...d],w=g.length+c;if(w<0)p=[];else{let S=c<0?w:0;if(u!==void 0){let A=u<0?g.length+u:S+u;p=g.slice(S,Math.max(S,A))}else p=g.slice(S)}}else{let g=c-1;if(g>=d.length)p=[];else if(u!==void 0){let w=u<0?d.length+u:g+u;p=d.slice(g,Math.max(g,w))}else p=d.slice(g)}let m="";for(let g=0;g<i;g++)m+=await r(e,s.parts[g]);let E="";for(let g=i+1;g<s.parts.length;g++)E+=await r(e,s.parts[g]);if(p.length===0){let g=m+E;return{values:g?[g]:[],quoted:!0}}if(a){let g=Z(e.state.env);return{values:[m+p.join(g)+E],quoted:!0}}return p.length===1?{values:[m+p[0]+E],quoted:!0}:{values:[m+p[0],...p.slice(1,-1),p[p.length-1]+E],quoted:!0}}async function Tl(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0],i=-1,a=!1;for(let g=0;g<s.parts.length;g++){let w=s.parts[g];if(w.type==="ParameterExpansion"&&(w.parameter==="@"||w.parameter==="*")&&w.operation?.type==="PatternReplacement"){i=g,a=w.parameter==="*";break}}if(i===-1)return null;let l=s.parts[i].operation,c=Il(e),u="";for(let g=0;g<i;g++)u=zr(u,await n(e,s.parts[g]),e.limits.maxStringLength);let f="";for(let g=i+1;g<s.parts.length;g++)f=zr(f,await n(e,s.parts[g]),e.limits.maxStringLength);if(c.length===0){let g=u+f;return{values:g?[g]:[],quoted:!0}}let d="";if(l.pattern)for(let g of l.pattern.parts)if(g.type==="Glob")d+=X(g.pattern,!0,e.state.shoptOptions.extglob);else if(g.type==="Literal")d+=X(g.value,!0,e.state.shoptOptions.extglob);else if(g.type==="SingleQuoted"||g.type==="Escaped")d+=te(g.value);else if(g.type==="DoubleQuoted"){let w=await r(e,g.parts);d+=te(w)}else if(g.type==="ParameterExpansion"){let w=await n(e,g);d+=X(w,!0,e.state.shoptOptions.extglob)}else{let w=await n(e,g);d+=te(w)}let h=l.replacement?await r(e,l.replacement.parts):"",p=d;l.anchor==="start"?p=`^${d}`:l.anchor==="end"&&(p=`${d}$`);let m=[],E={value:0};try{let g=ye(p,l.all?"g":"");for(let w of c){let S=0;g.lastIndex=0;for(let O=g.exec(w);O&&(S++,!!l.all);O=g.exec(w))O[0].length===0&&g.lastIndex++;let A=M(w),v=M(h),x=0,N=/\$(?:\$|&|\d+|<[^>]+>|`|')/g;for(;N.exec(h)!==null;)x++;if(A+S*v+S*x*A>e.limits.maxStringLength-E.value)throw new P(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");Ai(m,g.replace(w,h),E,e)}}catch(g){if(g instanceof P)throw g;for(let w of c)Ai(m,w,E,e)}if(a){let g=Z(e.state.env);if(E.value+Math.max(0,m.length-1)*M(g)+M(u)+M(f)>e.limits.maxStringLength)throw new P(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[u+m.join(g)+f],quoted:!0}}if(M(u)+E.value+M(f)>e.limits.maxStringLength)throw new P(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return m.length===1?{values:[u+m[0]+f],quoted:!0}:{values:[u+m[0],...m.slice(1,-1),m[m.length-1]+f],quoted:!0}}async function Ll(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0],i=-1,a=!1;for(let b=0;b<s.parts.length;b++){let g=s.parts[b];if(g.type==="ParameterExpansion"&&(g.parameter==="@"||g.parameter==="*")&&g.operation?.type==="PatternRemoval"){i=b,a=g.parameter==="*";break}}if(i===-1)return null;let l=s.parts[i].operation,c=Il(e),u="";for(let b=0;b<i;b++)u=zr(u,await n(e,s.parts[b]),e.limits.maxStringLength);let f="";for(let b=i+1;b<s.parts.length;b++)f=zr(f,await n(e,s.parts[b]),e.limits.maxStringLength);if(c.length===0){let b=u+f;return{values:b?[b]:[],quoted:!0}}let d="",h=e.state.shoptOptions.extglob;if(l.pattern)for(let b of l.pattern.parts)if(b.type==="Glob")d+=X(b.pattern,l.greedy,h);else if(b.type==="Literal")d+=X(b.value,l.greedy,h);else if(b.type==="SingleQuoted"||b.type==="Escaped")d+=te(b.value);else if(b.type==="DoubleQuoted"){let g=await r(e,b.parts);d+=te(g)}else if(b.type==="ParameterExpansion"){let g=await n(e,b);d+=X(g,l.greedy,h)}else{let g=await n(e,b);d+=te(g)}let p=[],m={value:0};for(let b of c)Ai(p,ot(e,b,d,l.side,l.greedy),m,e);if(a){let b=Z(e.state.env);if(m.value+Math.max(0,p.length-1)*M(b)+M(u)+M(f)>e.limits.maxStringLength)throw new P(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[u+p.join(b)+f],quoted:!0}}if(M(u)+m.value+M(f)>e.limits.maxStringLength)throw new P(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return p.length===1?{values:[u+p[0]+f],quoted:!0}:{values:[u+p[0],...p.slice(1,-1),p[p.length-1]+f],quoted:!0}}async function Ml(e,t,n){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let r=t[0],s=-1,i=!1;for(let d=0;d<r.parts.length;d++){let h=r.parts[d];if(h.type==="ParameterExpansion"&&(h.parameter==="@"||h.parameter==="*")){s=d,i=h.parameter==="*";break}}if(s===-1)return null;let a=r.parts[s];if(a.type==="ParameterExpansion"&&a.operation)return null;let o=Number.parseInt(e.state.env.get("#")||"0",10),l="";for(let d=0;d<s;d++)l+=await n(e,r.parts[d]);let c="";for(let d=s+1;d<r.parts.length;d++)c+=await n(e,r.parts[d]);if(o===0){if(i)return{values:[l+c],quoted:!0};let d=l+c;return{values:d?[d]:[],quoted:!0}}let u=[];for(let d=1;d<=o;d++)u.push(e.state.env.get(String(d))||"");if(i){let d=Z(e.state.env);return{values:[l+u.join(d)+c],quoted:!0}}return u.length===1?{values:[l+u[0]+c],quoted:!0}:{values:[l+u[0],...u.slice(1,-1),u[u.length-1]+c],quoted:!0}}function Et(e,t,n,r){if(t.length>=e.limits.maxArrayElements)throw new P(`unquoted expansion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let s=M(n);if(s>e.limits.maxStringLength-r.value)throw new P(`unquoted expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");t.push(n),r.value+=s}function xi(e,t,n,r){let s=M(n),i=Math.max(0,t.length-1);if(s>0&&i>Math.floor((e.limits.maxStringLength-r)/s))throw new P(`unquoted expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return t.join(n)}function fd(e){return new Vt(e.fs,e.state.cwd,e.state.env,{globstar:e.state.shoptOptions.globstar,nullglob:e.state.shoptOptions.nullglob,failglob:e.state.shoptOptions.failglob,dotglob:e.state.shoptOptions.dotglob,extglob:e.state.shoptOptions.extglob,globskipdots:e.state.shoptOptions.globskipdots,maxGlobOperations:e.limits.maxGlobOperations,consumeOperation:()=>e.executionScope.consumeLimited("glob_operations",1,e.limits.maxGlobOperations,"glob expansion")})}async function qr(e,t){if(e.state.options.noglob)return t;let n=fd(e),r=[];for(let s of t)if(wt(s,e.state.shoptOptions.extglob)){let i=await n.expand(s);if(i.length>0)De(r,i,e.limits.maxArrayElements,"unquoted glob expansion");else{if(n.hasFailglob())throw new Rt(s);n.hasNullglob()||r.push(s)}}else r.push(s);return r}async function Bl(e,t,n,r){let s=-1,i="",a=!1;for(let S=0;S<t.length;S++){let A=t[S];if(A.type==="ParameterExpansion"&&A.operation?.type==="PatternReplacement"){let v=A.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(v){s=S,i=v[1],a=v[2]==="*";break}}}if(s===-1)return null;let l=t[s].operation,c=j(e,i),u=c.map(([,S])=>S);if(c.length===0){let S=e.state.env.get(i);S!==void 0&&(u=[S])}if(u.length===0)return{values:[],quoted:!1};let f="";if(l.pattern)for(let S of l.pattern.parts)if(S.type==="Glob")f+=X(S.pattern,!0,e.state.shoptOptions.extglob);else if(S.type==="Literal")f+=X(S.value,!0,e.state.shoptOptions.extglob);else if(S.type==="SingleQuoted"||S.type==="Escaped")f+=te(S.value);else if(S.type==="DoubleQuoted"){let A=await n(e,S.parts);f+=te(A)}else if(S.type==="ParameterExpansion"){let A=await r(e,S);f+=X(A,!0,e.state.shoptOptions.extglob)}else{let A=await r(e,S);f+=te(A)}let d=l.replacement?await n(e,l.replacement.parts):"",h=f;l.anchor==="start"?h=`^${f}`:l.anchor==="end"&&(h=`${f}$`);let p=[],m={value:0};try{let S=ye(h,l.all?"g":"");for(let A of u)Et(e,p,Wr(e,A,S,d,l.all),m)}catch(S){if(S instanceof P)throw S;for(let A of u)Et(e,p,A,m)}let E=ve(e.state.env),b=Ce(e.state.env);if(a){let S=Z(e.state.env),A=xi(e,p,S,m.value);return b?{values:A?[A]:[],quoted:!1}:{values:ue(A,E,e.limits.maxArrayElements),quoted:!1}}if(b)return{values:p,quoted:!1};let g=[],w={value:0};for(let S of p)if(S==="")Et(e,g,"",w);else for(let A of ue(S,E,e.limits.maxArrayElements))Et(e,g,A,w);return{values:g,quoted:!1}}async function Wl(e,t,n,r){let s=-1,i="",a=!1;for(let w=0;w<t.length;w++){let S=t[w];if(S.type==="ParameterExpansion"&&S.operation?.type==="PatternRemoval"){let A=S.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(A){s=w,i=A[1],a=A[2]==="*";break}}}if(s===-1)return null;let l=t[s].operation,c=j(e,i),u=c.map(([,w])=>w);if(c.length===0){let w=e.state.env.get(i);w!==void 0&&(u=[w])}if(u.length===0)return{values:[],quoted:!1};let f="",d=e.state.shoptOptions.extglob;if(l.pattern)for(let w of l.pattern.parts)if(w.type==="Glob")f+=X(w.pattern,l.greedy,d);else if(w.type==="Literal")f+=X(w.value,l.greedy,d);else if(w.type==="SingleQuoted"||w.type==="Escaped")f+=te(w.value);else if(w.type==="DoubleQuoted"){let S=await n(e,w.parts);f+=te(S)}else if(w.type==="ParameterExpansion"){let S=await r(e,w);f+=X(S,l.greedy,d)}else{let S=await r(e,w);f+=te(S)}let h=[],p={value:0};for(let w of u)Et(e,h,ot(e,w,f,l.side,l.greedy),p);let m=ve(e.state.env),E=Ce(e.state.env);if(a){let w=Z(e.state.env),S=xi(e,h,w,p.value);return E?{values:S?[S]:[],quoted:!1}:{values:ue(S,m,e.limits.maxArrayElements),quoted:!1}}if(E)return{values:h,quoted:!1};let b=[],g={value:0};for(let w of h)if(w==="")Et(e,b,"",g);else for(let S of ue(w,m,e.limits.maxArrayElements))Et(e,b,S,g);return{values:b,quoted:!1}}async function Fl(e,t,n,r){let s=-1,i=!1;for(let g=0;g<t.length;g++){let w=t[g];if(w.type==="ParameterExpansion"&&(w.parameter==="@"||w.parameter==="*")&&w.operation?.type==="PatternRemoval"){s=g,i=w.parameter==="*";break}}if(s===-1)return null;let o=t[s].operation,l=Number.parseInt(e.state.env.get("#")||"0",10),c=[];for(let g=1;g<=l;g++)c.push(e.state.env.get(String(g))||"");if(c.length===0)return{values:[],quoted:!1};let u="",f=e.state.shoptOptions.extglob;if(o.pattern)for(let g of o.pattern.parts)if(g.type==="Glob")u+=X(g.pattern,o.greedy,f);else if(g.type==="Literal")u+=X(g.value,o.greedy,f);else if(g.type==="SingleQuoted"||g.type==="Escaped")u+=te(g.value);else if(g.type==="DoubleQuoted"){let w=await n(e,g.parts);u+=te(w)}else if(g.type==="ParameterExpansion"){let w=await r(e,g);u+=X(w,o.greedy,f)}else{let w=await r(e,g);u+=te(w)}let d=[],h={value:0};for(let g of c)Et(e,d,ot(e,g,u,o.side,o.greedy),h);let p=ve(e.state.env),m=Ce(e.state.env);if(i){let g=Z(e.state.env),w=xi(e,d,g,h.value);return m?{values:w?[w]:[],quoted:!1}:{values:ue(w,p,e.limits.maxArrayElements),quoted:!1}}if(m)return{values:d,quoted:!1};let E=[],b={value:0};for(let g of d)if(g==="")Et(e,E,"",b);else for(let w of ue(g,p,e.limits.maxArrayElements))Et(e,E,w,b);return{values:E,quoted:!1}}async function Vl(e,t,n,r){let s=-1,i=!1;for(let w=0;w<t.length;w++){let S=t[w];if(S.type==="ParameterExpansion"&&(S.parameter==="@"||S.parameter==="*")&&S.operation?.type==="Substring"){s=w,i=S.parameter==="*";break}}if(s===-1)return null;let o=t[s].operation,l=o.offset?await n(e,o.offset.expression):0,c=o.length?await n(e,o.length.expression):void 0,u=Number.parseInt(e.state.env.get("#")||"0",10),f=[];for(let w=1;w<=u;w++)f.push(e.state.env.get(String(w))||"");let d=e.state.env.get("0")||"bash",h;if(l<=0){let w=[d,...f],S=w.length+l;if(S<0)h=[];else{let A=l<0?S:0;if(c!==void 0){let v=c<0?w.length+c:A+c;h=w.slice(A,Math.max(A,v))}else h=w.slice(A)}}else{let w=l-1;if(w>=f.length)h=[];else if(c!==void 0){let S=c<0?f.length+c:w+c;h=f.slice(w,Math.max(w,S))}else h=f.slice(w)}let p="";for(let w=0;w<s;w++)p+=await r(e,t[w]);let m="";for(let w=s+1;w<t.length;w++)m+=await r(e,t[w]);let E=ve(e.state.env),b=Ce(e.state.env);if(h.length===0){let w=p+m;return w?b?{values:[w],quoted:!1}:{values:ue(w,E,e.limits.maxArrayElements),quoted:!1}:{values:[],quoted:!1}}let g;if(i){let w=Z(e.state.env),S=p+h.join(w)+m;b?g=S?[S]:[]:g=ue(S,E,e.limits.maxArrayElements)}else if(b)h.length===1?g=[p+h[0]+m]:g=[p+h[0],...h.slice(1,-1),h[h.length-1]+m];else{g=[];for(let w=0;w<h.length;w++){let S=h[w];if(w===0&&(S=p+S),w===h.length-1&&(S=S+m),S==="")g.push("");else{let A=ue(S,E,e.limits.maxArrayElements);De(g,A,e.limits.maxArrayElements,"unquoted expansion")}}}return{values:await qr(e,g),quoted:!1}}async function zl(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].parameter!=="@"&&t[0].parameter!=="*"||t[0].operation)return null;let n=t[0].parameter==="*",r=Number.parseInt(e.state.env.get("#")||"0",10);if(r===0)return{values:[],quoted:!1};let s=[];for(let c=1;c<=r;c++)s.push(e.state.env.get(String(c))||"");let i=ve(e.state.env),a=Ce(e.state.env),o=_r(e.state.env),l;if(n)if(a)l=s.filter(c=>c!=="");else{let c=Z(e.state.env),u=s.join(c);l=ue(u,i,e.limits.maxArrayElements)}else if(a)l=s.filter(c=>c!=="");else if(o){l=[];for(let c of s){if(c==="")continue;let u=ue(c,i,e.limits.maxArrayElements);De(l,u,e.limits.maxArrayElements,"unquoted expansion")}}else{l=[];for(let c of s)if(c==="")l.push("");else{let u=ue(c,i,e.limits.maxArrayElements);De(l,u,e.limits.maxArrayElements,"unquoted expansion")}for(;l.length>0&&l[l.length-1]==="";)l.pop()}return{values:await qr(e,l),quoted:!1}}async function ql(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation)return null;let n=t[0].parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!n)return null;let r=n[1],s=n[2]==="*",i=j(e,r),a;if(i.length===0){let f=e.state.env.get(r);if(f!==void 0)a=[f];else return{values:[],quoted:!1}}else a=i.map(([,f])=>f);let o=ve(e.state.env),l=Ce(e.state.env),c=_r(e.state.env),u;if(s)if(l)u=a.filter(f=>f!=="");else{let f=Z(e.state.env),d=a.join(f);u=ue(d,o,e.limits.maxArrayElements)}else if(l)u=a.filter(f=>f!=="");else if(c){u=[];for(let f of a){if(f==="")continue;let d=ue(f,o,e.limits.maxArrayElements);De(u,d,e.limits.maxArrayElements,"unquoted expansion")}}else{u=[];for(let f of a)if(f==="")u.push("");else{let d=ue(f,o,e.limits.maxArrayElements);De(u,d,e.limits.maxArrayElements,"unquoted expansion")}for(;u.length>0&&u[u.length-1]==="";)u.pop()}return{values:await qr(e,u),quoted:!1}}function Ul(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="VarNamePrefix")return null;let n=t[0].operation,r=bn(e,n.prefix);if(r.length===0)return{values:[],quoted:!1};let s=ve(e.state.env),i=Ce(e.state.env),a;if(n.star)if(i)a=r;else{let o=Z(e.state.env),l=r.join(o);a=ue(l,s,e.limits.maxArrayElements)}else if(i)a=r;else{a=[];for(let o of r){let l=ue(o,s,e.limits.maxArrayElements);De(a,l,e.limits.maxArrayElements,"unquoted expansion")}}return{values:a,quoted:!1}}function jl(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="ArrayKeys")return null;let n=t[0].operation,s=j(e,n.array).map(([l])=>String(l));if(s.length===0)return{values:[],quoted:!1};let i=ve(e.state.env),a=Ce(e.state.env),o;if(n.star)if(a)o=s;else{let l=Z(e.state.env),c=s.join(l);o=ue(c,i,e.limits.maxArrayElements)}else if(a)o=s;else{o=[];for(let l of s){let c=ue(l,i,e.limits.maxArrayElements);De(o,c,e.limits.maxArrayElements,"unquoted expansion")}}return{values:o,quoted:!1}}async function Gl(e,t,n){let r=-1;for(let d=0;d<t.length;d++){let h=t[d];if(h.type==="ParameterExpansion"&&(h.parameter==="@"||h.parameter==="*")&&!h.operation){r=d;break}}if(r===-1||t.length<=1)return null;let s=Number.parseInt(e.state.env.get("#")||"0",10),i=[];for(let d=1;d<=s;d++)i.push(e.state.env.get(String(d))||"");let a="";for(let d=0;d<r;d++)a+=await n(e,t[d]);let o="";for(let d=r+1;d<t.length;d++)o+=await n(e,t[d]);let l=ve(e.state.env),c=Ce(e.state.env),u=_r(e.state.env);if(s===0){let d=a+o;return{values:d?[d]:[],quoted:!1}}let f;{let d=[];for(let h=0;h<i.length;h++){let p=i[h];h===0&&(p=a+p),h===i.length-1&&(p=p+o),d.push(p)}if(c)f=d.filter(h=>h!=="");else if(u){f=[];for(let h of d){if(h==="")continue;let p=ue(h,l,e.limits.maxArrayElements);De(f,p,e.limits.maxArrayElements,"unquoted expansion")}}else{f=[];for(let h of d)if(h==="")f.push("");else{let p=ue(h,l,e.limits.maxArrayElements);De(f,p,e.limits.maxArrayElements,"unquoted expansion")}for(;f.length>0&&f[f.length-1]==="";)f.pop()}}return f.length===0?{values:[],quoted:!1}:{values:await qr(e,f),quoted:!1}}async function Ql(e,t,n){e.coverage?.hit("bash:expansion:word_glob");let r=t.parts,{hasQuoted:s,hasCommandSub:i,hasArrayVar:a,hasArrayAtExpansion:o,hasParamExpansion:l,hasVarNamePrefixExpansion:c,hasIndirection:u}=Zn(r),d=n.hasBraceExpansion(r)?await n.expandWordWithBracesAsync(e,t):null;if(d&&d.length>1)return dd(e,d,s);let h=await hd(e,r,o,c,u,n);if(h!==null)return h;let p=await md(e,r,n);if(p!==null)return p;let m=await yd(e,r,n);if(m!==null)return m;let E=await wd(e,r,n.expandPart);if(E!==null)return Hl(e,E);if((i||a||l)&&!Ce(e.state.env)){let g=ve(e.state.env),w=n.buildIfsCharClassPattern(g),S=await n.smartWordSplit(e,r,g,w,n.expandPart);return Hl(e,S)}let b=await n.expandWordAsync(e,t);return Ed(e,t,r,b,s,n.expandWordForGlobbing)}async function dd(e,t,n){let r=[];for(let s of t)if(!(!n&&s===""))if(!n&&!e.state.options.noglob&&wt(s,e.state.shoptOptions.extglob)){let i=await Ur(e,s);De(r,i,e.limits.maxArrayElements,"brace/glob expansion")}else r.push(s);return{values:r,quoted:!1}}async function hd(e,t,n,r,s,i){if(n){let a=Nl(e,t);if(a!==null)return a}{let a=Cl(e,t);if(a!==null)return a}{let a=await Al(e,t);if(a!==null)return a}{let a=await xl(e,t,n,i.expandPart,i.expandWordPartsAsync);if(a!==null)return a}{let a=await Pl(e,t,n,i.expandPart);if(a!==null)return a}{let a=await $l(e,t,i.evaluateArithmetic);if(a!==null)return a}{let a=kl(e,t);if(a!==null)return a}{let a=await Sl(e,t,i.expandWordPartsAsync,i.expandPart);if(a!==null)return a}{let a=await vl(e,t,i.expandWordPartsAsync,i.expandPart);if(a!==null)return a}if(r&&t.length===1&&t[0].type==="DoubleQuoted"){let a=pd(e,t);if(a!==null)return a}{let a=await Dl(e,t,s,i.expandParameterAsync,i.expandWordPartsAsync);if(a!==null)return a}{let a=await Rl(e,t);if(a!==null)return a}{let a=await Ol(e,t);if(a!==null)return a}return null}function pd(e,t){let n=t[0];if(n.type!=="DoubleQuoted")return null;if(n.parts.length===1&&n.parts[0].type==="ParameterExpansion"&&n.parts[0].operation?.type==="VarNamePrefix"){let r=n.parts[0].operation,s=bn(e,r.prefix);return r.star?{values:[s.join(Z(e.state.env))],quoted:!0}:{values:s,quoted:!0}}if(n.parts.length===1&&n.parts[0].type==="ParameterExpansion"&&n.parts[0].operation?.type==="ArrayKeys"){let r=n.parts[0].operation,i=j(e,r.array).map(([a])=>String(a));return r.star?{values:[i.join(Z(e.state.env))],quoted:!0}:{values:i,quoted:!0}}return null}async function md(e,t,n){{let r=await _l(e,t,n.evaluateArithmetic,n.expandPart);if(r!==null)return r}{let r=await Tl(e,t,n.expandPart,n.expandWordPartsAsync);if(r!==null)return r}{let r=await Ll(e,t,n.expandPart,n.expandWordPartsAsync);if(r!==null)return r}{let r=await Ml(e,t,n.expandPart);if(r!==null)return r}return null}async function yd(e,t,n){{let r=await Bl(e,t,n.expandWordPartsAsync,n.expandPart);if(r!==null)return r}{let r=await Wl(e,t,n.expandWordPartsAsync,n.expandPart);if(r!==null)return r}{let r=await Fl(e,t,n.expandWordPartsAsync,n.expandPart);if(r!==null)return r}{let r=await Vl(e,t,n.evaluateArithmetic,n.expandPart);if(r!==null)return r}{let r=await zl(e,t);if(r!==null)return r}{let r=await ql(e,t);if(r!==null)return r}{let r=Ul(e,t);if(r!==null)return r}{let r=jl(e,t);if(r!==null)return r}{let r=await Gl(e,t,n.expandPart);if(r!==null)return r}return null}function Zl(e){if(e.type!=="DoubleQuoted")return null;for(let t=0;t<e.parts.length;t++){let n=e.parts[t];if(n.type!=="ParameterExpansion"||n.operation)continue;let r=n.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(r)return{type:"array",name:r[1],atIndex:t,isStar:r[2]==="*"};if(n.parameter==="@"||n.parameter==="*")return{type:"positional",atIndex:t,isStar:n.parameter==="*"}}return null}async function gd(e,t,n,r){let s="";for(let o=0;o<n.atIndex;o++)s+=await r(e,t.parts[o]);let i="";for(let o=n.atIndex+1;o<t.parts.length;o++)i+=await r(e,t.parts[o]);let a;if(n.type==="array"){if(a=j(e,n.name).map(([,l])=>l),a.length===0){let l=e.state.env.get(n.name);l!==void 0&&(a=[l])}}else{let o=Number.parseInt(e.state.env.get("#")||"0",10);a=[];for(let l=1;l<=o;l++)a.push(e.state.env.get(String(l))||"")}if(n.isStar){let o=Z(e.state.env),l=a.join(o);return[s+l+i]}if(a.length===0){let o=s+i;return o?[o]:[]}return a.length===1?[s+a[0]+i]:[s+a[0],...a.slice(1,-1),a[a.length-1]+i]}async function wd(e,t,n){if(t.length<2)return null;let r=!1;for(let l of t)if(Zl(l)){r=!0;break}if(!r)return null;let s=ve(e.state.env),i=Ce(e.state.env),a=[];for(let l of t){let c=Zl(l);if(c&&l.type==="DoubleQuoted"){let u=await gd(e,l,c,n);a.push(u)}else if(l.type==="DoubleQuoted"||l.type==="SingleQuoted"){let u=await n(e,l);a.push([u])}else if(l.type==="Literal")a.push([l.value]);else if(l.type==="ParameterExpansion"){let u=await n(e,l);if(i)a.push(u?[u]:[]);else{let f=ue(u,s,e.limits.maxArrayElements);a.push(f)}}else{let u=await n(e,l);if(i)a.push(u?[u]:[]);else{let f=ue(u,s,e.limits.maxArrayElements);a.push(f)}}}let o=[];for(let l of a)if(l.length!==0)if(o.length===0)De(o,l,e.limits.maxArrayElements,"word expansion");else{let c=o.length-1;o[c]=o[c]+l[0];for(let u=1;u<l.length;u++)o.push(l[u])}return o}async function Hl(e,t){if(e.state.options.noglob)return{values:t,quoted:!1};let n=[];for(let r of t)if(wt(r,e.state.shoptOptions.extglob)){let s=await Ur(e,r);De(n,s,e.limits.maxArrayElements,"glob expansion")}else n.push(r);return{values:n,quoted:!1}}async function Ur(e,t){let n=new Vt(e.fs,e.state.cwd,e.state.env,{globstar:e.state.shoptOptions.globstar,nullglob:e.state.shoptOptions.nullglob,failglob:e.state.shoptOptions.failglob,dotglob:e.state.shoptOptions.dotglob,extglob:e.state.shoptOptions.extglob,globskipdots:e.state.shoptOptions.globskipdots,maxGlobOperations:e.limits.maxGlobOperations,consumeOperation:()=>e.executionScope.consumeLimited("glob_operations",1,e.limits.maxGlobOperations,"glob expansion")}),r=await n.expand(t);if(r.length>0)return r;if(n.hasFailglob())throw new Rt(t);return n.hasNullglob()?[]:[t]}async function Ed(e,t,n,r,s,i){let a=n.some(o=>o.type==="Glob");if(!e.state.options.noglob&&a){let o=await i(e,t);if(wt(o,e.state.shoptOptions.extglob)){let c=await Ur(e,o);if(c.length>0&&c[0]!==o)return{values:c,quoted:!1};if(c.length===0)return{values:[],quoted:!1}}let l=bi(r);if(!Ce(e.state.env)){let c=ve(e.state.env);return{values:ue(l,c,e.limits.maxArrayElements),quoted:!1}}return{values:[l],quoted:!1}}if(!s&&!e.state.options.noglob&&wt(r,e.state.shoptOptions.extglob)){let o=await i(e,t);if(wt(o,e.state.shoptOptions.extglob)){let l=await Ur(e,o);if(l.length>0&&l[0]!==o)return{values:l,quoted:!1}}}if(r===""&&!s)return{values:[],quoted:!1};if(a&&!s){let o=bi(r);if(!Ce(e.state.env)){let l=ve(e.state.env);return{values:ue(o,l,e.limits.maxArrayElements),quoted:!1}}return{values:[o],quoted:!1}}return{values:[r],quoted:s}}function Oe(e,t,n){if(t.length>=e.limits.maxArrayElements)throw new P(`word splitting element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");t.push(n)}async function Xl(e,t){let n=t.operation;if(!n||n.type!=="DefaultValue"&&n.type!=="AssignDefault"&&n.type!=="UseAlternative")return null;let r=n.word;if(!r||r.parts.length===0)return null;let s=await gt(e,t.parameter),a=await ie(e,t.parameter,!1)==="",o=n.checkEmpty??!1,l;return n.type==="UseAlternative"?l=s&&!(o&&a):l=!s||o&&a,l?r.parts:null}function bd(e){return e.type==="SingleQuoted"?!0:e.type==="DoubleQuoted"?e.parts.every(n=>n.type==="Literal"):!1}async function Sd(e,t){if(t.type!=="ParameterExpansion")return null;let n=await Xl(e,t);if(!n||n.length<=1)return null;let r=n.some(i=>bd(i)),s=n.some(i=>i.type==="Literal"||i.type==="ParameterExpansion"||i.type==="CommandSubstitution"||i.type==="ArithmeticExpansion");return r&&s?n:null}function vd(e){return e.type==="DoubleQuoted"||e.type==="SingleQuoted"||e.type==="Literal"?!1:e.type==="Glob"?di(e.pattern):!(!(e.type==="ParameterExpansion"||e.type==="CommandSubstitution"||e.type==="ArithmeticExpansion")||e.type==="ParameterExpansion"&&Ho(e))}async function Yl(e,t,n,r,s){if(e.coverage?.hit("bash:expansion:word_split"),t.length===1&&t[0].type==="ParameterExpansion"){let d=t[0],h=await Xl(e,d);if(h&&h.length>0&&h.length>1&&h.some(m=>m.type==="DoubleQuoted"||m.type==="SingleQuoted")&&h.some(m=>m.type==="Literal"||m.type==="ParameterExpansion"||m.type==="CommandSubstitution"||m.type==="ArithmeticExpansion"))return Kl(e,h,n,r,s)}let i=[],a=!1;for(let d of t){let h=vd(d),p=d.type==="DoubleQuoted"||d.type==="SingleQuoted",m=h?await Sd(e,d):null,E=await s(e,d);i.push({value:E,isSplittable:h,isQuoted:p,mixedDefaultParts:m??void 0}),h&&(a=!0)}if(!a){let d=i.map(h=>h.value).join("");return d?[d]:[]}let o=[],l="",c=!1,u=!1,f=!1;for(let d of i)if(!d.isSplittable)u?d.isQuoted&&d.value===""?(l!==""&&Oe(e,o,l),Oe(e,o,""),c=!0,l="",u=!1,f=!0):d.value!==""?(l!==""&&Oe(e,o,l),l=d.value,u=!1,f=!1):(l+=d.value,f=!1):(l+=d.value,f=d.isQuoted&&d.value==="");else if(d.mixedDefaultParts){let h=await Kl(e,d.mixedDefaultParts,n,r,s);if(h.length!==0)if(h.length===1)l+=h[0],c=!0;else{l+=h[0],Oe(e,o,l),c=!0;for(let p=1;p<h.length-1;p++)Oe(e,o,h[p]);l=h[h.length-1]}u=!1,f=!1}else{let{words:h,hadLeadingDelimiter:p,hadTrailingDelimiter:m}=Tr(d.value,n,e.limits.maxArrayElements);if(f&&p&&l===""&&(Oe(e,o,""),c=!0),h.length===0)m&&(u=!0);else if(h.length===1)l+=h[0],c=!0,u=m;else{l+=h[0],Oe(e,o,l),c=!0;for(let E=1;E<h.length-1;E++)Oe(e,o,h[E]);l=h[h.length-1],u=m}f=!1}return l!==""?Oe(e,o,l):o.length===0&&c&&Oe(e,o,""),o}function Ad(e,t){return e.length>0&&t.includes(e[0])}async function Kl(e,t,n,r,s){let i=[];for(let u of t){let d=!(u.type==="DoubleQuoted"||u.type==="SingleQuoted"),h=await s(e,u);i.push({value:h,isSplittable:d})}let a=[],o="",l=!1,c=!1;for(let u of i)if(!u.isSplittable)c&&u.value!==""?(o!==""&&Oe(e,a,o),o=u.value,c=!1):o+=u.value;else{Ad(u.value,n)&&o!==""&&(Oe(e,a,o),o="",l=!0);let{words:d,hadTrailingDelimiter:h}=Tr(u.value,n,e.limits.maxArrayElements);if(d.length===0)h&&(c=!0);else if(d.length===1)o+=d[0],l=!0,c=h;else{o+=d[0],Oe(e,a,o),l=!0;for(let p=1;p<d.length-1;p++)Oe(e,a,d[p]);o=d[d.length-1],c=h}}return o!==""?Oe(e,a,o):a.length===0&&l&&Oe(e,a,""),a}function Jl(e){switch(e.type){case"Literal":return e.value;case"SingleQuoted":return e.value;case"Escaped":return e.value;default:return null}}function ec(e){switch(e.type){case"SingleQuoted":case"Escaped":case"DoubleQuoted":return!0;case"Literal":return e.value==="";default:return!1}}function jt(e,t,n){if(e.length>t)throw new P(`${n}: string length limit exceeded (${t} bytes)`,"string_length")}async function ct(e,t,n=!1){let r=[];for(let s of t)r.push(await Ye(e,s,n));return r.join("")}function xd(e){return ec(e)}function nc(e){if(e.parts.length===0)return!0;for(let t of e.parts)if(!xd(t))return!1;return!0}function Pd(e,t,n=!1){let r=Jl(t);if(r!==null)return r;switch(t.type){case"TildeExpansion":return n?t.user===null?"~":`~${t.user}`:(e.coverage?.hit("bash:expansion:tilde"),t.user===null?e.state.env.get("HOME")??"/home/user":t.user==="root"?"/root":`~${t.user}`);case"Glob":return Si(e,t.pattern);default:return null}}async function z(e,t){return Pi(e,t)}async function rc(e,t){let n=[];for(let r of t.parts)if(r.type==="Escaped")n.push(`\\${r.value}`);else if(r.type==="SingleQuoted")n.push(r.value);else if(r.type==="DoubleQuoted"){let s=await ct(e,r.parts);n.push(s)}else if(r.type==="TildeExpansion"){let s=await Ye(e,r);n.push(Qn(s))}else n.push(await Ye(e,r));return n.join("")}async function sc(e,t){let n=[];for(let r of t.parts)if(r.type==="Escaped"){let s=r.value;"()|*?[]".includes(s)?n.push(`\\${s}`):n.push(s)}else if(r.type==="SingleQuoted")n.push(Xe(r.value));else if(r.type==="DoubleQuoted"){let s=await ct(e,r.parts);n.push(Xe(s))}else n.push(await Ye(e,r));return n.join("")}async function ic(e,t){let n=[];for(let r of t.parts)if(r.type==="SingleQuoted")n.push(Xe(r.value));else if(r.type==="Escaped"){let s=r.value;"*?[]\\()|".includes(s)?n.push(`\\${s}`):n.push(s)}else if(r.type==="DoubleQuoted"){let s=await ct(e,r.parts);n.push(Xe(s))}else r.type==="Glob"?wl(r.pattern)?n.push(await bl(e,r.pattern)):n.push(Si(e,r.pattern)):r.type==="Literal"?n.push(r.value):n.push(await Ye(e,r));return n.join("")}function Gr(e){for(let t of e)if(t.type==="BraceExpansion"||t.type==="DoubleQuoted"&&Gr(t.parts))return!0;return!1}var tc=1e5;async function ac(e,t,n={count:0}){let r=()=>{n.count++,e.executionScope.consumeLimited("brace_operations",1,Math.min(tc,e.limits.maxBraceExpansionResults),"brace expansion")},s=(a,o)=>{if(a.length>=e.limits.maxBraceExpansionResults)throw new P(`brace expansion result limit exceeded (${e.limits.maxBraceExpansionResults})`,"array_elements");r(),a.push(o)},i=[[]];for(let a of t)if(a.type==="BraceExpansion"){let o=[],l=!1,c="";for(let d of a.items)if(d.type==="Range"){let h=Ei(d.start,d.end,d.step,d.startStr,d.endStr,{maxResults:e.limits.maxBraceExpansionResults,maxStringBytes:e.limits.maxStringLength});if(h.expanded)for(let p of h.expanded)s(o,p);else{l=!0,c=h.literal;break}}else{let h=await ac(e,d.word.parts,n);for(let p of h){let m=[];for(let E of p)typeof E=="string"?m.push(E):m.push(await Ye(e,E));s(o,m.join(""))}}if(l){for(let d of i)r(),d.push(c);continue}if(i.length*o.length>e.limits.maxBraceExpansionResults||n.count>tc)throw new P(`brace expansion result limit exceeded (${e.limits.maxBraceExpansionResults})`,"array_elements");let f=[];for(let d of i)for(let h of o){if(f.length>=e.limits.maxBraceExpansionResults)throw new P(`brace expansion result limit exceeded (${e.limits.maxBraceExpansionResults})`,"array_elements");r(),f.push([...d,h])}i=f}else for(let o of i)r(),o.push(a);return i}async function oc(e,t){let n=t.parts;if(!Gr(n))return[await z(e,t)];let r=await ac(e,n),s=[];for(let i of r){let a=[];for(let o of i)typeof o=="string"?a.push(o):a.push(await Ye(e,o));s.push(vi(e,a.join("")))}return s}function $d(){return{expandWordAsync:Pi,expandWordForGlobbing:ic,expandWordWithBracesAsync:oc,expandWordPartsAsync:ct,expandPart:Ye,expandParameterAsync:jr,hasBraceExpansion:Gr,evaluateArithmetic:K,buildIfsCharClassPattern:Qo,smartWordSplit:Yl}}async function ut(e,t){return Ql(e,t,$d())}function kd(e){for(let t of e){if(t.type==="ParameterExpansion")return t.parameter;if(t.type==="Literal")return t.value}return""}function Xn(e,t){if(Number.parseInt(e.state.env.get("#")||"0",10)<2)return!1;function r(s){for(let i of s)if(i.type==="DoubleQuoted"){for(let a of i.parts)if(a.type==="ParameterExpansion"&&a.parameter==="@"&&!a.operation)return!0}return!1}return r(t.parts)}async function Zr(e,t){if(Xn(e,t))return{error:`bash: $@: ambiguous redirect
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
63
|
+
`);)d=!0,f++;if(d&&f<r&&n[f]===")"||l)return!0}if(i===0)return!1;s++;continue}s++}return!1}dparenClosesWithSpacedParens(t){let n=this.input,r=n.length,s=t,i=2,o=!1,a=!1;for(;s<r&&i>0;){let l=n[s];if(o){l==="'"&&(o=!1),s++;continue}if(a){if(l==="\\"){s+=2;continue}l==='"'&&(a=!1),s++;continue}if(l==="'"){o=!0,s++;continue}if(l==='"'){a=!0,s++;continue}if(l==="\\"){s+=2;continue}if(l==="("){i++,s++;continue}if(l===")"){if(i--,i===1){let c=s+1;if(c<r&&n[c]===")")return!1;let u=c,f=!1;for(;u<r&&(n[u]===" "||n[u]===" "||n[u]===`
|
|
64
|
+
`);)f=!0,u++;if(f&&u<r&&n[u]===")")return!0}if(i===0)return!1;s++;continue}if(i===1&&(l==="|"&&s+1<r&&n[s+1]==="|"||l==="&"&&s+1<r&&n[s+1]==="&"||l==="|"&&s+1<r&&n[s+1]!=="|"))return!0;s++}return!1}};var ci=1e6,ir=1e5,pd=1e6,za=200,Ne;(function(e){e[e.Default=0]="Default",e[e.Assignment=1]="Assignment",e[e.NoBraceExpansion=2]="NoBraceExpansion",e[e.Regex=4]="Regex"})(Ne||(Ne={}));var Ua=new Set([w.LESS,w.GREAT,w.DLESS,w.DGREAT,w.LESSAND,w.GREATAND,w.LESSGREAT,w.DLESSDASH,w.CLOBBER,w.TLESS,w.AND_GREAT,w.AND_DGREAT]),qa=new Set([w.LESS,w.GREAT,w.DLESS,w.DGREAT,w.LESSAND,w.GREATAND,w.LESSGREAT,w.DLESSDASH,w.CLOBBER,w.TLESS]),ja=new Set([w.LESS,w.GREAT,w.DLESS,w.DGREAT,w.LESSAND,w.GREATAND,w.LESSGREAT,w.DLESSDASH,w.CLOBBER,w.TLESS,w.AND_GREAT,w.AND_DGREAT]),xe=class extends Error{line;column;token;constructor(t,n,r,s=void 0){super(`Parse error at ${n}:${r}: ${t}`),this.line=n,this.column=r,this.token=s,this.name="ParseException"}},zr=class{iterations=0;tokens=0;depth=0;reset(){this.iterations=0,this.tokens=0,this.depth=0}chargeIteration(t,n){if(this.iterations++,this.iterations>pd)throw new xe("Maximum parse iterations exceeded (possible infinite loop)",t,n)}chargeTokens(t,n=1,r=1){if(this.tokens+=t,this.tokens>ir)throw new xe(`Too many tokens: cumulative count exceeds limit of ${ir}`,n,r)}enter(t,n){if(this.depth++,this.depth>za)throw this.depth--,new xe(`Maximum parser nesting depth exceeded (${za})`,t,n);let r=!0;return()=>{r&&(r=!1,this.depth--)}}};function ye(e,t){for(;t<e.length;){if(e[t]==="\\"&&e[t+1]===`
|
|
65
|
+
`){t+=2;continue}if(/\s/.test(e[t])){t++;continue}break}return t}var Ur=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];function or(e){if(e.includes("#")){let n=e.split("#");if(n.length!==2)return Number.NaN;let[r,s]=n;if(!/^\d+$/.test(r)||s.length===0)return Number.NaN;let i=Number.parseInt(r,10);if(i<2||i>64)return Number.NaN;let o=0;for(let a of s){let l;if(/[0-9]/.test(a))l=a.charCodeAt(0)-48;else if(/[a-z]/.test(a))l=a.charCodeAt(0)-97+10;else if(/[A-Z]/.test(a))l=a.charCodeAt(0)-65+(i<=36?10:36);else if(a==="@")l=62;else if(a==="_")l=63;else return Number.NaN;if(l>=i)return Number.NaN;if(o=o*i+l,o>Number.MAX_SAFE_INTEGER)return Number.MAX_SAFE_INTEGER}return o}if(e.startsWith("0x")||e.startsWith("0X")){let n=Number.parseInt(e.slice(2),16);return n>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:n}if(e.startsWith("0")&&e.length>1&&/^[0-9]+$/.test(e)){if(/[89]/.test(e))return Number.NaN;let n=Number.parseInt(e,8);return n>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:n}let t=Number.parseInt(e,10);return t>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:t}function Ga(e,t,n,r){if(n.slice(r,r+3)!=="$((")return null;let s=r+3,i=1,o=s;for(;s<n.length-1&&i>0;)n[s]==="("&&n[s+1]==="("?(i++,s+=2):n[s]===")"&&n[s+1]===")"?(i--,i>0&&(s+=2)):s++;let a=n.slice(o,s),{expr:l}=e(t,a,0);return s+=2,{expr:{type:"ArithNested",expression:l},pos:s}}function Za(e,t){if(e.slice(t,t+2)!=="$'")return null;let n=t+2,r="";for(;n<e.length&&e[n]!=="'";)if(e[n]==="\\"&&n+1<e.length){let i=e[n+1];switch(i){case"n":r+=`
|
|
66
|
+
`;break;case"t":r+=" ";break;case"r":r+="\r";break;case"\\":r+="\\";break;case"'":r+="'";break;default:r+=i}n+=2}else r+=e[n],n++;e[n]==="'"&&n++;let s=Number.parseInt(r,10);return{expr:{type:"ArithNumber",value:Number.isNaN(s)?0:s},pos:n}}function Ha(e,t){if(e.slice(t,t+2)!=='$"')return null;let n=t+2,r="";for(;n<e.length&&e[n]!=='"';)e[n]==="\\"&&n+1<e.length?(r+=e[n+1],n+=2):(r+=e[n],n++);e[n]==='"'&&n++;let s=Number.parseInt(r,10);return{expr:{type:"ArithNumber",value:Number.isNaN(s)?0:s},pos:n}}function hd(e){let t="",n=0;for(;n<e.length;)if(e[n]==='"'){for(n++;n<e.length&&e[n]!=='"';)e[n]==="\\"&&n+1<e.length?(t+=e[n+1],n+=2):(t+=e[n],n++);n<e.length&&n++}else t+=e[n],n++;return t}function re(e,t){let n=hd(t),{expr:r,pos:s}=On(e,n,0),i=ye(n,s);if(i<n.length){let o=t.slice(i).trim();if(o)return{type:"ArithmeticExpression",originalText:t,expression:{type:"ArithSyntaxError",errorToken:o,message:`${o}: syntax error: invalid arithmetic operator (error token is "${o}")`}}}return{type:"ArithmeticExpression",expression:r,originalText:t}}function qe(e,t){return{expr:{type:"ArithSyntaxError",errorToken:e,message:`syntax error: operand expected (error token is "${e}")`},pos:t}}function je(e,t){return ye(e,t)>=e.length}function On(e,t,n){return md(e,t,n)}function hn(e,t,n){return e.withDepth(()=>On(e,t,n))}function md(e,t,n){let{expr:r,pos:s}=ar(e,t,n);for(s=ye(t,s);t[s]===",";){if(s++,je(t,s))return qe(",",s);let{expr:o,pos:a}=ar(e,t,s);r={type:"ArithBinary",operator:",",left:r,right:o},s=ye(t,a)}return{expr:r,pos:s}}function ar(e,t,n){let{expr:r,pos:s}=yd(e,t,n);if(s=ye(t,s),t[s]==="?"){s++;let{expr:i,pos:o}=hn(e,t,s);if(s=ye(t,o),t[s]===":"){s++;let{expr:a,pos:l}=hn(e,t,s);return{expr:{type:"ArithTernary",condition:r,consequent:i,alternate:a},pos:l}}}return{expr:r,pos:s}}function yd(e,t,n){let{expr:r,pos:s}=Qa(e,t,n);for(;s=ye(t,s),t.slice(s,s+2)==="||";){if(s+=2,je(t,s))return qe("||",s);let{expr:o,pos:a}=Qa(e,t,s);r={type:"ArithBinary",operator:"||",left:r,right:o},s=a}return{expr:r,pos:s}}function Qa(e,t,n){let{expr:r,pos:s}=Ka(e,t,n);for(;s=ye(t,s),t.slice(s,s+2)==="&&";){if(s+=2,je(t,s))return qe("&&",s);let{expr:o,pos:a}=Ka(e,t,s);r={type:"ArithBinary",operator:"&&",left:r,right:o},s=a}return{expr:r,pos:s}}function Ka(e,t,n){let{expr:r,pos:s}=Xa(e,t,n);for(;s=ye(t,s),t[s]==="|"&&t[s+1]!=="|";){if(s++,je(t,s))return qe("|",s);let{expr:o,pos:a}=Xa(e,t,s);r={type:"ArithBinary",operator:"|",left:r,right:o},s=a}return{expr:r,pos:s}}function Xa(e,t,n){let{expr:r,pos:s}=Ya(e,t,n);for(;s=ye(t,s),t[s]==="^";){if(s++,je(t,s))return qe("^",s);let{expr:o,pos:a}=Ya(e,t,s);r={type:"ArithBinary",operator:"^",left:r,right:o},s=a}return{expr:r,pos:s}}function Ya(e,t,n){let{expr:r,pos:s}=Ja(e,t,n);for(;s=ye(t,s),t[s]==="&"&&t[s+1]!=="&";){if(s++,je(t,s))return qe("&",s);let{expr:o,pos:a}=Ja(e,t,s);r={type:"ArithBinary",operator:"&",left:r,right:o},s=a}return{expr:r,pos:s}}function Ja(e,t,n){let{expr:r,pos:s}=el(e,t,n);for(;s=ye(t,s),t.slice(s,s+2)==="=="||t.slice(s,s+2)==="!=";){let i=t.slice(s,s+2);if(s+=2,je(t,s))return qe(i,s);let{expr:o,pos:a}=el(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}return{expr:r,pos:s}}function el(e,t,n){let{expr:r,pos:s}=ui(e,t,n);for(;;)if(s=ye(t,s),t.slice(s,s+2)==="<="||t.slice(s,s+2)===">="){let i=t.slice(s,s+2);if(s+=2,je(t,s))return qe(i,s);let{expr:o,pos:a}=ui(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}else if(t[s]==="<"||t[s]===">"){let i=t[s];if(s++,je(t,s))return qe(i,s);let{expr:o,pos:a}=ui(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}else break;return{expr:r,pos:s}}function ui(e,t,n){let{expr:r,pos:s}=tl(e,t,n);for(;s=ye(t,s),t.slice(s,s+2)==="<<"||t.slice(s,s+2)===">>";){let i=t.slice(s,s+2);if(s+=2,je(t,s))return qe(i,s);let{expr:o,pos:a}=tl(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}return{expr:r,pos:s}}function tl(e,t,n){let{expr:r,pos:s}=nl(e,t,n);for(;s=ye(t,s),(t[s]==="+"||t[s]==="-")&&t[s+1]!==t[s];){let i=t[s];if(s++,je(t,s))return qe(i,s);let{expr:o,pos:a}=nl(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}return{expr:r,pos:s}}function nl(e,t,n){let{expr:r,pos:s}=qr(e,t,n);for(;;)if(s=ye(t,s),t[s]==="*"&&t[s+1]!=="*"){if(s++,je(t,s))return qe("*",s);let{expr:o,pos:a}=qr(e,t,s);r={type:"ArithBinary",operator:"*",left:r,right:o},s=a}else if(t[s]==="/"||t[s]==="%"){let i=t[s];if(s++,je(t,s))return qe(i,s);let{expr:o,pos:a}=qr(e,t,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}else break;return{expr:r,pos:s}}function qr(e,t,n){let{expr:r,pos:s}=fi(e,t,n),i=ye(t,s);if(t.slice(i,i+2)==="**"){if(i+=2,je(t,i))return qe("**",i);let{expr:a,pos:l}=e.withDepth(()=>qr(e,t,i));return{expr:{type:"ArithBinary",operator:"**",left:r,right:a},pos:l}}return{expr:r,pos:s}}function fi(e,t,n){let r=ye(t,n);if(t.slice(r,r+2)==="++"||t.slice(r,r+2)==="--"){let s=t.slice(r,r+2);r+=2;let{expr:i,pos:o}=e.withDepth(()=>fi(e,t,r));return{expr:{type:"ArithUnary",operator:s,operand:i,prefix:!0},pos:o}}if(t[r]==="+"||t[r]==="-"||t[r]==="!"||t[r]==="~"){let s=t[r];r++;let{expr:i,pos:o}=e.withDepth(()=>fi(e,t,r));return{expr:{type:"ArithUnary",operator:s,operand:i,prefix:!0},pos:o}}return wd(e,t,r)}function gd(e,t){let n=e[t];return n==="$"||n==="`"}function wd(e,t,n){let{expr:r,pos:s}=rl(e,t,n,!1),i=[r];for(;gd(t,s);){let{expr:a,pos:l}=rl(e,t,s,!0);i.push(a),s=l}i.length>1&&(r={type:"ArithConcat",parts:i});let o;if(t[s]==="["&&r.type==="ArithConcat"){s++;let{expr:a,pos:l}=hn(e,t,s);o=a,s=l,t[s]==="]"&&s++}if(o&&r.type==="ArithConcat"&&(r={type:"ArithDynamicElement",nameExpr:r,subscript:o},o=void 0),s=ye(t,s),r.type==="ArithConcat"||r.type==="ArithVariable"||r.type==="ArithDynamicElement"){for(let a of Ur)if(t.slice(s,s+a.length)===a&&t.slice(s,s+a.length+1)!=="=="){s+=a.length;let{expr:l,pos:c}=e.withDepth(()=>ar(e,t,s));return r.type==="ArithDynamicElement"?{expr:{type:"ArithDynamicAssignment",operator:a,target:r.nameExpr,subscript:r.subscript,value:l},pos:c}:r.type==="ArithConcat"?{expr:{type:"ArithDynamicAssignment",operator:a,target:r,value:l},pos:c}:{expr:{type:"ArithAssignment",operator:a,variable:r.name,value:l},pos:c}}}if(t.slice(s,s+2)==="++"||t.slice(s,s+2)==="--"){let a=t.slice(s,s+2);return s+=2,{expr:{type:"ArithUnary",operator:a,operand:r,prefix:!1},pos:s}}return{expr:r,pos:s}}function rl(e,t,n,r=!1){let s=ye(t,n),i=Ga(hn,e,t,s);if(i)return i;let o=Za(t,s);if(o)return o;let a=Ha(t,s);if(a)return a;if(t.slice(s,s+2)==="$("&&t[s+2]!=="("){s+=2;let c=1,u=s;for(;s<t.length&&c>0;)t[s]==="("?c++:t[s]===")"&&c--,c>0&&s++;let f=t.slice(u,s);return s++,{expr:{type:"ArithCommandSubst",command:f},pos:s}}if(t[s]==="`"){s++;let c=s;for(;s<t.length&&t[s]!=="`";)s++;let u=t.slice(c,s);return t[s]==="`"&&s++,{expr:{type:"ArithCommandSubst",command:u},pos:s}}if(t[s]==="("){s++;let{expr:c,pos:u}=hn(e,t,s);return s=ye(t,u),t[s]===")"&&s++,{expr:{type:"ArithGroup",expression:c},pos:s}}if(t[s]==="'"){s++;let c="";for(;s<t.length&&t[s]!=="'";)c+=t[s],s++;t[s]==="'"&&s++;let u=Number.parseInt(c,10);return{expr:{type:"ArithSingleQuote",content:c,value:Number.isNaN(u)?0:u},pos:s}}if(t[s]==='"'){s++;let c="";for(;s<t.length&&t[s]!=='"';)t[s]==="\\"&&s+1<t.length?(c+=t[s+1],s+=2):(c+=t[s],s++);t[s]==='"'&&s++;let u=c.trim();if(!u)return{expr:{type:"ArithNumber",value:0},pos:s};let{expr:f}=hn(e,u,0);return{expr:f,pos:s}}if(/[0-9]/.test(t[s])){let c="",u=!1,f=!1;for(;s<t.length;){let p=t[s];if(u)if(/[0-9a-zA-Z@_]/.test(p))c+=p,s++;else break;else if(p==="#")u=!0,c+=p,s++;else if(c==="0"&&(p==="x"||p==="X")&&s+1<t.length&&/[0-9a-fA-F]/.test(t[s+1]))f=!0,c+=p,s++;else if(f&&/[0-9a-fA-F]/.test(p))c+=p,s++;else if(!f&&/[0-9]/.test(p))c+=p,s++;else break}if(s<t.length&&/[a-zA-Z_]/.test(t[s])){let p=c;for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)p+=t[s],s++;return{expr:{type:"ArithSyntaxError",errorToken:p,message:`${p}: value too great for base (error token is "${p}")`},pos:s}}if(t[s]==="."&&/[0-9]/.test(t[s+1]))throw new ce(`${c}.${t[s+1]}...: syntax error: invalid arithmetic operator`);if(t[s]==="["){let p=t.slice(s).trim();return{expr:{type:"ArithNumberSubscript",number:c,errorToken:p},pos:t.length}}return{expr:{type:"ArithNumber",value:or(c)},pos:s}}if(t[s]==="$"&&t[s+1]==="{"){let c=s+2,u=1,f=c;for(;f<t.length&&u>0;)t[f]==="{"?u++:t[f]==="}"&&u--,u>0&&f++;let d=t.slice(c,f),p=f+1;if(t[p]==="#"){let h=p+1;for(;h<t.length&&/[0-9a-zA-Z@_]/.test(t[h]);)h++;let m=t.slice(p+1,h);return{expr:{type:"ArithDynamicBase",baseExpr:d,value:m},pos:h}}if(/[0-9]/.test(t[p])||t[p]==="x"||t[p]==="X"){let h=p;if(t[p]==="x"||t[p]==="X")for(h++;h<t.length&&/[0-9a-fA-F]/.test(t[h]);)h++;else for(;h<t.length&&/[0-9]/.test(t[h]);)h++;let m=t.slice(p,h);return{expr:{type:"ArithDynamicNumber",prefix:d,suffix:m},pos:h}}return s=p,{expr:{type:"ArithBracedExpansion",content:d},pos:s}}if(t[s]==="$"&&s+1<t.length&&/[0-9]/.test(t[s+1])){s++;let c="";for(;s<t.length&&/[0-9]/.test(t[s]);)c+=t[s],s++;return{expr:{type:"ArithVariable",name:c,hasDollarPrefix:!0},pos:s}}if(t[s]==="$"&&s+1<t.length&&/[*@#?\-!$]/.test(t[s+1])){let c=t[s+1];return s+=2,{expr:{type:"ArithSpecialVar",name:c},pos:s}}let l=!1;if(t[s]==="$"&&s+1<t.length&&/[a-zA-Z_]/.test(t[s+1])&&(l=!0,s++),s<t.length&&/[a-zA-Z_]/.test(t[s])){let c="";for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)c+=t[s],s++;if(t[s]==="["&&!r){s++;let u;if(t[s]==="'"||t[s]==='"'){let d=t[s];for(s++,u="";s<t.length&&t[s]!==d;)u+=t[s],s++;t[s]===d&&s++,s=ye(t,s),t[s]==="]"&&s++}let f;if(u===void 0){let{expr:d,pos:p}=hn(e,t,s);f=d,s=p,t[s]==="]"&&s++}if(s=ye(t,s),t[s]==="["&&f)return{expr:{type:"ArithDoubleSubscript",array:c,index:f},pos:s};if(!r){for(let d of Ur)if(t.slice(s,s+d.length)===d&&t.slice(s,s+d.length+1)!=="=="){s+=d.length;let{expr:p,pos:h}=e.withDepth(()=>ar(e,t,s));return{expr:{type:"ArithAssignment",operator:d,variable:c,subscript:f,stringKey:u,value:p},pos:h}}}return{expr:{type:"ArithArrayElement",array:c,index:f,stringKey:u},pos:s}}if(s=ye(t,s),!r){for(let u of Ur)if(t.slice(s,s+u.length)===u&&t.slice(s,s+u.length+1)!=="=="){s+=u.length;let{expr:f,pos:d}=e.withDepth(()=>ar(e,t,s));return{expr:{type:"ArithAssignment",operator:u,variable:c,value:f},pos:d}}}return{expr:{type:"ArithVariable",name:c,hasDollarPrefix:l},pos:s}}if(t[s]==="#"){let c=s+1;for(;c<t.length&&t[c]!==`
|
|
67
|
+
`;)c++;let u=t.slice(s,c).trim()||"#";return{expr:{type:"ArithSyntaxError",errorToken:u,message:`${u}: syntax error: invalid arithmetic operator (error token is "${u}")`},pos:t.length}}return{expr:{type:"ArithNumber",value:0},pos:s}}var jr=e=>{let t,n="";for(let r=0;r<e.length;r++){let s=e[r];if(s==="\\"&&t==='"'&&r+1<e.length){n+=s+e[r+1],r+=1;continue}if(s==="'"||s==='"'){t===s?t=void 0:t||(t=s),n+=s;continue}if(s==="\\"&&!t&&r+1<e.length){let i=e[r+1];n+=i==="$"||i==="`"?`\\${i}`:i,r+=1;continue}n+=s}return n};function Ed(e){let t="",n=0;for(;n<e.length;){let r=e[n];if(r<128){t+=String.fromCharCode(r),n++;continue}if((r&224)===192){if(n+1<e.length&&(e[n+1]&192)===128&&r>=194){let s=(r&31)<<6|e[n+1]&63;t+=String.fromCharCode(s),n+=2;continue}t+=String.fromCharCode(r),n++;continue}if((r&240)===224){if(n+2<e.length&&(e[n+1]&192)===128&&(e[n+2]&192)===128){if(r===224&&e[n+1]<160){t+=String.fromCharCode(r),n++;continue}let s=(r&15)<<12|(e[n+1]&63)<<6|e[n+2]&63;if(s>=55296&&s<=57343){t+=String.fromCharCode(r),n++;continue}t+=String.fromCharCode(s),n+=3;continue}t+=String.fromCharCode(r),n++;continue}if((r&248)===240&&r<=244){if(n+3<e.length&&(e[n+1]&192)===128&&(e[n+2]&192)===128&&(e[n+3]&192)===128){if(r===240&&e[n+1]<144){t+=String.fromCharCode(r),n++;continue}let s=(r&7)<<18|(e[n+1]&63)<<12|(e[n+2]&63)<<6|e[n+3]&63;if(s>1114111){t+=String.fromCharCode(r),n++;continue}t+=String.fromCodePoint(s),n+=4;continue}t+=String.fromCharCode(r),n++;continue}t+=String.fromCharCode(r),n++}return t}function ol(e,t,n){let r=n+1;for(;r<t.length&&/[a-zA-Z0-9_-]/.test(t[r]);)r++;return r}function di(e,t,n,r,s){let i=1,o=n+1;for(;o<t.length&&i>0;)t[o]===r?i++:t[o]===s&&i--,i>0&&o++;return i===0?o:-1}function mn(e,t,n){let r=n,s=1;for(;r<t.length&&s>0;){let i=t[r];if(i==="\\"&&r+1<t.length){r+=2;continue}if(i==="'"){let o=t.indexOf("'",r+1);if(o!==-1){r=o+1;continue}}if(i==='"'){for(r++;r<t.length&&t[r]!=='"';)t[r]==="\\"&&r+1<t.length?r+=2:r++;r<t.length&&r++;continue}i==="{"?s++:i==="}"&&s--,s>0&&r++}return r}function al(e,t,n){let r=n,s=!1;for(;r<t.length;){let i=t[r];if(i==="/"&&s||i==="}")break;if(i==="'"){let o=t.indexOf("'",r+1);if(o!==-1){r=o+1,s=!0;continue}}if(i==='"'){for(r++;r<t.length&&t[r]!=='"';)t[r]==="\\"&&r+1<t.length?r+=2:r++;r<t.length&&r++,s=!0;continue}i==="\\"?(r+=2,s=!0):(r++,s=!0)}return r}function ll(e,t,n){let r=n,s="";for(;r<t.length;){let i=t[r];if(i==="*"||i==="?")s+=i,r++;else if(i==="["){let o=bd(t,r);o===-1?(s+=i,r++):(s+=t.slice(r,o+1),r=o+1)}else break}return{pattern:s,endIndex:r}}function bd(e,t){let n=t+1;for(n<e.length&&e[n]==="^"&&n++,n<e.length&&e[n]==="]"&&n++;n<e.length;){let r=e[n];if(r==="\\"&&n+1<e.length){let s=e[n+1];if(s==='"'||s==="'")return-1;n+=2;continue}if(r==="]")return n;if(r==='"'||r==="$"||r==="`")return-1;if(r==="'"){let s=e.indexOf("'",n+1);if(s!==-1){n=s+1;continue}}if(r==="["&&n+1<e.length&&e[n+1]===":"){let s=e.indexOf(":]",n+2);if(s!==-1){n=s+2;continue}}if(r==="["&&n+1<e.length&&(e[n+1]==="."||e[n+1]==="=")){let i=`${e[n+1]}]`,o=e.indexOf(i,n+2);if(o!==-1){n=o+2;continue}}n++}return-1}function cl(e,t,n){let r="",s=n;for(;s<t.length&&t[s]!=="'";){let i=t[s];if(i==="\\"&&s+1<t.length)switch(t[s+1]){case"n":r+=`
|
|
68
|
+
`,s+=2;break;case"t":r+=" ",s+=2;break;case"r":r+="\r",s+=2;break;case"\\":r+="\\",s+=2;break;case"'":r+="'",s+=2;break;case'"':r+='"',s+=2;break;case"a":r+="\x07",s+=2;break;case"b":r+="\b",s+=2;break;case"e":case"E":r+="\x1B",s+=2;break;case"f":r+="\f",s+=2;break;case"v":r+="\v",s+=2;break;case"x":{let a=[],l=s;for(;l+1<t.length&&t[l]==="\\"&&t[l+1]==="x";){let c=t.slice(l+2,l+4),u=parseInt(c,16);if(!Number.isNaN(u)&&c.length>0)a.push(u),l+=2+c.length;else break}a.length>0?(r+=Ed(a),s=l):(r+="\\x",s+=2);break}case"u":{let a=t.slice(s+2,s+6),l=parseInt(a,16);Number.isNaN(l)?(r+="\\u",s+=2):(r+=String.fromCharCode(l),s+=6);break}case"c":{if(s+2<t.length){let l=t[s+2].charCodeAt(0)&31;r+=String.fromCharCode(l),s+=3}else r+="\\c",s+=2;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let a="",l=s+1;for(;l<t.length&&l<s+4&&/[0-7]/.test(t[l]);)a+=t[l],l++;let c=parseInt(a,8);r+=String.fromCharCode(c),s=l;break}default:r+=i,s++}else r+=i,s++}return s<t.length&&t[s]==="'"&&s++,{part:M.literal(r),endIndex:s}}function pi(e,t){let n=t.trim();return n===""?{type:"ArithmeticExpression",expression:{type:"ArithNumber",value:0}}:re(e,n)}function il(e){let t=[],n="",r=0;for(let s=0;s<e.length;s++){let i=e[s];i==="{"?(r++,n+=i):i==="}"?(r--,n+=i):i===","&&r===0?(t.push(n),n=""):n+=i}return t.push(n),t}function ul(e,t,n,r){let s=di(e,t,n,"{","}");if(s===-1)return null;let i=t.slice(n+1,s),o=i.match(/^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/);if(o)return{part:{type:"BraceExpansion",items:[{type:"Range",start:Number.parseInt(o[1],10),end:Number.parseInt(o[2],10),step:o[3]?Number.parseInt(o[3],10):void 0,startStr:o[1],endStr:o[2]}]},endIndex:s+1};let a=i.match(/^([a-zA-Z])\.\.([a-zA-Z])(?:\.\.(-?\d+))?$/);return a?{part:{type:"BraceExpansion",items:[{type:"Range",start:a[1],end:a[2],step:a[3]?Number.parseInt(a[3],10):void 0}]},endIndex:s+1}:i.includes(",")&&r?{part:{type:"BraceExpansion",items:il(i).map(u=>e.withDepth(()=>({type:"Word",word:M.word(r(e,u,!1,!1,!1))})))},endIndex:s+1}:i.includes(",")?{part:{type:"BraceExpansion",items:il(i).map(u=>({type:"Word",word:M.word([M.literal(u)])}))},endIndex:s+1}:null}function hi(e,t){let n="";for(let r of t.parts)switch(r.type){case"Literal":n+=r.value;break;case"SingleQuoted":n+=`'${r.value}'`;break;case"Escaped":n+=r.value;break;case"DoubleQuoted":n+='"';for(let s of r.parts)s.type==="Literal"||s.type==="Escaped"?n+=s.value:s.type==="ParameterExpansion"&&(n+=`\${${s.parameter}}`);n+='"';break;case"ParameterExpansion":n+=`\${${r.parameter}}`;break;case"Glob":n+=r.pattern;break;case"TildeExpansion":n+="~",r.user&&(n+=r.user);break;case"BraceExpansion":{n+="{";let s=[];for(let i of r.items)if(i.type==="Range"){let o=i.startStr??String(i.start),a=i.endStr??String(i.end);i.step!==void 0?s.push(`${o}..${a}..${i.step}`):s.push(`${o}..${a}`)}else s.push(hi(e,i.word));s.length===1&&r.items[0].type==="Range"?n+=s[0]:n+=s.join(","),n+="}";break}default:n+=r.type}return n}function fl(e,t){return{[w.LESS]:"<",[w.GREAT]:">",[w.DGREAT]:">>",[w.LESSAND]:"<&",[w.GREATAND]:">&",[w.LESSGREAT]:"<>",[w.CLOBBER]:">|",[w.TLESS]:"<<<",[w.AND_GREAT]:"&>",[w.AND_DGREAT]:"&>>",[w.DLESS]:"<",[w.DLESSDASH]:"<"}[t]||">"}function lr(e){let t=e.current(),n=t.type;if(n===w.NUMBER){let r=e.peek(1);return t.end!==r.start||e.isProcessSubstitutionStart(1)?!1:qa.has(r.type)}if(n===w.FD_VARIABLE){let r=e.peek(1);return t.end!==r.start||e.isProcessSubstitutionStart(1)?!1:ja.has(r.type)}return!e.isProcessSubstitutionStart()&&Ua.has(n)}function Gr(e){let t=null,n;e.check(w.NUMBER)?t=Number.parseInt(e.advance().value,10):e.check(w.FD_VARIABLE)&&(n=e.advance().value);let r=e.advance(),s=fl(e,r.type);if(r.type===w.DLESS||r.type===w.DLESSDASH)return Sd(e,t,n,r.type===w.DLESSDASH);e.isWord()||e.error("Expected redirection target");let i=e.parseWord();return M.redirection(s,i,t,n)}function Sd(e,t,n,r){e.isWord()||e.error("Expected here-document delimiter");let s=e.advance(),i=s.heredocDelimiter??s.value,o=s.quoted||!1,a=M.redirection(r?"<<-":"<<",M.hereDoc(i,M.word([]),r,o),t,n);return e.addPendingHeredoc(a,i,r,o),a}function yi(e){let t=e.getSourceLine(),n=[],r=null,s=[],i=[];for(;e.check(w.ASSIGNMENT_WORD)||lr(e);)e.checkIterationLimit(),e.check(w.ASSIGNMENT_WORD)?n.push(Ad(e)):i.push(Gr(e));if(e.isWord())r=e.parseWord();else if(n.length>0&&(e.check(w.DBRACK_START)||e.check(w.DPAREN_START))){let a=e.advance();r=M.word([M.literal(a.value)])}for(;(!e.isStatementEnd()||e.check(w.RBRACE))&&!e.check(w.PIPE,w.PIPE_AMP);)if(e.checkIterationLimit(),lr(e))i.push(Gr(e));else if(e.check(w.ASSIGNMENT_WORD)){let a=e.advance(),l=a.value,c=l.endsWith("="),u=l.endsWith("=(");if((c||u)&&(u||e.check(w.LPAREN))){let f=u?l.slice(0,-2):l.slice(0,-1);u||e.expect(w.LPAREN);let d=mi(e);e.expect(w.RPAREN);let p=d.map(m=>hi(e,m)),h=`${f}=(${p.join(" ")})`;s.push(e.parseWordFromString(h,!1,!1,!0))}else{let f=e.parseWordFromString(l,a.quoted,a.singleQuoted,!0);s.push(e.parseAdjacentWordParts(f.parts,a.end,Ne.Assignment))}}else if(e.isWord())s.push(e.parseWord());else if(e.check(w.RBRACE)){let a=e.advance();s.push(e.parseWordFromString(a.value,!1,!1))}else if(e.check(w.LBRACE)){let a=e.advance();s.push(e.parseWordFromString(a.value,!1,!1))}else if(e.check(w.DBRACK_END)){let a=e.advance();s.push(e.parseWordFromString(a.value,!1,!1))}else if(e.check(w.LPAREN))e.error("syntax error near unexpected token `('");else break;let o=M.simpleCommand(r,s,n,i);return o.line=t,o}function Ad(e){let t=e.expect(w.ASSIGNMENT_WORD),n=t.value,r=n.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);r||e.error(`Invalid assignment: ${n}`);let s=r[0],i,o=s.length;if(n[o]==="["){let f=0,d=o+1;for(;o<n.length;o++)if(n[o]==="[")f++;else if(n[o]==="]"&&(f--,f===0))break;f!==0&&e.error(`Invalid assignment: ${n}`),i=jr(n.slice(d,o)),o++}let a=n[o]==="+";a&&o++,n[o]!=="="&&e.error(`Invalid assignment: ${n}`),o++;let l=n.slice(o);if(l==="("){let f=mi(e);e.expect(w.RPAREN);let d=i!==void 0?`${s}[${i}]`:s;return M.assignment(d,null,a,f)}if(l===""&&e.check(w.LPAREN)){let f=e.current();if(t.end===f.start){e.advance();let d=mi(e);e.expect(w.RPAREN);let p=i!==void 0?`${s}[${i}]`:s;return M.assignment(p,null,a,d)}}let c=l?e.parseWordFromString(l,t.quoted,t.singleQuoted,!0):null;t.end===e.current().start&&e.isProcessSubstitutionStart()&&(c=e.parseAdjacentWordParts(c?.parts??[],t.end,Ne.Assignment));let u=i!==void 0?`${s}[${i}]`:s;return M.assignment(u,c,a,null)}var vd=new Set([w.AMP,w.PIPE,w.PIPE_AMP,w.SEMICOLON,w.AND_AND,w.OR_OR,w.DSEMI,w.SEMI_AND,w.SEMI_SEMI_AND]);function mi(e){let t=[];for(e.skipNewlines();!e.check(w.RPAREN,w.EOF);)e.checkIterationLimit(),e.isWord()?t.push(e.parseWord()):vd.has(e.current().type)?e.error(`syntax error near unexpected token \`${e.current().value}'`):e.advance(),e.skipNewlines();return t}function gi(e,t){e.expect(w.IF);let n=[],r=e.parseCompoundList();e.expect(w.THEN);let s=e.parseCompoundList();if(s.length===0){let a=e.check(w.FI)?"fi":e.check(w.ELSE)?"else":e.check(w.ELIF)?"elif":"fi";e.error(`syntax error near unexpected token \`${a}'`)}for(n.push({condition:r,body:s});e.check(w.ELIF);){e.advance();let a=e.parseCompoundList();e.expect(w.THEN);let l=e.parseCompoundList();if(l.length===0){let c=e.check(w.FI)?"fi":e.check(w.ELSE)?"else":e.check(w.ELIF)?"elif":"fi";e.error(`syntax error near unexpected token \`${c}'`)}n.push({condition:a,body:l})}let i=null;e.check(w.ELSE)&&(e.advance(),i=e.parseCompoundList(),i.length===0&&e.error("syntax error near unexpected token `fi'")),e.expect(w.FI);let o=t?.skipRedirections?[]:e.parseOptionalRedirections();return M.ifNode(n,i,o)}function wi(e,t){let n=e.expect(w.FOR);if(e.check(w.DPAREN_START))return Pd(e,t,e.getSourceLine(n));e.isWord()||e.error("Expected variable name in for loop");let s=e.advance().value,i=null;if(e.skipNewlines(),e.check(w.IN))for(e.advance(),i=[];!e.check(w.SEMICOLON,w.NEWLINE,w.DO,w.EOF)&&e.isWord();)i.push(e.parseWord());e.check(w.SEMICOLON)&&e.advance(),e.skipNewlines(),e.expect(w.DO);let o=e.parseCompoundList();e.expect(w.DONE);let a=t?.skipRedirections?[]:e.parseOptionalRedirections();return M.forNode(s,i,o,a)}function Pd(e,t,n){e.expect(w.DPAREN_START);let r=null,s=null,i=null,o=["","",""],a=0,l=0;for(;!e.check(w.DPAREN_END,w.EOF);){let f=e.advance();if(f.type===w.SEMICOLON&&l===0){if(a++,a>2)break}else f.value==="("&&l++,f.value===")"&&l--,o[a]+=f.value}e.expect(w.DPAREN_END),o[0].trim()&&(r=re(e,o[0].trim())),o[1].trim()&&(s=re(e,o[1].trim())),o[2].trim()&&(i=re(e,o[2].trim())),e.skipNewlines(),e.check(w.SEMICOLON)&&e.advance(),e.skipNewlines();let c;e.check(w.LBRACE)?(e.advance(),c=e.parseCompoundList(),e.expect(w.RBRACE)):(e.expect(w.DO),c=e.parseCompoundList(),e.expect(w.DONE));let u=t?.skipRedirections?[]:e.parseOptionalRedirections();return{type:"CStyleFor",init:r,condition:s,update:i,body:c,redirections:u,line:n}}function Ei(e,t){e.expect(w.WHILE);let n=e.parseCompoundList();e.expect(w.DO);let r=e.parseCompoundList();r.length===0&&e.error("syntax error near unexpected token `done'"),e.expect(w.DONE);let s=t?.skipRedirections?[]:e.parseOptionalRedirections();return M.whileNode(n,r,s)}function bi(e,t){e.expect(w.UNTIL);let n=e.parseCompoundList();e.expect(w.DO);let r=e.parseCompoundList();r.length===0&&e.error("syntax error near unexpected token `done'"),e.expect(w.DONE);let s=t?.skipRedirections?[]:e.parseOptionalRedirections();return M.untilNode(n,r,s)}function Si(e,t){e.expect(w.CASE),e.isWord()||e.error("Expected word after 'case'");let n=e.parseWord();e.skipNewlines(),e.expect(w.IN),e.skipNewlines();let r=[];for(;!e.check(w.ESAC,w.EOF);){e.checkIterationLimit();let i=e.getPos(),o=xd(e);if(o&&r.push(o),e.skipNewlines(),e.getPos()===i&&!o)break}e.expect(w.ESAC);let s=t?.skipRedirections?[]:e.parseOptionalRedirections();return M.caseNode(n,r,s)}function xd(e){e.check(w.LPAREN)&&e.advance();let t=[];for(;e.isWord()&&(t.push(e.parseWord()),e.check(w.PIPE));)e.advance();if(t.length===0)return null;e.expect(w.RPAREN),e.skipNewlines();let n=[];for(;!e.check(w.DSEMI,w.SEMI_AND,w.SEMI_SEMI_AND,w.ESAC,w.EOF);){e.checkIterationLimit(),e.isWord()&&e.peek(1).type===w.RPAREN&&e.error("syntax error near unexpected token `)'"),e.check(w.LPAREN)&&e.peek(1).type===w.WORD&&e.error(`syntax error near unexpected token \`${e.peek(1).value}'`);let s=e.getPos(),i=e.parseStatement();if(i&&n.push(i),e.skipSeparators(!1),e.getPos()===s&&!i)break}let r=";;";return e.check(w.DSEMI)?(e.advance(),r=";;"):e.check(w.SEMI_AND)?(e.advance(),r=";&"):e.check(w.SEMI_SEMI_AND)&&(e.advance(),r=";;&"),M.caseItem(t,n,r)}function Ai(e,t){e.expect(w.LPAREN);let n=e.parseCompoundList();e.expect(w.RPAREN);let r=t?.skipRedirections?[]:e.parseOptionalRedirections();return M.subshell(n,r)}function vi(e,t){e.expect(w.LBRACE);let n=e.parseCompoundList();e.expect(w.RBRACE);let r=t?.skipRedirections?[]:e.parseOptionalRedirections();return M.group(n,r)}var Cd=["-a","-b","-c","-d","-e","-f","-g","-h","-k","-p","-r","-s","-t","-u","-w","-x","-G","-L","-N","-O","-S","-z","-n","-o","-v","-R"],Nd=["==","!=","=~","<",">","-eq","-ne","-lt","-le","-gt","-ge","-nt","-ot","-ef"];function pl(e){return e.isWord()||e.check(w.LBRACE)||e.check(w.RBRACE)||e.check(w.ASSIGNMENT_WORD)}function hl(e){if(e.check(w.BANG)&&e.peek(1).type===w.LPAREN){e.advance(),e.advance();let t=1,n="!(";for(;t>0&&!e.check(w.EOF);)if(e.check(w.LPAREN))t++,n+="(",e.advance();else if(e.check(w.RPAREN))t--,t>0&&(n+=")"),e.advance();else if(e.isWord())n+=e.advance().value;else if(e.check(w.PIPE))n+="|",e.advance();else break;return n+=")",e.parseWordFromString(n,!1,!1,!1,!1,!0)}return e.parseWordNoBraceExpansion()}function Pi(e){return e.skipNewlines(),Rd(e)}function Rd(e){let t=ml(e);for(e.skipNewlines();e.check(w.OR_OR);){e.advance(),e.skipNewlines();let n=ml(e);t={type:"CondOr",left:t,right:n},e.skipNewlines()}return t}function ml(e){let t=ki(e);for(e.skipNewlines();e.check(w.AND_AND);){e.advance(),e.skipNewlines();let n=ki(e);t={type:"CondAnd",left:t,right:n},e.skipNewlines()}return t}function ki(e){return e.skipNewlines(),e.check(w.BANG)?(e.advance(),e.skipNewlines(),{type:"CondNot",operand:e.withDepth(()=>ki(e))}):Od(e)}function Od(e){if(e.check(w.LPAREN)){e.advance();let t=e.withDepth(()=>Pi(e));return e.expect(w.RPAREN),{type:"CondGroup",expression:t}}if(pl(e)){let t=e.current(),n=t.value;if(Cd.includes(n)&&!t.quoted){if(e.advance(),e.check(w.DBRACK_END)&&e.error(`Expected operand after ${n}`),pl(e)){let i=e.parseWordNoBraceExpansion();return{type:"CondUnary",operator:n,operand:i}}let s=e.current();e.error(`unexpected argument \`${s.value}' to conditional unary operator`)}let r=e.parseWordNoBraceExpansion();if(e.isWord()&&Nd.includes(e.current().value)){let s=e.advance().value,i;return s==="=~"?i=Dd(e):s==="=="||s==="!="?i=hl(e):i=e.parseWordNoBraceExpansion(),{type:"CondBinary",operator:s,left:r,right:i}}if(e.check(w.LESS)){e.advance();let s=e.parseWordNoBraceExpansion();return{type:"CondBinary",operator:"<",left:r,right:s}}if(e.check(w.GREAT)){e.advance();let s=e.parseWordNoBraceExpansion();return{type:"CondBinary",operator:">",left:r,right:s}}if(e.isWord()&&e.current().value==="="){e.advance();let s=hl(e);return{type:"CondBinary",operator:"==",left:r,right:s}}return{type:"CondWord",word:r}}e.error("Expected conditional expression")}function Dd(e){let t=[],n=0,r=-1,s=e.getInput(),i=()=>e.check(w.DBRACK_END)||e.check(w.AND_AND)||e.check(w.OR_OR)||e.check(w.NEWLINE)||e.check(w.EOF);for(;!i();){let o=e.current(),a=r>=0&&o.start>r;if(n===0&&a)break;if(n>0&&a){let l=s.slice(r,o.start);t.push({type:"Literal",value:l})}if(e.isWord()||e.check(w.ASSIGNMENT_WORD)){let l=e.parseWordForRegex();t.push(...l.parts),r=e.peek(-1).end}else if(e.check(w.LPAREN)){let l=e.advance();t.push({type:"Literal",value:"("}),n++,r=l.end}else if(e.check(w.DPAREN_START)){let l=e.advance();t.push({type:"Literal",value:"(("}),n+=2,r=l.end}else if(e.check(w.DPAREN_END))if(n>=2){let l=e.advance();t.push({type:"Literal",value:"))"}),n-=2,r=l.end}else{if(n===1)break;break}else if(e.check(w.RPAREN))if(n>0){let l=e.advance();t.push({type:"Literal",value:")"}),n--,r=l.end}else break;else if(e.check(w.PIPE)){let l=e.advance();t.push({type:"Literal",value:"|"}),r=l.end}else if(e.check(w.SEMICOLON))if(n>0){let l=e.advance();t.push({type:"Literal",value:";"}),r=l.end}else break;else if(n>0&&e.check(w.LESS)){let l=e.advance();t.push({type:"Literal",value:"<"}),r=l.end}else if(n>0&&e.check(w.GREAT)){let l=e.advance();t.push({type:"Literal",value:">"}),r=l.end}else if(n>0&&e.check(w.DGREAT)){let l=e.advance();t.push({type:"Literal",value:">>"}),r=l.end}else if(n>0&&e.check(w.DLESS)){let l=e.advance();t.push({type:"Literal",value:"<<"}),r=l.end}else if(n>0&&e.check(w.LESSAND)){let l=e.advance();t.push({type:"Literal",value:"<&"}),r=l.end}else if(n>0&&e.check(w.GREATAND)){let l=e.advance();t.push({type:"Literal",value:">&"}),r=l.end}else if(n>0&&e.check(w.LESSGREAT)){let l=e.advance();t.push({type:"Literal",value:"<>"}),r=l.end}else if(n>0&&e.check(w.CLOBBER)){let l=e.advance();t.push({type:"Literal",value:">|"}),r=l.end}else if(n>0&&e.check(w.TLESS)){let l=e.advance();t.push({type:"Literal",value:"<<<"}),r=l.end}else if(n>0&&e.check(w.AMP)){let l=e.advance();t.push({type:"Literal",value:"&"}),r=l.end}else if(n>0&&e.check(w.LBRACE)){let l=e.advance();t.push({type:"Literal",value:"{"}),r=l.end}else if(n>0&&e.check(w.RBRACE)){let l=e.advance();t.push({type:"Literal",value:"}"}),r=l.end}else break}return t.length===0&&e.error("Expected regex pattern after =~"),{type:"Word",parts:t}}function _d(e){let t="";for(let n=0;n<e.length;n++){let r=e[n],s=e[n+1];if(r!=="\\"||s===void 0){t+=r;continue}"\\[]^-".includes(s)&&(t+="\\"),t+=s,n++}return t}function cr(e){return e.length>0?e:[M.literal("")]}function Td(e,t){let n=1,r=t+1;for(;r<e.length&&n>0;){let s=e[r];if(s==="\\"){r+=2;continue}if("@*+?!".includes(s)&&r+1<e.length&&e[r+1]==="("){r++,n++,r++;continue}if(s==="(")n++;else if(s===")"&&(n--,n===0))return r;r++}return-1}function Ld(e,t,n){let r=n+1,s=t[r];if("@*#?$!-0123456789".includes(s))return{part:M.parameterExpansion(s),endIndex:r+1};let i="";for(;r<t.length&&/[a-zA-Z0-9_]/.test(t[r]);)i+=t[r],r++;return{part:M.parameterExpansion(i),endIndex:r}}function Md(e,t,n,r=!1){let s=n+2,i=!1;t[s]==="!"&&(i=!0,s++);let o=!1;t[s]==="#"&&!/[}:#%/^,]/.test(t[s+1]||"}")&&(o=!0,s++);let a="",l=t[s];if(/[@*#?$!-]/.test(l)&&!/[a-zA-Z0-9_]/.test(t[s+1]||""))a=l,s++;else for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)a+=t[s],s++;if(t[s]==="["){let u=di(e,t,s,"[","]");if(a+=`[${jr(t.slice(s+1,u))}]`,s=u+1,t[s]==="["){let f=1,d=s;for(;d<t.length&&f>0;)t[d]==="{"?f++:t[d]==="}"&&f--,f>0&&d++;let p=t.slice(n+2,d);return{part:M.parameterExpansion("",{type:"BadSubstitution",text:p}),endIndex:d+1}}}if(a===""&&!i&&!o&&t[s]!=="}"){let u=1,f=s;for(;f<t.length&&u>0;)t[f]==="{"?u++:t[f]==="}"&&u--,u>0&&f++;if(u>0)throw new xe("unexpected EOF while looking for matching '}'",0,0);let d=t.slice(n+2,f);return{part:M.parameterExpansion("",{type:"BadSubstitution",text:d}),endIndex:f+1}}let c=null;if(i){let u=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(u)if(s<t.length&&t[s]!=="}"&&/[:=\-+?#%/^,@]/.test(t[s])){let f=xi(e,t,s,a,r);f.operation?(c={type:"Indirection",innerOp:f.operation},s=f.endIndex):(c={type:"ArrayKeys",array:u[1],star:u[2]==="*"},a="")}else c={type:"ArrayKeys",array:u[1],star:u[2]==="*"},a="";else if(t[s]==="*"||t[s]==="@"&&!/[QPaAEKkuUL]/.test(t[s+1]||"")){let f=t[s];s++,c={type:"VarNamePrefix",prefix:a,star:f==="*"},a=""}else if(s<t.length&&t[s]!=="}"&&/[:=\-+?#%/^,@]/.test(t[s])){let f=xi(e,t,s,a,r);f.operation?(c={type:"Indirection",innerOp:f.operation},s=f.endIndex):c={type:"Indirection"}}else c={type:"Indirection"}}else if(o)if(t[s]===":")for(c={type:"LengthSliceError"};s<t.length&&t[s]!=="}";)s++;else t[s]!=="}"&&/[-+=?]/.test(t[s])?e.error(`\${#${a}${t.slice(s,t.indexOf("}",s))}}: bad substitution`):t[s]==="/"?e.error(`\${#${a}${t.slice(s,t.indexOf("}",s))}}: bad substitution`):c={type:"Length"};if(!c&&s<t.length&&t[s]!=="}"){let u=xi(e,t,s,a,r);c=u.operation,s=u.endIndex}if(s<t.length&&t[s]!=="}"){let u=t[s];if(!/[:\-+=?#%/^,@[]/.test(u)){let f=s;for(;f<t.length&&t[f]!=="}";)f++;let d=t.slice(n,f+1);e.error(`\${${d.slice(2,-1)}}: bad substitution`)}}for(;s<t.length&&t[s]!=="}";)s++;if(s>=t.length)throw new xe("unexpected EOF while looking for matching '}'",0,0);return{part:M.parameterExpansion(a,c),endIndex:s+1}}function xi(e,t,n,r,s=!1){let i=n,o=t[i],a=t[i+1]||"";if(o===":"){let l=a;if("-=?+".includes(l)){i+=2;let b=mn(e,t,i),g=t.slice(i,b),y=e.withDepth(()=>qt(e,g,!1,!1,!0,!1,s,!1,!1,!0)),S=M.word(cr(y));if(l==="-")return{operation:{type:"DefaultValue",word:S,checkEmpty:!0},endIndex:b};if(l==="=")return{operation:{type:"AssignDefault",word:S,checkEmpty:!0},endIndex:b};if(l==="?")return{operation:{type:"ErrorIfUnset",word:S,checkEmpty:!0},endIndex:b};if(l==="+")return{operation:{type:"UseAlternative",word:S,checkEmpty:!0},endIndex:b}}i++;let c=mn(e,t,i),u=t.slice(i,c),f=-1,d=0,p=0;for(let E=0;E<u.length;E++){let b=u[E];if(b==="("||b==="[")d++;else if(b===")"||b==="]")d--;else if(b==="?"&&d===0)p++;else if(b===":"&&d===0)if(p>0)p--;else{f=E;break}}let h=f>=0?u.slice(0,f):u,m=f>=0?u.slice(f+1):null;return{operation:{type:"Substring",offset:pi(e,h),length:m!==null?pi(e,m):null},endIndex:c}}if("-=?+".includes(o)){i++;let l=mn(e,t,i),c=t.slice(i,l),u=e.withDepth(()=>qt(e,c,!1,!1,!0,!1,s,!1,!1,!0)),f=M.word(cr(u));if(o==="-")return{operation:{type:"DefaultValue",word:f,checkEmpty:!1},endIndex:l};if(o==="=")return{operation:{type:"AssignDefault",word:f,checkEmpty:!1},endIndex:l};if(o==="?")return{operation:{type:"ErrorIfUnset",word:c?f:null,checkEmpty:!1},endIndex:l};if(o==="+")return{operation:{type:"UseAlternative",word:f,checkEmpty:!1},endIndex:l}}if(o==="#"||o==="%"){let l=a===o,c=o==="#"?"prefix":"suffix";i+=l?2:1;let u=mn(e,t,i),f=t.slice(i,u),d=e.withDepth(()=>qt(e,f,!1,!1,!1));return{operation:{type:"PatternRemoval",pattern:M.word(cr(d)),side:c,greedy:l},endIndex:u}}if(o==="/"){let l=a==="/";i+=l?2:1;let c=null;t[i]==="#"?(c="start",i++):t[i]==="%"&&(c="end",i++);let u;c!==null&&(t[i]==="/"||t[i]==="}")?u=i:u=al(e,t,i);let f=t.slice(i,u),d=e.withDepth(()=>qt(e,f,!1,!1,!1)),p=M.word(cr(d)),h=null,m=u;if(t[u]==="/"){let E=u+1,b=mn(e,t,E),g=t.slice(E,b),y=e.withDepth(()=>qt(e,g,!1,!1,!1));h=M.word(cr(y)),m=b}return{operation:{type:"PatternReplacement",pattern:p,replacement:h,all:l,anchor:c},endIndex:m}}if(o==="^"||o===","){let l=a===o,c=o==="^"?"upper":"lower";i+=l?2:1;let u=mn(e,t,i),f=t.slice(i,u),d=f?M.word([M.literal(f)]):null;return{operation:{type:"CaseModification",direction:c,all:l,pattern:d},endIndex:u}}return o==="@"&&/[QPaAEKkuUL]/.test(a)?{operation:{type:"Transform",operator:a},endIndex:i+2}:{operation:null,endIndex:i}}function $i(e,t,n,r=!1){let s=n+1;if(s>=t.length)return{part:M.literal("$"),endIndex:s};let i=t[s];if(i==="("&&t[s+1]==="(")return e.isDollarDparenSubshell(t,n)?e.parseCommandSubstitution(t,n):e.parseArithmeticExpansion(t,n);if(i==="["){let o=1,a=s+1;for(;a<t.length&&o>0;)t[a]==="["?o++:t[a]==="]"&&o--,o>0&&a++;if(o===0){let l=t.slice(s+1,a),c=re(e,l);return{part:M.arithmeticExpansion(c),endIndex:a+1}}}return i==="("?e.parseCommandSubstitution(t,n):i==="{"?Md(e,t,n,r):/[a-zA-Z_0-9@*#?$!-]/.test(i)?Ld(e,t,n):{part:M.literal("$"),endIndex:s}}function yl(e,t){let n=[],r=0,s="",i=()=>{s&&(n.push(M.literal(s)),s="")};for(;r<t.length;){let o=t[r];if(o==="\\"&&r+1<t.length){let a=t[r+1];if(a==="$"||a==="`"||a==='"'||a==="\\"){s+=a,r+=2;continue}s+=o,r++;continue}if(o==="$"){i();let{part:a,endIndex:l}=$i(e,t,r,!0);a&&n.push(a),r=l;continue}if(o==="`"){i();let{part:a,endIndex:l}=e.parseBacktickSubstitution(t,r,!0);n.push(a),r=l;continue}s+=o,r++}return i(),n}function Fd(e,t,n){let r=[],s=n,i="",o=()=>{i&&(r.push(M.literal(i)),i="")};for(;s<t.length&&t[s]!=='"';){let a=t[s];if(a==="\\"&&s+1<t.length){let l=t[s+1];if('"\\$`\n'.includes(l)){i+=l,s+=2;continue}i+=a,s++;continue}if(a==="$"){o();let{part:l,endIndex:c}=$i(e,t,s,!0);l&&r.push(l),s=c;continue}if(a==="`"){o();let{part:l,endIndex:c}=e.parseBacktickSubstitution(t,s,!0);r.push(l),s=c;continue}i+=a,s++}return o(),{part:M.doubleQuoted(r),endIndex:s}}function qt(e,t,n=!1,r=!1,s=!1,i=!1,o=!1,a=!1,l=!1,c=!1,u=!0){if(r)return[M.singleQuoted(t)];if(n){let m=yl(e,t);return[M.doubleQuoted(m)]}if(t.length>=2&&t[0]==='"'&&t[t.length-1]==='"'){let m=t.slice(1,-1),E=!1;for(let b=0;b<m.length;b++){if(m[b]==='"'){E=!0;break}m[b]==="\\"&&b+1<m.length&&b++}if(!E){let b=yl(e,m);return[M.doubleQuoted(b)]}}let f=[],d=0,p="",h=()=>{p&&(f.push(M.literal(p)),p="")};for(;d<t.length;){let m=t[d];if(m==="\\"&&d+1<t.length){let E=t[d+1];if(l){h(),f.push(M.escaped(E)),d+=2;continue}if(!i&&!o){E!==`
|
|
69
|
+
`&&(h(),f.push(M.escaped(E))),d+=2;continue}let b=i?E==="$"||E==="`"||E===`
|
|
70
|
+
`:E==="$"||E==="`"||E==='"'||E==="'"||E===`
|
|
71
|
+
`||c&&E==="}",g=o?"*?[]\\".includes(E):"*?[]\\(){}.^+".includes(E);b?E!==`
|
|
72
|
+
`&&(p+=E):g?(h(),f.push(M.escaped(E))):p+=`\\${E}`,d+=2;continue}if(m==="'"&&!o&&!i){h();let E=t.indexOf("'",d+1);if(E===-1){p+=t.slice(d);break}f.push(M.singleQuoted(t.slice(d+1,E))),d=E+1;continue}if(m==='"'&&!i){h();let{part:E,endIndex:b}=Fd(e,t,d+1);f.push(E),d=b+1;continue}if(m==="$"&&t[d+1]==="'"){h();let{part:E,endIndex:b}=cl(e,t,d+2);f.push(E),d=b;continue}if(m==="$"){h();let{part:E,endIndex:b}=$i(e,t,d);E&&f.push(E),d=b;continue}if(m==="`"){h();let{part:E,endIndex:b}=e.parseBacktickSubstitution(t,d);f.push(E),d=b;continue}if((m==="<"||m===">")&&t[d+1]==="("&&!i&&!o){h();let{part:E,endIndex:b}=e.parseProcessSubstitutionFromString(t,d);f.push(E),d=b;continue}if(m==="~"){let E=d>0?t[d-1]:"";if(d===0&&u||E==="="||s&&E===":"){let g=ol(e,t,d),y=t[g];if(y===void 0||y==="/"||y===":"){h();let S=t.slice(d+1,g)||null;f.push({type:"TildeExpansion",user:S}),d=g;continue}}}if("@*+?!".includes(m)&&d+1<t.length&&t[d+1]==="("){let E=Td(t,d+1);if(E!==-1){h();let b=t.slice(d,E+1);f.push({type:"Glob",pattern:b}),d=E+1;continue}}if(m==="*"||m==="?"||m==="["){h();let{pattern:E,endIndex:b}=ll(e,t,d);f.push({type:"Glob",pattern:l?_d(E):E}),d=b;continue}if(m==="{"&&!s&&!a&&!i){let E=ul(e,t,d,qt);if(E){h(),f.push(E.part),d=E.endIndex;continue}}p+=m,d++}return h(),f}var H=class e{tokens=[];pos=0;pendingHeredocs=[];parseBudget;ownsParseBudget;_input="";processLineState;constructor(t){this.parseBudget=t??new zr,this.ownsParseBudget=t===void 0}getInput(){return this._input}checkIterationLimit(){let t=this.current();this.parseBudget.chargeIteration(t?.line??1,t?.column??1)}enterDepth(){let t=this.current();return this.parseBudget.enter(t?.line??1,t?.column??1)}withDepth(t){let n=this.enterDepth();try{return t()}finally{n()}}parse(t,n){this.ownsParseBudget&&this.parseBudget.reset();let r=this.ownsParseBudget?void 0:this.enterDepth();try{if(t.length>ci)throw new xe(`Input too large: ${t.length} bytes exceeds limit of ${ci}`,1,1);this._input=t,this.processLineState=void 0;let s=new Vr(t,n);if(this.tokens=s.tokenize(),this.tokens.length>ir)throw new xe(`Too many tokens: ${this.tokens.length} exceeds limit of ${ir}`,1,1);return this.pos=0,this.pendingHeredocs=[],this.parseBudget.chargeTokens(this.tokens.length),this.parseScript()}finally{r?.()}}parseTokens(t){this.ownsParseBudget&&this.parseBudget.reset();let n=this.ownsParseBudget?void 0:this.enterDepth();try{return this.tokens=t,this.pos=0,this.pendingHeredocs=[],this.processLineState=void 0,this.parseBudget.chargeTokens(t.length),this.parseScript()}finally{n?.()}}current(){return this.tokens[this.pos]||this.tokens[this.tokens.length-1]}peek(t=0){return this.tokens[this.pos+t]||this.tokens[this.tokens.length-1]}advance(){let t=this.current();return this.pos<this.tokens.length-1&&this.pos++,t}getPos(){return this.pos}getSourceLine(t=this.current()){let n=this.processLineState;return n?(n.currentPhysicalLine===void 0?n.currentPhysicalLine=t.line:t.line>n.currentPhysicalLine&&(n.currentPhysicalLine=t.line,n.currentLogicalLine+=1),n.currentLogicalLine):t.line}check(t,n,r,s,...i){let o=this.tokens[this.pos]?.type;return o===t||n!==void 0&&o===n||r!==void 0&&o===r||s!==void 0&&o===s?!0:i.length>0?i.includes(o):!1}expect(t,n){if(this.check(t))return this.advance();let r=this.current();throw new xe(n||`Expected ${t}, got ${r.type}`,r.line,r.column,r)}error(t){let n=this.current();throw new xe(t,n.line,n.column,n)}skipNewlines(){for(;this.check(w.NEWLINE,w.COMMENT);)this.check(w.NEWLINE)?(this.advance(),this.processHeredocs()):this.advance()}skipSeparators(t=!0){for(;;){if(this.check(w.NEWLINE)){this.advance(),this.processHeredocs();continue}if(this.check(w.SEMICOLON,w.COMMENT)){this.advance();continue}if(t&&this.check(w.DSEMI,w.SEMI_AND,w.SEMI_SEMI_AND)){this.advance();continue}break}}addPendingHeredoc(t,n,r,s){this.pendingHeredocs.push({redirect:t,delimiter:n,stripTabs:r,quoted:s})}processHeredocs(){for(let t of this.pendingHeredocs)if(this.check(w.HEREDOC_CONTENT)){let n=this.advance(),r;t.quoted?r=M.word([M.literal(n.value)]):r=this.parseWordFromString(n.value,!1,!1,!1,!0),t.redirect.target=M.hereDoc(t.delimiter,r,t.stripTabs,t.quoted,n.heredocTerminated??!1)}this.pendingHeredocs=[]}isStatementEnd(){return this.check(w.EOF,w.NEWLINE,w.SEMICOLON,w.AMP,w.AND_AND,w.OR_OR,w.RPAREN,w.RBRACE,w.DSEMI,w.SEMI_AND,w.SEMI_SEMI_AND)}isCommandStart(){let t=this.current().type;return this.isWord()||t===w.ASSIGNMENT_WORD||t===w.FD_VARIABLE||t===w.LPAREN||t===w.LBRACE||t===w.DPAREN_START||t===w.DBRACK_START||lr(this)}parseScript(){let t=[],r=0;for(this.skipNewlines();!this.check(w.EOF);){r++,r>1e4&&this.error("Parser stuck: too many iterations (>10000)");let s=this.checkUnexpectedToken();if(s){t.push(s),this.skipSeparators(!1);continue}let i=this.pos,o=this.parseStatement();o&&t.push(o),this.check(w.HEREDOC_CONTENT)&&this.processHeredocs(),this.skipSeparators(!1),this.check(w.DSEMI,w.SEMI_AND,w.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${this.current().value}'`),this.pos===i&&!this.check(w.EOF)&&this.error(`syntax error near unexpected token \`${this.current().value}'`)}return M.script(t)}checkUnexpectedToken(){let t=this.current().type,n=this.current().value;if(this.currentTokenJoinsProcessSubstitution())return null;if((t===w.DO||t===w.DONE||t===w.THEN||t===w.ELSE||t===w.ELIF||t===w.FI||t===w.ESAC)&&this.error(`syntax error near unexpected token \`${n}'`),t===w.RBRACE||t===w.RPAREN){let r=`syntax error near unexpected token \`${n}'`;return this.advance(),M.statement([M.pipeline([M.simpleCommand(null,[],[],[])])],[],!1,{message:r,token:n})}return(t===w.DSEMI||t===w.SEMI_AND||t===w.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${n}'`),t===w.SEMICOLON&&this.error(`syntax error near unexpected token \`${n}'`),(t===w.AMP||t===w.AND_AND||t===w.OR_OR||t===w.PIPE||t===w.PIPE_AMP)&&this.error(`syntax error near unexpected token \`${n}'`),null}parseStatement(){if(this.skipNewlines(),!this.isCommandStart())return null;let t=this.current().start,n=[],r=[],s=!1,i=this.parsePipeline();for(n.push(i);this.check(w.AND_AND,w.OR_OR);){let l=this.advance();r.push(l.type===w.AND_AND?"&&":"||"),this.skipNewlines();let c=this.parsePipeline();n.push(c)}this.check(w.AMP)&&(this.advance(),s=!0);let o=this.pos>0?this.tokens[this.pos-1].end:t,a=this._input.slice(t,o);return M.statement(n,r,s,void 0,a)}parseTimePrefix(){if(!this.check(w.TIME)||this.currentTokenJoinsProcessSubstitution())return;this.advance();let t=!1;return this.check(w.WORD,w.NAME)&&this.current().value==="-p"&&(this.advance(),t=!0),t}parsePipeline(){let t=!1,n=!1,r=0;for(;this.check(w.BANG)&&!this.currentTokenJoinsProcessSubstitution();)this.advance(),r++;if(r===0){let l=this.parseTimePrefix();if(l!==void 0)for(t=!0,n=l;this.check(w.BANG)&&!this.currentTokenJoinsProcessSubstitution();)this.advance(),r++}let s=r%2===1,i=[],o=[],a=this.parseCommand();for(i.push(a);this.check(w.PIPE,w.PIPE_AMP);){let l=this.advance();this.skipNewlines(),o.push(l.type===w.PIPE_AMP);let c=this.parseCommand();i.push(c)}return M.pipeline(i,s,t,n,o.length>0?o:void 0)}parseCommand(){if(this.currentTokenJoinsProcessSubstitution())return yi(this);let t=this.current();switch(t.type){case w.IF:return gi(this);case w.FOR:return wi(this);case w.WHILE:return Ei(this);case w.UNTIL:return bi(this);case w.CASE:return Si(this);case w.LPAREN:return Ai(this);case w.LBRACE:return vi(this);case w.DPAREN_START:return this.dparenClosesWithSpacedParens()?this.parseNestedSubshellsFromDparen():this.parseArithmeticCommand();case w.DBRACK_START:return this.parseConditionalCommand();case w.FUNCTION:return this.parseFunctionDef();case w.TIME:break;case w.BANG:this.error(`syntax error near unexpected token \`${t.value}'`);break;default:li(t.type)&&this.error(`syntax error near unexpected token \`${t.value}'`)}return this.check(w.NAME,w.WORD)&&this.peek(1).type===w.LPAREN&&this.peek(2).type===w.RPAREN?this.parseFunctionDef():yi(this)}dparenClosesWithSpacedParens(){let t=1,n=1;for(;n<this.tokens.length-this.pos;){let r=this.peek(n);if(r.type===w.EOF)return!1;if(r.type===w.DPAREN_START||r.type===w.LPAREN)t++;else if(r.type===w.DPAREN_END){if(t-=2,t<=0)return!1}else if(r.type===w.RPAREN&&(t--,t===0&&this.peek(n+1).type===w.RPAREN))return!0;n++}return!1}parseNestedSubshellsFromDparen(){this.advance();let t=this.parseCompoundList();this.expect(w.RPAREN),this.expect(w.RPAREN);let n=this.parseOptionalRedirections(),r=M.subshell(t,[]);return M.subshell([M.statement([M.pipeline([r],!1,!1,!1)])],n)}isWord(){return this.isWordToken(Ne.Default)||this.isProcessSubstitutionStart()||this.currentTokenJoinsProcessSubstitution()}isWordToken(t){let n=this.current().type;return n===w.WORD||n===w.NAME||n===w.NUMBER||li(n)||n===w.BANG||n===w.ASSIGNMENT_WORD&&(t&Ne.Regex)!==0}isProcessSubstitutionStart(t=0){let n=this.peek(t),r=this.peek(t+1);return(n.type===w.LESS||n.type===w.GREAT)&&r.type===w.LPAREN&&n.end===r.start}currentTokenJoinsProcessSubstitution(){return this.current().type===w.COMMENT||!this.isAdjacentWordToken(Ne.Default)?!1:this.current().end===this.peek(1).start&&this.isProcessSubstitutionStart(1)}isAdjacentWordToken(t){let n=this.current().type;return this.isWordToken(t)||n===w.ASSIGNMENT_WORD||n===w.COMMENT||n===w.LBRACE||n===w.RBRACE||n===w.DBRACK_START||n===w.DBRACK_END||n===w.FD_VARIABLE}parseWord(t=Ne.Default){if(this.isProcessSubstitutionStart())return this.parseAdjacentWordParts([],this.current().start,t);let n=this.advance(),r=this.parseWordToken(n,t);return this.parseAdjacentWordParts(r.parts,n.end,t)}parseAdjacentWordParts(t,n,r=Ne.Default){for(;n===this.current().start;){if(this.isProcessSubstitutionStart()){t.push(this.parseProcessSubstitution()),n=this.tokens[this.pos-1].end;continue}if(!this.isAdjacentWordToken(r))break;let s=this.advance();t.push(...this.parseWordToken(s,r,t.length===0).parts),n=s.end}return M.word(t)}parseWordNoBraceExpansion(){return this.parseWord(Ne.NoBraceExpansion)}parseWordForRegex(){return this.parseWord(Ne.NoBraceExpansion|Ne.Regex)}parseWordToken(t,n,r=!0){return t.type===w.LBRACE||t.type===w.RBRACE||t.type===w.DBRACK_START||t.type===w.DBRACK_END||t.type===w.FD_VARIABLE?M.word([M.literal(t.type===w.FD_VARIABLE?`{${t.value}}`:t.value)]):this.parseWordFromString(t.value,t.quoted,t.singleQuoted,(n&Ne.Assignment)!==0,!1,(n&Ne.NoBraceExpansion)!==0,(n&Ne.Regex)!==0,r)}parseWordFromString(t,n=!1,r=!1,s=!1,i=!1,o=!1,a=!1,l=!0){let c=qt(this,t,n,r,s,i,!1,o,a,!1,l);return M.word(c)}parseCommandSubstitution(t,n){return La(t,n,()=>new e(this.parseBudget),r=>this.error(r))}parseProcessSubstitutionFromString(t,n){return Ma(t,n,()=>new e(this.parseBudget),r=>this.error(r))}parseProcessSubstitution(){let t=this.advance();this.expect(w.LPAREN);let n=this.processLineState,r=this.getSourceLine(t);this.processLineState={currentLogicalLine:r};let s;try{s=M.script(this.parseCompoundList())}finally{this.processLineState=n}return this.check(w.EOF)&&this.error("unexpected EOF while looking for matching `)'"),this.expect(w.RPAREN),M.processSubstitution(s,t.type===w.LESS?"input":"output")}parseBacktickSubstitution(t,n,r=!1){return Fa(t,n,r,()=>new e(this.parseBudget),s=>this.error(s))}isDollarDparenSubshell(t,n){return _a(t,n)}parseArithmeticExpansion(t,n){let r=n+3,s=1,i=0,o=r;for(;o<t.length-1&&s>0;)t[o]==="$"&&t[o+1]==="("?t[o+2]==="("?(s++,o+=3):(i++,o+=2):t[o]==="("&&t[o+1]==="("?(s++,o+=2):t[o]===")"&&t[o+1]===")"?i>0?(i--,o++):(s--,s>0&&(o+=2)):t[o]==="("?(i++,o++):(t[o]===")"&&i>0&&i--,o++);let a=t.slice(r,o),l=this.parseArithmeticExpression(a);return{part:M.arithmeticExpansion(l),endIndex:o+2}}parseArithmeticCommand(){let t=this.expect(w.DPAREN_START),n="",r=1,s=0,i=!1,o=!1;for(;r>0&&!this.check(w.EOF);){if(i){if(i=!1,s>0){s--,n+=")";continue}if(this.check(w.RPAREN)){r--,o=!0,this.advance();continue}if(this.check(w.DPAREN_END)){r--,o=!0;continue}n+=")";continue}if(this.check(w.DPAREN_START))r++,n+="((",this.advance();else if(this.check(w.DPAREN_END))s>=2?(s-=2,n+="))",this.advance()):s===1?(s--,n+=")",i=!0,this.advance()):(r--,o=!0,r>0&&(n+="))"),this.advance());else if(this.check(w.LPAREN))s++,n+="(",this.advance();else if(this.check(w.RPAREN))s>0&&s--,n+=")",this.advance();else{let c=this.current().value,u=n.length>0?n[n.length-1]:"";n.length>0&&!n.endsWith(" ")&&!(c==="="&&/[|&^+\-*/%<>]$/.test(n))&&!(c==="<"&&u==="<")&&!(c===">"&&u===">")&&(n+=" "),n+=c,this.advance()}}o||this.expect(w.DPAREN_END);let a=this.parseArithmeticExpression(n.trim()),l=this.parseOptionalRedirections();return M.arithmeticCommand(a,l,this.getSourceLine(t))}parseConditionalCommand(){let t=this.expect(w.DBRACK_START),n=Pi(this);this.expect(w.DBRACK_END);let r=this.parseOptionalRedirections();return M.conditionalCommand(n,r,this.getSourceLine(t))}parseFunctionDef(){let t;if(this.check(w.FUNCTION)){if(this.advance(),this.check(w.NAME)||this.check(w.WORD))t=this.advance().value;else{let s=this.current();throw new xe("Expected function name",s.line,s.column,s)}this.check(w.LPAREN)&&(this.advance(),this.expect(w.RPAREN))}else t=this.advance().value,t.includes("$")&&this.error(`\`${t}': not a valid identifier`),this.expect(w.LPAREN),this.expect(w.RPAREN);this.skipNewlines();let n=this.parseCompoundCommandBody({forFunctionBody:!0}),r=this.parseOptionalRedirections();return M.functionDef(t,n,r)}parseCompoundCommandBody(t){let n=t?.forFunctionBody;if(this.check(w.LBRACE))return vi(this,{skipRedirections:n});if(this.check(w.LPAREN))return Ai(this,{skipRedirections:n});if(this.check(w.IF))return gi(this,{skipRedirections:n});if(this.check(w.FOR))return wi(this,{skipRedirections:n});if(this.check(w.WHILE))return Ei(this,{skipRedirections:n});if(this.check(w.UNTIL))return bi(this,{skipRedirections:n});if(this.check(w.CASE))return Si(this,{skipRedirections:n});this.error("Expected compound command for function body")}parseCompoundList(){let t=this.enterDepth();try{let n=[];for(this.skipNewlines();(this.currentTokenJoinsProcessSubstitution()||!this.check(w.EOF,w.FI,w.ELSE,w.ELIF,w.THEN,w.DO,w.DONE,w.ESAC,w.RPAREN,w.RBRACE,w.DSEMI,w.SEMI_AND,w.SEMI_SEMI_AND))&&this.isCommandStart();){this.checkIterationLimit();let r=this.pos,s=this.parseStatement();if(s&&n.push(s),this.skipSeparators(),this.pos===r&&!s)break}return n}finally{t()}}parseOptionalRedirections(){let t=[];for(;lr(this);){this.checkIterationLimit();let n=this.pos;if(t.push(Gr(this)),this.pos===n)break}return t}parseArithmeticExpression(t){return re(this,t)}};function Ge(e,t){return new H().parse(e,t)}function ur(e){return gn(e)}function gn(e){return e.statements.map(gl).join(`
|
|
73
|
+
`)}function gl(e){let t=[];for(let r=0;r<e.pipelines.length;r++)t.push(Wd(e.pipelines[r])),r<e.operators.length&&t.push(e.operators[r]);let n=t.join(" ");return e.background&&(n+=" &"),n}function Wd(e){let t=[];e.timed&&t.push(e.timePosix?"time -p":"time"),e.negated&&t.push("!");let n=[];for(let s=0;s<e.commands.length;s++)if(n.push(wl(e.commands[s])),s<e.commands.length-1){let i=e.pipeStderr?.[s];n.push(i?"|&":"|")}return(t.length>0?`${t.join(" ")} `:"")+n.join(" ")}function wl(e){switch(e.type){case"SimpleCommand":return Vd(e);case"If":return Kd(e);case"For":return Xd(e);case"CStyleFor":return Yd(e);case"While":return Jd(e);case"Until":return ep(e);case"Case":return tp(e);case"Subshell":return rp(e);case"Group":return sp(e);case"ArithmeticCommand":return ip(e);case"ConditionalCommand":return op(e);case"FunctionDef":return ap(e);default:{let t=e;throw new Error(`Unsupported command type: ${t.type}`)}}}function Vd(e){let t=[];for(let n of e.assignments)t.push(zd(n));e.name&&t.push(we(e.name));for(let n of e.args)t.push(we(n));for(let n of e.redirections)t.push(Sl(n));return t.join(" ")}function zd(e){let t=e.append?"+=":"=";if(e.array){let n=e.array.map(we).join(" ");return`${e.name}${t}(${n})`}return e.value?`${e.name}${t}${we(e.value)}`:`${e.name}${t}`}function we(e){return e.parts.map(t=>Zr(t,!1)).join("")}function jt(e){return e.parts.map(t=>Zr(t,!0)).join("")}function Zr(e,t){switch(e.type){case"Literal":return t?qd(e.value):Ud(e.value);case"SingleQuoted":return`'${e.value}'`;case"DoubleQuoted":return`"${e.parts.map(n=>Zr(n,!0)).join("")}"`;case"Escaped":return`\\${e.value}`;case"ParameterExpansion":return El(e);case"CommandSubstitution":return e.legacy?`\`${gn(e.body)}\``:`$(${gn(e.body)})`;case"ArithmeticExpansion":return`$((${pe(e.expression.expression)}))`;case"ProcessSubstitution":return e.direction==="input"?`<(${gn(e.body)})`:`>(${gn(e.body)})`;case"BraceExpansion":return Hd(e);case"TildeExpansion":return e.user!==null?`~${e.user}`:"~";case"Glob":return e.pattern;default:{let n=e;throw new Error(`Unsupported word part type: ${n.type}`)}}}function Ud(e){return e.replace(/[\s\\'"`!|&;()<>{}[\]*?~#]/g,"\\$&")}function qd(e){return e.replace(/[$`"\\]/g,"\\$&")}function jd(e,t){return e.parts.map(n=>Gd(n,t)).join("")}function Gd(e,t){switch(e.type){case"Literal":return t?e.value:e.value.replace(/[$`]/g,"\\$&");case"Escaped":return`\\${e.value}`;case"ParameterExpansion":return El(e);case"CommandSubstitution":return e.legacy?`\`${gn(e.body)}\``:`$(${gn(e.body)})`;case"ArithmeticExpansion":return`$((${pe(e.expression.expression)}))`;default:return Zr(e,!1)}}function El(e){return e.operation?`\${${bl(e.parameter,e.operation)}}`:Zd(e.parameter)?`\${${e.parameter}}`:`$${e.parameter}`}function Zd(e){return!(/^[?#@*$!\-0-9]$/.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e))}function bl(e,t){switch(t.type){case"Length":return`#${e}`;case"LengthSliceError":return`#${e}:`;case"BadSubstitution":return t.text;case"DefaultValue":return`${e}${t.checkEmpty?":":""}-${jt(t.word)}`;case"AssignDefault":return`${e}${t.checkEmpty?":":""}=${jt(t.word)}`;case"ErrorIfUnset":return`${e}${t.checkEmpty?":":""}?${t.word?jt(t.word):""}`;case"UseAlternative":return`${e}${t.checkEmpty?":":""}+${jt(t.word)}`;case"Substring":{let n=pe(t.offset.expression);return t.length?`${e}:${n}:${pe(t.length.expression)}`:`${e}:${n}`}case"PatternRemoval":{let n=t.side==="prefix"?"#":"%",r=t.greedy?`${n}${n}`:n;return`${e}${r}${jt(t.pattern)}`}case"PatternReplacement":{let n="/";t.all?n="//":t.anchor==="start"?n="/#":t.anchor==="end"&&(n="/%");let r=t.replacement?`/${jt(t.replacement)}`:"";return`${e}${n}${jt(t.pattern)}${r}`}case"CaseModification":{let n=t.direction==="upper"?"^":",",r=t.all?`${n}${n}`:n,s=t.pattern?jt(t.pattern):"";return`${e}${r}${s}`}case"Transform":return`${e}@${t.operator}`;case"Indirection":return t.innerOp?`!${bl(e,t.innerOp)}`:`!${e}`;case"ArrayKeys":return`!${t.array}[${t.star?"*":"@"}]`;case"VarNamePrefix":return`!${t.prefix}${t.star?"*":"@"}`;default:{let n=t;throw new Error(`Unsupported parameter operation type: ${n.type}`)}}}function Hd(e){return`{${e.items.map(Qd).join(",")}}`}function Qd(e){if(e.type==="Word")return we(e.word);let t=e.startStr??String(e.start),n=e.endStr??String(e.end);return e.step!==void 0?`${t}..${n}..${e.step}`:`${t}..${n}`}function Sl(e){let t=e.fdVariable?`{${e.fdVariable}}`:e.fd!==null?String(e.fd):"";if(e.operator==="<<"||e.operator==="<<-"){let n=e.target;if(n.terminated===!1)throw new Error("Cannot serialize an unterminated here-document");let r=n.quoted?`'${n.delimiter}'`:n.delimiter,s=jd(n.content,n.quoted);return`${t}${e.operator}${r}
|
|
74
|
+
${s}${n.delimiter}`}return e.operator==="<<<"?`${t}<<< ${we(e.target)}`:e.operator==="&>"||e.operator==="&>>"?`${e.operator} ${we(e.target)}`:`${t}${e.operator} ${we(e.target)}`}function dt(e){return e.length===0?"":` ${e.map(Sl).join(" ")}`}function at(e){return e.map(gl).join(`
|
|
75
|
+
`)}function Kd(e){let t=[];for(let n=0;n<e.clauses.length;n++){let r=e.clauses[n],s=n===0?"if":"elif";t.push(`${s} ${at(r.condition)}; then
|
|
76
|
+
${at(r.body)}`)}return e.elseBody&&t.push(`else
|
|
77
|
+
${at(e.elseBody)}`),`${t.join(`
|
|
78
|
+
`)}
|
|
79
|
+
fi${dt(e.redirections)}`}function Xd(e){let t;if(e.words===null)t=`for ${e.variable}`;else{let n=e.words.map(we).join(" ");t=`for ${e.variable} in ${n}`}return`${t}; do
|
|
80
|
+
${at(e.body)}
|
|
81
|
+
done${dt(e.redirections)}`}function Yd(e){let t=e.init?pe(e.init.expression):"",n=e.condition?pe(e.condition.expression):"",r=e.update?pe(e.update.expression):"";return`for ((${t}; ${n}; ${r})); do
|
|
82
|
+
${at(e.body)}
|
|
83
|
+
done${dt(e.redirections)}`}function Jd(e){return`while ${at(e.condition)}; do
|
|
84
|
+
${at(e.body)}
|
|
85
|
+
done${dt(e.redirections)}`}function ep(e){return`until ${at(e.condition)}; do
|
|
86
|
+
${at(e.body)}
|
|
87
|
+
done${dt(e.redirections)}`}function tp(e){let t=e.items.map(np).join(`
|
|
88
|
+
`);return`case ${we(e.word)} in
|
|
89
|
+
${t}
|
|
90
|
+
esac${dt(e.redirections)}`}function np(e){let t=e.patterns.map(we).join(" | "),n=at(e.body);return n?`${t})
|
|
91
|
+
${n}
|
|
92
|
+
${e.terminator}`:`${t})
|
|
93
|
+
${e.terminator}`}function rp(e){return`(${at(e.body)})${dt(e.redirections)}`}function sp(e){return`{ ${at(e.body)}; }${dt(e.redirections)}`}function ip(e){return`((${pe(e.expression.expression)}))${dt(e.redirections)}`}function op(e){return`[[ ${yn(e.expression)} ]]${dt(e.redirections)}`}function ap(e){let t=wl(e.body);return`${e.name}() ${t}${dt(e.redirections)}`}function pe(e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return e.hasDollarPrefix?`$${e.name}`:e.name;case"ArithSpecialVar":return`$${e.name}`;case"ArithBinary":return`${pe(e.left)} ${e.operator} ${pe(e.right)}`;case"ArithUnary":return e.prefix?`${e.operator}${pe(e.operand)}`:`${pe(e.operand)}${e.operator}`;case"ArithTernary":return`${pe(e.condition)} ? ${pe(e.consequent)} : ${pe(e.alternate)}`;case"ArithAssignment":return`${e.subscript?`${e.variable}[${pe(e.subscript)}]`:e.stringKey!==void 0?`${e.variable}[${e.stringKey}]`:e.variable} ${e.operator} ${pe(e.value)}`;case"ArithDynamicAssignment":return`${e.subscript?`${pe(e.target)}[${pe(e.subscript)}]`:pe(e.target)} ${e.operator} ${pe(e.value)}`;case"ArithDynamicElement":return`${pe(e.nameExpr)}[${pe(e.subscript)}]`;case"ArithGroup":return`(${pe(e.expression)})`;case"ArithNested":return`$((${pe(e.expression)}))`;case"ArithCommandSubst":return`$(${e.command})`;case"ArithBracedExpansion":return`\${${e.content}}`;case"ArithArrayElement":return e.stringKey!==void 0?`${e.array}[${e.stringKey}]`:e.index?`${e.array}[${pe(e.index)}]`:e.array;case"ArithDynamicBase":return`\${${e.baseExpr}}#${e.value}`;case"ArithDynamicNumber":return`\${${e.prefix}}${e.suffix}`;case"ArithConcat":return e.parts.map(pe).join("");case"ArithDoubleSubscript":return`${e.array}[${pe(e.index)}]`;case"ArithNumberSubscript":return`${e.number}[${e.errorToken}]`;case"ArithSyntaxError":return e.errorToken;case"ArithSingleQuote":return`'${e.content}'`;default:{let t=e;throw new Error(`Unsupported arithmetic expression type: ${t.type}`)}}}function yn(e){switch(e.type){case"CondBinary":return`${we(e.left)} ${e.operator} ${we(e.right)}`;case"CondUnary":return`${e.operator} ${we(e.operand)}`;case"CondNot":return`! ${yn(e.operand)}`;case"CondAnd":return`${yn(e.left)} && ${yn(e.right)}`;case"CondOr":return`${yn(e.left)} || ${yn(e.right)}`;case"CondGroup":return`( ${yn(e.expression)} )`;case"CondWord":return we(e.word);default:{let t=e;throw new Error(`Unsupported conditional expression type: ${t.type}`)}}}var lp="BASH_ALIAS_";function Hr(e,t,n,r){let s=B(t);if(s>n-r.value)throw new x(`alias expansion exceeds string length limit (${n} bytes)`,"string_length");return r.value+=s,e+t}function Al(e){return e.parts.length!==1?!1:e.parts[0].type==="Literal"}function vl(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type==="Literal"?t.value:null}function kl(e,t){return e.env.get(`${lp}${t}`)}function xl(e,t,n){return $l(e,t,n)}function $l(e,t,n,r=!0){if(!t.name||!Al(t.name))return t;let s=vl(t.name);if(!s)return t;let i=kl(e,s);if(!i||n.has(s))return t;try{n.add(s);let o=new H,a={value:0},l=Hr("",i,e.limits.maxStringLength,a),c=i.endsWith(" ");if(!c)for(let p of t.args){let h=we(p);l=Hr(l,` ${h}`,e.limits.maxStringLength,a)}let u;try{u=o.parse(l)}catch(p){if(p instanceof xe)throw p;return t}if(u.statements.length!==1||u.statements[0].pipelines.length!==1||u.statements[0].pipelines[0].commands.length!==1)return Pl(e,t,i);let f=u.statements[0].pipelines[0].commands[0];if(f.type!=="SimpleCommand")return Pl(e,t,i);let d={...f,assignments:[...t.assignments,...f.assignments],redirections:[...f.redirections,...t.redirections],line:t.line};if(c&&t.args.length>0){d={...d,args:[...d.args,...t.args]};let p=1;for(;r&&d.args.length>0;){let h=d.args[0];if(!Al(h))break;let m=vl(h),E=m?kl(e,m):null;if(!E)break;if(p>=e.limits.maxCallDepth)throw new x(`alias expansion depth limit exceeded (${e.limits.maxCallDepth})`,"recursion");p++;let b={type:"SimpleCommand",name:h,args:d.args.slice(1),assignments:[],redirections:[]},g=$l(e,b,n,!1);if(g===b||(d={...d,name:g.name,args:[...g.args]},!E.endsWith(" ")))break}}return d}catch(o){throw n.delete(s),o}}function Pl(e,t,n){let r={value:0},s=Hr("",n,e.limits.maxStringLength,r);for(let c of t.args){let u=we(c);s=Hr(s,` ${u}`,e.limits.maxStringLength,r)}let i=new H,o=i.parseWordFromString("eval",!1,!1),a=0;for(let c of s)c==="'"&&a++;if(r.value+2+a*3>e.limits.maxStringLength)throw new x(`alias expansion exceeds string length limit (${e.limits.maxStringLength} bytes)`,"string_length");let l=i.parseWordFromString(`'${s.replace(/'/g,"'\\''")}'`,!1,!1);return{type:"SimpleCommand",name:o,args:[l],assignments:t.assignments,redirections:t.redirections,line:t.line}}var cp=new Map([["alnum","a-zA-Z0-9"],["alpha","a-zA-Z"],["ascii","\\x00-\\x7F"],["blank"," \\t"],["cntrl","\\x00-\\x1F\\x7F"],["digit","0-9"],["graph","!-~"],["lower","a-z"],["print"," -~"],["punct","!-/:-@\\[-`{-~"],["space"," \\t\\n\\r\\f\\v"],["upper","A-Z"],["word","a-zA-Z0-9_"],["xdigit","0-9a-fA-F"]]);function Ci(e){return cp.get(e)??""}function Cl(e){let t=[],n="",r=0;for(;r<e.length;){let s=e[r];if(s==="["){for(n+=s,r++,r<e.length&&(e[r]==="!"||e[r]==="^")&&(n+=e[r],r++),r<e.length&&e[r]==="]"&&(n+=e[r],r++);r<e.length&&e[r]!=="]";){if(e[r]==="["&&r+1<e.length&&e[r+1]===":"){let i=e.indexOf(":]",r+2);if(i!==-1){n+=e.slice(r,i+2),r=i+2;continue}}if(e[r]==="\\"&&r+1<e.length){n+=e[r]+e[r+1],r+=2;continue}n+=e[r],r++}r<e.length&&e[r]==="]"&&(n+=e[r],r++)}else s===":"?(n!==""&&t.push(n),n="",r++):s==="\\"&&r+1<e.length?(n+=s+e[r+1],r+=2):(n+=s,r++)}return n!==""&&t.push(n),t}function Nl(e){let t="^";for(let n=0;n<e.length;n++){let r=e[n];if(r==="*")t+="[^/]*";else if(r==="?")t+="[^/]";else if(r==="["){let s=n+1,i="[";s<e.length&&(e[s]==="^"||e[s]==="!")&&(i+="^",s++),s<e.length&&e[s]==="]"&&(i+="\\]",s++);let o=s;for(;o<e.length;){if(e[o]==="\\"&&o+1<e.length){o+=2;continue}if(e[o]==="["&&o+1<e.length&&e[o+1]===":"){let l=e.indexOf(":]",o+2);if(l!==-1){o=l+2;continue}}if(e[o]==="]")break;o++}let a=s;for(;s<e.length&&e[s]!=="]";){if(e[s]==="["&&s+1<e.length&&e[s+1]===":"){let l=e.indexOf(":]",s+2);if(l!==-1){let c=e.slice(s+2,l),u=Ci(c);i+=u,s=l+2;continue}}if(e[s]==="\\"&&s+1<e.length){i+=`\\${e[s+1]}`,s+=2;continue}if(e[s]==="-"){let l=s===a,c=s+1===o;l||c?i+="\\-":i+="-"}else i+=e[s];s++}i+="]",t+=i,n=s}else if(r==="\\"&&n+1<e.length){let s=e[n+1];/[.+^${}()|\\*?[\]]/.test(s)?t+=`\\${s}`:t+=s,n++}else/[.+^${}()|]/.test(r)?t+=`\\${r}`:t+=r}return t+="$",ge(t)}function Ni(e,t){let n=1,r=t+1;for(;r<e.length&&n>0;){let s=e[r];if(s==="\\"){r+=2;continue}if(s==="(")n++;else if(s===")"&&(n--,n===0))return r;r++}return-1}function Ri(e){let t=[],n="",r=0,s=!1,i=0;for(;i<e.length;){let o=e[i];if(o==="'"&&!s){s=!0,n+="\0QUOTE_START\0",i++;continue}if(o==="'"&&s){s=!1,n+="\0QUOTE_END\0",i++;continue}if(s){n+=o,i++;continue}if(o==="\\"){n+=o,i+1<e.length?(n+=e[i+1],i+=2):i++;continue}o==="("?(r++,n+=o):o===")"?(r--,n+=o):o==="|"&&r===0?(t.push(n),n=""):n+=o,i++}return t.push(n),t}var Rl=5,Gt=class{fs;cwd;globignorePatterns=[];hasGlobignore=!1;globstar=!1;nullglob=!1;failglob=!1;dotglob=!1;extglob=!1;globskipdots=!0;ops={count:0};maxOps;consumeOperation;constructor(t,n,r,s){this.fs=t,this.cwd=n,typeof s=="boolean"?(this.globstar=s,this.maxOps=1e5):s?(this.globstar=s.globstar??!1,this.nullglob=s.nullglob??!1,this.failglob=s.failglob??!1,this.dotglob=s.dotglob??!1,this.extglob=s.extglob??!1,this.globskipdots=s.globskipdots??!0,this.maxOps=s.maxGlobOperations??1e5,this.consumeOperation=s.consumeOperation):this.maxOps=1e5;let i=r?.get("GLOBIGNORE");i!==void 0&&i!==""&&(this.hasGlobignore=!0,this.globignorePatterns=Cl(i))}checkOpsLimit(){if(++this.ops.count>this.maxOps)throw new x(`Glob operation limit exceeded (${this.maxOps})`,"glob_operations");this.consumeOperation?.()}hasNullglob(){return this.nullglob}hasFailglob(){return this.failglob}filterGlobignore(t){return!this.hasGlobignore&&!this.globskipdots?t:t.filter(n=>{let r=n.split("/").pop()||n;if((this.hasGlobignore||this.globskipdots)&&(r==="."||r===".."))return!1;if(this.hasGlobignore){for(let s of this.globignorePatterns)if(this.matchGlobignorePattern(n,s))return!1}return!0})}matchGlobignorePattern(t,n){return Nl(n).test(t)}isGlobPattern(t){return!!(t.includes("*")||t.includes("?")||/\[.*\]/.test(t)||this.extglob&&/[@*+?!]\(/.test(t))}async expandArgs(t,n){let r=t.map((o,a)=>(n?.[a]??!1)||!this.isGlobPattern(o)?null:this.expand(o)),s=await Promise.all(r.map(o=>o||Promise.resolve(null))),i=[];for(let o=0;o<t.length;o++){let a=s[o];a===null?i.push(t[o]):a.length>0?i.push(...a):i.push(t[o])}return i}async expand(t){if(this.globstar){let r=t.split("/"),s=0;for(let i of r)if(i==="**"&&(s++,s>Rl))throw new x(`Glob pattern has too many ** segments (max ${Rl})`,"glob_operations")}let n;if(t.includes("**")&&this.globstar&&this.isGlobstarValid(t))n=await this.expandRecursive(t);else{let r=t.replace(/\*\*+/g,"*");n=await this.expandSimple(r)}return this.filterGlobignore(n)}isGlobstarValid(t){let n=t.split("/");for(let r of n)if(r.includes("**")&&r!=="**")return!1;return!0}hasGlobChars(t){return!!(t.includes("*")||t.includes("?")||/\[.*\]/.test(t)||this.extglob&&/[@*+?!]\(/.test(t))}async expandSimple(t){let n=t.startsWith("/"),r=t.split("/").filter(c=>c!==""),s=-1;for(let c=0;c<r.length;c++)if(this.hasGlobChars(r[c])){s=c;break}if(s===-1)return[t];let i,o;if(s===0)n?(i="/",o="/"):(i=this.cwd,o="");else{let c=r.slice(0,s);n?(i=`/${c.join("/")}`,o=`/${c.join("/")}`):(i=this.fs.resolvePath(this.cwd,c.join("/")),o=c.join("/"))}let a=r.slice(s);return(await this.expandSegments(i,o,a)).sort()}async expandSegments(t,n,r){if(this.checkOpsLimit(),r.length===0)return[n];let[s,...i]=r,o=[];try{if(this.fs.readdirWithFileTypes){this.checkOpsLimit();let a=await this.fs.readdirWithFileTypes(t),l=[],c=[...a],u=this.dotglob||this.hasGlobignore;if(s.startsWith(".")||this.dotglob){let d=a.some(h=>h.name==="."),p=a.some(h=>h.name==="..");d||c.push({name:".",isFile:!1,isDirectory:!0,isSymbolicLink:!1}),p||c.push({name:"..",isFile:!1,isDirectory:!0,isSymbolicLink:!1})}for(let d of c)if(!(d.name.startsWith(".")&&!s.startsWith(".")&&!u)&&this.matchPattern(d.name,s)){let p=t==="/"?`/${d.name}`:`${t}/${d.name}`,h;n===""?h=d.name:n==="/"?h=`/${d.name}`:h=`${n}/${d.name}`,i.length===0?l.push(Promise.resolve([h])):d.isDirectory&&l.push(this.expandSegments(p,h,i))}let f=await Promise.all(l);for(let d of f)o.push(...d)}else{this.checkOpsLimit();let a=await this.fs.readdir(t),l=[],c=[...a],u=this.dotglob||this.hasGlobignore;(s.startsWith(".")||this.dotglob)&&(a.includes(".")||c.push("."),a.includes("..")||c.push(".."));for(let d of c)if(!(d.startsWith(".")&&!s.startsWith(".")&&!u)&&this.matchPattern(d,s)){let p=t==="/"?`/${d}`:`${t}/${d}`,h;n===""?h=d:n==="/"?h=`/${d}`:h=`${n}/${d}`,i.length===0?l.push(Promise.resolve([h])):l.push((async()=>{try{if(this.checkOpsLimit(),(await this.fs.stat(p)).isDirectory)return this.expandSegments(p,h,i)}catch(m){if(m instanceof x)throw m}return[]})())}let f=await Promise.all(l);for(let d of f)o.push(...d)}}catch(a){if(a instanceof x)throw a}return o}async expandRecursive(t){let n=[],r=t.indexOf("**"),s=t.slice(0,r).replace(/\/$/,"")||".",o=t.slice(r+2).replace(/^\//,"");return o.includes("**")&&this.isGlobstarValid(o)?(await this.walkDirectoryMultiGlobstar(s,o,n),[...new Set(n)].sort()):(await this.walkDirectory(s,o,n),n.sort())}async walkDirectoryMultiGlobstar(t,n,r){this.checkOpsLimit();let s=this.fs.resolvePath(this.cwd,t);try{this.checkOpsLimit();let i=this.fs.readdirWithFileTypes?await this.fs.readdirWithFileTypes(s):null;if(i){let o=[];for(let c of i){let u=t==="."?c.name:`${t}/${c.name}`;c.isDirectory&&o.push(u)}let a=t==="."?n:`${t}/${n}`,l=await this.expandRecursive(a);r.push(...l);for(let c=0;c<o.length;c+=100){let u=o.slice(c,c+100);await Promise.all(u.map(f=>this.walkDirectoryMultiGlobstar(f,n,r)))}}else{this.checkOpsLimit();let o=await this.fs.readdir(s),a=[];for(let u of o){let f=t==="."?u:`${t}/${u}`,d=this.fs.resolvePath(this.cwd,f);try{this.checkOpsLimit(),(await this.fs.stat(d)).isDirectory&&a.push(f)}catch(p){if(p instanceof x)throw p}}let l=t==="."?n:`${t}/${n}`,c=await this.expandRecursive(l);r.push(...c);for(let u=0;u<a.length;u+=100){let f=a.slice(u,u+100);await Promise.all(f.map(d=>this.walkDirectoryMultiGlobstar(d,n,r)))}}}catch(i){if(i instanceof x)throw i}}async walkDirectory(t,n,r){this.checkOpsLimit();let s=this.fs.resolvePath(this.cwd,t);try{if(this.fs.readdirWithFileTypes){this.checkOpsLimit();let i=await this.fs.readdirWithFileTypes(s),o=[],a=[];for(let l of i){let c=t==="."?l.name:`${t}/${l.name}`;l.isDirectory?a.push(c):n&&this.matchPattern(l.name,n)&&o.push(c)}r.push(...o);for(let l=0;l<a.length;l+=100){let c=a.slice(l,l+100);await Promise.all(c.map(u=>this.walkDirectory(u,n,r)))}}else{this.checkOpsLimit();let i=await this.fs.readdir(s),o=[];for(let l=0;l<i.length;l+=100){let c=i.slice(l,l+100),u=await Promise.all(c.map(async f=>{let d=t==="."?f:`${t}/${f}`,p=this.fs.resolvePath(this.cwd,d);try{this.checkOpsLimit();let h=await this.fs.stat(p);return{name:f,path:d,isDirectory:h.isDirectory}}catch(h){if(h instanceof x)throw h;return null}}));o.push(...u.filter(f=>f!==null))}for(let l of o)!l.isDirectory&&n&&this.matchPattern(l.name,n)&&r.push(l.path);let a=o.filter(l=>l.isDirectory);for(let l=0;l<a.length;l+=100){let c=a.slice(l,l+100);await Promise.all(c.map(u=>this.walkDirectory(u.path,n,r)))}}}catch(i){if(i instanceof x)throw i}}matchPattern(t,n){return this.patternToRegex(n).test(t)}patternToRegex(t){let n=this.patternToRegexStr(t);return ge(`^${n}$`)}patternToRegexStr(t){let n="",r=!1;for(let s=0;s<t.length;s++){if(t.slice(s,s+13)==="\0QUOTE_START\0"){r=!0,s+=12;continue}if(t.slice(s,s+11)==="\0QUOTE_END\0"){r=!1,s+=10;continue}let i=t[s];if(r){/[.+^${}()|\\*?[\]]/.test(i)?n+=`\\${i}`:n+=i;continue}if(this.extglob&&(i==="@"||i==="*"||i==="+"||i==="?"||i==="!")&&s+1<t.length&&t[s+1]==="("){let o=Ni(t,s+1);if(o!==-1){let a=t.slice(s+2,o),l=Ri(a),c=l.map(f=>this.patternToRegexStr(f)),u=c.length>0?c.join("|"):"(?:)";if(i==="@")n+=`(?:${u})`;else if(i==="*")n+=`(?:${u})*`;else if(i==="+")n+=`(?:${u})+`;else if(i==="?")n+=`(?:${u})?`;else if(i==="!")if(o<t.length-1){let d=l.map(h=>this.computePatternLength(h));if(d.every(h=>h!==null)&&d.every(h=>h===d[0])&&d[0]!==null){let h=d[0];if(h===0)n+="(?:.+)";else{let m=[];h>0&&m.push(`.{0,${h-1}}`),m.push(`.{${h+1},}`),m.push(`(?!(?:${u})).{${h}}`),n+=`(?:${m.join("|")})`}}else n+=`(?:(?!(?:${u})).)*?`}else n+=`(?!(?:${u})$).*`;s=o;continue}}if(i==="*")n+=".*";else if(i==="?")n+=".";else if(i==="["){let o=s+1,a="[";o<t.length&&(t[o]==="^"||t[o]==="!")&&(a+="^",o++),o<t.length&&t[o]==="]"&&(a+="\\]",o++);let l=o;for(;l<t.length;){if(t[l]==="\\"&&l+1<t.length){l+=2;continue}if(t[l]==="["&&l+1<t.length&&t[l+1]===":"){let u=t.indexOf(":]",l+2);if(u!==-1){l=u+2;continue}}if(t[l]==="]")break;l++}let c=o;for(;o<t.length&&t[o]!=="]";){if(t[o]==="["&&o+1<t.length&&t[o+1]===":"){let u=t.indexOf(":]",o+2);if(u!==-1){let f=t.slice(o+2,u),d=Ci(f);a+=d,o=u+2;continue}}if(t[o]==="\\"&&o+1<t.length){a+=`\\${t[o+1]}`,o+=2;continue}if(t[o]==="-"){let u=o===c,f=o+1===l;u||f?a+="\\-":a+="-"}else a+=t[o];o++}a+="]",n+=a,s=o}else if(i==="\\"&&s+1<t.length){let o=t[s+1];/[.+^${}()|\\*?[\]]/.test(o)?n+=`\\${o}`:n+=o,s++}else/[.+^${}()|]/.test(i)?n+=`\\${i}`:n+=i}return n}computePatternLength(t){let n=0,r=0,s=!1;for(;r<t.length;){if(t.slice(r,r+13)==="\0QUOTE_START\0"){s=!0,r+=13;continue}if(t.slice(r,r+11)==="\0QUOTE_END\0"){s=!1,r+=11;continue}let i=t[r];if(s){n+=1,r++;continue}if((i==="@"||i==="*"||i==="+"||i==="?"||i==="!")&&r+1<t.length&&t[r+1]==="("){let o=Ni(t,r+1);if(o!==-1){if(i==="@"){let a=t.slice(r+2,o),c=Ri(a).map(u=>this.computePatternLength(u));if(c.every(u=>u!==null)&&c.every(u=>u===c[0])){n+=c[0],r=o+1;continue}return null}return null}}if(i==="*")return null;if(i==="?"){n+=1,r++;continue}if(i==="["){let o=t.indexOf("]",r+1);if(o!==-1){n+=1,r=o+1;continue}n+=1,r++;continue}if(i==="\\"){n+=1,r+=2;continue}n+=1,r++}return n}};function Oi(e){for(let t=0;t<e.length;t++){if(e[t]==="\\"){t++;continue}if(e[t]==="$"){let n=e[t+1];if(n==="{"||n&&/[a-zA-Z_]/.test(n))return!0}}return!1}function up(e){if(!e.operation)return!1;let t=e.operation,n;if((t.type==="DefaultValue"||t.type==="AssignDefault"||t.type==="UseAlternative"||t.type==="ErrorIfUnset")&&(n=t.word?.parts),!n)return!1;for(let r of n)if(r.type==="DoubleQuoted"||r.type==="SingleQuoted")return!0;return!1}function Ol(e){if(!e.operation)return!1;let t=e.operation,n;if((t.type==="DefaultValue"||t.type==="AssignDefault"||t.type==="UseAlternative"||t.type==="ErrorIfUnset")&&(n=t.word?.parts),!n||n.length===0)return!1;for(let r of n)if(r.type!=="DoubleQuoted"&&r.type!=="SingleQuoted")return!1;return!0}function fr(e){let t=!1,n=!1,r=!1,s=!1,i=!1,o=!1,a=!1;for(let l of e){if((l.type==="SingleQuoted"||l.type==="DoubleQuoted")&&(t=!0,l.type==="DoubleQuoted"))for(let c of l.parts)c.type==="ParameterExpansion"&&(c.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/)&&(!c.operation||c.operation.type==="PatternRemoval"||c.operation.type==="PatternReplacement")&&(s=!0),(c.operation?.type==="VarNamePrefix"||c.operation?.type==="ArrayKeys")&&(o=!0),c.operation?.type==="Indirection"&&(a=!0));l.type==="CommandSubstitution"&&(n=!0),l.type==="ParameterExpansion"&&(i=!0,(l.parameter==="@"||l.parameter==="*")&&(r=!0),up(l)&&(t=!0),(l.operation?.type==="VarNamePrefix"||l.operation?.type==="ArrayKeys")&&(o=!0),l.operation?.type==="Indirection"&&(a=!0)),l.type==="Glob"&&Oi(l.pattern)&&(i=!0)}return{hasQuoted:t,hasCommandSub:n,hasArrayVar:r,hasArrayAtExpansion:s,hasParamExpansion:i,hasVarNamePrefixExpansion:o,hasIndirection:a}}var fp=`
|
|
94
|
+
`;function wn(e,t){if(e>=t)throw new x(`array element limit exceeded (${t})`,"array_elements")}function Di(e,t,n,r,s){wn(e.length,s),wn(t.length,s),e.push(n),t.push(r)}function ke(e){return e.get("IFS")??fp}function Re(e){return e.get("IFS")===""}function Qr(e){let t=ke(e);if(t==="")return!0;for(let n of t)if(n!==" "&&n!==" "&&n!==`
|
|
95
|
+
`)return!1;return!0}function Dl(e){let t=!1,n=[];for(let r of e.split(""))r==="-"?t=!0:/[\\^$.*+?()[\]{}|]/.test(r)?n.push(`\\${r}`):r===" "?n.push("\\t"):r===`
|
|
96
|
+
`?n.push("\\n"):n.push(r);return t&&n.push("\\-"),n.join("")}function K(e){let t=e.get("IFS");return t===void 0?" ":t[0]||""}var dp=`
|
|
97
|
+
`;function pp(e){return dp.includes(e)}function Ii(e){let t=new Set,n=new Set;for(let r of e)pp(r)?t.add(r):n.add(r);return{whitespace:t,nonWhitespace:n}}function _i(e,t,n,r,s){if(t==="")return e===""?{words:[],wordStarts:[]}:(wn(0,n),{words:[e],wordStarts:[0]});let{whitespace:i,nonWhitespace:o}=Ii(t),a=[],l=[],c=0;for(;c<e.length&&i.has(e[c]);)c++;if(c>=e.length)return{words:[],wordStarts:[]};if(o.has(e[c]))for(Di(a,l,"",c,n),c++;c<e.length&&i.has(e[c]);)c++;for(;c<e.length&&!(r!==void 0&&a.length>=r);){let u=c;for(;c<e.length;){let f=e[c];if(!s&&f==="\\"){c++,c<e.length&&c++;continue}if(i.has(f)||o.has(f))break;c++}if(Di(a,l,e.substring(u,c),u,n),c>=e.length)break;for(;c<e.length&&i.has(e[c]);)c++;if(c<e.length&&o.has(e[c])){for(c++;c<e.length&&i.has(e[c]);)c++;for(;c<e.length&&o.has(e[c])&&!(r!==void 0&&a.length>=r);)for(Di(a,l,"",c,n),c++;c<e.length&&i.has(e[c]);)c++}}return{words:a,wordStarts:l}}function Kr(e,t,n){if(t==="")return e&&wn(0,n),{words:e?[e]:[],hadLeadingDelimiter:!1,hadTrailingDelimiter:!1};if(e==="")return{words:[],hadLeadingDelimiter:!1,hadTrailingDelimiter:!1};let{whitespace:r,nonWhitespace:s}=Ii(t),i=[],o=0,a=!1,l=!1,c=o;for(;o<e.length&&r.has(e[o]);)o++;if(o>c&&(a=!0),o>=e.length)return{words:[],hadLeadingDelimiter:!0,hadTrailingDelimiter:!0};if(s.has(e[o]))for(wn(i.length,n),i.push(""),o++;o<e.length&&r.has(e[o]);)o++;for(;o<e.length;){let u=o;for(;o<e.length;){let d=e[o];if(r.has(d)||s.has(d))break;o++}if(wn(i.length,n),i.push(e.substring(u,o)),o>=e.length){l=!1;break}let f=o;for(;o<e.length&&r.has(e[o]);)o++;if(o<e.length&&s.has(e[o])){for(o++;o<e.length&&r.has(e[o]);)o++;for(;o<e.length&&s.has(e[o]);)for(wn(i.length,n),i.push(""),o++;o<e.length&&r.has(e[o]);)o++}o>=e.length&&o>f&&(l=!0)}return{words:i,hadLeadingDelimiter:a,hadTrailingDelimiter:l}}function de(e,t,n){return Kr(e,t,n).words}function hp(e,t){for(let n of e)if(t.has(n))return!0;return!1}function Il(e,t,n){if(t==="")return e;let{whitespace:r,nonWhitespace:s}=Ii(t),i=e.length;for(;i>0&&r.has(e[i-1]);){if(!n&&i>=2){let a=0,l=i-2;for(;l>=0&&e[l]==="\\";)a++,l--;if(a%2===1)break}i--}let o=e.substring(0,i);if(o.length>=1&&s.has(o[o.length-1])){if(!n&&o.length>=2){let l=0,c=o.length-2;for(;c>=0&&o[c]==="\\";)l++,c--;if(l%2===1)return o}let a=o.substring(0,o.length-1);if(!hp(a,s))return a}return o}function ue(e,t){return e.state.namerefs?.has(t)??!1}function Dt(e,t){e.state.namerefs??=new Set,e.state.namerefs.add(t)}function _l(e,t){e.state.namerefs?.delete(t),e.state.boundNamerefs?.delete(t),e.state.invalidNamerefs?.delete(t)}function Tl(e,t){e.state.invalidNamerefs??=new Set,e.state.invalidNamerefs.add(t)}function Ll(e,t){return e.state.invalidNamerefs?.has(t)??!1}function Ti(e,t){e.state.boundNamerefs??=new Set,e.state.boundNamerefs.add(t)}function Xr(e,t){let n=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(n){let s=n[1],i=Ce(e,s),o=e.state.associativeArrays?.has(s)??!1;return i||o}return Ce(e,t)?!0:e.state.env.has(t)}function Fe(e,t,n=100){if(!ue(e,t)||Ll(e,t))return t;let r=new Set,s=t;for(;n-- >0;){if(r.has(s))return;if(r.add(s),!ue(e,s))return s;let i=e.state.env.get(s);if(i===void 0||i===""||!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(i))return s;s=i}}function En(e,t){if(ue(e,t))return e.state.env.get(t)}function Yr(e,t,n,r=100){if(!ue(e,t)||Ll(e,t))return t;let s=new Set,i=t;for(;r-- >0;){if(s.has(i))return;if(s.add(i),!ue(e,i))return i;let o=e.state.env.get(i);if(o===void 0||o==="")return n!==void 0?/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)&&Xr(e,n)?i:null:i;if(!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(o))return i;i=o}}function Ml(e,t){let n=t.replace(/\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g,(r,s)=>e.state.env.get(s)??"");return n=n.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,s)=>e.state.env.get(s)??""),n}function Q(e,t){return t==="FUNCNAME"?(e.state.funcNameStack??[]).map((i,o)=>[o,i]):t==="BASH_LINENO"?(e.state.callLineStack??[]).map((i,o)=>[o,String(i)]):t==="BASH_SOURCE"?(e.state.sourceStack??[]).map((i,o)=>[o,i]):e.state.associativeArrays?.has(t)?Et(e,t).map(i=>[i,le(e,t,i)??""]):ve(e,t).map(s=>[s,le(e,t,s)??""])}function pt(e,t){return t==="FUNCNAME"?(e.state.funcNameStack?.length??0)>0:t==="BASH_LINENO"?(e.state.callLineStack?.length??0)>0:t==="BASH_SOURCE"?(e.state.sourceStack?.length??0)>0:e.state.associativeArrays?.has(t)?Ce(e,t):Ce(e,t)}async function ie(e,t,n=!0,r=!1){switch(t){case"?":return String(e.state.lastExitCode);case"$":return String(e.state.virtualPid);case"#":return e.state.env.get("#")||"0";case"@":return e.state.env.get("@")||"";case"_":return e.state.lastArg;case"-":{let o="";return o+="h",e.state.options.errexit&&(o+="e"),e.state.options.noglob&&(o+="f"),e.state.options.nounset&&(o+="u"),e.state.options.verbose&&(o+="v"),e.state.options.xtrace&&(o+="x"),o+="B",e.state.options.noclobber&&(o+="C"),o+="s",o}case"*":{let o=Number.parseInt(e.state.env.get("#")||"0",10);if(o===0)return"";let a=[];for(let l=1;l<=o;l++)a.push(e.state.env.get(String(l))||"");return a.join(K(e.state.env))}case"0":return e.state.env.get("0")||"bash";case"PWD":return e.state.env.get("PWD")??"";case"OLDPWD":return e.state.env.get("OLDPWD")??"";case"PPID":return String(e.state.virtualPpid);case"UID":return String(e.state.virtualUid);case"EUID":return String(e.state.virtualUid);case"RANDOM":return String(Math.floor(Math.random()*32768));case"SECONDS":return String(Math.floor((Date.now()-e.state.startTime)/1e3));case"BASH_VERSION":return Oa;case"!":return String(e.state.lastBackgroundPid);case"BASHPID":return String(e.state.bashPid);case"LINENO":return String(e.state.currentLine);case"FUNCNAME":{let o=e.state.funcNameStack?.[0];if(o!==void 0)return o;if(n&&e.state.options.nounset)throw new Ve("FUNCNAME");return""}case"BASH_LINENO":{let o=e.state.callLineStack?.[0];if(o!==void 0)return String(o);if(n&&e.state.options.nounset)throw new Ve("BASH_LINENO");return""}case"BASH_SOURCE":{let o=e.state.sourceStack?.[0];if(o!==void 0)return o;if(n&&e.state.options.nounset)throw new Ve("BASH_SOURCE");return""}}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[\]$/.test(t))throw new Ke(`\${${t}}`);let s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let o=s[1],a=s[2];if(ue(e,o)){let f=Fe(e,o);if(f&&f!==o){if(f.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/))return"";o=f}}if(a==="@"||a==="*"){let f=Q(e,o);if(f.length>0)return f.map(([,p])=>p).join(" ");let d=e.state.env.get(o);return d!==void 0?d:""}if(o==="FUNCNAME"){let f=Number.parseInt(a,10);return!Number.isNaN(f)&&f>=0?e.state.funcNameStack?.[f]??"":""}if(o==="BASH_LINENO"){let f=Number.parseInt(a,10);if(!Number.isNaN(f)&&f>=0){let d=e.state.callLineStack?.[f];return d!==void 0?String(d):""}return""}if(o==="BASH_SOURCE"){let f=Number.parseInt(a,10);return!Number.isNaN(f)&&f>=0?e.state.sourceStack?.[f]??"":""}if(e.state.associativeArrays?.has(o)){let f=Br(a);f=Ml(e,f);let d=le(e,o,f);if(d===void 0&&n&&e.state.options.nounset)throw new Ve(`${o}[${a}]`);return d||""}let c;if(/^-?\d+$/.test(a))c=Number.parseInt(a,10);else try{let f=new H,d=re(f,a);c=await Y(e,d.expression)}catch{let f=e.state.env.get(a);c=f?Number.parseInt(f,10):0,Number.isNaN(c)&&(c=0)}if(c<0){let f=Q(e,o),d=e.state.currentLine;if(f.length===0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${d}: ${o}: bad array subscript
|
|
98
|
+
`,"";let h=Math.max(...f.map(([E])=>typeof E=="number"?E:0))+1+c;return h<0?(e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${d}: ${o}: bad array subscript
|
|
99
|
+
`,""):le(e,o,h)||""}let u=le(e,o,c);if(u!==void 0)return u;if(c===0){let f=e.state.env.get(o);if(f!==void 0)return f}if(n&&e.state.options.nounset)throw new Ve(`${o}[${c}]`);return""}if(/^[1-9][0-9]*$/.test(t)){let o=e.state.env.get(t);if(o===void 0&&n&&e.state.options.nounset)throw new Ve(t);return o||""}if(ue(e,t)){let o=Fe(e,t);if(o===void 0)return"";if(o!==t)return await ie(e,o,n,r);let a=e.state.env.get(t);if((a===void 0||a==="")&&n&&e.state.options.nounset)throw new Ve(t);return a||""}let i=e.state.env.get(t);if(i!==void 0)return e.state.tempEnvBindings?.some(o=>o.has(t))&&(e.state.accessedTempEnvVars=e.state.accessedTempEnvVars||new Set,e.state.accessedTempEnvVars.add(t)),i;if(pt(e,t)){let o=le(e,t,0);if(o!==void 0)return o;if(n&&e.state.options.nounset)throw new Ve(t);return""}if(n&&e.state.options.nounset)throw new Ve(t);return""}async function St(e,t){if(new Set(["?","$","#","_","-","0","PPID","UID","EUID","RANDOM","SECONDS","BASH_VERSION","!","BASHPID","LINENO"]).has(t))return!0;if(t==="@"||t==="*")return Number.parseInt(e.state.env.get("#")||"0",10)>0;if(t==="PWD"||t==="OLDPWD")return e.state.env.has(t);let r=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(r){let s=r[1],i=r[2];if(ue(e,s)){let l=Fe(e,s);if(l&&l!==s){if(l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/))return!1;s=l}}if(i==="@"||i==="*")return Q(e,s).length>0?!0:e.state.env.has(s);if(e.state.associativeArrays?.has(s)){let l=Ml(e,Br(i));return Ut(e,s,l)}let a;if(/^-?\d+$/.test(i))a=Number.parseInt(i,10);else try{let l=new H,c=re(l,i);a=await Y(e,c.expression)}catch{let l=e.state.env.get(i);a=l?Number.parseInt(l,10):0,Number.isNaN(a)&&(a=0)}if(a<0){let l=Q(e,s);if(l.length===0)return!1;let u=Math.max(...l.map(([f])=>typeof f=="number"?f:0))+1+a;return u<0?!1:Ut(e,s,u)}return Ut(e,s,a)}if(ue(e,t)){let s=Fe(e,t);return s===void 0||s===t?e.state.env.has(t):St(e,s)}return e.state.env.has(t)?!0:pt(e,t)?Ut(e,t,0):!1}async function Fl(e,t){let n="",r=0;for(;r<t.length;){if(t[r]==="$"){if(t[r+1]==="{"){let s=1,i=r+2;for(;i<t.length&&s>0;)t[i]==="{"?s++:t[i]==="}"&&s--,i++;n+=t.slice(r,i),r=i;continue}if(t[r+1]==="("){let s=1,i=r+2;for(;i<t.length&&s>0;)t[i]==="("?s++:t[i]===")"&&s--,i++;n+=t.slice(r,i),r=i;continue}if(/[a-zA-Z_]/.test(t[r+1]||"")){let s=r+1;for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)s++;let i=t.slice(r+1,s),o=await ie(e,i);n+=o,r=s;continue}if(/[0-9]/.test(t[r+1]||"")){let s=r+1;for(;s<t.length&&/[0-9]/.test(t[s]);)s++;let i=t.slice(r+1,s),o=await ie(e,i);n+=o,r=s;continue}if(/[*@#?\-!$]/.test(t[r+1]||"")){let s=t[r+1],i=await ie(e,s);n+=i,r+=2;continue}}if(t[r]==='"'){for(n+='"',r++;r<t.length&&t[r]!=='"';)if(t[r]==="$"&&/[a-zA-Z_]/.test(t[r+1]||"")){let s=r+1;for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)s++;let i=t.slice(r+1,s),o=await ie(e,i);n+=o,r=s}else t[r]==="\\"?(n+=t[r],r++,r<t.length&&(n+=t[r],r++)):(n+=t[r],r++);r<t.length&&(n+='"',r++);continue}n+=t[r],r++}return n}async function Li(e,t){let n=t,r=t.startsWith('"')&&t.endsWith('"'),s=t.startsWith("'")&&t.endsWith("'");if((r||s)&&(n=t.slice(1,-1)),s)return n;let i="",o=0;for(;o<n.length;)if(n[o]==="$")if(n[o+1]==="("){let a=1,l=o+2;for(;l<n.length&&a>0;)n[l]==="("&&n[l-1]==="$"||n[l]==="("?a++:n[l]===")"&&a--,l++;let c=n.slice(o+2,l-1);if(e.execFn){let u=await e.execFn(c,{signal:e.state.signal});i+=u.stdout.replace(/\n+$/,""),u.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+u.stderr)}o=l}else if(n[o+1]==="{"){let a=1,l=o+2;for(;l<n.length&&a>0;)n[l]==="{"?a++:n[l]==="}"&&a--,l++;let c=n.slice(o+2,l-1),u=await ie(e,c);i+=u,o=l}else if(/[a-zA-Z_]/.test(n[o+1]||"")){let a=o+1;for(;a<n.length&&/[a-zA-Z0-9_]/.test(n[a]);)a++;let l=n.slice(o+1,a),c=await ie(e,l);i+=c,o=a}else i+=n[o],o++;else if(n[o]==="`"){let a=o+1;for(;a<n.length&&n[a]!=="`";)a++;let l=n.slice(o+1,a);if(e.execFn){let c=await e.execFn(l,{signal:e.state.signal});i+=c.stdout.replace(/\n+$/,""),c.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+c.stderr)}o=a+1}else i+=n[o],o++;return i}var dr=1e4,Mi={maxResults:dr,maxStringBytes:10*1024*1024};function Jr(e,t,n,r){if(e.length>=n.maxResults)return!1;let s=B(t);if(s>n.maxStringBytes-r.value)throw new x(`brace expansion string limit exceeded (${n.maxStringBytes} bytes)`,"string_length");return e.push(t),r.value+=s,!0}function mp(e,t,n,r,s,i=Mi){let o=n??1;o===0&&(o=1);let a=Math.abs(o),l=[],c=0;if(r?.match(/^-?0\d/)&&(c=Math.max(c,r.replace(/^-/,"").length)),s?.match(/^-?0\d/)&&(c=Math.max(c,s.replace(/^-/,"").length)),c>i.maxStringBytes)throw new x(`brace expansion padding limit exceeded (${i.maxStringBytes} bytes)`,"string_length");let u={value:0},f=d=>{if(c>0){let p=d<0,h=String(Math.abs(d)).padStart(c,"0");return p?`-${h}`:h}return String(d)};if(e<=t)for(let d=e,p=0;d<=t&&p<dr&&Jr(l,f(d),i,u);d+=a,p++);else for(let d=e,p=0;d>=t&&p<dr&&Jr(l,f(d),i,u);d-=a,p++);return l}function yp(e,t,n,r=Mi){let s=n??1;s===0&&(s=1);let i=e.charCodeAt(0),o=t.charCodeAt(0),a=Math.abs(s),l=e>="A"&&e<="Z",c=e>="a"&&e<="z",u=t>="A"&&t<="Z",f=t>="a"&&t<="z";if(l&&f||c&&u){let h=n!==void 0?`..${n}`:"";throw new Rr(`{${e}..${t}${h}}: invalid sequence`)}let d=[],p={value:0};if(i<=o)for(let h=i,m=0;h<=o&&m<dr&&Jr(d,String.fromCharCode(h),r,p);h+=a,m++);else for(let h=i,m=0;h>=o&&m<dr&&Jr(d,String.fromCharCode(h),r,p);h-=a,m++);return d}function Fi(e,t,n,r,s,i=Mi){let o=n!==void 0?`..${n}`:"";return typeof e=="number"&&typeof t=="number"?{expanded:mp(e,t,n,r,s,i),literal:`{${e}..${t}${o}}`}:typeof e=="string"&&typeof t=="string"?{expanded:yp(e,t,n,i),literal:`{${e}..${t}${o}}`}:{expanded:null,literal:`{${e}..${t}${o}}`}}function Bl(e){if(e.statements.length!==1)return null;let t=e.statements[0];if(t.operators.length!==0||t.pipelines.length!==1)return null;let n=t.pipelines[0];if(n.negated||n.commands.length!==1)return null;let r=n.commands[0];if(r.type!=="SimpleCommand")return null;let s=r;if(s.name!==null||s.args.length!==0||s.assignments.length!==0||s.redirections.length!==1)return null;let i=s.redirections[0];return i.operator!=="<"||i.target.type!=="Word"?null:{target:i.target}}function At(e,t){return!!(/[*?[]/.test(e)||t&&/[@*+?!]\(/.test(e))}function Bi(e){let t="",n=0;for(;n<e.length;)e[n]==="\\"&&n+1<e.length?(t+=e[n+1],n+=2):(t+=e[n],n++);return t}function Je(e){return e.replace(/([*?[\]\\()|])/g,"\\$1")}function Dn(e){return e.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&")}function te(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function J(e,t,n=!1){let r="",s=0;for(;s<e.length;){let i=e[s];if(n&&(i==="@"||i==="*"||i==="+"||i==="?"||i==="!")&&s+1<e.length&&e[s+1]==="("){let o=gp(e,s+1);if(o!==-1){let a=e.slice(s+2,o),c=wp(a).map(f=>J(f,t,n)),u=c.length>0?c.join("|"):"(?:)";i==="@"?r+=`(?:${u})`:i==="*"?r+=`(?:${u})*`:i==="+"?r+=`(?:${u})+`:i==="?"?r+=`(?:${u})?`:i==="!"&&(r+=`(?!(?:${u})$).*`),s=o+1;continue}}if(i==="\\")if(s+1<e.length){let o=e[s+1];/[\\^$.|+(){}[\]*?]/.test(o)?r+=`\\${o}`:r+=o,s+=2}else r+="\\\\",s++;else if(i==="*")r+=t?".*":".*?",s++;else if(i==="?")r+=".",s++;else if(i==="["){let o=Ep(e,s);if(o===-1)r+="\\[",s++;else{let a=e.slice(s+1,o);r+=bp(a),s=o+1}}else/[\^$.|+(){}]/.test(i)?(r+=`\\${i}`,s++):(r+=i,s++)}return r}function gp(e,t){let n=1,r=t+1;for(;r<e.length&&n>0;){let s=e[r];if(s==="\\"){r+=2;continue}if(s==="(")n++;else if(s===")"&&(n--,n===0))return r;r++}return-1}function wp(e){let t=[],n="",r=0,s=0;for(;s<e.length;){let i=e[s];if(i==="\\"){n+=i,s+1<e.length?(n+=e[s+1],s+=2):s++;continue}i==="("?(r++,n+=i):i===")"?(r--,n+=i):i==="|"&&r===0?(t.push(n),n=""):n+=i,s++}return t.push(n),t}function Ep(e,t){let n=t+1;for(n<e.length&&e[n]==="^"&&n++,n<e.length&&e[n]==="]"&&n++;n<e.length;){if(e[n]==="\\"&&n+1<e.length){n+=2;continue}if(e[n]==="]")return n;if(e[n]==="'"){let r=e.indexOf("'",n+1);if(r!==-1){n=r+1;continue}}if(e[n]==="["&&n+1<e.length&&e[n+1]===":"){let r=e.indexOf(":]",n+2);if(r!==-1){n=r+2;continue}}n++}return-1}function bp(e){let t="[",n=0;for((e[0]==="^"||e[0]==="!")&&(t+="^",n++);n<e.length;){if(e[n]==="'"){let s=e.indexOf("'",n+1);if(s!==-1){let i=e.slice(n+1,s);for(let o of i)o==="\\"?t+="\\\\":o==="]"?t+="\\]":o==="^"&&t==="["?t+="\\^":t+=o;n=s+1;continue}}if(e[n]==="["&&n+1<e.length&&e[n+1]===":"){let s=e.indexOf(":]",n+2);if(s!==-1){let i=e.slice(n+2,s);t+=Ap(i),n=s+2;continue}}let r=e[n];r==="\\"?n+1<e.length?(t+=`\\${e[n+1]}`,n+=2):(t+="\\\\",n++):r==="-"&&n>0&&n<e.length-1?(t+="-",n++):r==="^"&&n===0?(t+="^",n++):(r==="]"&&n===0?t+="\\]":t+=r,n++)}return t+="]",t}var Sp=new Map([["alnum","a-zA-Z0-9"],["alpha","a-zA-Z"],["ascii","\\x00-\\x7F"],["blank"," \\t"],["cntrl","\\x00-\\x1F\\x7F"],["digit","0-9"],["graph","!-~"],["lower","a-z"],["print"," -~"],["punct","!-/:-@\\[-`{-~"],["space"," \\t\\n\\r\\f\\v"],["upper","A-Z"],["word","a-zA-Z0-9_"],["xdigit","0-9A-Fa-f"]]);function Ap(e){return Sp.get(e)??""}function ht(e,t,n,r,s){if(r==="prefix")return e.executionScope.consumeLimited("pattern-removal",Math.max(1,t.length),e.limits.maxGlobOperations,"pattern removal"),ge(`^${n}`,"s").replace(t,"");let i=ge(`${n}$`,"s");if(s)return e.executionScope.consumeLimited("pattern-removal",Math.max(1,t.length),e.limits.maxGlobOperations,"pattern removal"),i.replace(t,"");e.executionScope.consumeLimited("pattern-removal",Math.max(1,t.length),e.limits.maxGlobOperations,"pattern removal");let o=ge(`^(?:.*)(${n})$`,"s").exec(t);if(!o)return t;let a=o[1]??"";return t.slice(0,t.length-a.length)}function In(e,t){let n=new Set;for(let r of e.state.env.keys())r.startsWith(t)&&n.add(r);for(let r of e.state.arrays?.keys()??[])r.startsWith(t)&&n.add(r);return[...n].sort()}function es(e,t,n,r,s){let i=new Pn(e.limits.maxStringLength,"pattern replacement",()=>new x(`pattern replacement: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length"));n.lastIndex=0;let o=0,a=n.exec(t);for(;a!==null&&(e.executionScope.consumeLimited("pattern_operations",1,e.limits.maxGlobOperations,"pattern replacement"),!(s&&a[0].length===0&&a.index===t.length||(i.append(t.slice(o,a.index)),i.append(r),o=a.index+a[0].length,!s)));)a[0].length===0&&(o++,n.lastIndex<=a.index&&(n.lastIndex=a.index+1)),a=n.exec(t);return i.append(t.slice(o)),n.lastIndex=0,i.build()}function Wl(e){let t=[],n=0;return{append(r){let s=B(r);if(s>e-n)throw new x(`prompt expansion exceeds string length limit (${e} bytes)`,"string_length");r&&t.push(r),n+=s},build:()=>t.join("")}}function vp(e,t,n){let r=(o,a=2)=>String(o).padStart(a,"0");if(e===""){let o=r(t.getHours()),a=r(t.getMinutes()),l=r(t.getSeconds());return`${o}:${a}:${l}`}let s=Wl(n),i=0;for(;i<e.length;)if(e[i]==="%"){if(i+1>=e.length){s.append("%"),i++;continue}let o=e[i+1];switch(o){case"H":s.append(r(t.getHours()));break;case"M":s.append(r(t.getMinutes()));break;case"S":s.append(r(t.getSeconds()));break;case"d":s.append(r(t.getDate()));break;case"m":s.append(r(t.getMonth()+1));break;case"Y":s.append(String(t.getFullYear()));break;case"y":s.append(r(t.getFullYear()%100));break;case"I":{let a=t.getHours()%12;a===0&&(a=12),s.append(r(a));break}case"p":s.append(t.getHours()<12?"AM":"PM");break;case"P":s.append(t.getHours()<12?"am":"pm");break;case"%":s.append("%");break;case"a":{let a=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];s.append(a[t.getDay()]);break}case"b":{let a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];s.append(a[t.getMonth()]);break}default:s.append(`%${o}`)}i+=2}else s.append(e[i]),i++;return s.build()}function pr(e,t){let n=Wl(e.limits.maxStringLength),r=0,s=e.state.env.get("USER")||e.state.env.get("LOGNAME")||"user",i=e.state.env.get("HOSTNAME")||"localhost",o=i.split(".")[0],a=e.state.env.get("PWD")||"/",l=e.state.env.get("HOME")||"/",c=a.startsWith(l)?`~${a.slice(l.length)}`:a,u=a.split("/").pop()||a,f=new Date,d=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],p=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],h=e.state.env.get("__COMMAND_NUMBER")||"1";for(;r<t.length;){let m=t[r];if(m==="\\"){if(r+1>=t.length){n.append("\\"),r++;continue}let E=t[r+1];if(E>="0"&&E<="7"){let b="",g=r+1;for(;g<t.length&&g<r+4&&t[g]>="0"&&t[g]<="7";)b+=t[g],g++;let y=Number.parseInt(b,8)%256;n.append(String.fromCharCode(y)),r=g;continue}switch(E){case"\\":n.append("\\"),r+=2;break;case"a":n.append("\x07"),r+=2;break;case"e":n.append("\x1B"),r+=2;break;case"n":n.append(`
|
|
100
|
+
`),r+=2;break;case"r":n.append("\r"),r+=2;break;case"$":n.append("$"),r+=2;break;case"[":case"]":r+=2;break;case"u":n.append(s),r+=2;break;case"h":n.append(o),r+=2;break;case"H":n.append(i),r+=2;break;case"w":n.append(c),r+=2;break;case"W":n.append(u),r+=2;break;case"d":{let b=String(f.getDate()).padStart(2," ");n.append(`${d[f.getDay()]} ${p[f.getMonth()]} ${b}`),r+=2;break}case"t":{let b=String(f.getHours()).padStart(2,"0"),g=String(f.getMinutes()).padStart(2,"0"),y=String(f.getSeconds()).padStart(2,"0");n.append(`${b}:${g}:${y}`),r+=2;break}case"T":{let b=f.getHours()%12;b===0&&(b=12);let g=String(b).padStart(2,"0"),y=String(f.getMinutes()).padStart(2,"0"),S=String(f.getSeconds()).padStart(2,"0");n.append(`${g}:${y}:${S}`),r+=2;break}case"@":{let b=f.getHours()%12;b===0&&(b=12);let g=String(b).padStart(2,"0"),y=String(f.getMinutes()).padStart(2,"0"),S=f.getHours()<12?"AM":"PM";n.append(`${g}:${y} ${S}`),r+=2;break}case"A":{let b=String(f.getHours()).padStart(2,"0"),g=String(f.getMinutes()).padStart(2,"0");n.append(`${b}:${g}`),r+=2;break}case"D":if(r+2<t.length&&t[r+2]==="{"){let b=t.indexOf("}",r+3);if(b!==-1){let g=t.slice(r+3,b);n.append(vp(g,f,e.limits.maxStringLength)),r=b+1}else n.append("\\D"),r+=2}else n.append("\\D"),r+=2;break;case"s":n.append("bash"),r+=2;break;case"v":n.append("5.0"),r+=2;break;case"V":n.append("5.0.0"),r+=2;break;case"j":n.append("0"),r+=2;break;case"l":n.append("tty"),r+=2;break;case"#":n.append(h),r+=2;break;case"!":n.append(h),r+=2;break;case"x":n.append("\\x"),r+=2;break;default:n.append(`\\${E}`),r+=2}}else n.append(m),r++}return n.build()}function Zt(e){if(e==="")return"''";if(/[\n\r\t\x00-\x1f\x7f']/.test(e)){let n="$'";for(let r of e)switch(r){case"'":n+="\\'";break;case"\\":n+="\\\\";break;case`
|
|
101
|
+
`:n+="\\n";break;case"\r":n+="\\r";break;case" ":n+="\\t";break;default:{let s=r.charCodeAt(0);s<32||s===127?n+=`\\${s.toString(8).padStart(3,"0")}`:n+=r}}return`${n}'`}return`'${e}'`}function Ze(e,t){e.state.readonlyVars=e.state.readonlyVars||new Set,e.state.readonlyVars.add(t)}function Be(e,t){return e.state.readonlyVars?.has(t)??!1}function fe(e,t,n="bash"){if(Be(e,t)){let r=`${n}: ${t}: readonly variable
|
|
102
|
+
`;throw new j(1,"",r)}return null}function mt(e,t){let n=e.state.exportedVars?.has(t)??!1;if(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(t),e.state.localScopes.length>0&&e.state.localScopes[e.state.localScopes.length-1].has(t)&&!n){for(e.state.localExportedVars||(e.state.localExportedVars=[]);e.state.localExportedVars.length<e.state.localScopes.length;)e.state.localExportedVars.push(new Set);e.state.localExportedVars[e.state.localExportedVars.length-1].add(t)}}function ts(e,t){e.state.exportedVars?.delete(t)}function Ht(e,t){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t))return"";let n="",r=Pe(e,t)?.kind==="indexed",s=e.state.associativeArrays?.has(t)??!1;return r&&!s&&(n+="a"),s&&(n+="A"),e.state.integerVars?.has(t)&&(n+="i"),ue(e,t)&&(n+="n"),Be(e,t)&&(n+="r"),e.state.exportedVars?.has(t)&&(n+="x"),n}async function Vl(e,t,n,r){return e.coverage?.hit("bash:expansion:default_value"),(n.isUnset||t.checkEmpty&&n.isEmpty)&&t.word?r(e,t.word.parts,n.inDoubleQuotes):n.effectiveValue}async function zl(e,t,n,r,s){if(e.coverage?.hit("bash:expansion:assign_default"),(r.isUnset||n.checkEmpty&&r.isEmpty)&&n.word){let o=await s(e,n.word.parts,r.inDoubleQuotes),a=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(a){let[,l,c]=a,u;if(/^\d+$/.test(c))u=Number.parseInt(c,10);else{try{let f=new H,d=re(f,c);u=await Y(e,d.expression)}catch{let f=e.state.env.get(c);u=f?Number.parseInt(f,10):0}Number.isNaN(u)&&(u=0)}G(e,l,u,o)}else e.state.env.set(t,o);return o}return r.effectiveValue}async function Ul(e,t,n,r,s){if(e.coverage?.hit("bash:expansion:error_if_unset"),r.isUnset||n.checkEmpty&&r.isEmpty){let o=n.word?await s(e,n.word.parts,r.inDoubleQuotes):`${t}: parameter null or not set`;throw new j(1,"",`bash: ${o}
|
|
103
|
+
`)}return r.effectiveValue}async function ql(e,t,n,r){return e.coverage?.hit("bash:expansion:use_alternative"),!(n.isUnset||t.checkEmpty&&n.isEmpty)&&t.word?r(e,t.word.parts,n.inDoubleQuotes):""}async function jl(e,t,n,r,s){e.coverage?.hit("bash:expansion:pattern_removal");let i="",o=e.state.shoptOptions.extglob;if(n.pattern)for(let a of n.pattern.parts)if(a.type==="Glob")i+=J(a.pattern,n.greedy,o);else if(a.type==="Literal")i+=J(a.value,n.greedy,o);else if(a.type==="SingleQuoted"||a.type==="Escaped")i+=te(a.value);else if(a.type==="DoubleQuoted"){let l=await r(e,a.parts);i+=te(l)}else if(a.type==="ParameterExpansion"){let l=await s(e,a);i+=J(l,n.greedy,o)}else{let l=await s(e,a);i+=te(l)}return ht(e,t,i,n.side,n.greedy)}async function Gl(e,t,n,r,s){e.coverage?.hit("bash:expansion:pattern_replacement");let i="",o=e.state.shoptOptions.extglob;if(n.pattern)for(let c of n.pattern.parts)if(c.type==="Glob")i+=J(c.pattern,!0,o);else if(c.type==="Literal")i+=J(c.value,!0,o);else if(c.type==="SingleQuoted"||c.type==="Escaped")i+=te(c.value);else if(c.type==="DoubleQuoted"){let u=await r(e,c.parts);i+=te(u)}else if(c.type==="ParameterExpansion"){let u=await s(e,c);i+=J(u,!0,o)}else{let u=await s(e,c);i+=te(u)}let a=n.replacement?await r(e,n.replacement.parts):"";if(n.anchor==="start"?i=`^${i}`:n.anchor==="end"&&(i=`${i}$`),i==="")return t;let l=n.all?"gs":"s";try{let c=ge(i,l);return es(e,t,c,a,n.all)}catch(c){if(c instanceof x)throw c;return t}}function Zl(e,t,n){e.coverage?.hit("bash:expansion:length");let r=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(r){let s=r[1],i=Q(e,s);return i.length>0?String(i.length):e.state.env.get(s)!==void 0?"1":"0"}if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&pt(e,t)){if(t==="FUNCNAME"){let i=e.state.funcNameStack?.[0]||"";return String([...i].length)}if(t==="BASH_LINENO"){let i=e.state.callLineStack?.[0];return String(i!==void 0?[...String(i)].length:0)}let s=le(e,t,0)||"";return String([...s].length)}return String([...n].length)}async function Hl(e,t,n,r){e.coverage?.hit("bash:expansion:substring");let s=await Y(e,r.offset.expression),i=r.length?await Y(e,r.length.expression):void 0;if(t==="@"||t==="*"){let c=Number.parseInt(e.state.env.get("#")||"0",10),u=[];for(let h=1;h<=c;h++)u.push(e.state.env.get(String(h))||"");let f=e.state.env.get("0")||"bash",d,p;if(s<=0)if(d=[f,...u],s<0){if(p=d.length+s,p<0)return""}else p=0;else d=u,p=s-1;if(p<0||p>=d.length)return"";if(i!==void 0){let h=i<0?d.length+i:p+i;return d.slice(p,Math.max(p,h)).join(" ")}return d.slice(p).join(" ")}let o=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(o){let c=o[1];if(e.state.associativeArrays?.has(c))throw new j(1,"",`bash: \${${c}[@]: 0: 3}: bad substitution
|
|
104
|
+
`);let u=Q(e,c),f=0;if(s<0){if(u.length>0){let d=u[u.length-1][0],h=(typeof d=="number"?d:0)+1+s;if(h<0||(f=u.findIndex(([m])=>typeof m=="number"&&m>=h),f<0))return""}}else if(f=u.findIndex(([d])=>typeof d=="number"&&d>=s),f<0)return"";if(i!==void 0){if(i<0)throw new ce(`${o[1]}[@]: substring expression < 0`);return u.slice(f,f+i).map(([,d])=>d).join(" ")}return u.slice(f).map(([,d])=>d).join(" ")}let a=[...n],l=s;if(l<0&&(l=Math.max(0,a.length+l)),i!==void 0){if(i<0){let c=a.length+i;return a.slice(l,Math.max(l,c)).join("")}return a.slice(l,l+i).join("")}return a.slice(l).join("")}async function Ql(e,t,n,r,s){if(e.coverage?.hit("bash:expansion:case_modification"),n.pattern){let i=e.state.shoptOptions.extglob,o="";for(let f of n.pattern.parts)if(f.type==="Glob")o+=J(f.pattern,!0,i);else if(f.type==="Literal")o+=J(f.value,!0,i);else if(f.type==="SingleQuoted"||f.type==="Escaped")o+=te(f.value);else if(f.type==="DoubleQuoted"){let d=await r(e,f.parts);o+=te(d)}else if(f.type==="ParameterExpansion"){let d=await s(e,f);o+=J(d,!0,i)}let a=ge(`^(?:${o})$`),l=n.direction==="upper"?f=>f.toUpperCase():f=>f.toLowerCase(),c="",u=!1;for(let f of t)!n.all&&u?c+=f:a.test(f)?(c+=l(f),u=!0):c+=f;return c}return n.direction==="upper"?n.all?t.toUpperCase():t.charAt(0).toUpperCase()+t.slice(1):n.all?t.toLowerCase():t.charAt(0).toLowerCase()+t.slice(1)}function Kl(e,t,n,r,s){e.coverage?.hit("bash:expansion:transform");let i=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(i&&s.operator==="Q")return Q(e,i[1]).map(([,c])=>Zt(c)).join(" ");if(i&&s.operator==="a")return Ht(e,i[1]);let o=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[.+\]$/);if(o&&s.operator==="a")return Ht(e,o[1]);switch(s.operator){case"Q":return r?"":Zt(n);case"P":return pr(e,n);case"a":return Ht(e,t);case"A":return r?"":`${t}=${Zt(n)}`;case"E":return n.replace(/\\([\\abefnrtv'"?])/g,(a,l)=>{switch(l){case"\\":return"\\";case"a":return"\x07";case"b":return"\b";case"e":return"\x1B";case"f":return"\f";case"n":return`
|
|
105
|
+
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"'":return"'";case'"':return'"';case"?":return"?";default:return l}});case"K":case"k":return r?"":Zt(n);case"u":return n.charAt(0).toUpperCase()+n.slice(1);case"U":return n.toUpperCase();case"L":return n.toLowerCase();default:return n}}async function Xl(e,t,n,r,s,i,o=!1){if(e.coverage?.hit("bash:expansion:indirection"),ue(e,t))return En(e,t)||"";let a=/^[a-zA-Z_][a-zA-Z0-9_]*\[([@*])\]$/.test(t);if(r){if(s.innerOp?.type==="UseAlternative")return"";throw new Ke(`\${!${t}}`)}let l=n;if(a&&(l===""||l.includes(" ")))throw new Ke(`\${!${t}}`);let c=l.match(/^[a-zA-Z_][a-zA-Z0-9_]*\[(.+)\]$/);if(c&&c[1].includes("~"))throw new Ke(`\${!${t}}`);if(s.innerOp){let u={type:"ParameterExpansion",parameter:l,operation:s.innerOp};return i(e,u,o)}return await ie(e,l)}function Yl(e,t){e.coverage?.hit("bash:expansion:array_keys");let r=Q(e,t.array).map(([s])=>String(s));return t.star?r.join(K(e.state.env)):r.join(" ")}function Jl(e,t){e.coverage?.hit("bash:expansion:var_name_prefix");let n=In(e,t.prefix);return t.star?n.join(K(e.state.env)):n.join(" ")}function ec(e,t,n,r){let s=Number.parseInt(e.state.env.get("#")||"0",10),i=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(t==="*")return{isEmpty:s===0,effectiveValue:n};if(t==="@")return{isEmpty:s===0||s===1&&e.state.env.get("1")==="",effectiveValue:n};if(i){let[,o,a]=i,l=Q(e,o);if(l.length===0)return{isEmpty:!0,effectiveValue:""};if(a==="*"){let c=K(e.state.env),u=l.map(([,f])=>f).join(c);return{isEmpty:r?u==="":!1,effectiveValue:u}}return{isEmpty:l.length===1&&l.every(([,c])=>c===""),effectiveValue:l.map(([,c])=>c).join(" ")}}return{isEmpty:n==="",effectiveValue:n}}function tc(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="\\"&&t+1<e.length){t+=2;continue}if(n==="'"){let r=e.indexOf("'",t+1);if(r!==-1){t=r+1;continue}}if(n==="$"&&t+1<e.length&&e[t+1]==="("||n==="`")return!0;t++}return!1}function nc(e,t){let n=1,r=t,s=!1,i=!1;for(;r<e.length&&n>0;){let o=e[r];if(o==="\\"&&!s&&r+1<e.length){r+=2;continue}if(o==="'"&&!i){s=!s,r++;continue}if(o==='"'&&!s){i=!i,r++;continue}if(!s&&!i){if(o==="(")n++;else if(o===")"&&(n--,n===0))return r}r++}return-1}async function ns(e,t){let n=new H,r;try{r=n.parse(t)}catch{return""}let s=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let i=new Map(e.state.env),o=ot(e.state.arrays),a=e.state.cwd,l=e.state.suppressVerbose;e.state.suppressVerbose=!0;try{let c=await e.executeScript(r),u=c.exitCode;return e.state.env=i,e.state.arrays=o,e.state.cwd=a,e.state.suppressVerbose=l,e.state.lastExitCode=u,e.state.env.set("?",String(u)),c.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+c.stderr),e.state.bashPid=s,c.stdout.replace(/\n+$/,"")}catch(c){if(e.state.env=i,e.state.arrays=o,e.state.cwd=a,e.state.bashPid=s,e.state.suppressVerbose=l,c instanceof x)throw c;return c instanceof j?(e.state.lastExitCode=c.exitCode,e.state.env.set("?",String(c.exitCode)),c.stdout?.replace(/\n+$/,"")??""):""}}function Wi(e,t){let n="",r=0;for(;r<t.length;){let s=t[r];if(s==="'"){let i=t.indexOf("'",r+1);if(i!==-1){let o=t.slice(r+1,i);n+=Je(o),r=i+1;continue}}if(s==='"'){let i=-1,o=r+1;for(;o<t.length;){if(t[o]==="\\"){o+=2;continue}if(t[o]==='"'){i=o;break}o++}if(i!==-1){let a=t.slice(r+1,i),l=kp(e,a);n+=Je(l),r=i+1;continue}}if(s==="$"&&r+1<t.length){let i=t[r+1];if(i==="{"){let o=t.indexOf("}",r+2);if(o!==-1){let a=t.slice(r+2,o);n+=e.state.env.get(a)??"",r=o+1;continue}}else if(/[a-zA-Z_]/.test(i)){let o=r+1;for(;o<t.length&&/[a-zA-Z0-9_]/.test(t[o]);)o++;let a=t.slice(r+1,o);n+=e.state.env.get(a)??"",r=o;continue}}if(s==="\\"&&r+1<t.length){n+=s+t[r+1],r+=2;continue}n+=s,r++}return n}function kp(e,t){let n="",r=0;for(;r<t.length;){let s=t[r];if(s==="\\"&&r+1<t.length){let i=t[r+1];if(i==="$"||i==="`"||i==="\\"||i==='"'){n+=i,r+=2;continue}n+=s,r++;continue}if(s==="$"&&r+1<t.length){let i=t[r+1];if(i==="{"){let o=t.indexOf("}",r+2);if(o!==-1){let a=t.slice(r+2,o);n+=e.state.env.get(a)??"",r=o+1;continue}}else if(/[a-zA-Z_]/.test(i)){let o=r+1;for(;o<t.length&&/[a-zA-Z0-9_]/.test(t[o]);)o++;let a=t.slice(r+1,o);n+=e.state.env.get(a)??"",r=o;continue}}n+=s,r++}return n}async function rc(e,t){let n="",r=0;for(;r<t.length;){let s=t[r];if(s==="'"){let i=t.indexOf("'",r+1);if(i!==-1){let o=t.slice(r+1,i);n+=Je(o),r=i+1;continue}}if(s==='"'){let i=-1,o=r+1;for(;o<t.length;){if(t[o]==="\\"){o+=2;continue}if(t[o]==='"'){i=o;break}o++}if(i!==-1){let a=t.slice(r+1,i),l=await Pp(e,a);n+=Je(l),r=i+1;continue}}if(s==="$"&&r+1<t.length&&t[r+1]==="("){let i=nc(t,r+2);if(i!==-1){let o=t.slice(r+2,i),a=await ns(e,o);n+=a,r=i+1;continue}}if(s==="`"){let i=t.indexOf("`",r+1);if(i!==-1){let o=t.slice(r+1,i),a=await ns(e,o);n+=a,r=i+1;continue}}if(s==="$"&&r+1<t.length){let i=t[r+1];if(i==="{"){let o=t.indexOf("}",r+2);if(o!==-1){let a=t.slice(r+2,o);n+=e.state.env.get(a)??"",r=o+1;continue}}else if(/[a-zA-Z_]/.test(i)){let o=r+1;for(;o<t.length&&/[a-zA-Z0-9_]/.test(t[o]);)o++;let a=t.slice(r+1,o);n+=e.state.env.get(a)??"",r=o;continue}}if(s==="\\"&&r+1<t.length){n+=s+t[r+1],r+=2;continue}n+=s,r++}return n}async function Pp(e,t){let n="",r=0;for(;r<t.length;){let s=t[r];if(s==="\\"&&r+1<t.length){let i=t[r+1];if(i==="$"||i==="`"||i==="\\"||i==='"'){n+=i,r+=2;continue}n+=s,r++;continue}if(s==="$"&&r+1<t.length&&t[r+1]==="("){let i=nc(t,r+2);if(i!==-1){let o=t.slice(r+2,i),a=await ns(e,o);n+=a,r=i+1;continue}}if(s==="`"){let i=t.indexOf("`",r+1);if(i!==-1){let o=t.slice(r+1,i),a=await ns(e,o);n+=a,r=i+1;continue}}if(s==="$"&&r+1<t.length){let i=t[r+1];if(i==="{"){let o=t.indexOf("}",r+2);if(o!==-1){let a=t.slice(r+2,o);n+=e.state.env.get(a)??"",r=o+1;continue}}else if(/[a-zA-Z_]/.test(i)){let o=r+1;for(;o<t.length&&/[a-zA-Z0-9_]/.test(t[o]);)o++;let a=t.slice(r+1,o);n+=e.state.env.get(a)??"",r=o;continue}}n+=s,r++}return n}function Vi(e,t){if(!t.startsWith("~"))return t;e.coverage?.hit("bash:expansion:tilde");let n=e.state.env.get("HOME")!==void 0?e.state.env.get("HOME"):"/home/user";if(t==="~"||t.startsWith("~/"))return n+t.slice(1);let r=1;for(;r<t.length&&/[a-zA-Z0-9_-]/.test(t[r]);)r++;let s=t.slice(1,r),i=t.slice(r);return i!==""&&!i.startsWith("/")?t:s==="root"?`/root${i}`:t}function Qt(e,t){return t.split(":").map(n=>Vi(e,n)).join(":")}function Oe(e,t,n,r){if(e.length>n-t.length)throw new x(`${r} element limit exceeded (${n})`,"array_elements");for(let s of t)e.push(s)}async function xp(e,t,n,r){let s="";for(let i of t.parts)if(i.type==="Glob")s+=J(i.pattern,!0,e.state.shoptOptions.extglob);else if(i.type==="Literal")s+=J(i.value,!0,e.state.shoptOptions.extglob);else if(i.type==="SingleQuoted"||i.type==="Escaped")s+=te(i.value);else if(i.type==="DoubleQuoted"){let o=await n(e,i.parts);s+=te(o)}else if(i.type==="ParameterExpansion"){let o=await r(e,i);s+=J(o,!0,e.state.shoptOptions.extglob)}else{let o=await r(e,i);s+=te(o)}return s}async function sc(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0];if(s.parts.length!==1||s.parts[0].type!=="ParameterExpansion"||s.parts[0].operation?.type!=="PatternReplacement")return null;let i=s.parts[0],o=i.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!o)return null;let a=o[1],l=o[2]==="*",c=i.operation,u=Q(e,a),f=u.map(([,E])=>E);if(u.length===0){let E=e.state.env.get(a);E!==void 0&&f.push(E)}if(f.length===0)return{values:[],quoted:!0};let d="";c.pattern&&(d=await xp(e,c.pattern,n,r));let p=c.replacement?await n(e,c.replacement.parts):"",h=d;c.anchor==="start"?h=`^${d}`:c.anchor==="end"&&(h=`${d}$`);let m=[];try{let E=ge(h,c.all?"g":"");for(let b of f)m.push(E.replace(b,p))}catch{m.push(...f)}if(l){let E=K(e.state.env);return{values:[m.join(E)],quoted:!0}}return{values:m,quoted:!0}}async function ic(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0];if(s.parts.length!==1||s.parts[0].type!=="ParameterExpansion"||s.parts[0].operation?.type!=="PatternRemoval")return null;let i=s.parts[0],o=i.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!o)return null;let a=o[1],l=o[2]==="*",c=i.operation,u=Q(e,a),f=u.map(([,m])=>m);if(u.length===0){let m=e.state.env.get(a);m!==void 0&&f.push(m)}if(f.length===0)return{values:[],quoted:!0};let d="",p=e.state.shoptOptions.extglob;if(c.pattern)for(let m of c.pattern.parts)if(m.type==="Glob")d+=J(m.pattern,c.greedy,p);else if(m.type==="Literal")d+=J(m.value,c.greedy,p);else if(m.type==="SingleQuoted"||m.type==="Escaped")d+=te(m.value);else if(m.type==="DoubleQuoted"){let E=await n(e,m.parts);d+=te(E)}else if(m.type==="ParameterExpansion"){let E=await r(e,m);d+=J(E,c.greedy,p)}else{let E=await r(e,m);d+=te(E)}let h=[];for(let m of f)h.push(ht(e,m,d,c.side,c.greedy));if(l){let m=K(e.state.env);return{values:[h.join(m)],quoted:!0}}return{values:h,quoted:!0}}async function oc(e,t){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!=="ParameterExpansion"||n.parts[0].operation?.type!=="DefaultValue"&&n.parts[0].operation?.type!=="UseAlternative"&&n.parts[0].operation?.type!=="AssignDefault")return null;let r=n.parts[0],s=r.operation,i=r.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/),o,a=!1;if(i){let l=i[1];a=i[2]==="*";let c=Q(e,l),u=c.length>0||e.state.env.has(l),f=c.length===0||c.length===1&&c.every(([,p])=>p===""),d=s.checkEmpty??!1;if(s.type==="UseAlternative"?o=u&&!(d&&f):o=!u||d&&f,!o){if(c.length>0){let h=c.map(([,m])=>m);if(a){let m=K(e.state.env);return{values:[h.join(m)],quoted:!0}}return{values:h,quoted:!0}}let p=e.state.env.get(l);return p!==void 0?{values:[p],quoted:!0}:{values:[],quoted:!0}}}else{let l=r.parameter,c=await St(e,l),u=await ie(e,l),f=u==="",d=s.checkEmpty??!1;if(s.type==="UseAlternative"?o=c&&!(d&&f):o=!c||d&&f,!o)return{values:[u],quoted:!0}}if(o&&s.word){let l=s.word.parts,c=null,u=!1;for(let f of l)if(f.type==="ParameterExpansion"&&!f.operation){let d=f.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(d){c=d[1],u=d[2]==="*";break}}if(c){let f=Q(e,c);if(f.length>0){let p=f.map(([,h])=>h);if(u||a){let h=K(e.state.env);return{values:[p.join(h)],quoted:!0}}return{values:p,quoted:!0}}let d=e.state.env.get(c);return d!==void 0?{values:[d],quoted:!0}:{values:[],quoted:!0}}}return null}async function ac(e,t,n,r,s){if(!n||t.length!==1||t[0].type!=="DoubleQuoted")return null;let i=t[0],o=-1,a="",l=!1,c=null;for(let m=0;m<i.parts.length;m++){let E=i.parts[m];if(E.type==="ParameterExpansion"&&(E.operation?.type==="PatternRemoval"||E.operation?.type==="PatternReplacement")){let b=E.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(b){o=m,a=b[1],l=b[2]==="*",c=E.operation;break}}}if(o===-1||o===0&&o===i.parts.length-1)return null;let u="";for(let m=0;m<o;m++)u+=await r(e,i.parts[m]);let f="";for(let m=o+1;m<i.parts.length;m++)f+=await r(e,i.parts[m]);let d=Q(e,a),p=d.map(([,m])=>m);if(d.length===0){let m=e.state.env.get(a);if(m!==void 0)p=[m];else{if(l)return{values:[u+f],quoted:!0};let E=u+f;return{values:E?[E]:[],quoted:!0}}}if(c?.type==="PatternRemoval"){let m=c,E="",b=e.state.shoptOptions.extglob;if(m.pattern)for(let g of m.pattern.parts)if(g.type==="Glob")E+=J(g.pattern,m.greedy,b);else if(g.type==="Literal")E+=J(g.value,m.greedy,b);else if(g.type==="SingleQuoted"||g.type==="Escaped")E+=te(g.value);else if(g.type==="DoubleQuoted"){let y=await s(e,g.parts);E+=te(y)}else if(g.type==="ParameterExpansion"){let y=await r(e,g);E+=J(y,m.greedy,b)}else{let y=await r(e,g);E+=te(y)}p=p.map(g=>ht(e,g,E,m.side,m.greedy))}else if(c?.type==="PatternReplacement"){let m=c,E="";if(m.pattern)for(let y of m.pattern.parts)if(y.type==="Glob")E+=J(y.pattern,!0,e.state.shoptOptions.extglob);else if(y.type==="Literal")E+=J(y.value,!0,e.state.shoptOptions.extglob);else if(y.type==="SingleQuoted"||y.type==="Escaped")E+=te(y.value);else if(y.type==="DoubleQuoted"){let S=await s(e,y.parts);E+=te(S)}else if(y.type==="ParameterExpansion"){let S=await r(e,y);E+=J(S,!0,e.state.shoptOptions.extglob)}else{let S=await r(e,y);E+=te(S)}let b=m.replacement?await s(e,m.replacement.parts):"",g=E;m.anchor==="start"?g=`^${E}`:m.anchor==="end"&&(g=`${E}$`);try{let y=ge(g,m.all?"g":"");p=p.map(S=>y.replace(S,b))}catch{}}if(l){let m=K(e.state.env);return{values:[u+p.join(m)+f],quoted:!0}}return p.length===1?{values:[u+p[0]+f],quoted:!0}:{values:[u+p[0],...p.slice(1,-1),p[p.length-1]+f],quoted:!0}}async function lc(e,t,n,r){if(!n||t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0],i=-1,o="",a=!1;for(let p=0;p<s.parts.length;p++){let h=s.parts[p];if(h.type==="ParameterExpansion"&&!h.operation){let m=h.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(m){i=p,o=m[1],a=m[2]==="*";break}}}if(i===-1)return null;let l="";for(let p=0;p<i;p++)l+=await r(e,s.parts[p]);let c="";for(let p=i+1;p<s.parts.length;p++)c+=await r(e,s.parts[p]);let u=Q(e,o),f=u.map(([,p])=>p);if(u.length===0){let p=e.state.env.get(o);if(p!==void 0)return{values:[l+p+c],quoted:!0};if(a)return{values:[l+c],quoted:!0};let h=l+c;return{values:h?[h]:[],quoted:!0}}if(a){let p=K(e.state.env);return{values:[l+f.join(p)+c],quoted:!0}}return f.length===1?{values:[l+f[0]+c],quoted:!0}:{values:[l+f[0],...f.slice(1,-1),f[f.length-1]+c],quoted:!0}}async function cc(e,t,n){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let r=t[0];if(r.parts.length!==1||r.parts[0].type!=="ParameterExpansion"||r.parts[0].operation?.type!=="Substring")return null;let s=r.parts[0],i=s.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!i)return null;let o=i[1],a=i[2]==="*",l=s.operation;if(e.state.associativeArrays?.has(o))throw new j(1,"",`bash: \${${o}[@]: 0: 3}: bad substitution
|
|
106
|
+
`);let c=l.offset?await n(e,l.offset.expression):0,u=l.length?await n(e,l.length.expression):void 0,f=Q(e,o);if(f.length>e.limits.maxArrayElements)throw new x(`array transform element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let d=0;if(c<0){if(f.length>0){let h=f[f.length-1][0],E=(typeof h=="number"?h:0)+1+c;if(E<0)return{values:[],quoted:!0};d=f.findIndex(([b])=>typeof b=="number"&&b>=E),d<0&&(d=f.length)}}else d=f.findIndex(([h])=>typeof h=="number"&&h>=c),d<0&&(d=f.length);let p;if(u!==void 0){if(u<0)throw new ce(`${o}[@]: substring expression < 0`);p=f.slice(d,d+u).map(([,h])=>h)}else p=f.slice(d).map(([,h])=>h);if(p.length===0)return{values:[],quoted:!0};if(a){let h=K(e.state.env);return{values:[p.join(h)],quoted:!0}}return{values:p,quoted:!0}}function uc(e,t){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!=="ParameterExpansion"||n.parts[0].operation?.type!=="Transform")return null;let r=n.parts[0],s=r.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!s)return null;let i=s[1],o=s[2]==="*",a=r.operation,l=Q(e,i);if(l.length===0){let d=e.state.env.get(i);if(d!==void 0){let p;switch(a.operator){case"a":p="";break;case"P":p=pr(e,d);break;case"Q":p=Zt(d);break;default:p=d}if(B(p)>e.limits.maxStringLength)throw new x(`array transform string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[p],quoted:!0}}return o?{values:[""],quoted:!0}:{values:[],quoted:!0}}let c=Ht(e,i),u=[],f=0;for(let[,d]of l){let p;switch(a.operator){case"a":p=c;break;case"P":p=pr(e,d);break;case"Q":p=Zt(d);break;case"u":p=d.charAt(0).toUpperCase()+d.slice(1);break;case"U":p=d.toUpperCase();break;case"L":p=d.toLowerCase();break;default:p=d}let h=B(p);if(h>e.limits.maxStringLength-f)throw new x(`array transform string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");u.push(p),f+=h}if(o){let d=K(e.state.env);if(Math.max(0,u.length-1)*B(d)>e.limits.maxStringLength-f)throw new x(`array transform string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[u.join(d)],quoted:!0}}return{values:u,quoted:!0}}function fc(e,t){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!=="ParameterExpansion")return null;let r=n.parts[0];if(r.operation)return null;let s=r.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(@)\]$/);if(!s)return null;let i=s[1];if(ue(e,i)){let l=En(e,i);if(l?.endsWith("[@]")||l?.endsWith("[*]"))return{values:[],quoted:!0}}let o=Q(e,i);if(o.length>0)return{values:o.map(([,l])=>l),quoted:!0};let a=e.state.env.get(i);return a!==void 0?{values:[a],quoted:!0}:{values:[],quoted:!0}}function dc(e,t){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let n=t[0];if(n.parts.length!==1||n.parts[0].type!=="ParameterExpansion"||n.parts[0].operation)return null;let s=n.parts[0].parameter;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)||!ue(e,s))return null;let i=En(e,s);if(!i)return null;let o=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(@)\]$/);if(!o)return null;let a=o[1],l=Q(e,a);if(l.length>0)return{values:l.map(([,u])=>u),quoted:!0};let c=e.state.env.get(a);return c!==void 0?{values:[c],quoted:!0}:{values:[],quoted:!0}}async function pc(e,t,n,r,s){if(!n||t.length!==1||t[0].type!=="DoubleQuoted")return null;let i=t[0];if(i.parts.length!==1||i.parts[0].type!=="ParameterExpansion"||i.parts[0].operation?.type!=="Indirection")return null;let o=i.parts[0],a=o.operation,l=await ie(e,o.parameter),c=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!c){if(!a.innerOp&&(l==="@"||l==="*")){let h=Number.parseInt(e.state.env.get("#")||"0",10),m=[];for(let E=1;E<=h;E++)m.push(e.state.env.get(String(E))||"");return l==="*"?{values:[m.join(K(e.state.env))],quoted:!0}:{values:m,quoted:!0}}return null}let u=c[1],f=c[2]==="*",d=Q(e,u);if(a.innerOp){if(a.innerOp.type==="Substring")return $p(e,d,u,f,a.innerOp);if(a.innerOp.type==="DefaultValue"||a.innerOp.type==="UseAlternative"||a.innerOp.type==="AssignDefault"||a.innerOp.type==="ErrorIfUnset")return Cp(e,d,u,f,a.innerOp,s);if(a.innerOp.type==="Transform"&&a.innerOp.operator==="a"){let m=Ht(e,u),E=d.map(()=>m);return f?{values:[E.join(K(e.state.env))],quoted:!0}:{values:E,quoted:!0}}let h=[];for(let[,m]of d){let E={type:"ParameterExpansion",parameter:"_indirect_elem_",operation:a.innerOp},b=e.state.env.get("_indirect_elem_");e.state.env.set("_indirect_elem_",m);try{let g=await r(e,E,!0);h.push(g)}finally{b!==void 0?e.state.env.set("_indirect_elem_",b):e.state.env.delete("_indirect_elem_")}}return f?{values:[h.join(K(e.state.env))],quoted:!0}:{values:h,quoted:!0}}if(d.length>0){let h=d.map(([,m])=>m);return f?{values:[h.join(K(e.state.env))],quoted:!0}:{values:h,quoted:!0}}let p=e.state.env.get(u);return p!==void 0?{values:[p],quoted:!0}:{values:[],quoted:!0}}async function $p(e,t,n,r,s){let i=s.offset?await Y(e,s.offset.expression):0,o=s.length?await Y(e,s.length.expression):void 0,a=0;if(i<0){if(t.length>0){let u=t[t.length-1][0],d=(typeof u=="number"?u:0)+1+i;if(d<0)return{values:[],quoted:!0};if(a=t.findIndex(([p])=>typeof p=="number"&&p>=d),a<0)return{values:[],quoted:!0}}}else if(a=t.findIndex(([u])=>typeof u=="number"&&u>=i),a<0)return{values:[],quoted:!0};let l;if(o!==void 0){if(o<0)throw new ce(`${n}[@]: substring expression < 0`);l=t.slice(a,a+o)}else l=t.slice(a);let c=l.map(([,u])=>u);return r?{values:[c.join(K(e.state.env))],quoted:!0}:{values:c,quoted:!0}}async function Cp(e,t,n,r,s,i){let o=s.checkEmpty??!1,a=t.map(([,u])=>u),l=t.length===0,c=t.length===0;if(s.type==="UseAlternative")return!c&&!(o&&l)&&s.word?{values:[await i(e,s.word.parts,!0)],quoted:!0}:{values:[],quoted:!0};if(s.type==="DefaultValue")return(c||o&&l)&&s.word?{values:[await i(e,s.word.parts,!0)],quoted:!0}:r?{values:[a.join(K(e.state.env))],quoted:!0}:{values:a,quoted:!0};if(s.type==="AssignDefault"){if((c||o&&l)&&s.word){let f=await i(e,s.word.parts,!0);return G(e,n,0,f),{values:[f],quoted:!0}}return r?{values:[a.join(K(e.state.env))],quoted:!0}:{values:a,quoted:!0}}return r?{values:[a.join(K(e.state.env))],quoted:!0}:{values:a,quoted:!0}}async function hc(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="UseAlternative"&&t[0].operation?.type!=="DefaultValue")return null;let n=t[0],r=n.operation,s=r?.word;if(!s||s.parts.length!==1||s.parts[0].type!=="DoubleQuoted")return null;let i=s.parts[0];if(i.parts.length!==1||i.parts[0].type!=="ParameterExpansion"||i.parts[0].operation?.type!=="Indirection")return null;let o=i.parts[0],l=(await ie(e,o.parameter)).match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!l)return null;let c=await St(e,n.parameter),u=await ie(e,n.parameter)==="",f=r.checkEmpty??!1,d;if(r.type==="UseAlternative"?d=c&&!(f&&u):d=!c||f&&u,d){let p=l[1],h=l[2]==="*",m=Q(e,p);if(m.length>0){let b=m.map(([,g])=>g);return h?{values:[b.join(K(e.state.env))],quoted:!0}:{values:b,quoted:!0}}let E=e.state.env.get(p);return E!==void 0?{values:[E],quoted:!0}:{values:[],quoted:!0}}return{values:[],quoted:!1}}async function mc(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="Indirection")return null;let n=t[0],s=n.operation.innerOp;if(!s||s.type!=="UseAlternative"&&s.type!=="DefaultValue")return null;let i=s.word;if(!i||i.parts.length!==1||i.parts[0].type!=="DoubleQuoted")return null;let o=i.parts[0];if(o.parts.length!==1||o.parts[0].type!=="ParameterExpansion"||o.parts[0].operation?.type!=="Indirection")return null;let a=o.parts[0],c=(await ie(e,a.parameter)).match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!c)return null;let u=await ie(e,n.parameter),f=await St(e,n.parameter),d=u==="",p=s.checkEmpty??!1,h;if(s.type==="UseAlternative"?h=f&&!(p&&d):h=!f||p&&d,h){let m=c[1],E=c[2]==="*",b=Q(e,m);if(b.length>0){let y=b.map(([,S])=>S);return E?{values:[y.join(K(e.state.env))],quoted:!0}:{values:y,quoted:!0}}let g=e.state.env.get(m);return g!==void 0?{values:[g],quoted:!0}:{values:[],quoted:!0}}return{values:[],quoted:!1}}function yc(e){let t=Number.parseInt(e.state.env.get("#")||"0",10);if(t>e.limits.maxArrayElements)throw new x(`positional parameter element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let n=[],r=0;for(let s=1;s<=t;s++){let i=e.state.env.get(String(s))||"",o=B(i);if(o>e.limits.maxStringLength-r)throw new x(`positional parameter string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");n.push(i),r+=o}return n}function rs(e,t,n){if(B(t)>n-B(e))throw new x(`positional expansion string limit exceeded (${n} bytes)`,"string_length");return e+t}function zi(e,t,n,r){if(e.length>=r.limits.maxArrayElements)throw new x(`positional expansion element limit exceeded (${r.limits.maxArrayElements})`,"array_elements");let s=B(t);if(s>r.limits.maxStringLength-n.value)throw new x(`positional expansion string limit exceeded (${r.limits.maxStringLength} bytes)`,"string_length");e.push(t),n.value+=s}async function gc(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0],i=-1,o=!1;for(let g=0;g<s.parts.length;g++){let y=s.parts[g];if(y.type==="ParameterExpansion"&&(y.parameter==="@"||y.parameter==="*")&&y.operation?.type==="Substring"){i=g,o=y.parameter==="*";break}}if(i===-1)return null;let l=s.parts[i].operation,c=l.offset?await n(e,l.offset.expression):0,u=l.length?await n(e,l.length.expression):void 0,f=Number.parseInt(e.state.env.get("#")||"0",10),d=[];for(let g=1;g<=f;g++)d.push(e.state.env.get(String(g))||"");let p=e.state.env.get("0")||"bash",h;if(c<=0){let g=[p,...d],y=g.length+c;if(y<0)h=[];else{let S=c<0?y:0;if(u!==void 0){let v=u<0?g.length+u:S+u;h=g.slice(S,Math.max(S,v))}else h=g.slice(S)}}else{let g=c-1;if(g>=d.length)h=[];else if(u!==void 0){let y=u<0?d.length+u:g+u;h=d.slice(g,Math.max(g,y))}else h=d.slice(g)}let m="";for(let g=0;g<i;g++)m+=await r(e,s.parts[g]);let E="";for(let g=i+1;g<s.parts.length;g++)E+=await r(e,s.parts[g]);if(h.length===0){let g=m+E;return{values:g?[g]:[],quoted:!0}}if(o){let g=K(e.state.env);return{values:[m+h.join(g)+E],quoted:!0}}return h.length===1?{values:[m+h[0]+E],quoted:!0}:{values:[m+h[0],...h.slice(1,-1),h[h.length-1]+E],quoted:!0}}async function wc(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0],i=-1,o=!1;for(let g=0;g<s.parts.length;g++){let y=s.parts[g];if(y.type==="ParameterExpansion"&&(y.parameter==="@"||y.parameter==="*")&&y.operation?.type==="PatternReplacement"){i=g,o=y.parameter==="*";break}}if(i===-1)return null;let l=s.parts[i].operation,c=yc(e),u="";for(let g=0;g<i;g++)u=rs(u,await n(e,s.parts[g]),e.limits.maxStringLength);let f="";for(let g=i+1;g<s.parts.length;g++)f=rs(f,await n(e,s.parts[g]),e.limits.maxStringLength);if(c.length===0){let g=u+f;return{values:g?[g]:[],quoted:!0}}let d="";if(l.pattern)for(let g of l.pattern.parts)if(g.type==="Glob")d+=J(g.pattern,!0,e.state.shoptOptions.extglob);else if(g.type==="Literal")d+=J(g.value,!0,e.state.shoptOptions.extglob);else if(g.type==="SingleQuoted"||g.type==="Escaped")d+=te(g.value);else if(g.type==="DoubleQuoted"){let y=await r(e,g.parts);d+=te(y)}else if(g.type==="ParameterExpansion"){let y=await n(e,g);d+=J(y,!0,e.state.shoptOptions.extglob)}else{let y=await n(e,g);d+=te(y)}let p=l.replacement?await r(e,l.replacement.parts):"",h=d;l.anchor==="start"?h=`^${d}`:l.anchor==="end"&&(h=`${d}$`);let m=[],E={value:0};try{let g=ge(h,l.all?"g":"");for(let y of c){let S=0;g.lastIndex=0;for(let P=g.exec(y);P&&(S++,!!l.all);P=g.exec(y))P[0].length===0&&g.lastIndex++;let v=B(y),k=B(p),A=0,$=/\$(?:\$|&|\d+|<[^>]+>|`|')/g;for(;$.exec(p)!==null;)A++;if(v+S*k+S*A*v>e.limits.maxStringLength-E.value)throw new x(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");zi(m,g.replace(y,p),E,e)}}catch(g){if(g instanceof x)throw g;for(let y of c)zi(m,y,E,e)}if(o){let g=K(e.state.env);if(E.value+Math.max(0,m.length-1)*B(g)+B(u)+B(f)>e.limits.maxStringLength)throw new x(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[u+m.join(g)+f],quoted:!0}}if(B(u)+E.value+B(f)>e.limits.maxStringLength)throw new x(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return m.length===1?{values:[u+m[0]+f],quoted:!0}:{values:[u+m[0],...m.slice(1,-1),m[m.length-1]+f],quoted:!0}}async function Ec(e,t,n,r){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let s=t[0],i=-1,o=!1;for(let b=0;b<s.parts.length;b++){let g=s.parts[b];if(g.type==="ParameterExpansion"&&(g.parameter==="@"||g.parameter==="*")&&g.operation?.type==="PatternRemoval"){i=b,o=g.parameter==="*";break}}if(i===-1)return null;let l=s.parts[i].operation,c=yc(e),u="";for(let b=0;b<i;b++)u=rs(u,await n(e,s.parts[b]),e.limits.maxStringLength);let f="";for(let b=i+1;b<s.parts.length;b++)f=rs(f,await n(e,s.parts[b]),e.limits.maxStringLength);if(c.length===0){let b=u+f;return{values:b?[b]:[],quoted:!0}}let d="",p=e.state.shoptOptions.extglob;if(l.pattern)for(let b of l.pattern.parts)if(b.type==="Glob")d+=J(b.pattern,l.greedy,p);else if(b.type==="Literal")d+=J(b.value,l.greedy,p);else if(b.type==="SingleQuoted"||b.type==="Escaped")d+=te(b.value);else if(b.type==="DoubleQuoted"){let g=await r(e,b.parts);d+=te(g)}else if(b.type==="ParameterExpansion"){let g=await n(e,b);d+=J(g,l.greedy,p)}else{let g=await n(e,b);d+=te(g)}let h=[],m={value:0};for(let b of c)zi(h,ht(e,b,d,l.side,l.greedy),m,e);if(o){let b=K(e.state.env);if(m.value+Math.max(0,h.length-1)*B(b)+B(u)+B(f)>e.limits.maxStringLength)throw new x(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return{values:[u+h.join(b)+f],quoted:!0}}if(B(u)+m.value+B(f)>e.limits.maxStringLength)throw new x(`positional expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return h.length===1?{values:[u+h[0]+f],quoted:!0}:{values:[u+h[0],...h.slice(1,-1),h[h.length-1]+f],quoted:!0}}async function bc(e,t,n){if(t.length!==1||t[0].type!=="DoubleQuoted")return null;let r=t[0],s=-1,i=!1;for(let d=0;d<r.parts.length;d++){let p=r.parts[d];if(p.type==="ParameterExpansion"&&(p.parameter==="@"||p.parameter==="*")){s=d,i=p.parameter==="*";break}}if(s===-1)return null;let o=r.parts[s];if(o.type==="ParameterExpansion"&&o.operation)return null;let a=Number.parseInt(e.state.env.get("#")||"0",10),l="";for(let d=0;d<s;d++)l+=await n(e,r.parts[d]);let c="";for(let d=s+1;d<r.parts.length;d++)c+=await n(e,r.parts[d]);if(a===0){if(i)return{values:[l+c],quoted:!0};let d=l+c;return{values:d?[d]:[],quoted:!0}}let u=[];for(let d=1;d<=a;d++)u.push(e.state.env.get(String(d))||"");if(i){let d=K(e.state.env);return{values:[l+u.join(d)+c],quoted:!0}}return u.length===1?{values:[l+u[0]+c],quoted:!0}:{values:[l+u[0],...u.slice(1,-1),u[u.length-1]+c],quoted:!0}}function vt(e,t,n,r){if(t.length>=e.limits.maxArrayElements)throw new x(`unquoted expansion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let s=B(n);if(s>e.limits.maxStringLength-r.value)throw new x(`unquoted expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");t.push(n),r.value+=s}function Ui(e,t,n,r){let s=B(n),i=Math.max(0,t.length-1);if(s>0&&i>Math.floor((e.limits.maxStringLength-r)/s))throw new x(`unquoted expansion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");return t.join(n)}function Np(e){return new Gt(e.fs,e.state.cwd,e.state.env,{globstar:e.state.shoptOptions.globstar,nullglob:e.state.shoptOptions.nullglob,failglob:e.state.shoptOptions.failglob,dotglob:e.state.shoptOptions.dotglob,extglob:e.state.shoptOptions.extglob,globskipdots:e.state.shoptOptions.globskipdots,maxGlobOperations:e.limits.maxGlobOperations,consumeOperation:()=>e.executionScope.consumeLimited("glob_operations",1,e.limits.maxGlobOperations,"glob expansion")})}async function ss(e,t){if(e.state.options.noglob)return t;let n=Np(e),r=[];for(let s of t)if(At(s,e.state.shoptOptions.extglob)){let i=await n.expand(s);if(i.length>0)Oe(r,i,e.limits.maxArrayElements,"unquoted glob expansion");else{if(n.hasFailglob())throw new Lt(s);n.hasNullglob()||r.push(s)}}else r.push(s);return r}async function Sc(e,t,n,r){let s=-1,i="",o=!1;for(let S=0;S<t.length;S++){let v=t[S];if(v.type==="ParameterExpansion"&&v.operation?.type==="PatternReplacement"){let k=v.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(k){s=S,i=k[1],o=k[2]==="*";break}}}if(s===-1)return null;let l=t[s].operation,c=Q(e,i),u=c.map(([,S])=>S);if(c.length===0){let S=e.state.env.get(i);S!==void 0&&(u=[S])}if(u.length===0)return{values:[],quoted:!1};let f="";if(l.pattern)for(let S of l.pattern.parts)if(S.type==="Glob")f+=J(S.pattern,!0,e.state.shoptOptions.extglob);else if(S.type==="Literal")f+=J(S.value,!0,e.state.shoptOptions.extglob);else if(S.type==="SingleQuoted"||S.type==="Escaped")f+=te(S.value);else if(S.type==="DoubleQuoted"){let v=await n(e,S.parts);f+=te(v)}else if(S.type==="ParameterExpansion"){let v=await r(e,S);f+=J(v,!0,e.state.shoptOptions.extglob)}else{let v=await r(e,S);f+=te(v)}let d=l.replacement?await n(e,l.replacement.parts):"",p=f;l.anchor==="start"?p=`^${f}`:l.anchor==="end"&&(p=`${f}$`);let h=[],m={value:0};try{let S=ge(p,l.all?"g":"");for(let v of u)vt(e,h,es(e,v,S,d,l.all),m)}catch(S){if(S instanceof x)throw S;for(let v of u)vt(e,h,v,m)}let E=ke(e.state.env),b=Re(e.state.env);if(o){let S=K(e.state.env),v=Ui(e,h,S,m.value);return b?{values:v?[v]:[],quoted:!1}:{values:de(v,E,e.limits.maxArrayElements),quoted:!1}}if(b)return{values:h,quoted:!1};let g=[],y={value:0};for(let S of h)if(S==="")vt(e,g,"",y);else for(let v of de(S,E,e.limits.maxArrayElements))vt(e,g,v,y);return{values:g,quoted:!1}}async function Ac(e,t,n,r){let s=-1,i="",o=!1;for(let y=0;y<t.length;y++){let S=t[y];if(S.type==="ParameterExpansion"&&S.operation?.type==="PatternRemoval"){let v=S.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(v){s=y,i=v[1],o=v[2]==="*";break}}}if(s===-1)return null;let l=t[s].operation,c=Q(e,i),u=c.map(([,y])=>y);if(c.length===0){let y=e.state.env.get(i);y!==void 0&&(u=[y])}if(u.length===0)return{values:[],quoted:!1};let f="",d=e.state.shoptOptions.extglob;if(l.pattern)for(let y of l.pattern.parts)if(y.type==="Glob")f+=J(y.pattern,l.greedy,d);else if(y.type==="Literal")f+=J(y.value,l.greedy,d);else if(y.type==="SingleQuoted"||y.type==="Escaped")f+=te(y.value);else if(y.type==="DoubleQuoted"){let S=await n(e,y.parts);f+=te(S)}else if(y.type==="ParameterExpansion"){let S=await r(e,y);f+=J(S,l.greedy,d)}else{let S=await r(e,y);f+=te(S)}let p=[],h={value:0};for(let y of u)vt(e,p,ht(e,y,f,l.side,l.greedy),h);let m=ke(e.state.env),E=Re(e.state.env);if(o){let y=K(e.state.env),S=Ui(e,p,y,h.value);return E?{values:S?[S]:[],quoted:!1}:{values:de(S,m,e.limits.maxArrayElements),quoted:!1}}if(E)return{values:p,quoted:!1};let b=[],g={value:0};for(let y of p)if(y==="")vt(e,b,"",g);else for(let S of de(y,m,e.limits.maxArrayElements))vt(e,b,S,g);return{values:b,quoted:!1}}async function vc(e,t,n,r){let s=-1,i=!1;for(let g=0;g<t.length;g++){let y=t[g];if(y.type==="ParameterExpansion"&&(y.parameter==="@"||y.parameter==="*")&&y.operation?.type==="PatternRemoval"){s=g,i=y.parameter==="*";break}}if(s===-1)return null;let a=t[s].operation,l=Number.parseInt(e.state.env.get("#")||"0",10),c=[];for(let g=1;g<=l;g++)c.push(e.state.env.get(String(g))||"");if(c.length===0)return{values:[],quoted:!1};let u="",f=e.state.shoptOptions.extglob;if(a.pattern)for(let g of a.pattern.parts)if(g.type==="Glob")u+=J(g.pattern,a.greedy,f);else if(g.type==="Literal")u+=J(g.value,a.greedy,f);else if(g.type==="SingleQuoted"||g.type==="Escaped")u+=te(g.value);else if(g.type==="DoubleQuoted"){let y=await n(e,g.parts);u+=te(y)}else if(g.type==="ParameterExpansion"){let y=await r(e,g);u+=J(y,a.greedy,f)}else{let y=await r(e,g);u+=te(y)}let d=[],p={value:0};for(let g of c)vt(e,d,ht(e,g,u,a.side,a.greedy),p);let h=ke(e.state.env),m=Re(e.state.env);if(i){let g=K(e.state.env),y=Ui(e,d,g,p.value);return m?{values:y?[y]:[],quoted:!1}:{values:de(y,h,e.limits.maxArrayElements),quoted:!1}}if(m)return{values:d,quoted:!1};let E=[],b={value:0};for(let g of d)if(g==="")vt(e,E,"",b);else for(let y of de(g,h,e.limits.maxArrayElements))vt(e,E,y,b);return{values:E,quoted:!1}}async function kc(e,t,n,r){let s=-1,i=!1;for(let y=0;y<t.length;y++){let S=t[y];if(S.type==="ParameterExpansion"&&(S.parameter==="@"||S.parameter==="*")&&S.operation?.type==="Substring"){s=y,i=S.parameter==="*";break}}if(s===-1)return null;let a=t[s].operation,l=a.offset?await n(e,a.offset.expression):0,c=a.length?await n(e,a.length.expression):void 0,u=Number.parseInt(e.state.env.get("#")||"0",10),f=[];for(let y=1;y<=u;y++)f.push(e.state.env.get(String(y))||"");let d=e.state.env.get("0")||"bash",p;if(l<=0){let y=[d,...f],S=y.length+l;if(S<0)p=[];else{let v=l<0?S:0;if(c!==void 0){let k=c<0?y.length+c:v+c;p=y.slice(v,Math.max(v,k))}else p=y.slice(v)}}else{let y=l-1;if(y>=f.length)p=[];else if(c!==void 0){let S=c<0?f.length+c:y+c;p=f.slice(y,Math.max(y,S))}else p=f.slice(y)}let h="";for(let y=0;y<s;y++)h+=await r(e,t[y]);let m="";for(let y=s+1;y<t.length;y++)m+=await r(e,t[y]);let E=ke(e.state.env),b=Re(e.state.env);if(p.length===0){let y=h+m;return y?b?{values:[y],quoted:!1}:{values:de(y,E,e.limits.maxArrayElements),quoted:!1}:{values:[],quoted:!1}}let g;if(i){let y=K(e.state.env),S=h+p.join(y)+m;b?g=S?[S]:[]:g=de(S,E,e.limits.maxArrayElements)}else if(b)p.length===1?g=[h+p[0]+m]:g=[h+p[0],...p.slice(1,-1),p[p.length-1]+m];else{g=[];for(let y=0;y<p.length;y++){let S=p[y];if(y===0&&(S=h+S),y===p.length-1&&(S=S+m),S==="")g.push("");else{let v=de(S,E,e.limits.maxArrayElements);Oe(g,v,e.limits.maxArrayElements,"unquoted expansion")}}}return{values:await ss(e,g),quoted:!1}}async function Pc(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].parameter!=="@"&&t[0].parameter!=="*"||t[0].operation)return null;let n=t[0].parameter==="*",r=Number.parseInt(e.state.env.get("#")||"0",10);if(r===0)return{values:[],quoted:!1};let s=[];for(let c=1;c<=r;c++)s.push(e.state.env.get(String(c))||"");let i=ke(e.state.env),o=Re(e.state.env),a=Qr(e.state.env),l;if(n)if(o)l=s.filter(c=>c!=="");else{let c=K(e.state.env),u=s.join(c);l=de(u,i,e.limits.maxArrayElements)}else if(o)l=s.filter(c=>c!=="");else if(a){l=[];for(let c of s){if(c==="")continue;let u=de(c,i,e.limits.maxArrayElements);Oe(l,u,e.limits.maxArrayElements,"unquoted expansion")}}else{l=[];for(let c of s)if(c==="")l.push("");else{let u=de(c,i,e.limits.maxArrayElements);Oe(l,u,e.limits.maxArrayElements,"unquoted expansion")}for(;l.length>0&&l[l.length-1]==="";)l.pop()}return{values:await ss(e,l),quoted:!1}}async function xc(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation)return null;let n=t[0].parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(!n)return null;let r=n[1],s=n[2]==="*",i=Q(e,r),o;if(i.length===0){let f=e.state.env.get(r);if(f!==void 0)o=[f];else return{values:[],quoted:!1}}else o=i.map(([,f])=>f);let a=ke(e.state.env),l=Re(e.state.env),c=Qr(e.state.env),u;if(s)if(l)u=o.filter(f=>f!=="");else{let f=K(e.state.env),d=o.join(f);u=de(d,a,e.limits.maxArrayElements)}else if(l)u=o.filter(f=>f!=="");else if(c){u=[];for(let f of o){if(f==="")continue;let d=de(f,a,e.limits.maxArrayElements);Oe(u,d,e.limits.maxArrayElements,"unquoted expansion")}}else{u=[];for(let f of o)if(f==="")u.push("");else{let d=de(f,a,e.limits.maxArrayElements);Oe(u,d,e.limits.maxArrayElements,"unquoted expansion")}for(;u.length>0&&u[u.length-1]==="";)u.pop()}return{values:await ss(e,u),quoted:!1}}function $c(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="VarNamePrefix")return null;let n=t[0].operation,r=In(e,n.prefix);if(r.length===0)return{values:[],quoted:!1};let s=ke(e.state.env),i=Re(e.state.env),o;if(n.star)if(i)o=r;else{let a=K(e.state.env),l=r.join(a);o=de(l,s,e.limits.maxArrayElements)}else if(i)o=r;else{o=[];for(let a of r){let l=de(a,s,e.limits.maxArrayElements);Oe(o,l,e.limits.maxArrayElements,"unquoted expansion")}}return{values:o,quoted:!1}}function Cc(e,t){if(t.length!==1||t[0].type!=="ParameterExpansion"||t[0].operation?.type!=="ArrayKeys")return null;let n=t[0].operation,s=Q(e,n.array).map(([l])=>String(l));if(s.length===0)return{values:[],quoted:!1};let i=ke(e.state.env),o=Re(e.state.env),a;if(n.star)if(o)a=s;else{let l=K(e.state.env),c=s.join(l);a=de(c,i,e.limits.maxArrayElements)}else if(o)a=s;else{a=[];for(let l of s){let c=de(l,i,e.limits.maxArrayElements);Oe(a,c,e.limits.maxArrayElements,"unquoted expansion")}}return{values:a,quoted:!1}}async function Nc(e,t,n){let r=-1;for(let d=0;d<t.length;d++){let p=t[d];if(p.type==="ParameterExpansion"&&(p.parameter==="@"||p.parameter==="*")&&!p.operation){r=d;break}}if(r===-1||t.length<=1)return null;let s=Number.parseInt(e.state.env.get("#")||"0",10),i=[];for(let d=1;d<=s;d++)i.push(e.state.env.get(String(d))||"");let o="";for(let d=0;d<r;d++)o+=await n(e,t[d]);let a="";for(let d=r+1;d<t.length;d++)a+=await n(e,t[d]);let l=ke(e.state.env),c=Re(e.state.env),u=Qr(e.state.env);if(s===0){let d=o+a;return{values:d?[d]:[],quoted:!1}}let f;{let d=[];for(let p=0;p<i.length;p++){let h=i[p];p===0&&(h=o+h),p===i.length-1&&(h=h+a),d.push(h)}if(c)f=d.filter(p=>p!=="");else if(u){f=[];for(let p of d){if(p==="")continue;let h=de(p,l,e.limits.maxArrayElements);Oe(f,h,e.limits.maxArrayElements,"unquoted expansion")}}else{f=[];for(let p of d)if(p==="")f.push("");else{let h=de(p,l,e.limits.maxArrayElements);Oe(f,h,e.limits.maxArrayElements,"unquoted expansion")}for(;f.length>0&&f[f.length-1]==="";)f.pop()}}return f.length===0?{values:[],quoted:!1}:{values:await ss(e,f),quoted:!1}}async function Dc(e,t,n){e.coverage?.hit("bash:expansion:word_glob");let r=t.parts,{hasQuoted:s,hasCommandSub:i,hasArrayVar:o,hasArrayAtExpansion:a,hasParamExpansion:l,hasVarNamePrefixExpansion:c,hasIndirection:u}=fr(r),d=n.hasBraceExpansion(r)?await n.expandWordWithBracesAsync(e,t):null;if(d&&d.length>1)return Rp(e,d,s);let p=await Op(e,r,a,c,u,n);if(p!==null)return p;let h=await Ip(e,r,n);if(h!==null)return h;let m=await _p(e,r,n);if(m!==null)return m;let E=await Lp(e,r,n.expandPart);if(E!==null)return Oc(e,E);if((i||o||l)&&!Re(e.state.env)){let g=ke(e.state.env),y=n.buildIfsCharClassPattern(g),S=await n.smartWordSplit(e,r,g,y,n.expandPart);return Oc(e,S)}let b=await n.expandWordAsync(e,t);return Mp(e,t,r,b,s,n.expandWordForGlobbing)}async function Rp(e,t,n){let r=[];for(let s of t)if(!(!n&&s===""))if(!n&&!e.state.options.noglob&&At(s,e.state.shoptOptions.extglob)){let i=await is(e,s);Oe(r,i,e.limits.maxArrayElements,"brace/glob expansion")}else r.push(s);return{values:r,quoted:!1}}async function Op(e,t,n,r,s,i){if(n){let o=fc(e,t);if(o!==null)return o}{let o=dc(e,t);if(o!==null)return o}{let o=await oc(e,t);if(o!==null)return o}{let o=await ac(e,t,n,i.expandPart,i.expandWordPartsAsync);if(o!==null)return o}{let o=await lc(e,t,n,i.expandPart);if(o!==null)return o}{let o=await cc(e,t,i.evaluateArithmetic);if(o!==null)return o}{let o=uc(e,t);if(o!==null)return o}{let o=await sc(e,t,i.expandWordPartsAsync,i.expandPart);if(o!==null)return o}{let o=await ic(e,t,i.expandWordPartsAsync,i.expandPart);if(o!==null)return o}if(r&&t.length===1&&t[0].type==="DoubleQuoted"){let o=Dp(e,t);if(o!==null)return o}{let o=await pc(e,t,s,i.expandParameterAsync,i.expandWordPartsAsync);if(o!==null)return o}{let o=await hc(e,t);if(o!==null)return o}{let o=await mc(e,t);if(o!==null)return o}return null}function Dp(e,t){let n=t[0];if(n.type!=="DoubleQuoted")return null;if(n.parts.length===1&&n.parts[0].type==="ParameterExpansion"&&n.parts[0].operation?.type==="VarNamePrefix"){let r=n.parts[0].operation,s=In(e,r.prefix);return r.star?{values:[s.join(K(e.state.env))],quoted:!0}:{values:s,quoted:!0}}if(n.parts.length===1&&n.parts[0].type==="ParameterExpansion"&&n.parts[0].operation?.type==="ArrayKeys"){let r=n.parts[0].operation,i=Q(e,r.array).map(([o])=>String(o));return r.star?{values:[i.join(K(e.state.env))],quoted:!0}:{values:i,quoted:!0}}return null}async function Ip(e,t,n){{let r=await gc(e,t,n.evaluateArithmetic,n.expandPart);if(r!==null)return r}{let r=await wc(e,t,n.expandPart,n.expandWordPartsAsync);if(r!==null)return r}{let r=await Ec(e,t,n.expandPart,n.expandWordPartsAsync);if(r!==null)return r}{let r=await bc(e,t,n.expandPart);if(r!==null)return r}return null}async function _p(e,t,n){{let r=await Sc(e,t,n.expandWordPartsAsync,n.expandPart);if(r!==null)return r}{let r=await Ac(e,t,n.expandWordPartsAsync,n.expandPart);if(r!==null)return r}{let r=await vc(e,t,n.expandWordPartsAsync,n.expandPart);if(r!==null)return r}{let r=await kc(e,t,n.evaluateArithmetic,n.expandPart);if(r!==null)return r}{let r=await Pc(e,t);if(r!==null)return r}{let r=await xc(e,t);if(r!==null)return r}{let r=$c(e,t);if(r!==null)return r}{let r=Cc(e,t);if(r!==null)return r}{let r=await Nc(e,t,n.expandPart);if(r!==null)return r}return null}function Rc(e){if(e.type!=="DoubleQuoted")return null;for(let t=0;t<e.parts.length;t++){let n=e.parts[t];if(n.type!=="ParameterExpansion"||n.operation)continue;let r=n.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(r)return{type:"array",name:r[1],atIndex:t,isStar:r[2]==="*"};if(n.parameter==="@"||n.parameter==="*")return{type:"positional",atIndex:t,isStar:n.parameter==="*"}}return null}async function Tp(e,t,n,r){let s="";for(let a=0;a<n.atIndex;a++)s+=await r(e,t.parts[a]);let i="";for(let a=n.atIndex+1;a<t.parts.length;a++)i+=await r(e,t.parts[a]);let o;if(n.type==="array"){if(o=Q(e,n.name).map(([,l])=>l),o.length===0){let l=e.state.env.get(n.name);l!==void 0&&(o=[l])}}else{let a=Number.parseInt(e.state.env.get("#")||"0",10);o=[];for(let l=1;l<=a;l++)o.push(e.state.env.get(String(l))||"")}if(n.isStar){let a=K(e.state.env),l=o.join(a);return[s+l+i]}if(o.length===0){let a=s+i;return a?[a]:[]}return o.length===1?[s+o[0]+i]:[s+o[0],...o.slice(1,-1),o[o.length-1]+i]}async function Lp(e,t,n){if(t.length<2)return null;let r=!1;for(let l of t)if(Rc(l)){r=!0;break}if(!r)return null;let s=ke(e.state.env),i=Re(e.state.env),o=[];for(let l of t){let c=Rc(l);if(c&&l.type==="DoubleQuoted"){let u=await Tp(e,l,c,n);o.push(u)}else if(l.type==="DoubleQuoted"||l.type==="SingleQuoted"){let u=await n(e,l);o.push([u])}else if(l.type==="Literal")o.push([l.value]);else if(l.type==="ParameterExpansion"){let u=await n(e,l);if(i)o.push(u?[u]:[]);else{let f=de(u,s,e.limits.maxArrayElements);o.push(f)}}else{let u=await n(e,l);if(i)o.push(u?[u]:[]);else{let f=de(u,s,e.limits.maxArrayElements);o.push(f)}}}let a=[];for(let l of o)if(l.length!==0)if(a.length===0)Oe(a,l,e.limits.maxArrayElements,"word expansion");else{let c=a.length-1;a[c]=a[c]+l[0];for(let u=1;u<l.length;u++)a.push(l[u])}return a}async function Oc(e,t){if(e.state.options.noglob)return{values:t,quoted:!1};let n=[];for(let r of t)if(At(r,e.state.shoptOptions.extglob)){let s=await is(e,r);Oe(n,s,e.limits.maxArrayElements,"glob expansion")}else n.push(r);return{values:n,quoted:!1}}async function is(e,t){let n=new Gt(e.fs,e.state.cwd,e.state.env,{globstar:e.state.shoptOptions.globstar,nullglob:e.state.shoptOptions.nullglob,failglob:e.state.shoptOptions.failglob,dotglob:e.state.shoptOptions.dotglob,extglob:e.state.shoptOptions.extglob,globskipdots:e.state.shoptOptions.globskipdots,maxGlobOperations:e.limits.maxGlobOperations,consumeOperation:()=>e.executionScope.consumeLimited("glob_operations",1,e.limits.maxGlobOperations,"glob expansion")}),r=await n.expand(t);if(r.length>0)return r;if(n.hasFailglob())throw new Lt(t);return n.hasNullglob()?[]:[t]}async function Mp(e,t,n,r,s,i){let o=n.some(a=>a.type==="Glob");if(!e.state.options.noglob&&o){let a=await i(e,t);if(At(a,e.state.shoptOptions.extglob)){let c=await is(e,a);if(c.length>0&&c[0]!==a)return{values:c,quoted:!1};if(c.length===0)return{values:[],quoted:!1}}let l=Bi(r);if(!Re(e.state.env)){let c=ke(e.state.env);return{values:de(l,c,e.limits.maxArrayElements),quoted:!1}}return{values:[l],quoted:!1}}if(!s&&!e.state.options.noglob&&At(r,e.state.shoptOptions.extglob)){let a=await i(e,t);if(At(a,e.state.shoptOptions.extglob)){let l=await is(e,a);if(l.length>0&&l[0]!==a)return{values:l,quoted:!1}}}if(r===""&&!s)return{values:[],quoted:!1};if(o&&!s){let a=Bi(r);if(!Re(e.state.env)){let l=ke(e.state.env);return{values:de(a,l,e.limits.maxArrayElements),quoted:!1}}return{values:[a],quoted:!1}}return{values:[r],quoted:s}}function Te(e,t,n){if(t.length>=e.limits.maxArrayElements)throw new x(`word splitting element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");t.push(n)}async function _c(e,t){let n=t.operation;if(!n||n.type!=="DefaultValue"&&n.type!=="AssignDefault"&&n.type!=="UseAlternative")return null;let r=n.word;if(!r||r.parts.length===0)return null;let s=await St(e,t.parameter),o=await ie(e,t.parameter,!1)==="",a=n.checkEmpty??!1,l;return n.type==="UseAlternative"?l=s&&!(a&&o):l=!s||a&&o,l?r.parts:null}function Fp(e){return e.type==="SingleQuoted"?!0:e.type==="DoubleQuoted"?e.parts.every(n=>n.type==="Literal"):!1}async function Bp(e,t){if(t.type!=="ParameterExpansion")return null;let n=await _c(e,t);if(!n||n.length<=1)return null;let r=n.some(i=>Fp(i)),s=n.some(i=>i.type==="Literal"||i.type==="ParameterExpansion"||i.type==="CommandSubstitution"||i.type==="ArithmeticExpansion");return r&&s?n:null}function Wp(e){return e.type==="DoubleQuoted"||e.type==="SingleQuoted"||e.type==="Literal"?!1:e.type==="Glob"?Oi(e.pattern):!(!(e.type==="ParameterExpansion"||e.type==="CommandSubstitution"||e.type==="ArithmeticExpansion")||e.type==="ParameterExpansion"&&Ol(e))}async function Tc(e,t,n,r,s){if(e.coverage?.hit("bash:expansion:word_split"),t.length===1&&t[0].type==="ParameterExpansion"){let d=t[0],p=await _c(e,d);if(p&&p.length>0&&p.length>1&&p.some(m=>m.type==="DoubleQuoted"||m.type==="SingleQuoted")&&p.some(m=>m.type==="Literal"||m.type==="ParameterExpansion"||m.type==="CommandSubstitution"||m.type==="ArithmeticExpansion"))return Ic(e,p,n,r,s)}let i=[],o=!1;for(let d of t){let p=Wp(d),h=d.type==="DoubleQuoted"||d.type==="SingleQuoted",m=p?await Bp(e,d):null,E=await s(e,d);i.push({value:E,isSplittable:p,isQuoted:h,mixedDefaultParts:m??void 0}),p&&(o=!0)}if(!o){let d=i.map(p=>p.value).join("");return d?[d]:[]}let a=[],l="",c=!1,u=!1,f=!1;for(let d of i)if(!d.isSplittable)u?d.isQuoted&&d.value===""?(l!==""&&Te(e,a,l),Te(e,a,""),c=!0,l="",u=!1,f=!0):d.value!==""?(l!==""&&Te(e,a,l),l=d.value,u=!1,f=!1):(l+=d.value,f=!1):(l+=d.value,f=d.isQuoted&&d.value==="");else if(d.mixedDefaultParts){let p=await Ic(e,d.mixedDefaultParts,n,r,s);if(p.length!==0)if(p.length===1)l+=p[0],c=!0;else{l+=p[0],Te(e,a,l),c=!0;for(let h=1;h<p.length-1;h++)Te(e,a,p[h]);l=p[p.length-1]}u=!1,f=!1}else{let{words:p,hadLeadingDelimiter:h,hadTrailingDelimiter:m}=Kr(d.value,n,e.limits.maxArrayElements);if(f&&h&&l===""&&(Te(e,a,""),c=!0),p.length===0)m&&(u=!0);else if(p.length===1)l+=p[0],c=!0,u=m;else{l+=p[0],Te(e,a,l),c=!0;for(let E=1;E<p.length-1;E++)Te(e,a,p[E]);l=p[p.length-1],u=m}f=!1}return l!==""?Te(e,a,l):a.length===0&&c&&Te(e,a,""),a}function Vp(e,t){return e.length>0&&t.includes(e[0])}async function Ic(e,t,n,r,s){let i=[];for(let u of t){let d=!(u.type==="DoubleQuoted"||u.type==="SingleQuoted"),p=await s(e,u);i.push({value:p,isSplittable:d})}let o=[],a="",l=!1,c=!1;for(let u of i)if(!u.isSplittable)c&&u.value!==""?(a!==""&&Te(e,o,a),a=u.value,c=!1):a+=u.value;else{Vp(u.value,n)&&a!==""&&(Te(e,o,a),a="",l=!0);let{words:d,hadTrailingDelimiter:p}=Kr(u.value,n,e.limits.maxArrayElements);if(d.length===0)p&&(c=!0);else if(d.length===1)a+=d[0],l=!0,c=p;else{a+=d[0],Te(e,o,a),l=!0;for(let h=1;h<d.length-1;h++)Te(e,o,d[h]);a=d[d.length-1],c=p}}return a!==""?Te(e,o,a):o.length===0&&l&&Te(e,o,""),o}function Lc(e){switch(e.type){case"Literal":return e.value;case"SingleQuoted":return e.value;case"Escaped":return e.value;default:return null}}function Mc(e){switch(e.type){case"SingleQuoted":case"Escaped":case"DoubleQuoted":return!0;case"Literal":return e.value==="";default:return!1}}var _n=class{baseFs;mounts=new Map;constructor(t){if(this.baseFs=t?.base??new ft,t?.mounts)for(let{mountPoint:n,filesystem:r}of t.mounts)this.mount(n,r)}mount(t,n){this.validateMountPath(t);let r=W(t);this.validateMount(r),this.mounts.set(r,{mountPoint:r,filesystem:n})}unmount(t){let n=W(t);if(!this.mounts.has(n))throw new Error(`No filesystem mounted at '${t}'`);this.mounts.delete(n)}getMounts(){return Array.from(this.mounts.values()).map(t=>({mountPoint:t.mountPoint,filesystem:t.filesystem}))}isMountPoint(t){let n=W(t);return this.mounts.has(n)}validateMountPath(t){let n=t.split("/");for(let r of n)if(r==="."||r==="..")throw new Error(`Invalid mount point '${t}': contains '.' or '..' segments`)}validateMount(t){if(t==="/")throw new Error("Cannot mount at root '/'");for(let n of this.mounts.keys())if(n!==t){if(t.startsWith(`${n}/`))throw new Error(`Cannot mount at '${t}': inside existing mount '${n}'`);if(n.startsWith(`${t}/`))throw new Error(`Cannot mount at '${t}': would contain existing mount '${n}'`)}}routePath(t){V(t,"access");let n=W(t),r=null,s=0;for(let i of this.mounts.values()){let o=i.mountPoint;if(n===o)return{fs:i.filesystem,relativePath:"/"};n.startsWith(`${o}/`)&&o.length>s&&(r=i,s=o.length)}if(r){let i=n.slice(s);return{fs:r.filesystem,relativePath:i||"/"}}return{fs:this.baseFs,relativePath:n}}getChildMountPoints(t){let n=W(t),r=n==="/"?"/":`${n}/`,s=[];for(let i of this.mounts.keys())if(i.startsWith(r)){let a=i.slice(r.length).split("/")[0];a&&!s.includes(a)&&s.push(a)}return s}async readFile(t,n){let{fs:r,relativePath:s}=this.routePath(t);return r.readFile(s,n)}async readFileBytes(t){let{fs:n,relativePath:r}=this.routePath(t);return vn(n,r)}async readFileBuffer(t){let{fs:n,relativePath:r}=this.routePath(t);return n.readFileBuffer(r)}async writeFile(t,n,r){let{fs:s,relativePath:i}=this.routePath(t);return s.writeFile(i,n,r)}async appendFile(t,n,r){let{fs:s,relativePath:i}=this.routePath(t);return s.appendFile(i,n,r)}async exists(t){let n=W(t);if(this.mounts.has(n)||this.getChildMountPoints(n).length>0)return!0;let{fs:s,relativePath:i}=this.routePath(t);return s.exists(i)}async stat(t){let n=W(t),r=this.mounts.get(n);if(r)try{return await r.filesystem.stat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(n).length>0)try{return await this.baseFs.stat(n)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:o}=this.routePath(t);return i.stat(o)}async lstat(t){let n=W(t),r=this.mounts.get(n);if(r)try{return await r.filesystem.lstat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(n).length>0)try{return await this.baseFs.lstat(n)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:o}=this.routePath(t);return i.lstat(o)}async mkdir(t,n){let r=W(t);if(this.mounts.has(r)){if(n?.recursive)return;throw new Error(`EEXIST: directory already exists, mkdir '${t}'`)}if(this.getChildMountPoints(r).length>0&&n?.recursive)return;let{fs:i,relativePath:o}=this.routePath(t);return i.mkdir(o,n)}async readdir(t){let n=W(t),r=new Set,s=null,{fs:i,relativePath:o}=this.routePath(t);try{let l=await i.readdir(o);for(let c of l)r.add(c)}catch(l){let c=l.code,u=l.message||"";if(c!=="ENOENT"&&!u.includes("ENOENT"))throw l;s=l}let a=this.getChildMountPoints(n);for(let l of a)r.add(l);if(r.size===0&&s&&!this.mounts.has(n))throw s;return Array.from(r).sort()}async rm(t,n){let r=W(t);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot remove '${t}'`);if(this.getChildMountPoints(r).length>0)throw new Error(`EBUSY: contains mount points, cannot remove '${t}'`);let{fs:i,relativePath:o}=this.routePath(t);return i.rm(o,n)}async cp(t,n,r){if((await this.stat(t)).isDirectory&&Ct(t,n))throw new Error(`EINVAL: cannot copy '${t}' into itself, '${n}'`);let i=this.routePath(t),o=this.routePath(n);return i.fs===o.fs?i.fs.cp(i.relativePath,o.relativePath,r):this.crossMountCopy(t,n,r)}async mv(t,n){let r=W(t);if((await this.stat(t)).isDirectory&&Ct(t,n))throw new Error(`EINVAL: cannot move '${t}' into itself, '${n}'`);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot move '${t}'`);let i=this.routePath(t),o=this.routePath(n);if(i.fs===o.fs)return i.fs.mv(i.relativePath,o.relativePath);await this.cp(t,n,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,n){return Bt(t,n)}getAllPaths(){let t=new Set;for(let n of this.baseFs.getAllPaths())t.add(n);for(let n of this.mounts.keys()){let r=n.split("/").filter(Boolean),s="";for(let o of r)s=`${s}/${o}`,t.add(s);let i=this.mounts.get(n);if(i)for(let o of i.filesystem.getAllPaths())o==="/"?t.add(n):t.add(`${n}${o}`)}return Array.from(t).sort()}async chmod(t,n){let r=W(t),s=this.mounts.get(r);if(s)return s.filesystem.chmod("/",n);let{fs:i,relativePath:o}=this.routePath(t);return i.chmod(o,n)}async symlink(t,n){let{fs:r,relativePath:s}=this.routePath(n);return r.symlink(t,s)}async link(t,n){let r=this.routePath(t),s=this.routePath(n);if(r.fs!==s.fs)throw new Error(`EXDEV: cross-device link not permitted, link '${t}' -> '${n}'`);return r.fs.link(r.relativePath,s.relativePath)}async readlink(t){let{fs:n,relativePath:r}=this.routePath(t);return n.readlink(r)}async realpath(t){let n=W(t);if(this.mounts.get(n))return n;let{fs:s,relativePath:i}=this.routePath(t),o=await s.realpath(i);for(let[a,l]of this.mounts)if(n===a||n.startsWith(`${a}/`))return o==="/"?a:`${a}${o}`;return o}async crossMountCopy(t,n,r){let s=await this.lstat(t);if(s.isFile){let i=await this.readFileBuffer(t);await this.writeFile(n,i),await this.chmod(n,s.mode)}else if(s.isDirectory){if(!r?.recursive)throw new Error(`cp: ${t} is a directory (not copied)`);await this.mkdir(n,{recursive:!0});let i=await this.readdir(t);for(let o of i){let a=Nt(t,o),l=Nt(n,o);await this.crossMountCopy(a,l,r)}}else if(s.isSymbolicLink){let i=await this.readlink(t);await this.symlink(i,n)}}async utimes(t,n,r){let{fs:s,relativePath:i}=this.routePath(t);return s.utimes(i,n,r)}};var os="/dev/fd",Bc=63,zp=10,Fc=Bc-zp+1,qi=class extends ft{isLiveDescriptor;constructor(t){super(),this.isLiveDescriptor=t}assertLiveDescriptor(t,n){this.isLiveDescriptor(t)||this.refuse(t,n)}refuse(t,n){throw new Error(`EROFS: read-only file system, ${n} '${os}${t}'`)}async writeFile(t,n,r){return this.assertLiveDescriptor(t,"write"),super.writeFile(t,n,r)}async appendFile(t,n,r){return this.assertLiveDescriptor(t,"append"),super.appendFile(t,n,r)}async rm(t,n){return this.assertLiveDescriptor(t,"rm"),super.rm(t,n)}async mkdir(t,n){this.refuse(t,"mkdir")}async cp(t,n){this.refuse(n,"cp")}async mv(t,n){this.refuse(n,"mv")}async symlink(t,n){this.refuse(n,"symlink")}async link(t,n){this.refuse(n,"link")}async chmod(t,n){this.refuse(t,"chmod")}async utimes(t,n,r){this.refuse(t,"utimes")}};function Up(e){let t=new qi(n=>Wc(e).some(r=>r.path===`${os}${n}`));e.fs=new _n({base:e.fs,mounts:[{mountPoint:os,filesystem:t}]}),e.state.processSubstitutionFsMounted=!0}async function qp(e,t,n){try{await e.fs.writeFile(t,n,"binary");return}catch(r){if(e.state.processSubstitutionFsMounted)throw r;Up(e)}await e.fs.writeFile(t,n,"binary")}async function jp(e,t){try{await e.fs.rm(t,{force:!0})}catch{}}function Wc(e){let t=e.state.processSubstitutions;if(t)return t;let n=[];return e.state.processSubstitutions=n,n}async function Vc(e,t,n){let r=e.substitutionDepth??0,s=e.limits.maxSubstitutionDepth;if(r>=s)throw new x(`Process substitution nesting limit exceeded (${s})`,"substitution_depth");let i=e.substitutionDepth,o=new Map(e.state.env),a=ot(e.state.arrays),l=e.state.cwd,c=e.state.bashPid,u=e.state.suppressVerbose,f=e.state.groupStdin,d=e.state.lastExitCode,p=e.state.env.get("?");e.substitutionDepth=r+1,e.state.bashPid=e.state.nextVirtualPid++,e.state.suppressVerbose=!0,n!==void 0&&(e.state.groupStdin=n);let h;try{h=await e.executeScript(t)}catch(m){if(m instanceof x)throw m;if(m instanceof j)return{stdout:m.stdout,stderr:m.stderr,exitCode:m.exitCode};throw m}finally{e.substitutionDepth=i,e.state.env=o,e.state.arrays=a,e.state.cwd=l,e.state.bashPid=c,e.state.suppressVerbose=u,e.state.groupStdin=f,e.state.lastExitCode=d,p!==void 0?e.state.env.set("?",p):e.state.env.delete("?")}return h}async function zc(e,t){let n=Wc(e);if(n.length>=Fc)throw new x(`Process substitution limit exceeded (${Fc} concurrent)`,"file_descriptors");let r="";if(t.direction==="input"){let o=await Vc(e,t.body,void 0);if(o.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+o.stderr),r=xt(o),r.length>e.limits.maxStringLength)throw new x(`process substitution: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length")}let s=Bc-n.length,i=`${os}/${s}`;n.push({fd:s,path:i,direction:t.direction,body:t.body});try{await qp(e,i,r)}catch(o){throw n.pop(),o}return i}function Uc(e){return e.state.processSubstitutions?.length??0}var Gp={stdout:"",stderr:""};async function ji(e,t){let n=e.state.processSubstitutions;if(!n||n.length<=t)return Gp;let r="",s="";for(;n.length>t;){let i=n[n.length-1],o="";if(i.direction==="output")try{o=await vn(e.fs,i.path)}catch{}if(await jp(e,i.path),n.pop(),i.direction==="output"){let a=await Vc(e,i.body,o);r+=xt(a),s+=a.stderr}}return{stdout:r,stderr:s}}function Kt(e,t,n){if(e.length>t)throw new x(`${n}: string length limit exceeded (${t} bytes)`,"string_length")}async function yt(e,t,n=!1){let r=[];for(let s of t)r.push(await et(e,s,n));return r.join("")}function Zp(e){return Mc(e)}function jc(e){if(e.parts.length===0)return!0;for(let t of e.parts)if(!Zp(t))return!1;return!0}function Hp(e,t,n=!1){let r=Lc(t);if(r!==null)return r;switch(t.type){case"TildeExpansion":return n?t.user===null?"~":`~${t.user}`:(e.coverage?.hit("bash:expansion:tilde"),t.user===null?e.state.env.get("HOME")??"/home/user":t.user==="root"?"/root":`~${t.user}`);case"Glob":return Wi(e,t.pattern);default:return null}}async function se(e,t){return Zi(e,t)}async function Gc(e,t){let n=[];for(let r of t.parts)if(r.type==="Escaped")n.push(Dn(r.value));else if(r.type==="SingleQuoted")n.push(r.value);else if(r.type==="DoubleQuoted"){let s=await yt(e,r.parts);n.push(s)}else if(r.type==="TildeExpansion"){let s=await et(e,r);n.push(Dn(s))}else n.push(await et(e,r));return n.join("")}async function Zc(e,t){let n=[];for(let r of t.parts)if(r.type==="Escaped"){let s=r.value;"()|*?[]".includes(s)?n.push(`\\${s}`):n.push(s)}else if(r.type==="SingleQuoted")n.push(Je(r.value));else if(r.type==="DoubleQuoted"){let s=await yt(e,r.parts);n.push(Je(s))}else n.push(await et(e,r));return n.join("")}async function Hc(e,t){let n=[];for(let r of t.parts)if(r.type==="SingleQuoted")n.push(Je(r.value));else if(r.type==="Escaped"){let s=r.value;"*?[]\\()|".includes(s)?n.push(`\\${s}`):n.push(s)}else if(r.type==="DoubleQuoted"){let s=await yt(e,r.parts);n.push(Je(s))}else r.type==="Glob"?tc(r.pattern)?n.push(await rc(e,r.pattern)):n.push(Wi(e,r.pattern)):r.type==="Literal"?n.push(r.value):n.push(await et(e,r));return n.join("")}function ls(e){for(let t of e)if(t.type==="BraceExpansion"||t.type==="DoubleQuoted"&&ls(t.parts))return!0;return!1}var qc=1e5;async function Qc(e,t,n={count:0}){let r=()=>{n.count++,e.executionScope.consumeLimited("brace_operations",1,Math.min(qc,e.limits.maxBraceExpansionResults),"brace expansion")},s=(o,a)=>{if(o.length>=e.limits.maxBraceExpansionResults)throw new x(`brace expansion result limit exceeded (${e.limits.maxBraceExpansionResults})`,"array_elements");r(),o.push(a)},i=[[]];for(let o of t)if(o.type==="BraceExpansion"){let a=[],l=!1,c="";for(let d of o.items)if(d.type==="Range"){let p=Fi(d.start,d.end,d.step,d.startStr,d.endStr,{maxResults:e.limits.maxBraceExpansionResults,maxStringBytes:e.limits.maxStringLength});if(p.expanded)for(let h of p.expanded)s(a,h);else{l=!0,c=p.literal;break}}else{let p=await Qc(e,d.word.parts,n);for(let h of p){let m=[];for(let E of h)typeof E=="string"?m.push(E):m.push(await et(e,E));s(a,m.join(""))}}if(l){for(let d of i)r(),d.push(c);continue}if(i.length*a.length>e.limits.maxBraceExpansionResults||n.count>qc)throw new x(`brace expansion result limit exceeded (${e.limits.maxBraceExpansionResults})`,"array_elements");let f=[];for(let d of i)for(let p of a){if(f.length>=e.limits.maxBraceExpansionResults)throw new x(`brace expansion result limit exceeded (${e.limits.maxBraceExpansionResults})`,"array_elements");r(),f.push([...d,p])}i=f}else for(let a of i)r(),a.push(o);return i}async function Kc(e,t){let n=t.parts;if(!ls(n))return[await se(e,t)];let r=await Qc(e,n),s=[];for(let i of r){let o=[];for(let a of i)typeof a=="string"?o.push(a):o.push(await et(e,a));s.push(Vi(e,o.join("")))}return s}function Qp(){return{expandWordAsync:Zi,expandWordForGlobbing:Hc,expandWordWithBracesAsync:Kc,expandWordPartsAsync:yt,expandPart:et,expandParameterAsync:as,hasBraceExpansion:ls,evaluateArithmetic:Y,buildIfsCharClassPattern:Dl,smartWordSplit:Tc}}async function gt(e,t){return Dc(e,t,Qp())}function Kp(e){for(let t of e){if(t.type==="ParameterExpansion")return t.parameter;if(t.type==="Literal")return t.value}return""}function Gi(e,t){if(Number.parseInt(e.state.env.get("#")||"0",10)<2)return!1;function r(s){for(let i of s)if(i.type==="DoubleQuoted"){for(let o of i.parts)if(o.type==="ParameterExpansion"&&o.parameter==="@"&&!o.operation)return!0}return!1}return r(t.parts)}async function Xc(e,t){if(Gi(e,t))return{error:`bash: $@: ambiguous redirect
|
|
107
|
+
`};let n=t.parts,{hasQuoted:r}=fr(n);if(ls(n)&&(await Kc(e,t)).length>1)return{error:`bash: ${n.map(p=>p.type==="Literal"?p.value:p.type==="BraceExpansion"?`{${p.items.map(m=>{if(m.type==="Range"){let E=m.step?`..${m.step}`:"";return`${m.startStr??m.start}..${m.endStr??m.end}${E}`}return m.word.parts.map(E=>E.type==="Literal"?E.value:"").join("")}).join(",")}}`:"").join("")}: ambiguous redirect
|
|
108
|
+
`};let s=await Zi(e,t),{hasParamExpansion:i,hasCommandSub:o}=fr(n);if((i||o)&&!r&&!Re(e.state.env)){let f=ke(e.state.env);if(de(s,f,e.limits.maxArrayElements).length>1)return{error:`bash: $${Kp(n)}: ambiguous redirect
|
|
109
|
+
`}}if(r||e.state.options.noglob||n.some(f=>f.type==="ProcessSubstitution"))return{target:s};let l=await Hc(e,t);if(!At(l,e.state.shoptOptions.extglob))return{target:s};let c=new Gt(e.fs,e.state.cwd,e.state.env,{globstar:e.state.shoptOptions.globstar,nullglob:e.state.shoptOptions.nullglob,failglob:e.state.shoptOptions.failglob,dotglob:e.state.shoptOptions.dotglob,extglob:e.state.shoptOptions.extglob,globskipdots:e.state.shoptOptions.globskipdots,maxGlobOperations:e.limits.maxGlobOperations,consumeOperation:()=>e.executionScope.consumeLimited("glob_operations",1,e.limits.maxGlobOperations,"glob expansion")}),u=await c.expand(l);return u.length===0?c.hasFailglob()?{error:`bash: no match: ${s}
|
|
80
110
|
`}:{target:s}:u.length===1?{target:u[0]}:{error:`bash: ${s}: ambiguous redirect
|
|
81
|
-
`}}async function
|
|
82
|
-
`,0;let
|
|
83
|
-
`,0;
|
|
84
|
-
`);let n=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw new
|
|
85
|
-
`);n=r}throw new
|
|
86
|
-
`)}catch{return
|
|
87
|
-
`)}}let u=c||"/";if(s)try{u=await e.fs.realpath(u)}catch{}return e.state.previousDir=e.state.cwd,e.state.cwd=u,e.state.env.set("PWD",e.state.cwd),e.state.env.set("OLDPWD",e.state.previousDir),
|
|
88
|
-
`:"")}function
|
|
89
|
-
`,!1;if(
|
|
90
|
-
`,!1}return
|
|
91
|
-
`,2):
|
|
92
|
-
`,2):
|
|
93
|
-
`,2):
|
|
94
|
-
`)&&!s&&!i){
|
|
111
|
+
`}}async function Zi(e,t){let n=t.parts,r=n.length;if(r===1){let o=await et(e,n[0]);return Kt(o,e.limits.maxStringLength,"word expansion"),o}let s=[];for(let o=0;o<r;o++)s.push(await et(e,n[o]));let i=s.join("");return Kt(i,e.limits.maxStringLength,"word expansion"),i}async function et(e,t,n=!1){if(t.type==="ParameterExpansion")return as(e,t,n);let r=Hp(e,t,n);if(r!==null)return r;switch(t.type){case"DoubleQuoted":{let s=[];for(let i of t.parts)s.push(await et(e,i,!0));return s.join("")}case"CommandSubstitution":{let s=Bl(t.body);if(s)try{let p=await se(e,s.target),h=p.startsWith("/")?p:`${e.state.cwd}/${p}`,m=await e.fs.readFile(h);e.state.lastExitCode=0,e.state.env.set("?","0");let E=m.replace(/\n+$/,"");return Kt(E,e.limits.maxStringLength,"command substitution"),E}catch(p){if(p instanceof x)throw p;return e.state.lastExitCode=1,e.state.env.set("?","1"),""}let i=e.substitutionDepth??0,o=e.limits.maxSubstitutionDepth;if(i>=o)throw new x(`Command substitution nesting limit exceeded (${o})`,"substitution_depth");let a=e.substitutionDepth;e.substitutionDepth=i+1;let l=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let c=new Map(e.state.env),u=ot(e.state.arrays),f=e.state.cwd,d=e.state.suppressVerbose;e.state.suppressVerbose=!0;try{let p=await e.executeScript(t.body),h=p.exitCode;e.state.env=c,e.state.arrays=u,e.state.cwd=f,e.state.suppressVerbose=d,e.state.lastExitCode=h,e.state.env.set("?",String(h)),p.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+p.stderr),e.state.bashPid=l,e.substitutionDepth=a;let m=p.stdout.replace(/\n+$/,"");return Kt(m,e.limits.maxStringLength,"command substitution"),m}catch(p){if(e.state.env=c,e.state.arrays=u,e.state.cwd=f,e.state.bashPid=l,e.substitutionDepth=a,e.state.suppressVerbose=d,p instanceof x)throw p;if(p instanceof j){e.state.lastExitCode=p.exitCode,e.state.env.set("?",String(p.exitCode)),p.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+p.stderr);let h=p.stdout.replace(/\n+$/,"");return Kt(h,e.limits.maxStringLength,"command substitution"),h}throw p}}case"ProcessSubstitution":return zc(e,t);case"ArithmeticExpansion":{let s=t.expression.originalText;if(s&&/\$[a-zA-Z_][a-zA-Z0-9_]*(?![{[(])/.test(s)){let o=await Fl(e,s),a=new H,l=re(a,o);return String(await Y(e,l.expression,!0))}return String(await Y(e,t.expression.expression,!0))}case"BraceExpansion":{let s=[];for(let i of t.items)if(i.type==="Range"){let o=Fi(i.start,i.end,i.step,i.startStr,i.endStr,{maxResults:e.limits.maxBraceExpansionResults,maxStringBytes:e.limits.maxStringLength});if(o.expanded)s.push(...o.expanded);else return o.literal}else s.push(await se(e,i.word));return s.join(" ")}default:return""}}async function as(e,t,n=!1){let{parameter:r}=t,{operation:s}=t,i=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(i){let[,d,p]=i;if(e.state.associativeArrays?.has(d)||p.includes("$(")||p.includes("`")||p.includes("${")){let m=await Li(e,p);r=`${d}[${m}]`}}else if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)&&ue(e,r)){let d=Fe(e,r);if(d&&d!==r){let p=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(p){let[,h,m]=p;if(e.state.associativeArrays?.has(h)||m.includes("$(")||m.includes("`")||m.includes("${")){let b=await Li(e,m);r=`${h}[${b}]`}}}}let o=s&&(s.type==="DefaultValue"||s.type==="AssignDefault"||s.type==="UseAlternative"||s.type==="ErrorIfUnset"),a=await ie(e,r,!o);if(!s)return a;let l=!await St(e,r),{isEmpty:c,effectiveValue:u}=ec(e,r,a,n),f={value:a,isUnset:l,isEmpty:c,effectiveValue:u,inDoubleQuotes:n};switch(s.type){case"DefaultValue":return Vl(e,s,f,yt);case"AssignDefault":return zl(e,r,s,f,yt);case"ErrorIfUnset":return Ul(e,r,s,f,yt);case"UseAlternative":return ql(e,s,f,yt);case"PatternRemoval":{let d=await jl(e,a,s,yt,et);return Kt(d,e.limits.maxStringLength,"pattern removal"),d}case"PatternReplacement":{let d=await Gl(e,a,s,yt,et);return Kt(d,e.limits.maxStringLength,"pattern replacement"),d}case"Length":return Zl(e,r,a);case"LengthSliceError":throw new Ke(r);case"BadSubstitution":throw new Ke(s.text);case"Substring":return Hl(e,r,a,s);case"CaseModification":{let d=await Ql(e,a,s,yt,as);return Kt(d,e.limits.maxStringLength,"case modification"),d}case"Transform":return Kl(e,r,a,l,s);case"Indirection":return Xl(e,r,a,l,s,as,n);case"ArrayKeys":return Yl(e,s);case"VarNamePrefix":return Jl(e,s);default:return a}}function Jc(){return{visited:new Set,depth:0}}function Xp(e,t,n){switch(n){case"+":return e+t;case"-":return e-t;case"*":return e*t;case"/":if(t===0)throw new ce("division by 0");return Math.trunc(e/t);case"%":if(t===0)throw new ce("division by 0");return e%t;case"**":if(t<0)throw new ce("exponent less than 0");return e**t;case"<<":return e<<t;case">>":return e>>t;case"<":return e<t?1:0;case"<=":return e<=t?1:0;case">":return e>t?1:0;case">=":return e>=t?1:0;case"==":return e===t?1:0;case"!=":return e!==t?1:0;case"&":return e&t;case"|":return e|t;case"^":return e^t;case",":return t;default:return 0}}function Yc(e,t,n){switch(n){case"=":return t;case"+=":return e+t;case"-=":return e-t;case"*=":return e*t;case"/=":return t!==0?Math.trunc(e/t):0;case"%=":return t!==0?e%t:0;case"<<=":return e<<t;case">>=":return e>>t;case"&=":return e&t;case"|=":return e|t;case"^=":return e^t;default:return t}}function Yp(e,t){switch(t){case"-":return-e;case"+":return+e;case"!":return e===0?1:0;case"~":return~e;default:return e}}async function Jp(e,t){let n=e.state.env.get(t);if(n!==void 0)return n;let r=le(e,t,0);return r!==void 0?r:await ie(e,t)}async function eh(e,t,n){if(!t)return 0;let r=Number.parseInt(t,10);if(!Number.isNaN(r)&&/^-?\d+$/.test(t.trim()))return r;let s=t.trim();if(!s)return 0;let i=new H,{expr:o,pos:a}=On(i,s,0);if(a<s.length){let l=s.slice(a).trim(),c=l.split(/\s+/)[0]||l;throw new ce(`syntax error in expression (error token is "${c}")`,"","")}return await Ln(e,o,!1,n)}async function cs(e,t,n,r){if(r.depth>100)throw new ce("maximum variable indirection depth exceeded");if(r.visited.has(t))throw new ce(`arithmetic variable cycle detected at ${t}`);r.visited.add(t),r.depth++;try{return await eh(e,n,r)}finally{r.depth--,r.visited.delete(t)}}async function Hi(e,t,n){if(n.depth>100)throw new ce("maximum variable indirection depth exceeded");if(n.visited.has(t))throw new ce(`arithmetic variable cycle detected at ${t}`);n.visited.add(t),n.depth++;try{let r=await Jp(e,t);if(!r)return 0;let s=Number.parseInt(r,10);if(!Number.isNaN(s)&&/^-?\d+$/.test(r.trim()))return s;let i=r.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i))return await Hi(e,i,n);let o=new H,{expr:a,pos:l}=On(o,i,0);if(l<i.length){let c=i.slice(l).trim(),u=c.split(/\s+/)[0]||c;throw new ce(`${i}: syntax error in expression (error token is "${u}")`)}return await Ln(e,a,!1,n)}finally{n.depth--,n.visited.delete(t)}}async function us(e,t){if(t.startsWith("#")){let f=t.slice(1),d=f.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(d){let h=d[1],m=Q(e,h);return String(m.length)}let p=e.state.env.get(f)||"";return String(p.length)}if(t.startsWith("!")){let f=t.slice(1),d=e.state.env.get(f)||"";return e.state.env.get(d)||""}let n=[":-",":=",":?",":+","-","=","?","+"],r=-1,s="";for(let f of n){let d=t.indexOf(f);d>0&&(r===-1||d<r)&&(r=d,s=f)}if(r===-1)return await ie(e,t);let i=t.slice(0,r),o=t.slice(r+s.length),a=e.state.env.get(i),l=a===void 0,c=a==="",u=s.startsWith(":");switch(s){case":-":case"-":return l||u&&c?o:a||"";case":=":case"=":return l||u&&c?(e.state.env.set(i,o),o):a||"";case":+":case"+":return!(l||u&&c)?o:"";case":?":case"?":{if(l||u&&c)throw new Error(o||`${i}: parameter null or not set`);return a||""}default:return a||""}}async function Y(e,t,n=!1){return Ln(e,t,n,Jc())}async function Ln(e,t,n,r){let s=(i,o=n)=>Ln(e,i,o,r);switch(t.type){case"ArithNumber":if(Number.isNaN(t.value))throw new ce("value too great for base");return t.value;case"ArithVariable":return await Hi(e,t.name,r);case"ArithSpecialVar":{let o=(await ie(e,t.name)).trim();if(!o)return 0;let a=Number.parseInt(o,10);if(!Number.isNaN(a)&&/^-?\d+$/.test(o))return a;let l=new H,{expr:c}=On(l,o,0);return await s(c)}case"ArithNested":return await s(t.expression);case"ArithCommandSubst":{if(e.execFn){let i=await e.execFn(t.command,{signal:e.state.signal});i.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+i.stderr);let o=i.stdout.trim();return Number.parseInt(o,10)||0}return 0}case"ArithBracedExpansion":{let i=await us(e,t.content);return Number.parseInt(i,10)||0}case"ArithDynamicBase":{let i=await us(e,t.baseExpr),o=Number.parseInt(i,10);if(o<2||o>64)return 0;let a=`${o}#${t.value}`;return or(a)}case"ArithDynamicNumber":{let o=await us(e,t.prefix)+t.suffix;return or(o)}case"ArithArrayElement":{let i=e.state.associativeArrays?.has(t.array),o=async a=>{let l=le(e,t.array,a);return l!==void 0?await cs(e,`${t.array}[${a}]`,l,r):0};if(t.stringKey!==void 0)return await o(t.stringKey);if(i&&t.index?.type==="ArithVariable"&&!t.index.hasDollarPrefix)return await o(t.index.name);if(i&&t.index?.type==="ArithVariable"&&t.index.hasDollarPrefix){let a=await ie(e,t.index.name);return await o(a)}if(t.index){let a=await s(t.index);if(a<0){let u=Q(e,t.array),f=e.state.currentLine;if(u.length===0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${f}: ${t.array}: bad array subscript
|
|
112
|
+
`,0;let p=Math.max(...u.map(([h])=>typeof h=="number"?h:0))+1+a;if(p<0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${f}: ${t.array}: bad array subscript
|
|
113
|
+
`,0;a=p}let l=`${t.array}[${a}]`,c=le(e,t.array,a);if(c!==void 0)return cs(e,l,c,r);if(a===0){let u=e.state.env.get(t.array);if(u!==void 0)return cs(e,t.array,u,r)}if(e.state.options.nounset&&!(e.state.env.has(t.array)||Ce(e,t.array)))throw new Ve(`${t.array}[${a}]`);return 0}return 0}case"ArithDoubleSubscript":throw new ce("double subscript","","");case"ArithNumberSubscript":throw new ce(`${t.number}${t.errorToken}: syntax error: invalid arithmetic operator (error token is "${t.errorToken}")`);case"ArithSyntaxError":throw new ce(t.message,"","",!0);case"ArithSingleQuote":{if(n)throw new ce(`syntax error: operand expected (error token is "'${t.content}'")`);return t.value}case"ArithBinary":{if(t.operator==="||")return await s(t.left)||await s(t.right)?1:0;if(t.operator==="&&")return await s(t.left)&&await s(t.right)?1:0;let i=await s(t.left),o=await s(t.right);return Xp(i,o,t.operator)}case"ArithUnary":{let i=await s(t.operand);if(t.operator==="++"||t.operator==="--"){if(t.operand.type==="ArithVariable"){let o=t.operand.name,a=Number.parseInt(await ie(e,o),10)||0,l=t.operator==="++"?a+1:a-1;return e.state.env.set(o,String(l)),t.prefix?l:a}if(t.operand.type==="ArithArrayElement"){let o=t.operand.array,a=e.state.associativeArrays?.has(o),l;if(t.operand.stringKey!==void 0)l=t.operand.stringKey;else if(a&&t.operand.index?.type==="ArithVariable"&&!t.operand.index.hasDollarPrefix)l=t.operand.index.name;else if(a&&t.operand.index?.type==="ArithVariable"&&t.operand.index.hasDollarPrefix)l=await ie(e,t.operand.index.name);else if(t.operand.index){let f=await s(t.operand.index);l=String(f)}else return i;let c=Number.parseInt(le(e,o,l)||"0",10)||0,u=t.operator==="++"?c+1:c-1;return G(e,o,l,String(u),a?"associative":"indexed"),t.prefix?u:c}if(t.operand.type==="ArithConcat"){let o="";for(let a of t.operand.parts)o+=await Tn(e,a,n,r);if(o&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){let a=Number.parseInt(e.state.env.get(o)||"0",10)||0,l=t.operator==="++"?a+1:a-1;return e.state.env.set(o,String(l)),t.prefix?l:a}}if(t.operand.type==="ArithDynamicElement"){let o="";if(t.operand.nameExpr.type==="ArithConcat")for(let a of t.operand.nameExpr.parts)o+=await Tn(e,a,n,r);else t.operand.nameExpr.type==="ArithVariable"&&(o=t.operand.nameExpr.hasDollarPrefix?await ie(e,t.operand.nameExpr.name):t.operand.nameExpr.name);if(o&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){let a=await s(t.operand.subscript),l=Number.parseInt(le(e,o,a)||"0",10)||0,c=t.operator==="++"?l+1:l-1;return G(e,o,a,String(c)),t.prefix?c:l}}return i}return Yp(i,t.operator)}case"ArithTernary":return await s(t.condition)?await s(t.consequent):await s(t.alternate);case"ArithAssignment":{let i=t.variable,o=i,a;if(t.stringKey!==void 0)a=t.stringKey;else if(t.subscript){let d=e.state.associativeArrays?.has(i);if(d&&t.subscript.type==="ArithVariable"&&!t.subscript.hasDollarPrefix)a=t.subscript.name;else if(d&&t.subscript.type==="ArithVariable"&&t.subscript.hasDollarPrefix)a=await ie(e,t.subscript.name)||"\\";else if(d){let p=await s(t.subscript);a=String(p)}else{let p=await s(t.subscript);if(p<0){let h=Q(e,i);h.length>0&&(p=Math.max(...h.map(([E])=>typeof E=="number"?E:0))+1+p)}a=String(p)}}let l=a===void 0?e.state.env.get(o):le(e,i,a),c=Number.parseInt(l||"0",10)||0,u=await s(t.value),f=Yc(c,u,t.operator);return a===void 0?e.state.env.set(o,String(f)):G(e,i,a,String(f),e.state.associativeArrays?.has(i)?"associative":"indexed"),f}case"ArithGroup":return await s(t.expression);case"ArithConcat":{let i="";for(let o of t.parts)i+=await Tn(e,o,n,r);return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)?await Hi(e,i,r):Number.parseInt(i,10)||0}case"ArithDynamicAssignment":{let i="";if(t.target.type==="ArithConcat")for(let u of t.target.parts)i+=await Tn(e,u,n,r);else t.target.type==="ArithVariable"&&(i=t.target.hasDollarPrefix?await ie(e,t.target.name):t.target.name);if(!i||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i))return 0;let o=i;if(t.subscript){let u=await s(t.subscript);o=`${i}_${u}`}let a=Number.parseInt(e.state.env.get(o)||"0",10)||0,l=await s(t.value),c=Yc(a,l,t.operator);return e.state.env.set(o,String(c)),c}case"ArithDynamicElement":{let i="";if(t.nameExpr.type==="ArithConcat")for(let c of t.nameExpr.parts)i+=await Tn(e,c,n,r);else t.nameExpr.type==="ArithVariable"&&(i=t.nameExpr.hasDollarPrefix?await ie(e,t.nameExpr.name):t.nameExpr.name);if(!i||!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i))return 0;let o=await s(t.subscript),a=`${i}_${o}`,l=e.state.env.get(a);return l!==void 0?cs(e,a,l,r):0}default:return 0}}async function Tn(e,t,n=!1,r=Jc()){switch(t.type){case"ArithNumber":return String(t.value);case"ArithSingleQuote":return String(await Ln(e,t,n,r));case"ArithVariable":return t.hasDollarPrefix?await ie(e,t.name):t.name;case"ArithSpecialVar":return await ie(e,t.name);case"ArithBracedExpansion":return await us(e,t.content);case"ArithCommandSubst":return e.execFn?(await e.execFn(t.command,{signal:e.state.signal})).stdout.trim():"0";case"ArithConcat":{let s="";for(let i of t.parts)s+=await Tn(e,i,n,r);return s}default:return String(await Ln(e,t,n,r))}}async function eu(e,t){let n="",r=0;for(let v of t.parts){let k=v.type==="Literal"?v.value:"\0",A=B(k);if(A>e.limits.maxStringLength-r)throw new x(`array assignment string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");n+=k,r+=A}let s=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);if(!s||!n.endsWith(")"))return null;let i=s[1],o=[],a=[],l=!1,c="",u=0,f=0,d=!1,p=!0,h=v=>{let k=B(v);if(k>e.limits.maxStringLength-f-u)throw new x(`array assignment string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");c+=v,u+=k},m=(v,k=!1)=>{if(o.length>=e.limits.maxArrayElements)throw new x(`array assignment element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let A=B(v);if(A>e.limits.maxStringLength-f)throw new x(`array assignment string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");o.push(v),a.push(k),f+=A},E=()=>{m(c,p),c="",u=0,d=!1,p=!0};for(let v of t.parts)if(v.type==="Literal"){let k=v.value;if(!l){let A=k.indexOf("=(");A!==-1&&(l=!0,k=k.slice(A+2))}if(l){k.endsWith(")")&&(k=k.slice(0,-1));for(let A of k)/\s/.test(A)?(c||d)&&E():h(A)}}else if(l)if(v.type==="BraceExpansion")if(/^\[.+\]=/.test(c))h(Nn({type:"Word",parts:[v]}));else{(c||d)&&E();let A=await gt(e,{type:"Word",parts:[v]});for(let $ of A.values)m($)}else{(v.type==="SingleQuoted"||v.type==="DoubleQuoted"||v.type==="Escaped")&&(d=!0),p=!1;let k=await se(e,{type:"Word",parts:[v]});h(k)}(c||d)&&E();let b=o.splice(0),g=a.splice(0);f=0;for(let v=0;v<b.length;v++){let k=b[v];if(!g[v]){m(k);continue}let A=k.match(/^(\[[^\]]+\]=)(.*)$/s);if(A){let $=Qt(e,A[2]);k=A[1]+$}if(k.includes("{")&&k.includes("}")){let $=new H().parseWordFromString(k,!1,!1);if($.parts.some(N=>N.type==="BraceExpansion")){let N=await gt(e,$);for(let P of N.values)m(P);continue}}m(k)}let y=[`${i}=(`],S=B(y[0]);for(let v=0;v<o.length;v++){let k=o[v],A;/^\[.+\]=/.test(k)?A=k:k===""?A="''":/[\s"'\\$`!*?[\]{}|&;<>()]/.test(k)&&!k.startsWith("'")&&!k.startsWith('"')?A=`'${k.replace(/'/g,"'\\''")}'`:A=k;let $=`${v>0?" ":""}${A}`,N=B($);if(N+1>e.limits.maxStringLength-S)throw new x(`array assignment string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");y.push($),S+=N}return y.push(")"),y.join("")}async function tu(e,t){let n=-1,r=-1,s=!1;for(let m=0;m<t.parts.length;m++){let E=t.parts[m];if(E.type==="Literal"){let b=E.value.indexOf("+=");if(b!==-1){let y=E.value.slice(0,b);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(y)){n=m,r=b,s=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(y)){n=m,r=b,s=!0;break}}let g=E.value.indexOf("=");if(g!==-1&&(g===0||E.value[g-1]!=="+")){let y=E.value.slice(0,g);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(y)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(y)){n=m,r=g;break}}}}if(n===-1)return null;let i=t.parts.slice(0,n),o=t.parts[n];if(o.type!=="Literal")return null;let a=s?2:1,l=o.value.slice(0,r),c=o.value.slice(r+a),u=t.parts.slice(n+1),f="";for(let m of i)f+=await se(e,{type:"Word",parts:[m]});f+=l;let d={type:"Word",parts:c!==""?[{type:"Literal",value:c},...u]:u},p=d.parts.length>0?await se(e,d):"";return`${f}${s?"+=":"="}${p}`}var th=["tar","yq","xan","sqlite3","python3","python"];function nu(e){return th.includes(e)}var ne=Object.freeze({stdout:"",stderr:"",exitCode:0,internalStdinConsumed:0});function ee(e=""){return{stdout:e,stderr:"",exitCode:0}}function D(e,t=1){return{stdout:"",stderr:e,exitCode:t}}function L(e,t,n){return{stdout:e,stderr:t,exitCode:n}}function be(e){return{stdout:"",stderr:"",exitCode:e?0:1,internalStdinConsumed:0}}function Xt(e,t,n="",r=""){throw new x(e,t,n,r)}function ru(e){let t=e.state.fileDescriptors;if(t&&t.size>=e.limits.maxFileDescriptors)throw new x(`too many open file descriptors (max ${e.limits.maxFileDescriptors})`,"file_descriptors")}function Qi(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new Mt;return ne}if(t.length>1)throw new j(1,"",`bash: break: too many arguments
|
|
114
|
+
`);let n=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw new j(128,"",`bash: break: ${t[0]}: numeric argument required
|
|
115
|
+
`);n=r}throw new He(n)}async function Ki(e,t){let n,r=!1,s=!1,i=0;for(;i<t.length;)if(t[i]==="--"){i++;break}else if(t[i]==="-L")s=!1,i++;else if(t[i]==="-P")s=!0,i++;else if(t[i].startsWith("-")&&t[i]!=="-")i++;else break;let o=t.slice(i);if(o.length===0||o[0]==="~"?n=e.state.env.get("HOME")||"/":o[0]==="-"?(n=e.state.previousDir,r=!0):n=o[0],!n.startsWith("/")&&!n.startsWith("./")&&!n.startsWith("../")&&n!=="."&&n!==".."){let f=e.state.env.get("CDPATH");if(f){let d=f.split(":").filter(p=>p);for(let p of d){let h=p.startsWith("/")?`${p}/${n}`:`${e.state.cwd}/${p}/${n}`;try{if((await e.fs.stat(h)).isDirectory){n=h,r=!0;break}}catch{}}}}let l=(n.startsWith("/")?n:`${e.state.cwd}/${n}`).split("/").filter(f=>f&&f!=="."),c="";for(let f of l)if(f==="..")c=c.split("/").slice(0,-1).join("/")||"/";else{c=c?`${c}/${f}`:`/${f}`;try{if(!(await e.fs.stat(c)).isDirectory)return D(`bash: cd: ${n}: Not a directory
|
|
116
|
+
`)}catch{return D(`bash: cd: ${n}: No such file or directory
|
|
117
|
+
`)}}let u=c||"/";if(s)try{u=await e.fs.realpath(u)}catch{}return e.state.previousDir=e.state.cwd,e.state.cwd=u,e.state.env.set("PWD",e.state.cwd),e.state.env.set("OLDPWD",e.state.previousDir),ee(r?`${u}
|
|
118
|
+
`:"")}function Xi(e,t){return e.fs.resolvePath(e.state.cwd,t)}var nh=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function fs(e){return nh.includes(e)}async function ds(e,t,n){let r=Xi(e,n);switch(t){case"-e":case"-a":return e.fs.exists(r);case"-f":return await e.fs.exists(r)?(await e.fs.stat(r)).isFile:!1;case"-d":return await e.fs.exists(r)?(await e.fs.stat(r)).isDirectory:!1;case"-r":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&256)!==0:!1;case"-w":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&128)!==0:!1;case"-x":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&64)!==0:!1;case"-s":return await e.fs.exists(r)?(await e.fs.stat(r)).size>0:!1;case"-L":case"-h":try{return(await e.fs.lstat(r)).isSymbolicLink}catch{return!1}case"-k":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&512)!==0:!1;case"-g":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&1024)!==0:!1;case"-u":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&2048)!==0:!1;case"-G":case"-O":return e.fs.exists(r);case"-b":return!1;case"-c":return["/dev/null","/dev/zero","/dev/random","/dev/urandom","/dev/tty","/dev/stdin","/dev/stdout","/dev/stderr"].includes(r);case"-p":return!1;case"-S":return!1;case"-t":return!1;case"-N":return e.fs.exists(r);default:return!1}}var rh=["-nt","-ot","-ef"];function ps(e){return rh.includes(e)}async function hs(e,t,n,r){let s=Xi(e,n),i=Xi(e,r);switch(t){case"-nt":{let[o,a]=await Promise.all([e.fs.stat(s).catch(()=>null),e.fs.stat(i).catch(()=>null)]);return o!==null&&(a===null||o.mtime>a.mtime)}case"-ot":{let[o,a]=await Promise.all([e.fs.stat(s).catch(()=>null),e.fs.stat(i).catch(()=>null)]);return a!==null&&(o===null||o.mtime<a.mtime)}case"-ef":try{let[o,a]=await Promise.all([e.fs.realpath(s),e.fs.realpath(i)]);if(o===a)return!0;let[l,c]=await Promise.all([e.fs.stat(s),e.fs.stat(i)]);return l.dev!==void 0&&l.ino!==void 0&&c.dev!==void 0&&c.ino!==void 0?l.dev===c.dev&&l.ino===c.ino:l.identity&&c.identity?l.identity===c.identity:!1}catch{return!1}default:return!1}}var sh=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function ms(e){return sh.has(e)}function ys(e,t,n){switch(e){case"-eq":return t===n;case"-ne":return t!==n;case"-lt":return t<n;case"-le":return t<=n;case"-gt":return t>n;case"-ge":return t>=n}}function hr(e){return e==="="||e==="=="||e==="!="}function gs(e,t,n,r=!1,s=!1,i=!1,o=256){if(r){let l=Mn(t,n,s,i,o);return e==="!="?!l:l}if(s){let l=t.toLowerCase()===n.toLowerCase();return e==="!="?!l:l}let a=t===n;return e==="!="?!a:a}var ih=new Set(["-z","-n"]);function ws(e){return ih.has(e)}function Es(e,t){switch(e){case"-z":return t==="";case"-n":return t!==""}}async function bs(e,t){let n=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(n){let r=n[1],s=n[2];if(e.state.associativeArrays?.has(r)){let a=s;return(a.startsWith("'")&&a.endsWith("'")||a.startsWith('"')&&a.endsWith('"'))&&(a=a.slice(1,-1)),a=a.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(l,c)=>e.state.env.get(c)||""),Ut(e,r,a)}let o;try{let a=new H,l=re(a,s);o=await Y(e,l.expression)}catch{if(/^-?\d+$/.test(s))o=Number.parseInt(s,10);else{let a=e.state.env.get(s);o=a?Number.parseInt(a,10):0}}if(o<0){let a=ve(e,r),l=e.state.currentLine;if(a.length===0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${l}: ${r}: bad array subscript
|
|
119
|
+
`,!1;if(o=Math.max(...a)+1+o,o<0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${l}: ${r}: bad array subscript
|
|
120
|
+
`,!1}return Ut(e,r,o)}return e.state.env.has(t)?!0:e.state.associativeArrays?.has(t)?Et(e,t).length>0:ve(e,t).length>0}async function Yt(e,t){switch(t.type){case"CondBinary":{let n=await se(e,t.left),r=t.right.parts.length>0&&t.right.parts.every(i=>i.type==="SingleQuoted"||i.type==="DoubleQuoted"||i.type==="Escaped"&&t.operator!=="=~"),s;if(t.operator==="=~")if(r){let i=await se(e,t.right);s=Dn(i)}else s=await Gc(e,t.right);else hr(t.operator)&&!r?s=await Zc(e,t.right):s=await se(e,t.right);if(hr(t.operator)){let i=e.state.shoptOptions.nocasematch;return gs(t.operator,n,s,!r,i,!0,e.limits.maxCallDepth)}if(ms(t.operator))return ys(t.operator,await iu(e,n),await iu(e,s));if(ps(t.operator))return hs(e,t.operator,n,s);switch(t.operator){case"=~":try{let i=e.state.shoptOptions.nocasematch,o=uh(s),l=ge(o,i?"i":"").match(n);if(Ee(e,"BASH_REMATCH"),l)for(let c=0;c<l.length;c++)G(e,"BASH_REMATCH",c,l[c]||"");return l!==null}catch{throw new Error("syntax error in regular expression")}case"<":return n<s;case">":return n>s;default:return!1}}case"CondUnary":{let n=await se(e,t.operand);return fs(t.operator)?ds(e,t.operator,n):ws(t.operator)?Es(t.operator,n):t.operator==="-v"?await bs(e,n):t.operator==="-o"?Ji(e,n):!1}case"CondNot":return e.state.shoptOptions.extglob&&t.operand.type==="CondGroup"&&t.operand.expression.type==="CondWord"?`!(${await se(e,t.operand.expression.word)})`!=="":!await Yt(e,t.operand);case"CondAnd":return await Yt(e,t.left)?await Yt(e,t.right):!1;case"CondOr":return await Yt(e,t.left)?!0:await Yt(e,t.right);case"CondGroup":return await Yt(e,t.expression);case"CondWord":return await se(e,t.word)!=="";default:return!1}}async function mr(e,t){if(t.length===0)return L("","",1);if(t.length===1)return be(!!t[0]);if(t.length===2){let r=t[0],s=t[1];return r==="("?D(`test: '(' without matching ')'
|
|
121
|
+
`,2):fs(r)?be(await ds(e,r,s)):ws(r)?be(Es(r,s)):r==="!"?be(!s):r==="-v"?be(await bs(e,s)):r==="-o"?be(Ji(e,s)):r==="="||r==="=="||r==="!="||r==="<"||r===">"||r==="-eq"||r==="-ne"||r==="-lt"||r==="-le"||r==="-gt"||r==="-ge"||r==="-nt"||r==="-ot"||r==="-ef"?D(`test: ${r}: unary operator expected
|
|
122
|
+
`,2):L("","",1)}if(t.length===3){let r=t[0],s=t[1],i=t[2];if(hr(s))return be(gs(s,r,i));if(ms(s)){let o=Ss(r),a=Ss(i);return!o.valid||!a.valid?L("","",2):be(ys(s,o.value,a.value))}if(ps(s))return be(await hs(e,s,r,i));switch(s){case"-a":return be(r!==""&&i!=="");case"-o":return be(r!==""||i!=="");case">":return be(r>i);case"<":return be(r<i)}if(r==="!"){let o=await mr(e,[s,i]);return L("",o.stderr,o.exitCode===0?1:o.exitCode===1?0:o.exitCode)}if(r==="("&&i===")")return be(s!=="")}if(t.length===4){if(t[0]==="!"){let r=await mr(e,t.slice(1));return L("",r.stderr,r.exitCode===0?1:r.exitCode===1?0:r.exitCode)}if(t[0]==="("&&t[3]===")")return mr(e,[t[1],t[2]])}let n=await au(e,t,0);return n.pos<t.length?D(`test: too many arguments
|
|
123
|
+
`,2):be(n.value)}async function au(e,t,n){return oh(e,t,n)}async function oh(e,t,n){let{value:r,pos:s}=await su(e,t,n);for(;t[s]==="-o";){let i=await su(e,t,s+1);r=r||i.value,s=i.pos}return{value:r,pos:s}}async function su(e,t,n){let{value:r,pos:s}=await Yi(e,t,n);for(;t[s]==="-a";){let i=await Yi(e,t,s+1);r=r&&i.value,s=i.pos}return{value:r,pos:s}}async function Yi(e,t,n){let r=e.executionScope.enterDepth("test_expression",e.limits.maxCallDepth,"test expression");try{if(t[n]==="!"){let{value:s,pos:i}=await Yi(e,t,n+1);return{value:!s,pos:i}}return ah(e,t,n)}finally{r.release()}}async function ah(e,t,n){let r=t[n];if(r==="("){let{value:i,pos:o}=await au(e,t,n+1);return{value:i,pos:t[o]===")"?o+1:o}}let s=t[n+1];if(hr(s)){let i=r,o=t[n+2]??"";return{value:gs(s,i,o),pos:n+3}}if(ms(s)){let i=Ss(r),o=Ss(t[n+2]??"0");return!i.valid||!o.valid?{value:!1,pos:n+3}:{value:ys(s,i.value,o.value),pos:n+3}}if(ps(s)){let i=r,o=t[n+2]??"";return{value:await hs(e,s,i,o),pos:n+3}}if(fs(r)){let i=t[n+1]??"";return{value:await ds(e,r,i),pos:n+2}}if(ws(r)){let i=t[n+1]??"";return{value:Es(r,i),pos:n+2}}if(r==="-v"){let i=t[n+1]??"";return{value:await bs(e,i),pos:n+2}}if(r==="-o"){let i=t[n+1]??"";return{value:Ji(e,i),pos:n+2}}return{value:r!==void 0&&r!=="",pos:n+1}}function Mn(e,t,n=!1,r=!1,s=256){r&&lh(t,s);let i=`^${lu(t,r)}$`;return ge(i,n?"is":"s").test(e)}function lh(e,t){let n=0,r=[];for(let s=0;s<e.length;s++){if(e[s]==="\\"){s++;continue}if(e[s]==="("){let i=s>0&&"@*+?!".includes(e[s-1]);if(r.push(i),i&&n++,n>t)throw new x(`extglob maximum depth (${t}) exceeded`,"recursion")}else e[s]===")"&&r.length>0&&r.pop()&&n--}}function lu(e,t){let n="";for(let r=0;r<e.length;r++){let s=e[r];if(t&&(s==="@"||s==="*"||s==="+"||s==="?"||s==="!")&&r+1<e.length&&e[r+1]==="("){let i=cu(e,r+1);if(i!==-1){let o=e.slice(r+2,i),a=uu(o),l=a.map(u=>lu(u,t)),c=l.length>0?l.join("|"):"(?:)";if(s==="@")n+=`(?:${c})`;else if(s==="*")n+=`(?:${c})*`;else if(s==="+")n+=`(?:${c})+`;else if(s==="?")n+=`(?:${c})?`;else if(s==="!")if(i<e.length-1){let f=a.map(p=>fu(p,t));if(f.every(p=>p!==null)&&f.every(p=>p===f[0])&&f[0]!==null){let p=f[0];if(p===0)n+="(?:.+)";else{let h=[];p>0&&h.push(`.{0,${p-1}}`),h.push(`.{${p+1},}`),h.push(`(?!(?:${c})).{${p}}`),n+=`(?:${h.join("|")})`}}else n+=`(?:(?!(?:${c})).)*?`}else n+=`(?!(?:${c})$).*`;r=i;continue}}if(s==="\\")if(r+1<e.length){let i=e[r+1];/[\\^$.|+(){}[\]*?]/.test(i)?n+=`\\${i}`:n+=i,r++}else n+="\\\\";else if(s==="*")n+=".*";else if(s==="?")n+=".";else if(s==="["){let i=e.indexOf("]",r+1);i!==-1?(n+=e.slice(r,i+1),r=i):n+="\\["}else/[\\^$.|+(){}]/.test(s)?n+=`\\${s}`:n+=s}return n}function cu(e,t){let n=1,r=t+1;for(;r<e.length&&n>0;){let s=e[r];if(s==="\\"){r+=2;continue}if(s==="(")n++;else if(s===")"&&(n--,n===0))return r;r++}return-1}function uu(e){let t=[],n="",r=0,s=0;for(;s<e.length;){let i=e[s];if(i==="\\"){n+=i,s+1<e.length?(n+=e[s+1],s+=2):s++;continue}i==="("?(r++,n+=i):i===")"?(r--,n+=i):i==="|"&&r===0?(t.push(n),n=""):n+=i,s++}return t.push(n),t}function fu(e,t){let n=0,r=0;for(;r<e.length;){let s=e[r];if(t&&(s==="@"||s==="*"||s==="+"||s==="?"||s==="!")&&r+1<e.length&&e[r+1]==="("){let i=cu(e,r+1);if(i!==-1){if(s==="@"){let o=e.slice(r+2,i),l=uu(o).map(c=>fu(c,t));if(l.every(c=>c!==null)&&l.every(c=>c===l[0])){n+=l[0],r=i+1;continue}return null}return null}}if(s==="*")return null;if(s==="?"){n+=1,r++;continue}if(s==="["){let i=e.indexOf("]",r+1);if(i!==-1){n+=1,r=i+1;continue}n+=1,r++;continue}if(s==="\\"){n+=1,r+=2;continue}n+=1,r++}return n}function Ji(e,t){let r=new Map([["errexit",()=>e.state.options.errexit===!0],["nounset",()=>e.state.options.nounset===!0],["pipefail",()=>e.state.options.pipefail===!0],["xtrace",()=>e.state.options.xtrace===!0],["e",()=>e.state.options.errexit===!0],["u",()=>e.state.options.nounset===!0],["x",()=>e.state.options.xtrace===!0]]).get(t);return r?r():!1}async function iu(e,t){if(t=t.trim(),t==="")return 0;if(/^[+-]?(\d+#[a-zA-Z0-9@_]+|0[xX][0-9a-fA-F]+|0[0-7]+|\d+)$/.test(t))return ou(t);try{let n=new H,r=re(n,t);return await Y(e,r.expression)}catch{return ou(t)}}function ch(e,t){let n=0;for(let r of e){let s;if(r>="0"&&r<="9")s=r.charCodeAt(0)-48;else if(r>="a"&&r<="z")s=r.charCodeAt(0)-97+10;else if(r>="A"&&r<="Z")s=r.charCodeAt(0)-65+36;else if(r==="@")s=62;else if(r==="_")s=63;else return Number.NaN;if(s>=t)return Number.NaN;n=n*t+s}return n}function ou(e){if(e=e.trim(),e==="")return 0;let t=!1;e.startsWith("-")?(t=!0,e=e.slice(1)):e.startsWith("+")&&(e=e.slice(1));let n,r=e.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(r){let s=Number.parseInt(r[1],10);s>=2&&s<=64?n=ch(r[2],s):n=0}else/^0[xX][0-9a-fA-F]+$/.test(e)?n=Number.parseInt(e,16):/^0[0-7]+$/.test(e)?n=Number.parseInt(e,8):n=Number.parseInt(e,10);return Number.isNaN(n)&&(n=0),t?-n:n}function Ss(e){if(e=e.trim(),e==="")return{value:0,valid:!0};let t=!1;if(e.startsWith("-")?(t=!0,e=e.slice(1)):e.startsWith("+")&&(e=e.slice(1)),!/^\d+$/.test(e))return{value:0,valid:!1};let n=Number.parseInt(e,10);return Number.isNaN(n)?{value:0,valid:!1}:{value:t?-n:n,valid:!0}}function uh(e){let t="",n=0;for(;n<e.length;)if(e[n]==="\\"&&n+1<e.length)t+=e[n]+e[n+1],n+=2;else if(e[n]==="["){let r=fh(e,n);t+=r.converted,n=r.endIndex}else t+=e[n],n++;return t}function fh(e,t){let n=t+1,r="[";n<e.length&&(e[n]==="^"||e[n]==="!")&&(r+="^",n++);let s=!1;n<e.length&&e[n]==="]"&&(s=!0,n++);let i=!1;n<e.length&&e[n]==="["&&n+1<e.length&&e[n+1]!==":"&&(i=!0,n++);let o="",a=!1;for(;n<e.length;){let l=e[n];if(l==="]"){a=!0,n++;break}if(l==="["&&n+1<e.length&&e[n+1]===":"){let c=e.indexOf(":]",n+2);if(c!==-1){let u=e.slice(n+2,c);o+=dh(u),n=c+2;continue}}if(l==="["&&n+1<e.length){let c=e[n+1];if(c==="."||c==="="){let u=`${c}]`,f=e.indexOf(u,n+2);if(f!==-1){let d=e.slice(n+2,f);o+=d,n=f+2;continue}}}if(l==="\\"&&n+1<e.length){o+=l+e[n+1],n+=2;continue}o+=l,n++}return a?(s&&(r+="\\]"),i&&(r+="\\["),r+=o,r+="]",{converted:r,endIndex:n}):{converted:"\\[",endIndex:t+1}}function dh(e){return new Map([["alnum","a-zA-Z0-9"],["alpha","a-zA-Z"],["ascii","\\x00-\\x7F"],["blank"," \\t"],["cntrl","\\x00-\\x1F\\x7F"],["digit","0-9"],["graph","!-~"],["lower","a-z"],["print"," -~"],["punct","!-/:-@\\[-`{-~"],["space"," \\t\\n\\r\\f\\v"],["upper","A-Z"],["word","a-zA-Z0-9_"],["xdigit","0-9A-Fa-f"]]).get(e)??""}function eo(e,t,n){if(n&&e.length>=n.maxElements)throw new x(`array element limit exceeded (${n.maxElements})`,"array_elements");e.push(t)}function It(e,t){if(t&&B(e)>t.maxStringBytes)throw new x(`array assignment string limit exceeded (${t.maxStringBytes} bytes)`,"string_length");let n=[],r="",s=!1,i=!1,o=!1,a=!1;for(let l of e){if(o){r+=l,o=!1,a=!0;continue}if(l==="\\"){o=!0;continue}if(l==="'"&&!i){s||(a=!0),s=!s;continue}if(l==='"'&&!s){i||(a=!0),i=!i;continue}if((l===" "||l===" "||l===`
|
|
124
|
+
`)&&!s&&!i){a&&(eo(n,r,t),r="",a=!1);continue}r+=l,a=!0}return a&&eo(n,r,t),n}function As(e,t){if(t&&B(e)>t.maxStringBytes)throw new x(`array assignment string limit exceeded (${t.maxStringBytes} bytes)`,"string_length");let n=[],r=0;for(;r<e.length;){for(;r<e.length&&/\s/.test(e[r]);)r++;if(r>=e.length)break;if(e[r]!=="["){r++;continue}r++;let s="";if(e[r]==="'"||e[r]==='"'){let o=e[r];for(r++;r<e.length&&e[r]!==o;)s+=e[r],r++;e[r]===o&&r++}else for(;r<e.length&&e[r]!=="]"&&e[r]!=="=";)s+=e[r],r++;for(;r<e.length&&e[r]!=="]";)r++;if(e[r]==="]"&&r++,e[r]!=="=")continue;r++;let i="";if(e[r]==="'"||e[r]==='"'){let o=e[r];for(r++;r<e.length&&e[r]!==o;)e[r]==="\\"&&r+1<e.length&&r++,i+=e[r],r++;e[r]===o&&r++}else for(;r<e.length&&!/\s/.test(e[r]);)i+=e[r],r++;eo(n,[s,i],t)}return n}function du(e,t){let n=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(n)return{name:n[1],isArray:!0,arrayElements:It(n[2],t)};let r=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(r)return{name:r[1],isArray:!1,arrayIndex:r[2],value:r[3]};if(e.includes("=")){let s=e.indexOf("=");return{name:e.slice(0,s),isArray:!1,value:e.slice(s+1)}}return{name:e,isArray:!1}}async function ph(e,t){try{let n=new H,r=re(n,t);return await Y(e,r.expression)}catch{let n=parseInt(t,10);return Number.isNaN(n)?0:n}}async function pu(e,t,n={}){let{name:r,isArray:s,arrayElements:i,value:o,arrayIndex:a}=t,{makeReadonly:l=!1,checkReadonly:c=!0}=n;if(c){let u=fe(e,r);if(u)return u}if(s&&i){e.executionScope.consumeWork(i.length,"array assignment");let u=Pe(e,r),f=u?Me(u):void 0,d=e.state.env.get(r);try{Ee(e,r);for(let p=0;p<i.length;p++)G(e,r,p,i[p]);e.state.env.delete(r)}catch(p){throw e.state.arrays??=new Map,f?e.state.arrays.set(r,f):e.state.arrays.delete(r),d===void 0?e.state.env.delete(r):e.state.env.set(r,d),p}}else if(a!==void 0&&o!==void 0){let u=await ph(e,a);G(e,r,u,o)}else o!==void 0&&e.state.env.set(r,o);return l&&Ze(e,r),null}function Jt(e,t){e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,e.state.callDepth)}function to(e,t){return e.state.localVarDepth?.get(t)}function vs(e,t){e.state.localVarDepth?.delete(t)}function hu(e,t,n){e.state.localVarStack=e.state.localVarStack||new Map;let r=e.state.localVarStack.get(t)||[];r.push({value:n,scopeIndex:e.state.localScopes.length-1}),e.state.localVarStack.set(t,r)}function ks(e,t){let n=e.state.localVarStack?.get(t);if(!(!n||n.length===0))return n.pop()}function mu(e,t){if(e.state.localVarStack)for(let[n,r]of e.state.localVarStack.entries()){for(;r.length>0&&r[r.length-1].scopeIndex===t;)r.pop();r.length===0&&e.state.localVarStack.delete(n)}}var no=new Set([":",".","break","continue","eval","exec","exit","export","readonly","return","set","shift","trap","unset"]);function yu(e){return no.has(e)}var ro=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]),Fn=new Set([":","true","false","cd","export","unset","exit","local","set","break","continue","return","eval","shift","getopts","compgen","complete","compopt","pushd","popd","dirs","source",".","read","mapfile","readarray","declare","typeset","readonly","let","command","shopt","exec","test","[","echo","printf","pwd","alias","unalias","type","hash","ulimit","umask","trap","times","wait","kill","jobs","fg","bg","disown","suspend","fc","history","help","enable","builtin","caller"]);var so="__file__:",io="__file_append__:",lo="__rw__:",oo="__dupout__:",ao="__dupin__:",Se=3;function hh(e){let t=e.slice(lo.length),n=t.indexOf(":");if(n===-1)return null;let r=Number.parseInt(t.slice(0,n),10);if(Number.isNaN(r)||r<0)return null;let s=n+1,i=t.slice(s,s+r),o=t.slice(s+r+1),a=o.indexOf(":");if(a===-1)return null;let l=Number.parseInt(o.slice(0,a),10);return Number.isNaN(l)||l<0?null:{path:i,position:l,content:o.slice(a+1)}}function gu(e,t){let n=Number.parseInt(e.slice(t.length),10);return Number.isNaN(n)?null:n}function mh(e){if(e.startsWith(so))return{kind:"output",path:e.slice(so.length),append:!1};if(e.startsWith(io))return{kind:"output",path:e.slice(io.length),append:!0};if(e.startsWith(lo)){let t=hh(e);if(t)return{kind:"readwrite",...t}}if(e.startsWith(oo)){let t=gu(e,oo);if(t!==null)return{kind:"dup-out",sourceFd:t}}if(e.startsWith(ao)){let t=gu(e,ao);if(t!==null)return{kind:"dup-in",sourceFd:t}}return{kind:"input",content:e}}function co(e){switch(e.kind){case"input":return e.content;case"output":return`${e.append?io:so}${e.path}`;case"readwrite":return`${lo}${e.path.length}:${e.path}:${e.position}:${e.content}`;case"dup-out":return`${oo}${e.sourceFd}`;case"dup-in":return`${ao}${e.sourceFd}`;case"closed":throw new Error("Closed descriptors have no table encoding")}}function yh(e){return e.state.fileDescriptors??=new Map,e.state.fileDescriptors}function gh(e,t,n){n?(e.state.inputFds??=new Set,e.state.inputFds.add(t)):e.state.inputFds?.delete(t)}function Bn(e,t){return e.state.fdAliases?.get(t)}function en(e,t){return[...Bn(e,t)??[t]]}function wu(e,t){let n=Bn(e,t);if(n&&(n.delete(t),e.state.fdAliases?.delete(t),n.size<2))for(let r of n)e.state.fdAliases?.delete(r)}function uo(e,t,n){if(t===n)return;e.state.fdAliases??=new Map;let r=Bn(e,n)??new Set([n]);r.add(t);for(let s of r)e.state.fdAliases.set(s,r)}function Ps(e,t){return e.state.fileDescriptors?.get(t)}function tt(e,t){let n=Ps(e,t);if(n!==void 0)return e.state.inputFds?.has(t)?{kind:"input",content:n}:mh(n)}function bn(e,t){return e.state.fileDescriptors?.has(t)===!0}function fo(e,t,n,r){let s=yh(e);s.has(t)||ru(e),s.set(t,n),gh(e,t,r)}function xs(e,t,n,r=!1){wu(e,t),fo(e,t,n,r)}function lt(e,t,n){xs(e,t,co(n),n.kind==="input")}function kt(e,t){e.state.fileDescriptors?.delete(t),e.state.inputFds?.delete(t),wu(e,t)}function $s(e,t,n){let r=Ps(e,n);return r===void 0?!1:(xs(e,t,r,e.state.inputFds?.has(n)===!0),uo(e,t,n),!0)}function po(e,t,n){let r=Ps(e,n);if(r===void 0)return!1;if(t===n)return!0;let s=e.state.inputFds?.has(n)===!0,i=[...Bn(e,n)??[]].filter(a=>a!==n);kt(e,n),xs(e,t,r,s);let o=i.find(a=>bn(e,a));return o!==void 0&&uo(e,t,o),!0}function Cs(e,t){let n=tt(e,t);if(n===void 0)return{error:"not-open"};switch(n.kind){case"input":return{content:n.content};case"readwrite":return{content:n.content.slice(n.position)};case"output":case"dup-out":return{error:"write-only"};case"dup-in":return{error:"not-open"};case"closed":return{error:"not-open"}}}function tn(e,t,n){let r=tt(e,t);if(r===void 0)return;let s;if(r.kind==="input")s={kind:"input",content:r.content.slice(n)};else if(r.kind==="readwrite")s={...r,position:r.position+n};else return;let i=co(s),o=s.kind==="input";for(let a of Bn(e,t)??[t])fo(e,a,i,o)}async function ho(e,t,n,r,s){if(t.kind==="output")return await e.fs.appendFile(t.path,r,s),!0;let o=n.map(u=>tt(e,u)).find(u=>u?.kind==="readwrite")??t;if(o.kind!=="readwrite")return!1;let a=o.content.slice(0,o.position)+r+o.content.slice(o.position+r.length),l={...o,position:o.position+r.length,content:a};await e.fs.writeFile(o.path,a,s);let c=co(l);for(let u of n)bn(e,u)&&fo(e,u,c,!1);return!0}function nn(e,t,n){if(t.has(n))return;let r=Bn(e,n);t.set(n,{raw:Ps(e,n),isInput:e.state.inputFds?.has(n)===!0,aliases:r?[...r].filter(s=>s!==n):[]})}function Ns(e,t){let n=e.state.fileDescriptors;if(n)for(let[r,{raw:s,isInput:i,aliases:o}]of t){if(s===void 0){kt(e,r);continue}xs(e,r,s,i);let a=o.find(l=>n.has(l));a!==void 0&&uo(e,r,a)}}function mo(e){switch(e.operator){case"<":case"<>":case"<<":case"<<-":case"<<<":case"<&":return e.fd??0;case">":case">>":case">|":case">&":return e.fd??1;default:return null}}function Eu(e){if(e.fdVariable)return!1;let t=mo(e);return t!==null&&t>=Se}async function wh(e,t,n,r){try{if(!await e.fs.exists(t))return null;if((await e.fs.stat(t)).isDirectory)return`bash: ${n}: Is a directory
|
|
95
125
|
`;if(r.checkNoclobber&&e.state.options.noclobber&&!r.isClobber&&n!=="/dev/null")return`bash: ${n}: cannot overwrite existing file
|
|
96
126
|
`}catch{return`bash: ${n}: cannot open redirect target
|
|
97
|
-
`}return null}function
|
|
98
|
-
|
|
99
|
-
`,1)
|
|
100
|
-
`,1)
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
`,1)
|
|
105
|
-
`,1)}
|
|
106
|
-
`,1)}
|
|
107
|
-
`,1)
|
|
108
|
-
`,1)
|
|
109
|
-
|
|
110
|
-
`,
|
|
111
|
-
`,
|
|
112
|
-
`,
|
|
113
|
-
`,
|
|
114
|
-
`,
|
|
115
|
-
|
|
116
|
-
`,
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
`,
|
|
122
|
-
`,2);
|
|
123
|
-
`,
|
|
124
|
-
|
|
125
|
-
`,2);
|
|
126
|
-
`,2);
|
|
127
|
-
`,2)}else if(
|
|
128
|
-
`,2);
|
|
129
|
-
`,2);
|
|
130
|
-
`,2);
|
|
131
|
-
`,2)}else if(
|
|
132
|
-
`,2);
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
`,t),
|
|
136
|
-
`,2);
|
|
137
|
-
|
|
138
|
-
`,
|
|
139
|
-
`,2);l.
|
|
140
|
-
`,2);
|
|
141
|
-
`,2);o=t[f]}else if(d==="-
|
|
142
|
-
`,2)
|
|
143
|
-
`,2)}else if(d==="-
|
|
144
|
-
`,2)}else if(d==="-
|
|
145
|
-
`,2)}else if(d==="
|
|
146
|
-
`,2)
|
|
147
|
-
|
|
127
|
+
`}return null}function bu(e){let n=Math.min(e.length,8192);for(let r=0;r<n;r++)if(e.charCodeAt(r)>127)return"utf8";return"binary"}var yr="scoped",Au="bare",vu="persistent",Eh=e=>new x(`too many open file descriptors (max ${e.limits.maxFileDescriptors})`,"file_descriptors"),bh=(e,t)=>bn(e,t)||(e.state.fileDescriptors?.size??0)<e.limits.maxFileDescriptors,Su=e=>{let t=Math.max(e.state.nextFd??10,10);for(;bn(e,t);)t+=1;return t},Rs=e=>{let t=e.endsWith("-"),n=t?e.slice(0,-1):e;return/^\d+$/.test(n)?{sourceFd:Number.parseInt(n,10),move:t}:null},Sh=(e,t,n)=>{let r=tt(e,t);return t<Se?r?{kind:"entry",entry:r,descriptors:en(e,t)}:{kind:"standard",fd:t}:r?n?r.kind==="input"||r.kind==="readwrite"||r.kind==="dup-in"?{kind:"entry",entry:r,descriptors:en(e,t)}:null:r.kind==="output"||r.kind==="readwrite"||r.kind==="dup-out"?{kind:"entry",entry:r,descriptors:en(e,t)}:null:null};async function Wn(e,t,n,r,s=!0){let i=e.fs.resolvePath(e.state.cwd,t),o=await wh(e,i,t,{checkNoclobber:!n,isClobber:r});if(o)return{error:L("",o,1)};if(t==="/dev/full")return{error:L("",`bash: /dev/full: No space left on device
|
|
128
|
+
`,1)};if(t==="/dev/stdout")return{entry:{kind:"dup-out",sourceFd:1}};if(t==="/dev/stderr")return{entry:{kind:"dup-out",sourceFd:2}};try{n?await e.fs.appendFile(i,"","binary"):await e.fs.writeFile(i,"","binary")}catch(a){if(!s)throw a;return{error:L("",`bash: ${t}: cannot open redirect target
|
|
129
|
+
`,1)}}return{entry:{kind:"output",path:i,append:n}}}async function yo(e,t,n){let r=e.fs.resolvePath(e.state.cwd,t);try{let s=await e.fs.readFile(r);return n?{entry:{kind:"readwrite",path:r,position:0,content:s}}:{entry:{kind:"input",content:s}}}catch{if(!n)return{error:L("",`bash: ${t}: No such file or directory
|
|
130
|
+
`,1)};try{return await e.fs.writeFile(r,"","binary"),{entry:{kind:"readwrite",path:r,position:0,content:""}}}catch{return{error:L("",`bash: ${t}: No such file or directory
|
|
131
|
+
`,1)}}}}var Ah=async(e,t)=>{let n=await se(e,t.content);return t.stripTabs?n.split(`
|
|
132
|
+
`).map(r=>r.replace(/^\t+/,"")).join(`
|
|
133
|
+
`):n};async function vh(e,t,n,r){let s=new Map,i=new Map,o=(g,y)=>e.state.closedStandardFds?.has(g)?{kind:"closed"}:tt(e,g)??y,a=new Map([[0,o(0,{kind:"dup-in",sourceFd:0})],[1,o(1,{kind:"dup-out",sourceFd:1})],[2,o(2,{kind:"dup-out",sourceFd:2})]]),l=r.numericSnapshot,c,u=-1,f=a.get(0);f?.kind==="input"?(c=f.content,u=0):f?.kind==="readwrite"&&(c=f.content.slice(f.position),u=0);let d=()=>({targets:s,dupSources:i,standardRoutes:a,stdin:c,stdinSourceFd:u,error:null}),p=async(g,y,S)=>{let v={...d(),error:await rn(e,g,t.slice(0,y),s,i,a)};return S?{...v,errorCause:S}:v},h=async(g,y)=>{if(bh(e,g))return null;let S=Eh(e);return p(L("",S.stderr,x.EXIT_CODE),y,S)},m=(g,y)=>{g!==null&&g<Se&&a.set(g,y),r.policy==="persistent"&&g!==null&&g<Se&&(e.state.closedStandardFds?.delete(g),lt(e,g,y))},E=(g,y)=>{a.set(g,y),nn(e,r.standardSnapshot,g),r.standardClosedSnapshot.has(g)||r.standardClosedSnapshot.set(g,e.state.closedStandardFds?.has(g)===!0),e.state.closedStandardFds?.delete(g),lt(e,g,y)},b=(g,y)=>{if(g<Se){let S=a.get(g);return S?.kind==="closed"?null:S?{kind:"entry",entry:S,descriptors:en(e,g)}:{kind:"standard",fd:g}}return Sh(e,g,y)};for(let g=0;g<t.length;g++){let y=t[g],S=mo(y);if(y.target.type==="HereDoc"){let A=await Ah(e,y.target);if(y.fdVariable){try{fe(e,y.fdVariable)}catch(P){if(!(P instanceof j))throw P;return p(L(P.stdout,P.stderr,P.exitCode),g,P)}let $=Su(e),N=await h($,g);if(N)return N;nn(e,r.fdVariableSnapshot,$),r.fdVariableEnv.has(y.fdVariable)||r.fdVariableEnv.set(y.fdVariable,e.state.env.get(y.fdVariable)),lt(e,$,{kind:"input",content:A}),e.state.env.set(y.fdVariable,String($)),e.state.nextFd=$+1}else if(S!==null&&S>=Se){let $=await h(S,g);if($)return $;nn(e,l,S),lt(e,S,{kind:"input",content:A})}else if(S===0||S===null)c=Tt(A),u=-1,m(S,{kind:"input",content:c});else{let $={kind:"input",content:A};r.policy==="persistent"?m(S,$):E(S,$)}continue}let v,k=y.operator===">&"||y.operator==="<&";if(k){if(Gi(e,y.target))return p(L("",`bash: $@: ambiguous redirect
|
|
134
|
+
`,1),g);v=await se(e,y.target)}else if(y.operator==="<<<")v=await se(e,y.target);else{let A=await Xc(e,y.target);if("error"in A)return p(L("",A.error,1),g);v=A.target}if(s.set(g,v),v.includes("\0"))return p(L("",`bash: ${v.replace(/\0/g,"")}: No such file or directory
|
|
135
|
+
`,1),g);if(y.fdVariable){try{fe(e,y.fdVariable)}catch(O){if(!(O instanceof j))throw O;return p(L(O.stdout,O.stderr,O.exitCode),g,O)}if(k&&v==="-"){let O=Number.parseInt(e.state.env.get(y.fdVariable)??"",10);Number.isNaN(O)||(nn(e,r.fdVariableSnapshot,O),kt(e,O));continue}let A=Su(e),$=k?Rs(v):null;if($&&!b($.sourceFd,y.operator==="<&"))return p(L("",`bash: ${$.sourceFd}: Bad file descriptor
|
|
136
|
+
`,1),g);if(!($?.move===!0&&$.sourceFd>=Se)){let O=await h(A,g);if(O)return O}nn(e,r.fdVariableSnapshot,A),r.fdVariableEnv.has(y.fdVariable)||r.fdVariableEnv.set(y.fdVariable,e.state.env.get(y.fdVariable));let P,C;if(k){let O=$;if(O){let U=b(O.sourceFd,y.operator==="<&");if(!U)return p(L("",`bash: ${O.sourceFd}: Bad file descriptor
|
|
137
|
+
`,1),g);C=O,U.kind==="standard"?P={kind:y.operator==="<&"?"dup-in":"dup-out",sourceFd:U.fd}:O.sourceFd<Se&&(P=U.entry)}else{if(y.operator==="<&")return p(L("",`bash: ${v}: ambiguous redirect
|
|
138
|
+
`,1),g);let U=await Wn(e,v,!1,!1);if(U.error)return p(U.error,g);P=U.entry}}else if(y.operator===">"||y.operator===">|"||y.operator===">>"||y.operator==="&>"||y.operator==="&>>"){let O=y.operator===">>"||y.operator==="&>>",U=await Wn(e,v,O,y.operator===">|");if(U.error)return p(U.error,g);P=U.entry}else if(y.operator==="<<<")P={kind:"input",content:`${v}
|
|
139
|
+
`};else if(y.operator==="<"||y.operator==="<>"){let O=await yo(e,v,y.operator==="<>");if(O.error)return p(O.error,g);P=O.entry}if(C&&C.sourceFd>=Se){if(!(C.move?po(e,A,C.sourceFd):$s(e,A,C.sourceFd)))return p(L("",`bash: ${C.sourceFd}: Bad file descriptor
|
|
140
|
+
`,1),g)}else P&<(e,A,P);C?.move&&C.sourceFd!==A&&C.sourceFd<Se&&kt(e,C.sourceFd),e.state.env.set(y.fdVariable,String(A)),e.state.nextFd=A+1;continue}if(Eu(y)){let A=S;if(k&&v==="-"){nn(e,l,A),kt(e,A);continue}let $=k?Rs(v):null;if($&&!b($.sourceFd,y.operator==="<&"))return p(L("",`bash: ${$.sourceFd}: Bad file descriptor
|
|
141
|
+
`,1),g);if(!($?.move===!0&&$.sourceFd>=Se)){let P=await h(A,g);if(P)return P}if(nn(e,l,A),k){let P=$;if(!P){if(y.operator==="<&")return p(L("",`bash: ${v}: ambiguous redirect
|
|
142
|
+
`,1),g);let O=await Wn(e,v,!1,!1);if(O.error)return p(O.error,g);lt(e,A,O.entry);continue}let C=b(P.sourceFd,y.operator==="<&");if(!C)return p(L("",`bash: ${P.sourceFd}: Bad file descriptor
|
|
143
|
+
`,1),g);if(C.kind==="standard")lt(e,A,{kind:y.operator==="<&"?"dup-in":"dup-out",sourceFd:C.fd});else if(P.sourceFd<Se)lt(e,A,C.entry);else if(!(P.move?po(e,A,P.sourceFd):$s(e,A,P.sourceFd)))return p(L("",`bash: ${P.sourceFd}: Bad file descriptor
|
|
144
|
+
`,1),g);P.move&&P.sourceFd!==A&&P.sourceFd<Se&&kt(e,P.sourceFd);continue}if(y.operator===">"||y.operator===">|"||y.operator===">>"){let P=await Wn(e,v,y.operator===">>",y.operator===">|");if(P.error)return p(P.error,g);lt(e,A,P.entry)}else if(y.operator==="<<<")lt(e,A,{kind:"input",content:`${v}
|
|
145
|
+
`});else if(y.operator==="<"||y.operator==="<>"){let P=await yo(e,v,y.operator==="<>");if(P.error)return p(P.error,g);lt(e,A,P.entry)}continue}if(k){if(v==="-"){S===0&&(c="",u=-1),S!==null&&S<Se&&(a.set(S,{kind:"closed"}),r.policy==="persistent"&&(kt(e,S),e.state.closedStandardFds??=new Set,e.state.closedStandardFds.add(S)));continue}let A=Rs(v);if(!A){if(y.operator==="<&")return p(L("",`bash: ${v}: ambiguous redirect
|
|
146
|
+
`,1),g);let N=await Wn(e,v,!1,!1,!1);if(N.error)return p(N.error,g);let P=N.entry;i.set(g,{kind:"entry",entry:P,descriptors:[]}),y.fd==null?(m(1,P),m(2,P)):m(S,P);continue}let $=b(A.sourceFd,y.operator==="<&");if(!$)return p(L("",`bash: ${A.sourceFd}: Bad file descriptor
|
|
147
|
+
`,1),g);if(i.set(g,$),$.kind==="entry"&&r.policy==="persistent"&&S!==null&&S<Se&&A.sourceFd>=Se){if(!$s(e,S,A.sourceFd))return p(L("",`bash: ${A.sourceFd}: Bad file descriptor
|
|
148
|
+
`,1),g);a.set(S,tt(e,S)),e.state.closedStandardFds?.delete(S)}else $.kind==="standard"?m(S,{kind:y.operator==="<&"?"dup-in":"dup-out",sourceFd:$.fd}):m(S,$.entry);if(y.operator==="<&"&&S===0)if($.kind==="standard")c=$.fd===0?n:"",u=-1;else if($.entry.kind==="input"||$.entry.kind==="readwrite"){let N=A.sourceFd<Se&&!bn(e,A.sourceFd)?{content:$.entry.kind==="input"?$.entry.content:$.entry.content.slice($.entry.position)}:Cs(e,A.sourceFd);if("error"in N)return p(L("",`bash: ${A.sourceFd}: Bad file descriptor
|
|
149
|
+
`,1),g);c=N.content,u=bn(e,A.sourceFd)?A.sourceFd:-1}else c=n,u=-1;A.move&&(A.sourceFd>=Se?kt(e,A.sourceFd):(a.set(A.sourceFd,{kind:"closed"}),r.policy==="persistent"&&(kt(e,A.sourceFd),e.state.closedStandardFds??=new Set,e.state.closedStandardFds.add(A.sourceFd))));continue}if(y.operator===">"||y.operator===">|"||y.operator===">>"||y.operator==="&>"||y.operator==="&>>"){let A=await Wn(e,v,y.operator===">>"||y.operator==="&>>",y.operator===">|",!1);if(A.error)return p(A.error,g);let $=A.entry;y.operator==="&>"||y.operator==="&>>"?(m(1,$),m(2,$)):m(S,$);continue}if(y.operator==="<<<")c=Tt(`${v}
|
|
150
|
+
`),u=-1,m(S,{kind:"input",content:c});else if(y.operator==="<"){let A=e.fs.resolvePath(e.state.cwd,v);try{c=await vn(e.fs,A),u=-1,m(S,{kind:"input",content:c})}catch{return p(L("",`bash: ${v}: No such file or directory
|
|
151
|
+
`,1),g)}}else if(y.operator==="<>"){let A=await yo(e,v,!0);if(A.error)return p(A.error,g);let $=A.entry;m(S,$),S===0&&$.kind==="readwrite"&&(c=$.content,u=-1)}}return d()}function Vn(e,t,n){let r={numericSnapshot:new Map,fdVariableSnapshot:new Map,standardSnapshot:new Map,standardClosedSnapshot:new Map,fdVariableEnv:new Map,nextFd:e.state.nextFd,policy:n},s=!1;return{prepare:(i="")=>vh(e,t,i,r),finish:()=>{if(!s){if(s=!0,n!=="persistent"&&Ns(e,r.numericSnapshot),n!=="persistent"){Ns(e,r.standardSnapshot);for(let[i,o]of r.standardClosedSnapshot)o?(e.state.closedStandardFds??=new Set,e.state.closedStandardFds.add(i)):e.state.closedStandardFds?.delete(i)}if(n==="bare"){Ns(e,r.fdVariableSnapshot);for(let[i,o]of r.fdVariableEnv)o===void 0?e.state.env.delete(i):e.state.env.set(i,o);e.state.nextFd=r.nextFd}}}}}function zn(e){if(!e.error)throw new Error("Expected a redirection error");if(e.errorCause)throw e.errorCause.stdout=e.error.stdout,e.errorCause.stderr=e.error.stderr,e.errorCause;return e.error}async function go(e,t,n,r){let s=t instanceof j||t instanceof _e||t instanceof We?t.exitCode:t instanceof x?x.EXIT_CODE:0,i=await rn(e,L(t.stdout,t.stderr,s),n,r.targets,r.dupSources,r.standardRoutes);t.stdout=i.stdout,t.stderr=i.stderr,t.internalOutputAccounting=i.internalOutputAccounting??{stdout:B(i.stdout),stderr:B(i.stderr)}}async function nt(e,t,n,r){let s=Vn(e,t,yr),i;try{if(i=await s.prepare(n),i.error)return zn(i);let o=e.state.groupStdin,a=e.state.groupStdinSourceFd;i.stdin!==void 0&&(e.state.groupStdin=i.stdin,e.state.groupStdinSourceFd=i.stdinSourceFd);try{let l=await r(i);return await rn(e,l,t,i.targets,i.dupSources,i.standardRoutes)}finally{i.stdin!==void 0&&(e.state.groupStdin=o,e.state.groupStdinSourceFd=a)}}catch(o){throw!(o instanceof kn)||!i||await go(e,o,t,i),o}finally{s.finish()}}async function rn(e,t,n,r,s=new Map,i=new Map,o="bash",a=!1){n.length>0&&(t=e.executionScope.accountResult(t,"redirection"));let{stdout:l,stderr:c,exitCode:u}=t,d=t.stdoutKind==="bytes"||t.stdoutKind===void 0&&t.stdoutEncoding==="binary"?"binary":"utf8",p=S=>d,h={kind:"live-stdout"},m={kind:"live-stderr"},E=S=>{if(!S)return null;if(S.kind==="entry"){if(S.entry.kind==="dup-out"){if(S.entry.sourceFd===1)return{kind:"live-stdout"};if(S.entry.sourceFd===2)return{kind:"live-stderr"}}return S.entry.kind==="output"||S.entry.kind==="readwrite"?{kind:"descriptor",source:S}:null}return S.fd===1?h:S.fd===2?m:null},b=S=>{let v=i.get(S)??tt(e,S);return v?v.kind==="closed"?{kind:"invalid-output",fd:S}:v.kind==="input"||v.kind==="dup-in"?{kind:"invalid-output",fd:S}:v.kind==="dup-out"?v.sourceFd===1?{kind:"live-stdout"}:v.sourceFd===2?{kind:"live-stderr"}:null:v.kind==="output"||v.kind==="readwrite"?{kind:"descriptor",source:{kind:"entry",entry:v,descriptors:en(e,S)}}:null:null};h=b(1)??h,m=b(2)??m;for(let S=0;S<n.length;S++){let v=n[S];if(v.target.type==="HereDoc"||v.fdVariable)continue;let k=r.get(S);if(k!==void 0)switch(v.operator){case">":case">|":case">>":{let A=v.fd??1;if(A!==1&&A!==2)break;let $=v.operator===">>";if(k==="/dev/stdout"){A===2&&(m=h);break}if(k==="/dev/stderr"){A===1&&(h=m);break}if(k==="/dev/full"){c+=`bash: echo: write error: No space left on device
|
|
152
|
+
`,u=1,A===1&&(l="");break}if(k==="/dev/null"&&A===2){m={kind:"discard"};break}let N=e.fs.resolvePath(e.state.cwd,k);A===1?h={kind:"file",path:N,append:$}:m={kind:"file",path:N,append:$};break}case">&":case"<&":{let A=v.fd??(v.operator==="<&"?0:1);if(A>=Se||A===0)break;if(k==="-"){A===1?h={kind:"discard"}:m={kind:"discard"};break}let $=E(s.get(S));if(!$)break;v.fd==null&&Rs(k)===null?(h=$,m=$):A===1?h=$:A===2&&(m=$);break}case"&>":{h={kind:"file",path:e.fs.resolvePath(e.state.cwd,k),append:!1},m=h;break}case"&>>":{h={kind:"file",path:e.fs.resolvePath(e.state.cwd,k),append:!0},m=h;break}}}if(l!==""||c!==""){let S=l,v=c;l="",c="",h.kind==="invalid-output"&&S!==""&&(S="",v+=`${a?"":"bash: "}${o}: write error: Bad file descriptor
|
|
153
|
+
`,u=1),m.kind==="invalid-output"&&(v="");let k=async(A,$,N)=>{A.append?await e.fs.appendFile(A.path,$,N):await e.fs.writeFile(A.path,$,N)};if(h===m&&(h.kind==="file"||h.kind==="descriptor")){let A=S+v;A!==""&&(h.kind==="file"?await k(h,A,p(A)):await ho(e,h.source.entry,h.source.descriptors,A,p(A)))}else for(let[A,$,N]of[[S,h,!0],[v,m,!1]])if(A!=="")switch($.kind){case"live-stdout":l+=A;break;case"live-stderr":c+=A;break;case"file":await k($,A,N?p(A):bu(A));break;case"descriptor":await ho(e,$.source.entry,$.source.descriptors,A,N?p(A):bu(A));break;case"invalid-output":break;case"discard":break}}let g=L(l,c,u);if(t.stdoutKind&&(g.stdoutKind=t.stdoutKind),t.stdoutEncoding==="binary"&&(g.stdoutEncoding="binary"),t.internalPipeStatusOverride&&(g.internalPipeStatusOverride=t.internalPipeStatusOverride),n.length>0||e.state.fileDescriptors?.has(1)===!0||e.state.fileDescriptors?.has(2)===!0){let S=(t.internalOutputAccounting?.stdout??0)+(t.internalOutputAccounting?.stderr??0),v=B(g.stdout),k=B(g.stderr),A=Math.min(v,S);g.internalOutputAccounting={stdout:A,stderr:Math.min(k,S-A)},e.executionScope.accountResult(g,"redirection")}else t.internalOutputAccounting&&(g.internalOutputAccounting=t.internalOutputAccounting);return g}function ku(e,t){if(e.state.options.posix&&no.has(t.name)){let r=`bash: line ${e.state.currentLine}: \`${t.name}': is a special builtin
|
|
154
|
+
`;throw new j(2,"",r)}let n={...t,sourceFile:t.sourceFile??e.state.currentSource??"main"};return e.state.functions.set(t.name,n),ne}async function Os(e,t,n,r="",s,i=!1){e.state.callDepth++,e.state.callDepth>e.limits.maxCallDepth&&(e.state.callDepth--,Xt(`${t.name}: maximum recursion depth (${e.limits.maxCallDepth}) exceeded, increase executionLimits.maxCallDepth`,"recursion")),e.state.funcNameStack||(e.state.funcNameStack=[]),e.state.callLineStack||(e.state.callLineStack=[]),e.state.sourceStack||(e.state.sourceStack=[]),e.state.funcNameStack.unshift(t.name),e.state.callLineStack.unshift(s??e.state.currentLine),e.state.sourceStack.unshift(t.sourceFile??"main"),e.state.localScopes.push(new Map),e.state.localArrayScopes??=[],e.state.localArrayScopes.push(new Map),e.state.localExportedVars||(e.state.localExportedVars=[]),e.state.localExportedVars.push(new Set);let o=new Map,a=Number.parseInt(e.state.env.get("#")??"0",10),l=Math.max(n.length,a);for(let p=0;p<l;p++){let h=String(p+1);o.set(h,e.state.env.get(h)),p<n.length?e.state.env.set(h,n[p]):e.state.env.delete(h)}o.set("@",e.state.env.get("@")),o.set("#",e.state.env.get("#")),e.state.env.set("@",n.join(" ")),e.state.env.set("#",String(n.length));let c=!1,u=()=>{if(c)return;c=!0;let p=e.state.localScopes.length-1,h=e.state.localScopes.pop(),m=e.state.localArrayScopes?.pop();if(h)for(let[E,b]of h)b===void 0?e.state.env.delete(E):e.state.env.set(E,b);if(m){e.state.arrays??=new Map;for(let[E,b]of m)b===void 0?(e.state.arrays.delete(E),e.state.associativeArrays?.delete(E)):(e.state.arrays.set(E,Me(b)),e.state.associativeArrays??=new Set,b.kind==="associative"?e.state.associativeArrays.add(E):e.state.associativeArrays.delete(E))}if(mu(e,p),e.state.fullyUnsetLocals)for(let[E,b]of e.state.fullyUnsetLocals.entries())b===p&&e.state.fullyUnsetLocals.delete(E);if(e.state.localExportedVars&&e.state.localExportedVars.length>0){let E=e.state.localExportedVars.pop();if(E)for(let b of E)e.state.exportedVars?.delete(b)}for(let[E,b]of o)b===void 0?e.state.env.delete(E):e.state.env.set(E,b);e.state.funcNameStack?.shift(),e.state.callLineStack?.shift(),e.state.sourceStack?.shift(),e.state.callDepth--},f=null,d=Vn(e,t.redirections,yr);try{if(f=await d.prepare(r),f.error)return zn(f);let p=f.stdin??r,h=i||f.stdin!==void 0||r!=="",m=await e.executeCommand(t.body,p,h);return rn(e,m,t.redirections,f.targets,f.dupSources,f.standardRoutes)}catch(p){if(p instanceof kn&&f&&(await go(e,p,t.redirections,f),p instanceof _e))return L(p.stdout,p.stderr,p.exitCode);throw p}finally{d.finish(),u()}}var xu=e=>e.type==="Escaped"?M.literal(`\\${e.value}`):e.type==="DoubleQuoted"?{...e,parts:e.parts.map(xu)}:e,$u=["!","[[","]]","case","do","done","elif","else","esac","fi","for","function","if","in","then","time","until","while","{","}"],bo=[".",":","[","alias","bg","bind","break","builtin","caller","cd","command","compgen","complete","compopt","continue","declare","dirs","disown","echo","enable","eval","exec","exit","export","false","fc","fg","getopts","hash","help","history","jobs","kill","let","local","logout","mapfile","popd","printf","pushd","pwd","read","readarray","readonly","return","set","shift","shopt","source","suspend","test","times","trap","true","type","typeset","ulimit","umask","unalias","unset","wait"],kh=["autocd","assoc_expand_once","cdable_vars","cdspell","checkhash","checkjobs","checkwinsize","cmdhist","compat31","compat32","compat40","compat41","compat42","compat43","compat44","complete_fullquote","direxpand","dirspell","dotglob","execfail","expand_aliases","extdebug","extglob","extquote","failglob","force_fignore","globasciiranges","globstar","gnu_errfmt","histappend","histreedit","histverify","hostcomplete","huponexit","inherit_errexit","interactive_comments","lastpipe","lithist","localvar_inherit","localvar_unset","login_shell","mailwarn","no_empty_cmd_completion","nocaseglob","nocasematch","nullglob","progcomp","progcomp_alias","promptvars","restricted_shell","shift_verbose","sourcepath","xpg_echo"],Ph=bo;async function So(e,t){let n=[],r=null,s="",i="",o=null,a=!1,l=!1,c=!1,u=null,f=null,d=null,p=[],h=["alias","arrayvar","binding","builtin","command","directory","disabled","enabled","export","file","function","group","helptopic","hostname","job","keyword","running","service","setopt","shopt","signal","stopped","user","variable"];for(let k=0;k<t.length;k++){let A=t[k];if(A==="-v")n.push("variable");else if(A==="-e")n.push("export");else if(A==="-f")n.push("file");else if(A==="-d")n.push("directory");else if(A==="-k")n.push("keyword");else if(A==="-A"){if(k++,k>=t.length)return D(`compgen: -A: option requires an argument
|
|
155
|
+
`,2);let $=t[k];if(!h.includes($))return D(`compgen: ${$}: invalid action name
|
|
156
|
+
`,2);n.push($)}else if(A==="-W"){if(k++,k>=t.length)return D(`compgen: -W: option requires an argument
|
|
157
|
+
`,2);r=t[k]}else if(A==="-P"){if(k++,k>=t.length)return D(`compgen: -P: option requires an argument
|
|
158
|
+
`,2);s=t[k]}else if(A==="-S"){if(k++,k>=t.length)return D(`compgen: -S: option requires an argument
|
|
159
|
+
`,2);i=t[k]}else if(A==="-o"){if(k++,k>=t.length)return D(`compgen: -o: option requires an argument
|
|
160
|
+
`,2);let $=t[k];if($==="plusdirs")a=!0;else if($==="dirnames")l=!0;else if($==="default")c=!0;else if(!($==="filenames"||$==="nospace"||$==="bashdefault"||$==="noquote"))return D(`compgen: ${$}: invalid option name
|
|
161
|
+
`,2)}else if(A==="-F"){if(k++,k>=t.length)return D(`compgen: -F: option requires an argument
|
|
162
|
+
`,2);f=t[k]}else if(A==="-C"){if(k++,k>=t.length)return D(`compgen: -C: option requires an argument
|
|
163
|
+
`,2);d=t[k]}else if(A==="-X"){if(k++,k>=t.length)return D(`compgen: -X: option requires an argument
|
|
164
|
+
`,2);u=t[k]}else if(A==="-G"){if(k++,k>=t.length)return D(`compgen: -G: option requires an argument
|
|
165
|
+
`,2)}else if(A==="--"){p.push(...t.slice(k+1));break}else A.startsWith("-")||p.push(A)}o=p[0]??null;let m=[],E=new Set,b=()=>e.limits.maxArrayElements-m.length,g=k=>{for(let A of k){if(m.length>=e.limits.maxArrayElements)throw new x(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");if(B(A)>e.limits.maxStringLength)throw new x(`compgen: completion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");e.executionScope.consumeWork(1,"compgen completion"),m.push(A),E.add(A)}};if(l){let k=await wo(e,o,b());g(k)}if(c){let k=await Pu(e,o,b());g(k)}for(let k of n)if(k==="variable"){let A=xh(e,o,b());g(A)}else if(k==="export"){let A=$h(e,o,b());g(A)}else if(k==="function"){let A=Ch(e,o,b());g(A)}else if(k==="builtin"){let A=Nh(e,o,b());g(A)}else if(k==="keyword"){let A=Rh(e,o,b());g(A)}else if(k==="alias"){let A=Oh(e,o,b());g(A)}else if(k==="shopt"){let A=Dh(e,o,b());g(A)}else if(k==="helptopic"){let A=Ih(e,o,b());g(A)}else if(k==="directory"){let A=await wo(e,o,b());g(A)}else if(k==="file"){let A=await Pu(e,o,b());g(A)}else if(k==="user"){let A=_h(e,o,b());g(A)}else if(k==="command"){let A=await Th(e,o,b());g(A)}if(r!==null)try{let k=await Lh(e,r),A=Mh(e,k,b(),o);for(let $ of A)g([$])}catch(k){if(k instanceof x)throw k;return L("","",1)}if(a){let k=await wo(e,o,b(),E);for(let A of k)E.has(A)||g([A])}let y="";if(f!==null){let k=e.state.functions.get(f);if(k){let A=new Map,$=Pe(e,"COMP_WORDS"),N=$?Me($):void 0;Ee(e,"COMP_WORDS"),rr(e,"COMP_WORDS"),A.set("COMP_CWORD",e.state.env.get("COMP_CWORD")),e.state.env.set("COMP_CWORD","-1"),A.set("COMP_LINE",e.state.env.get("COMP_LINE")),e.state.env.set("COMP_LINE",""),A.set("COMP_POINT",e.state.env.get("COMP_POINT")),e.state.env.set("COMP_POINT","0");let P=Pe(e,"COMPREPLY"),C=P?Me(P):void 0,O=e.state.env.get("COMPREPLY");Ee(e,"COMPREPLY"),e.state.env.delete("COMPREPLY");let U=["compgen",p[0]??"",""];try{let X=await Os(e,k,U,"");if(X.exitCode!==0)return Eo(e,A),Un(e,"COMP_WORDS",N),Un(e,"COMPREPLY",C),O!==void 0&&e.state.env.set("COMPREPLY",O),L("",X.stderr,1);y=X.stdout;let R=Fh(e,b());g(R)}catch(X){if(X instanceof x)throw X;return Eo(e,A),Un(e,"COMP_WORDS",N),Un(e,"COMPREPLY",C),O!==void 0&&e.state.env.set("COMPREPLY",O),L("","",1)}Eo(e,A),Un(e,"COMP_WORDS",N),Un(e,"COMPREPLY",C),O!==void 0&&e.state.env.set("COMPREPLY",O)}}if(d!==null)try{let k=Ge(d),A=await e.executeScript(k);if(A.exitCode!==0)return L("",A.stderr,A.exitCode);if(A.stdout)for(let $ of Bh(A.stdout))$.length>0&&g([$])}catch(k){if(k.name==="ParseException")return D(`compgen: -C: ${k.message}
|
|
166
|
+
`,2);throw k}let S=m;if(u!==null){let k=u.startsWith("!"),A=k?u.slice(1):u;S=m.filter($=>{let N=Mn($,A,!1,!0,e.limits.maxCallDepth);return k?N:!N})}if(S.length===0&&o!==null)return L(y,"",1);let v=new Pn(e.limits.maxOutputSize,"compgen");v.append(y);for(let k of S)v.append(s).append(k).append(i).append(`
|
|
167
|
+
`);return ee(v.build())}function xh(e,t,n){let r=ct(e,t,n);for(let s of e.state.env.keys())/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)&&r.add(s);for(let s of e.state.arrays?.keys()??[])r.add(s);return r.build()}function $h(e,t,n){let r=ct(e,t,n),s=e.state.exportedVars??new Set;for(let i of s)e.state.env.has(i)&&r.add(i);return r.build()}function Ch(e,t,n){let r=ct(e,t,n);for(let s of e.state.functions.keys())r.add(s);return r.build()}function Nh(e,t,n){let r=ct(e,t,n);for(let s of bo)r.add(s);return r.build()}function Rh(e,t,n){let r=ct(e,t,n);for(let s of $u)r.add(s);return r.build()}function Oh(e,t,n){let r=ct(e,t,n);for(let s of e.state.env.keys())if(s.startsWith("BASH_ALIAS_")){let i=s.slice(11);r.add(i)}return r.build()}function Dh(e,t,n){let r=ct(e,t,n);for(let s of kh)r.add(s);return r.build()}function Ih(e,t,n){let r=ct(e,t,n);for(let s of Ph)r.add(s);return r.build()}async function wo(e,t,n=e.limits.maxArrayElements,r){let s=ct(e,null,n,r);try{let i=e.state.cwd,o=t??"";if(t){let l=t.lastIndexOf("/");if(l!==-1){let c=t.slice(0,l)||"/";o=t.slice(l+1),c.startsWith("/")?i=c:i=`${e.state.cwd}/${c}`}}let a=await e.fs.readdir(i);for(let l of a){e.executionScope.consumeWork(1,"compgen directory scan");let c=`${i}/${l}`;try{if((await e.fs.stat(c)).isDirectory&&(!o||l.startsWith(o)))if(t?.includes("/")){let f=t.lastIndexOf("/"),d=t.slice(0,f+1);s.add(d+l)}else s.add(l)}catch(u){if(u instanceof x)throw u}}}catch(i){if(i instanceof x)throw i}return s.build()}async function Pu(e,t,n=e.limits.maxArrayElements){let r=ct(e,null,n);try{let s=e.state.cwd,i=t??"";if(t){let a=t.lastIndexOf("/");if(a!==-1){let l=t.slice(0,a)||"/";i=t.slice(a+1),l.startsWith("/")?s=l:s=`${e.state.cwd}/${l}`}}let o=await e.fs.readdir(s);for(let a of o)if(e.executionScope.consumeWork(1,"compgen file scan"),!i||a.startsWith(i))if(t?.includes("/")){let l=t.lastIndexOf("/"),c=t.slice(0,l+1);r.add(c+a)}else r.add(a)}catch(s){if(s instanceof x)throw s}return r.build()}function _h(e,t,n){let r=ct(e,t,n);return r.add("root"),r.add("nobody"),r.build()}async function Th(e,t,n){let r=ct(e,t,n);for(let i of bo)r.add(i);for(let i of e.state.functions.keys())r.add(i);for(let i of e.state.env.keys())i.startsWith("BASH_ALIAS_")&&r.add(i.slice(11));for(let i of $u)r.add(i);let s=e.state.env.get("PATH")??"/usr/bin:/bin";for(let i of s.split(":"))if(i)try{let o=await e.fs.readdir(i);for(let a of o)r.add(a)}catch(o){if(o instanceof x)throw o}return r.build()}function ct(e,t,n,r){let s=new Set;return{add(i){if(e.executionScope.consumeWork(1,"compgen candidate collection"),!(t!==null&&!i.startsWith(t))&&!r?.has(i)&&!s.has(i)){if(s.size>=n)throw new x(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");if(B(i)>e.limits.maxStringLength)throw new x(`compgen: completion string limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");s.add(i)}},build(){return Array.from(s).sort()}}}async function Lh(e,t){let r=new H().parseWordFromString(t,!1,!1);return await se(e,M.word(r.parts.map(xu)))}function Mh(e,t,n,r){let s=e.state.env.get("IFS")??`
|
|
168
|
+
`;if(s.length===0){if(r!==null&&!t.startsWith(r))return[];if(n===0)throw new x(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");return[t]}let i=new Set(s.split("")),o=[],a=u=>{if(!(r!==null&&!u.startsWith(r))){if(o.length>=n)throw new x(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");o.push(u)}},l="",c=0;for(;c<t.length;){let u=t[c];if(u==="\\"&&c+1<t.length){let f=t[c+1];l+=f,c+=2}else i.has(u)?(l.length>0&&(a(l),l=""),c++):(l+=u,c++)}return l.length>0&&a(l),o}function Eo(e,t){for(let[n,r]of t)r===void 0?e.state.env.delete(n):e.state.env.set(n,r)}function Un(e,t,n){e.state.arrays??=new Map,n?e.state.arrays.set(t,Me(n)):e.state.arrays.delete(t)}function Fh(e,t){let n=[],r=s=>{if(n.length>=t)throw new x(`compgen: completion element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");n.push(s)};if(Ce(e,"COMPREPLY")){let s=Q(e,"COMPREPLY");for(let[,i]of s)r(i)}else{let s=e.state.env.get("COMPREPLY");s!==void 0&&r(s)}return n}function*Bh(e){let t=0;for(;t<=e.length;){let n=e.indexOf(`
|
|
169
|
+
`,t),r=n===-1?e.length:n;if(r>t&&(yield e.slice(t,r)),n===-1)return;t=n+1}}function gr(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!0}return!1}function Ao(e){let t="$'";for(let n=0;n<e.length;n++){let r=e[n],s=e.charCodeAt(n);s===7?t+="\\a":s===8?t+="\\b":s===9?t+="\\t":s===10?t+="\\n":s===11?t+="\\v":s===12?t+="\\f":s===13?t+="\\r":s===27?t+="\\e":s===39?t+="\\'":s===92?t+="\\\\":s<32||s===127?t+=`\\${s.toString(8).padStart(3,"0")}`:t+=r}return t+="'",t}function Cu(e){if(gr(e))return Nu(e);if(e==="")return 2;if(/^[a-zA-Z0-9_/.:\-@%+,=]+$/.test(e))return B(e);let t=B(e)+2;for(let n of e)n==="'"&&(t+=3);return t}function Ae(e){return gr(e)?Ao(e):e===""?"''":/^[a-zA-Z0-9_/.:\-@%+,=]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Ds(e){if(gr(e))return Nu(e);let t=B(e)+2;for(let n of e)(n==="\\"||n==='"'||n==="$"||n==="`")&&t++;return t}function sn(e){return gr(e)?Ao(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}"`}function Nu(e){let t=3;for(let n of e){let r=n.codePointAt(0)??0;r===7||r===8||r===9||r===10||r===11||r===12||r===13||r===27||r===39||r===92?t+=2:r<32||r===127?t+=4:t+=B(n)}return t}function wr(e){return gr(e)?Ao(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}"`}var Wh=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function ko(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let n=!1,r=!1,s=!1,i,o,a,l=[],c=[],u=[];for(let f=0;f<t.length;f++){let d=t[f];if(d==="-p")n=!0;else if(d==="-r")r=!0;else if(d==="-D")s=!0;else if(d==="-W"){if(f++,f>=t.length)return D(`complete: -W: option requires an argument
|
|
170
|
+
`,2);i=t[f]}else if(d==="-F"){if(f++,f>=t.length)return D(`complete: -F: option requires an argument
|
|
171
|
+
`,2);o=t[f]}else if(d==="-o"){if(f++,f>=t.length)return D(`complete: -o: option requires an argument
|
|
172
|
+
`,2);let p=t[f];if(!Wh.includes(p))return D(`complete: ${p}: invalid option name
|
|
173
|
+
`,2);l.push(p)}else if(d==="-A"){if(f++,f>=t.length)return D(`complete: -A: option requires an argument
|
|
174
|
+
`,2);c.push(t[f])}else if(d==="-C"){if(f++,f>=t.length)return D(`complete: -C: option requires an argument
|
|
175
|
+
`,2);a=t[f]}else if(d==="-G"){if(f++,f>=t.length)return D(`complete: -G: option requires an argument
|
|
176
|
+
`,2)}else if(d==="-P"){if(f++,f>=t.length)return D(`complete: -P: option requires an argument
|
|
177
|
+
`,2)}else if(d==="-S"){if(f++,f>=t.length)return D(`complete: -S: option requires an argument
|
|
178
|
+
`,2)}else if(d==="-X"){if(f++,f>=t.length)return D(`complete: -X: option requires an argument
|
|
179
|
+
`,2)}else if(d==="--"){u.push(...t.slice(f+1));break}else d.startsWith("-")||u.push(d)}if(r){if(u.length===0)return e.state.completionSpecs.clear(),e.state.defaultCompletionSpec=void 0,e.state.emptyCompletionSpec=void 0,ee("");for(let f of u)e.state.completionSpecs.delete(f);return ee("")}if(n)return u.length===0?vo(e):vo(e,u);if(t.length===0||u.length===0&&!i&&!o&&!a&&l.length===0&&c.length===0&&!s)return vo(e);if(o&&u.length===0&&!s)return D(`complete: -F: option requires a command name
|
|
180
|
+
`,2);if(s){let f={isDefault:!0};return i!==void 0&&(f.wordlist=i),o!==void 0&&(f.function=o),a!==void 0&&(f.command=a),l.length>0&&(f.options=l),c.length>0&&(f.actions=c),e.state.defaultCompletionSpec=f,ee("")}for(let f of u){let d=Object.create(null);i!==void 0&&(d.wordlist=i),o!==void 0&&(d.function=o),a!==void 0&&(d.command=a),l.length>0&&(d.options=l),c.length>0&&(d.actions=c),e.state.completionSpecs.set(f,d)}return ee("")}function vo(e,t){let n=e.state.completionSpecs??new Map;if(n.size===0&&!e.state.defaultCompletionSpec){if(t&&t.length>0){let i="";for(let o of t)i+=`complete: ${o}: no completion specification
|
|
181
|
+
`;return L("",i,1)}return ee("")}let r=[],s=t||Array.from(n.keys());for(let i of s){let o=n.get(i);if(!o){if(t)return L(r.join(`
|
|
148
182
|
`)+(r.length>0?`
|
|
149
183
|
`:""),`complete: ${i}: no completion specification
|
|
150
|
-
`,1);continue}let
|
|
184
|
+
`,1);continue}let a="complete";if(o.options)for(let l of o.options)a+=` -o ${Ae(l)}`;if(o.actions)for(let l of o.actions)a+=` -A ${Ae(l)}`;o.wordlist!==void 0&&(o.wordlist.includes(" ")||o.wordlist.includes("'")?a+=` -W ${Ae(o.wordlist)}`:a+=` -W ${Ae(o.wordlist)}`),o.function!==void 0&&(a+=` -F ${Ae(o.function)}`),o.command!==void 0&&(a+=` -C ${Ae(o.command)}`),o.isDefault&&(a+=" -D"),a+=`${i.startsWith("-")?" -- ":" "}${Ae(i)}`,r.push(a)}if(!t&&e.state.defaultCompletionSpec){let i=e.state.defaultCompletionSpec,o="complete";for(let a of i.options??[])o+=` -o ${Ae(a)}`;for(let a of i.actions??[])o+=` -A ${Ae(a)}`;i.wordlist!==void 0&&(o+=` -W ${Ae(i.wordlist)}`),i.function!==void 0&&(o+=` -F ${Ae(i.function)}`),i.command!==void 0&&(o+=` -C ${Ae(i.command)}`),o+=" -D",r.push(o)}return r.length===0?ee(""):ee(`${r.join(`
|
|
151
185
|
`)}
|
|
152
|
-
`)}var
|
|
153
|
-
`,2);let c=t[
|
|
154
|
-
`,2);s.push(c)}else if(l==="+o"){if(
|
|
155
|
-
`,2);let c=t[
|
|
156
|
-
`,2);i.push(c)}else if(l==="--"){
|
|
157
|
-
`,1)}function
|
|
158
|
-
`);let n=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw new
|
|
159
|
-
`);n=r}throw new
|
|
160
|
-
`;else{let f=u.map(d=>{let
|
|
161
|
-
`}continue}let l=
|
|
162
|
-
`;continue}if(
|
|
163
|
-
`;continue}let c=e.state.env.get(i);if(c!==void 0)n+=`declare ${
|
|
164
|
-
`;else{let u=e.state.declaredVars?.has(i),f=e.state.localVarDepth?.has(i);u||f?n+=`declare ${
|
|
186
|
+
`)}var Ru=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function Po(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let n=!1,r=!1,s=[],i=[],o=[];for(let a=0;a<t.length;a++){let l=t[a];if(l==="-D")n=!0;else if(l==="-E")r=!0;else if(l==="-o"){if(a++,a>=t.length)return D(`compopt: -o: option requires an argument
|
|
187
|
+
`,2);let c=t[a];if(!Ru.includes(c))return D(`compopt: ${c}: invalid option name
|
|
188
|
+
`,2);s.push(c)}else if(l==="+o"){if(a++,a>=t.length)return D(`compopt: +o: option requires an argument
|
|
189
|
+
`,2);let c=t[a];if(!Ru.includes(c))return D(`compopt: ${c}: invalid option name
|
|
190
|
+
`,2);i.push(c)}else if(l==="--"){o.push(...t.slice(a+1));break}else!l.startsWith("-")&&!l.startsWith("+")&&o.push(l)}if(n){let a=e.state.defaultCompletionSpec??{isDefault:!0},l=new Set(a.options??[]);for(let c of s)l.add(c);for(let c of i)l.delete(c);return a.options=l.size>0?Array.from(l):void 0,e.state.defaultCompletionSpec=a,ee("")}if(r){let a=e.state.emptyCompletionSpec??Object.create(null),l=new Set(a.options??[]);for(let c of s)l.add(c);for(let c of i)l.delete(c);return a.options=l.size>0?Array.from(l):void 0,e.state.emptyCompletionSpec=a,ee("")}if(o.length>0){for(let a of o){let l=e.state.completionSpecs.get(a)??{},c=new Set(l.options??[]);for(let u of s)c.add(u);for(let u of i)c.delete(u);l.options=c.size>0?Array.from(c):void 0,e.state.completionSpecs.set(a,l)}return ee("")}return D(`compopt: not currently executing completion function
|
|
191
|
+
`,1)}function xo(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new Mt;return ne}if(t.length>1)throw new j(1,"",`bash: continue: too many arguments
|
|
192
|
+
`);let n=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw new j(1,"",`bash: continue: ${t[0]}: numeric argument required
|
|
193
|
+
`);n=r}throw new Qe(n)}function Ou(e,t){let n="";return e.state.integerVars?.has(t)&&(n+="i"),e.state.lowercaseVars?.has(t)&&(n+="l"),ue(e,t)&&(n+="n"),e.state.readonlyVars?.has(t)&&(n+="r"),e.state.uppercaseVars?.has(t)&&(n+="u"),e.state.exportedVars?.has(t)&&(n+="x"),n===""?"--":`-${n}`}function $o(e){return Ae(e)}function Co(e){return`'${e.replace(/'/g,"'\\''")}'`}function Du(e,t){let n="",r="",s=!1;for(let i of t){let o=Ou(e,i);if(e.state.associativeArrays?.has(i)){let u=Et(e,i);if(u.length===0)n+=`declare -A ${i}=()
|
|
194
|
+
`;else{let f=u.map(d=>{let p=le(e,i,d)??"",h=$o(p);return`[${Co(d)}]=${h}`});n+=`declare -A ${i}=(${f.join(" ")})
|
|
195
|
+
`}continue}let l=ve(e,i);if(l.length>0){let u=l.map(f=>{let d=le(e,i,f)??"";return`[${f}]=${sn(d)}`});n+=`declare -a ${i}=(${u.join(" ")})
|
|
196
|
+
`;continue}if(Ce(e,i)){n+=`declare -a ${i}=()
|
|
197
|
+
`;continue}let c=e.state.env.get(i);if(c!==void 0)n+=`declare ${o} ${i}=${wr(c)}
|
|
198
|
+
`;else{let u=e.state.declaredVars?.has(i),f=e.state.localVarDepth?.has(i);u||f?n+=`declare ${o} ${i}
|
|
165
199
|
`:(r+=`bash: declare: ${i}: not found
|
|
166
|
-
`,s=!0)}}return
|
|
167
|
-
`;else{let g=b.map(
|
|
168
|
-
`}continue}if(
|
|
169
|
-
`;continue}if(
|
|
170
|
-
`;continue}let E=e.state.env.get(f);E!==void 0&&(l+=`declare ${d} ${f}=${
|
|
171
|
-
`)}return
|
|
172
|
-
`;else{let i=s.map(
|
|
173
|
-
`}}return
|
|
174
|
-
`;else{let
|
|
175
|
-
`}}return
|
|
176
|
-
`)}return
|
|
177
|
-
`,2)}}}else if(
|
|
178
|
-
`,2);else g.push(
|
|
179
|
-
`;return
|
|
180
|
-
`:
|
|
200
|
+
`,s=!0)}}return L(n,r,s?1:0)}function Iu(e,t){let{filterExport:n,filterReadonly:r,filterNameref:s,filterIndexedArray:i,filterAssocArray:o}=t,a=n||r||s||i||o,l="",c=new Set;for(let f of e.state.env.keys())f.startsWith("BASH_")||c.add(f);for(let f of e.state.arrays?.keys()??[])c.add(f);if(e.state.localVarDepth)for(let f of e.state.localVarDepth.keys())c.add(f);if(e.state.associativeArrays)for(let f of e.state.associativeArrays)c.add(f);let u=Array.from(c).sort();for(let f of u){let d=Ou(e,f),p=e.state.associativeArrays?.has(f),h=ve(e,f),m=!p&&Ce(e,f);if(a&&(o&&!p||i&&!m||n&&!e.state.exportedVars?.has(f)||r&&!e.state.readonlyVars?.has(f)||s&&!ue(e,f)))continue;if(p){let b=Et(e,f);if(b.length===0)l+=`declare -A ${f}=()
|
|
201
|
+
`;else{let g=b.map(y=>{let S=le(e,f,y)??"",v=$o(S);return`[${Co(y)}]=${v}`});l+=`declare -A ${f}=(${g.join(" ")})
|
|
202
|
+
`}continue}if(h.length>0){let b=h.map(g=>{let y=le(e,f,g)??"";return`[${g}]=${sn(y)}`});l+=`declare -a ${f}=(${b.join(" ")})
|
|
203
|
+
`;continue}if(Ce(e,f)){l+=`declare -a ${f}=()
|
|
204
|
+
`;continue}let E=e.state.env.get(f);E!==void 0&&(l+=`declare ${d} ${f}=${wr(E)}
|
|
205
|
+
`)}return ee(l)}function _u(e){let t="",n=Array.from(e.state.associativeArrays??[]).sort();for(let r of n){let s=Et(e,r);if(s.length===0)t+=`declare -A ${r}=()
|
|
206
|
+
`;else{let i=s.map(o=>{let a=le(e,r,o)??"",l=$o(a);return`[${Co(o)}]=${l}`});t+=`declare -A ${r}=(${i.join(" ")})
|
|
207
|
+
`}}return ee(t)}function Tu(e){let t="",n=new Set(Array.from(e.state.arrays??[]).filter(([,s])=>s.kind==="indexed").map(([s])=>s)),r=Array.from(n).sort();for(let s of r){let i=ve(e,s);if(i.length===0)t+=`declare -a ${s}=()
|
|
208
|
+
`;else{let o=i.map(a=>{let l=le(e,s,a)??"";return`[${a}]=${sn(l)}`});t+=`declare -a ${s}=(${o.join(" ")})
|
|
209
|
+
`}}return ee(t)}function Lu(e){let t="",n=new Set;for(let s of e.state.env.keys())s.startsWith("BASH_")||n.add(s);let r=Array.from(n).sort();for(let s of r){if(e.state.associativeArrays?.has(s)||ve(e,s).length>0||Ce(e,s))continue;let a=e.state.env.get(s);a!==void 0&&(t+=`${s}=${Ae(a)}
|
|
210
|
+
`)}return ee(t)}function No(e,t){e.state.integerVars??=new Set,e.state.integerVars.add(t)}function Er(e,t){return e.state.integerVars?.has(t)??!1}function Ro(e,t){e.state.lowercaseVars??=new Set,e.state.lowercaseVars.add(t),e.state.uppercaseVars?.delete(t)}function Vh(e,t){return e.state.lowercaseVars?.has(t)??!1}function Oo(e,t){e.state.uppercaseVars??=new Set,e.state.uppercaseVars.add(t),e.state.lowercaseVars?.delete(t)}function zh(e,t){return e.state.uppercaseVars?.has(t)??!1}function qn(e,t,n){return Vh(e,t)?n.toLowerCase():zh(e,t)?n.toUpperCase():n}async function Mu(e,t){try{let n=new H,r=re(n,t),s=await Y(e,r.expression);return String(s)}catch{return"0"}}function Uh(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return null;let n=t[0],r=n.length;if(e[r]!=="[")return null;let s=0,i=r+1;for(;r<e.length;r++)if(e[r]==="[")s++;else if(e[r]==="]"&&(s--,s===0))break;if(s!==0)return null;let o=e.slice(i,r);if(r++,e[r]!=="=")return null;r++;let a=e.slice(r);return{name:n,indexExpr:o,value:a}}async function Do(e,t){let n={maxElements:e.limits.maxArrayElements,maxStringBytes:e.limits.maxStringLength},r=!1,s=!1,i=!1,o=!1,a=!1,l=!1,c=!1,u=!1,f=!1,d=!1,p=!1,h=!1,m=!1,E=!1,b=!1,g=[];for(let P=0;P<t.length;P++){let C=t[P];if(C==="-a")r=!0;else if(C==="-A")s=!0;else if(C==="-r")i=!0;else if(C==="-x")o=!0;else if(C==="-p")a=!0;else if(C==="-n")l=!0;else if(C==="+n")c=!0;else if(C==="+a")u=!0;else if(C==="+x")f=!0;else if(C==="--"){g.push(...t.slice(P+1));break}else if(C.startsWith("+")){for(let O of C.slice(1))if(O==="n")c=!0;else if(O==="a")u=!0;else if(O==="x")f=!0;else if(O!=="r"){if(O!=="i"){if(!(O==="f"||O==="F"))return L("",`bash: typeset: +${O}: invalid option
|
|
211
|
+
`,2)}}}else if(C==="-i")d=!0;else if(C==="-l")p=!0;else if(C==="-u")h=!0;else if(C==="-f")m=!0;else if(C==="-F")E=!0;else if(C==="-g")b=!0;else if(C.startsWith("-"))for(let O of C.slice(1))if(O==="a")r=!0;else if(O==="A")s=!0;else if(O==="r")i=!0;else if(O==="x")o=!0;else if(O==="p")a=!0;else if(O==="n")l=!0;else if(O==="i")d=!0;else if(O==="l")p=!0;else if(O==="u")h=!0;else if(O==="f")m=!0;else if(O==="F")E=!0;else if(O==="g")b=!0;else return L("",`bash: typeset: -${O}: invalid option
|
|
212
|
+
`,2);else g.push(C)}let S=e.state.localScopes.length>0&&!b,v=P=>{if(!S)return;let C=e.state.localScopes[e.state.localScopes.length-1];C.has(P)||C.set(P,e.state.env.get(P))},k=P=>{if(!S)return;let C=e.state.localScopes[e.state.localScopes.length-1];for(C.has(P)||C.set(P,e.state.env.get(P)),e.state.localArrayScopes??=[];e.state.localArrayScopes.length<e.state.localScopes.length;)e.state.localArrayScopes.push(new Map);let O=e.state.localArrayScopes.at(-1);if(O&&!O.has(P)){let U=Pe(e,P);O.set(P,U?Me(U):void 0)}},A=P=>{S&&Jt(e,P)};if(E){if(g.length===0){let O=Array.from(e.state.functions.keys()).sort(),U="";for(let X of O)U+=`declare -f ${X}
|
|
213
|
+
`;return ee(U)}let P=!0,C="";for(let O of g)e.state.functions.has(O)?C+=`${O}
|
|
214
|
+
`:P=!1;return L(C,"",P?0:1)}if(m){if(g.length===0){let C="",O=Array.from(e.state.functions.keys()).sort();for(let U of O)C+=`${U} ()
|
|
181
215
|
{
|
|
182
216
|
# function body
|
|
183
217
|
}
|
|
184
|
-
`;return
|
|
185
|
-
`,
|
|
186
|
-
`,
|
|
187
|
-
`,
|
|
188
|
-
`,
|
|
189
|
-
`,
|
|
190
|
-
`,
|
|
191
|
-
`}}return
|
|
192
|
-
`,2);r=t[
|
|
193
|
-
`,2);if(r!==void 0)return
|
|
194
|
-
`,2);r=l}}if(r===void 0){if(n.length<2)return
|
|
195
|
-
`,1);let
|
|
196
|
-
`,1)}catch{return
|
|
197
|
-
`,1)}n.unshift(e.state.cwd),e.state.previousDir=e.state.cwd,e.state.cwd=s,e.state.env.set("PWD",s),e.state.env.set("OLDPWD",e.state.previousDir);let i=e.state.env.get("HOME")||"",
|
|
198
|
-
`;return
|
|
199
|
-
`,2):
|
|
200
|
-
`,2);if(n.length===0)return
|
|
201
|
-
`,1);let r=n.shift();if(!r)return
|
|
202
|
-
`,1);e.state.previousDir=e.state.cwd,e.state.cwd=r,e.state.env.set("PWD",r),e.state.env.set("OLDPWD",e.state.previousDir);let s=e.state.env.get("HOME")||"",i=`${[r,...n].map(
|
|
203
|
-
`;return
|
|
204
|
-
`,2);else return
|
|
205
|
-
`,1);if(r)return e.state.directoryStack=[],ne;let
|
|
218
|
+
`;return ee(C)}let P=!0;for(let C of g)e.state.functions.has(C)||(P=!1);return L("","",P?0:1)}if(a&&g.length>0)return Du(e,g);if(a&&g.length===0)return Iu(e,{filterExport:o,filterReadonly:i,filterNameref:l,filterIndexedArray:r,filterAssocArray:s});if(g.length===0&&s&&!a)return _u(e);if(g.length===0&&r&&!a)return Tu(e);if(g.length===0&&!a)return Lu(e);let $="",N=0;for(let P of g){let C=P.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(C&&!u){let R=C[1],z=C[2],q=fe(e,R);if(q)return q;if(s&&ve(e,R).length>0){$+=`bash: declare: ${R}: cannot convert indexed to associative array
|
|
219
|
+
`,N=1;continue}if((r||!s&&!r)&&e.state.associativeArrays?.has(R)){$+=`bash: declare: ${R}: cannot convert associative to indexed array
|
|
220
|
+
`,N=1;continue}let _=s&&z.includes("[")?As(z,n):void 0,T=_===void 0?It(z,{...n,maxElements:s?n.maxElements*2:n.maxElements}):void 0;if(e.executionScope.consumeWork(_?.length??T?.length??0,"declare array assignment"),k(R),s?(e.state.associativeArrays??=new Set,e.state.associativeArrays.add(R),zt(e,R,"associative")):zt(e,R,"indexed"),Ee(e,R),e.state.env.delete(R),s&&z.includes("["))for(let[F,oe]of _??[])G(e,R,F,Qt(e,oe),"associative");else if(s){let F=T??[];for(let oe=0;oe<F.length;oe+=2){let ae=F[oe],An=oe+1<F.length?F[oe+1]:"";G(e,R,ae,An,"associative")}}else{let F=T??[];if(F.some(ae=>/^\[[^\]]+\]=/.test(ae))){let ae=0;for(let An of F){let Hs=An.match(/^\[([^\]]+)\]=(.*)$/);if(Hs){let Qs=Hs[1],Mf=Hs[2],Xn;if(/^-?\d+$/.test(Qs))Xn=Number.parseInt(Qs,10);else try{let Ff=new H,Bf=re(Ff,Qs);Xn=await Y(e,Bf.expression)}catch{Xn=0}G(e,R,Xn,Qt(e,Mf)),ae=Xn+1}else G(e,R,ae,An),ae++}}else for(let ae=0;ae<F.length;ae++)G(e,R,ae,F[ae])}A(R),i&&Ze(e,R),o&&mt(e,R);continue}if(c){let R=P.includes("=")?P.slice(0,P.indexOf("=")):P;if(_l(e,R),!P.includes("="))continue}if(f){let R=P.includes("=")?P.slice(0,P.indexOf("=")):P;if(ts(e,R),!P.includes("="))continue}let O=Uh(P);if(O){let{name:R,indexExpr:z,value:q}=O,_=fe(e,R);if(_)return _;k(R);let T;try{let F=new H,oe=re(F,z);T=await Y(e,oe.expression)}catch{let F=parseInt(z,10);T=Number.isNaN(F)?0:F}G(e,R,T,q),A(R),i&&Ze(e,R),o&&mt(e,R);continue}let U=P.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(U&&!u){let R=U[1],z=U[2],q=fe(e,R);if(q)return q;k(R);let _=It(z,n);if(e.state.associativeArrays?.has(R)){let T=As(z,n);e.executionScope.consumeWork(T.length,"declare array append"),dn(e,R,T.map(([F])=>F));for(let[F,oe]of T)G(e,R,F,oe,"associative")}else{e.executionScope.consumeWork(_.length,"declare array append");let T=ve(e,R),F=0,oe=e.state.env.get(R);T.length===0&&oe!==void 0?(G(e,R,0,oe),e.state.env.delete(R),F=1):T.length>0&&(F=Math.max(...T)+1),dn(e,R,Array.from({length:_.length},(ae,An)=>F+An));for(let ae=0;ae<_.length;ae++)G(e,R,F+ae,_[ae])}A(R),i&&Ze(e,R),o&&mt(e,R);continue}let X=P.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(X){let R=X[1],z=X[2],q=fe(e,R);if(q)return q;v(R),d&&No(e,R),p&&Ro(e,R),h&&Oo(e,R);let T=ve(e,R).length>0||e.state.associativeArrays?.has(R);if(Er(e,R)){let F=e.state.env.get(R)??"0",oe=parseInt(F,10)||0,ae=parseInt(await Mu(e,z),10)||0;z=String(oe+ae),e.state.env.set(R,z)}else if(T){z=qn(e,R,z);let F=le(e,R,0)??"";G(e,R,0,Ft([F,z],"",e.limits.maxStringLength,"declare append"))}else{z=qn(e,R,z);let F=e.state.env.get(R)??"";e.state.env.set(R,Ft([F,z],"",e.limits.maxStringLength,"declare append"))}A(R),i&&Ze(e,R),o&&mt(e,R),e.state.options.allexport&&!f&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(R));continue}if(P.includes("=")){let R=P.indexOf("="),z=P.slice(0,R),q=P.slice(R+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(z)){$+=`bash: typeset: \`${z}': not a valid identifier
|
|
221
|
+
`,N=1;continue}let _=fe(e,z);if(_)return _;if(v(z),l){if(q!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(q)){$+=`bash: declare: \`${q}': invalid variable name for name reference
|
|
222
|
+
`,N=1;continue}e.state.env.set(z,q),Dt(e,z),q!==""&&Xr(e,q)&&Ti(e,z),A(z),i&&Ze(e,z),o&&mt(e,z);continue}if(d&&No(e,z),p&&Ro(e,z),h&&Oo(e,z),Er(e,z)&&(q=await Mu(e,q)),q=qn(e,z,q),ue(e,z)){let T=Fe(e,z);T&&T!==z?e.state.env.set(T,q):e.state.env.set(z,q)}else e.state.env.set(z,q);A(z),i&&Ze(e,z),o&&mt(e,z),e.state.options.allexport&&!f&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(z))}else{let R=P;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(R)){$+=`bash: typeset: \`${R}': not a valid identifier
|
|
223
|
+
`,N=1;continue}if(r||s?k(R):v(R),l){Dt(e,R);let q=e.state.env.get(R);q!==void 0&&q!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(q)?Tl(e,R):q&&Xr(e,q)&&Ti(e,R),A(R),i&&Ze(e,R),o&&mt(e,R);continue}if(d&&No(e,R),p&&Ro(e,R),h&&Oo(e,R),s){if(ve(e,R).length>0){$+=`bash: declare: ${R}: cannot convert indexed to associative array
|
|
224
|
+
`,N=1;continue}e.state.associativeArrays??=new Set,e.state.associativeArrays.add(R),zt(e,R,"associative")}let z=Ce(e,R);!e.state.env.has(R)&&!z&&(r||s?zt(e,R,s?"associative":"indexed"):(e.state.declaredVars??=new Set,e.state.declaredVars.add(R))),A(R),i&&Ze(e,R),o&&mt(e,R)}}return L("",$,N)}async function Io(e,t){let n={maxElements:e.limits.maxArrayElements,maxStringBytes:e.limits.maxStringLength},r=!1,s=!1,i=!1,o=[];for(let a=0;a<t.length;a++){let l=t[a];if(l==="-a")r=!0;else if(l==="-A")s=!0;else if(l==="-p")i=!0;else if(l==="--"){o.push(...t.slice(a+1));break}else l.startsWith("-")||o.push(l)}if(o.length===0){let a="",l=Array.from(e.state.readonlyVars||[]).sort();for(let c of l){let u=e.state.env.get(c);if(u!==void 0){let f=u.replace(/\\/g,"\\\\").replace(/"/g,'\\"');a+=`declare -r ${c}="${f}"
|
|
225
|
+
`}}return ee(a)}for(let a of o){let l=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(l){let d=l[1],p=l[2],h=fe(e,d);if(h)return h;let m=It(p,n);if(e.state.associativeArrays?.has(d)){let E=As(p,n);e.executionScope.consumeWork(E.length,"readonly array append"),dn(e,d,E.map(([b])=>b));for(let[b,g]of E)G(e,d,b,g,"associative")}else{e.executionScope.consumeWork(m.length,"readonly array append");let E=ve(e,d),b=0,g=e.state.env.get(d);E.length===0&&g!==void 0?(G(e,d,0,g),e.state.env.delete(d),b=1):E.length>0&&(b=Math.max(...E)+1),dn(e,d,Array.from({length:m.length},(y,S)=>b+S));for(let y=0;y<m.length;y++)G(e,d,b+y,m[y])}Ze(e,d);continue}let c=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(c){let d=c[1],p=c[2],h=fe(e,d);if(h)return h;let m=e.state.env.get(d)??"";e.state.env.set(d,Ft([m,p],"",e.limits.maxStringLength,"readonly append")),Ze(e,d);continue}let u=du(a,n);if(u.value===void 0&&!u.isArray){Ze(e,u.name);continue}let f=await pu(e,u,{makeReadonly:!0});if(f)return f}return ne}function _o(e){return e.state.directoryStack??=[],e.state.directoryStack}function br(e,t){return t&&e===t?"~":t&&e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function qh(e){let t=e.split("/").filter(r=>r&&r!=="."),n=[];for(let r of t)r===".."?n.pop():n.push(r);return`/${n.join("/")}`}async function To(e,t){let n=_o(e),r;for(let a=0;a<t.length;a++){let l=t[a];if(l==="--"){if(a+1<t.length){if(r!==void 0)return D(`bash: pushd: too many arguments
|
|
226
|
+
`,2);r=t[a+1],a++}}else{if(l.startsWith("-")&&l!=="-")return D(`bash: pushd: ${l}: invalid option
|
|
227
|
+
`,2);if(r!==void 0)return D(`bash: pushd: too many arguments
|
|
228
|
+
`,2);r=l}}if(r===void 0){if(n.length<2)return D(`bash: pushd: no other directory
|
|
229
|
+
`,1);let a=n[0];n[0]=n[1],n[1]=a,r=n[0]}let s;if(r.startsWith("/"))s=r;else if(r===".."){let a=e.state.cwd.split("/").filter(l=>l);a.pop(),s=`/${a.join("/")}`}else r==="."?s=e.state.cwd:r.startsWith("~")?s=(e.state.env.get("HOME")||"/")+r.slice(1):s=`${e.state.cwd}/${r}`;s=qh(s);try{if(!(await e.fs.stat(s)).isDirectory)return D(`bash: pushd: ${r}: Not a directory
|
|
230
|
+
`,1)}catch{return D(`bash: pushd: ${r}: No such file or directory
|
|
231
|
+
`,1)}n.unshift(e.state.cwd),e.state.previousDir=e.state.cwd,e.state.cwd=s,e.state.env.set("PWD",s),e.state.env.set("OLDPWD",e.state.previousDir);let i=e.state.env.get("HOME")||"",o=`${[s,...n].map(a=>br(a,i)).join(" ")}
|
|
232
|
+
`;return ee(o)}function Lo(e,t){let n=_o(e);for(let o of t)if(o!=="--")return o.startsWith("-")&&o!=="-"?D(`bash: popd: ${o}: invalid option
|
|
233
|
+
`,2):D(`bash: popd: too many arguments
|
|
234
|
+
`,2);if(n.length===0)return D(`bash: popd: directory stack empty
|
|
235
|
+
`,1);let r=n.shift();if(!r)return D(`bash: popd: directory stack empty
|
|
236
|
+
`,1);e.state.previousDir=e.state.cwd,e.state.cwd=r,e.state.env.set("PWD",r),e.state.env.set("OLDPWD",e.state.previousDir);let s=e.state.env.get("HOME")||"",i=`${[r,...n].map(o=>br(o,s)).join(" ")}
|
|
237
|
+
`;return ee(i)}function Mo(e,t){let n=_o(e),r=!1,s=!1,i=!1,o=!1;for(let u of t)if(u!=="--")if(u.startsWith("-"))for(let f of u.slice(1))if(f==="c")r=!0;else if(f==="l")s=!0;else if(f==="p")i=!0;else if(f==="v")i=!0,o=!0;else return D(`bash: dirs: -${f}: invalid option
|
|
238
|
+
`,2);else return D(`bash: dirs: too many arguments
|
|
239
|
+
`,1);if(r)return e.state.directoryStack=[],ne;let a=[e.state.cwd,...n],l=e.state.env.get("HOME")||"",c;return o?(c=a.map((u,f)=>{let d=s?u:br(u,l);return` ${f} ${d}`}).join(`
|
|
206
240
|
`),c+=`
|
|
207
|
-
`):i?c=
|
|
241
|
+
`):i?c=a.map(u=>s?u:br(u,l)).join(`
|
|
208
242
|
`)+`
|
|
209
|
-
`:c=
|
|
210
|
-
`,
|
|
243
|
+
`:c=a.map(u=>s?u:br(u,l)).join(" ")+`
|
|
244
|
+
`,ee(c)}async function Is(e,t,n,r=!1){let s=t;if(s.length>0){let l=s[0];if(l==="--")s=s.slice(1);else if(l.startsWith("-")&&l!=="-"&&l.length>1)return D(`bash: eval: ${l}: invalid option
|
|
211
245
|
eval: usage: eval [arg ...]
|
|
212
|
-
`,2)}if(
|
|
213
|
-
`);throw
|
|
214
|
-
`,n=2;else{let i=BigInt(s);n=Number((i%256n+256n)%256n)}}throw new
|
|
215
|
-
`)}return
|
|
216
|
-
`,1);l!==void 0&&(
|
|
217
|
-
`,i=1;continue}if(l!==void 0)if(
|
|
218
|
-
`);let n=t[0],r=t[1],s=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r),i=n.startsWith(":"),
|
|
219
|
-
`,s||e.state.env.set(r,"?"),f+1<u.length?(e.state.env.set("__GETOPTS_CHARINDEX",String(f+1)),e.state.env.set("OPTIND",String(l))):(e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0")),{exitCode:s?2:0,stdout:"",stderr:m}}if(
|
|
220
|
-
`,s||e.state.env.set(r,"?")),e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"),{exitCode:s?2:0,stdout:"",stderr:m}}e.state.env.set("OPTARG",
|
|
221
|
-
`,1);
|
|
222
|
-
`,1):
|
|
223
|
-
`,1);c++}else l.push(
|
|
224
|
-
`,1);let
|
|
225
|
-
`,
|
|
226
|
-
`,1);let
|
|
227
|
-
`:
|
|
246
|
+
`,2)}if(s.length===0)return ne;let i=s.join(" ");if(i.trim()==="")return ne;let o=e.state.groupStdin,a=r||n!==void 0&&n!=="";a&&(e.state.groupStdin=n??"");try{let l=Ge(i);return await e.executeScript(l)}catch(l){if(l instanceof He||l instanceof Qe||l instanceof _e||l instanceof j)throw l;if(l.name==="ParseException")return D(`bash: eval: ${l.message}
|
|
247
|
+
`);throw l}finally{(a||o!==void 0&&e.state.groupStdin===void 0)&&(e.state.groupStdin=o)}}function Fo(e,t){let n,r="";if(t.length===0)n=e.state.lastExitCode;else{let s=t[0];if(s===""||!/^-?\d+$/.test(s))r=`bash: exit: ${s}: numeric argument required
|
|
248
|
+
`,n=2;else{let i=BigInt(s);n=Number((i%256n+256n)%256n)}}throw new j(n,"",r)}function Bo(e,t){let n=!1,r=[];for(let o of t)o==="-n"?n=!0:o==="-p"||o==="--"||r.push(o);if(r.length===0&&!n){let o="",a=e.state.exportedVars??new Set,l=Array.from(a).sort();for(let c of l){let u=e.state.env.get(c);u!==void 0&&(o+=`declare -x ${c}=${wr(u)}
|
|
249
|
+
`)}return ee(o)}if(n){for(let o of r){let a,l;if(o.includes("=")){let c=o.indexOf("=");a=o.slice(0,c),l=o.slice(c+1)}else a=o;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a))return L("",`bash: export: \`${o}': not a valid identifier
|
|
250
|
+
`,1);l!==void 0&&(fe(e,a),e.state.env.set(a,l)),ts(e,a)}return ne}let s="",i=0;for(let o of r){let a,l,c=!1,u=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(u)a=u[1],l=u[2],c=!0;else if(o.includes("=")){let f=o.indexOf("=");a=o.slice(0,f),l=o.slice(f+1)}else a=o;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)){s+=`bash: export: \`${o}': not a valid identifier
|
|
251
|
+
`,i=1;continue}if(l!==void 0)if(fe(e,a),c){let f=e.state.env.get(a)??"";e.state.env.set(a,f+l)}else e.state.env.set(a,l);else e.state.env.has(a)||e.state.env.set(a,"");mt(e,a)}return L("",s,i)}function _s(e,t){if(t.length<2)return D(`bash: getopts: usage: getopts optstring name [arg ...]
|
|
252
|
+
`);let n=t[0],r=t[1],s=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r),i=n.startsWith(":"),o=i?n.slice(1):n,a;if(t.length>2)a=t.slice(2);else{let m=Number.parseInt(e.state.env.get("#")||"0",10);a=[];for(let E=1;E<=m;E++)a.push(e.state.env.get(String(E))||"")}let l=Number.parseInt(e.state.env.get("OPTIND")||"1",10);l<1&&(l=1);let c=Number.parseInt(e.state.env.get("__GETOPTS_CHARINDEX")||"0",10);if(e.state.env.set("OPTARG",""),l>a.length)return s||e.state.env.set(r,"?"),e.state.env.set("OPTIND",String(a.length+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"),{exitCode:s?2:1,stdout:"",stderr:""};let u=a[l-1];if(!u||u==="-"||!u.startsWith("-"))return s||e.state.env.set(r,"?"),{exitCode:s?2:1,stdout:"",stderr:""};if(u==="--")return e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"),s||e.state.env.set(r,"?"),{exitCode:s?2:1,stdout:"",stderr:""};let f=c===0?1:c,d=u[f];if(!d)return e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"),_s(e,t);let p=o.indexOf(d);if(p===-1){let m="";return i?e.state.env.set("OPTARG",d):m=`bash: illegal option -- ${d}
|
|
253
|
+
`,s||e.state.env.set(r,"?"),f+1<u.length?(e.state.env.set("__GETOPTS_CHARINDEX",String(f+1)),e.state.env.set("OPTIND",String(l))):(e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0")),{exitCode:s?2:0,stdout:"",stderr:m}}if(p+1<o.length&&o[p+1]===":")if(f+1<u.length)e.state.env.set("OPTARG",u.slice(f+1)),e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0");else{if(l>=a.length){let m="";return i?(e.state.env.set("OPTARG",d),s||e.state.env.set(r,":")):(m=`bash: option requires an argument -- ${d}
|
|
254
|
+
`,s||e.state.env.set(r,"?")),e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"),{exitCode:s?2:0,stdout:"",stderr:m}}e.state.env.set("OPTARG",a[l]),e.state.env.set("OPTIND",String(l+2)),e.state.env.set("__GETOPTS_CHARINDEX","0")}else f+1<u.length?(e.state.env.set("__GETOPTS_CHARINDEX",String(f+1)),e.state.env.set("OPTIND",String(l))):(e.state.env.set("OPTIND",String(l+1)),e.state.env.set("__GETOPTS_CHARINDEX","0"));return s||e.state.env.set(r,d),{exitCode:s?2:0,stdout:"",stderr:""}}async function Wo(e,t){e.state.hashTable||(e.state.hashTable=new Map);let n=!1,r=!1,s=!1,i=!1,o=!1,a="",l=[],c=0;for(;c<t.length;){let h=t[c];if(h==="--"){c++,l.push(...t.slice(c));break}if(h==="-r")n=!0,c++;else if(h==="-d")r=!0,c++;else if(h==="-l")s=!0,c++;else if(h==="-t")o=!0,c++;else if(h==="-p"){if(i=!0,c++,c>=t.length)return D(`bash: hash: -p: option requires an argument
|
|
255
|
+
`,1);a=t[c],c++}else if(h.startsWith("-")&&h.length>1){for(let m of h.slice(1))if(m==="r")n=!0;else if(m==="d")r=!0;else if(m==="l")s=!0;else if(m==="t")o=!0;else return m==="p"?D(`bash: hash: -p: option requires an argument
|
|
256
|
+
`,1):D(`bash: hash: -${m}: invalid option
|
|
257
|
+
`,1);c++}else l.push(h),c++}if(n)return e.state.hashTable.clear(),ne;if(r){if(l.length===0)return D(`bash: hash: -d: option requires an argument
|
|
258
|
+
`,1);let h=!1,m="";for(let E of l)e.state.hashTable.has(E)?e.state.hashTable.delete(E):(m+=`bash: hash: ${E}: not found
|
|
259
|
+
`,h=!0);return h?D(m,1):ne}if(o){if(l.length===0)return D(`bash: hash: -t: option requires an argument
|
|
260
|
+
`,1);let h="",m=!1,E="";for(let b of l){let g=e.state.hashTable.get(b);g?l.length>1?h+=`${b} ${g}
|
|
261
|
+
`:h+=`${g}
|
|
228
262
|
`:(E+=`bash: hash: ${b}: not found
|
|
229
|
-
`,m=!0)}return m?{exitCode:1,stdout:
|
|
230
|
-
`,1);let
|
|
231
|
-
`);let
|
|
232
|
-
`}else{
|
|
233
|
-
`;for(let[,m]of e.state.hashTable)
|
|
234
|
-
`}return
|
|
235
|
-
`,u=!0;continue}let m=!1;for(let E of
|
|
236
|
-
`,u=!0)}return u?
|
|
263
|
+
`,m=!0)}return m?{exitCode:1,stdout:h,stderr:E}:ee(h)}if(i){if(l.length===0)return D(`bash: hash: usage: hash [-lr] [-p pathname] [-dt] [name ...]
|
|
264
|
+
`,1);let h=l[0];return e.state.hashTable.set(h,a),ne}if(l.length===0){if(e.state.hashTable.size===0)return ee(`hash: hash table empty
|
|
265
|
+
`);let h="";if(s)for(let[m,E]of e.state.hashTable){let b=m.startsWith("-")?" --":"";h+=`builtin hash -p ${Ae(E)}${b} ${Ae(m)}
|
|
266
|
+
`}else{h=`hits command
|
|
267
|
+
`;for(let[,m]of e.state.hashTable)h+=` 1 ${m}
|
|
268
|
+
`}return ee(h)}let u=!1,f="",p=(e.state.env.get("PATH")||"/usr/bin:/bin").split(":");for(let h of l){if(h.includes("/")){f+=`bash: hash: ${h}: cannot use / in name
|
|
269
|
+
`,u=!0;continue}let m=!1;for(let E of p){if(!E)continue;let b=`${E}/${h}`;if(await e.fs.exists(b)){e.state.hashTable.set(h,b),m=!0;break}}m||(f+=`bash: hash: ${h}: not found
|
|
270
|
+
`,u=!0)}return u?D(f,1):ne}var Fu=new Map([[":",[": [arguments]",`Null command.
|
|
237
271
|
No effect; the command does nothing.
|
|
238
272
|
Exit Status:
|
|
239
273
|
Always succeeds.`]],[".",[". filename [arguments]",`Execute commands from a file in the current shell.
|
|
@@ -578,35 +612,37 @@ eval: usage: eval [arg ...]
|
|
|
578
612
|
job specification, and reports its termination status.
|
|
579
613
|
Exit Status:
|
|
580
614
|
Returns the status of the last ID; fails if ID is invalid or an invalid
|
|
581
|
-
option is given.`]]]),
|
|
582
|
-
`,2)}s++}else r.push(l),s++}if(r.length===0)return
|
|
583
|
-
`,
|
|
615
|
+
option is given.`]]]),Bu=[...Fu.keys()].sort();function Vo(e,t){let n=!1,r=[],s=0;for(;s<t.length;){let l=t[s];if(l==="--"){for(s++;s<t.length;)r.push(t[s]),s++;break}if(l.startsWith("-")&&l.length>1){for(let c=1;c<l.length;c++){let u=l[c];if(u==="s")n=!0;else return D(`bash: help: -${u}: invalid option
|
|
616
|
+
`,2)}s++}else r.push(l),s++}if(r.length===0)return Gh();let i="",o=!1,a="";for(let l of r){let c=jh(l);if(c.length===0){a+=`bash: help: no help topics match \`${l}'. Try \`help help' or \`man -k ${l}' or \`info ${l}'.
|
|
617
|
+
`,o=!0;continue}for(let u of c){let f=Fu.get(u);if(!f)continue;let[d,p]=f;n?i+=`${u}: ${d}
|
|
584
618
|
`:i+=`${u}: ${d}
|
|
585
|
-
${
|
|
586
|
-
`}}return{exitCode:
|
|
619
|
+
${p}
|
|
620
|
+
`}}return{exitCode:o?1:0,stdout:i,stderr:a}}function jh(e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,"."),n=ge(`^${t}$`);return Bu.filter(r=>n.test(r))}function Gh(){let e=[];e.push("just-bash shell builtins"),e.push("These shell commands are defined internally. Type `help' to see this list."),e.push("Type `help name' to find out more about the function `name'."),e.push("");let t=36,n=Bu.slice(),r=Math.ceil(n.length/2);for(let s=0;s<r;s++){let i=n[s]||"",o=n[s+r]||"",a=i.padEnd(t);e.push(o?`${a}${o}`:i)}return ee(`${e.join(`
|
|
587
621
|
`)}
|
|
588
|
-
`)}function
|
|
589
|
-
`);let n=
|
|
590
|
-
`)}return
|
|
591
|
-
`);let r=e.state.localScopes[e.state.localScopes.length-1];for(e.state.localArrayScopes??=[];e.state.localArrayScopes.length<e.state.localScopes.length;)e.state.localArrayScopes.push(new Map);let s=e.state.localArrayScopes.at(-1),i=d=>{if(r.has(d)||r.set(d,e.state.env.get(d)),s&&!s.has(d)){let
|
|
592
|
-
`)}return
|
|
593
|
-
`,
|
|
594
|
-
`,
|
|
595
|
-
`,
|
|
596
|
-
`,s=0,i=0,
|
|
597
|
-
`,c+=2):g==="-n"&&c+1<t.length?(s=Number.parseInt(t[c+1],10)||0,c+=2):g==="-O"&&c+1<t.length?(i=Number.parseInt(t[c+1],10)||0,c+=2):g==="-s"&&c+1<t.length?(
|
|
598
|
-
`,1);if(!Number.isSafeInteger(i)||i<0)return
|
|
599
|
-
`,1);
|
|
600
|
-
`,1);E(
|
|
601
|
-
`,1);E(
|
|
602
|
-
`,1);i===0&&
|
|
603
|
-
`,
|
|
604
|
-
`,1);
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
`)
|
|
609
|
-
|
|
622
|
+
`)}function Zh(e){let t=[],n="",r=0;for(let s of e){for(let i of s)i==="("?r++:i===")"&&r--;n?n+=` ${s}`:n=s,r===0&&(t.push(n),n="")}return n&&t.push(n),t}async function zo(e,t){if(t.length===0)return D(`bash: let: expression expected
|
|
623
|
+
`);let n=Zh(t),r=0;for(let s of n)try{let o=Ge(`(( ${s} ))`).statements[0];if(o&&o.pipelines.length>0&&o.pipelines[0].commands.length>0){let a=o.pipelines[0].commands[0];a.type==="ArithmeticCommand"&&(r=await Y(e,a.expression.expression))}}catch(i){return D(`bash: let: ${s}: ${i.message}
|
|
624
|
+
`)}return L("","",r===0?1:0)}async function Uo(e,t){let n={maxElements:e.limits.maxArrayElements,maxStringBytes:e.limits.maxStringLength};if(e.state.localScopes.length===0)return D(`bash: local: can only be used in a function
|
|
625
|
+
`);let r=e.state.localScopes[e.state.localScopes.length-1];for(e.state.localArrayScopes??=[];e.state.localArrayScopes.length<e.state.localScopes.length;)e.state.localArrayScopes.push(new Map);let s=e.state.localArrayScopes.at(-1),i=d=>{if(r.has(d)||r.set(d,e.state.env.get(d)),s&&!s.has(d)){let p=Pe(e,d);s.set(d,p?Me(p):void 0)}},o="",a=0,l=!1,c=!1,u=!1,f=[];for(let d of t)if(d==="-n")l=!0;else if(d==="-a")c=!0;else if(d==="-p")u=!0;else if(d.startsWith("-")&&!d.includes("="))for(let p of d.slice(1))p==="n"?l=!0:p==="a"?c=!0:p==="p"&&(u=!0);else f.push(d);if(f.length===0){let d="",p=Array.from(r.keys()).sort();for(let h of p){let m=e.state.env.get(h);m!==void 0&&(d+=`${h}=${m}
|
|
626
|
+
`)}return L(d,"",0)}for(let d of f){let p,h,m=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(m){p=m[1];let S=m[2];if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(p)){o+=`bash: local: \`${d}': not a valid identifier
|
|
627
|
+
`,a=1;continue}fe(e,p,"bash");let v=It(S,n);e.executionScope.consumeWork(v.length,"local array assignment"),i(p),Ee(e,p),zt(e,p,"indexed");for(let k=0;k<v.length;k++)G(e,p,k,v[k]);Jt(e,p),l&&Dt(e,p);continue}let E=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(E){p=E[1];let S=E[2];fe(e,p,"bash"),i(p);let v=It(S,n);e.executionScope.consumeWork(v.length,"local array append");let k=ve(e,p),A=0,$=e.state.env.get(p);k.length===0&&$!==void 0?(G(e,p,0,$),e.state.env.delete(p),A=1):k.length>0&&(A=Math.max(...k)+1),dn(e,p,Array.from({length:v.length},(N,P)=>A+P));for(let N=0;N<v.length;N++)G(e,p,A+N,v[N]);Jt(e,p),l&&Dt(e,p);continue}let b=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(b){p=b[1];let S=b[2];fe(e,p,"bash"),r.has(p)||r.set(p,e.state.env.get(p));let v=e.state.env.get(p)??"";e.state.env.set(p,Ft([v,S],"",e.limits.maxStringLength,"local append")),Jt(e,p),l&&Dt(e,p);continue}let g=d.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(g){p=g[1];let S=g[2],v=g[3];fe(e,p,"bash"),i(p);let k;try{let A=new H,$=re(A,S);k=await Y(e,$.expression)}catch{let A=parseInt(S,10);k=Number.isNaN(A)?0:A}G(e,p,k,v),Jt(e,p),l&&Dt(e,p);continue}if(d.includes("=")){let S=d.indexOf("=");p=d.slice(0,S),h=d.slice(S+1)}else p=d;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(p)){o+=`bash: local: \`${d}': not a valid identifier
|
|
628
|
+
`,a=1;continue}let y=r.has(p);if(h!==void 0){let S=e.state.env.get(p);if(e.state.tempEnvBindings){let v=e.state.accessedTempEnvVars?.has(p),k=e.state.mutatedTempEnvVars?.has(p);if(!v&&!k)for(let A=e.state.tempEnvBindings.length-1;A>=0;A--){let $=e.state.tempEnvBindings[A];if($.has(p)){S=$.get(p);break}}}hu(e,p,S)}if(!y){let S=e.state.env.get(p);if(e.state.tempEnvBindings)for(let v=e.state.tempEnvBindings.length-1;v>=0;v--){let k=e.state.tempEnvBindings[v];if(k.has(p)){S=k.get(p);break}}r.set(p,S),c&&i(p)}if(c&&h===void 0)Ee(e,p),zt(e,p,"indexed");else if(h!==void 0){if(fe(e,p,"bash"),l&&h!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(h)){o+=`bash: local: \`${h}': invalid variable name for name reference
|
|
629
|
+
`,a=1;continue}e.state.env.set(p,h),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(p))}else{let S=e.state.tempEnvBindings?.some(v=>v.has(p));!y&&!S&&e.state.env.delete(p)}Jt(e,p),l&&Dt(e,p)}return L("",o,a)}function qo(e,t,n){let r=`
|
|
630
|
+
`,s=0,i=0,o=0,a=!1,l="MAPFILE",c=0;for(;c<t.length;){let g=t[c];g==="-d"&&c+1<t.length?(r=t[c+1]===""?"\0":t[c+1]||`
|
|
631
|
+
`,c+=2):g==="-n"&&c+1<t.length?(s=Number.parseInt(t[c+1],10)||0,c+=2):g==="-O"&&c+1<t.length?(i=Number.parseInt(t[c+1],10)||0,c+=2):g==="-s"&&c+1<t.length?(o=Number.parseInt(t[c+1],10)||0,c+=2):g==="-t"?(a=!0,c++):g==="-u"||g==="-C"||g==="-c"?c+=2:(g.startsWith("-")||(l=g),c++)}if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(l))return L("",`mapfile: ${l}: not a valid identifier
|
|
632
|
+
`,1);if(!Number.isSafeInteger(i)||i<0)return L("",`mapfile: invalid array origin
|
|
633
|
+
`,1);fe(e,l,"mapfile");let u=n;!u&&e.state.groupStdin!==void 0&&(u=e.state.groupStdin);let f=[],d=0,p=0,h=0,m=e.limits.maxArrayElements,E=g=>{if(B(g)>e.limits.maxStringLength)throw new x(`mapfile: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");f.push(g)};for(;d<u.length;){e.executionScope.consumeWork(1,"mapfile input");let g=u.indexOf(r,d);if(g===-1){if(d<u.length){if(h<o)h++;else if(s===0||p<s){let v=u.slice(d),k=v.indexOf("\0");if(k!==-1&&(v=v.substring(0,k)),f.length>=m)return L("",`mapfile: array element limit exceeded (${m})
|
|
634
|
+
`,1);E(v),p++}}break}let y=u.slice(d,g),S=y.indexOf("\0");if(S!==-1&&(y=y.substring(0,S)),!a&&r!=="\0"&&(y+=r),d=g+r.length,h<o){h++;continue}if(s>0&&p>=s)break;if(f.length>=m)return L("",`mapfile: array element limit exceeded (${m})
|
|
635
|
+
`,1);E(y),p++}let b=new Set(i===0?[]:e.state.arrays?.get(l)?.elements.keys()??[]);for(let g=0;g<f.length;g++)if(b.add(String(i+g)),b.size>m)return L("",`mapfile: array element limit exceeded (${m})
|
|
636
|
+
`,1);i===0&&Ee(e,l);for(let g=0;g<f.length;g++)G(e,l,i+g,f[g]);return e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=""),{...L("","",0),internalStdinConsumed:u.length}}function jo(e,t,n,r=-1){let s=!1,i=`
|
|
637
|
+
`,o="",a=-1,l=-1,c=null,u=-1,f=-1,d=[],p=0,h=!1,m=(_,T)=>{let F=1;for(;F<_.length;){let oe=_[F];if(oe==="r")s=!0,F++;else if(oe==="s")F++;else{if(oe==="d")return F+1<_.length?(i=_.substring(F+1),{nextArgIndex:T+1}):T+1<t.length?(i=t[T+1],{nextArgIndex:T+2}):{nextArgIndex:T+1};if(oe==="n"){if(F+1<_.length){let ae=_.substring(F+1);return a=Number.parseInt(ae,10),(Number.isNaN(a)||a<0)&&(h=!0,a=0),{nextArgIndex:T+1}}else if(T+1<t.length)return a=Number.parseInt(t[T+1],10),(Number.isNaN(a)||a<0)&&(h=!0,a=0),{nextArgIndex:T+2};return{nextArgIndex:T+1}}else if(oe==="N"){if(F+1<_.length){let ae=_.substring(F+1);return l=Number.parseInt(ae,10),(Number.isNaN(l)||l<0)&&(h=!0,l=0),{nextArgIndex:T+1}}else if(T+1<t.length)return l=Number.parseInt(t[T+1],10),(Number.isNaN(l)||l<0)&&(h=!0,l=0),{nextArgIndex:T+2};return{nextArgIndex:T+1}}else{if(oe==="a")return F+1<_.length?(c=_.substring(F+1),{nextArgIndex:T+1}):T+1<t.length?(c=t[T+1],{nextArgIndex:T+2}):{nextArgIndex:T+1};if(oe==="p")return F+1<_.length?(o=_.substring(F+1),{nextArgIndex:T+1}):T+1<t.length?(o=t[T+1],{nextArgIndex:T+2}):{nextArgIndex:T+1};if(oe==="u"){if(F+1<_.length){let ae=_.substring(F+1);return u=Number.parseInt(ae,10),Number.isNaN(u)||u<0?{nextArgIndex:-2}:{nextArgIndex:T+1}}else if(T+1<t.length)return u=Number.parseInt(t[T+1],10),Number.isNaN(u)||u<0?{nextArgIndex:-2}:{nextArgIndex:T+2};return{nextArgIndex:T+1}}else if(oe==="t"){if(F+1<_.length){let ae=_.substring(F+1);return f=Number.parseFloat(ae),Number.isNaN(f)&&(f=0),{nextArgIndex:T+1}}else if(T+1<t.length)return f=Number.parseFloat(t[T+1]),Number.isNaN(f)&&(f=0),{nextArgIndex:T+2};return{nextArgIndex:T+1}}else if(oe==="e"||oe==="i"||oe==="P"){if(oe==="i"&&T+1<t.length)return{nextArgIndex:T+2};F++}else F++}}}return{nextArgIndex:T+1}};for(;p<t.length;){let _=t[p];if(_.startsWith("-")&&_.length>1&&_!=="--"){let T=m(_,p);if(T.nextArgIndex===-1)return{stdout:"",stderr:"",exitCode:2};if(T.nextArgIndex===-2)return{stdout:"",stderr:"",exitCode:1};p=T.nextArgIndex}else if(_==="--")for(p++;p<t.length;)d.push(t[p]),p++;else d.push(_),p++}if(h)return L("","",1);d.length===0&&c===null&&d.push("REPLY");let E=new Set;c&&E.add(c);for(let _ of d)E.add(_);l>=0&&d.length===0&&E.add("REPLY");for(let _ of E){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(_))return L("",`bash: read: \`${_}': not a valid identifier
|
|
638
|
+
`,1);fe(e,_,"bash")}if(f===0){if(c)Ee(e,c);else{for(let _ of d)e.state.env.set(_,"");d.length===0&&e.state.env.set("REPLY","")}return L("","",0)}if(f<0&&f!==-1)return L("","",1);let b=n,g=tt(e,u),y=u>0&&!(g?.kind==="dup-in"&&g.sourceFd===0);if(y){let _=Cs(e,u);if("error"in _){let F=_.error==="write-only"||u===1||u===2?`bash: read: read error: ${u}: Bad file descriptor
|
|
639
|
+
`:`bash: read: ${u}: invalid file descriptor: Bad file descriptor
|
|
640
|
+
`;return L("",F,1)}b=_.content}else!b&&e.state.groupStdin!==void 0&&(b=e.state.groupStdin);let S=i===""?"\0":i,v="",k=0,A=_=>{let T=B(_);if(T>e.limits.maxStringLength-k)throw new x(`read: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length");v+=_,k+=T},$=_=>{if(B(_)>e.limits.maxStringLength)throw new x(`read: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"string_length")},N=0,P=!0,C=_=>{y?tn(e,u,_):r>=0?tn(e,r,_):e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=b.substring(_),e.state.groupStdinSourceFd!==void 0&&tn(e,e.state.groupStdinSourceFd,_))};if(l>=0){let _=Math.min(l,b.length);v=b.substring(0,_),$(v),N=_,P=_>=l,C(N);let T=d[0]||"REPLY";e.state.env.set(T,v);for(let F=1;F<d.length;F++)e.state.env.set(d[F],"");return L("","",P?0:1)}else if(a>=0){let _=0,T=0,F=!1;for(;T<b.length&&_<a;){let oe=b[T];if(oe===S){N=T+1,F=!0;break}if(!s&&oe==="\\"&&T+1<b.length){let ae=b[T+1];if(ae===S&&S===`
|
|
641
|
+
`){T+=2,N=T;continue}if(ae===S){T+=2,_++,A(ae),N=T;continue}A(ae),T+=2,_++,N=T}else A(oe),T++,_++,N=T}P=_>=a||F,C(N)}else{N=0;let _=0;for(;_<b.length;){let T=b[_];if(T===S){N=_+S.length,P=!0;break}if(!s&&T==="\\"&&_+1<b.length){let F=b[_+1];if(F===`
|
|
642
|
+
`){_+=2;continue}if(F===S){A(F),_+=2;continue}A(T),A(F),_+=2;continue}A(T),_++}if(_>=b.length&&(P=!1,N=_,v.length===0&&b.length===0)){for(let T of d)e.state.env.set(T,"");return c&&Ee(e,c),L("","",1)}C(N)}S===`
|
|
643
|
+
`&&v.endsWith(`
|
|
644
|
+
`)&&(v=v.slice(0,-1));let O=_=>s?_:_.replace(/\\(.)/g,"$1");if(d.length===1&&d[0]==="REPLY")return e.state.env.set("REPLY",O(v)),L("","",P?0:1);let U=ke(e.state.env),X=e.limits.maxArrayElements;if(c){let{words:_}=_i(v,U,X,void 0,s);Ee(e,c);for(let T=0;T<_.length;T++)G(e,c,T,O(_[T]));return L("","",P?0:1)}let R=d.length,{words:z,wordStarts:q}=_i(v,U,X,R,s);for(let _=0;_<d.length;_++){let T=d[_];if(_<d.length-1)e.state.env.set(T,O(z[_]??""));else if(_<q.length){let F=v.substring(q[_]);F=Il(F,U,s),F=O(F),e.state.env.set(T,F)}else e.state.env.set(T,"")}return L("","",P?0:1)}function Go(e,t){if(e.state.callDepth===0&&e.state.sourceDepth===0)return D("bash: return: can only `return' from a function or sourced script\n");let n=e.state.lastExitCode;if(t.length>0){let r=t[0],s=Number.parseInt(r,10);if(r===""||Number.isNaN(s)||!/^-?\d+$/.test(r))return D(`bash: return: ${r}: numeric argument required
|
|
645
|
+
`,2);n=(s%256+256)%256}throw new _e(n)}var Sr=`set: usage: set [-eux] [+eux] [-o option] [+o option]
|
|
610
646
|
Options:
|
|
611
647
|
-e Exit immediately if a command exits with non-zero status
|
|
612
648
|
+e Disable -e
|
|
@@ -622,185 +658,151 @@ Options:
|
|
|
622
658
|
+o pipefail Disable pipefail
|
|
623
659
|
-o xtrace Same as -x
|
|
624
660
|
+o xtrace Disable xtrace
|
|
625
|
-
`,
|
|
661
|
+
`,Wu=new Map([["e","errexit"],["u","nounset"],["x","xtrace"],["v","verbose"],["f","noglob"],["C","noclobber"],["a","allexport"],["n","noexec"],["h",null],["b",null],["m",null],["B",null],["H",null],["P",null],["T",null],["E",null],["p",null]]),Ts=new Map([["errexit","errexit"],["pipefail","pipefail"],["nounset","nounset"],["xtrace","xtrace"],["verbose","verbose"],["noclobber","noclobber"],["noglob","noglob"],["allexport","allexport"],["noexec","noexec"],["posix","posix"],["vi","vi"],["emacs","emacs"],["notify",null],["monitor",null],["braceexpand",null],["histexpand",null],["physical",null],["functrace",null],["errtrace",null],["privileged",null],["hashall",null],["ignoreeof",null],["interactive-comments",null],["keyword",null],["onecmd",null]]),Uu=["errexit","nounset","pipefail","verbose","xtrace","posix","allexport","noclobber","noglob","noexec","vi","emacs"],qu=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"];function Zo(e,t,n){t!==null&&(n&&(t==="vi"?e.state.options.emacs=!1:t==="emacs"&&(e.state.options.vi=!1)),e.state.options[t]=n,Rn(e))}function Hh(e,t){return t+1<e.length&&!e[t+1].startsWith("-")&&!e[t+1].startsWith("+")}function Qh(e,t,n){let r=ve(e,n);if(r.length===0){t.append(n).append("=()");return}t.append(n).append("=(");for(let s=0;s<r.length;s++){let i=r[s],o=le(e,n,i)??"";s>0&&t.append(" "),t.append(`[${i}]=`),t.reserve(Ds(o)),t.append(sn(o))}t.append(")")}function Kh(e,t){if(/^[a-zA-Z0-9_]+$/.test(t)){e.append(t);return}e.reserve(Ds(t)),e.append(sn(t))}function Xh(e,t,n){let r=Et(e,n);if(r.length===0){t.append(n).append("=()");return}t.append(n).append("=(");for(let s=0;s<r.length;s++){let i=r[s],o=le(e,n,i)??"";s>0&&t.append(" "),t.append("["),Kh(t,i),t.append("]="),t.reserve(Ds(o)),t.append(sn(o))}t.append(" )")}function Yh(e){let t=new Set,n=e.state.associativeArrays??new Set;for(let[r,s]of e.state.arrays??[])s.kind==="indexed"&&!n.has(r)&&t.add(r);return t}function Jh(e){return e.state.associativeArrays??new Set}function Vu(e){let t=Uu.map(r=>`${r.padEnd(16)}${e.state.options[r]?"on":"off"}`),n=qu.map(r=>`${r.padEnd(16)}off`);return`${[...t,...n].sort().join(`
|
|
626
662
|
`)}
|
|
627
|
-
`}function
|
|
663
|
+
`}function zu(e){let t=Uu.map(r=>`set ${e.state.options[r]?"-o":"+o"} ${r}`),n=qu.map(r=>`set +o ${r}`);return`${[...t,...n].sort().join(`
|
|
628
664
|
`)}
|
|
629
|
-
`}function
|
|
630
|
-
`);return
|
|
631
|
-
${
|
|
632
|
-
${
|
|
633
|
-
${
|
|
634
|
-
${
|
|
635
|
-
`;if(e.state.options.posix)throw new
|
|
636
|
-
`;if(e.state.options.posix)throw new
|
|
637
|
-
`,2);let r=n[0],s=null,i=null;if(r.includes("/")){let c=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(c),s=c}catch{}}else{let u=(e.state.env.get("PATH")||"").split(":").filter(f=>f);for(let f of u){let d=e.fs.resolvePath(e.state.cwd,`${f}/${r}`);try{if((await e.fs.stat(d)).isDirectory)continue;i=await e.fs.readFile(d),s=d;break}catch{}}if(i===null){let f=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(f),s=f}catch{}}}if(i===null)return
|
|
638
|
-
`);let
|
|
639
|
-
`);throw c}}function
|
|
640
|
-
`,s=1;continue}if(
|
|
641
|
-
`,s=1;continue}let g=await
|
|
642
|
-
`,s=1;continue}if(g===null)continue;if(g<0){let
|
|
643
|
-
`,s=1;continue}let
|
|
644
|
-
`,s=1;continue}let
|
|
645
|
-
`,s=1;continue}let u=i;if(
|
|
646
|
-
`,s=1;continue}
|
|
647
|
-
`,s=1;continue}if(u==="@"||u==="*"){
|
|
648
|
-
`,s=1;continue}let
|
|
649
|
-
`,s=1;continue}if(
|
|
650
|
-
`,s=1;continue}let g=E+
|
|
651
|
-
`,s=1;continue}let
|
|
652
|
-
`,s=1;continue}let
|
|
653
|
-
`,s=1;continue}
|
|
654
|
-
`}}}u++}else break}for(;u<t.length;)c.push(t[u]),u++;if(l)return
|
|
655
|
-
`};if(c.length===0){if(s||i){let b=[];for(let g of
|
|
665
|
+
`}function Qo(e,t){if(t.includes("--help"))return ee(Sr);if(t.length===0){let i=Yh(e),o=Jh(e),a=[];for(let[u,f]of e.state.env)/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)&&(i.has(u)||o.has(u)||a.push([u,f]));let l=[...a.map(([u,f])=>({kind:"scalar",name:u,value:f})),...Array.from(i,u=>({kind:"indexed",name:u})),...Array.from(o,u=>({kind:"associative",name:u}))];l.sort((u,f)=>u.name<f.name?-1:u.name>f.name?1:0);let c=new Pn(e.limits.maxOutputSize,"set");for(let u of l)e.executionScope.consumeWork(1,"set variable listing"),u.kind==="scalar"?(c.append(u.name).append("="),c.reserve(Cu(u.value)),c.append(Ae(u.value))):u.kind==="indexed"?Qh(e,c,u.name):Xh(e,c,u.name),c.append(`
|
|
666
|
+
`);return ee(c.build())}let n=[],r=()=>n.length>0?ee(n.join("")):ne,s=0;for(;s<t.length;){let i=t[s];if((i==="-o"||i==="+o")&&Hh(t,s)){let o=t[s+1];if(!Ts.has(o)){let a=`bash: set: ${o}: invalid option name
|
|
667
|
+
${Sr}`;if(e.state.options.posix)throw new st(1,"",a);return D(a)}Zo(e,Ts.get(o)??null,i==="-o"),s+=2;continue}if(i==="-o"){n.push(Vu(e)),s++;continue}if(i==="+o"){n.push(zu(e)),s++;continue}if(i.length>1&&(i[0]==="-"||i[0]==="+")&&i[1]!=="-"){let o=i[0]==="-",a=0;for(let l=1;l<i.length;l++){let c=i[l];if(c==="o"){let u=s+1+a;if(u<t.length&&!t[u].startsWith("-")&&!t[u].startsWith("+")){let d=t[u];if(!Ts.has(d)){let p=`bash: set: ${d}: invalid option name
|
|
668
|
+
${Sr}`;if(e.state.options.posix)throw new st(1,"",p);return D(p)}Zo(e,Ts.get(d)??null,o),a++;continue}n.push(o?Vu(e):zu(e));continue}if(!Wu.has(c)){let u=`bash: set: ${i[0]}${c}: invalid option
|
|
669
|
+
${Sr}`;if(e.state.options.posix)throw new st(1,"",u);return D(u)}Zo(e,Wu.get(c)??null,o)}s+=1+a;continue}if(i==="--")return Ho(e,t.slice(s+1)),r();if(i==="-"){if(e.state.options.xtrace=!1,e.state.options.verbose=!1,Rn(e),s+1<t.length)return Ho(e,t.slice(s+1)),r();s++;continue}if(i==="+"){s++;continue}if(i.startsWith("-")||i.startsWith("+")){let o=`bash: set: ${i}: invalid option
|
|
670
|
+
${Sr}`;if(e.state.options.posix)throw new st(1,"",o);return D(o)}return Ho(e,t.slice(s)),r()}return r()}function Ho(e,t){let n=1;for(;e.state.env.has(String(n));)e.state.env.delete(String(n)),n++;for(let r=0;r<t.length;r++)e.state.env.set(String(r+1),t[r]);e.state.env.set("#",String(t.length)),e.state.env.set("@",t.join(" ")),e.state.env.set("*",t.join(" "))}function Ko(e,t){let n=1;if(t.length>0){let o=Number.parseInt(t[0],10);if(Number.isNaN(o)||o<0){let a=`bash: shift: ${t[0]}: numeric argument required
|
|
671
|
+
`;if(e.state.options.posix)throw new st(1,"",a);return D(a)}n=o}let r=Number.parseInt(e.state.env.get("#")||"0",10);if(n>r){let o=`bash: shift: shift count out of range
|
|
672
|
+
`;if(e.state.options.posix)throw new st(1,"",o);return D(o)}if(n===0)return ne;let s=[];for(let o=1;o<=r;o++)s.push(e.state.env.get(String(o))||"");let i=s.slice(n);for(let o=1;o<=r;o++)e.state.env.delete(String(o));for(let o=0;o<i.length;o++)e.state.env.set(String(o+1),i[o]);return e.state.env.set("#",String(i.length)),e.state.env.set("@",i.join(" ")),ne}async function Xo(e,t){let n=t;if(n.length>0&&n[0]==="--"&&(n=n.slice(1)),n.length===0)return L("",`bash: source: filename argument required
|
|
673
|
+
`,2);let r=n[0],s=null,i=null;if(r.includes("/")){let c=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(c),s=c}catch{}}else{let u=(e.state.env.get("PATH")||"").split(":").filter(f=>f);for(let f of u){let d=e.fs.resolvePath(e.state.cwd,`${f}/${r}`);try{if((await e.fs.stat(d)).isDirectory)continue;i=await e.fs.readFile(d),s=d;break}catch{}}if(i===null){let f=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFile(f),s=f}catch{}}}if(i===null)return D(`bash: ${r}: No such file or directory
|
|
674
|
+
`);let o=new Map;if(n.length>1){for(let u=1;u<=9;u++)o.set(String(u),e.state.env.get(String(u)));o.set("#",e.state.env.get("#")),o.set("@",e.state.env.get("@"));let c=n.slice(1);e.state.env.set("#",String(c.length)),e.state.env.set("@",c.join(" "));for(let u=0;u<c.length&&u<9;u++)e.state.env.set(String(u+1),c[u]);for(let u=c.length+1;u<=9;u++)e.state.env.delete(String(u))}let a=e.state.currentSource,l=()=>{if(e.state.sourceDepth--,e.state.currentSource=a,n.length>1)for(let[c,u]of o)u===void 0?e.state.env.delete(c):e.state.env.set(c,u)};if(e.state.sourceDepth++,e.state.sourceDepth>e.limits.maxSourceDepth)throw e.state.sourceDepth--,new x(`source: maximum nesting depth (${e.limits.maxSourceDepth}) exceeded, increase executionLimits.maxSourceDepth`,"recursion");e.state.currentSource=r;try{let c=Ge(i),u=await e.executeScript(c);return l(),u}catch(c){if(l(),c instanceof j)throw c;if(c instanceof _e)return L(c.stdout,c.stderr,c.exitCode);if(c.name==="ParseException")return D(`bash: ${r}: ${c.message}
|
|
675
|
+
`);throw c}}function ju(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function em(e){return e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"')}async function Gu(e,t){if(em(t))return null;try{let n=new H,r=re(n,t);return await Y(e,r.expression)}catch{let n=parseInt(t,10);return Number.isNaN(n)?0:n}}function Zu(e,t){if(e.state.localVarStack?.has(t)){let r=ks(e,t);if(r){r.value===void 0?e.state.env.delete(t):e.state.env.set(t,r.value);let s=e.state.localVarStack?.get(t);if(!s||s.length===0)vs(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,r.scopeIndex),Yo(e,t);else{let i=s[s.length-1];e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,i.scopeIndex+1)}return!0}return e.state.env.delete(t),vs(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,0),!0}for(let r=e.state.localScopes.length-1;r>=0;r--){let s=e.state.localScopes[r];if(s.has(t)){let i=s.get(t);i===void 0?e.state.env.delete(t):e.state.env.set(t,i),s.delete(t);let o=!1;for(let a=r-1;a>=0;a--)if(e.state.localScopes[a].has(t)){e.state.localVarDepth&&e.state.localVarDepth.set(t,a+1),o=!0;break}return o||vs(e,t),!0}}return!1}function Yo(e,t){if(!e.state.tempEnvBindings||e.state.tempEnvBindings.length===0)return!1;for(let n=e.state.tempEnvBindings.length-1;n>=0;n--){let r=e.state.tempEnvBindings[n];if(r.has(t)){let s=r.get(t);return s===void 0?e.state.env.delete(t):e.state.env.set(t,s),r.delete(t),!0}}return!1}async function Hu(e,t){if(t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t.startsWith('"')&&t.endsWith('"')){let n=t.slice(1,-1),s=new H().parseWordFromString(n,!0,!1);return se(e,s)}if(t.includes("$")){let r=new H().parseWordFromString(t,!1,!1);return se(e,r)}return t}async function Jo(e,t){let n="both",r="",s=0;for(let i of t){if(i==="-v"){n="variable";continue}if(i==="-f"){n="function";continue}if(n==="function"){e.state.functions.delete(i);continue}if(n==="variable"){let c=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(c){let d=c[1],p=c[2];if(Be(e,d)){r+=`bash: unset: ${d}: cannot unset: readonly variable
|
|
676
|
+
`,s=1;continue}if(p==="@"||p==="*"){sr(e,d),e.state.env.delete(d);continue}let h=e.state.associativeArrays?.has(d);if(h){let y=await Hu(e,p);pn(e,d,y);continue}let m=pt(e,d),E=e.state.declaredVars?.has(d);if((e.state.env.has(d)||E)&&!m&&!h){r+=`bash: unset: ${d}: not an array variable
|
|
677
|
+
`,s=1;continue}let g=await Gu(e,p);if(g===null&&m){r+=`bash: unset: ${p}: not a valid identifier
|
|
678
|
+
`,s=1;continue}if(g===null)continue;if(g<0){let y=Q(e,d),S=y.length,v=e.state.currentLine;if(S===0){r+=`bash: line ${v}: unset: [${g}]: bad array subscript
|
|
679
|
+
`,s=1;continue}let k=S+g;if(k<0){r+=`bash: line ${v}: unset: [${g}]: bad array subscript
|
|
680
|
+
`,s=1;continue}let A=y[k][0];pn(e,d,A);continue}pn(e,d,g);continue}if(!ju(i)){r+=`bash: unset: \`${i}': not a valid identifier
|
|
681
|
+
`,s=1;continue}let u=i;if(ue(e,i)){let d=Fe(e,i);d&&d!==i&&(u=d)}if(Be(e,u)){r+=`bash: unset: ${u}: cannot unset: readonly variable
|
|
682
|
+
`,s=1;continue}sr(e,u);let f=to(e,u);if(f!==void 0&&f!==e.state.callDepth)Zu(e,u);else if(e.state.fullyUnsetLocals?.has(u))e.state.env.delete(u);else if(f!==void 0){let d=e.state.accessedTempEnvVars?.has(u),p=e.state.mutatedTempEnvVars?.has(u);if((d||p)&&e.state.localVarStack?.has(u)){let h=ks(e,u);h?h.value===void 0?e.state.env.delete(u):e.state.env.set(u,h.value):e.state.env.delete(u)}else e.state.env.delete(u)}else Yo(e,u)||e.state.env.delete(u);e.state.exportedVars?.delete(u);continue}let o=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(o){let c=o[1],u=o[2];if(Be(e,c)){r+=`bash: unset: ${c}: cannot unset: readonly variable
|
|
683
|
+
`,s=1;continue}if(u==="@"||u==="*"){sr(e,c),e.state.env.delete(c);continue}let f=e.state.associativeArrays?.has(c);if(f){let m=await Hu(e,u);pn(e,c,m);continue}let d=pt(e,c);if(e.state.env.has(c)&&!d&&!f){r+=`bash: unset: ${c}: not an array variable
|
|
684
|
+
`,s=1;continue}let h=await Gu(e,u);if(h===null&&d){r+=`bash: unset: ${u}: not a valid identifier
|
|
685
|
+
`,s=1;continue}if(h===null)continue;if(h<0){let m=Q(e,c),E=m.length,b=e.state.currentLine;if(E===0){r+=`bash: line ${b}: unset: [${h}]: bad array subscript
|
|
686
|
+
`,s=1;continue}let g=E+h;if(g<0){r+=`bash: line ${b}: unset: [${h}]: bad array subscript
|
|
687
|
+
`,s=1;continue}let y=m[g][0];pn(e,c,y);continue}pn(e,c,h);continue}if(!ju(i)){r+=`bash: unset: \`${i}': not a valid identifier
|
|
688
|
+
`,s=1;continue}let a=i;if(ue(e,i)){let c=Fe(e,i);c&&c!==i&&(a=c)}if(Be(e,a)){r+=`bash: unset: ${a}: cannot unset: readonly variable
|
|
689
|
+
`,s=1;continue}sr(e,a);let l=to(e,a);if(l!==void 0&&l!==e.state.callDepth)Zu(e,a);else if(e.state.fullyUnsetLocals?.has(a))e.state.env.delete(a);else if(l!==void 0){let c=e.state.accessedTempEnvVars?.has(a),u=e.state.mutatedTempEnvVars?.has(a);if((c||u)&&e.state.localVarStack?.has(a)){let f=ks(e,a);f?f.value===void 0?e.state.env.delete(a):e.state.env.set(a,f.value):e.state.env.delete(a)}else e.state.env.delete(a)}else Yo(e,a)||e.state.env.delete(a);e.state.exportedVars?.delete(a),e.state.functions.delete(i)}return L("",r,s)}function Pt(e,t,n,r){let s=n+B(t)+1;if(s>r)throw new x(`shopt: output size limit exceeded (${r} bytes)`,"output_size");return e.push(t),s}var ea=["extglob","dotglob","nullglob","failglob","globstar","globskipdots","nocaseglob","nocasematch","expand_aliases","lastpipe","xpg_echo"],tm=["autocd","cdable_vars","cdspell","checkhash","checkjobs","checkwinsize","cmdhist","compat31","compat32","compat40","compat41","compat42","compat43","compat44","complete_fullquote","direxpand","dirspell","execfail","extdebug","extquote","force_fignore","globasciiranges","gnu_errfmt","histappend","histreedit","histverify","hostcomplete","huponexit","inherit_errexit","interactive_comments","lithist","localvar_inherit","localvar_unset","login_shell","mailwarn","no_empty_cmd_completion","progcomp","progcomp_alias","promptvars","restricted_shell","shift_verbose","sourcepath"];function Ls(e){return ea.includes(e)}function nm(e){return tm.includes(e)}function Qu(e,t){let n=e.limits.maxArrayElements;if(t.length>n)throw new x(`shopt: argument limit exceeded (${n})`,"array_elements");let r=Math.min(e.limits.maxOutputSize,e.limits.maxStringLength),s=!1,i=!1,o=!1,a=!1,l=!1,c=[],u=0;for(;u<t.length;){let E=t[u];if(E==="--"){u++;break}if(E.startsWith("-")&&E.length>1){for(let b=1;b<E.length;b++){let g=E[b];switch(g){case"s":s=!0;break;case"u":i=!0;break;case"p":o=!0;break;case"q":a=!0;break;case"o":l=!0;break;default:return{exitCode:2,stdout:"",stderr:`shopt: -${g}: invalid option
|
|
690
|
+
`}}}u++}else break}for(;u<t.length;)c.push(t[u]),u++;if(l)return rm(e,c,s,i,o,a);if(s&&i)return{exitCode:1,stdout:"",stderr:`shopt: cannot set and unset shell options simultaneously
|
|
691
|
+
`};if(c.length===0){if(s||i){let b=[];for(let g of ea){let y=e.state.shoptOptions[g];s&&y?b.push(o?`shopt -s ${g}`:`${g} on`):i&&!y&&b.push(o?`shopt -u ${g}`:`${g} off`)}return{exitCode:0,stdout:b.length>0?`${b.join(`
|
|
656
692
|
`)}
|
|
657
|
-
`:"",stderr:""}}let E=[];for(let b of
|
|
693
|
+
`:"",stderr:""}}let E=[];for(let b of ea){let g=e.state.shoptOptions[b];E.push(o?`shopt ${g?"-s":"-u"} ${b}`:`${b} ${g?"on":"off"}`)}return{exitCode:0,stdout:`${E.join(`
|
|
658
694
|
`)}
|
|
659
|
-
`,stderr:""}}let f=!1,d=[],
|
|
695
|
+
`,stderr:""}}let f=!1,d=[],p=0,h=[],m=0;for(let E of c){if(!Ls(E)&&!nm(E)){p=Pt(d,`shopt: ${E}: invalid shell option name`,p,r),f=!0;continue}if(s)Ls(E)&&(e.state.shoptOptions[E]=!0,oi(e));else if(i)Ls(E)&&(e.state.shoptOptions[E]=!1,oi(e));else if(Ls(E)){let b=e.state.shoptOptions[E];a?b||(f=!0):o?(m=Pt(h,`shopt ${b?"-s":"-u"} ${E}`,m,r),b||(f=!0)):(m=Pt(h,`${E} ${b?"on":"off"}`,m,r),b||(f=!0))}else a?f=!0:o?(m=Pt(h,`shopt -u ${E}`,m,r),f=!0):(m=Pt(h,`${E} off`,m,r),f=!0)}return{exitCode:f?1:0,stdout:h.length>0?`${h.join(`
|
|
660
696
|
`)}
|
|
661
697
|
`:"",stderr:d.length>0?`${d.join(`
|
|
662
698
|
`)}
|
|
663
|
-
`:""}}function
|
|
699
|
+
`:""}}function rm(e,t,n,r,s,i){let o=Math.min(e.limits.maxOutputSize,e.limits.maxStringLength),a=new Map([["errexit","errexit"],["pipefail","pipefail"],["nounset","nounset"],["xtrace","xtrace"],["verbose","verbose"],["posix","posix"],["allexport","allexport"],["noclobber","noclobber"],["noglob","noglob"],["noexec","noexec"],["vi","vi"],["emacs","emacs"]]),l=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"],c=[...a.keys(),...l].sort();if(t.length===0){let m=[];for(let E of c){let b=l.includes(E),g=a.get(E),y=b||!g?!1:e.state.options[g];n&&!y||r&&y||m.push(s?`set ${y?"-o":"+o"} ${E}`:`${E} ${y?"on":"off"}`)}return{exitCode:0,stdout:m.length>0?`${m.join(`
|
|
664
700
|
`)}
|
|
665
|
-
`:"",stderr:""}}let u=!1,f=[],d=0,
|
|
701
|
+
`:"",stderr:""}}let u=!1,f=[],d=0,p=[],h=0;for(let m of t){let E=a.has(m),b=l.includes(m);if(!E&&!b){d=Pt(f,`shopt: ${m}: invalid option name`,d,o),u=!0;continue}if(b){n||r||(i?u=!0:s?(h=Pt(p,`set +o ${m}`,h,o),u=!0):(h=Pt(p,`${m} off`,h,o),u=!0));continue}let g=a.get(m);if(g)if(n)g==="vi"?e.state.options.emacs=!1:g==="emacs"&&(e.state.options.vi=!1),e.state.options[g]=!0,Rn(e);else if(r)e.state.options[g]=!1,Rn(e);else{let y=e.state.options[g];i?y||(u=!0):s?(h=Pt(p,`set ${y?"-o":"+o"} ${m}`,h,o),y||(u=!0)):(h=Pt(p,`${m} ${y?"on":"off"}`,h,o),y||(u=!0))}}return{exitCode:u?1:0,stdout:p.length>0?`${p.join(`
|
|
666
702
|
`)}
|
|
667
703
|
`:"",stderr:f.length>0?`${f.join(`
|
|
668
704
|
`)}
|
|
669
|
-
`:""}}function
|
|
670
|
-
`,t||
|
|
671
|
-
`),s=e.includes(" "),i=e.includes("\\"),
|
|
672
|
-
`?l+="\\n":c===" "?l+="\\t":c==="\\"?l+="\\\\":c==="'"?l+="'":c==='"'?l+='"':u<32||u===127?u<256?l+=`\\x${u.toString(16).padStart(2,"0")}`:l+=`\\u${u.toString(16).padStart(4,"0")}`:l+=c}return`$'${l}'`}return
|
|
673
|
-
`}async function
|
|
674
|
-
`:""}function
|
|
675
|
-
`,1)};let l=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(l){let u=await
|
|
676
|
-
`,1)};if(
|
|
677
|
-
`,1)}}if(
|
|
678
|
-
`,{continueToNext:!0,xtraceOutput:
|
|
679
|
-
`)}}async function
|
|
680
|
-
`,1)};
|
|
681
|
-
`;if(i.fatal)throw new
|
|
682
|
-
`,1)}}Number.isNaN(s)&&(s=0)}if(s<0){let i=
|
|
683
|
-
`,1)}}if(s=Math.max(...i.map(([
|
|
684
|
-
`,1)}}}return{index:s}}async function
|
|
685
|
-
`,1)};if(f===null)return{continueToNext:!0,xtraceOutput:""};
|
|
686
|
-
`,{continueToNext:!0,xtraceOutput:
|
|
687
|
-
`;
|
|
688
|
-
`,
|
|
689
|
-
`;else{let
|
|
690
|
-
`;u+=
|
|
705
|
+
`:""}}function Ms(e,t){return e===`/bin/${t}`||e===`/usr/bin/${t}`}async function Ku(e,t,n){if(t.includes("/")){let o=e.fs.resolvePath(e.state.cwd,t);if(!await e.fs.exists(o))return{error:"not_found",path:o};try{let a=await e.fs.stat(o);if(a.isDirectory)return{error:"permission_denied",path:o};let l=o.split("/").pop()||t,c=e.commands.get(l);return c&&Ms(o,l)?{cmd:c,path:o}:(a.mode&73)!==0?{script:!0,path:o}:{error:"permission_denied",path:o}}catch{return{error:"not_found",path:o}}}if(!n&&e.state.hashTable){let o=e.state.hashTable.get(t);if(o){try{let a=await e.fs.stat(o);if(!a.isDirectory){let l=e.commands.get(t);if(l&&Ms(o,t))return{cmd:l,path:o};if((a.mode&73)!==0)return{script:!0,path:o}}}catch{}e.state.hashTable.delete(t)}}let s=(n??e.state.env.get("PATH")??"/usr/bin:/bin").split(":");for(let o of s){if(!o)continue;let l=`${o.startsWith("/")?o:e.fs.resolvePath(e.state.cwd,o)}/${t}`;if(await e.fs.exists(l))try{let c=await e.fs.stat(l);if(c.isDirectory)continue;let u=(c.mode&73)!==0,f=e.commands.get(t),d=Ms(l,t);if(f&&d)return{cmd:f,path:l};if(u){if(f&&!d)return{script:!0,path:l};if(!f)return{script:!0,path:l}}}catch{}}if(!await e.fs.exists("/usr/bin")){let o=e.commands.get(t);if(o)return{cmd:o,path:`/usr/bin/${t}`}}return null}async function Fs(e,t){let n=[];if(t.includes("/")){let i=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(i))try{let o=await e.fs.stat(i);o.isDirectory||(o.mode&73)!==0&&n.push(t)}catch{}return n}let s=(e.state.env.get("PATH")||"/usr/bin:/bin").split(":");for(let i of s){if(!i)continue;let a=`${i.startsWith("/")?i:e.fs.resolvePath(e.state.cwd,i)}/${t}`;if(Ms(a,t)&&e.commands.has(t)){n.push(a);continue}if(await e.fs.exists(a)){try{let l=await e.fs.stat(a);if(l.isDirectory||(l.mode&73)===0)continue}catch{continue}n.push(i.startsWith("/")?a:`${i}/${t}`)}}return n}function sm(e){return e!==null&&typeof e=="object"&&"then"in e&&typeof e.then=="function"}function me(e,t,n,r){return((...s)=>{tr(t,n,`${r} call`);let i=e(...s);return sm(i)?i.then(o=>(tr(t,n,`${r} post-await`),o),o=>{throw tr(t,n,`${r} post-await`),o}):(tr(t,n,`${r} return`),i)})}function im(e,t,n){let r={readFile:me(e.readFile.bind(e),t,n,"fs.readFile"),...typeof e.readFileBytes=="function"?{readFileBytes:me(e.readFileBytes.bind(e),t,n,"fs.readFileBytes")}:Object.create(null),readFileBuffer:me(e.readFileBuffer.bind(e),t,n,"fs.readFileBuffer"),writeFile:me(e.writeFile.bind(e),t,n,"fs.writeFile"),appendFile:me(e.appendFile.bind(e),t,n,"fs.appendFile"),exists:me(e.exists.bind(e),t,n,"fs.exists"),stat:me(e.stat.bind(e),t,n,"fs.stat"),mkdir:me(e.mkdir.bind(e),t,n,"fs.mkdir"),readdir:me(e.readdir.bind(e),t,n,"fs.readdir"),rm:me(e.rm.bind(e),t,n,"fs.rm"),cp:me(e.cp.bind(e),t,n,"fs.cp"),mv:me(e.mv.bind(e),t,n,"fs.mv"),resolvePath:me(e.resolvePath.bind(e),t,n,"fs.resolvePath"),getAllPaths:me(e.getAllPaths.bind(e),t,n,"fs.getAllPaths"),chmod:me(e.chmod.bind(e),t,n,"fs.chmod"),symlink:me(e.symlink.bind(e),t,n,"fs.symlink"),link:me(e.link.bind(e),t,n,"fs.link"),readlink:me(e.readlink.bind(e),t,n,"fs.readlink"),lstat:me(e.lstat.bind(e),t,n,"fs.lstat"),realpath:me(e.realpath.bind(e),t,n,"fs.realpath"),utimes:me(e.utimes.bind(e),t,n,"fs.utimes")};return e.readdirWithFileTypes&&(r.readdirWithFileTypes=me(e.readdirWithFileTypes.bind(e),t,n,"fs.readdirWithFileTypes")),r}function Xu(e,t){if(!e.requireDefenseContext)return e;let n=`command:${t}`,r=Object.getOwnPropertyDescriptors(e);r.fs={value:im(e.fs,e.requireDefenseContext,n),enumerable:!0,configurable:!0,writable:!0};let s=Object.defineProperties(Object.create(Object.getPrototypeOf(e)),r);return e.exec&&(s.exec=me(e.exec,e.requireDefenseContext,n,"exec")),e.fetch&&(s.fetch=me(e.fetch,e.requireDefenseContext,n,"fetch")),e.sleep&&(s.sleep=me(e.sleep,e.requireDefenseContext,n,"sleep")),e.getRegisteredCommands&&(s.getRegisteredCommands=me(e.getRegisteredCommands,e.requireDefenseContext,n,"getRegisteredCommands")),s}var Yu="+ ";async function Ju(e){let t=e.state.env.get("PS4");if(t===void 0)return Yu;if(t==="")return"";let n=e.state.options.xtrace;e.state.options.xtrace=!1;try{let s=new H().parseWordFromString(t,!1,!1);return await se(e,s)}catch(r){if(r instanceof ce&&!r.fatal)return t;if(r instanceof kn||r instanceof Error&&r.name==="AbortError")throw r;return e.state.expansionStderr=`${e.state.expansionStderr||""}bash: ${t}: bad substitution
|
|
706
|
+
`,t||Yu}finally{e.state.options.xtrace=n}}function om(e){return e.map(t=>am(t)).join(" ")}function am(e){if(e==="")return"''";if(!/[\s'"\\$`!*?[\]{}|&;<>()~#\n\t]/.test(e))return e;let n=/[\x00-\x1f\x7f]/.test(e),r=e.includes(`
|
|
707
|
+
`),s=e.includes(" "),i=e.includes("\\"),o=e.includes("'");if(n||r||s||i){let l="";for(let c of e){let u=c.charCodeAt(0);c===`
|
|
708
|
+
`?l+="\\n":c===" "?l+="\\t":c==="\\"?l+="\\\\":c==="'"?l+="'":c==='"'?l+='"':u<32||u===127?u<256?l+=`\\x${u.toString(16).padStart(2,"0")}`:l+=`\\u${u.toString(16).padStart(4,"0")}`:l+=c}return`$'${l}'`}return o?`"${e.replace(/([\\$`"])/g,"\\$1")}"`:`'${e}'`}async function ef(e,t,n){if(!e.state.options.xtrace)return"";let r=await Ju(e),s=[t,...n],i=om(s);return`${r}${i}
|
|
709
|
+
`}async function tf(e,t,n){return e.state.options.xtrace?`${await Ju(e)}${t}=${n}
|
|
710
|
+
`:""}function Bs(e,t,n){return Ft([t,n],"",e.limits.maxStringLength,"array assignment")}async function nf(e,t){let n=new Map,r="";for(let s of t.assignments){let i=s.name;if(s.array){let u=await lm(e,t,i,s.array,s.append,n);if(u.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:u.error};if(r+=u.xtraceOutput,u.continueToNext)continue}let o=s.value?await se(e,s.value):"";if(i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:L("",`bash: ${i}: bad array subscript
|
|
711
|
+
`,1)};let l=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(l){let u=await pm(e,t,l[1],l[2],o,s.append,n);if(u.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:u.error};if(u.continueToNext)continue}let c=await hm(e,t,i,o,s.append,n);if(c.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:n,error:c.error};r+=c.xtraceOutput,c.continueToNext}return{continueToNext:!1,xtraceOutput:r,tempAssignments:n}}async function lm(e,t,n,r,s,i){let o="";if(/\[.+\]$/.test(n))return{continueToNext:!1,xtraceOutput:"",error:L("",`bash: ${n}: cannot assign list to array member
|
|
712
|
+
`,1)};if(ue(e,n)){let h=En(e,n);if(h===void 0||h==="")throw new j(1,"","");let m=Fe(e,n);if(m&&/^[a-zA-Z_][a-zA-Z0-9_]*\[@\]$/.test(m))return{continueToNext:!1,xtraceOutput:"",error:L("",`bash: ${n}: cannot assign list to array member
|
|
713
|
+
`,1)}}if(Be(e,n)){if(t.name)return o+=`bash: ${n}: readonly variable
|
|
714
|
+
`,{continueToNext:!0,xtraceOutput:o};let h=fe(e,n);if(h)return{continueToNext:!1,xtraceOutput:"",error:h}}let a=e.state.associativeArrays?.has(n),l=Pe(e,n),c=l?Me(l):void 0,u=e.state.env.get(n),f=()=>{e.state.arrays??=new Map,c?e.state.arrays.set(n,c):e.state.arrays.delete(n),u===void 0?e.state.env.delete(n):e.state.env.set(n,u)},d=cm(r),p=()=>{Ee(e,n),e.state.env.delete(n)};try{a&&d?await um(e,t,n,r,s,p,h=>{o+=h}):d?await fm(e,n,r,s,p):await dm(e,n,r,s,p)}catch(h){throw f(),h}if(t.name){i.set(n,e.state.env.get(n));let m=`(${r.map(E=>Nn(E)).join(" ")})`;e.state.env.set(n,m)}return{continueToNext:!0,xtraceOutput:o}}function cm(e){return e.some(t=>{if(t.parts.length>=2){let n=t.parts[0],r=t.parts[1];if(n.type!=="Glob"||!n.pattern.startsWith("["))return!1;if(n.pattern==="["&&(r.type==="DoubleQuoted"||r.type==="SingleQuoted")){if(t.parts.length<3)return!1;let s=t.parts[2];return s.type!=="Literal"?!1:s.value.startsWith("]=")||s.value.startsWith("]+=")}return r.type!=="Literal"?!1:r.value.startsWith("]")?r.value.startsWith("]=")||r.value.startsWith("]+="):n.pattern.endsWith("]")?r.value.startsWith("=")||r.value.startsWith("+="):!1}return!1})}async function um(e,t,n,r,s,i,o){let a=[];for(let l of r){if(a.length>=e.limits.maxArrayElements)throw new x(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let c=ri(l);if(c){let{key:u,valueParts:f,append:d}=c,p;f.length>0?(p=await se(e,{type:"Word",parts:f}),f.every(m=>m.type==="Literal"||m.type==="TildeExpansion")&&(p=Qt(e,p))):p="",a.push({type:"keyed",key:u,value:p,append:d})}else{let u=await se(e,l);a.push({type:"invalid",expandedValue:u})}}e.executionScope.consumeWork(a.length,"associative array assignment"),s||i();for(let l of a)if(l.type==="keyed")if(l.append){let c=le(e,n,l.key)??"";G(e,n,l.key,Bs(e,c,l.value),"associative")}else G(e,n,l.key,l.value,"associative");else{let c=t.line??e.state.currentLine??1;o(`bash: line ${c}: ${n}: ${l.expandedValue}: must use subscript when assigning associative array
|
|
715
|
+
`)}}async function fm(e,t,n,r,s){let i=[],o=0;for(let l of n){let c=ri(l);if(c){if(o>=e.limits.maxArrayElements)throw new x(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");let{key:u,valueParts:f,append:d}=c,p;f.length>0?(p=await se(e,{type:"Word",parts:f}),f.every(m=>m.type==="Literal"||m.type==="TildeExpansion")&&(p=Qt(e,p))):p="",i.push({type:"keyed",indexExpr:u,value:p,append:d}),o++}else{let u=await gt(e,l);if(u.values.length>e.limits.maxArrayElements-o)throw new x(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");i.push({type:"non-keyed",values:u.values}),o+=u.values.length}}e.executionScope.consumeWork(o,"indexed array assignment"),r||s();let a=0;for(let l of i)if(l.type==="keyed"){let c;try{let u=new H,f=re(u,l.indexExpr);c=await Y(e,f.expression,!1)}catch{if(/^-?\d+$/.test(l.indexExpr))c=Number.parseInt(l.indexExpr,10);else{let u=e.state.env.get(l.indexExpr);c=u?Number.parseInt(u,10):0,Number.isNaN(c)&&(c=0)}}if(l.append){let u=le(e,t,c)??"";G(e,t,c,Bs(e,u,l.value))}else G(e,t,c,l.value);a=c+1}else for(let c of l.values)G(e,t,a++,c)}async function dm(e,t,n,r,s){let i=[];for(let a of n){let l=await gt(e,a);for(let c of l.values){if(i.length>=e.limits.maxArrayElements)throw new x(`array element limit exceeded (${e.limits.maxArrayElements})`,"array_elements");i.push(c)}}let o=0;if(e.executionScope.consumeWork(i.length,"indexed array assignment"),r){let a=Q(e,t);if(a.length>0)o=Math.max(...a.map(([c])=>typeof c=="number"?c:0))+1;else{let l=e.state.env.get(t);l!==void 0&&(G(e,t,0,l),e.state.env.delete(t),o=1)}}else s();for(let a=0;a<i.length;a++)G(e,t,o+a,i[a])}async function pm(e,t,n,r,s,i,o){let a=n;if(ue(e,n)){let f=Fe(e,n);if(f&&f!==n){if(f.includes("["))return{continueToNext:!1,xtraceOutput:"",error:L("",`bash: \`${f}': not a valid identifier
|
|
716
|
+
`,1)};a=f}}if(Be(e,a)){if(t.name)return{continueToNext:!0,xtraceOutput:""};let f=fe(e,a);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let l=e.state.associativeArrays?.has(a),c;if(l)c=await rf(e,r);else{let f=await ta(e,a,r);if(f.error)return{continueToNext:!1,xtraceOutput:"",error:f.error};c=String(f.index)}let u=i?Bs(e,le(e,a,c)||"",s):s;return t.name||G(e,a,c,u,l?"associative":"indexed"),{continueToNext:!0,xtraceOutput:""}}async function rf(e,t){let n;if(t.startsWith("'")&&t.endsWith("'"))n=t.slice(1,-1);else if(t.startsWith('"')&&t.endsWith('"')){let r=t.slice(1,-1),i=new H().parseWordFromString(r,!0,!1);n=await se(e,i)}else if(t.includes("$")){let s=new H().parseWordFromString(t,!1,!1);n=await se(e,s)}else n=t;return n}async function ta(e,t,n){let r=n;n.startsWith('"')&&n.endsWith('"')&&n.length>=2&&(r=n.slice(1,-1));let s;if(/^-?\d+$/.test(r))s=Number.parseInt(r,10);else{try{let i=new H,o=re(i,r);s=await Y(e,o.expression,!1)}catch(i){if(i instanceof j)throw i;if(i instanceof ce){let l=`bash: line ${e.state.currentLine}: ${n}: ${i.message}
|
|
717
|
+
`;if(i.fatal)throw new j(1,"",l);return{index:0,error:L("",l,1)}}let o=e.state.currentLine;return{index:0,error:L("",`bash: line ${o}: ${t}[${n}]: bad array subscript
|
|
718
|
+
`,1)}}Number.isNaN(s)&&(s=0)}if(s<0){let i=Q(e,t);if(i.length===0){let a=e.state.currentLine;return{index:0,error:L("",`bash: line ${a}: ${t}[${n}]: bad array subscript
|
|
719
|
+
`,1)}}if(s=Math.max(...i.map(([a])=>typeof a=="number"?a:0))+1+s,s<0){let a=e.state.currentLine;return{index:0,error:L("",`bash: line ${a}: ${t}[${n}]: bad array subscript
|
|
720
|
+
`,1)}}}return{index:s}}async function hm(e,t,n,r,s,i){let o="",a=n,l=null;if(ue(e,n)){let f=Yr(e,n,r);if(f===void 0)return{continueToNext:!1,xtraceOutput:"",error:L("",`bash: ${n}: circular name reference
|
|
721
|
+
`,1)};if(f===null)return{continueToNext:!0,xtraceOutput:""};a=f;let d=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);d&&(l={arrayName:d[1],subscriptExpr:d[2]},a=d[1])}if(Be(e,a)){if(t.name)return o+=`bash: ${a}: readonly variable
|
|
722
|
+
`,{continueToNext:!0,xtraceOutput:o};let f=fe(e,a);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let c;if(Er(e,a))try{let f=new H;if(s){let p=`(${e.state.env.get(a)||"0"}) + (${r})`,h=re(f,p);c=String(await Y(e,h.expression))}else{let d=re(f,r);c=String(await Y(e,d.expression))}}catch{c="0"}else{let f=pt(e,a)?le(e,a,0):e.state.env.get(a);c=s?Bs(e,f||"",r):r}c=qn(e,a,c),o+=await tf(e,a,c);let u;return l?u=await mm(e,l):pt(e,a)&&(u="0"),t.name?u===void 0&&(i.set(a,e.state.env.get(a)),e.state.env.set(a,c)):(u===void 0?e.state.env.set(a,c):G(e,a,u,c),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(a)),e.state.tempEnvBindings?.some(f=>f.has(a))&&(e.state.mutatedTempEnvVars=e.state.mutatedTempEnvVars||new Set,e.state.mutatedTempEnvVars.add(a))),{continueToNext:!1,xtraceOutput:o}}async function mm(e,t){let{arrayName:n,subscriptExpr:r}=t;if(e.state.associativeArrays?.has(n))return rf(e,r);let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{let o=new H,a=re(o,r);i=await Y(e,a.expression,!1)}catch{let o=e.state.env.get(r);i=o?Number.parseInt(o,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let o=Q(e,n);o.length>0&&(i=Math.max(...o.map(l=>l[0]))+1+i)}return String(i)}async function af(e,t,n,r){let s=!1,i=!1,o=!1,a=!1,l=!1,c=[];for(let m of t)if(m.startsWith("-")&&m.length>1)for(let E of m.slice(1))E==="t"?s=!0:E==="p"?i=!0:E==="P"?o=!0:E==="a"?a=!0:E==="f"&&(l=!0);else c.push(m);let u="",f="",d=0,p=!1,h=!1;for(let m of c){let E=!1;if(o){if(a){let k=await r(m);if(k.length>0){for(let A of k)u+=`${A}
|
|
723
|
+
`;p=!0,E=!0}}else{let k=await n(m);k&&(u+=`${k}
|
|
724
|
+
`,p=!0,E=!0)}E||(h=!0);continue}let b=!l&&e.state.functions.has(m);if(a&&b){if(!i)if(s)u+=`function
|
|
725
|
+
`;else{let k=e.state.functions.get(m),A=k?sf(m,k):`${m} is a function
|
|
726
|
+
`;u+=A}E=!0}let g=e.state.env.get(`BASH_ALIAS_${m}`);if(g!==void 0&&(a||!E)&&(i||(s?u+=`alias
|
|
691
727
|
`:u+=`${m} is aliased to \`${g}'
|
|
692
|
-
`),E=!0,!
|
|
728
|
+
`),E=!0,!a)||ro.has(m)&&(a||!E)&&(i||(s?u+=`keyword
|
|
693
729
|
`:u+=`${m} is a shell keyword
|
|
694
|
-
`),E=!0,!
|
|
695
|
-
`;else{let
|
|
696
|
-
`;u+=
|
|
730
|
+
`),E=!0,!a))continue;if(!a&&b&&!E){if(!i)if(s)u+=`function
|
|
731
|
+
`;else{let k=e.state.functions.get(m),A=k?sf(m,k):`${m} is a function
|
|
732
|
+
`;u+=A}E=!0;continue}if(!(Fn.has(m)&&(a||!E)&&(i||(s?u+=`builtin
|
|
697
733
|
`:u+=`${m} is a shell builtin
|
|
698
|
-
`),E=!0,!
|
|
734
|
+
`),E=!0,!a))){if(a){let k=await r(m);for(let A of k)i?u+=`${A}
|
|
699
735
|
`:s?u+=`file
|
|
700
|
-
`:u+=`${m} is ${
|
|
701
|
-
`,
|
|
736
|
+
`:u+=`${m} is ${A}
|
|
737
|
+
`,p=!0,E=!0}else if(!E){let k=await n(m);k&&(i?u+=`${k}
|
|
702
738
|
`:s?u+=`file
|
|
703
|
-
`:u+=`${m} is ${
|
|
704
|
-
`,
|
|
705
|
-
`)}}}return i?d=p
|
|
739
|
+
`:u+=`${m} is ${k}
|
|
740
|
+
`,p=!0,E=!0)}if(!E&&(h=!0,!s&&!i)){let k=!0;if(m.includes("/")){let A=e.fs.resolvePath(e.state.cwd,m);await e.fs.exists(A)&&(k=!1)}k&&(f+=`bash: type: ${m}: not found
|
|
741
|
+
`)}}}return i?d=h&&!p?1:0:d=h?1:0,L(u,f,d)}function sf(e,t){let n;return t.body.type==="Group"?n=t.body.body.map(s=>Ar(s)).join("; "):n=Ar(t.body),`${e} is a function
|
|
706
742
|
${e} ()
|
|
707
743
|
{
|
|
708
744
|
${n}
|
|
709
745
|
}
|
|
710
|
-
`}function
|
|
711
|
-
`:s+=`alias ${
|
|
712
|
-
`;else if(
|
|
713
|
-
`:s+=`${
|
|
714
|
-
`;else if(
|
|
715
|
-
`:s+=`${
|
|
716
|
-
`;else if(e.state.functions.has(
|
|
717
|
-
`:s+=`${
|
|
718
|
-
`;else if(
|
|
719
|
-
`:s+=`${
|
|
720
|
-
`,u=!0)}catch{}u||(r&&(i+=`${
|
|
721
|
-
`),
|
|
746
|
+
`}function Ar(e){if(Array.isArray(e))return e.map(t=>Ar(t)).join("; ");if(e.type==="Statement"){let t=[];for(let n=0;n<e.pipelines.length;n++){let r=e.pipelines[n];t.push(ym(r)),e.operators[n]&&t.push(e.operators[n])}return t.join(" ")}if(e.type==="SimpleCommand"){let t=e,n=[];t.name&&n.push(of(t.name));for(let r of t.args)n.push(of(r));return n.join(" ")}return e.type==="Group"?`{ ${e.body.map(r=>Ar(r)).join("; ")}; }`:"..."}function of(e){return e.parts.map(lf).join("")}function lf(e){switch(e.type){case"Literal":return e.value;case"Escaped":return`\\${e.value}`;case"SingleQuoted":return`'${e.value}'`;case"DoubleQuoted":return`"${e.parts.map(lf).join("")}"`;default:return we(M.word([e]))}}function ym(e){let t=e.commands.map(n=>Ar(n));return(e.negated?"! ":"")+t.join(" | ")}async function cf(e,t,n,r){let s="",i="",o=0;for(let a of t){if(!a){o=1;continue}let l=e.state.env.get(`BASH_ALIAS_${a}`);if(l!==void 0)r?s+=`${a} is an alias for "${l}"
|
|
747
|
+
`:s+=`alias ${a}='${l}'
|
|
748
|
+
`;else if(ro.has(a))r?s+=`${a} is a shell keyword
|
|
749
|
+
`:s+=`${a}
|
|
750
|
+
`;else if(Fn.has(a))r?s+=`${a} is a shell builtin
|
|
751
|
+
`:s+=`${a}
|
|
752
|
+
`;else if(e.state.functions.has(a))r?s+=`${a} is a function
|
|
753
|
+
`:s+=`${a}
|
|
754
|
+
`;else if(a.includes("/")){let c=e.fs.resolvePath(e.state.cwd,a),u=!1;if(await e.fs.exists(c))try{let f=await e.fs.stat(c);f.isDirectory||(f.mode&73)!==0&&(r?s+=`${a} is ${a}
|
|
755
|
+
`:s+=`${a}
|
|
756
|
+
`,u=!0)}catch{}u||(r&&(i+=`${a}: not found
|
|
757
|
+
`),o=1)}else if(e.commands.has(a)){let u=(e.state.env.get("PATH")??"/usr/bin:/bin").split(":"),f=null;for(let d of u){if(!d)continue;let p=`${d}/${a}`;try{let h=await e.fs.stat(p);if(!h.isDirectory&&(h.mode&73)!==0){f=p;break}}catch{}}f||(f=`/usr/bin/${a}`),r?s+=`${a} is ${f}
|
|
722
758
|
`:s+=`${f}
|
|
723
|
-
`}else r&&(i+=`${
|
|
724
|
-
`),
|
|
725
|
-
`)},
|
|
726
|
-
`))}}}async function
|
|
727
|
-
`):new
|
|
728
|
-
`);throw m||s.poisonAfterAbort(E),E}finally{n(),
|
|
729
|
-
`,2);let
|
|
730
|
-
`,2);let
|
|
731
|
-
`,2);
|
|
732
|
-
`);let[,...a]=
|
|
733
|
-
`,127):
|
|
734
|
-
`,127);if("error"in c)return c.error==="permission_denied"?
|
|
735
|
-
`,126):
|
|
736
|
-
`,127);if("script"in c)return t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,c.path)),await
|
|
737
|
-
`)}}async function
|
|
738
|
-
`,exitCode:1}}var
|
|
739
|
-
`),n.build(1)}return n.build(r)}async function
|
|
740
|
-
`);let
|
|
741
|
-
`).map(f=>f.replace(/^\t+/,"")).join(`
|
|
742
|
-
`)),a=u}else if(l.operator==="<<<"&&l.target.type==="Word")a=`${await z(e,l.target)}
|
|
743
|
-
`;else if(l.operator==="<"&&l.target.type==="Word")try{let c=await z(e,l.target),u=e.fs.resolvePath(e.state.cwd,c);a=await e.fs.readFile(u)}catch{let c=await z(e,l.target);return R(`bash: ${c}: No such file or directory
|
|
744
|
-
`)}let o=e.state.groupStdin;a&&(e.state.groupStdin=a),e.state.loopDepth++;try{for(;;){i++,i>e.limits.maxLoopIterations&&Gt(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r.stdout,r.stderr);let l=0,c=!1,u=!1,f=e.state.inCondition;e.state.inCondition=!0;try{for(let d of t.condition){let h=await e.executeStatement(d);r.append(h.stdout,h.stderr),l=h.exitCode}}catch(d){if(d instanceof Ze){if(r.append(d.stdout,d.stderr),d.levels>1&&e.state.loopDepth>1)throw d.levels--,d.stdout=r.stdout,d.stderr=r.stderr,e.state.inCondition=f,d;c=!0}else if(d instanceof He){if(r.append(d.stdout,d.stderr),d.levels>1&&e.state.loopDepth>1)throw d.levels--,d.stdout=r.stdout,d.stderr=r.stderr,e.state.inCondition=f,d;u=!0}else throw e.state.inCondition=f,d}finally{e.state.inCondition=f}if(c)break;if(!u){if(l!==0)break;try{for(let d of t.body){let h=await e.executeStatement(d);r.append(h.stdout,h.stderr),s=h.exitCode}}catch(d){let h=or(d,r.stdout,r.stderr,e.state.loopDepth);if(r.replace(h.stdout,h.stderr),h.action==="break")break;if(h.action==="continue")continue;if(h.action==="error")return r.build(h.exitCode??1);throw h.error}}}}finally{e.state.loopDepth--,e.state.groupStdin=o}return r.build(s)}async function gu(e,t){let n=new Kt(e),r=0,s=0;e.state.loopDepth++;try{for(;;){s++,s>e.limits.maxLoopIterations&&Gt(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n.stdout,n.stderr);let i=await Sa(e,t.condition);if(n.append(i.stdout,i.stderr),i.exitCode===0)break;try{for(let a of t.body){let o=await e.executeStatement(a);n.append(o.stdout,o.stderr),r=o.exitCode}}catch(a){let o=or(a,n.stdout,n.stderr,e.state.loopDepth);if(n.replace(o.stdout,o.stderr),o.action==="break")break;if(o.action==="continue")continue;if(o.action==="error")return n.build(o.exitCode??1);throw o.error}}}finally{e.state.loopDepth--}return n.build(r)}async function wu(e,t){let n=await ft(e,t.redirections);if(n.error)return n.error;let r=new Kt(e),s=0,i=await z(e,t.word),a=!1;for(let l=0;l<t.items.length;l++){let c=t.items[l],u=a;if(!a)for(let f of c.patterns){let d=await z(e,f);nc(f)&&(d=Xe(d));let h=e.state.shoptOptions.nocasematch,p=e.state.shoptOptions.extglob;if(An(i,d,h,p,e.limits.maxCallDepth)){u=!0;break}}if(u){let f=await va(e,c.body,r);if(r.replace(f.stdout,f.stderr),s=f.exitCode,c.terminator===";;")break;c.terminator===";&"?a=!0:a=!1}else a=!1}let o=r.build(s);return me(e,o,t.redirections,n.targets)}function Aa(e,t){if(e.parts.length!==1)return!1;let n=e.parts[0];return n.type!=="Literal"?!1:t.includes(n.value)}function Eu(e){if(!e.startsWith("__rw__:"))return null;let t=e.slice(7),n=t.indexOf(":");if(n===-1)return null;let r=Number.parseInt(t.slice(0,n),10);if(Number.isNaN(r)||r<0)return null;let s=n+1,i=t.slice(s,s+r),a=s+r+1,o=t.slice(a),l=o.indexOf(":");if(l===-1)return null;let c=Number.parseInt(o.slice(0,l),10);if(Number.isNaN(c)||c<0)return null;let u=o.slice(l+1);return{path:i,position:c,content:u}}async function bu(e,t,n){let r=t.timed?Ms():0,s="",i=ne,a=0,o=[],l="",c=0,u=t.commands.length>1,f=e.state.lastArg;for(let E=0;E<t.commands.length;E++){let b=t.commands[E],g=E===t.commands.length-1,w=E===0;u&&(e.state.lastArg="",w||(e.state.groupStdin=void 0));let S=u&&(!g||!e.state.shoptOptions.lastpipe),A=S?new Map(e.state.env):null,v=S?pt(e.state.arrays):null,x,N=e.executionScope.outputBytesUsed;try{e.state.commandCount=e.executionScope.chargeCommand(),x=await n(b,s)}catch(D){if(D instanceof Qe)x={stdout:D.stdout,stderr:D.stderr,exitCode:1};else if(D instanceof H&&t.commands.length>1)x={stdout:D.stdout,stderr:D.stderr,exitCode:D.exitCode};else if(D instanceof et&&t.commands.length>1)x={stdout:D.stdout,stderr:D.stderr,exitCode:D.exitCode};else throw A&&(e.state.env=A,e.state.arrays=v??new Map),D}if(A&&(e.state.env=A,e.state.arrays=v??new Map),x=e.executionScope.accountResult(x,"pipeline",e.executionScope.outputBytesUsed-N),!g){let D=t.pipeStderr?.[E]??!1,O=x.internalOutputAccounting?.stdout??0,_=D?x.internalOutputAccounting?.stderr??0:0;Ka(e.executionScope,O+_,"pipeline"),x={...x,internalOutputAccounting:{stdout:0,stderr:D?0:x.internalOutputAccounting?.stderr??0}}}o.push(x.exitCode),x.exitCode!==0&&(a=x.exitCode),g?i=x:(t.pipeStderr?.[E]??!1?s=Dt(x.stderr)+yr(x):(s=yr(x),l+=x.stderr,c+=x.internalOutputAccounting?.stderr??0),i={stdout:"",stderr:"",exitCode:x.exitCode})}l&&(i={...i,stderr:l+i.stderr,internalOutputAccounting:{stdout:i.internalOutputAccounting?.stdout??0,stderr:c+(i.internalOutputAccounting?.stderr??0)}});let d=t.commands.length>1||t.commands.length===1&&t.commands[0].type==="SimpleCommand",h=i.internalPipeStatusOverride??o;if(d){ge(e,"PIPESTATUS");for(let E=0;E<h.length;E++)q(e,"PIPESTATUS",E,String(h[E]))}if(e.state.options.pipefail&&a!==0&&(i={...i,exitCode:a}),t.negated&&(i={...i,exitCode:i.exitCode===0?1:0}),t.timed){let b=(Ms()-r)/1e3,g=Math.floor(b/60),w=b%60,S;t.timePosix?S=`real ${b.toFixed(2)}
|
|
759
|
+
`}else r&&(i+=`${a}: not found
|
|
760
|
+
`),o=1}return L(s,i,o)}async function uf(e,t){if(t.includes("/")){let s=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(s)){try{let i=await e.fs.stat(s);if(i.isDirectory||!((i.mode&73)!==0))return null}catch{return null}return t}return null}let r=(e.state.env.get("PATH")??"/usr/bin:/bin").split(":");for(let s of r){if(!s)continue;let o=`${s.startsWith("/")?s:e.fs.resolvePath(e.state.cwd,s)}/${t}`;if(await e.fs.exists(o)){try{let a=await e.fs.stat(o);if(a.isDirectory||(a.mode&73)===0)continue}catch{continue}return`${s}/${t}`}}if(e.commands.has(t)){for(let s of r)if(s==="/usr/bin"||s==="/bin")return`${s}/${t}`;return`/usr/bin/${t}`}return null}function gm(e,t){let n=!0,r=e.signal?new AbortController:void 0,s=new WeakMap,i=()=>{if(!n)throw new ze("",`bash: ${t} used its context after cancellation
|
|
761
|
+
`)},o=f=>{if(f===null||typeof f!="object"&&typeof f!="function")return f;let d=s.get(f);if(d!==void 0)return d;if(typeof f=="object"&&ka(f))return f;if(f instanceof Uint8Array){let E=new Uint8Array(f);return s.set(f,E),E}if(f instanceof ArrayBuffer){let E=f.slice(0);return s.set(f,E),E}if(f instanceof Promise){let E=f.then(b=>(i(),o(b)));return s.set(f,E),E}if(typeof f=="function"){let E=function(...b){return i(),o(Reflect.apply(f,this,b))};return s.set(f,E),E}let p=Object.getPrototypeOf(f);if(Array.isArray(f)||p===Object.prototype||p===null){let E=Array.isArray(f)?[]:Object.create(p);s.set(f,E);let b=Object.getOwnPropertyDescriptors(f);for(let g of Object.values(b)){if("value"in g){let y=g.value;g.value=typeof y=="function"?(...S)=>(i(),o(Reflect.apply(y,f,S))):o(y)}if(g.get){let y=g.get;g.get=()=>(i(),o(Reflect.apply(y,f,[])))}if(g.set){let y=g.set;g.set=S=>{i(),Reflect.apply(y,f,[S])}}}return Object.defineProperties(E,b),E}let h=new Map,m=new ma(f,{get(E,b){if(i(),b==="constructor"||b==="prototype"||b==="__proto__")throw new Error(`${t}: unsafe context property access`);let g=Reflect.get(E,b,E);if(typeof g!="function")return o(g);if(h.has(b))return h.get(b);let y=(...S)=>(i(),o(Reflect.apply(g,E,S)));return h.set(b,y),y},set(E,b,g){if(i(),b==="constructor"||b==="prototype"||b==="__proto__")throw new Error(`${t}: unsafe context property access`);return Reflect.set(E,b,g,E)}});return s.set(f,m),m},a=f=>o(f),l=f=>f&&((...d)=>(i(),o(f(...d)))),c=f=>({value:f,enumerable:!0,configurable:!0,writable:!0}),u=Object.getOwnPropertyDescriptors(e);return Object.assign(u,{fs:c(a(e.fs)),env:c(a(e.env)),limits:c(Object.freeze({...e.limits})),exportedEnv:c(e.exportedEnv?Object.freeze({...e.exportedEnv}):void 0),executionScope:c(e.executionScope?a(e.executionScope):void 0),fileDescriptors:c(e.fileDescriptors?a(e.fileDescriptors):void 0),coverage:c(e.coverage?a(e.coverage):void 0),assignShellVariable:c(l(e.assignShellVariable)),exec:c(l(e.exec)),execWithInheritedStdin:c(l(e.execWithInheritedStdin)),fetch:c(l(e.fetch)),getRegisteredCommands:c(l(e.getRegisteredCommands)),sleep:c(l(e.sleep)),trace:c(l(e.trace)),invokeTool:c(l(e.invokeTool)),signal:c(r?.signal)}),{context:Object.defineProperties(Object.create(Object.getPrototypeOf(e)),u),revoke(){n=!1,r?.signal.aborted||r?.abort(new ze("",`bash: ${t} context revoked
|
|
762
|
+
`))}}}async function wm(e,t,n,r,s,i){let o=s.remainingTimeMs()??t.limits.maxExecutionTimeMs,a=t.limits.maxExtensionCleanupTimeMs,l,c,u,d=Promise.resolve().then(e).then(h=>({kind:"result",result:h}),h=>({kind:"error",error:h})),p=new Promise(h=>{let m=()=>{n(),h({kind:"abort"})};c=m,i?.addEventListener("abort",m,{once:!0}),i?.aborted&&m(),l=Yn(()=>{n(),h({kind:"deadline"})},o)});try{let h=await Promise.race([d,p]);if(h.kind==="result")return h.result;if(h.kind==="error")throw h.error;n();let m=await Promise.race([d.then(()=>!0),new Promise(b=>{u=Yn(()=>b(!1),a)})]),E=h.kind==="deadline"?new ze("",`bash: ${r} exceeded its execution deadline
|
|
763
|
+
`):new ze("",`bash: execution aborted
|
|
764
|
+
`);throw m||s.poisonAfterAbort(E),E}finally{n(),Jn(l),Jn(u),c&&i?.removeEventListener("abort",c)}}async function ff(e,t,n,r,s,i,o,a,l=!1){let{ctx:c,runCommand:u}=e;if(c.coverage&&Fn.has(t)&&c.coverage.hit(`bash:builtin:${t}`),t==="export")return Bo(c,n);if(t==="unset")return Jo(c,n);if(t==="exit")return Fo(c,n);if(t==="local")return Uo(c,n);if(t==="set")return Qo(c,n);if(t==="break")return Qi(c,n);if(t==="continue")return xo(c,n);if(t==="return")return Go(c,n);if(t==="eval"&&c.state.options.posix)return Is(c,n,s,l);if(t==="shift")return Ko(c,n);if(t==="getopts")return _s(c,n);if(t==="compgen")return So(c,n);if(t==="complete")return ko(c,n);if(t==="compopt")return Po(c,n);if(t==="pushd")return await To(c,n);if(t==="popd")return Lo(c,n);if(t==="dirs")return Mo(c,n);if(t==="source"||t===".")return Xo(c,n);if(t==="read")return jo(c,n,s,a);if(t==="mapfile"||t==="readarray")return qo(c,n,s);if(t==="declare"||t==="typeset")return Do(c,n);if(t==="readonly")return Io(c,n);if(!i){let f=c.state.functions.get(t);if(f)return Os(c,f,n,s,void 0,l)}if(t==="__just_bash_tee_restore"){if(n.length===0||n.length>c.limits.maxArrayElements)return D(`bash: invalid internal pipeline status restore
|
|
765
|
+
`,2);let f=[];for(let h of n){if(!/^(?:0|[1-9][0-9]{0,2})$/.test(h))return D(`bash: invalid internal pipeline status restore
|
|
766
|
+
`,2);let m=Number(h);if(!Number.isSafeInteger(m)||m>255)return D(`bash: invalid internal pipeline status restore
|
|
767
|
+
`,2);f.push(m)}let d=f[f.length-1]??0,p=[...f].reverse().find(h=>h!==0);return{stdout:"",stderr:"",exitCode:c.state.options.pipefail&&p!==void 0?p:d,internalPipeStatusOverride:f}}if(t==="eval")return Is(c,n,s,l);if(t==="cd")return await Ki(c,n);if(t===":"||t==="true")return ne;if(t==="false")return be(!1);if(t==="let")return zo(c,n);if(t==="command")return Em(e,n,s,l);if(t==="builtin")return bm(e,n,s,l);if(t==="shopt")return Qu(c,n);if(t==="exec"){if(n.length===0)return ne;let[f,...d]=n;return{...await u(f,d,[],s,!1,!1,-1,l),internalProducerOmitsShellPrefix:!0}}if(t==="wait")return ne;if(t==="type")return await af(c,n,f=>uf(c,f),f=>Fs(c,f));if(t==="hash")return Wo(c,n);if(t==="help")return Vo(c,n);if(t==="["||t==="test"){let f=n;if(t==="["){if(n[n.length-1]!=="]")return D("[: missing `]'\n",2);f=n.slice(0,-1)}return mr(c,f)}return null}async function Em(e,t,n,r=!1){let{ctx:s,runCommand:i}=e;if(t.length===0)return ne;let o=!1,a=!1,l=!1,c=t;for(;c.length>0&&c[0].startsWith("-");){let d=c[0];if(d==="--"){c=c.slice(1);break}for(let p of d.slice(1))p==="p"?o=!0:p==="V"?a=!0:p==="v"&&(l=!0);c=c.slice(1)}if(c.length===0)return ne;if(l||a)return await cf(s,c,l,a);let[u,...f]=c;return i(u,f,[],n,!0,o,-1,r)}async function bm(e,t,n,r=!1){let{runCommand:s}=e;if(t.length===0)return ne;let i=t;if(i[0]==="--"&&(i=i.slice(1),i.length===0))return ne;let o=i[0];if(o!=="__just_bash_tee_restore"&&!Fn.has(o))return D(`bash: builtin: ${o}: not a shell builtin
|
|
768
|
+
`);let[,...a]=i;return s(o,a,[],n,!0,!1,-1,r)}async function df(e,t,n,r,s){let{ctx:i,buildExportedEnv:o,executeUserScript:a}=e,c=await Ku(i,t,s?"/usr/bin:/bin":void 0);if(!c)return nu(t)?D(`bash: ${t}: command not available in browser environments. Exclude '${t}' from your commands or use the Node.js bundle.
|
|
769
|
+
`,127):D(`bash: ${t}: command not found
|
|
770
|
+
`,127);if("error"in c)return c.error==="permission_denied"?D(`bash: ${t}: Permission denied
|
|
771
|
+
`,126):D(`bash: ${t}: No such file or directory
|
|
772
|
+
`,127);if("script"in c)return t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,c.path)),await a(c.path,n,r);let{cmd:u,path:f}=c;t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,f));let d=r||i.state.groupStdin||"",p=!1,h=o();i.state.fileDescriptors??=new Map;let m={fs:i.fs,fsIdentity:Tr(i.fs),cwd:i.state.cwd,env:i.state.env,assignShellVariable:async(g,y,S)=>{if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(g))throw new Error(`${g}: not a valid identifier`);let v=S===void 0?g:`${g}[${S}]`,k=Yr(i,g,y);if(k===void 0)throw new Error(`${g}: circular name reference`);if(k===null)return;let A=k.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(?:\[(.*)\])?$/);if(!A)throw new Error(`${v}: not a valid identifier`);let $=A[1],N=A[2]??S;if(Be(i,g)||Be(i,$))throw new Error(`${$}: readonly variable`);if(N===void 0)i.state.env.set($,y);else{let P=i.state.associativeArrays?.has($)?"associative":"indexed";if(P==="associative"){G(i,$,N,y,P);return}let C=await ta(i,$,N);if(C.error)throw new j(C.error.exitCode,C.error.stdout,C.error.stderr);G(i,$,C.index,y,P)}},exportedEnv:h,get stdin(){return p=!0,d},limits:i.limits,executionScope:u.internalIsExtension?Na(i.executionScope):i.executionScope,exec:(g,y)=>i.execFn(g,y,!1),execWithInheritedStdin:(g,y)=>i.execFn(g,{...y,stdin:d,stdinKind:"bytes"},!0),fetch:i.fetch,getRegisteredCommands:()=>Array.from(i.commands.keys()),sleep:i.sleep,trace:i.trace,fileDescriptors:i.state.fileDescriptors,xpgEcho:i.state.shoptOptions.xpg_echo,coverage:i.coverage,signal:i.state.signal,requireDefenseContext:i.requireDefenseContext,jsBootstrapCode:i.jsBootstrapCode,invokeTool:i.invokeTool},E=gm(m,t),b=Xu(E.context,t);try{let g=()=>ha(i.requireDefenseContext,"command",`${t} execution`,()=>u.execute(n,b)),y=()=>wm(g,b,E.revoke,t,i.executionScope,i.state.signal),S=u.trusted?await Le.runTrustedAsync(y):await y();return{...S,internalStdinConsumed:S.internalStdinConsumed??(p?r.length:0)}}catch(g){if(g instanceof x||g instanceof ze||g instanceof _t)throw g;return D(`${t}: ${wt($t(g))}
|
|
773
|
+
`)}}async function na(e,t){let n=e.state.inCondition;e.state.inCondition=!0;let r=new Vt(e.executionScope,"condition"),s=0;try{for(let i of t){let o=await e.executeStatement(i);r.appendResult(o),s=o.exitCode}}catch(i){throw r.prependTo(i),i}finally{e.state.inCondition=n}return r.build(s)}function vr(e,t,n,r){if(e instanceof He)return t+=e.stdout,n+=e.stderr,e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=n,{action:"rethrow",stdout:t,stderr:n,error:e}):{action:"break",stdout:t,stderr:n};if(e instanceof Qe)return t+=e.stdout,n+=e.stderr,e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=n,{action:"rethrow",stdout:t,stderr:n,error:e}):{action:"continue",stdout:t,stderr:n};if(e instanceof _e||e instanceof We||e instanceof j||e instanceof x)return e.prependOutput(t,n),{action:"rethrow",stdout:t,stderr:n,error:e};let s=$t(e);return{action:"error",stdout:t,stderr:`${n}${s}
|
|
774
|
+
`,exitCode:1}}function pf(e,t){return e!==void 0?{owns:!0,stdin:e}:t!==""?{owns:!0,stdin:t}:{owns:!1}}var on=class{ctx;stdoutChunks=[];stderrChunks=[];totalBytes=0;constructor(t){this.ctx=t}append(t,n){let r=B(t)+B(n);r>this.ctx.limits.maxOutputSize-this.totalBytes&&Xt(`total output size exceeded (>${this.ctx.limits.maxOutputSize} bytes), increase executionLimits.maxOutputSize`,"output_size"),t&&this.stdoutChunks.push(t),n&&this.stderrChunks.push(n),this.totalBytes+=r}appendUnaccounted(t,n){this.ctx.executionScope.appendOutput("stdout",t,"control-flow"),this.ctx.executionScope.appendOutput("stderr",n,"control-flow"),this.append(t,n)}replace(t,n){this.stdoutChunks=[],this.stderrChunks=[],this.totalBytes=0,this.append(t,n)}get stdout(){return this.stdoutChunks.join("")}get stderr(){return this.stderrChunks.join("")}build(t){let n=this.stdout,r=this.stderr;return{stdout:n,stderr:r,exitCode:t,internalOutputAccounting:{stdout:B(n),stderr:B(r)}}}};async function ra(e,t,n){let r=0;try{for(let s of t){let i=await e.executeStatement(s);n.append(i.stdout,i.stderr),r=i.exitCode}}catch(s){if(Or(s)||s instanceof We||s instanceof j||s instanceof x||s instanceof Mt)throw s.prependOutput(n.stdout,n.stderr),s;return n.appendUnaccounted("",`${$t(s)}
|
|
775
|
+
`),n.build(1)}return n.build(r)}async function hf(e,t){return nt(e,t.redirections,"",()=>Sm(e,t))}async function Sm(e,t){let n=new on(e);for(let r of t.clauses){let s=await na(e,r.condition);if(n.append(s.stdout,s.stderr),s.exitCode===0)return ra(e,r.body,n)}return t.elseBody?ra(e,t.elseBody,n):n.build(0)}async function mf(e,t){return nt(e,t.redirections,"",()=>Am(e,t))}async function Am(e,t){let n=new on(e),r=0,s=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t.variable))return D(`bash: \`${t.variable}': not a valid identifier
|
|
776
|
+
`);let i=[];if(t.words===null)i=(e.state.env.get("@")||"").split(" ").filter(Boolean);else if(t.words.length===0)i=[];else try{for(let o of t.words){let a=await gt(e,o);Oe(i,a.values,e.limits.maxArrayElements,"for-loop expansion")}}catch(o){if(o instanceof Lt)return{stdout:"",stderr:o.stderr,exitCode:1};throw o}e.state.loopDepth++;try{for(let o of i){s++,s>e.limits.maxLoopIterations&&Xt(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n.stdout,n.stderr),e.state.env.set(t.variable,o);try{for(let a of t.body){let l=await e.executeStatement(a);n.append(l.stdout,l.stderr),r=l.exitCode}}catch(a){let l=vr(a,n.stdout,n.stderr,e.state.loopDepth);if(n.replace(l.stdout,l.stderr),l.action==="break")break;if(l.action==="continue")continue;if(l.action==="error")return n.build(l.exitCode??1);throw l.error}}}finally{e.state.loopDepth--}return n.build(r)}async function yf(e,t){return nt(e,t.redirections,"",()=>vm(e,t))}async function vm(e,t){let n=t.line;n!==void 0&&(e.state.currentLine=n);let r=new on(e),s=0,i=0;t.init&&await Y(e,t.init.expression),e.state.loopDepth++;try{for(;i++,i>e.limits.maxLoopIterations&&Xt(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r.stdout,r.stderr),!(t.condition&&(n!==void 0&&(e.state.currentLine=n),await Y(e,t.condition.expression)===0));){try{for(let o of t.body){let a=await e.executeStatement(o);r.append(a.stdout,a.stderr),s=a.exitCode}}catch(o){let a=vr(o,r.stdout,r.stderr,e.state.loopDepth);if(r.replace(a.stdout,a.stderr),a.action==="break")break;if(a.action==="continue"){t.update&&await Y(e,t.update.expression);continue}if(a.action==="error")return r.build(a.exitCode??1);throw a.error}t.update&&await Y(e,t.update.expression)}}finally{e.state.loopDepth--}return r.build(s)}async function gf(e,t,n=""){return nt(e,t.redirections,n,r=>km(e,t,n,r))}async function km(e,t,n,r){let s=new on(e),i=0,o=0,a=pf(r.stdin,n),l=e.state.groupStdin;a.owns&&(e.state.groupStdin=a.stdin),e.state.loopDepth++;try{for(;;){o++,o>e.limits.maxLoopIterations&&Xt(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s.stdout,s.stderr);let c=0,u=!1,f=!1,d=e.state.inCondition;e.state.inCondition=!0;try{for(let p of t.condition){let h=await e.executeStatement(p);s.append(h.stdout,h.stderr),c=h.exitCode}}catch(p){if(p instanceof He){if(s.append(p.stdout,p.stderr),p.levels>1&&e.state.loopDepth>1)throw p.levels--,p.stdout=s.stdout,p.stderr=s.stderr,e.state.inCondition=d,p;u=!0}else if(p instanceof Qe){if(s.append(p.stdout,p.stderr),p.levels>1&&e.state.loopDepth>1)throw p.levels--,p.stdout=s.stdout,p.stderr=s.stderr,e.state.inCondition=d,p;f=!0}else throw e.state.inCondition=d,p}finally{e.state.inCondition=d}if(u)break;if(!f){if(c!==0)break;try{for(let p of t.body){let h=await e.executeStatement(p);s.append(h.stdout,h.stderr),i=h.exitCode}}catch(p){let h=vr(p,s.stdout,s.stderr,e.state.loopDepth);if(s.replace(h.stdout,h.stderr),h.action==="break")break;if(h.action==="continue")continue;if(h.action==="error")return s.build(h.exitCode??1);throw h.error}}}}finally{e.state.loopDepth--,a.owns&&(e.state.groupStdin=l)}return s.build(i)}async function wf(e,t,n=""){return nt(e,t.redirections,n,r=>Pm(e,t,n,r))}async function Pm(e,t,n,r){let s=new on(e),i=0,o=0,a=pf(r.stdin,n),l=e.state.groupStdin;a.owns&&(e.state.groupStdin=a.stdin),e.state.loopDepth++;try{for(;;){o++,o>e.limits.maxLoopIterations&&Xt(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s.stdout,s.stderr);let c=await na(e,t.condition);if(s.append(c.stdout,c.stderr),c.exitCode===0)break;try{for(let u of t.body){let f=await e.executeStatement(u);s.append(f.stdout,f.stderr),i=f.exitCode}}catch(u){let f=vr(u,s.stdout,s.stderr,e.state.loopDepth);if(s.replace(f.stdout,f.stderr),f.action==="break")break;if(f.action==="continue")continue;if(f.action==="error")return s.build(f.exitCode??1);throw f.error}}}finally{e.state.loopDepth--,a.owns&&(e.state.groupStdin=l)}return s.build(i)}async function Ef(e,t){return nt(e,t.redirections,"",()=>xm(e,t))}async function xm(e,t){let n=new on(e),r=0,s=await se(e,t.word),i=!1;for(let o=0;o<t.items.length;o++){let a=t.items[o],l=i;if(!i)for(let c of a.patterns){let u=await se(e,c);jc(c)&&(u=Je(u));let f=e.state.shoptOptions.nocasematch,d=e.state.shoptOptions.extglob;if(Mn(s,u,f,d,e.limits.maxCallDepth)){l=!0;break}}if(l){let c=await ra(e,a.body,n);if(n.replace(c.stdout,c.stderr),r=c.exitCode,a.terminator===";;")break;a.terminator===";&"?i=!0:i=!1}else i=!1}return n.build(r)}function sa(e,t){if(e.parts.length!==1)return!1;let n=e.parts[0];return n.type!=="Literal"?!1:t.includes(n.value)}async function bf(e,t,n){let r=t.timed?ei():0,s="",i=ne,o=0,a=[],l="",c=0,u=t.commands.length>1,f=e.state.lastArg,d=e.state.groupStdin,p=e.state.groupStdinSourceFd;for(let g=0;g<t.commands.length;g++){let y=t.commands[g],S=g===t.commands.length-1,v=g===0;u&&(e.state.lastArg="",e.state.groupStdin=v?d:void 0,e.state.groupStdinSourceFd=v?p:void 0);let k=u&&(!S||!e.state.shoptOptions.lastpipe),A=k?new Map(e.state.env):null,$=k?ot(e.state.arrays):null,N,P=e.executionScope.outputBytesUsed;try{e.state.commandCount=e.executionScope.chargeCommand(),N=await n(y,s)}catch(C){if(C instanceof Ke)N={stdout:C.stdout,stderr:C.stderr,exitCode:1};else if(C instanceof j&&t.commands.length>1)N={stdout:C.stdout,stderr:C.stderr,exitCode:C.exitCode};else if(C instanceof We&&t.commands.length>1)N={stdout:C.stdout,stderr:C.stderr,exitCode:C.exitCode};else throw A&&(e.state.env=A,e.state.arrays=$??new Map),C}finally{u&&(v&&(d=e.state.groupStdin,p=e.state.groupStdinSourceFd),e.state.groupStdin=d,e.state.groupStdinSourceFd=p)}if(A&&(e.state.env=A,e.state.arrays=$??new Map),N=e.executionScope.accountResult(N,"pipeline",e.executionScope.outputBytesUsed-P),!S){let C=t.pipeStderr?.[g]??!1,O=N.internalOutputAccounting?.stdout??0,U=C?N.internalOutputAccounting?.stderr??0:0;Ra(e.executionScope,O+U,"pipeline"),N={...N,internalOutputAccounting:{stdout:0,stderr:C?0:N.internalOutputAccounting?.stderr??0}}}a.push(N.exitCode),N.exitCode!==0&&(o=N.exitCode),S?i=N:(t.pipeStderr?.[g]??!1?s=Tt(N.stderr)+xt(N):(s=xt(N),l+=N.stderr,c+=N.internalOutputAccounting?.stderr??0),i={stdout:"",stderr:"",exitCode:N.exitCode})}l&&(i={...i,stderr:l+i.stderr,internalOutputAccounting:{stdout:i.internalOutputAccounting?.stdout??0,stderr:c+(i.internalOutputAccounting?.stderr??0)}});let h=t.commands.length>1||t.commands.length===1&&t.commands[0].type==="SimpleCommand",m=i.internalPipeStatusOverride??a;if(h){Ee(e,"PIPESTATUS");for(let g=0;g<m.length;g++)G(e,"PIPESTATUS",g,String(m[g]))}if(e.state.options.pipefail&&o!==0&&(i={...i,exitCode:o}),t.negated&&(i={...i,exitCode:i.exitCode===0?1:0}),t.timed){let y=(ei()-r)/1e3,S=Math.floor(y/60),v=y%60,k;t.timePosix?k=`real ${y.toFixed(2)}
|
|
745
777
|
user 0.00
|
|
746
778
|
sys 0.00
|
|
747
|
-
`:
|
|
748
|
-
real ${`${
|
|
779
|
+
`:k=`
|
|
780
|
+
real ${`${S}m${v.toFixed(3)}s`}
|
|
749
781
|
user 0m0.000s
|
|
750
782
|
sys 0m0.000s
|
|
751
|
-
`,i={...i,stderr:i.stderr+
|
|
752
|
-
`)
|
|
753
|
-
`).
|
|
754
|
-
`));let p=f.fd??0;p!==0?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),je(e),e.state.fileDescriptors.set(p,h)):l=h}else if(f.operator==="<<<"&&f.target.type==="Word")l=`${a.targets.get(t.redirections.indexOf(f))??""}
|
|
755
|
-
`;else if(f.operator==="<"&&f.target.type==="Word")try{let d=a.targets.get(t.redirections.indexOf(f))??"",h=e.fs.resolvePath(e.state.cwd,d);l=await e.fs.readFile(h)}catch{let d=a.targets.get(t.redirections.indexOf(f))??"";return I("",`bash: ${d}: No such file or directory
|
|
756
|
-
`,1)}let c=e.state.groupStdin;l&&(e.state.groupStdin=l);try{for(let f of t.body){let d=await r(f);s.appendResult(d),i=d.exitCode}}catch(f){if(e.state.groupStdin=c,f instanceof P)throw s.prependTo(f),f;if(wr(f)||f instanceof et||f instanceof H)throw f.prependOutput(s.stdout,s.stderr),f;return s.append("stderr",`${St(f)}
|
|
757
|
-
`),s.build(1)}e.state.groupStdin=c;let u=s.build(i);return me(e,u,t.redirections,a.targets)}async function Au(e,t,n,r,s){let i;try{i=await e.fs.readFile(t)}catch{return R(`bash: ${t}: No such file or directory
|
|
783
|
+
`,i={...i,stderr:i.stderr+k}}u&&!e.state.shoptOptions.lastpipe&&(e.state.lastArg=f),i=e.executionScope.accountResult(i,"pipeline");let{internalPipeStatusOverride:E,...b}=i;return b}function ia(e){return e?{...e,options:e.options?[...e.options]:void 0,actions:e.actions?[...e.actions]:void 0}:void 0}function $m(e){return e?new Map(Array.from(e,([t,n])=>[t,ia(n)])):void 0}function Cm(e){if(!e)return;let t=new Map,n=new Map;for(let[r,s]of e){let i=t.get(s);i||(i=new Set(s),t.set(s,i)),n.set(r,i)}return n}function Nm(e){return e?.map(t=>new Map(Array.from(t,([n,r])=>[n,r?{kind:r.kind,elements:new Map(r.elements)}:void 0])))}function Rm(e){return e?new Map(Array.from(e,([t,n])=>[t,n.map(r=>({...r}))])):void 0}function oa(e){let t={env:e.env,arrays:e.arrays,cwd:e.cwd,previousDir:e.previousDir,lastExitCode:e.lastExitCode,lastArg:e.lastArg,currentLine:e.currentLine,options:e.options,shoptOptions:e.shoptOptions,fileDescriptors:e.fileDescriptors,inputFds:e.inputFds,fdAliases:e.fdAliases,closedStandardFds:e.closedStandardFds,nextFd:e.nextFd,readonlyVars:e.readonlyVars,associativeArrays:e.associativeArrays,namerefs:e.namerefs,boundNamerefs:e.boundNamerefs,invalidNamerefs:e.invalidNamerefs,integerVars:e.integerVars,lowercaseVars:e.lowercaseVars,uppercaseVars:e.uppercaseVars,exportedVars:e.exportedVars,tempExportedVars:e.tempExportedVars,localExportedVars:e.localExportedVars,declaredVars:e.declaredVars,localScopes:e.localScopes,localArrayScopes:e.localArrayScopes,localVarDepth:e.localVarDepth,localVarStack:e.localVarStack,fullyUnsetLocals:e.fullyUnsetLocals,tempEnvBindings:e.tempEnvBindings,mutatedTempEnvVars:e.mutatedTempEnvVars,accessedTempEnvVars:e.accessedTempEnvVars,functions:e.functions,callDepth:e.callDepth,sourceDepth:e.sourceDepth,callLineStack:e.callLineStack,funcNameStack:e.funcNameStack,sourceStack:e.sourceStack,currentSource:e.currentSource,inCondition:e.inCondition,loopDepth:e.loopDepth,parentHasLoopContext:e.parentHasLoopContext,errexitSafe:e.errexitSafe,directoryStack:e.directoryStack,hashTable:e.hashTable,completionSpecs:e.completionSpecs,defaultCompletionSpec:e.defaultCompletionSpec,emptyCompletionSpec:e.emptyCompletionSpec,groupStdin:e.groupStdin,groupStdinSourceFd:e.groupStdinSourceFd,bashPid:e.bashPid,expansionExitCode:e.expansionExitCode,expansionStderr:e.expansionStderr};e.env=new Map(e.env),e.arrays=ot(e.arrays),e.options={...e.options},e.shoptOptions={...e.shoptOptions},e.fileDescriptors=e.fileDescriptors?new Map(e.fileDescriptors):void 0,e.inputFds=e.inputFds?new Set(e.inputFds):void 0,e.fdAliases=Cm(e.fdAliases),e.closedStandardFds=e.closedStandardFds?new Set(e.closedStandardFds):void 0,e.readonlyVars=new Set(e.readonlyVars),e.associativeArrays=new Set(e.associativeArrays),e.namerefs=new Set(e.namerefs),e.boundNamerefs=new Set(e.boundNamerefs),e.invalidNamerefs=new Set(e.invalidNamerefs),e.integerVars=new Set(e.integerVars),e.lowercaseVars=new Set(e.lowercaseVars),e.uppercaseVars=new Set(e.uppercaseVars),e.exportedVars=new Set(e.exportedVars),e.tempExportedVars=new Set(e.tempExportedVars),e.localExportedVars=e.localExportedVars?.map(r=>new Set(r)),e.declaredVars=new Set(e.declaredVars),e.localScopes=e.localScopes.map(r=>new Map(r)),e.localArrayScopes=Nm(e.localArrayScopes),e.localVarDepth=e.localVarDepth?new Map(e.localVarDepth):void 0,e.localVarStack=Rm(e.localVarStack),e.fullyUnsetLocals=e.fullyUnsetLocals?new Map(e.fullyUnsetLocals):void 0,e.tempEnvBindings=e.tempEnvBindings?.map(r=>new Map(r)),e.mutatedTempEnvVars=e.mutatedTempEnvVars?new Set(e.mutatedTempEnvVars):void 0,e.accessedTempEnvVars=e.accessedTempEnvVars?new Set(e.accessedTempEnvVars):void 0,e.functions=new Map(e.functions),e.callLineStack=e.callLineStack?[...e.callLineStack]:void 0,e.funcNameStack=e.funcNameStack?[...e.funcNameStack]:void 0,e.sourceStack=e.sourceStack?[...e.sourceStack]:void 0,e.directoryStack=e.directoryStack?[...e.directoryStack]:void 0,e.hashTable=e.hashTable?new Map(e.hashTable):void 0,e.completionSpecs=$m(e.completionSpecs),e.defaultCompletionSpec=ia(e.defaultCompletionSpec),e.emptyCompletionSpec=ia(e.emptyCompletionSpec);let n=!1;return()=>{n||(n=!0,Object.assign(e,t))}}async function Sf(e,t,n,r,s=!1){let i=e.state.loopDepth,o=new Map;for(let l of e.state.fileDescriptors?.keys()??[]){let c=tt(e,l);c&&o.set(l,c)}let a=oa(e.state);e.state.parentHasLoopContext=i>0,e.state.loopDepth=0,e.state.bashPid=e.state.nextVirtualPid++;try{return await nt(e,t.redirections,n,l=>Om(e,t,l.stdin??n,r,s||l.stdin!==void 0))}finally{let l=new Map;for(let[c,u]of o){let f=tt(e,c),d=u.kind==="input"&&f?.kind==="input"?u.content.length-f.content.length:u.kind==="readwrite"&&f?.kind==="readwrite"&&u.path===f.path?f.position-u.position:0;if(d<=0)continue;let p=Math.min(...en(e,c));l.set(p,Math.max(l.get(p)??0,d))}a();for(let[c,u]of l)tn(e,c,u)}}async function Om(e,t,n,r,s){(s||n)&&(e.state.groupStdin=n);let i=new Vt(e.executionScope,"subshell"),o=0;try{for(let a of t.body){let l=await r(a);i.appendResult(l),o=l.exitCode}}catch(a){if(a instanceof x)throw i.prependTo(a),a;return a instanceof Mt||a instanceof He||a instanceof Qe?(i.append("stdout",a.stdout,a.internalOutputAccounting.stdout),i.append("stderr",a.stderr,a.internalOutputAccounting.stderr),i.build(0)):a instanceof j||a instanceof _e||a instanceof We?(i.append("stdout",a.stdout,a.internalOutputAccounting.stdout),i.append("stderr",a.stderr,a.internalOutputAccounting.stderr),i.build(a.exitCode)):(i.append("stderr",`${$t(a)}
|
|
784
|
+
`),i.build(1))}return i.build(o)}async function Af(e,t,n,r,s=!1){return nt(e,t.redirections,n,i=>Dm(e,t,n,r,s,i))}async function Dm(e,t,n,r,s,i){let o=new Vt(e.executionScope,"group"),a=0,l=i.stdin??n,c=s||n!==""||i.stdin!==void 0,u=e.state.groupStdin;c&&(e.state.groupStdin=l);let f=()=>{(c||u!==void 0&&e.state.groupStdin===void 0)&&(e.state.groupStdin=u)};try{for(let d of t.body){let p=await r(d);o.appendResult(p),a=p.exitCode}}catch(d){if(f(),d instanceof x)throw o.prependTo(d),d;if(Or(d)||d instanceof We||d instanceof j)throw d.prependOutput(o.stdout,o.stderr),d;return o.append("stderr",`${$t(d)}
|
|
785
|
+
`),o.build(1)}return f(),o.build(a)}async function vf(e,t,n,r,s){let i;try{i=await e.fs.readFile(t)}catch{return D(`bash: ${t}: No such file or directory
|
|
758
786
|
`,127)}if(i.startsWith("#!")){let l=i.indexOf(`
|
|
759
|
-
`);l!==-1&&(i=i.slice(l+1))}let
|
|
760
|
-
`);throw l}}var
|
|
761
|
-
`);let r=0,s=-1,i=!1;try{for(let l=0;l<t.pipelines.length;l++){let c=t.pipelines[l],u=l>0?t.operators[l-1]:null;if(u==="&&"&&r!==0||u==="||"&&r===0)continue;let f=await this.executePipeline(c);n.appendResult(f,
|
|
762
|
-
|
|
763
|
-
`))
|
|
764
|
-
|
|
765
|
-
`)}if(A.operator==="<&"&&A.target.type==="Word"){let v=await z(this.ctx,A.target),x=Number.parseInt(v,10);if(!Number.isNaN(x)&&this.ctx.state.fileDescriptors){let N=this.ctx.state.fileDescriptors.get(x);if(N!==void 0)if(N.startsWith("__rw__:")){let D=Eu(N);D&&(n=D.content.slice(D.position),c=x)}else N.startsWith("__file__:")||N.startsWith("__file_append__:")||(n=N)}}}let u=await z(this.ctx,t.name),f=[],d=[],h=(A,v)=>{if(f.length>=this.ctx.limits.maxArrayElements)throw new P(`expanded argument element limit exceeded (${this.ctx.limits.maxArrayElements})`,"array_elements");f.push(A),d.push(v)};if(Aa(t.name,["local","declare","typeset","export","readonly"])&&(u==="local"||u==="declare"||u==="typeset"||u==="export"||u==="readonly"))for(let A of t.args){let v=await uc(this.ctx,A);if(v)h(v,!0);else{let x=await fc(this.ctx,A);if(x!==null)h(x,!0);else{let N=await ut(this.ctx,A);for(let D of N.values)h(D,N.quoted)}}}else for(let A of t.args){let v=await ut(this.ctx,A);for(let x of v.values)h(x,v.quoted)}if(!u){if(t.name.parts.every(v=>v.type==="CommandSubstitution"||v.type==="ParameterExpansion"||v.type==="ArithmeticExpansion")){if(f.length>0){let v=f.shift();return d.shift(),await this.runCommand(v,f,d,n,!1,!1,c)}return I("","",this.ctx.state.lastExitCode)}return R(`bash: : command not found
|
|
766
|
-
`,127)}if(u==="exec"&&(f.length===0||f[0]==="--")){for(let A of t.redirections){if(A.target.type==="HereDoc"||A.fdVariable)continue;let v=await z(this.ctx,A.target),x=A.fd??(A.operator==="<"||A.operator==="<>"?0:1);switch(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),A.operator){case">":case">|":{let N=this.ctx.fs.resolvePath(this.ctx.state.cwd,v);await this.ctx.fs.writeFile(N,"","utf8"),je(this.ctx),this.ctx.state.fileDescriptors.set(x,`__file__:${N}`);break}case">>":{let N=this.ctx.fs.resolvePath(this.ctx.state.cwd,v);je(this.ctx),this.ctx.state.fileDescriptors.set(x,`__file_append__:${N}`);break}case"<":{let N=this.ctx.fs.resolvePath(this.ctx.state.cwd,v);try{let D=await this.ctx.fs.readFile(N);je(this.ctx),this.ctx.state.fileDescriptors.set(x,D)}catch{return R(`bash: ${v}: No such file or directory
|
|
767
|
-
`)}break}case"<>":{let N=this.ctx.fs.resolvePath(this.ctx.state.cwd,v);try{let D=await this.ctx.fs.readFile(N);je(this.ctx),this.ctx.state.fileDescriptors.set(x,`__rw__:${N.length}:${N}:0:${D}`)}catch{await this.ctx.fs.writeFile(N,"","utf8"),je(this.ctx),this.ctx.state.fileDescriptors.set(x,`__rw__:${N.length}:${N}:0:`)}break}case">&":{if(v==="-")this.ctx.state.fileDescriptors.delete(x);else if(v.endsWith("-")){let N=v.slice(0,-1),D=Number.parseInt(N,10);if(!Number.isNaN(D)){let O=this.ctx.state.fileDescriptors.get(D);O!==void 0?this.ctx.state.fileDescriptors.set(x,O):this.ctx.state.fileDescriptors.set(x,`__dupout__:${D}`),this.ctx.state.fileDescriptors.delete(D)}}else{let N=Number.parseInt(v,10);Number.isNaN(N)||(je(this.ctx),this.ctx.state.fileDescriptors.set(x,`__dupout__:${N}`))}break}case"<&":{if(v==="-")this.ctx.state.fileDescriptors.delete(x);else if(v.endsWith("-")){let N=v.slice(0,-1),D=Number.parseInt(N,10);if(!Number.isNaN(D)){let O=this.ctx.state.fileDescriptors.get(D);O!==void 0?this.ctx.state.fileDescriptors.set(x,O):this.ctx.state.fileDescriptors.set(x,`__dupin__:${D}`),this.ctx.state.fileDescriptors.delete(D)}}else{let N=Number.parseInt(v,10);Number.isNaN(N)||(je(this.ctx),this.ctx.state.fileDescriptors.set(x,`__dupin__:${N}`))}break}}}for(let[A,v]of s)v===void 0?this.ctx.state.env.delete(A):this.ctx.state.env.set(A,v);if(this.ctx.state.tempExportedVars)for(let A of s.keys())this.ctx.state.tempExportedVars.delete(A);return ne}if(this.ctx.state.extraArgs){let A=this.ctx.state.extraArgs;this.ctx.state.extraArgs=void 0;for(let v of A)h(v,!0)}let m=await tu(this.ctx,u,f);s.size>0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(s)));let E,b=null;try{E=await this.runCommand(u,f,d,n,!1,!1,c)}catch(A){if(A instanceof Ze||A instanceof He)b=A,E=ne;else throw A}let g=i+m;if(g&&(E={...E,stderr:g+E.stderr}),E=await me(this.ctx,E,t.redirections),b)throw b;if(f.length>0){let A=f[f.length-1];if((u==="declare"||u==="local"||u==="typeset")&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test(A)){let v=A.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);v&&(A=v[1])}this.ctx.state.lastArg=A}else this.ctx.state.lastArg=u;let w=Pc(u)&&u!=="unset"&&u!=="eval";if(!this.ctx.state.options.posix||!w)for(let[A,v]of s)this.ctx.state.fullyUnsetLocals?.has(A)||(v===void 0?this.ctx.state.env.delete(A):this.ctx.state.env.set(A,v));if(this.ctx.state.tempExportedVars)for(let A of s.keys())this.ctx.state.tempExportedVars.delete(A);return s.size>0&&this.ctx.state.tempEnvBindings&&this.ctx.state.tempEnvBindings.pop(),this.ctx.state.expansionStderr&&(E={...E,stderr:this.ctx.state.expansionStderr+E.stderr},this.ctx.state.expansionStderr=""),E}async runCommand(t,n,r,s,i=!1,a=!1,o=-1){let l={ctx:this.ctx,runCommand:(u,f,d,h,p,m,E)=>this.runCommand(u,f,d,h,p,m,E),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(u,f,d)=>this.executeUserScript(u,f,d)},c=await fu(l,t,n,r,s,i,a,o);return c!==null?c:du(l,t,n,s,a)}aliasExpansionStack=new Set;expandAlias(t){return zo({env:this.ctx.state.env,limits:this.ctx.limits},t,this.aliasExpansionStack)}async findCommandInPath(t){return Es(this.ctx,t)}async executeSubshell(t,n=""){return Su(this.ctx,t,n,r=>this.executeStatement(r))}async executeGroup(t,n=""){return vu(this.ctx,t,n,r=>this.executeStatement(r))}async executeArithmeticCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let n=await ft(this.ctx,t.redirections);if(n.error)return n.error;try{let r=await K(this.ctx,t.expression.expression),s=we(r!==0);return this.ctx.state.expansionStderr&&(s={...s,stderr:this.ctx.state.expansionStderr+s.stderr},this.ctx.state.expansionStderr=""),me(this.ctx,s,t.redirections,n.targets)}catch(r){let s=R(`bash: arithmetic expression: ${r.message}
|
|
768
|
-
`);return me(this.ctx,s,t.redirections,n.targets)}}async executeConditionalCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let n=await ft(this.ctx,t.redirections);if(n.error)return n.error;try{let r=await Zt(this.ctx,t.expression),s=we(r);return this.ctx.state.expansionStderr&&(s={...s,stderr:this.ctx.state.expansionStderr+s.stderr},this.ctx.state.expansionStderr=""),me(this.ctx,s,t.redirections,n.targets)}catch(r){let s=r instanceof oe?1:2,i=R(`bash: conditional expression: ${r.message}
|
|
769
|
-
`,s);return me(this.ctx,i,t.redirections,n.targets)}}};import{lookup as ap}from"node:dns";function $a(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function Kh(e){let t=$a(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}var Xh=3;function xu(e){let t=e;for(let n=0;n<Xh;n++){if(t.includes("\\")||t.includes(";")||/%(?![0-9a-f]{2})/i.test(t))return!0;let r=t.toLowerCase();if(r.includes("%2f")||r.includes("%2e")||r.includes("%5c")||r.includes("%3b"))return!0;let s;try{s=decodeURIComponent(t)}catch{return!0}if(s===t)return!1;t=s}return t.includes("%")}function Yh(e,t){return t==="/"||t===""?!0:t.endsWith("/")?e.startsWith(t):e===t||e.startsWith(`${t}/`)}function ka(e,t){let n=$a(e);if(!n)return!1;let r=Kh(t);return!r||n.origin!==r.origin||r.pathPrefix!=="/"&&r.pathPrefix!==""&&xu(n.pathname)?!1:Yh(n.pathname,r.pathPrefix)}function Pu(e){return typeof e=="string"?e:e.url}function $u(e,t){return!t||t.length===0?!1:t.some(n=>ka(e,Pu(n)))}function Na(e){let t=Jh(e);if(t==="localhost"||t.endsWith(".localhost"))return!0;let n=ku(t);if(n)return Ss(n);let r=tp(t);return r?np(r):!1}function Jh(e){let t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function ep(e){if(!e)return null;let t=10,n=e;if(n.startsWith("0x")||n.startsWith("0X")?(t=16,n=n.slice(2)):n.length>1&&n.startsWith("0")&&(t=8),!n||t===16&&!/^[0-9a-fA-F]+$/.test(n)||t===10&&!/^\d+$/.test(n)||t===8&&!/^[0-7]+$/.test(n))return null;let r=Number.parseInt(n,t);return!Number.isFinite(r)||r<0?null:r}function ku(e){let t=e.split(".");if(t.length===0||t.length>4)return null;let n=t.map(l=>ep(l));if(n.some(l=>l===null))return null;let r=n;if(t.length===1){let l=r[0];return l>4294967295?null:[l>>>24&255,l>>>16&255,l>>>8&255,l&255]}if(t.length===2){let[l,c]=r;return l>255||c>16777215?null:[l,c>>>16&255,c>>>8&255,c&255]}if(t.length===3){let[l,c,u]=r;return l>255||c>255||u>65535?null:[l,c,u>>>8&255,u&255]}let[s,i,a,o]=r;return s>255||i>255||a>255||o>255?null:[s,i,a,o]}function tp(e){let t=e,n=null;if(t.includes(".")){let m=t.lastIndexOf(":");if(m<0)return null;let E=t.slice(m+1),b=ku(E);if(!b)return null;n=b,t=t.slice(0,m)}let r=t.includes("::")?t.split("::").length-1:0;if(r>1)return null;let[s,i]=t.split("::"),a=s?s.split(":").filter(Boolean):[],o=i?i.split(":").filter(Boolean):[],l=m=>/^[0-9a-f]{1,4}$/i.test(m)?Number.parseInt(m,16):null,c=a.map(l),u=o.map(l);if(c.some(m=>m===null)||u.some(m=>m===null))return null;let f=n?2:0,d=c.length+u.length+f,h=0;if(r===1){if(h=8-d,h<0)return null}else if(d!==8)return null;let p=[...c,...new Array(h).fill(0),...u];return n&&(p.push(n[0]<<8|n[1]),p.push(n[2]<<8|n[3])),p.length===8?p:null}function Ss(e){let[t,n]=e;return t===127||t===10||t===172&&n>=16&&n<=31||t===192&&n===168||t===169&&n===254||t===0||t===100&&n>=64&&n<=127||t===198&&(n===18||n===19)||t===192&&n===0&&e[2]===0||t===192&&n===0&&e[2]===2||t===198&&n===51&&e[2]===100||t===203&&n===0&&e[2]===113||t>=240}function np(e){if(e.every(s=>s===0)||e.slice(0,7).every(s=>s===0)&&e[7]===1||(e[0]&65472)===65152||(e[0]&65024)===64512)return!0;if(e[0]===0&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===65535){let s=[e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255];return Ss(s)}if(e[0]===8193&&e[1]===3512)return!0;if(e[0]===100&&e[1]===65435&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===0){let s=[e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255];return Ss(s)}if(e[0]===100&&e[1]===65435&&e[2]===1)return!0;if(e[0]===8194){let s=[e[1]>>>8&255,e[1]&255,e[2]>>>8&255,e[2]&255];return Ss(s)}return!1}function Nu(e){let t=[];for(let n of e){if(typeof n!="string"&&(n===null||typeof n!="object"||!("url"in n)||typeof n.url!="string")){t.push('Invalid allow-list entry: must be a string URL or an object with a "url" string property');continue}let r=Pu(n);if(!$a(r)){t.push(`Invalid URL in allow-list: "${r}" - must be a valid URL with scheme and host (e.g., "https://example.com")`);continue}let i=new URL(r);if(i.protocol!=="http:"&&i.protocol!=="https:"){t.push(`Only http and https URLs are allowed in allow-list: "${r}"`);continue}if(!i.hostname){t.push(`Allow-list entry must include a hostname: "${r}"`);continue}if(i.pathname!=="/"&&i.pathname!==""&&xu(i.pathname)){t.push(`Allow-list entry contains ambiguous path separators: "${r}"`);continue}(i.search||i.hash)&&t.push(`Query strings and fragments are ignored in allow-list entries: "${r}"`)}return t}var rp=typeof __BROWSER__<"u"&&__BROWSER__,Xt=class extends Error{constructor(){super("DNS pinning is unavailable in this runtime"),this.name="DnsPinningUnavailableError"}};function sp(e){let t=new Error(`ENOTFOUND ${e}`);return t.code="ENOTFOUND",t.errno=-3008,t.syscall="getaddrinfo",t.hostname=e,t}function ip(e){return(t,n,r)=>{let s=n.family==="IPv4"?4:n.family==="IPv6"?6:n.family;if(t.toLowerCase()!==e.hostname.toLowerCase()||s!==void 0&&s!==0&&s!==e.family){r(sp(t),"");return}n.all?r(null,[{address:e.address,family:e.family}]):r(null,e.address,e.family)}}var Cu=async e=>{if(rp)throw new Xt;try{let t=await import("./chunks/undici-HCLAUJT3.js"),n=new t.Agent({connections:1,pipelining:0,connect:{lookup:ip(e)}}),r=!1;return{async fetch(s,i){if(r)throw new Xt;let a=t.fetch;return await a(s,{...i,dispatcher:n})},async close(){r||(r=!0,await n.destroy())}}}catch(t){throw t instanceof Xt?t:new Xt}};var Je=class extends Error{constructor(t,n){let r=n??"URL not in allow-list";super(`Network access denied: ${r}: ${t}`),this.name="NetworkAccessDeniedError"}},Nn=class extends Error{constructor(t){super(`Too many redirects (max: ${t})`),this.name="TooManyRedirectsError"}},Cn=class extends Error{constructor(t){super(`Redirect target not in allow-list: ${t}`),this.name="RedirectNotAllowedError"}},vs=class extends Error{constructor(t,n){super(`HTTP method '${t}' not allowed. Allowed methods: ${n.join(", ")}`),this.name="MethodNotAllowedError"}},Dn=class extends Error{constructor(t){super(`Response body too large (max: ${t} bytes)`),this.name="ResponseTooLargeError"}};function op(e){return new Promise((t,n)=>{ap(e,{all:!0},(r,s)=>{r?n(r):t(s)})})}var lp=20,cp=3e4,up=10485760,fp=["GET","HEAD"],dp=new Set(["GET","HEAD","OPTIONS"]),hp=new Set([301,302,303,307,308]);function Rn(e){return e.reason instanceof Error?e.reason:new DOMException("The operation was aborted","AbortError")}function Du(e){if(e?.aborted)throw Rn(e)}async function Yt(e,t){if(!t)return e;if(t.aborted)throw e.catch(()=>{}),Rn(t);let n,r=new Promise((s,i)=>{n=()=>i(Rn(t)),t.addEventListener("abort",n,{once:!0})});try{return await Promise.race([e,r])}finally{n&&t.removeEventListener("abort",n)}}async function pp(e,t){try{return await Yt(e,t)}catch(n){throw t?.aborted&&e.then(r=>Ie.runTrustedAsync(()=>r.close())).catch(()=>{}),n}}async function mp(e){e.body&&!e.body.locked&&await e.body.cancel()}function Ca(e){let t=e.allowedUrlPrefixes??[];if(!e.dangerouslyAllowFullInternetAccess){let E=Nu(t);if(E.length>0)throw new Error(`Invalid network allow-list:
|
|
787
|
+
`);l!==-1&&(i=i.slice(l+1))}let o=e.state.loopDepth,a=oa(e.state);e.state.parentHasLoopContext=o>0,e.state.loopDepth=0,e.state.bashPid=e.state.nextVirtualPid++,r&&(e.state.groupStdin=r),e.state.currentSource=t,e.state.env.set("0",t),e.state.env.set("#",String(n.length)),e.state.env.set("@",n.join(" ")),e.state.env.set("*",n.join(" "));for(let l=0;l<n.length&&l<9;l++)e.state.env.set(String(l+1),n[l]);for(let l=n.length+1;l<=9;l++)e.state.env.delete(String(l));try{let c=new H().parse(i),u=await s(c);return a(),u}catch(l){if(a(),l instanceof j)return L(l.stdout,l.stderr,l.exitCode);if(l instanceof x)throw l;if(l.name==="ParseException")return D(`bash: ${t}: ${l.message}
|
|
788
|
+
`);throw l}}function Im(e){throw new TypeError(`Unsupported command node: ${JSON.stringify(e)}`)}var kr=class{ctx;constructor(t,n){this.ctx={state:n,fs:t.fs,commands:t.commands,limits:t.limits,executionScope:t.executionScope,execFn:t.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:t.fetch,sleep:t.sleep,trace:t.trace,coverage:t.coverage,requireDefenseContext:t.requireDefenseContext??!1,jsBootstrapCode:t.jsBootstrapCode,invokeTool:t.invokeTool}}assertDefenseContext(t){if(!this.ctx.requireDefenseContext||Le.isInSandboxedContext())return;let n=`interpreter ${t} attempted outside defense context`;throw new _t(n,{timestamp:Date.now(),type:"missing_defense_context",message:n,path:"DefenseInDepthBox.context",stack:new Error().stack,executionId:Le.getCurrentExecutionId()})}buildExportedEnv(){let t=this.ctx.state.exportedVars,n=this.ctx.state.tempExportedVars,r=new Set;if(t)for(let i of t)r.add(i);if(n)for(let i of n)r.add(i);if(r.size===0)return Object.create(null);let s=Object.create(null);for(let i of r){let o=this.ctx.state.env.get(i);o!==void 0&&(s[i]=o)}return s}async executeScript(t){this.assertDefenseContext("execution");let n=0,r=new Vt(this.ctx.executionScope,"script");for(let s of t.statements)try{let i=await this.executeStatement(s);r.appendResult(i,Ys(i)),n=i.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n))}catch(i){if(i instanceof j)throw i.prependOutput(r.stdout,r.stderr),i;if(i instanceof st)return r.append("stdout",i.stdout,i.internalOutputAccounting.stdout),r.append("stderr",i.stderr,i.internalOutputAccounting.stderr),n=i.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{...r.build(n),exitCode:n,env:Wt(this.ctx.state.env)};if(i instanceof x)throw r.prependTo(i),i;if(i instanceof We)return r.append("stdout",i.stdout,i.internalOutputAccounting.stdout),r.append("stderr",i.stderr,i.internalOutputAccounting.stderr),n=i.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{...r.build(n),exitCode:n,env:Wt(this.ctx.state.env)};if(i instanceof Ve)return r.append("stdout",i.stdout,i.internalOutputAccounting.stdout),r.append("stderr",i.stderr,i.internalOutputAccounting.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{...r.build(n),exitCode:n,env:Wt(this.ctx.state.env)};if(i instanceof Ke)return r.append("stdout",i.stdout,i.internalOutputAccounting.stdout),r.append("stderr",i.stderr,i.internalOutputAccounting.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{...r.build(n),exitCode:n,env:Wt(this.ctx.state.env)};if(i instanceof ce){r.append("stdout",i.stdout,i.internalOutputAccounting.stdout),r.append("stderr",i.stderr,i.internalOutputAccounting.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n));continue}if(i instanceof Rr){r.append("stdout",i.stdout,i.internalOutputAccounting.stdout),r.append("stderr",i.stderr,i.internalOutputAccounting.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n));continue}if(i instanceof He||i instanceof Qe){if(this.ctx.state.loopDepth>0)throw i.prependOutput(r.stdout,r.stderr),i;r.append("stdout",i.stdout),r.append("stderr",i.stderr);continue}throw i instanceof _e&&i.prependOutput(r.stdout,r.stderr),i}return{...r.build(n),env:Wt(this.ctx.state.env)}}async executeUserScript(t,n,r=""){return vf(this.ctx,t,n,r,s=>this.executeScript(s))}async executeStatement(t){if(this.assertDefenseContext("statement"),this.ctx.state.signal?.aborted)throw new ze;if(t.deferredError)throw new xe(t.deferredError.message,t.line??1,1);if(this.ctx.state.options.noexec)return ne;this.ctx.state.errexitSafe=!1;let n=new Vt(this.ctx.executionScope,"statement");this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&t.sourceText&&n.append("stderr",`${t.sourceText}
|
|
789
|
+
`);let r=0,s=-1,i=!1;try{for(let l=0;l<t.pipelines.length;l++){let c=t.pipelines[l],u=l>0?t.operators[l-1]:null;if(u==="&&"&&r!==0||u==="||"&&r===0)continue;let f=await this.executePipeline(c);n.appendResult(f,Ys(f)),r=f.exitCode,s=l,i=c.negated,this.ctx.state.lastExitCode=r,this.ctx.state.env.set("?",String(r))}}catch(l){throw n.prependTo(l),l}let o=s<t.pipelines.length-1,a=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=o||i||a,this.ctx.state.options.errexit&&r!==0&&s===t.pipelines.length-1&&!i&&!this.ctx.state.inCondition&&!a){let l=new We(r);throw l.prependOutput(n.stdout,n.stderr),l}return n.build(r)}async executePipeline(t){return bf(this.ctx,t,(n,r)=>this.executeCommand(n,r))}async executeCommand(t,n,r=!1){let s=Uc(this.ctx),i;try{i=await this.executeCommandInner(t,n,r)}catch(a){throw await ji(this.ctx,s).catch(()=>{}),a}let o=await ji(this.ctx,s);return!o.stdout&&!o.stderr?i:{...i,stdout:o.stdout?xt(i)+o.stdout:i.stdout,stdoutKind:o.stdout?"bytes":i.stdoutKind,stderr:i.stderr+o.stderr}}async executeCommandInner(t,n,r){switch(this.assertDefenseContext("command"),this.ctx.coverage?.hit(`bash:cmd:${t.type}`),t.type){case"SimpleCommand":return this.executeSimpleCommand(t,n);case"If":return hf(this.ctx,t);case"For":return mf(this.ctx,t);case"CStyleFor":return yf(this.ctx,t);case"While":return gf(this.ctx,t,n);case"Until":return wf(this.ctx,t,n);case"Case":return Ef(this.ctx,t);case"Subshell":return this.executeSubshell(t,n,r);case"Group":return this.executeGroup(t,n,r);case"FunctionDef":return ku(this.ctx,t);case"ArithmeticCommand":return this.executeArithmeticCommand(t);case"ConditionalCommand":return this.executeConditionalCommand(t);default:return Im(t)}}async executeSimpleCommand(t,n){let r;try{return await this.executeSimpleCommandInner(t,n,s=>{r=s})}catch(s){if(r?.finish(),s instanceof Lt)return D(s.stderr);throw s}}async executeSimpleCommandInner(t,n,r){if(t.line!==void 0&&(this.ctx.state.currentLine=t.line),this.ctx.state.shoptOptions.expand_aliases&&t.name){let P=t,C=0;for(;;){let O=this.expandAlias(P);if(O===P)break;if(C>=this.ctx.limits.maxCallDepth)throw new x(`alias expansion depth limit exceeded (${this.ctx.limits.maxCallDepth})`,"recursion");C++,P=O}this.aliasExpansionStack.clear(),P!==t&&(t=P)}this.ctx.state.expansionStderr="";let s=await nf(this.ctx,t);if(s.error)return s.error;let i=s.tempAssignments,o=s.xtraceOutput,a=()=>{for(let[P,C]of i)C===void 0?this.ctx.state.env.delete(P):this.ctx.state.env.set(P,C)};if(!t.name){if(t.redirections.length>0){let C=Vn(this.ctx,t.redirections,Au);r(C);let O=await C.prepare(n);if(O.error){if(a(),!O.errorCause)return C.finish(),O.error;try{return zn(O)}finally{C.finish()}}let U=L("",o,0),X=await rn(this.ctx,U,t.redirections,O.targets,O.dupSources,O.standardRoutes);return C.finish(),X}this.ctx.state.lastArg="";let P=(this.ctx.state.expansionStderr||"")+o;return this.ctx.state.expansionStderr="",L("",P,this.ctx.state.lastExitCode)}let l=t.name&&sa(t.name,["local","declare","typeset","export","readonly"]),c=Array.from(i.keys());if(c.length>0&&!l){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let P of c)this.ctx.state.tempExportedVars.add(P)}let u=await se(this.ctx,t.name),f=[],d=[],p=(P,C)=>{if(f.length>=this.ctx.limits.maxArrayElements)throw new x(`expanded argument element limit exceeded (${this.ctx.limits.maxArrayElements})`,"array_elements");f.push(P),d.push(C)};if(sa(t.name,["local","declare","typeset","export","readonly"])&&(u==="local"||u==="declare"||u==="typeset"||u==="export"||u==="readonly"))for(let P of t.args){let C=await eu(this.ctx,P);if(C)p(C,!0);else{let O=await tu(this.ctx,P);if(O!==null)p(O,!0);else{let U=await gt(this.ctx,P);for(let X of U.values)p(X,U.quoted)}}}else for(let P of t.args){let C=await gt(this.ctx,P);for(let O of C.values)p(O,C.quoted)}let m=t.name.parts.every(P=>P.type==="CommandSubstitution"||P.type==="ParameterExpansion"||P.type==="ArithmeticExpansion");!u&&m&&f.length>0&&(u=f.shift(),d.shift());let E=Vn(this.ctx,t.redirections,u==="exec"?vu:yr);r(E);let b=await E.prepare(n);if(b.error)return a(),b.errorCause?zn(b):(E.finish(),b.error);let g=b.stdinSourceFd,y=b.stdin!==void 0;if(b.stdin!==void 0&&(n=b.stdin),!u)return m?(E.finish(),L("","",this.ctx.state.lastExitCode)):(E.finish(),D(`bash: : command not found
|
|
790
|
+
`,127));if(u==="exec"&&(f.length===0||f[0]==="--")){for(let[P,C]of i)C===void 0?this.ctx.state.env.delete(P):this.ctx.state.env.set(P,C);if(this.ctx.state.tempExportedVars)for(let P of i.keys())this.ctx.state.tempExportedVars.delete(P);return E.finish(),ne}if(this.ctx.state.extraArgs){let P=this.ctx.state.extraArgs;this.ctx.state.extraArgs=void 0;for(let C of P)p(C,!0)}let S=await ef(this.ctx,u,f);i.size>0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(i)));let v,k=null;try{v=await this.runCommand(u,f,d,n,!1,!1,g,y)}catch(P){if(P instanceof He||P instanceof Qe)k=P,v=ne;else throw P}g>=0&&u!=="read"&&tn(this.ctx,g,v.internalStdinConsumed??0);let A=o+S;if(A&&(v={...v,stderr:A+v.stderr}),v=await rn(this.ctx,v,t.redirections,b.targets,b.dupSources,b.standardRoutes,v.internalProducerCommand??u,v.internalProducerOmitsShellPrefix),E.finish(),k)throw k;if(f.length>0){let P=f[f.length-1];if((u==="declare"||u==="local"||u==="typeset")&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test(P)){let C=P.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);C&&(P=C[1])}this.ctx.state.lastArg=P}else this.ctx.state.lastArg=u;let $=yu(u)&&u!=="unset"&&u!=="eval";if(!this.ctx.state.options.posix||!$)for(let[P,C]of i)this.ctx.state.fullyUnsetLocals?.has(P)||(C===void 0?this.ctx.state.env.delete(P):this.ctx.state.env.set(P,C));if(this.ctx.state.tempExportedVars)for(let P of i.keys())this.ctx.state.tempExportedVars.delete(P);return i.size>0&&this.ctx.state.tempEnvBindings&&this.ctx.state.tempEnvBindings.pop(),this.ctx.state.expansionStderr&&(v={...v,stderr:this.ctx.state.expansionStderr+v.stderr},this.ctx.state.expansionStderr=""),v}async runCommand(t,n,r,s,i=!1,o=!1,a=-1,l=!1){let c={ctx:this.ctx,runCommand:(d,p,h,m,E,b,g,y)=>this.runCommand(d,p,h,m,E,b,g,y),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(d,p,h)=>this.executeUserScript(d,p,h)},u=await ff(c,t,n,r,s,i,o,a,l);return u!==null?u.internalProducerCommand===void 0?{...u,internalProducerCommand:t}:u:{...await df(c,t,n,s,o),internalProducerCommand:t}}aliasExpansionStack=new Set;expandAlias(t){return xl({env:this.ctx.state.env,limits:this.ctx.limits},t,this.aliasExpansionStack)}async findCommandInPath(t){return Fs(this.ctx,t)}async executeSubshell(t,n="",r=!1){return Sf(this.ctx,t,n,s=>this.executeStatement(s),r)}async executeGroup(t,n="",r=!1){return Af(this.ctx,t,n,s=>this.executeStatement(s),r)}async executeArithmeticCommand(t){return t.line!==void 0&&(this.ctx.state.currentLine=t.line),nt(this.ctx,t.redirections,"",async()=>{try{let n=await Y(this.ctx,t.expression.expression),r=be(n!==0);return this.ctx.state.expansionStderr&&(r={...r,stderr:this.ctx.state.expansionStderr+r.stderr},this.ctx.state.expansionStderr=""),r}catch(n){return D(`bash: arithmetic expression: ${n.message}
|
|
791
|
+
`)}})}async executeConditionalCommand(t){return t.line!==void 0&&(this.ctx.state.currentLine=t.line),nt(this.ctx,t.redirections,"",async()=>{try{let n=await Yt(this.ctx,t.expression),r=be(n);return this.ctx.state.expansionStderr&&(r={...r,stderr:this.ctx.state.expansionStderr+r.stderr},this.ctx.state.expansionStderr=""),r}catch(n){let r=n instanceof ce?1:2;return D(`bash: conditional expression: ${n.message}
|
|
792
|
+
`,r)}})}};import{lookup as jm}from"node:dns";function aa(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function _m(e){let t=aa(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}var Tm=3;function kf(e){let t=e;for(let n=0;n<Tm;n++){if(t.includes("\\")||t.includes(";")||/%(?![0-9a-f]{2})/i.test(t))return!0;let r=t.toLowerCase();if(r.includes("%2f")||r.includes("%2e")||r.includes("%5c")||r.includes("%3b"))return!0;let s;try{s=decodeURIComponent(t)}catch{return!0}if(s===t)return!1;t=s}return t.includes("%")}function Lm(e,t){return t==="/"||t===""?!0:t.endsWith("/")?e.startsWith(t):e===t||e.startsWith(`${t}/`)}function la(e,t){let n=aa(e);if(!n)return!1;let r=_m(t);return!r||n.origin!==r.origin||r.pathPrefix!=="/"&&r.pathPrefix!==""&&kf(n.pathname)?!1:Lm(n.pathname,r.pathPrefix)}function Pf(e){return typeof e=="string"?e:e.url}function xf(e,t){return!t||t.length===0?!1:t.some(n=>la(e,Pf(n)))}function ca(e){let t=Mm(e);if(t==="localhost"||t.endsWith(".localhost"))return!0;let n=$f(t);if(n)return Ws(n);let r=Bm(t);return r?Wm(r):!1}function Mm(e){let t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function Fm(e){if(!e)return null;let t=10,n=e;if(n.startsWith("0x")||n.startsWith("0X")?(t=16,n=n.slice(2)):n.length>1&&n.startsWith("0")&&(t=8),!n||t===16&&!/^[0-9a-fA-F]+$/.test(n)||t===10&&!/^\d+$/.test(n)||t===8&&!/^[0-7]+$/.test(n))return null;let r=Number.parseInt(n,t);return!Number.isFinite(r)||r<0?null:r}function $f(e){let t=e.split(".");if(t.length===0||t.length>4)return null;let n=t.map(l=>Fm(l));if(n.some(l=>l===null))return null;let r=n;if(t.length===1){let l=r[0];return l>4294967295?null:[l>>>24&255,l>>>16&255,l>>>8&255,l&255]}if(t.length===2){let[l,c]=r;return l>255||c>16777215?null:[l,c>>>16&255,c>>>8&255,c&255]}if(t.length===3){let[l,c,u]=r;return l>255||c>255||u>65535?null:[l,c,u>>>8&255,u&255]}let[s,i,o,a]=r;return s>255||i>255||o>255||a>255?null:[s,i,o,a]}function Bm(e){let t=e,n=null;if(t.includes(".")){let m=t.lastIndexOf(":");if(m<0)return null;let E=t.slice(m+1),b=$f(E);if(!b)return null;n=b,t=t.slice(0,m)}let r=t.includes("::")?t.split("::").length-1:0;if(r>1)return null;let[s,i]=t.split("::"),o=s?s.split(":").filter(Boolean):[],a=i?i.split(":").filter(Boolean):[],l=m=>/^[0-9a-f]{1,4}$/i.test(m)?Number.parseInt(m,16):null,c=o.map(l),u=a.map(l);if(c.some(m=>m===null)||u.some(m=>m===null))return null;let f=n?2:0,d=c.length+u.length+f,p=0;if(r===1){if(p=8-d,p<0)return null}else if(d!==8)return null;let h=[...c,...new Array(p).fill(0),...u];return n&&(h.push(n[0]<<8|n[1]),h.push(n[2]<<8|n[3])),h.length===8?h:null}function Ws(e){let[t,n]=e;return t===127||t===10||t===172&&n>=16&&n<=31||t===192&&n===168||t===169&&n===254||t===0||t===100&&n>=64&&n<=127||t===198&&(n===18||n===19)||t===192&&n===0&&e[2]===0||t===192&&n===0&&e[2]===2||t===198&&n===51&&e[2]===100||t===203&&n===0&&e[2]===113||t>=240}function Wm(e){if(e.every(s=>s===0)||e.slice(0,7).every(s=>s===0)&&e[7]===1||(e[0]&65472)===65152||(e[0]&65024)===64512)return!0;if(e[0]===0&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===65535){let s=[e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255];return Ws(s)}if(e[0]===8193&&e[1]===3512)return!0;if(e[0]===100&&e[1]===65435&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===0){let s=[e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255];return Ws(s)}if(e[0]===100&&e[1]===65435&&e[2]===1)return!0;if(e[0]===8194){let s=[e[1]>>>8&255,e[1]&255,e[2]>>>8&255,e[2]&255];return Ws(s)}return!1}function Cf(e){let t=[];for(let n of e){if(typeof n!="string"&&(n===null||typeof n!="object"||!("url"in n)||typeof n.url!="string")){t.push('Invalid allow-list entry: must be a string URL or an object with a "url" string property');continue}let r=Pf(n);if(!aa(r)){t.push(`Invalid URL in allow-list: "${r}" - must be a valid URL with scheme and host (e.g., "https://example.com")`);continue}let i=new URL(r);if(i.protocol!=="http:"&&i.protocol!=="https:"){t.push(`Only http and https URLs are allowed in allow-list: "${r}"`);continue}if(!i.hostname){t.push(`Allow-list entry must include a hostname: "${r}"`);continue}if(i.pathname!=="/"&&i.pathname!==""&&kf(i.pathname)){t.push(`Allow-list entry contains ambiguous path separators: "${r}"`);continue}(i.search||i.hash)&&t.push(`Query strings and fragments are ignored in allow-list entries: "${r}"`)}return t}var Vm=typeof __BROWSER__<"u"&&__BROWSER__,an=class extends Error{constructor(){super("DNS pinning is unavailable in this runtime"),this.name="DnsPinningUnavailableError"}};function zm(e){return"Agent"in e?e:e.default}function Um(e){let t=new Error(`ENOTFOUND ${e}`);return t.code="ENOTFOUND",t.errno=-3008,t.syscall="getaddrinfo",t.hostname=e,t}function qm(e){return(t,n,r)=>{let s=n.family==="IPv4"?4:n.family==="IPv6"?6:n.family;if(t.toLowerCase()!==e.hostname.toLowerCase()||s!==void 0&&s!==0&&s!==e.family){r(Um(t),"");return}n.all?r(null,[{address:e.address,family:e.family}]):r(null,e.address,e.family)}}var Nf=async e=>{if(Vm)throw new an;try{let{Agent:t,fetch:n}=zm(await import("./chunks/undici-HCLAUJT3.js")),r=new t({connections:1,pipelining:0,connect:{lookup:qm(e)}}),s=!1;return{async fetch(i,o){if(s)throw new an;return await n(i,{...o,dispatcher:r})},async close(){s||(s=!0,await r.destroy())}}}catch(t){throw t instanceof an?t:new an}};var rt=class extends Error{constructor(t,n){let r=n??"URL not in allow-list";super(`Network access denied: ${r}: ${t}`),this.name="NetworkAccessDeniedError"}},jn=class extends Error{constructor(t){super(`Too many redirects (max: ${t})`),this.name="TooManyRedirectsError"}},Gn=class extends Error{constructor(t){super(`Redirect target not in allow-list: ${t}`),this.name="RedirectNotAllowedError"}},Vs=class extends Error{constructor(t,n){super(`HTTP method '${t}' not allowed. Allowed methods: ${n.join(", ")}`),this.name="MethodNotAllowedError"}},Zn=class extends Error{constructor(t){super(`Response body too large (max: ${t} bytes)`),this.name="ResponseTooLargeError"}};function Gm(e){return new Promise((t,n)=>{jm(e,{all:!0},(r,s)=>{r?n(r):t(s)})})}var Zm=20,Hm=3e4,Qm=10485760,Km=["GET","HEAD"],Xm=new Set(["GET","HEAD","OPTIONS"]),Ym=new Set([301,302,303,307,308]);function Hn(e){return e.reason instanceof Error?e.reason:new DOMException("The operation was aborted","AbortError")}function Rf(e){if(e?.aborted)throw Hn(e)}async function ln(e,t){if(!t)return e;if(t.aborted)throw e.catch(()=>{}),Hn(t);let n,r=new Promise((s,i)=>{n=()=>i(Hn(t)),t.addEventListener("abort",n,{once:!0})});try{return await Promise.race([e,r])}finally{n&&t.removeEventListener("abort",n)}}async function Jm(e,t){try{return await ln(e,t)}catch(n){throw t?.aborted&&e.then(r=>Le.runTrustedAsync(()=>r.close())).catch(()=>{}),n}}async function ey(e){e.body&&!e.body.locked&&await e.body.cancel()}function ua(e){let t=e.allowedUrlPrefixes??[];if(!e.dangerouslyAllowFullInternetAccess){let E=Cf(t);if(E.length>0)throw new Error(`Invalid network allow-list:
|
|
770
793
|
${E.join(`
|
|
771
|
-
`)}`)}let n=[];for(let E of t)typeof E=="object"&&E.transform&&E.transform.length>0&&n.push(E);function r(E){if(n.length===0)return null;let b=null;for(let g of n)if(
|
|
772
|
-
`
|
|
773
|
-
${s}${n.delimiter}`}return e.operator==="<<<"?`${t}<<< ${$e(e.target)}`:e.operator==="&>"||e.operator==="&>>"?`${e.operator} ${$e(e.target)}`:`${t}${e.operator} ${$e(e.target)}`}function dt(e){return e.length===0?"":` ${e.map(Lu).join(" ")}`}function st(e){return e.map(Ou).join(`
|
|
774
|
-
`)}function kp(e){let t=[];for(let n=0;n<e.clauses.length;n++){let r=e.clauses[n],s=n===0?"if":"elif";t.push(`${s} ${st(r.condition)}; then
|
|
775
|
-
${st(r.body)}`)}return e.elseBody&&t.push(`else
|
|
776
|
-
${st(e.elseBody)}`),`${t.join(`
|
|
777
|
-
`)}
|
|
778
|
-
fi${dt(e.redirections)}`}function Np(e){let t;if(e.words===null)t=`for ${e.variable}`;else{let n=e.words.map($e).join(" ");t=`for ${e.variable} in ${n}`}return`${t}; do
|
|
779
|
-
${st(e.body)}
|
|
780
|
-
done${dt(e.redirections)}`}function Cp(e){let t=e.init?fe(e.init.expression):"",n=e.condition?fe(e.condition.expression):"",r=e.update?fe(e.update.expression):"";return`for ((${t}; ${n}; ${r})); do
|
|
781
|
-
${st(e.body)}
|
|
782
|
-
done${dt(e.redirections)}`}function Dp(e){return`while ${st(e.condition)}; do
|
|
783
|
-
${st(e.body)}
|
|
784
|
-
done${dt(e.redirections)}`}function Rp(e){return`until ${st(e.condition)}; do
|
|
785
|
-
${st(e.body)}
|
|
786
|
-
done${dt(e.redirections)}`}function Op(e){let t=e.items.map(Ip).join(`
|
|
787
|
-
`);return`case ${$e(e.word)} in
|
|
788
|
-
${t}
|
|
789
|
-
esac${dt(e.redirections)}`}function Ip(e){let t=e.patterns.map($e).join(" | "),n=st(e.body);return n?`${t})
|
|
790
|
-
${n}
|
|
791
|
-
${e.terminator}`:`${t})
|
|
792
|
-
${e.terminator}`}function _p(e){return`(${st(e.body)})${dt(e.redirections)}`}function Tp(e){return`{ ${st(e.body)}; }${dt(e.redirections)}`}function Lp(e){return`((${fe(e.expression.expression)}))${dt(e.redirections)}`}function Mp(e){return`[[ ${cn(e.expression)} ]]${dt(e.redirections)}`}function Bp(e){let t=Iu(e.body);return`${e.name}() ${t}${dt(e.redirections)}`}function fe(e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return e.hasDollarPrefix?`$${e.name}`:e.name;case"ArithSpecialVar":return`$${e.name}`;case"ArithBinary":return`${fe(e.left)} ${e.operator} ${fe(e.right)}`;case"ArithUnary":return e.prefix?`${e.operator}${fe(e.operand)}`:`${fe(e.operand)}${e.operator}`;case"ArithTernary":return`${fe(e.condition)} ? ${fe(e.consequent)} : ${fe(e.alternate)}`;case"ArithAssignment":return`${e.subscript?`${e.variable}[${fe(e.subscript)}]`:e.stringKey!==void 0?`${e.variable}[${e.stringKey}]`:e.variable} ${e.operator} ${fe(e.value)}`;case"ArithDynamicAssignment":return`${e.subscript?`${fe(e.target)}[${fe(e.subscript)}]`:fe(e.target)} ${e.operator} ${fe(e.value)}`;case"ArithDynamicElement":return`${fe(e.nameExpr)}[${fe(e.subscript)}]`;case"ArithGroup":return`(${fe(e.expression)})`;case"ArithNested":return`$((${fe(e.expression)}))`;case"ArithCommandSubst":return`$(${e.command})`;case"ArithBracedExpansion":return`\${${e.content}}`;case"ArithArrayElement":return e.stringKey!==void 0?`${e.array}[${e.stringKey}]`:e.index?`${e.array}[${fe(e.index)}]`:e.array;case"ArithDynamicBase":return`\${${e.baseExpr}}#${e.value}`;case"ArithDynamicNumber":return`\${${e.prefix}}${e.suffix}`;case"ArithConcat":return e.parts.map(fe).join("");case"ArithDoubleSubscript":return`${e.array}[${fe(e.index)}]`;case"ArithNumberSubscript":return`${e.number}[${e.errorToken}]`;case"ArithSyntaxError":return e.errorToken;case"ArithSingleQuote":return`'${e.content}'`;default:{let t=e;throw new Error(`Unsupported arithmetic expression type: ${t.type}`)}}}function cn(e){switch(e.type){case"CondBinary":return`${$e(e.left)} ${e.operator} ${$e(e.right)}`;case"CondUnary":return`${e.operator} ${$e(e.operand)}`;case"CondNot":return`! ${cn(e.operand)}`;case"CondAnd":return`${cn(e.left)} && ${cn(e.right)}`;case"CondOr":return`${cn(e.left)} || ${cn(e.right)}`;case"CondGroup":return`( ${cn(e.expression)} )`;case"CondWord":return $e(e.word);default:{let t=e;throw new Error(`Unsupported conditional expression type: ${t.type}`)}}}var fr=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;jsBootstrapCode;invokeToolFn;transformPlugins=[];state;constructor(t={}){this.limits=Ar({...t.executionLimits,...t.maxCallDepth!==void 0&&{maxCallDepth:t.maxCallDepth},...t.maxCommandCount!==void 0&&{maxCommandCount:t.maxCommandCount},...t.maxLoopIterations!==void 0&&{maxLoopIterations:t.maxLoopIterations}},t.executionLimitProfile);let n=t.fs??new $t(t.files,{maxTotalBytes:this.limits.maxFileSystemBytes});this.fs=n,this.useDefaultLayout=!t.cwd&&!t.files;let r=t.cwd||(this.useDefaultLayout?"/home/user":"/"),s=new Map([["HOME",this.useDefaultLayout?"/home/user":"/"],["PATH","/usr/bin:/bin"],["IFS",`
|
|
793
|
-
`],["OSTYPE","linux-gnu"],["MACHTYPE","x86_64-pc-linux-gnu"],["HOSTTYPE","x86_64"],["HOSTNAME","localhost"],["PWD",r],["OLDPWD",r],["OPTIND","1"],...Object.entries(t.env??{})]);if(t.fetch?this.secureFetch=t.fetch:t.network&&(this.secureFetch=Ca(t.network)),this.sleepFn=t.sleep,this.traceFn=t.trace,this.logger=t.logger,this.defenseInDepthConfig=t.defenseInDepth??!0,this.coverageWriter=t.coverage,this.state={env:s,arrays:new Map,cwd:r,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:"",startTime:Date.now(),lastBackgroundPid:0,virtualPid:t.processInfo?.pid??1,virtualPpid:t.processInfo?.ppid??0,virtualUid:t.processInfo?.uid??1e3,virtualGid:t.processInfo?.gid??1e3,bashPid:t.processInfo?.pid??1,nextVirtualPid:(t.processInfo?.pid??1)+1,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1,posix:!1,allexport:!1,noclobber:!1,noglob:!1,noexec:!1,vi:!1,emacs:!1},shoptOptions:{extglob:!1,dotglob:!1,nullglob:!1,failglob:!1,globstar:!1,globskipdots:!0,nocaseglob:!1,nocasematch:!1,expand_aliases:!1,lastpipe:!1,xpg_echo:!1},inCondition:!1,loopDepth:0,exportedVars:new Set(["HOME","PATH","PWD","OLDPWD",...Object.keys(t.env||{})]),readonlyVars:new Set(["SHELLOPTS","BASHOPTS"]),hashTable:new Map},this.state.env.set("SHELLOPTS",Vs(this.state.options)),this.state.env.set("BASHOPTS",zs(this.state.shoptOptions)),Ja(n,this.useDefaultLayout,{pid:this.state.virtualPid,ppid:this.state.virtualPpid,uid:this.state.virtualUid,gid:this.state.virtualGid}),r!=="/"&&n instanceof $t)try{n.mkdirSync(r,{recursive:!0})}catch{}for(let a of Ba(t.commands))this.registerBundledCommand(a);if(t.fetch||t.network)for(let a of Wa())this.registerBundledCommand(a);if(t.python)for(let a of Fa())this.registerBundledCommand(a);let i=typeof t.javascript=="object"?t.javascript:Object.create(null);if(t.javascript||i.invokeTool){for(let a of Va())this.registerBundledCommand(a);i.bootstrap&&(this.jsBootstrapCode=i.bootstrap),i.invokeTool&&(this.invokeToolFn=i.invokeTool)}if(t.customCommands)for(let a of t.customCommands)if(Ga(a)){let o=Za(a);this.registerCommandInternal(o,!0)}else this.registerCommandInternal(a,!0)}registerCommand(t){this.registerCommandInternal(t,!0)}registerBundledCommand(t){this.registerCommandInternal(t,!1)}registerCommandInternal(t,n,r=n?t.trusted??!0:t.trusted){this.commands.set(t.name,{name:t.name,trusted:r,internalIsExtension:n,execute:(i,a)=>t.execute(i,a)});let s=this.fs;if(typeof s.writeFileSync=="function"){let i=`#!/bin/bash
|
|
794
|
+
`)}`)}let n=[];for(let E of t)typeof E=="object"&&E.transform&&E.transform.length>0&&n.push(E);function r(E){if(n.length===0)return null;let b=null;for(let g of n)if(la(E,g.url)&&g.transform){b||(b=new Headers);for(let y of g.transform)for(let[S,v]of Object.entries(y.headers))b.set(S,v)}return b}if(e.maxRedirects!==void 0&&(!Number.isSafeInteger(e.maxRedirects)||e.maxRedirects<0))throw new RangeError("maxRedirects must be a non-negative safe integer");let s=e.maxRedirects??Zm,i=e.timeoutMs??Hm,o=e.maxResponseSize??Qm,a=e.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:e.allowedMethods??Km,l=e.denyPrivateRanges??(typeof process<"u"&&process.env?.NODE_ENV==="production"),c=e._dnsResolve??Gm,u=e._createConnectionOwner??Nf;function f(E){let b=E.startsWith("[")&&E.endsWith("]")?E.slice(1,-1):E;if(/^(?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3}$/.test(b)&&b.split(".").every(y=>Number(y)<=255))return 4;if(b.includes(":")&&!b.includes("%"))try{if(new URL(`http://[${b}]/`).hostname.length>2)return 6}catch{}return null}function d(E,b,g){let{address:y,family:S}=g;if(f(y)!==S)throw new rt(E,"DNS returned an invalid address for private IP check");return{hostname:b,address:y,family:S}}async function p(E,b){if(Rf(b),!e.dangerouslyAllowFullInternetAccess&&!xf(E,t))throw new rt(E);if(!l)return null;let g;try{g=new URL(E)}catch{throw new rt(E,"invalid URL")}if(ca(g.hostname))throw new rt(E,"private/loopback IP address blocked");let y=g.hostname;if(f(y)!==null)return null;let S;try{S=await ln(c(y),b)}catch{throw b?.aborted?Hn(b):new rt(E,"DNS resolution failed for private IP check")}if(!Array.isArray(S)||S.length===0)throw new rt(E,"DNS resolution returned no addresses for private IP check");let v=S.map(k=>d(E,y,k));for(let{address:k}of v)if(ca(k))throw new rt(E,"hostname resolves to private/loopback IP address");return v[0]}function h(E){if(e.dangerouslyAllowFullInternetAccess)return;let b=E.toUpperCase();if(!a.includes(b))throw new Vs(b,a)}async function m(E,b={}){let g=b.method?.toUpperCase()??"GET",y=b.followRedirects??!0;if(b.maxRedirects!==void 0&&(!Number.isSafeInteger(b.maxRedirects)||b.maxRedirects<0))throw new RangeError("maxRedirects must be a non-negative safe integer");let S=b.maxRedirects??s,v=Math.min(s,S),k=b.timeoutMs!==void 0?Math.min(b.timeoutMs,i):i,A=new AbortController,$=$r(()=>A.abort(new DOMException("The operation was aborted","AbortError")),k),N=Nr(b.signal,A.signal);try{let P=await p(E,N.signal);h(g);let C=E,O=0;for(;;){Rf(N.signal);let U;try{let X=await Le.runTrustedAsync(async()=>{let R=r(C),z=ty(b.headers,R),q={method:g,headers:z,signal:N.signal,redirect:"manual"};if(b.body&&!Xm.has(g)&&(q.body=b.body),!P)return await ln(fetch(C,q),N.signal);try{return U=await Jm(u(P),N.signal),await ln(U.fetch(C,q),N.signal)}catch(_){throw _ instanceof an?new rt(C,"DNS pinning unavailable for private IP enforcement"):_}});if(Ym.has(X.status)&&y){let R=X.headers.get("location");if(!R)return await Of(X,C,o,N.signal);let z=new URL(R,C).href;await ln(ey(X),N.signal);try{P=await p(z,N.signal)}catch{throw N.signal?.aborted?Hn(N.signal):new Gn(z)}if(O++,O>v)throw new jn(v);C=z;continue}return await Of(X,C,o,N.signal)}finally{if(U){let X=U,R=Le.runTrustedAsync(()=>X.close());await ln(R,N.signal)}}}}finally{Cr($),N.cleanup()}}return m}function ty(e,t){if(!e&&!t)return;if(!t)return e;let n=e instanceof Headers?new Headers(e):new Headers(e);for(let[r,s]of t)n.set(r,s);return n}async function Of(e,t,n,r){let s=Object.create(null);if(e.headers.forEach((o,a)=>{s[a.toLowerCase()]=o}),n>0){let o=e.headers.get("content-length");if(o){let a=parseInt(o,10);if(!Number.isNaN(a)&&a>n)throw new Zn(n)}}let i;if(n>0&&e.body){let o=e.body.getReader(),a=[],l=0;try{for(;;){let{done:u,value:f}=await ln(o.read(),r);if(u)break;if(f){if(l+=f.byteLength,l>n)throw await o.cancel(),new Zn(n);a.push(f)}}}catch(u){throw r?.aborted&&await o.cancel(Hn(r)).catch(()=>{}),u}i=new Uint8Array(l);let c=0;for(let u of a)i.set(u,c),c+=u.byteLength}else{let o=await ln(e.arrayBuffer(),r);if(n>0&&o.byteLength>n)throw new Zn(n);i=new Uint8Array(o)}return{status:e.status,statusText:e.statusText,headers:s,body:i,url:t}}function Pr(e,t){if(e.length>t||B(e)>t)throw new x(`script input size limit exceeded (${t} bytes)`,"string_length")}var xr=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;jsBootstrapCode;invokeToolFn;transformPlugins=[];state;constructor(t={}){this.limits=Lr({...t.executionLimits,...t.maxCallDepth!==void 0&&{maxCallDepth:t.maxCallDepth},...t.maxCommandCount!==void 0&&{maxCommandCount:t.maxCommandCount},...t.maxLoopIterations!==void 0&&{maxLoopIterations:t.maxLoopIterations}},t.executionLimitProfile);let n=t.fs??new ft(t.files,{maxTotalBytes:this.limits.maxFileSystemBytes});this.fs=n,this.useDefaultLayout=!t.cwd&&!t.files;let r=t.cwd||(this.useDefaultLayout?"/home/user":"/"),s=new Map([["HOME",this.useDefaultLayout?"/home/user":"/"],["PATH","/usr/bin:/bin"],["IFS",`
|
|
795
|
+
`],["OSTYPE","linux-gnu"],["MACHTYPE","x86_64-pc-linux-gnu"],["HOSTTYPE","x86_64"],["HOSTNAME","localhost"],["PWD",r],["OLDPWD",r],["OPTIND","1"],...Object.entries(t.env??{})]);if(t.fetch?this.secureFetch=t.fetch:t.network&&(this.secureFetch=ua(t.network)),this.sleepFn=t.sleep,this.traceFn=t.trace,this.logger=t.logger,this.defenseInDepthConfig=t.defenseInDepth??!0,this.coverageWriter=t.coverage,this.state={env:s,arrays:new Map,cwd:r,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:"",startTime:Date.now(),lastBackgroundPid:0,virtualPid:t.processInfo?.pid??1,virtualPpid:t.processInfo?.ppid??0,virtualUid:t.processInfo?.uid??1e3,virtualGid:t.processInfo?.gid??1e3,bashPid:t.processInfo?.pid??1,nextVirtualPid:(t.processInfo?.pid??1)+1,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1,posix:!1,allexport:!1,noclobber:!1,noglob:!1,noexec:!1,vi:!1,emacs:!1},shoptOptions:{extglob:!1,dotglob:!1,nullglob:!1,failglob:!1,globstar:!1,globskipdots:!0,nocaseglob:!1,nocasematch:!1,expand_aliases:!1,lastpipe:!1,xpg_echo:!1},inCondition:!1,loopDepth:0,exportedVars:new Set(["HOME","PATH","PWD","OLDPWD",...Object.keys(t.env||{})]),readonlyVars:new Set(["SHELLOPTS","BASHOPTS"]),hashTable:new Map},this.state.env.set("SHELLOPTS",si(this.state.options)),this.state.env.set("BASHOPTS",ii(this.state.shoptOptions)),Ia(n,this.useDefaultLayout,{pid:this.state.virtualPid,ppid:this.state.virtualPpid,uid:this.state.virtualUid,gid:this.state.virtualGid}),r!=="/"&&n instanceof ft)try{n.mkdirSync(r,{recursive:!0})}catch{}for(let o of wa(t.commands))this.registerBundledCommand(o);if(t.fetch||t.network)for(let o of Ea())this.registerBundledCommand(o);if(t.python)for(let o of ba())this.registerBundledCommand(o);let i=typeof t.javascript=="object"?t.javascript:Object.create(null);if(t.javascript||i.invokeTool){for(let o of Sa())this.registerBundledCommand(o);i.bootstrap&&(this.jsBootstrapCode=i.bootstrap),i.invokeTool&&(this.invokeToolFn=i.invokeTool)}if(t.customCommands)for(let o of t.customCommands)if(xa(o)){let a=$a(o);this.registerCommandInternal(a,!0)}else this.registerCommandInternal(o,!0)}registerCommand(t){this.registerCommandInternal(t,!0)}registerBundledCommand(t){this.registerCommandInternal(t,!1)}registerCommandInternal(t,n,r=n?t.trusted??!0:t.trusted){this.commands.set(t.name,{name:t.name,trusted:r,internalIsExtension:n,execute:(i,o)=>t.execute(i,o)});let s=this.fs;if(typeof s.writeFileSync=="function"){let i=`#!/bin/bash
|
|
794
796
|
# Built-in command: ${t.name}
|
|
795
|
-
`;try{s.writeFileSync(`/bin/${t.name}`,i)}catch{}try{s.writeFileSync(`/usr/bin/${t.name}`,i)}catch{}}}logResult(t){return this.logger&&(t.stdout&&this.logger.debug("stdout",{output:t.stdout}),t.stderr&&this.logger.info("stderr",{output:t.stderr}),this.logger.info("exit",{exitCode:t.exitCode})),t.stdout=
|
|
796
|
-
`,exitCode:126}}return t.trim()?this.logResult(i):i}async execInScope(t,n,r,s,i,
|
|
797
|
-
`,exitCode:1,env:
|
|
798
|
-
`,exitCode:2,env:
|
|
799
|
-
`,exitCode:2,env:
|
|
800
|
-
`,exitCode:1,env:
|
|
801
|
-
`),n=[],r=[],s="none";for(let i=0;i<t.length;i++){let
|
|
802
|
-
`)}var Fp=new TextDecoder("utf-8",{fatal:!0});function Bu(e){if(!e)return e;let t=!1;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);if(s>255)return e;s>127&&(t=!0)}if(!t)return e;let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);try{return Fp.decode(n)}catch{return e}}function Vp(e,t,n,r,s,i){if(e===void 0)return;let a=t==="bytes"?e.length:M(e);if(a>n||a>r)throw new P(`stdin size limit exceeded (${Math.min(n,r)} bytes)`,"string_length");return i||s.consumeInput(a,"stdin"),t==="bytes"?e:Dt(e)}var xs=class{baseFs;mounts=new Map;constructor(t){if(this.baseFs=t?.base??new $t,t?.mounts)for(let{mountPoint:n,filesystem:r}of t.mounts)this.mount(n,r)}mount(t,n){this.validateMountPath(t);let r=B(t);this.validateMount(r),this.mounts.set(r,{mountPoint:r,filesystem:n})}unmount(t){let n=B(t);if(!this.mounts.has(n))throw new Error(`No filesystem mounted at '${t}'`);this.mounts.delete(n)}getMounts(){return Array.from(this.mounts.values()).map(t=>({mountPoint:t.mountPoint,filesystem:t.filesystem}))}isMountPoint(t){let n=B(t);return this.mounts.has(n)}validateMountPath(t){let n=t.split("/");for(let r of n)if(r==="."||r==="..")throw new Error(`Invalid mount point '${t}': contains '.' or '..' segments`)}validateMount(t){if(t==="/")throw new Error("Cannot mount at root '/'");for(let n of this.mounts.keys())if(n!==t){if(t.startsWith(`${n}/`))throw new Error(`Cannot mount at '${t}': inside existing mount '${n}'`);if(n.startsWith(`${t}/`))throw new Error(`Cannot mount at '${t}': would contain existing mount '${n}'`)}}routePath(t){F(t,"access");let n=B(t),r=null,s=0;for(let i of this.mounts.values()){let a=i.mountPoint;if(n===a)return{fs:i.filesystem,relativePath:"/"};n.startsWith(`${a}/`)&&a.length>s&&(r=i,s=a.length)}if(r){let i=n.slice(s);return{fs:r.filesystem,relativePath:i||"/"}}return{fs:this.baseFs,relativePath:n}}getChildMountPoints(t){let n=B(t),r=n==="/"?"/":`${n}/`,s=[];for(let i of this.mounts.keys())if(i.startsWith(r)){let o=i.slice(r.length).split("/")[0];o&&!s.includes(o)&&s.push(o)}return s}async readFile(t,n){let{fs:r,relativePath:s}=this.routePath(t);return r.readFile(s,n)}async readFileBytes(t){let{fs:n,relativePath:r}=this.routePath(t);return mr(n,r)}async readFileBuffer(t){let{fs:n,relativePath:r}=this.routePath(t);return n.readFileBuffer(r)}async writeFile(t,n,r){let{fs:s,relativePath:i}=this.routePath(t);return s.writeFile(i,n,r)}async appendFile(t,n,r){let{fs:s,relativePath:i}=this.routePath(t);return s.appendFile(i,n,r)}async exists(t){let n=B(t);if(this.mounts.has(n)||this.getChildMountPoints(n).length>0)return!0;let{fs:s,relativePath:i}=this.routePath(t);return s.exists(i)}async stat(t){let n=B(t),r=this.mounts.get(n);if(r)try{return await r.filesystem.stat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(n).length>0)try{return await this.baseFs.stat(n)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:a}=this.routePath(t);return i.stat(a)}async lstat(t){let n=B(t),r=this.mounts.get(n);if(r)try{return await r.filesystem.lstat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(n).length>0)try{return await this.baseFs.lstat(n)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:a}=this.routePath(t);return i.lstat(a)}async mkdir(t,n){let r=B(t);if(this.mounts.has(r)){if(n?.recursive)return;throw new Error(`EEXIST: directory already exists, mkdir '${t}'`)}if(this.getChildMountPoints(r).length>0&&n?.recursive)return;let{fs:i,relativePath:a}=this.routePath(t);return i.mkdir(a,n)}async readdir(t){let n=B(t),r=new Set,s=null,{fs:i,relativePath:a}=this.routePath(t);try{let l=await i.readdir(a);for(let c of l)r.add(c)}catch(l){let c=l.code,u=l.message||"";if(c!=="ENOENT"&&!u.includes("ENOENT"))throw l;s=l}let o=this.getChildMountPoints(n);for(let l of o)r.add(l);if(r.size===0&&s&&!this.mounts.has(n))throw s;return Array.from(r).sort()}async rm(t,n){let r=B(t);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot remove '${t}'`);if(this.getChildMountPoints(r).length>0)throw new Error(`EBUSY: contains mount points, cannot remove '${t}'`);let{fs:i,relativePath:a}=this.routePath(t);return i.rm(a,n)}async cp(t,n,r){if((await this.stat(t)).isDirectory&&vt(t,n))throw new Error(`EINVAL: cannot copy '${t}' into itself, '${n}'`);let i=this.routePath(t),a=this.routePath(n);return i.fs===a.fs?i.fs.cp(i.relativePath,a.relativePath,r):this.crossMountCopy(t,n,r)}async mv(t,n){let r=B(t);if((await this.stat(t)).isDirectory&&vt(t,n))throw new Error(`EINVAL: cannot move '${t}' into itself, '${n}'`);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot move '${t}'`);let i=this.routePath(t),a=this.routePath(n);if(i.fs===a.fs)return i.fs.mv(i.relativePath,a.relativePath);await this.cp(t,n,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,n){return _t(t,n)}getAllPaths(){let t=new Set;for(let n of this.baseFs.getAllPaths())t.add(n);for(let n of this.mounts.keys()){let r=n.split("/").filter(Boolean),s="";for(let a of r)s=`${s}/${a}`,t.add(s);let i=this.mounts.get(n);if(i)for(let a of i.filesystem.getAllPaths())a==="/"?t.add(n):t.add(`${n}${a}`)}return Array.from(t).sort()}async chmod(t,n){let r=B(t),s=this.mounts.get(r);if(s)return s.filesystem.chmod("/",n);let{fs:i,relativePath:a}=this.routePath(t);return i.chmod(a,n)}async symlink(t,n){let{fs:r,relativePath:s}=this.routePath(n);return r.symlink(t,s)}async link(t,n){let r=this.routePath(t),s=this.routePath(n);if(r.fs!==s.fs)throw new Error(`EXDEV: cross-device link not permitted, link '${t}' -> '${n}'`);return r.fs.link(r.relativePath,s.relativePath)}async readlink(t){let{fs:n,relativePath:r}=this.routePath(t);return n.readlink(r)}async realpath(t){let n=B(t);if(this.mounts.get(n))return n;let{fs:s,relativePath:i}=this.routePath(t),a=await s.realpath(i);for(let[o,l]of this.mounts)if(n===o||n.startsWith(`${o}/`))return a==="/"?o:`${o}${a}`;return a}async crossMountCopy(t,n,r){let s=await this.lstat(t);if(s.isFile){let i=await this.readFileBuffer(t);await this.writeFile(n,i),await this.chmod(n,s.mode)}else if(s.isDirectory){if(!r?.recursive)throw new Error(`cp: ${t} is a directory (not copied)`);await this.mkdir(n,{recursive:!0});let i=await this.readdir(t);for(let a of i){let o=At(t,a),l=At(n,a);await this.crossMountCopy(o,l,r)}}else if(s.isSymbolicLink){let i=await this.readlink(t);await this.symlink(i,n)}}async utimes(t,n,r){let{fs:s,relativePath:i}=this.routePath(t);return s.utimes(i,n,r)}};import*as de from"node:fs";import*as Re from"node:path";import*as it from"node:fs";import*as Pe from"node:path";function Ge(e,t){let n=/^[A-Za-z]:[\\/]/.test(t)?Pe.win32:Pe.posix,r=n.relative(t,e);return r===""||r!==".."&&!r.startsWith(`..${n.sep}`)&&!n.isAbsolute(r)}function fn(e,t){try{let n=it.realpathSync(e);return Ge(n,t)?n:null}catch(n){if(n.code==="ENOENT"){let r=Pe.dirname(e);if(r===e)return null;let s=fn(r,t);if(s===null)return null;try{if(it.lstatSync(e).isSymbolicLink()){let a=it.readlinkSync(e),o=Pe.isAbsolute(a)?a:Pe.resolve(Pe.dirname(e),a);if(fn(o,t)===null)return null}}catch{}return Pe.join(s,Pe.basename(e))}return null}}function Ps(e,t,n){let r=fn(e,n);if(r===null)return null;let s=Pe.resolve(e),i=s.slice(t.length),a=r.slice(n.length);if(i!==a)return null;try{if(it.lstatSync(s).isSymbolicLink())return null}catch{}return r}function $s(e,t){if(!it.existsSync(e))throw new Error(`${t} root does not exist`);if(!it.statSync(e).isDirectory())throw new Error(`${t} root is not a directory`)}function Wu(e,t){if(!Pe.isAbsolute(e))return{withinRoot:!0,relativePath:e};let n;try{n=it.realpathSync(e)}catch{n=Pe.resolve(e)}return Ge(n,t)?{withinRoot:!0,relativePath:n.slice(t.length).replace(/\\/g,"/")||"/"}:{withinRoot:!1,safeName:Pe.basename(e)}}function ks(e,t,n,r){let s=e;if(s.path===void 0){for(let a of r)if(s.message?.includes(a))throw e}let i=s.code||"EIO";throw new Error(`${i}: ${n} '${t}'`)}var zp=["ELOOP","EFBIG","EPERM"],qp="/home/user/project",On=class{root;canonicalRoot;mountPoint;readOnly;maxFileReadSize;maxMemoryBytes;allowSymlinks;memory=new Map;deleted=new Set;nextMemoryIdentity=1;retainedMemoryBytes=0;memoryEntryBytes(t){if(!t||t.type!=="file")return 0;let n=t.content.byteLength;for(let r of t.appendChunks??[])n+=r.byteLength;return n}assertMemoryCapacity(t,n=0){if(!Number.isSafeInteger(t)||t<0||t>this.maxMemoryBytes-this.retainedMemoryBytes+n)throw new Error(`ENOSPC: overlay memory byte limit exceeded (${this.maxMemoryBytes} bytes)`)}setMemoryEntry(t,n){let r=this.memoryEntryBytes(this.memory.get(t)),s=this.memoryEntryBytes(n);this.assertMemoryCapacity(s,r),this.memory.set(t,n),this.retainedMemoryBytes+=s-r}deleteMemoryEntry(t){let n=this.memory.get(t);n&&(this.retainedMemoryBytes-=this.memoryEntryBytes(n),this.memory.delete(t))}identityFor(t){return t.type==="symlink"?"":(t.identity||(t.identity=`overlay:${this.nextMemoryIdentity++}`),t.identity)}constructor(t){this.root=Re.resolve(t.root);let n=t.mountPoint??qp;if(this.mountPoint=n==="/"?"/":n.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${n}`);if(this.readOnly=t.readOnly??!1,this.maxFileReadSize=t.maxFileReadSize??10485760,this.maxMemoryBytes=t.maxMemoryBytes??1024*1024*1024,!Number.isSafeInteger(this.maxMemoryBytes)||this.maxMemoryBytes<0)throw new Error("OverlayFs: invalid maxMemoryBytes");this.allowSymlinks=t.allowSymlinks??!1,$s(this.root,"OverlayFs"),this.canonicalRoot=de.realpathSync(this.root),this.createMountPointDirs()}assertWritable(t){if(this.readOnly)throw new Error(`EROFS: read-only file system, ${t}`)}createMountPointDirs(){let t=this.mountPoint.split("/").filter(Boolean),n="";for(let r of t)n+=`/${r}`,this.memory.has(n)||this.setMemoryEntry(n,{type:"directory",mode:493,mtime:new Date});this.memory.has("/")||this.setMemoryEntry("/",{type:"directory",mode:493,mtime:new Date})}getMountPoint(){return this.mountPoint}mkdirSync(t,n){let s=B(t).split("/").filter(Boolean),i="";for(let a of s)i+=`/${a}`,this.memory.has(i)||this.setMemoryEntry(i,{type:"directory",mode:493,mtime:new Date})}writeFileSync(t,n){let r=B(t),s=this.getDirname(r);s!=="/"&&this.mkdirSync(s);let i=n instanceof Uint8Array?n:new TextEncoder().encode(n);this.setMemoryEntry(r,{type:"file",content:i,mode:420,mtime:new Date})}getDirname(t){let n=t.lastIndexOf("/");return n===0?"/":t.slice(0,n)}getRelativeToMount(t){return this.mountPoint==="/"?t:t===this.mountPoint?"/":t.startsWith(`${this.mountPoint}/`)?t.slice(this.mountPoint.length):null}toRealPath(t){let n=B(t),r=this.getRelativeToMount(n);if(r===null)return null;let s=Re.join(this.root,r),i=Re.resolve(s);return Ge(i,this.root)?i:null}resolveRealPath_(t){return t?this.allowSymlinks?fn(t,this.canonicalRoot):Ps(t,this.root,this.canonicalRoot):null}resolveRealPathParent_(t){if(!t)return null;let n=Re.dirname(t),r=this.resolveRealPath_(n);return r===null?null:Re.join(r,Re.basename(t))}sanitizeError(t,n,r){ks(t,n,r,zp)}ensureParentDirs(t){let n=pn(t);n!=="/"&&(this.memory.has(n)||(this.ensureParentDirs(n),this.setMemoryEntry(n,{type:"directory",mode:493,mtime:new Date})),this.deleted.delete(n))}async existsInOverlay(t){let n=B(t);if(this.deleted.has(n))return!1;if(this.memory.has(n))return!0;let r=this.resolveRealPathParent_(this.toRealPath(n));if(!r)return!1;try{return await de.promises.lstat(r),!0}catch{return!1}}async readFile(t,n){let r=await this.readFileBuffer(t),s=nt(n);return Pt(r,s)}async readFileBytes(t){let n=await this.readFileBuffer(t);return Pt(n,"binary")}async readFileBuffer(t,n=new Set){F(t,"open");let r=B(t);if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);if(n.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, open '${t}'`);let s=this.memory.get(r);if(s){if(s.type==="symlink"){let c=this.resolveSymlink(r,s.target);return this.readFileBuffer(c,n)}if(s.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(!s.appendChunks||s.appendChunks.length===0)return s.content;let a=s.appendChunks.reduce((c,u)=>c+u.byteLength,s.content.byteLength);if(!Number.isSafeInteger(a))throw new Error(`EFBIG: file too large, read '${t}'`);let o=new Uint8Array(a);o.set(s.content);let l=s.content.byteLength;for(let c of s.appendChunks)o.set(c,l),l+=c.byteLength;return s.content=o,s.appendChunks=void 0,o}let i=this.resolveRealPath_(this.toRealPath(r));if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let a=await de.promises.lstat(i);if(a.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, open '${t}'`);let c=await de.promises.readlink(i),u=this.realTargetToVirtual(r,c),f=this.resolveSymlink(r,u);return this.readFileBuffer(f,n)}if(a.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(this.maxFileReadSize>0&&a.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${a.size} bytes, max ${this.maxFileReadSize})`);let o=this.allowSymlinks?de.constants.O_RDONLY:de.constants.O_RDONLY|de.constants.O_NOFOLLOW,l=await de.promises.open(i,o);try{let c=await l.readFile();return new Uint8Array(c)}finally{await l.close()}}catch(a){let o=a.code;if(o==="ENOENT")throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(o==="ELOOP")throw new Error(`ENOENT: no such file or directory, open '${t}'`);this.sanitizeError(a,t,"open")}}async writeFile(t,n,r){F(t,"write"),this.assertWritable(`write '${t}'`);let s=B(t);this.ensureParentDirs(s);let i=nt(r),a=xt(n,i);this.setMemoryEntry(s,{type:"file",content:a,mode:420,mtime:new Date}),this.deleted.delete(s)}async appendFile(t,n,r){F(t,"append"),this.assertWritable(`append '${t}'`);let s=B(t),i=nt(r),a=xt(n,i),o=this.memory.get(s);if(o?.type==="file"){this.assertMemoryCapacity(a.byteLength),o.appendChunks||(o.appendChunks=[]),o.appendChunks.push(a),this.retainedMemoryBytes+=a.byteLength,o.mtime=new Date,this.deleted.delete(s);return}let l;try{l=await this.readFileBuffer(s)}catch{l=new Uint8Array(0)}this.ensureParentDirs(s),this.setMemoryEntry(s,{type:"file",content:l,appendChunks:[a],mode:420,mtime:new Date}),this.deleted.delete(s)}async exists(t){return t.includes("\0")?!1:this.existsInOverlay(t)}async stat(t,n=new Set){F(t,"stat");let r=B(t);if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, stat '${t}'`);if(n.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let s=this.memory.get(r);if(s){if(s.type==="symlink"){let o=this.resolveSymlink(r,s.target);return this.stat(o,n)}let a=0;return s.type==="file"&&(a=s.content.length+(s.appendChunks?.reduce((o,l)=>o+l.byteLength,0)??0)),{isFile:s.type==="file",isDirectory:s.type==="directory",isSymbolicLink:!1,mode:s.mode,size:a,mtime:s.mtime,identity:this.identityFor(s)}}let i=this.resolveRealPath_(this.toRealPath(r));if(!i)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);try{let a=await de.promises.lstat(i);if(a.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let o=await de.promises.readlink(i),l=this.realTargetToVirtual(r,o),c=this.resolveSymlink(r,l);return this.stat(c,n)}return{isFile:a.isFile(),isDirectory:a.isDirectory(),isSymbolicLink:!1,mode:a.mode,size:a.size,mtime:a.mtime,dev:a.dev,ino:a.ino}}catch(a){if(a.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, stat '${t}'`);this.sanitizeError(a,t,"stat")}}async lstat(t){F(t,"lstat");let n=B(t);if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);let r=this.memory.get(n);if(r){if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime};let i=0;return r.type==="file"&&(i=r.content.length+(r.appendChunks?.reduce((a,o)=>a+o.byteLength,0)??0)),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:i,mtime:r.mtime,identity:this.identityFor(r)}}let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);try{let i=await de.promises.lstat(s);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink(),mode:i.mode,size:i.size,mtime:i.mtime,dev:i.dev,ino:i.ino}}catch(i){if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);this.sanitizeError(i,t,"lstat")}}resolveSymlink(t,n){return mn(t,n)}realTargetToVirtual(t,n){let r=Wu(n,this.canonicalRoot);if(r.withinRoot){if(!Re.isAbsolute(n))return n;let s=r.relativePath;return this.mountPoint==="/"?s:`${this.mountPoint}${s}`}return r.safeName}async mkdir(t,n){F(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let r=B(t);if(await this.existsInOverlay(r)){if(!n?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${t}'`);return}let i=pn(r);if(i!=="/"&&!await this.existsInOverlay(i))if(n?.recursive)await this.mkdir(i,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.setMemoryEntry(r,{type:"directory",mode:493,mtime:new Date}),this.deleted.delete(r)}async readdirCore(t,n){if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let r=new Map,s=new Set,i=n==="/"?"/":`${n}/`;for(let o of this.deleted)if(o.startsWith(i)){let l=o.slice(i.length),c=l.split("/")[0];c&&!l.includes("/",c.length)&&s.add(c)}for(let[o,l]of this.memory)if(o!==n&&o.startsWith(i)){let c=o.slice(i.length),u=c.split("/")[0];u&&!s.has(u)&&!c.includes("/",1)&&r.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}let a=this.resolveRealPath_(this.toRealPath(n));if(a)try{if(!this.allowSymlinks&&(await de.promises.lstat(a)).isSymbolicLink()){if(!this.memory.has(n))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);return r}let o=await de.promises.readdir(a,{withFileTypes:!0});for(let l of o)!s.has(l.name)&&!r.has(l.name)&&r.set(l.name,{name:l.name,isFile:l.isFile(),isDirectory:l.isDirectory(),isSymbolicLink:l.isSymbolicLink()})}catch(o){if(o.code==="ENOENT"){if(!this.memory.has(n))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`)}else o.code!=="ENOTDIR"&&this.sanitizeError(o,t,"scandir")}return r}async resolveForReaddir(t,n=!1){let r=B(t),s=new Set,i=n,a=this.memory.get(r);for(;a&&a.type==="symlink";){if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);s.add(r),i=!0,r=this.resolveSymlink(r,a.target),a=this.memory.get(r)}if(a)return{normalized:r,outsideOverlay:!1};if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let l=this.resolveRealPath_(this.toRealPath(r));if(!l)return{normalized:r,outsideOverlay:!0};try{if((await de.promises.lstat(l)).isSymbolicLink()){if(!this.allowSymlinks)return{normalized:r,outsideOverlay:!0};let u=await de.promises.readlink(l),f=this.realTargetToVirtual(r,u),d=this.resolveSymlink(r,f);return this.resolveForReaddir(d,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(t){F(t,"scandir");let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let s=await this.readdirCore(t,n);return Array.from(s.keys()).sort((i,a)=>i<a?-1:i>a?1:0)}async readdirWithFileTypes(t){F(t,"scandir");let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let s=await this.readdirCore(t,n);return Array.from(s.values()).sort((i,a)=>i.name<a.name?-1:i.name>a.name?1:0)}async rm(t,n){F(t,"rm"),this.assertWritable(`rm '${t}'`);let r=B(t);if(!await this.existsInOverlay(r)){if(n?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}try{if((await this.stat(r)).isDirectory){let a=await this.readdir(r);if(a.length>0){if(!n?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let o of a){let l=r==="/"?`/${o}`:`${r}/${o}`;await this.rm(l,n)}}}}catch(i){if(i instanceof Error&&(i.message.includes("ENOTEMPTY")||i.message.includes("EISDIR")))throw i}this.deleteMemoryEntry(r),this.existsOnRealFs(r)&&this.deleted.add(r)}existsOnRealFs(t){let n=this.toRealPath(t),r=this.resolveRealPathParent_(n);if(!r)return!1;try{return de.lstatSync(r),!0}catch{return!1}}async cp(t,n,r){F(t,"cp"),F(n,"cp"),this.assertWritable(`cp '${n}'`);let s=B(t),i=B(n);if(!await this.existsInOverlay(s))throw new Error(`ENOENT: no such file or directory, cp '${t}'`);let o=await this.stat(s);if(o.isFile){let l=await this.readFileBuffer(s);await this.writeFile(i,l)}else if(o.isDirectory){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);if(vt(s,i))throw new Error(`EINVAL: cannot copy '${t}' into itself, '${n}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(s);for(let c of l){let u=s==="/"?`/${c}`:`${s}/${c}`,f=i==="/"?`/${c}`:`${i}/${c}`;await this.cp(u,f,r)}}}async mv(t,n){this.assertWritable(`mv '${n}'`),await this.cp(t,n,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,n){return _t(t,n)}getAllPaths(){let t=new Set(this.memory.keys());for(let n of this.deleted)t.delete(n);return this.scanRealFs("/",t),Array.from(t)}scanRealFs(t,n){if(this.deleted.has(t))return;let r=this.resolveRealPath_(this.toRealPath(t));if(r)try{let s=de.readdirSync(r);for(let i of s){let a=t==="/"?`/${i}`:`${t}/${i}`;if(this.deleted.has(a))continue;n.add(a);let o=Re.join(r,i);de.lstatSync(o).isDirectory()&&this.scanRealFs(a,n)}}catch{}}async chmod(t,n){F(t,"chmod"),this.assertWritable(`chmod '${t}'`);let r=B(t);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);let i=this.memory.get(r);if(i){i.mode=n;return}let a=await this.stat(r);if(a.isFile){let o=await this.readFileBuffer(r);this.setMemoryEntry(r,{type:"file",content:o,mode:n,mtime:new Date})}else a.isDirectory&&this.setMemoryEntry(r,{type:"directory",mode:n,mtime:new Date})}async symlink(t,n){if(!this.allowSymlinks)throw new Error(`EPERM: operation not permitted, symlink '${n}'`);F(n,"symlink"),this.assertWritable(`symlink '${n}'`);let r=B(n);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.setMemoryEntry(r,{type:"symlink",target:t,mode:511,mtime:new Date}),this.deleted.delete(r)}async link(t,n){F(t,"link"),F(n,"link"),this.assertWritable(`link '${n}'`);let r=B(t),s=B(n);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, link '${t}'`);let a=await this.stat(r);if(!a.isFile)throw new Error(`EPERM: operation not permitted, link '${t}'`);if(await this.existsInOverlay(s))throw new Error(`EEXIST: file already exists, link '${n}'`);let l=await this.readFileBuffer(r);this.ensureParentDirs(s),this.setMemoryEntry(s,{type:"file",content:l,mode:a.mode,mtime:new Date,identity:a.identity??`overlay:${this.nextMemoryIdentity++}`}),this.deleted.delete(s)}async readlink(t){F(t,"readlink");let n=B(t);if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);let r=this.memory.get(n);if(r){if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return r.target}let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);try{let i=await de.promises.readlink(s);if(!Re.isAbsolute(i)){let a=Re.resolve(Re.dirname(s),i),o;try{o=de.realpathSync(a)}catch{o=a}if(!Ge(o,this.canonicalRoot))return Re.basename(i)}return this.realTargetToVirtual(n,i)}catch(i){if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(i.code==="EINVAL")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);this.sanitizeError(i,t,"readlink")}}async realpath(t){F(t,"realpath");let n=B(t),r=new Set,s=async o=>{let l=o==="/"?[]:o.slice(1).split("/"),c="";for(let u of l){if(c=`${c}/${u}`,r.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(c))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let f=this.memory.get(c),d=0,h=40;for(;f&&f.type==="symlink"&&d<h;){if(r.add(c),c=this.resolveSymlink(c,f.target),d++,r.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(c))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);f=this.memory.get(c)}if(d>=h)throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(!f){let p=this.toRealPath(c),m=this.resolveRealPath_(p);if(m)try{if((await de.promises.lstat(m)).isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let b=await de.promises.readlink(m),g=this.realTargetToVirtual(c,b);return r.add(c),c=this.resolveSymlink(c,g),s(c)}}catch(E){if(E.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);this.sanitizeError(E,t,"realpath")}else if(!this.allowSymlinks){let E=this.resolveRealPathParent_(p);if(E)try{if((await de.promises.lstat(E)).isSymbolicLink())throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}catch(b){if(b.message?.includes("ENOENT")||b.message?.includes("ELOOP"))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);this.sanitizeError(b,t,"realpath")}}}}return c||"/"},i=await s(n);if(!await this.existsInOverlay(i))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return i}async utimes(t,n,r){F(t,"utimes"),this.assertWritable(`utimes '${t}'`);let s=B(t);if(!await this.existsInOverlay(s))throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);let a=this.memory.get(s);if(a){a.mtime=r;return}let o=await this.stat(s);if(o.isFile){let l=await this.readFileBuffer(s);this.setMemoryEntry(s,{type:"file",content:l,mode:o.mode,mtime:r})}else o.isDirectory&&this.setMemoryEntry(s,{type:"directory",mode:o.mode,mtime:r})}};import*as T from"node:fs";import*as se from"node:path";var Up=["EACCES","escaping sandbox","EFBIG"],Ns=class{root;canonicalRoot;maxFileReadSize;allowSymlinks;transactionId=0;constructor(t){this.root=se.resolve(t.root),this.maxFileReadSize=t.maxFileReadSize??10485760,this.allowSymlinks=t.allowSymlinks??!1,$s(this.root,"ReadWriteFs"),this.canonicalRoot=T.realpathSync(this.root)}resolveAndValidate(t,n){let r=this.allowSymlinks?fn(t,this.canonicalRoot):Ps(t,this.root,this.canonicalRoot);if(r===null)throw new Error(`EACCES: permission denied, '${n}' resolves outside sandbox`);return r}validateParent(t,n){let r=se.dirname(t),s=this.resolveAndValidate(r,n);return se.join(s,se.basename(t))}toRealPath(t){let n=B(t),r=se.join(this.root,n);return se.resolve(r)}async readFile(t,n){let r=await this.readFileBuffer(t),s=nt(n);return Pt(r,s)}async readFileBytes(t){let n=await this.readFileBuffer(t);return Pt(n,"binary")}async readFileBuffer(t){F(t,"open");let n=this.toRealPath(t),r=this.resolveAndValidate(n,t);try{let s=this.allowSymlinks?T.constants.O_RDONLY:T.constants.O_RDONLY|T.constants.O_NOFOLLOW,i=await T.promises.open(r,s);try{if(this.maxFileReadSize>0){let o=await i.stat();if(o.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${o.size} bytes, max ${this.maxFileReadSize})`)}let a=await i.readFile();return new Uint8Array(a)}finally{await i.close()}}catch(s){let i=s;if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(i.code==="EISDIR")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(i.code==="ELOOP")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(s,t,"open")}}async writeFile(t,n,r){F(t,"write");let s=this.toRealPath(t),i=this.resolveAndValidate(s,t),a=nt(r),o=xt(n,a),l=se.dirname(i);try{await T.promises.mkdir(l,{recursive:!0}),i=this.resolveAndValidate(s,t);let c=this.allowSymlinks?0:T.constants.O_NOFOLLOW,u=T.constants.O_WRONLY|T.constants.O_CREAT|T.constants.O_TRUNC|c,f=await T.promises.open(i,u,438);try{await f.writeFile(o)}finally{await f.close()}}catch(c){if(c.code==="ELOOP")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(c,t,"write")}}async appendFile(t,n,r){F(t,"append");let s=this.toRealPath(t),i=this.resolveAndValidate(s,t),a=nt(r),o=xt(n,a),l=se.dirname(i);try{await T.promises.mkdir(l,{recursive:!0}),i=this.resolveAndValidate(s,t);let c=this.allowSymlinks?0:T.constants.O_NOFOLLOW,u=T.constants.O_WRONLY|T.constants.O_CREAT|T.constants.O_APPEND|c,f=await T.promises.open(i,u,438);try{await f.writeFile(o)}finally{await f.close()}}catch(c){if(c.code==="ELOOP")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(c,t,"append")}}async exists(t){if(t.includes("\0"))return!1;let n=this.toRealPath(t);try{let r=this.resolveAndValidate(n,t);return await T.promises.access(r),!0}catch{return!1}}async stat(t){F(t,"stat");let n=this.toRealPath(t),r=this.resolveAndValidate(n,t);try{let s=await T.promises.lstat(r);if(!this.allowSymlinks&&s.isSymbolicLink())throw new Error(`EACCES: permission denied, '${t}' is a symlink`);return{isFile:s.isFile(),isDirectory:s.isDirectory(),isSymbolicLink:s.isSymbolicLink(),mode:s.mode,size:s.size,mtime:s.mtime,dev:s.dev,ino:s.ino,identity:`real:${s.dev}:${s.ino}`}}catch(s){if(s.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, stat '${t}'`);this.sanitizeError(s,t,"stat")}}async lstat(t){F(t,"lstat");let n=this.toRealPath(t),r=this.validateParent(n,t);try{let s=await T.promises.lstat(r);return{isFile:s.isFile(),isDirectory:s.isDirectory(),isSymbolicLink:s.isSymbolicLink(),mode:s.mode,size:s.size,mtime:s.mtime,dev:s.dev,ino:s.ino,identity:`real:${s.dev}:${s.ino}`}}catch(s){if(s.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);this.sanitizeError(s,t,"lstat")}}async mkdir(t,n){F(t,"mkdir");let r=this.toRealPath(t),s=this.resolveAndValidate(r,t);try{await T.promises.mkdir(s,{recursive:n?.recursive})}catch(i){let a=i;if(a.code==="EEXIST")throw new Error(`EEXIST: file already exists, mkdir '${t}'`);if(a.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.sanitizeError(i,t,"mkdir")}}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){F(t,"scandir");let n=this.toRealPath(t),r=this.resolveAndValidate(n,t);try{if(!this.allowSymlinks&&(await T.promises.lstat(r)).isSymbolicLink())throw new Error(`EACCES: permission denied, '${t}' is a symlink`);return(await T.promises.readdir(r,{withFileTypes:!0})).map(i=>({name:i.name,isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink()})).sort((i,a)=>i.name<a.name?-1:i.name>a.name?1:0)}catch(s){let i=s;if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);if(i.code==="ENOTDIR")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);this.sanitizeError(s,t,"scandir")}}async rm(t,n){F(t,"rm");let r=this.toRealPath(t),s=this.validateParent(r,t);try{let i=await T.promises.lstat(s);if(!this.allowSymlinks&&i.isSymbolicLink())throw new Error(`EACCES: permission denied, '${t}' is a symlink`);await T.promises.rm(s,{recursive:n?.recursive??!1,force:n?.force??!1})}catch(i){let a=i;if(a.code==="ENOENT"){if(n?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}if(a.code==="ENOTEMPTY")throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);this.sanitizeError(i,t,"rm")}}async cp(t,n,r){F(t,"cp"),F(n,"cp");let s=this.toRealPath(t),i=this.toRealPath(n),a=this.resolveAndValidate(s,t),o=this.resolveAndValidate(i,n),l;try{l=await T.promises.lstat(a)}catch(c){if(c.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, cp '${t}'`);this.sanitizeError(c,t,"cp")}if(l.isDirectory()&&Ge(o,a))throw new Error(`EINVAL: cannot copy '${t}' into itself, '${n}'`);try{await this.preflightCopyTree(a,t)}catch(c){this.sanitizeError(c,t,"cp")}try{await T.promises.cp(a,o,{recursive:r?.recursive??!1,filter:async c=>{try{if(T.lstatSync(c).isSymbolicLink()){let f=await T.promises.realpath(c).catch(()=>null);if(f===null||!Ge(f,this.canonicalRoot))throw new Error(`EACCES: permission denied, cp '${t}' contains an unsafe symlink`);return!0}return!0}catch(u){throw u.message?.includes("EACCES")||u.message?.includes("unsafe symlink")?u:new Error(`EIO: cp '${t}' could not validate source tree`)}}})}catch(c){let u=c;if(u.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, cp '${t}'`);if(u.code==="EISDIR")throw new Error(`EISDIR: is a directory, cp '${t}'`);this.sanitizeError(c,t,"cp")}}async preflightCopyTree(t,n,r=new Set){let s=await T.promises.lstat(t),i=`${s.dev}:${s.ino}`;if(r.has(i))throw new Error(`ELOOP: cp '${n}' contains a cycle`);if(s.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`EACCES: permission denied, cp '${n}' contains a symlink`);let a=await T.promises.realpath(t);if(!Ge(a,this.canonicalRoot))throw new Error(`EACCES: permission denied, cp '${n}' contains an unsafe symlink`);return}if(s.isDirectory()){r.add(i);try{let a=await T.promises.readdir(t);for(let o of a)await this.preflightCopyTree(se.join(t,o),n,r)}finally{r.delete(i)}}}async mv(t,n){F(t,"mv"),F(n,"mv");let r=this.toRealPath(t),s=this.toRealPath(n),i=this.validateParent(r,t),a=this.validateParent(s,n),o;try{o=await T.promises.lstat(i)}catch(c){if(c.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, mv '${t}'`);this.sanitizeError(c,t,"mv")}if(o.isDirectory()&&this.isSameOrDescendantIdentity(i,a))throw new Error(`EINVAL: cannot move '${t}' into itself, '${n}'`);try{if(o.isSymbolicLink()){let c=await T.promises.readlink(i),u=se.resolve(se.dirname(a),c),f=await T.promises.realpath(u).catch(()=>u);if(!Ge(f,this.canonicalRoot))throw new Error(`EACCES: permission denied, mv '${t}' -> '${n}' would create symlink escaping sandbox`)}}catch(c){let u=c;if(u.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, mv '${t}'`);if(u.message?.includes("EACCES")||u.message?.includes("escaping sandbox"))throw c}let l=se.dirname(a);try{await T.promises.mkdir(l,{recursive:!0})}catch(c){this.sanitizeError(c,n,"mv")}try{await T.promises.rename(i,a)}catch(c){let u=c;if(u.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, mv '${t}'`);if(u.code==="EXDEV"){await this.moveAcrossDevices(t,n);return}this.sanitizeError(c,t,"mv")}try{if(T.lstatSync(a).isDirectory()&&this.findEscapingSymlinks(a).length>0)throw await T.promises.rename(a,i),new Error(`EACCES: permission denied, mv '${t}' -> '${n}' would create symlinks escaping sandbox`)}catch(c){if(c.message?.includes("EACCES")||c.message?.includes("escaping sandbox"))throw c;await T.promises.rename(a,i).catch(()=>{}),this.sanitizeError(c,n,"mv")}}isSameOrDescendantIdentity(t,n){let r=t,s=n;try{r=T.realpathSync(t)}catch{}try{s=T.realpathSync(n)}catch{try{let i=T.realpathSync(se.dirname(n));s=se.join(i,se.basename(n))}catch{}}return Ge(s,r)}async uniqueTransactionPath(t,n){let r=se.posix.dirname(t);for(let s=0;s<100;s++){let i=this.transactionId++,a=se.posix.join(r,`.just-bash-mv-${n}-${i}`);if(!await this.exists(a))return a}throw new Error(`EEXIST: mv '${t}'`)}async moveAcrossDevices(t,n){let r=await this.uniqueTransactionPath(n,"stage"),s=await this.uniqueTransactionPath(n,"backup"),i=await this.uniqueTransactionPath(t,"source"),a=this.validateParent(this.toRealPath(r),r),o=this.validateParent(this.toRealPath(s),s),l=this.validateParent(this.toRealPath(t),t),c=this.validateParent(this.toRealPath(i),i),u=this.validateParent(this.toRealPath(n),n),f=!1,d=!1,h=!1,p=async()=>{h&&await T.promises.rename(c,l).catch(()=>{}),d&&await T.promises.rm(u,{recursive:!0,force:!0}).catch(()=>{}),f&&await T.promises.rename(o,u).catch(()=>{}),await T.promises.rm(a,{recursive:!0,force:!0}).catch(()=>{})};try{if(await this.cp(t,r,{recursive:!0}),this.findEscapingSymlinks(a).length>0)throw new Error(`EACCES: permission denied, mv '${t}' -> '${n}' would create symlinks escaping sandbox`);try{await T.promises.rename(u,o),f=!0}catch(m){if(m.code!=="ENOENT")throw m}await T.promises.rename(a,u),d=!0,await T.promises.rename(l,c),h=!0,await T.promises.rm(c,{recursive:!0,force:!1}),h=!1,f&&await T.promises.rm(o,{recursive:!0,force:!0}).catch(()=>{})}catch(m){await p(),this.sanitizeError(m,t,"mv")}}resolvePath(t,n){return _t(t,n)}getAllPaths(){let t=[];return this.scanDir("/",t),t}sanitizeError(t,n,r){ks(t,n,r,Up)}findEscapingSymlinks(t){let n=[],r=T.readdirSync(t);for(let s of r){let i=se.join(t,s),a=T.lstatSync(i);if(a.isSymbolicLink()){let o=T.readlinkSync(i),l=se.resolve(t,o),c;try{c=T.realpathSync(l)}catch(u){if(u.code!=="ENOENT")throw u;c=l}Ge(c,this.canonicalRoot)||n.push(i)}else a.isDirectory()&&n.push(...this.findEscapingSymlinks(i))}return n}scanDir(t,n){let r=this.toRealPath(t),s;try{s=this.resolveAndValidate(r,t)}catch{return}try{let i=T.readdirSync(s);for(let a of i){let o=t==="/"?`/${a}`:`${t}/${a}`;n.push(o);let l=se.join(s,a);T.lstatSync(l).isDirectory()&&this.scanDir(o,n)}}catch{}}async chmod(t,n){F(t,"chmod");let r=this.toRealPath(t),s=this.resolveAndValidate(r,t);try{let i=this.allowSymlinks?T.constants.O_RDONLY:T.constants.O_RDONLY|T.constants.O_NOFOLLOW,a=await T.promises.open(s,i);try{await a.chmod(n)}finally{await a.close()}}catch(i){let a=i;if(a.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);if(a.code==="ELOOP")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(i,t,"chmod")}}async symlink(t,n){if(!this.allowSymlinks)throw new Error(`EPERM: operation not permitted, symlink '${n}'`);F(n,"symlink");let r=this.toRealPath(n),s=this.validateParent(r,n),i=B(n),a=B(se.dirname(i)),o=t.startsWith("/")?B(t):B(a==="/"?`/${t}`:`${a}/${t}`),l=se.join(this.canonicalRoot,o),c=se.dirname(s),u=t.startsWith("/")?l:se.relative(c,l)||".";try{await T.promises.symlink(u,s)}catch(f){if(f.code==="EEXIST")throw new Error(`EEXIST: file already exists, symlink '${n}'`);this.sanitizeError(f,n,"symlink")}}async link(t,n){F(t,"link"),F(n,"link");let r=this.toRealPath(t),s=this.toRealPath(n),i=this.resolveAndValidate(r,t),a=this.resolveAndValidate(s,n);try{await T.promises.link(i,a)}catch(o){let l=o;if(l.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, link '${t}'`);if(l.code==="EEXIST")throw new Error(`EEXIST: file already exists, link '${n}'`);if(l.code==="EPERM")throw new Error(`EPERM: operation not permitted, link '${t}'`);this.sanitizeError(o,t,"link")}}async readlink(t){F(t,"readlink");let n=this.toRealPath(t),r=this.validateParent(n,t);try{let s=await T.promises.readlink(r),i=B(t),a=se.dirname(i),o=se.isAbsolute(s)?s:se.resolve(se.dirname(r),s),l=await T.promises.realpath(o).catch(()=>o);if(Ge(l,this.canonicalRoot)){let c=l.slice(this.canonicalRoot.length)||"/";return a==="/"?c.startsWith("/")?c.slice(1)||".":c:se.relative(a,c)}return se.basename(s)}catch(s){let i=s;if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(i.code==="EINVAL")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);this.sanitizeError(s,t,"readlink")}}async realpath(t){F(t,"realpath");let n=this.toRealPath(t);try{this.resolveAndValidate(n,t)}catch{throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}let r;try{r=await T.promises.realpath(n)}catch(s){let i=s;if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);if(i.code==="ELOOP")throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);this.sanitizeError(s,t,"realpath")}if(Ge(r,this.canonicalRoot))return r.slice(this.canonicalRoot.length)||"/";throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}async utimes(t,n,r){F(t,"utimes");let s=this.toRealPath(t),i=this.resolveAndValidate(s,t);try{let a=this.allowSymlinks?T.constants.O_RDONLY:T.constants.O_RDONLY|T.constants.O_NOFOLLOW,o=await T.promises.open(i,a);try{await o.utimes(n,r)}finally{await o.close()}}catch(a){let o=a;if(o.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);if(o.code==="ELOOP")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(a,t,"utimes")}}};var In=class{cmdId;cwd;startedAt;exitCode;bashEnv;cmdLine;env;explicitCwd;signal;timeoutMs;abortController=new AbortController;timeoutId;externalAbortListener;resultPromise;constructor(t,n,r,s,i=!1,a,o){this.cmdId=crypto.randomUUID(),this.cwd=r,this.startedAt=new Date,this.bashEnv=t,this.cmdLine=n,this.env=s,this.explicitCwd=i,this.signal=a,this.timeoutMs=o,this.setupCancellation(),this.resultPromise=this.execute()}setupCancellation(){if(this.signal&&(this.signal.aborted?this.abortController.abort(this.signal.reason):(this.externalAbortListener=()=>{this.abortController.abort(this.signal?.reason)},this.signal.addEventListener("abort",this.externalAbortListener,{once:!0}))),this.timeoutMs!==void 0){let t=Math.max(0,this.timeoutMs);this.timeoutId=dr(()=>{this.abortController.abort(new Error(`sandbox command timeout after ${t}ms`))},t)}}cleanupCancellation(){this.timeoutId!==void 0&&(hr(this.timeoutId),this.timeoutId=void 0),this.signal&&this.externalAbortListener&&(this.signal.removeEventListener("abort",this.externalAbortListener),this.externalAbortListener=void 0)}async execute(){let t={cwd:this.explicitCwd?this.cwd:void 0,env:this.env,signal:this.abortController.signal};try{let n=await this.bashEnv.exec(this.cmdLine,t);return this.exitCode=n.exitCode,n}finally{this.cleanupCancellation()}}async*logs(){let t=await this.resultPromise;t.stdout&&(yield{type:"stdout",data:t.stdout,timestamp:new Date}),t.stderr&&(yield{type:"stderr",data:t.stderr,timestamp:new Date})}async wait(){return await this.resultPromise,this}async output(){let t=await this.resultPromise;return t.stdout+t.stderr}async stdout(){return(await this.resultPromise).stdout}async stderr(){return(await this.resultPromise).stderr}async kill(){this.abortController.abort(new Error("command killed"))}};var Cs=class e{bashEnv;timeoutMs;constructor(t,n){this.bashEnv=t,this.timeoutMs=n}static async create(t){let n=t?.fs;if(t?.overlayRoot){if(t?.fs)throw new Error("Cannot specify both 'fs' and 'overlayRoot' options");n=new On({root:t.overlayRoot})}let r=new fr({env:t?.env,cwd:t?.cwd,fs:n,maxCallDepth:t?.maxCallDepth,maxCommandCount:t?.maxCommandCount,maxLoopIterations:t?.maxLoopIterations,network:t?.network,defenseInDepth:t?.defenseInDepth,python:t?.python,javascript:t?.javascript,commands:t?.commands,customCommands:t?.customCommands,fetch:t?.fetch});return new e(r,t?.timeoutMs)}async runCommand(t,n,r){let s,i,a,o,l=!1,c,u;if(typeof t=="object"){let m=t,E=[m.cmd,...m.args??[]];s=Ls(E),i=m.cwd,a=m.env,o=m.signal,l=m.detached??!1,c=m.stdout,u=m.stderr}else if(Array.isArray(n)){let m=r;s=Ls([t,...n]),o=m?.signal}else{s=t;let m=n;i=m?.cwd,a=m?.env}let f=i??this.bashEnv.getCwd(),d=i!==void 0,h=new In(this.bashEnv,s,f,a,d,o,this.timeoutMs);if(l)return h;let p=await h.wait();if(c){let m=await h.stdout();m&&c.write(m)}if(u){let m=await h.stderr();m&&u.write(m)}return p}async writeFiles(t){let n=this.bashEnv.getCwd();for(let[r,s]of Object.entries(t)){let i;typeof s=="string"?i=s:s.encoding==="base64"?i=Buffer.from(s.content,"base64").toString("utf-8"):i=s.content;let a=this.bashEnv.fs.resolvePath(n,r),o=a.substring(0,a.lastIndexOf("/"))||"/";o!=="/"&&await this.bashEnv.fs.mkdir(o,{recursive:!0}),await this.bashEnv.writeFile(a,i)}}async readFile(t,n){let r=await this.bashEnv.readFile(t);return n==="base64"?Buffer.from(r).toString("base64"):r}async mkDir(t,n){let r=this.bashEnv.fs.resolvePath(this.bashEnv.getCwd(),t);await this.bashEnv.fs.mkdir(r,{recursive:n?.recursive??!1})}async stop(){}async extendTimeout(t){}get domain(){}get bashEnvInstance(){return this.bashEnv}};var Ds=class{violations=[];violationsByType=new Map;options;constructor(t={}){this.options={maxViolationsPerType:t.maxViolationsPerType??100,maxViolationsTotal:t.maxViolationsTotal??1e3,includeStackTraces:t.includeStackTraces??!0,onViolation:t.onViolation??(()=>{}),logToConsole:t.logToConsole??!1}}record(t){let n=this.options.includeStackTraces?t:{...t,stack:void 0};this.violations.unshift(n),this.violations.length>this.options.maxViolationsTotal&&(this.violations.length=this.options.maxViolationsTotal);let r=this.violationsByType.get(t.type);r||(r=[],this.violationsByType.set(t.type,r)),r.length<this.options.maxViolationsPerType&&r.push(n),this.options.logToConsole&&console.warn(`[SecurityViolation] ${t.type}: ${t.message}`,t.path),this.options.onViolation(n)}getViolations(){return[...this.violations]}getViolationsByType(t){return[...this.violationsByType.get(t)??[]]}getSummary(){let t=[];for(let[n,r]of this.violationsByType){if(r.length===0)continue;let s=new Set,i=Number.POSITIVE_INFINITY,a=0;for(let o of r)s.add(o.path),i=Math.min(i,o.timestamp),a=Math.max(a,o.timestamp);t.push({type:n,count:r.length,firstSeen:i,lastSeen:a,paths:Array.from(s)})}return t.sort((n,r)=>r.count-n.count),t}getTotalCount(){return this.violations.length}hasViolations(){return this.violations.length>0}clear(){this.violations=[],this.violationsByType.clear()}createCallback(){return t=>this.record(t)}};function Fu(){return e=>{console.warn("[DefenseInDepth] Security violation detected:",`
|
|
797
|
+
`;try{s.writeFileSync(`/bin/${t.name}`,i)}catch{}try{s.writeFileSync(`/usr/bin/${t.name}`,i)}catch{}}}logResult(t){return this.logger&&(t.stdout&&this.logger.debug("stdout",{output:t.stdout}),t.stderr&&this.logger.info("stderr",{output:t.stderr}),this.logger.info("exit",{exitCode:t.exitCode})),t.stdout=If(t.stdout),t.stderr=If(t.stderr),t}async exec(t,n){let r=new Mr(this.limits,n?.signal),s;try{s=await this.execInScope(t,n,r,0,n?.signal,!1,!1)}catch(o){try{await r.close()}catch{}throw o}let i=s;try{await r.close()}catch{i={...s,stderr:`${s.stderr}bash: execution cleanup failed
|
|
798
|
+
`,exitCode:126}}return t.trim()?this.logResult(i):i}async execInScope(t,n,r,s,i,o=!1,a=!0){let l=f=>a?this.logResult(f):f,c=Nr(i,n?.signal),u=n?{...n,signal:c.signal}:{signal:c.signal};try{if(r.assertExecDepth(s),Pr(t,this.limits.maxSourceBytes),!t.trim())return{stdout:"",stderr:"",exitCode:0,env:Xe(this.state.env,u.env)};this.logger?.info("exec",{command:t});let f=u.cwd??this.state.cwd,d,p=f;if(u.cwd)if(u.env&&"PWD"in u.env)d=u.env.PWD;else if(u.env&&!("PWD"in u.env))try{d=await this.fs.realpath(f),p=d}catch{d=f}else d=f;let h=u.replaceEnv?new Map:new Map(this.state.env);if(u.env)for(let[y,S]of Object.entries(u.env))h.set(y,S);d!==void 0&&h.set("PWD",d);let m={...this.state,env:h,arrays:u.replaceEnv?new Map:ot(this.state.arrays),cwd:p,previousDir:u.env?.OLDPWD??this.state.previousDir,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:sy(u.stdin,u.stdinKind,this.limits.maxInputBytes,this.limits.maxStringLength,r,o),signal:u.signal,extraArgs:u.args},E=t;u.rawScript||(E=Df(t));let b=this.defenseInDepthConfig?Le.getInstance(this.defenseInDepthConfig):null,g=b?.activate();try{let y=async()=>{let S=Ge(E,{maxHeredocSize:this.limits.maxHeredocSize}),v;if(this.transformPlugins.length>0){let P=Object.create(null);for(let C of this.transformPlugins){let O=C.transform({ast:S,metadata:P});S=O.ast,O.metadata&&(P=nr(P,O.metadata))}v=P}let k={fs:this.fs,commands:this.commands,limits:this.limits,executionScope:r,exec:(P,C,O=!1)=>this.execInScope(P,C,r,s+1,u.signal,O),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,requireDefenseContext:b?.isEnabled()===!0,jsBootstrapCode:this.jsBootstrapCode,invokeTool:this.invokeToolFn},N=await new kr(k,m).executeScript(S);return v&&(N.metadata=v),l(N)};return g?await g.run(y):await y()}catch(y){if(y instanceof j)return l({stdout:y.stdout,stderr:y.stderr,exitCode:y.exitCode,internalOutputAccounting:y.internalOutputAccounting,env:Xe(this.state.env,u.env)});if(y instanceof st)return l({stdout:y.stdout,stderr:y.stderr,exitCode:y.exitCode,env:Xe(this.state.env,u.env)});if(y instanceof ce)return l({stdout:y.stdout,stderr:y.stderr,exitCode:1,env:Xe(this.state.env,u.env)});if(y instanceof ze)return l({stdout:y.stdout,stderr:y.stderr,exitCode:124,env:Xe(this.state.env,u.env)});if(y instanceof x)return l({stdout:y.stdout,stderr:wt(y.stderr),exitCode:x.EXIT_CODE,internalOutputAccounting:y.internalOutputAccounting,env:Xe(this.state.env,u.env)});if(y instanceof _t)return l({stdout:"",stderr:`bash: security violation: ${wt(y.message)}
|
|
799
|
+
`,exitCode:1,env:Xe(this.state.env,u.env)});if(y.name==="ParseException")return l({stdout:"",stderr:`bash: syntax error: ${wt(y.message)}
|
|
800
|
+
`,exitCode:2,env:Xe(this.state.env,u.env)});if(y instanceof Ye)return l({stdout:"",stderr:`bash: ${wt(y.message)}
|
|
801
|
+
`,exitCode:2,env:Xe(this.state.env,u.env)});if(y instanceof RangeError)return l({stdout:"",stderr:`bash: ${wt(y.message)}
|
|
802
|
+
`,exitCode:1,env:Xe(this.state.env,u.env)});throw y}finally{g?.deactivate()}}catch(f){if(f instanceof ze)return l({stdout:f.stdout,stderr:f.stderr,exitCode:124,env:Xe(this.state.env,u.env)});if(f instanceof x)return l({stdout:f.stdout,stderr:wt(f.stderr),exitCode:x.EXIT_CODE,internalOutputAccounting:f.internalOutputAccounting,env:Xe(this.state.env,u.env)});throw f}finally{c.cleanup()}}async readFile(t){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,t))}async writeFile(t,n){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,t),n)}getCwd(){return this.state.cwd}getEnv(){return Wt(this.state.env)}registerTransformPlugin(t){this.transformPlugins.push(t)}transform(t){Pr(t,this.limits.maxSourceBytes);let n=Df(t),r=Ge(n,{maxHeredocSize:this.limits.maxHeredocSize}),s=Object.create(null);for(let i of this.transformPlugins){let o=i.transform({ast:r,metadata:s});r=o.ast,o.metadata&&(s=nr(s,o.metadata))}return{script:ur(r),ast:r,metadata:s}}};function ny(e,t){let n=t;for(let r=0;r<e.length;r++){let s=e[r];if(n==="single")s==="'"&&(n="none");else if(n==="double")s==="\\"?r++:s==='"'&&(n="none");else if(s==="'")n="single";else if(s==='"')n="double";else if(s==="\\")r++;else if(s==="#"&&(r===0||/\s/.test(e[r-1])))break}return n}function Df(e){let t=e.split(`
|
|
803
|
+
`),n=[],r=[],s="none";for(let i=0;i<t.length;i++){let o=t[i];if(r.length>0){let u=r[r.length-1];if((u.stripTabs?o.replace(/^\t+/,""):o)===u.delimiter){n.push(o.trimStart()),r.pop();continue}n.push(o);continue}let a=s,l=a==="none"?o.trimStart():o;if(n.push(l),s=ny(o,a),a!=="none")continue;let c=/<<(-?)\s*(['"]?)([\w-]+)\2/g;for(let u of l.matchAll(c)){let f=u[1]==="-",d=u[3];r.push({delimiter:d,stripTabs:f})}}return n.join(`
|
|
804
|
+
`)}var ry=new TextDecoder("utf-8",{fatal:!0});function If(e){if(!e)return e;let t=!1;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);if(s>255)return e;s>127&&(t=!0)}if(!t)return e;let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);try{return ry.decode(n)}catch{return e}}function sy(e,t,n,r,s,i){if(e===void 0)return;let o=t==="bytes"?e.length:B(e);if(o>n||o>r)throw new x(`stdin size limit exceeded (${Math.min(n,r)} bytes)`,"string_length");return i||s.consumeInput(o,"stdin"),t==="bytes"?e:Tt(e)}import*as he from"node:fs";import*as Ie from"node:path";import*as ut from"node:fs";import*as $e from"node:path";function De(e,t){let n=/^[A-Za-z]:[\\/]/.test(t)?$e.win32:$e.posix,r=n.relative(t,e);return r===""||r!==".."&&!r.startsWith(`..${n.sep}`)&&!n.isAbsolute(r)}function Sn(e,t){try{let n=ut.realpathSync(e);return De(n,t)?n:null}catch(n){if(n.code==="ENOENT"){let r=$e.dirname(e);if(r===e)return null;let s=Sn(r,t);if(s===null)return null;try{if(ut.lstatSync(e).isSymbolicLink()){let o=ut.readlinkSync(e),a=$e.isAbsolute(o)?o:$e.resolve($e.dirname(e),o),l=Sn(a,t);return l===null?null:l}}catch{}return $e.join(s,$e.basename(e))}return null}}function zs(e,t,n){let r=Sn(e,n);if(r===null)return null;let s=$e.resolve(e),i=s.slice(t.length),o=r.slice(n.length);if(i!==o)return null;try{if(ut.lstatSync(s).isSymbolicLink())return null}catch{}return r}function Us(e,t){if(!ut.existsSync(e))throw new Error(`${t} root does not exist`);if(!ut.statSync(e).isDirectory())throw new Error(`${t} root is not a directory`)}function _f(e,t){if(!$e.isAbsolute(e))return{withinRoot:!0,relativePath:e};let n;try{n=ut.realpathSync(e)}catch{n=$e.resolve(e)}return De(n,t)?{withinRoot:!0,relativePath:n.slice(t.length).replace(/\\/g,"/")||"/"}:{withinRoot:!1,safeName:$e.basename(e)}}function qs(e,t,n,r){let s=e;if(s.path===void 0){for(let o of r)if(s.message?.includes(o))throw e}let i=s.code||"EIO";throw new Error(`${i}: ${n} '${t}'`)}var iy=["ELOOP","EFBIG","EPERM"],oy="/home/user/project",Qn=class{root;canonicalRoot;mountPoint;readOnly;maxFileReadSize;maxMemoryBytes;allowSymlinks;memory=new Map;deleted=new Set;nextMemoryIdentity=1;retainedMemoryBytes=0;memoryEntryBytes(t){if(!t||t.type!=="file")return 0;let n=t.content.byteLength;for(let r of t.appendChunks??[])n+=r.byteLength;return n}assertMemoryCapacity(t,n=0){if(!Number.isSafeInteger(t)||t<0||t>this.maxMemoryBytes-this.retainedMemoryBytes+n)throw new Error(`ENOSPC: overlay memory byte limit exceeded (${this.maxMemoryBytes} bytes)`)}setMemoryEntry(t,n){let r=this.memoryEntryBytes(this.memory.get(t)),s=this.memoryEntryBytes(n);this.assertMemoryCapacity(s,r),this.memory.set(t,n),this.retainedMemoryBytes+=s-r}deleteMemoryEntry(t){let n=this.memory.get(t);n&&(this.retainedMemoryBytes-=this.memoryEntryBytes(n),this.memory.delete(t))}identityFor(t){return t.type==="symlink"?"":(t.identity||(t.identity=`overlay:${this.nextMemoryIdentity++}`),t.identity)}constructor(t){this.root=Ie.resolve(t.root);let n=t.mountPoint??oy;if(this.mountPoint=n==="/"?"/":n.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${n}`);if(this.readOnly=t.readOnly??!1,this.maxFileReadSize=t.maxFileReadSize??10485760,this.maxMemoryBytes=t.maxMemoryBytes??1024*1024*1024,!Number.isSafeInteger(this.maxMemoryBytes)||this.maxMemoryBytes<0)throw new Error("OverlayFs: invalid maxMemoryBytes");this.allowSymlinks=t.allowSymlinks??!1,Us(this.root,"OverlayFs"),this.canonicalRoot=he.realpathSync(this.root),this.createMountPointDirs()}assertWritable(t){if(this.readOnly)throw new Error(`EROFS: read-only file system, ${t}`)}createMountPointDirs(){let t=this.mountPoint.split("/").filter(Boolean),n="";for(let r of t)n+=`/${r}`,this.memory.has(n)||this.setMemoryEntry(n,{type:"directory",mode:493,mtime:new Date});this.memory.has("/")||this.setMemoryEntry("/",{type:"directory",mode:493,mtime:new Date})}getMountPoint(){return this.mountPoint}mkdirSync(t,n){let s=W(t).split("/").filter(Boolean),i="";for(let o of s)i+=`/${o}`,this.memory.has(i)||this.setMemoryEntry(i,{type:"directory",mode:493,mtime:new Date})}writeFileSync(t,n){let r=W(t),s=this.getDirname(r);s!=="/"&&this.mkdirSync(s);let i=n instanceof Uint8Array?n:new TextEncoder().encode(n);this.setMemoryEntry(r,{type:"file",content:i,mode:420,mtime:new Date})}getDirname(t){let n=t.lastIndexOf("/");return n===0?"/":t.slice(0,n)}getRelativeToMount(t){return this.mountPoint==="/"?t:t===this.mountPoint?"/":t.startsWith(`${this.mountPoint}/`)?t.slice(this.mountPoint.length):null}toRealPath(t){let n=W(t),r=this.getRelativeToMount(n);if(r===null)return null;let s=Ie.join(this.root,r),i=Ie.resolve(s);return De(i,this.root)?i:null}resolveRealPath_(t){return t?this.allowSymlinks?Sn(t,this.canonicalRoot):zs(t,this.root,this.canonicalRoot):null}resolveRealPathParent_(t){if(!t)return null;let n=Ie.dirname(t),r=this.resolveRealPath_(n);return r===null?null:Ie.join(r,Ie.basename(t))}sanitizeError(t,n,r){qs(t,n,r,iy)}ensureParentDirs(t){let n=xn(t);n!=="/"&&(this.memory.has(n)||(this.ensureParentDirs(n),this.setMemoryEntry(n,{type:"directory",mode:493,mtime:new Date})),this.deleted.delete(n))}async existsInOverlay(t){let n=W(t);if(this.deleted.has(n))return!1;if(this.memory.has(n))return!0;let r=this.resolveRealPathParent_(this.toRealPath(n));if(!r)return!1;try{return await he.promises.lstat(r),!0}catch{return!1}}async readFile(t,n){let r=await this.readFileBuffer(t),s=it(n);return Ot(r,s)}async readFileBytes(t){let n=await this.readFileBuffer(t);return Ot(n,"binary")}async readFileBuffer(t,n=new Set){V(t,"open");let r=W(t);if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);if(n.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, open '${t}'`);let s=this.memory.get(r);if(s){if(s.type==="symlink"){let c=this.resolveSymlink(r,s.target);return this.readFileBuffer(c,n)}if(s.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(!s.appendChunks||s.appendChunks.length===0)return s.content;let o=s.appendChunks.reduce((c,u)=>c+u.byteLength,s.content.byteLength);if(!Number.isSafeInteger(o))throw new Error(`EFBIG: file too large, read '${t}'`);let a=new Uint8Array(o);a.set(s.content);let l=s.content.byteLength;for(let c of s.appendChunks)a.set(c,l),l+=c.byteLength;return s.content=a,s.appendChunks=void 0,a}let i=this.resolveRealPath_(this.toRealPath(r));if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let o=await he.promises.lstat(i);if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, open '${t}'`);let c=await he.promises.readlink(i),u=this.realTargetToVirtual(r,c),f=this.resolveSymlink(r,u);return this.readFileBuffer(f,n)}if(o.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(this.maxFileReadSize>0&&o.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${o.size} bytes, max ${this.maxFileReadSize})`);let a=this.allowSymlinks?he.constants.O_RDONLY:he.constants.O_RDONLY|he.constants.O_NOFOLLOW,l=await he.promises.open(i,a);try{let c=await l.readFile();return new Uint8Array(c)}finally{await l.close()}}catch(o){let a=o.code;if(a==="ENOENT")throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(a==="ELOOP")throw new Error(`ENOENT: no such file or directory, open '${t}'`);this.sanitizeError(o,t,"open")}}async writeFile(t,n,r){V(t,"write"),this.assertWritable(`write '${t}'`);let s=W(t);this.ensureParentDirs(s);let i=it(r),o=Rt(n,i);this.setMemoryEntry(s,{type:"file",content:o,mode:420,mtime:new Date}),this.deleted.delete(s)}async appendFile(t,n,r){V(t,"append"),this.assertWritable(`append '${t}'`);let s=W(t),i=it(r),o=Rt(n,i),a=this.memory.get(s);if(a?.type==="file"){this.assertMemoryCapacity(o.byteLength),a.appendChunks||(a.appendChunks=[]),a.appendChunks.push(o),this.retainedMemoryBytes+=o.byteLength,a.mtime=new Date,this.deleted.delete(s);return}let l;try{l=await this.readFileBuffer(s)}catch{l=new Uint8Array(0)}this.ensureParentDirs(s),this.setMemoryEntry(s,{type:"file",content:l,appendChunks:[o],mode:420,mtime:new Date}),this.deleted.delete(s)}async exists(t){return t.includes("\0")?!1:this.existsInOverlay(t)}async stat(t,n=new Set){V(t,"stat");let r=W(t);if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, stat '${t}'`);if(n.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let s=this.memory.get(r);if(s){if(s.type==="symlink"){let a=this.resolveSymlink(r,s.target);return this.stat(a,n)}let o=0;return s.type==="file"&&(o=s.content.length+(s.appendChunks?.reduce((a,l)=>a+l.byteLength,0)??0)),{isFile:s.type==="file",isDirectory:s.type==="directory",isSymbolicLink:!1,mode:s.mode,size:o,mtime:s.mtime,identity:this.identityFor(s)}}let i=this.resolveRealPath_(this.toRealPath(r));if(!i)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);try{let o=await he.promises.lstat(i);if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let a=await he.promises.readlink(i),l=this.realTargetToVirtual(r,a),c=this.resolveSymlink(r,l);return this.stat(c,n)}return{isFile:o.isFile(),isDirectory:o.isDirectory(),isSymbolicLink:!1,mode:o.mode,size:o.size,mtime:o.mtime,dev:o.dev,ino:o.ino}}catch(o){if(o.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, stat '${t}'`);this.sanitizeError(o,t,"stat")}}async lstat(t){V(t,"lstat");let n=W(t);if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);let r=this.memory.get(n);if(r){if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime};let i=0;return r.type==="file"&&(i=r.content.length+(r.appendChunks?.reduce((o,a)=>o+a.byteLength,0)??0)),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:i,mtime:r.mtime,identity:this.identityFor(r)}}let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);try{let i=await he.promises.lstat(s);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink(),mode:i.mode,size:i.size,mtime:i.mtime,dev:i.dev,ino:i.ino}}catch(i){if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);this.sanitizeError(i,t,"lstat")}}resolveSymlink(t,n){return $n(t,n)}realTargetToVirtual(t,n){let r=_f(n,this.canonicalRoot);if(r.withinRoot){if(!Ie.isAbsolute(n))return n;let s=r.relativePath;return this.mountPoint==="/"?s:`${this.mountPoint}${s}`}return r.safeName}async mkdir(t,n){V(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let r=W(t);if(await this.existsInOverlay(r)){if(!n?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${t}'`);return}let i=xn(r);if(i!=="/"&&!await this.existsInOverlay(i))if(n?.recursive)await this.mkdir(i,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.setMemoryEntry(r,{type:"directory",mode:493,mtime:new Date}),this.deleted.delete(r)}async readdirCore(t,n){if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let r=new Map,s=new Set,i=n==="/"?"/":`${n}/`;for(let a of this.deleted)if(a.startsWith(i)){let l=a.slice(i.length),c=l.split("/")[0];c&&!l.includes("/",c.length)&&s.add(c)}for(let[a,l]of this.memory)if(a!==n&&a.startsWith(i)){let c=a.slice(i.length),u=c.split("/")[0];u&&!s.has(u)&&!c.includes("/",1)&&r.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}let o=this.resolveRealPath_(this.toRealPath(n));if(o)try{if(!this.allowSymlinks&&(await he.promises.lstat(o)).isSymbolicLink()){if(!this.memory.has(n))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);return r}let a=await he.promises.readdir(o,{withFileTypes:!0});for(let l of a)!s.has(l.name)&&!r.has(l.name)&&r.set(l.name,{name:l.name,isFile:l.isFile(),isDirectory:l.isDirectory(),isSymbolicLink:l.isSymbolicLink()})}catch(a){if(a.code==="ENOENT"){if(!this.memory.has(n))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`)}else a.code!=="ENOTDIR"&&this.sanitizeError(a,t,"scandir")}return r}async resolveForReaddir(t,n=!1){let r=W(t),s=new Set,i=n,o=this.memory.get(r);for(;o&&o.type==="symlink";){if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);s.add(r),i=!0,r=this.resolveSymlink(r,o.target),o=this.memory.get(r)}if(o)return{normalized:r,outsideOverlay:!1};if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let l=this.resolveRealPath_(this.toRealPath(r));if(!l)return{normalized:r,outsideOverlay:!0};try{if((await he.promises.lstat(l)).isSymbolicLink()){if(!this.allowSymlinks)return{normalized:r,outsideOverlay:!0};let u=await he.promises.readlink(l),f=this.realTargetToVirtual(r,u),d=this.resolveSymlink(r,f);return this.resolveForReaddir(d,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(t){V(t,"scandir");let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let s=await this.readdirCore(t,n);return Array.from(s.keys()).sort((i,o)=>i<o?-1:i>o?1:0)}async readdirWithFileTypes(t){V(t,"scandir");let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let s=await this.readdirCore(t,n);return Array.from(s.values()).sort((i,o)=>i.name<o.name?-1:i.name>o.name?1:0)}async rm(t,n){V(t,"rm"),this.assertWritable(`rm '${t}'`);let r=W(t);if(!await this.existsInOverlay(r)){if(n?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}try{if((await this.stat(r)).isDirectory){let o=await this.readdir(r);if(o.length>0){if(!n?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let a of o){let l=r==="/"?`/${a}`:`${r}/${a}`;await this.rm(l,n)}}}}catch(i){if(i instanceof Error&&(i.message.includes("ENOTEMPTY")||i.message.includes("EISDIR")))throw i}this.deleteMemoryEntry(r),this.existsOnRealFs(r)&&this.deleted.add(r)}existsOnRealFs(t){let n=this.toRealPath(t),r=this.resolveRealPathParent_(n);if(!r)return!1;try{return he.lstatSync(r),!0}catch{return!1}}async cp(t,n,r){V(t,"cp"),V(n,"cp"),this.assertWritable(`cp '${n}'`);let s=W(t),i=W(n);if(!await this.existsInOverlay(s))throw new Error(`ENOENT: no such file or directory, cp '${t}'`);let a=await this.stat(s);if(a.isFile){let l=await this.readFileBuffer(s);await this.writeFile(i,l)}else if(a.isDirectory){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);if(Ct(s,i))throw new Error(`EINVAL: cannot copy '${t}' into itself, '${n}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(s);for(let c of l){let u=s==="/"?`/${c}`:`${s}/${c}`,f=i==="/"?`/${c}`:`${i}/${c}`;await this.cp(u,f,r)}}}async mv(t,n){this.assertWritable(`mv '${n}'`),await this.cp(t,n,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,n){return Bt(t,n)}getAllPaths(){let t=new Set(this.memory.keys());for(let n of this.deleted)t.delete(n);return this.scanRealFs("/",t),Array.from(t)}scanRealFs(t,n){if(this.deleted.has(t))return;let r=this.resolveRealPath_(this.toRealPath(t));if(r)try{let s=he.readdirSync(r);for(let i of s){let o=t==="/"?`/${i}`:`${t}/${i}`;if(this.deleted.has(o))continue;n.add(o);let a=Ie.join(r,i);he.lstatSync(a).isDirectory()&&this.scanRealFs(o,n)}}catch{}}async chmod(t,n){V(t,"chmod"),this.assertWritable(`chmod '${t}'`);let r=W(t);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);let i=this.memory.get(r);if(i){i.mode=n;return}let o=await this.stat(r);if(o.isFile){let a=await this.readFileBuffer(r);this.setMemoryEntry(r,{type:"file",content:a,mode:n,mtime:new Date})}else o.isDirectory&&this.setMemoryEntry(r,{type:"directory",mode:n,mtime:new Date})}async symlink(t,n){if(!this.allowSymlinks)throw new Error(`EPERM: operation not permitted, symlink '${n}'`);V(n,"symlink"),this.assertWritable(`symlink '${n}'`);let r=W(n);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.setMemoryEntry(r,{type:"symlink",target:t,mode:511,mtime:new Date}),this.deleted.delete(r)}async link(t,n){V(t,"link"),V(n,"link"),this.assertWritable(`link '${n}'`);let r=W(t),s=W(n);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, link '${t}'`);let o=await this.stat(r);if(!o.isFile)throw new Error(`EPERM: operation not permitted, link '${t}'`);if(await this.existsInOverlay(s))throw new Error(`EEXIST: file already exists, link '${n}'`);let l=await this.readFileBuffer(r);this.ensureParentDirs(s),this.setMemoryEntry(s,{type:"file",content:l,mode:o.mode,mtime:new Date,identity:o.identity??`overlay:${this.nextMemoryIdentity++}`}),this.deleted.delete(s)}async readlink(t){V(t,"readlink");let n=W(t);if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);let r=this.memory.get(n);if(r){if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return r.target}let s=this.resolveRealPathParent_(this.toRealPath(n));if(!s)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);try{let i=await he.promises.readlink(s);if(!Ie.isAbsolute(i)){let o=Ie.resolve(Ie.dirname(s),i),a;try{a=he.realpathSync(o)}catch{a=o}if(!De(a,this.canonicalRoot))return Ie.basename(i)}return this.realTargetToVirtual(n,i)}catch(i){if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(i.code==="EINVAL")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);this.sanitizeError(i,t,"readlink")}}async realpath(t){V(t,"realpath");let n=W(t),r=new Set,s=async a=>{let l=a==="/"?[]:a.slice(1).split("/"),c="";for(let u of l){if(c=`${c}/${u}`,r.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(c))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let f=this.memory.get(c),d=0,p=40;for(;f&&f.type==="symlink"&&d<p;){if(r.add(c),c=this.resolveSymlink(c,f.target),d++,r.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(c))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);f=this.memory.get(c)}if(d>=p)throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(!f){let h=this.toRealPath(c),m=this.resolveRealPath_(h);if(m)try{if((await he.promises.lstat(m)).isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let b=await he.promises.readlink(m),g=this.realTargetToVirtual(c,b);return r.add(c),c=this.resolveSymlink(c,g),s(c)}}catch(E){if(E.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);this.sanitizeError(E,t,"realpath")}else if(!this.allowSymlinks){let E=this.resolveRealPathParent_(h);if(E)try{if((await he.promises.lstat(E)).isSymbolicLink())throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}catch(b){if(b.message?.includes("ENOENT")||b.message?.includes("ELOOP"))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);this.sanitizeError(b,t,"realpath")}}}}return c||"/"},i=await s(n);if(!await this.existsInOverlay(i))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return i}async utimes(t,n,r){V(t,"utimes"),this.assertWritable(`utimes '${t}'`);let s=W(t);if(!await this.existsInOverlay(s))throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);let o=this.memory.get(s);if(o){o.mtime=r;return}let a=await this.stat(s);if(a.isFile){let l=await this.readFileBuffer(s);this.setMemoryEntry(s,{type:"file",content:l,mode:a.mode,mtime:r})}else a.isDirectory&&this.setMemoryEntry(s,{type:"directory",mode:a.mode,mtime:r})}};import{randomBytes as ay}from"node:crypto";import*as I from"node:fs";import*as Z from"node:path";var ly=["EACCES","escaping sandbox","EFBIG","ENOTSUP"],js=class e{static activeMutationRoots=new Set;static pendingMutations=[];root;canonicalRoot;maxFileReadSize;maxCopyOnWriteSize;maxCopySize;allowSymlinks;constructor(t){this.root=Z.resolve(t.root),this.maxFileReadSize=t.maxFileReadSize??10485760,this.maxCopyOnWriteSize=t.maxCopyOnWriteSize??104857600,this.maxCopySize=t.maxCopySize??0,this.allowSymlinks=t.allowSymlinks??!1,Us(this.root,"ReadWriteFs"),this.canonicalRoot=I.realpathSync(this.root)}resolveAndValidate(t,n){let r=this.allowSymlinks?Sn(t,this.canonicalRoot):zs(t,this.root,this.canonicalRoot);if(r===null)throw new Error(`EACCES: permission denied, '${n}' resolves outside sandbox`);return r}validateParent(t,n){let r=Z.dirname(t),s=this.resolveAndValidate(r,n);return Z.join(s,Z.basename(t))}toRealPath(t){let n=W(t),r=Z.join(this.root,n);return Z.resolve(r)}async readFile(t,n){let r=await this.readFileBuffer(t),s=it(n);return Ot(r,s)}async readFileBytes(t){let n=await this.readFileBuffer(t);return Ot(n,"binary")}async readFileBuffer(t){V(t,"open");let n=this.toRealPath(t),r=this.resolveAndValidate(n,t);try{let s=this.allowSymlinks?I.constants.O_RDONLY:I.constants.O_RDONLY|I.constants.O_NOFOLLOW,i=await I.promises.open(r,s);try{if(this.maxFileReadSize>0){let a=await i.stat();if(a.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${a.size} bytes, max ${this.maxFileReadSize})`)}let o=await i.readFile();return new Uint8Array(o)}finally{await i.close()}}catch(s){let i=s;if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(i.code==="EISDIR")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(i.code==="ELOOP")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(s,t,"open")}}async writeFile(t,n,r){await this.withFilesystemMutation(()=>this.writeFileUnlocked(t,n,r))}async writeFileUnlocked(t,n,r){V(t,"write");let s=this.toRealPath(t),i=this.resolveAndValidate(s,t),o=it(r),a=Rt(n,o),l=Z.dirname(i);try{await I.promises.mkdir(l,{recursive:!0}),i=this.resolveAndValidate(s,t);let c=this.allowSymlinks?0:I.constants.O_NOFOLLOW,u=null;try{let f=await I.promises.lstat(i);if(!f.isFile()&&!f.isDirectory())throw new Error(`EACCES: cannot write special file '${t}'`);let d=await I.promises.open(i,I.constants.O_WRONLY|I.constants.O_NONBLOCK|c);try{if(u=await d.stat(),!u.isFile())throw new Error(`EACCES: cannot write special file '${t}'`);if(u.nlink<=1){await d.truncate(0),await d.writeFile(a);return}}finally{await d.close()}}catch(f){if(f.code!=="ENOENT")throw f}await this.replaceFile(i,a,u)}catch(c){if(c.code==="ELOOP")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(c,t,"write")}}async appendFile(t,n,r){await this.withFilesystemMutation(()=>this.appendFileUnlocked(t,n,r))}async appendFileUnlocked(t,n,r){V(t,"append");let s=this.toRealPath(t),i=it(r),o=Rt(n,i),a=this.resolveAndValidate(s,t),l=Z.dirname(a);try{await I.promises.mkdir(l,{recursive:!0}),a=this.resolveAndValidate(s,t);let c=this.allowSymlinks?0:I.constants.O_NOFOLLOW,u=null;try{let d=await I.promises.lstat(a);if(!d.isFile()&&!d.isDirectory())throw new Error(`EACCES: cannot append special file '${t}'`);let p=await I.promises.open(a,I.constants.O_WRONLY|I.constants.O_APPEND|I.constants.O_NONBLOCK|c);try{if(u=await p.stat(),!u.isFile())throw new Error(`EACCES: cannot append special file '${t}'`);if(u.nlink<=1){await p.writeFile(o);return}}finally{await p.close()}}catch(d){if(d.code!=="ENOENT")throw d}if(!u){await this.replaceFile(a,o,null);return}this.assertCopyOnWriteSize(u.size,"append",t);let f=await this.openCopySource(a);try{let d=await f.stat();if(!d.isFile()||d.dev!==u.dev||d.ino!==u.ino)throw new Error(`EACCES: file identity changed, append '${t}'`);await this.replaceFile(a,o,d,{handle:f,size:u.size})}finally{await f.close()}}catch(c){if(c.code==="ELOOP")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(c,t,"append")}}async withFilesystemMutation(t){return new Promise((n,r)=>{e.pendingMutations.push({root:this.canonicalRoot,start:()=>{e.activeMutationRoots.add(this.canonicalRoot),t().then(n,r).finally(()=>{e.activeMutationRoots.delete(this.canonicalRoot),e.drainMutationQueue()})}}),e.drainMutationQueue()})}static drainMutationQueue(){for(let t=0;t<e.pendingMutations.length;){let n=e.pendingMutations[t];if([...e.activeMutationRoots].some(s=>De(n.root,s)||De(s,n.root))){t++;continue}e.pendingMutations.splice(t,1),n.start()}}assertCopyOnWriteSize(t,n,r){if(this.maxCopyOnWriteSize>0&&t>this.maxCopyOnWriteSize)throw new Error(`EFBIG: file too large for copy-on-write ${n} '${r}' (${t} bytes, max ${this.maxCopyOnWriteSize})`)}assertCopySize(t,n){if(this.maxCopySize>0&&t.size>this.maxCopySize)throw new Error(`EFBIG: file too large to copy '${n}' (${t.size} bytes, max ${this.maxCopySize})`)}randomTransactionToken(){return ay(16).toString("hex")}async openCopySource(t){let n=this.allowSymlinks?0:I.constants.O_NOFOLLOW,r=I.constants.O_RDONLY|I.constants.O_NONBLOCK|n,s=I.constants.O_NOATIME;if(process.platform!=="linux"||s===void 0)return I.promises.open(t,r);try{return await I.promises.open(t,r|s)}catch(i){if(i.code!=="EPERM")throw i;return I.promises.open(t,r)}}async replaceFile(t,n,r,s,i,o=!1){let a=Z.dirname(t),l="",c=null,u=r===null?438:384;for(let h=0;h<16;h++){l=Z.join(a,`.just-bash-write-${this.randomTransactionToken()}`);try{c=await I.promises.open(l,I.constants.O_WRONLY|I.constants.O_CREAT|I.constants.O_EXCL,u);break}catch(m){if(m.code!=="EEXIST")throw m}}if(!c)throw new Error(`EEXIST: replacement write '${t}'`);let f=c,d=await f.stat(),p=!1;try{try{let m=0,E=async b=>{let g=0;for(;g<b.byteLength;){let{bytesWritten:y}=await f.write(b,g,b.byteLength-g,m+g);if(y===0)throw new Error("EIO: replacement write made no progress");g+=y}m+=g};if(s){let b=Buffer.allocUnsafe(65536),g=0,y=s.size;for(;y>0;){let S=Math.min(b.length,y),{bytesRead:v}=await s.handle.read(b,0,S,g);if(v===0)break;await E(b.subarray(0,v)),g+=v,y-=v}}if(await E(n),r!==null&&await f.chmod(r.mode&(o?4095:511)),i)await f.utimes(i.atime,i.mtime);else if(r!==null){let b=await f.stat();await f.utimes(r.atime,b.mtime)}}finally{await f.close(),c=null}let h=await I.promises.lstat(l);if(!h.isFile()||h.dev!==d.dev||h.ino!==d.ino)throw new Error("EACCES: replacement staging entry changed");await I.promises.rename(l,t),p=!0}finally{c&&await c.close().catch(()=>{}),p||await I.promises.rm(l,{force:!0}).catch(()=>{})}}async exists(t){if(t.includes("\0"))return!1;let n=this.toRealPath(t);try{let r=this.resolveAndValidate(n,t);return await I.promises.access(r),!0}catch{return!1}}async stat(t){V(t,"stat");let n=this.toRealPath(t),r=this.resolveAndValidate(n,t);try{let s=await I.promises.lstat(r);if(!this.allowSymlinks&&s.isSymbolicLink())throw new Error(`EACCES: permission denied, '${t}' is a symlink`);return{isFile:s.isFile(),isDirectory:s.isDirectory(),isSymbolicLink:s.isSymbolicLink(),mode:s.mode,size:s.size,mtime:s.mtime,dev:s.dev,ino:s.ino,identity:`real:${s.dev}:${s.ino}`}}catch(s){if(s.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, stat '${t}'`);this.sanitizeError(s,t,"stat")}}async lstat(t){V(t,"lstat");let n=this.toRealPath(t),r=this.validateParent(n,t);try{let s=await I.promises.lstat(r);return{isFile:s.isFile(),isDirectory:s.isDirectory(),isSymbolicLink:s.isSymbolicLink(),mode:s.mode,size:s.size,mtime:s.mtime,dev:s.dev,ino:s.ino,identity:`real:${s.dev}:${s.ino}`}}catch(s){if(s.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);this.sanitizeError(s,t,"lstat")}}async mkdir(t,n){await this.withFilesystemMutation(()=>this.mkdirUnlocked(t,n))}async mkdirUnlocked(t,n){V(t,"mkdir");let r=this.toRealPath(t),s=r===this.root?this.resolveAndValidate(r,t):this.validateParent(r,t);try{await I.promises.mkdir(s,{recursive:n?.recursive})}catch(i){let o=i;if(o.code==="EEXIST")throw new Error(`EEXIST: file already exists, mkdir '${t}'`);if(o.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.sanitizeError(i,t,"mkdir")}}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){V(t,"scandir");let n=this.toRealPath(t),r=this.resolveAndValidate(n,t);try{if(!this.allowSymlinks&&(await I.promises.lstat(r)).isSymbolicLink())throw new Error(`EACCES: permission denied, '${t}' is a symlink`);return(await I.promises.readdir(r,{withFileTypes:!0})).map(i=>({name:i.name,isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink()})).sort((i,o)=>i.name<o.name?-1:i.name>o.name?1:0)}catch(s){let i=s;if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);if(i.code==="ENOTDIR")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);this.sanitizeError(s,t,"scandir")}}async rm(t,n){await this.withFilesystemMutation(()=>this.rmUnlocked(t,n))}async rmUnlocked(t,n){V(t,"rm");let r=this.toRealPath(t),s=this.validateParent(r,t);try{let i=await I.promises.lstat(s);if(!this.allowSymlinks&&i.isSymbolicLink())throw new Error(`EACCES: permission denied, '${t}' is a symlink`);await I.promises.rm(s,{recursive:n?.recursive??!1,force:n?.force??!1})}catch(i){let o=i;if(o.code==="ENOENT"){if(n?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}if(o.code==="ENOTEMPTY")throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);this.sanitizeError(i,t,"rm")}}async cp(t,n,r){await this.withFilesystemMutation(()=>this.cpUnlocked(t,n,r))}async cpUnlocked(t,n,r){V(t,"cp"),V(n,"cp");let s=this.toRealPath(t),i=this.toRealPath(n),o=this.validateParent(s,t),a=this.resolveAndValidate(i,n),l;try{l=await I.promises.lstat(o)}catch(c){if(c.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, cp '${t}'`);this.sanitizeError(c,t,"cp")}if(l.isDirectory()&&De(a,o))throw new Error(`EINVAL: cannot copy '${t}' into itself, '${n}'`);if(!l.isDirectory())try{let c=this.validateParent(i,n),u=await I.promises.lstat(c);if(l.dev===u.dev&&l.ino===u.ino)throw new Error(`EINVAL: cannot copy '${t}' onto itself, '${n}'`)}catch(c){if(c.code!=="ENOENT")throw c}if(l.isFile())try{let c=await I.promises.stat(a);if(l.dev===c.dev&&l.ino===c.ino)throw new Error(`EINVAL: cannot copy '${t}' onto itself, '${n}'`)}catch(c){if(c.code!=="ENOENT")throw c}try{await this.preflightCopyTree(o,t)}catch(c){this.sanitizeError(c,t,"cp")}if(l.isFile()||l.isSymbolicLink())try{await I.promises.mkdir(Z.dirname(a),{recursive:!0}),this.resolveAndValidate(i,n)}catch(c){this.sanitizeError(c,n,"cp")}try{await this.copyTreeEntry(o,i,t,n,r?.recursive??!1)}catch(c){let u=c;if(u.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, cp '${t}'`);if(u.code==="EISDIR")throw new Error(`EISDIR: is a directory, cp '${t}'`);this.sanitizeError(c,t,"cp")}}async copyTreeEntry(t,n,r,s,i){let o=await I.promises.lstat(t);if(o.isFile()){this.assertCopySize(o,r);let a=this.resolveAndValidate(n,s),l=await this.assertCopyDestinationWritable(a,s),c=await this.openCopySource(t);try{let u=await c.stat();if(!u.isFile()||u.dev!==o.dev||u.ino!==o.ino)throw new Error(`EACCES: file identity changed, cp '${r}'`);await this.replaceFile(a,new Uint8Array(0),l??o,{handle:c,size:o.size})}finally{await c.close()}return}if(o.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`EACCES: permission denied, cp '${r}' contains a symlink`);let a=await I.promises.readlink(t),l=Z.isAbsolute(a)?await this.toVirtualAbsoluteSymlinkTarget(a,r):a;await this.replaceSymlink(n,s,l);return}if(o.isDirectory()){if(!i)throw new Error(`EISDIR: is a directory, cp '${r}'`);let a=this.resolveAndValidate(n,s);await I.promises.mkdir(a,{recursive:!0}),a=this.resolveAndValidate(n,s);for(let l of await I.promises.readdir(t))await this.copyTreeEntry(Z.join(t,l),Z.join(n,l),Z.join(r,l),Z.join(s,l),!0);await I.promises.chmod(a,o.mode&4095);return}throw new Error(`EINVAL: unsupported file type, cp '${r}'`)}async assertCopyDestinationWritable(t,n){let r;try{r=await I.promises.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}if(!r.isFile()){if(r.isDirectory())return r;throw new Error(`EACCES: cannot copy over special file '${n}'`)}let s=this.allowSymlinks?0:I.constants.O_NOFOLLOW,i=await I.promises.open(t,I.constants.O_WRONLY|I.constants.O_NONBLOCK|s);try{let o=await i.stat();if(!o.isFile()||o.dev!==r.dev||o.ino!==r.ino)throw new Error(`EACCES: destination changed, cp '${n}'`)}finally{await i.close()}return r}async replaceSymlink(t,n,r){let s=this.validateParent(t,n),i=Z.dirname(W(n)),o="",a="",l="",c=null;for(let f=0;f<16;f++){let d=`.just-bash-copy-link-${this.randomTransactionToken()}`;o=i==="/"?`/${d}`:`${i}/${d}`,a=this.toRealPath(o);try{await this.symlinkUnlocked(r,o),l=this.validateParent(a,o),c=await I.promises.lstat(l);break}catch(p){let h=p;if(h.code!=="EEXIST"&&!h.message.startsWith("EEXIST:"))throw p}}if(!c)throw new Error(`EEXIST: replacement symlink '${n}'`);let u=!1;try{let f=await I.promises.lstat(l);if(!f.isSymbolicLink()||f.dev!==c.dev||f.ino!==c.ino)throw new Error("EACCES: replacement symlink entry changed");await I.promises.rename(l,s),u=!0}finally{!u&&l&&await I.promises.rm(l,{force:!0}).catch(()=>{})}}async toVirtualAbsoluteSymlinkTarget(t,n){let r=Z.resolve(t),s=await I.promises.realpath(r),i=await I.promises.realpath(Z.dirname(r)),o=Z.join(i,Z.basename(r));if(!De(s,this.canonicalRoot)||!De(o,this.canonicalRoot))throw new Error(`EACCES: permission denied, cp '${n}' contains an unsafe symlink`);return o.slice(this.canonicalRoot.length)||"/"}async preflightCopyTree(t,n,r=new Set){let s=await I.promises.lstat(t),i=`${s.dev}:${s.ino}`;if(r.has(i))throw new Error(`ELOOP: cp '${n}' contains a cycle`);if(s.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`EACCES: permission denied, cp '${n}' contains a symlink`);let o=await I.promises.realpath(t);if(!De(o,this.canonicalRoot))throw new Error(`EACCES: permission denied, cp '${n}' contains an unsafe symlink`);return}if(s.isDirectory()){r.add(i);try{let o=await I.promises.readdir(t);for(let a of o)await this.preflightCopyTree(Z.join(t,a),Z.join(n,a),r)}finally{r.delete(i)}}}async mv(t,n){await this.withFilesystemMutation(()=>this.mvUnlocked(t,n))}async mvUnlocked(t,n){V(t,"mv"),V(n,"mv");let r=this.toRealPath(t),s=this.toRealPath(n),i=this.validateParent(r,t),o=this.validateParent(s,n),a;try{a=await I.promises.lstat(i)}catch(c){if(c.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, mv '${t}'`);this.sanitizeError(c,t,"mv")}if(a.isDirectory()&&this.isSameOrDescendantIdentity(i,o))throw new Error(`EINVAL: cannot move '${t}' into itself, '${n}'`);try{if(a.isSymbolicLink()){let c=await I.promises.readlink(i),u=Z.resolve(Z.dirname(o),c),f=await I.promises.realpath(u).catch(()=>u);if(!De(f,this.canonicalRoot))throw new Error(`EACCES: permission denied, mv '${t}' -> '${n}' would create symlink escaping sandbox`)}}catch(c){let u=c;if(u.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, mv '${t}'`);if(u.message?.includes("EACCES")||u.message?.includes("escaping sandbox"))throw c}let l=Z.dirname(o);try{await I.promises.mkdir(l,{recursive:!0})}catch(c){this.sanitizeError(c,n,"mv")}try{await I.promises.rename(i,o)}catch(c){let u=c;if(u.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, mv '${t}'`);if(u.code==="EXDEV"){await this.moveAcrossDevices(t,n);return}this.sanitizeError(c,t,"mv")}try{if(I.lstatSync(o).isDirectory()&&this.findEscapingSymlinks(o).length>0)throw await I.promises.rename(o,i),new Error(`EACCES: permission denied, mv '${t}' -> '${n}' would create symlinks escaping sandbox`)}catch(c){if(c.message?.includes("EACCES")||c.message?.includes("escaping sandbox"))throw c;await I.promises.rename(o,i).catch(()=>{}),this.sanitizeError(c,n,"mv")}}isSameOrDescendantIdentity(t,n){let r=t,s=n;try{r=I.realpathSync(t)}catch{}try{s=I.realpathSync(n)}catch{try{let i=I.realpathSync(Z.dirname(n));s=Z.join(i,Z.basename(n))}catch{}}return De(s,r)}async uniqueTransactionPath(t,n){let r=Z.posix.dirname(t);for(let s=0;s<16;s++){let i=Z.posix.join(r,`.just-bash-mv-${n}-${this.randomTransactionToken()}`);if(!await this.exists(i))return i}throw new Error(`EEXIST: mv '${t}'`)}async moveAcrossDevices(t,n){let r=await this.uniqueTransactionPath(n,"stage"),s=await this.uniqueTransactionPath(n,"backup"),i=await this.uniqueTransactionPath(t,"source"),o=this.validateParent(this.toRealPath(r),r),a=this.validateParent(this.toRealPath(s),s),l=this.validateParent(this.toRealPath(t),t),c=this.validateParent(this.toRealPath(i),i),u=this.validateParent(this.toRealPath(n),n),f=!1,d=!1,p=!1,h=async()=>{p&&await I.promises.rename(c,l).catch(()=>{}),d&&await I.promises.rm(u,{recursive:!0,force:!0}).catch(()=>{}),f&&await I.promises.rename(a,u).catch(()=>{}),await I.promises.rm(o,{recursive:!0,force:!0}).catch(()=>{})};try{if(await this.cpUnlocked(t,r,{recursive:!0}),(await I.promises.lstat(o)).isDirectory()&&this.findEscapingSymlinks(o).length>0)throw new Error(`EACCES: permission denied, mv '${t}' -> '${n}' would create symlinks escaping sandbox`);try{await I.promises.rename(u,a),f=!0}catch(E){if(E.code!=="ENOENT")throw E}await I.promises.rename(o,u),d=!0,await I.promises.rename(l,c),p=!0,await I.promises.rm(c,{recursive:!0,force:!1}),p=!1,f&&await I.promises.rm(a,{recursive:!0,force:!0}).catch(()=>{})}catch(m){await h(),this.sanitizeError(m,t,"mv")}}resolvePath(t,n){return Bt(t,n)}getAllPaths(){let t=[];return this.scanDir("/",t),t}sanitizeError(t,n,r){qs(t,n,r,ly)}findEscapingSymlinks(t){let n=[],r=I.readdirSync(t);for(let s of r){let i=Z.join(t,s),o=I.lstatSync(i);if(o.isSymbolicLink()){let a=I.readlinkSync(i),l=Z.resolve(t,a),c;try{c=I.realpathSync(l)}catch(u){if(u.code!=="ENOENT")throw u;c=l}De(c,this.canonicalRoot)||n.push(i)}else o.isDirectory()&&n.push(...this.findEscapingSymlinks(i))}return n}scanDir(t,n){let r=this.toRealPath(t),s;try{s=this.resolveAndValidate(r,t)}catch{return}try{let i=I.readdirSync(s);for(let o of i){let a=t==="/"?`/${o}`:`${t}/${o}`;n.push(a);let l=Z.join(s,o);I.lstatSync(l).isDirectory()&&this.scanDir(a,n)}}catch{}}async chmod(t,n){await this.withFilesystemMutation(()=>this.chmodUnlocked(t,n))}async chmodUnlocked(t,n){V(t,"chmod");let r=this.toRealPath(t),s=this.resolveAndValidate(r,t);try{let i=await I.promises.lstat(s);if(!i.isFile()){if(!i.isDirectory()&&i.nlink>1)throw new Error(`EACCES: cannot chmod multiply-linked special file '${t}'`);await I.promises.chmod(s,n);return}if(i.nlink<=1){await I.promises.chmod(s,n);return}this.assertCopyOnWriteSize(i.size,"chmod",t);let o=await this.openCopySource(s);try{let a=await o.stat();if(!a.isFile())throw new Error(`EACCES: file type changed, chmod '${t}'`);await this.replaceFile(s,new Uint8Array(0),{mode:n,atime:a.atime,mtime:a.mtime},{handle:o,size:a.size},{atime:a.atime,mtime:a.mtime},!0)}finally{await o.close()}}catch(i){let o=i;if(o.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);if(o.code==="ELOOP")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(i,t,"chmod")}}async symlink(t,n){await this.withFilesystemMutation(()=>this.symlinkUnlocked(t,n))}async symlinkUnlocked(t,n){if(!this.allowSymlinks)throw new Error(`EPERM: operation not permitted, symlink '${n}'`);V(n,"symlink");let r=this.toRealPath(n),s=this.validateParent(r,n),i=W(n),o=W(Z.dirname(i)),a=t.startsWith("/")?W(t):W(o==="/"?`/${t}`:`${o}/${t}`),l=Z.join(this.canonicalRoot,a),c=Z.dirname(s),u=t.startsWith("/")?l:Z.relative(c,l)||".";try{await I.promises.symlink(u,s)}catch(f){if(f.code==="EEXIST")throw new Error(`EEXIST: file already exists, symlink '${n}'`);this.sanitizeError(f,n,"symlink")}}async link(t,n){await this.withFilesystemMutation(()=>this.linkUnlocked(t,n))}async linkUnlocked(t,n){V(t,"link"),V(n,"link");let r=this.toRealPath(t),s=this.toRealPath(n),i=this.resolveAndValidate(r,t),o=s===this.root?this.resolveAndValidate(s,n):this.validateParent(s,n);try{await I.promises.link(i,o)}catch(a){let l=a;if(l.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, link '${t}'`);if(l.code==="EEXIST")throw new Error(`EEXIST: file already exists, link '${n}'`);if(l.code==="EPERM")throw new Error(`EPERM: operation not permitted, link '${t}'`);this.sanitizeError(a,t,"link")}}async readlink(t){V(t,"readlink");let n=this.toRealPath(t),r=this.validateParent(n,t);try{let s=await I.promises.readlink(r),i=W(t),o=Z.dirname(i),a=Z.isAbsolute(s)?s:Z.resolve(Z.dirname(r),s),l=await I.promises.realpath(a).catch(()=>a);if(De(l,this.canonicalRoot)){let c=l.slice(this.canonicalRoot.length)||"/";return o==="/"?c.startsWith("/")?c.slice(1)||".":c:Z.relative(o,c)}return Z.basename(s)}catch(s){let i=s;if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(i.code==="EINVAL")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);this.sanitizeError(s,t,"readlink")}}async realpath(t){V(t,"realpath");let n=this.toRealPath(t);try{this.resolveAndValidate(n,t)}catch{throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}let r;try{r=await I.promises.realpath(n)}catch(s){let i=s;if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);if(i.code==="ELOOP")throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);this.sanitizeError(s,t,"realpath")}if(De(r,this.canonicalRoot))return r.slice(this.canonicalRoot.length)||"/";throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}async utimes(t,n,r){await this.withFilesystemMutation(()=>this.utimesUnlocked(t,n,r))}async utimesUnlocked(t,n,r){V(t,"utimes");let s=this.toRealPath(t),i=this.resolveAndValidate(s,t);try{let o=await I.promises.lstat(i);if(!o.isFile()){if(!o.isDirectory()&&o.nlink>1)throw new Error(`EACCES: cannot change times on multiply-linked special file '${t}'`);await I.promises.utimes(i,n,r);return}if(o.nlink<=1){await I.promises.utimes(i,n,r);return}this.assertCopyOnWriteSize(o.size,"utimes",t);let a=await this.openCopySource(i);try{let l=await a.stat();if(!l.isFile())throw new Error(`EACCES: file type changed, utimes '${t}'`);await this.replaceFile(i,new Uint8Array(0),l,{handle:a,size:l.size},{atime:n,mtime:r},!0)}finally{await a.close()}}catch(o){let a=o;if(a.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);if(a.code==="ELOOP")throw new Error(`EACCES: permission denied, '${t}' is a symlink`);this.sanitizeError(o,t,"utimes")}}};var Kn=class{cmdId;cwd;startedAt;exitCode;bashEnv;cmdLine;env;explicitCwd;signal;timeoutMs;abortController=new AbortController;timeoutId;externalAbortListener;resultPromise;constructor(t,n,r,s,i=!1,o,a){this.cmdId=crypto.randomUUID(),this.cwd=r,this.startedAt=new Date,this.bashEnv=t,this.cmdLine=n,this.env=s,this.explicitCwd=i,this.signal=o,this.timeoutMs=a,this.setupCancellation(),this.resultPromise=this.execute()}setupCancellation(){if(this.signal&&(this.signal.aborted?this.abortController.abort(this.signal.reason):(this.externalAbortListener=()=>{this.abortController.abort(this.signal?.reason)},this.signal.addEventListener("abort",this.externalAbortListener,{once:!0}))),this.timeoutMs!==void 0){let t=Math.max(0,this.timeoutMs);this.timeoutId=$r(()=>{this.abortController.abort(new Error(`sandbox command timeout after ${t}ms`))},t)}}cleanupCancellation(){this.timeoutId!==void 0&&(Cr(this.timeoutId),this.timeoutId=void 0),this.signal&&this.externalAbortListener&&(this.signal.removeEventListener("abort",this.externalAbortListener),this.externalAbortListener=void 0)}async execute(){let t={cwd:this.explicitCwd?this.cwd:void 0,env:this.env,signal:this.abortController.signal};try{let n=await this.bashEnv.exec(this.cmdLine,t);return this.exitCode=n.exitCode,n}finally{this.cleanupCancellation()}}async*logs(){let t=await this.resultPromise;t.stdout&&(yield{type:"stdout",data:t.stdout,timestamp:new Date}),t.stderr&&(yield{type:"stderr",data:t.stderr,timestamp:new Date})}async wait(){return await this.resultPromise,this}async output(){let t=await this.resultPromise;return t.stdout+t.stderr}async stdout(){return(await this.resultPromise).stdout}async stderr(){return(await this.resultPromise).stderr}async kill(){this.abortController.abort(new Error("command killed"))}};var Gs=class e{bashEnv;timeoutMs;constructor(t,n){this.bashEnv=t,this.timeoutMs=n}static async create(t){let n=t?.fs;if(t?.overlayRoot){if(t?.fs)throw new Error("Cannot specify both 'fs' and 'overlayRoot' options");n=new Qn({root:t.overlayRoot})}let r=new xr({env:t?.env,cwd:t?.cwd,fs:n,maxCallDepth:t?.maxCallDepth,maxCommandCount:t?.maxCommandCount,maxLoopIterations:t?.maxLoopIterations,network:t?.network,defenseInDepth:t?.defenseInDepth,python:t?.python,javascript:t?.javascript,commands:t?.commands,customCommands:t?.customCommands,fetch:t?.fetch});return new e(r,t?.timeoutMs)}async runCommand(t,n,r){let s,i,o,a,l=!1,c,u;if(typeof t=="object"){let m=t,E=[m.cmd,...m.args??[]];s=Js(E),i=m.cwd,o=m.env,a=m.signal,l=m.detached??!1,c=m.stdout,u=m.stderr}else if(Array.isArray(n)){let m=r;s=Js([t,...n]),a=m?.signal}else{s=t;let m=n;i=m?.cwd,o=m?.env}let f=i??this.bashEnv.getCwd(),d=i!==void 0,p=new Kn(this.bashEnv,s,f,o,d,a,this.timeoutMs);if(l)return p;let h=await p.wait();if(c){let m=await p.stdout();m&&c.write(m)}if(u){let m=await p.stderr();m&&u.write(m)}return h}async writeFiles(t){let n=this.bashEnv.getCwd();for(let[r,s]of Object.entries(t)){let i;typeof s=="string"?i=s:s.encoding==="base64"?i=Buffer.from(s.content,"base64").toString("utf-8"):i=s.content;let o=this.bashEnv.fs.resolvePath(n,r),a=o.substring(0,o.lastIndexOf("/"))||"/";a!=="/"&&await this.bashEnv.fs.mkdir(a,{recursive:!0}),await this.bashEnv.writeFile(o,i)}}async readFile(t,n){let r=await this.bashEnv.readFile(t);return n==="base64"?Buffer.from(r).toString("base64"):r}async mkDir(t,n){let r=this.bashEnv.fs.resolvePath(this.bashEnv.getCwd(),t);await this.bashEnv.fs.mkdir(r,{recursive:n?.recursive??!1})}async stop(){}async extendTimeout(t){}get domain(){}get bashEnvInstance(){return this.bashEnv}};var Zs=class{violations=[];violationsByType=new Map;options;constructor(t={}){this.options={maxViolationsPerType:t.maxViolationsPerType??100,maxViolationsTotal:t.maxViolationsTotal??1e3,includeStackTraces:t.includeStackTraces??!0,onViolation:t.onViolation??(()=>{}),logToConsole:t.logToConsole??!1}}record(t){let n=this.options.includeStackTraces?t:{...t,stack:void 0};this.violations.unshift(n),this.violations.length>this.options.maxViolationsTotal&&(this.violations.length=this.options.maxViolationsTotal);let r=this.violationsByType.get(t.type);r||(r=[],this.violationsByType.set(t.type,r)),r.length<this.options.maxViolationsPerType&&r.push(n),this.options.logToConsole&&console.warn(`[SecurityViolation] ${t.type}: ${t.message}`,t.path),this.options.onViolation(n)}getViolations(){return[...this.violations]}getViolationsByType(t){return[...this.violationsByType.get(t)??[]]}getSummary(){let t=[];for(let[n,r]of this.violationsByType){if(r.length===0)continue;let s=new Set,i=Number.POSITIVE_INFINITY,o=0;for(let a of r)s.add(a.path),i=Math.min(i,a.timestamp),o=Math.max(o,a.timestamp);t.push({type:n,count:r.length,firstSeen:i,lastSeen:o,paths:Array.from(s)})}return t.sort((n,r)=>r.count-n.count),t}getTotalCount(){return this.violations.length}hasViolations(){return this.violations.length>0}clear(){this.violations=[],this.violationsByType.clear()}createCallback(){return t=>this.record(t)}};function Tf(){return e=>{console.warn("[DefenseInDepth] Security violation detected:",`
|
|
803
805
|
Type: ${e.type}`,`
|
|
804
806
|
Path: ${e.path}`,`
|
|
805
807
|
Message: ${e.message}`,e.executionId?`
|
|
806
|
-
ExecutionId: ${e.executionId}`:"")}}var
|
|
808
|
+
ExecutionId: ${e.executionId}`:"")}}var Lf=null;try{let e=process.getBuiltinModule,t=typeof e=="function"?e("module"):typeof Ks=="function"?Ks("node:module"):null;Lf=t?.Module??t?.default??null,typeof e=="function"&&e("worker_threads")?.isMainThread===!1&&e("crypto")?.randomUUID?.()}catch{Lf=null}var fa=class{maxSourceBytes;plugins=[];constructor(t=67108864){if(this.maxSourceBytes=t,!Number.isSafeInteger(t)||t<0)throw new Error("BashTransformPipeline: invalid maxSourceBytes")}use(t){return this.plugins.push(t),this}transform(t){Pr(t,this.maxSourceBytes);let n=Ge(t),r=Object.create(null);for(let s of this.plugins){let i=s.transform({ast:n,metadata:r});n=i.ast,i.metadata&&(r=nr(r,i.metadata))}return{script:ur(n),ast:n,metadata:r}}};var da=class{name="command-collector";transform(t){let n=new Set;return this.walkScript(t.ast,n),{ast:t.ast,metadata:{commands:[...n].sort()}}}walkScript(t,n){for(let r of t.statements)this.walkStatement(r,n)}walkStatement(t,n){for(let r of t.pipelines)this.walkPipeline(r,n)}walkPipeline(t,n){for(let r of t.commands)this.walkCommand(r,n)}walkCommand(t,n){switch(t.type){case"SimpleCommand":if(t.name){let r=this.extractName(t.name);r&&n.add(r)}t.name&&this.walkWordParts(t.name.parts,n);for(let r of t.args)this.walkWordParts(r.parts,n);for(let r of t.assignments)if(r.value&&this.walkWordParts(r.value.parts,n),r.array)for(let s of r.array)this.walkWordParts(s.parts,n);break;case"If":for(let r of t.clauses){for(let s of r.condition)this.walkStatement(s,n);for(let s of r.body)this.walkStatement(s,n)}if(t.elseBody)for(let r of t.elseBody)this.walkStatement(r,n);break;case"For":if(t.words)for(let r of t.words)this.walkWordParts(r.parts,n);for(let r of t.body)this.walkStatement(r,n);break;case"CStyleFor":for(let r of t.body)this.walkStatement(r,n);break;case"While":case"Until":for(let r of t.condition)this.walkStatement(r,n);for(let r of t.body)this.walkStatement(r,n);break;case"Case":this.walkWordParts(t.word.parts,n);for(let r of t.items)for(let s of r.body)this.walkStatement(s,n);break;case"Subshell":case"Group":for(let r of t.body)this.walkStatement(r,n);break;case"ArithmeticCommand":case"ConditionalCommand":break;case"FunctionDef":this.walkCommand(t.body,n);break}}walkWordParts(t,n){for(let r of t)switch(r.type){case"CommandSubstitution":this.walkScript(r.body,n);break;case"ProcessSubstitution":this.walkScript(r.body,n);break;case"DoubleQuoted":this.walkWordParts(r.parts,n);break;case"ParameterExpansion":r.operation&&this.walkParameterOp(r.operation,n);break}}walkParameterOp(t,n){switch(t.type){case"DefaultValue":case"AssignDefault":case"UseAlternative":this.walkWordParts(t.word.parts,n);break;case"ErrorIfUnset":t.word&&this.walkWordParts(t.word.parts,n);break;case"PatternRemoval":this.walkWordParts(t.pattern.parts,n);break;case"PatternReplacement":this.walkWordParts(t.pattern.parts,n),t.replacement&&this.walkWordParts(t.replacement.parts,n);break;case"CaseModification":t.pattern&&this.walkWordParts(t.pattern.parts,n);break;case"Indirection":t.innerOp&&this.walkParameterOp(t.innerOp,n);break}}extractName(t){return t.parts.length===1&&t.parts[0].type==="Literal"?t.parts[0].value:null}};var pa=class{name="tee";options;counter=0;constructor(t){this.options=t}transform(t){let n=[],r=this.options.timestamp??new Date;return{ast:this.transformScript(t.ast,n,r),metadata:{teeFiles:n}}}formatTimestamp(t){return t.toISOString().replace(/:/g,"-")}generateStdoutPath(t,n,r){let s=this.formatTimestamp(r),i=String(t).padStart(3,"0");if(V(this.options.outputDir,"create tee output"),!this.options.outputDir.startsWith("/")||this.options.outputDir.split("/").includes(".."))throw new Error("tee output directory must be an absolute safe path");let o=W(this.options.outputDir),a=this.encodeCommandName(n),l=W(`${o}/${s}-${i}-${a}.stdout.txt`);if(o!=="/"&&!l.startsWith(`${o}/`))throw new Error("tee output path escapes configured output directory");return l}encodeCommandName(t){if(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(t))return t;let n=2166136261;for(let s=0;s<t.length;s++)n^=t.charCodeAt(s),n=Math.imul(n,16777619)>>>0;return`${t.replace(/[^A-Za-z0-9_-]/g,"_").replace(/^_+|_+$/g,"").slice(0,32)||"command"}-${n.toString(16).padStart(8,"0")}`}transformScript(t,n,r){return{...t,statements:t.statements.map(s=>this.transformStatement(s,n,r))}}transformStatement(t,n,r){let s=[],i=[];for(let o=0;o<t.pipelines.length;o++){let a=t.pipelines[o];o>0&&i.push(t.operators[o-1]);let l=this.transformPipeline(a,n,r);s.push(l.pipeline),l.origCmdNewIndices!==null&&(i.push(";"),s.push(this.makePipestatusRestore(l.origCmdNewIndices,l.negated)))}return{...t,pipelines:s,operators:i}}transformPipeline(t,n,r){if(t.commands.length<=1)return{pipeline:t,origCmdNewIndices:null,negated:!1};let s=[],i=[],o=[],a=!1;for(let l=0;l<t.commands.length;l++){let c=t.commands[l],u=l===t.commands.length-1;if(c.type!=="SimpleCommand"||!c.name||!this.shouldTarget(c)){o.push(s.length),s.push(c),u||i.push(t.pipeStderr?.[l]??!1);continue}let f=this.getCommandName(c.name)??"unknown",d=this.counter++,p=this.generateStdoutPath(d,f,r),h=this.makeTeeCommand(p),m=this.serializeCommand(c);n.push({commandIndex:d,commandName:f,command:m,stdoutFile:p}),o.push(s.length),s.push(c),i.push(t.pipeStderr?.[l]??!1),s.push(h),u||i.push(!1),a=!0}return a?{pipeline:{...t,negated:!1,commands:s,pipeStderr:i.length>0?i:void 0},origCmdNewIndices:o,negated:t.negated}:{pipeline:t,origCmdNewIndices:null,negated:!1}}makePipestatusRestore(t,n){return{type:"Pipeline",commands:[{type:"SimpleCommand",assignments:[],name:{type:"Word",parts:[{type:"Literal",value:"builtin"}]},args:[{type:"Word",parts:[{type:"Literal",value:"__just_bash_tee_restore"}]},...t.map(r=>({type:"Word",parts:[{type:"ParameterExpansion",parameter:`PIPESTATUS[${r}]`,operation:null}]}))],redirections:[]}],negated:n}}shouldTarget(t){if(!this.options.targetCommandPattern)return!0;let n=this.getCommandName(t.name);return n!==null&&this.options.targetCommandPattern.test(n)}getCommandName(t){return t&&t.parts.length===1&&t.parts[0].type==="Literal"?t.parts[0].value:null}serializeCommand(t){let n=[];t.name&&n.push(we(t.name));for(let r of t.args)n.push(we(r));return n.join(" ")}makeTeeCommand(t){return{type:"SimpleCommand",assignments:[],name:{type:"Word",parts:[{type:"Literal",value:"tee"}]},args:[{type:"Word",parts:[{type:"Literal",value:t}]}],redirections:[]}}};export{xr as Bash,fa as BashTransformPipeline,da as CommandCollectorPlugin,Le as DefenseInDepthBox,Xs as EMPTY_BYTES,ft as InMemoryFs,_n as MountableFs,rt as NetworkAccessDeniedError,Qn as OverlayFs,js as ReadWriteFs,Gn as RedirectNotAllowedError,Gs as Sandbox,Kn as SandboxCommand,_t as SecurityViolationError,Zs as SecurityViolationLogger,pa as TeePlugin,jn as TooManyRedirectsError,Uf as bytesOutput,Qf as createCommandContext,Tf as createConsoleViolationCallback,Wf as decodeBytesToUtf8,Kf as defineCommand,Tt as encodeUtf8ToBytes,qf as getCommandNames,Zf as getJavaScriptCommandNames,jf as getNetworkCommandNames,Gf as getPythonCommandNames,cn as latin1FromBytes,Ge as parse,ur as serialize,xt as stdoutAsBytes,Vf as stdoutKind,zf as textOutput,er as unsafeBytesFromLatin1};
|