just-bash 2.12.3 → 2.12.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/chunks/awk2-RGDNV4HO.js +2 -0
- package/dist/bin/chunks/chunk-4C4F4EKM.js +2 -0
- package/dist/bin/chunks/chunk-55QIFSKH.js +36 -0
- package/dist/bin/chunks/chunk-6MF2IYQX.js +10 -0
- package/dist/bin/chunks/chunk-DGFDVZ4N.js +21 -0
- package/dist/bin/chunks/chunk-EO5AH4U7.js +5 -0
- package/dist/bin/{shell/chunks/chunk-2SIXTZCJ.js → chunks/chunk-EZS766DD.js} +4 -4
- package/dist/bin/chunks/{chunk-435ZOZCY.js → chunk-J4WYAO5Q.js} +1 -1
- package/dist/bin/chunks/chunk-LHN3LRVT.js +100 -0
- package/dist/bin/{shell/chunks/chunk-JNPUO56K.js → chunks/chunk-NDP6L74Z.js} +1 -1
- package/dist/bin/chunks/chunk-PWZZGTFL.js +13 -0
- package/dist/bin/{shell/chunks/chunk-3NVWSLHI.js → chunks/chunk-Q3FNZYGG.js} +99 -99
- package/dist/bin/{shell/chunks/chunk-7SWOLTCR.js → chunks/chunk-Q4WHWGOT.js} +1 -1
- package/dist/bin/chunks/chunk-SY2WM5RM.js +14 -0
- package/dist/bin/chunks/chunk-SYG3IW7P.js +2 -0
- package/dist/bin/chunks/chunk-SYL34GE7.js +21 -0
- package/dist/bin/{shell/chunks/chunk-DREQRXNN.js → chunks/chunk-V5YFCVCZ.js} +1 -1
- package/dist/bin/chunks/chunk-V7VIJQD6.js +6 -0
- package/dist/bin/chunks/chunk-WMYKQURM.js +2 -0
- package/dist/bin/chunks/chunk-WO4B7WUT.js +2 -0
- package/dist/bin/chunks/expr-VEFRBJT4.js +2 -0
- package/dist/bin/{shell/chunks/flag-coverage-23ZUDENJ.js → chunks/flag-coverage-K6IBGWAC.js} +1 -1
- package/dist/bin/chunks/jq-VBB2XIZS.js +2 -0
- package/dist/bin/chunks/ln-BEOFQJNP.js +2 -0
- package/dist/bin/chunks/python3-JX5PXXTX.js +17 -0
- package/dist/bin/chunks/sed-BYFYBR4A.js +2 -0
- package/dist/bin/chunks/sleep-E3K6M6BN.js +2 -0
- package/dist/bin/chunks/sqlite3-SJHZFBT2.js +2 -0
- package/dist/bin/chunks/{tar-VIYVHMER.js → tar-W5GBTEDZ.js} +1 -1
- package/dist/bin/chunks/time-AWAKKRSE.js +2 -0
- package/dist/bin/chunks/timeout-OLS72AZG.js +2 -0
- package/dist/bin/chunks/tr-LZF57GYP.js +2 -0
- package/dist/bin/chunks/worker.js +92 -29
- package/dist/bin/chunks/xan-BJ66NSYT.js +2 -0
- package/dist/bin/chunks/yq-GPYVGU2N.js +2 -0
- package/dist/bin/just-bash.js +287 -287
- package/dist/bin/shell/chunks/awk2-RGDNV4HO.js +2 -0
- package/dist/bin/shell/chunks/chunk-4C4F4EKM.js +2 -0
- package/dist/bin/shell/chunks/chunk-55QIFSKH.js +36 -0
- package/dist/bin/shell/chunks/chunk-6MF2IYQX.js +10 -0
- package/dist/bin/shell/chunks/chunk-DGFDVZ4N.js +21 -0
- package/dist/bin/shell/chunks/chunk-EO5AH4U7.js +5 -0
- package/dist/bin/{chunks/chunk-2SIXTZCJ.js → shell/chunks/chunk-EZS766DD.js} +4 -4
- package/dist/bin/shell/chunks/{chunk-435ZOZCY.js → chunk-J4WYAO5Q.js} +1 -1
- package/dist/bin/shell/chunks/chunk-LHN3LRVT.js +100 -0
- package/dist/bin/{chunks/chunk-JNPUO56K.js → shell/chunks/chunk-NDP6L74Z.js} +1 -1
- package/dist/bin/shell/chunks/chunk-PWZZGTFL.js +13 -0
- package/dist/bin/{chunks/chunk-3NVWSLHI.js → shell/chunks/chunk-Q3FNZYGG.js} +99 -99
- package/dist/bin/{chunks/chunk-7SWOLTCR.js → shell/chunks/chunk-Q4WHWGOT.js} +1 -1
- package/dist/bin/shell/chunks/chunk-SY2WM5RM.js +14 -0
- package/dist/bin/shell/chunks/chunk-SYG3IW7P.js +2 -0
- package/dist/bin/shell/chunks/chunk-SYL34GE7.js +21 -0
- package/dist/bin/{chunks/chunk-DREQRXNN.js → shell/chunks/chunk-V5YFCVCZ.js} +1 -1
- package/dist/bin/shell/chunks/chunk-V7VIJQD6.js +6 -0
- package/dist/bin/shell/chunks/chunk-WMYKQURM.js +2 -0
- package/dist/bin/shell/chunks/chunk-WO4B7WUT.js +2 -0
- package/dist/bin/shell/chunks/expr-VEFRBJT4.js +2 -0
- package/dist/bin/{chunks/flag-coverage-23ZUDENJ.js → shell/chunks/flag-coverage-K6IBGWAC.js} +1 -1
- package/dist/bin/shell/chunks/jq-VBB2XIZS.js +2 -0
- package/dist/bin/shell/chunks/ln-BEOFQJNP.js +2 -0
- package/dist/bin/shell/chunks/python3-JX5PXXTX.js +17 -0
- package/dist/bin/shell/chunks/sed-BYFYBR4A.js +2 -0
- package/dist/bin/shell/chunks/sleep-E3K6M6BN.js +2 -0
- package/dist/bin/shell/chunks/sqlite3-SJHZFBT2.js +2 -0
- package/dist/bin/shell/chunks/{tar-VIYVHMER.js → tar-W5GBTEDZ.js} +1 -1
- package/dist/bin/shell/chunks/time-AWAKKRSE.js +2 -0
- package/dist/bin/shell/chunks/timeout-OLS72AZG.js +2 -0
- package/dist/bin/shell/chunks/tr-LZF57GYP.js +2 -0
- package/dist/bin/shell/chunks/xan-BJ66NSYT.js +2 -0
- package/dist/bin/shell/chunks/yq-GPYVGU2N.js +2 -0
- package/dist/bin/shell/shell.js +250 -250
- package/dist/bundle/browser.js +658 -658
- package/dist/bundle/chunks/awk2-XLDR2J4Q.js +1 -0
- package/dist/bundle/chunks/chunk-2OHMPZNZ.js +20 -0
- package/dist/bundle/chunks/chunk-3RCXHB4E.js +4 -0
- package/dist/bundle/chunks/chunk-CCNMISUL.js +1 -0
- package/dist/bundle/chunks/chunk-DOTBQEPN.js +5 -0
- package/dist/bundle/chunks/chunk-GENDESYN.js +1 -0
- package/dist/bundle/chunks/chunk-H4QOE4W3.js +99 -0
- package/dist/bundle/chunks/{chunk-C6ZZC5FL.js → chunk-K5BTXJQC.js} +99 -99
- package/dist/bundle/chunks/chunk-KAZYKNBG.js +13 -0
- package/dist/bundle/chunks/{chunk-XULIVM35.js → chunk-N4QLRJ32.js} +1 -1
- package/dist/bundle/chunks/{chunk-5CJQNRNJ.js → chunk-NTP6TTH5.js} +1 -1
- package/dist/bundle/chunks/chunk-QUME7R6S.js +9 -0
- package/dist/bundle/chunks/{chunk-U7QI5ZS5.js → chunk-RVT3MU3A.js} +4 -4
- package/dist/bundle/chunks/chunk-T2EHE3CV.js +1 -0
- package/dist/bundle/chunks/chunk-TBAWQWQB.js +12 -0
- package/dist/bundle/chunks/chunk-VYV3YE2F.js +35 -0
- package/dist/bundle/chunks/{chunk-UJIR5V54.js → chunk-W42IGK5R.js} +1 -1
- package/dist/bundle/chunks/{chunk-7BQDVPII.js → chunk-WAN3B6E3.js} +1 -1
- package/dist/bundle/chunks/chunk-XXZ46GOX.js +20 -0
- package/dist/bundle/chunks/chunk-ZK6J6F7O.js +1 -0
- package/dist/bundle/chunks/expr-74QHYJL5.js +1 -0
- package/dist/bundle/chunks/{flag-coverage-L3DCLG6V.js → flag-coverage-VGF5NAZP.js} +1 -1
- package/dist/bundle/chunks/jq-JQXAVWNT.js +1 -0
- package/dist/bundle/chunks/ln-RI2SJGXU.js +1 -0
- package/dist/bundle/chunks/python3-TSPOVUHX.js +16 -0
- package/dist/bundle/chunks/sed-CJFW7UYO.js +1 -0
- package/dist/bundle/chunks/sleep-TFDNFOXK.js +1 -0
- package/dist/bundle/chunks/sqlite3-CTI4ZW7L.js +1 -0
- package/dist/bundle/chunks/{tar-E2DVQEWO.js → tar-Y6LP5EBC.js} +1 -1
- package/dist/bundle/chunks/time-WBKSMCJ6.js +1 -0
- package/dist/bundle/chunks/timeout-O7WSXY5H.js +1 -0
- package/dist/bundle/chunks/tr-GVTWMRZB.js +1 -0
- package/dist/bundle/chunks/worker.js +92 -29
- package/dist/bundle/chunks/xan-VMLUNIDS.js +1 -0
- package/dist/bundle/chunks/yq-QXIYE3MW.js +1 -0
- package/dist/bundle/index.cjs +849 -849
- package/dist/bundle/index.js +225 -225
- package/dist/commands/awk/interpreter/context.d.ts +2 -0
- package/dist/commands/awk/interpreter/interpreter.d.ts +2 -0
- package/dist/commands/query-engine/evaluator.d.ts +3 -0
- package/dist/interpreter/defense-aware-command-context.d.ts +6 -0
- package/dist/interpreter/interpreter.d.ts +8 -0
- package/dist/interpreter/types.d.ts +5 -0
- package/dist/timers.d.ts +2 -11
- package/dist/types.d.ts +6 -0
- package/package.json +1 -1
- package/dist/bin/chunks/awk2-ZE5HJBNV.js +0 -2
- package/dist/bin/chunks/chunk-2FFXXW3F.js +0 -14
- package/dist/bin/chunks/chunk-4E3LY6YK.js +0 -10
- package/dist/bin/chunks/chunk-4FNW6LFM.js +0 -5
- package/dist/bin/chunks/chunk-4PZYIYYG.js +0 -36
- package/dist/bin/chunks/chunk-6L4K3UGO.js +0 -100
- package/dist/bin/chunks/chunk-EPIOK4SY.js +0 -6
- package/dist/bin/chunks/chunk-IYZRLSTQ.js +0 -2
- package/dist/bin/chunks/chunk-JJHAWOIB.js +0 -2
- package/dist/bin/chunks/chunk-KPWFKFSD.js +0 -21
- package/dist/bin/chunks/chunk-RYXW3SZQ.js +0 -13
- package/dist/bin/chunks/chunk-VZKEP45B.js +0 -21
- package/dist/bin/chunks/expr-MLHUWFYI.js +0 -2
- package/dist/bin/chunks/jq-CXSPO2J5.js +0 -2
- package/dist/bin/chunks/ln-5TCJXDGY.js +0 -2
- package/dist/bin/chunks/python3-74B25WCY.js +0 -17
- package/dist/bin/chunks/sed-DNLJZZXZ.js +0 -2
- package/dist/bin/chunks/sleep-GUJH2AMQ.js +0 -2
- package/dist/bin/chunks/sqlite3-57UI7HYL.js +0 -2
- package/dist/bin/chunks/time-FAWHHOMA.js +0 -2
- package/dist/bin/chunks/timeout-4O4YYRTS.js +0 -2
- package/dist/bin/chunks/tr-4V5A3V2C.js +0 -2
- package/dist/bin/chunks/xan-7NIVZ3HP.js +0 -2
- package/dist/bin/chunks/yq-L5ZSGLLO.js +0 -2
- package/dist/bin/shell/chunks/awk2-ZE5HJBNV.js +0 -2
- package/dist/bin/shell/chunks/chunk-2FFXXW3F.js +0 -14
- package/dist/bin/shell/chunks/chunk-4E3LY6YK.js +0 -10
- package/dist/bin/shell/chunks/chunk-4FNW6LFM.js +0 -5
- package/dist/bin/shell/chunks/chunk-4PZYIYYG.js +0 -36
- package/dist/bin/shell/chunks/chunk-6L4K3UGO.js +0 -100
- package/dist/bin/shell/chunks/chunk-EPIOK4SY.js +0 -6
- package/dist/bin/shell/chunks/chunk-IYZRLSTQ.js +0 -2
- package/dist/bin/shell/chunks/chunk-JJHAWOIB.js +0 -2
- package/dist/bin/shell/chunks/chunk-KPWFKFSD.js +0 -21
- package/dist/bin/shell/chunks/chunk-RYXW3SZQ.js +0 -13
- package/dist/bin/shell/chunks/chunk-VZKEP45B.js +0 -21
- package/dist/bin/shell/chunks/expr-MLHUWFYI.js +0 -2
- package/dist/bin/shell/chunks/jq-CXSPO2J5.js +0 -2
- package/dist/bin/shell/chunks/ln-5TCJXDGY.js +0 -2
- package/dist/bin/shell/chunks/python3-74B25WCY.js +0 -17
- package/dist/bin/shell/chunks/sed-DNLJZZXZ.js +0 -2
- package/dist/bin/shell/chunks/sleep-GUJH2AMQ.js +0 -2
- package/dist/bin/shell/chunks/sqlite3-57UI7HYL.js +0 -2
- package/dist/bin/shell/chunks/time-FAWHHOMA.js +0 -2
- package/dist/bin/shell/chunks/timeout-4O4YYRTS.js +0 -2
- package/dist/bin/shell/chunks/tr-4V5A3V2C.js +0 -2
- package/dist/bin/shell/chunks/xan-7NIVZ3HP.js +0 -2
- package/dist/bin/shell/chunks/yq-L5ZSGLLO.js +0 -2
- package/dist/bundle/chunks/awk2-T6LHPVZE.js +0 -1
- package/dist/bundle/chunks/chunk-5BFLZVGH.js +0 -20
- package/dist/bundle/chunks/chunk-7KHLIOOW.js +0 -4
- package/dist/bundle/chunks/chunk-AOFQVUAD.js +0 -99
- package/dist/bundle/chunks/chunk-BAAVD5NO.js +0 -20
- package/dist/bundle/chunks/chunk-BEFDX7IY.js +0 -1
- package/dist/bundle/chunks/chunk-KPFCTJEX.js +0 -12
- package/dist/bundle/chunks/chunk-LN5KAJOV.js +0 -5
- package/dist/bundle/chunks/chunk-NBAARP4B.js +0 -1
- package/dist/bundle/chunks/chunk-RHOPHAL6.js +0 -35
- package/dist/bundle/chunks/chunk-SL4FN3A5.js +0 -9
- package/dist/bundle/chunks/chunk-YIY2RKBW.js +0 -13
- package/dist/bundle/chunks/expr-3572LAOT.js +0 -1
- package/dist/bundle/chunks/jq-MYSLFARY.js +0 -1
- package/dist/bundle/chunks/ln-YAIFIHCT.js +0 -1
- package/dist/bundle/chunks/python3-6BKA3FYA.js +0 -16
- package/dist/bundle/chunks/sed-3ZCNFRHI.js +0 -1
- package/dist/bundle/chunks/sleep-LB7FI6AB.js +0 -1
- package/dist/bundle/chunks/sqlite3-FVNA4KNF.js +0 -1
- package/dist/bundle/chunks/time-AGNW2ZY6.js +0 -1
- package/dist/bundle/chunks/timeout-VN35D5O7.js +0 -1
- package/dist/bundle/chunks/tr-2N7Q3KKJ.js +0 -1
- package/dist/bundle/chunks/xan-VTO4FP3H.js +0 -1
- package/dist/bundle/chunks/yq-JRZFRYSK.js +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{a,b}from"./chunk-DGFDVZ4N.js";import"./chunk-4PRVMER6.js";import"./chunk-WO4B7WUT.js";import"./chunk-EO5AH4U7.js";import"./chunk-SE4C7FJY.js";import"./chunk-6KZRLMG3.js";import"./chunk-GTNBSMZR.js";import"./chunk-KGOUQS5A.js";export{a as awkCommand2,b as flagsForFuzzing};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import*as o from"node:fs";import*as r from"node:path";function y(t){if(!t||t==="/")return"/";let e=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;e.startsWith("/")||(e=`/${e}`);let n=e.split("/").filter(i=>i&&i!=="."),s=[];for(let i of n)i===".."?s.pop():s.push(i);return`/${s.join("/")}`||"/"}function u(t,e){return t===e||t.startsWith(`${e}/`)}function a(t,e){try{let n=o.realpathSync(t);return u(n,e)?n:null}catch(n){if(n.code==="ENOENT"){let s=r.dirname(t);if(s===t)return null;let i=a(s,e);if(i===null)return null;try{if(o.lstatSync(t).isSymbolicLink()){let l=o.readlinkSync(t),f=r.isAbsolute(l)?l:r.resolve(r.dirname(t),l);if(a(f,e)===null)return null}}catch{}return r.join(i,r.basename(t))}return null}}function m(t,e,n){let s=a(t,n);if(s===null)return null;let i=r.resolve(t),c=i.slice(e.length),l=s.slice(n.length);if(c!==l)return null;try{if(o.lstatSync(i).isSymbolicLink())return null}catch{}return s}function v(t,e){if(!o.existsSync(t))throw new Error(`${e} root does not exist`);if(!o.statSync(t).isDirectory())throw new Error(`${e} root is not a directory`)}function p(t,e){if(t.includes("\0"))throw new Error(`ENOENT: path contains null byte, ${e} '${t}'`)}function S(t,e){if(!r.isAbsolute(t))return{withinRoot:!0,relativePath:t};let n;try{n=o.realpathSync(t)}catch{n=r.resolve(t)}return u(n,e)?{withinRoot:!0,relativePath:n.slice(e.length)||"/"}:{withinRoot:!1,safeName:r.basename(t)}}export{y as a,u as b,a as c,m as d,v as e,p as f,S as g};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{a as x,b as w}from"./chunk-WMYKQURM.js";import{c as b}from"./chunk-WO4B7WUT.js";import{b as E}from"./chunk-EO5AH4U7.js";import{a as m}from"./chunk-SYG3IW7P.js";import{a as T,b as C}from"./chunk-GTNBSMZR.js";import{existsSync as k}from"node:fs";import{dirname as _,join as q}from"node:path";import{fileURLToPath as z}from"node:url";import{Worker as X}from"node:worker_threads";import Y from"sql.js";function V(e,r,n){switch(n.mode){case"list":return B(e,r,n);case"csv":return O(e,r,n);case"json":return N(e,r);case"line":return P(e,r,n);case"column":return R(e,r,n);case"table":return F(e,r,n);case"markdown":return Q(e,r,n);case"tabs":return U(e,r,n);case"box":return D(e,r,n);case"quote":return W(e,r,n);case"html":return H(e,r,n);case"ascii":return J(e,r,n)}}function f(e,r){return e==null?r:e instanceof Uint8Array||Buffer.isBuffer(e)?Buffer.from(e).toString("utf8"):typeof e=="number"&&!Number.isInteger(e)?e.toPrecision(17).replace(/\.?0+$/,""):String(e)}function B(e,r,n){let t=[];n.header&&e.length>0&&t.push(e.join(n.separator));for(let a of r)t.push(a.map(o=>f(o,n.nullValue)).join(n.separator));return t.length>0?`${t.join(n.newline)}${n.newline}`:""}function O(e,r,n){let t=[];n.header&&e.length>0&&t.push(e.map(L).join(","));for(let a of r)t.push(a.map(o=>L(f(o,n.nullValue))).join(","));return t.length>0?`${t.join(`
|
|
3
|
+
`)}
|
|
4
|
+
`:""}function L(e){return e.includes(",")||e.includes('"')||e.includes("'")||e.includes(`
|
|
5
|
+
`)?`"${e.replace(/"/g,'""')}"`:e}function A(e){return e.toPrecision(17).replace(/\.?0+$/,"")}function I(e){return e===null?"null":typeof e=="number"?Number.isInteger(e)?String(e):A(e):JSON.stringify(e)}function N(e,r){return r.length===0?"":`[${r.map(t=>`{${e.map((o,i)=>`${JSON.stringify(o)}:${I(t[i])}`).join(",")}}`).join(`,
|
|
6
|
+
`)}]
|
|
7
|
+
`}function P(e,r,n){if(e.length===0||r.length===0)return"";let t=Math.max(5,...e.map(o=>o.length)),a=[];for(let o of r)for(let i=0;i<e.length;i++){let s=e[i].padStart(t);a.push(`${s} = ${f(o[i],n.nullValue)}`)}return`${a.join(`
|
|
8
|
+
`)}
|
|
9
|
+
`}function R(e,r,n){if(e.length===0)return"";let t=e.map(o=>o.length);for(let o of r)for(let i=0;i<o.length;i++){let s=f(o[i],n.nullValue).length;s>t[i]&&(t[i]=s)}let a=[];n.header&&(a.push(e.map((o,i)=>o.padEnd(t[i])).join(" ")),a.push(t.map(o=>"-".repeat(o)).join(" ")));for(let o of r)a.push(o.map((i,s)=>f(i,n.nullValue).padEnd(t[s])).join(" "));return a.length>0?`${a.join(`
|
|
10
|
+
`)}
|
|
11
|
+
`:""}function F(e,r,n){if(e.length===0)return"";let t=e.map(i=>i.length);for(let i of r)for(let s=0;s<i.length;s++){let h=f(i[s],n.nullValue).length;h>t[s]&&(t[s]=h)}let a=[],o=`+${t.map(i=>"-".repeat(i+2)).join("+")}+`;a.push(o),n.header&&(a.push(`| ${e.map((i,s)=>i.padEnd(t[s])).join(" | ")} |`),a.push(o));for(let i of r)a.push(`| ${i.map((s,h)=>f(s,n.nullValue).padEnd(t[h])).join(" | ")} |`);return a.push(o),`${a.join(`
|
|
12
|
+
`)}
|
|
13
|
+
`}function Q(e,r,n){if(e.length===0)return"";let t=[];n.header&&(t.push(`| ${e.join(" | ")} |`),t.push(`|${e.map(()=>"---").join("|")}|`));for(let a of r)t.push(`| ${a.map(o=>f(o,n.nullValue)).join(" | ")} |`);return t.length>0?`${t.join(`
|
|
14
|
+
`)}
|
|
15
|
+
`:""}function U(e,r,n){let t=[];n.header&&e.length>0&&t.push(e.join(" "));for(let a of r)t.push(a.map(o=>f(o,n.nullValue)).join(" "));return t.length>0?`${t.join(n.newline)}${n.newline}`:""}function D(e,r,n){if(e.length===0)return"";let t=e.map(o=>o.length);for(let o of r)for(let i=0;i<o.length;i++){let s=f(o[i],n.nullValue).length;s>t[i]&&(t[i]=s)}let a=[];a.push(`\u250C${t.map(o=>"\u2500".repeat(o+2)).join("\u252C")}\u2510`),a.push(`\u2502 ${e.map((o,i)=>o.padEnd(t[i])).join(" \u2502 ")} \u2502`),a.push(`\u251C${t.map(o=>"\u2500".repeat(o+2)).join("\u253C")}\u2524`);for(let o of r)a.push(`\u2502 ${o.map((i,s)=>f(i,n.nullValue).padEnd(t[s])).join(" \u2502 ")} \u2502`);return a.push(`\u2514${t.map(o=>"\u2500".repeat(o+2)).join("\u2534")}\u2518`),`${a.join(`
|
|
16
|
+
`)}
|
|
17
|
+
`}function W(e,r,n){let t=[];n.header&&e.length>0&&t.push(e.map(a=>`'${a}'`).join(","));for(let a of r)t.push(a.map(o=>o==null?"NULL":typeof o=="number"?Number.isInteger(o)?String(o):A(o):`'${String(o)}'`).join(","));return t.length>0?`${t.join(n.newline)}${n.newline}`:""}function H(e,r,n){let t=[];n.header&&e.length>0&&(t.push(`<TR>${e.map(a=>`<TH>${M(a)}</TH>`).join("")}`),t.push("</TR>"));for(let a of r)t.push(`<TR>${a.map(o=>`<TD>${M(f(o,n.nullValue))}</TD>`).join("")}`),t.push("</TR>");return t.length>0?`${t.join(`
|
|
18
|
+
`)}
|
|
19
|
+
`:""}function M(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function J(e,r,n){let o=[];n.header&&e.length>0&&o.push(e.join(""));for(let i of r)o.push(i.map(s=>f(s,n.nullValue)).join(""));return o.length>0?o.join("")+"":""}var G=5e3,K={name:"sqlite3",summary:"SQLite database CLI",usage:"sqlite3 [OPTIONS] DATABASE [SQL]",options:["-list output in list mode (default)","-csv output in CSV mode","-json output in JSON mode","-line output in line mode","-column output in column mode","-table output as ASCII table","-markdown output as markdown table","-tabs output in tab-separated mode","-box output in Unicode box mode","-quote output in SQL quote mode","-html output as HTML table","-ascii output in ASCII mode (control chars)","-header show column headers","-noheader hide column headers","-separator SEP field separator for list mode (default: |)","-newline SEP row separator (default: \\n)","-nullvalue TEXT text for NULL values (default: empty)","-readonly open database read-only (no writeback)","-bail stop on first error","-echo print SQL before execution","-cmd COMMAND run SQL command before main SQL","-version show SQLite version","-- end of options","--help show this help"],examples:['sqlite3 :memory: "CREATE TABLE t(x); INSERT INTO t VALUES(1); SELECT * FROM t"','sqlite3 -json data.db "SELECT * FROM users"','sqlite3 -csv -header data.db "SELECT id, name FROM products"','sqlite3 -box data.db "SELECT * FROM users"']};function Z(e){let r={mode:"list",header:!1,separator:"|",newline:`
|
|
20
|
+
`,nullValue:"",readonly:!1,bail:!1,echo:!1,cmd:null},n=null,t=null,a=!1,o=!1;for(let i=0;i<e.length;i++){let s=e[i];if(o){n===null?n=s:t===null&&(t=s);continue}if(s==="--")o=!0;else if(s==="-version")a=!0;else if(s==="-list")r.mode="list";else if(s==="-csv")r.mode="csv";else if(s==="-json")r.mode="json";else if(s==="-line")r.mode="line";else if(s==="-column")r.mode="column";else if(s==="-table")r.mode="table";else if(s==="-markdown")r.mode="markdown";else if(s==="-tabs")r.mode="tabs";else if(s==="-box")r.mode="box";else if(s==="-quote")r.mode="quote";else if(s==="-html")r.mode="html";else if(s==="-ascii")r.mode="ascii";else if(s==="-header")r.header=!0;else if(s==="-noheader")r.header=!1;else if(s==="-readonly")r.readonly=!0;else if(s==="-bail")r.bail=!0;else if(s==="-echo")r.echo=!0;else if(s==="-separator"){if(i+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -separator
|
|
21
|
+
`,exitCode:1};r.separator=e[++i]}else if(s==="-newline"){if(i+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -newline
|
|
22
|
+
`,exitCode:1};r.newline=e[++i]}else if(s==="-nullvalue"){if(i+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -nullvalue
|
|
23
|
+
`,exitCode:1};r.nullValue=e[++i]}else if(s==="-cmd"){if(i+1>=e.length)return{stdout:"",stderr:`sqlite3: Error: missing argument to -cmd
|
|
24
|
+
`,exitCode:1};r.cmd=e[++i]}else{if(s.startsWith("-"))return{stdout:"",stderr:`sqlite3: Error: unknown option: ${s.startsWith("--")?s.slice(1):s}
|
|
25
|
+
Use -help for a list of options.
|
|
26
|
+
`,exitCode:1};n===null?n=s:t===null&&(t=s)}}return{options:r,database:n,sql:t,showVersion:a}}async function v(){let e=await E.runTrustedAsync(()=>Y()),r=new e.Database;try{let n=r.exec("SELECT sqlite_version()");return n.length>0&&n[0].values.length>0?String(n[0].values[0][0]):"unknown"}finally{r.close()}}function ee(){let e=_(z(import.meta.url)),r=q(e,"../../commands/sqlite3/worker.js");if(k(r))return r;let n=q(e,"worker.js");if(k(n))return n;let t=q(e,"../../../dist/commands/sqlite3/worker.js");if(k(t))return t;throw new Error("sqlite3 worker not found. Run 'pnpm build' to compile the worker.")}var re={createWorker(e,r){return new X(e,{workerData:r})}};function te(e){if(!e||typeof e!="object")return{success:!1,error:"Malformed worker response"};let r=e;return r.type==="security-violation"?{success:!1,error:`Security violation: ${typeof r.violation?.type=="string"?r.violation.type:"unknown"}`}:typeof r.success!="boolean"?{success:!1,error:"Malformed worker response: missing success flag"}:r.success?Array.isArray(r.results)?typeof r.hasModifications!="boolean"?{success:!1,error:"Malformed worker response: missing hasModifications flag"}:r.dbBuffer!==null&&r.dbBuffer!==void 0&&!(r.dbBuffer instanceof Uint8Array)?{success:!1,error:"Malformed worker response: invalid dbBuffer"}:{success:!0,results:r.results,hasModifications:r.hasModifications,dbBuffer:r.dbBuffer===void 0?null:r.dbBuffer,defenseStats:r.defenseStats}:{success:!1,error:"Malformed worker response: missing results array"}:{success:!1,error:typeof r.error=="string"&&r.error.length>0?r.error:"Worker execution failed"}}async function ne(e,r,n){try{let t=ee();return await new Promise((a,o)=>{let i=E.runTrusted(()=>re.createWorker(t,e)),s=b(n,"sqlite3","worker timeout callback",()=>{i.terminate(),a({success:!1,error:`Query timeout: execution exceeded ${r}ms limit`})}),c=x(()=>{try{s()}catch(u){let l=u instanceof Error?u.message:String(u);a({success:!1,error:m(l)})}},r),S=b(n,"sqlite3","worker message callback",u=>{w(c),a(te(u))}),$=b(n,"sqlite3","worker error callback",u=>{w(c),o(u)}),j=b(n,"sqlite3","worker exit callback",u=>{w(c),u!==0&&a({success:!1,error:`Worker exited with code ${u}`})}),p=u=>{try{S(u)}catch(l){w(c);let d=l instanceof Error?l.message:String(l);a({success:!1,error:m(d)})}},y=u=>{try{$(u)}catch(l){w(c);let d=l instanceof Error?l.message:String(l);o(new Error(m(d)))}},g=u=>{try{j(u)}catch(l){w(c);let d=l instanceof Error?l.message:String(l);a({success:!1,error:m(d)})}};i.on("message",p),i.on("error",y),i.on("exit",g)})}catch(t){let a=m(t.message);throw new Error(`sqlite3 worker failed to load: ${a}`)}}var ge={name:"sqlite3",async execute(e,r){if(C(e)||e.includes("-help"))return T(K);let n=Z(e);if("exitCode"in n)return n;let{options:t,database:a,sql:o,showVersion:i}=n;if(i)return{stdout:`${await v()}
|
|
27
|
+
`,stderr:"",exitCode:0};if(!a)return{stdout:"",stderr:`sqlite3: missing database argument
|
|
28
|
+
`,exitCode:1};let s=o||r.stdin.trim();if(t.cmd&&(s=t.cmd+(s?`; ${s}`:"")),!s)return{stdout:"",stderr:`sqlite3: no SQL provided
|
|
29
|
+
`,exitCode:1};let h=a===":memory:",c="",S=null;try{h||(c=r.fs.resolvePath(r.cwd,a),await r.fs.exists(c)&&(S=await r.fs.readFileBuffer(c)))}catch(l){let d=m(l.message);return{stdout:"",stderr:`sqlite3: unable to open database "${a}": ${d}
|
|
30
|
+
`,exitCode:1}}let $=r.limits?.maxSqliteTimeoutMs??G,j={dbBuffer:S,sql:s,options:{bail:t.bail,echo:t.echo}},p;try{p=await ne(j,$,r.requireDefenseContext)}catch(l){return{stdout:"",stderr:`sqlite3: worker error: ${m(l.message)}
|
|
31
|
+
`,exitCode:1}}if(!p.success)return{stdout:"",stderr:`sqlite3: ${m(p.error)}
|
|
32
|
+
`,exitCode:1};let y={mode:t.mode,header:t.header,separator:t.separator,newline:t.newline,nullValue:t.nullValue},g="";t.echo&&(g+=`${s}
|
|
33
|
+
`);let u=!1;for(let l of p.results)if(l.type==="error"){if(t.bail)return{stdout:g,stderr:`Error: ${l.error}
|
|
34
|
+
`,exitCode:1};g+=`Error: ${l.error}
|
|
35
|
+
`,u=!0}else l.columns&&l.rows&&(l.rows.length>0||t.header)&&(g+=V(l.columns,l.rows,y));if(p.hasModifications&&!t.readonly&&!h&&c&&p.dbBuffer)try{await r.fs.writeFile(c,p.dbBuffer)}catch(l){let d=m(l.message);return{stdout:g,stderr:`sqlite3: failed to write database: ${d}
|
|
36
|
+
`,exitCode:1}}return{stdout:g,stderr:"",exitCode:u&&t.bail?1:0}}},we={name:"sqlite3",flags:[],needsArgs:!0};export{re as a,ge as b,we as c};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{a as h}from"./chunk-SYG3IW7P.js";import{a as m,b as g}from"./chunk-GTNBSMZR.js";var p={name:"ln",summary:"make links between files",usage:"ln [OPTIONS] TARGET LINK_NAME",options:["-s create a symbolic link instead of a hard link","-f remove existing destination files","-n treat LINK_NAME as a normal file if it is a symbolic link to a directory","-v print name of each linked file"," --help display this help and exit"]},v={name:"ln",async execute(i,s){if(g(i))return m(p);let r=!1,a=!1,f=!1,t=0;for(;t<i.length&&i[t].startsWith("-");){let e=i[t];if(e==="-s"||e==="--symbolic")r=!0,t++;else if(e==="-f"||e==="--force")a=!0,t++;else if(e==="-v"||e==="--verbose")f=!0,t++;else if(e==="-n"||e==="--no-dereference")t++;else if(/^-[sfvn]+$/.test(e))e.includes("s")&&(r=!0),e.includes("f")&&(a=!0),e.includes("v")&&(f=!0),t++;else if(e==="--"){t++;break}else return{stdout:"",stderr:`ln: invalid option -- '${e.slice(1)}'
|
|
3
|
+
`,exitCode:1}}let d=i.slice(t);if(d.length<2)return{stdout:"",stderr:`ln: missing file operand
|
|
4
|
+
`,exitCode:1};let n=d[0],l=d[1],o=s.fs.resolvePath(s.cwd,l);if(await s.fs.exists(o))if(a)try{await s.fs.rm(o,{force:!0})}catch{return{stdout:"",stderr:`ln: cannot remove '${l}': Permission denied
|
|
5
|
+
`,exitCode:1}}else return{stdout:"",stderr:`ln: failed to create ${r?"symbolic ":""}link '${l}': File exists
|
|
6
|
+
`,exitCode:1};try{if(r)await s.fs.symlink(n,o);else{let e=s.fs.resolvePath(s.cwd,n);if(!await s.fs.exists(e))return{stdout:"",stderr:`ln: failed to access '${n}': No such file or directory
|
|
7
|
+
`,exitCode:1};await s.fs.link(e,o)}}catch(e){let u=e;return u.message.includes("EPERM")?{stdout:"",stderr:`ln: '${n}': hard link not allowed for directory
|
|
8
|
+
`,exitCode:1}:{stdout:"",stderr:`ln: ${h(u.message)}
|
|
9
|
+
`,exitCode:1}}let c="";return f&&(c=`'${l}' -> '${n}'
|
|
10
|
+
`),{stdout:c,stderr:"",exitCode:0}}},w={name:"ln",flags:[{flag:"-s",type:"boolean"},{flag:"-f",type:"boolean"},{flag:"-n",type:"boolean"},{flag:"-v",type:"boolean"}],needsArgs:!0,minArgs:2};export{v as a,w as b};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{a as de}from"./chunk-4PRVMER6.js";import{a as D,b as _}from"./chunk-WO4B7WUT.js";import{a as x}from"./chunk-EO5AH4U7.js";import{a as A,b as H}from"./chunk-SE4C7FJY.js";import{k as P}from"./chunk-6KZRLMG3.js";import{a as pe,b as fe,c as re}from"./chunk-GTNBSMZR.js";var Ue=1e4,Be=100,He=new H(/\s+/);function ie(e={}){let{fieldSep:t=He,maxIterations:n=Ue,maxRecursionDepth:i=Be,maxOutputSize:s=0,fs:a,cwd:o,exec:l,coverage:u,requireDefenseContext:N}=e;return{FS:" ",OFS:" ",ORS:`
|
|
3
|
+
`,OFMT:"%.6g",NR:0,NF:0,FNR:0,FILENAME:"",RSTART:0,RLENGTH:-1,SUBSEP:"",fields:[],line:"",vars:Object.create(null),arrays:Object.create(null),arrayAliases:new Map,ARGC:0,ARGV:Object.create(null),ENVIRON:Object.create(null),functions:new Map,fieldSep:t,maxIterations:n,maxRecursionDepth:i,maxOutputSize:s,currentRecursionDepth:0,exitCode:0,shouldExit:!1,shouldNext:!1,shouldNextFile:!1,loopBreak:!1,loopContinue:!1,hasReturn:!1,inEndBlock:!1,output:"",openedFiles:new Set,fs:a,cwd:o,exec:l,coverage:u,requireDefenseContext:N}}function Ee(e,t,n){switch(n){case"+":return e+t;case"-":return e-t;case"*":return e*t;case"/":return t!==0?e/t:0;case"%":return t!==0?e%t:0;case"^":case"**":return e**t;default:return 0}}function M(e){if(typeof e=="number")return e;let t=parseFloat(e);return Number.isNaN(t)?0:t}function k(e){return typeof e=="string"?e:(Number.isInteger(e),String(e))}async function z(e,t){if(e.type==="regex")return e.pattern;let n=k(await t.evalExpr(e));return n.startsWith("/")&&n.endsWith("/")&&(n=n.slice(1,-1)),n}async function ye(e,t){return e?e.type==="variable"?e.name:e.type==="field"?`$${Math.floor(M(await t.evalExpr(e.index)))}`:"$0":"$0"}function me(e,t){if(e==="$0")return t.line;if(e.startsWith("$")){let n=parseInt(e.slice(1),10)-1;return t.fields[n]||""}return k(t.vars[e]??"")}function Se(e,t,n){if(e==="$0")n.line=t,n.fields=n.FS===" "?t.trim().split(/\s+/).filter(Boolean):n.fieldSep.split(t),n.NF=n.fields.length;else if(e.startsWith("$")){let i=parseInt(e.slice(1),10)-1;for(;n.fields.length<=i;)n.fields.push("");n.fields[i]=t,n.NF=n.fields.length,n.line=n.fields.join(n.OFS)}else n.vars[e]=t}async function $e(e,t,n){return e.length===0?t.line.length:k(await n.evalExpr(e[0])).length}async function We(e,t,n){if(e.length<2)return"";let i=k(await n.evalExpr(e[0])),s=Math.floor(M(await n.evalExpr(e[1])))-1;if(e.length>=3){let a=Math.floor(M(await n.evalExpr(e[2])));return i.substr(Math.max(0,s),a)}return i.substr(Math.max(0,s))}async function Ve(e,t,n){if(e.length<2)return 0;let i=k(await n.evalExpr(e[0])),s=k(await n.evalExpr(e[1])),a=i.indexOf(s);return a===-1?0:a+1}async function Ke(e,t,n){if(e.length<2)return 0;let i=k(await n.evalExpr(e[0])),s=e[1];if(s.type!=="variable")return 0;let a=s.name,o=t.FS;if(e.length>=3){let u=e[2];if(u.type==="regex")o=A(u.pattern);else{let N=k(await n.evalExpr(u));o=N===" "?A("\\s+"):N}}else t.FS===" "&&(o=A("\\s+"));let l=typeof o=="string"?i.split(o):o.split(i);t.arrays[a]=Object.create(null);for(let u=0;u<l.length;u++)t.arrays[a][String(u+1)]=l[u];return l.length}async function Xe(e,t,n){if(e.length<2)return 0;let i=await z(e[0],n),s=k(await n.evalExpr(e[1])),a=await ye(e[2],n),o=me(a,t);try{let u=A(i).replace(o,we(s)),N=u!==o?1:0;return Se(a,u,t),N}catch{return 0}}async function qe(e,t,n){if(e.length<2)return 0;let i=await z(e[0],n),s=k(await n.evalExpr(e[1])),a=await ye(e[2],n),o=me(a,t);try{let l=A(i,"g"),u=l.match(o),N=u?u.length:0,v=l.replace(o,we(s));return Se(a,v,t),N}catch{return 0}}function we(e){return t=>{let n="",i=0;for(;i<e.length;)if(e[i]==="\\"&&i+1<e.length){let s=e[i+1];s==="&"?(n+="&",i+=2):s==="\\"?(n+="\\",i+=2):(n+=e[i+1],i+=2)}else e[i]==="&"?(n+=t,i++):(n+=e[i],i++);return n}}async function ze(e,t,n){if(e.length<2)return t.RSTART=0,t.RLENGTH=-1,0;let i=k(await n.evalExpr(e[0])),s=await z(e[1],n);try{let o=A(s).exec(i);if(o)return t.RSTART=o.index+1,t.RLENGTH=o[0].length,t.RSTART}catch{}return t.RSTART=0,t.RLENGTH=-1,0}async function je(e,t,n){if(e.length<3)return"";let i=await z(e[0],n),s=k(await n.evalExpr(e[1])),a=k(await n.evalExpr(e[2])),o=e.length>=4?k(await n.evalExpr(e[3])):t.line;try{let l=a.toLowerCase()==="g",u=l?0:parseInt(a,10)||1;if(l)return A(i,"g").replace(o,(v,...C)=>Ne(s,v,C.slice(0,-2)));{let N=0;return A(i,"g").replace(o,(C,...O)=>(N++,N===u?Ne(s,C,O.slice(0,-2)):C))}}catch{return o}}function Ne(e,t,n){let i="",s=0;for(;s<e.length;)if(e[s]==="\\"&&s+1<e.length){let a=e[s+1];if(a==="&")i+="&",s+=2;else if(a==="0")i+=t,s+=2;else if(a>="1"&&a<="9"){let o=parseInt(a,10)-1;i+=n[o]||"",s+=2}else a==="n"?(i+=`
|
|
4
|
+
`,s+=2):a==="t"?(i+=" ",s+=2):(i+=a,s+=2)}else e[s]==="&"?(i+=t,s++):(i+=e[s],s++);return i}async function Qe(e,t,n){return e.length===0?"":k(await n.evalExpr(e[0])).toLowerCase()}async function Je(e,t,n){return e.length===0?"":k(await n.evalExpr(e[0])).toUpperCase()}async function Ze(e,t,n){if(e.length===0)return"";let i=k(await n.evalExpr(e[0])),s=[];for(let a=1;a<e.length;a++)s.push(await n.evalExpr(e[a]));return j(i,s)}async function Ye(e,t,n){return e.length===0?0:Math.floor(M(await n.evalExpr(e[0])))}async function et(e,t,n){return e.length===0?0:Math.sqrt(M(await n.evalExpr(e[0])))}async function tt(e,t,n){return e.length===0?0:Math.sin(M(await n.evalExpr(e[0])))}async function nt(e,t,n){return e.length===0?0:Math.cos(M(await n.evalExpr(e[0])))}async function rt(e,t,n){let i=e.length>0?M(await n.evalExpr(e[0])):0,s=e.length>1?M(await n.evalExpr(e[1])):0;return Math.atan2(i,s)}async function it(e,t,n){return e.length===0?0:Math.log(M(await n.evalExpr(e[0])))}async function st(e,t,n){return e.length===0?1:Math.exp(M(await n.evalExpr(e[0])))}function at(e,t,n){return t.random?t.random():Math.random()}async function ot(e,t,n){let i=e.length>0?M(await n.evalExpr(e[0])):Date.now();return t.vars._srand_seed=i,i}function lt(e,t){return()=>{throw new Error(`${e}() is not supported - ${t}`)}}function se(e){return()=>{throw new Error(`function '${e}()' is not implemented`)}}var U=1e4;function j(e,t){let n=0,i="",s=0;for(;s<e.length;)if(e[s]==="%"&&s+1<e.length){let a=s+1,o="",l="",u="",N,v=a;for(;a<e.length&&/\d/.test(e[a]);)a++;a>v&&e[a]==="$"?(N=parseInt(e.substring(v,a),10)-1,a++):a=v;let C=()=>{if(a<e.length){if(a+1<e.length&&(e[a]==="h"&&e[a+1]==="h"||e[a]==="l"&&e[a+1]==="l")){a+=2;return}/[lzjh]/.test(e[a])&&a++}};for(;a<e.length&&/[-+ #0]/.test(e[a]);)o+=e[a++];if(e[a]==="*"){let d=t[n++],R=d!==void 0?Math.floor(Number(d)):0;R<0?(o+="-",l=String(Math.min(-R,U))):l=String(Math.min(R,U)),a++}else for(;a<e.length&&/\d/.test(e[a]);)l+=e[a++];if(l&&parseInt(l,10)>U&&(l=String(U)),e[a]==="."){if(a++,e[a]==="*"){let d=t[n++];u=String(Math.min(d!==void 0?Math.floor(Number(d)):0,U)),a++}else for(;a<e.length&&/\d/.test(e[a]);)u+=e[a++];u&&parseInt(u,10)>U&&(u=String(U))}C();let O=e[a],w=t[N!==void 0?N:n];switch(O){case"s":{let d=w!==void 0?String(w):"";if(u&&(d=d.substring(0,parseInt(u,10))),l){let R=parseInt(l,10);o.includes("-")?d=d.padEnd(R):d=d.padStart(R)}i+=d,N===void 0&&n++;break}case"d":case"i":{let d=w!==void 0?Math.floor(Number(w)):0;Number.isNaN(d)&&(d=0);let R=d<0,h=Math.abs(d).toString();if(u){let F=parseInt(u,10);h=h.padStart(F,"0")}let c="";R?c="-":o.includes("+")?c="+":o.includes(" ")&&(c=" ");let E=c+h;if(l){let F=parseInt(l,10);o.includes("-")?E=E.padEnd(F):o.includes("0")&&!u?E=c+h.padStart(F-c.length,"0"):E=E.padStart(F)}i+=E,N===void 0&&n++;break}case"f":{let d=w!==void 0?Number(w):0;Number.isNaN(d)&&(d=0);let R=u?parseInt(u,10):6,h=d.toFixed(R);if(l){let c=parseInt(l,10);o.includes("-")?h=h.padEnd(c):h=h.padStart(c)}i+=h,N===void 0&&n++;break}case"e":case"E":{let d=w!==void 0?Number(w):0;Number.isNaN(d)&&(d=0);let R=u?parseInt(u,10):6,h=d.toExponential(R);if(O==="E"&&(h=h.toUpperCase()),l){let c=parseInt(l,10);o.includes("-")?h=h.padEnd(c):h=h.padStart(c)}i+=h,N===void 0&&n++;break}case"g":case"G":{let d=w!==void 0?Number(w):0;Number.isNaN(d)&&(d=0);let R=u?parseInt(u,10):6,h=d!==0?Math.floor(Math.log10(Math.abs(d))):0,c;if(d===0?c="0":h<-4||h>=R?(c=d.toExponential(R-1),O==="G"&&(c=c.toUpperCase())):c=d.toPrecision(R),c.includes(".")&&(c=c.replace(/\.?0+$/,"").replace(/\.?0+e/,"e")),c.includes("e")&&(c=c.replace(/\.?0+e/,"e")),l){let E=parseInt(l,10);o.includes("-")?c=c.padEnd(E):c=c.padStart(E)}i+=c,N===void 0&&n++;break}case"x":case"X":{let d=w!==void 0?Math.floor(Number(w)):0;Number.isNaN(d)&&(d=0);let R=Math.abs(d).toString(16);if(O==="X"&&(R=R.toUpperCase()),u){let E=parseInt(u,10);R=R.padStart(E,"0")}let h=d<0?"-":"",c=h+R;if(l){let E=parseInt(l,10);o.includes("-")?c=c.padEnd(E):o.includes("0")&&!u?c=h+R.padStart(E-h.length,"0"):c=c.padStart(E)}i+=c,N===void 0&&n++;break}case"o":{let d=w!==void 0?Math.floor(Number(w)):0;Number.isNaN(d)&&(d=0);let R=Math.abs(d).toString(8);if(u){let E=parseInt(u,10);R=R.padStart(E,"0")}let h=d<0?"-":"",c=h+R;if(l){let E=parseInt(l,10);o.includes("-")?c=c.padEnd(E):o.includes("0")&&!u?c=h+R.padStart(E-h.length,"0"):c=c.padStart(E)}i+=c,N===void 0&&n++;break}case"c":{typeof w=="number"?i+=String.fromCharCode(w):i+=String(w??"").charAt(0)||"",N===void 0&&n++;break}case"%":i+="%";break;default:i+=e.substring(s,a+1)}s=a+1}else if(e[s]==="\\"&&s+1<e.length){let a=e[s+1];switch(a){case"n":i+=`
|
|
5
|
+
`;break;case"t":i+=" ";break;case"r":i+="\r";break;case"\\":i+="\\";break;default:i+=a}s+=2}else i+=e[s++];return i}var Re=new Map([["length",$e],["substr",We],["index",Ve],["split",Ke],["sub",Xe],["gsub",qe],["match",ze],["gensub",je],["tolower",Qe],["toupper",Je],["sprintf",Ze],["int",Ye],["sqrt",et],["sin",tt],["cos",nt],["atan2",rt],["log",it],["exp",st],["rand",at],["srand",ot],["system",lt("system","shell execution not allowed in sandboxed environment")],["close",()=>0],["fflush",()=>0],["systime",se("systime")],["mktime",se("mktime")],["strftime",se("strftime")]]);function b(e){return typeof e=="number"?e!==0:!(e===""||e==="0")}function g(e){if(typeof e=="number")return e;let t=parseFloat(e);return Number.isNaN(t)?0:t}function S(e){return typeof e=="string"?e:(Number.isInteger(e),String(e))}function ae(e){if(typeof e=="number")return!0;let t=String(e).trim();return t===""?!1:!Number.isNaN(Number(t))}function K(e,t){try{return A(e).test(t)}catch{return!1}}function ge(e,t){return t===""?[]:e.FS===" "?t.trim().split(/\s+/).filter(Boolean):e.fieldSep.split(t)}function Q(e,t){return t===0?e.line:t<0||t>e.fields.length?"":e.fields[t-1]??""}function oe(e,t,n){if(t===0)e.line=S(n),e.fields=ge(e,e.line),e.NF=e.fields.length;else if(t>0){for(;e.fields.length<t;)e.fields.push("");e.fields[t-1]=S(n),e.NF=e.fields.length,e.line=e.fields.join(e.OFS)}}function $(e,t){e.line=t,e.fields=ge(e,t),e.NF=e.fields.length}function ve(e,t){if(e.FS=t,t===" ")e.fieldSep=new H(/\s+/);else try{e.fieldSep=A(t)}catch{e.fieldSep=A(t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"))}}function J(e,t){switch(t){case"FS":return e.FS;case"OFS":return e.OFS;case"ORS":return e.ORS;case"OFMT":return e.OFMT;case"NR":return e.NR;case"NF":return e.NF;case"FNR":return e.FNR;case"FILENAME":return e.FILENAME;case"RSTART":return e.RSTART;case"RLENGTH":return e.RLENGTH;case"SUBSEP":return e.SUBSEP;case"ARGC":return e.ARGC}return e.vars[t]??""}function W(e,t,n){switch(t){case"FS":ve(e,S(n));return;case"OFS":e.OFS=S(n);return;case"ORS":e.ORS=S(n);return;case"OFMT":e.OFMT=S(n);return;case"NR":e.NR=Math.floor(g(n));return;case"NF":{let i=Math.floor(g(n));if(i<e.NF)e.fields=e.fields.slice(0,i),e.line=e.fields.join(e.OFS);else if(i>e.NF){for(;e.fields.length<i;)e.fields.push("");e.line=e.fields.join(e.OFS)}e.NF=i;return}case"FNR":e.FNR=Math.floor(g(n));return;case"FILENAME":e.FILENAME=S(n);return;case"RSTART":e.RSTART=Math.floor(g(n));return;case"RLENGTH":e.RLENGTH=Math.floor(g(n));return;case"SUBSEP":e.SUBSEP=S(n);return}e.vars[t]=n}function X(e,t){let n=t,i=new Set,s=e.arrayAliases.get(n);for(;s!==void 0&&!i.has(n);)i.add(n),n=s,s=e.arrayAliases.get(n);return n}function Z(e,t,n){if(t==="ARGV")return e.ARGV[n]??"";if(t==="ENVIRON")return e.ENVIRON[n]??"";let i=X(e,t);return e.arrays[i]?.[n]??""}function le(e,t,n,i){let s=X(e,t);e.arrays[s]||(e.arrays[s]=Object.create(null)),e.arrays[s][n]=i}function Ae(e,t,n){if(t==="ARGV")return e.ARGV[n]!==void 0;if(t==="ENVIRON")return e.ENVIRON[n]!==void 0;let i=X(e,t);return e.arrays[i]?.[n]!==void 0}function Ie(e,t,n){let i=X(e,t);e.arrays[i]&&delete e.arrays[i][n]}function ke(e,t){let n=X(e,t);delete e.arrays[n]}var Ce=null;function be(e){Ce=e}function L(e,t){D(e.requireDefenseContext,"awk",t)}function m(e,t,n){return _(e.requireDefenseContext,"awk",t,n)}async function f(e,t){switch(L(e,"expression evaluation"),e.coverage?.hit(`awk:expr:${t.type}`),t.type){case"number":return t.value;case"string":return t.value;case"regex":return K(t.pattern,e.line)?1:0;case"field":return ut(e,t);case"variable":return J(e,t.name);case"array_access":return ct(e,t);case"binary":return ht(e,t);case"unary":return dt(e,t);case"ternary":return b(await m(e,"ternary condition evaluation",()=>f(e,t.condition)))?await m(e,"ternary consequent evaluation",()=>f(e,t.consequent)):await m(e,"ternary alternate evaluation",()=>f(e,t.alternate));case"call":return Et(e,t.name,t.args);case"assignment":return yt(e,t);case"pre_increment":return mt(e,t.operand);case"pre_decrement":return St(e,t.operand);case"post_increment":return wt(e,t.operand);case"post_decrement":return Rt(e,t.operand);case"in":return gt(e,t.key,t.array);case"getline":return vt(e,t.variable,t.file,t.command);case"tuple":return kt(e,t.elements);default:return""}}async function ut(e,t){L(e,"field reference evaluation");let n=Math.floor(g(await m(e,"field index evaluation",()=>f(e,t.index))));return Q(e,n)}async function ct(e,t){L(e,"array access evaluation");let n=S(await m(e,"array key evaluation",()=>f(e,t.key)));return Z(e,t.array,n)}async function ht(e,t){L(e,"binary expression evaluation");let n=t.operator;if(n==="||")return b(await m(e,"logical-or left evaluation",()=>f(e,t.left)))||b(await m(e,"logical-or right evaluation",()=>f(e,t.right)))?1:0;if(n==="&&")return b(await m(e,"logical-and left evaluation",()=>f(e,t.left)))&&b(await m(e,"logical-and right evaluation",()=>f(e,t.right)))?1:0;if(n==="~"){let l=await m(e,"regex left evaluation",()=>f(e,t.left));t.right.type==="regex"&&e.coverage?.hit("awk:expr:regex");let u=t.right.type==="regex"?t.right.pattern:S(await m(e,"regex right evaluation",()=>f(e,t.right)));try{return A(u).test(S(l))?1:0}catch{return 0}}if(n==="!~"){let l=await m(e,"negated-regex left evaluation",()=>f(e,t.left));t.right.type==="regex"&&e.coverage?.hit("awk:expr:regex");let u=t.right.type==="regex"?t.right.pattern:S(await m(e,"negated-regex right evaluation",()=>f(e,t.right)));try{return A(u).test(S(l))?0:1}catch{return 1}}let i=await m(e,"binary left evaluation",()=>f(e,t.left)),s=await m(e,"binary right evaluation",()=>f(e,t.right));if(n===" "){let l=S(i)+S(s);if(e.maxOutputSize>0&&l.length>e.maxOutputSize)throw new P(`awk: string concatenation size limit exceeded (${e.maxOutputSize} bytes)`,"string_length",e.output);return l}if(pt(n))return ft(i,s,n);let a=g(i),o=g(s);return Ee(a,o,n)}function pt(e){return["<","<=",">",">=","==","!="].includes(e)}function ft(e,t,n){let i=ae(e),s=ae(t);if(i&&s){let l=g(e),u=g(t);switch(n){case"<":return l<u?1:0;case"<=":return l<=u?1:0;case">":return l>u?1:0;case">=":return l>=u?1:0;case"==":return l===u?1:0;case"!=":return l!==u?1:0}}let a=S(e),o=S(t);switch(n){case"<":return a<o?1:0;case"<=":return a<=o?1:0;case">":return a>o?1:0;case">=":return a>=o?1:0;case"==":return a===o?1:0;case"!=":return a!==o?1:0}return 0}async function dt(e,t){L(e,"unary expression evaluation");let n=await m(e,"unary operand evaluation",()=>f(e,t.operand));switch(t.operator){case"!":return b(n)?0:1;case"-":return-g(n);case"+":return+g(n);default:return n}}async function Et(e,t,n){L(e,"function call evaluation");let i=Re.get(t);if(i)return i(n,e,{evalExpr:a=>f(e,a)});let s=e.functions.get(t);return s?Nt(e,s,n):""}async function Nt(e,t,n){if(L(e,"user function call"),e.currentRecursionDepth++,e.currentRecursionDepth>e.maxRecursionDepth)throw e.currentRecursionDepth--,new P(`awk: recursion depth exceeded maximum (${e.maxRecursionDepth})`,"recursion",e.output);let i=Object.create(null);for(let l of t.params)i[l]=e.vars[l];let s=[];for(let l=0;l<t.params.length;l++){let u=t.params[l];if(l<n.length){let N=n[l];N.type==="variable"&&(e.arrayAliases.set(u,N.name),s.push(u));let v=await m(e,"user function argument evaluation",()=>f(e,N));e.vars[u]=v}else e.vars[u]=""}e.hasReturn=!1,e.returnValue=void 0;let a=Ce;a&&await m(e,"user function body execution",()=>a(e,t.body.statements));let o=e.returnValue??"";for(let l of t.params)i[l]!==void 0?e.vars[l]=i[l]:delete e.vars[l];for(let l of s)e.arrayAliases.delete(l);return e.hasReturn=!1,e.returnValue=void 0,e.currentRecursionDepth--,o}async function yt(e,t){L(e,"assignment evaluation");let n=await m(e,"assignment value evaluation",()=>f(e,t.value)),i=t.target,s=t.operator,a;if(s==="=")a=n;else{let o;if(i.type==="field"){let N=Math.floor(g(await m(e,"assignment field index",()=>f(e,i.index))));o=Q(e,N)}else if(i.type==="variable")o=J(e,i.name);else{let N=S(await m(e,"assignment array key",()=>f(e,i.key)));o=Z(e,i.array,N)}let l=g(o),u=g(n);switch(s){case"+=":a=l+u;break;case"-=":a=l-u;break;case"*=":a=l*u;break;case"/=":a=u!==0?l/u:0;break;case"%=":a=u!==0?l%u:0;break;case"^=":a=l**u;break;default:a=n}}if(i.type==="field"){let o=Math.floor(g(await m(e,"assignment target field index",()=>f(e,i.index))));oe(e,o,a)}else if(i.type==="variable")W(e,i.name,a);else{let o=S(await m(e,"assignment target array key",()=>f(e,i.key)));le(e,i.array,o,a)}return a}async function Y(e,t,n,i){L(e,"inc/dec evaluation");let s;if(t.type==="field"){let a=Math.floor(g(await m(e,"inc/dec field index",()=>f(e,t.index))));s=g(Q(e,a)),oe(e,a,s+n)}else if(t.type==="variable")s=g(J(e,t.name)),W(e,t.name,s+n);else{let a=S(await m(e,"inc/dec array key",()=>f(e,t.key)));s=g(Z(e,t.array,a)),le(e,t.array,a,s+n)}return i?s+n:s}async function mt(e,t){return Y(e,t,1,!0)}async function St(e,t){return Y(e,t,-1,!0)}async function wt(e,t){return Y(e,t,1,!1)}async function Rt(e,t){return Y(e,t,-1,!1)}async function gt(e,t,n){L(e,"in-expression evaluation");let i;if(t.type==="tuple"){e.coverage?.hit("awk:expr:tuple");let s=[];for(let a of t.elements)s.push(S(await m(e,"tuple key element evaluation",()=>f(e,a))));i=s.join(e.SUBSEP)}else i=S(await m(e,"in-expression key evaluation",()=>f(e,t)));return Ae(e,n,i)?1:0}async function vt(e,t,n,i){if(L(e,"getline evaluation"),i)return At(e,t,i);if(n)return It(e,t,n);if(!e.lines||e.lineIndex===void 0)return-1;let s=e.lineIndex+1;if(s>=e.lines.length)return 0;let a=e.lines[s];return t?W(e,t,a):$(e,a),e.NR++,e.lineIndex=s,1}async function At(e,t,n){let i=e.exec;if(!i)return-1;L(e,"getline command source");let s=S(await m(e,"getline command expression",()=>f(e,n))),a=`__cmd_${s}`,o=`__cmdi_${s}`,l,u;if(e.vars[a]===void 0)try{l=(await m(e,"getline command exec",()=>i(s))).stdout.split(`
|
|
6
|
+
`),l.length>0&&l[l.length-1]===""&&l.pop(),e.vars[a]=JSON.stringify(l),e.vars[o]=-1,u=-1}catch(C){if(C instanceof x)throw C;return-1}else l=JSON.parse(e.vars[a]),u=e.vars[o];let N=u+1;if(N>=l.length)return 0;let v=l[N];return e.vars[o]=N,t?W(e,t,v):$(e,v),1}async function It(e,t,n){let i=e.fs;if(!i||!e.cwd)return-1;L(e,"getline file source");let s=S(await m(e,"getline filename evaluation",()=>f(e,n)));if(s==="/dev/null")return 0;let a=i.resolvePath(e.cwd,s),o=`__fc_${a}`,l=`__fi_${a}`,u,N;if(e.vars[o]===void 0)try{u=(await m(e,"getline file read",()=>i.readFile(a))).split(`
|
|
7
|
+
`),u.length>0&&u[u.length-1]===""&&u.pop(),e.vars[o]=JSON.stringify(u),e.vars[l]=-1,N=-1}catch(O){if(O instanceof x)throw O;return-1}else u=JSON.parse(e.vars[o]),N=e.vars[l];let v=N+1;if(v>=u.length)return 0;let C=u[v];return e.vars[l]=v,t?W(e,t,C):$(e,C),1}async function kt(e,t){if(L(e,"tuple evaluation"),t.length===0)return"";for(let n=0;n<t.length-1;n++)await m(e,"tuple intermediate element",()=>f(e,t[n]));return m(e,"tuple final element",()=>f(e,t[t.length-1]))}be(V);function ue(e){if(e.maxOutputSize>0&&e.output.length>e.maxOutputSize)throw new P(`awk: output size limit exceeded (${e.maxOutputSize} bytes)`,"string_length",e.output)}function T(e,t){D(e.requireDefenseContext,"awk",t)}function y(e,t,n){return _(e.requireDefenseContext,"awk",t,n)}async function V(e,t){T(e,"block execution");for(let n of t)if(await y(e,"statement execution",()=>B(e,n)),Ct(e))break}function Ct(e){return e.shouldExit||e.shouldNext||e.shouldNextFile||e.loopBreak||e.loopContinue||e.hasReturn}async function B(e,t){switch(T(e,"single statement execution"),e.coverage?.hit(`awk:stmt:${t.type}`),t.type){case"block":await y(e,"nested block statement",()=>V(e,t.statements));break;case"expr_stmt":await y(e,"expression statement",()=>f(e,t.expression));break;case"print":await y(e,"print statement",()=>bt(e,t.args,t.output));break;case"printf":await y(e,"printf statement",()=>Ot(e,t.format,t.args,t.output));break;case"if":await y(e,"if statement",()=>Lt(e,t));break;case"while":await y(e,"while statement",()=>Mt(e,t));break;case"do_while":await y(e,"do-while statement",()=>Pt(e,t));break;case"for":await y(e,"for statement",()=>Tt(e,t));break;case"for_in":await y(e,"for-in statement",()=>Ft(e,t));break;case"break":e.loopBreak=!0;break;case"continue":e.loopContinue=!0;break;case"next":e.shouldNext=!0;break;case"nextfile":e.shouldNextFile=!0;break;case"exit":e.shouldExit=!0;{let n=t.code;e.exitCode=n?Math.floor(g(await y(e,"exit code expression",()=>f(e,n)))):0}break;case"return":e.hasReturn=!0;{let n=t.value;e.returnValue=n?await y(e,"return expression",()=>f(e,n)):""}break;case"delete":await y(e,"delete statement",()=>Dt(e,t.target));break}}async function bt(e,t,n){T(e,"print execution");let i=[];for(let a of t){let o=await y(e,"print argument evaluation",()=>f(e,a));typeof o=="number"?Number.isInteger(o)&&Math.abs(o)<Number.MAX_SAFE_INTEGER?i.push(String(o)):i.push(j(e.OFMT,[o])):i.push(S(o))}let s=i.join(e.OFS)+e.ORS;n?await y(e,"print redirection write",()=>Oe(e,n.redirect,n.file,s)):(e.output+=s,ue(e))}async function Ot(e,t,n,i){T(e,"printf execution");let s=S(await y(e,"printf format evaluation",()=>f(e,t))),a=[];for(let l of n)a.push(await y(e,"printf argument evaluation",()=>f(e,l)));let o=j(s,a);i?await y(e,"printf redirection write",()=>Oe(e,i.redirect,i.file,o)):(e.output+=o,ue(e))}async function Oe(e,t,n,i){T(e,"file write execution");let s=e.fs;if(!s||!e.cwd){e.output+=i,ue(e);return}let a=S(await y(e,"redirection filename evaluation",()=>f(e,n))),o=s.resolvePath(e.cwd,a);t===">"?e.openedFiles.has(o)?await y(e,"redirection append write",()=>s.appendFile(o,i)):(await y(e,"redirection overwrite write",()=>s.writeFile(o,i)),e.openedFiles.add(o)):(e.openedFiles.has(o)||e.openedFiles.add(o),await y(e,"redirection append mode write",()=>s.appendFile(o,i)))}async function Lt(e,t){if(T(e,"if execution"),b(await y(e,"if condition evaluation",()=>f(e,t.condition))))await y(e,"if consequent execution",()=>B(e,t.consequent));else if(t.alternate){let n=t.alternate;await y(e,"if alternate execution",()=>B(e,n))}}async function Mt(e,t){T(e,"while execution");let n=0;for(;b(await y(e,"while condition evaluation",()=>f(e,t.condition)));){if(n++,n>e.maxIterations)throw new P(`awk: while loop exceeded maximum iterations (${e.maxIterations})`,"iterations",e.output);if(e.loopContinue=!1,await y(e,"while body execution",()=>B(e,t.body)),e.loopBreak){e.loopBreak=!1;break}if(e.shouldExit||e.shouldNext||e.hasReturn)break}}async function Pt(e,t){T(e,"do-while execution");let n=0;do{if(n++,n>e.maxIterations)throw new P(`awk: do-while loop exceeded maximum iterations (${e.maxIterations})`,"iterations",e.output);if(e.loopContinue=!1,await y(e,"do-while body execution",()=>B(e,t.body)),e.loopBreak){e.loopBreak=!1;break}if(e.shouldExit||e.shouldNext||e.hasReturn)break}while(b(await y(e,"do-while condition evaluation",()=>f(e,t.condition))))}async function Tt(e,t){T(e,"for execution");let n=t.init,i=t.condition,s=t.update;n&&await y(e,"for init evaluation",()=>f(e,n));let a=0;for(;!i||b(await y(e,"for condition evaluation",()=>f(e,i)));){if(a++,a>e.maxIterations)throw new P(`awk: for loop exceeded maximum iterations (${e.maxIterations})`,"iterations",e.output);if(e.loopContinue=!1,await y(e,"for body execution",()=>B(e,t.body)),e.loopBreak){e.loopBreak=!1;break}if(e.shouldExit||e.shouldNext||e.hasReturn)break;s&&await y(e,"for update evaluation",()=>f(e,s))}}async function Ft(e,t){T(e,"for-in execution");let n=e.arrays[t.array];if(n)for(let i of Object.keys(n)){if(e.vars[t.variable]=i,e.loopContinue=!1,await y(e,"for-in body execution",()=>B(e,t.body)),e.loopBreak){e.loopBreak=!1;break}if(e.shouldExit||e.shouldNext||e.hasReturn)break}}async function Dt(e,t){if(T(e,"delete execution"),t.type==="array_access"){let n=S(await y(e,"delete key evaluation",()=>f(e,t.key)));Ie(e,t.array,n)}else t.type==="variable"&&ke(e,t.name)}var q=class{ctx;program=null;rangeStates=[];constructor(t){this.ctx=t}assertDefenseContext(t){D(this.ctx.requireDefenseContext,"awk",t)}withDefenseContext(t,n){return _(this.ctx.requireDefenseContext,"awk",t,n)}execute(t){this.assertDefenseContext("program initialization"),this.program=t,this.ctx.output="";for(let n of t.functions)this.ctx.functions.set(n.name,n);this.rangeStates=t.rules.map(()=>!1)}async executeBegin(){if(this.assertDefenseContext("BEGIN execution entry"),!!this.program){for(let t of this.program.rules)if(t.pattern?.type==="begin"&&(await this.withDefenseContext("BEGIN block execution",()=>V(this.ctx,t.action.statements)),this.ctx.shouldExit))break}}async executeLine(t){if(this.assertDefenseContext("line execution entry"),!(!this.program||this.ctx.shouldExit)){$(this.ctx,t),this.ctx.NR++,this.ctx.FNR++,this.ctx.shouldNext=!1;for(let n=0;n<this.program.rules.length&&!(this.ctx.shouldExit||this.ctx.shouldNext||this.ctx.shouldNextFile);n++){let i=this.program.rules[n];i.pattern?.type==="begin"||i.pattern?.type==="end"||await this.withDefenseContext("rule match",()=>this.matchesRule(i,n))&&await this.withDefenseContext("rule block execution",()=>V(this.ctx,i.action.statements))}}}async executeEnd(){if(this.assertDefenseContext("END execution entry"),!!this.program&&!this.ctx.inEndBlock){this.ctx.inEndBlock=!0,this.ctx.shouldExit=!1;for(let t of this.program.rules)if(t.pattern?.type==="end"&&(await this.withDefenseContext("END block execution",()=>V(this.ctx,t.action.statements)),this.ctx.shouldExit))break;this.ctx.inEndBlock=!1}}getOutput(){return this.ctx.output}getExitCode(){return this.ctx.exitCode}getContext(){return this.ctx}async matchesRule(t,n){this.assertDefenseContext("rule matching");let i=t.pattern;if(!i)return!0;switch(i.type){case"begin":case"end":return!1;case"regex_pattern":return K(i.pattern,this.ctx.line);case"expr_pattern":return b(await this.withDefenseContext("expression pattern evaluation",()=>f(this.ctx,i.expression)));case"range":{let s=await this.withDefenseContext("range start pattern",()=>this.matchPattern(i.start)),a=await this.withDefenseContext("range end pattern",()=>this.matchPattern(i.end));return this.rangeStates[n]?(a&&(this.rangeStates[n]=!1),!0):s?(this.rangeStates[n]=!0,a&&(this.rangeStates[n]=!1),!0):!1}default:return!1}}async matchPattern(t){switch(this.assertDefenseContext("pattern matching"),t.type){case"regex_pattern":return K(t.pattern,this.ctx.line);case"expr_pattern":return b(await this.withDefenseContext("nested expression pattern",()=>f(this.ctx,t.expression)));default:return!1}}};var r;(function(e){e.NUMBER="NUMBER",e.STRING="STRING",e.REGEX="REGEX",e.IDENT="IDENT",e.BEGIN="BEGIN",e.END="END",e.IF="IF",e.ELSE="ELSE",e.WHILE="WHILE",e.DO="DO",e.FOR="FOR",e.IN="IN",e.BREAK="BREAK",e.CONTINUE="CONTINUE",e.NEXT="NEXT",e.NEXTFILE="NEXTFILE",e.EXIT="EXIT",e.RETURN="RETURN",e.DELETE="DELETE",e.FUNCTION="FUNCTION",e.PRINT="PRINT",e.PRINTF="PRINTF",e.GETLINE="GETLINE",e.PLUS="PLUS",e.MINUS="MINUS",e.STAR="STAR",e.SLASH="SLASH",e.PERCENT="PERCENT",e.CARET="CARET",e.EQ="EQ",e.NE="NE",e.LT="LT",e.GT="GT",e.LE="LE",e.GE="GE",e.MATCH="MATCH",e.NOT_MATCH="NOT_MATCH",e.AND="AND",e.OR="OR",e.NOT="NOT",e.ASSIGN="ASSIGN",e.PLUS_ASSIGN="PLUS_ASSIGN",e.MINUS_ASSIGN="MINUS_ASSIGN",e.STAR_ASSIGN="STAR_ASSIGN",e.SLASH_ASSIGN="SLASH_ASSIGN",e.PERCENT_ASSIGN="PERCENT_ASSIGN",e.CARET_ASSIGN="CARET_ASSIGN",e.INCREMENT="INCREMENT",e.DECREMENT="DECREMENT",e.QUESTION="QUESTION",e.COLON="COLON",e.COMMA="COMMA",e.SEMICOLON="SEMICOLON",e.NEWLINE="NEWLINE",e.LPAREN="LPAREN",e.RPAREN="RPAREN",e.LBRACE="LBRACE",e.RBRACE="RBRACE",e.LBRACKET="LBRACKET",e.RBRACKET="RBRACKET",e.DOLLAR="DOLLAR",e.APPEND="APPEND",e.PIPE="PIPE",e.EOF="EOF"})(r||(r={}));var _t=new Map([["BEGIN",r.BEGIN],["END",r.END],["if",r.IF],["else",r.ELSE],["while",r.WHILE],["do",r.DO],["for",r.FOR],["in",r.IN],["break",r.BREAK],["continue",r.CONTINUE],["next",r.NEXT],["nextfile",r.NEXTFILE],["exit",r.EXIT],["return",r.RETURN],["delete",r.DELETE],["function",r.FUNCTION],["print",r.PRINT],["printf",r.PRINTF],["getline",r.GETLINE]]);function Gt(e){return e.replace(/\[\[:space:\]\]/g,"[ \\t\\n\\r\\f\\v]").replace(/\[\[:blank:\]\]/g,"[ \\t]").replace(/\[\[:alpha:\]\]/g,"[a-zA-Z]").replace(/\[\[:digit:\]\]/g,"[0-9]").replace(/\[\[:alnum:\]\]/g,"[a-zA-Z0-9]").replace(/\[\[:upper:\]\]/g,"[A-Z]").replace(/\[\[:lower:\]\]/g,"[a-z]").replace(/\[\[:punct:\]\]/g,"[!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~]").replace(/\[\[:xdigit:\]\]/g,"[0-9A-Fa-f]").replace(/\[\[:graph:\]\]/g,"[!-~]").replace(/\[\[:print:\]\]/g,"[ -~]").replace(/\[\[:cntrl:\]\]/g,"[\\x00-\\x1f\\x7f]")}var ee=class{input;pos=0;line=1;column=1;lastTokenType=null;constructor(t){this.input=t}tokenize(){let t=[];for(;this.pos<this.input.length;){let n=this.nextToken();n&&(t.push(n),this.lastTokenType=n.type)}return t.push(this.makeToken(r.EOF,"")),t}makeToken(t,n){return{type:t,value:n,line:this.line,column:this.column}}peek(t=0){return this.input[this.pos+t]||""}advance(){let t=this.input[this.pos++]||"";return t===`
|
|
8
|
+
`?(this.line++,this.column=1):this.column++,t}skipWhitespace(){for(;this.pos<this.input.length;){let t=this.peek();if(t===" "||t===" "||t==="\r")this.advance();else if(t==="\\")if(this.peek(1)===`
|
|
9
|
+
`)this.advance(),this.advance();else break;else if(t==="#")for(;this.pos<this.input.length&&this.peek()!==`
|
|
10
|
+
`;)this.advance();else break}}nextToken(){if(this.skipWhitespace(),this.pos>=this.input.length)return null;let t=this.line,n=this.column,i=this.peek();return i===`
|
|
11
|
+
`?(this.advance(),{type:r.NEWLINE,value:`
|
|
12
|
+
`,line:t,column:n}):i==='"'?this.readString():i==="/"&&this.canBeRegex()?this.readRegex():this.isDigit(i)||i==="."&&this.isDigit(this.peek(1))?this.readNumber():this.isAlpha(i)||i==="_"?this.readIdentifier():this.readOperator()}canBeRegex(){return new Set([null,r.NEWLINE,r.SEMICOLON,r.LBRACE,r.RBRACE,r.LPAREN,r.LBRACKET,r.COMMA,r.ASSIGN,r.PLUS_ASSIGN,r.MINUS_ASSIGN,r.STAR_ASSIGN,r.SLASH_ASSIGN,r.PERCENT_ASSIGN,r.CARET_ASSIGN,r.AND,r.OR,r.NOT,r.MATCH,r.NOT_MATCH,r.QUESTION,r.COLON,r.LT,r.GT,r.LE,r.GE,r.EQ,r.NE,r.PLUS,r.MINUS,r.STAR,r.PERCENT,r.CARET,r.PRINT,r.PRINTF,r.IF,r.WHILE,r.DO,r.FOR,r.RETURN]).has(this.lastTokenType)}readString(){let t=this.line,n=this.column;this.advance();let i="";for(;this.pos<this.input.length&&this.peek()!=='"';)if(this.peek()==="\\"){this.advance();let s=this.advance();switch(s){case"n":i+=`
|
|
13
|
+
`;break;case"t":i+=" ";break;case"r":i+="\r";break;case"f":i+="\f";break;case"b":i+="\b";break;case"v":i+="\v";break;case"a":i+="\x07";break;case"\\":i+="\\";break;case'"':i+='"';break;case"/":i+="/";break;case"x":{let a="";for(;a.length<2&&/[0-9a-fA-F]/.test(this.peek());)a+=this.advance();a.length>0?i+=String.fromCharCode(parseInt(a,16)):i+="x";break}default:if(/[0-7]/.test(s)){let a=s;for(;a.length<3&&/[0-7]/.test(this.peek());)a+=this.advance();i+=String.fromCharCode(parseInt(a,8))}else i+=s}}else i+=this.advance();return this.peek()==='"'&&this.advance(),{type:r.STRING,value:i,line:t,column:n}}readRegex(){let t=this.line,n=this.column;this.advance();let i="";for(;this.pos<this.input.length&&this.peek()!=="/";)if(this.peek()==="\\")i+=this.advance(),this.pos<this.input.length&&(i+=this.advance());else{if(this.peek()===`
|
|
14
|
+
`)break;i+=this.advance()}return this.peek()==="/"&&this.advance(),i=Gt(i),{type:r.REGEX,value:i,line:t,column:n}}readNumber(){let t=this.line,n=this.column,i="";for(;this.isDigit(this.peek());)i+=this.advance();if(this.peek()==="."&&this.isDigit(this.peek(1)))for(i+=this.advance();this.isDigit(this.peek());)i+=this.advance();if(this.peek()==="e"||this.peek()==="E")for(i+=this.advance(),(this.peek()==="+"||this.peek()==="-")&&(i+=this.advance());this.isDigit(this.peek());)i+=this.advance();return{type:r.NUMBER,value:parseFloat(i),line:t,column:n}}readIdentifier(){let t=this.line,n=this.column,i="";for(;this.isAlphaNumeric(this.peek())||this.peek()==="_";)i+=this.advance();let s=_t.get(i);return s!==void 0?{type:s,value:i,line:t,column:n}:{type:r.IDENT,value:i,line:t,column:n}}readOperator(){let t=this.line,n=this.column,i=this.advance(),s=this.peek();switch(i){case"+":return s==="+"?(this.advance(),{type:r.INCREMENT,value:"++",line:t,column:n}):s==="="?(this.advance(),{type:r.PLUS_ASSIGN,value:"+=",line:t,column:n}):{type:r.PLUS,value:"+",line:t,column:n};case"-":return s==="-"?(this.advance(),{type:r.DECREMENT,value:"--",line:t,column:n}):s==="="?(this.advance(),{type:r.MINUS_ASSIGN,value:"-=",line:t,column:n}):{type:r.MINUS,value:"-",line:t,column:n};case"*":return s==="*"?(this.advance(),{type:r.CARET,value:"**",line:t,column:n}):s==="="?(this.advance(),{type:r.STAR_ASSIGN,value:"*=",line:t,column:n}):{type:r.STAR,value:"*",line:t,column:n};case"/":return s==="="?(this.advance(),{type:r.SLASH_ASSIGN,value:"/=",line:t,column:n}):{type:r.SLASH,value:"/",line:t,column:n};case"%":return s==="="?(this.advance(),{type:r.PERCENT_ASSIGN,value:"%=",line:t,column:n}):{type:r.PERCENT,value:"%",line:t,column:n};case"^":return s==="="?(this.advance(),{type:r.CARET_ASSIGN,value:"^=",line:t,column:n}):{type:r.CARET,value:"^",line:t,column:n};case"=":return s==="="?(this.advance(),{type:r.EQ,value:"==",line:t,column:n}):{type:r.ASSIGN,value:"=",line:t,column:n};case"!":return s==="="?(this.advance(),{type:r.NE,value:"!=",line:t,column:n}):s==="~"?(this.advance(),{type:r.NOT_MATCH,value:"!~",line:t,column:n}):{type:r.NOT,value:"!",line:t,column:n};case"<":return s==="="?(this.advance(),{type:r.LE,value:"<=",line:t,column:n}):{type:r.LT,value:"<",line:t,column:n};case">":return s==="="?(this.advance(),{type:r.GE,value:">=",line:t,column:n}):s===">"?(this.advance(),{type:r.APPEND,value:">>",line:t,column:n}):{type:r.GT,value:">",line:t,column:n};case"&":return s==="&"?(this.advance(),{type:r.AND,value:"&&",line:t,column:n}):{type:r.IDENT,value:"&",line:t,column:n};case"|":return s==="|"?(this.advance(),{type:r.OR,value:"||",line:t,column:n}):{type:r.PIPE,value:"|",line:t,column:n};case"~":return{type:r.MATCH,value:"~",line:t,column:n};case"?":return{type:r.QUESTION,value:"?",line:t,column:n};case":":return{type:r.COLON,value:":",line:t,column:n};case",":return{type:r.COMMA,value:",",line:t,column:n};case";":return{type:r.SEMICOLON,value:";",line:t,column:n};case"(":return{type:r.LPAREN,value:"(",line:t,column:n};case")":return{type:r.RPAREN,value:")",line:t,column:n};case"{":return{type:r.LBRACE,value:"{",line:t,column:n};case"}":return{type:r.RBRACE,value:"}",line:t,column:n};case"[":return{type:r.LBRACKET,value:"[",line:t,column:n};case"]":return{type:r.RBRACKET,value:"]",line:t,column:n};case"$":return{type:r.DOLLAR,value:"$",line:t,column:n};default:return{type:r.IDENT,value:i,line:t,column:n}}}isDigit(t){return t>="0"&&t<="9"}isAlpha(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"}isAlphaNumeric(t){return this.isDigit(t)||this.isAlpha(t)}};var p={LPAREN:"LPAREN",RPAREN:"RPAREN",QUESTION:"QUESTION",NEWLINE:"NEWLINE",SEMICOLON:"SEMICOLON",RBRACE:"RBRACE",COMMA:"COMMA",PIPE:"PIPE",GT:"GT",APPEND:"APPEND",AND:"AND",OR:"OR",ASSIGN:"ASSIGN",PLUS_ASSIGN:"PLUS_ASSIGN",MINUS_ASSIGN:"MINUS_ASSIGN",STAR_ASSIGN:"STAR_ASSIGN",SLASH_ASSIGN:"SLASH_ASSIGN",PERCENT_ASSIGN:"PERCENT_ASSIGN",CARET_ASSIGN:"CARET_ASSIGN",RBRACKET:"RBRACKET",COLON:"COLON",IN:"IN",PRINT:"PRINT",PRINTF:"PRINTF",IDENT:"IDENT",LT:"LT",LE:"LE",GE:"GE",EQ:"EQ",NE:"NE",MATCH:"MATCH",NOT_MATCH:"NOT_MATCH",NUMBER:"NUMBER",STRING:"STRING",DOLLAR:"DOLLAR",NOT:"NOT",MINUS:"MINUS",PLUS:"PLUS",INCREMENT:"INCREMENT",DECREMENT:"DECREMENT"};function Fe(e){e.expect(p.PRINT);let t=[];if(e.check(p.NEWLINE)||e.check(p.SEMICOLON)||e.check(p.RBRACE)||e.check(p.PIPE)||e.check(p.GT)||e.check(p.APPEND))t.push({type:"field",index:{type:"number",value:0}});else for(t.push(te(e));e.check(p.COMMA);)e.advance(),t.push(te(e));let n;return e.check(p.GT)?(e.advance(),n={redirect:">",file:e.parsePrimary()}):e.check(p.APPEND)&&(e.advance(),n={redirect:">>",file:e.parsePrimary()}),{type:"print",args:t,output:n}}function te(e){return xt(e)?ce(e,!0):ce(e,!1)}function ce(e,t){let n=t?e.parseTernary():Ut(e);if(e.match(p.ASSIGN,p.PLUS_ASSIGN,p.MINUS_ASSIGN,p.STAR_ASSIGN,p.SLASH_ASSIGN,p.PERCENT_ASSIGN,p.CARET_ASSIGN)){let i=e.advance(),s=ce(e,t);if(n.type!=="variable"&&n.type!=="field"&&n.type!=="array_access")throw new Error("Invalid assignment target");return{type:"assignment",operator:new Map([["=","="],["+=","+="],["-=","-="],["*=","*="],["/=","/="],["%=","%="],["^=","^="]]).get(i.value)??"=",target:n,value:s}}return n}function xt(e){let t=0,n=e.pos;for(;n<e.tokens.length;){let i=e.tokens[n];if(i.type===p.LPAREN&&t++,i.type===p.RPAREN&&t--,i.type===p.QUESTION&&t===0)return!0;if(i.type===p.NEWLINE||i.type===p.SEMICOLON||i.type===p.RBRACE||i.type===p.COMMA||i.type===p.PIPE)return!1;n++}return!1}function Ut(e){let t=Le(e);for(;e.check(p.OR);){e.advance();let n=Le(e);t={type:"binary",operator:"||",left:t,right:n}}return t}function Le(e){let t=Me(e);for(;e.check(p.AND);){e.advance();let n=Me(e);t={type:"binary",operator:"&&",left:t,right:n}}return t}function Me(e){let t=Bt(e);if(e.check(p.IN)){e.advance();let n=String(e.expect(p.IDENT).value);return{type:"in",key:t,array:n}}return t}function Bt(e){let t=Pe(e);for(;Ht(e)&&!$t(e);){let n=Pe(e);t={type:"binary",operator:" ",left:t,right:n}}return t}function Pe(e){let t=Te(e);for(;e.match(p.MATCH,p.NOT_MATCH);){let n=e.advance().type===p.MATCH?"~":"!~",i=Te(e);t={type:"binary",operator:n,left:t,right:i}}return t}function Te(e){let t=e.parseAddSub();for(;e.match(p.LT,p.LE,p.GE,p.EQ,p.NE);){let n=e.advance(),i=e.parseAddSub();t={type:"binary",operator:new Map([["<","<"],["<=","<="],[">=",">="],["==","=="],["!=","!="]]).get(n.value)??"==",left:t,right:i}}return t}function Ht(e){return e.match(p.NUMBER,p.STRING,p.IDENT,p.DOLLAR,p.LPAREN,p.NOT,p.MINUS,p.PLUS,p.INCREMENT,p.DECREMENT)}function $t(e){return e.match(p.AND,p.OR,p.QUESTION,p.ASSIGN,p.PLUS_ASSIGN,p.MINUS_ASSIGN,p.STAR_ASSIGN,p.SLASH_ASSIGN,p.PERCENT_ASSIGN,p.CARET_ASSIGN,p.COMMA,p.SEMICOLON,p.NEWLINE,p.RBRACE,p.RPAREN,p.RBRACKET,p.COLON,p.PIPE,p.APPEND,p.GT,p.IN)}function De(e){e.expect(p.PRINTF);let t=e.check(p.LPAREN);t&&(e.advance(),e.skipNewlines());let n=t?e.parseExpression():te(e),i=[];for(;e.check(p.COMMA);)e.advance(),t&&e.skipNewlines(),i.push(t?e.parseExpression():te(e));t&&(e.skipNewlines(),e.expect(p.RPAREN));let s;return e.check(p.GT)?(e.advance(),s={redirect:">",file:e.parsePrimary()}):e.check(p.APPEND)&&(e.advance(),s={redirect:">>",file:e.parsePrimary()}),{type:"printf",format:n,args:i,output:s}}var ne=class{tokens=[];pos=0;parse(t){let n=new ee(t);return this.tokens=n.tokenize(),this.pos=0,this.parseProgram()}setPos(t){this.pos=t}current(){return this.tokens[this.pos]||{type:r.EOF,value:"",line:0,column:0}}advance(){let t=this.current();return this.pos<this.tokens.length&&this.pos++,t}match(...t){return t.includes(this.current().type)}check(t){return this.current().type===t}expect(t,n){if(!this.check(t)){let i=this.current();throw new Error(n||`Expected ${t}, got ${i.type} at line ${i.line}:${i.column}`)}return this.advance()}skipNewlines(){for(;this.check(r.NEWLINE);)this.advance()}skipTerminators(){for(;this.check(r.NEWLINE)||this.check(r.SEMICOLON);)this.advance()}parseProgram(){let t=[],n=[];for(this.skipNewlines();!this.check(r.EOF)&&(this.skipNewlines(),!this.check(r.EOF));)this.check(r.FUNCTION)?t.push(this.parseFunction()):n.push(this.parseRule()),this.skipTerminators();return{functions:t,rules:n}}parseFunction(){this.expect(r.FUNCTION);let t=this.expect(r.IDENT).value;this.expect(r.LPAREN);let n=[];if(!this.check(r.RPAREN))for(n.push(this.expect(r.IDENT).value);this.check(r.COMMA);)this.advance(),n.push(this.expect(r.IDENT).value);this.expect(r.RPAREN),this.skipNewlines();let i=this.parseBlock();return{name:t,params:n,body:i}}parseRule(){let t;if(this.check(r.BEGIN))this.advance(),t={type:"begin"};else if(this.check(r.END))this.advance(),t={type:"end"};else if(this.check(r.LBRACE))t=void 0;else if(this.check(r.REGEX)){let i=this.advance();if(this.check(r.AND)||this.check(r.OR)){let s={type:"binary",operator:"~",left:{type:"field",index:{type:"number",value:0}},right:{type:"regex",pattern:i.value}};t={type:"expr_pattern",expression:this.parseLogicalOrRest(s)}}else{let s={type:"regex_pattern",pattern:i.value};if(this.check(r.COMMA)){this.advance();let a;this.check(r.REGEX)?a={type:"regex_pattern",pattern:this.advance().value}:a={type:"expr_pattern",expression:this.parseExpression()},t={type:"range",start:s,end:a}}else t=s}}else{let s={type:"expr_pattern",expression:this.parseExpression()};if(this.check(r.COMMA)){this.advance();let a;this.check(r.REGEX)?a={type:"regex_pattern",pattern:this.advance().value}:a={type:"expr_pattern",expression:this.parseExpression()},t={type:"range",start:s,end:a}}else t=s}this.skipNewlines();let n;return this.check(r.LBRACE)?n=this.parseBlock():n={type:"block",statements:[{type:"print",args:[{type:"field",index:{type:"number",value:0}}]}]},{pattern:t,action:n}}parseBlock(){this.expect(r.LBRACE),this.skipNewlines();let t=[];for(;!this.check(r.RBRACE)&&!this.check(r.EOF);)t.push(this.parseStatement()),this.skipTerminators();return this.expect(r.RBRACE),{type:"block",statements:t}}parseStatement(){if(this.check(r.SEMICOLON)||this.check(r.NEWLINE))return this.advance(),{type:"block",statements:[]};if(this.check(r.LBRACE))return this.parseBlock();if(this.check(r.IF))return this.parseIf();if(this.check(r.WHILE))return this.parseWhile();if(this.check(r.DO))return this.parseDoWhile();if(this.check(r.FOR))return this.parseFor();if(this.check(r.BREAK))return this.advance(),{type:"break"};if(this.check(r.CONTINUE))return this.advance(),{type:"continue"};if(this.check(r.NEXT))return this.advance(),{type:"next"};if(this.check(r.NEXTFILE))return this.advance(),{type:"nextfile"};if(this.check(r.EXIT)){this.advance();let n;return!this.check(r.NEWLINE)&&!this.check(r.SEMICOLON)&&!this.check(r.RBRACE)&&!this.check(r.EOF)&&(n=this.parseExpression()),{type:"exit",code:n}}if(this.check(r.RETURN)){this.advance();let n;return!this.check(r.NEWLINE)&&!this.check(r.SEMICOLON)&&!this.check(r.RBRACE)&&!this.check(r.EOF)&&(n=this.parseExpression()),{type:"return",value:n}}if(this.check(r.DELETE)){this.advance();let n=this.parsePrimary();if(n.type!=="array_access"&&n.type!=="variable")throw new Error("delete requires array element or array");return{type:"delete",target:n}}return this.check(r.PRINT)?Fe(this):this.check(r.PRINTF)?De(this):{type:"expr_stmt",expression:this.parseExpression()}}parseIf(){this.expect(r.IF),this.expect(r.LPAREN);let t=this.parseExpression();this.expect(r.RPAREN),this.skipNewlines();let n=this.parseStatement();this.skipTerminators();let i;return this.check(r.ELSE)&&(this.advance(),this.skipNewlines(),i=this.parseStatement()),{type:"if",condition:t,consequent:n,alternate:i}}parseWhile(){this.expect(r.WHILE),this.expect(r.LPAREN);let t=this.parseExpression();this.expect(r.RPAREN),this.skipNewlines();let n=this.parseStatement();return{type:"while",condition:t,body:n}}parseDoWhile(){this.expect(r.DO),this.skipNewlines();let t=this.parseStatement();this.skipNewlines(),this.expect(r.WHILE),this.expect(r.LPAREN);let n=this.parseExpression();return this.expect(r.RPAREN),{type:"do_while",body:t,condition:n}}parseFor(){if(this.expect(r.FOR),this.expect(r.LPAREN),this.check(r.IDENT)){let a=this.advance();if(this.check(r.IN)){this.advance();let o=this.expect(r.IDENT).value;this.expect(r.RPAREN),this.skipNewlines();let l=this.parseStatement();return{type:"for_in",variable:a.value,array:o,body:l}}this.pos--}let t;this.check(r.SEMICOLON)||(t=this.parseExpression()),this.expect(r.SEMICOLON);let n;this.check(r.SEMICOLON)||(n=this.parseExpression()),this.expect(r.SEMICOLON);let i;this.check(r.RPAREN)||(i=this.parseExpression()),this.expect(r.RPAREN),this.skipNewlines();let s=this.parseStatement();return{type:"for",init:t,condition:n,update:i,body:s}}parseExpression(){return this.parseAssignment()}parseAssignment(){let t=this.parseTernary();if(this.match(r.ASSIGN,r.PLUS_ASSIGN,r.MINUS_ASSIGN,r.STAR_ASSIGN,r.SLASH_ASSIGN,r.PERCENT_ASSIGN,r.CARET_ASSIGN)){let n=this.advance(),i=this.parseAssignment();if(t.type!=="variable"&&t.type!=="field"&&t.type!=="array_access")throw new Error("Invalid assignment target");return{type:"assignment",operator:{"=":"=","+=":"+=","-=":"-=","*=":"*=","/=":"/=","%=":"%=","^=":"^="}[n.value],target:t,value:i}}return t}parseTernary(){let t=this.parsePipeGetline();if(this.check(r.QUESTION)){this.advance();let n=this.parseExpression();this.expect(r.COLON);let i=this.parseExpression();t={type:"ternary",condition:t,consequent:n,alternate:i}}return t}parsePipeGetline(){let t=this.parseOr();if(this.check(r.PIPE)){if(this.advance(),!this.check(r.GETLINE))throw new Error("Expected 'getline' after '|' in expression context");this.advance();let n;return this.check(r.IDENT)&&(n=this.advance().value),{type:"getline",command:t,variable:n}}return t}parseOr(){let t=this.parseAnd();for(;this.check(r.OR);){this.advance();let n=this.parseAnd();t={type:"binary",operator:"||",left:t,right:n}}return t}parseLogicalOrRest(t){for(t=this.parseLogicalAndRest(t);this.check(r.OR);){this.advance();let n=this.parseAnd();t={type:"binary",operator:"||",left:t,right:n}}return t}parseLogicalAndRest(t){for(;this.check(r.AND);){this.advance();let n=this.parseIn();t={type:"binary",operator:"&&",left:t,right:n}}return t}parseAnd(){let t=this.parseIn();for(;this.check(r.AND);){this.advance();let n=this.parseIn();t={type:"binary",operator:"&&",left:t,right:n}}return t}parseIn(){let t=this.parseConcatenation();if(this.check(r.IN)){this.advance();let n=this.expect(r.IDENT).value;return{type:"in",key:t,array:n}}return t}parseConcatenation(){let t=this.parseMatch();for(;this.canStartExpression()&&!this.isConcatTerminator();){let n=this.parseMatch();t={type:"binary",operator:" ",left:t,right:n}}return t}parseMatch(){let t=this.parseComparison();for(;this.match(r.MATCH,r.NOT_MATCH);){let n=this.advance().type===r.MATCH?"~":"!~",i=this.parseComparison();t={type:"binary",operator:n,left:t,right:i}}return t}parseComparison(){let t=this.parseAddSub();for(;this.match(r.LT,r.LE,r.GT,r.GE,r.EQ,r.NE);){let n=this.advance(),i=this.parseAddSub();t={type:"binary",operator:new Map([["<","<"],["<=","<="],[">",">"],[">=",">="],["==","=="],["!=","!="]]).get(n.value)??"==",left:t,right:i}}return t}canStartExpression(){return this.match(r.NUMBER,r.STRING,r.IDENT,r.DOLLAR,r.LPAREN,r.NOT,r.MINUS,r.PLUS,r.INCREMENT,r.DECREMENT)}isConcatTerminator(){return this.match(r.AND,r.OR,r.QUESTION,r.ASSIGN,r.PLUS_ASSIGN,r.MINUS_ASSIGN,r.STAR_ASSIGN,r.SLASH_ASSIGN,r.PERCENT_ASSIGN,r.CARET_ASSIGN,r.COMMA,r.SEMICOLON,r.NEWLINE,r.RBRACE,r.RPAREN,r.RBRACKET,r.COLON,r.PIPE,r.APPEND,r.IN)}parseAddSub(){let t=this.parseMulDiv();for(;this.match(r.PLUS,r.MINUS);){let n=this.advance().value,i=this.parseMulDiv();t={type:"binary",operator:n,left:t,right:i}}return t}parseMulDiv(){let t=this.parseUnary();for(;this.match(r.STAR,r.SLASH,r.PERCENT);){let n=this.advance(),i=this.parseUnary();t={type:"binary",operator:new Map([["*","*"],["/","/"],["%","%"]]).get(n.value)??"*",left:t,right:i}}return t}parseUnary(){if(this.check(r.INCREMENT)){this.advance();let t=this.parseUnary();return t.type!=="variable"&&t.type!=="field"&&t.type!=="array_access"?{type:"unary",operator:"+",operand:{type:"unary",operator:"+",operand:t}}:{type:"pre_increment",operand:t}}if(this.check(r.DECREMENT)){this.advance();let t=this.parseUnary();return t.type!=="variable"&&t.type!=="field"&&t.type!=="array_access"?{type:"unary",operator:"-",operand:{type:"unary",operator:"-",operand:t}}:{type:"pre_decrement",operand:t}}if(this.match(r.NOT,r.MINUS,r.PLUS)){let t=this.advance().value,n=this.parseUnary();return{type:"unary",operator:t,operand:n}}return this.parsePower()}parsePower(){let t=this.parsePostfix();if(this.check(r.CARET)){this.advance();let n=this.parsePower();t={type:"binary",operator:"^",left:t,right:n}}return t}parsePostfix(){let t=this.parsePrimary();if(this.check(r.INCREMENT)){if(this.advance(),t.type!=="variable"&&t.type!=="field"&&t.type!=="array_access")throw new Error("Invalid increment operand");return{type:"post_increment",operand:t}}if(this.check(r.DECREMENT)){if(this.advance(),t.type!=="variable"&&t.type!=="field"&&t.type!=="array_access")throw new Error("Invalid decrement operand");return{type:"post_decrement",operand:t}}return t}parseFieldIndex(){if(this.check(r.INCREMENT)){this.advance();let t=this.parseFieldIndex();return t.type!=="variable"&&t.type!=="field"&&t.type!=="array_access"?{type:"unary",operator:"+",operand:{type:"unary",operator:"+",operand:t}}:{type:"pre_increment",operand:t}}if(this.check(r.DECREMENT)){this.advance();let t=this.parseFieldIndex();return t.type!=="variable"&&t.type!=="field"&&t.type!=="array_access"?{type:"unary",operator:"-",operand:{type:"unary",operator:"-",operand:t}}:{type:"pre_decrement",operand:t}}if(this.match(r.NOT,r.MINUS,r.PLUS)){let t=this.advance().value,n=this.parseFieldIndex();return{type:"unary",operator:t,operand:n}}return this.parseFieldIndexPower()}parseFieldIndexPower(){let t=this.parseFieldIndexPrimary();if(this.check(r.CARET)){this.advance();let n=this.parseFieldIndexPower();t={type:"binary",operator:"^",left:t,right:n}}return t}parseFieldIndexPrimary(){if(this.check(r.NUMBER))return{type:"number",value:this.advance().value};if(this.check(r.STRING))return{type:"string",value:this.advance().value};if(this.check(r.DOLLAR))return this.advance(),{type:"field",index:this.parseFieldIndex()};if(this.check(r.LPAREN)){this.advance();let t=this.parseExpression();return this.expect(r.RPAREN),t}if(this.check(r.IDENT)){let t=this.advance().value;if(this.check(r.LPAREN)){this.advance();let n=[];if(!this.check(r.RPAREN))for(n.push(this.parseExpression());this.check(r.COMMA);)this.advance(),n.push(this.parseExpression());return this.expect(r.RPAREN),{type:"call",name:t,args:n}}if(this.check(r.LBRACKET)){this.advance();let n=this.parseExpression();if(this.check(r.COMMA)){let i=[n];for(;this.check(r.COMMA);)this.advance(),i.push(this.parseExpression());this.expect(r.RBRACKET);let s=i.reduce((a,o)=>({type:"binary",operator:" ",left:{type:"binary",operator:" ",left:a,right:{type:"variable",name:"SUBSEP"}},right:o}));return{type:"array_access",array:t,key:s}}return this.expect(r.RBRACKET),{type:"array_access",array:t,key:n}}return{type:"variable",name:t}}throw new Error(`Unexpected token in field index: ${this.current().type} at line ${this.current().line}:${this.current().column}`)}parsePrimary(){if(this.check(r.NUMBER))return{type:"number",value:this.advance().value};if(this.check(r.STRING))return{type:"string",value:this.advance().value};if(this.check(r.REGEX))return{type:"regex",pattern:this.advance().value};if(this.check(r.DOLLAR))return this.advance(),{type:"field",index:this.parseFieldIndex()};if(this.check(r.LPAREN)){this.advance();let t=this.parseExpression();if(this.check(r.COMMA)){let n=[t];for(;this.check(r.COMMA);)this.advance(),n.push(this.parseExpression());return this.expect(r.RPAREN),{type:"tuple",elements:n}}return this.expect(r.RPAREN),t}if(this.check(r.GETLINE)){this.advance();let t,n;return this.check(r.IDENT)&&(t=this.advance().value),this.check(r.LT)&&(this.advance(),n=this.parsePrimary()),{type:"getline",variable:t,file:n}}if(this.check(r.IDENT)){let t=this.advance().value;if(this.check(r.LPAREN)){this.advance();let n=[];if(this.skipNewlines(),!this.check(r.RPAREN))for(n.push(this.parseExpression());this.check(r.COMMA);)this.advance(),this.skipNewlines(),n.push(this.parseExpression());return this.skipNewlines(),this.expect(r.RPAREN),{type:"call",name:t,args:n}}if(this.check(r.LBRACKET)){this.advance();let n=[this.parseExpression()];for(;this.check(r.COMMA);)this.advance(),n.push(this.parseExpression());this.expect(r.RBRACKET);let i;if(n.length===1)i=n[0];else{i=n[0];for(let s=1;s<n.length;s++)i={type:"binary",operator:" ",left:{type:"binary",operator:" ",left:i,right:{type:"variable",name:"SUBSEP"}},right:n[s]}}return{type:"array_access",array:t,key:i}}return{type:"variable",name:t}}throw new Error(`Unexpected token: ${this.current().type} at line ${this.current().line}:${this.current().column}`)}};var Wt={name:"awk",summary:"pattern scanning and text processing language",usage:"awk [OPTIONS] 'PROGRAM' [FILE...]",options:["-F FS use FS as field separator","-v VAR=VAL assign VAL to variable VAR"," --help display this help and exit"]},Wn={name:"awk",async execute(e,t){D(t.requireDefenseContext,"awk","execution entry");let n=(h,c)=>_(t.requireDefenseContext,"awk",h,c);if(fe(e))return pe(Wt);let i=new H(/\s+/),s=" ",a=Object.create(null),o=0;for(let h=0;h<e.length;h++){let c=e[h];if(c==="-F"&&h+1<e.length)s=he(e[++h]),i=_e(s),o=h+1;else if(c.startsWith("-F"))s=he(c.slice(2)),i=_e(s),o=h+1;else if(c==="-v"&&h+1<e.length){let E=e[++h],F=E.indexOf("=");if(F>0){let G=E.slice(0,F),xe=he(E.slice(F+1));a[G]=xe}o=h+1}else{if(c.startsWith("--"))return re("awk",c);if(c.startsWith("-")&&c.length>1){let E=c[1];if(E!=="F"&&E!=="v")return re("awk",`-${E}`);o=h+1}else if(!c.startsWith("-")){o=h;break}}}if(o>=e.length)return{stdout:"",stderr:`awk: missing program
|
|
15
|
+
`,exitCode:1};let l=e[o],u=e.slice(o+1),N=new ne,v;try{v=N.parse(l)}catch(h){return{stdout:"",stderr:`awk: ${h instanceof Error?h.message:String(h)}
|
|
16
|
+
`,exitCode:1}}let C={readFile:t.fs.readFile.bind(t.fs),writeFile:t.fs.writeFile.bind(t.fs),appendFile:async(h,c)=>{try{let E=await n("appendFile read",()=>t.fs.readFile(h));await n("appendFile write",()=>t.fs.writeFile(h,E+c))}catch(E){if(E instanceof x)throw E;await n("appendFile create",()=>t.fs.writeFile(h,c))}},resolvePath:t.fs.resolvePath.bind(t.fs)},O=t.exec,I=ie({fieldSep:i,maxIterations:t.limits?.maxAwkIterations,maxOutputSize:t.limits?.maxStringLength,fs:C,cwd:t.cwd,exec:O?h=>n("command pipe exec",()=>O(h,{cwd:t.cwd,signal:t.signal})):void 0,coverage:t.coverage,requireDefenseContext:t.requireDefenseContext});I.FS=s,I.vars=Object.assign(Object.create(null),a),I.ARGC=u.length+1,I.ARGV=Object.create(null),I.ARGV[0]="awk";for(let h=0;h<u.length;h++)I.ARGV[String(h+1)]=u[h];I.ENVIRON=de(t.env);let w=new q(I);w.execute(v);let d=v.rules.some(h=>h.pattern?.type!=="begin"&&h.pattern?.type!=="end"),R=v.rules.some(h=>h.pattern?.type==="end");try{if(await n("BEGIN execution",()=>w.executeBegin()),I.shouldExit)return await n("END execution after BEGIN exit",()=>w.executeEnd()),{stdout:w.getOutput(),stderr:"",exitCode:w.getExitCode()};if(!d&&!R)return{stdout:w.getOutput(),stderr:"",exitCode:w.getExitCode()};let h=[];if(u.length>0)for(let c of u)try{let E=t.fs.resolvePath(t.cwd,c),G=(await n("input file read",()=>t.fs.readFile(E))).split(`
|
|
17
|
+
`);G.length>0&&G[G.length-1]===""&&G.pop(),h.push({filename:c,lines:G})}catch(E){if(E instanceof x)throw E;return{stdout:"",stderr:`awk: ${c}: No such file or directory
|
|
18
|
+
`,exitCode:1}}else{let c=t.stdin.split(`
|
|
19
|
+
`);c.length>0&&c[c.length-1]===""&&c.pop(),h.push({filename:"",lines:c})}for(let c of h){for(I.FILENAME=c.filename,I.FNR=0,I.lines=c.lines,I.lineIndex=-1,I.shouldNextFile=!1;I.lineIndex<c.lines.length-1;){I.lineIndex++;let E=I.lineIndex;if(await n("line execution",()=>w.executeLine(c.lines[E])),I.shouldExit||I.shouldNextFile)break}if(I.shouldExit)break}return await n("END execution",()=>w.executeEnd()),{stdout:w.getOutput(),stderr:"",exitCode:w.getExitCode()}}catch(h){if(h instanceof x)throw h;let c=h instanceof Error?h.message:String(h),E=h instanceof P?P.EXIT_CODE:2;return{stdout:w.getOutput(),stderr:`awk: ${c}
|
|
20
|
+
`,exitCode:E}}}};function he(e){return e.replace(/\\t/g," ").replace(/\\n/g,`
|
|
21
|
+
`).replace(/\\r/g,"\r").replace(/\\b/g,"\b").replace(/\\f/g,"\f").replace(/\\a/g,"\x07").replace(/\\v/g,"\v").replace(/\\\\/g,"\\")}function _e(e){if(e===" ")return A("\\s+");if(/[[\](){}.*+?^$|\\]/.test(e))try{return A(e)}catch{return A(Ge(e))}return A(Ge(e))}function Ge(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Vn={name:"awk",flags:[{flag:"-F",type:"value",valueHint:"delimiter"},{flag:"-v",type:"value",valueHint:"string"}],stdinType:"text",needsArgs:!0};export{Wn as a,Vn as b};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{a as h}from"./chunk-KGOUQS5A.js";function v(){let a=[{prop:"Function",target:globalThis,violationType:"function_constructor",strategy:"throw",reason:"Function constructor allows arbitrary code execution"},{prop:"eval",target:globalThis,violationType:"eval",strategy:"throw",reason:"eval() allows arbitrary code execution"},{prop:"setTimeout",target:globalThis,violationType:"setTimeout",strategy:"throw",reason:"setTimeout with string argument allows code execution"},{prop:"setInterval",target:globalThis,violationType:"setInterval",strategy:"throw",reason:"setInterval with string argument allows code execution"},{prop:"setImmediate",target:globalThis,violationType:"setImmediate",strategy:"throw",reason:"setImmediate could be used to escape sandbox context"},{prop:"env",target:process,violationType:"process_env",strategy:"throw",reason:"process.env could leak sensitive environment variables",allowedKeys:new Set(["NODE_V8_COVERAGE","NODE_DEBUG","NODE_DEBUG_NATIVE","NODE_COMPILE_CACHE","WATCH_REPORT_DEPENDENCIES","FORCE_COLOR","DEBUG","UNDICI_NO_FG","JEST_WORKER_ID","__MINIMATCH_TESTING_PLATFORM__","LOG_TOKENS","LOG_STREAM"])},{prop:"binding",target:process,violationType:"process_binding",strategy:"throw",reason:"process.binding provides access to native Node.js modules"},{prop:"_linkedBinding",target:process,violationType:"process_binding",strategy:"throw",reason:"process._linkedBinding provides access to native Node.js modules"},{prop:"dlopen",target:process,violationType:"process_dlopen",strategy:"throw",reason:"process.dlopen allows loading native addons"},{prop:"getBuiltinModule",target:process,violationType:"process_get_builtin_module",strategy:"throw",reason:"process.getBuiltinModule allows loading native Node.js modules (fs, child_process, vm)"},{prop:"exit",target:process,violationType:"process_exit",strategy:"throw",reason:"process.exit could terminate the interpreter"},{prop:"abort",target:process,violationType:"process_exit",strategy:"throw",reason:"process.abort could crash the interpreter"},{prop:"kill",target:process,violationType:"process_kill",strategy:"throw",reason:"process.kill could signal other processes"},{prop:"setuid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setuid could escalate privileges"},{prop:"setgid",target:process,violationType:"process_setuid",strategy:"throw",reason:"process.setgid could escalate privileges"},{prop:"umask",target:process,violationType:"process_umask",strategy:"throw",reason:"process.umask could modify file creation permissions"},{prop:"argv",target:process,violationType:"process_argv",strategy:"throw",reason:"process.argv may contain secrets in CLI arguments"},{prop:"chdir",target:process,violationType:"process_chdir",strategy:"throw",reason:"process.chdir could confuse the interpreter's CWD tracking"},{prop:"send",target:process,violationType:"process_send",strategy:"throw",reason:"process.send could communicate with parent process in IPC contexts"},{prop:"channel",target:process,violationType:"process_channel",strategy:"throw",reason:"process.channel could access IPC channel to parent process"},{prop:"cpuUsage",target:process,violationType:"process_timing",strategy:"throw",reason:"process.cpuUsage could enable timing side-channel attacks"},{prop:"memoryUsage",target:process,violationType:"process_timing",strategy:"throw",reason:"process.memoryUsage could enable timing side-channel attacks"},{prop:"hrtime",target:process,violationType:"process_timing",strategy:"throw",reason:"process.hrtime could enable timing side-channel attacks"},{prop:"WeakRef",target:globalThis,violationType:"weak_ref",strategy:"throw",reason:"WeakRef could be used to leak references outside sandbox"},{prop:"FinalizationRegistry",target:globalThis,violationType:"finalization_registry",strategy:"throw",reason:"FinalizationRegistry could be used to leak references outside sandbox"},{prop:"Reflect",target:globalThis,violationType:"reflect",strategy:"freeze",reason:"Reflect provides introspection capabilities"},{prop:"Proxy",target:globalThis,violationType:"proxy",strategy:"throw",reason:"Proxy allows intercepting and modifying object behavior"},{prop:"WebAssembly",target:globalThis,violationType:"webassembly",strategy:"throw",reason:"WebAssembly allows executing arbitrary compiled code"},{prop:"SharedArrayBuffer",target:globalThis,violationType:"shared_array_buffer",strategy:"throw",reason:"SharedArrayBuffer could enable side-channel communication or timing attacks"},{prop:"Atomics",target:globalThis,violationType:"atomics",strategy:"throw",reason:"Atomics could enable side-channel communication or timing attacks"},{prop:"performance",target:globalThis,violationType:"performance_timing",strategy:"throw",reason:"performance.now() provides sub-millisecond timing for side-channel attacks"},{prop:"stdout",target:process,violationType:"process_stdout",strategy:"throw",reason:"process.stdout could bypass interpreter output to write to host stdout"},{prop:"stderr",target:process,violationType:"process_stderr",strategy:"throw",reason:"process.stderr could bypass interpreter output to write to host stderr"},{prop:"__defineGetter__",target:Object.prototype,violationType:"prototype_mutation",strategy:"throw",reason:"__defineGetter__ allows prototype pollution via getter injection"},{prop:"__defineSetter__",target:Object.prototype,violationType:"prototype_mutation",strategy:"throw",reason:"__defineSetter__ allows prototype pollution via setter injection"},{prop:"__lookupGetter__",target:Object.prototype,violationType:"prototype_mutation",strategy:"throw",reason:"__lookupGetter__ enables introspection for prototype pollution attacks"},{prop:"__lookupSetter__",target:Object.prototype,violationType:"prototype_mutation",strategy:"throw",reason:"__lookupSetter__ enables introspection for prototype pollution attacks"},{prop:"JSON",target:globalThis,violationType:"json_mutation",strategy:"freeze",reason:"Freeze JSON to prevent mutation of parsing/serialization"},{prop:"Math",target:globalThis,violationType:"math_mutation",strategy:"freeze",reason:"Freeze Math to prevent mutation of math utilities"}];try{let e=Object.getPrototypeOf(async()=>{}).constructor;e&&e!==Function&&a.push({prop:"constructor",target:Object.getPrototypeOf(async()=>{}),violationType:"async_function_constructor",strategy:"throw",reason:"AsyncFunction constructor allows arbitrary async code execution"})}catch{}try{let e=Object.getPrototypeOf(function*(){}).constructor;e&&e!==Function&&a.push({prop:"constructor",target:Object.getPrototypeOf(function*(){}),violationType:"generator_function_constructor",strategy:"throw",reason:"GeneratorFunction constructor allows arbitrary generator code execution"})}catch{}try{let e=Object.getPrototypeOf(async function*(){}).constructor;e&&e!==Function&&e!==Object.getPrototypeOf(async()=>{}).constructor&&a.push({prop:"constructor",target:Object.getPrototypeOf(async function*(){}),violationType:"async_generator_function_constructor",strategy:"throw",reason:"AsyncGeneratorFunction constructor allows arbitrary async generator code execution"})}catch{}return a.filter(e=>{try{return e.target[e.prop]!==void 0}catch{return!1}})}var g=typeof __BROWSER__<"u"&&__BROWSER__;function _(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,a=>{let e=Math.random()*16|0;return(a==="x"?e:e&3|8).toString(16)})}var x=null;if(!g)try{let{AsyncLocalStorage:a}=h("node:async_hooks");x=a}catch{}var T=`
|
|
3
|
+
|
|
4
|
+
This is a defense-in-depth measure and indicates a bug in just-bash. Please report this at security@vercel.com`,p=class extends Error{violation;constructor(e,t){super(e+T),this.violation=t,this.name="SecurityViolationError"}},u=!g&&x?new x:null,k=1e3;function D(a,e,...t){return u.run(a,()=>e(...t))}var m={enabled:!0,auditMode:!1};function O(a){return a===void 0?{...m,enabled:!1}:typeof a=="boolean"?{...m,enabled:a}:{...m,...a}}var w=class a{static instance=null;static importHooksRegistered=!1;config;refCount=0;patchFailures=[];activeExecutionIds=new Set;contextCache=new Map;originalDescriptors=[];violations=[];activationTime=0;totalActiveTimeMs=0;constructor(e){this.config=e}static getInstance(e){let t=O(e);if(!a.instance)a.instance=new a(t);else{let o=a.instance.config;if(t.enabled!==o.enabled||t.auditMode!==o.auditMode)throw new Error(`DefenseInDepthBox config conflict: requested {enabled: ${t.enabled}, auditMode: ${t.auditMode}} but singleton already has {enabled: ${o.enabled}, auditMode: ${o.auditMode}}. All Bash instances must use the same defense-in-depth security settings, or call DefenseInDepthBox.resetInstance() between incompatible configurations.`)}return a.instance}static resetInstance(){a.instance&&(a.instance.forceDeactivate(),a.instance=null)}static isInSandboxedContext(){return u?u?.getStore()?.sandboxActive===!0:!1}static getCurrentExecutionId(){if(u)return u?.getStore()?.executionId}isExecutionIdActive(e){return this.activeExecutionIds.has(e)}getCachedContext(e){let t=this.contextCache.get(e);return t||(t={sandboxActive:!0,executionId:e},this.contextCache.set(e,t)),t}getPreferredActiveExecutionId(){if(this.activeExecutionIds.size!==0)for(let e of this.activeExecutionIds)return e}static bindCurrentContext(e){if(!u)return e;let t=u.getStore(),o=t?.sandboxActive===!0?t.executionId:a.instance?.getPreferredActiveExecutionId();if(!o)return e;let s=a.instance?.getCachedContext(o)??{sandboxActive:!0,executionId:o};return D.bind(null,s,e)}isEnabled(){return this.config.enabled===!0&&u!==null&&!g}updateConfig(e){this.config={...this.config,...e}}activate(){if(g||!this.config.enabled||!u){let o=_(),s=!1;return{run:r=>s?Promise.reject(new Error("DefenseInDepthBox handle is deactivated and cannot run new work")):r(),deactivate:()=>{s=!0},executionId:o}}this.refCount++,this.refCount===1&&(this.applyPatches(),this.activationTime=Date.now());let e=_(),t=!1;return{run:o=>t?Promise.reject(new Error("DefenseInDepthBox handle is deactivated and cannot run new work")):(this.activeExecutionIds.add(e),u.run({sandboxActive:!0,executionId:e},o)),deactivate:()=>{t||(t=!0,this.activeExecutionIds.delete(e),this.contextCache.delete(e),this.refCount--,this.refCount===0&&(this.restorePatches(),this.totalActiveTimeMs+=Date.now()-this.activationTime),this.refCount<0&&(this.refCount=0))},executionId:e}}forceDeactivate(){this.refCount>0&&(this.restorePatches(),this.totalActiveTimeMs+=Date.now()-this.activationTime),this.activeExecutionIds.clear(),this.contextCache.clear(),this.refCount=0}isActive(){return this.refCount>0}getStats(){return{violationsBlocked:this.violations.length,violations:[...this.violations],activeTimeMs:this.totalActiveTimeMs+(this.refCount>0?Date.now()-this.activationTime:0),refCount:this.refCount}}getPatchFailures(){return[...this.patchFailures]}clearViolations(){this.violations=[]}getPathForTarget(e,t){return e===globalThis?`globalThis.${t}`:e===process?`process.${t}`:e===Error?`Error.${t}`:e===Function.prototype?`Function.prototype.${t}`:e===Object.prototype?`Object.prototype.${t}`:`<object>.${t}`}static runTrusted(e){if(!u)return e();let t=u.getStore();return t?u.run({...t,trusted:!0},e):e()}static async runTrustedAsync(e){if(!u)return e();let t=u.getStore();return t?u.run({...t,trusted:!0},e):e()}shouldBlock(){if(g||this.config.auditMode||!u)return!1;let e=u?.getStore();return!(e?.sandboxActive!==!0||e.trusted)}recordViolation(e,t,o){let s={timestamp:Date.now(),type:e,message:o,path:t,stack:new Error().stack,executionId:u?.getStore()?.executionId};if(this.violations.length<k&&this.violations.push(s),this.config.onViolation)try{this.config.onViolation(s)}catch(r){console.debug("[DefenseInDepthBox] onViolation callback threw:",r instanceof Error?r.message:r)}return s}createBlockingProxy(e,t,o){let s=this;return new Proxy(e,{apply(r,n,i){if(s.shouldBlock()){let c=`${t} is blocked during script execution`,l=s.recordViolation(o,t,c);throw new p(c,l)}return s.config.auditMode&&u?.getStore()?.sandboxActive===!0&&s.recordViolation(o,t,`${t} called (audit mode)`),Reflect.apply(r,n,i)},construct(r,n,i){if(s.shouldBlock()){let c=`${t} constructor is blocked during script execution`,l=s.recordViolation(o,t,c);throw new p(c,l)}return s.config.auditMode&&u?.getStore()?.sandboxActive===!0&&s.recordViolation(o,t,`${t} constructor called (audit mode)`),Reflect.construct(r,n,i)}})}createBlockingObjectProxy(e,t,o,s){let r=this;return new Proxy(e,{get(n,i,c){if(r.shouldBlock()){if(s&&typeof i=="string"&&s.has(i))return Reflect.get(n,i,c);let l=`${t}.${String(i)}`,d=`${l} is blocked during script execution`,f=r.recordViolation(o,l,d);throw new p(d,f)}if(r.config.auditMode&&u?.getStore()?.sandboxActive===!0){let l=`${t}.${String(i)}`;r.recordViolation(o,l,`${l} accessed (audit mode)`)}return Reflect.get(n,i,c)},set(n,i,c,l){if(r.shouldBlock()){let d=`${t}.${String(i)}`,f=`${d} modification is blocked during script execution`,y=r.recordViolation(o,d,f);throw new p(f,y)}return Reflect.set(n,i,c,l)},ownKeys(n){if(r.shouldBlock()){let i=`${t} enumeration is blocked during script execution`,c=r.recordViolation(o,t,i);throw new p(i,c)}return Reflect.ownKeys(n)},getOwnPropertyDescriptor(n,i){if(r.shouldBlock()){let c=`${t}.${String(i)}`,l=`${c} descriptor access is blocked during script execution`,d=r.recordViolation(o,c,l);throw new p(l,d)}return Reflect.getOwnPropertyDescriptor(n,i)},has(n,i){if(r.shouldBlock()){let c=`${t}.${String(i)}`,l=`${c} existence check is blocked during script execution`,d=r.recordViolation(o,c,l);throw new p(l,d)}return Reflect.has(n,i)}})}applyPatches(){this.patchFailures=[];let e=v(),t=new Set(["process_send","process_channel","process_stdout","process_stderr"]);for(let r of e)t.has(r.violationType)||this.applyPatch(r);this.protectConstructorChain(),this.protectErrorPrepareStackTrace(),this.protectPromiseThen(),this.protectDynamicImport(),this.protectModuleLoad(),this.protectModuleResolveFilename(),this.protectProcessMainModule(),this.protectProcessExecPath();let o=["Function.prototype.constructor","Module._load"],s=this.patchFailures.filter(r=>o.includes(r));if(s.length>0)throw this.restorePatches(),new Error(`DefenseInDepthBox: critical patches failed: ${s.join(", ")}`)}protectConstructorChain(){this.patchPrototypeConstructor(Function.prototype,"Function.prototype.constructor","function_constructor");try{let e=Object.getPrototypeOf(async()=>{}).constructor;e&&e!==Function&&this.patchPrototypeConstructor(e.prototype,"AsyncFunction.prototype.constructor","async_function_constructor")}catch(e){this.patchFailures.push("AsyncFunction.prototype.constructor"),console.debug("[DefenseInDepthBox] Could not patch AsyncFunction.prototype.constructor:",e instanceof Error?e.message:e)}try{let e=Object.getPrototypeOf(function*(){}).constructor;e&&e!==Function&&this.patchPrototypeConstructor(e.prototype,"GeneratorFunction.prototype.constructor","generator_function_constructor")}catch(e){this.patchFailures.push("GeneratorFunction.prototype.constructor"),console.debug("[DefenseInDepthBox] Could not patch GeneratorFunction.prototype.constructor:",e instanceof Error?e.message:e)}try{let e=Object.getPrototypeOf(async function*(){}).constructor,t=Object.getPrototypeOf(async()=>{}).constructor;e&&e!==Function&&e!==t&&this.patchPrototypeConstructor(e.prototype,"AsyncGeneratorFunction.prototype.constructor","async_generator_function_constructor")}catch(e){this.patchFailures.push("AsyncGeneratorFunction.prototype.constructor"),console.debug("[DefenseInDepthBox] Could not patch AsyncGeneratorFunction.prototype.constructor:",e instanceof Error?e.message:e)}}protectErrorPrepareStackTrace(){let e=this;try{let t=Object.getOwnPropertyDescriptor(Error,"prepareStackTrace");this.originalDescriptors.push({target:Error,prop:"prepareStackTrace",descriptor:t});let o=t?.value;Object.defineProperty(Error,"prepareStackTrace",{get(){return o},set(s){if(e.shouldBlock()){let r="Error.prepareStackTrace modification is blocked during script execution",n=e.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace",r);throw new p(r,n)}e.config.auditMode&&u?.getStore()?.sandboxActive===!0&&e.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace","Error.prepareStackTrace set (audit mode)"),o=s},configurable:!0})}catch(t){this.patchFailures.push("Error.prepareStackTrace"),console.debug("[DefenseInDepthBox] Could not protect Error.prepareStackTrace:",t instanceof Error?t.message:t)}}protectPromiseThen(){let e=this;try{let r=function(...n){return u.run(this.captured,()=>{if(!this.box.isExecutionIdActive(this.executionId)){if(this.box.recordViolation("promise_then_after_deactivate","Promise.then","Promise.then callback is blocked after defense deactivation"),this.box.config.auditMode)return Reflect.apply(this.cb,void 0,n);if(this.kind==="fulfilled")return n[0];throw n[0]}return Reflect.apply(this.cb,void 0,n)})};var t=r;let o=Object.getOwnPropertyDescriptor(Promise.prototype,"then");this.originalDescriptors.push({target:Promise.prototype,prop:"then",descriptor:o});let s=o?.value;if(typeof s!="function")return;Object.defineProperty(Promise.prototype,"then",{value:function(i,c){if(!u)return Reflect.apply(s,this,[i,c]);let l=u.getStore(),d=l?.sandboxActive===!0&&l.trusted!==!0?l.executionId:void 0;if(!d)return Reflect.apply(s,this,[i,c]);let f=e.getCachedContext(d),y=(b,P)=>typeof b!="function"?b:r.bind({box:e,executionId:d,captured:f,cb:b,kind:P});return Reflect.apply(s,this,[y(i,"fulfilled"),y(c,"rejected")])},writable:!0,configurable:!0})}catch(o){this.patchFailures.push("Promise.prototype.then"),console.debug("[DefenseInDepthBox] Could not protect Promise.prototype.then:",o instanceof Error?o.message:o)}}patchPrototypeConstructor(e,t,o){let s=this;try{let r=Object.getOwnPropertyDescriptor(e,"constructor");this.originalDescriptors.push({target:e,prop:"constructor",descriptor:r});let n=r?.value;Object.defineProperty(e,"constructor",{get(){if(s.shouldBlock()){let i=`${t} access is blocked during script execution`,c=s.recordViolation(o,t,i);throw new p(i,c)}return s.config.auditMode&&u?.getStore()?.sandboxActive===!0&&s.recordViolation(o,t,`${t} accessed (audit mode)`),n},set(i){if(s.shouldBlock()){let c=`${t} modification is blocked during script execution`,l=s.recordViolation(o,t,c);throw new p(c,l)}Object.defineProperty(this,"constructor",{value:i,writable:!0,configurable:!0})},configurable:!0})}catch(r){this.patchFailures.push(t),console.debug(`[DefenseInDepthBox] Could not patch ${t}:`,r instanceof Error?r.message:r)}}protectProcessMainModule(){if(typeof process>"u")return;let e=this;try{let t=Object.getOwnPropertyDescriptor(process,"mainModule");this.originalDescriptors.push({target:process,prop:"mainModule",descriptor:t});let o=t?.value;o!==void 0&&Object.defineProperty(process,"mainModule",{get(){if(e.shouldBlock()){let s="process.mainModule access is blocked during script execution",r=e.recordViolation("process_main_module","process.mainModule",s);throw new p(s,r)}return e.config.auditMode&&u?.getStore()?.sandboxActive===!0&&e.recordViolation("process_main_module","process.mainModule","process.mainModule accessed (audit mode)"),o},set(s){if(e.shouldBlock()){let r="process.mainModule modification is blocked during script execution",n=e.recordViolation("process_main_module","process.mainModule",r);throw new p(r,n)}Object.defineProperty(process,"mainModule",{value:s,writable:!0,configurable:!0})},configurable:!0})}catch(t){this.patchFailures.push("process.mainModule"),console.debug("[DefenseInDepthBox] Could not protect process.mainModule:",t instanceof Error?t.message:t)}}protectProcessExecPath(){if(typeof process>"u")return;let e=this;try{let t=Object.getOwnPropertyDescriptor(process,"execPath");this.originalDescriptors.push({target:process,prop:"execPath",descriptor:t});let o=t?.value??process.execPath;Object.defineProperty(process,"execPath",{get(){if(e.shouldBlock()){let s="process.execPath access is blocked during script execution",r=e.recordViolation("process_exec_path","process.execPath",s);throw new p(s,r)}return e.config.auditMode&&u?.getStore()?.sandboxActive===!0&&e.recordViolation("process_exec_path","process.execPath","process.execPath accessed (audit mode)"),o},set(s){if(e.shouldBlock()){let r="process.execPath modification is blocked during script execution",n=e.recordViolation("process_exec_path","process.execPath",r);throw new p(r,n)}Object.defineProperty(process,"execPath",{value:s,writable:!0,configurable:!0})},configurable:!0})}catch(t){this.patchFailures.push("process.execPath"),console.debug("[DefenseInDepthBox] Could not protect process.execPath:",t instanceof Error?t.message:t)}}protectDynamicImport(){if(!(g||a.importHooksRegistered))try{let e=h("node:module");if(typeof e.registerHooks=="function"){e.registerHooks({resolve(t,o,s){if(t.startsWith("data:")||t.startsWith("blob:"))throw new Error(`dynamic import of ${t.startsWith("data:")?"data:":"blob:"} URLs is blocked by defense-in-depth`);return s(t,o)}}),a.importHooksRegistered=!0;return}if(typeof e.register=="function"){let t=["export async function resolve(specifier, context, nextResolve) {",' if (specifier.startsWith("data:") || specifier.startsWith("blob:")) {',' throw new Error("dynamic import of " + (specifier.startsWith("data:") ? "data:" : "blob:") + " URLs is blocked by defense-in-depth");'," }"," return nextResolve(specifier, context);","}"].join(`
|
|
5
|
+
`);e.register(`data:text/javascript,${encodeURIComponent(t)}`),a.importHooksRegistered=!0}}catch(e){console.debug("[DefenseInDepthBox] Could not register import() hooks:",e instanceof Error?e.message:e)}}protectModuleLoad(){if(!g)try{let e=null;if(typeof process<"u"){let n=process.mainModule;n&&typeof n=="object"&&(e=n.constructor)}if(!e&&typeof h<"u"&&typeof h.main<"u"&&(e=h.main.constructor),!e||typeof e._load!="function")return;let t=e._load,o=Object.getOwnPropertyDescriptor(e,"_load");this.originalDescriptors.push({target:e,prop:"_load",descriptor:o});let r=this.createBlockingProxy(t,"Module._load","module_load");Object.defineProperty(e,"_load",{value:r,writable:!0,configurable:!0})}catch(e){this.patchFailures.push("Module._load"),console.debug("[DefenseInDepthBox] Could not protect Module._load:",e instanceof Error?e.message:e)}}protectModuleResolveFilename(){if(!g)try{let e=null;if(typeof process<"u"){let n=process.mainModule;n&&typeof n=="object"&&(e=n.constructor)}if(!e&&typeof h<"u"&&typeof h.main<"u"&&(e=h.main.constructor),!e||typeof e._resolveFilename!="function")return;let t=e._resolveFilename,o=Object.getOwnPropertyDescriptor(e,"_resolveFilename");this.originalDescriptors.push({target:e,prop:"_resolveFilename",descriptor:o});let r=this.createBlockingProxy(t,"Module._resolveFilename","module_resolve_filename");Object.defineProperty(e,"_resolveFilename",{value:r,writable:!0,configurable:!0})}catch(e){this.patchFailures.push("Module._resolveFilename"),console.debug("[DefenseInDepthBox] Could not protect Module._resolveFilename:",e instanceof Error?e.message:e)}}applyPatch(e){let{target:t,prop:o,violationType:s,strategy:r}=e;try{let n=t[o];if(n===void 0)return;let i=Object.getOwnPropertyDescriptor(t,o);if(this.originalDescriptors.push({target:t,prop:o,descriptor:i}),r==="freeze")typeof n=="object"&&n!==null&&Object.freeze(n);else{let c=this.getPathForTarget(t,o),l=typeof n=="function"?this.createBlockingProxy(n,c,s):this.createBlockingObjectProxy(n,c,s,e.allowedKeys);Object.defineProperty(t,o,{value:l,writable:!0,configurable:!0})}}catch(n){let i=this.getPathForTarget(t,o);this.patchFailures.push(i),console.debug(`[DefenseInDepthBox] Could not patch ${i}:`,n instanceof Error?n.message:n)}}restorePatches(){for(let e=this.originalDescriptors.length-1;e>=0;e--){let{target:t,prop:o,descriptor:s}=this.originalDescriptors[e];try{s?Object.defineProperty(t,o,s):delete t[o]}catch(r){let n=this.getPathForTarget(t,o);console.debug(`[DefenseInDepthBox] Could not restore ${n}:`,r instanceof Error?r.message:r)}}this.originalDescriptors=[]}};export{p as a,w as b};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a}from"./chunk-SE4C7FJY.js";var
|
|
3
|
-
`,exitCode:2};try{let
|
|
4
|
-
`,stderr:"",exitCode:h}}catch(
|
|
5
|
-
`,exitCode:2}}}};function
|
|
2
|
+
import{a}from"./chunk-SE4C7FJY.js";import{a as d}from"./chunk-SYG3IW7P.js";var S={name:"expr",async execute(s,r){if(s.length===0)return{stdout:"",stderr:`expr: missing operand
|
|
3
|
+
`,exitCode:2};try{let c=x(s),h=c==="0"||c===""?1:0;return{stdout:`${c}
|
|
4
|
+
`,stderr:"",exitCode:h}}catch(c){return{stdout:"",stderr:`expr: ${d(c.message)}
|
|
5
|
+
`,exitCode:2}}}};function x(s){if(s.length===1)return s[0];let r=0;function c(){let e=h();for(;r<s.length&&s[r]==="|";){r++;let t=h();if(e!=="0"&&e!=="")return e;e=t}return e}function h(){let e=m();for(;r<s.length&&s[r]==="&";){r++;let t=m();(e==="0"||e===""||t==="0"||t==="")&&(e="0")}return e}function m(){let e=g();for(;r<s.length;){let t=s[r];if(["=","!=","<",">","<=",">="].includes(t)){r++;let o=g(),n=parseInt(e,10),i=parseInt(o,10),f=!Number.isNaN(n)&&!Number.isNaN(i),l;t==="="?l=f?n===i:e===o:t==="!="?l=f?n!==i:e!==o:t==="<"?l=f?n<i:e<o:t===">"?l=f?n>i:e>o:t==="<="?l=f?n<=i:e<=o:l=f?n>=i:e>=o,e=l?"1":"0"}else break}return e}function g(){let e=p();for(;r<s.length;){let t=s[r];if(t==="+"||t==="-"){r++;let o=p(),n=parseInt(e,10),i=parseInt(o,10);if(Number.isNaN(n)||Number.isNaN(i))throw new Error("non-integer argument");e=String(t==="+"?n+i:n-i)}else break}return e}function p(){let e=N();for(;r<s.length;){let t=s[r];if(t==="*"||t==="/"||t==="%"){r++;let o=N(),n=parseInt(e,10),i=parseInt(o,10);if(Number.isNaN(n)||Number.isNaN(i))throw new Error("non-integer argument");if((t==="/"||t==="%")&&i===0)throw new Error("division by zero");t==="*"?e=String(n*i):t==="/"?e=String(Math.trunc(n/i)):e=String(n%i)}else break}return e}function N(){let e=u();for(;r<s.length&&s[r]===":";){r++;let t=u(),n=a(`^${t}`).match(e);n?e=n[1]!==void 0?n[1]:String(n[0].length):e="0"}return e}function u(){if(r>=s.length)throw new Error("syntax error");let e=s[r];if(e==="match"){r++;let t=u(),o=u(),i=a(o).match(t);return i?i[1]!==void 0?i[1]:String(i[0].length):"0"}if(e==="substr"){r++;let t=u(),o=parseInt(u(),10),n=parseInt(u(),10);if(Number.isNaN(o)||Number.isNaN(n))throw new Error("non-integer argument");return t.substring(o-1,o-1+n)}if(e==="index"){r++;let t=u(),o=u();for(let n=0;n<t.length;n++)if(o.includes(t[n]))return String(n+1);return"0"}if(e==="length"){r++;let t=u();return String(t.length)}if(e==="("){r++;let t=c();if(r>=s.length||s[r]!==")")throw new Error("syntax error");return r++,t}return r++,e}return c()}var E={name:"expr",flags:[],needsArgs:!0};export{S as a,E as b};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as G}from"./chunk-
|
|
2
|
+
import{b as G}from"./chunk-EO5AH4U7.js";import{a as I}from"./chunk-SE4C7FJY.js";import{a as se,b as ae,c as H}from"./chunk-GTNBSMZR.js";import ve from"compressjs";var j="file",le="link",ue="symlink",Z="directory",Ze={file:"0",link:"1",symlink:"2","character-device":"3","block-device":"4",directory:"5",fifo:"6","pax-header":"x","pax-global-header":"g","gnu-long-name":"L","gnu-long-link-name":"K"},Be={0:j,1:le,2:ue,3:"character-device",4:"block-device",5:Z,6:"fifo",x:"pax-header",g:"pax-global-header",L:"gnu-long-name",K:"gnu-long-link-name"},Ne=new Uint8Array(512),$=new Uint8Array(0),F=new TextEncoder,fe=new TextDecoder;function v(e,t,n,r){r&&F.encodeInto(r,e.subarray(t,t+n))}function z(e,t,n,r){if(r===void 0)return;let i=r.toString(8).padStart(n-1,"0");F.encodeInto(i,e.subarray(t,t+n-1))}function x(e,t,n){let r=e.indexOf(0,t),i=r===-1||r>t+n?t+n:r;return fe.decode(e.subarray(t,i))}function q(e,t,n){let r=0,i=t+n;for(let s=t;s<i;s++){let o=e[s];if(o===0)break;o!==32&&(r=r*8+(o-48))}return r}function b(e,t,n){if(e[t]&128){let r=0;r=e[t]&127;for(let i=1;i<n;i++)r=r*256+e[t+i];if(!Number.isSafeInteger(r))throw new Error("TAR number too large");return r}return q(e,t,n)}var R=e=>e.type===Z||e.type===ue||e.type===le;async function de(e){if(e==null)return $;if(e instanceof Uint8Array)return e;if(typeof e=="string")return F.encode(e);if(e instanceof ArrayBuffer)return new Uint8Array(e);if(e instanceof Blob)return new Uint8Array(await e.arrayBuffer());throw new TypeError("Unsupported content type for entry body.")}function me(e,t){let{strip:n,filter:r,map:i}=t;if(!n&&!r&&!i)return e;let s={...e};if(n&&n>0){let a=s.name.split("/").filter(Boolean);if(n>=a.length)return null;let c=a.slice(n).join("/");if(s.name=s.type===Z&&!c.endsWith("/")?`${c}/`:c,s.linkname?.startsWith("/")){let l=s.linkname.split("/").filter(Boolean);s.linkname=n>=l.length?"/":`/${l.slice(n).join("/")}`}}if(r?.(s)===!1)return null;let o=i?i(s):s;return o&&(!o.name||!o.name.trim()||o.name==="."||o.name==="/")?null:o}var X=32,De=48;function Le(e){let t=q(e,148,8),n=0;for(let r=0;r<e.length;r++)r>=148&&r<156?n+=X:n+=e[r];return t===n}function Pe(e){e.fill(X,148,156);let t=0;for(let n of e)t+=n;for(let n=153;n>=148;n--)e[n]=(t&7)+De,t>>=3;e[154]=0,e[155]=X}function Ke(e){let t={};e.name.length>100&&pe(e.name)===null&&(t.path=e.name),e.linkname&&e.linkname.length>100&&(t.linkpath=e.linkname),e.uname&&e.uname.length>32&&(t.uname=e.uname),e.gname&&e.gname.length>32&&(t.gname=e.gname),e.uid!=null&&e.uid>2097151&&(t.uid=String(e.uid)),e.gid!=null&&e.gid>2097151&&(t.gid=String(e.gid)),e.size!=null&&e.size>8589934591&&(t.size=String(e.size)),e.pax&&Object.assign(t,e.pax);let n=Object.entries(t);if(n.length===0)return null;let r=F.encode(n.map(([i,s])=>{let o=`${i}=${s}
|
|
3
3
|
`,a=F.encode(o).length+1,c=a+String(a).length;return c=a+String(c).length,`${c} ${o}`}).join(""));return{paxHeader:he({name:fe.decode(F.encode(`PaxHeader/${e.name}`).slice(0,100)),size:r.length,type:"pax-header",mode:420,mtime:e.mtime,uname:e.uname,gname:e.gname,uid:e.uid,gid:e.gid}),paxBody:r}}function pe(e){if(e.length<=100)return null;let t=e.length-100-1,n=e.lastIndexOf("/",155);return n>0&&n>=t?{prefix:e.slice(0,n),name:e.slice(n+1)}:null}function he(e){let t=new Uint8Array(512),n=R(e)?0:e.size??0,r=e.name,i="";if(!e.pax?.path){let s=pe(r);s&&(r=s.name,i=s.prefix)}return v(t,0,100,r),z(t,100,8,e.mode??(e.type===Z?493:420)),z(t,108,8,e.uid??0),z(t,116,8,e.gid??0),z(t,124,12,n),z(t,136,12,Math.floor((e.mtime?.getTime()??Date.now())/1e3)),v(t,156,1,Ze[e.type??j]),v(t,157,100,e.linkname),v(t,257,6,"ustar\0"),v(t,263,2,"00"),v(t,265,32,e.uname),v(t,297,32,e.gname),v(t,345,155,i),Pe(t),t}function Ge(e,t){if(t&&!Le(e))throw new Error("Invalid tar header checksum.");let n=x(e,156,1),r={name:x(e,0,100),mode:q(e,100,8),uid:b(e,108,8),gid:b(e,116,8),size:b(e,124,12),mtime:new Date(b(e,136,12)*1e3),type:Be[n]||j,linkname:x(e,157,100)},i=x(e,257,6);return i.trim()==="ustar"&&(r.uname=x(e,265,32),r.gname=x(e,297,32)),i==="ustar"&&(r.prefix=x(e,345,155)),r}var He={path:["name",e=>e],linkpath:["linkname",e=>e],size:["size",e=>parseInt(e,10)],mtime:["mtime",parseFloat],uid:["uid",e=>parseInt(e,10)],gid:["gid",e=>parseInt(e,10)],uname:["uname",e=>e],gname:["gname",e=>e]};function We(e){let t=new TextDecoder("utf-8"),n={},r={},i=0;for(;i<e.length;){let s=e.indexOf(32,i);if(s===-1)break;let o=parseInt(t.decode(e.subarray(i,s)),10);if(Number.isNaN(o)||o===0)break;let a=i+o,[c,l]=t.decode(e.subarray(s+1,a-1)).split("=",2);if(c&&l!==void 0){r[c]=l;let f=He[c];if(f){let[u,g]=f,p=g(l);(typeof p=="string"||!Number.isNaN(p))&&(n[u]=p)}}i=a}return Object.keys(r).length>0&&(n.pax=r),n}function oe(e,t){t.name!==void 0&&(e.name=t.name),t.linkname!==void 0&&(e.linkname=t.linkname),t.size!==void 0&&(e.size=t.size),t.mtime!==void 0&&(e.mtime=new Date(t.mtime*1e3)),t.uid!==void 0&&(e.uid=t.uid),t.gid!==void 0&&(e.gid=t.gid),t.uname!==void 0&&(e.uname=t.uname),t.gname!==void 0&&(e.gname=t.gname),t.pax&&(e.pax=Object.assign({},e.pax??{},t.pax))}function Xe(e){switch(e){case"pax-global-header":case"pax-header":return We;case"gnu-long-name":return t=>({name:x(t,0,t.length)});case"gnu-long-link-name":return t=>({linkname:x(t,0,t.length)});default:return}}function je(e){let t=he(e),n=Ke(e);if(!n)return[t];let r=-n.paxBody.length&511,i=r>0?[Ne.subarray(0,r)]:[];return[n.paxHeader,n.paxBody,...i,t]}var qe=new Uint8Array(512*2);function ge(e,t,n){let r=null,i=0,s=!1;return{add(o){if(s){let a=new Error("No new tar entries after finalize.");throw t(a),a}if(r!==null){let a=new Error("Previous entry must be completed before adding a new one");throw t(a),a}try{let a=R(o)?0:o.size??0,c=je({...o,size:a});for(let l of c)e(l);r={...o,size:a},i=0}catch(a){t(a)}},write(o){if(!r){let c=new Error("No active tar entry.");throw t(c),c}if(s){let c=new Error("Cannot write data after finalize.");throw t(c),c}let a=i+o.length;if(a>r.size){let c=new Error(`"${r.name}" exceeds given size of ${r.size} bytes.`);throw t(c),c}try{i=a,e(o)}catch(c){t(c)}},endEntry(){if(!r){let o=new Error("No active entry to end.");throw t(o),o}if(s){let o=new Error("Cannot end entry after finalize.");throw t(o),o}try{if(i!==r.size){let a=new Error(`Size mismatch for "${r.name}".`);throw t(a),a}let o=-r.size&511;o>0&&e(new Uint8Array(o)),r=null,i=0}catch(o){throw t(o),o}},finalize(){if(s){let o=new Error("Archive has already been finalized");throw t(o),o}if(r!==null){let o=new Error("Cannot finalize while an entry is still active");throw t(o),o}try{e(qe),s=!0,n&&n()}catch(o){t(o)}}}}var O=256;function Ye(){let e=new Array(O),t=e.length-1,n=0,r=0,i=0,s=a=>{let c=e[n];a===c.length?(e[n]=$,n=n+1&t):e[n]=c.subarray(a),i-=a,i===0&&e.length>O&&(e=new Array(O),t=O-1,n=0,r=0)};function o(a,c){if(c){let p=0,d=Math.min(a,i);for(;d>0;){let h=e[n],m=Math.min(d,h.length),E=m===h.length?h:h.subarray(0,m);if(s(m),d-=m,p+=m,!c(E))break}return p}if(i<a)return null;if(a===0)return $;let l=e[n];if(l.length>=a){let p=l.length===a?l:l.subarray(0,a);return s(a),p}let f=new Uint8Array(a),u=0,g=a;for(;g>0;){let p=e[n],d=Math.min(g,p.length);f.set(d===p.length?p:p.subarray(0,d),u),u+=d,g-=d,s(d)}return f}return{push:a=>{if(a.length===0)return;let c=r+1&t;if(c===n){let l=e.length,f=l*2,u=new Array(f),g=r-n+l&l-1;if(n<r)for(let p=0;p<g;p++)u[p]=e[n+p];else if(g>0){let p=l-n;for(let d=0;d<p;d++)u[d]=e[n+d];for(let d=0;d<r;d++)u[p+d]=e[d]}e=u,t=f-1,n=0,r=g,c=r+1&t}e[r]=a,r=c,i+=a.length},available:()=>i,peek:a=>{if(i<a)return null;if(a===0)return $;let c=e[n];if(c.length>=a)return c.length===a?c:c.subarray(0,a);let l=new Uint8Array(a),f=0,u=n;for(;f<a;){let g=e[u],p=Math.min(a-f,g.length);p===g.length?l.set(g,f):l.set(g.subarray(0,p),f),f+=p,u=u+1&t}return l},discard:a=>{if(a>i)throw new Error("Too many bytes consumed");if(a===0)return;let c=a;for(;c>0;){let l=e[n],f=Math.min(c,l.length);s(f),c-=f}},pull:o}}var W=0,k=1,M=new Error("Tar archive is truncated.");function Se(e={}){let t=e.strict??!1,{available:n,peek:r,push:i,discard:s,pull:o}=Ye(),a=W,c=!1,l=!1,f=!1,u=null,g={},p={},d={isEntryActive:()=>a===k,isBodyComplete:()=>!u||u.remaining===0,write(h){if(c)throw new Error("Archive already ended.");i(h)},end(){c=!0},readHeader(){if(a!==W)throw new Error("Cannot read header while an entry is active");if(!l)for(;!l;){if(n()<512){if(c){if(n()>0&&t)throw M;l=!0;return}return null}let h=r(512);if(ce(h)){if(n()<512*2){if(c){if(t)throw M;l=!0;return}return null}if(ce(r(512*2).subarray(512))){s(512*2),l=!0,f=!0;return}if(t)throw new Error("Invalid tar header.");s(512);continue}let m;try{m=Ge(h,t)}catch(A){if(t)throw A;s(512);continue}let E=Xe(m.type);if(E){let A=m.size+511&-512;if(n()<512+A){if(c&&t)throw M;return null}s(512);let w=E(o(A).subarray(0,m.size)),_=m.type==="pax-global-header"?g:p;for(let T in w)_[T]=w[T];continue}s(512);let S=m;return m.prefix&&(S.name=`${m.prefix}/${S.name}`),oe(S,g),oe(S,p),p={},u={header:S,remaining:S.size,padding:-S.size&511},a=k,S}},streamBody(h){if(a!==k||!u||u.remaining===0)return 0;let m=Math.min(u.remaining,n());if(m===0)return 0;let E=o(m,h);return u.remaining-=E,E},skipPadding(){if(a!==k||!u)return!0;if(u.remaining>0)throw new Error("Body not fully consumed");return n()<u.padding?!1:(s(u.padding),u=null,a=W,!0)},skipEntry(){if(a!==k||!u)return!0;let h=Math.min(u.remaining,n());return h>0&&(s(h),u.remaining-=h),u.remaining>0?!1:d.skipPadding()},validateEOF(){if(t){if(!f)throw M;if(n()>0&&o(n()).some(h=>h!==0))throw new Error("Invalid EOF.")}}};return d}function ce(e){if(e.byteOffset%8===0){let t=new BigUint64Array(e.buffer,e.byteOffset,e.length/8);for(let n=0;n<t.length;n++)if(t[n]!==0n)return!1;return!0}for(let t=0;t<e.length;t++)if(e[t]!==0)return!1;return!0}function ye(){return new CompressionStream("gzip")}function we(){return new DecompressionStream("gzip")}function Ve(){let e,t;return{readable:new ReadableStream({start(n){e=n,t=ge(n.enqueue.bind(n),n.error.bind(n),n.close.bind(n))}}),controller:{add(n){let r=R(n),i={...n};return r&&(i.size=0),t.add(i),r&&t.endEntry(),new WritableStream({write(s){t.write(s)},close(){r||t.endEntry()},abort(s){e.error(s)}})},finalize(){t.finalize()},error(n){e.error(n)}}}}async function Ae(e){let t=[],n=e.getReader(),r=0;try{for(;;){let{done:o,value:a}=await n.read();if(o)break;t.push(a),r+=a.length}let i=new Uint8Array(r),s=0;for(let o of t)i.set(o,s),s+=o.length;return i}finally{n.releaseLock()}}var Ee=e=>e.pipeTo(new WritableStream);function Je(e={}){let t=Se(e),n=null,r=!1,i=s=>{if(!r){r=!0;try{for(;;)if(t.isEntryActive()){if(n){if(t.streamBody(o=>(n.enqueue(o),!0))===0&&!t.isBodyComplete())break}else if(!t.skipEntry())break;if(t.isBodyComplete()){try{n?.close()}catch{}if(n=null,!t.skipPadding())break}}else{let o=t.readHeader();if(o==null)break;s.enqueue({header:o,body:new ReadableStream({start(a){o.size===0?a.close():n=a},pull:()=>i(s),cancel(){n=null,i(s)}})})}}catch(o){try{n?.error(o)}catch{}throw n=null,o}finally{r=!1}}};return new TransformStream({transform(s,o){try{t.write(s),i(o)}catch(a){try{n?.error(a)}catch{}throw a}},flush(s){try{if(t.end(),i(s),t.validateEOF(),t.isEntryActive()&&!t.isBodyComplete())try{n?.close()}catch{}}catch(o){try{n?.error(o)}catch{}throw o}}},void 0,{highWaterMark:1})}async function _e(e){let{readable:t,controller:n}=Ve();return await(async()=>{for(let r of e){let i=n.add(r.header),s="body"in r?r.body:r.data;if(!s){await i.close();continue}if(s instanceof ReadableStream)await s.pipeTo(i);else if(s instanceof Blob)await s.stream().pipeTo(i);else try{let o=await de(s);if(o.length>0){let a=i.getWriter();await a.write(o),await a.close()}else await i.close()}catch{throw new TypeError(`Unsupported content type for entry "${r.header.name}".`)}}})().then(()=>n.finalize()).catch(r=>n.error(r)),new Uint8Array(await Ae(t))}async function Te(e,t={}){let n=e instanceof ReadableStream?e:new ReadableStream({start(s){s.enqueue(e instanceof Uint8Array?e:new Uint8Array(e)),s.close()}}),r=[],i=n.pipeThrough(Je(t));for await(let s of i){let o;try{o=me(s.header,t)}catch(a){throw await s.body.cancel(),a}if(o===null){await Ee(s.body);continue}R(o)?(await Ee(s.body),r.push({header:o})):r.push({header:o,data:await Ae(s.body)})}return r}var B=null,N=null;async function Ue(){if(B)return B;if(N)throw N;try{return B=await G.runTrustedAsync(()=>import("node-liblzma")),B}catch{throw N=new Error("xz compression requires node-liblzma which failed to load. Install liblzma-dev (apt) or xz (brew) and reinstall dependencies."),N}}var D=null,L=null;async function Ie(){if(D)return D;if(L)throw L;try{return D=await G.runTrustedAsync(()=>import("@mongodb-js/zstd")),D}catch{throw L=new Error("zstd compression requires @mongodb-js/zstd which is not installed. Install it with: npm install @mongodb-js/zstd"),L}}var y=100*1024*1024,xe=512,Ce=1e4;function Qe(e){let t="file";e.isDirectory?t="directory":e.isSymlink&&(t="symlink");let n=e.name;e.isDirectory&&!n.endsWith("/")&&(n+="/");let r;e.content!==void 0&&(typeof e.content=="string"?r=new TextEncoder().encode(e.content):r=e.content);let i=e.isDirectory||e.isSymlink?0:r?.length??0;return{header:{name:n,mode:e.mode??(e.isDirectory?493:420),uid:e.uid??0,gid:e.gid??0,size:i,mtime:e.mtime??new Date,type:t,linkname:e.linkTarget??"",uname:"user",gname:"user"},body:r}}async function U(e){let t=e.map(Qe);return _e(t)}async function Fe(e){let t=await U(e),i=new ReadableStream({start(l){l.enqueue(t),l.close()}}).pipeThrough(ye()).getReader(),s=[];for(;;){let{done:l,value:f}=await i.read();if(l)break;s.push(f)}let o=s.reduce((l,f)=>l+f.length,0),a=new Uint8Array(o),c=0;for(let l of s)a.set(l,c),c+=l.length;return a}async function C(e){if(e.length>y)return{entries:[],error:`Archive too large (max ${y} bytes)`};if(e.length<xe||e.length%xe!==0)return{entries:[],error:"Invalid tar archive format"};try{let t=await Te(e),n=[];for(let r of t){if(n.length>=Ce)return{entries:n,error:`Too many entries (max ${Ce})`};let i="file";switch(r.header.type){case"directory":i="directory";break;case"symlink":i="symlink";break;case"link":i="hardlink";break;case"file":i="file";break;default:i="other"}n.push({name:r.header.name,mode:r.header.mode??420,uid:r.header.uid??0,gid:r.header.gid??0,size:r.header.size,mtime:r.header.mtime??new Date,type:i,linkTarget:r.header.linkname||void 0,content:r.data??new Uint8Array(0)})}return{entries:n}}catch(t){let n=t instanceof Error?t.message:"Unknown error";return{entries:[],error:n}}}async function Y(e){if(e.length>y)return{entries:[],error:`Archive too large (max ${y} bytes)`};try{let r=new ReadableStream({start(c){c.enqueue(e),c.close()}}).pipeThrough(we()).getReader(),i=[],s=0;for(;;){let{done:c,value:l}=await r.read();if(c)break;if(s+=l.length,s>y)return await r.cancel(),{entries:[],error:`Decompressed archive too large (max ${y} bytes)`};i.push(l)}let o=new Uint8Array(s),a=0;for(let c of i)o.set(c,a),a+=c.length;return C(o)}catch(t){let n=t instanceof Error?t.message:"Unknown error";return{entries:[],error:`Decompression failed: ${n}`}}}function V(e){return e.length>=2&&e[0]===31&&e[1]===139}function J(e){return e.length>=3&&e[0]===66&&e[1]===90&&e[2]===104}function Q(e){return e.length>=6&&e[0]===253&&e[1]===55&&e[2]===122&&e[3]===88&&e[4]===90&&e[5]===0}async function et(e){let n=ve.Bzip2.decompressFile(Array.from(e));return new Uint8Array(n)}async function tt(e){let t=ve.Bzip2,n=[];return t.compressFile(Array.from(e),n,9),new Uint8Array(n)}async function rt(e){let n=(await Ue()).unxzSync(Buffer.from(e));return new Uint8Array(n)}async function nt(e){let n=(await Ue()).xzSync(Buffer.from(e));return new Uint8Array(n)}async function ze(e){let t=await U(e);return tt(t)}async function ke(e){let t=await U(e);return nt(t)}async function ee(e){if(e.length>y)return{entries:[],error:`Archive too large (max ${y} bytes)`};try{let t=await et(e);return t.length>y?{entries:[],error:`Decompressed archive too large (max ${y} bytes)`}:C(t)}catch(t){let n=t instanceof Error?t.message:"Unknown error";return{entries:[],error:n}}}async function te(e,t){if(!t?.allowNativeCodecs)return{entries:[],error:"xz decompression is disabled by default (native codec risk). Pass { allowNativeCodecs: true } to opt in, or decompress the archive externally before extraction."};if(e.length>y)return{entries:[],error:`Archive too large (max ${y} bytes)`};try{let n=await rt(e);return n.length>y?{entries:[],error:`Decompressed archive too large (max ${y} bytes)`}:C(n)}catch(n){let r=n instanceof Error?n.message:"Unknown error";return{entries:[],error:r}}}function re(e){return e.length>=4&&e[0]===40&&e[1]===181&&e[2]===47&&e[3]===253}async function it(e){let n=await(await Ie()).compress(Buffer.from(e),3);return new Uint8Array(n)}async function st(e){let n=await(await Ie()).decompress(Buffer.from(e));return new Uint8Array(n)}async function Re(e){let t=await U(e);return it(t)}async function ne(e,t){if(!t?.allowNativeCodecs)return{entries:[],error:"zstd decompression is disabled by default (native codec risk). Pass { allowNativeCodecs: true } to opt in, or decompress the archive externally before extraction."};if(e.length>y)return{entries:[],error:`Archive too large (max ${y} bytes)`};try{let n=await st(e);return n.length>y?{entries:[],error:`Decompressed archive too large (max ${y} bytes)`}:C(n)}catch(n){let r=n instanceof Error?n.message:"Unknown error";return{entries:[],error:r}}}function be(e){let t={create:!1,append:!1,update:!1,extract:!1,list:!1,file:"",autoCompress:!1,gzip:!1,bzip2:!1,xz:!1,zstd:!1,verbose:!1,toStdout:!1,keepOldFiles:!1,touch:!1,directory:"",preserve:!1,absoluteNames:!1,strip:0,exclude:[],filesFrom:"",excludeFrom:"",wildcards:!1},n=[],r=0;for(;r<e.length;){let i=e[r];if(i.startsWith("-")&&!i.startsWith("--")&&i.length>2){if(/^-\d+$/.test(i)){n.push(i),r++;continue}for(let s=1;s<i.length;s++){let o=i[s];switch(o){case"c":t.create=!0;break;case"r":t.append=!0;break;case"u":t.update=!0;break;case"x":t.extract=!0;break;case"t":t.list=!0;break;case"a":t.autoCompress=!0;break;case"z":t.gzip=!0;break;case"j":t.bzip2=!0;break;case"J":t.xz=!0;break;case"v":t.verbose=!0;break;case"O":t.toStdout=!0;break;case"k":t.keepOldFiles=!0;break;case"m":t.touch=!0;break;case"p":t.preserve=!0;break;case"P":t.absoluteNames=!0;break;case"f":if(s<i.length-1)t.file=i.substring(s+1),s=i.length;else{if(r++,r>=e.length)return{ok:!1,error:{stdout:"",stderr:`tar: option requires an argument -- 'f'
|
|
4
4
|
`,exitCode:2}};t.file=e[r]}break;case"C":if(s<i.length-1)t.directory=i.substring(s+1),s=i.length;else{if(r++,r>=e.length)return{ok:!1,error:{stdout:"",stderr:`tar: option requires an argument -- 'C'
|
|
5
5
|
`,exitCode:2}};t.directory=e[r]}break;case"T":if(s<i.length-1)t.filesFrom=i.substring(s+1),s=i.length;else{if(r++,r>=e.length)return{ok:!1,error:{stdout:"",stderr:`tar: option requires an argument -- 'T'
|