#!/usr/bin/env node
import{a as W,b as U}from"./chunk-WO4B7WUT.js";import{a as I}from"./chunk-EO5AH4U7.js";import{a as A}from"./chunk-SE4C7FJY.js";import{a as L}from"./chunk-SYG3IW7P.js";import{k}from"./chunk-6KZRLMG3.js";import{a as ee,b as te,c as P}from"./chunk-GTNBSMZR.js";var z=new Map([["alnum","a-zA-Z0-9"],["alpha","a-zA-Z"],["ascii","\\x00-\\x7F"],["blank"," \\t"],["cntrl","\\x00-\\x1F\\x7F"],["digit","0-9"],["graph","!-~"],["lower","a-z"],["print"," -~"],["punct","!-/:-@\\[-`{-~"],["space"," \\t\\n\\r\\f\\v"],["upper","A-Z"],["word","a-zA-Z0-9_"],["xdigit","0-9A-Fa-f"]]);function H(i){let e="",t=0,n=!1;for(;t<i.length;){if(i[t]==="["&&!n){if(i[t+1]==="["&&i[t+2]===":"){let s=i.indexOf(":]]",t+3);if(s!==-1){let a=i.slice(t+3,s),r=z.get(a);if(r){e+=`[${r}]`,t=s+3;continue}}}if(i[t+1]==="^"&&i[t+2]==="["&&i[t+3]===":"){let s=i.indexOf(":]]",t+4);if(s!==-1){let a=i.slice(t+4,s),r=z.get(a);if(r){e+=`[^${r}]`,t=s+3;continue}}}e+="[",t++,n=!0,t<i.length&&i[t]==="^"&&(e+="^",t++),t<i.length&&i[t]==="]"&&(e+="\\]",t++);continue}if(n){if(i[t]==="]"){e+="]",t++,n=!1;continue}if(i[t]==="["&&i[t+1]===":"){let s=i.indexOf(":]",t+2);if(s!==-1){let a=i.slice(t+2,s),r=z.get(a);if(r){e+=r,t=s+2;continue}}}if(i[t]==="\\"&&t+1<i.length){e+=i[t]+i[t+1],t+=2;continue}e+=i[t],t++;continue}if(i[t]==="\\"&&t+1<i.length){let s=i[t+1];if(s==="+"||s==="?"||s==="|"){e+=s,t+=2;continue}if(s==="("||s===")"){e+=s,t+=2;continue}if(s==="{"||s==="}"){e+=s,t+=2;continue}if(s==="t"){e+="	",t+=2;continue}if(s==="n"){e+=`
`,t+=2;continue}if(s==="r"){e+="\r",t+=2;continue}e+=i[t]+s,t+=2;continue}if(i[t]==="+"||i[t]==="?"||i[t]==="|"||i[t]==="("||i[t]===")"){e+=`\\${i[t]}`,t++;continue}if(i[t]==="^"&&!(e===""||e.endsWith("("))){e+="\\^",t++;continue}if(i[t]==="$"){let s=t===i.length-1,a=t+2<i.length&&i[t+1]==="\\"&&i[t+2]===")";if(!s&&!a){e+="\\$",t++;continue}}e+=i[t],t++}return e}function V(i){let e="",t=!1;for(let n=0;n<i.length;n++)i[n]==="["&&!t?(t=!0,e+="[",n++,n<i.length&&i[n]==="^"&&(e+="^",n++),n<i.length&&i[n]==="]"&&(e+="]",n++),n--):i[n]==="]"&&t?(t=!1,e+="]"):!t&&i[n]==="{"&&i[n+1]===","?(e+="{0,",n++):e+=i[n];return e}function ne(i){let e="";for(let t=0;t<i.length;t++){let n=i[t],s=n.charCodeAt(0);n==="\\"?e+="\\\\":n==="	"?e+="\\t":n===`
`?e+=`$
`:n==="\r"?e+="\\r":n==="\x07"?e+="\\a":n==="\b"?e+="\\b":n==="\f"?e+="\\f":n==="\v"?e+="\\v":s<32||s>=127?e+=`\\${s.toString(8).padStart(3,"0")}`:e+=n}return`${e}$`}var de=1e4;function se(i,e,t){return{patternSpace:"",holdSpace:"",lineNumber:0,totalLines:i,deleted:!1,printed:!1,quit:!1,quitSilent:!1,exitCode:void 0,errorMessage:void 0,appendBuffer:[],substitutionMade:!1,lineNumberOutput:[],nCommandOutput:[],restartCycle:!1,inDRestartedCycle:!1,currentFilename:e,pendingFileReads:[],pendingFileWrites:[],pendingExecute:void 0,rangeStates:t||new Map,linesConsumedInCycle:0}}function pe(i){return typeof i=="object"&&"first"in i&&"step"in i}function me(i){return typeof i=="object"&&"offset"in i}function N(i,e,t,n,s){if(i==="$")return e===t;if(typeof i=="number")return e===i;if(pe(i)){let{first:a,step:r}=i;return r===0?e===a:(e-a)%r===0&&e>=a}if(typeof i=="object"&&"pattern"in i)try{let a=i.pattern;a===""&&s?.lastPattern?a=s.lastPattern:a!==""&&s&&(s.lastPattern=a);let r=V(H(a));return A(r).test(n)}catch{return!1}return!1}function X(i){let e=t=>t===void 0?"undefined":t==="$"?"$":typeof t=="number"?String(t):"pattern"in t?`/${t.pattern}/`:"first"in t?`${t.first}~${t.step}`:"unknown";return`${e(i.start)},${e(i.end)}`}function ge(i,e,t,n,s,a){if(!i||!i.start&&!i.end)return!0;let r=i.start,l=i.end;if(r!==void 0&&l===void 0)return N(r,e,t,n,a);if(r!==void 0&&l!==void 0){let c=typeof r=="object"&&"pattern"in r,h=typeof l=="object"&&"pattern"in l,p=me(l);if(p&&s){let g=X(i),d=s.get(g);if(d||(d={active:!1},s.set(g,d)),d.active){let E=d.startLine||e;return e>=E+l.offset&&(d.active=!1,s.set(g,d)),!0}else return N(r,e,t,n,a)?(d.active=!0,d.startLine=e,s.set(g,d),l.offset===0&&(d.active=!1,s.set(g,d)),!0):!1}if(!c&&!h&&!p){let g=typeof r=="number"?r:r==="$"?t:1,d=typeof l=="number"?l:t;if(g<=d)return e>=g&&e<=d;if(s){let E=X(i),u=s.get(E);return u||(u={active:!1},s.set(E,u)),!u.completed&&e>=g?(u.completed=!0,s.set(E,u),!0):!1}return!1}if(s){let g=X(i),d=s.get(g);if(d||(d={active:!1},s.set(g,d)),d.active)return N(l,e,t,n,a)&&(d.active=!1,typeof r=="number"&&(d.completed=!0),s.set(g,d)),!0;{if(d.completed)return!1;let E=!1;return typeof r=="number"?E=e>=r:E=N(r,e,t,n,a),E?(d.active=!0,d.startLine=e,s.set(g,d),N(l,e,t,n,a)&&(d.active=!1,typeof r=="number"&&(d.completed=!0),s.set(g,d)),!0):!1}}return N(r,e,t,n,a)}return!0}function w(i,e,t,n,s,a){let r=ge(i,e,t,n,s,a);return i?.negated?!r:r}function be(i,e,t,n){let s="",a=0,r=!1;for(;a<=i.length;){e.lastIndex=a;let l=e.exec(i);if(!l){s+=i.slice(a);break}if(l.index!==a){s+=i.slice(a,l.index),a=l.index,r=!1;continue}let c=l[0],h=l.slice(1);if(r&&c.length===0){if(a<i.length)s+=i[a],a++;else break;r=!1;continue}if(s+=n(c,h),r=!1,c.length===0)if(a<i.length)s+=i[a],a++;else break;else a+=c.length,r=!0}return s}function G(i,e,t){let n="",s=0;for(;s<i.length;){if(i[s]==="\\"&&s+1<i.length){let a=i[s+1];if(a==="&"){n+="&",s+=2;continue}if(a==="n"){n+=`
`,s+=2;continue}if(a==="t"){n+="	",s+=2;continue}if(a==="r"){n+="\r",s+=2;continue}let r=parseInt(a,10);if(r===0){n+=e,s+=2;continue}if(r>=1&&r<=9){n+=t[r-1]||"",s+=2;continue}n+=a,s+=2;continue}if(i[s]==="&"){n+=e,s++;continue}n+=i[s],s++}return n}function ie(i,e,t){if(e>0&&i.length>e)throw new k(`sed: ${t} size limit exceeded (${e} bytes)`,"string_length")}function Ee(i,e,t){let{lineNumber:n,totalLines:s,patternSpace:a}=e;if(i.type==="label"){e.coverage?.hit(`sed:cmd:${i.type}`);return}if(w(i.address,n,s,a,e.rangeStates,e))switch(e.coverage?.hit(`sed:cmd:${i.type}`),i.type){case"substitute":{let r=i,l="";r.global&&(l+="g"),r.ignoreCase&&(l+="i");let c=r.pattern;c===""&&e.lastPattern?c=e.lastPattern:c!==""&&(e.lastPattern=c);let h=V(r.extendedRegex?c:H(c));try{let p=A(h,l),x=p.test(e.patternSpace);if(p.lastIndex=0,x){if(e.substitutionMade=!0,r.nthOccurrence&&r.nthOccurrence>0&&!r.global){let g=0,d=r.nthOccurrence,E=A(h,`g${r.ignoreCase?"i":""}`);e.patternSpace=E.replace(e.patternSpace,(u,...f)=>{if(g++,g===d){let b=f.slice(0,-2);return G(r.replacement,u,b)}return u})}else if(r.global){let g=A(h,`g${r.ignoreCase?"i":""}`);e.patternSpace=be(e.patternSpace,g,r.replacement,(d,E)=>G(r.replacement,d,E))}else e.patternSpace=p.replace(e.patternSpace,(g,...d)=>{let E=d.slice(0,-2);return G(r.replacement,g,E)});r.printOnMatch&&e.lineNumberOutput.push(e.patternSpace)}}catch{}break}case"print":e.lineNumberOutput.push(e.patternSpace);break;case"printFirstLine":{let r=e.patternSpace.indexOf(`
`);r!==-1?e.lineNumberOutput.push(e.patternSpace.slice(0,r)):e.lineNumberOutput.push(e.patternSpace);break}case"delete":e.deleted=!0;break;case"deleteFirstLine":{let r=e.patternSpace.indexOf(`
`);r!==-1?(e.patternSpace=e.patternSpace.slice(r+1),e.restartCycle=!0,e.inDRestartedCycle=!0):e.deleted=!0;break}case"zap":e.patternSpace="";break;case"append":e.appendBuffer.push(i.text);break;case"insert":e.appendBuffer.unshift(`__INSERT__${i.text}`);break;case"change":e.deleted=!0,e.changedText=i.text;break;case"hold":e.holdSpace=e.patternSpace;break;case"holdAppend":e.holdSpace?e.holdSpace+=`
${e.patternSpace}`:e.holdSpace=e.patternSpace,ie(e.holdSpace,t?.maxStringLength??0,"hold space");break;case"get":e.patternSpace=e.holdSpace;break;case"getAppend":e.patternSpace+=`
${e.holdSpace}`,ie(e.patternSpace,t?.maxStringLength??0,"pattern space");break;case"exchange":{let r=e.patternSpace;e.patternSpace=e.holdSpace,e.holdSpace=r;break}case"next":e.printed=!0;break;case"quit":e.quit=!0,i.exitCode!==void 0&&(e.exitCode=i.exitCode);break;case"quitSilent":e.quit=!0,e.quitSilent=!0,i.exitCode!==void 0&&(e.exitCode=i.exitCode);break;case"list":{let r=ne(e.patternSpace);e.lineNumberOutput.push(r);break}case"printFilename":e.currentFilename&&e.lineNumberOutput.push(e.currentFilename);break;case"version":{let r=[4,8,0];if(i.minVersion){let l=i.minVersion.split("."),c=[],h=!1;for(let p of l){let x=parseInt(p,10);if(Number.isNaN(x)||x<0){e.quit=!0,e.exitCode=1,e.errorMessage=`sed: invalid version string: ${i.minVersion}`,h=!0;break}c.push(x)}if(!h){for(;c.length<3;)c.push(0);for(let p=0;p<3;p++){if(c[p]>r[p]){e.quit=!0,e.exitCode=1,e.errorMessage=`sed: this is not GNU sed version ${i.minVersion}`;break}if(c[p]<r[p])break}}}break}case"readFile":e.pendingFileReads.push({filename:i.filename,wholeFile:!0});break;case"readFileLine":e.pendingFileReads.push({filename:i.filename,wholeFile:!1});break;case"writeFile":e.pendingFileWrites.push({filename:i.filename,content:`${e.patternSpace}
`});break;case"writeFirstLine":{let r=e.patternSpace.indexOf(`
`),l=r!==-1?e.patternSpace.slice(0,r):e.patternSpace;e.pendingFileWrites.push({filename:i.filename,content:`${l}
`});break}case"execute":i.command?e.pendingExecute={command:i.command,replacePattern:!1}:e.pendingExecute={command:e.patternSpace,replacePattern:!0};break;case"transliterate":e.patternSpace=ve(e.patternSpace,i);break;case"lineNumber":e.lineNumberOutput.push(String(e.lineNumber));break;case"branch":break;case"branchOnSubst":break;case"branchOnNoSubst":break;case"group":break}}function ve(i,e){let t="";for(let n of i){let s=e.source.indexOf(n);s!==-1?t+=e.dest[s]:t+=n}return t}function j(i,e,t,n){let s=new Map;for(let c=0;c<i.length;c++){let h=i[c];h.type==="label"&&s.set(h.name,c)}let a=n?.maxIterations??de,r=0,l=0;for(;l<i.length;){if(r++,r>a)throw new k(`sed: command execution exceeded maximum iterations (${a})`,"iterations");if(e.deleted||e.quit||e.quitSilent||e.restartCycle)break;let c=i[l];if(c.type==="next"){if(w(c.address,e.lineNumber,e.totalLines,e.patternSpace,e.rangeStates,e))if(e.coverage?.hit("sed:cmd:next"),e.nCommandOutput.push(e.patternSpace),t&&t.currentLineIndex+e.linesConsumedInCycle+1<t.lines.length){e.linesConsumedInCycle++;let h=t.lines[t.currentLineIndex+e.linesConsumedInCycle];e.patternSpace=h,e.lineNumber=t.currentLineIndex+e.linesConsumedInCycle+1,e.substitutionMade=!1}else{e.quit=!0,e.deleted=!0;break}l++;continue}if(c.type==="nextAppend"){if(w(c.address,e.lineNumber,e.totalLines,e.patternSpace,e.rangeStates,e))if(e.coverage?.hit("sed:cmd:nextAppend"),t&&t.currentLineIndex+e.linesConsumedInCycle+1<t.lines.length){e.linesConsumedInCycle++;let h=t.lines[t.currentLineIndex+e.linesConsumedInCycle];e.patternSpace+=`
${h}`,e.lineNumber=t.currentLineIndex+e.linesConsumedInCycle+1}else{e.quit=!0;break}l++;continue}if(c.type==="branch"){let h=c;if(w(h.address,e.lineNumber,e.totalLines,e.patternSpace,e.rangeStates,e)){if(e.coverage?.hit("sed:cmd:branch"),h.label){let p=s.get(h.label);if(p!==void 0){l=p;continue}e.branchRequest=h.label;break}break}l++;continue}if(c.type==="branchOnSubst"){let h=c;if(w(h.address,e.lineNumber,e.totalLines,e.patternSpace,e.rangeStates,e)&&(e.coverage?.hit("sed:cmd:branchOnSubst"),e.substitutionMade)){if(e.substitutionMade=!1,h.label){let p=s.get(h.label);if(p!==void 0){l=p;continue}e.branchRequest=h.label;break}break}l++;continue}if(c.type==="branchOnNoSubst"){let h=c;if(w(h.address,e.lineNumber,e.totalLines,e.patternSpace,e.rangeStates,e)&&(e.coverage?.hit("sed:cmd:branchOnNoSubst"),!e.substitutionMade)){if(h.label){let p=s.get(h.label);if(p!==void 0){l=p;continue}e.branchRequest=h.label;break}break}l++;continue}if(c.type==="group"){let h=c;if(w(h.address,e.lineNumber,e.totalLines,e.patternSpace,e.rangeStates,e)&&(e.coverage?.hit("sed:cmd:group"),j(h.commands,e,t,n),e.branchRequest)){let p=s.get(e.branchRequest);if(p!==void 0){e.branchRequest=void 0,l=p;continue}break}l++;continue}Ee(c,e,n),l++}return e.linesConsumedInCycle}var o;(function(i){i.NUMBER="NUMBER",i.DOLLAR="DOLLAR",i.PATTERN="PATTERN",i.STEP="STEP",i.RELATIVE_OFFSET="RELATIVE_OFFSET",i.LBRACE="LBRACE",i.RBRACE="RBRACE",i.SEMICOLON="SEMICOLON",i.NEWLINE="NEWLINE",i.COMMA="COMMA",i.NEGATION="NEGATION",i.COMMAND="COMMAND",i.SUBSTITUTE="SUBSTITUTE",i.TRANSLITERATE="TRANSLITERATE",i.LABEL_DEF="LABEL_DEF",i.BRANCH="BRANCH",i.BRANCH_ON_SUBST="BRANCH_ON_SUBST",i.BRANCH_ON_NO_SUBST="BRANCH_ON_NO_SUBST",i.TEXT_CMD="TEXT_CMD",i.FILE_READ="FILE_READ",i.FILE_READ_LINE="FILE_READ_LINE",i.FILE_WRITE="FILE_WRITE",i.FILE_WRITE_LINE="FILE_WRITE_LINE",i.EXECUTE="EXECUTE",i.VERSION="VERSION",i.EOF="EOF",i.ERROR="ERROR"})(o||(o={}));var _=class{input;pos=0;line=1;column=1;constructor(e){this.input=e}tokenize(){let e=[];for(;this.pos<this.input.length;){let t=this.nextToken();t&&e.push(t)}return e.push(this.makeToken(o.EOF,"")),e}makeToken(e,t,n){return{type:e,value:t,line:this.line,column:this.column,...n}}peek(e=0){return this.input[this.pos+e]||""}advance(){let e=this.input[this.pos++]||"";return e===`
`?(this.line++,this.column=1):this.column++,e}readEscapedString(e){let t="";for(;this.pos<this.input.length&&this.peek()!==e;)if(this.peek()==="\\"){this.advance();let n=this.advance();n==="n"?t+=`
`:n==="t"?t+="	":t+=n}else{if(this.peek()===`
`)return null;t+=this.advance()}return t}skipWhitespace(){for(;this.pos<this.input.length;){let e=this.peek();if(e===" "||e==="	"||e==="\r")this.advance();else if(e==="#")for(;this.pos<this.input.length&&this.peek()!==`
`;)this.advance();else break}}nextToken(){if(this.skipWhitespace(),this.pos>=this.input.length)return null;let e=this.line,t=this.column,n=this.peek();return n===`
`?(this.advance(),{type:o.NEWLINE,value:`
`,line:e,column:t}):n===";"?(this.advance(),{type:o.SEMICOLON,value:";",line:e,column:t}):n==="{"?(this.advance(),{type:o.LBRACE,value:"{",line:e,column:t}):n==="}"?(this.advance(),{type:o.RBRACE,value:"}",line:e,column:t}):n===","?(this.advance(),{type:o.COMMA,value:",",line:e,column:t}):n==="!"?(this.advance(),{type:o.NEGATION,value:"!",line:e,column:t}):n==="$"?(this.advance(),{type:o.DOLLAR,value:"$",line:e,column:t}):this.isDigit(n)?this.readNumber():n==="+"&&this.isDigit(this.input[this.pos+1]||"")?this.readRelativeOffset():n==="/"?this.readPattern():n===":"?this.readLabelDef():this.readCommand()}readNumber(){let e=this.line,t=this.column,n="";for(;this.isDigit(this.peek());)n+=this.advance();if(this.peek()==="~"){this.advance();let s="";for(;this.isDigit(this.peek());)s+=this.advance();let a=parseInt(n,10),r=parseInt(s,10)||0;return{type:o.STEP,value:`${a}~${r}`,first:a,step:r,line:e,column:t}}return{type:o.NUMBER,value:parseInt(n,10),line:e,column:t}}readRelativeOffset(){let e=this.line,t=this.column;this.advance();let n="";for(;this.isDigit(this.peek());)n+=this.advance();let s=parseInt(n,10)||0;return{type:o.RELATIVE_OFFSET,value:`+${s}`,offset:s,line:e,column:t}}readPattern(){let e=this.line,t=this.column;this.advance();let n="",s=!1;for(;this.pos<this.input.length;){let a=this.peek();if(a==="/"&&!s)break;if(a==="\\")n+=this.advance(),this.pos<this.input.length&&this.peek()!==`
`&&(n+=this.advance());else{if(a===`
`)break;a==="["&&!s?(s=!0,n+=this.advance(),this.peek()==="^"&&(n+=this.advance()),this.peek()==="]"&&(n+=this.advance())):a==="]"&&s?(s=!1,n+=this.advance()):n+=this.advance()}}return this.peek()==="/"&&this.advance(),{type:o.PATTERN,value:n,pattern:n,line:e,column:t}}readLabelDef(){let e=this.line,t=this.column;for(this.advance();this.peek()===" "||this.peek()==="	";)this.advance();let n="";for(;this.pos<this.input.length;){let s=this.peek();if(s===" "||s==="	"||s===`
`||s===";"||s==="}"||s==="{")break;n+=this.advance()}return{type:o.LABEL_DEF,value:n,label:n,line:e,column:t}}readCommand(){let e=this.line,t=this.column,n=this.advance();switch(n){case"s":return this.readSubstitute(e,t);case"y":return this.readTransliterate(e,t);case"a":case"i":case"c":return this.readTextCommand(n,e,t);case"b":return this.readBranch(o.BRANCH,"b",e,t);case"t":return this.readBranch(o.BRANCH_ON_SUBST,"t",e,t);case"T":return this.readBranch(o.BRANCH_ON_NO_SUBST,"T",e,t);case"r":return this.readFileCommand(o.FILE_READ,"r",e,t);case"R":return this.readFileCommand(o.FILE_READ_LINE,"R",e,t);case"w":return this.readFileCommand(o.FILE_WRITE,"w",e,t);case"W":return this.readFileCommand(o.FILE_WRITE_LINE,"W",e,t);case"e":return this.readExecute(e,t);case"p":case"P":case"d":case"D":case"h":case"H":case"g":case"G":case"x":case"n":case"N":case"q":case"Q":case"z":case"=":case"l":case"F":return{type:o.COMMAND,value:n,line:e,column:t};case"v":return this.readVersion(e,t);default:return{type:o.ERROR,value:n,line:e,column:t}}}readSubstitute(e,t){let n=this.advance();if(!n||n===`
`)return{type:o.ERROR,value:"s",line:e,column:t};let s="",a=!1;for(;this.pos<this.input.length;){let c=this.peek();if(c===n&&!a)break;if(c==="\\")this.advance(),this.pos<this.input.length&&this.peek()!==`
`?this.peek()===n&&!a?s+=this.advance():(s+="\\",s+=this.advance()):s+="\\";else{if(c===`
`)break;c==="["&&!a?(a=!0,s+=this.advance(),this.peek()==="^"&&(s+=this.advance()),this.peek()==="]"&&(s+=this.advance())):c==="]"&&a?(a=!1,s+=this.advance()):s+=this.advance()}}if(this.peek()!==n)return{type:o.ERROR,value:"unterminated substitution pattern",line:e,column:t};this.advance();let r="";for(;this.pos<this.input.length&&this.peek()!==n;)if(this.peek()==="\\")if(this.advance(),this.pos<this.input.length){let c=this.peek();c==="\\"?(this.advance(),this.pos<this.input.length&&this.peek()===`
`?(r+=`
`,this.advance()):r+="\\"):c===`
`?(r+=`
`,this.advance()):r+=`\\${this.advance()}`}else r+="\\";else{if(this.peek()===`
`)break;r+=this.advance()}this.peek()===n&&this.advance();let l="";for(;this.pos<this.input.length;){let c=this.peek();if(c==="g"||c==="i"||c==="p"||c==="I"||this.isDigit(c))l+=this.advance();else break}return{type:o.SUBSTITUTE,value:`s${n}${s}${n}${r}${n}${l}`,pattern:s,replacement:r,flags:l,line:e,column:t}}readTransliterate(e,t){let n=this.advance();if(!n||n===`
`)return{type:o.ERROR,value:"y",line:e,column:t};let s=this.readEscapedString(n);if(s===null||this.peek()!==n)return{type:o.ERROR,value:"unterminated transliteration source",line:e,column:t};this.advance();let a=this.readEscapedString(n);if(a===null||this.peek()!==n)return{type:o.ERROR,value:"unterminated transliteration dest",line:e,column:t};this.advance();let r=this.peek();for(;r===" "||r==="	";)this.advance(),r=this.peek();return r!==""&&r!==";"&&r!==`
`&&r!=="}"?{type:o.ERROR,value:"extra text at the end of a transform command",line:e,column:t}:{type:o.TRANSLITERATE,value:`y${n}${s}${n}${a}${n}`,source:s,dest:a,line:e,column:t}}readTextCommand(e,t,n){let s=!1;this.peek()==="\\"&&this.pos+1<this.input.length&&(this.input[this.pos+1]===`
`||this.input[this.pos+1]===" "||this.input[this.pos+1]==="	")&&(s=!0,this.advance()),(this.peek()===" "||this.peek()==="	")&&this.advance(),this.peek()==="\\"&&this.pos+1<this.input.length&&(this.input[this.pos+1]===" "||this.input[this.pos+1]==="	")&&this.advance(),s&&this.peek()===`
`&&this.advance();let a="";for(;this.pos<this.input.length;){let r=this.peek();if(r===`
`){if(a.endsWith("\\")){a=`${a.slice(0,-1)}
`,this.advance();continue}break}if(r==="\\"&&this.pos+1<this.input.length){let l=this.input[this.pos+1];if(l==="n"){a+=`
`,this.advance(),this.advance();continue}if(l==="t"){a+="	",this.advance(),this.advance();continue}if(l==="r"){a+="\r",this.advance(),this.advance();continue}}a+=this.advance()}return{type:o.TEXT_CMD,value:e,text:a,line:t,column:n}}readBranch(e,t,n,s){for(;this.peek()===" "||this.peek()==="	";)this.advance();let a="";for(;this.pos<this.input.length;){let r=this.peek();if(r===" "||r==="	"||r===`
`||r===";"||r==="}"||r==="{")break;a+=this.advance()}return{type:e,value:t,label:a||void 0,line:n,column:s}}readVersion(e,t){for(;this.peek()===" "||this.peek()==="	";)this.advance();let n="";for(;this.pos<this.input.length;){let s=this.peek();if(s===" "||s==="	"||s===`
`||s===";"||s==="}"||s==="{")break;n+=this.advance()}return{type:o.VERSION,value:"v",label:n||void 0,line:e,column:t}}readFileCommand(e,t,n,s){for(;this.peek()===" "||this.peek()==="	";)this.advance();let a="";for(;this.pos<this.input.length;){let r=this.peek();if(r===`
`||r===";")break;a+=this.advance()}return{type:e,value:t,filename:a.trim(),line:n,column:s}}readExecute(e,t){for(;this.peek()===" "||this.peek()==="	";)this.advance();let n="";for(;this.pos<this.input.length;){let s=this.peek();if(s===`
`||s===";")break;n+=this.advance()}return{type:o.EXECUTE,value:"e",command:n.trim()||void 0,line:e,column:t}}isDigit(e){return e>="0"&&e<="9"}};var Z=class{scripts;tokens=[];pos=0;extendedRegex=!1;constructor(e,t=!1){this.scripts=e,this.extendedRegex=t}parse(){let e=[];for(let t of this.scripts){let n=new _(t);for(this.tokens=n.tokenize(),this.pos=0;!this.isAtEnd();){if(this.check(o.NEWLINE)||this.check(o.SEMICOLON)){this.advance();continue}let s=this.pos,a=this.parseCommand();if(a.error)return{commands:[],error:a.error};if(a.command&&e.push(a.command),this.pos===s&&!this.isAtEnd())return{commands:[],error:`unknown command: '${this.peek()?.value??this.peek()?.type}'`}}}return{commands:e}}parseCommand(){let e=this.parseAddressRange();if(e?.error)return{command:null,error:e.error};let t=e?.address;for(this.check(o.NEGATION)&&(this.advance(),t&&(t.negated=!0));this.check(o.NEWLINE)||this.check(o.SEMICOLON);)this.advance();if(this.isAtEnd())return t&&(t.start!==void 0||t.end!==void 0)?{command:null,error:"command expected"}:{command:null};let n=this.peek();switch(n.type){case o.COMMAND:return this.parseSimpleCommand(n,t);case o.SUBSTITUTE:return this.parseSubstituteFromToken(n,t);case o.TRANSLITERATE:return this.parseTransliterateFromToken(n,t);case o.LABEL_DEF:return this.advance(),{command:{type:"label",name:n.label||""}};case o.BRANCH:return this.advance(),{command:{type:"branch",address:t,label:n.label}};case o.BRANCH_ON_SUBST:return this.advance(),{command:{type:"branchOnSubst",address:t,label:n.label}};case o.BRANCH_ON_NO_SUBST:return this.advance(),{command:{type:"branchOnNoSubst",address:t,label:n.label}};case o.TEXT_CMD:return this.advance(),this.parseTextCommand(n,t);case o.FILE_READ:return this.advance(),{command:{type:"readFile",address:t,filename:n.filename||""}};case o.FILE_READ_LINE:return this.advance(),{command:{type:"readFileLine",address:t,filename:n.filename||""}};case o.FILE_WRITE:return this.advance(),{command:{type:"writeFile",address:t,filename:n.filename||""}};case o.FILE_WRITE_LINE:return this.advance(),{command:{type:"writeFirstLine",address:t,filename:n.filename||""}};case o.EXECUTE:return this.advance(),{command:{type:"execute",address:t,command:n.command}};case o.VERSION:return this.advance(),{command:{type:"version",address:t,minVersion:n.label}};case o.LBRACE:return this.parseGroup(t);case o.RBRACE:return{command:null};case o.ERROR:return{command:null,error:`invalid command: ${n.value}`};default:return t&&(t.start!==void 0||t.end!==void 0)?{command:null,error:"command expected"}:{command:null}}}parseSimpleCommand(e,t){this.advance();let n=e.value;switch(n){case"p":return{command:{type:"print",address:t}};case"P":return{command:{type:"printFirstLine",address:t}};case"d":return{command:{type:"delete",address:t}};case"D":return{command:{type:"deleteFirstLine",address:t}};case"h":return{command:{type:"hold",address:t}};case"H":return{command:{type:"holdAppend",address:t}};case"g":return{command:{type:"get",address:t}};case"G":return{command:{type:"getAppend",address:t}};case"x":return{command:{type:"exchange",address:t}};case"n":return{command:{type:"next",address:t}};case"N":return{command:{type:"nextAppend",address:t}};case"q":return{command:{type:"quit",address:t}};case"Q":return{command:{type:"quitSilent",address:t}};case"z":return{command:{type:"zap",address:t}};case"=":return{command:{type:"lineNumber",address:t}};case"l":return{command:{type:"list",address:t}};case"F":return{command:{type:"printFilename",address:t}};default:return{command:null,error:`unknown command: ${n}`}}}parseSubstituteFromToken(e,t){this.advance();let n=e.flags||"",s,a=n.match(/(\d+)/);return a&&(s=parseInt(a[1],10)),{command:{type:"substitute",address:t,pattern:e.pattern||"",replacement:e.replacement||"",global:n.includes("g"),ignoreCase:n.includes("i")||n.includes("I"),printOnMatch:n.includes("p"),nthOccurrence:s,extendedRegex:this.extendedRegex}}}parseTransliterateFromToken(e,t){this.advance();let n=e.source||"",s=e.dest||"";return n.length!==s.length?{command:null,error:"transliteration sets must have same length"}:{command:{type:"transliterate",address:t,source:n,dest:s}}}parseTextCommand(e,t){let n=e.value,s=e.text||"";switch(n){case"a":return{command:{type:"append",address:t,text:s}};case"i":return{command:{type:"insert",address:t,text:s}};case"c":return{command:{type:"change",address:t,text:s}};default:return{command:null,error:`unknown text command: ${n}`}}}parseGroup(e){this.advance();let t=[];for(;!this.isAtEnd()&&!this.check(o.RBRACE);){if(this.check(o.NEWLINE)||this.check(o.SEMICOLON)){this.advance();continue}let n=this.pos,s=this.parseCommand();if(s.error)return{command:null,error:s.error};if(s.command&&t.push(s.command),this.pos===n&&!this.isAtEnd())return{command:null,error:`unknown command: '${this.peek()?.value??this.peek()?.type}'`}}return this.check(o.RBRACE)?(this.advance(),{command:{type:"group",address:e,commands:t}}):{command:null,error:"unmatched brace in grouped commands"}}parseAddressRange(){if(this.check(o.COMMA))return{error:"expected context address"};let e=this.parseAddress();if(e===void 0)return;let t;if(this.check(o.RELATIVE_OFFSET))t={offset:this.advance().offset||0};else if(this.check(o.COMMA)&&(this.advance(),t=this.parseAddress(),t===void 0))return{error:"expected context address"};return{address:{start:e,end:t}}}parseAddress(){let e=this.peek();switch(e.type){case o.NUMBER:return this.advance(),e.value;case o.DOLLAR:return this.advance(),"$";case o.PATTERN:return this.advance(),{pattern:e.pattern||e.value};case o.STEP:return this.advance(),{first:e.first||0,step:e.step||0};case o.RELATIVE_OFFSET:return this.advance(),{offset:e.offset||0};default:return}}peek(){return this.tokens[this.pos]||{type:o.EOF,value:"",line:0,column:0}}advance(){return this.isAtEnd()||this.pos++,this.tokens[this.pos-1]}check(e){return this.peek().type===e}isAtEnd(){return this.peek().type===o.EOF}};function re(i,e=!1){let t=!1,n=!1,s=[];for(let c=0;c<i.length;c++){let h=i[c];if(s.length===0&&c===0){let p=h.match(/^#([nr]+)\s*(?:\n|$)/i);if(p){let x=p[1].toLowerCase();x.includes("n")&&(t=!0),x.includes("r")&&(n=!0),h=h.slice(p[0].length)}}if(s.length>0&&s[s.length-1].endsWith("\\")){let p=s[s.length-1];s[s.length-1]=`${p}
${h}`}else s.push(h)}let a=s.join(`
`),l=new Z([a],e||n).parse();if(!l.error&&l.commands.length>0){let c=Ce(l.commands);if(c)return{commands:[],error:c,silentMode:t,extendedRegexMode:n}}return{...l,silentMode:t,extendedRegexMode:n}}function Ce(i){let e=new Set;ae(i,e);let t=ce(i,e);if(t)return`undefined label '${t}'`}function ae(i,e){for(let t of i)t.type==="label"?e.add(t.name):t.type==="group"&&ae(t.commands,e)}function ce(i,e){for(let t of i){if((t.type==="branch"||t.type==="branchOnSubst"||t.type==="branchOnNoSubst")&&t.label&&!e.has(t.label))return t.label;if(t.type==="group"){let n=ce(t.commands,e);if(n)return n}}}var xe={name:"sed",summary:"stream editor for filtering and transforming text",usage:"sed [OPTION]... {script} [input-file]...",options:["-n, --quiet, --silent  suppress automatic printing of pattern space","-e script              add the script to commands to be executed","-f script-file         read script from file","-i, --in-place         edit files in place","-E, -r, --regexp-extended  use extended regular expressions","    --help             display this help and exit"],description:`Commands:
  s/regexp/replacement/[flags]  substitute
  d                             delete pattern space
  p                             print pattern space
  a\\ text                       append text after line
  i\\ text                       insert text before line
  c\\ text                       change (replace) line with text
  h                             copy pattern space to hold space
  H                             append pattern space to hold space
  g                             copy hold space to pattern space
  G                             append hold space to pattern space
  x                             exchange pattern and hold spaces
  n                             read next line into pattern space
  N                             append next line to pattern space
  y/source/dest/                transliterate characters
  =                             print line number
  l                             list pattern space (escape special chars)
  b [label]                     branch to label
  t [label]                     branch on substitution
  T [label]                     branch if no substitution
  :label                        define label
  q                             quit
  Q                             quit without printing

Addresses:
  N                             line number
  $                             last line
  /regexp/                      lines matching regexp
  N,M                           range from line N to M
  first~step                    every step-th line starting at first`};async function K(i,e,t,n={}){let{limits:s,filename:a,fs:r,cwd:l,coverage:c,requireDefenseContext:h}=n;W(h,"sed","processing entry");let p=(R,m)=>U(h,"sed",R,m),x=i.endsWith(`
`),g=i.split(`
`);g.length>0&&g[g.length-1]===""&&g.pop();let d=g.length,E="",u,f=!1,b=s?.maxStringLength??0,v=R=>{if(E+=R,b>0&&E.length>b)throw new k(`sed: output size limit exceeded (${b} bytes)`,"string_length")},O="",Q,oe=new Map,T=new Map,B=new Map,D=new Map,le=s?{maxIterations:s.maxSedIterations,maxStringLength:b}:void 0;for(let R=0;R<g.length;R++){let m={...se(d,a,oe),patternSpace:g[R],holdSpace:O,lastPattern:Q,lineNumber:R+1,totalLines:d,substitutionMade:!1,coverage:c},F={lines:g,currentLineIndex:R},J=0,ue=1e4;m.linesConsumedInCycle=0;do{if(J++,J>ue)break;if(m.restartCycle=!1,m.pendingFileReads=[],m.pendingFileWrites=[],j(e,m,F,le),r&&l){for(let C of m.pendingFileReads){let S=r.resolvePath(l,C.filename);try{if(C.wholeFile){let y=await p("read command file",()=>r.readFile(S));m.appendBuffer.push(y.replace(/\n$/,""))}else{if(!T.has(S)){let he=await p("read command file line cache",()=>r.readFile(S));T.set(S,he.split(`
`)),B.set(S,0)}let y=T.get(S),M=B.get(S);y&&M!==void 0&&M<y.length&&(m.appendBuffer.push(y[M]),B.set(S,M+1))}}catch(y){if(y instanceof I)throw y}}for(let C of m.pendingFileWrites){let S=r.resolvePath(l,C.filename),y=D.get(S)||"";D.set(S,y+C.content)}}}while(m.restartCycle&&!m.deleted&&!m.quit&&!m.quitSilent);if(R+=m.linesConsumedInCycle,O=m.holdSpace,Q=m.lastPattern,!t)for(let C of m.nCommandOutput)v(`${C}
`);let fe=m.lineNumberOutput.length>0;for(let C of m.lineNumberOutput)v(`${C}
`);let Y=[],q=[];for(let C of m.appendBuffer)C.startsWith("__INSERT__")?Y.push(C.slice(10)):q.push(C);for(let C of Y)v(`${C}
`);let $=!1;!m.deleted&&!m.quitSilent?t?m.printed&&(v(`${m.patternSpace}
`),$=!0):(v(`${m.patternSpace}
`),$=!0):m.changedText!==void 0&&(v(`${m.changedText}
`),$=!0);for(let C of q)v(`${C}
`);if(f=(fe||$)&&q.length===0,m.quit||m.quitSilent){if(m.exitCode!==void 0&&(u=m.exitCode),m.errorMessage)return{output:"",exitCode:u||1,errorMessage:m.errorMessage};break}}if(r&&l)for(let[R,m]of D)try{await p("flush pending file writes",()=>r.writeFile(R,m))}catch(F){if(F instanceof I)throw F}return!x&&f&&E.endsWith(`
`)&&(E=E.slice(0,-1)),{output:E,exitCode:u}}var De={name:"sed",async execute(i,e){W(e.requireDefenseContext,"sed","execution entry");let t=(u,f)=>U(e.requireDefenseContext,"sed",u,f);if(te(i))return ee(xe);let n=[],s=[],a=!1,r=!1,l=!1,c=[];for(let u=0;u<i.length;u++){let f=i[u];if(f==="-n"||f==="--quiet"||f==="--silent")a=!0;else if(f==="-i"||f==="--in-place")r=!0;else if(f.startsWith("-i"))r=!0;else if(f==="-E"||f==="-r"||f==="--regexp-extended")l=!0;else if(f==="-e")u+1<i.length&&n.push(i[++u]);else if(f==="-f")u+1<i.length&&s.push(i[++u]);else{if(f.startsWith("--"))return P("sed",f);if(f==="-")c.push(f);else if(f.startsWith("-")&&f.length>1){for(let b of f.slice(1))if(b!=="n"&&b!=="e"&&b!=="f"&&b!=="i"&&b!=="E"&&b!=="r")return P("sed",`-${b}`);f.includes("n")&&(a=!0),f.includes("i")&&(r=!0),(f.includes("E")||f.includes("r"))&&(l=!0),f.includes("e")&&!f.includes("n")&&!f.includes("i")&&u+1<i.length&&n.push(i[++u]),f.includes("f")&&!f.includes("e")&&u+1<i.length&&s.push(i[++u])}else!f.startsWith("-")&&n.length===0&&s.length===0?n.push(f):f.startsWith("-")||c.push(f)}}for(let u of s){let f=e.fs.resolvePath(e.cwd,u);try{let b=await t("script file read",()=>e.fs.readFile(f));for(let v of b.split(`
`)){let O=v.trim();O&&!O.startsWith("#")&&n.push(O)}}catch(b){if(b instanceof I)throw b;return{stdout:"",stderr:`sed: couldn't open file ${u}: No such file or directory
`,exitCode:1}}}if(n.length===0)return{stdout:"",stderr:`sed: no script specified
`,exitCode:1};let{commands:h,error:p,silentMode:x}=re(n,l);if(p)return{stdout:"",stderr:`sed: ${p}
`,exitCode:1};let g=!!(a||x);if(r){if(c.length===0)return{stdout:"",stderr:`sed: -i requires at least one file argument
`,exitCode:1};for(let u of c){if(u==="-")continue;let f=e.fs.resolvePath(e.cwd,u);try{let b=await t("in-place input read",()=>e.fs.readFile(f)),v=await t("in-place processing",()=>K(b,h,g,{limits:e.limits,filename:u,fs:e.fs,cwd:e.cwd,coverage:e.coverage,requireDefenseContext:e.requireDefenseContext}));if(v.errorMessage)return{stdout:"",stderr:`${v.errorMessage}
`,exitCode:v.exitCode??1};await t("in-place output write",()=>e.fs.writeFile(f,v.output))}catch(b){if(b instanceof I)throw b;return b instanceof k?{stdout:"",stderr:`sed: ${L(b.message)}
`,exitCode:k.EXIT_CODE}:{stdout:"",stderr:`sed: ${u}: No such file or directory
`,exitCode:1}}}return{stdout:"",stderr:"",exitCode:0}}let d="";if(c.length===0){d=e.stdin;try{let u=await t("stdin processing",()=>K(d,h,g,{limits:e.limits,fs:e.fs,cwd:e.cwd,coverage:e.coverage,requireDefenseContext:e.requireDefenseContext}));return{stdout:u.output,stderr:u.errorMessage?`${u.errorMessage}
`:"",exitCode:u.exitCode??0}}catch(u){if(u instanceof I)throw u;if(u instanceof k)return{stdout:"",stderr:`sed: ${L(u.message)}
`,exitCode:k.EXIT_CODE};throw u}}let E=!1;for(let u of c){let f;if(u==="-")E?f="":(f=e.stdin,E=!0);else{let b=e.fs.resolvePath(e.cwd,u);try{f=await t("input file read",()=>e.fs.readFile(b))}catch(v){if(v instanceof I)throw v;return v instanceof k?{stdout:"",stderr:`sed: ${L(v.message)}
`,exitCode:k.EXIT_CODE}:{stdout:"",stderr:`sed: ${u}: No such file or directory
`,exitCode:1}}}d.length>0&&f.length>0&&!d.endsWith(`
`)&&(d+=`
`),d+=f}try{let u=await t("final processing",()=>K(d,h,g,{limits:e.limits,filename:c.length===1?c[0]:void 0,fs:e.fs,cwd:e.cwd,coverage:e.coverage,requireDefenseContext:e.requireDefenseContext}));return{stdout:u.output,stderr:u.errorMessage?`${u.errorMessage}
`:"",exitCode:u.exitCode??0}}catch(u){if(u instanceof I)throw u;if(u instanceof k)return{stdout:"",stderr:`sed: ${L(u.message)}
`,exitCode:k.EXIT_CODE};throw u}}},qe={name:"sed",flags:[{flag:"-n",type:"boolean"},{flag:"-i",type:"boolean"},{flag:"-E",type:"boolean"},{flag:"-r",type:"boolean"},{flag:"-e",type:"value",valueHint:"string"}],stdinType:"text",needsArgs:!0};export{De as a,qe as b};
