@innovatorved/code-lab 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +1 -1
- package/CHANGELOG.md +23 -0
- package/README.md +38 -1
- package/dist/code-lab-sql.css +87 -64
- package/dist/code-lab-sql.esm.js +109 -86
- package/dist/code-lab-sql.umd.js +110 -87
- package/dist/code-lab.css +1 -1
- package/dist/code-lab.d.ts +19 -1
- package/dist/code-lab.esm.js +1261 -900
- package/dist/code-lab.js +1260 -899
- package/dist/code-lab.umd.js +1260 -899
- package/dist/extensions/cpp.esm.js +9 -0
- package/dist/extensions/cpp.js +9 -0
- package/dist/extensions/guided-lab.esm.js +9 -0
- package/dist/extensions/guided-lab.js +9 -0
- package/dist/extensions/python.esm.js +9 -0
- package/dist/extensions/python.js +9 -0
- package/dist/index.d.ts +1 -1
- package/dist/packages/sql/src/styles.d.ts +1 -1
- package/dist/packages/ui/src/settings-dialog.d.ts +2 -0
- package/dist/preview-sw.js +1 -1
- package/dist/runtime.esm.js +70 -70
- package/dist/runtime.js +70 -70
- package/dist/schemas.d.ts +13 -1
- package/dist/schemas.esm.js +9 -0
- package/dist/schemas.js +9 -0
- package/dist/shell.esm.js +250 -244
- package/dist/shell.js +250 -244
- package/dist/terminal.esm.js +1 -1
- package/dist/terminal.js +1 -1
- package/dist/workbench/index.d.ts +1 -1
- package/dist/workbench/intellisense.d.ts +1 -1
- package/dist/workbench/styles.d.ts +1 -1
- package/package.json +1 -1
- package/packages/commands/package.json +1 -1
- package/packages/core/package.json +1 -1
- package/packages/editor/package.json +1 -1
- package/packages/fs/package.json +1 -1
- package/packages/preview/package.json +1 -1
- package/packages/runtime/package.json +1 -1
- package/packages/settings/package.json +1 -1
- package/packages/settings/src/builtin-schemas.ts +16 -0
- package/packages/sql/package.json +1 -1
- package/packages/sql/src/styles.ts +87 -64
- package/packages/terminal/package.json +1 -1
- package/packages/ui/package.json +1 -1
- package/packages/ui/src/observability.ts +12 -14
- package/packages/ui/src/settings-dialog.ts +409 -57
- package/packages/ui/src/themes.ts +78 -78
- package/src/code-lab.css +757 -310
- package/src/index.ts +1 -1
- package/src/runtime.ts +29 -3
- package/src/schemas.ts +10 -1
- package/src/shell.ts +106 -16
- package/src/workbench/diff-editor.ts +5 -1
- package/src/workbench/drawer.ts +5 -5
- package/src/workbench/icons.ts +5 -5
- package/src/workbench/intellisense.ts +94 -82
- package/src/workbench/styles.ts +58 -54
- package/src/workbench/toolbar.ts +1 -1
- package/src/workbench/xterm-adapter.ts +61 -56
- package/src/workbench.ts +462 -173
package/dist/shell.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* ============================================================
|
|
3
|
-
* @innovatorved/code-lab v0.
|
|
3
|
+
* @innovatorved/code-lab v0.7.0 — Standalone Browser Code IDE & Virtual Runtime
|
|
4
4
|
* ============================================================
|
|
5
5
|
* Features:
|
|
6
6
|
* - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
|
|
@@ -180,23 +180,23 @@ isomorphic-git/index.js:
|
|
|
180
180
|
|
|
181
181
|
if (typeof CodeLabScm !== 'undefined') root.CodeLabScm = CodeLabScm;
|
|
182
182
|
(function () {
|
|
183
|
-
(function(W,N){const U=N(W);W&&(W.CodeLabShell=U,W.createPosixShell=U.createPosixShell,W.PosixShell=U.PosixShell,W.parseShellCommand=U.parseShellCommand,W.tokenizeShell=U.tokenizeShell,W.COREUTILS=U.COREUTILS,W.createVirtualPortTable=U.createVirtualPortTable,W.parseGitHubRepoUrl=U.parseGitHubRepoUrl,W.cloneGitHubRepository=U.cloneGitHubRepository),typeof module<"u"&&module.exports?module.exports=U:typeof define=="function"&&define.amd&&define([],function(){return U})})(typeof globalThis<"u"?globalThis:this,function(W){"use strict";const N=W&&W.CodeLabLogger&&typeof W.CodeLabLogger.createLogger=="function"?W.CodeLabLogger.createLogger():{debug(){},info(...n){typeof console<"u"&&console.info&&console.info("[code-lab]",...n)},warn(...n){typeof console<"u"&&console.warn&&console.warn("[code-lab]",...n)},error(...n){typeof console<"u"&&console.error&&console.error("[code-lab]",...n)}};function U(){if(typeof W<"u"&&W&&W.CodeLabRuntime)return W.CodeLabRuntime;if(typeof globalThis<"u"&&globalThis.CodeLabRuntime)return globalThis.CodeLabRuntime;try{if(typeof require<"u")return require("./runtime.js")}catch(n){N.debug("Optional ./runtime.js require skipped in shell.",n)}return null}function $e(){if(typeof W<"u"&&W&&W.CodeLabScm)return W.CodeLabScm;if(typeof globalThis<"u"&&globalThis.CodeLabScm)return globalThis.CodeLabScm;try{if(typeof require<"u")return require("./scm.js")}catch(n){N.debug("Optional ./scm.js require skipped in shell.",n)}return null}function ke(){const n=U();return!!(n&&typeof n.executeInVirtualRuntime=="function")}function je(...n){const e=U();if(e&&typeof e.executeInVirtualRuntime=="function")return e.executeInVirtualRuntime(...n);throw new Error("Virtual runtime engine is not available")}async function H(n,e){const s=U();if(!s||typeof s.executeInVirtualRuntime!="function")throw new Error("Virtual runtime engine is not available");let t=typeof n.replCode=="string"?n.replCode:"";if(!t&&typeof n.entry=="string"&&e&&e.vfs&&typeof e.vfs.existsSync=="function")try{const h=typeof e.resolvePath=="function"?e.resolvePath(n.entry):n.entry,u=e.vfs.existsSync(h)?h:e.vfs.existsSync(n.entry)?n.entry:"";u&&(t=String(e.vfs.readFileSync(u,"utf8")||""))}catch(h){}let r=n.npmModules;const o=new Set(["assert","buffer","child_process","cluster","console","constants","crypto","dgram","diagnostics_channel","dns","domain","events","fs","http","http2","https","inspector","module","net","os","path","perf_hooks","process","punycode","querystring","readline","repl","sqlite","stream","string_decoder","sys","test","timers","tls","tty","url","util","v8","vm","wasi","worker_threads","zlib"]);let i=!1;if(t&&!(n.isBackground||e&&e.isBackground)){const h=/(?:from\s+|require\s*\(\s*)['"]([^./'"]+)['"]/g;let u;for(;(u=h.exec(t))!==null;){const p=u[1];if(p.startsWith("node:")||p.startsWith("bun:"))continue;const g=p.startsWith("@")?p.split("/").slice(0,2).join("/"):p.split("/")[0];if(!o.has(g)){i=!0;break}}}if(i&&typeof s.preloadNpmPackages=="function")try{const h=await s.preloadNpmPackages({[n.entry||"eval.js"]:t});h&&typeof h=="object"&&(r=Object.assign({},h,r||{}))}catch(h){N.debug("preloadNpmPackages skipped in shell:",h)}const f=(e&&typeof e.onRequestStdin=="function"?e.onRequestStdin:null)||(e&&e.shell&&e.shell.options&&typeof e.shell.options.onRequestStdin=="function"?e.shell.options.onRequestStdin:void 0),c=e&&e.shell?e.shell.portTable:null,y=!!(c&&typeof c.listServers=="function"&&c.listServers().length>0),l=!!(n.isBackground||e&&e.isBackground||y||/(?:\bcreateServer\b|\.listen\s*\(|\bBun\.serve\b|\blocalhost\b|127\.0\.0\.1)/.test(t)),a=n.instanceId||(e&&e.shell&&e.shell.options&&e.shell.options.instanceId?e.shell.options.instanceId:void 0),d={...n,...a?{instanceId:a}:{},concurrent:!0,npmModules:r,onRequestStdin:f};if(!l&&typeof Worker<"u"&&typeof s.executeInWorker=="function"){const h={...d};return delete h.activePortTable,delete h.portTable,s.executeInWorker(h)}return s.executeInVirtualRuntime({...d,activePortTable:c})}function le(...n){const e=U();return e&&typeof e.createVirtualPortTable=="function"?e.createVirtualPortTable(...n):null}function Ve(n,e){const s=U();return s&&typeof s.transpileTS=="function"?s.transpileTS(n,e):String(n).replace(/^\s*import\s+type\s+[^\n;]+;?\s*$/gm,"").replace(/^\s*export\s+(?:interface|type)\s+[A-Za-z0-9_$]+[\s\S]*?(?:^\}|\n)/gm,"").replace(/^\s*(?:interface|type)\s+[A-Za-z0-9_$]+[^;{]*\{[^}]*\}/gm,"").replace(/:\s*[A-Za-z0-9_$<>\[\]|&\s]+(?=[,=)\n;{])/g,"")}const j={normalize(n){if(typeof n!="string"||!n)return"/";const e=n.startsWith("/"),s=n.split("/").filter(Boolean),t=[];for(const o of s)o!=="."&&(o===".."?t.length>0&&t.pop():t.push(o));return(e?"/":"")+t.join("/")||(e?"/":".")},resolve(n,...e){let s=n.startsWith("/")?n:"/"+n;const t=j._homeDir||"/home/codelab";for(const r of e)r&&(r.startsWith("/")?s=r:r==="~"||r.startsWith("~/")?s=t+r.slice(1):s=s.endsWith("/")?s+r:s+"/"+r);return j.normalize(s)},dirname(n){const e=j.normalize(n);if(e==="/"||e===".")return e;const s=e.lastIndexOf("/");return s===-1?".":s===0?"/":e.slice(0,s)},basename(n,e){const s=j.normalize(n);if(s==="/")return"/";const t=s.lastIndexOf("/");let r=t===-1?s:s.slice(t+1);return e&&r.endsWith(e)&&r!==e&&(r=r.slice(0,-e.length)),r},join(...n){return j.normalize(n.filter(Boolean).join("/"))}};function Re(n,e=!0){let s="^",t=0;for(;t<n.length;){const r=n[t];if(r==="*"&&n[t+1]==="*"&&(n[t+2]==="/"||t+2===n.length))s+="(?:.+/)?",t+=n[t+2]==="/"?3:2;else if(r==="*"&&n[t+1]==="*")s+=".*",t+=2;else if(r==="*")s+=e?"[^/]*":".*",t++;else if(r==="?")s+=e?"[^/]":".",t++;else if(r==="["){const o=n.indexOf("]",t+1);if(o!==-1){let i=n.slice(t+1,o);i.startsWith("!")&&(i="^"+i.slice(1)),s+="["+i+"]",t=o+1}else s+="\\[",t++}else[".","$","^","+","(",")","{","}","|","\\"].includes(r)?(s+="\\"+r,t++):(s+=r,t++)}return s+="$",new RegExp(s)}function Oe(n){if(typeof n!="string"||!n.includes("{")||!n.includes("}"))return[n];let e=-1,s=-1,t=0;for(let a=0;a<n.length;a++){if(n[a]==="\\"){a++;continue}if(n[a]==="{")t===0&&(e=a),t++;else if(n[a]==="}"&&t>0&&(t--,t===0)){const d=n.slice(e+1,a);if(ae(d)||/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(d)||/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(d)){s=a;break}}}if(e===-1||s===-1)return[n];const r=n.slice(0,e),o=n.slice(e+1,s),i=n.slice(s+1);let f=[];const c=o.match(/^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/),y=o.match(/^([a-zA-Z])\.\.([a-zA-Z])(?:\.\.(-?\d+))?$/);if(c&&!ae(o)){const a=c[1],d=c[2],h=parseInt(a,10),u=parseInt(d,10);let p=c[3]!==void 0?parseInt(c[3],10):h<=u?1:-1;p===0&&(p=1),(h<=u&&p<0||h>u&&p>0)&&(p=-p);const g=a.startsWith("0")&&a.length>1||d.startsWith("0")&&d.length>1?Math.max(a.length,d.length):0;for(let m=h;p>0?m<=u:m>=u;m+=p){let S=String(Math.abs(m));g>0&&(S=S.padStart(g-(m<0?1:0),"0")),f.push(m<0?"-"+S:S)}}else if(y&&!ae(o)){const a=y[1].charCodeAt(0),d=y[2].charCodeAt(0);let h=y[3]!==void 0&&Math.abs(parseInt(y[3],10))||1;a>d&&(h=-h);for(let u=a;h>0?u<=d:u>=d;u+=h)f.push(String.fromCharCode(u))}else f=Je(o);const l=[];for(const a of f)for(const d of Oe(a))for(const h of Oe(i))l.push(r+d+h);return l}function ae(n){let e=0;for(let s=0;s<n.length;s++){if(n[s]==="\\"){s++;continue}if(n[s]==="{")e++;else if(n[s]==="}")e=Math.max(0,e-1);else if(n[s]===","&&e===0)return!0}return!1}function Je(n){const e=[];let s="",t=0;for(let r=0;r<n.length;r++){if(n[r]==="\\"&&r+1<n.length){s+=n[r]+n[r+1],r++;continue}n[r]==="{"?(t++,s+=n[r]):n[r]==="}"?(t=Math.max(0,t-1),s+=n[r]):n[r]===","&&t===0?(e.push(s),s=""):s+=n[r]}return e.push(s),e}function ce(n,e={},s=null){const t=String(n||"").trim();if(!t)return 0;const r=[];let o=0;const i=t.length;for(;o<i;){const k=t[o];if(/\s/.test(k)){o++;continue}const O=t.slice(o,o+3);if(O==="<<="||O===">>="){r.push({type:"OP",value:O}),o+=3;continue}const F=t.slice(o,o+2);if(["**","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^=","|="].includes(F)){r.push({type:"OP",value:F}),o+=2;continue}if("+-*/%<>&|^!~?:=,()".includes(k)){r.push({type:"OP",value:k}),o++;continue}if(k==="$"){o++;let P="";if(t[o]==="{"){for(o++;o<i&&t[o]!=="}";)P+=t[o++];t[o]==="}"&&o++}else for(;o<i&&/[a-zA-Z0-9_?#]/.test(t[o]);)P+=t[o++];const A=e[P]!==void 0?e[P]:s&&s[P]!==void 0?s[P]:"0",_=Number(A);r.push({type:"NUM",value:Number.isFinite(_)?Math.trunc(_):0,name:P});continue}if(/[0-9]/.test(k)){let P="";for(;o<i&&/[0-9a-fA-FxXbBoO_]/.test(t[o]);)t[o]!=="_"&&(P+=t[o]),o++;let A=0;/^0[xX]/.test(P)?A=parseInt(P.slice(2),16)||0:/^0[bB]/.test(P)?A=parseInt(P.slice(2),2)||0:/^0[oO]/.test(P)?A=parseInt(P.slice(2),8)||0:P.length>1&&P.startsWith("0")&&/^[0-7]+$/.test(P)?A=parseInt(P,8)||0:A=parseInt(P,10)||0,r.push({type:"NUM",value:A});continue}if(/[a-zA-Z_]/.test(k)){let P="";for(;o<i&&/[a-zA-Z0-9_]/.test(t[o]);)P+=t[o++];r.push({type:"IDENT",name:P});continue}o++}let f=0;const c=()=>r[f]||null,y=()=>r[f++]||null;function l(k){const O=e[k]!==void 0?e[k]:s&&s[k]!==void 0?s[k]:0,F=Number(O);return Number.isFinite(F)?Math.trunc(F):0}function a(k,O){const F=Math.trunc(Number(O)||0);return e[k]=String(F),s&&(s[k]=String(F)),F}function d(){let k=h();for(;c()&&c().type==="OP"&&c().value===",";)y(),k=h();return k}function h(){if(c()&&(c().type==="IDENT"||c().type==="NUM"&&c().name)){const k=r[f+1];if(k&&k.type==="OP"&&["=","+=","-=","*=","/=","%=","<<=",">>=","&=","^=","|="].includes(k.value)){const O=y().name,F=y().value,P=h(),A=l(O);if(F==="=")return a(O,P);if(F==="+=")return a(O,A+P);if(F==="-=")return a(O,A-P);if(F==="*=")return a(O,A*P);if(F==="/=")return a(O,P===0?0:Math.trunc(A/P));if(F==="%=")return a(O,P===0?0:A%P);if(F==="<<=")return a(O,A<<P);if(F===">>=")return a(O,A>>P);if(F==="&=")return a(O,A&P);if(F==="^=")return a(O,A^P);if(F==="|=")return a(O,A|P)}}return u()}function u(){const k=p();if(c()&&c().type==="OP"&&c().value==="?"){y();const O=h();c()&&c().type==="OP"&&c().value===":"&&y();const F=h();return k!==0?O:F}return k}function p(){let k=g();for(;c()&&c().type==="OP"&&c().value==="||";){y();const O=g();k=k!==0||O!==0?1:0}return k}function g(){let k=m();for(;c()&&c().type==="OP"&&c().value==="&&";){y();const O=m();k=k!==0&&O!==0?1:0}return k}function m(){let k=S();for(;c()&&c().type==="OP"&&c().value==="|";)y(),k=k|S();return k}function S(){let k=b();for(;c()&&c().type==="OP"&&c().value==="^";)y(),k=k^b();return k}function b(){let k=w();for(;c()&&c().type==="OP"&&c().value==="&";)y(),k=k&w();return k}function w(){let k=v();for(;c()&&c().type==="OP"&&(c().value==="=="||c().value==="!=");){const O=y().value,F=v();k=O==="=="?k===F?1:0:k!==F?1:0}return k}function v(){let k=$();for(;c()&&c().type==="OP"&&["<","<=",">",">="].includes(c().value);){const O=y().value,F=$();O==="<"?k=k<F?1:0:O==="<="?k=k<=F?1:0:O===">"?k=k>F?1:0:O===">="&&(k=k>=F?1:0)}return k}function $(){let k=R();for(;c()&&c().type==="OP"&&(c().value==="<<"||c().value===">>");){const O=y().value,F=R();k=O==="<<"?k<<F:k>>F}return k}function R(){let k=I();for(;c()&&c().type==="OP"&&(c().value==="+"||c().value==="-");){const O=y().value,F=I();k=O==="+"?k+F:k-F}return k}function I(){let k=C();for(;c()&&c().type==="OP"&&["*","/","%"].includes(c().value);){const O=y().value,F=C();O==="*"?k=k*F:O==="/"?k=F===0?0:Math.trunc(k/F):O==="%"&&(k=F===0?0:k%F)}return k}function C(){const k=E();if(c()&&c().type==="OP"&&c().value==="**"){y();const O=C();return Math.trunc(Math.pow(k,O))}return k}function E(){const k=c();if(k&&k.type==="OP"){if(k.value==="+")return y(),+E();if(k.value==="-")return y(),-E();if(k.value==="!")return y(),E()===0?1:0;if(k.value==="~")return y(),~E();if(k.value==="++"||k.value==="--"){const O=y().value,F=c();if(F&&(F.type==="IDENT"||F.name)){y();const P=l(F.name);return a(F.name,O==="++"?P+1:P-1)}return E()}}return T()}function T(){const k=c();if(!k)return 0;if(k.type==="OP"&&k.value==="("){y();const O=d();return c()&&c().type==="OP"&&c().value===")"&&y(),O}if(k.type==="IDENT"){y();const O=l(k.name);if(c()&&c().type==="OP"&&(c().value==="++"||c().value==="--")){const F=y().value;a(k.name,F==="++"?O+1:O-1)}return O}if(k.type==="NUM"){if(y(),k.name&&c()&&c().type==="OP"&&(c().value==="++"||c().value==="--")){const O=y().value;a(k.name,O==="++"?k.value+1:k.value-1)}return k.value}return y(),0}return Math.trunc(d()||0)}function Pe(n,e,s){if(!s)return[n];if(!/[*?\[]/.test(n))return[n];const t=n.startsWith("/"),r=t?"/":e,o=[];function i(l,a){let d=[];try{typeof s.readdirSync=="function"&&(d=s.readdirSync(l))}catch{return}for(const h of d){const u=l==="/"?"/"+h:l+"/"+h,p=a?a+"/"+h:h;o.push({full:u,rel:p});let g=!1;try{typeof s.statSync=="function"&&(g=s.statSync(u).isDirectory())}catch(m){N.debug("Glob statSync failed.",u,m)}g&&i(u,p)}}i(r,"");const f=t?n:n.startsWith("./")?n.slice(2):n,c=Re(f,!0),y=[];for(const l of o){const a=t?l.full:l.rel;if(c.test(a)){const d=a.split("/").filter(Boolean),h=f.split("/").filter(Boolean);let u=!1;for(let p=0;p<d.length;p++){const g=d[p],m=h[p]!==void 0?h[p]:h[h.length-1];if(g&&g.startsWith(".")&&m&&!m.startsWith(".")){u=!0;break}}u||y.push(t?l.full:n.startsWith("./")?"./"+l.rel:l.rel)}}return y.sort(),y.length>0?y:[n]}function Ee(n){if(typeof n!="string")return[];const e=[],s=n.length;let t=0,r=-1;for(;t<s;){const o=n[t];if(o===`
|
|
183
|
+
(function(W,M){const U=M(W);W&&(W.CodeLabShell=U,W.createPosixShell=U.createPosixShell,W.PosixShell=U.PosixShell,W.parseShellCommand=U.parseShellCommand,W.tokenizeShell=U.tokenizeShell,W.COREUTILS=U.COREUTILS,W.createVirtualPortTable=U.createVirtualPortTable,W.parseGitHubRepoUrl=U.parseGitHubRepoUrl,W.cloneGitHubRepository=U.cloneGitHubRepository),typeof module<"u"&&module.exports?module.exports=U:typeof define=="function"&&define.amd&&define([],function(){return U})})(typeof globalThis<"u"?globalThis:this,function(W){"use strict";const M=W&&W.CodeLabLogger&&typeof W.CodeLabLogger.createLogger=="function"?W.CodeLabLogger.createLogger():{debug(){},info(...n){typeof console<"u"&&console.info&&console.info("[code-lab]",...n)},warn(...n){typeof console<"u"&&console.warn&&console.warn("[code-lab]",...n)},error(...n){typeof console<"u"&&console.error&&console.error("[code-lab]",...n)}};function U(){if(typeof W<"u"&&W&&W.CodeLabRuntime)return W.CodeLabRuntime;if(typeof globalThis<"u"&&globalThis.CodeLabRuntime)return globalThis.CodeLabRuntime;try{if(typeof require<"u")return require("./runtime.js")}catch(n){M.debug("Optional ./runtime.js require skipped in shell.",n)}return null}function je(){if(typeof W<"u"&&W&&W.CodeLabScm)return W.CodeLabScm;if(typeof globalThis<"u"&&globalThis.CodeLabScm)return globalThis.CodeLabScm;try{if(typeof require<"u")return require("./scm.js")}catch(n){M.debug("Optional ./scm.js require skipped in shell.",n)}return null}function Re(){const n=U();return!!(n&&typeof n.executeInVirtualRuntime=="function")}function Oe(...n){const e=U();if(e&&typeof e.executeInVirtualRuntime=="function")return e.executeInVirtualRuntime(...n);throw new Error("Virtual runtime engine is not available")}async function q(n,e){const s=U();if(!s||typeof s.executeInVirtualRuntime!="function")throw new Error("Virtual runtime engine is not available");let t=typeof n.replCode=="string"?n.replCode:"";if(!t&&typeof n.entry=="string"&&e&&e.vfs&&typeof e.vfs.existsSync=="function")try{const h=typeof e.resolvePath=="function"?e.resolvePath(n.entry):n.entry,u=e.vfs.existsSync(h)?h:e.vfs.existsSync(n.entry)?n.entry:"";u&&(t=String(e.vfs.readFileSync(u,"utf8")||""))}catch(h){}let r=n.npmModules;const o=new Set(["assert","buffer","child_process","cluster","console","constants","crypto","dgram","diagnostics_channel","dns","domain","events","fs","http","http2","https","inspector","module","net","os","path","perf_hooks","process","punycode","querystring","readline","repl","sqlite","stream","string_decoder","sys","test","timers","tls","tty","url","util","v8","vm","wasi","worker_threads","zlib"]);let i=!1;if(t&&!(n.isBackground||e&&e.isBackground)){const h=/(?:from\s+|require\s*\(\s*)['"]([^./'"]+)['"]/g;let u;for(;(u=h.exec(t))!==null;){const p=u[1];if(p.startsWith("node:")||p.startsWith("bun:"))continue;const g=p.startsWith("@")?p.split("/").slice(0,2).join("/"):p.split("/")[0];if(!o.has(g)){i=!0;break}}}if(i&&typeof s.preloadNpmPackages=="function")try{const h=await s.preloadNpmPackages({[n.entry||"eval.js"]:t});h&&typeof h=="object"&&(r=Object.assign({},h,r||{}))}catch(h){M.debug("preloadNpmPackages skipped in shell:",h)}const f=(e&&typeof e.onRequestStdin=="function"?e.onRequestStdin:null)||(e&&e.shell&&e.shell.options&&typeof e.shell.options.onRequestStdin=="function"?e.shell.options.onRequestStdin:void 0),d=e&&e.shell?e.shell.portTable:null,y=!!(d&&typeof d.listServers=="function"&&d.listServers().length>0),l=!!(n.isBackground||e&&e.isBackground||y||/(?:\bcreateServer\b|\.listen\s*\(|\bBun\.serve\b|\blocalhost\b|127\.0\.0\.1)/.test(t)),a=n.instanceId||(e&&e.shell&&e.shell.options&&e.shell.options.instanceId?e.shell.options.instanceId:void 0),c={...n,...a?{instanceId:a}:{},concurrent:!0,npmModules:r,onRequestStdin:f};if(!l&&typeof Worker<"u"&&typeof s.executeInWorker=="function"){const h={...c};return delete h.activePortTable,delete h.portTable,s.executeInWorker(h)}return s.executeInVirtualRuntime({...c,activePortTable:d})}function le(...n){const e=U();return e&&typeof e.createVirtualPortTable=="function"?e.createVirtualPortTable(...n):null}function Je(n,e){const s=U();return s&&typeof s.transpileTS=="function"?s.transpileTS(n,e):String(n).replace(/^\s*import\s+type\s+[^\n;]+;?\s*$/gm,"").replace(/^\s*export\s+(?:interface|type)\s+[A-Za-z0-9_$]+[\s\S]*?(?:^\}|\n)/gm,"").replace(/^\s*(?:interface|type)\s+[A-Za-z0-9_$]+[^;{]*\{[^}]*\}/gm,"").replace(/:\s*[A-Za-z0-9_$<>\[\]|&\s]+(?=[,=)\n;{])/g,"")}const j={normalize(n){if(typeof n!="string"||!n)return"/";const e=n.startsWith("/"),s=n.split("/").filter(Boolean),t=[];for(const o of s)o!=="."&&(o===".."?t.length>0&&t.pop():t.push(o));return(e?"/":"")+t.join("/")||(e?"/":".")},resolve(n,...e){let s=n.startsWith("/")?n:"/"+n;const t=j._homeDir||"/home/codelab";for(const r of e)r&&(r.startsWith("/")?s=r:r==="~"||r.startsWith("~/")?s=t+r.slice(1):s=s.endsWith("/")?s+r:s+"/"+r);return j.normalize(s)},dirname(n){const e=j.normalize(n);if(e==="/"||e===".")return e;const s=e.lastIndexOf("/");return s===-1?".":s===0?"/":e.slice(0,s)},basename(n,e){const s=j.normalize(n);if(s==="/")return"/";const t=s.lastIndexOf("/");let r=t===-1?s:s.slice(t+1);return e&&r.endsWith(e)&&r!==e&&(r=r.slice(0,-e.length)),r},join(...n){return j.normalize(n.filter(Boolean).join("/"))}};function Pe(n,e=!0){let s="^",t=0;for(;t<n.length;){const r=n[t];if(r==="*"&&n[t+1]==="*"&&(n[t+2]==="/"||t+2===n.length))s+="(?:.+/)?",t+=n[t+2]==="/"?3:2;else if(r==="*"&&n[t+1]==="*")s+=".*",t+=2;else if(r==="*")s+=e?"[^/]*":".*",t++;else if(r==="?")s+=e?"[^/]":".",t++;else if(r==="["){const o=n.indexOf("]",t+1);if(o!==-1){let i=n.slice(t+1,o);i.startsWith("!")&&(i="^"+i.slice(1)),s+="["+i+"]",t=o+1}else s+="\\[",t++}else[".","$","^","+","(",")","{","}","|","\\"].includes(r)?(s+="\\"+r,t++):(s+=r,t++)}return s+="$",new RegExp(s)}function Ee(n){if(typeof n!="string"||!n.includes("{")||!n.includes("}"))return[n];let e=-1,s=-1,t=0;for(let a=0;a<n.length;a++){if(n[a]==="\\"){a++;continue}if(n[a]==="{")t===0&&(e=a),t++;else if(n[a]==="}"&&t>0&&(t--,t===0)){const c=n.slice(e+1,a);if(ae(c)||/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(c)||/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(c)){s=a;break}}}if(e===-1||s===-1)return[n];const r=n.slice(0,e),o=n.slice(e+1,s),i=n.slice(s+1);let f=[];const d=o.match(/^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/),y=o.match(/^([a-zA-Z])\.\.([a-zA-Z])(?:\.\.(-?\d+))?$/);if(d&&!ae(o)){const a=d[1],c=d[2],h=parseInt(a,10),u=parseInt(c,10);let p=d[3]!==void 0?parseInt(d[3],10):h<=u?1:-1;p===0&&(p=1),(h<=u&&p<0||h>u&&p>0)&&(p=-p);const g=a.startsWith("0")&&a.length>1||c.startsWith("0")&&c.length>1?Math.max(a.length,c.length):0;for(let m=h;p>0?m<=u:m>=u;m+=p){let S=String(Math.abs(m));g>0&&(S=S.padStart(g-(m<0?1:0),"0")),f.push(m<0?"-"+S:S)}}else if(y&&!ae(o)){const a=y[1].charCodeAt(0),c=y[2].charCodeAt(0);let h=y[3]!==void 0&&Math.abs(parseInt(y[3],10))||1;a>c&&(h=-h);for(let u=a;h>0?u<=c:u>=c;u+=h)f.push(String.fromCharCode(u))}else f=Ge(o);const l=[];for(const a of f)for(const c of Ee(a))for(const h of Ee(i))l.push(r+c+h);return l}function ae(n){let e=0;for(let s=0;s<n.length;s++){if(n[s]==="\\"){s++;continue}if(n[s]==="{")e++;else if(n[s]==="}")e=Math.max(0,e-1);else if(n[s]===","&&e===0)return!0}return!1}function Ge(n){const e=[];let s="",t=0;for(let r=0;r<n.length;r++){if(n[r]==="\\"&&r+1<n.length){s+=n[r]+n[r+1],r++;continue}n[r]==="{"?(t++,s+=n[r]):n[r]==="}"?(t=Math.max(0,t-1),s+=n[r]):n[r]===","&&t===0?(e.push(s),s=""):s+=n[r]}return e.push(s),e}function ce(n,e={},s=null){const t=String(n||"").trim();if(!t)return 0;const r=[];let o=0;const i=t.length;for(;o<i;){const k=t[o];if(/\s/.test(k)){o++;continue}const O=t.slice(o,o+3);if(O==="<<="||O===">>="){r.push({type:"OP",value:O}),o+=3;continue}const F=t.slice(o,o+2);if(["**","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^=","|="].includes(F)){r.push({type:"OP",value:F}),o+=2;continue}if("+-*/%<>&|^!~?:=,()".includes(k)){r.push({type:"OP",value:k}),o++;continue}if(k==="$"){o++;let P="";if(t[o]==="{"){for(o++;o<i&&t[o]!=="}";)P+=t[o++];t[o]==="}"&&o++}else for(;o<i&&/[a-zA-Z0-9_?#]/.test(t[o]);)P+=t[o++];const A=e[P]!==void 0?e[P]:s&&s[P]!==void 0?s[P]:"0",_=Number(A);r.push({type:"NUM",value:Number.isFinite(_)?Math.trunc(_):0,name:P});continue}if(/[0-9]/.test(k)){let P="";for(;o<i&&/[0-9a-fA-FxXbBoO_]/.test(t[o]);)t[o]!=="_"&&(P+=t[o]),o++;let A=0;/^0[xX]/.test(P)?A=parseInt(P.slice(2),16)||0:/^0[bB]/.test(P)?A=parseInt(P.slice(2),2)||0:/^0[oO]/.test(P)?A=parseInt(P.slice(2),8)||0:P.length>1&&P.startsWith("0")&&/^[0-7]+$/.test(P)?A=parseInt(P,8)||0:A=parseInt(P,10)||0,r.push({type:"NUM",value:A});continue}if(/[a-zA-Z_]/.test(k)){let P="";for(;o<i&&/[a-zA-Z0-9_]/.test(t[o]);)P+=t[o++];r.push({type:"IDENT",name:P});continue}o++}let f=0;const d=()=>r[f]||null,y=()=>r[f++]||null;function l(k){const O=e[k]!==void 0?e[k]:s&&s[k]!==void 0?s[k]:0,F=Number(O);return Number.isFinite(F)?Math.trunc(F):0}function a(k,O){const F=Math.trunc(Number(O)||0);return e[k]=String(F),s&&(s[k]=String(F)),F}function c(){let k=h();for(;d()&&d().type==="OP"&&d().value===",";)y(),k=h();return k}function h(){if(d()&&(d().type==="IDENT"||d().type==="NUM"&&d().name)){const k=r[f+1];if(k&&k.type==="OP"&&["=","+=","-=","*=","/=","%=","<<=",">>=","&=","^=","|="].includes(k.value)){const O=y().name,F=y().value,P=h(),A=l(O);if(F==="=")return a(O,P);if(F==="+=")return a(O,A+P);if(F==="-=")return a(O,A-P);if(F==="*=")return a(O,A*P);if(F==="/=")return a(O,P===0?0:Math.trunc(A/P));if(F==="%=")return a(O,P===0?0:A%P);if(F==="<<=")return a(O,A<<P);if(F===">>=")return a(O,A>>P);if(F==="&=")return a(O,A&P);if(F==="^=")return a(O,A^P);if(F==="|=")return a(O,A|P)}}return u()}function u(){const k=p();if(d()&&d().type==="OP"&&d().value==="?"){y();const O=h();d()&&d().type==="OP"&&d().value===":"&&y();const F=h();return k!==0?O:F}return k}function p(){let k=g();for(;d()&&d().type==="OP"&&d().value==="||";){y();const O=g();k=k!==0||O!==0?1:0}return k}function g(){let k=m();for(;d()&&d().type==="OP"&&d().value==="&&";){y();const O=m();k=k!==0&&O!==0?1:0}return k}function m(){let k=S();for(;d()&&d().type==="OP"&&d().value==="|";)y(),k=k|S();return k}function S(){let k=b();for(;d()&&d().type==="OP"&&d().value==="^";)y(),k=k^b();return k}function b(){let k=v();for(;d()&&d().type==="OP"&&d().value==="&";)y(),k=k&v();return k}function v(){let k=w();for(;d()&&d().type==="OP"&&(d().value==="=="||d().value==="!=");){const O=y().value,F=w();k=O==="=="?k===F?1:0:k!==F?1:0}return k}function w(){let k=$();for(;d()&&d().type==="OP"&&["<","<=",">",">="].includes(d().value);){const O=y().value,F=$();O==="<"?k=k<F?1:0:O==="<="?k=k<=F?1:0:O===">"?k=k>F?1:0:O===">="&&(k=k>=F?1:0)}return k}function $(){let k=R();for(;d()&&d().type==="OP"&&(d().value==="<<"||d().value===">>");){const O=y().value,F=R();k=O==="<<"?k<<F:k>>F}return k}function R(){let k=I();for(;d()&&d().type==="OP"&&(d().value==="+"||d().value==="-");){const O=y().value,F=I();k=O==="+"?k+F:k-F}return k}function I(){let k=C();for(;d()&&d().type==="OP"&&["*","/","%"].includes(d().value);){const O=y().value,F=C();O==="*"?k=k*F:O==="/"?k=F===0?0:Math.trunc(k/F):O==="%"&&(k=F===0?0:k%F)}return k}function C(){const k=E();if(d()&&d().type==="OP"&&d().value==="**"){y();const O=C();return Math.trunc(Math.pow(k,O))}return k}function E(){const k=d();if(k&&k.type==="OP"){if(k.value==="+")return y(),+E();if(k.value==="-")return y(),-E();if(k.value==="!")return y(),E()===0?1:0;if(k.value==="~")return y(),~E();if(k.value==="++"||k.value==="--"){const O=y().value,F=d();if(F&&(F.type==="IDENT"||F.name)){y();const P=l(F.name);return a(F.name,O==="++"?P+1:P-1)}return E()}}return T()}function T(){const k=d();if(!k)return 0;if(k.type==="OP"&&k.value==="("){y();const O=c();return d()&&d().type==="OP"&&d().value===")"&&y(),O}if(k.type==="IDENT"){y();const O=l(k.name);if(d()&&d().type==="OP"&&(d().value==="++"||d().value==="--")){const F=y().value;a(k.name,F==="++"?O+1:O-1)}return O}if(k.type==="NUM"){if(y(),k.name&&d()&&d().type==="OP"&&(d().value==="++"||d().value==="--")){const O=y().value;a(k.name,O==="++"?k.value+1:k.value-1)}return k.value}return y(),0}return Math.trunc(c()||0)}function Fe(n,e,s){if(!s)return[n];if(!/[*?\[]/.test(n))return[n];const t=n.startsWith("/"),r=t?"/":e,o=[];function i(l,a){let c=[];try{typeof s.readdirSync=="function"&&(c=s.readdirSync(l))}catch{return}for(const h of c){const u=l==="/"?"/"+h:l+"/"+h,p=a?a+"/"+h:h;o.push({full:u,rel:p});let g=!1;try{typeof s.statSync=="function"&&(g=s.statSync(u).isDirectory())}catch(m){M.debug("Glob statSync failed.",u,m)}g&&i(u,p)}}i(r,"");const f=t?n:n.startsWith("./")?n.slice(2):n,d=Pe(f,!0),y=[];for(const l of o){const a=t?l.full:l.rel;if(d.test(a)){const c=a.split("/").filter(Boolean),h=f.split("/").filter(Boolean);let u=!1;for(let p=0;p<c.length;p++){const g=c[p],m=h[p]!==void 0?h[p]:h[h.length-1];if(g&&g.startsWith(".")&&m&&!m.startsWith(".")){u=!0;break}}u||y.push(t?l.full:n.startsWith("./")?"./"+l.rel:l.rel)}}return y.sort(),y.length>0?y:[n]}function Te(n){if(typeof n!="string")return[];const e=[],s=n.length;let t=0,r=-1;for(;t<s;){const o=n[t];if(o===`
|
|
184
184
|
`){if(r>t?(t=r,r=-1):t++,e.length>0){const l=e[e.length-1].type;l!=="SEMICOLON"&&l!=="DSEMI"&&l!=="AND"&&l!=="OR"&&l!=="PIPE"&&l!=="LPAREN"&&e.push({type:"SEMICOLON",raw:";"})}continue}if(/[ \t\r\f\v]/.test(o)){t++;continue}if(o==="#"){for(;t<s&&n[t]!==`
|
|
185
|
-
`;)t++;continue}if(o===";"&&n[t+1]===";"){e.push({type:"DSEMI",raw:";;"}),t+=2;continue}if(o===";"){e.push({type:"SEMICOLON",raw:";"}),t++;continue}if(o==="("){e.push({type:"LPAREN",raw:"("}),t++;continue}if(o===")"){e.push({type:"RPAREN",raw:")"}),t++;continue}if(o==="&"&&n[t+1]==="&"){e.push({type:"AND",raw:"&&"}),t+=2;continue}if(o==="|"&&n[t+1]==="|"){e.push({type:"OR",raw:"||"}),t+=2;continue}if(o==="|"){e.push({type:"PIPE",raw:"|"}),t++;continue}if(o==="&"&&n[t+1]===">"){e.push({type:"REDIRECT",op:"&>",sourceFd:"all",raw:"&>"}),t+=2;continue}if(o==="&"){e.push({type:"BACKGROUND",raw:"&"}),t++;continue}if((o==="1"||o==="2"||o==="0")&&(n[t+1]===">"||n[t+1]==="<")){const l=parseInt(o,10),a=n[t+1];if(a===">"&&n[t+2]==="&"&&(n[t+3]==="1"||n[t+3]==="2")){const
|
|
185
|
+
`;)t++;continue}if(o===";"&&n[t+1]===";"){e.push({type:"DSEMI",raw:";;"}),t+=2;continue}if(o===";"){e.push({type:"SEMICOLON",raw:";"}),t++;continue}if(o==="("){e.push({type:"LPAREN",raw:"("}),t++;continue}if(o===")"){e.push({type:"RPAREN",raw:")"}),t++;continue}if(o==="&"&&n[t+1]==="&"){e.push({type:"AND",raw:"&&"}),t+=2;continue}if(o==="|"&&n[t+1]==="|"){e.push({type:"OR",raw:"||"}),t+=2;continue}if(o==="|"){e.push({type:"PIPE",raw:"|"}),t++;continue}if(o==="&"&&n[t+1]===">"){e.push({type:"REDIRECT",op:"&>",sourceFd:"all",raw:"&>"}),t+=2;continue}if(o==="&"){e.push({type:"BACKGROUND",raw:"&"}),t++;continue}if((o==="1"||o==="2"||o==="0")&&(n[t+1]===">"||n[t+1]==="<")){const l=parseInt(o,10),a=n[t+1];if(a===">"&&n[t+2]==="&"&&(n[t+3]==="1"||n[t+3]==="2")){const c=parseInt(n[t+3],10);e.push({type:"REDIRECT_FD",sourceFd:l,targetFd:c,raw:`${l}>&${c}`}),t+=4;continue}if(a===">"&&n[t+2]===">"){e.push({type:"REDIRECT",op:">>",sourceFd:l,raw:`${l}>>`}),t+=3;continue}e.push({type:"REDIRECT",op:a,sourceFd:l,raw:`${l}${a}`}),t+=2;continue}if(o===">"){if(n[t+1]==="&"&&(n[t+2]==="1"||n[t+2]==="2")){const l=parseInt(n[t+2],10);e.push({type:"REDIRECT_FD",sourceFd:1,targetFd:l,raw:`>&${l}`}),t+=3;continue}if(n[t+1]===">"){e.push({type:"REDIRECT",op:">>",sourceFd:1,raw:">>"}),t+=2;continue}e.push({type:"REDIRECT",op:">",sourceFd:1,raw:">"}),t++;continue}if(o==="<"){if(n[t+1]==="<"&&n[t+2]==="<"){e.push({type:"REDIRECT",op:"<<<",sourceFd:0,raw:"<<<"}),t+=3;continue}if(n[t+1]==="<"){const l=n[t+2]==="-";for(t+=l?3:2;t<s&&(n[t]===" "||n[t]===" ");)t++;let a="",c=!1;for(;t<s&&!/[\s;|&<>()]/.test(n[t]);)if(n[t]==="'"||n[t]==='"'){const p=n[t++];for(c=!0;t<s&&n[t]!==p;)a+=n[t++];t<s&&n[t]===p&&t++}else n[t]==="\\"&&t+1<s&&(c=!0,t++),a+=n[t++];const h=r>t?r:n.indexOf(`
|
|
186
186
|
`,t);let u="";if(h!==-1&&h<s){let p=h+1;for(;p<=s;){let g=n.indexOf(`
|
|
187
187
|
`,p);g===-1&&(g=s);const m=n.slice(p,g).replace(/\r$/,"");if((l?m.replace(/^\t+/,""):m)===a){r=g<s?g+1:s;break}if(u+=(l?m.replace(/^\t+/,""):m)+`
|
|
188
|
-
`,g===s){r=s;break}p=g+1}}e.push({type:"REDIRECT",op:"<<",sourceFd:0,stripTabs:l,quoted:
|
|
189
|
-
`,t+=2;continue}if(p==="t"){h+=" ",t+=2;continue}h+="\\"+p,t+=2;continue}if(u==="$"&&n[t+1]==="("&&n[t+2]==="("){h&&(d.push({type:"literal",value:h}),h=""),t+=3;let p=2,g="";for(;t<s&&p>0;)if(n[t]==="(")p++,g+="(",t++;else if(n[t]===")"){if(p===2&&n[t+1]===")"){p=0,t+=2;break}p--,p>0&&(g+=")"),t++}else g+=n[t++];d.push({type:"arith",expr:g});continue}if(u==="$"&&n[t+1]==="("){h&&(d.push({type:"literal",value:h}),h=""),t+=2;let p=1,g="";for(;t<s&&p>0;)n[t]==="("?p++:n[t]===")"&&p--,p>0&&(g+=n[t]),t++;d.push({type:"subshell",command:g});continue}if(u==="`"){h&&(d.push({type:"literal",value:h}),h=""),t++;let p="";for(;t<s&&n[t]!=="`";)p+=n[t++];t<s&&n[t]==="`"&&t++,d.push({type:"subshell",command:p});continue}if(u==="$"){if(h&&(d.push({type:"literal",value:h}),h=""),t++,n[t]==="{"){t++;let p="",g=1;for(;t<s&&g>0;)n[t]==="{"?g++:n[t]==="}"&&g--,g>0&&(p+=n[t]),t++;d.push({type:"variable",name:p})}else if(/[0-9?!$#@*]/.test(n[t])){const p=n[t++];d.push({type:"variable",name:p})}else if(/[a-zA-Z_]/.test(n[t])){let p="";for(;t<s&&/[a-zA-Z0-9_]/.test(n[t]);)p+=n[t++];d.push({type:"variable",name:p})}else h+="$";continue}h+=u,t++}t<s&&n[t]==='"'&&t++,h&&d.push({type:"literal",value:h}),i.push({type:"double_quoted",parts:d}),f+=n.slice(a,t);continue}if(l==="\\"&&t+1<s){i.push({type:"literal",value:n[t+1],escaped:!0}),f+="\\"+n[t+1],t+=2;continue}if(l==="$"&&n[t+1]==="("&&n[t+2]==="("){t+=3;let a=2,d="";for(;t<s&&a>0;)if(n[t]==="(")a++,d+="(",t++;else if(n[t]===")"){if(a===2&&n[t+1]===")"){a=0,t+=2;break}a--,a>0&&(d+=")"),t++}else d+=n[t++];i.push({type:"arith",expr:d}),f+=`$((${d}))`;continue}if(l==="$"&&n[t+1]==="("){t+=2;let a=1,d="";for(;t<s&&a>0;)n[t]==="("?a++:n[t]===")"&&a--,a>0&&(d+=n[t]),t++;i.push({type:"subshell",command:d}),f+=`$(${d})`;continue}if(l==="`"){t++;let a="";for(;t<s&&n[t]!=="`";)a+=n[t],t++;t<s&&n[t]==="`"&&t++,i.push({type:"subshell",command:a}),f+=`\`${a}\``;continue}if(l==="$"){if(t++,n[t]==="{"){t++;let a="",d=1;for(;t<s&&d>0;)n[t]==="{"?d++:n[t]==="}"&&d--,d>0&&(a+=n[t]),t++;i.push({type:"variable",name:a}),f+=`\${${a}}`}else if(/[0-9?!$#@*]/.test(n[t])){const a=n[t++];i.push({type:"variable",name:a}),f+=`$${a}`}else if(/[a-zA-Z_]/.test(n[t])){let a="";for(;t<s&&/[a-zA-Z0-9_]/.test(n[t]);)a+=n[t++];i.push({type:"variable",name:a}),f+=`$${a}`}else i.push({type:"literal",value:"$"}),f+="$";continue}(l==="*"||l==="?"||l==="[")&&(c=!0),(l==="{"||l==="}")&&(y=!0),i.push({type:"literal",value:l}),f+=l,t++}e.push({type:"WORD",segments:i,raw:f,hasWildcard:c,hasBraces:y})}return e}function Fe(n){const e=typeof n=="string"?Ee(n):n;let s=0;function t(){return e[s]||null}function r(){return e[s++]||null}function o(d,...h){return!!(d&&d.type==="WORD"&&h.includes(d.raw))}function i(){for(;t()&&t().type==="SEMICOLON";)r()}function f(d=[]){const h=[];for(;s<e.length;){i();const u=t();if(!u||u.type==="RPAREN"||u.type==="DSEMI"||d.length>0&&o(u,...d))break;const p=c(d);if(!p)break;let g=!1;t()&&t().type==="BACKGROUND"?(r(),g=!0):t()&&t().type==="SEMICOLON"&&r(),h.push({node:p,background:g})}return{type:"Sequence",items:h}}function c(d=[]){let h=y(d);if(!h)return null;for(;t()&&(t().type==="AND"||t().type==="OR");){const u=r();i();const p=y(d);if(!p)break;h={type:"Logical",op:u.type==="AND"?"&&":"||",left:h,right:p}}return h}function y(d=[]){let h=!1;o(t(),"!")&&(r(),h=!0);const u=[],p=a(d);if(!p)return null;for(u.push(p);t()&&t().type==="PIPE";){r(),i();const g=a(d);g&&u.push(g)}return u.length===1&&!h?u[0]:{type:"Pipeline",negated:h,commands:u}}function l(){const d=[];for(;t()&&(t().type==="REDIRECT"||t().type==="REDIRECT_FD");){const h=r();if(h.type==="REDIRECT")if(h.op==="<<")d.push({type:"<<",sourceFd:h.sourceFd,body:h.body,quoted:h.quoted,stripTabs:h.stripTabs});else{let u=null;t()&&t().type==="WORD"&&(u=r()),d.push({type:h.op,sourceFd:h.sourceFd,target:u})}else d.push({type:">&",sourceFd:h.sourceFd,targetFd:h.targetFd})}return d}function a(d=[]){const h=t();if(!h||h.type==="RPAREN"||h.type==="DSEMI"||d.length>0&&o(h,...d))return null;if(h.type==="LPAREN"){r();const m=f([]);return t()&&t().type==="RPAREN"&&r(),{type:"Subshell",body:m,redirects:l()}}if(o(h,"{")){r();const m=f(["}"]);return o(t(),"}")&&r(),{type:"BraceGroup",body:m,redirects:l()}}if(o(h,"if")){r();const m=[],S=f(["then"]);o(t(),"then")&&r();const b=f(["elif","else","fi"]);for(m.push({cond:S,body:b});o(t(),"elif");){r();const v=f(["then"]);o(t(),"then")&&r();const $=f(["elif","else","fi"]);m.push({cond:v,body:$})}let w=null;return o(t(),"else")&&(r(),w=f(["fi"])),o(t(),"fi")&&r(),{type:"If",branches:m,elseBody:w,redirects:l()}}if(o(h,"for")){r();const m=r(),S=m?m.raw:"i";let b=null;if(o(t(),"in"))for(r(),b=[];t()&&t().type==="WORD"&&!o(t(),"do");)b.push(r());i(),o(t(),"do")&&r();const w=f(["done"]);return o(t(),"done")&&r(),{type:"For",varName:S,items:b,body:w,redirects:l()}}if(o(h,"while","until")){const m=r().raw,S=f(["do"]);o(t(),"do")&&r();const b=f(["done"]);return o(t(),"done")&&r(),{type:m==="while"?"While":"Until",cond:S,body:b,redirects:l()}}if(o(h,"case")){r();const m=r();i(),o(t(),"in")&&r(),i();const S=[];for(;s<e.length&&!o(t(),"esac")&&(i(),!o(t(),"esac"));){t()&&t().type==="LPAREN"&&r();const b=[];for(;s<e.length&&t().type!=="RPAREN"&&!o(t(),"esac");){if(t().type==="PIPE"){r();continue}b.push(r())}t()&&t().type==="RPAREN"&&r();const w=f(["esac"]);t()&&t().type==="DSEMI"&&r(),i(),S.push({patterns:b,body:w})}return o(t(),"esac")&&r(),{type:"Case",word:m,clauses:S,redirects:l()}}if(o(h,"function")){r();const m=r(),S=m?m.raw:"";t()&&t().type==="LPAREN"&&(r(),t()&&t().type==="RPAREN"&&r()),i();const b=a(d);return{type:"FunctionDef",name:S,body:b}}if(h.type==="WORD"&&e[s+1]&&e[s+1].type==="LPAREN"&&e[s+2]&&e[s+2].type==="RPAREN"){const m=r().raw;r(),r(),i();const S=a(d);return{type:"FunctionDef",name:m,body:S}}const u=[],p=[],g=[];for(;s<e.length;){const m=t();if(!m)break;if(p.length>=1&&p[0].raw==="[["){if(m.type==="WORD"&&m.raw==="]]"){p.push(r());break}if(m.type==="SEMICOLON")break;const S=r();if(S.type==="WORD")p.push(S);else{const b=S.raw||S.op||"";p.push({type:"WORD",segments:[{type:"literal",value:b}],raw:b,hasWildcard:!1})}continue}if(m.type==="PIPE"||m.type==="AND"||m.type==="OR"||m.type==="SEMICOLON"||m.type==="DSEMI"||m.type==="BACKGROUND"||m.type==="LPAREN"||m.type==="RPAREN")break;if(m.type==="REDIRECT"){if(r(),m.op==="<<"){g.push({type:"<<",sourceFd:m.sourceFd,body:m.body,quoted:m.quoted,stripTabs:m.stripTabs});continue}const S=t();let b=null;S&&S.type==="WORD"&&(b=r()),g.push({type:m.op,sourceFd:m.sourceFd,target:b});continue}if(m.type==="REDIRECT_FD"){r(),g.push({type:">&",sourceFd:m.sourceFd,targetFd:m.targetFd});continue}if(m.type==="WORD"){if(p.length===0&&m.raw.includes("=")){const S=m.raw.indexOf("="),b=m.raw.slice(0,S);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(b)){u.push({key:b,rawVal:m.raw.slice(S+1),token:m}),r();continue}}p.push(r());continue}r()}return p.length===0&&u.length===0&&g.length===0?null:{type:"Command",name:p[0]||null,args:p.slice(1),envVars:u,redirects:g}}return f([])}function Ge(){const n=new Map,e=new Set(["/","/tmp","/workspace","/etc","/home","/home/user","/home/codelab"]);let s="",t="/workspace";function r(i){const f=String(i);if(f.startsWith("/"))return j.normalize(f);const c=t&&t.startsWith("/")?t:"/workspace";return j.normalize(c.endsWith("/")?c+f:c+"/"+f)}return{...{_listeners:new Map,on(i,f){this._listeners.has(i)||this._listeners.set(i,[]),this._listeners.get(i).push(f)},emit(i,...f){const c=this._listeners.get(i)||[];for(const y of c)y(...f)}},existsSync(i){const f=r(i);return e.has(f)||n.has(f)},statSync(i){const f=r(i);if(e.has(f))return{size:0,mtimeMs:Date.now(),isDirectory:()=>!0,isFile:()=>!1,isSymbolicLink:()=>!1,mode:16877};const c=n.get(f);if(c)return{size:c.data.length,mtimeMs:c.mtimeMs,isDirectory:()=>!1,isFile:()=>!0,isSymbolicLink:()=>!!c.symlinkTarget,symlinkTarget:c.symlinkTarget||null,mode:c.mode!==void 0?c.mode:33188};const y=new Error(`ENOENT: no such file or directory, stat '${i}'`);throw y.code="ENOENT",y},lstatSync(i){return this.statSync(i)},symlinkSync(i,f){const c=r(f),y=r(i),l=n.has(y)?n.get(y).data:"";n.set(c,{data:l,mtimeMs:Date.now(),mode:41471,symlinkTarget:i})},chmodSync(i,f){const c=r(i);if(e.has(c))return;const y=n.get(c);if(!y){const d=new Error(`ENOENT: no such file or directory, chmod '${i}'`);throw d.code="ENOENT",d}const l=typeof f=="string"?parseInt(f,8):Number(f),a=(y.mode!==void 0?y.mode:33188)&-512;y.mode=a|l&511},readdirSync(i){const f=r(i);if(!e.has(f)){const l=new Error(`ENOTDIR: not a directory, scandir '${i}'`);throw l.code="ENOTDIR",l}const c=f==="/"?"/":f+"/",y=new Set;for(const l of e)if(l!==f&&l.startsWith(c)){const a=l.slice(c.length).split("/")[0];a&&y.add(a)}for(const l of n.keys())if(l.startsWith(c)){const a=l.slice(c.length);a.includes("/")||y.add(a)}return Array.from(y).sort()},readFileSync(i,f){if(i===0||i==="/dev/stdin")return!f||f==="buffer"?new TextEncoder().encode(s):s;const c=r(i),y=n.get(c);if(!y){const l=new Error(`ENOENT: no such file or directory, open '${i}'`);throw l.code="ENOENT",l}return!f&&y.rawBytes instanceof Uint8Array?y.rawBytes:y.data},_setActiveStdin(i){s=i==null?"":String(i)},_setCwd(i){i&&typeof i=="string"&&(t=j.normalize(i))},_getRawFileBytes(i){const f=r(i),c=n.get(f);return c&&c.rawBytes instanceof Uint8Array?c.rawBytes:null},_getAllRawFiles(){const i={};for(const[f,c]of n.entries())c&&c.rawBytes instanceof Uint8Array&&(i[f]=c.rawBytes);return i},writeFileSync(i,f){const c=r(i),y=j.dirname(c);if(!e.has(y)){const u=y.split("/").filter(Boolean);let p="";for(const g of u)p+="/"+g,e.add(p)}const l=f instanceof Uint8Array,a=l?new Uint8Array(f.buffer,f.byteOffset,f.byteLength):null,d=l?new TextDecoder("utf-8").decode(a):typeof f=="string"?f:f&&f.toString?f.toString("utf8"):String(f),h=n.has(c)?n.get(c).mode:33188;n.set(c,{data:d,rawBytes:a,mtimeMs:Date.now(),mode:h})},appendFileSync(i,f){const c=r(i),y=n.has(c)?n.get(c).data:"",l=typeof f=="string"?f:f.toString?f.toString("utf8"):String(f);this.writeFileSync(c,y+l)},mkdirSync(i,f={}){const c=r(i),y=!!(f&&f.recursive);if(n.has(c))throw new Error(`EEXIST: file already exists, mkdir '${i}'`);if(e.has(c))return;const l=j.dirname(c);if(!e.has(l)){if(!y)throw new Error(`ENOENT: no such file or directory, mkdir '${i}'`);const a=c.split("/").filter(Boolean);let d="";for(const h of a)d+="/"+h,e.add(d);return}e.add(c)},rmdirSync(i,f={}){const c=r(i),y=!!(f&&f.recursive);if(!e.has(c)){const l=new Error(`ENOENT: no such file or directory, rmdir '${i}'`);throw l.code="ENOENT",l}if(!y){const l=c==="/"?"/":c+"/";for(const a of n.keys())if(a.startsWith(l)){const d=new Error(`ENOTEMPTY: directory not empty, rmdir '${i}'`);throw d.code="ENOTEMPTY",d}for(const a of e)if(a!==c&&a.startsWith(l)){const d=new Error(`ENOTEMPTY: directory not empty, rmdir '${i}'`);throw d.code="ENOTEMPTY",d}c!=="/"&&c!=="/workspace"&&c!=="/tmp"&&e.delete(c);return}this.rmSync(i,{...f,recursive:!0})},unlinkSync(i){const f=r(i);if(!n.has(f))throw new Error(`ENOENT: no such file or directory, unlink '${i}'`);n.delete(f)},rmSync(i,f={}){const c=r(i),y=!!(f&&f.recursive),l=!!(f&&f.force);if(n.has(c)){n.delete(c);return}if(e.has(c)){if(!y){const d=new Error(`EISDIR: illegal operation on a directory, rm '${i}'`);throw d.code="EISDIR",d}const a=c==="/"?"/":c+"/";for(const d of Array.from(n.keys()))d.startsWith(a)&&n.delete(d);for(const d of Array.from(e))d.startsWith(a)&&d!=="/"&&d!=="/workspace"&&d!=="/tmp"&&e.delete(d);c!=="/"&&c!=="/workspace"&&c!=="/tmp"&&e.delete(c);return}if(!l)throw new Error(`ENOENT: no such file or directory, rm '${i}'`)},renameSync(i,f){const c=r(i),y=r(f);if(n.has(c))n.set(y,n.get(c)),n.delete(c);else if(e.has(c)){const l=c==="/"?"/":c+"/";e.add(y),c!=="/"&&c!=="/workspace"&&c!=="/tmp"&&e.delete(c);for(const a of Array.from(e))a.startsWith(l)&&(e.add(y+"/"+a.slice(l.length)),e.delete(a));for(const[a,d]of Array.from(n.entries()))a.startsWith(l)&&(n.set(y+"/"+a.slice(l.length),d),n.delete(a))}else throw new Error(`ENOENT: no such file or directory, rename '${i}' -> '${f}'`)},copyFileSync(i,f){const c=r(i),y=r(f);if(!n.has(c))throw new Error(`ENOENT: no such file or directory, copy '${i}'`);const l=n.get(c),a=l.rawBytes instanceof Uint8Array?new Uint8Array(l.rawBytes):null;n.set(y,{data:l.data,rawBytes:a,mtimeMs:Date.now(),mode:l.mode!==void 0?l.mode:33188})}}}function de(n,e,s,t){const r=$e();if(r&&typeof r.computeUnifiedHunkDiff=="function"){const u=r.computeUnifiedHunkDiff(n,e,s,t,3);return u?u.endsWith(`
|
|
188
|
+
`,g===s){r=s;break}p=g+1}}e.push({type:"REDIRECT",op:"<<",sourceFd:0,stripTabs:l,quoted:c,body:u,delim:a,raw:l?"<<-":"<<"});continue}e.push({type:"REDIRECT",op:"<",sourceFd:0,raw:"<"}),t++;continue}const i=[];let f="",d=!1,y=!1;for(;t<s;){const l=n[t];if(/\s/.test(l)||l==="|"||l==="&"||l===";"||l==="<"||l===">"||l==="("||l===")")break;if(l==="'"){t++;let a="";for(;t<s&&n[t]!=="'";)a+=n[t],t++;t<s&&n[t]==="'"&&t++,i.push({type:"single_quoted",value:a}),f+=`'${a}'`;continue}if(l==='"'){const a=t;t++;const c=[];let h="";for(;t<s&&n[t]!=='"';){const u=n[t];if(u==="\\"&&t+1<s){const p=n[t+1];if(p==='"'||p==="\\"||p==="$"||p==="`"){h+=p,t+=2;continue}if(p==="n"){h+=`
|
|
189
|
+
`,t+=2;continue}if(p==="t"){h+=" ",t+=2;continue}h+="\\"+p,t+=2;continue}if(u==="$"&&n[t+1]==="("&&n[t+2]==="("){h&&(c.push({type:"literal",value:h}),h=""),t+=3;let p=2,g="";for(;t<s&&p>0;)if(n[t]==="(")p++,g+="(",t++;else if(n[t]===")"){if(p===2&&n[t+1]===")"){p=0,t+=2;break}p--,p>0&&(g+=")"),t++}else g+=n[t++];c.push({type:"arith",expr:g});continue}if(u==="$"&&n[t+1]==="("){h&&(c.push({type:"literal",value:h}),h=""),t+=2;let p=1,g="";for(;t<s&&p>0;)n[t]==="("?p++:n[t]===")"&&p--,p>0&&(g+=n[t]),t++;c.push({type:"subshell",command:g});continue}if(u==="`"){h&&(c.push({type:"literal",value:h}),h=""),t++;let p="";for(;t<s&&n[t]!=="`";)p+=n[t++];t<s&&n[t]==="`"&&t++,c.push({type:"subshell",command:p});continue}if(u==="$"){if(h&&(c.push({type:"literal",value:h}),h=""),t++,n[t]==="{"){t++;let p="",g=1;for(;t<s&&g>0;)n[t]==="{"?g++:n[t]==="}"&&g--,g>0&&(p+=n[t]),t++;c.push({type:"variable",name:p})}else if(/[0-9?!$#@*]/.test(n[t])){const p=n[t++];c.push({type:"variable",name:p})}else if(/[a-zA-Z_]/.test(n[t])){let p="";for(;t<s&&/[a-zA-Z0-9_]/.test(n[t]);)p+=n[t++];c.push({type:"variable",name:p})}else h+="$";continue}h+=u,t++}t<s&&n[t]==='"'&&t++,h&&c.push({type:"literal",value:h}),i.push({type:"double_quoted",parts:c}),f+=n.slice(a,t);continue}if(l==="\\"&&t+1<s){i.push({type:"literal",value:n[t+1],escaped:!0}),f+="\\"+n[t+1],t+=2;continue}if(l==="$"&&n[t+1]==="("&&n[t+2]==="("){t+=3;let a=2,c="";for(;t<s&&a>0;)if(n[t]==="(")a++,c+="(",t++;else if(n[t]===")"){if(a===2&&n[t+1]===")"){a=0,t+=2;break}a--,a>0&&(c+=")"),t++}else c+=n[t++];i.push({type:"arith",expr:c}),f+=`$((${c}))`;continue}if(l==="$"&&n[t+1]==="("){t+=2;let a=1,c="";for(;t<s&&a>0;)n[t]==="("?a++:n[t]===")"&&a--,a>0&&(c+=n[t]),t++;i.push({type:"subshell",command:c}),f+=`$(${c})`;continue}if(l==="`"){t++;let a="";for(;t<s&&n[t]!=="`";)a+=n[t],t++;t<s&&n[t]==="`"&&t++,i.push({type:"subshell",command:a}),f+=`\`${a}\``;continue}if(l==="$"){if(t++,n[t]==="{"){t++;let a="",c=1;for(;t<s&&c>0;)n[t]==="{"?c++:n[t]==="}"&&c--,c>0&&(a+=n[t]),t++;i.push({type:"variable",name:a}),f+=`\${${a}}`}else if(/[0-9?!$#@*]/.test(n[t])){const a=n[t++];i.push({type:"variable",name:a}),f+=`$${a}`}else if(/[a-zA-Z_]/.test(n[t])){let a="";for(;t<s&&/[a-zA-Z0-9_]/.test(n[t]);)a+=n[t++];i.push({type:"variable",name:a}),f+=`$${a}`}else i.push({type:"literal",value:"$"}),f+="$";continue}(l==="*"||l==="?"||l==="[")&&(d=!0),(l==="{"||l==="}")&&(y=!0),i.push({type:"literal",value:l}),f+=l,t++}e.push({type:"WORD",segments:i,raw:f,hasWildcard:d,hasBraces:y})}return e}function Ce(n){const e=typeof n=="string"?Te(n):n;let s=0;function t(){return e[s]||null}function r(){return e[s++]||null}function o(c,...h){return!!(c&&c.type==="WORD"&&h.includes(c.raw))}function i(){for(;t()&&t().type==="SEMICOLON";)r()}function f(c=[]){const h=[];for(;s<e.length;){i();const u=t();if(!u||u.type==="RPAREN"||u.type==="DSEMI"||c.length>0&&o(u,...c))break;const p=d(c);if(!p)break;let g=!1;t()&&t().type==="BACKGROUND"?(r(),g=!0):t()&&t().type==="SEMICOLON"&&r(),h.push({node:p,background:g})}return{type:"Sequence",items:h}}function d(c=[]){let h=y(c);if(!h)return null;for(;t()&&(t().type==="AND"||t().type==="OR");){const u=r();i();const p=y(c);if(!p)break;h={type:"Logical",op:u.type==="AND"?"&&":"||",left:h,right:p}}return h}function y(c=[]){let h=!1;o(t(),"!")&&(r(),h=!0);const u=[],p=a(c);if(!p)return null;for(u.push(p);t()&&t().type==="PIPE";){r(),i();const g=a(c);g&&u.push(g)}return u.length===1&&!h?u[0]:{type:"Pipeline",negated:h,commands:u}}function l(){const c=[];for(;t()&&(t().type==="REDIRECT"||t().type==="REDIRECT_FD");){const h=r();if(h.type==="REDIRECT")if(h.op==="<<")c.push({type:"<<",sourceFd:h.sourceFd,body:h.body,quoted:h.quoted,stripTabs:h.stripTabs});else{let u=null;t()&&t().type==="WORD"&&(u=r()),c.push({type:h.op,sourceFd:h.sourceFd,target:u})}else c.push({type:">&",sourceFd:h.sourceFd,targetFd:h.targetFd})}return c}function a(c=[]){const h=t();if(!h||h.type==="RPAREN"||h.type==="DSEMI"||c.length>0&&o(h,...c))return null;if(h.type==="LPAREN"){r();const m=f([]);return t()&&t().type==="RPAREN"&&r(),{type:"Subshell",body:m,redirects:l()}}if(o(h,"{")){r();const m=f(["}"]);return o(t(),"}")&&r(),{type:"BraceGroup",body:m,redirects:l()}}if(o(h,"if")){r();const m=[],S=f(["then"]);o(t(),"then")&&r();const b=f(["elif","else","fi"]);for(m.push({cond:S,body:b});o(t(),"elif");){r();const w=f(["then"]);o(t(),"then")&&r();const $=f(["elif","else","fi"]);m.push({cond:w,body:$})}let v=null;return o(t(),"else")&&(r(),v=f(["fi"])),o(t(),"fi")&&r(),{type:"If",branches:m,elseBody:v,redirects:l()}}if(o(h,"for")){r();const m=r(),S=m?m.raw:"i";let b=null;if(o(t(),"in"))for(r(),b=[];t()&&t().type==="WORD"&&!o(t(),"do");)b.push(r());i(),o(t(),"do")&&r();const v=f(["done"]);return o(t(),"done")&&r(),{type:"For",varName:S,items:b,body:v,redirects:l()}}if(o(h,"while","until")){const m=r().raw,S=f(["do"]);o(t(),"do")&&r();const b=f(["done"]);return o(t(),"done")&&r(),{type:m==="while"?"While":"Until",cond:S,body:b,redirects:l()}}if(o(h,"case")){r();const m=r();i(),o(t(),"in")&&r(),i();const S=[];for(;s<e.length&&!o(t(),"esac")&&(i(),!o(t(),"esac"));){t()&&t().type==="LPAREN"&&r();const b=[];for(;s<e.length&&t().type!=="RPAREN"&&!o(t(),"esac");){if(t().type==="PIPE"){r();continue}b.push(r())}t()&&t().type==="RPAREN"&&r();const v=f(["esac"]);t()&&t().type==="DSEMI"&&r(),i(),S.push({patterns:b,body:v})}return o(t(),"esac")&&r(),{type:"Case",word:m,clauses:S,redirects:l()}}if(o(h,"function")){r();const m=r(),S=m?m.raw:"";t()&&t().type==="LPAREN"&&(r(),t()&&t().type==="RPAREN"&&r()),i();const b=a(c);return{type:"FunctionDef",name:S,body:b}}if(h.type==="WORD"&&e[s+1]&&e[s+1].type==="LPAREN"&&e[s+2]&&e[s+2].type==="RPAREN"){const m=r().raw;r(),r(),i();const S=a(c);return{type:"FunctionDef",name:m,body:S}}const u=[],p=[],g=[];for(;s<e.length;){const m=t();if(!m)break;if(p.length>=1&&p[0].raw==="[["){if(m.type==="WORD"&&m.raw==="]]"){p.push(r());break}if(m.type==="SEMICOLON")break;const S=r();if(S.type==="WORD")p.push(S);else{const b=S.raw||S.op||"";p.push({type:"WORD",segments:[{type:"literal",value:b}],raw:b,hasWildcard:!1})}continue}if(m.type==="PIPE"||m.type==="AND"||m.type==="OR"||m.type==="SEMICOLON"||m.type==="DSEMI"||m.type==="BACKGROUND"||m.type==="LPAREN"||m.type==="RPAREN")break;if(m.type==="REDIRECT"){if(r(),m.op==="<<"){g.push({type:"<<",sourceFd:m.sourceFd,body:m.body,quoted:m.quoted,stripTabs:m.stripTabs});continue}const S=t();let b=null;S&&S.type==="WORD"&&(b=r()),g.push({type:m.op,sourceFd:m.sourceFd,target:b});continue}if(m.type==="REDIRECT_FD"){r(),g.push({type:">&",sourceFd:m.sourceFd,targetFd:m.targetFd});continue}if(m.type==="WORD"){if(p.length===0&&m.raw.includes("=")){const S=m.raw.indexOf("="),b=m.raw.slice(0,S);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(b)){u.push({key:b,rawVal:m.raw.slice(S+1),token:m}),r();continue}}p.push(r());continue}r()}return p.length===0&&u.length===0&&g.length===0?null:{type:"Command",name:p[0]||null,args:p.slice(1),envVars:u,redirects:g}}return f([])}function Ze(){const n=new Map,e=new Set(["/","/tmp","/workspace","/etc","/home","/home/user","/home/codelab"]);let s="",t="/workspace";function r(i){const f=String(i);if(f.startsWith("/"))return j.normalize(f);const d=t&&t.startsWith("/")?t:"/workspace";return j.normalize(d.endsWith("/")?d+f:d+"/"+f)}return{...{_listeners:new Map,on(i,f){this._listeners.has(i)||this._listeners.set(i,[]),this._listeners.get(i).push(f)},emit(i,...f){const d=this._listeners.get(i)||[];for(const y of d)y(...f)}},existsSync(i){const f=r(i);return e.has(f)||n.has(f)},statSync(i){const f=r(i);if(e.has(f))return{size:0,mtimeMs:Date.now(),isDirectory:()=>!0,isFile:()=>!1,isSymbolicLink:()=>!1,mode:16877};const d=n.get(f);if(d)return{size:d.data.length,mtimeMs:d.mtimeMs,isDirectory:()=>!1,isFile:()=>!0,isSymbolicLink:()=>!!d.symlinkTarget,symlinkTarget:d.symlinkTarget||null,mode:d.mode!==void 0?d.mode:33188};const y=new Error(`ENOENT: no such file or directory, stat '${i}'`);throw y.code="ENOENT",y},lstatSync(i){return this.statSync(i)},symlinkSync(i,f){const d=r(f),y=r(i),l=n.has(y)?n.get(y).data:"";n.set(d,{data:l,mtimeMs:Date.now(),mode:41471,symlinkTarget:i})},chmodSync(i,f){const d=r(i);if(e.has(d))return;const y=n.get(d);if(!y){const c=new Error(`ENOENT: no such file or directory, chmod '${i}'`);throw c.code="ENOENT",c}const l=typeof f=="string"?parseInt(f,8):Number(f),a=(y.mode!==void 0?y.mode:33188)&-512;y.mode=a|l&511},readdirSync(i){const f=r(i);if(!e.has(f)){const l=new Error(`ENOTDIR: not a directory, scandir '${i}'`);throw l.code="ENOTDIR",l}const d=f==="/"?"/":f+"/",y=new Set;for(const l of e)if(l!==f&&l.startsWith(d)){const a=l.slice(d.length).split("/")[0];a&&y.add(a)}for(const l of n.keys())if(l.startsWith(d)){const a=l.slice(d.length);a.includes("/")||y.add(a)}return Array.from(y).sort()},readFileSync(i,f){if(i===0||i==="/dev/stdin")return!f||f==="buffer"?new TextEncoder().encode(s):s;const d=r(i),y=n.get(d);if(!y){const l=new Error(`ENOENT: no such file or directory, open '${i}'`);throw l.code="ENOENT",l}return!f&&y.rawBytes instanceof Uint8Array?y.rawBytes:y.data},_setActiveStdin(i){s=i==null?"":String(i)},_setCwd(i){i&&typeof i=="string"&&(t=j.normalize(i))},_getRawFileBytes(i){const f=r(i),d=n.get(f);return d&&d.rawBytes instanceof Uint8Array?d.rawBytes:null},_getAllRawFiles(){const i={};for(const[f,d]of n.entries())d&&d.rawBytes instanceof Uint8Array&&(i[f]=d.rawBytes);return i},writeFileSync(i,f){const d=r(i),y=j.dirname(d);if(!e.has(y)){const u=y.split("/").filter(Boolean);let p="";for(const g of u)p+="/"+g,e.add(p)}const l=f instanceof Uint8Array,a=l?new Uint8Array(f.buffer,f.byteOffset,f.byteLength):null,c=l?new TextDecoder("utf-8").decode(a):typeof f=="string"?f:f&&f.toString?f.toString("utf8"):String(f),h=n.has(d)?n.get(d).mode:33188;n.set(d,{data:c,rawBytes:a,mtimeMs:Date.now(),mode:h})},appendFileSync(i,f){const d=r(i),y=n.has(d)?n.get(d).data:"",l=typeof f=="string"?f:f.toString?f.toString("utf8"):String(f);this.writeFileSync(d,y+l)},mkdirSync(i,f={}){const d=r(i),y=!!(f&&f.recursive);if(n.has(d))throw new Error(`EEXIST: file already exists, mkdir '${i}'`);if(e.has(d))return;const l=j.dirname(d);if(!e.has(l)){if(!y)throw new Error(`ENOENT: no such file or directory, mkdir '${i}'`);const a=d.split("/").filter(Boolean);let c="";for(const h of a)c+="/"+h,e.add(c);return}e.add(d)},rmdirSync(i,f={}){const d=r(i),y=!!(f&&f.recursive);if(!e.has(d)){const l=new Error(`ENOENT: no such file or directory, rmdir '${i}'`);throw l.code="ENOENT",l}if(!y){const l=d==="/"?"/":d+"/";for(const a of n.keys())if(a.startsWith(l)){const c=new Error(`ENOTEMPTY: directory not empty, rmdir '${i}'`);throw c.code="ENOTEMPTY",c}for(const a of e)if(a!==d&&a.startsWith(l)){const c=new Error(`ENOTEMPTY: directory not empty, rmdir '${i}'`);throw c.code="ENOTEMPTY",c}d!=="/"&&d!=="/workspace"&&d!=="/tmp"&&e.delete(d);return}this.rmSync(i,{...f,recursive:!0})},unlinkSync(i){const f=r(i);if(!n.has(f))throw new Error(`ENOENT: no such file or directory, unlink '${i}'`);n.delete(f)},rmSync(i,f={}){const d=r(i),y=!!(f&&f.recursive),l=!!(f&&f.force);if(n.has(d)){n.delete(d);return}if(e.has(d)){if(!y){const c=new Error(`EISDIR: illegal operation on a directory, rm '${i}'`);throw c.code="EISDIR",c}const a=d==="/"?"/":d+"/";for(const c of Array.from(n.keys()))c.startsWith(a)&&n.delete(c);for(const c of Array.from(e))c.startsWith(a)&&c!=="/"&&c!=="/workspace"&&c!=="/tmp"&&e.delete(c);d!=="/"&&d!=="/workspace"&&d!=="/tmp"&&e.delete(d);return}if(!l)throw new Error(`ENOENT: no such file or directory, rm '${i}'`)},renameSync(i,f){const d=r(i),y=r(f);if(n.has(d))n.set(y,n.get(d)),n.delete(d);else if(e.has(d)){const l=d==="/"?"/":d+"/";e.add(y),d!=="/"&&d!=="/workspace"&&d!=="/tmp"&&e.delete(d);for(const a of Array.from(e))a.startsWith(l)&&(e.add(y+"/"+a.slice(l.length)),e.delete(a));for(const[a,c]of Array.from(n.entries()))a.startsWith(l)&&(n.set(y+"/"+a.slice(l.length),c),n.delete(a))}else throw new Error(`ENOENT: no such file or directory, rename '${i}' -> '${f}'`)},copyFileSync(i,f){const d=r(i),y=r(f);if(!n.has(d))throw new Error(`ENOENT: no such file or directory, copy '${i}'`);const l=n.get(d),a=l.rawBytes instanceof Uint8Array?new Uint8Array(l.rawBytes):null;n.set(y,{data:l.data,rawBytes:a,mtimeMs:Date.now(),mode:l.mode!==void 0?l.mode:33188})}}}function de(n,e,s,t){const r=je();if(r&&typeof r.computeUnifiedHunkDiff=="function"){const u=r.computeUnifiedHunkDiff(n,e,s,t,3);return u?u.endsWith(`
|
|
190
190
|
`)?u:u+`
|
|
191
191
|
`:""}const o=s.length>0?s.split(`
|
|
192
192
|
`):[],i=t.length>0?t.split(`
|
|
193
|
-
`):[],f=o.length,
|
|
193
|
+
`):[],f=o.length,d=i.length,y=Array.from({length:f+1},()=>new Int32Array(d+1));for(let u=1;u<=f;u++)for(let p=1;p<=d;p++)o[u-1]===i[p-1]?y[u][p]=y[u-1][p-1]+1:y[u][p]=Math.max(y[u-1][p],y[u][p-1]);const l=[];let a=f,c=d;for(;a>0||c>0;)a>0&&c>0&&o[a-1]===i[c-1]?(l.push({type:"common",line:o[a-1]}),a--,c--):c>0&&(a===0||y[a][c-1]>=y[a-1][c])?(l.push({type:"added",line:i[c-1]}),c--):a>0&&(c===0||y[a][c-1]<y[a-1][c])&&(l.push({type:"removed",line:o[a-1]}),a--);if(l.reverse(),!l.some(u=>u.type!=="common"))return"";let h=`--- ${n}
|
|
194
194
|
+++ ${e}
|
|
195
|
-
@@ -1,${f} +1,${
|
|
195
|
+
@@ -1,${f} +1,${d} @@
|
|
196
196
|
`;for(const u of l)u.type==="common"?h+=` ${u.line}
|
|
197
197
|
`:u.type==="added"?h+=`+${u.line}
|
|
198
198
|
`:u.type==="removed"&&(h+=`-${u.line}
|
|
199
|
-
`);return h}function fe(n){if(!n||typeof n!="string")return null;let e=n.trim();if(!e)return null;let s=null,t=null,r=null,o=null;const i=e.indexOf("#");if(i!==-1){const l=e.slice(i+1).trim();e=e.slice(0,i).trim(),l&&(r=l)}const f=e.match(/^git@github\.com:([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/);if(f)return s=f[1],t=f[2],{owner:s,repo:t,branch:r,subpath:null,fullName:`${s}/${t}`,httpsUrl:`https://github.com/${s}/${t}`,gitUrl:`https://github.com/${s}/${t}.git`,url:`https://github.com/${s}/${t}.git`};const c=e.match(/^(?:https?:\/\/)?(?:www\.)?github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?(?:\/(tree|blob)\/([^/]+)(?:\/(.+?))?)?\/?$/);if(c){s=c[1],t=c[2];const l=c[4]?c[5]?`${c[4]}/${c[5].replace(/^\/+|\/+$/g,"")}`:c[4]:null;return l&&/^(?:feature|feat|fix|bugfix|hotfix|release|chore|refactor|docs|test|ci|depend|dependabot)\/[^/]+$/.test(l)&&!r?(r=l,o=null):(r=c[4]||r||null,o=c[5]?c[5].replace(/^\/+|\/+$/g,""):null),{owner:s,repo:t,branch:r,subpath:o,rawTreeTail:l,fullName:`${s}/${t}`,httpsUrl:`https://github.com/${s}/${t}`,gitUrl:`https://github.com/${s}/${t}.git`,url:`https://github.com/${s}/${t}.git`}}const y=e.match(/^([A-Za-z0-9_-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?(?:@([A-Za-z0-9_./-]+))?$/);return y&&!y[1].startsWith("-")?(s=y[1],t=y[2],r=y[3]||r||null,{owner:s,repo:t,branch:r,subpath:null,fullName:`${s}/${t}`,httpsUrl:`https://github.com/${s}/${t}`,gitUrl:`https://github.com/${s}/${t}.git`,url:`https://github.com/${s}/${t}.git`}):null}function L(n,e){const s={};if(!n||!e||!n.existsSync(e))return s;const t=j.normalize(e);function r(o){let i=[];try{i=n.readdirSync(o)}catch{return}for(const f of i){if(f===".git"||f==="node_modules")continue;const c=j.join(o,f);let y;try{y=n.statSync(c)}catch{continue}if(y.isDirectory())r(c);else{const l=c.startsWith(t==="/"?"/":t+"/")?c.slice(t==="/"?1:t.length+1):f;try{s[l]=String(n.readFileSync(c,"utf8"))}catch(a){N.debug("Skipped unreadable VFS file in snapshot.",c,a)}}}}return r(t),s}function re(n){const e=String(n||"");let s=3735928559^e.length,t=1103547991^e.length;for(let o=0;o<e.length;o++){const i=e.charCodeAt(o);s=Math.imul(s^i,2654435761),t=Math.imul(t^i,1597334677)}return s=Math.imul(s^s>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),t=Math.imul(t^t>>>16,2246822507)^Math.imul(s^s>>>13,3266489909),(4294967296*(2097151&t)+(s>>>0)).toString(16).padStart(7,"0").slice(0,7)}function ee(n,e){if(!n||typeof n!="string")return"";let s=n.trim().replace(/\\/g,"/");if(!s)return"";const t=j.normalize(e||"/workspace"),r=t==="/"?"/":t+"/";if(s===t)return"";for(s.startsWith(r)?s=s.slice(r.length):s.startsWith("/workspace/")&&(s=s.slice(11));s.startsWith("./");)s=s.slice(2);s.startsWith("/")&&(s=s.replace(/^\/+/,""));const o=[];for(const f of s.split("/"))if(!(!f||f===".")){if(f===".."){if(o.length===0)return"";o.pop();continue}o.push(f)}const i=o.join("/");return!i||i===".git"||i.startsWith(".git/")||i.includes("/.git/")||i.endsWith("/.git")||i==="node_modules"||i.startsWith("node_modules/")||i.includes("/node_modules/")||i.endsWith("/node_modules")?"":i}function oe(n){return(!Array.isArray(n&&n.commits)||n.commits.length===0)&&!(n&&n.headCommit)}function ue(n,e,s,t){if(!e)return!1;const r=t||n&&(n.headSnapshot||n.headFiles)||{},o=Object.prototype.hasOwnProperty.call(r,e),i=s==null?null:String(s);return i===null?o:!o||oe(n)?!0:i!==r[e]}function K(n,e,s,t,r){const o=n&&n.repoRoot||"/workspace",i=ee(s,o);if(!i)return;const f=t==null?null:String(t);ue(n,i,f,r)?e.set(i,f):e.delete(i)}function Y(n,e,s){if(!(e instanceof Map))return;const t=n&&n.repoRoot||"/workspace",r=s||n&&(n.headSnapshot||n.headFiles)||{};for(const[o,i]of Array.from(e.entries())){const f=ee(o,t);if(f!==o&&e.delete(o),!f){e.delete(o);continue}const c=i==null?null:String(i);ue(n,f,c,r)?e.set(f,c):e.delete(f)}}function Ze(n,e){if(!n||!n._initialBootSnapshot||!n._initialBootRoot)return{};const s=j.normalize(e),t=n._initialBootRoot;if(s===t)return n._initialBootSnapshot;const r=t==="/"?"/":t+"/";if(s.startsWith(r)){const o=s.slice(r.length)+"/",i={};for(const[f,c]of Object.entries(n._initialBootSnapshot))f.startsWith(o)&&(i[f.slice(o.length)]=c);return i}return{}}function Q(n,e,s,t){return n instanceof Map&&(n._hasShellStagedShim||(Object.defineProperty(n,"_hasShellStagedShim",{value:!0,enumerable:!1,configurable:!0,writable:!0}),Object.defineProperty(n,"add",{value(r){const o=typeof t=="function"?t():null,i=typeof s=="function"?s():o&&o.repoRoot||"/workspace",f=ee(r,i);if(!f)return n;let c=null;if(e&&typeof e.existsSync=="function"){const y=j.join(i,f);if(e.existsSync(y)){if(typeof e.statSync=="function")try{if(e.statSync(y).isDirectory())return n}catch(l){N.debug("Failed statting staged path in VFS.",y,l)}if(typeof e.readFileSync=="function")try{c=String(e.readFileSync(y,"utf8"))}catch(l){return N.debug("Failed reading staged file from VFS.",y,l),n}}}return o?K(o,n,f,c):n.set(f,c),n},enumerable:!1,configurable:!0,writable:!0}))),n}function Ke(n,e,s){const t=()=>n&&n.repoRoot||s||"/workspace",r=()=>n;if(n.staged instanceof Map)return Q(n.staged,e,t,r),Y(n,n.staged),n.stagedFiles=n.staged,n.staged;const o=Q(new Map,e,t,r);if(n.staged&&typeof n.staged[Symbol.iterator]=="function")for(const i of n.staged)Array.isArray(i)&&i.length>=2?K(n,o,i[0],i[1]===null?null:String(i[1])):typeof i=="string"&&o.add(i);return n.staged=o,n.stagedFiles=o,o}function Xe(n,e){if(!n||typeof n.existsSync!="function"||typeof n.readFileSync!="function")return null;const s=[j.join(e,".git/HEAD"),"/workspace/.git/HEAD"];for(const t of s)if(n.existsSync(t))try{const r=String(n.readFileSync(t,"utf8")).trim(),o=/^ref:\s*refs\/heads\/([^\s]+)$/.exec(r);if(o&&o[1])return o[1]}catch(r){N.debug("Could not parse .git/HEAD branch.",t,r)}return null}function Ye(n,e,s={}){const t=j.normalize(e||"/workspace"),r=!!(n&&typeof n.existsSync=="function"&&(n.existsSync(j.join(t,".git"))||n.existsSync(j.join(t,".git/HEAD"))||n.existsSync("/workspace/.git")||n.existsSync("/workspace/.git/HEAD")));let o=!!(s.gitInitialized===!0||r),i=t;const c=(r?Xe(n,t):null)||"main";let y=o?L(n,t):{},l=o?re(JSON.stringify(y)+":init"):"";const a=Date.now();let d=o?[{hash:l,author:"CodeLab Developer <dev@codelab.internal>",date:new Date(a).toUTCString(),timestamp:a,message:"Initial commit",files:Object.assign({},y)}]:[];const h={branch:c,branches:new Set([c]),remoteUrl:null,remotes:{}};let u=Q(new Map,n,()=>i,()=>h);return Object.defineProperties(h,{initialized:{enumerable:!0,configurable:!0,get(){if(o)return!0;const p=i||t;return n&&typeof n.existsSync=="function"&&(n.existsSync(j.join(p,".git"))||n.existsSync(j.join(p,".git/HEAD")))?(o=!0,!0):!1},set(p){o=!!p}},repoRoot:{enumerable:!0,configurable:!0,get(){return i},set(p){i=j.normalize(String(p||t))}},headCommit:{enumerable:!0,configurable:!0,get(){return l},set(p){l=String(p||"")}},headSnapshot:{enumerable:!0,configurable:!0,get(){return y},set(p){y=p&&typeof p=="object"?p:{}}},headFiles:{enumerable:!0,configurable:!0,get(){return y},set(p){y=p&&typeof p=="object"?p:{}}},staged:{enumerable:!0,configurable:!0,get(){return u},set(p){if(p instanceof Map)u=Q(p,n,()=>i,()=>h),Y(h,u);else{const g=Q(new Map,n,()=>i,()=>h);if(p&&typeof p[Symbol.iterator]=="function")for(const m of p)typeof m=="string"?g.add(m):Array.isArray(m)&&m.length>=2&&K(h,g,m[0],m[1]===null?null:String(m[1]));u=g}}},stagedFiles:{enumerable:!0,configurable:!0,get(){return u},set(p){p instanceof Map&&(u=Q(p,n,()=>i,()=>h),Y(h,u))}},commits:{enumerable:!0,configurable:!0,get(){return d},set(p){d=Array.isArray(p)?p:[],d.length>0&&d[0]&&d[0].hash?l=String(d[0].hash):d.length===0&&(l="")}}}),h}const Qe=/\.(png|jpg|jpeg|gif|webp|ico|bmp|tiff|woff|woff2|ttf|eot|otf|mp3|mp4|wav|ogg|webm|avi|mov|pdf|zip|tar|gz|tgz|bz2|7z|rar|exe|dll|so|dylib|wasm|pyc|pyo|class|jar|war|ear|bin|dat|iso|dmg|pkg|deb|rpm|o|a|lib|DS_Store)$/i;function xe(n){const e=n.toLowerCase(),s=j.basename(e),t=n.split("/").length;return s==="readme.md"||s==="package.json"||s==="cargo.toml"||s==="go.mod"||s==="pyproject.toml"?0:t===1&&/\.(js|ts|jsx|tsx|mjs|cjs|py|go|rs|json|md|yml|yaml|toml|sh)$/.test(e)?1:e.startsWith("src/")||e.startsWith("lib/")||e.startsWith("app/")?2+t*.1:e.startsWith("test/")||e.startsWith("tests/")||e.startsWith("examples/")?5+t*.1:10+t*.1}async function et(n,e,s={}){const t=typeof s.onProgress=="function"?s.onProgress:null;t&&t({phase:"connecting",message:`Connecting to repository '${n}'...`});const r=fe(n);if(!r)throw new Error(`fatal: repository '${n}' does not exist or is not a valid GitHub repository URL`);if(!e)throw new Error("fatal: virtual filesystem (vfs) is required to clone repository");const o=s.fetchImpl||(typeof fetch=="function"?fetch.bind(globalThis):null);if(!o)throw new Error("fatal: global fetch API is unavailable in this environment");const i=j.normalize(s.targetDir||"/workspace"),f=s.maxFiles||250,c=s.maxFileSize||512*1024,y=s.branch||r.branch||null,{owner:l,repo:a}=r,d=s.signal||null,h=()=>{if(d&&d.aborted){const T=new Error("fatal: clone cancelled (SIGINT)");throw T.name="AbortError",T}};h();let u=y,p=null,g=!1;t&&t({phase:"metadata",message:`Fetching repository metadata for ${l}/${a}...`});try{if(!u){const T=await o(`https://api.github.com/repos/${l}/${a}`,{headers:{Accept:"application/vnd.github.v3+json"},signal:d});if(T.status===404)g=!0;else if(T.ok){const k=await T.json();k&&k.default_branch&&(u=k.default_branch)}}if(!g){const T=Array.from(y?new Set([y,!s.branch&&r.rawTreeTail&&r.rawTreeTail!==y?r.rawTreeTail:null].filter(Boolean)):new Set([u,"main","master"].filter(Boolean)));for(const k of T){h();const O=await o(`https://api.github.com/repos/${l}/${a}/git/trees/${encodeURIComponent(k)}?recursive=1`,{headers:{Accept:"application/vnd.github.v3+json"},signal:d});if(O.ok){const F=await O.json();if(F&&Array.isArray(F.tree)){u=k,r.rawTreeTail&&k===r.rawTreeTail&&(r.subpath=null),p=F.tree.filter(P=>P&&P.type==="blob"&&P.path).map(P=>({path:P.path.replace(/^\/+/,""),size:P.size||0}));break}}}}}catch(T){N.debug("GitHub REST API tree fetch failed; falling back to jsDelivr.",T)}if(!p&&!g)try{const T=y?[y]:Array.from(new Set([u,"main","master"].filter(Boolean)));for(const k of T){h();const O=await o(`https://data.jsdelivr.com/v1/package/gh/${l}/${a}@${encodeURIComponent(k)}/flat`,{signal:d});if(O&&O.ok){const F=await O.json();if(F&&Array.isArray(F.files)&&F.files.length>0){u=k,p=F.files.filter(P=>P&&P.name).map(P=>({path:P.name.replace(/^\/+/,""),size:P.size||0}));break}}}}catch(T){N.debug("jsDelivr flat tree fetch failed.",T)}if(g||!p)throw new Error(`fatal: repository '${r.url}' not found or could not be fetched`);const m=r.subpath?r.subpath.replace(/^\/+|\/+$/g,"")+"/":null,S=[];for(const T of p){let k=T.path;if(m)if(T.path===r.subpath)k=j.basename(T.path);else if(T.path.startsWith(m))k=T.path.slice(m.length);else continue;!k||k.startsWith(".git/")||k.includes("/node_modules/")||k.startsWith("node_modules/")||Qe.test(k)||T.size&&T.size>c||S.push({repoPath:T.path,destPath:k,size:T.size||0,priority:xe(k)})}S.sort((T,k)=>T.priority-k.priority||T.destPath.localeCompare(k.destPath));const b=S.slice(0,f),w=b.length;t&&t({phase:"downloading",message:`Downloading files (0/${w})...`,loaded:0,total:w}),e.existsSync(i)||e.mkdirSync(i,{recursive:!0});const v={};let $=0,R=0;const I=12;for(let T=0;T<b.length;T+=I){h();const k=b.slice(T,T+I);await Promise.all(k.map(async O=>{h();const F=O.repoPath.split("/").map(encodeURIComponent).join("/"),P=`https://raw.githubusercontent.com/${l}/${a}/${encodeURIComponent(u)}/${F}`,A=`https://cdn.jsdelivr.net/gh/${l}/${a}@${encodeURIComponent(u)}/${F}`;let _=null;try{const D=await o(P,{signal:d});D&&D.ok&&(_=await D.text())}catch(D){if(d&&d.aborted)throw D}if(_===null)try{const D=await o(A,{signal:d});D&&D.ok&&(_=await D.text())}catch(D){if(d&&d.aborted)throw D}if(_!==null&&_.length<=c){const D=j.join(i,O.destPath),M=j.dirname(D);e.existsSync(M)||e.mkdirSync(M,{recursive:!0}),e.writeFileSync(D,_),v[O.destPath]=_,$++,R+=_.length,t&&t({phase:"downloading",message:`Downloading files (${$}/${w}): ${O.destPath}`,loaded:$,total:w}),typeof s.onFile=="function"&&s.onFile(D,_,O.destPath)}}))}h(),t&&t({phase:"mounting",message:`Mounting files and writing Git metadata into ${i}...`,loaded:$,total:w});const C=j.join(i,".git");e.existsSync(C)||e.mkdirSync(C,{recursive:!0}),e.writeFileSync(j.join(C,"HEAD"),`ref: refs/heads/${u}
|
|
199
|
+
`);return h}function fe(n){if(!n||typeof n!="string")return null;let e=n.trim();if(!e)return null;let s=null,t=null,r=null,o=null;const i=e.indexOf("#");if(i!==-1){const l=e.slice(i+1).trim();e=e.slice(0,i).trim(),l&&(r=l)}const f=e.match(/^git@github\.com:([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/);if(f)return s=f[1],t=f[2],{owner:s,repo:t,branch:r,subpath:null,fullName:`${s}/${t}`,httpsUrl:`https://github.com/${s}/${t}`,gitUrl:`https://github.com/${s}/${t}.git`,url:`https://github.com/${s}/${t}.git`};const d=e.match(/^(?:https?:\/\/)?(?:www\.)?github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?(?:\/(tree|blob)\/([^/]+)(?:\/(.+?))?)?\/?$/);if(d){s=d[1],t=d[2];const l=d[4]?d[5]?`${d[4]}/${d[5].replace(/^\/+|\/+$/g,"")}`:d[4]:null;return l&&/^(?:feature|feat|fix|bugfix|hotfix|release|chore|refactor|docs|test|ci|depend|dependabot)\/[^/]+$/.test(l)&&!r?(r=l,o=null):(r=d[4]||r||null,o=d[5]?d[5].replace(/^\/+|\/+$/g,""):null),{owner:s,repo:t,branch:r,subpath:o,rawTreeTail:l,fullName:`${s}/${t}`,httpsUrl:`https://github.com/${s}/${t}`,gitUrl:`https://github.com/${s}/${t}.git`,url:`https://github.com/${s}/${t}.git`}}const y=e.match(/^([A-Za-z0-9_-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?(?:@([A-Za-z0-9_./-]+))?$/);return y&&!y[1].startsWith("-")?(s=y[1],t=y[2],r=y[3]||r||null,{owner:s,repo:t,branch:r,subpath:null,fullName:`${s}/${t}`,httpsUrl:`https://github.com/${s}/${t}`,gitUrl:`https://github.com/${s}/${t}.git`,url:`https://github.com/${s}/${t}.git`}):null}function L(n,e){const s={};if(!n||!e||!n.existsSync(e))return s;const t=j.normalize(e);function r(o){let i=[];try{i=n.readdirSync(o)}catch{return}for(const f of i){if(f===".git"||f==="node_modules")continue;const d=j.join(o,f);let y;try{y=n.statSync(d)}catch{continue}if(y.isDirectory())r(d);else{const l=d.startsWith(t==="/"?"/":t+"/")?d.slice(t==="/"?1:t.length+1):f;try{s[l]=String(n.readFileSync(d,"utf8"))}catch(a){M.debug("Skipped unreadable VFS file in snapshot.",d,a)}}}}return r(t),s}function re(n){const e=String(n||"");let s=3735928559^e.length,t=1103547991^e.length;for(let o=0;o<e.length;o++){const i=e.charCodeAt(o);s=Math.imul(s^i,2654435761),t=Math.imul(t^i,1597334677)}return s=Math.imul(s^s>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),t=Math.imul(t^t>>>16,2246822507)^Math.imul(s^s>>>13,3266489909),(4294967296*(2097151&t)+(s>>>0)).toString(16).padStart(7,"0").slice(0,7)}function ee(n,e){if(!n||typeof n!="string")return"";let s=n.trim().replace(/\\/g,"/");if(!s)return"";const t=j.normalize(e||"/workspace"),r=t==="/"?"/":t+"/";if(s===t)return"";for(s.startsWith(r)?s=s.slice(r.length):s.startsWith("/workspace/")&&(s=s.slice(11));s.startsWith("./");)s=s.slice(2);s.startsWith("/")&&(s=s.replace(/^\/+/,""));const o=[];for(const f of s.split("/"))if(!(!f||f===".")){if(f===".."){if(o.length===0)return"";o.pop();continue}o.push(f)}const i=o.join("/");return!i||i===".git"||i.startsWith(".git/")||i.includes("/.git/")||i.endsWith("/.git")||i==="node_modules"||i.startsWith("node_modules/")||i.includes("/node_modules/")||i.endsWith("/node_modules")?"":i}function oe(n){return(!Array.isArray(n&&n.commits)||n.commits.length===0)&&!(n&&n.headCommit)}function ue(n,e,s,t){if(!e)return!1;const r=t||n&&(n.headSnapshot||n.headFiles)||{},o=Object.prototype.hasOwnProperty.call(r,e),i=s==null?null:String(s);return i===null?o:!o||oe(n)?!0:i!==r[e]}function K(n,e,s,t,r){const o=n&&n.repoRoot||"/workspace",i=ee(s,o);if(!i)return;const f=t==null?null:String(t);ue(n,i,f,r)?e.set(i,f):e.delete(i)}function Y(n,e,s){if(!(e instanceof Map))return;const t=n&&n.repoRoot||"/workspace",r=s||n&&(n.headSnapshot||n.headFiles)||{};for(const[o,i]of Array.from(e.entries())){const f=ee(o,t);if(f!==o&&e.delete(o),!f){e.delete(o);continue}const d=i==null?null:String(i);ue(n,f,d,r)?e.set(f,d):e.delete(f)}}function Ke(n,e){if(!n||!n._initialBootSnapshot||!n._initialBootRoot)return{};const s=j.normalize(e),t=n._initialBootRoot;if(s===t)return n._initialBootSnapshot;const r=t==="/"?"/":t+"/";if(s.startsWith(r)){const o=s.slice(r.length)+"/",i={};for(const[f,d]of Object.entries(n._initialBootSnapshot))f.startsWith(o)&&(i[f.slice(o.length)]=d);return i}return{}}function Q(n,e,s,t){return n instanceof Map&&(n._hasShellStagedShim||(Object.defineProperty(n,"_hasShellStagedShim",{value:!0,enumerable:!1,configurable:!0,writable:!0}),Object.defineProperty(n,"add",{value(r){const o=typeof t=="function"?t():null,i=typeof s=="function"?s():o&&o.repoRoot||"/workspace",f=ee(r,i);if(!f)return n;let d=null;if(e&&typeof e.existsSync=="function"){const y=j.join(i,f);if(e.existsSync(y)){if(typeof e.statSync=="function")try{if(e.statSync(y).isDirectory())return n}catch(l){M.debug("Failed statting staged path in VFS.",y,l)}if(typeof e.readFileSync=="function")try{d=String(e.readFileSync(y,"utf8"))}catch(l){return M.debug("Failed reading staged file from VFS.",y,l),n}}}return o?K(o,n,f,d):n.set(f,d),n},enumerable:!1,configurable:!0,writable:!0}))),n}function Xe(n,e,s){const t=()=>n&&n.repoRoot||s||"/workspace",r=()=>n;if(n.staged instanceof Map)return Q(n.staged,e,t,r),Y(n,n.staged),n.stagedFiles=n.staged,n.staged;const o=Q(new Map,e,t,r);if(n.staged&&typeof n.staged[Symbol.iterator]=="function")for(const i of n.staged)Array.isArray(i)&&i.length>=2?K(n,o,i[0],i[1]===null?null:String(i[1])):typeof i=="string"&&o.add(i);return n.staged=o,n.stagedFiles=o,o}function Ye(n,e){if(!n||typeof n.existsSync!="function"||typeof n.readFileSync!="function")return null;const s=[j.join(e,".git/HEAD"),"/workspace/.git/HEAD"];for(const t of s)if(n.existsSync(t))try{const r=String(n.readFileSync(t,"utf8")).trim(),o=/^ref:\s*refs\/heads\/([^\s]+)$/.exec(r);if(o&&o[1])return o[1]}catch(r){M.debug("Could not parse .git/HEAD branch.",t,r)}return null}function Qe(n,e,s={}){const t=j.normalize(e||"/workspace"),r=!!(n&&typeof n.existsSync=="function"&&(n.existsSync(j.join(t,".git"))||n.existsSync(j.join(t,".git/HEAD"))||n.existsSync("/workspace/.git")||n.existsSync("/workspace/.git/HEAD")));let o=!!(s.gitInitialized===!0||r),i=t;const d=(r?Ye(n,t):null)||"main";let y=o?L(n,t):{},l=o?re(JSON.stringify(y)+":init"):"";const a=Date.now();let c=o?[{hash:l,author:"CodeLab Developer <dev@codelab.internal>",date:new Date(a).toUTCString(),timestamp:a,message:"Initial commit",files:Object.assign({},y)}]:[];const h={branch:d,branches:new Set([d]),remoteUrl:null,remotes:{}};let u=Q(new Map,n,()=>i,()=>h);return Object.defineProperties(h,{initialized:{enumerable:!0,configurable:!0,get(){if(o)return!0;const p=i||t;return n&&typeof n.existsSync=="function"&&(n.existsSync(j.join(p,".git"))||n.existsSync(j.join(p,".git/HEAD")))?(o=!0,!0):!1},set(p){o=!!p}},repoRoot:{enumerable:!0,configurable:!0,get(){return i},set(p){i=j.normalize(String(p||t))}},headCommit:{enumerable:!0,configurable:!0,get(){return l},set(p){l=String(p||"")}},headSnapshot:{enumerable:!0,configurable:!0,get(){return y},set(p){y=p&&typeof p=="object"?p:{}}},headFiles:{enumerable:!0,configurable:!0,get(){return y},set(p){y=p&&typeof p=="object"?p:{}}},staged:{enumerable:!0,configurable:!0,get(){return u},set(p){if(p instanceof Map)u=Q(p,n,()=>i,()=>h),Y(h,u);else{const g=Q(new Map,n,()=>i,()=>h);if(p&&typeof p[Symbol.iterator]=="function")for(const m of p)typeof m=="string"?g.add(m):Array.isArray(m)&&m.length>=2&&K(h,g,m[0],m[1]===null?null:String(m[1]));u=g}}},stagedFiles:{enumerable:!0,configurable:!0,get(){return u},set(p){p instanceof Map&&(u=Q(p,n,()=>i,()=>h),Y(h,u))}},commits:{enumerable:!0,configurable:!0,get(){return c},set(p){c=Array.isArray(p)?p:[],c.length>0&&c[0]&&c[0].hash?l=String(c[0].hash):c.length===0&&(l="")}}}),h}const xe=/\.(png|jpg|jpeg|gif|webp|ico|bmp|tiff|woff|woff2|ttf|eot|otf|mp3|mp4|wav|ogg|webm|avi|mov|pdf|zip|tar|gz|tgz|bz2|7z|rar|exe|dll|so|dylib|wasm|pyc|pyo|class|jar|war|ear|bin|dat|iso|dmg|pkg|deb|rpm|o|a|lib|DS_Store)$/i;function et(n){const e=n.toLowerCase(),s=j.basename(e),t=n.split("/").length;return s==="readme.md"||s==="package.json"||s==="cargo.toml"||s==="go.mod"||s==="pyproject.toml"?0:t===1&&/\.(js|ts|jsx|tsx|mjs|cjs|py|go|rs|json|md|yml|yaml|toml|sh)$/.test(e)?1:e.startsWith("src/")||e.startsWith("lib/")||e.startsWith("app/")?2+t*.1:e.startsWith("test/")||e.startsWith("tests/")||e.startsWith("examples/")?5+t*.1:10+t*.1}async function tt(n,e,s={}){const t=typeof s.onProgress=="function"?s.onProgress:null;t&&t({phase:"connecting",message:`Connecting to repository '${n}'...`});const r=fe(n);if(!r)throw new Error(`fatal: repository '${n}' does not exist or is not a valid GitHub repository URL`);if(!e)throw new Error("fatal: virtual filesystem (vfs) is required to clone repository");const o=s.fetchImpl||(typeof fetch=="function"?fetch.bind(globalThis):null);if(!o)throw new Error("fatal: global fetch API is unavailable in this environment");const i=j.normalize(s.targetDir||"/workspace"),f=s.maxFiles||250,d=s.maxFileSize||512*1024,y=s.branch||r.branch||null,{owner:l,repo:a}=r,c=s.signal||null,h=()=>{if(c&&c.aborted){const T=new Error("fatal: clone cancelled (SIGINT)");throw T.name="AbortError",T}};h();let u=y,p=null,g=!1;t&&t({phase:"metadata",message:`Fetching repository metadata for ${l}/${a}...`});try{if(!u){const T=await o(`https://api.github.com/repos/${l}/${a}`,{headers:{Accept:"application/vnd.github.v3+json"},signal:c});if(T.status===404)g=!0;else if(T.ok){const k=await T.json();k&&k.default_branch&&(u=k.default_branch)}}if(!g){const T=Array.from(y?new Set([y,!s.branch&&r.rawTreeTail&&r.rawTreeTail!==y?r.rawTreeTail:null].filter(Boolean)):new Set([u,"main","master"].filter(Boolean)));for(const k of T){h();const O=await o(`https://api.github.com/repos/${l}/${a}/git/trees/${encodeURIComponent(k)}?recursive=1`,{headers:{Accept:"application/vnd.github.v3+json"},signal:c});if(O.ok){const F=await O.json();if(F&&Array.isArray(F.tree)){u=k,r.rawTreeTail&&k===r.rawTreeTail&&(r.subpath=null),p=F.tree.filter(P=>P&&P.type==="blob"&&P.path).map(P=>({path:P.path.replace(/^\/+/,""),size:P.size||0}));break}}}}}catch(T){M.debug("GitHub REST API tree fetch failed; falling back to jsDelivr.",T)}if(!p&&!g)try{const T=y?[y]:Array.from(new Set([u,"main","master"].filter(Boolean)));for(const k of T){h();const O=await o(`https://data.jsdelivr.com/v1/package/gh/${l}/${a}@${encodeURIComponent(k)}/flat`,{signal:c});if(O&&O.ok){const F=await O.json();if(F&&Array.isArray(F.files)&&F.files.length>0){u=k,p=F.files.filter(P=>P&&P.name).map(P=>({path:P.name.replace(/^\/+/,""),size:P.size||0}));break}}}}catch(T){M.debug("jsDelivr flat tree fetch failed.",T)}if(g||!p)throw new Error(`fatal: repository '${r.url}' not found or could not be fetched`);const m=r.subpath?r.subpath.replace(/^\/+|\/+$/g,"")+"/":null,S=[];for(const T of p){let k=T.path;if(m)if(T.path===r.subpath)k=j.basename(T.path);else if(T.path.startsWith(m))k=T.path.slice(m.length);else continue;!k||k.startsWith(".git/")||k.includes("/node_modules/")||k.startsWith("node_modules/")||xe.test(k)||T.size&&T.size>d||S.push({repoPath:T.path,destPath:k,size:T.size||0,priority:et(k)})}S.sort((T,k)=>T.priority-k.priority||T.destPath.localeCompare(k.destPath));const b=S.slice(0,f),v=b.length;t&&t({phase:"downloading",message:`Downloading files (0/${v})...`,loaded:0,total:v}),e.existsSync(i)||e.mkdirSync(i,{recursive:!0});const w={};let $=0,R=0;const I=12;for(let T=0;T<b.length;T+=I){h();const k=b.slice(T,T+I);await Promise.all(k.map(async O=>{h();const F=O.repoPath.split("/").map(encodeURIComponent).join("/"),P=`https://raw.githubusercontent.com/${l}/${a}/${encodeURIComponent(u)}/${F}`,A=`https://cdn.jsdelivr.net/gh/${l}/${a}@${encodeURIComponent(u)}/${F}`;let _=null;try{const D=await o(P,{signal:c});D&&D.ok&&(_=await D.text())}catch(D){if(c&&c.aborted)throw D}if(_===null)try{const D=await o(A,{signal:c});D&&D.ok&&(_=await D.text())}catch(D){if(c&&c.aborted)throw D}if(_!==null&&_.length<=d){const D=j.join(i,O.destPath),N=j.dirname(D);e.existsSync(N)||e.mkdirSync(N,{recursive:!0}),e.writeFileSync(D,_),w[O.destPath]=_,$++,R+=_.length,t&&t({phase:"downloading",message:`Downloading files (${$}/${v}): ${O.destPath}`,loaded:$,total:v}),typeof s.onFile=="function"&&s.onFile(D,_,O.destPath)}}))}h(),t&&t({phase:"mounting",message:`Mounting files and writing Git metadata into ${i}...`,loaded:$,total:v});const C=j.join(i,".git");e.existsSync(C)||e.mkdirSync(C,{recursive:!0}),e.writeFileSync(j.join(C,"HEAD"),`ref: refs/heads/${u}
|
|
200
200
|
`),e.writeFileSync(j.join(C,"config"),`[core]
|
|
201
201
|
repositoryformatversion = 0
|
|
202
202
|
filemode = true
|
|
@@ -207,174 +207,177 @@ isomorphic-git/index.js:
|
|
|
207
207
|
[branch "${u}"]
|
|
208
208
|
remote = origin
|
|
209
209
|
merge = refs/heads/${u}
|
|
210
|
-
`);let E=[];try{const T=await o(`https://api.github.com/repos/${l}/${a}/commits?sha=${encodeURIComponent(u)}&per_page=10`,{headers:{Accept:"application/vnd.github.v3+json"},signal:
|
|
211
|
-
`)[0]:"Commit",A=re(`${l}/${a}:${u}:${F}:${P}`),_=O.commit&&O.commit.author&&O.commit.author.date&&Date.parse(O.commit.author.date)||Date.now();return{hash:String(O.sha||A).slice(0,7),author:O.commit&&O.commit.author?`${O.commit.author.name||l} <${O.commit.author.email||`${l}@users.noreply.github.com`}>`:`${l} <${l}@users.noreply.github.com>`,date:new Date(_).toUTCString(),timestamp:_,message:P}}))}}catch(T){
|
|
212
|
-
`;n.writeFileSync(e,o),typeof t=="function"&&t("change",e)}function G(n,e,s){n.existsSync(e)||(n.mkdirSync(e,{recursive:!0}),typeof s=="function"&&s("create",e))}function pe(n,e,s){if(n.existsSync(e))try{if(typeof n.rmSync=="function")n.rmSync(e,{recursive:!0,force:!0});else{const t=n.readdirSync(e);for(const r of t){const o=j.join(e,r);n.statSync(o).isDirectory()?pe(n,o,s):n.unlinkSync(o)}n.rmdirSync(e)}typeof s=="function"&&s("delete",e)}catch(t){
|
|
210
|
+
`);let E=[];try{const T=await o(`https://api.github.com/repos/${l}/${a}/commits?sha=${encodeURIComponent(u)}&per_page=10`,{headers:{Accept:"application/vnd.github.v3+json"},signal:c});if(T&&T.ok){const k=await T.json();Array.isArray(k)&&k.length>0&&(E=k.map((O,F)=>{const P=O.commit&&O.commit.message?String(O.commit.message).split(`
|
|
211
|
+
`)[0]:"Commit",A=re(`${l}/${a}:${u}:${F}:${P}`),_=O.commit&&O.commit.author&&O.commit.author.date&&Date.parse(O.commit.author.date)||Date.now();return{hash:String(O.sha||A).slice(0,7),author:O.commit&&O.commit.author?`${O.commit.author.name||l} <${O.commit.author.email||`${l}@users.noreply.github.com`}>`:`${l} <${l}@users.noreply.github.com>`,date:new Date(_).toUTCString(),timestamp:_,message:P}}))}}catch(T){M.debug("Optional commit history fetch skipped.",T)}if(E.length===0){const T=Date.now();E=[{hash:re(`${l}/${a}:${u}:${$}`),author:`${l} <${l}@users.noreply.github.com>`,date:new Date(T).toUTCString(),timestamp:T,message:`Clone ${l}/${a} (${u})`}]}return t&&t({phase:"ready",message:`Repository cloned successfully (${$} files).`,loaded:$,total:v}),{owner:l,repo:a,branch:u,url:r.url,targetDir:i,count:$,fileCount:$,filesWritten:$,totalBytes:R,commits:E,headSnapshot:w}}async function he(n,e,s={}){const t=typeof s.onProgress=="function"?s.onProgress:null;try{return await tt(n,e,s)}catch(r){throw t&&t({phase:"error",message:r&&r.message?r.message:String(r)}),r}}function nt(n,e){const s=j.join(e||"/workspace","package.json");if(n.existsSync(s))return s;const t="/workspace/package.json";return n.existsSync(t)?t:s}function H(n,e){const s=nt(n,e);if(n.existsSync(s))try{const t=JSON.parse(n.readFileSync(s,"utf8"));return{path:s,data:t}}catch(t){M.warn(`Invalid JSON in ${s}; falling back to default package metadata.`,t)}return{path:s,data:{name:"app",dependencies:{},devDependencies:{},scripts:{}}}}function De(n,e,s,t){const r=j.dirname(e);n.existsSync(r)||n.mkdirSync(r,{recursive:!0});const o=JSON.stringify(s,null,2)+`
|
|
212
|
+
`;n.writeFileSync(e,o),typeof t=="function"&&t("change",e)}function G(n,e,s){n.existsSync(e)||(n.mkdirSync(e,{recursive:!0}),typeof s=="function"&&s("create",e))}function pe(n,e,s){if(n.existsSync(e))try{if(typeof n.rmSync=="function")n.rmSync(e,{recursive:!0,force:!0});else{const t=n.readdirSync(e);for(const r of t){const o=j.join(e,r);n.statSync(o).isDirectory()?pe(n,o,s):n.unlinkSync(o)}n.rmdirSync(e)}typeof s=="function"&&s("delete",e)}catch(t){M.debug("removeDirRecursive failed.",e,t)}}const Ie="https://cdn.jsdelivr.net/npm",st=["https://cdn.jsdelivr.net/npm","https://unpkg.com","https://esm.sh"],rt={"is-even":`module.exports = function isEven(n) { return (Number(n) % 2) === 0; };
|
|
213
213
|
`,"tiny-invariant":`module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };
|
|
214
214
|
`,lodash:`module.exports = { isArray: Array.isArray, isObject: function (v) { return v !== null && typeof v === "object"; } };
|
|
215
215
|
`,"left-pad":`module.exports = function leftPad(str, len, ch) { str = String(str); ch = (ch === undefined ? " " : String(ch)); while (str.length < len) str = ch + str; return str.slice(-len); };
|
|
216
|
-
`};function
|
|
217
|
-
`),typeof n.emitMutation=="function"&&n.emitMutation("create",o),t.pkgBin){const f=r.slice(0,r.length-s.length-1),
|
|
218
|
-
require(${JSON.stringify(
|
|
219
|
-
`;if(n.vfs.writeFileSync(h,u),typeof n.vfs.chmodSync=="function")try{n.vfs.chmodSync(h,493)}catch(p){}typeof n.emitMutation=="function"&&n.emitMutation("create",h)}}}}async function
|
|
220
|
-
`}]}),m||(m=
|
|
221
|
-
`),typeof e.emitMutation=="function"&&e.emitMutation("modify",b)}catch(b){
|
|
222
|
-
`}function
|
|
216
|
+
`};function ot(n){return n&&n.shell&&n.shell.options&&typeof n.shell.options.fetchImpl=="function"?n.shell.options.fetchImpl:typeof fetch=="function"?fetch.bind(globalThis):null}function ye(n){const e=String(n||"").trim();if(!e)return{name:"",range:null};if(e.startsWith("@")){const t=e.indexOf("@",1);return t===-1?{name:e,range:null}:{name:e.slice(0,t),range:e.slice(t+1)||null}}const s=e.indexOf("@");return s<=0?{name:e,range:null}:{name:e.slice(0,s),range:e.slice(s+1)||null}}function te(n){if(typeof n=="string")return n;if(Array.isArray(n)){for(const e of n){const s=te(e);if(s)return s}return null}if(!n||typeof n!="object")return null;for(const e of["require","node","default","browser","import","module"])if(n[e]!==void 0){const s=te(n[e]);if(s)return s}return null}function Ae(n){let e=null;const s=n&&n.exports;return typeof s=="string"?e=s:s&&typeof s=="object"&&s["."]!==void 0&&(e=te(s["."])),e||(e=n.main||n.module||(typeof n.browser=="string"?n.browser:"")||"index.js"),e=String(e).replace(/^[./]+/,""),e||"index.js"}function Ne(n){return String(n||"").replace(/^[./]+/,"")}function it(n){const e=new Set,s=[/\bfrom\s*['"](\.{1,2}\/[^'"]+)['"]/g,/\brequire\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,/\bimport\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,/\bimport\s*['"](\.{1,2}\/[^'"]+)['"]/g];for(const t of s){let r;for(;(r=t.exec(n))!==null;)e.add(r[1])}return Array.from(e)}function lt(n,e){const s=String(n||"").split("/").filter(Boolean);for(const t of String(e).split("/"))!t||t==="."||(t===".."?s.pop():s.push(t));return s.join("/")}function me(n){return new Promise(e=>{typeof setTimeout=="function"?setTimeout(e,n):e()})}async function ge(n,e){for(let t=1;t<=3;t++)try{const r=await n(e);if(!r){if(t<3){await me(t*150);continue}return null}if(!(r.ok===!0||r.status===200||r.status===void 0)){if((r.status>=500||r.status===429||r.status===408)&&t<3){await me(t*150);continue}return null}const i=r.headers&&typeof r.headers.get=="function"&&r.headers.get("content-type")||"",f=/\.html?(?:[?#]|$)/i.test(e);if(/text\/html/i.test(i)&&!f)return null;const d=typeof r.text=="function"?await r.text():String(r.body!=null?r.body:"");return!f&&/^\s*(?:<!doctype\s+html|<html[\s>]|<head[\s>])/i.test(d)?null:d}catch{if(t<3){await me(t*150);continue}return null}return null}async function at(n,e,s){for(const t of st){const r=s?[`${t}/${e}@${s}/package.json`,`${t}/${e}/package.json`]:[`${t}/${e}/package.json`];for(const o of r){const i=await ge(n,o);if(i)try{const f=JSON.parse(i);if(f&&f.version)return f._resolvedCdnBase=t,f}catch(f){M.debug("Invalid package.json metadata from CDN.",o,f)}}}return null}async function ct(n,e,s,t){const r=await at(n,e,s);if(!r){const b=rt[e];return b?{ok:!0,offline:!0,version:s&&s.replace(/^[\^~>=<\s]+/,"")||"1.0.0",entry:"index.js",files:[{rel:"index.js",content:b}],deps:[]}:{ok:!1,reason:`${e}: package metadata not found on the registry (offline?)`}}const o=r._resolvedCdnBase||Ie,i=r.version,f=`${e}@${i}`;if(t.has(f))return{ok:!0,deduped:!0,version:i,entry:Ae(r),files:[],deps:[]};t.add(f);const d=Ae(r),y=[],l=new Set,a=[d,`${d}.js`,`${d}.json`,`${d}.mjs`,`${d}.cjs`,`${d}/index.js`,`${d}/index.json`,`${d}/index.mjs`,`${d}/index.cjs`],c=r.exports;if(c&&typeof c=="object")for(const b of Object.keys(c)){if(b==="."||b.slice(0,2)!=="./"||b.includes("*"))continue;const v=te(c[b]);v&&a.push(v)}let h=a;for(;h.length>0;){const b=[];for(const w of h){const $=Ne(w);!$||$.endsWith("/")||l.has($)||(l.add($),b.push($))}if(h=[],b.length===0)break;const v=await Promise.all(b.map(w=>ge(n,`${o}/${e}@${i}/${w}`)));for(let w=0;w<b.length;w++){const $=b[w],R=v[w];if(R===null)continue;y.push({rel:$,content:R});const I=$.includes("/")?$.slice(0,$.lastIndexOf("/")):"";for(const C of it(R)){const E=lt(I,C),T=/\.[a-z0-9]+$/i.test(E)?[E]:[E,`${E}.js`,`${E}.json`,`${E}.mjs`,`${E}.cjs`,`${E}/index.js`];for(const k of T){const O=Ne(k);O&&!l.has(O)&&h.push(k)}}}}if(!y.some(b=>b.rel===d)){const b=await ge(n,`${o}/${e}@${i}/index.js`);b!==null&&y.push({rel:"index.js",content:b})}const u=[],p=new Set,g=r.dependencies||{};for(const b of Object.keys(g))p.has(b)||(p.add(b),u.push({name:b,range:g[b]||null}));const m=r.peerDependenciesMeta||{},S=r.peerDependencies||{};for(const b of Object.keys(S))m[b]&&m[b].optional||p.has(b)||(p.add(b),u.push({name:b,range:S[b]||null}));return{ok:!0,version:i,entry:d,files:y,deps:u,pkgBin:r.bin||null,pkgExports:r.exports&&typeof r.exports=="object"?r.exports:null}}function Me(n,e){const s=["/workspace/node_modules/"+e],t=j.join(n.cwd||"/workspace","node_modules",e);return s.includes(t)||s.push(t),s}function _e(n,e,s,t){for(const r of e){G(n.vfs,r,n.emitMutation);for(const f of t.files){if(!f||!f.rel||f.rel.endsWith("/"))continue;const d=j.join(r,f.rel);try{if(n.vfs.existsSync(d)&&n.vfs.statSync(d).isDirectory())continue}catch(y){M.debug("Package install statSync check skipped.",d,y)}G(n.vfs,j.dirname(d),n.emitMutation),n.vfs.writeFileSync(d,f.content),typeof n.emitMutation=="function"&&n.emitMutation("create",d)}const o=j.join(r,"package.json"),i={name:s,version:t.version||"1.0.0",main:"./"+(t.entry||"index.js")};if(t.pkgBin&&(i.bin=t.pkgBin),t.pkgExports&&typeof t.pkgExports=="object"){const f={".":"./"+(t.entry||"index.js")};for(const d of Object.keys(t.pkgExports)){if(d==="."||d.indexOf("*")!==-1)continue;const y=te(t.pkgExports[d]);y&&(f[d]=y.charAt(0)==="."?y:"./"+y)}i.exports=f}if(n.vfs.writeFileSync(o,JSON.stringify(i,null,2)+`
|
|
217
|
+
`),typeof n.emitMutation=="function"&&n.emitMutation("create",o),t.pkgBin){const f=r.slice(0,r.length-s.length-1),d=j.join(f,".bin");G(n.vfs,d,n.emitMutation);const y=typeof t.pkgBin=="string"?{[s.includes("/")?s.split("/").pop():s]:t.pkgBin}:typeof t.pkgBin=="object"?t.pkgBin:{};for(const[l,a]of Object.entries(y)){if(!l||!a)continue;const c=j.join(r,String(a).replace(/^\.\//,"")),h=j.join(d,l),u=`// Auto-generated bin shim for ${s}
|
|
218
|
+
require(${JSON.stringify(c)});
|
|
219
|
+
`;if(n.vfs.writeFileSync(h,u),typeof n.vfs.chmodSync=="function")try{n.vfs.chmodSync(h,493)}catch(p){}typeof n.emitMutation=="function"&&n.emitMutation("create",h)}}}}async function dt(n,e,s,t){const r=s&&typeof s=="object"?s:t||{},o=typeof s=="function"?s:typeof r.onLine=="function"?r.onLine:null,i=!!r.dev,{name:f,range:d}=ye(n);if(!f)return{name:null,ok:!1,installed:[],warning:null};const{path:y,data:l}=H(e.vfs,e.cwd),a=i?"devDependencies":"dependencies";l[a]||(l[a]={});const c=ot(e),h=e.shell&&e.shell._cdnSeen?e.shell._cdnSeen:e.shell?e.shell._cdnSeen=new Set:new Set,u=[{name:f,range:d,direct:!0}],p=new Set([f]),g=[];let m=null,S=null;for(;u.length>0;){const b=u.shift(),v=c?await ct(c,b.name,b.range,h):{ok:!1,reason:`${b.name}: no fetch implementation available`};if(!v.ok){_e(e,Me(e,b.name),b.name,{version:"0.0.0",entry:"index.js",files:[{rel:"index.js",content:`module.exports = {};
|
|
220
|
+
`}]}),m||(m=v.reason),g.push({name:b.name,version:"0.0.0"}),typeof o=="function"&&o({name:b.name,version:"0.0.0",offline:!0});continue}_e(e,Me(e,b.name),b.name,v),g.push({name:b.name,version:v.version||"1.0.0"}),typeof o=="function"&&o({name:b.name,version:v.version||"1.0.0",deduped:!!v.deduped}),b.direct&&(S=v.version||null);for(const w of v.deps||[]){const $=w&&typeof w=="object"?w.name:ye(w).name,R=w&&typeof w=="object"?w.range:ye(w).range;$&&!p.has($)&&(p.add($),u.push({name:$,range:R||null,direct:!1}))}}l[a][f]=d||(S?`^${S}`:l[a][f]||"latest"),De(e.vfs,y,l,e.emitMutation);try{const b=j.join(j.dirname(y),"package-lock.json");let v={name:l.name||"workspace",version:l.version||"1.0.0",lockfileVersion:3,packages:{}};if(e.vfs.existsSync(b)){const w=String(e.vfs.readFileSync(b,"utf8")||""),$=JSON.parse(w);$&&typeof $=="object"&&(v=$,(!v.packages||typeof v.packages!="object")&&(v.packages={}))}for(const w of g)w&&w.name&&(v.packages[`node_modules/${w.name}`]={version:w.version||"1.0.0",resolved:`${Ie}/${w.name}@${w.version||"1.0.0"}`});e.vfs.writeFileSync(b,JSON.stringify(v,null,2)+`
|
|
221
|
+
`),typeof e.emitMutation=="function"&&e.emitMutation("modify",b)}catch(b){M.debug("Could not write package-lock.json during installPackage.",b)}return{name:f,ok:!0,version:S,installed:g,warning:m}}function ft(n,e){const s=n&&typeof n.onStdout=="function"?n.onStdout:null;return function(r){r&&(e.push(r),s&&s(r))}}function ut(n){if(!n||!n.name)return"";const e=n.offline?" (offline fallback)":n.deduped?" (deduped)":"";return` + ${n.name}@${n.version||"1.0.0"}${e}
|
|
222
|
+
`}function ht(n){const e=new Set;for(const s of n)if(s){s.name&&e.add(s.name);for(const t of s.installed||[])t&&t.name&&e.add(t.name)}return e.size}async function ne(n,e,s){const t=s||{},r=t.manager||"bun",o=t.header||(r==="npm"?"npm install v10.2.0":"bun add v1.1.20 (1.1.20)"),i=[],f=ft(e,i),d=Date.now();f(`${o}
|
|
223
223
|
|
|
224
224
|
Resolving dependencies...
|
|
225
|
-
`);const y=[];for(const h of n)y.push(await
|
|
226
|
-
added ${a} package(s) in ${
|
|
225
|
+
`);const y=[];for(const h of n)y.push(await dt(h,e,{onLine:u=>f(ut(u)),dev:!!t.dev}));const l=y.map(h=>h&&h.warning).filter(Boolean)[0],a=ht(y),c=Date.now()-d;return f(r==="npm"?`
|
|
226
|
+
added ${a} package(s) in ${c}ms
|
|
227
227
|
`:r==="pnpm"?`
|
|
228
228
|
Packages: +${a}
|
|
229
229
|
${"+".repeat(Math.min(a,40))}
|
|
230
|
-
Done in ${
|
|
230
|
+
Done in ${c}ms using pnpm v9.0.0
|
|
231
231
|
`:`Saved lockfile
|
|
232
232
|
|
|
233
|
-
${a} package(s) installed [${
|
|
233
|
+
${a} package(s) installed [${c}ms]
|
|
234
234
|
`),{code:0,stdout:i.join(""),stderr:l?`${r==="npm"?"npm warn":r==="pnpm"?"pnpm warn":"bun warn"} ${l}
|
|
235
|
-
`:""}}function be(n,e){const{path:s,data:t}=
|
|
235
|
+
`:""}}function be(n,e){const{path:s,data:t}=H(e.vfs,e.cwd);let r=!1;t.dependencies&&n in t.dependencies&&(delete t.dependencies[n],r=!0),t.devDependencies&&n in t.devDependencies&&(delete t.devDependencies[n],r=!0),r&&De(e.vfs,s,t,e.emitMutation);const o=["/workspace/node_modules/"+n],i=j.join(e.cwd||"/workspace","node_modules",n);o.includes(i)||o.push(i);for(const f of o)pe(e.vfs,f,e.emitMutation)}function ie(n){const{data:e}=H(n.vfs,n.cwd),s=Object.assign({},e.dependencies||{});let t=`${e.name||"project"}@${e.version||"1.0.0"} ${n.cwd||"/workspace"}
|
|
236
236
|
`;const r=Object.keys(s);if(r.length===0)t+=`\u2514\u2500\u2500 (empty)
|
|
237
|
-
`;else for(let o=0;o<r.length;o++){const i=r[o],f=String(s[i]).replace(/^[\^~]/,""),
|
|
238
|
-
`}return t}function
|
|
239
|
-
`};let r=t.scripts[n];e&&e.length>0&&(r+=" "+e.map(
|
|
237
|
+
`;else for(let o=0;o<r.length;o++){const i=r[o],f=String(s[i]).replace(/^[\^~]/,""),d=o===r.length-1?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ";t+=`${d}${i}@${f}
|
|
238
|
+
`}return t}function We(n){const e=String(n??"");return e.length===0?"''":/[\s"'\\$&|;<>()`!*?~#]/.test(e)?"'"+e.replace(/'/g,"'\\''")+"'":e}async function Z(n,e,s){const{data:t}=H(s.vfs,s.cwd);if(!t.scripts||!t.scripts[n])return{code:1,stdout:"",stderr:`npm ERR! Missing script: "${n}"
|
|
239
|
+
`};let r=t.scripts[n];e&&e.length>0&&(r+=" "+e.map(We).join(" "));const o=await Ve(n,r,s);if(o)return o;const i=`${j.join(s.cwd||"/workspace","node_modules/.bin")}:/workspace/node_modules/.bin`,f={...s.env,PATH:s.env&&s.env.PATH?`${i}:${s.env.PATH}`:`${i}:/usr/local/bin:/usr/bin:/bin`},d=await s.shell.execute(r,{cwd:s.cwd,env:f,stdin:s.stdin,signal:s.signal,isBackground:s.isBackground,onStdout:s.onStdout,onStderr:s.onStderr,onRequestStdin:s.onRequestStdin||(s.shell&&s.shell.options?s.shell.options.onRequestStdin:void 0)});return{code:d.code!==void 0?d.code:0,stdout:d.stdout||"",stderr:d.stderr||"",alreadyStreamed:!!s.onStdout,aborted:d.aborted}}const Be="https://cdn.jsdelivr.net/npm",pt={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".cjs":"text/javascript; charset=utf-8",".jsx":"text/javascript; charset=utf-8",".ts":"text/javascript; charset=utf-8",".tsx":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".wasm":"application/wasm",".pdf":"application/pdf",".mp3":"audio/mpeg",".mp4":"video/mp4",".webm":"video/webm",".txt":"text/plain; charset=utf-8"};function yt(n){const e=String(n||"").toLowerCase().split(";")[0].trim();return e?!(e.startsWith("text/")||e==="application/javascript"||e==="application/json"||e==="application/xml"||e==="application/xhtml+xml"||e==="image/svg+xml"):!1}function mt(n){const e=String(n).toLowerCase(),s=e.lastIndexOf(".");return s===-1?"application/octet-stream":pt[e.slice(s)]||"application/octet-stream"}function Se(n){return/\.(?:[cm]?jsx?|tsx?)$/i.test(n)&&!/\.d\.ts$/i.test(n)}function ve(n){const e=new Set,s=[/\bfrom\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,/\brequire\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,/\bimport\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,/\bimport\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g];for(const t of s){let r;for(;(r=t.exec(n))!==null;){const o=r[1];!o||o.startsWith(".")||o.startsWith("/")||o.includes(":")||e.add(o)}}return Array.from(e)}function gt(n){if(!n||typeof n!="string")return"latest";const e=n.trim();return!e||e==="*"||/^(?:latest|next|beta|canary)$/.test(e)||/^(?:file|link|workspace|portal|git|https?):/.test(e)?"latest":e.replace(/\s+/g,"").replace(/^[v=\s]+/,"")||"latest"}function Ue(n,e,s){try{const t=j.join(e,"node_modules",s,"package.json");if(n.existsSync(t)){const r=JSON.parse(n.readFileSync(t,"utf8"));if(r&&r.version)return r.version}}catch(t){M.debug("Could not read installed module package.json.",s,t)}try{for(const t of[e,"/workspace"]){const r=j.join(t,"package.json");if(!n.existsSync(r))continue;const o=JSON.parse(n.readFileSync(r,"utf8")),i=Object.assign({},o.dependencies||{},o.devDependencies||{},o.peerDependencies||{});if(i[s])return gt(i[s])}}catch(t){M.debug("Could not read workspace package.json for version resolution.",s,t)}return"latest"}function ze(n,e,s){const t=`${Be}/${n}@${e}`,r=s?"/"+String(s).replace(/^\/+|\/+$/g,""):"";return`${t}${r}/+esm`}function bt(n,e,s){const t={};for(const r of s){const o=String(r).split("/"),i=r.startsWith("@")?o.slice(0,2).join("/"):o[0];if(!i)continue;const f=r.slice(i.length).replace(/^\/+/,""),d=Ue(n,e,i);if(f&&/\.css$/i.test(f)){const y=`${Be}/${i}@${d}/${f.replace(/^\/+/,"")}`,l=`if(typeof document!=='undefined'){const l=document.createElement('link');l.rel='stylesheet';l.href=${JSON.stringify(y)};document.head.appendChild(l);}export default ${JSON.stringify(y)};`;t[r]=`data:text/javascript;charset=utf-8,${encodeURIComponent(l)}`;continue}t[r]=ze(i,d,f||void 0)}return t}const St=/https?:\/\/(?:cdn\.jsdelivr\.net\/npm|esm\.sh)\/((?:@[^\/'"`@\s]+\/)?[^\/'"`@\s]+)@([^\s'"`),;]+)/g;function He(n,e,s,t){if(!s||typeof s!="string")return;const r=new RegExp(St.source,"g");let o;for(;(o=r.exec(s))!==null;){const i=o[0];if(i.includes("${"))continue;const f=decodeURIComponent(o[1]),d=o[2],y=d.split(/[\/?]/)[0],l=d.slice(y.length),c=(l.startsWith("/")&&l!=="/+esm"?l.slice(1).split(/[?#]/)[0]:"").replace(/^\/+|\/+$/g,""),h=c?`${f}/${c}`:f,u=Ue(n,e,f),p=u&&u!=="latest"?u:decodeURIComponent(y),g=t[h]||ze(f,p,c||void 0);g&&g!==i&&(t[i]=g)}}function qe(n,e,s=200){const t=[],r=(o,i)=>{if(i>8||t.length>=s)return;let f=[];try{f=n.readdirSync(o)}catch{return}for(const d of f){if(d==="node_modules"||d.startsWith("."))continue;const y=j.join(o,d);let l;try{l=n.statSync(y)}catch{continue}if(l&&(typeof l.isDirectory=="function"?l.isDirectory():l.isDirectory))r(y,i+1);else if(Se(d)&&t.length<s)try{const c=n.readFileSync(y,"utf8"),h=y.startsWith(e+"/")?y.slice(e.length+1):d;t.push({full:y,rel:h,content:c})}catch(c){M.debug("Preview script read skipped.",y,c)}}};return r(e,0),t}function vt(n,e,s=200){const t=[],r=(o,i)=>{if(i>8||t.length>=s)return;let f=[];try{f=n.readdirSync(o)}catch{return}for(const d of f){if(d==="node_modules"||d.startsWith("."))continue;const y=j.join(o,d);let l;try{l=n.statSync(y)}catch{continue}if(l&&(typeof l.isDirectory=="function"?l.isDirectory():l.isDirectory))r(y,i+1);else if(/\.(?:css|json|svg)$/i.test(d)&&t.length<s)try{const c=n.readFileSync(y,"utf8"),h=y.startsWith(e+"/")?y.slice(e.length+1):d;t.push({full:y,rel:h,content:c})}catch(c){M.debug("Preview asset read skipped.",y,c)}}};return r(e,0),t}function Pt(n,e,s=200){return qe(n,e,s).map(t=>t.content)}function wt(n,e){let s=n;const r=`<script type="importmap">
|
|
240
240
|
${JSON.stringify({imports:e},null,2).replace(/</g,"\\u003c")}
|
|
241
241
|
<\/script>`;/<head[^>]*>/i.test(s)?s=s.replace(/<head[^>]*>/i,i=>`${i}
|
|
242
242
|
${r}`):s=r+`
|
|
243
243
|
`+s;const o="<script>window.__CODELAB_PREVIEW__ = true;<\/script>";return/<\/body>/i.test(s)?s=s.replace(/<\/body>/i,`${o}
|
|
244
244
|
</body>`):s=s+`
|
|
245
|
-
`+o,s}function
|
|
245
|
+
`+o,s}function we(n,e,s){const t=n.shell&&n.shell.portTable;if(!t||typeof t.registerServer!="function")return null;let r=Number(s)||3e3;const o=new Set((typeof t.listServers=="function"?t.listServers():[]).map(S=>Number(S.port)));for(;o.has(r);)r++;const i=S=>{try{return n.vfs.existsSync(S)}catch{return!1}},f=S=>{try{const b=n.vfs.statSync(S);return!!(b&&(typeof b.isDirectory=="function"?b.isDirectory():b.isDirectory))}catch{return!1}},d=S=>i(S)&&!f(S),y=S=>{try{return n.vfs.readFileSync(S,"utf8")}catch{return null}},l=S=>{const b=e==="/"?"/":e+"/";return S===e||S.startsWith(b)},a=(S,b)=>{if(!b||typeof b!="string")return null;const v=b.split(/[?#]/)[0].trim();if(!v||/^(?:https?:|data:|blob:|\/\/)/i.test(v))return null;const w=v.startsWith("/")?j.join(e,v.replace(/^\/+/,"")):j.join(S,v);if(!l(w))return null;if(d(w))return w;const $=[w+".tsx",w+".ts",w+".jsx",w+".js",w+".mjs",w+".cjs",j.join(w,"index.tsx"),j.join(w,"index.ts"),j.join(w,"index.jsx"),j.join(w,"index.js")];for(const R of $)if(l(R)&&d(R))return R;return null},c=S=>`@codelab-local/${S.startsWith(e+"/")?S.slice(e.length+1):S.replace(/^\/+/,"")}`,h=(S,b)=>{let v=S;try{const R=U();R&&typeof R.transpileForBrowser=="function"&&(v=R.transpileForBrowser(v,b))}catch(R){M.warn(`Preview script transpilation failed for ${b}.`,R)}const w=j.dirname(b),$=R=>{if(!R||!R.startsWith(".")&&!R.startsWith("/"))return R;const I=a(w,R);return I?c(I):R};return v=v.replace(/(\b(?:from|import)\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"])/g,(R,I,C,E)=>`${I}${$(C)}${E}`),v=v.replace(/(\bimport\s*\(\s*['"])(\.{1,2}\/[^'"]+|\/[^'"]+)(['"]\s*\))/g,(R,I,C,E)=>`${I}${$(C)}${E}`),v},u=(S,b)=>S?S.replace(/@import\s+(?:url\(\s*['"]?([^'")]+)['"]?\s*\)|['"]([^'"]+)['"])\s*;?/gi,(v,w,$)=>{const R=(w||$||"").trim();if(!R||/^(?:https?:|data:|\/\/)/i.test(R))return v;if(R==="tailwindcss")return"";const I=a(b,R);if(I&&/\.css$/i.test(I)){const C=y(I);if(C!==null)return C}return""}):"",p=(S,b)=>{const v=qe(n.vfs,e),w=vt(n.vfs,e),$=new Set,R=[];for(const P of v){for(const _ of ve(P.content))$.add(_);const A=h(P.content,P.full);for(const _ of ve(A))$.add(_);R.push({file:P,compiled:A})}const I=/<script\b[^>]*>([\s\S]*?)<\/script>/gi;let C;for(;(C=I.exec(S))!==null;)if(C[1])for(const P of ve(C[1]))$.add(P);const E=bt(n.vfs,e,$);for(const P of v)He(n.vfs,e,P.content,E);He(n.vfs,e,S,E);for(const{file:P,compiled:A}of R){const _=c(P.full);E[_]=`data:text/javascript;charset=utf-8,${encodeURIComponent(A)}`}let T=!1;for(const P of w){const A=c(P.full);if(/\.css$/i.test(P.full)){/@import\s+['"]tailwindcss['"]/i.test(P.content)&&(T=!0);const _=u(P.content,j.dirname(P.full)),D=`const __css=${JSON.stringify(_)};if(typeof document!=='undefined'){const __s=document.createElement('style');__s.setAttribute('data-codelab-css',${JSON.stringify(P.rel)});__s.textContent=__css;document.head.appendChild(__s);}export default __css;`;E[A]=`data:text/javascript;charset=utf-8,${encodeURIComponent(D)}`}else if(/\.json$/i.test(P.full)){const _=`export default ${P.content.trim()||"null"};`;E[A]=`data:text/javascript;charset=utf-8,${encodeURIComponent(_)}`}else if(/\.svg$/i.test(P.full)){const _=`data:image/svg+xml;utf8,${encodeURIComponent(P.content)}`,D=`export default ${JSON.stringify(_)};`;E[A]=`data:text/javascript;charset=utf-8,${encodeURIComponent(D)}`}}const k=j.dirname(b);let O=S.replace(/%PUBLIC_URL%\//g,"/").replace(/%PUBLIC_URL%/g,"");if(!/<script\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/i.test(O)){const P=["/src/main.tsx","/src/main.jsx","/src/main.ts","/src/main.js","/src/index.tsx","/src/index.jsx","/src/index.ts","/src/index.js"];for(const A of P)if(d(j.join(e,A.slice(1)))){const _=`<script type="module" src="${A}"><\/script>`;/<\/body>/i.test(O)?O=O.replace(/<\/body>/i,` ${_}
|
|
246
246
|
</body>`):O+=`
|
|
247
|
-
${_}`;break}}if(O=O.replace(/<link\b([^>]*?)>/gi,(P,A)=>{if(!/\brel\s*=\s*["']stylesheet["']/i.test(A))return P;const _=/\bhref\s*=\s*["']([^"']+)["']/i.exec(A);if(!_)return P;const D=a(k,_[1]);if(!D||!/\.css$/i.test(D))return P;const
|
|
247
|
+
${_}`;break}}if(O=O.replace(/<link\b([^>]*?)>/gi,(P,A)=>{if(!/\brel\s*=\s*["']stylesheet["']/i.test(A))return P;const _=/\bhref\s*=\s*["']([^"']+)["']/i.exec(A);if(!_)return P;const D=a(k,_[1]);if(!D||!/\.css$/i.test(D))return P;const N=y(D);if(N===null)return P;/@import\s+['"]tailwindcss['"]/i.test(N)&&(T=!0);const B=u(N,j.dirname(D)).replace(/<\/style/gi,"<\\/style");return`<style data-codelab-href="${_[1].replace(/"/g,""")}">
|
|
248
248
|
${B}
|
|
249
|
-
</style>`}),O=O.replace(/<script\b([^>]*?)>\s*<\/script>/gi,(P,A)=>{const _=/\bsrc\s*=\s*["']([^"']+)["']/i.exec(A);if(!_)return P;const D=a(k,_[1]);if(!D||!Se(D))return P;const
|
|
249
|
+
</style>`}),O=O.replace(/<script\b([^>]*?)>\s*<\/script>/gi,(P,A)=>{const _=/\bsrc\s*=\s*["']([^"']+)["']/i.exec(A);if(!_)return P;const D=a(k,_[1]);if(!D||!Se(D))return P;const N=y(D);if(N===null)return P;const B=h(N,D).replace(/<\/script/gi,"<\\/script");return`<script${/\btype\s*=\s*["']module["']/i.test(A)||/\.(?:tsx|ts|jsx|mjs)$/i.test(D)||/^\s*(?:import|export)\b/m.test(N)?' type="module"':""} data-codelab-src="${_[1].replace(/"/g,""")}">
|
|
250
250
|
${B}
|
|
251
251
|
<\/script>`}),T&&!O.includes("@tailwindcss/browser")){const P='<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"><\/script>';/<head[^>]*>/i.test(O)?O=O.replace(/<head[^>]*>/i,A=>`${A}
|
|
252
252
|
${P}`):O=P+`
|
|
253
|
-
`+O}return wt(O,E)},g=async S=>{let b="/";try{b=decodeURIComponent(new URL(S.url).pathname)}catch(C){
|
|
253
|
+
`+O}return wt(O,E)},g=async S=>{let b="/";try{b=decodeURIComponent(new URL(S.url).pathname)}catch(C){M.debug("Preview URL decode failed.",C)}const v=b.replace(/^\/+/,"");let w=j.join(e,v);if(!l(w))return new Response('<!doctype html><meta charset="utf-8"><title>403</title><h1>403 Forbidden</h1>',{status:403,headers:{"content-type":"text/html; charset=utf-8"}});const $=/\.[A-Za-z0-9]+$/.test(v);if(!v||b.endsWith("/")||f(w)){const C=j.join(w,"index.html"),E=j.join(w,"public","index.html");w=!i(C)&&i(E)?E:C}if(!i(w)&&!$){const C=[w+".tsx",w+".ts",w+".jsx",w+".js",w+".mjs",w+".cjs",j.join(w,"index.tsx"),j.join(w,"index.ts"),j.join(w,"index.jsx"),j.join(w,"index.js")];for(const E of C)if(i(E)){w=E;break}}if(!i(w)&&!$){const C=j.join(e,"index.html"),E=j.join(e,"public","index.html");w=!i(C)&&i(E)?E:C}if(!i(w)){const C=String(b).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");return new Response(`<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${C}</p>`,{status:404,headers:{"content-type":"text/html; charset=utf-8"}})}const R=mt(w);if(yt(R)){let C=null;try{C=n.vfs.readFileSync(w)}catch(T){M.debug("Binary preview asset read failed.",w,T)}const E=C instanceof Uint8Array?C:typeof C=="string"?new TextEncoder().encode(C):new Uint8Array(0);return new Response(E,{status:200,headers:{"content-type":R}})}let I=y(w);if(I===null&&(I=""),/\.html?$/i.test(w))I=p(I,w);else if(Se(w))try{const C=U();C&&typeof C.transpileForBrowser=="function"&&(I=C.transpileForBrowser(I,w))}catch(C){M.warn(`Preview script transpilation failed for ${w}.`,C)}return new Response(I,{status:200,headers:{"content-type":R}})},m=n.shell&&typeof n.shell.nextPid=="number"?n.shell.nextPid++:n.pid||1e3;return t.registerServer(r,{server:{close(){try{t.unregisterServer(r)}catch(S){M.debug("Preview server unregister failed.",r,S)}}},fetch:g,name:"code-lab-serve",pid:m,root:e})}const Le=/\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/,$t=/^(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts)$/,kt=/^(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|http-server)$/;async function $e(n,e,s){const t=e&&e.shell?e.shell.portTable:null;if(!!!(e&&!e.isBackground&&e.signal))return{code:0,stdout:s,stderr:""};const o=`${s.replace(/\n+$/,"")}
|
|
254
|
+
\u279C Press Ctrl+C to stop
|
|
255
|
+
|
|
256
|
+
`;typeof e.onStdout=="function"&&e.onStdout(o);const i=()=>{if(n&&n.server&&typeof n.server.close=="function")try{n.server.close()}catch(f){M.debug("Foreground server close failed.",f)}else if(t&&typeof t.unregisterServer=="function"&&n)try{t.unregisterServer(n.port)}catch(f){M.debug("Foreground server unregister failed.",f)}};return e.signal.aborted?(i(),{code:130,stdout:o,stderr:"",alreadyStreamed:typeof e.onStdout=="function",aborted:!0}):await new Promise(f=>{let d=!1;const y=()=>{if(e.signal&&typeof e.signal.removeEventListener=="function")try{e.signal.removeEventListener("abort",a)}catch(h){}if(t&&typeof t.off=="function")try{t.off("close",c)}catch(h){}},l=(h,u)=>{d||(d=!0,y(),f({code:h,stdout:o,stderr:"",alreadyStreamed:typeof e.onStdout=="function",aborted:u}))},a=()=>{i(),l(130,!0)},c=(h,u)=>{n&&Number(h)===Number(n.port)&&(!u||u===n)&&l(0,!1)};e.signal.addEventListener("abort",a,{once:!0}),t&&typeof t.on=="function"&&t.on("close",c)})}async function Ve(n,e,s,t){if(!Le.test(e))return null;const r=(e.match(Le)||[])[1],o=!!(t&&t.force),i=j.join("/workspace/node_modules/.bin",r),f=s.vfs.existsSync(i);if(!o&&!$t.test(r)&&f)return null;const d=e.match(/--port(?:=|\s+)(\d+)/),l=d?Number(d[1]):{ng:4200,vite:5173,astro:4321,next:3e3}[r]||3e3,a=typeof s.resolvePath=="function"?s.resolvePath("."):s.cwd||"/workspace",c=we(s,a,l);if(!c)return null;const h=o||f?`${r} is a native dev server and cannot execute inside this virtual runtime \u2014 using the CodeLab preview server instead.`:`${r} is not available in this virtual runtime \u2014 using the CodeLab preview server instead.`,u=`
|
|
254
257
|
> ${n}
|
|
255
258
|
> ${e}
|
|
256
259
|
|
|
257
|
-
${
|
|
260
|
+
${h}
|
|
258
261
|
|
|
259
|
-
\u279C Local: http://127.0.0.1:${
|
|
262
|
+
\u279C Local: http://127.0.0.1:${c.port}/
|
|
260
263
|
|
|
261
|
-
|
|
264
|
+
`;return await $e(c,s,u)}function ke(n,e){const s=[...n];if(s.length>0&&s[s.length-1]==="]"&&s.pop(),s.length===0)return 1;if(s[0]==="!")return ke(s.slice(1),e)===0?1:0;if(s.length===1)return s[0]?0:1;if(s.length===2){const[t,r]=s;if(t==="-z")return r.length===0?0:1;if(t==="-n")return r.length>0?0:1;if(t==="-e"||t==="-f"||t==="-d"||t==="-s"){const o=e.resolvePath(r);if(!e.vfs.existsSync(o))return 1;if(t==="-e")return 0;const i=e.vfs.statSync(o);if(t==="-f")return typeof i.isFile=="function"?i.isFile()?0:1:i.isFile?0:1;if(t==="-d")return typeof i.isDirectory=="function"?i.isDirectory()?0:1:i.isDirectory?0:1;if(t==="-s")return i.size>0?0:1}}if(s.length===3){const[t,r,o]=s;if(r==="="||r==="==")return t===o?0:1;if(r==="!=")return t!==o?0:1;const i=parseInt(t,10),f=parseInt(o,10);if(r==="-eq")return i===f?0:1;if(r==="-ne")return i!==f?0:1;if(r==="-lt")return i<f?0:1;if(r==="-le")return i<=f?0:1;if(r==="-gt")return i>f?0:1;if(r==="-ge")return i>=f?0:1}return 1}const V={async pwd(n,e){return{code:0,stdout:(e.shell?e.shell.cwd:e.cwd)+`
|
|
262
265
|
`,stderr:""}},async cd(n,e){const s=e.env&&e.env.HOME||"/home/codelab";j._homeDir=s;let t=n[0];!t||t==="~"?t=s:t==="-"&&(t=e.env.OLDPWD||e.cwd);const r=e.resolvePath(t);if(r===s&&!e.vfs.existsSync(r)&&typeof e.vfs.mkdirSync=="function")try{e.vfs.mkdirSync(r,{recursive:!0})}catch(f){}if(!e.vfs.existsSync(r))return{code:1,stdout:"",stderr:`cd: ${t}: No such file or directory
|
|
263
|
-
`};let o=!1;try{o=e.vfs.statSync(r).isDirectory()}catch(f){
|
|
264
|
-
`};const i=e.cwd;return e.cwd=r,e.env.OLDPWD=i,e.env.PWD=r,e.vfs&&typeof e.vfs._setCwd=="function"&&e.vfs._setCwd(r),e.shell&&(e.shell.cwd=r,e.shell.env.OLDPWD=i,e.shell.env.PWD=r),{code:0,stdout:"",stderr:""}},async ls(n,e){let s=!1,t=!1,r=!1,o=!1,i=!1,f=!1,
|
|
266
|
+
`};let o=!1;try{o=e.vfs.statSync(r).isDirectory()}catch(f){M.debug("cd statSync failed.",r,f)}if(!o)return{code:1,stdout:"",stderr:`cd: ${t}: Not a directory
|
|
267
|
+
`};const i=e.cwd;return e.cwd=r,e.env.OLDPWD=i,e.env.PWD=r,e.vfs&&typeof e.vfs._setCwd=="function"&&e.vfs._setCwd(r),e.shell&&(e.shell.cwd=r,e.shell.env.OLDPWD=i,e.shell.env.PWD=r),{code:0,stdout:"",stderr:""}},async ls(n,e){let s=!1,t=!1,r=!1,o=!1,i=!1,f=!1,d=!1,y=!1;const l=[];for(const m of n)if(m.startsWith("-")&&m.length>1)for(let S=1;S<m.length;S++){const b=m[S];b==="a"||b==="A"?s=!0:b==="l"?t=!0:b==="h"?r=!0:b==="r"?o=!0:b==="t"?i=!0:b==="1"?f=!0:b==="R"?d=!0:b==="d"&&(y=!0)}else l.push(m);l.length===0&&l.push(".");function a(m){return r?m<1024?`${m}B`.padStart(5," "):m<1024*1024?`${(m/1024).toFixed(1)}K`.padStart(5," "):`${(m/(1024*1024)).toFixed(1)}M`.padStart(5," "):String(m).padStart(6," ")}function c(m){const S=new Date(m||Date.now()),v=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][S.getMonth()],w=String(S.getDate()).padStart(2," "),$=String(S.getHours()).padStart(2,"0"),R=String(S.getMinutes()).padStart(2,"0");return`${v} ${w} ${$}:${R}`}let h="",u="",p=0;function g(m,S,b){b&&(h+=(h.length>0?`
|
|
265
268
|
`:"")+`${m}:
|
|
266
|
-
`);let
|
|
267
|
-
`,p=2;return}s?
|
|
268
|
-
`;for(const R of
|
|
269
|
-
`}}else if(f)for(const $ of
|
|
270
|
-
`;else h+=
|
|
271
|
-
`:"");if(
|
|
272
|
-
`,p=2;continue}let
|
|
273
|
-
`,p=2;continue}if(
|
|
269
|
+
`);let v=[];try{v=e.vfs.readdirSync(S)}catch($){u+=`ls: cannot open directory '${m}': ${$.message}
|
|
270
|
+
`,p=2;return}s?v=[".","..",...v]:v=v.filter($=>!$.startsWith("."));const w=v.map($=>{const R=S==="/"?"/"+$:S+"/"+$;let I=!1,C=0,E=Date.now();try{const T=e.vfs.statSync(R);I=T.isDirectory(),C=T.size,E=T.mtimeMs||Date.now()}catch(T){M.debug("ls statSync skipped.",R,T)}return{name:$,isDirectory:I,size:C,mtimeMs:E,absPath:R}});if(i?w.sort(($,R)=>R.mtimeMs-$.mtimeMs):w.sort(($,R)=>$.name.localeCompare(R.name)),o&&w.reverse(),t){let $=0;for(const R of w)$+=Math.ceil(R.size/512);h+=`total ${$}
|
|
271
|
+
`;for(const R of w){const I=R.isDirectory?"drwxr-xr-x":"-rw-r--r--";h+=`${I} 1 ${e.env.USER||"codelab"} ${e.env.USER||"codelab"} ${a(R.size)} ${c(R.mtimeMs)} ${R.name}
|
|
272
|
+
`}}else if(f)for(const $ of w)h+=`${$.name}
|
|
273
|
+
`;else h+=w.map($=>$.name).join(" ")+(w.length>0?`
|
|
274
|
+
`:"");if(d){for(const $ of w)if($.isDirectory&&$.name!=="."&&$.name!==".."){const R=m==="/"?"/"+$.name:m.replace(/\/+$/,"")+"/"+$.name;g(R,$.absPath,!0)}}}for(let m=0;m<l.length;m++){const S=l[m],b=e.resolvePath(S);if(!e.vfs.existsSync(b)){u+=`ls: cannot access '${S}': No such file or directory
|
|
275
|
+
`,p=2;continue}let v;try{v=e.vfs.statSync(b)}catch(w){u+=`ls: cannot access '${S}': ${w.message}
|
|
276
|
+
`,p=2;continue}if(v.isFile()||y){t?h+=`-rw-r--r-- 1 ${e.env.USER||"codelab"} ${e.env.USER||"codelab"} ${a(v.size)} ${c(v.mtimeMs)} ${S}
|
|
274
277
|
`:h+=`${S}
|
|
275
|
-
`;continue}g(S,b,l.length>1||
|
|
278
|
+
`;continue}g(S,b,l.length>1||d)}return{code:p,stdout:h,stderr:u}},async stat(n,e){if(n.length===0)return{code:1,stdout:"",stderr:`stat: missing operand
|
|
276
279
|
`};let s="",t="",r=0;for(const o of n){const i=e.resolvePath(o);if(!e.vfs.existsSync(i)){t+=`stat: cannot stat '${o}': No such file or directory
|
|
277
|
-
`,r=1;continue}const f=e.vfs.statSync(i),
|
|
278
|
-
`,s+=` Size: ${f.size} Blocks: ${Math.ceil(f.size/512)} IO Block: 4096 ${
|
|
280
|
+
`,r=1;continue}const f=e.vfs.statSync(i),d=f.isDirectory(),y=new Date(f.mtimeMs||Date.now());s+=` File: ${o}
|
|
281
|
+
`,s+=` Size: ${f.size} Blocks: ${Math.ceil(f.size/512)} IO Block: 4096 ${d?"directory":"regular file"}
|
|
279
282
|
`,s+=`Device: 1h/1d Inode: 100 Links: 1
|
|
280
|
-
`,s+=`Access: (${
|
|
283
|
+
`,s+=`Access: (${d?"0755/drwxr-xr-x":"0644/-rw-r--r--"}) Uid: (1000/${e.env.USER||"codelab"}) Gid: (1000/${e.env.USER||"codelab"})
|
|
281
284
|
`,s+=`Access: ${y.toISOString()}
|
|
282
285
|
`,s+=`Modify: ${y.toISOString()}
|
|
283
286
|
`,s+=`Change: ${y.toISOString()}
|
|
284
287
|
`,s+=` Birth: ${y.toISOString()}
|
|
285
|
-
`}return{code:r,stdout:s,stderr:t}},async cat(n,e){let s=!1,t=!1,r=!1;const o=[];for(const h of n)h==="-n"?s=!0:h==="-b"?t=!0:h==="-s"?r=!0:o.push(h);let i="",f=0,
|
|
286
|
-
`,f=1;continue}try{i+=e.vfs.readFileSync(u,"utf8")}catch(p){
|
|
287
|
-
`,f=1}}if(!s&&!t&&!r)return{code:f,stdout:i,stderr:
|
|
288
|
-
`);let l=[],a=1,
|
|
289
|
-
`),stderr:
|
|
288
|
+
`}return{code:r,stdout:s,stderr:t}},async cat(n,e){let s=!1,t=!1,r=!1;const o=[];for(const h of n)h==="-n"?s=!0:h==="-b"?t=!0:h==="-s"?r=!0:o.push(h);let i="",f=0,d="";if(o.length===0||o.length===1&&o[0]==="-")i=e.stdin||"";else for(const h of o){if(h==="-"){i+=e.stdin||"";continue}const u=e.resolvePath(h);if(!e.vfs.existsSync(u)){d+=`cat: ${h}: No such file or directory
|
|
289
|
+
`,f=1;continue}try{i+=e.vfs.readFileSync(u,"utf8")}catch(p){d+=`cat: ${h}: ${p.message}
|
|
290
|
+
`,f=1}}if(!s&&!t&&!r)return{code:f,stdout:i,stderr:d};const y=i.split(`
|
|
291
|
+
`);let l=[],a=1,c=!1;for(let h=0;h<y.length;h++){const u=y[h],p=u.trim()==="";r&&p&&c||(c=p,t?p?l.push(u):l.push(`${String(a++).padStart(6," ")} ${u}`):s?l.push(`${String(a++).padStart(6," ")} ${u}`):l.push(u))}return{code:f,stdout:l.join(`
|
|
292
|
+
`),stderr:d}},async head(n,e){let s=10;const t=[];for(let d=0;d<n.length;d++){const y=n[d];if(y==="-n"&&d+1<n.length){const l=parseInt(n[++d],10);s=isNaN(l)?10:l}else if(/^-\d+$/.test(y)){const l=parseInt(y.slice(1),10);s=isNaN(l)?10:l}else t.push(y)}function r(d){if(s<=0)return"";const y=d.split(`
|
|
290
293
|
`);return y.slice(0,s).join(`
|
|
291
294
|
`)+(y.length>0?`
|
|
292
|
-
`:"")}if(t.length===0)return{code:0,stdout:r(e.stdin||""),stderr:""};let o="",i="",f=0;for(const
|
|
293
|
-
`,f=1;continue}if(e.vfs.statSync&&e.vfs.statSync(y).isDirectory()){i+=`head: error reading '${
|
|
295
|
+
`:"")}if(t.length===0)return{code:0,stdout:r(e.stdin||""),stderr:""};let o="",i="",f=0;for(const d of t){const y=e.resolvePath(d);if(!e.vfs.existsSync(y)){i+=`head: cannot open '${d}' for reading: No such file or directory
|
|
296
|
+
`,f=1;continue}if(e.vfs.statSync&&e.vfs.statSync(y).isDirectory()){i+=`head: error reading '${d}': Is a directory
|
|
294
297
|
`,f=1;continue}try{const l=e.vfs.readFileSync(y,"utf8");o+=r(l)}catch(l){i+=`head: ${l.message}
|
|
295
|
-
`,f=1}}return{code:f,stdout:o,stderr:i}},async tail(n,e){let s=10;const t=[];for(let
|
|
296
|
-
`)?
|
|
297
|
-
`):
|
|
298
|
+
`,f=1}}return{code:f,stdout:o,stderr:i}},async tail(n,e){let s=10;const t=[];for(let d=0;d<n.length;d++){const y=n[d];if(y==="-n"&&d+1<n.length){const l=parseInt(n[++d],10);s=isNaN(l)?10:l}else if(/^-\d+$/.test(y)){const l=parseInt(y.slice(1),10);s=isNaN(l)?10:l}else t.push(y)}function r(d){if(s<=0)return"";const y=d.endsWith(`
|
|
299
|
+
`)?d.slice(0,-1).split(`
|
|
300
|
+
`):d.split(`
|
|
298
301
|
`);return y.slice(Math.max(0,y.length-s)).join(`
|
|
299
302
|
`)+`
|
|
300
|
-
`}if(t.length===0)return{code:0,stdout:r(e.stdin||""),stderr:""};let o="",i="",f=0;for(const
|
|
301
|
-
`,f=1;continue}if(e.vfs.statSync&&e.vfs.statSync(y).isDirectory()){i+=`tail: error reading '${
|
|
303
|
+
`}if(t.length===0)return{code:0,stdout:r(e.stdin||""),stderr:""};let o="",i="",f=0;for(const d of t){const y=e.resolvePath(d);if(!e.vfs.existsSync(y)){i+=`tail: cannot open '${d}' for reading: No such file or directory
|
|
304
|
+
`,f=1;continue}if(e.vfs.statSync&&e.vfs.statSync(y).isDirectory()){i+=`tail: error reading '${d}': Is a directory
|
|
302
305
|
`,f=1;continue}try{const l=e.vfs.readFileSync(y,"utf8");o+=r(l)}catch(l){i+=`tail: ${l.message}
|
|
303
306
|
`,f=1}}return{code:f,stdout:o,stderr:i}},async echo(n,e){let s=!1,t=!1,r=0;for(;r<n.length&&n[r].startsWith("-");){const i=n[r];if(i==="-n")s=!0;else if(i==="-e")t=!0;else if(i==="-ne"||i==="-en")s=!0,t=!0;else break;r++}let o=n.slice(r).join(" ");return t&&(o=o.replace(/\\n/g,`
|
|
304
307
|
`).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\b/g,"\b").replace(/\\f/g,"\f").replace(/\\\\/g,"\\")),{code:0,stdout:o+(s?"":`
|
|
305
308
|
`),stderr:""}},async printf(n,e){if(n.length===0)return{code:0,stdout:"",stderr:""};let s=n[0].replace(/\\n/g,`
|
|
306
|
-
`).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\\\/g,"\\"),t=1;return{code:0,stdout:s.replace(/%([-+0 #]*)(\d+)?(?:\.(\d+))?([sdifxX%])/g,(o,i,f,
|
|
309
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\\\/g,"\\"),t=1;return{code:0,stdout:s.replace(/%([-+0 #]*)(\d+)?(?:\.(\d+))?([sdifxX%])/g,(o,i,f,d,y)=>{if(y==="%")return"%";const l=n[t++];if(l===void 0)return"";let a="";if(y==="s")a=String(l),d!==void 0&&d!==""&&(a=a.slice(0,parseInt(d,10)));else if(y==="d"||y==="i")a=String(parseInt(l,10)||0);else if(y==="f"){const c=parseFloat(l)||0;a=d!==void 0&&d!==""?c.toFixed(parseInt(d,10)):String(c)}else if(y==="x")a=(Number(l)||0).toString(16);else if(y==="X")a=(Number(l)||0).toString(16).toUpperCase();else return o;if(f){const c=parseInt(f,10);if(i&&i.includes("0")&&(y==="d"||y==="i")){const h=a.startsWith("-");h&&(a=a.slice(1)),a=a.padStart(c-(h?1:0),"0"),h&&(a="-"+a)}else i&&i.includes("-")?a=a.padEnd(c," "):a=a.padStart(c," ")}return a}),stderr:""}},async grep(n,e){let s=!1,t=!1,r=!1,o=!1,i=!1,f=!1,d=!1,y=null;const l=[];for(let b=0;b<n.length;b++){const v=n[b];if(v.startsWith("-")&&v.length>1)for(let w=1;w<v.length;w++){const $=v[w];$==="i"?s=!0:$==="v"?t=!0:$==="n"?r=!0:$==="c"?o=!0:$==="l"?i=!0:$==="r"||$==="R"?f=!0:$==="E"&&(d=!0)}else y===null?y=v:l.push(v)}if(!y)return{code:2,stdout:"",stderr:`grep: missing pattern
|
|
307
310
|
`};let a;try{a=new RegExp(y,s?"i":"")}catch(b){return{code:2,stdout:"",stderr:`grep: invalid pattern: ${b.message}
|
|
308
|
-
`}}const
|
|
309
|
-
`);
|
|
310
|
-
`;return}if(!o){const k=
|
|
311
|
-
`}}}if(o){const I=
|
|
312
|
-
`}else h+=R}if(
|
|
313
|
-
`,g=!0;continue}try{const
|
|
314
|
-
`,g=!0}}}let S=1;return p>0?S=0:g&&(S=2),{code:S,stdout:h,stderr:u}},async find(n,e){let s=".",t=null,r=null,o=1/0,i=0;for(n[0]&&!n[0].startsWith("-")&&(s=n[0],i=1);i<n.length;){const a=n[i];if(a==="-name"&&i+1<n.length)t=n[++i];else if(a==="-type"&&i+1<n.length)r=n[++i];else if(a==="-maxdepth"&&i+1<n.length){const
|
|
311
|
+
`}}const c=[];if(f){const b=l.length>0?l:["."];for(const v of b){let $=function(R){try{const I=e.vfs.readdirSync(R);for(const C of I){const E=R==="/"?"/"+C:R+"/"+C;e.vfs.statSync(E).isDirectory()?$(E):c.push(E)}}catch(I){M.debug("grep directory walk skipped.",R,I)}};const w=e.resolvePath(v);e.vfs.existsSync(w)&&(e.vfs.statSync(w).isDirectory()?$(w):c.push(w))}}else for(const b of l)c.push(e.resolvePath(b));let h="",u="",p=0,g=!1;function m(b,v){const w=b.split(`
|
|
312
|
+
`);w.length>0&&w[w.length-1]===""&&w.pop();let $=0,R="";for(let I=0;I<w.length;I++){const C=w[I],E=a.test(C);if(t?!E:E){if($++,p++,i){h+=`${v}
|
|
313
|
+
`;return}if(!o){const k=v?`${v}:`:"",O=r?`${I+1}:`:"";R+=`${k}${O}${C}
|
|
314
|
+
`}}}if(o){const I=v?`${v}:`:"";h+=`${I}${$}
|
|
315
|
+
`}else h+=R}if(c.length===0)m(e.stdin||"","");else{const b=c.length>1;for(const v of c){if(!e.vfs.existsSync(v)){u+=`grep: ${v}: No such file or directory
|
|
316
|
+
`,g=!0;continue}try{const w=e.vfs.readFileSync(v,"utf8"),$=b?j.normalize(v.replace("/workspace/","")):"";m(w,$)}catch(w){u+=`grep: ${v}: ${w.message}
|
|
317
|
+
`,g=!0}}}let S=1;return p>0?S=0:g&&(S=2),{code:S,stdout:h,stderr:u}},async find(n,e){let s=".",t=null,r=null,o=1/0,i=0;for(n[0]&&!n[0].startsWith("-")&&(s=n[0],i=1);i<n.length;){const a=n[i];if(a==="-name"&&i+1<n.length)t=n[++i];else if(a==="-type"&&i+1<n.length)r=n[++i];else if(a==="-maxdepth"&&i+1<n.length){const c=parseInt(n[++i],10);o=isNaN(c)?1/0:c}i++}const f=t?Pe(t,!1):null,d=e.resolvePath(s),y=[];function l(a,c){if(c>o)return;let h=[];try{h=e.vfs.readdirSync(a)}catch{return}for(const u of h){const p=a==="/"?"/"+u:a+"/"+u;let g=!1;try{g=e.vfs.statSync(p).isDirectory()}catch(b){M.debug("find statSync skipped.",p,b)}const m=s==="."?"./"+p.replace(d.endsWith("/")?d:d+"/",""):p;let S=!0;r==="f"&&g&&(S=!1),r==="d"&&!g&&(S=!1),f&&!f.test(u)&&(S=!1),S&&y.push(m),g&&l(p,c+1)}}if(e.vfs.existsSync(d)){let a=!1;try{a=e.vfs.statSync(d).isDirectory()}catch(c){M.debug("find root statSync skipped.",d,c)}(!r||r==="d"&&a||r==="f"&&!a)&&(!f||f.test(j.basename(s)))&&y.push(s),a&&l(d,1)}else return{code:1,stdout:"",stderr:`find: '${s}': No such file or directory
|
|
315
318
|
`};return y.sort(),{code:0,stdout:y.join(`
|
|
316
319
|
`)+(y.length>0?`
|
|
317
|
-
`:""),stderr:""}},async wc(n,e){let s=!1,t=!1,r=!1;const o=[];for(const
|
|
318
|
-
`}if(o.length===0){const
|
|
319
|
-
`,l=1;continue}try{if(e.vfs.statSync(h).isDirectory()){y+=`wc: ${
|
|
320
|
-
`,l=1;continue}const p=e.vfs.readFileSync(h,"utf8"),g=i(p);a.lines+=g.lines,a.words+=g.words,a.bytes+=g.bytes,
|
|
321
|
-
`,l=1}}return o.length>1&&(
|
|
322
|
-
`};try{if(e.vfs.statSync(
|
|
323
|
-
`};y+=e.vfs.readFileSync(
|
|
320
|
+
`:""),stderr:""}},async wc(n,e){let s=!1,t=!1,r=!1;const o=[];for(const c of n)c==="-l"?s=!0:c==="-w"?t=!0:c==="-c"||c==="-m"?r=!0:o.push(c);!s&&!t&&!r&&(s=!0,t=!0,r=!0);function i(c){const h=c.length===0?0:(c.match(/\n/g)||[]).length,u=(c.trim().match(/\S+/g)||[]).length,p=typeof Buffer<"u"?Buffer.byteLength(c,"utf8"):typeof TextEncoder<"u"?new TextEncoder().encode(c).length:c.length;return{lines:h,words:u,bytes:p}}function f(c,h){let u=[];return s&&u.push(String(c.lines).padStart(4," ")),t&&u.push(String(c.words).padStart(4," ")),r&&u.push(String(c.bytes).padStart(4," ")),h&&u.push(h),u.join(" ")+`
|
|
321
|
+
`}if(o.length===0){const c=i(e.stdin||"");return{code:0,stdout:f(c,""),stderr:""}}let d="",y="",l=0,a={lines:0,words:0,bytes:0};for(const c of o){const h=e.resolvePath(c);if(!e.vfs.existsSync(h)){y+=`wc: ${c}: No such file or directory
|
|
322
|
+
`,l=1;continue}try{if(e.vfs.statSync(h).isDirectory()){y+=`wc: ${c}: Is a directory
|
|
323
|
+
`,l=1;continue}const p=e.vfs.readFileSync(h,"utf8"),g=i(p);a.lines+=g.lines,a.words+=g.words,a.bytes+=g.bytes,d+=f(g,c)}catch(u){y+=`wc: ${c}: ${u.message}
|
|
324
|
+
`,l=1}}return o.length>1&&(d+=f(a,"total")),{code:l,stdout:d,stderr:y}},async sort(n,e){let s=!1,t=!1,r=!1,o=!1,i=null,f=null;const d=[];for(let a=0;a<n.length;a++){const c=n[a];if(c==="-k"&&a+1<n.length)i=parseInt(n[++a],10)-1;else if(c==="-t"&&a+1<n.length)f=n[++a];else if(c.startsWith("-")&&c.length>1&&!c.startsWith("--"))for(let h=1;h<c.length;h++){const u=c[h];if(u==="r")s=!0;else if(u==="n")t=!0;else if(u==="u")r=!0;else if(u==="f")o=!0;else{d.push(c);break}}else d.push(c)}let y="";if(d.length===0)y=e.stdin||"";else for(const a of d){const c=e.resolvePath(a);if(!e.vfs.existsSync(c))return{code:1,stdout:"",stderr:`sort: cannot read '${a}': No such file or directory
|
|
325
|
+
`};try{if(e.vfs.statSync(c).isDirectory())return{code:1,stdout:"",stderr:`sort: read failed: ${a}: Is a directory
|
|
326
|
+
`};y+=e.vfs.readFileSync(c,"utf8")}catch(h){return{code:1,stdout:"",stderr:`sort: cannot read '${a}': ${h.message}
|
|
324
327
|
`}}}let l=y.split(`
|
|
325
|
-
`);return l.length>0&&l[l.length-1]===""&&l.pop(),l.sort((a,
|
|
328
|
+
`);return l.length>0&&l[l.length-1]===""&&l.pop(),l.sort((a,c)=>{let h=a,u=c;if(i!==null){const p=f?a.split(f):a.trim().split(/\s+/),g=f?c.split(f):c.trim().split(/\s+/);h=p[i]||"",u=g[i]||""}if(t){const p=parseFloat(h)||0,g=parseFloat(u)||0;return p-g}return o?h.toLowerCase().localeCompare(u.toLowerCase()):h.localeCompare(u)}),s&&l.reverse(),r&&(l=Array.from(new Set(l))),{code:0,stdout:l.join(`
|
|
326
329
|
`)+(l.length>0?`
|
|
327
330
|
`:""),stderr:""}},async uniq(n,e){let s=!1,t=!1,r=!1,o=!1;const i=[];for(const h of n)if(h.startsWith("-")&&h.length>1&&!h.startsWith("--"))for(let u=1;u<h.length;u++){const p=h[u];if(p==="c")s=!0;else if(p==="d")t=!0;else if(p==="u")r=!0;else if(p==="i")o=!0;else{i.push(h);break}}else i.push(h);let f=e.stdin||"";if(i.length>0){const h=e.resolvePath(i[0]);if(!e.vfs.existsSync(h))return{code:1,stdout:"",stderr:`uniq: ${i[0]}: No such file or directory
|
|
328
331
|
`};try{if(e.vfs.statSync(h).isDirectory())return{code:1,stdout:"",stderr:`uniq: error reading '${i[0]}': Is a directory
|
|
329
332
|
`};f=e.vfs.readFileSync(h,"utf8")}catch(u){return{code:1,stdout:"",stderr:`uniq: error reading '${i[0]}': ${u.message}
|
|
330
|
-
`}}}const
|
|
331
|
-
`);
|
|
332
|
-
`:
|
|
333
|
-
`);return{code:0,stdout:
|
|
334
|
-
`};function o(l,a){const
|
|
333
|
+
`}}}const d=f.split(`
|
|
334
|
+
`);d.length>0&&d[d.length-1]===""&&d.pop();const y=[];let l=null,a=0;for(const h of d){const u=o?h.toLowerCase():h,p=o&&l!==null?l.toLowerCase():l;u===p?a++:(l!==null&&y.push({line:l,count:a}),l=h,a=1)}l!==null&&y.push({line:l,count:a});let c="";for(const h of y)t&&h.count===1||r&&h.count>1||(s?c+=`${String(h.count).padStart(4," ")} ${h.line}
|
|
335
|
+
`:c+=`${h.line}
|
|
336
|
+
`);return{code:0,stdout:c,stderr:""}},async sed(n,e){let s=!1,t=null;const r=[];for(let l=0;l<n.length;l++){const a=n[l];a==="-i"?s=!0:a==="-e"&&l+1<n.length?t=n[++l]:t?r.push(a):t=a}if(!t)return{code:1,stdout:"",stderr:`sed: missing expression
|
|
337
|
+
`};function o(l,a){const c=[];let h="",u=!1;for(let p=0;p<l.length;p++){const g=l[p];u?(g===a?h+=a:h+="\\"+g,u=!1):g==="\\"?u=!0:g===a?(c.push(h),h=""):h+=g}return c.push(h),c}function i(l){if(t.startsWith("s")){const a=t[1],c=o(t.slice(2),a);if(c.length>=2){const h=c[0],u=c[1],p=c[2]||"",g=new RegExp(h,p.includes("g")?"g":"");return l.split(`
|
|
335
338
|
`).map(m=>m.replace(g,u)).join(`
|
|
336
|
-
`)}}if(t.endsWith("d")){const a=t.slice(0,-1);if(/^\d+$/.test(a)){const
|
|
337
|
-
`).filter((h,u)=>u+1!==
|
|
338
|
-
`)}if(a.startsWith("/")&&a.endsWith("/")){const
|
|
339
|
+
`)}}if(t.endsWith("d")){const a=t.slice(0,-1);if(/^\d+$/.test(a)){const c=parseInt(a,10);return l.split(`
|
|
340
|
+
`).filter((h,u)=>u+1!==c).join(`
|
|
341
|
+
`)}if(a.startsWith("/")&&a.endsWith("/")){const c=a.slice(1,-1),h=new RegExp(c);return l.split(`
|
|
339
342
|
`).filter(u=>!h.test(u)).join(`
|
|
340
343
|
`)}}return l}if(r.length===0)try{return{code:0,stdout:i(e.stdin||""),stderr:""}}catch(l){return{code:1,stdout:"",stderr:`sed: ${l.message}
|
|
341
|
-
`}}let f="",
|
|
342
|
-
`,y=1;continue}try{if(e.vfs.statSync(a).isDirectory()){
|
|
343
|
-
`,y=1;continue}const h=e.vfs.readFileSync(a,"utf8"),u=i(h);s?(e.vfs.writeFileSync(a,u),e.emitMutation("change",a)):f+=u}catch(
|
|
344
|
-
`,y=1}}return{code:y,stdout:f,stderr:
|
|
345
|
-
`};let o=e.stdin||"";if(r.length>0){o="";for(const
|
|
346
|
-
`};try{if(e.vfs.statSync(y).isDirectory())return{code:1,stdout:"",stderr:`awk: ${
|
|
347
|
-
`};o+=e.vfs.readFileSync(y,"utf8")}catch(l){return{code:1,stdout:"",stderr:`awk: ${
|
|
344
|
+
`}}let f="",d="",y=0;for(const l of r){const a=e.resolvePath(l);if(!e.vfs.existsSync(a)){d+=`sed: can't read ${l}: No such file or directory
|
|
345
|
+
`,y=1;continue}try{if(e.vfs.statSync(a).isDirectory()){d+=`sed: couldn't edit ${l}: is a directory
|
|
346
|
+
`,y=1;continue}const h=e.vfs.readFileSync(a,"utf8"),u=i(h);s?(e.vfs.writeFileSync(a,u),e.emitMutation("change",a)):f+=u}catch(c){d+=`sed: ${c.message}
|
|
347
|
+
`,y=1}}return{code:y,stdout:f,stderr:d}},async awk(n,e){let s=null,t=null;const r=[];for(let d=0;d<n.length;d++){const y=n[d];y==="-F"&&d+1<n.length?s=n[++d]:y.startsWith("-F")&&y.length>2?s=y.slice(2):t?r.push(y):t=y}if(!t)return{code:1,stdout:"",stderr:`awk: missing script
|
|
348
|
+
`};let o=e.stdin||"";if(r.length>0){o="";for(const d of r){const y=e.resolvePath(d);if(!e.vfs.existsSync(y))return{code:1,stdout:"",stderr:`awk: cannot open ${d} (No such file or directory)
|
|
349
|
+
`};try{if(e.vfs.statSync(y).isDirectory())return{code:1,stdout:"",stderr:`awk: ${d}: Is a directory
|
|
350
|
+
`};o+=e.vfs.readFileSync(y,"utf8")}catch(l){return{code:1,stdout:"",stderr:`awk: ${d}: ${l.message}
|
|
348
351
|
`}}}}const i=o.split(`
|
|
349
|
-
`);i.length>0&&i[i.length-1]===""&&i.pop();let f="";for(let
|
|
352
|
+
`);i.length>0&&i[i.length-1]===""&&i.pop();let f="";for(let d=0;d<i.length;d++){const y=i[d],l=s?s.length===1?y.split(s):y.split(new RegExp(s)):y.trim().split(/\s+/),a=d+1,c=l.length,h=t.match(/print\s+(.+)}/);if(h){const p=h[1].split(",").map(g=>g.trim()).map(g=>{if(g==="$0")return y;if(g==="$NF")return l[l.length-1]||"";if(g.startsWith("$")){const m=parseInt(g.slice(1),10)-1;return l[m]||""}return g==="NR"?String(a):g==="NF"?String(c):g.startsWith('"')&&g.endsWith('"')?g.slice(1,-1):g});f+=p.join(" ")+`
|
|
350
353
|
`}else f+=y+`
|
|
351
|
-
`}return{code:0,stdout:f,stderr:""}},async cut(n,e){let s=" ",t=null,r=null;const o=[];for(let a=0;a<n.length;a++){const
|
|
352
|
-
`};try{if(e.vfs.statSync(
|
|
353
|
-
`};f+=e.vfs.readFileSync(
|
|
354
|
-
`}}}}const
|
|
355
|
-
`);if(
|
|
356
|
-
`)+(
|
|
357
|
-
`:""),stderr:""}}const y=t?i(t):[],l=
|
|
354
|
+
`}return{code:0,stdout:f,stderr:""}},async cut(n,e){let s=" ",t=null,r=null;const o=[];for(let a=0;a<n.length;a++){const c=n[a];c==="-d"&&a+1<n.length?s=n[++a]:c.startsWith("-d")?s=c.slice(2):c==="-f"&&a+1<n.length?t=n[++a]:c.startsWith("-f")?t=c.slice(2):c==="-c"&&a+1<n.length?r=n[++a]:c.startsWith("-c")?r=c.slice(2):o.push(c)}function i(a){return a.split(",").map(c=>{if(c.includes("-")){const[u,p]=c.split("-"),g=u?Math.max(1,parseInt(u,10))-1:0,m=p?parseInt(p,10):1/0;return{start:g,end:m}}const h=Math.max(1,parseInt(c,10))-1;return{start:h,end:h+1}})}let f=e.stdin||"";if(o.length>0){f="";for(const a of o){const c=e.resolvePath(a);if(!e.vfs.existsSync(c))return{code:1,stdout:"",stderr:`cut: ${a}: No such file or directory
|
|
355
|
+
`};try{if(e.vfs.statSync(c).isDirectory())return{code:1,stdout:"",stderr:`cut: ${a}: Is a directory
|
|
356
|
+
`};f+=e.vfs.readFileSync(c,"utf8")}catch(h){return{code:1,stdout:"",stderr:`cut: ${a}: ${h.message}
|
|
357
|
+
`}}}}const d=f.split(`
|
|
358
|
+
`);if(d.length>0&&d[d.length-1]===""&&d.pop(),r){const a=i(r),c=d.map(h=>{let u="";for(const p of a)u+=h.slice(p.start,p.end===1/0?void 0:p.end);return u});return{code:0,stdout:c.join(`
|
|
359
|
+
`)+(c.length>0?`
|
|
360
|
+
`:""),stderr:""}}const y=t?i(t):[],l=d.map(a=>{if(y.length===0)return a;const c=a.split(s),h=[];for(const u of y){const p=Math.min(c.length,u.end);for(let g=u.start;g<p;g++)h.push(c[g]!==void 0?c[g]:"")}return h.join(s)});return{code:0,stdout:l.join(`
|
|
358
361
|
`)+(l.length>0?`
|
|
359
362
|
`:""),stderr:""}},async tr(n,e){let s=!1,t=!1,r="",o="";for(const h of n)h==="-d"?s=!0:h==="-s"?t=!0:h==="-ds"||h==="-sd"?(s=!0,t=!0):r?o||(o=h):r=h;function i(h){if(!h)return"";if(h==="[:lower:]")return"abcdefghijklmnopqrstuvwxyz";if(h==="[:upper:]")return"ABCDEFGHIJKLMNOPQRSTUVWXYZ";if(h==="[:digit:]")return"0123456789";if(h==="[:space:]")return`
|
|
360
363
|
\r\f\v`;let u=h.replace(/\\n/g,`
|
|
361
|
-
`).replace(/\\t/g," ").replace(/\\r/g,"\r");return u=u.replace(/(.)-(.)/g,(p,g,m)=>{const S=g.charCodeAt(0),b=m.charCodeAt(0);if(S>b)return g+"-"+m;let
|
|
364
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r");return u=u.replace(/(.)-(.)/g,(p,g,m)=>{const S=g.charCodeAt(0),b=m.charCodeAt(0);if(S>b)return g+"-"+m;let v="";for(let w=S;w<=b;w++)v+=String.fromCharCode(w);return v}),u}const f=i(r),d=i(o),y=t?d||f:"",l=e.stdin||"";let a="",c="";for(let h=0;h<l.length;h++){const u=l[h],p=f.indexOf(u);let g=u;if(p!==-1){if(s)continue;d.length>0&&(g=d[p]||d[d.length-1])}t&&y.includes(g)&&g===c||(a+=g,c=g)}return{code:0,stdout:a,stderr:""}},async diff(n,e){let s=!1;const t=[];for(const a of n)a==="-u"?s=!0:t.push(a);if(t.length<2)return{code:2,stdout:"",stderr:`diff: missing operand
|
|
362
365
|
`};const r=e.resolvePath(t[0]),o=e.resolvePath(t[1]);if(!e.vfs.existsSync(r))return{code:2,stdout:"",stderr:`diff: ${t[0]}: No such file or directory
|
|
363
366
|
`};if(!e.vfs.existsSync(o))return{code:2,stdout:"",stderr:`diff: ${t[1]}: No such file or directory
|
|
364
367
|
`};if(e.vfs.statSync(r).isDirectory())return{code:2,stdout:"",stderr:`diff: ${t[0]}: Is a directory
|
|
365
368
|
`};if(e.vfs.statSync(o).isDirectory())return{code:2,stdout:"",stderr:`diff: ${t[1]}: Is a directory
|
|
366
|
-
`};const
|
|
367
|
-
`};let r=0,o="";for(const i of t){const f=e.resolvePath(i);try{if(s){const
|
|
369
|
+
`};const d=e.vfs.readFileSync(r,"utf8"),y=e.vfs.readFileSync(o,"utf8");return d===y?{code:0,stdout:"",stderr:""}:{code:1,stdout:de(t[0],t[1],d,y),stderr:""}},async mkdir(n,e){let s=!1;const t=[];for(const i of n)i==="-p"?s=!0:t.push(i);if(t.length===0)return{code:1,stdout:"",stderr:`mkdir: missing operand
|
|
370
|
+
`};let r=0,o="";for(const i of t){const f=e.resolvePath(i);try{if(s){const d=f.split("/").filter(Boolean);let y="";for(const l of d)y+="/"+l,e.vfs.existsSync(y)||(e.vfs.mkdirSync(y,{recursive:!0}),e.emitMutation("create",y))}else e.vfs.mkdirSync(f,{recursive:s}),e.emitMutation("create",f)}catch(d){o+=`mkdir: cannot create directory '${i}': ${d.message}
|
|
368
371
|
`,r=1}}return{code:r,stdout:"",stderr:o}},async touch(n,e){if(n.length===0)return{code:1,stdout:"",stderr:`touch: missing file operand
|
|
369
372
|
`};let s=0,t="";for(const r of n){if(r.startsWith("-"))continue;const o=e.resolvePath(r);try{if(!e.vfs.existsSync(o))e.vfs.writeFileSync(o,""),e.emitMutation("create",o);else{const i=e.vfs.readFileSync(o,"utf8");e.vfs.writeFileSync(o,i),e.emitMutation("change",o)}}catch(i){t+=`touch: cannot touch '${r}': ${i.message}
|
|
370
373
|
`,s=1}}return{code:s,stdout:"",stderr:t}},async rm(n,e){let s=!1,t=!1;const r=[];for(const f of n)(f==="-r"||f==="-R"||f==="-rf"||f==="-fr")&&(s=!0),(f==="-f"||f==="-rf"||f==="-fr")&&(t=!0),f.startsWith("-")||r.push(f);if(r.length===0)return t?{code:0,stdout:"",stderr:""}:{code:1,stdout:"",stderr:`rm: missing operand
|
|
371
|
-
`};let o=0,i="";for(const f of r){const
|
|
372
|
-
`,o=1);continue}const y=e.vfs.statSync(
|
|
373
|
-
`,o=1;continue}try{typeof e.vfs.rmSync=="function"?e.vfs.rmSync(
|
|
374
|
+
`};let o=0,i="";for(const f of r){const d=e.resolvePath(f);if(!e.vfs.existsSync(d)){t||(i+=`rm: cannot remove '${f}': No such file or directory
|
|
375
|
+
`,o=1);continue}const y=e.vfs.statSync(d);if(y.isDirectory()&&!s){i+=`rm: cannot remove '${f}': Is a directory
|
|
376
|
+
`,o=1;continue}try{typeof e.vfs.rmSync=="function"?e.vfs.rmSync(d,{recursive:s,force:t}):y.isDirectory()?e.vfs.rmdirSync(d,{recursive:s}):e.vfs.unlinkSync(d),e.emitMutation("delete",d)}catch(l){t||(i+=`rm: cannot remove '${f}': ${l.message}
|
|
374
377
|
`,o=1)}}return{code:o,stdout:"",stderr:i}},async cp(n,e){let s=!1;const t=[];for(const f of n)f==="-r"||f==="-R"?s=!0:f.startsWith("-")||t.push(f);if(t.length<2)return{code:1,stdout:"",stderr:`cp: missing destination file operand
|
|
375
|
-
`};const r=e.resolvePath(t[t.length-1]),o=t.slice(0,-1);function i(f,
|
|
376
|
-
`};if(e.vfs.statSync(
|
|
377
|
-
`};try{let l=r;e.vfs.existsSync(r)&&e.vfs.statSync(r).isDirectory()&&(l=r==="/"?"/"+j.basename(
|
|
378
|
+
`};const r=e.resolvePath(t[t.length-1]),o=t.slice(0,-1);function i(f,d){if(e.vfs.statSync(f).isDirectory()){e.vfs.mkdirSync(d,{recursive:!0});const l=e.vfs.readdirSync(f);for(const a of l)i(f+"/"+a,d+"/"+a)}else{if(typeof e.vfs.copyFileSync=="function")e.vfs.copyFileSync(f,d);else{const l=e.vfs.readFileSync(f);e.vfs.writeFileSync(d,l)}e.emitMutation("create",d)}}for(const f of o){const d=e.resolvePath(f);if(!e.vfs.existsSync(d))return{code:1,stdout:"",stderr:`cp: cannot stat '${f}': No such file or directory
|
|
379
|
+
`};if(e.vfs.statSync(d).isDirectory()&&!s)return{code:1,stdout:"",stderr:`cp: -r not specified; omitting directory '${f}'
|
|
380
|
+
`};try{let l=r;e.vfs.existsSync(r)&&e.vfs.statSync(r).isDirectory()&&(l=r==="/"?"/"+j.basename(d):r+"/"+j.basename(d)),i(d,l)}catch(l){return{code:1,stdout:"",stderr:`cp: ${l.message}
|
|
378
381
|
`}}}return{code:0,stdout:"",stderr:""}},async mv(n,e){const s=n.filter(o=>!o.startsWith("-"));if(s.length<2)return{code:1,stdout:"",stderr:`mv: missing destination file operand
|
|
379
382
|
`};const t=e.resolvePath(s[0]);let r=e.resolvePath(s[1]);if(!e.vfs.existsSync(t))return{code:1,stdout:"",stderr:`mv: cannot stat '${s[0]}': No such file or directory
|
|
380
383
|
`};try{if(e.vfs.existsSync(r)&&e.vfs.statSync(r).isDirectory()&&(r=r==="/"?"/"+j.basename(t):r+"/"+j.basename(t)),typeof e.vfs.renameSync=="function")e.vfs.renameSync(t,r);else{const o=e.vfs.readFileSync(t);e.vfs.writeFileSync(r,o),e.vfs.unlinkSync(t)}e.emitMutation("rename",r)}catch(o){return{code:1,stdout:"",stderr:`mv: ${o.message}
|
|
@@ -383,9 +386,9 @@ ${B}
|
|
|
383
386
|
`};if(typeof e.vfs.chmodSync=="function")try{e.vfs.chmodSync(o,s)}catch(i){return{code:1,stdout:"",stderr:`chmod: ${i.message}
|
|
384
387
|
`}}}return{code:0,stdout:"",stderr:""}},async tree(n,e){let s=!1,t=1/0,r=".";for(let l=0;l<n.length;l++){const a=n[l];a==="-a"?s=!0:a==="-L"&&l+1<n.length?t=parseInt(n[++l],10)||1/0:a.startsWith("-")||(r=a)}const o=e.resolvePath(r);if(!e.vfs.existsSync(o))return{code:1,stdout:"",stderr:`tree: '${r}': No such file or directory
|
|
385
388
|
`};let i=`${r}
|
|
386
|
-
`,f=0,
|
|
387
|
-
`,S?(f++,y(m,a+(g?" ":"\u2502 "),
|
|
388
|
-
${f} directories, ${
|
|
389
|
+
`,f=0,d=0;function y(l,a,c){if(c>t)return;let h=[];try{h=e.vfs.readdirSync(l)}catch{return}s||(h=h.filter(u=>!u.startsWith("."))),h.sort();for(let u=0;u<h.length;u++){const p=h[u],g=u===h.length-1,m=l==="/"?"/"+p:l+"/"+p;let S=!1;try{S=e.vfs.statSync(m).isDirectory()}catch(b){M.debug("tree statSync skipped.",m,b)}i+=`${a}${g?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${p}
|
|
390
|
+
`,S?(f++,y(m,a+(g?" ":"\u2502 "),c+1)):d++}}return y(o,"",1),i+=`
|
|
391
|
+
${f} directories, ${d} files
|
|
389
392
|
`,{code:0,stdout:i,stderr:""}},async env(n,e){const s=Object.keys(e.env).sort();let t="";for(const r of s)r!=="?"&&!r.startsWith("__")&&(t+=`${r}=${e.env[r]}
|
|
390
393
|
`);return{code:0,stdout:t,stderr:""}},async export(n,e){const s=e.shell?e.shell.env:e.env;if(n.length===0){const t=Object.keys(s).filter(o=>o!=="?"&&!o.startsWith("__")).sort();let r="";for(const o of t)r+=`declare -x ${o}="${s[o]}"
|
|
391
394
|
`;return{code:0,stdout:r,stderr:""}}for(const t of n){const r=t.indexOf("=");if(r!==-1){const o=t.slice(0,r),i=t.slice(r+1);e.env[o]=i,e.shell&&(e.shell.env[o]=i)}else{const o=e.shell&&e.shell.env[t]!==void 0?e.shell.env[t]:e.env[t]||"";e.env[t]=o,e.shell&&(e.shell.env[t]=o)}}return{code:0,stdout:"",stderr:""}},async unset(n,e){for(const s of n)delete e.env[s],e.shell&&delete e.shell.env[s];return{code:0,stdout:"",stderr:""}},async which(n,e){if(n.length===0)return{code:1,stdout:"",stderr:""};let s="",t=0;for(const r of n)V[r]?s+=`/usr/bin/${r}
|
|
@@ -394,14 +397,14 @@ ${f} directories, ${c} files
|
|
|
394
397
|
`,stderr:""}:{code:0,stdout:`Linux
|
|
395
398
|
`,stderr:""}},async date(n,e){const s=new Date;if(n.length>0&&n[0].startsWith("+")){const t=n[0].slice(1),r=i=>String(i).padStart(2,"0");return{code:0,stdout:t.replace(/%Y/g,s.getFullYear()).replace(/%m/g,r(s.getMonth()+1)).replace(/%d/g,r(s.getDate())).replace(/%H/g,r(s.getHours())).replace(/%M/g,r(s.getMinutes())).replace(/%S/g,r(s.getSeconds())).replace(/%s/g,Math.floor(s.getTime()/1e3))+`
|
|
396
399
|
`,stderr:""}}return{code:0,stdout:s.toUTCString()+`
|
|
397
|
-
`,stderr:""}},async sleep(n,e){const s=parseFloat(n[0])||0,t=Math.max(0,s*1e3);return t<=0?{code:0,stdout:"",stderr:""}:e&&e.signal&&e.signal.aborted?{code:130,stdout:"",stderr:""}:(await new Promise(r=>{let o=null;const i=()=>{o&&clearTimeout(o),r()};e&&e.signal&&e.signal.addEventListener("abort",i,{once:!0}),o=setTimeout(()=>{e&&e.signal&&e.signal.removeEventListener("abort",i),r()},t)}),e&&e.signal&&e.signal.aborted?{code:130,stdout:"",stderr:""}:{code:0,stdout:"",stderr:""})},async"["(n,e){return{code:
|
|
400
|
+
`,stderr:""}},async sleep(n,e){const s=parseFloat(n[0])||0,t=Math.max(0,s*1e3);return t<=0?{code:0,stdout:"",stderr:""}:e&&e.signal&&e.signal.aborted?{code:130,stdout:"",stderr:""}:(await new Promise(r=>{let o=null;const i=()=>{o&&clearTimeout(o),r()};e&&e.signal&&e.signal.addEventListener("abort",i,{once:!0}),o=setTimeout(()=>{e&&e.signal&&e.signal.removeEventListener("abort",i),r()},t)}),e&&e.signal&&e.signal.aborted?{code:130,stdout:"",stderr:""}:{code:0,stdout:"",stderr:""})},async"["(n,e){return{code:ke(n,e),stdout:"",stderr:""}},async test(n,e){return{code:ke(n,e),stdout:"",stderr:""}},async true(){return{code:0,stdout:"",stderr:""}},async false(){return{code:1,stdout:"",stderr:""}},async clear(){return{code:0,stdout:"\x1B[2J\x1B[H",stderr:""}},async history(n,e){if(n[0]==="-c")return e.shell.history.length=0,{code:0,stdout:"",stderr:""};let s="";for(let t=0;t<e.shell.history.length;t++)s+=`${String(t+1).padStart(5," ")} ${e.shell.history[t]}
|
|
398
401
|
`;return{code:0,stdout:s,stderr:""}},async ps(n,e){let s=` PID TTY TIME CMD
|
|
399
402
|
`;s+=` 1 ? 00:00:00 sh
|
|
400
403
|
`;for(const[t,r]of e.shell.jobs.entries())r.status==="Running"&&(s+=`${String(r.pid).padStart(5," ")} ? 00:00:00 ${r.command}
|
|
401
404
|
`);return{code:0,stdout:s,stderr:""}},async jobs(n,e){let s="";for(const[t,r]of e.shell.jobs.entries()){const o=String(r.command||"").replace(/\s*&\s*$/,"");s+=`[${t}]+ ${r.status} ${o} &
|
|
402
405
|
`}return{code:0,stdout:s,stderr:""}},async kill(n,e){if(n.length===0)return{code:1,stdout:"",stderr:`kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ...
|
|
403
406
|
`};const s=n[n.length-1],t=parseInt(s.replace("%",""),10);if(isNaN(t))return{code:1,stdout:"",stderr:`kill: ${s}: arguments must be process or job IDs
|
|
404
|
-
`};let r=!1;for(const[i,f]of e.shell.jobs.entries())if(f.pid===t||i===t){f.status="Terminated",typeof f.abort=="function"&&f.abort(),r=!0;break}let o=!1;if(e.shell.portTable&&(typeof e.shell.portTable.killProcess=="function"&&(o=e.shell.portTable.killProcess(t)||o),typeof e.shell.portTable.unregisterByPid=="function"&&(o=e.shell.portTable.unregisterByPid(t)||o),typeof e.shell.portTable.listServers=="function"&&typeof e.shell.portTable.unregisterServer=="function")){for(const i of e.shell.portTable.listServers())if(i.pid!==void 0&&String(i.pid)===String(t)){if(i.server&&typeof i.server.close=="function")try{i.server.close()}catch(f){
|
|
407
|
+
`};let r=!1;for(const[i,f]of e.shell.jobs.entries())if(f.pid===t||i===t){f.status="Terminated",typeof f.abort=="function"&&f.abort(),r=!0;break}let o=!1;if(e.shell.portTable&&(typeof e.shell.portTable.killProcess=="function"&&(o=e.shell.portTable.killProcess(t)||o),typeof e.shell.portTable.unregisterByPid=="function"&&(o=e.shell.portTable.unregisterByPid(t)||o),typeof e.shell.portTable.listServers=="function"&&typeof e.shell.portTable.unregisterServer=="function")){for(const i of e.shell.portTable.listServers())if(i.pid!==void 0&&String(i.pid)===String(t)){if(i.server&&typeof i.server.close=="function")try{i.server.close()}catch(f){M.debug("kill server.close failed.",f)}if(typeof i.stop=="function")try{i.stop()}catch(f){M.debug("kill server.stop failed.",f)}e.shell.portTable.unregisterServer(i.port),o=!0}}return r||o?{code:0,stdout:"",stderr:""}:{code:1,stdout:"",stderr:`kill: (${s}) - No such process
|
|
405
408
|
`}},async dirname(n){const e=n[0]||".";return{code:0,stdout:j.dirname(e)+`
|
|
406
409
|
`,stderr:""}},async basename(n){const e=n[0]||"",s=n[1]||"";return{code:0,stdout:j.basename(e,s)+`
|
|
407
410
|
`,stderr:""}},async seq(n){let e=1,s=1,t=1;n.length===1?t=parseFloat(n[0])||1:n.length===2?(e=parseFloat(n[0])||1,t=parseFloat(n[1])||1):n.length>=3&&(e=parseFloat(n[0])||1,s=parseFloat(n[1])||1,t=parseFloat(n[2])||1);let r="";for(let o=e;s>0?o<=t:o>=t;o+=s)r+=`${o}
|
|
@@ -410,107 +413,107 @@ ${f} directories, ${c} files
|
|
|
410
413
|
`,stderr:""};if(s==="help"||s==="--help"||s==="-h")return{code:0,stdout:`usage: git <command> [<args>]
|
|
411
414
|
|
|
412
415
|
Common commands: init, clone, status, add, diff, commit, restore, reset, rm, branch, checkout, switch, merge, stash, tag, show, blame, remote, fetch, pull, push, log
|
|
413
|
-
`,stderr:""};const t=e.shell.gitState;t.branches instanceof Set||(t.branches=new Set(Array.isArray(t.branches)?t.branches:[t.branch||"main"])),t.remotes||(t.remotes=t.remoteUrl?{origin:t.remoteUrl}:{});let r=j.normalize(t.repoRoot||e.cwd);const o=
|
|
414
|
-
`};l&&!t.initialized&&(t.initialized=!0)}if(s==="clone"){let l=null;const a=[];for(let
|
|
415
|
-
`};const u=fe(
|
|
416
|
-
`};let p,g;h==="."?(p=e.cwd,g="."):h?(p=e.resolvePath(h),g=h):(p=j.join(e.cwd,u.repo),g=u.repo);const m=typeof e.onStdout=="function",S=
|
|
417
|
-
`);let b=!1,
|
|
416
|
+
`,stderr:""};const t=e.shell.gitState;t.branches instanceof Set||(t.branches=new Set(Array.isArray(t.branches)?t.branches:[t.branch||"main"])),t.remotes||(t.remotes=t.remoteUrl?{origin:t.remoteUrl}:{});let r=j.normalize(t.repoRoot||e.cwd);const o=Xe(t,e.vfs,r),i=l=>{const a=e.resolvePath(l),c=r==="/"?"/":r+"/";return a===r?".":a.startsWith(c)?ee(a.slice(c.length),r):""};if(s!=="init"&&s!=="clone"){const l=!!(e.vfs&&typeof e.vfs.existsSync=="function"&&(e.vfs.existsSync(j.join(r,".git"))||e.vfs.existsSync(j.join(e.cwd,".git"))));if(!t.initialized&&!l)return{code:128,stdout:"",stderr:`fatal: not a git repository (or any of the parent directories): .git
|
|
417
|
+
`};l&&!t.initialized&&(t.initialized=!0)}if(s==="clone"){let l=null;const a=[];for(let w=1;w<n.length;w++){const $=n[w];($==="-b"||$==="--branch")&&w+1<n.length?l=n[++w]:$.startsWith("--branch=")?l=$.slice(9):($==="--depth"||$==="-o"||$==="--origin")&&w+1<n.length?w++:$.startsWith("-")||a.push($)}const c=a[0],h=a[1];if(!c)return{code:128,stdout:"",stderr:`fatal: You must specify a repository to clone.
|
|
418
|
+
`};const u=fe(c);if(!u)return{code:128,stdout:"",stderr:`fatal: repository '${c}' does not exist or is not a valid GitHub repository URL
|
|
419
|
+
`};let p,g;h==="."?(p=e.cwd,g="."):h?(p=e.resolvePath(h),g=h):(p=j.join(e.cwd,u.repo),g=u.repo);const m=typeof e.onStdout=="function",S=w=>{m&&w&&e.onStdout(w)};S(`Cloning into '${g}'...
|
|
420
|
+
`);let b=!1,v=-1;try{const w=await he(c,e.vfs,{targetDir:p,branch:l,fetchImpl:e.shell&&e.shell.options?e.shell.options.fetchImpl:void 0,signal:e.signal,onFile:E=>e.emitMutation("create",E),onProgress:E=>{if(E){if(E.phase==="downloading"&&!b&&typeof E.total=="number"&&E.total>0&&(b=!0,S(`remote: Enumerating objects: ${E.total}, done.
|
|
418
421
|
`),S(`remote: Counting objects: 100% (${E.total}/${E.total}), done.
|
|
419
|
-
`)),E.phase==="downloading"&&typeof E.total=="number"&&E.total>0&&typeof E.loaded=="number"&&E.loaded<E.total){const T=Math.min(100,Math.max(0,Math.floor(E.loaded/E.total*100)));T>=
|
|
422
|
+
`)),E.phase==="downloading"&&typeof E.total=="number"&&E.total>0&&typeof E.loaded=="number"&&E.loaded<E.total){const T=Math.min(100,Math.max(0,Math.floor(E.loaded/E.total*100)));T>=v+10&&(v=T,S(`Receiving objects: ${T}% (${E.loaded}/${E.total})
|
|
420
423
|
`))}E.phase==="mounting"&&S(`Resolving deltas: 100% (${E.total||0}/${E.total||0}), done.
|
|
421
|
-
`)}}}),$=Object.assign({},
|
|
424
|
+
`)}}}),$=Object.assign({},w.headSnapshot);t.initialized=!0,t.branch=w.branch,t.branches.add(w.branch),t.remoteUrl=w.url,t.remotes.origin=w.url,t.repoRoot=p,t.headSnapshot=$,t.headFiles=$,t.commits=w.commits,t.headCommit=w.commits&&w.commits[0]&&w.commits[0].hash||"",o.clear();const R=Math.max(1,w.filesWritten),I=Math.max(.1,w.totalBytes/1024).toFixed(1);return b||(S(`remote: Enumerating objects: ${R}, done.
|
|
422
425
|
`),S(`remote: Counting objects: 100% (${R}/${R}), done.
|
|
423
426
|
`)),S(`Receiving objects: 100% (${R}/${R}), ${I} KiB, done.
|
|
424
427
|
`),{code:0,stdout:`Cloning into '${g}'...
|
|
425
428
|
remote: Enumerating objects: ${R}, done.
|
|
426
429
|
remote: Counting objects: 100% (${R}/${R}), done.
|
|
427
430
|
Receiving objects: 100% (${R}/${R}), ${I} KiB, done.
|
|
428
|
-
`,stderr:"",alreadyStreamed:m}}catch(
|
|
431
|
+
`,stderr:"",alreadyStreamed:m}}catch(w){if(e.signal&&e.signal.aborted)return{code:130,stdout:"",stderr:"",aborted:!0};const $=w&&w.message?w.message:String(w);return m&&S($.endsWith(`
|
|
429
432
|
`)?$:$+`
|
|
430
433
|
`),{code:128,stdout:"",stderr:$.endsWith(`
|
|
431
434
|
`)?$:$+`
|
|
432
|
-
`}}}if(s==="init"){let l=t.branch||"main",a=!1,
|
|
435
|
+
`}}}if(s==="init"){let l=t.branch||"main",a=!1,c=null;for(let m=1;m<n.length;m++){const S=n[m];(S==="-b"||S==="--initial-branch")&&m+1<n.length?l=n[++m]:S.startsWith("--initial-branch=")?l=S.slice(17)||l:S==="--empty-head"?a=!0:!S.startsWith("-")&&!c&&(c=S)}const h=j.normalize(c?e.resolvePath(c):e.cwd),u=j.join(h,".git"),p=!!t.initialized&&j.normalize(t.repoRoot||e.cwd)===h&&!a;if(G(e.vfs,u,e.emitMutation),(!p||!e.vfs.existsSync(j.join(u,"HEAD")))&&e.vfs.writeFileSync(j.join(u,"HEAD"),`ref: refs/heads/${l}
|
|
433
436
|
`),e.vfs.writeFileSync(j.join(u,"config"),`[core]
|
|
434
437
|
repositoryformatversion = 0
|
|
435
438
|
filemode = true
|
|
436
439
|
bare = false
|
|
437
440
|
`),e.emitMutation("create",j.join(u,"HEAD")),p&&!oe(t))return t.branches.add(t.branch||l),{code:0,stdout:`Reinitialized existing Git repository in ${u}/
|
|
438
|
-
`,stderr:""};const g={};if(!a){const m=L(e.vfs,h),S=
|
|
439
|
-
`,stderr:""}}r=j.normalize(t.repoRoot||e.cwd);const f
|
|
440
|
-
`}for(const $ of m)
|
|
441
|
-
`;return{code:0,stdout:
|
|
441
|
+
`,stderr:""};const g={};if(!a){const m=L(e.vfs,h),S=Ke(e.shell,h);for(const[b,v]of Object.entries(m))Object.prototype.hasOwnProperty.call(S,b)&&S[b]===v&&(g[b]=v)}return t.initialized=!0,t.branch=l,t.branches.add(l),t.repoRoot=h,t.headSnapshot=g,t.headFiles=g,t.commits=[],t.headCommit="",o.clear(),{code:0,stdout:`${p?"Reinitialized existing":"Initialized empty"} Git repository in ${u}/
|
|
442
|
+
`,stderr:""}}r=j.normalize(t.repoRoot||e.cwd);const f=je(),d=l=>{const a=l&&typeof l[".gitignore"]=="string"?l[".gitignore"]:t.headSnapshot&&typeof t.headSnapshot[".gitignore"]=="string"?t.headSnapshot[".gitignore"]:"";if(!a)return()=>!1;if(f&&typeof f.parseGitignoreRules=="function"&&typeof f.isIgnoredByRules=="function"){const c=f.parseGitignoreRules(a);return h=>f.isIgnoredByRules(h,c)}return()=>!1},y=()=>{if(f&&typeof f.saveBranchTip=="function"){f.saveBranchTip(t);return}(!t.branchHeads||typeof t.branchHeads!="object")&&(t.branchHeads={});const l=t.branch||"main";t.branchHeads[l]={headCommit:t.headCommit||"",headSnapshot:Object.assign({},t.headSnapshot||t.headFiles||{}),commits:Array.isArray(t.commits)?t.commits.map(a=>Object.assign({},a)):[]}};if(s==="status"){const l=n.includes("-s")||n.includes("--short")||n.includes("--porcelain"),a=L(e.vfs,r),c=t.headSnapshot||t.headFiles||{},h=d(a);Y(t,o,c);const u=oe(t),p=[],g=[],m=[],S=Array.from(o.keys()).sort();for(const v of S){const w=o.get(v),$=Object.prototype.hasOwnProperty.call(c,v),R=Object.prototype.hasOwnProperty.call(a,v);w===null?($&&p.push({status:"deleted",code:"D",path:v}),R&&!h(v)&&m.push(v)):(!$||u?p.push({status:"new file",code:"A",path:v}):w!==c[v]&&p.push({status:"modified",code:"M",path:v}),R?a[v]!==w&&g.push({status:"modified",code:"M",path:v}):g.push({status:"deleted",code:"D",path:v}))}for(const v of Object.keys(c).sort())o.has(v)||(Object.prototype.hasOwnProperty.call(a,v)?a[v]!==c[v]&&g.push({status:"modified",code:"M",path:v}):g.push({status:"deleted",code:"D",path:v}));for(const v of Object.keys(a).sort())!Object.prototype.hasOwnProperty.call(c,v)&&!o.has(v)&&(h(v)||m.push(v));if(g.sort((v,w)=>v.path.localeCompare(w.path)),m.sort(),l){const v=new Map;for(const $ of p)v.set($.path,{idx:$.code,wt:" "});for(const $ of g){const R=v.get($.path);R?R.wt=$.code:v.set($.path,{idx:" ",wt:$.code})}let w="";for(const $ of Array.from(v.keys()).sort()){const R=v.get($);w+=`${R.idx}${R.wt} ${$}
|
|
443
|
+
`}for(const $ of m)w+=`?? ${$}
|
|
444
|
+
`;return{code:0,stdout:w,stderr:""}}let b=`On branch ${t.branch}
|
|
442
445
|
`;if(t.remoteUrl&&(b+=`Your branch is up to date with 'origin/${t.branch}'.
|
|
443
446
|
|
|
444
447
|
`),p.length>0){b+=`Changes to be committed:
|
|
445
|
-
`;for(const
|
|
448
|
+
`;for(const v of p)b+=` ${v.status}: ${v.path}
|
|
446
449
|
`;b+=`
|
|
447
450
|
`}if(g.length>0){b+=`Changes not staged for commit:
|
|
448
|
-
`;for(const
|
|
451
|
+
`;for(const v of g)b+=` ${v.status}: ${v.path}
|
|
449
452
|
`;b+=`
|
|
450
453
|
`}if(m.length>0){b+=`Untracked files:
|
|
451
|
-
`;for(const
|
|
454
|
+
`;for(const v of m)b+=` ${v}
|
|
452
455
|
`;b+=`
|
|
453
456
|
`}return p.length===0&&g.length===0&&m.length===0&&(b+=`nothing to commit, working tree clean
|
|
454
|
-
`),{code:0,stdout:b,stderr:""}}if(s==="diff"){const l=n.includes("--staged")||n.includes("--cached"),
|
|
455
|
-
${R}`)}}else{if(!(Object.prototype.hasOwnProperty.call(p,b)||o.has(b)))continue;const
|
|
456
|
-
${I}`)}}return{code:0,stdout:S,stderr:""}}if(s==="add"){const l=n.slice(1),a=l.includes("-f")||l.includes("--force"),
|
|
457
|
+
`),{code:0,stdout:b,stderr:""}}if(s==="diff"){const l=n.includes("--staged")||n.includes("--cached"),c=n.slice(1).filter(b=>!b.startsWith("-")).map(i),h=c.length===0||c.includes("."),u=L(e.vfs,r),p=t.headSnapshot||t.headFiles||{};Y(t,o,p);const g=oe(t),m=Array.from(new Set([...Object.keys(p),...Object.keys(u),...Array.from(o.keys())])).sort();let S="";for(const b of m)if(!(!h&&!c.includes(b)))if(l){if(!o.has(b))continue;const v=o.get(b);if(!ue(t,b,v,p))continue;const w=!g&&Object.prototype.hasOwnProperty.call(p,b)?p[b]:"",$=v===null?"":String(v);if(w!==$){const R=de(`a/${b}`,`b/${b}`,w,$);R&&(S+=`diff --git a/${b} b/${b}
|
|
458
|
+
${R}`)}}else{if(!(Object.prototype.hasOwnProperty.call(p,b)||o.has(b)))continue;const w=o.has(b)?o.get(b):p[b],$=w==null?"":String(w),R=Object.prototype.hasOwnProperty.call(u,b)?u[b]:"";if($!==R){const I=de(`a/${b}`,`b/${b}`,$,R);I&&(S+=`diff --git a/${b} b/${b}
|
|
459
|
+
${I}`)}}return{code:0,stdout:S,stderr:""}}if(s==="add"){const l=n.slice(1),a=l.includes("-f")||l.includes("--force"),c=L(e.vfs,r),h=t.headSnapshot||t.headFiles||{},u=a?()=>!1:d(c),p=(g,m=!1)=>{const S=ee(g,r);if(!S)return;const b=Object.prototype.hasOwnProperty.call(c,S),v=Object.prototype.hasOwnProperty.call(h,S);!v&&!o.has(S)&&!m&&u(S)||(b?K(t,o,S,c[S],h):v?K(t,o,S,null,h):o.delete(S))};if(l.includes(".")||l.includes("-A")||l.includes("--all")||l.includes("-u")){const g=!l.includes("-u");for(const m of Object.keys(c)){const S=Object.prototype.hasOwnProperty.call(h,m);(!S&&g||S)&&p(m,!1)}for(const m of Object.keys(h))Object.prototype.hasOwnProperty.call(c,m)||p(m,!1);for(const m of Array.from(o.keys()))!Object.prototype.hasOwnProperty.call(c,m)&&!Object.prototype.hasOwnProperty.call(h,m)&&o.delete(m)}else for(const g of l){if(g.startsWith("-"))continue;const m=i(g);if(m)if(m==="."){for(const S of Object.keys(c))p(S,!1);for(const S of Object.keys(h))Object.prototype.hasOwnProperty.call(c,S)||p(S,!1);for(const S of Array.from(o.keys()))!Object.prototype.hasOwnProperty.call(c,S)&&!Object.prototype.hasOwnProperty.call(h,S)&&o.delete(S)}else{const S=m.replace(/\/+$/,"")+"/",b=Array.from(new Set([...Object.keys(c).filter(v=>v.startsWith(S)),...Object.keys(h).filter(v=>v.startsWith(S)),...Array.from(o.keys()).filter(v=>v.startsWith(S))]));if(b.length>0)for(const v of b)p(v,!1);else{if(!Object.prototype.hasOwnProperty.call(h,m)&&!o.has(m)&&u(m))return{code:1,stdout:"",stderr:`The following paths are ignored by one of your .gitignore files:
|
|
457
460
|
${m}
|
|
458
461
|
hint: Use -f if you really want to add them.
|
|
459
|
-
`};p(m,!0)}}}return{code:0,stdout:"",stderr:""}}if(s==="commit"){const l=L(e.vfs,r),a=t.headSnapshot||t.headFiles||{};if(n.some(
|
|
462
|
+
`};p(m,!0)}}}return{code:0,stdout:"",stderr:""}}if(s==="commit"){const l=L(e.vfs,r),a=t.headSnapshot||t.headFiles||{};if(n.some(v=>v==="-a"||v==="--all"||v.startsWith("-")&&!v.startsWith("--")&&v!=="-m"&&v.includes("a")))for(const v of Object.keys(a))Object.prototype.hasOwnProperty.call(l,v)?K(t,o,v,l[v],a):K(t,o,v,null,a);if(Y(t,o,a),o.size===0)return{code:1,stdout:`On branch ${t.branch}
|
|
460
463
|
nothing to commit, working tree clean
|
|
461
|
-
`,stderr:""};let h="Commit changes";const u=n.findIndex(
|
|
464
|
+
`,stderr:""};let h="Commit changes";const u=n.findIndex(v=>v==="-m"||v==="-am"||v==="-ma");u!==-1&&u+1<n.length&&(h=n[u+1]);const p=Object.assign({},a),g=[];for(const[v,w]of o.entries())g.push(`${v}:${w===null?"<DEL>":w}`),w===null?delete p[v]:p[v]=String(w);const m=Date.now(),S=re(`${t.headCommit||""}:${h}:${m}:${t.commits.length}:${g.join("|")}`),b=o.size;return t.headSnapshot=p,t.headFiles=p,t.commits.unshift({hash:S,author:`${e.env.USER||"CodeLab Developer"} <dev@codelab.internal>`,date:new Date(m).toUTCString(),timestamp:m,message:h,files:Object.assign({},p)}),t.headCommit=S,o.clear(),y(),{code:0,stdout:`[${t.branch} ${S}] ${h}
|
|
462
465
|
${b} file${b===1?"":"s"} changed
|
|
463
466
|
`,stderr:""}}if(s==="branch"){y();const l=n.findIndex(p=>p==="-d"||p==="-D");if(l!==-1&&l+1<n.length){const p=n[l+1];return p===t.branch?{code:1,stdout:"",stderr:`error: Cannot delete branch '${p}' checked out
|
|
464
467
|
`}:(t.branches.delete(p),t.branchHeads&&delete t.branchHeads[p],{code:0,stdout:`Deleted branch ${p}.
|
|
465
|
-
`,stderr:""})}const a=n.findIndex(p=>p==="-m"||p==="-M");if(a!==-1&&a+1<n.length){const p=t.branch,g=n[a+1];return t.branches.delete(p),t.branch=g,t.branches.add(g),t.branchHeads&&t.branchHeads[p]&&(t.branchHeads[g]=t.branchHeads[p],delete t.branchHeads[p]),{code:0,stdout:"",stderr:""}}const
|
|
468
|
+
`,stderr:""})}const a=n.findIndex(p=>p==="-m"||p==="-M");if(a!==-1&&a+1<n.length){const p=t.branch,g=n[a+1];return t.branches.delete(p),t.branch=g,t.branches.add(g),t.branchHeads&&t.branchHeads[p]&&(t.branchHeads[g]=t.branchHeads[p],delete t.branchHeads[p]),{code:0,stdout:"",stderr:""}}const c=n.slice(1).filter(p=>!p.startsWith("-"));if(c.length>0){for(const p of c)t.branches.add(p),t.branchHeads||(t.branchHeads={}),t.branchHeads[p]||(t.branchHeads[p]={headCommit:t.headCommit||"",headSnapshot:Object.assign({},t.headSnapshot||t.headFiles||{}),commits:Array.isArray(t.commits)?t.commits.map(g=>Object.assign({},g)):[]});return{code:0,stdout:"",stderr:""}}const h=n.includes("-a")||n.includes("--all");let u="";for(const p of t.branches)u+=p===t.branch?`* ${p}
|
|
466
469
|
`:` ${p}
|
|
467
470
|
`;return h&&t.remoteUrl&&(u+=` remotes/origin/${t.branch}
|
|
468
471
|
`),{code:0,stdout:u,stderr:""}}if(s==="checkout"||s==="switch"){const l=n.includes("-f")||n.includes("--force"),a=n.findIndex(p=>p==="-b"||p==="-B"||p==="-c"||p==="-C");if(a!==-1&&a+1<n.length){const p=n[a+1];y(),t.branches.add(p),t.branch=p,y();const g=j.join(r,".git/HEAD");return e.vfs.existsSync(j.join(r,".git"))&&e.vfs.writeFileSync(g,`ref: refs/heads/${p}
|
|
469
472
|
`),{code:0,stdout:`Switched to a new branch '${p}'
|
|
470
|
-
`,stderr:""}}const
|
|
471
|
-
`};if(t.branches.has(
|
|
472
|
-
`};const g=j.join(r,".git/HEAD");return e.vfs.existsSync(j.join(r,".git"))&&e.vfs.writeFileSync(g,`ref: refs/heads/${
|
|
473
|
-
`),{code:0,stdout:`Switched to branch '${
|
|
474
|
-
`,stderr:""}}return y(),t.branch=
|
|
475
|
-
`,stderr:""}}const h=i(
|
|
476
|
-
`,stderr:""}}return{code:1,stdout:"",stderr:`error: pathspec '${
|
|
477
|
-
`}}if(s==="restore"){const l=n.includes("--staged")||n.includes("-S"),a=n.includes("--worktree")||n.includes("-W")||!l,
|
|
473
|
+
`,stderr:""}}const c=n.slice(1).find(p=>p!=="--"&&!p.startsWith("-"));if(!c)return{code:1,stdout:"",stderr:`error: branch or path required
|
|
474
|
+
`};if(t.branches.has(c)&&!n.includes("--")){if(f&&typeof f.checkoutBranch=="function"){const p=f.checkoutBranch(e.shell,c,void 0,{force:l});if(!p.ok)return{code:1,stdout:"",stderr:(p.error||`error: cannot checkout '${c}'`)+`
|
|
475
|
+
`};const g=j.join(r,".git/HEAD");return e.vfs.existsSync(j.join(r,".git"))&&e.vfs.writeFileSync(g,`ref: refs/heads/${c}
|
|
476
|
+
`),{code:0,stdout:`Switched to branch '${c}'
|
|
477
|
+
`,stderr:""}}return y(),t.branch=c,{code:0,stdout:`Switched to branch '${c}'
|
|
478
|
+
`,stderr:""}}const h=i(c),u=t.headSnapshot||t.headFiles||{};if(h&&Object.prototype.hasOwnProperty.call(u,h)){const p=j.join(r,h);return G(e.vfs,j.dirname(p),e.emitMutation),e.vfs.writeFileSync(p,u[h]),e.emitMutation("change",p),{code:0,stdout:`Updated 1 path from the index
|
|
479
|
+
`,stderr:""}}return{code:1,stdout:"",stderr:`error: pathspec '${c}' did not match any file(s) known to git
|
|
480
|
+
`}}if(s==="restore"){const l=n.includes("--staged")||n.includes("-S"),a=n.includes("--worktree")||n.includes("-W")||!l,c=n.slice(1).filter(u=>!u.startsWith("-")&&u!=="--"),h=t.headSnapshot||t.headFiles||{};for(const u of c){const p=i(u);if(p){if(l)if(p===".")o.clear();else{const g=p.replace(/\/+$/,""),m=g+"/";o.delete(g);for(const S of Array.from(o.keys()))S.startsWith(m)&&o.delete(S)}if(a)if(p===".")for(const[g,m]of Object.entries(h)){const S=j.join(r,g);G(e.vfs,j.dirname(S),e.emitMutation),e.vfs.writeFileSync(S,m),e.emitMutation("change",S)}else{const g=p.replace(/\/+$/,""),m=g+"/",S=Object.keys(h).filter(b=>b.startsWith(m));if(S.length>0&&!Object.prototype.hasOwnProperty.call(h,g))for(const b of S){const v=!l&&o.has(b)&&o.get(b)!==null?o.get(b):h[b],w=j.join(r,b);G(e.vfs,j.dirname(w),e.emitMutation),e.vfs.writeFileSync(w,String(v)),e.emitMutation("change",w)}else{const b=!l&&o.has(g)&&o.get(g)!==null?o.get(g):Object.prototype.hasOwnProperty.call(h,g)?h[g]:void 0;if(b!==void 0){const v=j.join(r,g);G(e.vfs,j.dirname(v),e.emitMutation),e.vfs.writeFileSync(v,String(b)),e.emitMutation("change",v)}}}}}return{code:0,stdout:"",stderr:""}}if(s==="reset"){const l=n.includes("--hard"),a=n.includes("--soft"),c=l?"hard":a?"soft":"mixed",h=n.slice(1).filter(m=>!m.startsWith("-")&&m!=="--"),u=h[0];if(u&&(u==="HEAD"||/^HEAD(?:~\d*|\^+)$/i.test(u)||f&&typeof f.resolveCommitRef=="function"&&f.resolveCommitRef(t,u)!==null)&&h.length===1&&u!=="HEAD"&&f&&typeof f.resetToRef=="function"){const m=f.resetToRef(e.shell,u,c);return m.ok?{code:0,stdout:l&&m.commit?`HEAD is now at ${m.commit.hash} ${m.commit.message}
|
|
478
481
|
`:"",stderr:""}:{code:128,stdout:"",stderr:(m.error||`fatal: ambiguous argument '${u}'`)+`
|
|
479
|
-
`}}const g=h.filter(m=>m!=="HEAD");if(g.length>0&&!l&&!a){for(const m of g){const S=i(m);if(S)if(S===".")o.clear();else{const b=S.replace(/\/+$/,""),
|
|
480
|
-
`};const p=g=>{if(!g)return;const m=j.join(r,g);!l&&e.vfs.existsSync(m)&&(typeof e.vfs.rmSync=="function"?e.vfs.rmSync(m,{force:!0,recursive:a}):typeof e.vfs.unlinkSync=="function"&&e.vfs.unlinkSync(m),e.emitMutation("delete",m)),Object.prototype.hasOwnProperty.call(h,g)?o.set(g,null):o.delete(g)};for(const g of
|
|
481
|
-
`}}catch(
|
|
482
|
+
`}}const g=h.filter(m=>m!=="HEAD");if(g.length>0&&!l&&!a){for(const m of g){const S=i(m);if(S)if(S===".")o.clear();else{const b=S.replace(/\/+$/,""),v=b+"/";o.delete(b);for(const w of Array.from(o.keys()))w.startsWith(v)&&o.delete(w)}}return{code:0,stdout:"",stderr:""}}if(a||o.clear(),l){const m=t.headSnapshot||t.headFiles||{},S=L(e.vfs,r);for(const b of Object.keys(S))if(!Object.prototype.hasOwnProperty.call(m,b)){const v=j.join(r,b);typeof e.vfs.rmSync=="function"?e.vfs.rmSync(v,{force:!0}):typeof e.vfs.unlinkSync=="function"&&e.vfs.existsSync(v)&&e.vfs.unlinkSync(v),e.emitMutation("delete",v)}for(const[b,v]of Object.entries(m)){const w=j.join(r,b);G(e.vfs,j.dirname(w),e.emitMutation),e.vfs.writeFileSync(w,v),e.emitMutation("change",w)}}return y(),{code:0,stdout:"",stderr:""}}if(s==="rm"){const l=n.includes("--cached"),a=n.some(g=>g==="-r"||g==="-rf"||g==="-fr"),c=n.slice(1).filter(g=>!g.startsWith("-")&&g!=="--"),h=t.headSnapshot||t.headFiles||{},u=L(e.vfs,r);if(c.length===0)return{code:128,stdout:"",stderr:`usage: git rm [--cached] [-r] [-f] <file>...
|
|
483
|
+
`};const p=g=>{if(!g)return;const m=j.join(r,g);!l&&e.vfs.existsSync(m)&&(typeof e.vfs.rmSync=="function"?e.vfs.rmSync(m,{force:!0,recursive:a}):typeof e.vfs.unlinkSync=="function"&&e.vfs.unlinkSync(m),e.emitMutation("delete",m)),Object.prototype.hasOwnProperty.call(h,g)?o.set(g,null):o.delete(g)};for(const g of c){const m=i(g);if(!m)continue;if(m==="."){if(a){const v=Array.from(new Set([...Object.keys(h),...Object.keys(u),...Array.from(o.keys())]));for(const w of v)p(w)}continue}const S=m.replace(/\/+$/,"")+"/",b=a?Array.from(new Set([...Object.keys(h).filter(v=>v.startsWith(S)),...Object.keys(u).filter(v=>v.startsWith(S)),...Array.from(o.keys()).filter(v=>v.startsWith(S))])):[];if(b.length>0){for(const v of b)p(v);l||pe(e.vfs,j.join(r,m),e.emitMutation)}else{const v=j.join(r,m);if(!a&&e.vfs&&typeof e.vfs.existsSync=="function"&&e.vfs.existsSync(v)&&typeof e.vfs.statSync=="function")try{if(e.vfs.statSync(v).isDirectory())return{code:128,stdout:"",stderr:`fatal: not removing '${g}' recursively without -r
|
|
484
|
+
`}}catch(w){M.debug("Failed statting path in git rm.",v,w)}p(m)}}return{code:0,stdout:"",stderr:""}}if(s==="remote"){const l=n[1];if(!l){const a=Object.keys(t.remotes);return{code:0,stdout:a.length>0?a.join(`
|
|
482
485
|
`)+`
|
|
483
|
-
`:"",stderr:""}}if(l==="-v"||l==="--verbose"){let a="";for(const[
|
|
484
|
-
${
|
|
486
|
+
`:"",stderr:""}}if(l==="-v"||l==="--verbose"){let a="";for(const[c,h]of Object.entries(t.remotes))a+=`${c} ${h} (fetch)
|
|
487
|
+
${c} ${h} (push)
|
|
485
488
|
`;return{code:0,stdout:a,stderr:""}}if((l==="add"||l==="set-url")&&n[2]&&n[3])return t.remotes[n[2]]=n[3],n[2]==="origin"&&(t.remoteUrl=n[3]),{code:0,stdout:"",stderr:""};if(l==="get-url"&&n[2]){const a=t.remotes[n[2]];return a?{code:0,stdout:`${a}
|
|
486
489
|
`,stderr:""}:{code:2,stdout:"",stderr:`fatal: No such remote '${n[2]}'
|
|
487
490
|
`}}return(l==="remove"||l==="rm")&&n[2]?(delete t.remotes[n[2]],n[2]==="origin"&&(t.remoteUrl=null),{code:0,stdout:"",stderr:""}):{code:0,stdout:"",stderr:""}}if(s==="pull"||s==="fetch"){const l=t.remoteUrl||t.remotes.origin;if(!l)return{code:1,stdout:"",stderr:`fatal: No remote repository specified.
|
|
488
491
|
`};if(s==="fetch")return{code:0,stdout:`From ${l.replace(/\.git$/,"")}
|
|
489
492
|
* branch ${t.branch} -> FETCH_HEAD
|
|
490
|
-
`,stderr:""};try{const a=await he(l,e.vfs,{targetDir:r,branch:t.branch,fetchImpl:e.shell&&e.shell.options?e.shell.options.fetchImpl:void 0,signal:e.signal,onFile:h=>e.emitMutation("change",h)}),
|
|
493
|
+
`,stderr:""};try{const a=await he(l,e.vfs,{targetDir:r,branch:t.branch,fetchImpl:e.shell&&e.shell.options?e.shell.options.fetchImpl:void 0,signal:e.signal,onFile:h=>e.emitMutation("change",h)}),c=Object.assign({},a.headSnapshot);return t.headSnapshot=c,t.headFiles=c,{code:0,stdout:`From ${l.replace(/\.git$/,"")}
|
|
491
494
|
* branch ${a.branch} -> FETCH_HEAD
|
|
492
495
|
Already up to date.
|
|
493
|
-
`,stderr:""}}catch(a){if(e.signal&&e.signal.aborted)return{code:130,stdout:"",stderr:"",aborted:!0};const
|
|
494
|
-
`)?
|
|
495
|
-
`}}}if(s==="stash"){Array.isArray(t.stashes)||(t.stashes=[]);const l=n[1]&&!n[1].startsWith("-")?n[1]:"push";if(l==="list"){const a=t.stashes.map((
|
|
496
|
+
`,stderr:""}}catch(a){if(e.signal&&e.signal.aborted)return{code:130,stdout:"",stderr:"",aborted:!0};const c=a&&a.message?a.message:String(a);return{code:1,stdout:"",stderr:c.endsWith(`
|
|
497
|
+
`)?c:c+`
|
|
498
|
+
`}}}if(s==="stash"){Array.isArray(t.stashes)||(t.stashes=[]);const l=n[1]&&!n[1].startsWith("-")?n[1]:"push";if(l==="list"){const a=t.stashes.map((c,h)=>`stash@{${h}}: ${c.message}`);return{code:0,stdout:a.length?a.join(`
|
|
496
499
|
`)+`
|
|
497
|
-
`:"",stderr:""}}if(l==="clear")return t.stashes=[],{code:0,stdout:"",stderr:""};if(l==="drop"){const a=(n[2]||"stash@{0}").match(/(\d+)/),
|
|
498
|
-
`}:(t.stashes.splice(
|
|
499
|
-
`,stderr:""})}if(l==="pop"||l==="apply"){const a=(n[2]||"stash@{0}").match(/(\d+)/),
|
|
500
|
+
`:"",stderr:""}}if(l==="clear")return t.stashes=[],{code:0,stdout:"",stderr:""};if(l==="drop"){const a=(n[2]||"stash@{0}").match(/(\d+)/),c=a?parseInt(a[1],10):0;return c<0||c>=t.stashes.length?{code:1,stdout:"",stderr:`error: stash@{${c}} is not a valid reference
|
|
501
|
+
`}:(t.stashes.splice(c,1),{code:0,stdout:`Dropped stash@{${c}}
|
|
502
|
+
`,stderr:""})}if(l==="pop"||l==="apply"){const a=(n[2]||"stash@{0}").match(/(\d+)/),c=a?parseInt(a[1],10):0;if(f&&typeof f.stashApply=="function"){const h=f.stashApply(e.shell,c,l==="pop");return h.ok?{code:0,stdout:`Restored working directory from stash@{${c}}
|
|
500
503
|
`,stderr:""}:{code:1,stdout:"",stderr:(h.error||"No stash entries found.")+`
|
|
501
504
|
`}}return{code:1,stdout:"",stderr:`No stash entries found.
|
|
502
|
-
`}}if(l==="push"||l==="save"){let a;const
|
|
505
|
+
`}}if(l==="push"||l==="save"){let a;const c=n.findIndex(u=>u==="-m"||u==="--message");c!==-1&&n[c+1]?a=n[c+1]:l==="save"&&n[2]&&(a=n.slice(2).join(" "));const h=n.includes("-u")||n.includes("--include-untracked");if(f&&typeof f.stashPush=="function"){const u=f.stashPush(e.shell,a,h);return u.ok?{code:0,stdout:(u.label||"No local changes to save")+`
|
|
503
506
|
`,stderr:""}:{code:1,stdout:"",stderr:(u.label||"not a git repository")+`
|
|
504
507
|
`}}}return{code:1,stdout:"",stderr:`git stash: unknown subcommand '${l}'
|
|
505
|
-
`}}if(s==="merge"){const l=n.includes("--no-ff"),a=n.slice(1).find(
|
|
506
|
-
`};if(f&&typeof f.mergeBranch=="function"){const
|
|
507
|
-
`}:
|
|
508
|
+
`}}if(s==="merge"){const l=n.includes("--no-ff"),a=n.slice(1).find(c=>!c.startsWith("-"));if(!a)return{code:1,stdout:"",stderr:`fatal: No branch specified to merge.
|
|
509
|
+
`};if(f&&typeof f.mergeBranch=="function"){const c=f.mergeBranch(e.shell,a,void 0,{noFf:l});return!c.ok&&(!c.conflicts||c.conflicts.length===0)?{code:1,stdout:"",stderr:(c.error||`merge: ${a} - not something we can merge`)+`
|
|
510
|
+
`}:c.conflicts&&c.conflicts.length>0?{code:1,stdout:c.conflicts.map(h=>`CONFLICT (content): Merge conflict in ${h}`).join(`
|
|
508
511
|
`)+`
|
|
509
512
|
Automatic merge failed; fix conflicts and then commit the result.
|
|
510
|
-
`,stderr:""}:
|
|
513
|
+
`,stderr:""}:c.fastForward&&c.commit?{code:0,stdout:`Updating ..${c.commit.hash}
|
|
511
514
|
Fast-forward
|
|
512
|
-
`,stderr:""}:
|
|
513
|
-
[${t.branch} ${
|
|
515
|
+
`,stderr:""}:c.commit?{code:0,stdout:`Merge made by the 'ort' strategy.
|
|
516
|
+
[${t.branch} ${c.commit.hash}] ${c.commit.message}
|
|
514
517
|
`,stderr:""}:{code:0,stdout:`Already up to date.
|
|
515
518
|
`,stderr:""}}return{code:1,stdout:"",stderr:`git merge: SCM module unavailable
|
|
516
519
|
`}}if(s==="tag"){if((!t.tags||typeof t.tags!="object")&&(t.tags={}),n[1]==="-d"&&n[2])return t.tags[n[2]]?(delete t.tags[n[2]],{code:0,stdout:`Deleted tag '${n[2]}'
|
|
@@ -521,21 +524,21 @@ Fast-forward
|
|
|
521
524
|
`}}if(s==="show"){const l=n.slice(1).find(a=>!a.startsWith("-"))||"HEAD";if(f&&typeof f.showCommit=="function"){const a=f.showCommit(t,l);return a?{code:0,stdout:a,stderr:""}:{code:128,stdout:"",stderr:`fatal: bad object ${l}
|
|
522
525
|
`}}return{code:128,stdout:"",stderr:`fatal: bad object ${l}
|
|
523
526
|
`}}if(s==="blame"){const l=n.slice(1).find(h=>!h.startsWith("-"));if(!l)return{code:128,stdout:"",stderr:`usage: git blame <file>
|
|
524
|
-
`};const a=i(l),
|
|
527
|
+
`};const a=i(l),c=L(e.vfs,r);if(f&&typeof f.blameFile=="function"){const h=f.blameFile(t,a,c);return!h&&!Object.prototype.hasOwnProperty.call(c,a)?{code:128,stdout:"",stderr:`fatal: no such path '${l}' in HEAD
|
|
525
528
|
`}:{code:0,stdout:h,stderr:""}}return{code:128,stdout:"",stderr:`fatal: no such path '${l}' in HEAD
|
|
526
529
|
`}}if(s==="push"){const l=t.remoteUrl||t.remotes&&t.remotes.origin;return l?{code:128,stdout:"",stderr:`fatal: Authentication required to push to '${l}' from browser sandbox.
|
|
527
530
|
`}:{code:128,stdout:"",stderr:`fatal: No configured push destination.
|
|
528
531
|
Either specify the URL from the command-line or configure a remote repository using
|
|
529
532
|
|
|
530
533
|
git remote add <name> <url>
|
|
531
|
-
`}}if(s==="log"){const l=n.includes("--oneline");let a=t.commits.length;for(let h=1;h<n.length;h++)n[h]==="-n"&&n[h+1]?a=parseInt(n[++h],10)||a:/^-\d+$/.test(n[h])&&(a=parseInt(n[h].slice(1),10)||a);let
|
|
532
|
-
`;else{const u=h.author||"CodeLab Developer <dev@codelab.internal>",p=h.date||(h.timestamp?new Date(h.timestamp).toUTCString():new Date(0).toUTCString());
|
|
533
|
-
`,
|
|
534
|
-
`,
|
|
534
|
+
`}}if(s==="log"){const l=n.includes("--oneline");let a=t.commits.length;for(let h=1;h<n.length;h++)n[h]==="-n"&&n[h+1]?a=parseInt(n[++h],10)||a:/^-\d+$/.test(n[h])&&(a=parseInt(n[h].slice(1),10)||a);let c="";for(const h of t.commits.slice(0,a))if(l)c+=`${h.hash} ${h.message}
|
|
535
|
+
`;else{const u=h.author||"CodeLab Developer <dev@codelab.internal>",p=h.date||(h.timestamp?new Date(h.timestamp).toUTCString():new Date(0).toUTCString());c+=`commit ${h.hash}
|
|
536
|
+
`,c+=`Author: ${u}
|
|
537
|
+
`,c+=`Date: ${p}
|
|
535
538
|
|
|
536
|
-
`,
|
|
539
|
+
`,c+=` ${h.message}
|
|
537
540
|
|
|
538
|
-
`}return{code:0,stdout:
|
|
541
|
+
`}return{code:0,stdout:c,stderr:""}}return{code:1,stdout:"",stderr:`git: '${s}' is not a git command. See 'git --help'.
|
|
539
542
|
`}},async help(n,e){let s=`CodeLab POSIX Shell & UNIX Coreutils (Pure-JS Engine)
|
|
540
543
|
|
|
541
544
|
`;return s+=`Filesystem:
|
|
@@ -581,18 +584,18 @@ Either specify the URL from the command-line or configure a remote repository us
|
|
|
581
584
|
`,s+=` hey, ab, wrk Concurrent HTTP load generator & latency percentiles
|
|
582
585
|
`,s+=` chaos Network fault injection (delay, drop, error, partition, crash, heal)
|
|
583
586
|
`,s+=` sqlite3, redis-cli Interactive SQLite SQL engine & in-memory Redis data store CLI
|
|
584
|
-
`,{code:0,stdout:s,stderr:""}},async node(n,e){if(!
|
|
587
|
+
`,{code:0,stdout:s,stderr:""}},async node(n,e){if(!Re())return{code:1,stdout:"",stderr:`node: Virtual runtime engine is not available
|
|
585
588
|
`};if(n[0]==="-v"||n[0]==="--version")return{code:0,stdout:`v22.0.0
|
|
586
|
-
`,stderr:""};if(n.length===0||n[0]==="-i"||n[0]==="--interactive"){const o=(typeof e.onRequestStdin=="function"?e.onRequestStdin:null)||(e.shell&&e.shell.options&&typeof e.shell.options.onRequestStdin=="function"?e.shell.options.onRequestStdin:null);if(e.stdin&&!o){const i=await
|
|
589
|
+
`,stderr:""};if(n.length===0||n[0]==="-i"||n[0]==="--interactive"){const o=(typeof e.onRequestStdin=="function"?e.onRequestStdin:null)||(e.shell&&e.shell.options&&typeof e.shell.options.onRequestStdin=="function"?e.shell.options.onRequestStdin:null);if(e.stdin&&!o){const i=await q({mode:"repl",replCode:e.stdin,printReplResult:!0,stdin:"",env:e.env,cwd:e.cwd,vfs:e.vfs,pid:e.pid,isBackground:e.isBackground,onStdout:e.onStdout,onStderr:e.onStderr,signal:e.signal},e);return{code:i.ok?0:i.exitCode||1,stdout:i.stdout,stderr:i.stderr}}if(o&&!e.stdin){const i=`Welcome to Node.js v22.0.0.
|
|
587
590
|
Type ".help" for more information.
|
|
588
|
-
`;let f=i,
|
|
591
|
+
`;let f=i,d="";e.onStdout&&e.onStdout(i);const y="node_repl_"+Date.now()+"_"+Math.random().toString(36).slice(2,7),l=U();try{for(;!(e.signal&&e.signal.aborted);){const a=await o("> ");if(a==null)break;const c=String(a).trim();if(c===".exit")break;if(c===".help"){const u=`.break Sometimes you get stuck, this gets you out
|
|
589
592
|
.clear Break, and also clear the local context
|
|
590
593
|
.exit Exit the REPL
|
|
591
594
|
.help Print this help message
|
|
592
|
-
`;f+=u,e.onStdout&&e.onStdout(u);continue}if(
|
|
595
|
+
`;f+=u,e.onStdout&&e.onStdout(u);continue}if(c===".clear"||c===".break"){c===".clear"&&l&&typeof l.clearReplSession=="function"&&l.clearReplSession(y);continue}if(!c)continue;const h=await Oe({mode:"repl",replSessionId:y,replCode:String(a),printReplResult:!0,env:e.env,cwd:e.cwd,vfs:e.vfs,activePortTable:e.shell?e.shell.portTable:null,pid:e.pid,onRequestStdin:o,onStdout:u=>{f+=u,e.onStdout&&e.onStdout(u)},onStderr:u=>{d+=u,e.onStderr&&e.onStderr(u)},signal:e.signal})}}finally{l&&typeof l.clearReplSession=="function"&&l.clearReplSession(y)}return{code:0,stdout:f,stderr:d,alreadyStreamed:!0}}return{code:0,stdout:`Welcome to Node.js v22.0.0.
|
|
593
596
|
Type ".help" for more information.
|
|
594
|
-
`,stderr:""}}if(n[0]==="-e"||n[0]==="--eval"){const o=n[1]||"",i=await
|
|
595
|
-
`};const t=n.slice(1),r=await
|
|
597
|
+
`,stderr:""}}if(n[0]==="-e"||n[0]==="--eval"){const o=n[1]||"",i=await q({mode:"repl",replCode:o,printReplResult:!1,stdin:e.stdin||"",env:e.env,cwd:e.cwd,vfs:e.vfs,pid:e.pid,isBackground:e.isBackground,onStdout:e.onStdout,onStderr:e.onStderr,signal:e.signal},e);return{code:i.ok?0:i.exitCode||1,stdout:i.stdout,stderr:i.stderr}}if(n[0]==="-p"||n[0]==="--print"){const o=n[1]||"",i=await q({mode:"repl",replCode:o,printReplResult:!0,stdin:e.stdin||"",env:e.env,cwd:e.cwd,vfs:e.vfs,pid:e.pid,isBackground:e.isBackground,onStdout:e.onStdout,onStderr:e.onStderr,signal:e.signal},e);return{code:i.ok?0:i.exitCode||1,stdout:i.stdout,stderr:i.stderr}}if(n[0]==="--test"){const o=n[1]?e.resolvePath(n[1]):null;let i=[];if(o)i.push(o);else{const l=a=>{if(e.vfs.existsSync(a))for(const c of e.vfs.readdirSync(a)){const h=j.join(a,c);e.vfs.statSync(h).isDirectory()&&c!=="node_modules"&&c!==".git"?l(h):(c.endsWith(".test.js")||c.endsWith(".test.ts")||c==="test.js")&&i.push(h)}};l(e.cwd)}let f="",d="",y=!0;for(const l of i){const a=await q({mode:"test",entry:l,stdin:e.stdin||"",env:e.env,cwd:e.cwd,vfs:e.vfs,pid:e.pid,isBackground:e.isBackground,onStdout:e.onStdout,onStderr:e.onStderr,signal:e.signal},e);f+=a.stdout,d+=a.stderr,a.ok||(y=!1)}return{code:y?0:1,stdout:f,stderr:d}}const s=e.resolvePath(n[0]);if(!e.vfs.existsSync(s))return{code:1,stdout:"",stderr:`node: cannot find module '${n[0]}'
|
|
598
|
+
`};const t=n.slice(1),r=await q({mode:"run",entry:s,argv:["node",s,...t],stdin:e.stdin||"",env:e.env,cwd:e.cwd,vfs:e.vfs,pid:e.pid,isBackground:e.isBackground,onStdout:e.onStdout,onStderr:e.onStderr,signal:e.signal},e);return{code:r.ok?0:r.exitCode||1,stdout:r.stdout,stderr:r.stderr}},async"g++"(n,e){if(n.includes("--version")||n.includes("-v"))return{code:0,stdout:`clang version 18.1.8 (Target: wasm32-unknown-wasi)
|
|
596
599
|
Target: wasm32-unknown-wasi
|
|
597
600
|
Thread model: posix
|
|
598
601
|
InstalledDir: /usr/bin
|
|
@@ -602,18 +605,21 @@ Options:
|
|
|
602
605
|
-O0, -O1, -O2, -O3 Optimization level
|
|
603
606
|
-o <file> Write output to <file> (default: a.out)
|
|
604
607
|
-I <dir> Add directory to include search path
|
|
605
|
-
`,stderr:""};const s=[],t=[];let r=j.join(e.cwd,"a.out"),o="c++20",i="-O2";for(let a=0;a<n.length;a++){const
|
|
608
|
+
`,stderr:""};const s=[],t=[];let r=j.join(e.cwd,"a.out"),o="c++20",i="-O2";for(let a=0;a<n.length;a++){const c=n[a];if(c==="-o"&&a+1<n.length)r=e.resolvePath(n[++a]);else if(c.startsWith("-o")&&c.length>2)r=e.resolvePath(c.slice(2));else if(c.startsWith("-std=")){const h=c.slice(5);h==="c++17"||h==="gnu++17"?o="c++17":h==="c++23"||h==="c++2b"||h==="gnu++23"?o="c++23":o="c++20"}else c==="-O0"||c==="-O1"||c==="-O2"||c==="-O3"?i=c:c.startsWith("-I")||c.startsWith("-D")||c.startsWith("-W")?t.push(c):c.startsWith("-")||s.push(e.resolvePath(c))}if(s.length===0)return{code:1,stdout:"",stderr:`g++: fatal error: no input files
|
|
606
609
|
compilation terminated.
|
|
607
610
|
`};for(const a of s)if(!e.vfs.existsSync(a))return{code:1,stdout:"",stderr:`g++: error: ${a}: No such file or directory
|
|
608
611
|
`};const f=e.shell&&e.shell.options&&e.shell.options.cppCompiler||typeof globalThis<"u"&&globalThis.__codelabCppCompiler||typeof window<"u"&&window.__codelabCppCompiler;if(typeof f!="function")return{code:1,stdout:"",stderr:`g++: C++ toolchain is not enabled. Enable cppExtension from "@innovatorved/code-lab/extensions/cpp" to compile C++ files.
|
|
609
|
-
`};let
|
|
610
|
-
`};if(l.wasmBinary){if(e.vfs.writeFileSync(r,l.wasmBinary),typeof e.vfs.chmodSync=="function")try{e.vfs.chmodSync(r,493)}catch(a){
|
|
611
|
-
`,stderr:""};
|
|
612
|
+
`};let d="",y="";const l=await f({entry:s[0],sourceFiles:s,outputPath:r,std:o,optLevel:i,extraFlags:t,vfs:e.vfs,onStdout:a=>{d+=a,e.onStdout&&e.onStdout(a)},onStderr:a=>{y+=a,e.onStderr&&e.onStderr(a)}});if(!l||l.exitCode!==0)return{code:l&&l.exitCode||1,stdout:d,stderr:y||`g++: error: linker command failed with exit code 1
|
|
613
|
+
`};if(l.wasmBinary){if(e.vfs.writeFileSync(r,l.wasmBinary),typeof e.vfs.chmodSync=="function")try{e.vfs.chmodSync(r,493)}catch(a){M.debug("chmodSync failed on compiled binary",a)}typeof e.emitMutation=="function"&&e.emitMutation("create",r)}return{code:0,stdout:d,stderr:y}},async"clang++"(n,e){return V["g++"](n,e)},async"c++"(n,e){return V["g++"](n,e)},async python3(n,e){if(n[0]==="--version"||n[0]==="-V")return{code:0,stdout:`Python 3.12.8 (CPython WebAssembly via Pyodide)
|
|
614
|
+
`,stderr:""};if(n[0]==="-m"&&n[1]==="http.server"){let y=8e3,l=".";for(let u=2;u<n.length;u++){const p=n[u];(p==="-d"||p==="--directory")&&n[u+1]?l=n[++u]:p.startsWith("--directory=")?l=p.slice(12)||".":p==="-b"||p==="--bind"?u++:/^\d+$/.test(p)&&(y=Number(p))}const a=e.resolvePath(l);if(!e.vfs.existsSync(a))return{code:1,stdout:"",stderr:`python3: http.server: ${l}: No such file or directory
|
|
615
|
+
`};const c=we(e,a,y);if(!c)return{code:1,stdout:"",stderr:`python3: http.server: no virtual port table available
|
|
616
|
+
`};const h=`Serving HTTP on 127.0.0.1 port ${c.port} (http://127.0.0.1:${c.port}/) ...
|
|
617
|
+
`;return await $e(c,e,h)}const s=e.shell&&e.shell.options&&e.shell.options.pythonCompiler||typeof globalThis<"u"&&globalThis.__codelabPythonCompiler||typeof window<"u"&&window.__codelabPythonCompiler,t=(typeof e.onRequestStdin=="function"?e.onRequestStdin:null)||(e.shell&&e.shell.options&&typeof e.shell.options.onRequestStdin=="function"?e.shell.options.onRequestStdin:void 0);if(n.length===0||n[0]==="-i"){if(!e.stdin&&!t)return{code:0,stdout:`Python 3.12.8 (CPython WebAssembly via Pyodide)
|
|
612
618
|
`,stderr:""};if(typeof s!="function")return{code:1,stdout:"",stderr:`python3: Python WebAssembly toolchain is not enabled. Enable pythonExtension from "@innovatorved/code-lab/extensions/python".
|
|
613
|
-
`};if(e.stdin&&!t){let
|
|
619
|
+
`};if(e.stdin&&!t){let c="",h="";const u=await s({source:e.stdin,stdin:"",env:e.env,cwd:e.cwd,vfs:e.vfs,signal:e.signal,onStdout:p=>{c+=p,e.onStdout&&e.onStdout(p)},onStderr:p=>{h+=p,e.onStderr&&e.onStderr(p)}});return{code:u&&u.ok?0:u&&u.exitCode||1,stdout:c,stderr:h}}const y=`Python 3.12.8 (CPython WebAssembly via Pyodide)
|
|
614
620
|
Type "exit()" or Ctrl+D to exit.
|
|
615
|
-
`;let l=y,a="";for(e.onStdout&&e.onStdout(y);!(e.signal&&e.signal.aborted);){const
|
|
616
|
-
`};let i="",f="";const
|
|
621
|
+
`;let l=y,a="";for(e.onStdout&&e.onStdout(y);!(e.signal&&e.signal.aborted);){const c=await t(">>> ");if(c==null)break;const h=String(c).trim();if(h==="exit()"||h==="quit()")break;h&&await s({source:String(c),repl:!0,stdin:"",env:e.env,cwd:e.cwd,vfs:e.vfs,signal:e.signal,onRequestStdin:t,onStdout:u=>{l+=u,e.onStdout&&e.onStdout(u)},onStderr:u=>{a+=u,e.onStderr&&e.onStderr(u)}})}return{code:0,stdout:l,stderr:a,alreadyStreamed:!0}}let r,o;if(n[0]==="-c"&&n.length>1?r=n[1]:n[0].startsWith("-")||(o=e.resolvePath(n[0])),typeof s!="function")return{code:1,stdout:"",stderr:`python3: Python WebAssembly toolchain is not enabled. Enable pythonExtension from "@innovatorved/code-lab/extensions/python".
|
|
622
|
+
`};let i="",f="";const d=await s({entry:o,source:r,stdin:e.stdin||"",env:e.env,cwd:e.cwd,vfs:e.vfs,signal:e.signal,onRequestStdin:t,onStdout:y=>{i+=y,e.onStdout&&e.onStdout(y)},onStderr:y=>{f+=y,e.onStderr&&e.onStderr(y)}});return{code:d&&d.ok?0:d&&d.exitCode||1,stdout:i,stderr:f}},async python(n,e){return V.python3(n,e)},async pytest(n,e){if(n.length>0&&(n[0]==="--version"||n[0]==="-V"))return{code:0,stdout:`pytest 8.3.4 (Python 3.12 WebAssembly)
|
|
617
623
|
`,stderr:""};let t=n.filter(r=>!r.startsWith("-"))[0];if(!t&&e.vfs)try{t=Object.keys(typeof e.vfs.toSnapshot=="function"?e.vfs.toSnapshot("/workspace"):e.vfs.files||{}).find(o=>/(?:^|\/)(?:test_.*|.*_test|test)\.py$/i.test(o))}catch(r){}return t=t||"test.py",V.python3([t],e)},async pip(n,e){if(n.length===0||n[0]==="--version"||n[0]==="-V")return{code:0,stdout:`pip 24.0 from /usr/lib/python/pip (python 3.12)
|
|
618
624
|
`,stderr:""};if(n[0]==="install"){const s=n.slice(1).filter(r=>!r.startsWith("-")),t=e.shell&&e.shell.options&&e.shell.options.pythonToolchain||typeof globalThis<"u"&&globalThis.__codelabPythonToolchain||typeof window<"u"&&window.__codelabPythonToolchain;if(t&&typeof t.installPackages=="function"){const r=await t.installPackages(s);return r.ok?{code:0,stdout:`Successfully installed ${r.installed.join(", ")||"packages"}
|
|
619
625
|
`,stderr:""}:{code:1,stdout:"",stderr:`ERROR: Could not find a version that satisfies the requirement ${r.error||s.join(", ")}
|
|
@@ -633,13 +639,13 @@ Commands:
|
|
|
633
639
|
-e <code> Evaluate JavaScript
|
|
634
640
|
`,stderr:""};if(s==="init"){const o=j.join(e.cwd,"package.json"),i=j.basename(e.cwd)||"app";e.vfs.existsSync(o)||(e.vfs.writeFileSync(o,JSON.stringify({name:i,module:"index.ts",type:"module",devDependencies:{"@types/bun":"latest"},peerDependencies:{typescript:"^5.0.0"}},null,2)+`
|
|
635
641
|
`),typeof e.emitMutation=="function"&&e.emitMutation("create",o));const f=j.join(e.cwd,"index.ts");e.vfs.existsSync(f)||(e.vfs.writeFileSync(f,`console.log("Hello via Bun!");
|
|
636
|
-
`),typeof e.emitMutation=="function"&&e.emitMutation("create",f));const
|
|
637
|
-
`),typeof e.emitMutation=="function"&&e.emitMutation("create",
|
|
638
|
-
`,stderr:""}}if(s==="install"||s==="i"||s==="ci"){const o=n.slice(1).filter(f=>!f.startsWith("-")),i=n.some(f=>f==="-D"||f==="--dev"||f==="--save-dev"||f==="-d");if(o.length===0){const{data:f}=
|
|
639
|
-
`,stderr:""}:await ne(
|
|
642
|
+
`),typeof e.emitMutation=="function"&&e.emitMutation("create",f));const d=j.join(e.cwd,"tsconfig.json");return e.vfs.existsSync(d)||(e.vfs.writeFileSync(d,JSON.stringify({compilerOptions:{lib:["ESNext"],module:"esnext",target:"esnext",moduleResolution:"bundler",moduleDetection:"force",allowImportingTsExtensions:!0,noEmit:!0,composite:!0,strict:!0,downlevelIteration:!0,skipLibCheck:!0,jsx:"react-jsx",allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0,allowJs:!0,types:["bun-types"]}},null,2)+`
|
|
643
|
+
`),typeof e.emitMutation=="function"&&e.emitMutation("create",d)),{code:0,stdout:"Done! A package.json file was created in "+e.cwd+`
|
|
644
|
+
`,stderr:""}}if(s==="install"||s==="i"||s==="ci"){const o=n.slice(1).filter(f=>!f.startsWith("-")),i=n.some(f=>f==="-D"||f==="--dev"||f==="--save-dev"||f==="-d");if(o.length===0){const{data:f}=H(e.vfs,e.cwd),d=Object.keys(Object.assign({},f.dependencies||{},f.devDependencies||{}));return d.length===0?{code:0,stdout:`up to date
|
|
645
|
+
`,stderr:""}:await ne(d,e,{manager:"bun",header:"bun install v1.1.20 (1.1.20)"})}return await ne(o,e,{manager:"bun",dev:i,header:"bun add v1.1.20 (1.1.20)"})}if(s==="add"){let o=n.slice(1).filter(f=>!f.startsWith("-"));const i=n.some(f=>f==="-D"||f==="--dev"||f==="--save-dev"||f==="-d");if(o.length===0){const{data:f}=H(e.vfs,e.cwd);o=Object.keys(f.dependencies||{})}return o.length===0?{code:0,stdout:`up to date
|
|
640
646
|
`,stderr:""}:await ne(o,e,{manager:"bun",dev:i,header:"bun add v1.1.20 (1.1.20)"})}if(s==="remove"||s==="rm"){const o=n.slice(1).filter(i=>!i.startsWith("-"));for(const i of o)be(i,e);return{code:0,stdout:`removed ${o.length} package(s)
|
|
641
|
-
`,stderr:""}}if(s==="pm")return n[1]==="ls"?{code:0,stdout:ie(e),stderr:""}:{code:0,stdout:"",stderr:""};if(s==="-e"){const o=n[1]||"",i=await
|
|
642
|
-
`}}const t=e.resolvePath(s);if(e.vfs.existsSync(t)){const o=n.slice(1),i=await
|
|
647
|
+
`,stderr:""}}if(s==="pm")return n[1]==="ls"?{code:0,stdout:ie(e),stderr:""}:{code:0,stdout:"",stderr:""};if(s==="-e"){const o=n[1]||"",i=await q({mode:"repl",replCode:o,printReplResult:!1,stdin:e.stdin||"",env:e.env,cwd:e.cwd,vfs:e.vfs,pid:e.pid,isBackground:e.isBackground,onStdout:e.onStdout,onStderr:e.onStderr,signal:e.signal},e);return{code:i.ok?0:i.exitCode||1,stdout:i.stdout,stderr:i.stderr}}if(s==="test"){const o=n[1]?e.resolvePath(n[1]):null;let i=[];if(o)i.push(o);else{const l=a=>{if(e.vfs.existsSync(a))for(const c of e.vfs.readdirSync(a)){const h=j.join(a,c);e.vfs.statSync(h).isDirectory()&&c!=="node_modules"&&c!==".git"?l(h):(c.endsWith(".test.js")||c.endsWith(".test.ts"))&&i.push(h)}};l(e.cwd)}let f="",d="",y=!0;for(const l of i){const a=await q({mode:"test",entry:l,stdin:e.stdin||"",env:e.env,cwd:e.cwd,vfs:e.vfs,pid:e.pid,isBackground:e.isBackground,onStdout:e.onStdout,onStderr:e.onStderr,signal:e.signal},e);f+=a.stdout,d+=a.stderr,a.ok||(y=!1)}return{code:y?0:1,stdout:f,stderr:d}}if(s==="run"){const o=n[1];if(!o)return{code:0,stdout:ie(e),stderr:""};const i=e.resolvePath(o);if(e.vfs.existsSync(i)){const d=n.slice(2),y=await q({mode:"run",entry:i,argv:["bun",i,...d],stdin:e.stdin||"",env:e.env,cwd:e.cwd,vfs:e.vfs,pid:e.pid,isBackground:e.isBackground,onStdout:e.onStdout,onStderr:e.onStderr,signal:e.signal},e);return{code:y.ok?0:y.exitCode||1,stdout:y.stdout,stderr:y.stderr}}const{data:f}=H(e.vfs,e.cwd);return f.scripts&&f.scripts[o]?await Z(o,n.slice(2),e):{code:1,stdout:"",stderr:`error: Script or file not found "${o}"
|
|
648
|
+
`}}const t=e.resolvePath(s);if(e.vfs.existsSync(t)){const o=n.slice(1),i=await q({mode:"run",entry:t,argv:["bun",t,...o],stdin:e.stdin||"",env:e.env,cwd:e.cwd,vfs:e.vfs,pid:e.pid,isBackground:e.isBackground,onStdout:e.onStdout,onStderr:e.onStderr,signal:e.signal},e);return{code:i.ok?0:i.exitCode||1,stdout:i.stdout,stderr:i.stderr}}const{data:r}=H(e.vfs,e.cwd);return r.scripts&&r.scripts[s]?await Z(s,n.slice(1),e):{code:1,stdout:"",stderr:`bun: file or command not found: ${s}
|
|
643
649
|
`}},async npm(n,e){if(n.length===0)return{code:0,stdout:`npm v10.2.0
|
|
644
650
|
`,stderr:""};const s=n[0];if(s==="--version"||s==="-v"||s==="version")return{code:0,stdout:`10.2.0
|
|
645
651
|
`,stderr:""};if(s==="--help"||s==="-h"||s==="help")return{code:0,stdout:`npm v10.2.0
|
|
@@ -648,12 +654,12 @@ Usage: npm <command>
|
|
|
648
654
|
Commands: init, install, uninstall, list, run, start, test
|
|
649
655
|
`,stderr:""};if(s==="init"){const r=j.join(e.cwd,"package.json");return e.vfs.existsSync(r)||(e.vfs.writeFileSync(r,JSON.stringify({name:j.basename(e.cwd)||"app",version:"1.0.0",description:"",main:"index.js",scripts:{test:'echo "Error: no test specified" && exit 1'},keywords:[],author:"",license:"ISC"},null,2)+`
|
|
650
656
|
`),typeof e.emitMutation=="function"&&e.emitMutation("create",r)),{code:0,stdout:"Wrote to "+r+`
|
|
651
|
-
`,stderr:""}}if(s==="i"||s==="install"||s==="add"){let r=n.slice(1).filter(i=>!i.startsWith("-"));const o=n.some(i=>i==="-D"||i==="--save-dev"||i==="--dev");if(r.length===0){const{data:i}=
|
|
657
|
+
`,stderr:""}}if(s==="i"||s==="install"||s==="add"){let r=n.slice(1).filter(i=>!i.startsWith("-"));const o=n.some(i=>i==="-D"||i==="--save-dev"||i==="--dev");if(r.length===0){const{data:i}=H(e.vfs,e.cwd);if(r=Object.keys(Object.assign({},i.dependencies||{},i.devDependencies||{})),r.length===0)return{code:0,stdout:`up to date
|
|
652
658
|
`,stderr:""}}return await ne(r,e,{manager:"npm",dev:o,header:"npm install v10.2.0"})}if(s==="uninstall"||s==="remove"||s==="rm"){const r=n.slice(1).filter(o=>!o.startsWith("-"));for(const o of r)be(o,e);return{code:0,stdout:`removed ${r.length} package(s) in 0.1s
|
|
653
659
|
`,stderr:""}}if(s==="list"||s==="ls")return{code:0,stdout:ie(e),stderr:""};if(s==="run"||s==="run-script"){const r=n[1];return r?await Z(r,n.slice(2),e):{code:1,stdout:"",stderr:`npm ERR! missing script name
|
|
654
|
-
`}}if(s==="test")return await Z("test",n.slice(1),e);if(s==="start")return await Z("start",n.slice(1),e);const{data:t}=
|
|
660
|
+
`}}if(s==="test")return await Z("test",n.slice(1),e);if(s==="start")return await Z("start",n.slice(1),e);const{data:t}=H(e.vfs,e.cwd);return t.scripts&&t.scripts[s]?await Z(s,n.slice(1),e):{code:1,stdout:"",stderr:`npm ERR! Unknown command: "${s}"
|
|
655
661
|
`}},async npx(n,e){const s=[];for(let y=0;y<n.length;y++)n[y]==="-y"||n[y]==="--yes"||n[y]==="--no-install"||s.push(n[y]);if(s.length===0)return{code:1,stdout:"",stderr:`npx: missing command
|
|
656
|
-
`};const t=s[0],r=s.slice(1),o=j.join(e.cwd||"/workspace","node_modules/.bin",t),i=j.join("/workspace/node_modules/.bin",t),f=e.vfs.existsSync(o)?o:e.vfs.existsSync(i)?i:null;if(f){const l=String(e.vfs.readFileSync(f,"utf8")||"").match(/exec\s+node\s+"([^"]+)"/);return l&&l[1]?await e.shell.commands.node([l[1],...r],e):await e.shell.commands.node([f,...r],e)}const
|
|
662
|
+
`};const t=s[0],r=s.slice(1),o=j.join(e.cwd||"/workspace","node_modules/.bin",t),i=j.join("/workspace/node_modules/.bin",t),f=e.vfs.existsSync(o)?o:e.vfs.existsSync(i)?i:null;if(f){const l=String(e.vfs.readFileSync(f,"utf8")||"").match(/exec\s+node\s+"([^"]+)"/);return l&&l[1]?await e.shell.commands.node([l[1],...r],e):await e.shell.commands.node([f,...r],e)}const d=[t,...r].map(We).join(" ");return await e.shell.execute(d,{cwd:e.cwd,env:e.env,stdin:e.stdin,signal:e.signal,onStdout:e.onStdout,onStderr:e.onStderr,onRequestStdin:e.onRequestStdin})},async bunx(n,e){return await this.npx(n,e)},async pnpm(n,e){if(n.length===0||n[0]==="--help"||n[0]==="-h")return{code:0,stdout:`pnpm v9.0.0
|
|
657
663
|
Usage: pnpm <command>
|
|
658
664
|
|
|
659
665
|
Commands:
|
|
@@ -668,11 +674,11 @@ Commands:
|
|
|
668
674
|
`,stderr:""};const s=n[0];if(s==="--version"||s==="-v")return{code:0,stdout:`9.0.0
|
|
669
675
|
`,stderr:""};const t=n.some(o=>o==="-D"||o==="--save-dev"||o==="--dev"||o==="-d");if(s==="init"){const o=j.join(e.cwd,"package.json");return e.vfs.existsSync(o)||(e.vfs.writeFileSync(o,JSON.stringify({name:j.basename(e.cwd)||"app",version:"1.0.0",main:"index.js",scripts:{test:'echo "Error: no test specified" && exit 1'}},null,2)+`
|
|
670
676
|
`),typeof e.emitMutation=="function"&&e.emitMutation("create",o)),{code:0,stdout:"Wrote to "+o+`
|
|
671
|
-
`,stderr:""}}if(s==="install"||s==="i"||s==="add"){let o=n.slice(1).filter(f=>!f.startsWith("-"));if(o.length===0){const{data:f}=
|
|
677
|
+
`,stderr:""}}if(s==="install"||s==="i"||s==="add"){let o=n.slice(1).filter(f=>!f.startsWith("-"));if(o.length===0){const{data:f}=H(e.vfs,e.cwd);if(o=Object.keys(Object.assign({},f.dependencies||{},f.devDependencies||{})),o.length===0)return{code:0,stdout:`Already up to date
|
|
672
678
|
`,stderr:""}}return await ne(o,e,{manager:"pnpm",dev:t,header:`pnpm ${s==="add"?"add":"install"} v9.0.0`})}if(s==="remove"||s==="rm"||s==="uninstall"){const o=n.slice(1).filter(i=>!i.startsWith("-"));for(const i of o)be(i,e);return{code:0,stdout:`removed ${o.length} package(s)
|
|
673
679
|
`,stderr:""}}if(s==="list"||s==="ls")return{code:0,stdout:ie(e),stderr:""};if(s==="run"||s==="run-script"){const o=n[1];return o?await Z(o,n.slice(2),e):{code:1,stdout:"",stderr:`pnpm: missing script name
|
|
674
680
|
`}}if(s==="test")return await Z("test",n.slice(1),e);if(s==="exec"){const o=n[1];return o?await this.npx([o,...n.slice(2)],e):{code:1,stdout:"",stderr:`pnpm: exec requires a command
|
|
675
|
-
`}}if(s==="dlx")return await this.npx(n.slice(1),e);const{data:r}=
|
|
681
|
+
`}}if(s==="dlx")return await this.npx(n.slice(1),e);const{data:r}=H(e.vfs,e.cwd);return r.scripts&&r.scripts[s]?await Z(s,n.slice(1),e):{code:1,stdout:"",stderr:`ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL Unknown command: "${s}"
|
|
676
682
|
`}},async serve(n,e){if(n[0]==="--help"||n[0]==="-h")return{code:0,stdout:`Usage: serve [dir] [--port <n>]
|
|
677
683
|
|
|
678
684
|
Starts the built-in CodeLab preview server on the virtual port table.
|
|
@@ -680,33 +686,33 @@ Commands:
|
|
|
680
686
|
browser-native ESM on the fly, and bare imports resolve to jsDelivr ESM.
|
|
681
687
|
|
|
682
688
|
Open the Web Preview drawer (or http://127.0.0.1:<port>/) to view it.
|
|
683
|
-
`,stderr:""};const s=(()=>{const
|
|
684
|
-
`};const o=
|
|
689
|
+
`,stderr:""};const s=(()=>{const f=[];for(let d=0;d<n.length;d++){const y=n[d];if(y==="--port"||y==="-p"){d++;continue}y.startsWith("-")||f.push(y)}return f[0]})();let t=3e3;for(let f=0;f<n.length;f++)(n[f]==="--port"||n[f]==="-p")&&n[f+1]?(t=Number(n[f+1])||t,f++):n[f].startsWith("--port=")&&(t=Number(n[f].split("=")[1])||t);const r=e.resolvePath(s||".");if(!e.vfs.existsSync(r))return{code:1,stdout:"",stderr:`serve: ${s}: No such file or directory
|
|
690
|
+
`};const o=we(e,r,t);if(!o)return{code:1,stdout:"",stderr:`serve: no virtual port table available
|
|
691
|
+
`};const i=`
|
|
685
692
|
\u26A1 CodeLab preview server
|
|
686
693
|
|
|
687
694
|
\u279C Local: http://127.0.0.1:${o.port}/
|
|
688
695
|
\u279C Root: ${r}
|
|
689
696
|
\u279C Preview: open the Web Preview drawer for port ${o.port}
|
|
690
697
|
|
|
691
|
-
|
|
692
|
-
`}},async ports(n,e){const s=e.shell&&e.shell.portTable;if(!s||typeof s.listServers!="function")return{code:0,stdout:`PORT PID NAME
|
|
698
|
+
`;return await $e(o,e,i)},async ports(n,e){const s=e.shell&&e.shell.portTable;if(!s||typeof s.listServers!="function")return{code:0,stdout:`PORT PID NAME
|
|
693
699
|
`,stderr:""};const t=s.listServers();let r=`PORT PID NAME
|
|
694
|
-
`;for(const o of t){const i=String(o.port||"").padEnd(8," "),f=String(o.pid!==void 0?o.pid:"-").padEnd(8," "),
|
|
700
|
+
`;for(const o of t){const i=String(o.port||"").padEnd(8," "),f=String(o.pid!==void 0?o.pid:"-").padEnd(8," "),d=o.name||o.type||"server";r+=`${i} ${f} ${d}
|
|
695
701
|
`}return{code:0,stdout:r,stderr:""}},async curl(n,e){let s=null;const t={};let r=null,o=!1,i=null;for(let p=0;p<n.length;p++){const g=n[p];if(g==="-X"||g==="--request")s=n[++p];else if(g==="-H"||g==="--header"){const m=n[++p]||"",S=m.indexOf(":");S!==-1&&(t[m.slice(0,S).trim().toLowerCase()]=m.slice(S+1).trim())}else g==="-d"||g==="--data"||g==="--data-raw"?(r=n[++p],s||(s="POST")):g==="-i"||g==="--include"||g==="-v"||g==="--verbose"?o=!0:g==="-s"||g==="--silent"||g.startsWith("-")||(i=g)}if(!i)return{code:1,stdout:"",stderr:`curl: no URL specified!
|
|
696
|
-
`};!i.startsWith("http://")&&!i.startsWith("https://")&&(i="http://"+i),s||(s="GET");const f=e.shell&&e.shell.portTable||null,
|
|
702
|
+
`};!i.startsWith("http://")&&!i.startsWith("https://")&&(i="http://"+i),s||(s="GET");const f=e.shell&&e.shell.portTable||null,d=e.shell&&e.shell.options&&typeof(e.shell.options.fetch||e.shell.options.fetchImpl)=="function"?e.shell.options.fetch||e.shell.options.fetchImpl:fetch;let y=!1;try{const g=new URL(i).hostname.toLowerCase();y=g==="localhost"||g==="127.0.0.1"||g==="0.0.0.0"||g==="::1"||g==="[::1]"}catch(p){M.debug("curl URL parse fallback",i,p)}let l=null,a=null;const c=f&&y?25:1;for(let p=0;p<c;p++)try{if(f&&y){l=await f.dispatchRequest(i,{method:s,headers:t,body:r}),a=null;break}else{l=await d(i,{method:s,headers:t,body:r}),a=null;break}}catch(g){if(a=g,g&&g.chaosEffect)break;p+1<c&&await new Promise(m=>setTimeout(m,15))}if(!l)return{code:7,stdout:"",stderr:`curl: (7) Failed to connect to host: ${a?a.message:"Connection refused"}
|
|
697
703
|
`};const h=typeof l.text=="function"?await l.text():String(l.body||"");let u="";if(o){if(u+=`HTTP/1.1 ${l.status||200} ${l.statusText||"OK"}\r
|
|
698
704
|
`,l.headers)if(typeof l.headers.forEach=="function")l.headers.forEach((p,g)=>{u+=`${g}: ${p}\r
|
|
699
705
|
`});else if(typeof l.headers.entries=="function")for(const[p,g]of l.headers.entries())u+=`${p}: ${g}\r
|
|
700
706
|
`;else for(const[p,g]of Object.entries(l.headers))u+=`${p}: ${g}\r
|
|
701
707
|
`;u+=`\r
|
|
702
|
-
`}return u+=h,{code:0,stdout:u,stderr:""}},async hey(n,e){let s=50,t=10,r="GET";const o={};let i=null,f=!1,
|
|
703
|
-
`};!
|
|
704
|
-
`,stderr:""};let P="";if(
|
|
705
|
-
`}}let A="";for(const[D,
|
|
706
|
-
`;for(const[D,
|
|
708
|
+
`}return u+=h,{code:0,stdout:u,stderr:""}},async hey(n,e){let s=50,t=10,r="GET";const o={};let i=null,f=!1,d="";for(let D=0;D<n.length;D++){const N=n[D];if((N==="-n"||N==="--requests")&&D+1<n.length)s=Math.max(1,Math.min(2e3,parseInt(n[++D],10)||50));else if((N==="-c"||N==="--concurrency")&&D+1<n.length)t=Math.max(1,Math.min(200,parseInt(n[++D],10)||10));else if((N==="-m"||N==="-X"||N==="--method")&&D+1<n.length)r=String(n[++D]).toUpperCase();else if((N==="-H"||N==="--header")&&D+1<n.length){const B=n[++D],z=B.indexOf(":");z!==-1&&(o[B.slice(0,z).trim()]=B.slice(z+1).trim())}else(N==="-d"||N==="--body"||N==="--data")&&D+1<n.length?(i=n[++D],r==="GET"&&(r="POST")):N==="--json"?f=!0:N.startsWith("-")||(d=N)}if(!d)return{code:1,stdout:"",stderr:`Usage: hey [-n requests] [-c concurrency] [-m METHOD] [-H "Header: val"] [-d body] [--json] <url>
|
|
709
|
+
`};!d.startsWith("http://")&&!d.startsWith("https://")&&(d="http://"+d),t=Math.min(t,s);const y=e.shell&&e.shell.portTable||null,l=e.shell&&e.shell.options&&typeof(e.shell.options.fetch||e.shell.options.fetchImpl)=="function"?e.shell.options.fetch||e.shell.options.fetchImpl:fetch;let a=!1;try{const N=new URL(d).hostname.toLowerCase();a=N==="localhost"||N==="127.0.0.1"||N==="0.0.0.0"||N==="::1"||N==="[::1]"}catch(D){M.debug("hey URL parse fallback",d,D)}const c=[],h={},u={};let p=0,g=0;const m=typeof performance<"u"&&performance.now?performance.now():Date.now(),S=async()=>{for(;!(g++>=s);){const N=typeof performance<"u"&&performance.now?performance.now():Date.now();try{let B;y&&a?B=await y.dispatchRequest(d,{method:r,headers:{...o},body:i}):B=await l(d,{method:r,headers:{...o},body:i});const z=typeof performance<"u"&&performance.now?performance.now():Date.now(),X=Math.max(.05,z-N);c.push(X);const J=B&&B.status||200;h[J]=(h[J]||0)+1;const se=B&&typeof B.text=="function"?await B.text():String(B&&B.body||"");p+=se.length}catch(B){const z=typeof performance<"u"&&performance.now?performance.now():Date.now();c.push(Math.max(.05,z-N));const X=B&&(B.chaosEffect||B.code)||"ERROR";u[X]=(u[X]||0)+1}}},b=[];for(let D=0;D<t;D++)b.push(S());await Promise.all(b);const v=typeof performance<"u"&&performance.now?performance.now():Date.now(),w=Math.max(.001,(v-m)/1e3);c.sort((D,N)=>D-N);const $=D=>{if(c.length===0)return 0;const N=Math.min(c.length-1,Math.floor(D/100*c.length));return Number(c[N].toFixed(2))},R=c.length?Number(c[0].toFixed(2)):0,I=c.length?Number(c[c.length-1].toFixed(2)):0,C=c.length?Number((c.reduce((D,N)=>D+N,0)/c.length).toFixed(2)):0,E=Number((s/w).toFixed(2)),T=$(50),k=$(90),O=$(95),F=$(99);if(f)return{code:0,stdout:JSON.stringify({url:d,method:r,requests:s,concurrency:t,durationSec:Number(w.toFixed(4)),rps:E,totalBytes:p,latencyMs:{min:R,avg:C,p50:T,p90:k,p95:O,p99:F,max:I},statusCodes:h,errors:u},null,2)+`
|
|
710
|
+
`,stderr:""};let P="";if(c.length>0){const B=Math.max(.5,I-R)/5,z=new Array(5).fill(0);for(const J of c){const se=Math.min(4,Math.floor((J-R)/B));z[se]++}const X=Math.max(1,...z);for(let J=0;J<5;J++){const se=(R+B*(J+1)).toFixed(2).padStart(7),Rt=`[${z[J]}]`.padStart(6),Ot=Math.round(z[J]/X*28);P+=` ${se} ms ${Rt} |${"\u25A0".repeat(Ot)}
|
|
711
|
+
`}}let A="";for(const[D,N]of Object.entries(h))A+=` [${D}] ${N} responses
|
|
712
|
+
`;for(const[D,N]of Object.entries(u))A+=` [${D}] ${N} failed
|
|
707
713
|
`;return{code:0,stdout:`
|
|
708
714
|
Summary:
|
|
709
|
-
Total: ${
|
|
715
|
+
Total: ${w.toFixed(4)} secs
|
|
710
716
|
Slowest: ${I.toFixed(2)} ms
|
|
711
717
|
Fastest: ${R.toFixed(2)} ms
|
|
712
718
|
Average: ${C.toFixed(2)} ms
|
|
@@ -731,7 +737,7 @@ Status code distribution:
|
|
|
731
737
|
`,stderr:""}):{code:1,stdout:"",stderr:`Usage: chaos latency <port> <ms> [--jitter <ms>]
|
|
732
738
|
`}}if(t==="drop"||t==="loss"){const r=parseInt(n[1],10),o=parseFloat(n[2]);if(!r||isNaN(o))return{code:1,stdout:"",stderr:`Usage: chaos drop <port> <rate 0..1 or 0..100>
|
|
733
739
|
`};const i=o>1?o/100:o;return s.setChaosRule(r,{dropRate:i}),{code:0,stdout:`Injected ${Math.round(i*100)}% packet drop (ETIMEDOUT) on port :${r}
|
|
734
|
-
`,stderr:""}}if(t==="error"||t==="fail"||t==="503"){const r=parseInt(n[1],10),o=n[2]!==void 0?parseFloat(n[2]):.25;let i=503;for(let
|
|
740
|
+
`,stderr:""}}if(t==="error"||t==="fail"||t==="503"){const r=parseInt(n[1],10),o=n[2]!==void 0?parseFloat(n[2]):.25;let i=503;for(let d=3;d<n.length;d++)(n[d]==="--status"||n[d]==="-s")&&n[d+1]&&(i=parseInt(n[++d],10)||503);if(!r||isNaN(o))return{code:1,stdout:"",stderr:`Usage: chaos error <port> <rate> [--status 503]
|
|
735
741
|
`};const f=o>1?o/100:o;return s.setChaosRule(r,{errorRate:f,errorStatus:i}),{code:0,stdout:`Injected ${Math.round(f*100)}% HTTP ${i} error rate on port :${r}
|
|
736
742
|
`,stderr:""}}if(t==="crash"||t==="kill"||t==="down"){const r=parseInt(n[1],10);return r?(s.setChaosRule(r,{crashed:!0}),{code:0,stdout:`Port :${r} marked CRASHED (all connections will fail with ECONNREFUSED)
|
|
737
743
|
`,stderr:""}):{code:1,stdout:"",stderr:`Usage: chaos crash <port>
|
|
@@ -749,26 +755,26 @@ Commands:
|
|
|
749
755
|
chaos partition <fromPort> <toPort> Block traffic between two ports
|
|
750
756
|
chaos heal [port] Heal a port (or all ports)
|
|
751
757
|
chaos reset Remove all chaos rules
|
|
752
|
-
`}},async sqlite3(n,e){let s="pipe",t=!1;const r=[];for(let a=0;a<n.length;a++){const
|
|
758
|
+
`}},async sqlite3(n,e){let s="pipe",t=!1;const r=[];for(let a=0;a<n.length;a++){const c=n[a];c==="-header"||c==="--header"?t=!0:c==="-column"||c==="--column"||c==="-table"||c==="--table"?(s="column",t=!0):c==="-json"||c==="--json"?s="json":c==="-csv"||c==="--csv"?s="csv":c.startsWith("-")||r.push(c)}let o=":memory:",i="";r.length===1?/^\s*(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|PRAGMA|EXPLAIN|BEGIN|COMMIT|WITH|\.)/i.test(r[0])?i=r[0]:o=r[0]:r.length>=2&&(o=r[0],i=r.slice(1).join(" ")),!i&&e.stdin&&(i=String(e.stdin).trim());const f=(typeof e.onRequestStdin=="function"?e.onRequestStdin:null)||(e.shell&&e.shell.options&&typeof e.shell.options.onRequestStdin=="function"?e.shell.options.onRequestStdin:null);if(!i&&!f)return{code:0,stdout:`SQLite 3.45.0 (CodeLab VFS Engine)
|
|
753
759
|
Usage: sqlite3 [-column] [-header] [-json] [dbfile] "SQL"
|
|
754
|
-
`,stderr:""};const
|
|
755
|
-
`};const l=(a,
|
|
756
|
-
`:""}if(h.startsWith(".schema")){const g=[];for(const[m,S]of a.tables.entries()){const b=S.columns.map(
|
|
760
|
+
`,stderr:""};const d=U(),y=(d&&typeof d.createSqliteDatabase=="function"?d.createSqliteDatabase:null)||typeof _hostRuntime<"u"&&_hostRuntime&&_hostRuntime.createSqliteDatabase||typeof globalThis<"u"&&globalThis._codeLabCreateSqliteDatabase;if(typeof y!="function")return{code:1,stdout:"",stderr:`sqlite3: SQLite engine not initialized in runtime
|
|
761
|
+
`};const l=(a,c)=>{const h=String(c||"").trim();if(!h)return"";if(h===".tables"){const g=Array.from(a.tables.keys());return g.length?g.join(" ")+`
|
|
762
|
+
`:""}if(h.startsWith(".schema")){const g=[];for(const[m,S]of a.tables.entries()){const b=S.columns.map(v=>`${v.name} ${v.type||"TEXT"}`).join(", ");g.push(`CREATE TABLE ${m} (${b});`)}for(const m of a.indexes.values())g.push(`CREATE ${m.unique?"UNIQUE ":""}INDEX ${m.name} ON ${m.table} (${m.columns.join(", ")});`);return g.join(`
|
|
757
763
|
`)+(g.length?`
|
|
758
764
|
`:"")}if(h===".indexes"||h===".indices"){const g=Array.from(a.indexes.keys());return g.length?g.join(" ")+`
|
|
759
|
-
`:""}const u=h.split(";").map(g=>g.trim()).filter(Boolean),p=[];for(const g of u){const S=/^(SELECT|EXPLAIN|PRAGMA)\b/i.test(g)?a.query(g).all():(a.run(g),[]);if(Array.isArray(S)&&S.length>0)if(s==="json")p.push(JSON.stringify(S,null,2));else if(s==="column"){const b=Object.keys(S[0]),
|
|
765
|
+
`:""}const u=h.split(";").map(g=>g.trim()).filter(Boolean),p=[];for(const g of u){const S=/^(SELECT|EXPLAIN|PRAGMA)\b/i.test(g)?a.query(g).all():(a.run(g),[]);if(Array.isArray(S)&&S.length>0)if(s==="json")p.push(JSON.stringify(S,null,2));else if(s==="column"){const b=Object.keys(S[0]),v=b.map(w=>Math.max(w.length,...S.map($=>String($[w]??"").length)));t&&(p.push(b.map((w,$)=>w.padEnd(v[$])).join(" ")),p.push(v.map(w=>"-".repeat(w)).join(" ")));for(const w of S)p.push(b.map(($,R)=>String(w[$]??"").padEnd(v[R])).join(" "))}else{const b=Object.keys(S[0]),v=s==="csv"?",":"|";t&&p.push(b.join(v));for(const w of S)p.push(b.map($=>String(w[$]??"")).join(v))}}return p.length?p.join(`
|
|
760
766
|
`)+`
|
|
761
|
-
`:""};try{const a=y(e.vfs,()=>e.shell.cwd),
|
|
767
|
+
`:""};try{const a=y(e.vfs,()=>e.shell.cwd),c=new a(o);if(!i&&f){const u=`SQLite version 3.45.0 (CodeLab VFS Engine)
|
|
762
768
|
Enter ".help" for usage hints, ".quit" to exit.
|
|
763
769
|
`;let p=u,g="";for(e.onStdout&&e.onStdout(u);!(e.signal&&e.signal.aborted);){const m=await f("sqlite> ");if(m==null)break;const S=String(m).trim();if(S===".quit"||S===".exit")break;if(S===".help"){const b=`.tables List names of tables
|
|
764
770
|
.schema Show CREATE statements
|
|
765
771
|
.indexes Show names of indexes
|
|
766
772
|
.quit Exit this program
|
|
767
|
-
`;p+=b,e.onStdout&&e.onStdout(b);continue}if(S)try{const b=l(
|
|
768
|
-
`;g+=
|
|
769
|
-
`}}},async read(n,e){let s="",t=!1;const r=[];for(let
|
|
770
|
-
`);o=y===-1?
|
|
771
|
-
`;if(r.length===1){const
|
|
773
|
+
`;p+=b,e.onStdout&&e.onStdout(b);continue}if(S)try{const b=l(c,S);b&&(p+=b,e.onStdout&&e.onStdout(b))}catch(b){const v=`Error: ${b.message||String(b)}
|
|
774
|
+
`;g+=v,e.onStderr&&e.onStderr(v)}}return{code:0,stdout:p,stderr:g,alreadyStreamed:!0}}return{code:0,stdout:l(c,i),stderr:""}}catch(a){return{code:1,stdout:"",stderr:`Error: ${a.message||String(a)}
|
|
775
|
+
`}}},async read(n,e){let s="",t=!1;const r=[];for(let d=0;d<n.length;d++){const y=n[d];y==="-r"?t=!0:y==="-p"&&d+1<n.length?s=String(n[++d]):y.startsWith("-")&&y.length>1?y.includes("r")&&(t=!0):r.push(y)}r.length===0&&r.push("REPLY");let o=null;if(e.stdin&&String(e.stdin).length>0){const d=String(e.stdin),y=d.indexOf(`
|
|
776
|
+
`);o=y===-1?d:d.slice(0,y),o.endsWith("\r")&&(o=o.slice(0,-1))}else{const d=(typeof e.onRequestStdin=="function"?e.onRequestStdin:null)||(e.shell&&e.shell.options&&typeof e.shell.options.onRequestStdin=="function"?e.shell.options.onRequestStdin:null);d&&(o=await d(s))}if(o==null)return{code:1,stdout:"",stderr:""};let i=String(o).replace(/\r?\n$/,"");t||(i=i.replace(/\\(.)/g,"$1"));const f=e.env&&e.env.IFS!==void 0?String(e.env.IFS):`
|
|
777
|
+
`;if(r.length===1){const d=f.includes(" ")?i.trim():i;e.env[r[0]]=d,e.shell&&(e.shell.env[r[0]]=d)}else{const d=f.length>0?new RegExp("["+f.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")+"]+"):null,y=d?i.trim().split(d):[i];for(let l=0;l<r.length;l++){const a=r[l],c=l===r.length-1?y.slice(l).join(" "):y[l]||"";e.env[a]=c,e.shell&&(e.shell.env[a]=c)}}return{code:0,stdout:"",stderr:""}},async tsc(n,e){if(n.includes("--version")||n.includes("-v"))return{code:0,stdout:`Version 5.6.3
|
|
772
778
|
`,stderr:""};if(n.includes("--help")||n.includes("-h"))return{code:0,stdout:`Version 5.6.3
|
|
773
779
|
Syntax: tsc [options] [file...]
|
|
774
780
|
|
|
@@ -777,55 +783,55 @@ Options:
|
|
|
777
783
|
--noEmit Do not emit outputs.
|
|
778
784
|
--outDir <dir> Redirect output structure to the directory.
|
|
779
785
|
-v, --version Print the compiler's version.
|
|
780
|
-
`,stderr:""};if(n.includes("--init")){const
|
|
781
|
-
`),typeof e.emitMutation=="function"&&e.emitMutation("create",
|
|
782
|
-
`,stderr:""}}const s=n.includes("--noEmit");let t=null;const r=[];for(let
|
|
783
|
-
`,f=2;continue}const y=String(e.vfs.readFileSync(
|
|
784
|
-
`}f=2;continue}a=
|
|
785
|
-
`){if(m++,
|
|
786
|
-
`,f=2}}return{code:f,stdout:"",stderr:i}}};V["redis-cli"]=async function(e,s){const t="/workspace/.codelab-redis.json",r=()=>{try{if(s.vfs.existsSync(t)){const u=JSON.parse(s.vfs.readFileSync(t,"utf8"));if(u&&typeof u=="object")return u}}catch(u){
|
|
786
|
+
`,stderr:""};if(n.includes("--init")){const d=j.join(e.cwd,"tsconfig.json");return e.vfs.existsSync(d)||(e.vfs.writeFileSync(d,JSON.stringify({compilerOptions:{target:"ES2022",module:"ESNext",moduleResolution:"bundler",strict:!0,esModuleInterop:!0,skipLibCheck:!0,jsx:"react-jsx"}},null,2)+`
|
|
787
|
+
`),typeof e.emitMutation=="function"&&e.emitMutation("create",d)),{code:0,stdout:`Created a new tsconfig.json
|
|
788
|
+
`,stderr:""}}const s=n.includes("--noEmit");let t=null;const r=[];for(let d=0;d<n.length;d++){const y=n[d];y==="--outDir"&&d+1<n.length?t=e.resolvePath(n[++d]):y==="-p"||y==="--project"?d++:y.startsWith("-")||r.push(e.resolvePath(y))}const o=[];if(r.length>0)o.push(...r);else{const d=y=>{if(e.vfs.existsSync(y))for(const l of e.vfs.readdirSync(y)){if(l==="node_modules"||l===".git"||l==="dist")continue;const a=j.join(y,l);e.vfs.statSync(a).isDirectory()?d(a):/\.(ts|tsx)$/i.test(l)&&!l.endsWith(".d.ts")&&o.push(a)}};d(e.cwd)}let i="",f=0;for(const d of o){if(!e.vfs.existsSync(d)){i+=`error TS6053: File '${d}' not found.
|
|
789
|
+
`,f=2;continue}const y=String(e.vfs.readFileSync(d,"utf8")||"");try{const l=typeof globalThis<"u"&&globalThis.ts?globalThis.ts:null;let a="";if(l&&typeof l.transpileModule=="function"){const c=l.transpileModule(y,{fileName:d,reportDiagnostics:!0,compilerOptions:{target:l.ScriptTarget?l.ScriptTarget.ES2022:9,module:l.ModuleKind?l.ModuleKind.ESNext:99}});if(Array.isArray(c.diagnostics)&&c.diagnostics.length>0){for(const h of c.diagnostics){const u=typeof h.messageText=="string"?h.messageText:h.messageText&&h.messageText.messageText||"Syntax error";i+=`${j.relative(e.cwd,d)}(1,1): error TS${h.code||1005}: ${u}
|
|
790
|
+
`}f=2;continue}a=c.outputText}else{let c=null,h=!1,u=!1,p=0,g=0,m=1;for(let S=0;S<y.length;S++){const b=y[S],v=y[S+1];if(b===`
|
|
791
|
+
`){if(m++,c==='"'||c==="'")throw new Error(`Line ${m-1}: Unterminated string literal.`);h=!1;continue}if(!h){if(u){b==="*"&&v==="/"&&(u=!1,S++);continue}if(c){if(b==="\\"){S++;continue}b===c&&(c=null);continue}if(b==="/"&&v==="/"){h=!0,S++;continue}if(b==="/"&&v==="*"){u=!0,S++;continue}if(b==='"'||b==="'"||b==="`"){c=b;continue}if(b==="{"?p++:b==="}"?p--:b==="("?g++:b===")"&&g--,p<0||g<0)throw new Error(`Line ${m}: Unexpected closing token '${b}'.`)}}if(c)throw new Error(`Line ${m}: Unterminated string literal.`);if(p!==0||g!==0)throw new Error(`Line ${m}: Unexpected end of file (unclosed '${p!==0?"{":"("}').`);a=Je(y,d)}if(!s){const c=j.relative(e.cwd,d).replace(/\.(tsx|ts)$/i,".js"),h=t?j.join(t,c):d.replace(/\.(tsx|ts)$/i,".js"),u=j.dirname(h);e.vfs.existsSync(u)||e.vfs.mkdirSync(u,{recursive:!0}),e.vfs.writeFileSync(h,a),typeof e.emitMutation=="function"&&e.emitMutation("create",h)}}catch(l){i+=`${j.relative(e.cwd,d)}(1,1): error TS1005: ${l.message||String(l)}
|
|
792
|
+
`,f=2}}return{code:f,stdout:"",stderr:i}}};V["redis-cli"]=async function(e,s){const t="/workspace/.codelab-redis.json",r=()=>{try{if(s.vfs.existsSync(t)){const u=JSON.parse(s.vfs.readFileSync(t,"utf8"));if(u&&typeof u=="object")return u}}catch(u){M.debug("redis-cli state read fallback:",u)}return{kv:{},hashes:{},lists:{},sets:{},zsets:{},expires:{}}},o=u=>{try{s.vfs.writeFileSync(t,JSON.stringify(u))}catch(p){M.debug("redis-cli state write failed:",p)}},i=r(),f=Date.now();for(const[u,p]of Object.entries(i.expires||{}))typeof p=="number"&&p<=f&&(delete i.kv[u],delete i.hashes[u],delete i.lists[u],delete i.sets[u],delete i.zsets[u],delete i.expires[u]);const d=[];for(let u=0;u<e.length;u++){if((e[u]==="-h"||e[u]==="-p"||e[u]==="-n")&&u+1<e.length){u++;continue}d.push(e[u])}if(d.length===0&&s.stdin){const u=String(s.stdin).trim().split(/\r?\n/)[0];u&&d.push(...u.split(/\s+/))}if(d.length===0)return{code:0,stdout:`redis-cli 7.2.4 (CodeLab VFS Store)
|
|
787
793
|
Usage: redis-cli <COMMAND> [args...]
|
|
788
|
-
`,stderr:""};const y=String(
|
|
789
|
-
`,
|
|
794
|
+
`,stderr:""};const y=String(d[0]).toUpperCase(),l=d.slice(1),a=u=>`(integer) ${u}
|
|
795
|
+
`,c=u=>u==null?`(nil)
|
|
790
796
|
`:`"${u}"
|
|
791
797
|
`,h=u=>!u||u.length===0?`(empty array)
|
|
792
798
|
`:u.map((p,g)=>`${g+1}) "${p}"`).join(`
|
|
793
799
|
`)+`
|
|
794
|
-
`;if(y==="PING")return{code:0,stdout:l[0]?
|
|
800
|
+
`;if(y==="PING")return{code:0,stdout:l[0]?c(l[0]):`PONG
|
|
795
801
|
`,stderr:""};if(y==="FLUSHALL"||y==="FLUSHDB")return o({kv:{},hashes:{},lists:{},sets:{},zsets:{},expires:{}}),{code:0,stdout:`OK
|
|
796
802
|
`,stderr:""};if(y==="DBSIZE"){const u=new Set([...Object.keys(i.kv),...Object.keys(i.hashes),...Object.keys(i.lists),...Object.keys(i.sets),...Object.keys(i.zsets)]);return{code:0,stdout:a(u.size),stderr:""}}if(y==="INFO")return{code:0,stdout:`# Server
|
|
797
803
|
redis_version:7.2.4-codelab
|
|
798
804
|
# Keyspace
|
|
799
805
|
db0:keys=${new Set([...Object.keys(i.kv),...Object.keys(i.hashes),...Object.keys(i.lists),...Object.keys(i.sets),...Object.keys(i.zsets)]).size},expires=${Object.keys(i.expires).length}
|
|
800
806
|
`,stderr:""};if(y==="SET"){const[u,p,...g]=l;if(!u||p===void 0)return{code:1,stdout:"",stderr:`ERR wrong number of arguments for SET
|
|
801
|
-
`};let m=!1,S=!1,b=null;for(let
|
|
802
|
-
`,stderr:""}:S&&!
|
|
807
|
+
`};let m=!1,S=!1,b=null;for(let w=0;w<g.length;w++){const $=String(g[w]).toUpperCase();$==="NX"?m=!0:$==="XX"?S=!0:$==="EX"&&g[w+1]?b=parseInt(g[++w],10)*1e3:$==="PX"&&g[w+1]&&(b=parseInt(g[++w],10))}const v=Object.prototype.hasOwnProperty.call(i.kv,u);return m&&v?{code:0,stdout:`(nil)
|
|
808
|
+
`,stderr:""}:S&&!v?{code:0,stdout:`(nil)
|
|
803
809
|
`,stderr:""}:(i.kv[u]=String(p),b&&b>0?i.expires[u]=f+b:delete i.expires[u],o(i),{code:0,stdout:`OK
|
|
804
|
-
`,stderr:""})}if(y==="GET"){const u=l[0],p=Object.prototype.hasOwnProperty.call(i.kv,u)?i.kv[u]:null;return o(i),{code:0,stdout:
|
|
810
|
+
`,stderr:""})}if(y==="GET"){const u=l[0],p=Object.prototype.hasOwnProperty.call(i.kv,u)?i.kv[u]:null;return o(i),{code:0,stdout:c(p),stderr:""}}if(y==="MSET"){for(let u=0;u+1<l.length;u+=2)i.kv[l[u]]=String(l[u+1]);return o(i),{code:0,stdout:`OK
|
|
805
811
|
`,stderr:""}}if(y==="MGET")return{code:0,stdout:l.map((p,g)=>`${g+1}) ${Object.prototype.hasOwnProperty.call(i.kv,p)?`"${i.kv[p]}"`:"(nil)"}`).join(`
|
|
806
812
|
`)+`
|
|
807
|
-
`,stderr:""};if(y==="DEL"){let u=0;for(const p of l)(Object.prototype.hasOwnProperty.call(i.kv,p)||Object.prototype.hasOwnProperty.call(i.hashes,p)||Object.prototype.hasOwnProperty.call(i.lists,p)||Object.prototype.hasOwnProperty.call(i.sets,p)||Object.prototype.hasOwnProperty.call(i.zsets,p))&&(delete i.kv[p],delete i.hashes[p],delete i.lists[p],delete i.sets[p],delete i.zsets[p],delete i.expires[p],u++);return o(i),{code:0,stdout:a(u),stderr:""}}if(y==="EXISTS"){let u=0;for(const p of l)(Object.prototype.hasOwnProperty.call(i.kv,p)||Object.prototype.hasOwnProperty.call(i.hashes,p)||Object.prototype.hasOwnProperty.call(i.lists,p)||Object.prototype.hasOwnProperty.call(i.sets,p)||Object.prototype.hasOwnProperty.call(i.zsets,p))&&u++;return{code:0,stdout:a(u),stderr:""}}if(y==="INCR"||y==="DECR"||y==="INCRBY"||y==="DECRBY"){const u=l[0],p=y==="INCR"?1:y==="DECR"?-1:(parseInt(l[1],10)||0)*(y==="DECRBY"?-1:1),m=(parseInt(i.kv[u]||"0",10)||0)+p;return i.kv[u]=String(m),o(i),{code:0,stdout:a(m),stderr:""}}if(y==="EXPIRE"){const[u,p]=l;return Object.prototype.hasOwnProperty.call(i.kv,u)||Object.prototype.hasOwnProperty.call(i.hashes,u)||Object.prototype.hasOwnProperty.call(i.lists,u)||Object.prototype.hasOwnProperty.call(i.sets,u)||Object.prototype.hasOwnProperty.call(i.zsets,u)?(i.expires[u]=f+(parseInt(p,10)||0)*1e3,o(i),{code:0,stdout:a(1),stderr:""}):{code:0,stdout:a(0),stderr:""}}if(y==="TTL"){const u=l[0];if(!(Object.prototype.hasOwnProperty.call(i.kv,u)||Object.prototype.hasOwnProperty.call(i.hashes,u)||Object.prototype.hasOwnProperty.call(i.lists,u)||Object.prototype.hasOwnProperty.call(i.sets,u)||Object.prototype.hasOwnProperty.call(i.zsets,u)))return{code:0,stdout:a(-2),stderr:""};if(!i.expires[u])return{code:0,stdout:a(-1),stderr:""};const g=Math.max(0,Math.ceil((i.expires[u]-f)/1e3));return{code:0,stdout:a(g),stderr:""}}if(y==="KEYS"){const u=l[0]||"*",p=new RegExp("^"+u.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$"),g=Array.from(new Set([...Object.keys(i.kv),...Object.keys(i.hashes),...Object.keys(i.lists),...Object.keys(i.sets),...Object.keys(i.zsets)])).filter(m=>p.test(m));return{code:0,stdout:h(g),stderr:""}}if(y==="HSET"){const u=l[0];i.hashes[u]=i.hashes[u]||{};let p=0;for(let g=1;g+1<l.length;g+=2)Object.prototype.hasOwnProperty.call(i.hashes[u],l[g])||p++,i.hashes[u][l[g]]=String(l[g+1]);return o(i),{code:0,stdout:a(p),stderr:""}}if(y==="HGET"){const[u,p]=l,g=i.hashes[u]&&Object.prototype.hasOwnProperty.call(i.hashes[u],p)?i.hashes[u][p]:null;return{code:0,stdout:
|
|
808
|
-
`,stderr:""}}if(y==="ZRANGE"||y==="ZREVRANGE"){const[u,p,g,m]=l,S=i.zsets[u]||{},b=Object.entries(S).sort((C,E)=>y==="ZREVRANGE"?E[1]-C[1]||E[0].localeCompare(C[0]):C[1]-E[1]||C[0].localeCompare(E[0]));let
|
|
809
|
-
2) (integer) ${
|
|
813
|
+
`,stderr:""};if(y==="DEL"){let u=0;for(const p of l)(Object.prototype.hasOwnProperty.call(i.kv,p)||Object.prototype.hasOwnProperty.call(i.hashes,p)||Object.prototype.hasOwnProperty.call(i.lists,p)||Object.prototype.hasOwnProperty.call(i.sets,p)||Object.prototype.hasOwnProperty.call(i.zsets,p))&&(delete i.kv[p],delete i.hashes[p],delete i.lists[p],delete i.sets[p],delete i.zsets[p],delete i.expires[p],u++);return o(i),{code:0,stdout:a(u),stderr:""}}if(y==="EXISTS"){let u=0;for(const p of l)(Object.prototype.hasOwnProperty.call(i.kv,p)||Object.prototype.hasOwnProperty.call(i.hashes,p)||Object.prototype.hasOwnProperty.call(i.lists,p)||Object.prototype.hasOwnProperty.call(i.sets,p)||Object.prototype.hasOwnProperty.call(i.zsets,p))&&u++;return{code:0,stdout:a(u),stderr:""}}if(y==="INCR"||y==="DECR"||y==="INCRBY"||y==="DECRBY"){const u=l[0],p=y==="INCR"?1:y==="DECR"?-1:(parseInt(l[1],10)||0)*(y==="DECRBY"?-1:1),m=(parseInt(i.kv[u]||"0",10)||0)+p;return i.kv[u]=String(m),o(i),{code:0,stdout:a(m),stderr:""}}if(y==="EXPIRE"){const[u,p]=l;return Object.prototype.hasOwnProperty.call(i.kv,u)||Object.prototype.hasOwnProperty.call(i.hashes,u)||Object.prototype.hasOwnProperty.call(i.lists,u)||Object.prototype.hasOwnProperty.call(i.sets,u)||Object.prototype.hasOwnProperty.call(i.zsets,u)?(i.expires[u]=f+(parseInt(p,10)||0)*1e3,o(i),{code:0,stdout:a(1),stderr:""}):{code:0,stdout:a(0),stderr:""}}if(y==="TTL"){const u=l[0];if(!(Object.prototype.hasOwnProperty.call(i.kv,u)||Object.prototype.hasOwnProperty.call(i.hashes,u)||Object.prototype.hasOwnProperty.call(i.lists,u)||Object.prototype.hasOwnProperty.call(i.sets,u)||Object.prototype.hasOwnProperty.call(i.zsets,u)))return{code:0,stdout:a(-2),stderr:""};if(!i.expires[u])return{code:0,stdout:a(-1),stderr:""};const g=Math.max(0,Math.ceil((i.expires[u]-f)/1e3));return{code:0,stdout:a(g),stderr:""}}if(y==="KEYS"){const u=l[0]||"*",p=new RegExp("^"+u.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$"),g=Array.from(new Set([...Object.keys(i.kv),...Object.keys(i.hashes),...Object.keys(i.lists),...Object.keys(i.sets),...Object.keys(i.zsets)])).filter(m=>p.test(m));return{code:0,stdout:h(g),stderr:""}}if(y==="HSET"){const u=l[0];i.hashes[u]=i.hashes[u]||{};let p=0;for(let g=1;g+1<l.length;g+=2)Object.prototype.hasOwnProperty.call(i.hashes[u],l[g])||p++,i.hashes[u][l[g]]=String(l[g+1]);return o(i),{code:0,stdout:a(p),stderr:""}}if(y==="HGET"){const[u,p]=l,g=i.hashes[u]&&Object.prototype.hasOwnProperty.call(i.hashes[u],p)?i.hashes[u][p]:null;return{code:0,stdout:c(g),stderr:""}}if(y==="HGETALL"){const u=l[0],p=i.hashes[u]||{},g=[];for(const[m,S]of Object.entries(p))g.push(m,S);return{code:0,stdout:h(g),stderr:""}}if(y==="HDEL"){const[u,...p]=l,g=i.hashes[u]||{};let m=0;for(const S of p)Object.prototype.hasOwnProperty.call(g,S)&&(delete g[S],m++);return o(i),{code:0,stdout:a(m),stderr:""}}if(y==="LPUSH"||y==="RPUSH"){const[u,...p]=l;i.lists[u]=i.lists[u]||[];for(const g of p)y==="LPUSH"?i.lists[u].unshift(String(g)):i.lists[u].push(String(g));return o(i),{code:0,stdout:a(i.lists[u].length),stderr:""}}if(y==="LPOP"||y==="RPOP"){const u=l[0],p=i.lists[u]||[],g=p.length===0?null:y==="LPOP"?p.shift():p.pop();return o(i),{code:0,stdout:c(g),stderr:""}}if(y==="LRANGE"){const[u,p,g]=l,m=i.lists[u]||[];let S=parseInt(p,10)||0,b=parseInt(g,10);return isNaN(b)&&(b=-1),S<0&&(S=Math.max(0,m.length+S)),b<0&&(b=m.length+b),{code:0,stdout:h(m.slice(S,b+1)),stderr:""}}if(y==="LLEN"){const u=i.lists[l[0]]||[];return{code:0,stdout:a(u.length),stderr:""}}if(y==="SADD"){const[u,...p]=l,g=new Set(i.sets[u]||[]);let m=0;for(const S of p)g.has(String(S))||(g.add(String(S)),m++);return i.sets[u]=Array.from(g),o(i),{code:0,stdout:a(m),stderr:""}}if(y==="SMEMBERS")return{code:0,stdout:h(i.sets[l[0]]||[]),stderr:""};if(y==="SISMEMBER"){const[u,p]=l,g=new Set(i.sets[u]||[]);return{code:0,stdout:a(g.has(String(p))?1:0),stderr:""}}if(y==="SREM"){const[u,...p]=l,g=new Set(i.sets[u]||[]);let m=0;for(const S of p)g.delete(String(S))&&m++;return i.sets[u]=Array.from(g),o(i),{code:0,stdout:a(m),stderr:""}}if(y==="ZADD"){const[u,...p]=l;i.zsets[u]=i.zsets[u]||{};let g=0;for(let m=0;m+1<p.length;m+=2){const S=parseFloat(p[m]),b=String(p[m+1]);Object.prototype.hasOwnProperty.call(i.zsets[u],b)||g++,i.zsets[u][b]=isNaN(S)?0:S}return o(i),{code:0,stdout:a(g),stderr:""}}if(y==="ZSCORE"){const[u,p]=l,g=i.zsets[u]||{};return{code:0,stdout:Object.prototype.hasOwnProperty.call(g,p)?c(String(g[p])):`(nil)
|
|
814
|
+
`,stderr:""}}if(y==="ZRANGE"||y==="ZREVRANGE"){const[u,p,g,m]=l,S=i.zsets[u]||{},b=Object.entries(S).sort((C,E)=>y==="ZREVRANGE"?E[1]-C[1]||E[0].localeCompare(C[0]):C[1]-E[1]||C[0].localeCompare(E[0]));let v=parseInt(p,10)||0,w=parseInt(g,10);isNaN(w)&&(w=-1),v<0&&(v=Math.max(0,b.length+v)),w<0&&(w=b.length+w);const $=b.slice(v,w+1),R=m&&String(m).toUpperCase()==="WITHSCORES",I=[];for(const[C,E]of $)I.push(C),R&&I.push(String(E));return{code:0,stdout:h(I),stderr:""}}if(y==="ZCARD"){const u=i.zsets[l[0]]||{};return{code:0,stdout:a(Object.keys(u).length),stderr:""}}if(y==="ZREM"){const[u,...p]=l,g=i.zsets[u]||{};let m=0;for(const S of p)Object.prototype.hasOwnProperty.call(g,S)&&(delete g[S],m++);return o(i),{code:0,stdout:a(m),stderr:""}}if(y==="EVAL"){const u=String(l[0]||""),p=Math.max(0,parseInt(l[1],10)||0),g=l.slice(2,2+p),m=l.slice(2+p),S=g[0]||"bucket:default";if(/token_bucket|tokens/i.test(u)){const b=Math.max(1,parseInt(m[0],10)||10),v=i.kv[S]!==void 0?parseInt(i.kv[S],10):b;if(v>0){const w=v-1;return i.kv[S]=String(w),o(i),{code:0,stdout:`1) (integer) 1
|
|
815
|
+
2) (integer) ${w}
|
|
810
816
|
`,stderr:""}}return{code:0,stdout:`1) (integer) 0
|
|
811
817
|
2) (integer) 0
|
|
812
|
-
`,stderr:""}}return{code:0,stdout:
|
|
813
|
-
`}};class x{constructor(e={}){if(this.options=e,this.portTable=e.portTable||(typeof le=="function"?le():null),this.vfs=e.vfs||
|
|
814
|
-
`;f+=p,y=0,s.onStdout&&s.onStdout(p)}else{const a={...s,env:Object.assign({},this.env,o),cwd:this.cwd},
|
|
815
|
-
`){o+=2;continue}r+=t[o+1],o+=2;continue}if(i==="$"&&t[o+1]==="("&&t[o+2]==="("){o+=3;let f=2,
|
|
818
|
+
`,stderr:""}}return{code:0,stdout:c("OK"),stderr:""}}return{code:1,stdout:"",stderr:`ERR unknown command '${y}'
|
|
819
|
+
`}};class x{constructor(e={}){if(this.options=e,this.portTable=e.portTable||(typeof le=="function"?le():null),this.vfs=e.vfs||Ze(),this.env=Object.assign({PATH:"/workspace/node_modules/.bin:/usr/local/bin:/usr/bin:/bin",PWD:"/workspace",HOME:"/home/codelab",USER:"codelab",SHELL:"/bin/sh",TERM:"xterm-256color","?":"0"},e.env||{}),j._homeDir=this.env.HOME||"/home/codelab",this.cwd=this.env.PWD||"/workspace",this.vfs&&typeof this.vfs._setCwd=="function"&&this.vfs._setCwd(this.cwd),this.vfs&&typeof this.vfs.mkdirSync=="function"&&typeof this.vfs.existsSync=="function"&&this.env.HOME&&!this.vfs.existsSync(this.env.HOME))try{this.vfs.mkdirSync(this.env.HOME,{recursive:!0})}catch(s){}if(e.files&&typeof e.files=="object")for(const[s,t]of Object.entries(e.files)){const r=j.resolve(this.cwd,s);if(typeof this.vfs.mkdirSync=="function"){const o=j.dirname(r);o&&o!=="/"&&(typeof this.vfs.existsSync!="function"||!this.vfs.existsSync(o))&&this.vfs.mkdirSync(o,{recursive:!0})}typeof this.vfs.writeFileSync=="function"&&this.vfs.writeFileSync(r,String(t??""))}this.history=[],this.jobs=new Map,this.nextJobId=1,this.nextPid=100,this.commands=Object.assign({},V,e.commands||{}),this._initialBootRoot=e._initialBootRoot?j.normalize(e._initialBootRoot):j.normalize(this.cwd||"/workspace"),this._initialBootSnapshot=e._initialBootSnapshot&&typeof e._initialBootSnapshot=="object"?e._initialBootSnapshot:L(this.vfs,this._initialBootRoot),e.gitState&&typeof e.gitState=="object"?this.gitState=e.gitState:this.gitState=Qe(this.vfs,this.cwd,e)}resolvePath(e){return j._homeDir=this.env&&this.env.HOME||"/home/codelab",e?j.resolve(this.cwd,e):this.cwd}_resolvePathBinary(e){if(!e||!this.vfs||typeof this.vfs.existsSync!="function")return null;const s=String(e);if(s.includes("/"))return null;const t=j.join(this.cwd||"/workspace","node_modules/.bin",s);if(this.vfs.existsSync(t))return t;const r=String(this.env&&this.env.PATH||"/workspace/node_modules/.bin:/usr/local/bin:/usr/bin:/bin").split(":").filter(Boolean);for(const i of r){const f=j.join(i,s);if(this.vfs.existsSync(f))return f}const o=j.join("/workspace/node_modules/.bin",s);return this.vfs.existsSync(o)?o:null}hasCommand(e){if(!e)return!1;const s=String(e);return this.functions&&Object.prototype.hasOwnProperty.call(this.functions,s)||this.commands&&Object.prototype.hasOwnProperty.call(this.commands,s)?!0:!!this._resolvePathBinary(s)}_emitVfsMutation(e,s){if(!this.vfs)return;const t={type:e,path:s,timestamp:Date.now()};typeof this.vfs.emit=="function"?(this.vfs.emit("mutation",t),this.vfs.emit("change",t)):typeof this.vfs._emit=="function"&&(this.vfs._emit("mutation",t),this.vfs._emit("change",t)),typeof this.options.onFsChange=="function"&&this.options.onFsChange(t)}async evaluateWord(e,s){if(!e)return"";if(typeof e=="string")return e;let t="";for(const r of e.segments)if(r.type==="literal"||r.type==="single_quoted")t+=r.value;else if(r.type==="variable")t+=this._expandVariable(r.name,s);else if(r.type==="arith")t+=ce(r.expr,s,this.env);else if(r.type==="subshell")t+=await this._executeSubshell(r.command,s);else if(r.type==="double_quoted")for(const o of r.parts)o.type==="literal"?t+=o.value:o.type==="variable"?t+=this._expandVariable(o.name,s):o.type==="arith"?t+=ce(o.expr,s,this.env):o.type==="subshell"&&(t+=await this._executeSubshell(o.command,s));return t}async evaluateWordToArgs(e,s){const t=await this.evaluateWord(e,s);return e.hasWildcard?Fe(t,this.cwd,this.vfs):[t]}_expandVariable(e,s){if(e==="?")return s["?"]!==void 0?String(s["?"]):"0";if(e==="$")return"1";if(e==="PWD")return this.cwd;if(e==="OLDPWD")return s.OLDPWD||this.cwd;if(e.startsWith("#")&&e.length>1){const t=e.slice(1),r=s[t]!==void 0?String(s[t]):"";return String(r.length)}if(e.includes(":=")){const t=e.indexOf(":="),r=e.slice(0,t),o=e.slice(t+2);return(s[r]===void 0||s[r]==="")&&(s[r]=o,this.env[r]=o),String(s[r])}if(e.includes(":-")){const t=e.indexOf(":-"),r=e.slice(0,t),o=e.slice(t+2);return s[r]!==void 0&&s[r]!==""?String(s[r]):o}if(e.includes(":+")){const t=e.indexOf(":+"),r=e.slice(0,t),o=e.slice(t+2);return s[r]!==void 0&&s[r]!==""?o:""}if(e.includes("=")){const t=e.indexOf("="),r=e.slice(0,t),o=e.slice(t+1);return s[r]===void 0&&(s[r]=o,this.env[r]=o),String(s[r])}if(e.includes("-")){const t=e.indexOf("-"),r=e.slice(0,t),o=e.slice(t+1);return s[r]!==void 0?String(s[r]):o}return s[e]!==void 0?String(s[e]):""}async _executeSubshell(e,s){const t=new x({...this.options,vfs:this.vfs,portTable:this.portTable,gitState:this.gitState,_initialBootRoot:this._initialBootRoot,_initialBootSnapshot:this._initialBootSnapshot,env:{...s,PWD:this.cwd}});return t.cwd=this.cwd,(await t.execute(e)).stdout.replace(/\r?\n+$/,"")}async execute(e,s={}){const t=(e||"").trim();if(!t||t.startsWith("#"))return{code:0,exitCode:0,stdout:"",stderr:"",ok:!0};if(this.history.push(t),this.history.length>1e3&&this.history.splice(0,this.history.length-1e3),this.jobs.size>256)for(const[l,a]of this.jobs.entries()){if(this.jobs.size<=256)break;a&&a.status!=="Running"&&this.jobs.delete(l)}const r=s.cwd?this.resolvePath(s.cwd):this.cwd;this.cwd=r,this.env.PWD=r;let o=Object.assign({},this.env,s.env||{});const i=Ce(t);let f="",d="",y=0;for(const l of i.items){if(s.signal&&s.signal.aborted)return{code:130,exitCode:130,stdout:f,stderr:d,aborted:!0};if(l.background){const a=this.nextPid++,c=this.nextJobId++,h=typeof AbortController<"u"?new AbortController:null,u={id:c,pid:a,command:t,status:"Running",startTime:Date.now(),abort:()=>{h&&h.abort()}};this.jobs.set(c,u),typeof this.options.onJobStart=="function"&&this.options.onJobStart(u),this._executeAstNode(l.node,{...s,signal:h?h.signal:void 0,env:Object.assign({},this.env,o),cwd:this.cwd,pid:a,isBackground:!0}).then(g=>{u.status!=="Terminated"&&(u.status="Done",u.exitCode=g.code,typeof this.options.onJobEnd=="function"&&this.options.onJobEnd(u))}).catch(g=>{u.status!=="Terminated"&&(u.status="Failed",u.error=g,typeof this.options.onJobEnd=="function"&&this.options.onJobEnd(u))});const p=`[${c}] ${a}
|
|
820
|
+
`;f+=p,y=0,s.onStdout&&s.onStdout(p)}else{const a={...s,env:Object.assign({},this.env,o),cwd:this.cwd},c=await this._executeAstNode(l.node,a);if(f+=c.stdout||"",d+=c.stderr||"",y=c.code!==void 0?c.code:0,this.env["?"]=String(y),Object.assign(o,this.env),c.aborted||s.signal&&s.signal.aborted)return{code:130,exitCode:130,stdout:f,stderr:d,aborted:!0};if(c.controlFlow&&c.controlFlow.type==="exit"){y=c.controlFlow.code!==void 0?c.controlFlow.code:y;break}}}return{code:y,exitCode:y,stdout:f,stderr:d,ok:y===0}}async executeCommand(e,s={}){return this.execute(e,s)}async _expandHeredocBody(e,s){const t=String(e||"");let r="",o=0;for(;o<t.length;){const i=t[o];if(i==="\\"&&o+1<t.length&&"$`\\\n".includes(t[o+1])){if(t[o+1]===`
|
|
821
|
+
`){o+=2;continue}r+=t[o+1],o+=2;continue}if(i==="$"&&t[o+1]==="("&&t[o+2]==="("){o+=3;let f=2,d="";for(;o<t.length&&f>0;)if(t[o]==="(")f++,d+="(",o++;else if(t[o]===")"){if(f===2&&t[o+1]===")"){f=0,o+=2;break}f--,f>0&&(d+=")"),o++}else d+=t[o++];r+=ce(d,s,this.env);continue}if(i==="$"&&t[o+1]==="("){o+=2;let f=1,d="";for(;o<t.length&&f>0;)t[o]==="("?f++:t[o]===")"&&f--,f>0&&(d+=t[o]),o++;r+=await this._executeSubshell(d,s);continue}if(i==="`"){o++;let f="";for(;o<t.length&&t[o]!=="`";)f+=t[o++];o<t.length&&t[o]==="`"&&o++,r+=await this._executeSubshell(f,s);continue}if(i==="$"){if(o++,t[o]==="{"){o++;let f="",d=1;for(;o<t.length&&d>0;)t[o]==="{"?d++:t[o]==="}"&&d--,d>0&&(f+=t[o]),o++;r+=this._expandVariable(f,s)}else if(o<t.length&&/[0-9?!$#@*]/.test(t[o]))r+=this._expandVariable(t[o++],s);else if(o<t.length&&/[a-zA-Z_]/.test(t[o])){let f="";for(;o<t.length&&/[a-zA-Z0-9_]/.test(t[o]);)f+=t[o++];r+=this._expandVariable(f,s)}else r+="$";continue}r+=i,o++}return r}async _resolveInputRedirect(e,s){if(e.type==="<"){const t=await this.evaluateWord(e.target,s),r=this.resolvePath(t);if(!this.vfs.existsSync(r))return{ok:!1,error:{code:1,stdout:"",stderr:`shell: ${t}: No such file or directory
|
|
816
822
|
`}};try{return{ok:!0,stdin:this.vfs.readFileSync(r,"utf8")}}catch(o){return{ok:!1,error:{code:1,stdout:"",stderr:`shell: ${t}: ${o.message}
|
|
817
823
|
`}}}}if(e.type==="<<<")return{ok:!0,stdin:await this.evaluateWord(e.target,s)+`
|
|
818
|
-
`};if(e.type==="<<"){let t=String(e.body||"");return e.stripTabs&&(t=t.replace(/^\t+/gm,"")),e.quoted||(t=await this._expandHeredocBody(t,s)),{ok:!0,stdin:t}}return null}_evaluateDoubleBracket(e){const s=e.lastIndexOf("]]");if(s===-1)return{code:2,stdout:"",stderr:"shell: [[: missing `]]`\n"};const t=e.slice(0,s);let r=0;const o=a=>{let
|
|
819
|
-
`};if(h.type===">"){this.vfs.writeFileSync(p,""),this._emitVfsMutation("create",p);const m={type:"file",path:p,append:!0};h.sourceFd===2?i=m:o=m}else if(h.type===">>"){this.vfs.existsSync(p)||(this.vfs.writeFileSync(p,""),this._emitVfsMutation("create",p));const m={type:"file",path:p,append:!0};h.sourceFd===2?i=m:o=m}else if(h.type==="&>"){this.vfs.writeFileSync(p,""),this._emitVfsMutation("create",p);const m={type:"file",path:p,append:!0};o=m,i=m}}else h.type===">&"&&(h.sourceFd===2&&h.targetFd===1?i={...o}:h.sourceFd===1&&h.targetFd===2&&(o={...i}));let
|
|
820
|
-
`;t+=
|
|
821
|
-
`};if(!this.vfs.statSync(
|
|
824
|
+
`};if(e.type==="<<"){let t=String(e.body||"");return e.stripTabs&&(t=t.replace(/^\t+/gm,"")),e.quoted||(t=await this._expandHeredocBody(t,s)),{ok:!0,stdin:t}}return null}_evaluateDoubleBracket(e){const s=e.lastIndexOf("]]");if(s===-1)return{code:2,stdout:"",stderr:"shell: [[: missing `]]`\n"};const t=e.slice(0,s);let r=0;const o=a=>{let c="^";for(let h=0;h<a.length;h++){const u=a[h];u==="*"?c+=".*":u==="?"?c+=".":c+=u.replace(/[.+^${}()|[\]\\]/g,"\\$&")}return new RegExp(c+"$")},i=()=>{let a=f();for(;t[r]==="||";){r++;const c=f();a=a||c}return a},f=()=>{let a=d();for(;t[r]==="&&";){r++;const c=d();a=a&&c}return a},d=()=>t[r]==="!"?(r++,!d()):y(),y=()=>{if(r>=t.length)return!1;if(t[r]==="("){r++;const u=i();return t[r]===")"&&r++,u}const a=t[r];if(/^-(?:z|n|e|f|d|s)$/.test(a)&&r+1<t.length){r++;const u=String(t[r++]??"");if(a==="-z")return u.length===0;if(a==="-n")return u.length>0;const p=this.resolvePath(u),g=this.vfs.existsSync(p);if(a==="-e")return g;if(!g)return!1;const m=this.vfs.statSync(p);if(a==="-d")return!!(m&&m.isDirectory());if(a==="-f")return!!(m&&!m.isDirectory());if(a==="-s")return!!(m&&!m.isDirectory()&&m.size>0)}const c=String(t[r++]??""),h=t[r];if(h&&/^(?:==|=|!=|=~|<|>|-eq|-ne|-lt|-le|-gt|-ge)$/.test(h)&&r+1<t.length){r++;const u=String(t[r++]??"");if(h==="=="||h==="=")return o(u).test(c);if(h==="!=")return!o(u).test(c);if(h==="=~")try{return new RegExp(u).test(c)}catch(m){return M.debug("[[ =~ invalid regex",u,m),!1}if(h==="<")return c<u;if(h===">")return c>u;const p=Number(c)||0,g=Number(u)||0;if(h==="-eq")return p===g;if(h==="-ne")return p!==g;if(h==="-lt")return p<g;if(h==="-le")return p<=g;if(h==="-gt")return p>g;if(h==="-ge")return p>=g}return c.length>0};return{code:i()?0:1,stdout:"",stderr:""}}async _executeWithRedirects(e,s,t){if(!e||e.length===0)return t(s);const r=Object.assign({},this.env,s.env);let o={type:"stdout"},i={type:"stderr"},f=s.stdin||"";for(const h of e)if(h.type==="<"||h.type==="<<"||h.type==="<<<"){const u=await this._resolveInputRedirect(h,r);if(u&&!u.ok)return u.error;u&&u.ok&&(f=u.stdin)}for(const h of e)if(!(h.type==="<"||h.type==="<<"||h.type==="<<<"))if(h.type===">"||h.type===">>"||h.type==="&>"){const u=await this.evaluateWord(h.target,r),p=this.resolvePath(u),g=j.dirname(p);if(!this.vfs.existsSync(g))return{code:1,stdout:"",stderr:`shell: ${u}: No such file or directory
|
|
825
|
+
`};if(h.type===">"){this.vfs.writeFileSync(p,""),this._emitVfsMutation("create",p);const m={type:"file",path:p,append:!0};h.sourceFd===2?i=m:o=m}else if(h.type===">>"){this.vfs.existsSync(p)||(this.vfs.writeFileSync(p,""),this._emitVfsMutation("create",p));const m={type:"file",path:p,append:!0};h.sourceFd===2?i=m:o=m}else if(h.type==="&>"){this.vfs.writeFileSync(p,""),this._emitVfsMutation("create",p);const m={type:"file",path:p,append:!0};o=m,i=m}}else h.type===">&"&&(h.sourceFd===2&&h.targetFd===1?i={...o}:h.sourceFd===1&&h.targetFd===2&&(o={...i}));let d="",y="";const l=(h,u)=>{u&&(h.type==="stdout"?(d+=u,s.onStdout&&s.onStdout(u)):h.type==="stderr"?(y+=u,s.onStderr&&s.onStderr(u)):h.type==="file"&&(this.vfs.appendFileSync(h.path,u),this._emitVfsMutation("change",h.path)))},a={...s,stdin:f,onStdout:h=>l(o,h),onStderr:h=>l(i,h)};return{...await t(a),stdout:d,stderr:y}}async _executeAstNode(e,s){if(!e)return{code:0,stdout:"",stderr:""};if(s.signal&&s.signal.aborted)return{code:130,stdout:"",stderr:"",aborted:!0};if(e.type==="Sequence"){let t="",r="",o=0,i=null;for(const f of e.items||[]){if(s.signal&&s.signal.aborted)return{code:130,stdout:t,stderr:r,aborted:!0};if(f.background){const d=this.nextPid++,y=this.nextJobId++,l=typeof AbortController<"u"?new AbortController:null,a={id:y,pid:d,command:"background",status:"Running",startTime:Date.now(),abort:()=>{l&&l.abort()}};this.jobs.set(y,a),typeof this.options.onJobStart=="function"&&this.options.onJobStart(a),this._executeAstNode(f.node,{...s,signal:l?l.signal:void 0,pid:d,isBackground:!0}).then(h=>{a.status!=="Terminated"&&(a.status="Done",a.exitCode=h.code,typeof this.options.onJobEnd=="function"&&this.options.onJobEnd(a))}).catch(h=>{a.status!=="Terminated"&&(a.status="Failed",a.error=h,typeof this.options.onJobEnd=="function"&&this.options.onJobEnd(a))});const c=`[${y}] ${d}
|
|
826
|
+
`;t+=c,o=0,s.onStdout&&s.onStdout(c)}else{const d=await this._executeAstNode(f.node,s);if(t+=d.stdout||"",r+=d.stderr||"",o=d.code!==void 0?d.code:0,this.env["?"]=String(o),s.env&&(s.env["?"]=String(o)),d.controlFlow){i=d.controlFlow;break}if(d.aborted||s.signal&&s.signal.aborted)return{code:130,stdout:t,stderr:r,aborted:!0}}}return{code:o,stdout:t,stderr:r,controlFlow:i}}if(e.type==="Logical"){const t=await this._executeAstNode(e.left,s);if(t.aborted||s.signal&&s.signal.aborted)return{...t,code:130,aborted:!0};if(t.controlFlow)return t;if(e.op==="&&"){if(t.code===0){const r={...s,cwd:this.cwd,env:Object.assign({},this.env)},o=await this._executeAstNode(e.right,r);return{code:o.code,stdout:(t.stdout||"")+(o.stdout||""),stderr:(t.stderr||"")+(o.stderr||""),controlFlow:o.controlFlow,aborted:o.aborted}}return t}else if(e.op==="||"){if(t.code!==0){const r={...s,cwd:this.cwd,env:Object.assign({},this.env)},o=await this._executeAstNode(e.right,r);return{code:o.code,stdout:(t.stdout||"")+(o.stdout||""),stderr:(t.stderr||"")+(o.stderr||""),controlFlow:o.controlFlow,aborted:o.aborted}}return t}}return e.type==="Pipeline"?this._executePipeline(e,s):e.type==="Command"?this._executeSimpleCommand(e,s):e.type==="FunctionDef"?(this.functions||(this.functions={}),this.functions[e.name]=e,{code:0,stdout:"",stderr:""}):e.type==="For"?this._executeWithRedirects(e.redirects,s,async t=>{let r="",o="",i=0;const f=[];if(e.items)for(const y of e.items){const l=await this.evaluateWordToArgs(y,t.env);f.push(...l)}else f.push(...t.positionalArgs||[]);let d=0;for(const y of f){if(++d%250===0&&typeof setTimeout=="function"&&await new Promise(a=>setTimeout(a,0)),t.signal&&t.signal.aborted)return{code:130,stdout:r,stderr:o,aborted:!0};t.env[e.varName]=y,this.env[e.varName]=y;const l=await this._executeAstNode(e.body,t);if(r+=l.stdout||"",o+=l.stderr||"",i=l.code!==void 0?l.code:0,this.env["?"]=String(i),t.env&&(t.env["?"]=String(i)),l.aborted||t.signal&&t.signal.aborted)return{code:130,stdout:r,stderr:o,aborted:!0};if(l.controlFlow)if(l.controlFlow.type==="break"){const a=l.controlFlow.count||1;if(a>1)return{code:i,stdout:r,stderr:o,controlFlow:{type:"break",count:a-1}};break}else if(l.controlFlow.type==="continue"){const a=l.controlFlow.count||1;if(a>1)return{code:i,stdout:r,stderr:o,controlFlow:{type:"continue",count:a-1}};continue}else return{code:i,stdout:r,stderr:o,controlFlow:l.controlFlow}}return{code:i,stdout:r,stderr:o}}):e.type==="While"||e.type==="Until"?this._executeWithRedirects(e.redirects,s,async t=>{const r=e.type==="While";let o="",i="",f=0,d=0;for(;;){if(++d%250===0&&typeof setTimeout=="function"&&await new Promise(c=>setTimeout(c,0)),t.signal&&t.signal.aborted)return{code:130,stdout:o,stderr:i,aborted:!0};const y=await this._executeAstNode(e.cond,t);if(o+=y.stdout||"",i+=y.stderr||"",y.aborted||t.signal&&t.signal.aborted)return{code:130,stdout:o,stderr:i,aborted:!0};if(y.controlFlow)return{code:y.code,stdout:o,stderr:i,controlFlow:y.controlFlow};const l=y.code===0;if(r?!l:l)break;if(t.signal&&t.signal.aborted)return{code:130,stdout:o,stderr:i,aborted:!0};const a=await this._executeAstNode(e.body,t);if(o+=a.stdout||"",i+=a.stderr||"",f=a.code!==void 0?a.code:0,this.env["?"]=String(f),t.env&&(t.env["?"]=String(f)),a.aborted||t.signal&&t.signal.aborted)return{code:130,stdout:o,stderr:i,aborted:!0};if(a.controlFlow)if(a.controlFlow.type==="break"){const c=a.controlFlow.count||1;if(c>1)return{code:f,stdout:o,stderr:i,controlFlow:{type:"break",count:c-1}};break}else if(a.controlFlow.type==="continue"){const c=a.controlFlow.count||1;if(c>1)return{code:f,stdout:o,stderr:i,controlFlow:{type:"continue",count:c-1}};continue}else return{code:f,stdout:o,stderr:i,controlFlow:a.controlFlow}}return{code:f,stdout:o,stderr:i}}):e.type==="If"?this._executeWithRedirects(e.redirects,s,async t=>{let r="",o="";for(const i of e.branches||[]){if(t.signal&&t.signal.aborted)return{code:130,stdout:r,stderr:o,aborted:!0};const f=await this._executeAstNode(i.cond,t);if(r+=f.stdout||"",o+=f.stderr||"",f.aborted||t.signal&&t.signal.aborted)return{code:130,stdout:r,stderr:o,aborted:!0};if(f.code===0){const d=await this._executeAstNode(i.body,t);return r+=d.stdout||"",o+=d.stderr||"",{code:d.code,stdout:r,stderr:o,controlFlow:d.controlFlow,aborted:d.aborted}}}if(e.elseBody){const i=await this._executeAstNode(e.elseBody,t);return r+=i.stdout||"",o+=i.stderr||"",{code:i.code,stdout:r,stderr:o,controlFlow:i.controlFlow,aborted:i.aborted}}return{code:0,stdout:r,stderr:o}}):e.type==="BraceGroup"?this._executeWithRedirects(e.redirects,s,t=>this._executeAstNode(e.body,t)):e.type==="Subshell"?this._executeWithRedirects(e.redirects,s,async t=>{const r=new x({...this.options,vfs:this.vfs,portTable:this.portTable,gitState:this.gitState,env:Object.assign({},this.env,t.env||{})});r.cwd=t.cwd||this.cwd;const o={...t,env:Object.assign({},this.env,t.env||{}),cwd:r.cwd};return r._executeAstNode(e.body,o)}):e.type==="Case"?this._executeWithRedirects(e.redirects,s,async t=>{const r=await this.evaluateWord(e.word,t.env);for(const o of e.clauses||[]){let i=!1;for(const f of o.patterns||[]){const d=await this.evaluateWord(f,t.env);if(d==="*"||d===r){i=!0;break}if(new RegExp("^"+d.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$").test(r)){i=!0;break}}if(i)return this._executeAstNode(o.body,t)}return{code:0,stdout:"",stderr:""}}):{code:0,stdout:"",stderr:""}}async _executePipeline(e,s){const t=e.commands||[];let r=s.stdin||"",o="",i={code:0,stdout:"",stderr:""};const f=t.length>1,d=this.cwd;for(let l=0;l<t.length;l++){if(s.signal&&s.signal.aborted)return{code:130,stdout:i.stdout||"",stderr:o,aborted:!0};const a=t[l],c=l===t.length-1,h={...s,stdin:r,onStdout:c?s.onStdout:null,onStderr:s.onStderr};let u;if(f){const p=Object.assign({},this.env,s.env||{}),g=new x({...this.options,vfs:this.vfs,portTable:this.portTable,gitState:this.gitState,_initialBootRoot:this._initialBootRoot,_initialBootSnapshot:this._initialBootSnapshot,env:p});g.cwd=s.cwd||d,g.functions=Object.assign({},this.functions||{}),u=await g._executeAstNode(a,{...h,cwd:g.cwd,env:Object.assign({},p)}),this.vfs&&typeof this.vfs._setCwd=="function"&&this.vfs._setCwd(d)}else u=await this._executeAstNode(a,h);if(r=u.stdout||"",o+=u.stderr||"",i=u,u.aborted||s.signal&&s.signal.aborted)return{code:130,stdout:i.stdout||"",stderr:o,aborted:!0}}let y=i.code!==void 0?i.code:0;return e.negated&&!i.aborted&&(y=y===0?1:0),{code:y,stdout:i.stdout||"",stderr:o,controlFlow:i.controlFlow,aborted:!!(i.aborted||s.signal&&s.signal.aborted)}}async _executeSimpleCommand(e,s){const t=Object.assign({},this.env,s.env);for(const m of e.envVars){const S=await this.evaluateWord(m.token,t),b=S.indexOf("=");if(b!==-1){const v=S.slice(0,b),w=S.slice(b+1);t[v]=w,e.name||(this.env[v]=w,s.env[v]=w)}}if(!e.name)return Object.assign(s.env,this.env),{code:0,stdout:"",stderr:""};const r=await this.evaluateWord(e.name,t),o=[];for(const m of e.args){const S=await this.evaluateWordToArgs(m,t);o.push(...S)}if(r===":")return Object.assign(this.env,t),Object.assign(s.env,t),{code:0,stdout:"",stderr:""};if(r==="exit"){const m=o.length>0?parseInt(o[0],10):parseInt(this.env["?"]||"0",10),S=Number.isNaN(m)?2:(m%256+256)%256;return{code:S,stdout:"",stderr:"",controlFlow:{type:"exit",code:S}}}if(r==="[[")return this._evaluateDoubleBracket(o);if(r==="break")return{code:0,stdout:"",stderr:"",controlFlow:{type:"break",count:parseInt(o[0],10)||1}};if(r==="continue")return{code:0,stdout:"",stderr:"",controlFlow:{type:"continue",count:parseInt(o[0],10)||1}};if(r==="return"){const m=parseInt(o[0],10)||0;return{code:m,stdout:"",stderr:"",controlFlow:{type:"return",code:m}}}if(s.signal&&s.signal.aborted)return{code:130,stdout:"",stderr:"",aborted:!0};let i=s.stdin||"";for(const m of e.redirects)if(m.type==="<"||m.type==="<<"||m.type==="<<<"){const S=await this._resolveInputRedirect(m,t);if(S&&!S.ok)return S.error;S&&S.ok&&(i=S.stdin)}let f={type:"stdout"},d={type:"stderr"};for(const m of e.redirects)if(!(m.type==="<"||m.type==="<<"||m.type==="<<<"))if(m.type===">"||m.type===">>"||m.type==="&>"){const S=await this.evaluateWord(m.target,t),b=this.resolvePath(S),v=j.dirname(b);if(!this.vfs.existsSync(v))return{code:1,stdout:"",stderr:`shell: ${S}: No such file or directory
|
|
827
|
+
`};if(!this.vfs.statSync(v).isDirectory())return{code:1,stdout:"",stderr:`shell: ${S}: Not a directory
|
|
822
828
|
`};if(this.vfs.existsSync(b)&&this.vfs.statSync(b).isDirectory())return{code:1,stdout:"",stderr:`shell: ${S}: Is a directory
|
|
823
|
-
`};if(m.type===">"){this.vfs.writeFileSync(b,""),this._emitVfsMutation("create",b);const $={type:"file",path:b,append:!0};m.sourceFd===2?
|
|
824
|
-
`};else if(
|
|
825
|
-
`}}else if(
|
|
829
|
+
`};if(m.type===">"){this.vfs.writeFileSync(b,""),this._emitVfsMutation("create",b);const $={type:"file",path:b,append:!0};m.sourceFd===2?d=$:f=$}else if(m.type===">>"){this.vfs.existsSync(b)||(this.vfs.writeFileSync(b,""),this._emitVfsMutation("create",b));const $={type:"file",path:b,append:!0};m.sourceFd===2?d=$:f=$}else if(m.type==="&>"){this.vfs.writeFileSync(b,""),this._emitVfsMutation("create",b);const $={type:"file",path:b,append:!0};f=$,d=$}}else m.type===">&"&&(m.sourceFd===2&&m.targetFd===1?d={...f}:m.sourceFd===1&&m.targetFd===2&&(f={...d}));let y="",l="",a=0,c=0;const h=(m,S,b=!1)=>{S&&(m.type==="stdout"?(y+=S,b&&s.onStdout&&s.onStdout(S)):m.type==="stderr"?(l+=S,b&&s.onStderr&&s.onStderr(S)):m.type==="file"&&(this.vfs.appendFileSync(m.path,S),this._emitVfsMutation("change",m.path)))},u={vfs:this.vfs,shell:this,portTable:this.portTable,cwd:this.cwd,env:t,stdin:i,pid:s.pid||1e3,isBackground:!!s.isBackground,resolvePath:m=>this.resolvePath(m),emitMutation:(m,S)=>this._emitVfsMutation(m,S),signal:s.signal,onRequestStdin:(typeof s.onRequestStdin=="function"?s.onRequestStdin:null)||(this.options&&typeof this.options.onRequestStdin=="function"?this.options.onRequestStdin:void 0),onStdout:m=>{m&&(a+=m.length,h(f,m,!0))},onStderr:m=>{m&&(c+=m.length,h(d,m,!0))}};let p;const g=!(this.functions&&this.functions[r])&&!this.commands[r]?this._resolvePathBinary(r):null;if(this.functions&&this.functions[r]){const m=this.functions[r],S=Object.assign({},t);o.forEach((v,w)=>{S[String(w+1)]=v}),S["#"]=String(o.length),S["@"]=o.join(" "),S["*"]=o.join(" ");const b=await this._executeAstNode(m.body,{...s,env:S,positionalArgs:o});p={code:b.controlFlow?.type==="return"?b.controlFlow.code:b.code||0,stdout:b.stdout||"",stderr:b.stderr||""}}else if(this.commands[r]){if(p=await this.commands[r](o,u),r==="export"||r==="unset"||r==="cd"||r==="read"){for(const m of Object.keys(s.env))m in this.env||delete s.env[m];Object.assign(s.env,this.env),s.cwd=this.cwd}}else if(g){const S=String(this.vfs.readFileSync(g,"utf8")||"").match(/exec\s+node\s+"([^"]+)"/);S&&S[1]?p=await this.commands.node([S[1],...o],u):p=await this.commands.node([g,...o],u)}else if((r.startsWith("./")||r.startsWith("../")||r.startsWith("/"))&&this.vfs.existsSync(this.resolvePath(r))){const m=this.resolvePath(r),S=this.vfs.statSync(m);if(S&&S.isDirectory())p={code:126,stdout:"",stderr:`shell: ${r}: Is a directory
|
|
830
|
+
`};else if(Re()){let b=null;try{b=typeof this.vfs._getRawFileBytes=="function"?this.vfs._getRawFileBytes(m)||this.vfs.readFileSync(m):this.vfs.readFileSync(m)}catch(R){M.debug("Failed to read binary",R)}const v=b instanceof Uint8Array&&b.length>=4&&b[0]===0&&b[1]===97&&b[2]===115&&b[3]===109||typeof b=="string"&&b.startsWith("\0asm"),$=await(v?Oe:R=>q(R,u))({mode:"run",entry:m,wasmBinary:v&&b instanceof Uint8Array?b:void 0,argv:[r,...o],stdin:i,env:t,cwd:this.cwd,vfs:this.vfs,activePortTable:this.portTable,pid:u.pid,isBackground:u.isBackground,onRequestStdin:u.onRequestStdin,onStdout:u.onStdout,onStderr:u.onStderr,signal:s.signal});p={code:$.ok?0:$.exitCode||1,stdout:$.stdout||"",stderr:$.stderr||""}}else p={code:126,stdout:"",stderr:`shell: ${r}: cannot execute binary file
|
|
831
|
+
`}}else if(kt.test(r))p=await Ve(r,[r,...o].join(" "),u,{force:!0})||{code:127,stdout:"",stderr:`shell: ${r}: command not found
|
|
826
832
|
`};else if(typeof this.options.onProcessSpawn=="function"){const m=await this.options.onProcessSpawn(r,o,{cwd:this.cwd,env:t,stdin:i,onStdout:u.onStdout,onStderr:u.onStderr,signal:s.signal});m!=null?p=m:p={code:127,stdout:"",stderr:`shell: ${r}: command not found
|
|
827
833
|
`}}else p={code:127,stdout:"",stderr:`shell: ${r}: command not found
|
|
828
|
-
`};return p||(p={code:0,stdout:"",stderr:""}),p.stdout&&(p.alreadyStreamed?y=p.stdout:a>0?p.stdout.length>a&&h(f,p.stdout.slice(a),!0):(h(f,p.stdout,!1),s.onStdout&&y&&s.onStdout(y))),p.stderr&&(
|
|
834
|
+
`};return p||(p={code:0,stdout:"",stderr:""}),p.stdout&&(p.alreadyStreamed?y=p.stdout:a>0?p.stdout.length>a&&h(f,p.stdout.slice(a),!0):(h(f,p.stdout,!1),s.onStdout&&y&&s.onStdout(y))),p.stderr&&(c>0?p.stderr.length>c&&h(d,p.stderr.slice(c),!0):(h(d,p.stderr,!1),s.onStderr&&l&&s.onStderr(l))),{code:p.code!==void 0?p.code:0,stdout:y,stderr:l,controlFlow:p.controlFlow,aborted:p.aborted||s.signal&&s.signal.aborted}}}function jt(n={}){return new x(n)}return{createPosixShell:jt,parseShellCommand:Ce,tokenizeShell:Te,PosixShell:x,COREUTILS:V,PosixPath:j,expandGlob:Fe,createVirtualPortTable:le,parseGitHubRepoUrl:fe,cloneGitHubRepository:he}});
|
|
829
835
|
|
|
830
836
|
})();
|
|
831
837
|
|