From 944c0e6bd2464e25f2fa7e626eeed70603e6c240 Mon Sep 17 00:00:00 2001 From: MK Date: Wed, 16 Sep 2026 14:44:38 +0800 Subject: [PATCH 1/3] fix(ci): temporarily skip sfw blocking checks --- .github/workflows/test.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index db2f689..555fa70 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -706,6 +706,9 @@ jobs: run: vp exec node -e "console.log(require('is-odd')(3))" test-sfw-blocks-malicious: + # Temporarily skip while Socket alert lookups fail. Restore in #161: + # https://github.com/voidzero-dev/setup-vp/issues/161 + if: ${{ false }} # Verifies sfw actually intercepts a known-malicious package, not just # that it wraps the install. Uses `lodahs` (lodash typosquat), the same # canary SocketDev's own workflows use: @@ -830,6 +833,9 @@ jobs: run: vp exec node -e "console.log(require('is-odd')(3))" - name: Assert composed sfw blocks malicious package (lodahs) + # Temporarily skip while Socket alert lookups fail. Restore in #161: + # https://github.com/voidzero-dev/setup-vp/issues/161 + if: ${{ false }} shell: bash working-directory: ${{ runner.temp }}/test-project # Proves the composition path actually enforces, not just that sfw is From b2ccad2f40d285b35ced7822cd918872f395fde2 Mon Sep 17 00:00:00 2001 From: MK Date: Wed, 16 Sep 2026 12:17:19 +0800 Subject: [PATCH 2/3] fix: disable sfw for Vite+ preview builds --- README.md | 2 ++ dist/azure/index.mjs | 8 +++--- dist/gitlab/index.mjs | 4 +-- dist/index.mjs | 4 +-- src/azure/index.ts | 11 +++++++- src/azure/parity.test.ts | 45 +++++++++++++++++++++++++++++- src/ci/install-sfw.test.ts | 56 +++++++++++++++++++++++++++++++++++++- src/ci/install-sfw.ts | 15 ++++++++-- src/ci/sfw.ts | 12 ++++++++ src/gitlab/index.test.ts | 36 +++++++++++++++++++++++- src/gitlab/index.ts | 2 +- src/gitlab/install-sfw.ts | 2 ++ src/index.test.ts | 35 +++++++++++++++++++++++- src/index.ts | 6 ++-- src/install-sfw.test.ts | 34 +++++++++++++++++++++++ src/install-sfw.ts | 3 +- 16 files changed, 255 insertions(+), 20 deletions(-) create mode 100644 src/ci/sfw.ts diff --git a/README.md b/README.md index 0e7e522..4894d2b 100644 --- a/README.md +++ b/README.md @@ -281,6 +281,8 @@ steps: `sfw` is only applied when `run-install` is enabled; other `vp` commands (e.g. `vp env use`, `vp --version`) run unwrapped. +For Vite+ preview builds (`0.0.0-commit.<40-character SHA>`), setup-vp automatically disables `sfw`, even when it is enabled, and logs a warning. Dependency installation runs with plain `vp install`. This applies to GitHub Actions, GitLab CI/CD, and Azure Pipelines, including when `sfw` is already on `PATH`. + The action pins the `sfw` version it downloads so a re-run of the same commit gets the same binary. #### Advanced: stricter supply chain via `socketdev/action` diff --git a/dist/azure/index.mjs b/dist/azure/index.mjs index 99fb52f..6777f27 100644 --- a/dist/azure/index.mjs +++ b/dist/azure/index.mjs @@ -112,14 +112,14 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\ `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(` `,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=getFirstKeyStartProps(getPrevProps(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=getFirstKeyStartProps(getPrevProps(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),Qe=__commonJSMin((e=>{var t=We(),n=G(),r=K(),i=le(),a=O(),o=Xe(),s=Ze();function parseOptions(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function parseAllDocuments(e,n={}){let{lineCounter:i,prettyErrors:a}=parseOptions(n),o=new s.Parser(i?.addNewLine),c=new t.Composer(n),l=Array.from(c.compose(o.parse(e)));if(a&&i)for(let t of l)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return l.length>0?l:Object.assign([],{empty:!0},c.streamInfo())}function parseDocument(e,n={}){let{lineCounter:i,prettyErrors:a}=parseOptions(n),o=new s.Parser(i?.addNewLine),c=new t.Composer(n),l=null;for(let t of c.compose(o.parse(e),!0,e.length))if(!l)l=t;else if(l.options.logLevel!==`silent`){l.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(l.errors.forEach(r.prettifyError(e,i)),l.warnings.forEach(r.prettifyError(e,i))),l}function parse(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=parseDocument(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function stringify(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=parse,e.parseAllDocuments=parseAllDocuments,e.parseDocument=parseDocument,e.stringify=stringify})),Y=__commonJSMin((e=>{var t=We(),n=G(),r=ke(),i=K(),a=M(),o=O(),s=R(),c=N(),l=z(),u=V();Je();var d=Ye(),f=Xe(),p=Ze(),m=Qe(),h=k();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync}))();function parseInstalledVpVersion(e){return(e.match(/^\s*vp\s+v?(\d[^\s]*)/im)??e.match(/Global:\s*v?(\d[^\s]*)/i))?.[1]??`unknown`}const $e=new Set([`true`,`True`,`TRUE`]),et=new Set([`false`,`False`,`FALSE`]);function parseNodeManager(e){if(e){if($e.has(e))return!0;if(et.has(e))return!1;throw Error(`Invalid node-manager input: "${e}". Expected "true", "false", or unset.`)}}function supportsScopedEnv(e){let t=parseInstalledVpVersion(e);if(t.startsWith(`0.0.0-commit.`))return!0;let n=t.match(/^(\d+)\.(\d+)\.(\d+)/);if(!n)throw Error(`Could not determine the installed Vite+ version for env configuration.`);let[,r,i,a]=n.map(Number);return r>0||i>3||i===3&&a>=1}function nodeManagerOffArgs(e){return parseInstalledVpVersion(e).startsWith(`0.0.0-commit.`)&&console.info("setup-vp: node-manager: false requires a preview build that supports `vp env off node`. If this command is unsupported, use a newer preview or a stable release. setup-vp will not fall back to disabling package-manager management."),supportsScopedEnv(e)?[`env`,`off`,`node`]:[`env`,`off`]}const tt=[`npm`,`pnpm`,`yarn`,`bun`];function parsePackageManager(e){if(!e?.trim())return;let t;try{t=(0,Y.parse)(e)}catch(e){throw Error(`Invalid package-manager input: ${String(e)}`)}if(t!==``){if(typeof t==`boolean`)return t;if(t&&typeof t==`object`&&!Array.isArray(t)){for(let[e,n]of Object.entries(t))if(!tt.includes(e)||typeof n!=`boolean`)throw Error(`Invalid package-manager input: ${e} must be npm, pnpm, yarn, or bun with a boolean value.`);return t}throw Error(`Invalid package-manager input: expected a boolean or a mapping of npm, pnpm, yarn, and bun to booleans.`)}}function packageManagerArgs(e,t){if(e===void 0)return[];if(!supportsScopedEnv(t))throw Error(`package-manager configuration requires Vite+ 0.3.1 or newer.`);return typeof e==`boolean`?e?[]:[[`env`,`off`,`pm`]]:tt.filter(t=>e[t]===!1).map(e=>[`env`,`off`,e])}const X=`Vite+`,Z=`vite-plus`;function resolvePath$1(e,t){return u.isAbsolute(e)?e:u.join(t,e)}function isWithin(e,t){let n=u.relative(t,e);return!u.isAbsolute(n)&&n!==`..`&&!n.startsWith(`..${u.sep}`)}function resolveProjectDirectory(e){let{workingDirectory:t,workspaceRoot:n}=e,r=u.isAbsolute(t)?t:u.join(n,t);try{if(!c(r).isDirectory())throw Error(`working-directory is not a directory: ${t} (resolved to ${r})`)}catch(e){throw e instanceof Error&&`code`in e&&e.code===`ENOENT`?Error(`working-directory not found: ${t} (resolved to ${r})`):e}return r}function run(e,t,n={}){let r=y(e,t,{stdio:`inherit`,...n});if(r.error)throw r.error;if(r.status!==0)throw Error(`${e} ${t.join(` `)} exited with code ${r.status??1}`)}function runWithOutput(e,t,n={}){return new Promise((r,i)=>{let a=v(e,t,{...n,stdio:[`ignore`,`pipe`,`pipe`]}),o=``,s=``;a.stdout.on(`data`,e=>{process.stdout.write(e),o=(o+e.toString()).slice(-4e3)}),a.stderr.on(`data`,e=>{process.stderr.write(e),s=(s+e.toString()).slice(-4e3)}),a.on(`error`,i),a.on(`close`,e=>r({exitCode:e??1,stdout:o,stderr:s}))})}function commandPath(e){if(process.platform===`win32`){let t=y(`where`,[e],{encoding:`utf8`});return t.status===0&&t.stdout.trim().split(/\r?\n/)[0]?.trim()||void 0}let t=y(`sh`,[`-c`,`command -v "$1"`,`sh`,e],{encoding:`utf8`});if(t.status===0)return t.stdout.trim()}function getCommandOutput(e,t,n){let r=y(e,t,{cwd:n?.cwd,encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`]});if(r.status===0)return r.stdout.trim()}const nt=[{filename:`pnpm-lock.yaml`,type:`pnpm`},{filename:`bun.lockb`,type:`bun`},{filename:`bun.lock`,type:`bun`},{filename:`package-lock.json`,type:`npm`},{filename:`npm-shrinkwrap.json`,type:`npm`},{filename:`yarn.lock`,type:`yarn`}];function resolvePath(e,t){return p(e)?e:m(t,e)}function inferLockFileType(e,t){return t.includes(`pnpm`)?{type:`pnpm`,path:e,filename:t}:t.includes(`yarn`)?{type:`yarn`,path:e,filename:t}:t.startsWith(`bun.`)?{type:`bun`,path:e,filename:t}:{type:`npm`,path:e,filename:t}}function detectLockFile(e,t){if(e){let r=resolvePath(e,t);if(n(r)){let e=d(r),t=nt.find(t=>t.filename===e);return t?{type:t.type,path:r,filename:e}:inferLockFileType(r,e)}return}let r=o(t);for(let e of nt)if(r.includes(e.filename)){let n=m(t,e.filename);return{type:e.type,path:n,filename:e.filename}}}function prepareCacheMetadata(e){let{projectDir:t,cacheDependencyPath:n,logWarning:r}=e,i=detectLockFile(n||void 0,t);if(!i)return r?.(`setup-vp: cache is enabled but no supported lock file was found; skipping cache.`),{ready:!1};let a=getCommandOutput(`vp`,[`pm`,`cache`,`dir`],{cwd:u.dirname(i.path)});return a?{ready:!0,cachePath:a,lockFile:i.path,lockType:i.type}:(r?.(`setup-vp: could not resolve package-manager cache directory for ${i.filename}; skipping cache.`),{ready:!1})}function createLockfileResolver(e){let{getWorkspaceDir:t,info:r,debug:i}=e,o=/^\d+\.\d+\.\d+/;function tryResolveVitePlusVersionFromLockfile(e,t){let n=detectLockfileForProject(e,t);if(!n)return;let a=n.filename.endsWith(`.lockb`)?textBunLockBeside(n):n;if(!a){i(`Cannot read ${n.filename} (binary) to resolve the ${X} version; using "latest". Use the text bun.lock, or set the \`version\` input.`);return}let o=parseVitePlusVersionFromLockfile(a,workspaceSubPath(f(a.path),e));if(o)return r(`Resolved ${X} version '${o}' from ${a.filename}`),o;i(`No ${X} version found in ${a.path}`)}function detectLockfileForProject(e,n){if(n)return detectLockFile(n,e);let r=t(),i=e;for(;;){let e=detectLockFile(void 0,i);if(e)return e;let t=f(i);if(i===r||t===i||!isWithin(t,r))break;i=t}}function textBunLockBeside(e){let t=m(f(e.path),`bun.lock`);return n(t)?{type:`bun`,path:t,filename:`bun.lock`}:void 0}function workspaceSubPath(e,t){if(!isWithin(t,e))return``;let n=h(e,t);return n?n.split(g).join(`/`):``}function parseVitePlusVersionFromLockfile(e,t=``){if(e.filename.endsWith(`.lockb`))return;let n;try{n=a(e.path,`utf-8`)}catch{return}let r;switch(e.type){case`npm`:r=fromNpmLock(n,t);break;case`pnpm`:r=fromPnpmLock(n,t);break;case`yarn`:r=fromYarnLock(n);break;case`bun`:r=fromBunTextLock(n);break;default:return}return r&&o.test(r)?r:void 0}function fromNpmLock(e,t){let n;try{n=JSON.parse(e)}catch{return}let r=n.packages;if(t){let e=r?.[`${t}/node_modules/${Z}`]?.version;if(typeof e==`string`)return e;if(!npmPackageDeclaresVitePlus(r?.[t]))return}let i=r?.[`node_modules/${Z}`]?.version;if(typeof i==`string`)return i;let a=n.dependencies?.[Z]?.version;return typeof a==`string`?a:void 0}function npmPackageDeclaresVitePlus(e){if(!e)return!1;for(let t of[`dependencies`,`devDependencies`]){let n=e[t];if(n&&typeof n==`object`&&`vite-plus`in n)return!0}return!1}function fromPnpmLock(e,t){let n;try{n=(0,Y.parse)(e)}catch{return}if(!n||typeof n!=`object`)return;let r=n,i=r.importers;if(i&&typeof i==`object`){let e=t||`.`;return e in i?pnpmImporterVersion(i[e]):void 0}return pnpmImporterVersion(r)||e.match(/^\s*\/?vite-plus@(\d+\.\d+\.\d+[^\s():'"]*)/m)?.[1]}function pnpmImporterVersion(e){if(!e||typeof e!=`object`)return;let t=e;for(let e of[`dependencies`,`devDependencies`,`optionalDependencies`]){let n=t[e];if(n&&typeof n==`object`){let e=n[Z],t=typeof e==`string`?e:e?.version;if(typeof t==`string`){let e=t.replace(/\(.*$/,``).trim();if(o.test(e))return e}}}}function fromYarnLock(e){let t=new Set,n=e.split(/\r?\n/);for(let e=0;ee,info:console.info,debug:()=>{},warning:console.warn}}function readNpmrc(e){try{return a(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return``;throw e}}function authKeyFor(e){return(e.replace(/^\w+:/,``)+`:_authtoken`).toLowerCase()}function analyzeProjectNpmrc(e){let t=new Set,n=new Set,r=new Set;for(let i of e.split(/\r?\n/)){let e=i.trim();if(!e||e.startsWith(`;`)||e.startsWith(`#`))continue;let a=e.indexOf(`=`);if(a<0)continue;let o=e.slice(0,a).trim().toLowerCase(),s=e.slice(a+1).trim();(o===`registry`||o.endsWith(`:registry`))&&(s.includes("${")||t.add(s.endsWith(`/`)?s:s+`/`)),o.startsWith(`//`)&&o.endsWith(`:_authtoken`)&&n.add(o);for(let e of s.matchAll(/\$\{(\w+)\}/g))r.add(e[1])}return{registriesNeedingAuth:[...t].filter(e=>!n.has(authKeyFor(e))),envVarRefs:r}}function readUserConfigLines(e,t){let n=e.HOME||e.USERPROFILE,r=e.NPM_CONFIG_USERCONFIG||e.PNPM_CONFIG_USERCONFIG||n&&u.join(n,`.npmrc`);return(r?readNpmrc(r):``).split(/\r?\n/).filter(e=>!t.has(e.split(`=`)[0].trim().toLowerCase()))}function isReservedAuthVariable(e){return[`GITHUB_TOKEN`,`CI_JOB_TOKEN`,`SYSTEM_ACCESSTOKEN`].includes(e)?!1:/^(?:PATH|HOME|USERPROFILE|TMPDIR|CI)$/i.test(e)||/^(?:SETUP_VP_|RUNNER_|GITHUB_|CI_|SYSTEM_|AGENT_|BUILD_|RELEASE_)/i.test(e)}function writeUserConfig(e,t,n){let r=i(u.join(x(),`setup-vp-npmrc-`)),a=u.join(r,`.npmrc`);l(a,e,{encoding:`utf8`,mode:384});for(let e of[`NPM_CONFIG_USERCONFIG`,`PNPM_CONFIG_USERCONFIG`])t[e]=a,n?.(e,a);return a}function configureAuth(e,t,n,r,i){if(!e){if(!i)return;let{registriesNeedingAuth:e,envVarRefs:t}=analyzeProjectNpmrc(readNpmrc(u.join(i,`.npmrc`))),a;if(n.NODE_AUTH_TOKEN&&e.length>0){let i=readUserConfigLines(n,new Set(e.map(e=>(e.replace(/^\w+:/,``)+`:_authtoken`).toLowerCase())));i.push(...e.map(e=>e.replace(/^\w+:/,``)+":_authToken=${NODE_AUTH_TOKEN}")),a=writeUserConfig(i.join(` +`)){let e=t.trim();if(!e||e.startsWith(`#`))continue;let[n,...r]=e.split(/\s+/);if(n===`nodejs`||n===`node`){for(let e of r)if(isAsdfInstallableVersion(e))return e}}}function isAsdfInstallableVersion(e){return!!e&&e!==`system`&&!e.startsWith(`ref:`)&&!e.startsWith(`path:`)}function parsePackageJson(e){let t;try{t=JSON.parse(e)}catch{throw Error(`Failed to parse package.json: invalid JSON`)}let n=t.devEngines;if(n?.runtime){let e=findNodeRuntime(n.runtime);if(e)return e}let r=t.engines;if(r?.node&&typeof r.node==`string`)return r.node}function findNodeRuntime(e){let t=Array.isArray(e)?e:[e];for(let e of t)if(e?.name===`node`&&typeof e.version==`string`)return e.version}return{resolveNodeVersionFile}}function resolutionContext(e){return{getWorkspaceDir:()=>e,info:console.info,debug:()=>{},warning:console.warn}}const rt=`https://raw.githubusercontent.com/voidzero-dev/vite-plus`,it=`packages/cli`,at=/^0\.0\.0-commit\.([0-9a-f]{40})$/i,ot=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;function pkgPrNewCommitSha(e){return e.match(at)?.[1]}function getInstallScriptUrls(e,t=process.platform){let n=t===`win32`?`install.ps1`:`install.sh`,r=installScriptRef(e);return{pinned:r?[`${rt}/${r}/${it}/${n}`,`https://cdn.jsdelivr.net/gh/voidzero-dev/vite-plus@${r}/${it}/${n}`]:[],latest:[`https://viteplus.dev/${n}`,`${rt}/main/${it}/${n}`]}}function installScriptRef(e){let t=pkgPrNewCommitSha(e);if(t)return t.toLowerCase();if(ot.test(e))return`v${e}`}function readNpmrc(e){try{return a(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return``;throw e}}function authKeyFor(e){return(e.replace(/^\w+:/,``)+`:_authtoken`).toLowerCase()}function analyzeProjectNpmrc(e){let t=new Set,n=new Set,r=new Set;for(let i of e.split(/\r?\n/)){let e=i.trim();if(!e||e.startsWith(`;`)||e.startsWith(`#`))continue;let a=e.indexOf(`=`);if(a<0)continue;let o=e.slice(0,a).trim().toLowerCase(),s=e.slice(a+1).trim();(o===`registry`||o.endsWith(`:registry`))&&(s.includes("${")||t.add(s.endsWith(`/`)?s:s+`/`)),o.startsWith(`//`)&&o.endsWith(`:_authtoken`)&&n.add(o);for(let e of s.matchAll(/\$\{(\w+)\}/g))r.add(e[1])}return{registriesNeedingAuth:[...t].filter(e=>!n.has(authKeyFor(e))),envVarRefs:r}}function readUserConfigLines(e,t){let n=e.HOME||e.USERPROFILE,r=e.NPM_CONFIG_USERCONFIG||e.PNPM_CONFIG_USERCONFIG||n&&u.join(n,`.npmrc`);return(r?readNpmrc(r):``).split(/\r?\n/).filter(e=>!t.has(e.split(`=`)[0].trim().toLowerCase()))}function isReservedAuthVariable(e){return[`GITHUB_TOKEN`,`CI_JOB_TOKEN`,`SYSTEM_ACCESSTOKEN`].includes(e)?!1:/^(?:PATH|HOME|USERPROFILE|TMPDIR|CI)$/i.test(e)||/^(?:SETUP_VP_|RUNNER_|GITHUB_|CI_|SYSTEM_|AGENT_|BUILD_|RELEASE_)/i.test(e)}function writeUserConfig(e,t,n){let r=i(u.join(x(),`setup-vp-npmrc-`)),a=u.join(r,`.npmrc`);l(a,e,{encoding:`utf8`,mode:384});for(let e of[`NPM_CONFIG_USERCONFIG`,`PNPM_CONFIG_USERCONFIG`])t[e]=a,n?.(e,a);return a}function configureAuth(e,t,n,r,i){if(!e){if(!i)return;let{registriesNeedingAuth:e,envVarRefs:t}=analyzeProjectNpmrc(readNpmrc(u.join(i,`.npmrc`))),a;if(n.NODE_AUTH_TOKEN&&e.length>0){let i=readUserConfigLines(n,new Set(e.map(e=>(e.replace(/^\w+:/,``)+`:_authtoken`).toLowerCase())));i.push(...e.map(e=>e.replace(/^\w+:/,``)+":_authToken=${NODE_AUTH_TOKEN}")),a=writeUserConfig(i.join(` `)+` `,n,r),t.add(`NODE_AUTH_TOKEN`)}for(let e of t)!isReservedAuthVariable(e)&&n[e]&&r?.(e,n[e]);return a}let a;try{a=new URL(e)}catch{throw Error(`Invalid registry-url: "${e}". Must be a valid URL.`)}let o=a.href.endsWith(`/`)?a.href:`${a.href}/`,s=``;t&&(s=`${(t.startsWith(`@`)?t:`@${t}`).toLowerCase()}:`);let c=o.replace(/^\w+:/,``).toLowerCase(),l=readUserConfigLines(n,new Set([`${s}registry`,`${c}:_authtoken`]));l.push(`${c}:_authToken=\${NODE_AUTH_TOKEN}`,`${s}registry=${o}`);let d=writeUserConfig(l.filter(Boolean).join(` `)+` -`,n,r);return n.NODE_AUTH_TOKEN=n.NODE_AUTH_TOKEN||`XXXXX-XXXXX-XXXXX-XXXXX`,r?.(`NODE_AUTH_TOKEN`,n.NODE_AUTH_TOKEN),d}const Q=`v1.15.1`,rt=`https://github.com/SocketDev/sfw-free/releases/download/${Q}`;function isMuslLinux(){if(process.platform!==`linux`)return!1;try{let e=process.report?.getReport();if(e?.header&&!e.header.glibcVersionRuntime)return!0}catch{}return n(`/etc/alpine-release`)}function getSfwAssetName(e,t,n){if(e===`darwin`){if(t===`arm64`)return`sfw-free-macos-arm64`;if(t===`x64`)return`sfw-free-macos-x86_64`}else if(e===`linux`){if(t===`arm64`)return n?`sfw-free-musl-linux-arm64`:`sfw-free-linux-arm64`;if(t===`x64`)return n?`sfw-free-musl-linux-x86_64`:`sfw-free-linux-x86_64`}else if(e===`win32`){if(t===`arm64`)return`sfw-free-windows-arm64.exe`;if(t===`x64`)return`sfw-free-windows-x86_64.exe`}throw Error(`Unsupported platform/arch for sfw: ${e}/${t}${e===`linux`?` (${n?`musl`:`glibc`})`:``}`)}function downloadFileWithShell(e,t,n){let r=Math.max(1,Math.ceil(n/1e3)),i=commandPath(`curl`);if(i){let n=y(i,[`-fsSL`,`--connect-timeout`,`5`,`--max-time`,String(r),e,`-o`,t],{stdio:`ignore`});if(n.status===0)return;throw n.error||Error(`curl failed while downloading ${e}`)}let a=commandPath(`wget`);if(a){let n=y(a,[`-q`,`-T`,String(r),`-t`,`2`,`-O`,t,e],{stdio:`ignore`});if(n.status===0)return;throw n.error||Error(`wget failed while downloading ${e}`)}throw Error(`curl or wget is required to download sfw`)}function downloadFile(e,n,r=0,i=6e4,a){return r>5?Promise.reject(Error(`too many redirects while downloading ${e}`)):a?new Promise((o,s)=>{let c=!1,finish=e=>{c||(c=!0,clearTimeout(u),e?s(e):o())},l=a(e,o=>{let s=o.statusCode??0,c=o.headers.location;if(s>=300&&s<400&&c){o.resume(),downloadFile(new URL(c,e).toString(),n,r+1,i,a).then(()=>finish(),finish);return}if(s!==200){o.resume(),finish(Error(`download failed with HTTP ${s}: ${e}`));return}let l=t(n);o.pipe(l),l.on(`finish`,()=>l.close(()=>finish())),l.on(`error`,finish)}),u=setTimeout(()=>{l.destroy(Error(`download timed out after ${i}ms: ${e}`))},i);l.on(`error`,finish)}):(downloadFileWithShell(e,n,i),Promise.resolve())}async function setupSfw(e,t={}){let n=t.env??process.env,r=t.sfwEnabled??n.SETUP_VP_SFW===`true`,i=t.platform??process.platform,a=t.arch??process.arch,o=t.isMusl??isMuslLinux(),s=t.download??downloadFile;if(!r)return`vp`;if(e.length===0)return console.log(`setup-vp: sfw was requested but run-install is disabled; sfw will not be invoked.`),`vp`;let c=commandPath(`sfw`);if(c)return console.log(`setup-vp: using existing sfw on PATH: ${c}`),`sfw`;let l;try{l=getSfwAssetName(i,a,o)}catch{return console.error(`setup-vp: sfw has no published binary for this runner's platform/architecture (process.platform=${i}, process.arch=${a}, musl=${o}) and none was found on PATH; falling back to plain vp install.`),`vp`}let d=t.cacheDirectory||n.SETUP_VP_SFW_CACHE_DIR,f=d?u.join(d,Q,l):await w(u.join(x(),`setup-vp-sfw-`));await C(f,{recursive:!0});let p=u.join(f,i===`win32`?`sfw.exe`:`sfw`),m=`${rt}/${l}`;function activate(){return n.PATH=`${f}${i===`win32`?`;`:`:`}${n.PATH||``}`,t.exportVariable?.(`PATH`,n.PATH),`sfw`}if(await ee(p).then(e=>e.isFile()&&e.size>0,()=>!1))return console.log(`setup-vp: using cached sfw ${Q}: ${p}`),activate();for(let e=1;e<=2;e+=1){let t=await w(u.join(f,`.download-`)),n=u.join(t,`sfw`);try{if(console.log(`setup-vp: installing sfw ${Q} from ${m}`),await s(m,n),(await ee(n)).size===0)throw Error(`Downloaded sfw binary is empty`);return await S(n,493),await T(n,p),activate()}catch(t){if(e===2)throw t;await new Promise(e=>setTimeout(e,2e3))}finally{await E(t,{recursive:!0,force:!0})}}throw Error(`failed to install sfw after retrying`)}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function validateRunInstallEntry(e){if(!isRecord(e))throw Error(`run-install entries must be objects`);for(let t of Object.keys(e))if(t!==`cwd`&&t!==`args`)throw Error(`unsupported run-install key: ${t}`);let t={};if(e.cwd!==void 0){if(typeof e.cwd!=`string`)throw Error(`run-install.cwd must be a string`);t.cwd=e.cwd}if(e.args!==void 0){if(!Array.isArray(e.args)||e.args.some(e=>typeof e!=`string`))throw Error(`run-install.args must be an array of strings`);t.args=e.args}return t}function validateRunInstallInput(e){return e===null||typeof e==`boolean`?e:Array.isArray(e)?e.map(validateRunInstallEntry):validateRunInstallEntry(e)}function parseRunInstall(e){let t=validateRunInstallInput((0,Y.parse)(e)??null);return t?t===!0?[{}]:Array.isArray(t)?t:[t]:[]}function isSfwVpNotFoundFlake(e,t){return/Command 'vp' not found in PATH/.test(e+` +`,n,r);return n.NODE_AUTH_TOKEN=n.NODE_AUTH_TOKEN||`XXXXX-XXXXX-XXXXX-XXXXX`,r?.(`NODE_AUTH_TOKEN`,n.NODE_AUTH_TOKEN),d}function resolveSfwEnabled(e,t,n){return e?!pkgPrNewCommitSha(t)||(n(`sfw was requested but is automatically disabled for Vite+ preview build ${t}; Socket Firewall Free will not be used.`),!1):!1}const Q=`v1.15.1`,st=`https://github.com/SocketDev/sfw-free/releases/download/${Q}`;function isMuslLinux(){if(process.platform!==`linux`)return!1;try{let e=process.report?.getReport();if(e?.header&&!e.header.glibcVersionRuntime)return!0}catch{}return n(`/etc/alpine-release`)}function getSfwAssetName(e,t,n){if(e===`darwin`){if(t===`arm64`)return`sfw-free-macos-arm64`;if(t===`x64`)return`sfw-free-macos-x86_64`}else if(e===`linux`){if(t===`arm64`)return n?`sfw-free-musl-linux-arm64`:`sfw-free-linux-arm64`;if(t===`x64`)return n?`sfw-free-musl-linux-x86_64`:`sfw-free-linux-x86_64`}else if(e===`win32`){if(t===`arm64`)return`sfw-free-windows-arm64.exe`;if(t===`x64`)return`sfw-free-windows-x86_64.exe`}throw Error(`Unsupported platform/arch for sfw: ${e}/${t}${e===`linux`?` (${n?`musl`:`glibc`})`:``}`)}function downloadFileWithShell(e,t,n){let r=Math.max(1,Math.ceil(n/1e3)),i=commandPath(`curl`);if(i){let n=y(i,[`-fsSL`,`--connect-timeout`,`5`,`--max-time`,String(r),e,`-o`,t],{stdio:`ignore`});if(n.status===0)return;throw n.error||Error(`curl failed while downloading ${e}`)}let a=commandPath(`wget`);if(a){let n=y(a,[`-q`,`-T`,String(r),`-t`,`2`,`-O`,t,e],{stdio:`ignore`});if(n.status===0)return;throw n.error||Error(`wget failed while downloading ${e}`)}throw Error(`curl or wget is required to download sfw`)}function downloadFile(e,n,r=0,i=6e4,a){return r>5?Promise.reject(Error(`too many redirects while downloading ${e}`)):a?new Promise((o,s)=>{let c=!1,finish=e=>{c||(c=!0,clearTimeout(u),e?s(e):o())},l=a(e,o=>{let s=o.statusCode??0,c=o.headers.location;if(s>=300&&s<400&&c){o.resume(),downloadFile(new URL(c,e).toString(),n,r+1,i,a).then(()=>finish(),finish);return}if(s!==200){o.resume(),finish(Error(`download failed with HTTP ${s}: ${e}`));return}let l=t(n);o.pipe(l),l.on(`finish`,()=>l.close(()=>finish())),l.on(`error`,finish)}),u=setTimeout(()=>{l.destroy(Error(`download timed out after ${i}ms: ${e}`))},i);l.on(`error`,finish)}):(downloadFileWithShell(e,n,i),Promise.resolve())}async function setupSfw(e,t={}){let n=t.env??process.env,r=t.sfwEnabled??n.SETUP_VP_SFW===`true`,i=t.platform??process.platform,a=t.arch??process.arch,o=t.isMusl??isMuslLinux(),s=t.download??downloadFile;if(!resolveSfwEnabled(r,t.vitePlusVersion??``,t.logWarning??console.warn))return`vp`;if(e.length===0)return console.log(`setup-vp: sfw was requested but run-install is disabled; sfw will not be invoked.`),`vp`;let c=commandPath(`sfw`);if(c)return console.log(`setup-vp: using existing sfw on PATH: ${c}`),`sfw`;let l;try{l=getSfwAssetName(i,a,o)}catch{return console.error(`setup-vp: sfw has no published binary for this runner's platform/architecture (process.platform=${i}, process.arch=${a}, musl=${o}) and none was found on PATH; falling back to plain vp install.`),`vp`}let d=t.cacheDirectory||n.SETUP_VP_SFW_CACHE_DIR,f=d?u.join(d,Q,l):await w(u.join(x(),`setup-vp-sfw-`));await C(f,{recursive:!0});let p=u.join(f,i===`win32`?`sfw.exe`:`sfw`),m=`${st}/${l}`;function activate(){return n.PATH=`${f}${i===`win32`?`;`:`:`}${n.PATH||``}`,t.exportVariable?.(`PATH`,n.PATH),`sfw`}if(await ee(p).then(e=>e.isFile()&&e.size>0,()=>!1))return console.log(`setup-vp: using cached sfw ${Q}: ${p}`),activate();for(let e=1;e<=2;e+=1){let t=await w(u.join(f,`.download-`)),n=u.join(t,`sfw`);try{if(console.log(`setup-vp: installing sfw ${Q} from ${m}`),await s(m,n),(await ee(n)).size===0)throw Error(`Downloaded sfw binary is empty`);return await S(n,493),await T(n,p),activate()}catch(t){if(e===2)throw t;await new Promise(e=>setTimeout(e,2e3))}finally{await E(t,{recursive:!0,force:!0})}}throw Error(`failed to install sfw after retrying`)}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function validateRunInstallEntry(e){if(!isRecord(e))throw Error(`run-install entries must be objects`);for(let t of Object.keys(e))if(t!==`cwd`&&t!==`args`)throw Error(`unsupported run-install key: ${t}`);let t={};if(e.cwd!==void 0){if(typeof e.cwd!=`string`)throw Error(`run-install.cwd must be a string`);t.cwd=e.cwd}if(e.args!==void 0){if(!Array.isArray(e.args)||e.args.some(e=>typeof e!=`string`))throw Error(`run-install.args must be an array of strings`);t.args=e.args}return t}function validateRunInstallInput(e){return e===null||typeof e==`boolean`?e:Array.isArray(e)?e.map(validateRunInstallEntry):validateRunInstallEntry(e)}function parseRunInstall(e){let t=validateRunInstallInput((0,Y.parse)(e)??null);return t?t===!0?[{}]:Array.isArray(t)?t:[t]:[]}function isSfwVpNotFoundFlake(e,t){return/Command 'vp' not found in PATH/.test(e+` `+t)}async function runInstall(e,t,n,r=process.env,i={}){let a={...r};delete a.SETUP_VP_ENV_FILE;let o=i.execute??runWithOutput,s=[];for(let r of e){let e=r.cwd?u.resolve(t,r.cwd):t,c=[`install`,...r.args||[]],l=n===`sfw`?[`vp`,...c]:c,d=`${n} ${l.join(` `)} (cwd: ${e})`;console.log(`setup-vp: running ${d}`);try{let t=await o(n,l,{cwd:e,env:a});if(t.exitCode!==0&&n===`sfw`&&isSfwVpNotFoundFlake(t.stdout,t.stderr)){let r=(i.platform??process.platform)===`win32`;if(console.warn(r?`setup-vp: sfw could not resolve vp; warming the PowerShell command cache and retrying once.`:`setup-vp: sfw could not resolve vp; retrying once.`),r)try{await o(`powershell.exe`,[`-NoProfile`,`-Command`,`Get-Command vp`],{cwd:e,env:a})}catch{}t=await o(n,l,{cwd:e,env:a})}t.exitCode!==0&&s.push(`${d} exited with code ${t.exitCode}\n${t.stderr.trim()||t.stdout.trim()}`)}catch(e){s.push(`${d}: ${String(e)}`)}}if(s.length)throw Error(s.join(` `))}function escapeLoggingCommandData(e){return e.replaceAll(`%`,`%AZP25`).replaceAll(`\r`,`%0D`).replaceAll(` -`,`%0A`).replaceAll(`;`,`%3B`).replaceAll(`]`,`%5D`)}function prependPath(e){process.stdout.write(`##vso[task.prependpath]${escapeLoggingCommandData(e)}\n`)}function setVariable(e,t,n={}){let r=[`variable=${e}`];n.isOutput&&r.push(`isOutput=true`),n.isReadonly&&r.push(`isReadonly=true`),n.isSecret&&r.push(`issecret=true`),process.stdout.write(`##vso[task.setvariable ${r.join(`;`)}]${escapeLoggingCommandData(t)}\n`)}function logWarning(e){process.stdout.write(`##vso[task.logissue type=warning]${escapeLoggingCommandData(e)}\n`)}function logInfo(e){console.log(e)}const it=`https://raw.githubusercontent.com/voidzero-dev/vite-plus`,at=`packages/cli`,ot=/^0\.0\.0-commit\.([0-9a-f]{40})$/i,st=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;function pkgPrNewCommitSha(e){return e.match(ot)?.[1]}function getInstallScriptUrls(e,t=process.platform){let n=t===`win32`?`install.ps1`:`install.sh`,r=installScriptRef(e);return{pinned:r?[`${it}/${r}/${at}/${n}`,`https://cdn.jsdelivr.net/gh/voidzero-dev/vite-plus@${r}/${at}/${n}`]:[],latest:[`https://viteplus.dev/${n}`,`${it}/main/${at}/${n}`]}}function installScriptRef(e){let t=pkgPrNewCommitSha(e);if(t)return t.toLowerCase();if(st.test(e))return`v${e}`}const $=`SETUP_VP_DIRS_FILE`,ct=/^v?(\d+)\.(\d+)\.\d+(?:-[0-9A-Za-z.-]+)?$/;function supportsVitePlusDirs(e){if(pkgPrNewCommitSha(e))return!0;let t=e.match(ct);if(!t)return!0;let n=Number(t[1]),r=Number(t[2]);return n>0||r>=3}function createVitePlusDirsFile(){return m(x(),`setup-vp-dirs-${ne()}.txt`)}function removeVitePlusDirsFile(e){s(e,{force:!0})}function readVitePlusProbe(e){try{return a(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return;throw e}}function resolveVitePlusBinDir(e,t,n){if(!t){if(!supportsVitePlusDirs(e))return n;throw Error(`Vite+ was installed successfully, but setup-vp could not resolve its VpDirs.`)}let r=readVitePlusProbe(t),i=r===void 0?void 0:parseVitePlusDirs(r);if(i)return i.bin;if(!(pkgPrNewCommitSha(e)!==void 0||ct.test(e))&&r!==void 0){let e=parseInstalledVpVersion(r);if(e!==`unknown`&&!supportsVitePlusDirs(e))return n}throw Error(`Vite+ was installed successfully, but setup-vp could not resolve its VpDirs.`)}function parseVitePlusDirs(e){let t=new Map;for(let n of e.split(/\r?\n/)){let e=n.indexOf(` `);if(e<1)continue;let r=n.slice(0,e).replace(/^\uFEFF/,``),i=n.slice(e+1).trim();i&&t.set(r,i)}let n=t.get(`data`),r=t.get(`bin`),i=t.get(`cache`),a=t.get(`config`),o=t.get(`state`);if(n&&r&&i&&a&&o)return{data:n,bin:r,cache:i,config:a,state:o}}function getInstallScriptCommand(e,t=process.platform,n=!0){if(t===`win32`)return n?{command:`pwsh`,args:[`-Command`,` +`,`%0A`).replaceAll(`;`,`%3B`).replaceAll(`]`,`%5D`)}function prependPath(e){process.stdout.write(`##vso[task.prependpath]${escapeLoggingCommandData(e)}\n`)}function setVariable(e,t,n={}){let r=[`variable=${e}`];n.isOutput&&r.push(`isOutput=true`),n.isReadonly&&r.push(`isReadonly=true`),n.isSecret&&r.push(`issecret=true`),process.stdout.write(`##vso[task.setvariable ${r.join(`;`)}]${escapeLoggingCommandData(t)}\n`)}function logWarning(e){process.stdout.write(`##vso[task.logissue type=warning]${escapeLoggingCommandData(e)}\n`)}function logInfo(e){console.log(e)}const $=`SETUP_VP_DIRS_FILE`,ct=/^v?(\d+)\.(\d+)\.\d+(?:-[0-9A-Za-z.-]+)?$/;function supportsVitePlusDirs(e){if(pkgPrNewCommitSha(e))return!0;let t=e.match(ct);if(!t)return!0;let n=Number(t[1]),r=Number(t[2]);return n>0||r>=3}function createVitePlusDirsFile(){return m(x(),`setup-vp-dirs-${ne()}.txt`)}function removeVitePlusDirsFile(e){s(e,{force:!0})}function readVitePlusProbe(e){try{return a(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return;throw e}}function resolveVitePlusBinDir(e,t,n){if(!t){if(!supportsVitePlusDirs(e))return n;throw Error(`Vite+ was installed successfully, but setup-vp could not resolve its VpDirs.`)}let r=readVitePlusProbe(t),i=r===void 0?void 0:parseVitePlusDirs(r);if(i)return i.bin;if(!(pkgPrNewCommitSha(e)!==void 0||ct.test(e))&&r!==void 0){let e=parseInstalledVpVersion(r);if(e!==`unknown`&&!supportsVitePlusDirs(e))return n}throw Error(`Vite+ was installed successfully, but setup-vp could not resolve its VpDirs.`)}function parseVitePlusDirs(e){let t=new Map;for(let n of e.split(/\r?\n/)){let e=n.indexOf(` `);if(e<1)continue;let r=n.slice(0,e).replace(/^\uFEFF/,``),i=n.slice(e+1).trim();i&&t.set(r,i)}let n=t.get(`data`),r=t.get(`bin`),i=t.get(`cache`),a=t.get(`config`),o=t.get(`state`);if(n&&r&&i&&a&&o)return{data:n,bin:r,cache:i,config:a,state:o}}function getInstallScriptCommand(e,t=process.platform,n=!0){if(t===`win32`)return n?{command:`pwsh`,args:[`-Command`,` $dirsFile = $env:${$} Set-Content -LiteralPath $dirsFile -Value '' -NoNewline -Encoding UTF8 . ([scriptblock]::Create((irm -TimeoutSec 15 ${e}))) @@ -165,4 +165,4 @@ fi set +u set -o pipefail ${r} | bash -`.trim()]}}const lt=2e3;function getVitePlusHome(e=process.platform,t=process.env){let n=e===`win32`?t.USERPROFILE||b():t.HOME||b();return m(n,`.vite-plus`)}function runInstallCommand(e,t,n=process.platform){let{command:r,args:i}=getInstallScriptCommand(e,n,t.VP_VPDIRS_AWARE===`1`),a={env:{...process.env,...t},stdio:`inherit`},o=y(r,i,a);if(n===`win32`&&o.error?.code===`ENOENT`&&(o=y(`powershell.exe`,i,a)),o.error)throw o.error;return o.status??1}async function installVitePlus(e,t={}){let n=t.platform??process.platform,r=t.env??process.env,i=t.prependPath,a=t.sleep??te,o=t.runInstall??runInstallCommand,s=t.logWarningFn??console.warn,c={...Object.fromEntries(Object.entries(r).filter(e=>e[1]!==void 0)),VP_VERSION:e,VITE_PLUS_VERSION:e},l=supportsVitePlusDirs(e)?createVitePlusDirsFile():void 0;l?(c.VP_VPDIRS_AWARE=`1`,c[$]=l):(delete c.VP_VPDIRS_AWARE,delete c[$]);let u=pkgPrNewCommitSha(e);u&&(c.VP_PR_VERSION=u);let{pinned:d,latest:f}=getInstallScriptUrls(e,n),p=d.length+f.length,h=2*p,g=``,_=0;async function tryUrls(e){for(let t=0;t<2;t+=1)for(let t of e){_+=1;try{let e=o(t,c,n);if(e===0)return!0;g=`exit code ${e}`}catch(e){g=e instanceof Error?e.message:String(e)}_0){if(await tryUrls(d)){ensureBinInPath();return}s(`setup-vp: could not fetch the install script pinned to Vite+ ${e}. Falling back to the latest install script. The latest script may not be compatible with ${e}.`)}if(await tryUrls(f)){ensureBinInPath();return}throw Error(`Failed to install Vite+ after ${h} attempts across ${p} URL(s): ${g}`)}finally{l&&removeVitePlusDirsFile(l)}}function parseBoolean(e){return e?.toLowerCase()===`true`}function parseAzureInputs(e){return{version:e.SETUP_VP_VERSION||``,versionFile:e.SETUP_VP_VERSION_FILE||void 0,nodeVersion:e.SETUP_VP_NODE_VERSION||void 0,nodeVersionFile:e.SETUP_VP_NODE_VERSION_FILE||void 0,workingDirectory:e.SETUP_VP_WORKING_DIRECTORY||`.`,runInstall:e.SETUP_VP_RUN_INSTALL??`true`,sfw:parseBoolean(e.SETUP_VP_SFW),nodeManager:parseNodeManager(e.SETUP_VP_NODE_MANAGER),packageManager:parsePackageManager(e.SETUP_VP_PACKAGE_MANAGER),registryUrl:e.SETUP_VP_REGISTRY_URL||``,scope:e.SETUP_VP_SCOPE||``,cache:parseBoolean(e.SETUP_VP_CACHE),cacheDependencyPath:e.SETUP_VP_CACHE_DEPENDENCY_PATH||``,workspaceRoot:e.SYSTEM_DEFAULTWORKINGDIRECTORY||process.cwd()}}function resolveProjectDirFromInputs(e){return resolveProjectDirectory({workingDirectory:e.workingDirectory,workspaceRoot:e.workspaceRoot})}const ut={installVitePlus,prepareCacheMetadata,configureAuth,setupSfw,parseRunInstall,runInstall,getCommandOutput,run,parseInstalledVpVersion,prependPath,setVariable,logWarning,logInfo};function fail(e){console.error(`setup-vp: ${e}`),process.exit(1)}async function runPrepare(e=process.env,t=ut){let n=parseAzureInputs(e),i=resolveProjectDirFromInputs(n);if(n.nodeManager===!1&&(n.nodeVersion||n.nodeVersionFile))throw Error(`node-version and node-version-file cannot be used with node-manager: false`);let a={...resolutionContext(n.workspaceRoot),info:t.logInfo,warning:t.logWarning},o=createVersionResolver(a).resolveVitePlusVersion(n,i),s=n.nodeVersion||(n.nodeVersionFile?createNodeVersionResolver(a).resolveNodeVersionFile(n.nodeVersionFile,i):void 0);t.setVariable(`SETUP_VP_CACHE_HIT`,`false`),t.setVariable(`SETUP_VP_CACHE_READY`,`false`),t.setVariable(`SETUP_VP_SFW_READY`,`false`),t.setVariable(`SETUP_VP_BOOTSTRAP_NODE`,process.execPath),await t.installVitePlus(o,{env:e,prependPath:e=>t.prependPath(e),logWarningFn:t.logWarning});let c=(n.nodeManager===!1||n.packageManager!==void 0)&&t.getCommandOutput(`vp`,[`--version`])||``,l=packageManagerArgs(n.packageManager,c);n.nodeManager===!1?t.run(`vp`,nodeManagerOffArgs(c)):s&&t.run(`vp`,[`env`,`use`,s],{cwd:i});for(let e of l)t.run(`vp`,e);let d=u.resolve(process.argv[1]||``);if(t.setVariable(`SETUP_VP_RUNTIME_PATH`,d),n.sfw&&t.parseRunInstall(n.runInstall).length>0)try{let i=getSfwAssetName(process.platform,process.arch,isMuslLinux()),a=u.join(e.PIPELINE_WORKSPACE||n.workspaceRoot,`.setup-vp-sfw`);r(a,{recursive:!0}),t.setVariable(`SETUP_VP_SFW_CACHE_DIR`,a),t.setVariable(`SETUP_VP_SFW_CACHE_KEY`,`${Q}-${i}`),t.setVariable(`SETUP_VP_SFW_READY`,`true`)}catch(e){t.logWarning(String(e))}if(!n.cache)return;let f=t.prepareCacheMetadata({projectDir:i,cacheDependencyPath:n.cacheDependencyPath||void 0,logWarning:t.logWarning});if(!f.ready){t.setVariable(`SETUP_VP_CACHE_READY`,`false`);return}t.setVariable(`SETUP_VP_CACHE_READY`,`true`),f.cachePath&&t.setVariable(`SETUP_VP_CACHE_PATH`,f.cachePath),f.lockFile&&t.setVariable(`SETUP_VP_LOCK_FILE`,f.lockFile),f.lockType&&t.setVariable(`SETUP_VP_LOCK_TYPE`,f.lockType)}async function runFinalize(e=process.env,t=ut){let n=parseAzureInputs(e),r=resolveProjectDirFromInputs(n),i=analyzeProjectNpmrc(readNpmrc(u.join(r,`.npmrc`))).envVarRefs;i.add(`NODE_AUTH_TOKEN`);for(let t of i)!isReservedAuthVariable(t)&&/^\$\([^)]+\)$/.test(e[t]||``)&&delete e[t];t.configureAuth(n.registryUrl,n.scope,e,(e,n)=>{e!==`NODE_AUTH_TOKEN`&&n!==void 0&&t.setVariable(e,n,{isSecret:e!==`NPM_CONFIG_USERCONFIG`&&e!==`PNPM_CONFIG_USERCONFIG`})},r);let a=t.parseRunInstall(n.runInstall),o=await t.setupSfw(a,{env:e,sfwEnabled:n.sfw,exportVariable:(e,n)=>{n!==void 0&&(e===`PATH`?t.prependPath(n.split(u.delimiter)[0]):t.setVariable(e,n))}});a.length>0&&await t.runInstall(a,r,o,e);let s=t.getCommandOutput(`vp`,[`--version`],{cwd:r});if(!s)throw Error(`Failed to verify Vite+ installation: vp --version failed or returned no output.`);t.logInfo(s);let c=t.parseInstalledVpVersion(s);t.setVariable(`SETUP_VP_INSTALLED_VERSION`,c),t.setVariable(`version`,c,{isOutput:!0}),t.setVariable(`cacheHit`,String(e.SETUP_VP_CACHE_HIT===`true`),{isOutput:!0})}async function main(e){if(e===`prepare`){await runPrepare();return}if(e===`finalize`){await runFinalize();return}fail(`invalid phase "${String(e)}"; expected "prepare" or "finalize"`)}function isEntrypoint(e=process.argv[1],t=import.meta.url){return!!(e&&t===_(u.resolve(e)).href)}if(isEntrypoint()){let e=process.argv[2];e||fail(`missing phase argument; expected "prepare" or "finalize"`);try{await main(e)}catch(e){fail(e instanceof Error?e.message:String(e))}}export{isEntrypoint,main,runFinalize,runPrepare}; \ No newline at end of file +`.trim()]}}const lt=2e3;function getVitePlusHome(e=process.platform,t=process.env){let n=e===`win32`?t.USERPROFILE||b():t.HOME||b();return m(n,`.vite-plus`)}function runInstallCommand(e,t,n=process.platform){let{command:r,args:i}=getInstallScriptCommand(e,n,t.VP_VPDIRS_AWARE===`1`),a={env:{...process.env,...t},stdio:`inherit`},o=y(r,i,a);if(n===`win32`&&o.error?.code===`ENOENT`&&(o=y(`powershell.exe`,i,a)),o.error)throw o.error;return o.status??1}async function installVitePlus(e,t={}){let n=t.platform??process.platform,r=t.env??process.env,i=t.prependPath,a=t.sleep??te,o=t.runInstall??runInstallCommand,s=t.logWarningFn??console.warn,c={...Object.fromEntries(Object.entries(r).filter(e=>e[1]!==void 0)),VP_VERSION:e,VITE_PLUS_VERSION:e},l=supportsVitePlusDirs(e)?createVitePlusDirsFile():void 0;l?(c.VP_VPDIRS_AWARE=`1`,c[$]=l):(delete c.VP_VPDIRS_AWARE,delete c[$]);let u=pkgPrNewCommitSha(e);u&&(c.VP_PR_VERSION=u);let{pinned:d,latest:f}=getInstallScriptUrls(e,n),p=d.length+f.length,h=2*p,g=``,_=0;async function tryUrls(e){for(let t=0;t<2;t+=1)for(let t of e){_+=1;try{let e=o(t,c,n);if(e===0)return!0;g=`exit code ${e}`}catch(e){g=e instanceof Error?e.message:String(e)}_0){if(await tryUrls(d)){ensureBinInPath();return}s(`setup-vp: could not fetch the install script pinned to Vite+ ${e}. Falling back to the latest install script. The latest script may not be compatible with ${e}.`)}if(await tryUrls(f)){ensureBinInPath();return}throw Error(`Failed to install Vite+ after ${h} attempts across ${p} URL(s): ${g}`)}finally{l&&removeVitePlusDirsFile(l)}}function parseBoolean(e){return e?.toLowerCase()===`true`}function parseAzureInputs(e){return{version:e.SETUP_VP_VERSION||``,versionFile:e.SETUP_VP_VERSION_FILE||void 0,nodeVersion:e.SETUP_VP_NODE_VERSION||void 0,nodeVersionFile:e.SETUP_VP_NODE_VERSION_FILE||void 0,workingDirectory:e.SETUP_VP_WORKING_DIRECTORY||`.`,runInstall:e.SETUP_VP_RUN_INSTALL??`true`,sfw:parseBoolean(e.SETUP_VP_SFW),nodeManager:parseNodeManager(e.SETUP_VP_NODE_MANAGER),packageManager:parsePackageManager(e.SETUP_VP_PACKAGE_MANAGER),registryUrl:e.SETUP_VP_REGISTRY_URL||``,scope:e.SETUP_VP_SCOPE||``,cache:parseBoolean(e.SETUP_VP_CACHE),cacheDependencyPath:e.SETUP_VP_CACHE_DEPENDENCY_PATH||``,workspaceRoot:e.SYSTEM_DEFAULTWORKINGDIRECTORY||process.cwd()}}function resolveProjectDirFromInputs(e){return resolveProjectDirectory({workingDirectory:e.workingDirectory,workspaceRoot:e.workspaceRoot})}const ut={installVitePlus,prepareCacheMetadata,configureAuth,setupSfw,parseRunInstall,runInstall,getCommandOutput,run,parseInstalledVpVersion,prependPath,setVariable,logWarning,logInfo};function fail(e){console.error(`setup-vp: ${e}`),process.exit(1)}async function runPrepare(e=process.env,t=ut){let n=parseAzureInputs(e),i=resolveProjectDirFromInputs(n);if(n.nodeManager===!1&&(n.nodeVersion||n.nodeVersionFile))throw Error(`node-version and node-version-file cannot be used with node-manager: false`);let a={...resolutionContext(n.workspaceRoot),info:t.logInfo,warning:t.logWarning},o=createVersionResolver(a).resolveVitePlusVersion(n,i),s=n.nodeVersion||(n.nodeVersionFile?createNodeVersionResolver(a).resolveNodeVersionFile(n.nodeVersionFile,i):void 0);t.setVariable(`SETUP_VP_CACHE_HIT`,`false`),t.setVariable(`SETUP_VP_CACHE_READY`,`false`),t.setVariable(`SETUP_VP_SFW_READY`,`false`),t.setVariable(`SETUP_VP_BOOTSTRAP_NODE`,process.execPath),await t.installVitePlus(o,{env:e,prependPath:e=>t.prependPath(e),logWarningFn:t.logWarning}),t.setVariable(`SETUP_VP_RESOLVED_VERSION`,o);let c=(n.nodeManager===!1||n.packageManager!==void 0)&&t.getCommandOutput(`vp`,[`--version`])||``,l=packageManagerArgs(n.packageManager,c);n.nodeManager===!1?t.run(`vp`,nodeManagerOffArgs(c)):s&&t.run(`vp`,[`env`,`use`,s],{cwd:i});for(let e of l)t.run(`vp`,e);let d=u.resolve(process.argv[1]||``);if(t.setVariable(`SETUP_VP_RUNTIME_PATH`,d),n.sfw&&!pkgPrNewCommitSha(o)&&t.parseRunInstall(n.runInstall).length>0)try{let i=getSfwAssetName(process.platform,process.arch,isMuslLinux()),a=u.join(e.PIPELINE_WORKSPACE||n.workspaceRoot,`.setup-vp-sfw`);r(a,{recursive:!0}),t.setVariable(`SETUP_VP_SFW_CACHE_DIR`,a),t.setVariable(`SETUP_VP_SFW_CACHE_KEY`,`${Q}-${i}`),t.setVariable(`SETUP_VP_SFW_READY`,`true`)}catch(e){t.logWarning(String(e))}if(!n.cache)return;let f=t.prepareCacheMetadata({projectDir:i,cacheDependencyPath:n.cacheDependencyPath||void 0,logWarning:t.logWarning});if(!f.ready){t.setVariable(`SETUP_VP_CACHE_READY`,`false`);return}t.setVariable(`SETUP_VP_CACHE_READY`,`true`),f.cachePath&&t.setVariable(`SETUP_VP_CACHE_PATH`,f.cachePath),f.lockFile&&t.setVariable(`SETUP_VP_LOCK_FILE`,f.lockFile),f.lockType&&t.setVariable(`SETUP_VP_LOCK_TYPE`,f.lockType)}async function runFinalize(e=process.env,t=ut){let n=parseAzureInputs(e),r=resolveProjectDirFromInputs(n),i=analyzeProjectNpmrc(readNpmrc(u.join(r,`.npmrc`))).envVarRefs;i.add(`NODE_AUTH_TOKEN`);for(let t of i)!isReservedAuthVariable(t)&&/^\$\([^)]+\)$/.test(e[t]||``)&&delete e[t];t.configureAuth(n.registryUrl,n.scope,e,(e,n)=>{e!==`NODE_AUTH_TOKEN`&&n!==void 0&&t.setVariable(e,n,{isSecret:e!==`NPM_CONFIG_USERCONFIG`&&e!==`PNPM_CONFIG_USERCONFIG`})},r);let a=t.parseRunInstall(n.runInstall),o=await t.setupSfw(a,{env:e,sfwEnabled:n.sfw,vitePlusVersion:e.SETUP_VP_RESOLVED_VERSION||n.version,logWarning:t.logWarning,exportVariable:(e,n)=>{n!==void 0&&(e===`PATH`?t.prependPath(n.split(u.delimiter)[0]):t.setVariable(e,n))}});a.length>0&&await t.runInstall(a,r,o,e);let s=t.getCommandOutput(`vp`,[`--version`],{cwd:r});if(!s)throw Error(`Failed to verify Vite+ installation: vp --version failed or returned no output.`);t.logInfo(s);let c=t.parseInstalledVpVersion(s);t.setVariable(`SETUP_VP_INSTALLED_VERSION`,c),t.setVariable(`version`,c,{isOutput:!0}),t.setVariable(`cacheHit`,String(e.SETUP_VP_CACHE_HIT===`true`),{isOutput:!0})}async function main(e){if(e===`prepare`){await runPrepare();return}if(e===`finalize`){await runFinalize();return}fail(`invalid phase "${String(e)}"; expected "prepare" or "finalize"`)}function isEntrypoint(e=process.argv[1],t=import.meta.url){return!!(e&&t===_(u.resolve(e)).href)}if(isEntrypoint()){let e=process.argv[2];e||fail(`missing phase argument; expected "prepare" or "finalize"`);try{await main(e)}catch(e){fail(e instanceof Error?e.message:String(e))}}export{isEntrypoint,main,runFinalize,runPrepare}; \ No newline at end of file diff --git a/dist/gitlab/index.mjs b/dist/gitlab/index.mjs index 99d922e..cfea364 100644 --- a/dist/gitlab/index.mjs +++ b/dist/gitlab/index.mjs @@ -162,6 +162,6 @@ ${r} | bash `)+` `,n,r),t.add(`NODE_AUTH_TOKEN`)}for(let e of t)!isReservedAuthVariable(e)&&n[e]&&r?.(e,n[e]);return a}let a;try{a=new URL(e)}catch{throw Error(`Invalid registry-url: "${e}". Must be a valid URL.`)}let o=a.href.endsWith(`/`)?a.href:`${a.href}/`,s=``;t&&(s=`${(t.startsWith(`@`)?t:`@${t}`).toLowerCase()}:`);let c=o.replace(/^\w+:/,``).toLowerCase(),l=readUserConfigLines(n,new Set([`${s}registry`,`${c}:_authtoken`]));l.push(`${c}:_authToken=\${NODE_AUTH_TOKEN}`,`${s}registry=${o}`);let u=writeUserConfig(l.filter(Boolean).join(` `)+` -`,n,r);return n.NODE_AUTH_TOKEN=n.NODE_AUTH_TOKEN||`XXXXX-XXXXX-XXXXX-XXXXX`,r?.(`NODE_AUTH_TOKEN`,n.NODE_AUTH_TOKEN),u}function shellQuote(e){return`'${String(e).replaceAll(`'`,`'\\''`)}'`}function exportShellEnv(e,t,n=process.env){if(!n.SETUP_VP_ENV_FILE||t===void 0)return;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e))throw Error(`Invalid environment variable name`);let r=n.SETUP_VP_ENV_FORMAT===`powershell`?`$env:${e} = '${t.replaceAll(`'`,`''`)}'\n`:`export ${e}=${shellQuote(t)}\n`;m(n.SETUP_VP_ENV_FILE,r,{encoding:`utf8`,flag:`a`})}function configureAuth(e,t,n=process.env,r){return configureAuth$1(e,t,n,n===process.env?(e,t)=>exportShellEnv(e,t,n):void 0,r)}const $=`v1.15.1`,ht=`https://github.com/SocketDev/sfw-free/releases/download/${$}`;function isMuslLinux(){if(process.platform!==`linux`)return!1;try{let e=process.report?.getReport();if(e?.header&&!e.header.glibcVersionRuntime)return!0}catch{}return i(`/etc/alpine-release`)}function getSfwAssetName(e,t,n){if(e===`darwin`){if(t===`arm64`)return`sfw-free-macos-arm64`;if(t===`x64`)return`sfw-free-macos-x86_64`}else if(e===`linux`){if(t===`arm64`)return n?`sfw-free-musl-linux-arm64`:`sfw-free-linux-arm64`;if(t===`x64`)return n?`sfw-free-musl-linux-x86_64`:`sfw-free-linux-x86_64`}else if(e===`win32`){if(t===`arm64`)return`sfw-free-windows-arm64.exe`;if(t===`x64`)return`sfw-free-windows-x86_64.exe`}throw Error(`Unsupported platform/arch for sfw: ${e}/${t}${e===`linux`?` (${n?`musl`:`glibc`})`:``}`)}function downloadFileWithShell(e,t,n){let r=Math.max(1,Math.ceil(n/1e3)),i=commandPath(`curl`);if(i){let n=w(i,[`-fsSL`,`--connect-timeout`,`5`,`--max-time`,String(r),e,`-o`,t],{stdio:`ignore`});if(n.status===0)return;throw n.error||Error(`curl failed while downloading ${e}`)}let a=commandPath(`wget`);if(a){let n=w(a,[`-q`,`-T`,String(r),`-t`,`2`,`-O`,t,e],{stdio:`ignore`});if(n.status===0)return;throw n.error||Error(`wget failed while downloading ${e}`)}throw Error(`curl or wget is required to download sfw`)}function downloadFile(e,t,n=0,i=6e4,a){return n>5?Promise.reject(Error(`too many redirects while downloading ${e}`)):a?new Promise((o,s)=>{let c=!1,finish=e=>{c||(c=!0,clearTimeout(u),e?s(e):o())},l=a(e,o=>{let s=o.statusCode??0,c=o.headers.location;if(s>=300&&s<400&&c){o.resume(),downloadFile(new URL(c,e).toString(),t,n+1,i,a).then(()=>finish(),finish);return}if(s!==200){o.resume(),finish(Error(`download failed with HTTP ${s}: ${e}`));return}let l=r(t);o.pipe(l),l.on(`finish`,()=>l.close(()=>finish())),l.on(`error`,finish)}),u=setTimeout(()=>{l.destroy(Error(`download timed out after ${i}ms: ${e}`))},i);l.on(`error`,finish)}):(downloadFileWithShell(e,t,i),Promise.resolve())}async function setupSfw$1(e,t={}){let n=t.env??process.env,r=t.sfwEnabled??n.SETUP_VP_SFW===`true`,i=t.platform??process.platform,a=t.arch??process.arch,o=t.isMusl??isMuslLinux(),s=t.download??downloadFile;if(!r)return`vp`;if(e.length===0)return console.log(`setup-vp: sfw was requested but run-install is disabled; sfw will not be invoked.`),`vp`;let c=commandPath(`sfw`);if(c)return console.log(`setup-vp: using existing sfw on PATH: ${c}`),`sfw`;let l;try{l=getSfwAssetName(i,a,o)}catch{return console.error(`setup-vp: sfw has no published binary for this runner's platform/architecture (process.platform=${i}, process.arch=${a}, musl=${o}) and none was found on PATH; falling back to plain vp install.`),`vp`}let u=t.cacheDirectory||n.SETUP_VP_SFW_CACHE_DIR,d=u?h.join(u,$,l):await ae(h.join(E(),`setup-vp-sfw-`));await ie(d,{recursive:!0});let f=h.join(d,i===`win32`?`sfw.exe`:`sfw`),p=`${ht}/${l}`;function activate(){return n.PATH=`${d}${i===`win32`?`;`:`:`}${n.PATH||``}`,t.exportVariable?.(`PATH`,n.PATH),`sfw`}if(await ce(f).then(e=>e.isFile()&&e.size>0,()=>!1))return console.log(`setup-vp: using cached sfw ${$}: ${f}`),activate();for(let e=1;e<=2;e+=1){let t=await ae(h.join(d,`.download-`)),n=h.join(t,`sfw`);try{if(console.log(`setup-vp: installing sfw ${$} from ${p}`),await s(p,n),(await ce(n)).size===0)throw Error(`Downloaded sfw binary is empty`);return await re(n,493),await oe(n,f),activate()}catch(t){if(e===2)throw t;await new Promise(e=>setTimeout(e,2e3))}finally{await se(t,{recursive:!0,force:!0})}}throw Error(`failed to install sfw after retrying`)}async function setupSfw(e,t=process.env){return setupSfw$1(e,{env:t,exportVariable:(e,n)=>exportShellEnv(e,n,t)})}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function validateRunInstallEntry(e){if(!isRecord(e))throw Error(`run-install entries must be objects`);for(let t of Object.keys(e))if(t!==`cwd`&&t!==`args`)throw Error(`unsupported run-install key: ${t}`);let t={};if(e.cwd!==void 0){if(typeof e.cwd!=`string`)throw Error(`run-install.cwd must be a string`);t.cwd=e.cwd}if(e.args!==void 0){if(!Array.isArray(e.args)||e.args.some(e=>typeof e!=`string`))throw Error(`run-install.args must be an array of strings`);t.args=e.args}return t}function validateRunInstallInput(e){return e===null||typeof e==`boolean`?e:Array.isArray(e)?e.map(validateRunInstallEntry):validateRunInstallEntry(e)}function parseRunInstall(e){let t=validateRunInstallInput((0,Y.parse)(e)??null);return t?t===!0?[{}]:Array.isArray(t)?t:[t]:[]}function isSfwVpNotFoundFlake(e,t){return/Command 'vp' not found in PATH/.test(e+` +`,n,r);return n.NODE_AUTH_TOKEN=n.NODE_AUTH_TOKEN||`XXXXX-XXXXX-XXXXX-XXXXX`,r?.(`NODE_AUTH_TOKEN`,n.NODE_AUTH_TOKEN),u}function shellQuote(e){return`'${String(e).replaceAll(`'`,`'\\''`)}'`}function exportShellEnv(e,t,n=process.env){if(!n.SETUP_VP_ENV_FILE||t===void 0)return;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e))throw Error(`Invalid environment variable name`);let r=n.SETUP_VP_ENV_FORMAT===`powershell`?`$env:${e} = '${t.replaceAll(`'`,`''`)}'\n`:`export ${e}=${shellQuote(t)}\n`;m(n.SETUP_VP_ENV_FILE,r,{encoding:`utf8`,flag:`a`})}function configureAuth(e,t,n=process.env,r){return configureAuth$1(e,t,n,n===process.env?(e,t)=>exportShellEnv(e,t,n):void 0,r)}function resolveSfwEnabled(e,t,n){return e?!pkgPrNewCommitSha(t)||(n(`sfw was requested but is automatically disabled for Vite+ preview build ${t}; Socket Firewall Free will not be used.`),!1):!1}const $=`v1.15.1`,ht=`https://github.com/SocketDev/sfw-free/releases/download/${$}`;function isMuslLinux(){if(process.platform!==`linux`)return!1;try{let e=process.report?.getReport();if(e?.header&&!e.header.glibcVersionRuntime)return!0}catch{}return i(`/etc/alpine-release`)}function getSfwAssetName(e,t,n){if(e===`darwin`){if(t===`arm64`)return`sfw-free-macos-arm64`;if(t===`x64`)return`sfw-free-macos-x86_64`}else if(e===`linux`){if(t===`arm64`)return n?`sfw-free-musl-linux-arm64`:`sfw-free-linux-arm64`;if(t===`x64`)return n?`sfw-free-musl-linux-x86_64`:`sfw-free-linux-x86_64`}else if(e===`win32`){if(t===`arm64`)return`sfw-free-windows-arm64.exe`;if(t===`x64`)return`sfw-free-windows-x86_64.exe`}throw Error(`Unsupported platform/arch for sfw: ${e}/${t}${e===`linux`?` (${n?`musl`:`glibc`})`:``}`)}function downloadFileWithShell(e,t,n){let r=Math.max(1,Math.ceil(n/1e3)),i=commandPath(`curl`);if(i){let n=w(i,[`-fsSL`,`--connect-timeout`,`5`,`--max-time`,String(r),e,`-o`,t],{stdio:`ignore`});if(n.status===0)return;throw n.error||Error(`curl failed while downloading ${e}`)}let a=commandPath(`wget`);if(a){let n=w(a,[`-q`,`-T`,String(r),`-t`,`2`,`-O`,t,e],{stdio:`ignore`});if(n.status===0)return;throw n.error||Error(`wget failed while downloading ${e}`)}throw Error(`curl or wget is required to download sfw`)}function downloadFile(e,t,n=0,i=6e4,a){return n>5?Promise.reject(Error(`too many redirects while downloading ${e}`)):a?new Promise((o,s)=>{let c=!1,finish=e=>{c||(c=!0,clearTimeout(u),e?s(e):o())},l=a(e,o=>{let s=o.statusCode??0,c=o.headers.location;if(s>=300&&s<400&&c){o.resume(),downloadFile(new URL(c,e).toString(),t,n+1,i,a).then(()=>finish(),finish);return}if(s!==200){o.resume(),finish(Error(`download failed with HTTP ${s}: ${e}`));return}let l=r(t);o.pipe(l),l.on(`finish`,()=>l.close(()=>finish())),l.on(`error`,finish)}),u=setTimeout(()=>{l.destroy(Error(`download timed out after ${i}ms: ${e}`))},i);l.on(`error`,finish)}):(downloadFileWithShell(e,t,i),Promise.resolve())}async function setupSfw$1(e,t={}){let n=t.env??process.env,r=t.sfwEnabled??n.SETUP_VP_SFW===`true`,i=t.platform??process.platform,a=t.arch??process.arch,o=t.isMusl??isMuslLinux(),s=t.download??downloadFile;if(!resolveSfwEnabled(r,t.vitePlusVersion??``,t.logWarning??console.warn))return`vp`;if(e.length===0)return console.log(`setup-vp: sfw was requested but run-install is disabled; sfw will not be invoked.`),`vp`;let c=commandPath(`sfw`);if(c)return console.log(`setup-vp: using existing sfw on PATH: ${c}`),`sfw`;let l;try{l=getSfwAssetName(i,a,o)}catch{return console.error(`setup-vp: sfw has no published binary for this runner's platform/architecture (process.platform=${i}, process.arch=${a}, musl=${o}) and none was found on PATH; falling back to plain vp install.`),`vp`}let u=t.cacheDirectory||n.SETUP_VP_SFW_CACHE_DIR,d=u?h.join(u,$,l):await ae(h.join(E(),`setup-vp-sfw-`));await ie(d,{recursive:!0});let f=h.join(d,i===`win32`?`sfw.exe`:`sfw`),p=`${ht}/${l}`;function activate(){return n.PATH=`${d}${i===`win32`?`;`:`:`}${n.PATH||``}`,t.exportVariable?.(`PATH`,n.PATH),`sfw`}if(await ce(f).then(e=>e.isFile()&&e.size>0,()=>!1))return console.log(`setup-vp: using cached sfw ${$}: ${f}`),activate();for(let e=1;e<=2;e+=1){let t=await ae(h.join(d,`.download-`)),n=h.join(t,`sfw`);try{if(console.log(`setup-vp: installing sfw ${$} from ${p}`),await s(p,n),(await ce(n)).size===0)throw Error(`Downloaded sfw binary is empty`);return await re(n,493),await oe(n,f),activate()}catch(t){if(e===2)throw t;await new Promise(e=>setTimeout(e,2e3))}finally{await se(t,{recursive:!0,force:!0})}}throw Error(`failed to install sfw after retrying`)}async function setupSfw(e,t=process.env,n=``){return setupSfw$1(e,{env:t,vitePlusVersion:n,exportVariable:(e,n)=>exportShellEnv(e,n,t)})}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function validateRunInstallEntry(e){if(!isRecord(e))throw Error(`run-install entries must be objects`);for(let t of Object.keys(e))if(t!==`cwd`&&t!==`args`)throw Error(`unsupported run-install key: ${t}`);let t={};if(e.cwd!==void 0){if(typeof e.cwd!=`string`)throw Error(`run-install.cwd must be a string`);t.cwd=e.cwd}if(e.args!==void 0){if(!Array.isArray(e.args)||e.args.some(e=>typeof e!=`string`))throw Error(`run-install.args must be an array of strings`);t.args=e.args}return t}function validateRunInstallInput(e){return e===null||typeof e==`boolean`?e:Array.isArray(e)?e.map(validateRunInstallEntry):validateRunInstallEntry(e)}function parseRunInstall(e){let t=validateRunInstallInput((0,Y.parse)(e)??null);return t?t===!0?[{}]:Array.isArray(t)?t:[t]:[]}function isSfwVpNotFoundFlake(e,t){return/Command 'vp' not found in PATH/.test(e+` `+t)}async function runInstall(e,t,n,r=process.env,i={}){let a={...r};delete a.SETUP_VP_ENV_FILE;let o=i.execute??runWithOutput,s=[];for(let r of e){let e=r.cwd?h.resolve(t,r.cwd):t,c=[`install`,...r.args||[]],l=n===`sfw`?[`vp`,...c]:c,u=`${n} ${l.join(` `)} (cwd: ${e})`;console.log(`setup-vp: running ${u}`);try{let t=await o(n,l,{cwd:e,env:a});if(t.exitCode!==0&&n===`sfw`&&isSfwVpNotFoundFlake(t.stdout,t.stderr)){let r=(i.platform??process.platform)===`win32`;if(console.warn(r?`setup-vp: sfw could not resolve vp; warming the PowerShell command cache and retrying once.`:`setup-vp: sfw could not resolve vp; retrying once.`),r)try{await o(`powershell.exe`,[`-NoProfile`,`-Command`,`Get-Command vp`],{cwd:e,env:a})}catch{}t=await o(n,l,{cwd:e,env:a})}t.exitCode!==0&&s.push(`${u} exited with code ${t.exitCode}\n${t.stderr.trim()||t.stdout.trim()}`)}catch(e){s.push(`${u}: ${String(e)}`)}}if(s.length)throw Error(s.join(` -`))}function resolveProjectDir(e=process.env){return resolveProjectDirectory({workingDirectory:e.SETUP_VP_WORKING_DIRECTORY||`.`,workspaceRoot:e.CI_PROJECT_DIR||process.cwd()})}function fail(e){console.error(`setup-vp: ${e}`),process.exit(1)}function applyEnvironmentModes(e=process.env,t=run){let n=parseNodeManager(e.SETUP_VP_NODE_MANAGER),r=parsePackageManager(e.SETUP_VP_PACKAGE_MANAGER),i=(n===!1||r!==void 0)&&getCommandOutput(`vp`,[`--version`])||``,a=packageManagerArgs(r,i);n===!1&&t(`vp`,nodeManagerOffArgs(i));for(let e of a)t(`vp`,e)}async function main(e=`setup`){let n=process.env,r=n.CI_PROJECT_DIR||process.cwd(),i=h.join(r,`.setup-vp-cache`),a=h.join(r,`.setup-vp-cache-state.json`),o=h.join(r,`.setup-vp-outputs.env`);if(e===`save-cache`){restoreCacheSnapshot(JSON.parse(c(a,`utf8`)),i,console.warn,!1).save();return}if(e!==`setup`)throw Error(`Invalid GitLab phase: ${e}`);let s=resolveProjectDir(n);d(a,{force:!0}),d(o,{force:!0});let l=resolutionContext(r),u=parseNodeManager(n.SETUP_VP_NODE_MANAGER);parsePackageManager(n.SETUP_VP_PACKAGE_MANAGER);let f=parseRunInstall(n.SETUP_VP_RUN_INSTALL??`true`);if(u===!1&&(n.SETUP_VP_NODE_VERSION||n.SETUP_VP_NODE_VERSION_FILE))throw Error(`node-version and node-version-file cannot be used with node-manager: false`);let p=n.SETUP_VP_NODE_VERSION||(n.SETUP_VP_NODE_VERSION_FILE?createNodeVersionResolver(l).resolveNodeVersionFile(n.SETUP_VP_NODE_VERSION_FILE,s):void 0);await installVitePlus(createVersionResolver(l).resolveVitePlusVersion({version:n.SETUP_VP_VERSION,versionFile:n.SETUP_VP_VERSION_FILE,cacheDependencyPath:n.SETUP_VP_CACHE_DEPENDENCY_PATH},s),{env:n,prependPath:()=>exportShellEnv(`PATH`,n.PATH)}),applyEnvironmentModes(),p&&run(`vp`,[`env`,`use`,p],{cwd:s}),configureAuth(n.SETUP_VP_REGISTRY_URL||``,n.SETUP_VP_SCOPE||``,n,s);let g=n.SETUP_VP_CACHE?.toLowerCase()===`true`;g?n.SETUP_VP_SFW_CACHE_DIR=h.join(i,`sfw`):delete n.SETUP_VP_SFW_CACHE_DIR;let _=g?prepareCacheMetadata({projectDir:s,cacheDependencyPath:n.SETUP_VP_CACHE_DEPENDENCY_PATH,logWarning:console.warn}):{ready:!1},v=restoreCacheSnapshot(_,i),y=n.SETUP_VP_CACHE_SAVE?.toLowerCase()!==`false`;_.ready&&y&&(m(a,JSON.stringify(_),{mode:384}),t(process.argv[1],h.join(r,`.setup-vp-runtime.mjs`))),await runInstall(f,s,await setupSfw(f)),y&&v.save();let b=getCommandOutput(`vp`,[`--version`],{cwd:s});if(!b)throw Error(`Failed to verify Vite+ installation: vp --version failed or returned no output.`);console.log(b);let x={SETUP_VP_INSTALLED_VERSION:parseInstalledVpVersion(b),SETUP_VP_CACHE_HIT:String(v.hit)};for(let[e,t]of Object.entries(x))n[e]=t,exportShellEnv(e,t);m(o,Object.entries(x).map(([e,t])=>`${e}=${t}\n`).join(``),{mode:384})}function isEntrypoint(e=process.argv[1],t=import.meta.url){return!!(e&&t===S(h.resolve(e)).href)}if(isEntrypoint())try{await main(process.argv[2])}catch(e){fail(e instanceof Error?e.message:String(e))}export{applyEnvironmentModes,isEntrypoint,main}; \ No newline at end of file +`))}function resolveProjectDir(e=process.env){return resolveProjectDirectory({workingDirectory:e.SETUP_VP_WORKING_DIRECTORY||`.`,workspaceRoot:e.CI_PROJECT_DIR||process.cwd()})}function fail(e){console.error(`setup-vp: ${e}`),process.exit(1)}function applyEnvironmentModes(e=process.env,t=run){let n=parseNodeManager(e.SETUP_VP_NODE_MANAGER),r=parsePackageManager(e.SETUP_VP_PACKAGE_MANAGER),i=(n===!1||r!==void 0)&&getCommandOutput(`vp`,[`--version`])||``,a=packageManagerArgs(r,i);n===!1&&t(`vp`,nodeManagerOffArgs(i));for(let e of a)t(`vp`,e)}async function main(e=`setup`){let n=process.env,r=n.CI_PROJECT_DIR||process.cwd(),i=h.join(r,`.setup-vp-cache`),a=h.join(r,`.setup-vp-cache-state.json`),o=h.join(r,`.setup-vp-outputs.env`);if(e===`save-cache`){restoreCacheSnapshot(JSON.parse(c(a,`utf8`)),i,console.warn,!1).save();return}if(e!==`setup`)throw Error(`Invalid GitLab phase: ${e}`);let s=resolveProjectDir(n);d(a,{force:!0}),d(o,{force:!0});let l=resolutionContext(r),u=parseNodeManager(n.SETUP_VP_NODE_MANAGER);parsePackageManager(n.SETUP_VP_PACKAGE_MANAGER);let f=parseRunInstall(n.SETUP_VP_RUN_INSTALL??`true`);if(u===!1&&(n.SETUP_VP_NODE_VERSION||n.SETUP_VP_NODE_VERSION_FILE))throw Error(`node-version and node-version-file cannot be used with node-manager: false`);let p=n.SETUP_VP_NODE_VERSION||(n.SETUP_VP_NODE_VERSION_FILE?createNodeVersionResolver(l).resolveNodeVersionFile(n.SETUP_VP_NODE_VERSION_FILE,s):void 0),g=createVersionResolver(l).resolveVitePlusVersion({version:n.SETUP_VP_VERSION,versionFile:n.SETUP_VP_VERSION_FILE,cacheDependencyPath:n.SETUP_VP_CACHE_DEPENDENCY_PATH},s);await installVitePlus(g,{env:n,prependPath:()=>exportShellEnv(`PATH`,n.PATH)}),applyEnvironmentModes(),p&&run(`vp`,[`env`,`use`,p],{cwd:s}),configureAuth(n.SETUP_VP_REGISTRY_URL||``,n.SETUP_VP_SCOPE||``,n,s);let _=n.SETUP_VP_CACHE?.toLowerCase()===`true`;_?n.SETUP_VP_SFW_CACHE_DIR=h.join(i,`sfw`):delete n.SETUP_VP_SFW_CACHE_DIR;let v=_?prepareCacheMetadata({projectDir:s,cacheDependencyPath:n.SETUP_VP_CACHE_DEPENDENCY_PATH,logWarning:console.warn}):{ready:!1},y=restoreCacheSnapshot(v,i),b=n.SETUP_VP_CACHE_SAVE?.toLowerCase()!==`false`;v.ready&&b&&(m(a,JSON.stringify(v),{mode:384}),t(process.argv[1],h.join(r,`.setup-vp-runtime.mjs`))),await runInstall(f,s,await setupSfw(f,n,g)),b&&y.save();let x=getCommandOutput(`vp`,[`--version`],{cwd:s});if(!x)throw Error(`Failed to verify Vite+ installation: vp --version failed or returned no output.`);console.log(x);let S={SETUP_VP_INSTALLED_VERSION:parseInstalledVpVersion(x),SETUP_VP_CACHE_HIT:String(y.hit)};for(let[e,t]of Object.entries(S))n[e]=t,exportShellEnv(e,t);m(o,Object.entries(S).map(([e,t])=>`${e}=${t}\n`).join(``),{mode:384})}function isEntrypoint(e=process.argv[1],t=import.meta.url){return!!(e&&t===S(h.resolve(e)).href)}if(isEntrypoint())try{await main(process.argv[2])}catch(e){fail(e instanceof Error?e.message:String(e))}export{applyEnvironmentModes,isEntrypoint,main}; \ No newline at end of file diff --git a/dist/index.mjs b/dist/index.mjs index 2cf6202..9bbe78b 100644 --- a/dist/index.mjs +++ b/dist/index.mjs @@ -220,9 +220,9 @@ ${r} | bash More info on storage limits: https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions#calculating-minute-and-storage-spending`),this.name=`UsageError`}};UsageError.isUsageErrorMessage=e=>e?e.includes(`insufficient usage`):!1;var RateLimitError=class extends Error{constructor(e){super(e),this.name=`RateLimitError`}},__awaiter$9=function(e,t,n,r){function adopt(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())})},UploadProgress=class{constructor(e){this.contentLength=e,this.sentBytes=0,this.displayedComplete=!1,this.startTime=Date.now()}setSentBytes(e){this.sentBytes=e}getTransferredBytes(){return this.sentBytes}isDone(){return this.getTransferredBytes()===this.contentLength}display(){if(this.displayedComplete)return;let e=this.sentBytes,t=(100*(e/this.contentLength)).toFixed(1),n=Date.now()-this.startTime,r=(e/1048576/(n/1e3)).toFixed(1);info(`Sent ${e} of ${this.contentLength} (${t}%), ${r} MBs/sec`),this.isDone()&&(this.displayedComplete=!0)}onProgress(){return e=>{this.setSentBytes(e.loadedBytes)}}startDisplayTimer(e=1e3){let displayCallback=()=>{this.display(),this.isDone()||(this.timeoutHandle=setTimeout(displayCallback,e))};this.timeoutHandle=setTimeout(displayCallback,e)}stopDisplayTimer(){this.timeoutHandle&&=(clearTimeout(this.timeoutHandle),void 0),this.display()}};function uploadCacheArchiveSDK(e,t,n){return __awaiter$9(this,void 0,void 0,function*(){let r=new l_(e),i=r.getBlockBlobClient(),a=new UploadProgress(n?.archiveSizeBytes??0),o={blockSize:n?.uploadChunkSize,concurrency:n?.uploadConcurrency,maxSingleShotSize:134217728,onProgress:a.onProgress()};try{a.startDisplayTimer(),debug(`BlobClient: ${r.name}:${r.accountName}:${r.containerName}`);let e=yield i.uploadFile(t,o);if(e._response.status>=400)throw new InvalidResponseError(`uploadCacheArchiveSDK: upload failed with status code ${e._response.status}`);return e}catch(e){throw warning(`uploadCacheArchiveSDK: internal error uploading cache archive: ${e.message}`),e}finally{a.stopDisplayTimer()}})}var __awaiter$8=function(e,t,n,r){function adopt(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())})};function isSuccessStatusCode(e){return e?e>=200&&e<300:!1}function isServerErrorStatusCode(e){return!e||e>=500}function isRetryableStatusCode(e){return e?[On.BadGateway,On.ServiceUnavailable,On.GatewayTimeout].includes(e):!1}function sleep(e){return __awaiter$8(this,void 0,void 0,function*(){return new Promise(t=>setTimeout(t,e))})}function retry(e,t,n){return __awaiter$8(this,arguments,void 0,function*(e,t,n,r=2,i=Do,a=void 0){let o=``,s=1;for(;s<=r;){let c,l,u=!1;try{c=yield t()}catch(e){a&&(c=a(e)),u=!0,o=e.message}if(c&&(l=n(c),!isServerErrorStatusCode(l)))return c;if(l&&(u=isRetryableStatusCode(l),o=`Cache service responded with ${l}`),debug(`${e} - Attempt ${s} of ${r} failed with error: ${o}`),!u){debug(`${e} - Error is not retryable`);break}yield sleep(i),s++}throw Error(`${e} failed: ${o}`)})}function retryTypedResponse(e,t){return __awaiter$8(this,arguments,void 0,function*(e,t,n=2,r=Do){return yield retry(e,t,e=>e.statusCode,n,r,e=>{if(e instanceof Pn)return{statusCode:e.statusCode,result:null,headers:{},error:e}})})}function retryHttpClientResponse(e,t){return __awaiter$8(this,arguments,void 0,function*(e,t,n=2,r=Do){return yield retry(e,t,e=>e.message.statusCode,n,r)})}var __awaiter$7=function(e,t,n,r){function adopt(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())})};function pipeResponseToStream(e,t){return __awaiter$7(this,void 0,void 0,function*(){yield y.promisify(Ce.pipeline)(e.message,t)})}var DownloadProgress=class{constructor(e){this.contentLength=e,this.segmentIndex=0,this.segmentSize=0,this.segmentOffset=0,this.receivedBytes=0,this.displayedComplete=!1,this.startTime=Date.now()}nextSegment(e){this.segmentOffset+=this.segmentSize,this.segmentIndex+=1,this.segmentSize=e,this.receivedBytes=0,debug(`Downloading segment at offset ${this.segmentOffset} with length ${this.segmentSize}...`)}setReceivedBytes(e){this.receivedBytes=e}getTransferredBytes(){return this.segmentOffset+this.receivedBytes}isDone(){return this.getTransferredBytes()===this.contentLength}display(){if(this.displayedComplete)return;let e=this.segmentOffset+this.receivedBytes,t=(100*(e/this.contentLength)).toFixed(1),n=Date.now()-this.startTime,r=(e/1048576/(n/1e3)).toFixed(1);info(`Received ${e} of ${this.contentLength} (${t}%), ${r} MBs/sec`),this.isDone()&&(this.displayedComplete=!0)}onProgress(){return e=>{this.setReceivedBytes(e.loadedBytes)}}startDisplayTimer(e=1e3){let displayCallback=()=>{this.display(),this.isDone()||(this.timeoutHandle=setTimeout(displayCallback,e))};this.timeoutHandle=setTimeout(displayCallback,e)}stopDisplayTimer(){this.timeoutHandle&&=(clearTimeout(this.timeoutHandle),void 0),this.display()}};function downloadCacheHttpClient(e,t){return __awaiter$7(this,void 0,void 0,function*(){let n=a.createWriteStream(t),r=new HttpClient(`actions/cache`),i=yield retryHttpClientResponse(`downloadCache`,()=>__awaiter$7(this,void 0,void 0,function*(){return r.get(e)}));i.message.socket.setTimeout(Oo,()=>{i.message.destroy(),debug(`Aborting download, socket timed out after ${Oo} ms`)}),yield pipeResponseToStream(i,n);let o=i.message.headers[`content-length`];if(o){let e=parseInt(o),n=getArchiveFileSizeInBytes(t);if(n!==e)throw Error(`Incomplete download. Expected file size: ${e}, actual file size: ${n}`)}else debug(`Unable to validate download, no Content-Length header`)})}function downloadCacheHttpClientConcurrent(e,t,n){return __awaiter$7(this,void 0,void 0,function*(){let r=yield a.promises.open(t,`w`),i=new HttpClient(`actions/cache`,void 0,{socketTimeout:n.timeoutInMs,keepAlive:!0});try{let t=(yield retryHttpClientResponse(`downloadCacheMetadata`,()=>__awaiter$7(this,void 0,void 0,function*(){return yield i.request(`HEAD`,e,null,{})}))).message.headers[`content-length`];if(t==null)throw Error(`Content-Length not found on blob response`);let a=parseInt(t);if(Number.isNaN(a))throw Error(`Could not interpret Content-Length: ${a}`);let o=[],s=4194304;for(let t=0;t__awaiter$7(this,void 0,void 0,function*(){return yield downloadSegmentRetry(i,e,t,n)})})}o.reverse();let c=0,l=0,u=new DownloadProgress(a);u.startDisplayTimer();let d=u.onProgress(),f=[],p,waitAndWrite=()=>__awaiter$7(this,void 0,void 0,function*(){let e=yield Promise.race(Object.values(f));yield r.write(e.buffer,0,e.count,e.offset),c--,delete f[e.offset],l+=e.count,d({loadedBytes:l})});for(;p=o.pop();)f[p.offset]=p.promiseGetter(),c++,c>=(n.downloadConcurrency??10)&&(yield waitAndWrite());for(;c>0;)yield waitAndWrite()}finally{i.dispose(),yield r.close()}})}function downloadSegmentRetry(e,t,n,r){return __awaiter$7(this,void 0,void 0,function*(){let i=0;for(;;)try{let i=yield promiseWithTimeout(3e4,downloadSegment(e,t,n,r));if(typeof i==`string`)throw Error(`downloadSegmentRetry failed due to timeout`);return i}catch(e){if(i>=5)throw e;i++}})}function downloadSegment(e,t,n,r){return __awaiter$7(this,void 0,void 0,function*(){let i=yield retryHttpClientResponse(`downloadCachePart`,()=>__awaiter$7(this,void 0,void 0,function*(){return yield e.get(t,{Range:`bytes=${n}-${n+r-1}`})}));if(!i.readBodyBuffer)throw Error(`Expected HttpClientResponse to implement readBodyBuffer`);return{offset:n,count:r,buffer:yield i.readBodyBuffer()}})}function downloadCacheStorageSDK(e,t,n){return __awaiter$7(this,void 0,void 0,function*(){let r=new d_(e,void 0,{retryOptions:{tryTimeoutInMs:n.timeoutInMs}}),i=(yield r.getProperties()).contentLength??-1;if(i<0)debug(`Unable to determine content length, downloading file with http-client...`),yield downloadCacheHttpClient(e,t);else{let e=Math.min(134217728,P.constants.MAX_LENGTH),o=new DownloadProgress(i),s=a.openSync(t,`w`);try{o.startDisplayTimer();let t=new AbortController,c=t.signal;for(;!o.isDone();){let l=o.segmentOffset+o.segmentSize,u=Math.min(e,i-l);o.nextSegment(u);let d=yield promiseWithTimeout(n.segmentTimeoutInMs||36e5,r.downloadToBuffer(l,u,{abortSignal:c,concurrency:n.downloadConcurrency,onProgress:o.onProgress()}));if(d===`timeout`)throw t.abort(),Error(`Aborting cache download as the download time exceeded the timeout.`);Buffer.isBuffer(d)&&a.writeFileSync(s,d)}}finally{o.stopDisplayTimer(),a.closeSync(s)}}})}const promiseWithTimeout=(e,t)=>__awaiter$7(void 0,void 0,void 0,function*(){let n,r=new Promise(t=>{n=setTimeout(()=>t(`timeout`),e)});return Promise.race([t,r]).then(e=>(clearTimeout(n),e))});function getUploadOptions(e){let t={useAzureSdk:!1,uploadConcurrency:4,uploadChunkSize:33554432};return e&&(typeof e.useAzureSdk==`boolean`&&(t.useAzureSdk=e.useAzureSdk),typeof e.uploadConcurrency==`number`&&(t.uploadConcurrency=e.uploadConcurrency),typeof e.uploadChunkSize==`number`&&(t.uploadChunkSize=e.uploadChunkSize)),t.uploadConcurrency=isNaN(Number(process.env.CACHE_UPLOAD_CONCURRENCY))?t.uploadConcurrency:Math.min(32,Number(process.env.CACHE_UPLOAD_CONCURRENCY)),t.uploadChunkSize=isNaN(Number(process.env.CACHE_UPLOAD_CHUNK_SIZE))?t.uploadChunkSize:Math.min(134217728,Number(process.env.CACHE_UPLOAD_CHUNK_SIZE)*1024*1024),debug(`Use Azure SDK: ${t.useAzureSdk}`),debug(`Upload concurrency: ${t.uploadConcurrency}`),debug(`Upload chunk size: ${t.uploadChunkSize}`),t}function getDownloadOptions(e){let t={useAzureSdk:!1,concurrentBlobDownloads:!0,downloadConcurrency:8,timeoutInMs:3e4,segmentTimeoutInMs:6e5,lookupOnly:!1};e&&(typeof e.useAzureSdk==`boolean`&&(t.useAzureSdk=e.useAzureSdk),typeof e.concurrentBlobDownloads==`boolean`&&(t.concurrentBlobDownloads=e.concurrentBlobDownloads),typeof e.downloadConcurrency==`number`&&(t.downloadConcurrency=e.downloadConcurrency),typeof e.timeoutInMs==`number`&&(t.timeoutInMs=e.timeoutInMs),typeof e.segmentTimeoutInMs==`number`&&(t.segmentTimeoutInMs=e.segmentTimeoutInMs),typeof e.lookupOnly==`boolean`&&(t.lookupOnly=e.lookupOnly));let n=process.env.SEGMENT_DOWNLOAD_TIMEOUT_MINS;return n&&!isNaN(Number(n))&&isFinite(Number(n))&&(t.segmentTimeoutInMs=Number(n)*60*1e3),debug(`Use Azure SDK: ${t.useAzureSdk}`),debug(`Download concurrency: ${t.downloadConcurrency}`),debug(`Request timeout (ms): ${t.timeoutInMs}`),debug(`Cache segment download timeout mins env var: ${process.env.SEGMENT_DOWNLOAD_TIMEOUT_MINS}`),debug(`Segment download timeout (ms): ${t.segmentTimeoutInMs}`),debug(`Lookup only: ${t.lookupOnly}`),t}function isGhes(){let e=new URL(process.env.GITHUB_SERVER_URL||`https://github.com`).hostname.trimEnd().toUpperCase(),t=e===`GITHUB.COM`,n=e.endsWith(`.GHE.COM`),r=e.endsWith(`.LOCALHOST`);return!t&&!n&&!r}function getCacheServiceVersion(){return isGhes()?`v1`:process.env.ACTIONS_CACHE_SERVICE_V2?`v2`:`v1`}const p_=[`none`,`read`,`write`,`write-only`];function getCacheMode(){return(process.env.ACTIONS_CACHE_MODE||``).trim().toLowerCase()}function isCacheReadable(e){return!p_.includes(e)||e===`read`||e===`write`}function isCacheWritable(e){return!p_.includes(e)||e===`write`||e===`write-only`}function getCacheServiceURL(){let e=getCacheServiceVersion();switch(e){case`v1`:return process.env.ACTIONS_CACHE_URL||process.env.ACTIONS_RESULTS_URL||``;case`v2`:return process.env.ACTIONS_RESULTS_URL||``;default:throw Error(`Unsupported cache service version: ${e}`)}}var m_=__commonJSMin(((e,t)=>{t.exports={name:`@actions/cache`,version:`6.2.0`,description:`Actions cache lib`,keywords:[`github`,`actions`,`cache`],homepage:`https://github.com/actions/toolkit/tree/main/packages/cache`,license:`MIT`,type:`module`,main:`lib/cache.js`,types:`lib/cache.d.ts`,exports:{".":{types:`./lib/cache.d.ts`,import:`./lib/cache.js`}},directories:{lib:`lib`,test:`__tests__`},files:[`lib`,`!.DS_Store`],publishConfig:{access:`public`},repository:{type:`git`,url:`git+https://github.com/actions/toolkit.git`,directory:`packages/cache`},scripts:{"audit-moderate":`npm install && npm audit --json --audit-level=moderate > audit.json`,test:`echo "Error: run tests from root" && exit 1`,tsc:`tsc && cp src/internal/shared/package-version.cjs lib/internal/shared/`},bugs:{url:`https://github.com/actions/toolkit/issues`},dependencies:{"@actions/core":`^3.0.1`,"@actions/exec":`^3.0.0`,"@actions/glob":`^0.6.1`,"@actions/http-client":`^4.0.1`,"@actions/io":`^3.0.2`,"@azure/core-rest-pipeline":`^1.23.0`,"@azure/storage-blob":`^12.31.0`,"@protobuf-ts/runtime-rpc":`^2.11.1`,semver:`^7.7.4`},devDependencies:{"@protobuf-ts/plugin":`^2.11.1`,"@types/node":`^25.6.0`,"@types/semver":`^7.7.1`,typescript:`^5.9.3`},overrides:{"uri-js":`npm:uri-js-replace@^1.0.1`,"node-fetch":`^3.3.2`}}})),h_=__commonJSMin(((e,t)=>{t.exports={version:m_().version}}))();function getUserAgentString(){return`@actions/cache-${h_.version}`}var __awaiter$6=function(e,t,n,r){function adopt(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())})};function getCacheApiUrl(e){let t=getCacheServiceURL();if(!t)throw Error(`Cache Service Url not found, unable to restore cache.`);let n=`${t}_apis/artifactcache/${e}`;return debug(`Resource Url: ${n}`),n}function createAcceptHeader(e,t){return`${e};api-version=${t}`}function getRequestOptions(){return{headers:{Accept:createAcceptHeader(`application/json`,`6.0-preview.1`)}}}function createHttpClient(){let e=new BearerCredentialHandler(process.env.ACTIONS_RUNTIME_TOKEN||``);return new HttpClient(getUserAgentString(),[e],getRequestOptions())}function getCacheEntry(e,t,n){return __awaiter$6(this,void 0,void 0,function*(){let r=createHttpClient(),i=getCacheVersion(t,n?.compressionMethod,n?.enableCrossOsArchive),a=`cache?keys=${encodeURIComponent(e.join(`,`))}&version=${i}`,o=yield retryTypedResponse(`getCacheEntry`,()=>__awaiter$6(this,void 0,void 0,function*(){return r.getJson(getCacheApiUrl(a))}));if(o.statusCode===204)return isDebug()&&(yield printCachesListForDiagnostics(e[0],r,i)),null;if(!isSuccessStatusCode(o.statusCode)){let e=o.error?.message;throw e?.includes(`cache read denied:`)?Error(e):Error(`Cache service responded with ${o.statusCode}`)}let s=o.result,c=s?.archiveLocation;if(!c)throw Error(`Cache not found.`);return setSecret(c),debug(`Cache Result:`),debug(JSON.stringify(s)),s})}function printCachesListForDiagnostics(e,t,n){return __awaiter$6(this,void 0,void 0,function*(){let r=`caches?key=${encodeURIComponent(e)}`,i=yield retryTypedResponse(`listCache`,()=>__awaiter$6(this,void 0,void 0,function*(){return t.getJson(getCacheApiUrl(r))}));if(i.statusCode===200){let t=i.result,r=t?.totalCount;if(r&&r>0){debug(`No matching cache found for cache key '${e}', version '${n} and scope ${process.env.GITHUB_REF}. There exist one or more cache(s) with similar key but they have different version or scope. See more info on cache matching here: https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#matching-a-cache-key \nOther caches with similar key:`);for(let e of t?.artifactCaches||[])debug(`Cache Key: ${e?.cacheKey}, Cache Version: ${e?.cacheVersion}, Cache Scope: ${e?.scope}, Cache Created: ${e?.creationTime}`)}}})}function downloadCache(e,t,n){return __awaiter$6(this,void 0,void 0,function*(){let r=new Te(e),i=getDownloadOptions(n);r.hostname.endsWith(`.blob.core.windows.net`)?i.useAzureSdk?yield downloadCacheStorageSDK(e,t,i):i.concurrentBlobDownloads?yield downloadCacheHttpClientConcurrent(e,t,i):yield downloadCacheHttpClient(e,t):yield downloadCacheHttpClient(e,t)})}function reserveCache(e,t,n){return __awaiter$6(this,void 0,void 0,function*(){let r=createHttpClient(),i={key:e,version:getCacheVersion(t,n?.compressionMethod,n?.enableCrossOsArchive),cacheSize:n?.cacheSize};return yield retryTypedResponse(`reserveCache`,()=>__awaiter$6(this,void 0,void 0,function*(){return r.postJson(getCacheApiUrl(`caches`),i)}))})}function getContentRange(e,t){return`bytes ${e}-${t}/*`}function uploadChunk(e,t,n,r,i){return __awaiter$6(this,void 0,void 0,function*(){debug(`Uploading chunk of size ${i-r+1} bytes at offset ${r} with content range: ${getContentRange(r,i)}`);let a={"Content-Type":`application/octet-stream`,"Content-Range":getContentRange(r,i)},o=yield retryHttpClientResponse(`uploadChunk (start: ${r}, end: ${i})`,()=>__awaiter$6(this,void 0,void 0,function*(){return e.sendStream(`PATCH`,t,n(),a)}));if(!isSuccessStatusCode(o.message.statusCode))throw Error(`Cache service responded with ${o.message.statusCode} during upload chunk.`)})}function uploadFile(e,t,n,r){return __awaiter$6(this,void 0,void 0,function*(){let i=getArchiveFileSizeInBytes(n),o=getCacheApiUrl(`caches/${t.toString()}`),s=a.openSync(n,`r`),c=getUploadOptions(r),l=assertDefined(`uploadConcurrency`,c.uploadConcurrency),u=assertDefined(`uploadChunkSize`,c.uploadChunkSize),d=[...Array(l).keys()];debug(`Awaiting all uploads`);let f=0;try{yield Promise.all(d.map(()=>__awaiter$6(this,void 0,void 0,function*(){for(;fa.createReadStream(n,{fd:s,start:r,end:c,autoClose:!1}).on(`error`,e=>{throw Error(`Cache upload failed because file read failed with ${e.message}`)}),r,c)}})))}finally{a.closeSync(s)}})}function commitCache(e,t,n){return __awaiter$6(this,void 0,void 0,function*(){let r={size:n};return yield retryTypedResponse(`commitCache`,()=>__awaiter$6(this,void 0,void 0,function*(){return e.postJson(getCacheApiUrl(`caches/${t.toString()}`),r)}))})}function saveCache$2(e,t,n,r){return __awaiter$6(this,void 0,void 0,function*(){if(getUploadOptions(r).useAzureSdk){if(!n)throw Error(`Azure Storage SDK can only be used when a signed URL is provided.`);yield uploadCacheArchiveSDK(n,t,r)}else{let n=createHttpClient();debug(`Upload cache`),yield uploadFile(n,e,t,r),debug(`Commiting cache`);let i=getArchiveFileSizeInBytes(t);info(`Cache Size: ~${Math.round(i/1048576)} MB (${i} B)`);let a=yield commitCache(n,e,i);if(!isSuccessStatusCode(a.statusCode))throw Error(`Cache service responded with ${a.statusCode} during commit cache.`);info(`Cache saved successfully`)}})}var g_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.isJsonObject=e.typeofJsonValue=void 0;function typeofJsonValue(e){let t=typeof e;if(t==`object`){if(Array.isArray(e))return`array`;if(e===null)return`null`}return t}e.typeofJsonValue=typeofJsonValue;function isJsonObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}e.isJsonObject=isJsonObject})),__=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.base64encode=e.base64decode=void 0;let t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.split(``),n=[];for(let e=0;e>4,s=o,a=2;break;case 2:r[i++]=(s&15)<<4|(o&60)>>2,s=o,a=3;break;case 3:r[i++]=(s&3)<<6|o,a=0}}if(a==1)throw Error(`invalid base64 string.`);return r.subarray(0,i)}e.base64decode=base64decode;function base64encode(e){let n=``,r=0,i,a=0;for(let o=0;o>2],a=(i&3)<<4,r=1;break;case 1:n+=t[a|i>>4],a=(i&15)<<2,r=2;break;case 2:n+=t[a|i>>6],n+=t[i&63],r=0}return r&&(n+=t[a],n+=`=`,r==1&&(n+=`=`)),n}e.base64encode=base64encode})),v_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.utf8read=void 0;let fromCharCodes=e=>String.fromCharCode.apply(String,e);function utf8read(e){if(e.length<1)return``;let t=0,n=[],r=[],i=0,a,o=e.length;for(;t191&&a<224?r[i++]=(a&31)<<6|e[t++]&63:a>239&&a<365?(a=((a&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,r[i++]=55296+(a>>10),r[i++]=56320+(a&1023)):r[i++]=(a&15)<<12|(e[t++]&63)<<6|e[t++]&63,i>8191&&(n.push(fromCharCodes(r)),i=0);return n.length?(i&&n.push(fromCharCodes(r.slice(0,i))),n.join(``)):fromCharCodes(r.slice(0,i))}e.utf8read=utf8read})),y_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WireType=e.mergeBinaryOptions=e.UnknownFieldHandler=void 0,(function(e){e.symbol=Symbol.for(`protobuf-ts/unknown`),e.onRead=(t,n,r,i,a)=>{(is(n)?n[e.symbol]:n[e.symbol]=[]).push({no:r,wireType:i,data:a})},e.onWrite=(t,n,r)=>{for(let{no:t,wireType:i,data:a}of e.list(n))r.tag(t,i).raw(a)},e.list=(t,n)=>{if(is(t)){let r=t[e.symbol];return n?r.filter(e=>e.no==n):r}return[]},e.last=(t,n)=>e.list(t,n).slice(-1)[0];let is=t=>t&&Array.isArray(t[e.symbol])})(e.UnknownFieldHandler||={});function mergeBinaryOptions(e,t){return Object.assign(Object.assign({},e),t)}e.mergeBinaryOptions=mergeBinaryOptions,(function(e){e[e.Varint=0]=`Varint`,e[e.Bit64=1]=`Bit64`,e[e.LengthDelimited=2]=`LengthDelimited`,e[e.StartGroup=3]=`StartGroup`,e[e.EndGroup=4]=`EndGroup`,e[e.Bit32=5]=`Bit32`})(e.WireType||={})})),b_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.varint32read=e.varint32write=e.int64toString=e.int64fromString=e.varint64write=e.varint64read=void 0;function varint64read(){let e=0,t=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(e|=(r&127)<>4,!(n&128))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(t|=(r&127)<>>r,a=!(!(i>>>7)&&t==0),o=(a?i|128:i)&255;if(n.push(o),!a)return}let r=e>>>28&15|(t&7)<<4,i=!!(t>>3);if(n.push((i?r|128:r)&255),i){for(let e=3;e<31;e+=7){let r=t>>>e,i=!!(r>>>7),a=(i?r|128:r)&255;if(n.push(a),!i)return}n.push(t>>>31&1)}}e.varint64write=varint64write;let t=4294967296;function int64fromString(e){let n=e[0]==`-`;n&&(e=e.slice(1));let r=1e6,i=0,a=0;function add1e6digit(n,o){let s=Number(e.slice(n,o));a*=r,i=i*r+s,i>=t&&(a+=i/t|0,i%=t)}return add1e6digit(-24,-18),add1e6digit(-18,-12),add1e6digit(-12,-6),add1e6digit(-6),[n,i,a]}e.int64fromString=int64fromString;function int64toString(e,n){if(n>>>0<=2097151)return``+(t*n+(e>>>0));let r=e&16777215,i=(e>>>24|n<<8)>>>0&16777215,a=n>>16&65535,o=r+i*6777216+a*6710656,s=i+a*8147497,c=a*2,l=1e7;o>=l&&(s+=Math.floor(o/l),o%=l),s>=l&&(c+=Math.floor(s/l),s%=l);function decimalFrom1e7(e,t){let n=e?String(e):``;return t?`0000000`.slice(n.length)+n:n}return decimalFrom1e7(c,0)+decimalFrom1e7(s,c)+decimalFrom1e7(o,1)}e.int64toString=int64toString;function varint32write(e,t){if(e>=0){for(;e>127;)t.push(e&127|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(e&127|128),e>>=7;t.push(1)}}e.varint32write=varint32write;function varint32read(){let e=this.buf[this.pos++],t=e&127;if(!(e&128)||(e=this.buf[this.pos++],t|=(e&127)<<7,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<14,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<21,!(e&128)))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(e&15)<<28;for(let t=5;e&128&&t<10;t++)e=this.buf[this.pos++];if(e&128)throw Error(`invalid varint`);return this.assertBounds(),t>>>0}e.varint32read=varint32read})),x_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PbLong=e.PbULong=e.detectBi=void 0;let t=b_(),n;function detectBi(){let e=new DataView(new ArrayBuffer(8));n=globalThis.BigInt!==void 0&&typeof e.getBigInt64==`function`&&typeof e.getBigUint64==`function`&&typeof e.setBigInt64==`function`&&typeof e.setBigUint64==`function`?{MIN:BigInt(`-9223372036854775808`),MAX:BigInt(`9223372036854775807`),UMIN:BigInt(`0`),UMAX:BigInt(`18446744073709551615`),C:BigInt,V:e}:void 0}e.detectBi=detectBi,detectBi();function assertBi(e){if(!e)throw Error(`BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support`)}let r=/^-?[0-9]+$/,i=4294967296,a=2147483648;var SharedPbLong=class{constructor(e,t){this.lo=e|0,this.hi=t|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let e=this.hi*i+(this.lo>>>0);if(!Number.isSafeInteger(e))throw Error(`cannot convert to safe number`);return e}},o=class PbULong extends SharedPbLong{static from(e){if(n)switch(typeof e){case`string`:if(e==`0`)return this.ZERO;if(e==``)throw Error(`string is no integer`);e=n.C(e);case`number`:if(e===0)return this.ZERO;e=n.C(e);case`bigint`:if(!e)return this.ZERO;if(en.UMAX)throw Error(`ulong too large`);return n.V.setBigUint64(0,e,!0),new PbULong(n.V.getInt32(0,!0),n.V.getInt32(4,!0))}else switch(typeof e){case`string`:if(e==`0`)return this.ZERO;if(e=e.trim(),!r.test(e))throw Error(`string is no integer`);let[n,a,o]=t.int64fromString(e);if(n)throw Error(`signed value for ulong`);return new PbULong(a,o);case`number`:if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw Error(`number is no integer`);if(e<0)throw Error(`signed value for ulong`);return new PbULong(e,e/i)}throw Error(`unknown value `+typeof e)}toString(){return n?this.toBigInt().toString():t.int64toString(this.lo,this.hi)}toBigInt(){return assertBi(n),n.V.setInt32(0,this.lo,!0),n.V.setInt32(4,this.hi,!0),n.V.getBigUint64(0,!0)}};e.PbULong=o,o.ZERO=new o(0,0);var s=class PbLong extends SharedPbLong{static from(e){if(n)switch(typeof e){case`string`:if(e==`0`)return this.ZERO;if(e==``)throw Error(`string is no integer`);e=n.C(e);case`number`:if(e===0)return this.ZERO;e=n.C(e);case`bigint`:if(!e)return this.ZERO;if(en.MAX)throw Error(`signed long too large`);return n.V.setBigInt64(0,e,!0),new PbLong(n.V.getInt32(0,!0),n.V.getInt32(4,!0))}else switch(typeof e){case`string`:if(e==`0`)return this.ZERO;if(e=e.trim(),!r.test(e))throw Error(`string is no integer`);let[n,o,s]=t.int64fromString(e);if(n){if(s>a||s==a&&o!=0)throw Error(`signed long too small`)}else if(s>=a)throw Error(`signed long too large`);let c=new PbLong(o,s);return n?c.negate():c;case`number`:if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw Error(`number is no integer`);return e>0?new PbLong(e,e/i):new PbLong(-e,-e/i).negate()}throw Error(`unknown value `+typeof e)}isNegative(){return!!(this.hi&a)}negate(){let e=~this.hi,t=this.lo;return t?t=~t+1:e+=1,new PbLong(t,e)}toString(){if(n)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return`-`+t.int64toString(e.lo,e.hi)}return t.int64toString(this.lo,this.hi)}toBigInt(){return assertBi(n),n.V.setInt32(0,this.lo,!0),n.V.setInt32(4,this.hi,!0),n.V.getBigInt64(0,!0)}};e.PbLong=s,s.ZERO=new s(0,0)})),S_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BinaryReader=e.binaryReadOptions=void 0;let t=y_(),n=x_(),r=b_(),i={readUnknownField:!0,readerFactory:e=>new BinaryReader(e)};function binaryReadOptions(e){return e?Object.assign(Object.assign({},i),e):i}e.binaryReadOptions=binaryReadOptions;var BinaryReader=class{constructor(e,t){this.varint64=r.varint64read,this.uint32=r.varint32read,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0})}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw Error(`illegal tag: field no `+t+` wire type `+n);return[t,n]}skip(e){let n=this.pos;switch(e){case t.WireType.Varint:for(;this.buf[this.pos++]&128;);break;case t.WireType.Bit64:this.pos+=4;case t.WireType.Bit32:this.pos+=4;break;case t.WireType.LengthDelimited:let n=this.uint32();this.pos+=n;break;case t.WireType.StartGroup:let r;for(;(r=this.tag()[1])!==t.WireType.EndGroup;)this.skip(r);break;default:throw Error(`cant skip wire type `+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw RangeError(`premature EOF`)}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return new n.PbLong(...this.varint64())}uint64(){return new n.PbULong(...this.varint64())}sint64(){let[e,t]=this.varint64(),r=-(e&1);return e=(e>>>1|(t&1)<<31)^r,t=t>>>1^r,new n.PbLong(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new n.PbULong(this.sfixed32(),this.sfixed32())}sfixed64(){return new n.PbLong(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}};e.BinaryReader=BinaryReader})),C_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assertFloat32=e.assertUInt32=e.assertInt32=e.assertNever=e.assert=void 0;function assert(e,t){if(!e)throw Error(t)}e.assert=assert;function assertNever(e,t){throw Error(t??`Unexpected object: `+e)}e.assertNever=assertNever;function assertInt32(e){if(typeof e!=`number`)throw Error(`invalid int 32: `+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw Error(`invalid int 32: `+e)}e.assertInt32=assertInt32;function assertUInt32(e){if(typeof e!=`number`)throw Error(`invalid uint 32: `+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw Error(`invalid uint 32: `+e)}e.assertUInt32=assertUInt32;function assertFloat32(e){if(typeof e!=`number`)throw Error(`invalid float 32: `+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw Error(`invalid float 32: `+e)}e.assertFloat32=assertFloat32})),w_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BinaryWriter=e.binaryWriteOptions=void 0;let t=x_(),n=b_(),r=C_(),i={writeUnknownFields:!0,writerFactory:()=>new BinaryWriter};function binaryWriteOptions(e){return e?Object.assign(Object.assign({},i),e):i}e.binaryWriteOptions=binaryWriteOptions;var BinaryWriter=class{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(r.assertUInt32(e);e>127;)this.buf.push(e&127|128),e>>>=7;return this.buf.push(e),this}int32(e){return r.assertInt32(e),n.varint32write(e,this.buf),this}bool(e){return this.buf.push(+!!e),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){r.assertFloat32(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){r.assertUInt32(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){r.assertInt32(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return r.assertInt32(e),e=(e<<1^e>>31)>>>0,n.varint32write(e,this.buf),this}sfixed64(e){let n=new Uint8Array(8),r=new DataView(n.buffer),i=t.PbLong.from(e);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(n)}fixed64(e){let n=new Uint8Array(8),r=new DataView(n.buffer),i=t.PbULong.from(e);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(n)}int64(e){let r=t.PbLong.from(e);return n.varint64write(r.lo,r.hi,this.buf),this}sint64(e){let r=t.PbLong.from(e),i=r.hi>>31,a=r.lo<<1^i,o=(r.hi<<1|r.lo>>>31)^i;return n.varint64write(a,o,this.buf),this}uint64(e){let r=t.PbULong.from(e);return n.varint64write(r.lo,r.hi,this.buf),this}};e.BinaryWriter=BinaryWriter})),T_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.mergeJsonOptions=e.jsonWriteOptions=e.jsonReadOptions=void 0;let t={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},n={ignoreUnknownFields:!1};function jsonReadOptions(e){return e?Object.assign(Object.assign({},n),e):n}e.jsonReadOptions=jsonReadOptions;function jsonWriteOptions(e){return e?Object.assign(Object.assign({},t),e):t}e.jsonWriteOptions=jsonWriteOptions;function mergeJsonOptions(e,t){let n=Object.assign(Object.assign({},e),t);return n.typeRegistry=[...e?.typeRegistry??[],...t?.typeRegistry??[]],n}e.mergeJsonOptions=mergeJsonOptions})),E_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MESSAGE_TYPE=void 0,e.MESSAGE_TYPE=Symbol.for(`protobuf-ts/message-type`)})),D_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.lowerCamelCase=void 0;function lowerCamelCase(e){let t=!1,n=[];for(let r=0;r{Object.defineProperty(e,"__esModule",{value:!0}),e.readMessageOption=e.readFieldOption=e.readFieldOptions=e.normalizeFieldInfo=e.RepeatType=e.LongType=e.ScalarType=void 0;let t=D_();(function(e){e[e.DOUBLE=1]=`DOUBLE`,e[e.FLOAT=2]=`FLOAT`,e[e.INT64=3]=`INT64`,e[e.UINT64=4]=`UINT64`,e[e.INT32=5]=`INT32`,e[e.FIXED64=6]=`FIXED64`,e[e.FIXED32=7]=`FIXED32`,e[e.BOOL=8]=`BOOL`,e[e.STRING=9]=`STRING`,e[e.BYTES=12]=`BYTES`,e[e.UINT32=13]=`UINT32`,e[e.SFIXED32=15]=`SFIXED32`,e[e.SFIXED64=16]=`SFIXED64`,e[e.SINT32=17]=`SINT32`,e[e.SINT64=18]=`SINT64`})(e.ScalarType||={}),(function(e){e[e.BIGINT=0]=`BIGINT`,e[e.STRING=1]=`STRING`,e[e.NUMBER=2]=`NUMBER`})(e.LongType||={});var n;(function(e){e[e.NO=0]=`NO`,e[e.PACKED=1]=`PACKED`,e[e.UNPACKED=2]=`UNPACKED`})(n=e.RepeatType||={});function normalizeFieldInfo(e){return e.localName=e.localName??t.lowerCamelCase(e.name),e.jsonName=e.jsonName??t.lowerCamelCase(e.name),e.repeat=e.repeat??n.NO,e.opt=e.opt??(!e.repeat&&!e.oneof&&e.kind==`message`),e}e.normalizeFieldInfo=normalizeFieldInfo;function readFieldOptions(e,t,n,r){let i=e.fields.find((e,n)=>e.localName==t||n==t)?.options;return i&&i[n]?r.fromJson(i[n]):void 0}e.readFieldOptions=readFieldOptions;function readFieldOption(e,t,n,r){let i=e.fields.find((e,n)=>e.localName==t||n==t)?.options;if(!i)return;let a=i[n];return a===void 0?a:r?r.fromJson(a):a}e.readFieldOption=readFieldOption;function readMessageOption(e,t,n){let r=e.options[t];return r===void 0?r:n?n.fromJson(r):r}e.readMessageOption=readMessageOption})),k_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSelectedOneofValue=e.clearOneofValue=e.setUnknownOneofValue=e.setOneofValue=e.getOneofValue=e.isOneofGroup=void 0;function isOneofGroup(e){if(typeof e!=`object`||!e||!e.hasOwnProperty(`oneofKind`))return!1;switch(typeof e.oneofKind){case`string`:return e[e.oneofKind]!==void 0&&Object.keys(e).length==2;case`undefined`:return Object.keys(e).length==1;default:return!1}}e.isOneofGroup=isOneofGroup;function getOneofValue(e,t){return e[t]}e.getOneofValue=getOneofValue;function setOneofValue(e,t,n){e.oneofKind!==void 0&&delete e[e.oneofKind],e.oneofKind=t,n!==void 0&&(e[t]=n)}e.setOneofValue=setOneofValue;function setUnknownOneofValue(e,t,n){e.oneofKind!==void 0&&delete e[e.oneofKind],e.oneofKind=t,n!==void 0&&t!==void 0&&(e[t]=n)}e.setUnknownOneofValue=setUnknownOneofValue;function clearOneofValue(e){e.oneofKind!==void 0&&delete e[e.oneofKind],e.oneofKind=void 0}e.clearOneofValue=clearOneofValue;function getSelectedOneofValue(e){if(e.oneofKind!==void 0)return e[e.oneofKind]}e.getSelectedOneofValue=getSelectedOneofValue})),A_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ReflectionTypeCheck=void 0;let t=O_(),n=k_();e.ReflectionTypeCheck=class{constructor(e){this.fields=e.fields??[]}prepare(){if(this.data)return;let e=[],t=[],n=[];for(let r of this.fields)if(r.oneof)n.includes(r.oneof)||(n.push(r.oneof),e.push(r.oneof),t.push(r.oneof));else switch(t.push(r.localName),r.kind){case`scalar`:case`enum`:(!r.opt||r.repeat)&&e.push(r.localName);break;case`message`:r.repeat&&e.push(r.localName);break;case`map`:e.push(r.localName)}this.data={req:e,known:t,oneofs:Object.values(n)}}is(e,t,r=!1){if(t<0)return!0;if(typeof e!=`object`||!e)return!1;this.prepare();let i=Object.keys(e),a=this.data;if(i.length!i.includes(e))||!r&&i.some(e=>!a.known.includes(e)))return!1;if(t<1)return!0;for(let i of a.oneofs){let a=e[i];if(!n.isOneofGroup(a))return!1;if(a.oneofKind===void 0)continue;let o=this.fields.find(e=>e.localName===a.oneofKind);if(!o||!this.field(a[a.oneofKind],o,r,t))return!1}for(let n of this.fields)if(n.oneof===void 0&&!this.field(e[n.localName],n,r,t))return!1;return!0}field(e,n,r,i){let a=n.repeat;switch(n.kind){case`scalar`:return e===void 0?n.opt:a?this.scalars(e,n.T,i,n.L):this.scalar(e,n.T,n.L);case`enum`:return e===void 0?n.opt:a?this.scalars(e,t.ScalarType.INT32,i):this.scalar(e,t.ScalarType.INT32);case`message`:return e===void 0?!0:a?this.messages(e,n.T(),r,i):this.message(e,n.T(),r,i);case`map`:if(typeof e!=`object`||!e)return!1;if(i<2)return!0;if(!this.mapKeys(e,n.K,i))return!1;switch(n.V.kind){case`scalar`:return this.scalars(Object.values(e),n.V.T,i,n.V.L);case`enum`:return this.scalars(Object.values(e),t.ScalarType.INT32,i);case`message`:return this.messages(Object.values(e),n.V.T(),r,i)}}return!0}message(e,t,n,r){return n?t.isAssignable(e,r):t.is(e,r)}messages(e,t,n,r){if(!Array.isArray(e))return!1;if(r<2)return!0;if(n){for(let n=0;nparseInt(e)),n,r);case t.ScalarType.BOOL:return this.scalars(i.slice(0,r).map(e=>e==`true`||e!=`false`&&e),n,r);default:return this.scalars(i,n,r,t.LongType.STRING)}}}})),j_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reflectionLongConvert=void 0;let t=O_();function reflectionLongConvert(e,n){switch(n){case t.LongType.BIGINT:return e.toBigInt();case t.LongType.NUMBER:return e.toNumber();default:return e.toString()}}e.reflectionLongConvert=reflectionLongConvert})),M_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ReflectionJsonReader=void 0;let t=g_(),n=__(),r=O_(),i=x_(),a=C_(),o=j_();e.ReflectionJsonReader=class{constructor(e){this.info=e}prepare(){if(this.fMap===void 0){this.fMap={};let e=this.info.fields??[];for(let t of e)this.fMap[t.name]=t,this.fMap[t.jsonName]=t,this.fMap[t.localName]=t}}assert(e,n,r){if(!e){let e=t.typeofJsonValue(r);throw(e==`number`||e==`boolean`)&&(e=r.toString()),Error(`Cannot parse JSON ${e} for ${this.info.typeName}#${n}`)}}read(e,n,i){this.prepare();let a=[];for(let[o,s]of Object.entries(e)){let e=this.fMap[o];if(!e){if(!i.ignoreUnknownFields)throw Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${o}`);continue}let c=e.localName,l;if(e.oneof){if(s===null&&(e.kind!==`enum`||e.T()[0]!==`google.protobuf.NullValue`))continue;if(a.includes(e.oneof))throw Error(`Multiple members of the oneof group "${e.oneof}" of ${this.info.typeName} are present in JSON.`);a.push(e.oneof),l=n[e.oneof]={oneofKind:c}}else l=n;if(e.kind==`map`){if(s===null)continue;this.assert(t.isJsonObject(s),e.name,s);let n=l[c];for(let[t,a]of Object.entries(s)){this.assert(a!==null,e.name+` map value`,null);let o;switch(e.V.kind){case`message`:o=e.V.T().internalJsonRead(a,i);break;case`enum`:if(o=this.enum(e.V.T(),a,e.name,i.ignoreUnknownFields),o===!1)continue;break;case`scalar`:o=this.scalar(a,e.V.T,e.V.L,e.name)}this.assert(o!==void 0,e.name+` map value`,a);let s=t;e.K==r.ScalarType.BOOL&&(s=s==`true`||s!=`false`&&s),s=this.scalar(s,e.K,r.LongType.STRING,e.name).toString(),n[s]=o}}else if(e.repeat){if(s===null)continue;this.assert(Array.isArray(s),e.name,s);let t=l[c];for(let n of s){this.assert(n!==null,e.name,null);let r;switch(e.kind){case`message`:r=e.T().internalJsonRead(n,i);break;case`enum`:if(r=this.enum(e.T(),n,e.name,i.ignoreUnknownFields),r===!1)continue;break;case`scalar`:r=this.scalar(n,e.T,e.L,e.name)}this.assert(r!==void 0,e.name,s),t.push(r)}}else switch(e.kind){case`message`:if(s===null&&e.T().typeName!=`google.protobuf.Value`){this.assert(e.oneof===void 0,e.name+` (oneof member)`,null);continue}l[c]=e.T().internalJsonRead(s,i,l[c]);break;case`enum`:if(s===null)continue;let t=this.enum(e.T(),s,e.name,i.ignoreUnknownFields);if(t===!1)continue;l[c]=t;break;case`scalar`:if(s===null)continue;l[c]=this.scalar(s,e.T,e.L,e.name)}}}enum(e,t,n,r){if(e[0]==`google.protobuf.NullValue`&&a.assert(t===null||t===`NULL_VALUE`,`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} only accepts null.`),t===null)return 0;switch(typeof t){case`number`:return a.assert(Number.isInteger(t),`Unable to parse field ${this.info.typeName}#${n}, enum can only be integral number, got ${t}.`),t;case`string`:let i=t;e[2]&&t.substring(0,e[2].length)===e[2]&&(i=t.substring(e[2].length));let o=e[1][i];return o===void 0&&r?!1:(a.assert(typeof o==`number`,`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} has no value for "${t}".`),o)}a.assert(!1,`Unable to parse field ${this.info.typeName}#${n}, cannot parse enum value from ${typeof t}".`)}scalar(e,t,s,c){let l;try{switch(t){case r.ScalarType.DOUBLE:case r.ScalarType.FLOAT:if(e===null)return 0;if(e===`NaN`)return NaN;if(e===`Infinity`)return 1/0;if(e===`-Infinity`)return-1/0;if(e===``){l=`empty string`;break}if(typeof e==`string`&&e.trim().length!==e.length){l=`extra whitespace`;break}if(typeof e!=`string`&&typeof e!=`number`)break;let c=Number(e);if(Number.isNaN(c)){l=`not a number`;break}if(!Number.isFinite(c)){l=`too large or small`;break}return t==r.ScalarType.FLOAT&&a.assertFloat32(c),c;case r.ScalarType.INT32:case r.ScalarType.FIXED32:case r.ScalarType.SFIXED32:case r.ScalarType.SINT32:case r.ScalarType.UINT32:if(e===null)return 0;let u;if(typeof e==`number`?u=e:e===``?l=`empty string`:typeof e==`string`&&(e.trim().length===e.length?u=Number(e):l=`extra whitespace`),u===void 0)break;return t==r.ScalarType.UINT32?a.assertUInt32(u):a.assertInt32(u),u;case r.ScalarType.INT64:case r.ScalarType.SFIXED64:case r.ScalarType.SINT64:if(e===null)return o.reflectionLongConvert(i.PbLong.ZERO,s);if(typeof e!=`number`&&typeof e!=`string`)break;return o.reflectionLongConvert(i.PbLong.from(e),s);case r.ScalarType.FIXED64:case r.ScalarType.UINT64:if(e===null)return o.reflectionLongConvert(i.PbULong.ZERO,s);if(typeof e!=`number`&&typeof e!=`string`)break;return o.reflectionLongConvert(i.PbULong.from(e),s);case r.ScalarType.BOOL:if(e===null)return!1;if(typeof e!=`boolean`)break;return e;case r.ScalarType.STRING:if(e===null)return``;if(typeof e!=`string`){l=`extra whitespace`;break}return e;case r.ScalarType.BYTES:if(e===null||e===``)return new Uint8Array;if(typeof e!=`string`)break;return n.base64decode(e)}}catch(e){l=e.message}this.assert(!1,c+(l?` - `+l:``),e)}}})),N_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ReflectionJsonWriter=void 0;let t=__(),n=x_(),r=O_(),i=C_();e.ReflectionJsonWriter=class{constructor(e){this.fields=e.fields??[]}write(e,t){let n={},r=e;for(let e of this.fields){if(!e.oneof){let i=this.field(e,r[e.localName],t);i!==void 0&&(n[t.useProtoFieldName?e.name:e.jsonName]=i);continue}let a=r[e.oneof];if(a.oneofKind!==e.localName)continue;let o=e.kind==`scalar`||e.kind==`enum`?Object.assign(Object.assign({},t),{emitDefaultValues:!0}):t,s=this.field(e,a[e.localName],o);i.assert(s!==void 0),n[t.useProtoFieldName?e.name:e.jsonName]=s}return n}field(e,t,n){let r;if(e.kind==`map`){i.assert(typeof t==`object`&&!!t);let a={};switch(e.V.kind){case`scalar`:for(let[n,r]of Object.entries(t)){let t=this.scalar(e.V.T,r,e.name,!1,!0);i.assert(t!==void 0),a[n.toString()]=t}break;case`message`:let r=e.V.T();for(let[o,s]of Object.entries(t)){let t=this.message(r,s,e.name,n);i.assert(t!==void 0),a[o.toString()]=t}break;case`enum`:let o=e.V.T();for(let[r,s]of Object.entries(t)){i.assert(s===void 0||typeof s==`number`);let t=this.enum(o,s,e.name,!1,!0,n.enumAsInteger);i.assert(t!==void 0),a[r.toString()]=t}}(n.emitDefaultValues||Object.keys(a).length>0)&&(r=a)}else if(e.repeat){i.assert(Array.isArray(t));let a=[];switch(e.kind){case`scalar`:for(let n=0;n0||n.emitDefaultValues)&&(r=a)}else switch(e.kind){case`scalar`:r=this.scalar(e.T,t,e.name,e.opt,n.emitDefaultValues);break;case`enum`:r=this.enum(e.T(),t,e.name,e.opt,n.emitDefaultValues,n.enumAsInteger);break;case`message`:r=this.message(e.T(),t,e.name,n)}return r}enum(e,t,n,r,a,o){if(e[0]==`google.protobuf.NullValue`)return!a&&!r?void 0:null;if(t===void 0){i.assert(r);return}if(t!==0||a||r)return i.assert(typeof t==`number`),i.assert(Number.isInteger(t)),o||!e[1].hasOwnProperty(t)?t:e[2]?e[2]+e[1][t]:e[1][t]}message(e,t,n,r){return t===void 0?r.emitDefaultValues?null:void 0:e.internalJsonWrite(t,r)}scalar(e,a,o,s,c){if(a===void 0){i.assert(s);return}let l=c||s;switch(e){case r.ScalarType.INT32:case r.ScalarType.SFIXED32:case r.ScalarType.SINT32:return a===0?l?0:void 0:(i.assertInt32(a),a);case r.ScalarType.FIXED32:case r.ScalarType.UINT32:return a===0?l?0:void 0:(i.assertUInt32(a),a);case r.ScalarType.FLOAT:i.assertFloat32(a);case r.ScalarType.DOUBLE:return a===0?l?0:void 0:(i.assert(typeof a==`number`),Number.isNaN(a)?`NaN`:a===1/0?`Infinity`:a===-1/0?`-Infinity`:a);case r.ScalarType.STRING:return a===``?l?``:void 0:(i.assert(typeof a==`string`),a);case r.ScalarType.BOOL:return a===!1?!l&&void 0:(i.assert(typeof a==`boolean`),a);case r.ScalarType.UINT64:case r.ScalarType.FIXED64:i.assert(typeof a==`number`||typeof a==`string`||typeof a==`bigint`);let e=n.PbULong.from(a);return e.isZero()&&!l?void 0:e.toString();case r.ScalarType.INT64:case r.ScalarType.SFIXED64:case r.ScalarType.SINT64:i.assert(typeof a==`number`||typeof a==`string`||typeof a==`bigint`);let o=n.PbLong.from(a);return o.isZero()&&!l?void 0:o.toString();case r.ScalarType.BYTES:return i.assert(a instanceof Uint8Array),a.byteLength?t.base64encode(a):l?``:void 0}}}})),P_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reflectionScalarDefault=void 0;let t=O_(),n=j_(),r=x_();function reflectionScalarDefault(e,i=t.LongType.STRING){switch(e){case t.ScalarType.BOOL:return!1;case t.ScalarType.UINT64:case t.ScalarType.FIXED64:return n.reflectionLongConvert(r.PbULong.ZERO,i);case t.ScalarType.INT64:case t.ScalarType.SFIXED64:case t.ScalarType.SINT64:return n.reflectionLongConvert(r.PbLong.ZERO,i);case t.ScalarType.DOUBLE:case t.ScalarType.FLOAT:return 0;case t.ScalarType.BYTES:return new Uint8Array;case t.ScalarType.STRING:return``;default:return 0}}e.reflectionScalarDefault=reflectionScalarDefault})),F_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ReflectionBinaryReader=void 0;let t=y_(),n=O_(),r=j_(),i=P_();e.ReflectionBinaryReader=class{constructor(e){this.info=e}prepare(){if(!this.fieldNoToField){let e=this.info.fields??[];this.fieldNoToField=new Map(e.map(e=>[e.no,e]))}}read(e,r,i,a){this.prepare();let o=a===void 0?e.len:e.pos+a;for(;e.pos{Object.defineProperty(e,"__esModule",{value:!0}),e.ReflectionBinaryWriter=void 0;let t=y_(),n=O_(),r=C_(),i=x_();e.ReflectionBinaryWriter=class{constructor(e){this.info=e}prepare(){if(!this.fields){let e=this.info.fields?this.info.fields.concat():[];this.fields=e.sort((e,t)=>e.no-t.no)}}write(e,i,a){this.prepare();for(let t of this.fields){let o,s,c=t.repeat,l=t.localName;if(t.oneof){let n=e[t.oneof];if(n.oneofKind!==l)continue;o=n[l],s=!0}else o=e[l],s=!1;switch(t.kind){case`scalar`:case`enum`:let e=t.kind==`enum`?n.ScalarType.INT32:t.T;if(c){if(r.assert(Array.isArray(o)),c==n.RepeatType.PACKED)this.packed(i,e,t.no,o);else for(let n of o)this.scalar(i,e,t.no,n,!0)}else o===void 0?r.assert(t.opt):this.scalar(i,e,t.no,o,s||t.opt);break;case`message`:if(c){r.assert(Array.isArray(o));for(let e of o)this.message(i,a,t.T(),t.no,e)}else this.message(i,a,t.T(),t.no,o);break;case`map`:r.assert(typeof o==`object`&&!!o);for(let[e,n]of Object.entries(o))this.mapEntry(i,a,t,e,n)}}let o=a.writeUnknownFields;o!==!1&&(o===!0?t.UnknownFieldHandler.onWrite:o)(this.info.typeName,e,i)}mapEntry(e,i,a,o,s){e.tag(a.no,t.WireType.LengthDelimited),e.fork();let c=o;switch(a.K){case n.ScalarType.INT32:case n.ScalarType.FIXED32:case n.ScalarType.UINT32:case n.ScalarType.SFIXED32:case n.ScalarType.SINT32:c=Number.parseInt(o);break;case n.ScalarType.BOOL:r.assert(o==`true`||o==`false`),c=o==`true`}switch(this.scalar(e,a.K,1,c,!0),a.V.kind){case`scalar`:this.scalar(e,a.V.T,2,s,!0);break;case`enum`:this.scalar(e,n.ScalarType.INT32,2,s,!0);break;case`message`:this.message(e,i,a.V.T(),2,s)}e.join()}message(e,n,r,i,a){a!==void 0&&(r.internalBinaryWrite(a,e.tag(i,t.WireType.LengthDelimited).fork(),n),e.join())}scalar(e,t,n,r,i){let[a,o,s]=this.scalarInfo(t,r);(!s||i)&&(e.tag(n,a),e[o](r))}packed(e,i,a,o){if(!o.length)return;r.assert(i!==n.ScalarType.BYTES&&i!==n.ScalarType.STRING),e.tag(a,t.WireType.LengthDelimited),e.fork();let[,s]=this.scalarInfo(i);for(let t=0;t{Object.defineProperty(e,"__esModule",{value:!0}),e.reflectionCreate=void 0;let t=P_(),n=E_();function reflectionCreate(e){let r=e.messagePrototype?Object.create(e.messagePrototype):Object.defineProperty({},n.MESSAGE_TYPE,{value:e});for(let n of e.fields){let e=n.localName;if(!n.opt){if(n.oneof)r[n.oneof]={oneofKind:void 0};else if(n.repeat)r[e]=[];else switch(n.kind){case`scalar`:r[e]=t.reflectionScalarDefault(n.T,n.L);break;case`enum`:r[e]=0;break;case`map`:r[e]={}}}}return r}e.reflectionCreate=reflectionCreate})),R_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reflectionMergePartial=void 0;function reflectionMergePartial(e,t,n){let r,i=n,a;for(let n of e.fields){let e=n.localName;if(n.oneof){let o=i[n.oneof];if(o?.oneofKind==null)continue;if(r=o[e],a=t[n.oneof],a.oneofKind=o.oneofKind,r==null){delete a[e];continue}}else if(r=i[e],a=t,r==null)continue;switch(n.repeat&&(a[e].length=r.length),n.kind){case`scalar`:case`enum`:if(n.repeat)for(let t=0;t{Object.defineProperty(e,"__esModule",{value:!0}),e.reflectionEquals=void 0;let t=O_();function reflectionEquals(e,r,i){if(r===i)return!0;if(!r||!i)return!1;for(let a of e.fields){let e=a.localName,o=a.oneof?r[a.oneof][e]:r[e],s=a.oneof?i[a.oneof][e]:i[e];switch(a.kind){case`enum`:case`scalar`:let e=a.kind==`enum`?t.ScalarType.INT32:a.T;if(!(a.repeat?repeatedPrimitiveEq(e,o,s):primitiveEq(e,o,s)))return!1;break;case`map`:if(!(a.V.kind==`message`?repeatedMsgEq(a.V.T(),n(o),n(s)):repeatedPrimitiveEq(a.V.kind==`enum`?t.ScalarType.INT32:a.V.T,n(o),n(s))))return!1;break;case`message`:let r=a.T();if(!(a.repeat?repeatedMsgEq(r,o,s):r.equals(o,s)))return!1}}return!0}e.reflectionEquals=reflectionEquals;let n=Object.values;function primitiveEq(e,n,r){if(n===r)return!0;if(e!==t.ScalarType.BYTES)return!1;let i=n,a=r;if(i.length!==a.length)return!1;for(let e=0;e{Object.defineProperty(e,"__esModule",{value:!0}),e.MessageType=void 0;let t=E_(),n=O_(),r=A_(),i=M_(),a=N_(),o=F_(),s=I_(),c=L_(),l=R_(),u=g_(),d=T_(),f=z_(),p=w_(),h=S_(),g=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})),v=g[t.MESSAGE_TYPE]={};e.MessageType=class{constructor(e,t,c){this.defaultCheckDepth=16,this.typeName=e,this.fields=t.map(n.normalizeFieldInfo),this.options=c??{},v.value=this,this.messagePrototype=Object.create(null,g),this.refTypeCheck=new r.ReflectionTypeCheck(this),this.refJsonReader=new i.ReflectionJsonReader(this),this.refJsonWriter=new a.ReflectionJsonWriter(this),this.refBinReader=new o.ReflectionBinaryReader(this),this.refBinWriter=new s.ReflectionBinaryWriter(this)}create(e){let t=c.reflectionCreate(this);return e!==void 0&&l.reflectionMergePartial(this,t,e),t}clone(e){let t=this.create();return l.reflectionMergePartial(this,t,e),t}equals(e,t){return f.reflectionEquals(this,e,t)}is(e,t=this.defaultCheckDepth){return this.refTypeCheck.is(e,t,!1)}isAssignable(e,t=this.defaultCheckDepth){return this.refTypeCheck.is(e,t,!0)}mergePartial(e,t){l.reflectionMergePartial(this,e,t)}fromBinary(e,t){let n=h.binaryReadOptions(t);return this.internalBinaryRead(n.readerFactory(e),e.byteLength,n)}fromJson(e,t){return this.internalJsonRead(e,d.jsonReadOptions(t))}fromJsonString(e,t){let n=JSON.parse(e);return this.fromJson(n,t)}toJson(e,t){return this.internalJsonWrite(e,d.jsonWriteOptions(t))}toJsonString(e,t){let n=this.toJson(e,t);return JSON.stringify(n,null,t?.prettySpaces??0)}toBinary(e,t){let n=p.binaryWriteOptions(t);return this.internalBinaryWrite(e,n.writerFactory(),n).finish()}internalJsonRead(e,t,n){if(typeof e==`object`&&e&&!Array.isArray(e)){let r=n??this.create();return this.refJsonReader.read(e,r,t),r}throw Error(`Unable to parse message ${this.typeName} from JSON ${u.typeofJsonValue(e)}.`)}internalJsonWrite(e,t){return this.refJsonWriter.write(e,t)}internalBinaryWrite(e,t,n){return this.refBinWriter.write(e,t,n),t}internalBinaryRead(e,t,n,r){let i=r??this.create();return this.refBinReader.read(e,i,n,t),i}}})),V_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.containsMessageType=void 0;let t=E_();function containsMessageType(e){return e[t.MESSAGE_TYPE]!=null}e.containsMessageType=containsMessageType})),H_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.listEnumNumbers=e.listEnumNames=e.listEnumValues=e.isEnumObject=void 0;function isEnumObject(e){if(typeof e!=`object`||!e||!e.hasOwnProperty(0))return!1;for(let t of Object.keys(e)){let n=parseInt(t);if(Number.isNaN(n)){let n=e[t];if(n===void 0||typeof n!=`number`||e[n]===void 0)return!1}else{let t=e[n];if(t===void 0||e[t]!==n)return!1}}return!0}e.isEnumObject=isEnumObject;function listEnumValues(e){if(!isEnumObject(e))throw Error(`not a typescript enum object`);let t=[];for(let[n,r]of Object.entries(e))typeof r==`number`&&t.push({name:n,number:r});return t}e.listEnumValues=listEnumValues;function listEnumNames(e){return listEnumValues(e).map(e=>e.name)}e.listEnumNames=listEnumNames;function listEnumNumbers(e){return listEnumValues(e).map(e=>e.number).filter((e,t,n)=>n.indexOf(e)==t)}e.listEnumNumbers=listEnumNumbers})),U_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=g_();Object.defineProperty(e,"typeofJsonValue",{enumerable:!0,get:function(){return t.typeofJsonValue}}),Object.defineProperty(e,"isJsonObject",{enumerable:!0,get:function(){return t.isJsonObject}});var n=__();Object.defineProperty(e,"base64decode",{enumerable:!0,get:function(){return n.base64decode}}),Object.defineProperty(e,"base64encode",{enumerable:!0,get:function(){return n.base64encode}});var r=v_();Object.defineProperty(e,"utf8read",{enumerable:!0,get:function(){return r.utf8read}});var i=y_();Object.defineProperty(e,"WireType",{enumerable:!0,get:function(){return i.WireType}}),Object.defineProperty(e,"mergeBinaryOptions",{enumerable:!0,get:function(){return i.mergeBinaryOptions}}),Object.defineProperty(e,"UnknownFieldHandler",{enumerable:!0,get:function(){return i.UnknownFieldHandler}});var a=S_();Object.defineProperty(e,"BinaryReader",{enumerable:!0,get:function(){return a.BinaryReader}}),Object.defineProperty(e,"binaryReadOptions",{enumerable:!0,get:function(){return a.binaryReadOptions}});var o=w_();Object.defineProperty(e,"BinaryWriter",{enumerable:!0,get:function(){return o.BinaryWriter}}),Object.defineProperty(e,"binaryWriteOptions",{enumerable:!0,get:function(){return o.binaryWriteOptions}});var s=x_();Object.defineProperty(e,"PbLong",{enumerable:!0,get:function(){return s.PbLong}}),Object.defineProperty(e,"PbULong",{enumerable:!0,get:function(){return s.PbULong}});var c=T_();Object.defineProperty(e,"jsonReadOptions",{enumerable:!0,get:function(){return c.jsonReadOptions}}),Object.defineProperty(e,"jsonWriteOptions",{enumerable:!0,get:function(){return c.jsonWriteOptions}}),Object.defineProperty(e,"mergeJsonOptions",{enumerable:!0,get:function(){return c.mergeJsonOptions}});var l=E_();Object.defineProperty(e,"MESSAGE_TYPE",{enumerable:!0,get:function(){return l.MESSAGE_TYPE}});var u=B_();Object.defineProperty(e,"MessageType",{enumerable:!0,get:function(){return u.MessageType}});var d=O_();Object.defineProperty(e,"ScalarType",{enumerable:!0,get:function(){return d.ScalarType}}),Object.defineProperty(e,"LongType",{enumerable:!0,get:function(){return d.LongType}}),Object.defineProperty(e,"RepeatType",{enumerable:!0,get:function(){return d.RepeatType}}),Object.defineProperty(e,"normalizeFieldInfo",{enumerable:!0,get:function(){return d.normalizeFieldInfo}}),Object.defineProperty(e,"readFieldOptions",{enumerable:!0,get:function(){return d.readFieldOptions}}),Object.defineProperty(e,"readFieldOption",{enumerable:!0,get:function(){return d.readFieldOption}}),Object.defineProperty(e,"readMessageOption",{enumerable:!0,get:function(){return d.readMessageOption}});var f=A_();Object.defineProperty(e,"ReflectionTypeCheck",{enumerable:!0,get:function(){return f.ReflectionTypeCheck}});var p=L_();Object.defineProperty(e,"reflectionCreate",{enumerable:!0,get:function(){return p.reflectionCreate}});var h=P_();Object.defineProperty(e,"reflectionScalarDefault",{enumerable:!0,get:function(){return h.reflectionScalarDefault}});var g=R_();Object.defineProperty(e,"reflectionMergePartial",{enumerable:!0,get:function(){return g.reflectionMergePartial}});var v=z_();Object.defineProperty(e,"reflectionEquals",{enumerable:!0,get:function(){return v.reflectionEquals}});var y=F_();Object.defineProperty(e,"ReflectionBinaryReader",{enumerable:!0,get:function(){return y.ReflectionBinaryReader}});var b=I_();Object.defineProperty(e,"ReflectionBinaryWriter",{enumerable:!0,get:function(){return b.ReflectionBinaryWriter}});var x=M_();Object.defineProperty(e,"ReflectionJsonReader",{enumerable:!0,get:function(){return x.ReflectionJsonReader}});var S=N_();Object.defineProperty(e,"ReflectionJsonWriter",{enumerable:!0,get:function(){return S.ReflectionJsonWriter}});var C=V_();Object.defineProperty(e,"containsMessageType",{enumerable:!0,get:function(){return C.containsMessageType}});var w=k_();Object.defineProperty(e,"isOneofGroup",{enumerable:!0,get:function(){return w.isOneofGroup}}),Object.defineProperty(e,"setOneofValue",{enumerable:!0,get:function(){return w.setOneofValue}}),Object.defineProperty(e,"getOneofValue",{enumerable:!0,get:function(){return w.getOneofValue}}),Object.defineProperty(e,"clearOneofValue",{enumerable:!0,get:function(){return w.clearOneofValue}}),Object.defineProperty(e,"getSelectedOneofValue",{enumerable:!0,get:function(){return w.getSelectedOneofValue}});var T=H_();Object.defineProperty(e,"listEnumValues",{enumerable:!0,get:function(){return T.listEnumValues}}),Object.defineProperty(e,"listEnumNames",{enumerable:!0,get:function(){return T.listEnumNames}}),Object.defineProperty(e,"listEnumNumbers",{enumerable:!0,get:function(){return T.listEnumNumbers}}),Object.defineProperty(e,"isEnumObject",{enumerable:!0,get:function(){return T.isEnumObject}});var E=D_();Object.defineProperty(e,"lowerCamelCase",{enumerable:!0,get:function(){return E.lowerCamelCase}});var D=C_();Object.defineProperty(e,"assert",{enumerable:!0,get:function(){return D.assert}}),Object.defineProperty(e,"assertNever",{enumerable:!0,get:function(){return D.assertNever}}),Object.defineProperty(e,"assertInt32",{enumerable:!0,get:function(){return D.assertInt32}}),Object.defineProperty(e,"assertUInt32",{enumerable:!0,get:function(){return D.assertUInt32}}),Object.defineProperty(e,"assertFloat32",{enumerable:!0,get:function(){return D.assertFloat32}})})),W_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.readServiceOption=e.readMethodOption=e.readMethodOptions=e.normalizeMethodInfo=void 0;let t=U_();function normalizeMethodInfo(e,n){let r=e;return r.service=n,r.localName=r.localName??t.lowerCamelCase(r.name),r.serverStreaming=!!r.serverStreaming,r.clientStreaming=!!r.clientStreaming,r.options=r.options??{},r.idempotency=r.idempotency??void 0,r}e.normalizeMethodInfo=normalizeMethodInfo;function readMethodOptions(e,t,n,r){let i=e.methods.find((e,n)=>e.localName===t||n===t)?.options;return i&&i[n]?r.fromJson(i[n]):void 0}e.readMethodOptions=readMethodOptions;function readMethodOption(e,t,n,r){let i=e.methods.find((e,n)=>e.localName===t||n===t)?.options;if(!i)return;let a=i[n];return a===void 0?a:r?r.fromJson(a):a}e.readMethodOption=readMethodOption;function readServiceOption(e,t,n){let r=e.options;if(!r)return;let i=r[t];return i===void 0?i:n?n.fromJson(i):i}e.readServiceOption=readServiceOption})),G_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ServiceType=void 0;let t=W_();e.ServiceType=class{constructor(e,n,r){this.typeName=e,this.methods=n.map(e=>t.normalizeMethodInfo(e,this)),this.options=r??{}}}})),K_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.RpcError=void 0,e.RpcError=class extends Error{constructor(e,t=`UNKNOWN`,n){super(e),this.name=`RpcError`,Object.setPrototypeOf(this,new.target.prototype),this.code=t,this.meta=n??{}}toString(){let e=[this.name+`: `+this.message];this.code&&(e.push(``),e.push(`Code: `+this.code)),this.serviceName&&this.methodName&&e.push(`Method: `+this.serviceName+`/`+this.methodName);let t=Object.entries(this.meta);if(t.length){e.push(``),e.push(`Meta:`);for(let[n,r]of t)e.push(` ${n}: ${r}`)}return e.join(` `)}}})),q_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.mergeRpcOptions=void 0;let t=U_();function mergeRpcOptions(e,n){if(!n)return e;let r={};copy(e,r),copy(n,r);for(let i of Object.keys(n)){let a=n[i];switch(i){case`jsonOptions`:r.jsonOptions=t.mergeJsonOptions(e.jsonOptions,r.jsonOptions);break;case`binaryOptions`:r.binaryOptions=t.mergeBinaryOptions(e.binaryOptions,r.binaryOptions);break;case`meta`:r.meta={},copy(e.meta,r.meta),copy(n.meta,r.meta);break;case`interceptors`:r.interceptors=e.interceptors?e.interceptors.concat(a):a.concat()}}return r}e.mergeRpcOptions=mergeRpcOptions;function copy(e,t){if(!e)return;let n=t;for(let[t,r]of Object.entries(e))n[t]=r instanceof Date?new Date(r.getTime()):Array.isArray(r)?r.concat():r}})),J_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Deferred=e.DeferredState=void 0;var t;(function(e){e[e.PENDING=0]=`PENDING`,e[e.REJECTED=1]=`REJECTED`,e[e.RESOLVED=2]=`RESOLVED`})(t=e.DeferredState||={}),e.Deferred=class{constructor(e=!0){this._state=t.PENDING,this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t}),e&&this._promise.catch(e=>{})}get state(){return this._state}get promise(){return this._promise}resolve(e){if(this.state!==t.PENDING)throw Error(`cannot resolve ${t[this.state].toLowerCase()}`);this._resolve(e),this._state=t.RESOLVED}reject(e){if(this.state!==t.PENDING)throw Error(`cannot reject ${t[this.state].toLowerCase()}`);this._reject(e),this._state=t.REJECTED}resolvePending(e){this._state===t.PENDING&&this.resolve(e)}rejectPending(e){this._state===t.PENDING&&this.reject(e)}}})),Y_=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.RpcOutputStreamController=void 0;let t=J_(),n=U_();e.RpcOutputStreamController=class{constructor(){this._lis={nxt:[],msg:[],err:[],cmp:[]},this._closed=!1,this._itState={q:[]}}onNext(e){return this.addLis(e,this._lis.nxt)}onMessage(e){return this.addLis(e,this._lis.msg)}onError(e){return this.addLis(e,this._lis.err)}onComplete(e){return this.addLis(e,this._lis.cmp)}addLis(e,t){return t.push(e),()=>{let n=t.indexOf(e);n>=0&&t.splice(n,1)}}clearLis(){for(let e of Object.values(this._lis))e.splice(0,e.length)}get closed(){return this._closed!==!1}notifyNext(e,t,r){n.assert(+!!e+ +!!t+ +!!r<=1,`only one emission at a time`),e&&this.notifyMessage(e),t&&this.notifyError(t),r&&this.notifyComplete()}notifyMessage(e){n.assert(!this.closed,`stream is closed`),this.pushIt({value:e,done:!1}),this._lis.msg.forEach(t=>t(e)),this._lis.nxt.forEach(t=>t(e,void 0,!1))}notifyError(e){n.assert(!this.closed,`stream is closed`),this._closed=e,this.pushIt(e),this._lis.err.forEach(t=>t(e)),this._lis.nxt.forEach(t=>t(void 0,e,!1)),this.clearLis()}notifyComplete(){n.assert(!this.closed,`stream is closed`),this._closed=!0,this.pushIt({value:null,done:!0}),this._lis.cmp.forEach(e=>e()),this._lis.nxt.forEach(e=>e(void 0,void 0,!0)),this.clearLis()}[Symbol.asyncIterator](){return this._closed===!0?this.pushIt({value:null,done:!0}):this._closed!==!1&&this.pushIt(this._closed),{next:()=>{let e=this._itState;n.assert(e,`bad state`),n.assert(!e.p,`iterator contract broken`);let r=e.q.shift();return r?`value`in r?Promise.resolve(r):Promise.reject(r):(e.p=new t.Deferred,e.p.promise)}}}pushIt(e){let r=this._itState;if(r.p){let i=r.p;n.assert(i.state==t.DeferredState.PENDING,`iterator contract broken`),`value`in e?i.resolve(e):i.reject(e),delete r.p}else r.q.push(e)}}})),X_=__commonJSMin((e=>{var t=e&&e.__awaiter||function(e,t,n,r){function adopt(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.UnaryCall=void 0,e.UnaryCall=class{constructor(e,t,n,r,i,a,o){this.method=e,this.requestHeaders=t,this.request=n,this.headers=r,this.response=i,this.status=a,this.trailers=o}then(e,t){return this.promiseFinished().then(t=>e?Promise.resolve(e(t)):t,e=>t?Promise.resolve(t(e)):Promise.reject(e))}promiseFinished(){return t(this,void 0,void 0,function*(){let[e,t,n,r]=yield Promise.all([this.headers,this.response,this.status,this.trailers]);return{method:this.method,requestHeaders:this.requestHeaders,request:this.request,headers:e,response:t,status:n,trailers:r}})}}})),Z_=__commonJSMin((e=>{var t=e&&e.__awaiter||function(e,t,n,r){function adopt(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.ServerStreamingCall=void 0,e.ServerStreamingCall=class{constructor(e,t,n,r,i,a,o){this.method=e,this.requestHeaders=t,this.request=n,this.headers=r,this.responses=i,this.status=a,this.trailers=o}then(e,t){return this.promiseFinished().then(t=>e?Promise.resolve(e(t)):t,e=>t?Promise.resolve(t(e)):Promise.reject(e))}promiseFinished(){return t(this,void 0,void 0,function*(){let[e,t,n]=yield Promise.all([this.headers,this.status,this.trailers]);return{method:this.method,requestHeaders:this.requestHeaders,request:this.request,headers:e,status:t,trailers:n}})}}})),Q_=__commonJSMin((e=>{var t=e&&e.__awaiter||function(e,t,n,r){function adopt(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.ClientStreamingCall=void 0,e.ClientStreamingCall=class{constructor(e,t,n,r,i,a,o){this.method=e,this.requestHeaders=t,this.requests=n,this.headers=r,this.response=i,this.status=a,this.trailers=o}then(e,t){return this.promiseFinished().then(t=>e?Promise.resolve(e(t)):t,e=>t?Promise.resolve(t(e)):Promise.reject(e))}promiseFinished(){return t(this,void 0,void 0,function*(){let[e,t,n,r]=yield Promise.all([this.headers,this.response,this.status,this.trailers]);return{method:this.method,requestHeaders:this.requestHeaders,headers:e,response:t,status:n,trailers:r}})}}})),$_=__commonJSMin((e=>{var t=e&&e.__awaiter||function(e,t,n,r){function adopt(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.DuplexStreamingCall=void 0,e.DuplexStreamingCall=class{constructor(e,t,n,r,i,a,o){this.method=e,this.requestHeaders=t,this.requests=n,this.headers=r,this.responses=i,this.status=a,this.trailers=o}then(e,t){return this.promiseFinished().then(t=>e?Promise.resolve(e(t)):t,e=>t?Promise.resolve(t(e)):Promise.reject(e))}promiseFinished(){return t(this,void 0,void 0,function*(){let[e,t,n]=yield Promise.all([this.headers,this.status,this.trailers]);return{method:this.method,requestHeaders:this.requestHeaders,headers:e,status:t,trailers:n}})}}})),ev=__commonJSMin((e=>{var t=e&&e.__awaiter||function(e,t,n,r){function adopt(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.TestTransport=void 0;let n=K_(),r=U_(),i=Y_(),a=q_(),o=X_(),s=Z_(),c=Q_(),l=$_();var u=class TestTransport{constructor(e){this.suppressUncaughtRejections=!0,this.headerDelay=10,this.responseDelay=50,this.betweenResponseDelay=10,this.afterResponseDelay=10,this.data=e??{}}get sentMessages(){return this.lastInput instanceof TestInputStream?this.lastInput.sent:typeof this.lastInput==`object`?[this.lastInput.single]:[]}get sendComplete(){return this.lastInput instanceof TestInputStream?this.lastInput.completed:typeof this.lastInput==`object`}promiseHeaders(){let e=this.data.headers??TestTransport.defaultHeaders;return e instanceof n.RpcError?Promise.reject(e):Promise.resolve(e)}promiseSingleResponse(e){if(this.data.response instanceof n.RpcError)return Promise.reject(this.data.response);let t;return Array.isArray(this.data.response)?(r.assert(this.data.response.length>0),t=this.data.response[0]):t=this.data.response===void 0?e.O.create():this.data.response,r.assert(e.O.is(t)),Promise.resolve(t)}streamResponses(e,i,a){return t(this,void 0,void 0,function*(){let t=[];if(this.data.response===void 0)t.push(e.O.create());else if(Array.isArray(this.data.response))for(let n of this.data.response)r.assert(e.O.is(n)),t.push(n);else this.data.response instanceof n.RpcError||(r.assert(e.O.is(this.data.response)),t.push(this.data.response));try{yield delay(this.responseDelay,a)(void 0)}catch(e){i.notifyError(e);return}if(this.data.response instanceof n.RpcError){i.notifyError(this.data.response);return}for(let e of t){i.notifyMessage(e);try{yield delay(this.betweenResponseDelay,a)(void 0)}catch(e){i.notifyError(e);return}}if(this.data.status instanceof n.RpcError){i.notifyError(this.data.status);return}if(this.data.trailers instanceof n.RpcError){i.notifyError(this.data.trailers);return}i.notifyComplete()})}promiseStatus(){let e=this.data.status??TestTransport.defaultStatus;return e instanceof n.RpcError?Promise.reject(e):Promise.resolve(e)}promiseTrailers(){let e=this.data.trailers??TestTransport.defaultTrailers;return e instanceof n.RpcError?Promise.reject(e):Promise.resolve(e)}maybeSuppressUncaught(...e){if(this.suppressUncaughtRejections)for(let t of e)t.catch(()=>{})}mergeOptions(e){return a.mergeRpcOptions({},e)}unary(e,t,n){let r=n.meta??{},i=this.promiseHeaders().then(delay(this.headerDelay,n.abort)),a=i.catch(e=>{}).then(delay(this.responseDelay,n.abort)).then(t=>this.promiseSingleResponse(e)),s=a.catch(e=>{}).then(delay(this.afterResponseDelay,n.abort)).then(e=>this.promiseStatus()),c=a.catch(e=>{}).then(delay(this.afterResponseDelay,n.abort)).then(e=>this.promiseTrailers());return this.maybeSuppressUncaught(s,c),this.lastInput={single:t},new o.UnaryCall(e,r,t,i,a,s,c)}serverStreaming(e,t,n){let r=n.meta??{},a=this.promiseHeaders().then(delay(this.headerDelay,n.abort)),o=new i.RpcOutputStreamController,c=a.then(delay(this.responseDelay,n.abort)).catch(()=>{}).then(()=>this.streamResponses(e,o,n.abort)).then(delay(this.afterResponseDelay,n.abort)),l=c.then(()=>this.promiseStatus()),u=c.then(()=>this.promiseTrailers());return this.maybeSuppressUncaught(l,u),this.lastInput={single:t},new s.ServerStreamingCall(e,r,t,a,o,l,u)}clientStreaming(e,t){let n=t.meta??{},r=this.promiseHeaders().then(delay(this.headerDelay,t.abort)),i=r.catch(e=>{}).then(delay(this.responseDelay,t.abort)).then(t=>this.promiseSingleResponse(e)),a=i.catch(e=>{}).then(delay(this.afterResponseDelay,t.abort)).then(e=>this.promiseStatus()),o=i.catch(e=>{}).then(delay(this.afterResponseDelay,t.abort)).then(e=>this.promiseTrailers());return this.maybeSuppressUncaught(a,o),this.lastInput=new TestInputStream(this.data,t.abort),new c.ClientStreamingCall(e,n,this.lastInput,r,i,a,o)}duplex(e,t){let n=t.meta??{},r=this.promiseHeaders().then(delay(this.headerDelay,t.abort)),a=new i.RpcOutputStreamController,o=r.then(delay(this.responseDelay,t.abort)).catch(()=>{}).then(()=>this.streamResponses(e,a,t.abort)).then(delay(this.afterResponseDelay,t.abort)),s=o.then(()=>this.promiseStatus()),c=o.then(()=>this.promiseTrailers());return this.maybeSuppressUncaught(s,c),this.lastInput=new TestInputStream(this.data,t.abort),new l.DuplexStreamingCall(e,n,this.lastInput,r,a,s,c)}};e.TestTransport=u,u.defaultHeaders={responseHeader:`test`},u.defaultStatus={code:`OK`,detail:`all good`},u.defaultTrailers={responseTrailer:`test`};function delay(e,t){return r=>new Promise((i,a)=>{if(t?.aborted)a(new n.RpcError(`user cancel`,`CANCELLED`));else{let o=setTimeout(()=>i(r),e);t&&t.addEventListener(`abort`,e=>{clearTimeout(o),a(new n.RpcError(`user cancel`,`CANCELLED`))})}})}var TestInputStream=class{constructor(e,t){this._completed=!1,this._sent=[],this.data=e,this.abort=t}get sent(){return this._sent}get completed(){return this._completed}send(e){if(this.data.inputMessage instanceof n.RpcError)return Promise.reject(this.data.inputMessage);let t=this.data.inputMessage===void 0?10:this.data.inputMessage;return Promise.resolve(void 0).then(()=>{this._sent.push(e)}).then(delay(t,this.abort))}complete(){if(this.data.inputComplete instanceof n.RpcError)return Promise.reject(this.data.inputComplete);let e=this.data.inputComplete===void 0?10:this.data.inputComplete;return Promise.resolve(void 0).then(()=>{this._completed=!0}).then(delay(e,this.abort))}}})),tv=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.stackDuplexStreamingInterceptors=e.stackClientStreamingInterceptors=e.stackServerStreamingInterceptors=e.stackUnaryInterceptors=e.stackIntercept=void 0;let t=U_();function stackIntercept(e,n,r,i,a){if(e==`unary`){let tail=(e,t,r)=>n.unary(e,t,r);for(let e of(i.interceptors??[]).filter(e=>e.interceptUnary).reverse()){let t=tail;tail=(n,r,i)=>e.interceptUnary(t,n,r,i)}return tail(r,a,i)}if(e==`serverStreaming`){let tail=(e,t,r)=>n.serverStreaming(e,t,r);for(let e of(i.interceptors??[]).filter(e=>e.interceptServerStreaming).reverse()){let t=tail;tail=(n,r,i)=>e.interceptServerStreaming(t,n,r,i)}return tail(r,a,i)}if(e==`clientStreaming`){let tail=(e,t)=>n.clientStreaming(e,t);for(let e of(i.interceptors??[]).filter(e=>e.interceptClientStreaming).reverse()){let t=tail;tail=(n,r)=>e.interceptClientStreaming(t,n,r)}return tail(r,i)}if(e==`duplex`){let tail=(e,t)=>n.duplex(e,t);for(let e of(i.interceptors??[]).filter(e=>e.interceptDuplex).reverse()){let t=tail;tail=(n,r)=>e.interceptDuplex(t,n,r)}return tail(r,i)}t.assertNever(e)}e.stackIntercept=stackIntercept;function stackUnaryInterceptors(e,t,n,r){return stackIntercept(`unary`,e,t,r,n)}e.stackUnaryInterceptors=stackUnaryInterceptors;function stackServerStreamingInterceptors(e,t,n,r){return stackIntercept(`serverStreaming`,e,t,r,n)}e.stackServerStreamingInterceptors=stackServerStreamingInterceptors;function stackClientStreamingInterceptors(e,t,n){return stackIntercept(`clientStreaming`,e,t,n)}e.stackClientStreamingInterceptors=stackClientStreamingInterceptors;function stackDuplexStreamingInterceptors(e,t,n){return stackIntercept(`duplex`,e,t,n)}e.stackDuplexStreamingInterceptors=stackDuplexStreamingInterceptors})),nv=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ServerCallContextController=void 0,e.ServerCallContextController=class{constructor(e,t,n,r,i={code:`OK`,detail:``}){this._cancelled=!1,this._listeners=[],this.method=e,this.headers=t,this.deadline=n,this.trailers={},this._sendRH=r,this.status=i}notifyCancelled(){if(!this._cancelled){this._cancelled=!0;for(let e of this._listeners)e()}}sendResponseHeaders(e){this._sendRH(e)}get cancelled(){return this._cancelled}onCancel(e){let t=this._listeners;return t.push(e),()=>{let n=t.indexOf(e);n>=0&&t.splice(n,1)}}}})),rv=__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=G_();Object.defineProperty(e,"ServiceType",{enumerable:!0,get:function(){return t.ServiceType}});var n=W_();Object.defineProperty(e,"readMethodOptions",{enumerable:!0,get:function(){return n.readMethodOptions}}),Object.defineProperty(e,"readMethodOption",{enumerable:!0,get:function(){return n.readMethodOption}}),Object.defineProperty(e,"readServiceOption",{enumerable:!0,get:function(){return n.readServiceOption}});var r=K_();Object.defineProperty(e,"RpcError",{enumerable:!0,get:function(){return r.RpcError}});var i=q_();Object.defineProperty(e,"mergeRpcOptions",{enumerable:!0,get:function(){return i.mergeRpcOptions}});var a=Y_();Object.defineProperty(e,"RpcOutputStreamController",{enumerable:!0,get:function(){return a.RpcOutputStreamController}});var o=ev();Object.defineProperty(e,"TestTransport",{enumerable:!0,get:function(){return o.TestTransport}});var s=J_();Object.defineProperty(e,"Deferred",{enumerable:!0,get:function(){return s.Deferred}}),Object.defineProperty(e,"DeferredState",{enumerable:!0,get:function(){return s.DeferredState}});var c=$_();Object.defineProperty(e,"DuplexStreamingCall",{enumerable:!0,get:function(){return c.DuplexStreamingCall}});var l=Q_();Object.defineProperty(e,"ClientStreamingCall",{enumerable:!0,get:function(){return l.ClientStreamingCall}});var u=Z_();Object.defineProperty(e,"ServerStreamingCall",{enumerable:!0,get:function(){return u.ServerStreamingCall}});var d=X_();Object.defineProperty(e,"UnaryCall",{enumerable:!0,get:function(){return d.UnaryCall}});var f=tv();Object.defineProperty(e,"stackIntercept",{enumerable:!0,get:function(){return f.stackIntercept}}),Object.defineProperty(e,"stackDuplexStreamingInterceptors",{enumerable:!0,get:function(){return f.stackDuplexStreamingInterceptors}}),Object.defineProperty(e,"stackClientStreamingInterceptors",{enumerable:!0,get:function(){return f.stackClientStreamingInterceptors}}),Object.defineProperty(e,"stackServerStreamingInterceptors",{enumerable:!0,get:function(){return f.stackServerStreamingInterceptors}}),Object.defineProperty(e,"stackUnaryInterceptors",{enumerable:!0,get:function(){return f.stackUnaryInterceptors}});var p=nv();Object.defineProperty(e,"ServerCallContextController",{enumerable:!0,get:function(){return p.ServerCallContextController}})}))(),$=U_();const iv=new class extends $.MessageType{constructor(){super(`github.actions.results.entities.v1.CacheScope`,[{no:1,name:`scope`,kind:`scalar`,T:9},{no:2,name:`permission`,kind:`scalar`,T:3}])}create(e){let t={scope:``,permission:`0`};return globalThis.Object.defineProperty(t,$.MESSAGE_TYPE,{enumerable:!1,value:this}),e!==void 0&&(0,$.reflectionMergePartial)(this,t,e),t}internalBinaryRead(e,t,n,r){let i=r??this.create(),a=e.pos+t;for(;e.posiv}])}create(e){let t={repositoryId:`0`,scope:[]};return globalThis.Object.defineProperty(t,$.MESSAGE_TYPE,{enumerable:!1,value:this}),e!==void 0&&(0,$.reflectionMergePartial)(this,t,e),t}internalBinaryRead(e,t,n,r){let i=r??this.create(),a=e.pos+t;for(;e.posav},{no:2,name:`key`,kind:`scalar`,T:9},{no:3,name:`version`,kind:`scalar`,T:9}])}create(e){let t={key:``,version:``};return globalThis.Object.defineProperty(t,$.MESSAGE_TYPE,{enumerable:!1,value:this}),e!==void 0&&(0,$.reflectionMergePartial)(this,t,e),t}internalBinaryRead(e,t,n,r){let i=r??this.create(),a=e.pos+t;for(;e.posav},{no:2,name:`key`,kind:`scalar`,T:9},{no:3,name:`size_bytes`,kind:`scalar`,T:3},{no:4,name:`version`,kind:`scalar`,T:9}])}create(e){let t={key:``,sizeBytes:`0`,version:``};return globalThis.Object.defineProperty(t,$.MESSAGE_TYPE,{enumerable:!1,value:this}),e!==void 0&&(0,$.reflectionMergePartial)(this,t,e),t}internalBinaryRead(e,t,n,r){let i=r??this.create(),a=e.pos+t;for(;e.posav},{no:2,name:`key`,kind:`scalar`,T:9},{no:3,name:`restore_keys`,kind:`scalar`,repeat:2,T:9},{no:4,name:`version`,kind:`scalar`,T:9}])}create(e){let t={key:``,restoreKeys:[],version:``};return globalThis.Object.defineProperty(t,$.MESSAGE_TYPE,{enumerable:!1,value:this}),e!==void 0&&(0,$.reflectionMergePartial)(this,t,e),t}internalBinaryRead(e,t,n,r){let i=r??this.create(),a=e.pos+t;for(;e.possv.fromJson(e,{ignoreUnknownFields:!0}))}FinalizeCacheEntryUpload(e){let t=cv.toJson(e,{useProtoFieldName:!0,emitDefaultValues:!1});return this.rpc.request(`github.actions.results.api.v1.CacheService`,`FinalizeCacheEntryUpload`,`application/json`,t).then(e=>lv.fromJson(e,{ignoreUnknownFields:!0}))}GetCacheEntryDownloadURL(e){let t=uv.toJson(e,{useProtoFieldName:!0,emitDefaultValues:!1});return this.rpc.request(`github.actions.results.api.v1.CacheService`,`GetCacheEntryDownloadURL`,`application/json`,t).then(e=>dv.fromJson(e,{ignoreUnknownFields:!0}))}};function maskSigUrl(e){if(e)try{let t=new URL(e).searchParams.get(`sig`);t&&(setSecret(t),setSecret(encodeURIComponent(t)))}catch(t){debug(`Failed to parse URL: ${e} ${t instanceof Error?t.message:String(t)}`)}}function maskSecretUrls(e){if(typeof e!=`object`||!e){debug(`body is not an object or is null`);return}`signed_upload_url`in e&&typeof e.signed_upload_url==`string`&&maskSigUrl(e.signed_upload_url),`signed_download_url`in e&&typeof e.signed_download_url==`string`&&maskSigUrl(e.signed_download_url)}var __awaiter$5=function(e,t,n,r){function adopt(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())})},CacheServiceClient=class{constructor(e,t,n,r){this.maxAttempts=5,this.baseRetryIntervalMilliseconds=3e3,this.retryMultiplier=1.5;let i=getRuntimeToken();this.baseUrl=getCacheServiceURL(),t&&(this.maxAttempts=t),n&&(this.baseRetryIntervalMilliseconds=n),r&&(this.retryMultiplier=r),this.httpClient=new HttpClient(e,[new BearerCredentialHandler(i)])}request(e,t,n,r){return __awaiter$5(this,void 0,void 0,function*(){let i=new URL(`/twirp/${e}/${t}`,this.baseUrl).href;debug(`[Request] ${t} ${i}`);let a={"Content-Type":n};try{let{body:e}=yield this.retryableRequest(()=>__awaiter$5(this,void 0,void 0,function*(){return this.httpClient.post(i,JSON.stringify(r),a)}));return e}catch(e){throw Error(`Failed to ${t}: ${e.message}`)}})}retryableRequest(e){return __awaiter$5(this,void 0,void 0,function*(){let t=0,n=``,r=``;for(;t0&&warning(`You've hit a rate limit, your rate limit will reset in ${t} seconds`)}throw new RateLimitError(`Rate limited: ${n}`)}}catch(e){if(e instanceof SyntaxError&&debug(`Raw Body: ${r}`),e instanceof UsageError||e instanceof RateLimitError)throw e;if(NetworkError.isNetworkErrorCode(e?.code))throw new NetworkError(e?.code);i=!0,n=e.message}if(!i)throw Error(`Received non-retryable error: ${n}`);if(t+1===this.maxAttempts)throw Error(`Failed to make request after ${this.maxAttempts} attempts: ${n}`);let a=this.getExponentialRetryTimeMilliseconds(t);info(`Attempt ${t+1} of ${this.maxAttempts} failed with error: ${n}. Retrying request in ${a} ms...`),yield this.sleep(a),t++}throw Error(`Request failed`)})}isSuccessStatusCode(e){return e?e>=200&&e<300:!1}isRetryableHttpStatusCode(e){return e?[On.BadGateway,On.GatewayTimeout,On.InternalServerError,On.ServiceUnavailable].includes(e):!1}sleep(e){return __awaiter$5(this,void 0,void 0,function*(){return new Promise(t=>setTimeout(t,e))})}getExponentialRetryTimeMilliseconds(e){if(e<0)throw Error(`attempt should be a positive integer`);if(e===0)return this.baseRetryIntervalMilliseconds;let t=this.baseRetryIntervalMilliseconds*this.retryMultiplier**+e,n=t*this.retryMultiplier;return Math.trunc(Math.random()*(n-t)+t)}};function internalCacheTwirpClient(e){return new CacheServiceClientJSON(new CacheServiceClient(getUserAgentString(),e?.maxAttempts,e?.retryIntervalMs,e?.retryMultiplier))}var __awaiter$4=function(e,t,n,r){function adopt(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())})};const fv=process.platform===`win32`;function getTarPath(){return __awaiter$4(this,void 0,void 0,function*(){switch(process.platform){case`win32`:{let e=yield getGnuTarPathOnWindows(),t=Ao;if(e)return{path:e,type:Eo.GNU};if(s(t))return{path:t,type:Eo.BSD};break}case`darwin`:{let e=yield which(`gtar`,!1);return e?{path:e,type:Eo.GNU}:{path:yield which(`tar`,!0),type:Eo.BSD}}}return{path:yield which(`tar`,!0),type:Eo.GNU}})}function getTarArgs(e,t,n){return __awaiter$4(this,arguments,void 0,function*(e,t,n,r=``){let i=[`"${e.path}"`],a=getCacheFileName(t),o=`cache.tar`,s=getWorkingDirectory(),c=e.type===Eo.BSD&&t!==To.Gzip&&fv;switch(n){case`create`:i.push(`--posix`,`-cf`,c?o:a.replace(RegExp(`\\${u.sep}`,`g`),`/`),`--exclude`,c?o:a.replace(RegExp(`\\${u.sep}`,`g`),`/`),`-P`,`-C`,s.replace(RegExp(`\\${u.sep}`,`g`),`/`),`--files-from`,Mo);break;case`extract`:i.push(`-xf`,c?o:r.replace(RegExp(`\\${u.sep}`,`g`),`/`),`-P`,`-C`,s.replace(RegExp(`\\${u.sep}`,`g`),`/`));break;case`list`:i.push(`-tf`,c?o:r.replace(RegExp(`\\${u.sep}`,`g`),`/`),`-P`)}if(e.type===Eo.GNU)switch(process.platform){case`win32`:i.push(`--force-local`);break;case`darwin`:i.push(`--delay-directory-restore`)}return i})}function getCommands(e,t){return __awaiter$4(this,arguments,void 0,function*(e,t,n=``){let r,i=yield getTarPath(),a=yield getTarArgs(i,e,t,n),o=t===`create`?yield getCompressionProgram(i,e):yield getDecompressionProgram(i,e,n),s=i.type===Eo.BSD&&e!==To.Gzip&&fv;return r=s&&t!==`create`?[[...o].join(` `),[...a].join(` `)]:[[...a].join(` `),[...o].join(` `)],s?r:[r.join(` `)]})}function getWorkingDirectory(){return process.env.GITHUB_WORKSPACE??process.cwd()}function getDecompressionProgram(e,t,n){return __awaiter$4(this,void 0,void 0,function*(){let r=e.type===Eo.BSD&&t!==To.Gzip&&fv;switch(t){case To.Zstd:return r?[`zstd -d --long=30 --force -o`,jo,n.replace(RegExp(`\\${u.sep}`,`g`),`/`)]:[`--use-compress-program`,fv?`"zstd -d --long=30"`:`unzstd --long=30`];case To.ZstdWithoutLong:return r?[`zstd -d --force -o`,jo,n.replace(RegExp(`\\${u.sep}`,`g`),`/`)]:[`--use-compress-program`,fv?`"zstd -d"`:`unzstd`];default:return[`-z`]}})}function getCompressionProgram(e,t){return __awaiter$4(this,void 0,void 0,function*(){let n=getCacheFileName(t),r=e.type===Eo.BSD&&t!==To.Gzip&&fv;switch(t){case To.Zstd:return r?[`zstd -T0 --long=30 --force -o`,n.replace(RegExp(`\\${u.sep}`,`g`),`/`),jo]:[`--use-compress-program`,fv?`"zstd -T0 --long=30"`:`zstdmt --long=30`];case To.ZstdWithoutLong:return r?[`zstd -T0 --force -o`,n.replace(RegExp(`\\${u.sep}`,`g`),`/`),jo]:[`--use-compress-program`,fv?`"zstd -T0"`:`zstdmt`];default:return[`-z`]}})}function execCommands(e,t){return __awaiter$4(this,void 0,void 0,function*(){for(let n of e)try{yield exec(n,void 0,{cwd:t,env:Object.assign(Object.assign({},process.env),{MSYS:`winsymlinks:nativestrict`})})}catch(e){throw Error(`${n.split(` `)[0]} failed with error: ${e?.message}`)}})}function listTar(e,t){return __awaiter$4(this,void 0,void 0,function*(){yield execCommands(yield getCommands(t,`list`,e))})}function extractTar(e,t){return __awaiter$4(this,void 0,void 0,function*(){yield mkdirP(getWorkingDirectory()),yield execCommands(yield getCommands(t,`extract`,e))})}function createTar(e,t,n){return __awaiter$4(this,void 0,void 0,function*(){l(u.join(e,Mo),t.join(` -`)),yield execCommands(yield getCommands(n,`create`),e)})}var __awaiter$3=function(e,t,n,r){function adopt(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())})},pv=class ValidationError extends Error{constructor(e){super(e),this.name=`ValidationError`,Object.setPrototypeOf(this,ValidationError.prototype)}},mv=class ReserveCacheError extends Error{constructor(e){super(e),this.name=`ReserveCacheError`,Object.setPrototypeOf(this,ReserveCacheError.prototype)}},hv=class CacheWriteDeniedError extends mv{constructor(e){super(e),this.name=`CacheWriteDeniedError`,Object.setPrototypeOf(this,CacheWriteDeniedError.prototype)}};const gv=`cache read denied:`;var _v=class CacheReadDeniedError extends Error{constructor(e){super(e),this.name=`CacheReadDeniedError`,Object.setPrototypeOf(this,CacheReadDeniedError.prototype)}},vv=class FinalizeCacheError extends Error{constructor(e){super(e),this.name=`FinalizeCacheError`,Object.setPrototypeOf(this,FinalizeCacheError.prototype)}};function checkPaths(e){if(!e||e.length===0)throw new pv(`Path Validation Error: At least one directory or file path is required`)}function checkKey(e){if(e.length>512)throw new pv(`Key Validation Error: ${e} cannot be larger than 512 characters.`);if(!/^[^,]*$/.test(e))throw new pv(`Key Validation Error: ${e} cannot contain commas.`)}function restoreCache$1(e,t,n,r){return __awaiter$3(this,arguments,void 0,function*(e,t,n,r,i=!1){let a=getCacheServiceVersion();debug(`Cache service version: ${a}`),checkPaths(e);let o=getCacheMode();if(!isCacheReadable(o)){info(`Cache restore skipped: the effective cache-mode '${o}' does not permit reads.`),debug(`Skipped restore for paths [${e.join(`, `)}] with primary key '${t}'.`);return}switch(a){case`v2`:return yield restoreCacheV2(e,t,n,r,i);default:return yield restoreCacheV1(e,t,n,r,i)}})}function restoreCacheV1(e,t,n,r){return __awaiter$3(this,arguments,void 0,function*(e,t,n,r,i=!1){n||=[];let a=[t,...n];if(debug(`Resolved Keys:`),debug(JSON.stringify(a)),a.length>10)throw new pv(`Key Validation Error: Keys are limited to a maximum of 10.`);for(let e of a)checkKey(e);let o=yield getCompressionMethod(),s=``;try{let t;try{t=yield getCacheEntry(a,e,{compressionMethod:o,enableCrossOsArchive:i})}catch(e){let t=e?.message??``;throw t.includes(gv)?new _v(t):e}if(!t?.archiveLocation)return;if(r?.lookupOnly)return info(`Lookup only - skipping download`),t.cacheKey;s=u.join(yield createTempDirectory(),getCacheFileName(o)),debug(`Archive Path: ${s}`),yield downloadCache(t.archiveLocation,s,r),isDebug()&&(yield listTar(s,o));let n=getArchiveFileSizeInBytes(s);return info(`Cache Size: ~${Math.round(n/1048576)} MB (${n} B)`),yield extractTar(s,o),info(`Cache restored successfully`),t.cacheKey}catch(e){let t=e;if(t.name===pv.name)throw e;t instanceof Pn&&typeof t.statusCode==`number`&&t.statusCode>=500?error(`Failed to restore: ${e.message}`):warning(`Failed to restore: ${e.message}`)}finally{try{yield unlinkFile(s)}catch(e){debug(`Failed to delete archive: ${e}`)}}})}function restoreCacheV2(e,t,n,r){return __awaiter$3(this,arguments,void 0,function*(e,t,n,r,i=!1){r=Object.assign(Object.assign({},r),{useAzureSdk:!0}),n||=[];let a=[t,...n];if(debug(`Resolved Keys:`),debug(JSON.stringify(a)),a.length>10)throw new pv(`Key Validation Error: Keys are limited to a maximum of 10.`);for(let e of a)checkKey(e);let o=``;try{let s=internalCacheTwirpClient(),c=yield getCompressionMethod(),l={key:t,restoreKeys:n,version:getCacheVersion(e,c,i)},d;try{d=yield s.GetCacheEntryDownloadURL(l)}catch(e){let t=e?.message??``;throw t.includes(gv)?new _v(t):e}if(!d.ok){debug(`Cache not found for version ${l.version} of keys: ${a.join(`, `)}`);return}if(l.key===d.matchedKey?info(`Cache hit for: ${d.matchedKey}`):info(`Cache hit for restore-key: ${d.matchedKey}`),r?.lookupOnly)return info(`Lookup only - skipping download`),d.matchedKey;o=u.join(yield createTempDirectory(),getCacheFileName(c)),debug(`Archive path: ${o}`),debug(`Starting download of archive to: ${o}`),yield downloadCache(d.signedDownloadUrl,o,r);let f=getArchiveFileSizeInBytes(o);return info(`Cache Size: ~${Math.round(f/1048576)} MB (${f} B)`),isDebug()&&(yield listTar(o,c)),yield extractTar(o,c),info(`Cache restored successfully`),d.matchedKey}catch(e){let t=e;if(t.name===pv.name)throw e;t instanceof Pn&&typeof t.statusCode==`number`&&t.statusCode>=500?error(`Failed to restore: ${e.message}`):warning(`Failed to restore: ${e.message}`)}finally{try{o&&(yield unlinkFile(o))}catch(e){debug(`Failed to delete archive: ${e}`)}}})}function saveCache$1(e,t,n){return __awaiter$3(this,arguments,void 0,function*(e,t,n,r=!1){let i=getCacheServiceVersion();debug(`Cache service version: ${i}`),checkPaths(e),checkKey(t);let a=getCacheMode();if(!isCacheWritable(a))return info(`Cache save skipped: the effective cache-mode '${a}' does not permit writes.`),debug(`Skipped save for paths [${e.join(`, `)}] with key '${t}'.`),-1;switch(i){case`v2`:return yield saveCacheV2(e,t,n,r);default:return yield saveCacheV1(e,t,n,r)}})}function saveCacheV1(e,t,n){return __awaiter$3(this,arguments,void 0,function*(e,t,n,r=!1){let i=yield getCompressionMethod(),a=-1,o=yield resolvePaths(e);if(debug(`Cache Paths:`),debug(`${JSON.stringify(o)}`),o.length===0)throw Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`);let s=yield createTempDirectory(),c=u.join(s,getCacheFileName(i));debug(`Archive Path: ${c}`);try{yield createTar(s,o,i),isDebug()&&(yield listTar(c,i));let l=getArchiveFileSizeInBytes(c);if(debug(`File Size: ${l}`),l>10737418240&&!isGhes())throw Error(`Cache size of ~${Math.round(l/1048576)} MB (${l} B) is over the 10GB limit, not saving cache.`);debug(`Reserving Cache`);let u=yield reserveCache(t,e,{compressionMethod:i,enableCrossOsArchive:r,cacheSize:l});if(u?.result?.cacheId)a=u?.result?.cacheId;else if(u?.statusCode===400)throw Error(u?.error?.message??`Cache size of ~${Math.round(l/1048576)} MB (${l} B) is over the data cap limit, not saving cache.`);else{let e=u?.error?.message;throw e?.startsWith(`cache write denied:`)?new hv(`Unable to reserve cache with key ${t}. More details: ${e}`):new mv(`Unable to reserve cache with key ${t}, another job may be creating this cache. More details: ${u?.error?.message}`)}debug(`Saving Cache (ID: ${a})`),yield saveCache$2(a,c,``,n)}catch(e){let t=e;if(t.name===pv.name)throw e;t.name===mv.name?info(`Failed to save: ${t.message}`):t instanceof Pn&&typeof t.statusCode==`number`&&t.statusCode>=500?error(`Failed to save: ${t.message}`):warning(`Failed to save: ${t.message}`)}finally{try{yield unlinkFile(c)}catch(e){debug(`Failed to delete archive: ${e}`)}}return a})}function saveCacheV2(e,t,n){return __awaiter$3(this,arguments,void 0,function*(e,t,n,r=!1){n=Object.assign(Object.assign({},n),{uploadChunkSize:67108864,uploadConcurrency:8,useAzureSdk:!0});let i=yield getCompressionMethod(),a=internalCacheTwirpClient(),o=-1,s=yield resolvePaths(e);if(debug(`Cache Paths:`),debug(`${JSON.stringify(s)}`),s.length===0)throw Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`);let c=yield createTempDirectory(),l=u.join(c,getCacheFileName(i));debug(`Archive Path: ${l}`);try{yield createTar(c,s,i),isDebug()&&(yield listTar(l,i));let u=getArchiveFileSizeInBytes(l);debug(`File Size: ${u}`),n.archiveSizeBytes=u,debug(`Reserving Cache`);let d=getCacheVersion(e,i,r),f={key:t,version:d},p;try{let e=yield a.CreateCacheEntry(f);if(!e.ok)throw e.message&&!e.message.startsWith(`cache write denied:`)&&warning(`Cache reservation failed: ${e.message}`),Error(e.message||`Response was not ok`);p=e.signedUploadUrl}catch(e){debug(`Failed to reserve cache: ${e}`);let n=e?.message??``;throw n.startsWith(`cache write denied:`)?new hv(`Unable to reserve cache with key ${t}. More details: ${n}`):new mv(`Unable to reserve cache with key ${t}, another job may be creating this cache.`)}debug(`Attempting to upload cache located at: ${l}`),yield saveCache$2(o,l,p,n);let h={key:t,version:d,sizeBytes:`${u}`},g=yield a.FinalizeCacheEntryUpload(h);if(debug(`FinalizeCacheEntryUploadResponse: ${g.ok}`),!g.ok)throw g.message?new vv(g.message):Error(`Unable to finalize cache with key ${t}, another job may be finalizing this cache.`);o=parseInt(g.entryId)}catch(e){let t=e;if(t.name===pv.name)throw e;t.name===mv.name?info(`Failed to save: ${t.message}`):t.name===vv.name?warning(t.message):t instanceof Pn&&typeof t.statusCode==`number`&&t.statusCode>=500?error(`Failed to save: ${t.message}`):warning(`Failed to save: ${t.message}`)}finally{try{yield unlinkFile(l)}catch(e){debug(`Failed to delete archive: ${e}`)}}return o})}const yv=`v1.15.1`,bv=`https://github.com/SocketDev/sfw-free/releases/download/${yv}`,xv=2e3;function isSfwSupported(e=process.platform,t=process.arch,n=isMuslLinux()){try{return!!getSfwAssetName(e,t,n)}catch{return!1}}function isMuslLinux(){if(process.platform!==`linux`)return!1;try{let e=process.report?.getReport();if(e?.header&&!e.header.glibcVersionRuntime)return!0}catch{}return I(`/etc/alpine-release`)}function getSfwAssetName(e,t,n){if(e===`darwin`){if(t===`arm64`)return`sfw-free-macos-arm64`;if(t===`x64`)return`sfw-free-macos-x86_64`}else if(e===`linux`){if(t===`arm64`)return n?`sfw-free-musl-linux-arm64`:`sfw-free-linux-arm64`;if(t===`x64`)return n?`sfw-free-musl-linux-x86_64`:`sfw-free-linux-x86_64`}else if(e===`win32`){if(t===`arm64`)return`sfw-free-windows-arm64.exe`;if(t===`x64`)return`sfw-free-windows-x86_64.exe`}throw Error(`Unsupported platform/arch for sfw: ${e}/${t}${e===`linux`?` (${n?`musl`:`glibc`})`:``}`)}function getSfwBinDir(){let e=process.env.RUNNER_TEMP||process.env.TMPDIR||process.env.TEMP||`/tmp`;return ae(e,`sfw-bin`)}async function installSfw(){let e=getSfwAssetName(process.platform,process.arch,isMuslLinux()),t=`${bv}/${e}`,n=getSfwBinDir();fe(n,{recursive:!0});let r=ae(n,process.platform===`win32`?`sfw.exe`:`sfw`),i=`sfw-${yv}-${process.platform}-${process.arch}-${isMuslLinux()?`musl`:`glibc`}`;try{let e=await restoreCache$1([n],i);if(e&&I(r)){process.platform!==`win32`&&de(r,493),addPath(n),info(`sfw restored from cache: ${e}`);return}}catch(e){warning(`sfw cache restore failed (${e instanceof Error?e.message:String(e)}); falling through to download.`)}info(`Installing sfw from ${t}...`);let a=``;for(let e=1;e<=2;e++){try{let e=await runDownloadCommand(t,r);if(e===0&&I(r)){process.platform!==`win32`&&de(r,493),addPath(n),info(`sfw installed at ${r}`);try{await saveCache$1([n],i),info(`sfw cached under key: ${i}`)}catch(e){warning(`sfw cache save failed (${e instanceof Error?e.message:String(e)}); continuing.`)}return}a=`exit code ${e}`}catch(e){a=e instanceof Error?e.message:String(e)}e<2&&(warning(`Failed to install sfw from ${t} (${a}). Retrying in ${xv}ms... (attempt ${e+1}/2)`),await le(xv))}throw Error(`Failed to install sfw from ${t} after 2 attempts: ${a}`)}function findSfwOnPath(){let e=process.platform===`win32`?`where`:`which`;try{let t=Oe(e,[`sfw`],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).split(/\r?\n/).find(e=>e.trim().length>0);return t?t.trim():null}catch{return null}}async function setupSfw(e){if(!e.sfw)return!1;if(e.runInstall.length===0)return info("sfw was requested but `run-install` is disabled; sfw will not be invoked."),!1;let t=findSfwOnPath();return t?(info(`Using existing sfw on PATH: ${t}`),!0):isSfwSupported()?(await installSfw(),!0):(warning(`sfw has no published binary for this runner's platform/architecture (${`process.platform=${process.platform}, process.arch=${process.arch}, musl=${isMuslLinux()}`}) and none was found on PATH; falling back to plain \`vp install\`. To enable sfw here, install a working sfw binary on PATH in an earlier step (e.g. via \`socketdev/action@\` or a custom install).`),!1)}async function runDownloadCommand(e,t){let n={ignoreReturnCode:!0};return process.platform===`win32`?exec(`pwsh`,[`-Command`,`Invoke-WebRequest -UseBasicParsing -Uri '${e}' -OutFile '${t}' -TimeoutSec 60`],n):exec(`bash`,[`-c`,`set -o pipefail; curl -fsSL --connect-timeout 5 --max-time 60 -o '${t}' '${e}'`],n)}const Sv=/Command 'vp' not found in PATH/;function isSfwVpNotFoundFlake(e,t){return Sv.test(t)||Sv.test(e)}async function warmPowerShellCommandCache(){if(process.platform===`win32`)try{await getExecOutput(`powershell.exe`,[`-NoProfile`,`-Command`,`Get-Command vp`],{ignoreReturnCode:!0})}catch(e){info(`PowerShell warm-up failed (${String(e)}); retrying sfw anyway.`)}}function tailOutput(e,t){let n=e.trim();return n.length<=t?n:`…(truncated, showing last ${t} chars)…\n${n.slice(-t)}`}async function runViteInstall(e){let t=getConfiguredProjectDir(e);for(let n of e.runInstall){let r=[`install`];n.args&&r.push(...n.args);let i=e.sfw?`sfw`:`vp`,a=e.sfw?[`vp`,...r]:r,o=getInstallCwd(t,n.cwd),s=`${i} ${a.join(` `)}`,attempt=async e=>{startGroup(`Running ${e} in ${o}...`);try{return await getExecOutput(i,a,{cwd:o,ignoreReturnCode:!0})}finally{endGroup()}};try{let t=await attempt(s);if(t.exitCode!==0&&e.sfw&&isSfwVpNotFoundFlake(t.stdout,t.stderr)&&(warning(`sfw reported vp as not found even though it is on PATH. This is a known sfw flake on Windows: a cold PowerShell start exceeds sfw's 10s command-resolution timeout and the timeout is misreported as not-found. Warming the PowerShell command cache and retrying once.`),await warmPowerShellCommandCache(),t=await attempt(`${s} (retry)`)),t.exitCode===0){info(`Successfully ran ${s}`);continue}let n=t.stderr.trim()||t.stdout.trim();n&&error(tailOutput(n,4e3),{title:`${s} failed`}),setFailed(`Command "${s}" (cwd: ${o}) exited with code ${t.exitCode}`)}catch(e){setFailed(`Failed to run ${s}: ${String(e)}`)}}}function getOptions(e){let t={followSymbolicLinks:!0,implicitDescendants:!0,matchDirectories:!0,omitBrokenSymbolicLinks:!0,excludeHiddenFiles:!1};return e&&(typeof e.followSymbolicLinks==`boolean`&&(t.followSymbolicLinks=e.followSymbolicLinks,debug(`followSymbolicLinks '${t.followSymbolicLinks}'`)),typeof e.implicitDescendants==`boolean`&&(t.implicitDescendants=e.implicitDescendants,debug(`implicitDescendants '${t.implicitDescendants}'`)),typeof e.matchDirectories==`boolean`&&(t.matchDirectories=e.matchDirectories,debug(`matchDirectories '${t.matchDirectories}'`)),typeof e.omitBrokenSymbolicLinks==`boolean`&&(t.omitBrokenSymbolicLinks=e.omitBrokenSymbolicLinks,debug(`omitBrokenSymbolicLinks '${t.omitBrokenSymbolicLinks}'`)),typeof e.excludeHiddenFiles==`boolean`&&(t.excludeHiddenFiles=e.excludeHiddenFiles,debug(`excludeHiddenFiles '${t.excludeHiddenFiles}'`))),t}const Cv=process.platform===`win32`;function dirname$1(e){if(e=safeTrimTrailingSeparator(e),Cv&&/^\\\\[^\\]+(\\[^\\]+)?$/.test(e))return e;let t=u.dirname(e);return Cv&&/^\\\\[^\\]+\\[^\\]+\\$/.test(t)&&(t=safeTrimTrailingSeparator(t)),t}function ensureAbsoluteRoot(e,t){if(g(e,`ensureAbsoluteRoot parameter 'root' must not be empty`),g(t,`ensureAbsoluteRoot parameter 'itemPath' must not be empty`),hasAbsoluteRoot(t))return t;if(Cv){if(t.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)){let e=process.cwd();return g(e.match(/^[A-Z]:\\/i),`Expected current directory to start with an absolute drive root. Actual '${e}'`),t[0].toUpperCase()===e[0].toUpperCase()?t.length===2?`${t[0]}:\\${e.substr(3)}`:(e.endsWith(`\\`)||(e+=`\\`),`${t[0]}:\\${e.substr(3)}${t.substr(2)}`):`${t[0]}:\\${t.substr(2)}`}if(normalizeSeparators(t).match(/^\\$|^\\[^\\]/)){let e=process.cwd();return g(e.match(/^[A-Z]:\\/i),`Expected current directory to start with an absolute drive root. Actual '${e}'`),`${e[0]}:\\${t.substr(1)}`}}return g(hasAbsoluteRoot(e),`ensureAbsoluteRoot parameter 'root' must have an absolute root`),e.endsWith(`/`)||Cv&&e.endsWith(`\\`)||(e+=u.sep),e+t}function hasAbsoluteRoot(e){return g(e,`hasAbsoluteRoot parameter 'itemPath' must not be empty`),e=normalizeSeparators(e),Cv?e.startsWith(`\\\\`)||/^[A-Z]:\\/i.test(e):e.startsWith(`/`)}function hasRoot(e){return g(e,`isRooted parameter 'itemPath' must not be empty`),e=normalizeSeparators(e),Cv?e.startsWith(`\\`)||/^[A-Z]:/i.test(e):e.startsWith(`/`)}function normalizeSeparators(e){return e||=``,Cv?(e=e.replace(/\//g,`\\`),(/^\\\\+[^\\]/.test(e)?`\\`:``)+e.replace(/\\\\+/g,`\\`)):e.replace(/\/\/+/g,`/`)}function safeTrimTrailingSeparator(e){return e?(e=normalizeSeparators(e),!e.endsWith(u.sep)||e===u.sep||Cv&&/^[A-Z]:\\$/i.test(e)?e:e.substr(0,e.length-1)):``}var wv;(function(e){e[e.None=0]=`None`,e[e.Directory=1]=`Directory`,e[e.File=2]=`File`,e[e.All=3]=`All`})(wv||={});const Tv=process.platform===`win32`;function getSearchPaths(e){e=e.filter(e=>!e.negate);let t={};for(let n of e){let e=Tv?n.searchPath.toUpperCase():n.searchPath;t[e]=`candidate`}let n=[];for(let r of e){let e=Tv?r.searchPath.toUpperCase():r.searchPath;if(t[e]===`included`)continue;let i=!1,a=e,o=dirname$1(a);for(;o!==a;){if(t[o]){i=!0;break}a=o,o=dirname$1(a)}i||(n.push(r.searchPath),t[e]=`included`)}return n}function match$1(e,t){let n=wv.None;for(let r of e)r.negate?n&=~r.match(t):n|=r.match(t);return n}function partialMatch(e,t){return e.some(e=>!e.negate&&e.partialMatch(t))}const balanced=(e,t,n)=>{let r=e instanceof RegExp?maybeMatch(e,n):e,i=t instanceof RegExp?maybeMatch(t,n):t,a=r!==null&&i!=null&&range(r,i,n);return a&&{start:a[0],end:a[1],pre:n.slice(0,a[0]),body:n.slice(a[0]+r.length,a[1]),post:n.slice(a[1]+i.length)}},maybeMatch=(e,t)=>{let n=t.match(e);return n?n[0]:null},range=(e,t,n)=>{let r,i,a,o,s,c=n.indexOf(e),l=n.indexOf(t,c+1),u=c;if(c>=0&&l>0){if(e===t)return[c,l];for(r=[],a=n.length;u>=0&&!s;){if(u===c)r.push(u),c=n.indexOf(e,u+1);else if(r.length===1){let e=r.pop();e!==void 0&&(s=[e,l])}else i=r.pop(),i!==void 0&&i=0?c:l}r.length&&o!==void 0&&(s=[a,o])}return s},Ev=`\0SLASH`+Math.random()+`\0`,Dv=`\0OPEN`+Math.random()+`\0`,Ov=`\0CLOSE`+Math.random()+`\0`,kv=`\0COMMA`+Math.random()+`\0`,Av=`\0PERIOD`+Math.random()+`\0`,jv=new RegExp(Ev,`g`),Mv=new RegExp(Dv,`g`),Nv=new RegExp(Ov,`g`),Pv=new RegExp(kv,`g`),Fv=new RegExp(Av,`g`),Iv=/\\\\/g,Lv=/\\{/g,Rv=/\\}/g,zv=/\\,/g,Bv=/\\\./g;function numeric(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function escapeBraces(e){return e.replace(Iv,Ev).replace(Lv,Dv).replace(Rv,Ov).replace(zv,kv).replace(Bv,Av)}function unescapeBraces(e){return e.replace(jv,`\\`).replace(Mv,`{`).replace(Nv,`}`).replace(Pv,`,`).replace(Fv,`.`)}function parseCommaParts(e){if(!e)return[``];let t=[],n=balanced(`{`,`}`,e);if(!n)return e.split(`,`);let{pre:r,body:i,post:a}=n,o=r.split(`,`);o[o.length-1]+=`{`+i+`}`;let s=parseCommaParts(a);return a.length&&(o[o.length-1]+=s.shift(),o.push.apply(o,s)),t.push.apply(t,o),t}function expand(e,t={}){if(!e)return[];let{max:n=1e5}=t;return e.slice(0,2)===`{}`&&(e=`\\{\\}`+e.slice(2)),expand_(escapeBraces(e),n,!0).map(unescapeBraces)}function embrace(e){return`{`+e+`}`}function isPadded(e){return/^-?0\d/.test(e)}function lte(e,t){return e<=t}function gte(e,t){return e>=t}function expand_(e,t,n){let r=[],i=balanced(`{`,`}`,e);if(!i)return[e];let a=i.pre,o=i.post.length?expand_(i.post,t,!1):[``];if(/\$$/.test(i.pre))for(let e=0;e=0;if(!l&&!u)return i.post.match(/,(?!,).*\}/)?(e=i.pre+`{`+i.body+Ov+i.post,expand_(e,t,!0)):[e];let d;if(l)d=i.body.split(/\.\./);else if(d=parseCommaParts(i.body),d.length===1&&d[0]!==void 0&&(d=expand_(d[0],t,!1).map(embrace),d.length===1))return o.map(e=>i.pre+d[0]+e);let f;if(l&&d[0]!==void 0&&d[1]!==void 0){let e=numeric(d[0]),t=numeric(d[1]),n=Math.max(d[0].length,d[1].length),r=d.length===3&&d[2]!==void 0?Math.max(Math.abs(numeric(d[2])),1):1,i=lte;t0){let n=Array(t+1).join(`0`);e=o<0?`-`+n+e.slice(1):n+e}}f.push(e)}}else{f=[];for(let e=0;e{if(typeof e!=`string`)throw TypeError(`invalid pattern`);if(e.length>65536)throw TypeError(`pattern is too long`)},Vv={"[:alnum:]":[`\\p{L}\\p{Nl}\\p{Nd}`,!0],"[:alpha:]":[`\\p{L}\\p{Nl}`,!0],"[:ascii:]":[`\\x00-\\x7f`,!1],"[:blank:]":[`\\p{Zs}\\t`,!0],"[:cntrl:]":[`\\p{Cc}`,!0],"[:digit:]":[`\\p{Nd}`,!0],"[:graph:]":[`\\p{Z}\\p{C}`,!0,!0],"[:lower:]":[`\\p{Ll}`,!0],"[:print:]":[`\\p{C}`,!0],"[:punct:]":[`\\p{P}`,!0],"[:space:]":[`\\p{Z}\\t\\r\\n\\v\\f`,!0],"[:upper:]":[`\\p{Lu}`,!0],"[:word:]":[`\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}`,!0],"[:xdigit:]":[`A-Fa-f0-9`,!1]},braceEscape=e=>e.replace(/[[\]\\-]/g,`\\$&`),regexpEscape=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),rangesToString=e=>e.join(``),parseClass=(e,t)=>{let n=t;if(e.charAt(n)!==`[`)throw Error(`not in a brace expression`);let r=[],i=[],a=n+1,o=!1,s=!1,c=!1,l=!1,u=n,d=``;WHILE:for(;ad?r.push(braceEscape(d)+`-`+braceEscape(t)):t===d&&r.push(braceEscape(t)),d=``,a++;continue}if(e.startsWith(`-]`,a+1)){r.push(braceEscape(t+`-`)),a+=2;continue}if(e.startsWith(`-`,a+1)){d=t,a+=2;continue}r.push(braceEscape(t)),a++}if(un?t?e.replace(/\[([^/\\])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^/\\])\]/g,`$1$2`).replace(/\\([^/])/g,`$1`):t?e.replace(/\[([^/\\{}])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^/\\{}])\]/g,`$1$2`).replace(/\\([^/{}])/g,`$1`);var Hv;const Uv=new Set([`!`,`?`,`+`,`*`,`@`]),isExtglobType=e=>Uv.has(e),isExtglobAST=e=>isExtglobType(e.type),Wv=new Map([[`!`,[`@`]],[`?`,[`?`,`@`]],[`@`,[`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`]]]),Gv=new Map([[`!`,[`?`]],[`@`,[`?`]],[`+`,[`?`,`*`]]]),Kv=new Map([[`!`,[`?`,`@`]],[`?`,[`?`,`@`]],[`@`,[`?`,`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`,`?`,`*`]]]),qv=new Map([[`!`,new Map([[`!`,`@`]])],[`?`,new Map([[`*`,`*`],[`+`,`*`]])],[`@`,new Map([[`!`,`!`],[`?`,`?`],[`@`,`@`],[`*`,`*`],[`+`,`+`]])],[`+`,new Map([[`?`,`*`],[`*`,`*`]])]]),Jv=`(?!\\.)`,Yv=new Set([`[`,`.`]),Xv=new Set([`..`,`.`]),Zv=new Set(`().*{}+?[]^$\\!`),regExpEscape$1=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),Qv=`[^/]+?`;let $v=0;var AST=class{type;#e;#t;#n=!1;#r=[];#i;#a;#o;#s=!1;#c;#l;#u=!1;id=++$v;get depth(){return(this.#i?.depth??-1)+1}[Symbol.for(`nodejs.util.inspect.custom`)](){return{"@@type":`AST`,id:this.id,type:this.type,root:this.#e.id,parent:this.#i?.id,depth:this.depth,partsLength:this.#r.length,parts:this.#r}}constructor(e,t,n={}){this.type=e,e&&(this.#t=!0),this.#i=t,this.#e=this.#i?this.#i.#e:this,this.#c=this.#e===this?n:this.#e.#c,this.#o=this.#e===this?[]:this.#e.#o,e===`!`&&!this.#e.#s&&this.#o.push(this),this.#a=this.#i?this.#i.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#r)if(typeof e!=`string`&&(e.type||e.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#l===void 0?this.#l=this.type?this.type+`(`+this.#r.map(e=>String(e)).join(`|`)+`)`:this.#r.map(e=>String(e)).join(``):this.#l}#d(){if(this!==this.#e)throw Error(`should only call on root`);if(this.#s)return this;this.toString(),this.#s=!0;let e;for(;e=this.#o.pop();){if(e.type!==`!`)continue;let t=e,n=t.#i;for(;n;){for(let r=t.#a+1;!n.type&&rtypeof e==`string`?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#s&&this.#i?.type===`!`)&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#i?.isStart())return!1;if(this.#a===0)return!0;let e=this.#i;for(let t=0;ttypeof e!=`string`),r=this.#r.map(t=>{let[r,i,a,o]=typeof t==`string`?Hv.#C(t,this.#t,n):t.toRegExpSource(e);return this.#t=this.#t||a,this.#n=this.#n||o,r}).join(``),i=``;if(this.isStart()&&typeof this.#r[0]==`string`&&!(this.#r.length===1&&Xv.has(this.#r[0]))){let n=Yv,a=t&&n.has(r.charAt(0))||r.startsWith(`\\.`)&&n.has(r.charAt(2))||r.startsWith(`\\.\\.`)&&n.has(r.charAt(4)),o=!t&&!e&&n.has(r.charAt(0));i=a?`(?!(?:^|/)\\.\\.?(?:$|/))`:o?Jv:``}let a=``;return this.isEnd()&&this.#e.#s&&this.#i?.type===`!`&&(a=`(?:$|\\/)`),[i+r+a,unescape(r),this.#t=!!this.#t,this.#n]}let n=this.type===`*`||this.type===`+`,r=this.type===`!`?`(?:(?!(?:`:`(?:`,i=this.#S(t);if(this.isStart()&&this.isEnd()&&!i&&this.type!==`!`){let e=this.toString(),t=this;return t.#r=[e],t.type=null,t.#t=void 0,[e,unescape(this.toString()),!1,!1]}let a=!n||e||t?``:this.#S(!0);a===i&&(a=``),a&&(i=`(?:${i})(?:${a})*?`);let o=``;if(this.type===`!`&&this.#u)o=(this.isStart()&&!t?Jv:``)+Qv;else{let n=this.type===`!`?`))`+(this.isStart()&&!t&&!e?Jv:``)+`[^/]*?)`:this.type===`@`?`)`:this.type===`?`?`)?`:this.type===`+`&&a?`)`:this.type===`*`&&a?`)?`:`)${this.type}`;o=r+i+n}return[o,unescape(i),this.#t=!!this.#t,this.#n]}#x(){if(isExtglobAST(this)){let e=0,t=!1;do{t=!0;for(let e=0;e{if(typeof t==`string`)throw Error(`string type in extglob ast??`);let[n,r,i,a]=t.toRegExpSource(e);return this.#n=this.#n||a,n}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join(`|`)}static#C(e,t,n=!1){let r=!1,i=``,a=!1,o=!1;for(let s=0;sn?t?e.replace(/[?*()[\]{}]/g,`[$&]`):e.replace(/[?*()[\]\\{}]/g,`\\$&`):t?e.replace(/[?*()[\]]/g,`[$&]`):e.replace(/[?*()[\]\\]/g,`\\$&`),minimatch=(e,t,n={})=>(assertValidPattern(t),!n.nocomment&&t.charAt(0)===`#`?!1:new Minimatch(t,n).match(e)),ey=/^\*+([^+@!?*[(]*)$/,starDotExtTest=e=>t=>!t.startsWith(`.`)&&t.endsWith(e),starDotExtTestDot=e=>t=>t.endsWith(e),starDotExtTestNocase=e=>(e=e.toLowerCase(),t=>!t.startsWith(`.`)&&t.toLowerCase().endsWith(e)),starDotExtTestNocaseDot=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),ty=/^\*+\.\*+$/,starDotStarTest=e=>!e.startsWith(`.`)&&e.includes(`.`),starDotStarTestDot=e=>e!==`.`&&e!==`..`&&e.includes(`.`),ny=/^\.\*+$/,dotStarTest=e=>e!==`.`&&e!==`..`&&e.startsWith(`.`),ry=/^\*+$/,starTest=e=>e.length!==0&&!e.startsWith(`.`),starTestDot=e=>e.length!==0&&e!==`.`&&e!==`..`,iy=/^\?+([^+@!?*[(]*)?$/,qmarksTestNocase=([e,t=``])=>{let n=qmarksTestNoExt([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},qmarksTestNocaseDot=([e,t=``])=>{let n=qmarksTestNoExtDot([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},qmarksTestDot=([e,t=``])=>{let n=qmarksTestNoExtDot([e]);return t?e=>n(e)&&e.endsWith(t):n},qmarksTest=([e,t=``])=>{let n=qmarksTestNoExt([e]);return t?e=>n(e)&&e.endsWith(t):n},qmarksTestNoExt=([e])=>{let t=e.length;return e=>e.length===t&&!e.startsWith(`.`)},qmarksTestNoExtDot=([e])=>{let t=e.length;return e=>e.length===t&&e!==`.`&&e!==`..`},ay=typeof process==`object`&&process?typeof process.env==`object`&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:`posix`,oy={win32:{sep:`\\`},posix:{sep:`/`}};minimatch.sep=ay===`win32`?oy.win32.sep:oy.posix.sep;const sy=Symbol(`globstar **`);minimatch.GLOBSTAR=sy,minimatch.filter=(e,t={})=>n=>minimatch(n,e,t);const ext=(e,t={})=>Object.assign({},e,t);minimatch.defaults=e=>{if(!e||typeof e!=`object`||!Object.keys(e).length)return minimatch;let t=minimatch;return Object.assign((n,r,i={})=>t(n,r,ext(e,i)),{Minimatch:class extends t.Minimatch{constructor(t,n={}){super(t,ext(e,n))}static defaults(n){return t.defaults(ext(e,n)).Minimatch}},AST:class extends t.AST{constructor(t,n,r={}){super(t,n,ext(e,r))}static fromGlob(n,r={}){return t.AST.fromGlob(n,ext(e,r))}},unescape:(n,r={})=>t.unescape(n,ext(e,r)),escape:(n,r={})=>t.escape(n,ext(e,r)),filter:(n,r={})=>t.filter(n,ext(e,r)),defaults:n=>t.defaults(ext(e,n)),makeRe:(n,r={})=>t.makeRe(n,ext(e,r)),braceExpand:(n,r={})=>t.braceExpand(n,ext(e,r)),match:(n,r,i={})=>t.match(n,r,ext(e,i)),sep:t.sep,GLOBSTAR:sy})};const braceExpand=(e,t={})=>(assertValidPattern(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:expand(e,{max:t.braceExpandMax}));minimatch.braceExpand=braceExpand,minimatch.makeRe=(e,t={})=>new Minimatch(e,t).makeRe(),minimatch.match=(e,t,n={})=>{let r=new Minimatch(t,n);return e=e.filter(e=>r.match(e)),r.options.nonull&&!e.length&&e.push(t),e};const cy=/[?*]|[+@!]\(.*?\)|\[|\]/,regExpEscape=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`);var Minimatch=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(e,t={}){assertValidPattern(e),t||={},this.options=t,this.maxGlobstarRecursion=t.maxGlobstarRecursion??200,this.pattern=e,this.platform=t.platform||ay,this.isWindows=this.platform===`win32`,this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,`/`)),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot===void 0?!!(this.isWindows&&this.nocase):t.windowsNoMagicRoot,this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!=`string`)return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)===`#`){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...e)=>console.error(...e)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(e=>this.slashSplit(e));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let r=this.globParts.map((e,t,n)=>{if(this.isWindows&&this.windowsNoMagicRoot){let t=e[0]===``&&e[1]===``&&(e[2]===`?`||!cy.test(e[2]))&&!cy.test(e[3]),n=/^[a-z]:/i.test(e[0]);if(t)return[...e.slice(0,4),...e.slice(4).map(e=>this.parse(e))];if(n)return[e[0],...e.slice(1).map(e=>this.parse(e))]}return e.map(e=>this.parse(e))});if(this.debug(this.pattern,r),this.set=r.filter(e=>e.indexOf(!1)===-1),this.isWindows)for(let e=0;e=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):e=t>=1?this.levelOneOptimize(e):this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(e=>{let t=-1;for(;(t=e.indexOf(`**`,t+1))!==-1;){let n=t;for(;e[n+1]===`**`;)n++;n!==t&&e.splice(t,n-t)}return e})}levelOneOptimize(e){return e.map(e=>(e=e.reduce((e,t)=>{let n=e[e.length-1];return t===`**`&&n===`**`?e:t===`..`&&n&&n!==`..`&&n!==`.`&&n!==`**`?(e.pop(),e):(e.push(t),e)},[]),e.length===0?[``]:e))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let n=1;nr&&n.splice(r+1,i-r);let a=n[r+1],o=n[r+2],s=n[r+3];if(a!==`..`||!o||o===`.`||o===`..`||!s||s===`.`||s===`..`)continue;t=!0,n.splice(r,1);let c=n.slice(0);c[r]=`**`,e.push(c),r--}if(!this.preserveMultipleSlashes){for(let e=1;ee.length)}partsMatch(e,t,n=!1){let r=0,i=0,a=[],o=``;for(;r=2&&(e=this.levelTwoFileOptimize(e)),t.includes(sy)?this.#e(e,t,n,r,i):this.#n(e,t,n,r,i)}#e(e,t,n,r,i){let a=t.indexOf(sy,i),o=t.lastIndexOf(sy),[s,c,l]=n?[t.slice(i,a),t.slice(a+1),[]]:[t.slice(i,a),t.slice(a+1,o),t.slice(o+1)];if(s.length){let t=e.slice(r,r+s.length);if(!this.#n(t,s,n,0,0))return!1;r+=s.length,i+=s.length}let u=0;if(l.length){if(l.length+r>e.length)return!1;let t=e.length-l.length;if(this.#n(e,l,n,t,0))u=l.length;else{if(e[e.length-1]!==``||r+l.length===e.length||(t--,!this.#n(e,l,n,t,0)))return!1;u=l.length+1}}if(!c.length){let t=!!u;for(let n=r;n{let t=e.map(e=>{if(e instanceof RegExp)for(let t of e.flags.split(``))r.add(t);return typeof e==`string`?regExpEscape(e):e===sy?sy:e._src});t.forEach((e,r)=>{let i=t[r+1],a=t[r-1];e===sy&&a!==sy&&(a===void 0?i!==void 0&&i!==sy?t[r+1]=`(?:\\/|`+n+`\\/)?`+i:t[r]=n:i===void 0?t[r-1]=a+`(?:\\/|\\/`+n+`)?`:i!==sy&&(t[r-1]=a+`(?:\\/|\\/`+n+`\\/)`+i,t[r+1]=sy))});let i=t.filter(e=>e!==sy);if(this.partial&&i.length>=1){let e=[];for(let t=1;t<=i.length;t++)e.push(i.slice(0,t).join(`/`));return`(?:`+e.join(`|`)+`)`}return i.join(`/`)}).join(`|`),[a,o]=e.length>1?[`(?:`,`)`]:[``,``];i=`^`+a+i+o+`$`,this.partial&&(i=`^(?:\\/|`+a+i.slice(1,-1)+o+`)$`),this.negate&&(i=`^(?!`+i+`).+$`);try{this.regexp=new RegExp(i,[...r].join(``))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split(`/`):this.isWindows&&/^\/\/[^/]+/.test(e)?[``,...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug(`match`,e,this.pattern),this.comment)return!1;if(this.empty)return e===``;if(e===`/`&&t)return!0;let n=this.options;this.isWindows&&(e=e.split(`\\`).join(`/`));let r=this.slashSplit(e);this.debug(this.pattern,`split`,r);let i=this.set;this.debug(this.pattern,`set`,i);let a=r[r.length-1];if(!a)for(let e=r.length-2;!a&&e>=0;e--)a=r[e];for(let e of i){let i=r;if(n.matchBase&&e.length===1&&(i=[a]),this.matchOne(i,e,t))return n.flipNegate?!0:!this.negate}return!n.flipNegate&&this.negate}static defaults(e){return minimatch.defaults(e).Minimatch}};minimatch.AST=AST,minimatch.Minimatch=Minimatch,minimatch.escape=escape,minimatch.unescape=unescape;const ly=process.platform===`win32`;var Path=class{constructor(e){if(this.segments=[],typeof e==`string`){if(g(e,`Parameter 'itemPath' must not be empty`),e=safeTrimTrailingSeparator(e),!hasRoot(e))this.segments=e.split(u.sep);else{let t=e,n=dirname$1(t);for(;n!==t;){let e=u.basename(t);this.segments.unshift(e),t=n,n=dirname$1(t)}this.segments.unshift(t)}}else{g(e.length>0,`Parameter 'itemPath' must not be an empty array`);for(let t=0;tPattern.getLiteral(e)).filter(e=>!a&&!(a=e===``));this.searchPath=new Path(o).toString(),this.rootRegExp=new RegExp(Pattern.regExpEscape(o[0]),uy?`i`:``),this.isImplicitPattern=t;let s={dot:!0,nobrace:!0,nocase:uy,nocomment:!0,noext:!0,nonegate:!0};i=uy?i.replace(/\\/g,`/`):i,this.minimatch=new Minimatch(i,s)}match(e){return this.segments[this.segments.length-1]===`**`?(e=normalizeSeparators(e),!e.endsWith(u.sep)&&this.isImplicitPattern===!1&&(e=`${e}${u.sep}`)):e=safeTrimTrailingSeparator(e),this.minimatch.match(e)?this.trailingSeparator?wv.Directory:wv.All:wv.None}partialMatch(e){return e=safeTrimTrailingSeparator(e),dirname$1(e)===e?this.rootRegExp.test(e):this.minimatch.matchOne(e.split(uy?/\\+/:/\/+/),this.minimatch.set[0],!0)}static globEscape(e){return(uy?e:e.replace(/\\/g,`\\\\`)).replace(/(\[)(?=[^/]+\])/g,`[[]`).replace(/\?/g,`[?]`).replace(/\*/g,`[*]`)}static fixupPattern(e,n){g(e,`pattern cannot be empty`);let r=new Path(e).segments.map(e=>Pattern.getLiteral(e));if(g(r.every((e,t)=>(e!==`.`||t===0)&&e!==`..`),`Invalid pattern '${e}'. Relative pathing '.' and '..' is not allowed.`),g(!hasRoot(e)||r[0],`Invalid pattern '${e}'. Root segment must not contain globs.`),e=normalizeSeparators(e),e===`.`||e.startsWith(`.${u.sep}`))e=Pattern.globEscape(process.cwd())+e.substr(1);else if(e===`~`||e.startsWith(`~${u.sep}`))n||=t.homedir(),g(n,`Unable to determine HOME directory`),g(hasAbsoluteRoot(n),`Expected HOME directory to be a rooted path. Actual '${n}'`),e=Pattern.globEscape(n)+e.substr(1);else if(uy&&(e.match(/^[A-Z]:$/i)||e.match(/^[A-Z]:[^\\]/i))){let t=ensureAbsoluteRoot(`C:\\dummy-root`,e.substr(0,2));e.length>2&&!t.endsWith(`\\`)&&(t+=`\\`),e=Pattern.globEscape(t)+e.substr(2)}else if(uy&&(e===`\\`||e.match(/^\\[^\\]/))){let t=ensureAbsoluteRoot(`C:\\dummy-root`,`\\`);t.endsWith(`\\`)||(t+=`\\`),e=Pattern.globEscape(t)+e.substr(1)}else e=ensureAbsoluteRoot(Pattern.globEscape(process.cwd()),e);return normalizeSeparators(e)}static getLiteral(e){let t=``;for(let n=0;n=0){if(r.length>1)return``;if(r){t+=r,n=i;continue}}}t+=r}return t}static regExpEscape(e){return e.replace(/[[\\^$.|?*+()]/g,`\\$&`)}},SearchState=class{constructor(e,t){this.path=e,this.level=t}},__awaiter$2=function(e,t,n,r){function adopt(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())})},__asyncValues$1=function(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof __values==`function`?__values(e):e[Symbol.iterator](),n={},verb(`next`),verb(`throw`),verb(`return`),n[Symbol.asyncIterator]=function(){return this},n);function verb(t){n[t]=e[t]&&function(n){return new Promise(function(r,i){n=e[t](n),settle(r,i,n.done,n.value)})}}function settle(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}},__await=function(e){return this instanceof __await?(this.v=e,this):new __await(e)},__asyncGenerator=function(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),verb(`next`),verb(`throw`),verb(`return`,awaitReturn),i[Symbol.asyncIterator]=function(){return this},i;function awaitReturn(e){return function(t){return Promise.resolve(t).then(e,reject)}}function verb(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||resume(e,t)})},t&&(i[e]=t(i[e])))}function resume(e,t){try{step(r[e](t))}catch(e){settle(a[0][3],e)}}function step(e){e.value instanceof __await?Promise.resolve(e.value.v).then(fulfill,reject):settle(a[0][2],e)}function fulfill(e){resume(`next`,e)}function reject(e){resume(`throw`,e)}function settle(e,t){e(t),a.shift(),a.length&&resume(a[0][0],a[0][1])}};const fy=process.platform===`win32`;var py=class DefaultGlobber{constructor(e){this.patterns=[],this.searchPaths=[],this.options=getOptions(e)}getSearchPaths(){return this.searchPaths.slice()}glob(){return __awaiter$2(this,void 0,void 0,function*(){var e,t,n,r;let i=[];try{for(var a=!0,o=__asyncValues$1(this.globGenerator()),s;s=yield o.next(),e=s.done,!e;a=!0){r=s.value,a=!1;let e=r;i.push(e)}}catch(e){t={error:e}}finally{try{!a&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return i})}globGenerator(){return __asyncGenerator(this,arguments,function*(){let e=getOptions(this.options),t=[];for(let n of this.patterns)t.push(n),e.implicitDescendants&&(n.trailingSeparator||n.segments[n.segments.length-1]!==`**`)&&t.push(new dy(n.negate,!0,n.segments.concat(`**`)));let n=[];for(let e of getSearchPaths(t)){debug(`Search path '${e}'`);try{yield __await(a.promises.lstat(e))}catch(e){if(e.code===`ENOENT`)continue;throw e}n.unshift(new SearchState(e,1))}let r=[];for(;n.length;){let i=n.pop(),o=match$1(t,i.path),s=!!o||partialMatch(t,i.path);if(!o&&!s)continue;let c=yield __await(DefaultGlobber.stat(i,e,r));if(c&&!(e.excludeHiddenFiles&&u.basename(i.path).match(/^\./))){if(c.isDirectory()){if(o&wv.Directory&&e.matchDirectories)yield yield __await(i.path);else if(!s)continue;let t=i.level+1,r=(yield __await(a.promises.readdir(i.path))).map(e=>new SearchState(u.join(i.path,e),t));n.push(...r.reverse())}else o&wv.File&&(yield yield __await(i.path))}}})}static create(e,t){return __awaiter$2(this,void 0,void 0,function*(){let n=new DefaultGlobber(t);fy&&(e=e.replace(/\r\n/g,` +`)),yield execCommands(yield getCommands(n,`create`),e)})}var __awaiter$3=function(e,t,n,r){function adopt(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())})},pv=class ValidationError extends Error{constructor(e){super(e),this.name=`ValidationError`,Object.setPrototypeOf(this,ValidationError.prototype)}},mv=class ReserveCacheError extends Error{constructor(e){super(e),this.name=`ReserveCacheError`,Object.setPrototypeOf(this,ReserveCacheError.prototype)}},hv=class CacheWriteDeniedError extends mv{constructor(e){super(e),this.name=`CacheWriteDeniedError`,Object.setPrototypeOf(this,CacheWriteDeniedError.prototype)}};const gv=`cache read denied:`;var _v=class CacheReadDeniedError extends Error{constructor(e){super(e),this.name=`CacheReadDeniedError`,Object.setPrototypeOf(this,CacheReadDeniedError.prototype)}},vv=class FinalizeCacheError extends Error{constructor(e){super(e),this.name=`FinalizeCacheError`,Object.setPrototypeOf(this,FinalizeCacheError.prototype)}};function checkPaths(e){if(!e||e.length===0)throw new pv(`Path Validation Error: At least one directory or file path is required`)}function checkKey(e){if(e.length>512)throw new pv(`Key Validation Error: ${e} cannot be larger than 512 characters.`);if(!/^[^,]*$/.test(e))throw new pv(`Key Validation Error: ${e} cannot contain commas.`)}function restoreCache$1(e,t,n,r){return __awaiter$3(this,arguments,void 0,function*(e,t,n,r,i=!1){let a=getCacheServiceVersion();debug(`Cache service version: ${a}`),checkPaths(e);let o=getCacheMode();if(!isCacheReadable(o)){info(`Cache restore skipped: the effective cache-mode '${o}' does not permit reads.`),debug(`Skipped restore for paths [${e.join(`, `)}] with primary key '${t}'.`);return}switch(a){case`v2`:return yield restoreCacheV2(e,t,n,r,i);default:return yield restoreCacheV1(e,t,n,r,i)}})}function restoreCacheV1(e,t,n,r){return __awaiter$3(this,arguments,void 0,function*(e,t,n,r,i=!1){n||=[];let a=[t,...n];if(debug(`Resolved Keys:`),debug(JSON.stringify(a)),a.length>10)throw new pv(`Key Validation Error: Keys are limited to a maximum of 10.`);for(let e of a)checkKey(e);let o=yield getCompressionMethod(),s=``;try{let t;try{t=yield getCacheEntry(a,e,{compressionMethod:o,enableCrossOsArchive:i})}catch(e){let t=e?.message??``;throw t.includes(gv)?new _v(t):e}if(!t?.archiveLocation)return;if(r?.lookupOnly)return info(`Lookup only - skipping download`),t.cacheKey;s=u.join(yield createTempDirectory(),getCacheFileName(o)),debug(`Archive Path: ${s}`),yield downloadCache(t.archiveLocation,s,r),isDebug()&&(yield listTar(s,o));let n=getArchiveFileSizeInBytes(s);return info(`Cache Size: ~${Math.round(n/1048576)} MB (${n} B)`),yield extractTar(s,o),info(`Cache restored successfully`),t.cacheKey}catch(e){let t=e;if(t.name===pv.name)throw e;t instanceof Pn&&typeof t.statusCode==`number`&&t.statusCode>=500?error(`Failed to restore: ${e.message}`):warning(`Failed to restore: ${e.message}`)}finally{try{yield unlinkFile(s)}catch(e){debug(`Failed to delete archive: ${e}`)}}})}function restoreCacheV2(e,t,n,r){return __awaiter$3(this,arguments,void 0,function*(e,t,n,r,i=!1){r=Object.assign(Object.assign({},r),{useAzureSdk:!0}),n||=[];let a=[t,...n];if(debug(`Resolved Keys:`),debug(JSON.stringify(a)),a.length>10)throw new pv(`Key Validation Error: Keys are limited to a maximum of 10.`);for(let e of a)checkKey(e);let o=``;try{let s=internalCacheTwirpClient(),c=yield getCompressionMethod(),l={key:t,restoreKeys:n,version:getCacheVersion(e,c,i)},d;try{d=yield s.GetCacheEntryDownloadURL(l)}catch(e){let t=e?.message??``;throw t.includes(gv)?new _v(t):e}if(!d.ok){debug(`Cache not found for version ${l.version} of keys: ${a.join(`, `)}`);return}if(l.key===d.matchedKey?info(`Cache hit for: ${d.matchedKey}`):info(`Cache hit for restore-key: ${d.matchedKey}`),r?.lookupOnly)return info(`Lookup only - skipping download`),d.matchedKey;o=u.join(yield createTempDirectory(),getCacheFileName(c)),debug(`Archive path: ${o}`),debug(`Starting download of archive to: ${o}`),yield downloadCache(d.signedDownloadUrl,o,r);let f=getArchiveFileSizeInBytes(o);return info(`Cache Size: ~${Math.round(f/1048576)} MB (${f} B)`),isDebug()&&(yield listTar(o,c)),yield extractTar(o,c),info(`Cache restored successfully`),d.matchedKey}catch(e){let t=e;if(t.name===pv.name)throw e;t instanceof Pn&&typeof t.statusCode==`number`&&t.statusCode>=500?error(`Failed to restore: ${e.message}`):warning(`Failed to restore: ${e.message}`)}finally{try{o&&(yield unlinkFile(o))}catch(e){debug(`Failed to delete archive: ${e}`)}}})}function saveCache$1(e,t,n){return __awaiter$3(this,arguments,void 0,function*(e,t,n,r=!1){let i=getCacheServiceVersion();debug(`Cache service version: ${i}`),checkPaths(e),checkKey(t);let a=getCacheMode();if(!isCacheWritable(a))return info(`Cache save skipped: the effective cache-mode '${a}' does not permit writes.`),debug(`Skipped save for paths [${e.join(`, `)}] with key '${t}'.`),-1;switch(i){case`v2`:return yield saveCacheV2(e,t,n,r);default:return yield saveCacheV1(e,t,n,r)}})}function saveCacheV1(e,t,n){return __awaiter$3(this,arguments,void 0,function*(e,t,n,r=!1){let i=yield getCompressionMethod(),a=-1,o=yield resolvePaths(e);if(debug(`Cache Paths:`),debug(`${JSON.stringify(o)}`),o.length===0)throw Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`);let s=yield createTempDirectory(),c=u.join(s,getCacheFileName(i));debug(`Archive Path: ${c}`);try{yield createTar(s,o,i),isDebug()&&(yield listTar(c,i));let l=getArchiveFileSizeInBytes(c);if(debug(`File Size: ${l}`),l>10737418240&&!isGhes())throw Error(`Cache size of ~${Math.round(l/1048576)} MB (${l} B) is over the 10GB limit, not saving cache.`);debug(`Reserving Cache`);let u=yield reserveCache(t,e,{compressionMethod:i,enableCrossOsArchive:r,cacheSize:l});if(u?.result?.cacheId)a=u?.result?.cacheId;else if(u?.statusCode===400)throw Error(u?.error?.message??`Cache size of ~${Math.round(l/1048576)} MB (${l} B) is over the data cap limit, not saving cache.`);else{let e=u?.error?.message;throw e?.startsWith(`cache write denied:`)?new hv(`Unable to reserve cache with key ${t}. More details: ${e}`):new mv(`Unable to reserve cache with key ${t}, another job may be creating this cache. More details: ${u?.error?.message}`)}debug(`Saving Cache (ID: ${a})`),yield saveCache$2(a,c,``,n)}catch(e){let t=e;if(t.name===pv.name)throw e;t.name===mv.name?info(`Failed to save: ${t.message}`):t instanceof Pn&&typeof t.statusCode==`number`&&t.statusCode>=500?error(`Failed to save: ${t.message}`):warning(`Failed to save: ${t.message}`)}finally{try{yield unlinkFile(c)}catch(e){debug(`Failed to delete archive: ${e}`)}}return a})}function saveCacheV2(e,t,n){return __awaiter$3(this,arguments,void 0,function*(e,t,n,r=!1){n=Object.assign(Object.assign({},n),{uploadChunkSize:67108864,uploadConcurrency:8,useAzureSdk:!0});let i=yield getCompressionMethod(),a=internalCacheTwirpClient(),o=-1,s=yield resolvePaths(e);if(debug(`Cache Paths:`),debug(`${JSON.stringify(s)}`),s.length===0)throw Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`);let c=yield createTempDirectory(),l=u.join(c,getCacheFileName(i));debug(`Archive Path: ${l}`);try{yield createTar(c,s,i),isDebug()&&(yield listTar(l,i));let u=getArchiveFileSizeInBytes(l);debug(`File Size: ${u}`),n.archiveSizeBytes=u,debug(`Reserving Cache`);let d=getCacheVersion(e,i,r),f={key:t,version:d},p;try{let e=yield a.CreateCacheEntry(f);if(!e.ok)throw e.message&&!e.message.startsWith(`cache write denied:`)&&warning(`Cache reservation failed: ${e.message}`),Error(e.message||`Response was not ok`);p=e.signedUploadUrl}catch(e){debug(`Failed to reserve cache: ${e}`);let n=e?.message??``;throw n.startsWith(`cache write denied:`)?new hv(`Unable to reserve cache with key ${t}. More details: ${n}`):new mv(`Unable to reserve cache with key ${t}, another job may be creating this cache.`)}debug(`Attempting to upload cache located at: ${l}`),yield saveCache$2(o,l,p,n);let h={key:t,version:d,sizeBytes:`${u}`},g=yield a.FinalizeCacheEntryUpload(h);if(debug(`FinalizeCacheEntryUploadResponse: ${g.ok}`),!g.ok)throw g.message?new vv(g.message):Error(`Unable to finalize cache with key ${t}, another job may be finalizing this cache.`);o=parseInt(g.entryId)}catch(e){let t=e;if(t.name===pv.name)throw e;t.name===mv.name?info(`Failed to save: ${t.message}`):t.name===vv.name?warning(t.message):t instanceof Pn&&typeof t.statusCode==`number`&&t.statusCode>=500?error(`Failed to save: ${t.message}`):warning(`Failed to save: ${t.message}`)}finally{try{yield unlinkFile(l)}catch(e){debug(`Failed to delete archive: ${e}`)}}return o})}function resolveSfwEnabled(e,t,n){return e?!pkgPrNewCommitSha(t)||(n(`sfw was requested but is automatically disabled for Vite+ preview build ${t}; Socket Firewall Free will not be used.`),!1):!1}const yv=`v1.15.1`,bv=`https://github.com/SocketDev/sfw-free/releases/download/${yv}`,xv=2e3;function isSfwSupported(e=process.platform,t=process.arch,n=isMuslLinux()){try{return!!getSfwAssetName(e,t,n)}catch{return!1}}function isMuslLinux(){if(process.platform!==`linux`)return!1;try{let e=process.report?.getReport();if(e?.header&&!e.header.glibcVersionRuntime)return!0}catch{}return I(`/etc/alpine-release`)}function getSfwAssetName(e,t,n){if(e===`darwin`){if(t===`arm64`)return`sfw-free-macos-arm64`;if(t===`x64`)return`sfw-free-macos-x86_64`}else if(e===`linux`){if(t===`arm64`)return n?`sfw-free-musl-linux-arm64`:`sfw-free-linux-arm64`;if(t===`x64`)return n?`sfw-free-musl-linux-x86_64`:`sfw-free-linux-x86_64`}else if(e===`win32`){if(t===`arm64`)return`sfw-free-windows-arm64.exe`;if(t===`x64`)return`sfw-free-windows-x86_64.exe`}throw Error(`Unsupported platform/arch for sfw: ${e}/${t}${e===`linux`?` (${n?`musl`:`glibc`})`:``}`)}function getSfwBinDir(){let e=process.env.RUNNER_TEMP||process.env.TMPDIR||process.env.TEMP||`/tmp`;return ae(e,`sfw-bin`)}async function installSfw(){let e=getSfwAssetName(process.platform,process.arch,isMuslLinux()),t=`${bv}/${e}`,n=getSfwBinDir();fe(n,{recursive:!0});let r=ae(n,process.platform===`win32`?`sfw.exe`:`sfw`),i=`sfw-${yv}-${process.platform}-${process.arch}-${isMuslLinux()?`musl`:`glibc`}`;try{let e=await restoreCache$1([n],i);if(e&&I(r)){process.platform!==`win32`&&de(r,493),addPath(n),info(`sfw restored from cache: ${e}`);return}}catch(e){warning(`sfw cache restore failed (${e instanceof Error?e.message:String(e)}); falling through to download.`)}info(`Installing sfw from ${t}...`);let a=``;for(let e=1;e<=2;e++){try{let e=await runDownloadCommand(t,r);if(e===0&&I(r)){process.platform!==`win32`&&de(r,493),addPath(n),info(`sfw installed at ${r}`);try{await saveCache$1([n],i),info(`sfw cached under key: ${i}`)}catch(e){warning(`sfw cache save failed (${e instanceof Error?e.message:String(e)}); continuing.`)}return}a=`exit code ${e}`}catch(e){a=e instanceof Error?e.message:String(e)}e<2&&(warning(`Failed to install sfw from ${t} (${a}). Retrying in ${xv}ms... (attempt ${e+1}/2)`),await le(xv))}throw Error(`Failed to install sfw from ${t} after 2 attempts: ${a}`)}function findSfwOnPath(){let e=process.platform===`win32`?`where`:`which`;try{let t=Oe(e,[`sfw`],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).split(/\r?\n/).find(e=>e.trim().length>0);return t?t.trim():null}catch{return null}}async function setupSfw(e){if(!resolveSfwEnabled(e.sfw,e.version,warning))return!1;if(e.runInstall.length===0)return info("sfw was requested but `run-install` is disabled; sfw will not be invoked."),!1;let t=findSfwOnPath();return t?(info(`Using existing sfw on PATH: ${t}`),!0):isSfwSupported()?(await installSfw(),!0):(warning(`sfw has no published binary for this runner's platform/architecture (${`process.platform=${process.platform}, process.arch=${process.arch}, musl=${isMuslLinux()}`}) and none was found on PATH; falling back to plain \`vp install\`. To enable sfw here, install a working sfw binary on PATH in an earlier step (e.g. via \`socketdev/action@\` or a custom install).`),!1)}async function runDownloadCommand(e,t){let n={ignoreReturnCode:!0};return process.platform===`win32`?exec(`pwsh`,[`-Command`,`Invoke-WebRequest -UseBasicParsing -Uri '${e}' -OutFile '${t}' -TimeoutSec 60`],n):exec(`bash`,[`-c`,`set -o pipefail; curl -fsSL --connect-timeout 5 --max-time 60 -o '${t}' '${e}'`],n)}const Sv=/Command 'vp' not found in PATH/;function isSfwVpNotFoundFlake(e,t){return Sv.test(t)||Sv.test(e)}async function warmPowerShellCommandCache(){if(process.platform===`win32`)try{await getExecOutput(`powershell.exe`,[`-NoProfile`,`-Command`,`Get-Command vp`],{ignoreReturnCode:!0})}catch(e){info(`PowerShell warm-up failed (${String(e)}); retrying sfw anyway.`)}}function tailOutput(e,t){let n=e.trim();return n.length<=t?n:`…(truncated, showing last ${t} chars)…\n${n.slice(-t)}`}async function runViteInstall(e){let t=getConfiguredProjectDir(e);for(let n of e.runInstall){let r=[`install`];n.args&&r.push(...n.args);let i=e.sfw?`sfw`:`vp`,a=e.sfw?[`vp`,...r]:r,o=getInstallCwd(t,n.cwd),s=`${i} ${a.join(` `)}`,attempt=async e=>{startGroup(`Running ${e} in ${o}...`);try{return await getExecOutput(i,a,{cwd:o,ignoreReturnCode:!0})}finally{endGroup()}};try{let t=await attempt(s);if(t.exitCode!==0&&e.sfw&&isSfwVpNotFoundFlake(t.stdout,t.stderr)&&(warning(`sfw reported vp as not found even though it is on PATH. This is a known sfw flake on Windows: a cold PowerShell start exceeds sfw's 10s command-resolution timeout and the timeout is misreported as not-found. Warming the PowerShell command cache and retrying once.`),await warmPowerShellCommandCache(),t=await attempt(`${s} (retry)`)),t.exitCode===0){info(`Successfully ran ${s}`);continue}let n=t.stderr.trim()||t.stdout.trim();n&&error(tailOutput(n,4e3),{title:`${s} failed`}),setFailed(`Command "${s}" (cwd: ${o}) exited with code ${t.exitCode}`)}catch(e){setFailed(`Failed to run ${s}: ${String(e)}`)}}}function getOptions(e){let t={followSymbolicLinks:!0,implicitDescendants:!0,matchDirectories:!0,omitBrokenSymbolicLinks:!0,excludeHiddenFiles:!1};return e&&(typeof e.followSymbolicLinks==`boolean`&&(t.followSymbolicLinks=e.followSymbolicLinks,debug(`followSymbolicLinks '${t.followSymbolicLinks}'`)),typeof e.implicitDescendants==`boolean`&&(t.implicitDescendants=e.implicitDescendants,debug(`implicitDescendants '${t.implicitDescendants}'`)),typeof e.matchDirectories==`boolean`&&(t.matchDirectories=e.matchDirectories,debug(`matchDirectories '${t.matchDirectories}'`)),typeof e.omitBrokenSymbolicLinks==`boolean`&&(t.omitBrokenSymbolicLinks=e.omitBrokenSymbolicLinks,debug(`omitBrokenSymbolicLinks '${t.omitBrokenSymbolicLinks}'`)),typeof e.excludeHiddenFiles==`boolean`&&(t.excludeHiddenFiles=e.excludeHiddenFiles,debug(`excludeHiddenFiles '${t.excludeHiddenFiles}'`))),t}const Cv=process.platform===`win32`;function dirname$1(e){if(e=safeTrimTrailingSeparator(e),Cv&&/^\\\\[^\\]+(\\[^\\]+)?$/.test(e))return e;let t=u.dirname(e);return Cv&&/^\\\\[^\\]+\\[^\\]+\\$/.test(t)&&(t=safeTrimTrailingSeparator(t)),t}function ensureAbsoluteRoot(e,t){if(g(e,`ensureAbsoluteRoot parameter 'root' must not be empty`),g(t,`ensureAbsoluteRoot parameter 'itemPath' must not be empty`),hasAbsoluteRoot(t))return t;if(Cv){if(t.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)){let e=process.cwd();return g(e.match(/^[A-Z]:\\/i),`Expected current directory to start with an absolute drive root. Actual '${e}'`),t[0].toUpperCase()===e[0].toUpperCase()?t.length===2?`${t[0]}:\\${e.substr(3)}`:(e.endsWith(`\\`)||(e+=`\\`),`${t[0]}:\\${e.substr(3)}${t.substr(2)}`):`${t[0]}:\\${t.substr(2)}`}if(normalizeSeparators(t).match(/^\\$|^\\[^\\]/)){let e=process.cwd();return g(e.match(/^[A-Z]:\\/i),`Expected current directory to start with an absolute drive root. Actual '${e}'`),`${e[0]}:\\${t.substr(1)}`}}return g(hasAbsoluteRoot(e),`ensureAbsoluteRoot parameter 'root' must have an absolute root`),e.endsWith(`/`)||Cv&&e.endsWith(`\\`)||(e+=u.sep),e+t}function hasAbsoluteRoot(e){return g(e,`hasAbsoluteRoot parameter 'itemPath' must not be empty`),e=normalizeSeparators(e),Cv?e.startsWith(`\\\\`)||/^[A-Z]:\\/i.test(e):e.startsWith(`/`)}function hasRoot(e){return g(e,`isRooted parameter 'itemPath' must not be empty`),e=normalizeSeparators(e),Cv?e.startsWith(`\\`)||/^[A-Z]:/i.test(e):e.startsWith(`/`)}function normalizeSeparators(e){return e||=``,Cv?(e=e.replace(/\//g,`\\`),(/^\\\\+[^\\]/.test(e)?`\\`:``)+e.replace(/\\\\+/g,`\\`)):e.replace(/\/\/+/g,`/`)}function safeTrimTrailingSeparator(e){return e?(e=normalizeSeparators(e),!e.endsWith(u.sep)||e===u.sep||Cv&&/^[A-Z]:\\$/i.test(e)?e:e.substr(0,e.length-1)):``}var wv;(function(e){e[e.None=0]=`None`,e[e.Directory=1]=`Directory`,e[e.File=2]=`File`,e[e.All=3]=`All`})(wv||={});const Tv=process.platform===`win32`;function getSearchPaths(e){e=e.filter(e=>!e.negate);let t={};for(let n of e){let e=Tv?n.searchPath.toUpperCase():n.searchPath;t[e]=`candidate`}let n=[];for(let r of e){let e=Tv?r.searchPath.toUpperCase():r.searchPath;if(t[e]===`included`)continue;let i=!1,a=e,o=dirname$1(a);for(;o!==a;){if(t[o]){i=!0;break}a=o,o=dirname$1(a)}i||(n.push(r.searchPath),t[e]=`included`)}return n}function match$1(e,t){let n=wv.None;for(let r of e)r.negate?n&=~r.match(t):n|=r.match(t);return n}function partialMatch(e,t){return e.some(e=>!e.negate&&e.partialMatch(t))}const balanced=(e,t,n)=>{let r=e instanceof RegExp?maybeMatch(e,n):e,i=t instanceof RegExp?maybeMatch(t,n):t,a=r!==null&&i!=null&&range(r,i,n);return a&&{start:a[0],end:a[1],pre:n.slice(0,a[0]),body:n.slice(a[0]+r.length,a[1]),post:n.slice(a[1]+i.length)}},maybeMatch=(e,t)=>{let n=t.match(e);return n?n[0]:null},range=(e,t,n)=>{let r,i,a,o,s,c=n.indexOf(e),l=n.indexOf(t,c+1),u=c;if(c>=0&&l>0){if(e===t)return[c,l];for(r=[],a=n.length;u>=0&&!s;){if(u===c)r.push(u),c=n.indexOf(e,u+1);else if(r.length===1){let e=r.pop();e!==void 0&&(s=[e,l])}else i=r.pop(),i!==void 0&&i=0?c:l}r.length&&o!==void 0&&(s=[a,o])}return s},Ev=`\0SLASH`+Math.random()+`\0`,Dv=`\0OPEN`+Math.random()+`\0`,Ov=`\0CLOSE`+Math.random()+`\0`,kv=`\0COMMA`+Math.random()+`\0`,Av=`\0PERIOD`+Math.random()+`\0`,jv=new RegExp(Ev,`g`),Mv=new RegExp(Dv,`g`),Nv=new RegExp(Ov,`g`),Pv=new RegExp(kv,`g`),Fv=new RegExp(Av,`g`),Iv=/\\\\/g,Lv=/\\{/g,Rv=/\\}/g,zv=/\\,/g,Bv=/\\\./g;function numeric(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function escapeBraces(e){return e.replace(Iv,Ev).replace(Lv,Dv).replace(Rv,Ov).replace(zv,kv).replace(Bv,Av)}function unescapeBraces(e){return e.replace(jv,`\\`).replace(Mv,`{`).replace(Nv,`}`).replace(Pv,`,`).replace(Fv,`.`)}function parseCommaParts(e){if(!e)return[``];let t=[],n=balanced(`{`,`}`,e);if(!n)return e.split(`,`);let{pre:r,body:i,post:a}=n,o=r.split(`,`);o[o.length-1]+=`{`+i+`}`;let s=parseCommaParts(a);return a.length&&(o[o.length-1]+=s.shift(),o.push.apply(o,s)),t.push.apply(t,o),t}function expand(e,t={}){if(!e)return[];let{max:n=1e5}=t;return e.slice(0,2)===`{}`&&(e=`\\{\\}`+e.slice(2)),expand_(escapeBraces(e),n,!0).map(unescapeBraces)}function embrace(e){return`{`+e+`}`}function isPadded(e){return/^-?0\d/.test(e)}function lte(e,t){return e<=t}function gte(e,t){return e>=t}function expand_(e,t,n){let r=[],i=balanced(`{`,`}`,e);if(!i)return[e];let a=i.pre,o=i.post.length?expand_(i.post,t,!1):[``];if(/\$$/.test(i.pre))for(let e=0;e=0;if(!l&&!u)return i.post.match(/,(?!,).*\}/)?(e=i.pre+`{`+i.body+Ov+i.post,expand_(e,t,!0)):[e];let d;if(l)d=i.body.split(/\.\./);else if(d=parseCommaParts(i.body),d.length===1&&d[0]!==void 0&&(d=expand_(d[0],t,!1).map(embrace),d.length===1))return o.map(e=>i.pre+d[0]+e);let f;if(l&&d[0]!==void 0&&d[1]!==void 0){let e=numeric(d[0]),t=numeric(d[1]),n=Math.max(d[0].length,d[1].length),r=d.length===3&&d[2]!==void 0?Math.max(Math.abs(numeric(d[2])),1):1,i=lte;t0){let n=Array(t+1).join(`0`);e=o<0?`-`+n+e.slice(1):n+e}}f.push(e)}}else{f=[];for(let e=0;e{if(typeof e!=`string`)throw TypeError(`invalid pattern`);if(e.length>65536)throw TypeError(`pattern is too long`)},Vv={"[:alnum:]":[`\\p{L}\\p{Nl}\\p{Nd}`,!0],"[:alpha:]":[`\\p{L}\\p{Nl}`,!0],"[:ascii:]":[`\\x00-\\x7f`,!1],"[:blank:]":[`\\p{Zs}\\t`,!0],"[:cntrl:]":[`\\p{Cc}`,!0],"[:digit:]":[`\\p{Nd}`,!0],"[:graph:]":[`\\p{Z}\\p{C}`,!0,!0],"[:lower:]":[`\\p{Ll}`,!0],"[:print:]":[`\\p{C}`,!0],"[:punct:]":[`\\p{P}`,!0],"[:space:]":[`\\p{Z}\\t\\r\\n\\v\\f`,!0],"[:upper:]":[`\\p{Lu}`,!0],"[:word:]":[`\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}`,!0],"[:xdigit:]":[`A-Fa-f0-9`,!1]},braceEscape=e=>e.replace(/[[\]\\-]/g,`\\$&`),regexpEscape=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),rangesToString=e=>e.join(``),parseClass=(e,t)=>{let n=t;if(e.charAt(n)!==`[`)throw Error(`not in a brace expression`);let r=[],i=[],a=n+1,o=!1,s=!1,c=!1,l=!1,u=n,d=``;WHILE:for(;ad?r.push(braceEscape(d)+`-`+braceEscape(t)):t===d&&r.push(braceEscape(t)),d=``,a++;continue}if(e.startsWith(`-]`,a+1)){r.push(braceEscape(t+`-`)),a+=2;continue}if(e.startsWith(`-`,a+1)){d=t,a+=2;continue}r.push(braceEscape(t)),a++}if(un?t?e.replace(/\[([^/\\])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^/\\])\]/g,`$1$2`).replace(/\\([^/])/g,`$1`):t?e.replace(/\[([^/\\{}])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^/\\{}])\]/g,`$1$2`).replace(/\\([^/{}])/g,`$1`);var Hv;const Uv=new Set([`!`,`?`,`+`,`*`,`@`]),isExtglobType=e=>Uv.has(e),isExtglobAST=e=>isExtglobType(e.type),Wv=new Map([[`!`,[`@`]],[`?`,[`?`,`@`]],[`@`,[`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`]]]),Gv=new Map([[`!`,[`?`]],[`@`,[`?`]],[`+`,[`?`,`*`]]]),Kv=new Map([[`!`,[`?`,`@`]],[`?`,[`?`,`@`]],[`@`,[`?`,`@`]],[`*`,[`*`,`+`,`?`,`@`]],[`+`,[`+`,`@`,`?`,`*`]]]),qv=new Map([[`!`,new Map([[`!`,`@`]])],[`?`,new Map([[`*`,`*`],[`+`,`*`]])],[`@`,new Map([[`!`,`!`],[`?`,`?`],[`@`,`@`],[`*`,`*`],[`+`,`+`]])],[`+`,new Map([[`?`,`*`],[`*`,`*`]])]]),Jv=`(?!\\.)`,Yv=new Set([`[`,`.`]),Xv=new Set([`..`,`.`]),Zv=new Set(`().*{}+?[]^$\\!`),regExpEscape$1=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),Qv=`[^/]+?`;let $v=0;var AST=class{type;#e;#t;#n=!1;#r=[];#i;#a;#o;#s=!1;#c;#l;#u=!1;id=++$v;get depth(){return(this.#i?.depth??-1)+1}[Symbol.for(`nodejs.util.inspect.custom`)](){return{"@@type":`AST`,id:this.id,type:this.type,root:this.#e.id,parent:this.#i?.id,depth:this.depth,partsLength:this.#r.length,parts:this.#r}}constructor(e,t,n={}){this.type=e,e&&(this.#t=!0),this.#i=t,this.#e=this.#i?this.#i.#e:this,this.#c=this.#e===this?n:this.#e.#c,this.#o=this.#e===this?[]:this.#e.#o,e===`!`&&!this.#e.#s&&this.#o.push(this),this.#a=this.#i?this.#i.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#r)if(typeof e!=`string`&&(e.type||e.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#l===void 0?this.#l=this.type?this.type+`(`+this.#r.map(e=>String(e)).join(`|`)+`)`:this.#r.map(e=>String(e)).join(``):this.#l}#d(){if(this!==this.#e)throw Error(`should only call on root`);if(this.#s)return this;this.toString(),this.#s=!0;let e;for(;e=this.#o.pop();){if(e.type!==`!`)continue;let t=e,n=t.#i;for(;n;){for(let r=t.#a+1;!n.type&&rtypeof e==`string`?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#s&&this.#i?.type===`!`)&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#i?.isStart())return!1;if(this.#a===0)return!0;let e=this.#i;for(let t=0;ttypeof e!=`string`),r=this.#r.map(t=>{let[r,i,a,o]=typeof t==`string`?Hv.#C(t,this.#t,n):t.toRegExpSource(e);return this.#t=this.#t||a,this.#n=this.#n||o,r}).join(``),i=``;if(this.isStart()&&typeof this.#r[0]==`string`&&!(this.#r.length===1&&Xv.has(this.#r[0]))){let n=Yv,a=t&&n.has(r.charAt(0))||r.startsWith(`\\.`)&&n.has(r.charAt(2))||r.startsWith(`\\.\\.`)&&n.has(r.charAt(4)),o=!t&&!e&&n.has(r.charAt(0));i=a?`(?!(?:^|/)\\.\\.?(?:$|/))`:o?Jv:``}let a=``;return this.isEnd()&&this.#e.#s&&this.#i?.type===`!`&&(a=`(?:$|\\/)`),[i+r+a,unescape(r),this.#t=!!this.#t,this.#n]}let n=this.type===`*`||this.type===`+`,r=this.type===`!`?`(?:(?!(?:`:`(?:`,i=this.#S(t);if(this.isStart()&&this.isEnd()&&!i&&this.type!==`!`){let e=this.toString(),t=this;return t.#r=[e],t.type=null,t.#t=void 0,[e,unescape(this.toString()),!1,!1]}let a=!n||e||t?``:this.#S(!0);a===i&&(a=``),a&&(i=`(?:${i})(?:${a})*?`);let o=``;if(this.type===`!`&&this.#u)o=(this.isStart()&&!t?Jv:``)+Qv;else{let n=this.type===`!`?`))`+(this.isStart()&&!t&&!e?Jv:``)+`[^/]*?)`:this.type===`@`?`)`:this.type===`?`?`)?`:this.type===`+`&&a?`)`:this.type===`*`&&a?`)?`:`)${this.type}`;o=r+i+n}return[o,unescape(i),this.#t=!!this.#t,this.#n]}#x(){if(isExtglobAST(this)){let e=0,t=!1;do{t=!0;for(let e=0;e{if(typeof t==`string`)throw Error(`string type in extglob ast??`);let[n,r,i,a]=t.toRegExpSource(e);return this.#n=this.#n||a,n}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join(`|`)}static#C(e,t,n=!1){let r=!1,i=``,a=!1,o=!1;for(let s=0;sn?t?e.replace(/[?*()[\]{}]/g,`[$&]`):e.replace(/[?*()[\]\\{}]/g,`\\$&`):t?e.replace(/[?*()[\]]/g,`[$&]`):e.replace(/[?*()[\]\\]/g,`\\$&`),minimatch=(e,t,n={})=>(assertValidPattern(t),!n.nocomment&&t.charAt(0)===`#`?!1:new Minimatch(t,n).match(e)),ey=/^\*+([^+@!?*[(]*)$/,starDotExtTest=e=>t=>!t.startsWith(`.`)&&t.endsWith(e),starDotExtTestDot=e=>t=>t.endsWith(e),starDotExtTestNocase=e=>(e=e.toLowerCase(),t=>!t.startsWith(`.`)&&t.toLowerCase().endsWith(e)),starDotExtTestNocaseDot=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),ty=/^\*+\.\*+$/,starDotStarTest=e=>!e.startsWith(`.`)&&e.includes(`.`),starDotStarTestDot=e=>e!==`.`&&e!==`..`&&e.includes(`.`),ny=/^\.\*+$/,dotStarTest=e=>e!==`.`&&e!==`..`&&e.startsWith(`.`),ry=/^\*+$/,starTest=e=>e.length!==0&&!e.startsWith(`.`),starTestDot=e=>e.length!==0&&e!==`.`&&e!==`..`,iy=/^\?+([^+@!?*[(]*)?$/,qmarksTestNocase=([e,t=``])=>{let n=qmarksTestNoExt([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},qmarksTestNocaseDot=([e,t=``])=>{let n=qmarksTestNoExtDot([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},qmarksTestDot=([e,t=``])=>{let n=qmarksTestNoExtDot([e]);return t?e=>n(e)&&e.endsWith(t):n},qmarksTest=([e,t=``])=>{let n=qmarksTestNoExt([e]);return t?e=>n(e)&&e.endsWith(t):n},qmarksTestNoExt=([e])=>{let t=e.length;return e=>e.length===t&&!e.startsWith(`.`)},qmarksTestNoExtDot=([e])=>{let t=e.length;return e=>e.length===t&&e!==`.`&&e!==`..`},ay=typeof process==`object`&&process?typeof process.env==`object`&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:`posix`,oy={win32:{sep:`\\`},posix:{sep:`/`}};minimatch.sep=ay===`win32`?oy.win32.sep:oy.posix.sep;const sy=Symbol(`globstar **`);minimatch.GLOBSTAR=sy,minimatch.filter=(e,t={})=>n=>minimatch(n,e,t);const ext=(e,t={})=>Object.assign({},e,t);minimatch.defaults=e=>{if(!e||typeof e!=`object`||!Object.keys(e).length)return minimatch;let t=minimatch;return Object.assign((n,r,i={})=>t(n,r,ext(e,i)),{Minimatch:class extends t.Minimatch{constructor(t,n={}){super(t,ext(e,n))}static defaults(n){return t.defaults(ext(e,n)).Minimatch}},AST:class extends t.AST{constructor(t,n,r={}){super(t,n,ext(e,r))}static fromGlob(n,r={}){return t.AST.fromGlob(n,ext(e,r))}},unescape:(n,r={})=>t.unescape(n,ext(e,r)),escape:(n,r={})=>t.escape(n,ext(e,r)),filter:(n,r={})=>t.filter(n,ext(e,r)),defaults:n=>t.defaults(ext(e,n)),makeRe:(n,r={})=>t.makeRe(n,ext(e,r)),braceExpand:(n,r={})=>t.braceExpand(n,ext(e,r)),match:(n,r,i={})=>t.match(n,r,ext(e,i)),sep:t.sep,GLOBSTAR:sy})};const braceExpand=(e,t={})=>(assertValidPattern(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:expand(e,{max:t.braceExpandMax}));minimatch.braceExpand=braceExpand,minimatch.makeRe=(e,t={})=>new Minimatch(e,t).makeRe(),minimatch.match=(e,t,n={})=>{let r=new Minimatch(t,n);return e=e.filter(e=>r.match(e)),r.options.nonull&&!e.length&&e.push(t),e};const cy=/[?*]|[+@!]\(.*?\)|\[|\]/,regExpEscape=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`);var Minimatch=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(e,t={}){assertValidPattern(e),t||={},this.options=t,this.maxGlobstarRecursion=t.maxGlobstarRecursion??200,this.pattern=e,this.platform=t.platform||ay,this.isWindows=this.platform===`win32`,this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,`/`)),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot===void 0?!!(this.isWindows&&this.nocase):t.windowsNoMagicRoot,this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!=`string`)return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)===`#`){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...e)=>console.error(...e)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(e=>this.slashSplit(e));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let r=this.globParts.map((e,t,n)=>{if(this.isWindows&&this.windowsNoMagicRoot){let t=e[0]===``&&e[1]===``&&(e[2]===`?`||!cy.test(e[2]))&&!cy.test(e[3]),n=/^[a-z]:/i.test(e[0]);if(t)return[...e.slice(0,4),...e.slice(4).map(e=>this.parse(e))];if(n)return[e[0],...e.slice(1).map(e=>this.parse(e))]}return e.map(e=>this.parse(e))});if(this.debug(this.pattern,r),this.set=r.filter(e=>e.indexOf(!1)===-1),this.isWindows)for(let e=0;e=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):e=t>=1?this.levelOneOptimize(e):this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(e=>{let t=-1;for(;(t=e.indexOf(`**`,t+1))!==-1;){let n=t;for(;e[n+1]===`**`;)n++;n!==t&&e.splice(t,n-t)}return e})}levelOneOptimize(e){return e.map(e=>(e=e.reduce((e,t)=>{let n=e[e.length-1];return t===`**`&&n===`**`?e:t===`..`&&n&&n!==`..`&&n!==`.`&&n!==`**`?(e.pop(),e):(e.push(t),e)},[]),e.length===0?[``]:e))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let n=1;nr&&n.splice(r+1,i-r);let a=n[r+1],o=n[r+2],s=n[r+3];if(a!==`..`||!o||o===`.`||o===`..`||!s||s===`.`||s===`..`)continue;t=!0,n.splice(r,1);let c=n.slice(0);c[r]=`**`,e.push(c),r--}if(!this.preserveMultipleSlashes){for(let e=1;ee.length)}partsMatch(e,t,n=!1){let r=0,i=0,a=[],o=``;for(;r=2&&(e=this.levelTwoFileOptimize(e)),t.includes(sy)?this.#e(e,t,n,r,i):this.#n(e,t,n,r,i)}#e(e,t,n,r,i){let a=t.indexOf(sy,i),o=t.lastIndexOf(sy),[s,c,l]=n?[t.slice(i,a),t.slice(a+1),[]]:[t.slice(i,a),t.slice(a+1,o),t.slice(o+1)];if(s.length){let t=e.slice(r,r+s.length);if(!this.#n(t,s,n,0,0))return!1;r+=s.length,i+=s.length}let u=0;if(l.length){if(l.length+r>e.length)return!1;let t=e.length-l.length;if(this.#n(e,l,n,t,0))u=l.length;else{if(e[e.length-1]!==``||r+l.length===e.length||(t--,!this.#n(e,l,n,t,0)))return!1;u=l.length+1}}if(!c.length){let t=!!u;for(let n=r;n{let t=e.map(e=>{if(e instanceof RegExp)for(let t of e.flags.split(``))r.add(t);return typeof e==`string`?regExpEscape(e):e===sy?sy:e._src});t.forEach((e,r)=>{let i=t[r+1],a=t[r-1];e===sy&&a!==sy&&(a===void 0?i!==void 0&&i!==sy?t[r+1]=`(?:\\/|`+n+`\\/)?`+i:t[r]=n:i===void 0?t[r-1]=a+`(?:\\/|\\/`+n+`)?`:i!==sy&&(t[r-1]=a+`(?:\\/|\\/`+n+`\\/)`+i,t[r+1]=sy))});let i=t.filter(e=>e!==sy);if(this.partial&&i.length>=1){let e=[];for(let t=1;t<=i.length;t++)e.push(i.slice(0,t).join(`/`));return`(?:`+e.join(`|`)+`)`}return i.join(`/`)}).join(`|`),[a,o]=e.length>1?[`(?:`,`)`]:[``,``];i=`^`+a+i+o+`$`,this.partial&&(i=`^(?:\\/|`+a+i.slice(1,-1)+o+`)$`),this.negate&&(i=`^(?!`+i+`).+$`);try{this.regexp=new RegExp(i,[...r].join(``))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split(`/`):this.isWindows&&/^\/\/[^/]+/.test(e)?[``,...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug(`match`,e,this.pattern),this.comment)return!1;if(this.empty)return e===``;if(e===`/`&&t)return!0;let n=this.options;this.isWindows&&(e=e.split(`\\`).join(`/`));let r=this.slashSplit(e);this.debug(this.pattern,`split`,r);let i=this.set;this.debug(this.pattern,`set`,i);let a=r[r.length-1];if(!a)for(let e=r.length-2;!a&&e>=0;e--)a=r[e];for(let e of i){let i=r;if(n.matchBase&&e.length===1&&(i=[a]),this.matchOne(i,e,t))return n.flipNegate?!0:!this.negate}return!n.flipNegate&&this.negate}static defaults(e){return minimatch.defaults(e).Minimatch}};minimatch.AST=AST,minimatch.Minimatch=Minimatch,minimatch.escape=escape,minimatch.unescape=unescape;const ly=process.platform===`win32`;var Path=class{constructor(e){if(this.segments=[],typeof e==`string`){if(g(e,`Parameter 'itemPath' must not be empty`),e=safeTrimTrailingSeparator(e),!hasRoot(e))this.segments=e.split(u.sep);else{let t=e,n=dirname$1(t);for(;n!==t;){let e=u.basename(t);this.segments.unshift(e),t=n,n=dirname$1(t)}this.segments.unshift(t)}}else{g(e.length>0,`Parameter 'itemPath' must not be an empty array`);for(let t=0;tPattern.getLiteral(e)).filter(e=>!a&&!(a=e===``));this.searchPath=new Path(o).toString(),this.rootRegExp=new RegExp(Pattern.regExpEscape(o[0]),uy?`i`:``),this.isImplicitPattern=t;let s={dot:!0,nobrace:!0,nocase:uy,nocomment:!0,noext:!0,nonegate:!0};i=uy?i.replace(/\\/g,`/`):i,this.minimatch=new Minimatch(i,s)}match(e){return this.segments[this.segments.length-1]===`**`?(e=normalizeSeparators(e),!e.endsWith(u.sep)&&this.isImplicitPattern===!1&&(e=`${e}${u.sep}`)):e=safeTrimTrailingSeparator(e),this.minimatch.match(e)?this.trailingSeparator?wv.Directory:wv.All:wv.None}partialMatch(e){return e=safeTrimTrailingSeparator(e),dirname$1(e)===e?this.rootRegExp.test(e):this.minimatch.matchOne(e.split(uy?/\\+/:/\/+/),this.minimatch.set[0],!0)}static globEscape(e){return(uy?e:e.replace(/\\/g,`\\\\`)).replace(/(\[)(?=[^/]+\])/g,`[[]`).replace(/\?/g,`[?]`).replace(/\*/g,`[*]`)}static fixupPattern(e,n){g(e,`pattern cannot be empty`);let r=new Path(e).segments.map(e=>Pattern.getLiteral(e));if(g(r.every((e,t)=>(e!==`.`||t===0)&&e!==`..`),`Invalid pattern '${e}'. Relative pathing '.' and '..' is not allowed.`),g(!hasRoot(e)||r[0],`Invalid pattern '${e}'. Root segment must not contain globs.`),e=normalizeSeparators(e),e===`.`||e.startsWith(`.${u.sep}`))e=Pattern.globEscape(process.cwd())+e.substr(1);else if(e===`~`||e.startsWith(`~${u.sep}`))n||=t.homedir(),g(n,`Unable to determine HOME directory`),g(hasAbsoluteRoot(n),`Expected HOME directory to be a rooted path. Actual '${n}'`),e=Pattern.globEscape(n)+e.substr(1);else if(uy&&(e.match(/^[A-Z]:$/i)||e.match(/^[A-Z]:[^\\]/i))){let t=ensureAbsoluteRoot(`C:\\dummy-root`,e.substr(0,2));e.length>2&&!t.endsWith(`\\`)&&(t+=`\\`),e=Pattern.globEscape(t)+e.substr(2)}else if(uy&&(e===`\\`||e.match(/^\\[^\\]/))){let t=ensureAbsoluteRoot(`C:\\dummy-root`,`\\`);t.endsWith(`\\`)||(t+=`\\`),e=Pattern.globEscape(t)+e.substr(1)}else e=ensureAbsoluteRoot(Pattern.globEscape(process.cwd()),e);return normalizeSeparators(e)}static getLiteral(e){let t=``;for(let n=0;n=0){if(r.length>1)return``;if(r){t+=r,n=i;continue}}}t+=r}return t}static regExpEscape(e){return e.replace(/[[\\^$.|?*+()]/g,`\\$&`)}},SearchState=class{constructor(e,t){this.path=e,this.level=t}},__awaiter$2=function(e,t,n,r){function adopt(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())})},__asyncValues$1=function(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof __values==`function`?__values(e):e[Symbol.iterator](),n={},verb(`next`),verb(`throw`),verb(`return`),n[Symbol.asyncIterator]=function(){return this},n);function verb(t){n[t]=e[t]&&function(n){return new Promise(function(r,i){n=e[t](n),settle(r,i,n.done,n.value)})}}function settle(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}},__await=function(e){return this instanceof __await?(this.v=e,this):new __await(e)},__asyncGenerator=function(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),verb(`next`),verb(`throw`),verb(`return`,awaitReturn),i[Symbol.asyncIterator]=function(){return this},i;function awaitReturn(e){return function(t){return Promise.resolve(t).then(e,reject)}}function verb(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||resume(e,t)})},t&&(i[e]=t(i[e])))}function resume(e,t){try{step(r[e](t))}catch(e){settle(a[0][3],e)}}function step(e){e.value instanceof __await?Promise.resolve(e.value.v).then(fulfill,reject):settle(a[0][2],e)}function fulfill(e){resume(`next`,e)}function reject(e){resume(`throw`,e)}function settle(e,t){e(t),a.shift(),a.length&&resume(a[0][0],a[0][1])}};const fy=process.platform===`win32`;var py=class DefaultGlobber{constructor(e){this.patterns=[],this.searchPaths=[],this.options=getOptions(e)}getSearchPaths(){return this.searchPaths.slice()}glob(){return __awaiter$2(this,void 0,void 0,function*(){var e,t,n,r;let i=[];try{for(var a=!0,o=__asyncValues$1(this.globGenerator()),s;s=yield o.next(),e=s.done,!e;a=!0){r=s.value,a=!1;let e=r;i.push(e)}}catch(e){t={error:e}}finally{try{!a&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return i})}globGenerator(){return __asyncGenerator(this,arguments,function*(){let e=getOptions(this.options),t=[];for(let n of this.patterns)t.push(n),e.implicitDescendants&&(n.trailingSeparator||n.segments[n.segments.length-1]!==`**`)&&t.push(new dy(n.negate,!0,n.segments.concat(`**`)));let n=[];for(let e of getSearchPaths(t)){debug(`Search path '${e}'`);try{yield __await(a.promises.lstat(e))}catch(e){if(e.code===`ENOENT`)continue;throw e}n.unshift(new SearchState(e,1))}let r=[];for(;n.length;){let i=n.pop(),o=match$1(t,i.path),s=!!o||partialMatch(t,i.path);if(!o&&!s)continue;let c=yield __await(DefaultGlobber.stat(i,e,r));if(c&&!(e.excludeHiddenFiles&&u.basename(i.path).match(/^\./))){if(c.isDirectory()){if(o&wv.Directory&&e.matchDirectories)yield yield __await(i.path);else if(!s)continue;let t=i.level+1,r=(yield __await(a.promises.readdir(i.path))).map(e=>new SearchState(u.join(i.path,e),t));n.push(...r.reverse())}else o&wv.File&&(yield yield __await(i.path))}}})}static create(e,t){return __awaiter$2(this,void 0,void 0,function*(){let n=new DefaultGlobber(t);fy&&(e=e.replace(/\r\n/g,` `),e=e.replace(/\r/g,` `));let r=e.split(` `).map(e=>e.trim());for(let e of r)if(!e||e.startsWith(`#`))continue;else n.patterns.push(new dy(e));return n.searchPaths.push(...getSearchPaths(n.patterns)),n})}static stat(e,t,n){return __awaiter$2(this,void 0,void 0,function*(){let r;if(t.followSymbolicLinks)try{r=yield a.promises.stat(e.path)}catch(n){if(n.code===`ENOENT`){if(t.omitBrokenSymbolicLinks){debug(`Broken symlink '${e.path}'`);return}throw Error(`No information found for the path '${e.path}'. This may indicate a broken symbolic link.`)}throw n}else r=yield a.promises.lstat(e.path);if(r.isDirectory()&&t.followSymbolicLinks){let t=yield a.promises.realpath(e.path);for(;n.length>=e.level;)n.pop();if(n.some(e=>e===t)){debug(`Symlink cycle detected for path '${e.path}' and realpath '${t}'`);return}n.push(t)}return r})}},__awaiter$1=function(e,t,n,r){function adopt(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())})},__asyncValues=function(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof __values==`function`?__values(e):e[Symbol.iterator](),n={},verb(`next`),verb(`throw`),verb(`return`),n[Symbol.asyncIterator]=function(){return this},n);function verb(t){n[t]=e[t]&&function(n){return new Promise(function(r,i){n=e[t](n),settle(r,i,n.done,n.value)})}}function settle(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}};function hashFiles$1(e,t){return __awaiter$1(this,arguments,void 0,function*(e,t,n=!1){var r,o,s,c;let l=n?info:debug,d=!1,f=t||(process.env.GITHUB_WORKSPACE??process.cwd()),p=i.createHash(`sha256`),h=0;try{for(var g=!0,v=__asyncValues(e.globGenerator()),b;b=yield v.next(),r=b.done,!r;g=!0){c=b.value,g=!1;let e=c;if(l(e),!e.startsWith(`${f}${u.sep}`)){l(`Ignore '${e}' since it is not under GITHUB_WORKSPACE.`);continue}if(a.statSync(e).isDirectory()){l(`Skip directory '${e}'.`);continue}let t=i.createHash(`sha256`);yield y.promisify(Ce.pipeline)(a.createReadStream(e),t),p.write(t.digest()),h++,d||=!0}}catch(e){o={error:e}}finally{try{!g&&!r&&(s=v.return)&&(yield s.call(v))}finally{if(o)throw o.error}}return p.end(),d?(l(`Found ${h} files to hash.`),p.digest(`hex`)):(l(`No matches found for glob`),``)})}var __awaiter=function(e,t,n,r){function adopt(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?n(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())})};function create(e,t){return __awaiter(this,void 0,void 0,function*(){return yield py.create(e,t)})}function hashFiles(e){return __awaiter(this,arguments,void 0,function*(e,t=``,n,r=!1){let i=!0;return n&&typeof n.followSymbolicLinks==`boolean`&&(i=n.followSymbolicLinks),hashFiles$1(yield create(e,{followSymbolicLinks:i}),t,r)})}async function restoreCache(e){let t=getConfiguredProjectDir(e),n=detectLockFile$1(e.cacheDependencyPath,t);if(!n){warning(e.cacheDependencyPath?`No lock file found for cache-dependency-path: ${e.cacheDependencyPath}. Skipping cache restore.`:`No lock file found in project directory: ${t}. Skipping cache restore.`),setOutput(`cache-hit`,!1);return}info(`Using lock file: ${n.path}`);let r=re(n.path);info(`Resolving dependency cache directory in: ${r}`);let i=await getCacheDirectories(n.type,r);if(!i.length){warning(`No cache directories found for ${n.type} in ${r}. Skipping cache restore.`),setOutput(`cache-hit`,!1);return}debug(`Cache paths: ${i.join(`, `)}`),saveState(`CACHE_PATHS`,JSON.stringify(i));let a=process.env.RUNNER_OS||xe(),o=ye(),s=await hashFiles(n.path);if(!s)throw Error(`Failed to generate hash for lock file: ${n.path}`);let c=`vite-plus-${a}-${o}-${n.type}-${s}`,l=[`vite-plus-${a}-${o}-${n.type}-`,`vite-plus-${a}-${o}-`];debug(`Primary key: ${c}`),debug(`Restore keys: ${l.join(`, `)}`),saveState(`CACHE_PRIMARY_KEY`,c);let u=await restoreCache$1(i,c,l);u?(info(`Cache restored from key: ${u}`),saveState(`CACHE_MATCHED_KEY`,u),setOutput(`cache-hit`,!0)):(info(`Cache not found`),setOutput(`cache-hit`,!1))}async function saveCache(){let e=getState(`CACHE_PRIMARY_KEY`),t=getState(`CACHE_MATCHED_KEY`),n=getState(`CACHE_PATHS`);if(!e){info(`No cache key found. Skipping cache save.`);return}if(!n){info(`No cache paths found. Skipping cache save.`);return}if(e===t){info(`Cache hit on primary key "${e}". Skipping save.`);return}let r=JSON.parse(n);if(!r.length){info(`Empty cache paths. Skipping cache save.`);return}try{if(await saveCache$1(r,e)===-1){info(`Cache not saved (key already reserved by a concurrent job, or save was skipped).`);return}info(`Cache saved with key: ${e}`)}catch(e){warning(`Failed to save cache: ${String(e)}`)}}function resolvePath$1(e,t){return F.isAbsolute(e)?e:F.join(t,e)}function isWithin(e,t){let n=F.relative(t,e);return!F.isAbsolute(n)&&n!==`..`&&!n.startsWith(`..${F.sep}`)}function createNodeVersionResolver(e){let{getWorkspaceDir:t,info:n}=e;function resolveNodeVersionFile(e,r){let i=resolvePath$1(e,r||t()),a;try{a=pe(i,`utf-8`)}catch{throw Error(`node-version-file not found: ${i}`)}let o=te(i),s;if(s=o===`.tool-versions`?parseToolVersions(a):o===`package.json`?parsePackageJson(a):parsePlainVersionFile(a),!s)throw Error(`No Node.js version found in ${e}`);return s=s.replace(/^v/i,``),n(`Resolved Node.js version '${s}' from ${e}`),s}function parsePlainVersionFile(e){for(let t of e.split(` `)){let e=(t.includes(`#`)?t.slice(0,t.indexOf(`#`)):t).trim();if(e)return normalizeNvmAlias(e)}}function normalizeNvmAlias(e){let t=e.toLowerCase();return t===`node`||t===`stable`?`latest`:e}function parseToolVersions(e){for(let t of e.split(` -`)){let e=t.trim();if(!e||e.startsWith(`#`))continue;let[n,...r]=e.split(/\s+/);if(n===`nodejs`||n===`node`){for(let e of r)if(isAsdfInstallableVersion(e))return e}}}function isAsdfInstallableVersion(e){return!!e&&e!==`system`&&!e.startsWith(`ref:`)&&!e.startsWith(`path:`)}function parsePackageJson(e){let t;try{t=JSON.parse(e)}catch{throw Error(`Failed to parse package.json: invalid JSON`)}let n=t.devEngines;if(n?.runtime){let e=findNodeRuntime(n.runtime);if(e)return e}let r=t.engines;if(r?.node&&typeof r.node==`string`)return r.node}function findNodeRuntime(e){let t=Array.isArray(e)?e:[e];for(let e of t)if(e?.name===`node`&&typeof e.version==`string`)return e.version}return{resolveNodeVersionFile}}const{resolveNodeVersionFile:my}=createNodeVersionResolver({getWorkspaceDir,info}),hy=[{filename:`pnpm-lock.yaml`,type:`pnpm`},{filename:`bun.lockb`,type:`bun`},{filename:`bun.lock`,type:`bun`},{filename:`package-lock.json`,type:`npm`},{filename:`npm-shrinkwrap.json`,type:`npm`},{filename:`yarn.lock`,type:`yarn`}];function resolvePath(e,t){return ie(e)?e:ae(t,e)}function inferLockFileType(e,t){return t.includes(`pnpm`)?{type:`pnpm`,path:e,filename:t}:t.includes(`yarn`)?{type:`yarn`,path:e,filename:t}:t.startsWith(`bun.`)?{type:`bun`,path:e,filename:t}:{type:`npm`,path:e,filename:t}}function detectLockFile(e,t){if(e){let n=resolvePath(e,t);if(I(n)){let e=te(n),t=hy.find(t=>t.filename===e);return t?{type:t.type,path:n,filename:e}:inferLockFileType(n,e)}return}let n=me(t);for(let e of hy)if(n.includes(e.filename)){let n=ae(t,e.filename);return{type:e.type,path:n,filename:e.filename}}}function createLockfileResolver(e){let{getWorkspaceDir:t,info:n,debug:r}=e,i=/^\d+\.\d+\.\d+/;function tryResolveVitePlusVersionFromLockfile(e,t){let i=detectLockfileForProject(e,t);if(!i)return;let a=i.filename.endsWith(`.lockb`)?textBunLockBeside(i):i;if(!a){r(`Cannot read ${i.filename} (binary) to resolve the ${aa} version; using "latest". Use the text bun.lock, or set the \`version\` input.`);return}let o=parseVitePlusVersionFromLockfile(a,workspaceSubPath(re(a.path),e));if(o)return n(`Resolved ${aa} version '${o}' from ${a.filename}`),o;r(`No ${aa} version found in ${a.path}`)}function detectLockfileForProject(e,n){if(n)return detectLockFile(n,e);let r=t(),i=e;for(;;){let e=detectLockFile(void 0,i);if(e)return e;let t=re(i);if(i===r||t===i||!isWithin(t,r))break;i=t}}function textBunLockBeside(e){let t=ae(re(e.path),`bun.lock`);return I(t)?{type:`bun`,path:t,filename:`bun.lock`}:void 0}function workspaceSubPath(e,t){if(!isWithin(t,e))return``;let n=oe(e,t);return n?n.split(ce).join(`/`):``}function parseVitePlusVersionFromLockfile(e,t=``){if(e.filename.endsWith(`.lockb`))return;let n;try{n=pe(e.path,`utf-8`)}catch{return}let r;switch(e.type){case`npm`:r=fromNpmLock(n,t);break;case`pnpm`:r=fromPnpmLock(n,t);break;case`yarn`:r=fromYarnLock(n);break;case`bun`:r=fromBunTextLock(n);break;default:return}return r&&i.test(r)?r:void 0}function fromNpmLock(e,t){let n;try{n=JSON.parse(e)}catch{return}let r=n.packages;if(t){let e=r?.[`${t}/node_modules/${oa}`]?.version;if(typeof e==`string`)return e;if(!npmPackageDeclaresVitePlus(r?.[t]))return}let i=r?.[`node_modules/${oa}`]?.version;if(typeof i==`string`)return i;let a=n.dependencies?.[oa]?.version;return typeof a==`string`?a:void 0}function npmPackageDeclaresVitePlus(e){if(!e)return!1;for(let t of[`dependencies`,`devDependencies`]){let n=e[t];if(n&&typeof n==`object`&&`vite-plus`in n)return!0}return!1}function fromPnpmLock(e,t){let n;try{n=(0,_i.parse)(e)}catch{return}if(!n||typeof n!=`object`)return;let r=n,i=r.importers;if(i&&typeof i==`object`){let e=t||`.`;return e in i?pnpmImporterVersion(i[e]):void 0}return pnpmImporterVersion(r)||e.match(/^\s*\/?vite-plus@(\d+\.\d+\.\d+[^\s():'"]*)/m)?.[1]}function pnpmImporterVersion(e){if(!e||typeof e!=`object`)return;let t=e;for(let e of[`dependencies`,`devDependencies`,`optionalDependencies`]){let n=t[e];if(n&&typeof n==`object`){let e=n[oa],t=typeof e==`string`?e:e?.version;if(typeof t==`string`){let e=t.replace(/\(.*$/,``).trim();if(i.test(e))return e}}}}function fromYarnLock(e){let t=new Set,n=e.split(/\r?\n/);for(let e=0;e!n.has(authKeyFor$1(e))),envVarRefs:r}}function getRunnerNpmrcPath(){return se(process.env.RUNNER_TEMP||process.cwd(),`.npmrc`)}function stripProtocol(e){return e.replace(/^\w+:/,``)}function authKeyFor(e){return(stripProtocol(e)+`:_authtoken`).toLowerCase()}function buildAuthLine(e){return`${stripProtocol(e)}:_authToken=\${NODE_AUTH_TOKEN}`}function readNpmrc(e){try{return pe(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return;throw e}}function configAuthentication(e,t){let n;try{n=new URL(e)}catch{throw Error(`Invalid registry-url: "${e}". Must be a valid URL.`)}writeRegistryToFile(n.href.endsWith(`/`)?n.href:n.href+`/`,getRunnerNpmrcPath(),t)}function writeRegistryToFile(e,t,n){n||new URL(e).hostname===`npm.pkg.github.com`&&(n=process.env.GITHUB_REPOSITORY_OWNER);let r=``;n&&(r=(n.startsWith(`@`)?n:`@`+n).toLowerCase()+`:`),debug(`Setting auth in ${t}`);let i=stripProtocol(e).toLowerCase(),a=[],o=readNpmrc(t);if(o!==void 0)for(let e of o.split(/\r?\n/)){let t=e.toLowerCase();t.startsWith(`${r}registry`)||t.startsWith(i)&&t.includes(`_authtoken`)||a.push(e)}a.push(buildAuthLine(e),`${r}registry=${e}`),ge(t,a.join(ve)),exportVariable(`NPM_CONFIG_USERCONFIG`,t),exportVariable(`PNPM_CONFIG_USERCONFIG`,t),exportVariable(`NODE_AUTH_TOKEN`,process.env.NODE_AUTH_TOKEN||`XXXXX-XXXXX-XXXXX-XXXXX`)}const by=new Set([`GITHUB_TOKEN`]),xy=new Set([`PATH`,`HOME`,`USERPROFILE`,`TMPDIR`,`CI`]);function isReservedEnvVar(e){return xy.has(e)||e.startsWith(`RUNNER_`)?!0:e.startsWith(`GITHUB_`)?!by.has(e):!1}function writeSupplementalAuth(e){let t=getRunnerNpmrcPath(),n=new Set(e.map(authKeyFor)),r=readNpmrc(t),i=[...(r===void 0?[]:r.split(/\r?\n/)).filter(e=>{let t=e.indexOf(`=`);return t<=0||!n.has(e.slice(0,t).trim().toLowerCase())}),...e.map(buildAuthLine)].join(ve);if(exportVariable(`NPM_CONFIG_USERCONFIG`,t),exportVariable(`PNPM_CONFIG_USERCONFIG`,t),r===i){debug(`Supplemental .npmrc at ${t} already current`);return}ge(t,i),info(`Wrote _authToken entries to ${t} for registries: ${e.join(`, `)}`)}function propagateProjectNpmrcAuth(e){let t=ae(e,`.npmrc`),n=readNpmrc(t);if(n===void 0)return;let{registriesNeedingAuth:r,envVarRefs:i}=analyzeProjectNpmrc(n);process.env.NODE_AUTH_TOKEN&&r.length>0&&(writeSupplementalAuth(r),i.add(`NODE_AUTH_TOKEN`));let a=[...i].filter(e=>!isReservedEnvVar(e)&&!!process.env[e]);if(a.length===0){debug(`Project .npmrc at ${t}: no auth env vars to propagate`);return}info(`Detected project .npmrc at ${t}. Propagating auth env vars: ${a.join(`, `)}`);for(let e of a)exportVariable(e,process.env[e])}async function runMain(e){saveState(`IS_POST`,`true`);let t=getConfiguredProjectDir(e),n=e.nodeVersion;!n&&e.nodeVersionFile&&(n=my(e.nodeVersionFile,t));let r=gy(e,t);await installVitePlus({...e,version:r});let i=e.nodeManager===!1||e.packageManager!==void 0?(await getExecOutput(`vp`,[`--version`],{silent:!0})).stdout:``,a=packageManagerArgs(e.packageManager,i);e.nodeManager===!1?(info(`Disabling Vite+ Node.js version management...`),await exec(`vp`,nodeManagerOffArgs(i))):n&&(info(`Setting up Node.js ${n} via vp env use...`),await exec(`vp`,[`env`,`use`,n]));for(let e of a)await exec(`vp`,e);e.registryUrl?configAuthentication(e.registryUrl,e.scope):propagateProjectNpmrcAuth(t),e.cache&&await restoreCache(e);let o=await setupSfw(e);e.runInstall.length>0&&await runViteInstall({...e,sfw:o}),await printViteVersion(t)}async function printViteVersion(e){try{let t=(await getExecOutput(`vp`,[`--version`],{cwd:e,silent:!0})).stdout.trim();info(t);let n=parseInstalledVpVersion(t);saveState(`INSTALLED_VERSION`,n),setOutput(`version`,n)}catch(e){warning(`Could not get vp version: ${String(e)}`),setOutput(`version`,`unknown`)}}async function runPost(e){if(e.cache){if(!e.cacheSave){info(`Cache saving is disabled. Skipping cache save.`);return}await saveCache()}}async function main(){let e=getInputs();getState(`IS_POST`)===`true`?await runPost(e):await runMain(e)}main().catch(e=>{console.error(e),setFailed(e instanceof Error?e.message:String(e))});export{runPost}; \ No newline at end of file +`)){let e=t.trim();if(!e||e.startsWith(`#`))continue;let[n,...r]=e.split(/\s+/);if(n===`nodejs`||n===`node`){for(let e of r)if(isAsdfInstallableVersion(e))return e}}}function isAsdfInstallableVersion(e){return!!e&&e!==`system`&&!e.startsWith(`ref:`)&&!e.startsWith(`path:`)}function parsePackageJson(e){let t;try{t=JSON.parse(e)}catch{throw Error(`Failed to parse package.json: invalid JSON`)}let n=t.devEngines;if(n?.runtime){let e=findNodeRuntime(n.runtime);if(e)return e}let r=t.engines;if(r?.node&&typeof r.node==`string`)return r.node}function findNodeRuntime(e){let t=Array.isArray(e)?e:[e];for(let e of t)if(e?.name===`node`&&typeof e.version==`string`)return e.version}return{resolveNodeVersionFile}}const{resolveNodeVersionFile:my}=createNodeVersionResolver({getWorkspaceDir,info}),hy=[{filename:`pnpm-lock.yaml`,type:`pnpm`},{filename:`bun.lockb`,type:`bun`},{filename:`bun.lock`,type:`bun`},{filename:`package-lock.json`,type:`npm`},{filename:`npm-shrinkwrap.json`,type:`npm`},{filename:`yarn.lock`,type:`yarn`}];function resolvePath(e,t){return ie(e)?e:ae(t,e)}function inferLockFileType(e,t){return t.includes(`pnpm`)?{type:`pnpm`,path:e,filename:t}:t.includes(`yarn`)?{type:`yarn`,path:e,filename:t}:t.startsWith(`bun.`)?{type:`bun`,path:e,filename:t}:{type:`npm`,path:e,filename:t}}function detectLockFile(e,t){if(e){let n=resolvePath(e,t);if(I(n)){let e=te(n),t=hy.find(t=>t.filename===e);return t?{type:t.type,path:n,filename:e}:inferLockFileType(n,e)}return}let n=me(t);for(let e of hy)if(n.includes(e.filename)){let n=ae(t,e.filename);return{type:e.type,path:n,filename:e.filename}}}function createLockfileResolver(e){let{getWorkspaceDir:t,info:n,debug:r}=e,i=/^\d+\.\d+\.\d+/;function tryResolveVitePlusVersionFromLockfile(e,t){let i=detectLockfileForProject(e,t);if(!i)return;let a=i.filename.endsWith(`.lockb`)?textBunLockBeside(i):i;if(!a){r(`Cannot read ${i.filename} (binary) to resolve the ${aa} version; using "latest". Use the text bun.lock, or set the \`version\` input.`);return}let o=parseVitePlusVersionFromLockfile(a,workspaceSubPath(re(a.path),e));if(o)return n(`Resolved ${aa} version '${o}' from ${a.filename}`),o;r(`No ${aa} version found in ${a.path}`)}function detectLockfileForProject(e,n){if(n)return detectLockFile(n,e);let r=t(),i=e;for(;;){let e=detectLockFile(void 0,i);if(e)return e;let t=re(i);if(i===r||t===i||!isWithin(t,r))break;i=t}}function textBunLockBeside(e){let t=ae(re(e.path),`bun.lock`);return I(t)?{type:`bun`,path:t,filename:`bun.lock`}:void 0}function workspaceSubPath(e,t){if(!isWithin(t,e))return``;let n=oe(e,t);return n?n.split(ce).join(`/`):``}function parseVitePlusVersionFromLockfile(e,t=``){if(e.filename.endsWith(`.lockb`))return;let n;try{n=pe(e.path,`utf-8`)}catch{return}let r;switch(e.type){case`npm`:r=fromNpmLock(n,t);break;case`pnpm`:r=fromPnpmLock(n,t);break;case`yarn`:r=fromYarnLock(n);break;case`bun`:r=fromBunTextLock(n);break;default:return}return r&&i.test(r)?r:void 0}function fromNpmLock(e,t){let n;try{n=JSON.parse(e)}catch{return}let r=n.packages;if(t){let e=r?.[`${t}/node_modules/${oa}`]?.version;if(typeof e==`string`)return e;if(!npmPackageDeclaresVitePlus(r?.[t]))return}let i=r?.[`node_modules/${oa}`]?.version;if(typeof i==`string`)return i;let a=n.dependencies?.[oa]?.version;return typeof a==`string`?a:void 0}function npmPackageDeclaresVitePlus(e){if(!e)return!1;for(let t of[`dependencies`,`devDependencies`]){let n=e[t];if(n&&typeof n==`object`&&`vite-plus`in n)return!0}return!1}function fromPnpmLock(e,t){let n;try{n=(0,_i.parse)(e)}catch{return}if(!n||typeof n!=`object`)return;let r=n,i=r.importers;if(i&&typeof i==`object`){let e=t||`.`;return e in i?pnpmImporterVersion(i[e]):void 0}return pnpmImporterVersion(r)||e.match(/^\s*\/?vite-plus@(\d+\.\d+\.\d+[^\s():'"]*)/m)?.[1]}function pnpmImporterVersion(e){if(!e||typeof e!=`object`)return;let t=e;for(let e of[`dependencies`,`devDependencies`,`optionalDependencies`]){let n=t[e];if(n&&typeof n==`object`){let e=n[oa],t=typeof e==`string`?e:e?.version;if(typeof t==`string`){let e=t.replace(/\(.*$/,``).trim();if(i.test(e))return e}}}}function fromYarnLock(e){let t=new Set,n=e.split(/\r?\n/);for(let e=0;e!n.has(authKeyFor$1(e))),envVarRefs:r}}function getRunnerNpmrcPath(){return se(process.env.RUNNER_TEMP||process.cwd(),`.npmrc`)}function stripProtocol(e){return e.replace(/^\w+:/,``)}function authKeyFor(e){return(stripProtocol(e)+`:_authtoken`).toLowerCase()}function buildAuthLine(e){return`${stripProtocol(e)}:_authToken=\${NODE_AUTH_TOKEN}`}function readNpmrc(e){try{return pe(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return;throw e}}function configAuthentication(e,t){let n;try{n=new URL(e)}catch{throw Error(`Invalid registry-url: "${e}". Must be a valid URL.`)}writeRegistryToFile(n.href.endsWith(`/`)?n.href:n.href+`/`,getRunnerNpmrcPath(),t)}function writeRegistryToFile(e,t,n){n||new URL(e).hostname===`npm.pkg.github.com`&&(n=process.env.GITHUB_REPOSITORY_OWNER);let r=``;n&&(r=(n.startsWith(`@`)?n:`@`+n).toLowerCase()+`:`),debug(`Setting auth in ${t}`);let i=stripProtocol(e).toLowerCase(),a=[],o=readNpmrc(t);if(o!==void 0)for(let e of o.split(/\r?\n/)){let t=e.toLowerCase();t.startsWith(`${r}registry`)||t.startsWith(i)&&t.includes(`_authtoken`)||a.push(e)}a.push(buildAuthLine(e),`${r}registry=${e}`),ge(t,a.join(ve)),exportVariable(`NPM_CONFIG_USERCONFIG`,t),exportVariable(`PNPM_CONFIG_USERCONFIG`,t),exportVariable(`NODE_AUTH_TOKEN`,process.env.NODE_AUTH_TOKEN||`XXXXX-XXXXX-XXXXX-XXXXX`)}const by=new Set([`GITHUB_TOKEN`]),xy=new Set([`PATH`,`HOME`,`USERPROFILE`,`TMPDIR`,`CI`]);function isReservedEnvVar(e){return xy.has(e)||e.startsWith(`RUNNER_`)?!0:e.startsWith(`GITHUB_`)?!by.has(e):!1}function writeSupplementalAuth(e){let t=getRunnerNpmrcPath(),n=new Set(e.map(authKeyFor)),r=readNpmrc(t),i=[...(r===void 0?[]:r.split(/\r?\n/)).filter(e=>{let t=e.indexOf(`=`);return t<=0||!n.has(e.slice(0,t).trim().toLowerCase())}),...e.map(buildAuthLine)].join(ve);if(exportVariable(`NPM_CONFIG_USERCONFIG`,t),exportVariable(`PNPM_CONFIG_USERCONFIG`,t),r===i){debug(`Supplemental .npmrc at ${t} already current`);return}ge(t,i),info(`Wrote _authToken entries to ${t} for registries: ${e.join(`, `)}`)}function propagateProjectNpmrcAuth(e){let t=ae(e,`.npmrc`),n=readNpmrc(t);if(n===void 0)return;let{registriesNeedingAuth:r,envVarRefs:i}=analyzeProjectNpmrc(n);process.env.NODE_AUTH_TOKEN&&r.length>0&&(writeSupplementalAuth(r),i.add(`NODE_AUTH_TOKEN`));let a=[...i].filter(e=>!isReservedEnvVar(e)&&!!process.env[e]);if(a.length===0){debug(`Project .npmrc at ${t}: no auth env vars to propagate`);return}info(`Detected project .npmrc at ${t}. Propagating auth env vars: ${a.join(`, `)}`);for(let e of a)exportVariable(e,process.env[e])}async function runMain(e){saveState(`IS_POST`,`true`);let t=getConfiguredProjectDir(e),n=e.nodeVersion;!n&&e.nodeVersionFile&&(n=my(e.nodeVersionFile,t));let r=gy(e,t);await installVitePlus({...e,version:r});let i=e.nodeManager===!1||e.packageManager!==void 0?(await getExecOutput(`vp`,[`--version`],{silent:!0})).stdout:``,a=packageManagerArgs(e.packageManager,i);e.nodeManager===!1?(info(`Disabling Vite+ Node.js version management...`),await exec(`vp`,nodeManagerOffArgs(i))):n&&(info(`Setting up Node.js ${n} via vp env use...`),await exec(`vp`,[`env`,`use`,n]));for(let e of a)await exec(`vp`,e);e.registryUrl?configAuthentication(e.registryUrl,e.scope):propagateProjectNpmrcAuth(t),e.cache&&await restoreCache(e);let o=await setupSfw({...e,version:r});e.runInstall.length>0&&await runViteInstall({...e,sfw:o}),await printViteVersion(t)}async function printViteVersion(e){try{let t=(await getExecOutput(`vp`,[`--version`],{cwd:e,silent:!0})).stdout.trim();info(t);let n=parseInstalledVpVersion(t);saveState(`INSTALLED_VERSION`,n),setOutput(`version`,n)}catch(e){warning(`Could not get vp version: ${String(e)}`),setOutput(`version`,`unknown`)}}async function runPost(e){if(e.cache){if(!e.cacheSave){info(`Cache saving is disabled. Skipping cache save.`);return}await saveCache()}}async function main(){let e=getInputs();getState(`IS_POST`)===`true`?await runPost(e):await runMain(e)}main().catch(e=>{console.error(e),setFailed(e instanceof Error?e.message:String(e))});export{runMain,runPost}; \ No newline at end of file diff --git a/src/azure/index.ts b/src/azure/index.ts index f48206a..66b8e6d 100644 --- a/src/azure/index.ts +++ b/src/azure/index.ts @@ -6,6 +6,7 @@ import { createVersionResolver } from "../ci/version-file.js"; import { createNodeVersionResolver } from "../ci/node-version-file.js"; import { resolutionContext } from "../ci/resolution.js"; import { nodeManagerOffArgs } from "../ci/node-manager.js"; +import { pkgPrNewCommitSha } from "../ci/install-script-urls.js"; import { configureAuth, isReservedAuthVariable } from "../ci/auth.js"; import { analyzeProjectNpmrc, readNpmrc } from "../ci/npmrc.js"; import { prepareCacheMetadata } from "../ci/cache.js"; @@ -92,6 +93,8 @@ export async function runPrepare( prependPath: (binDir) => ports.prependPath(binDir), logWarningFn: ports.logWarning, }); + // Finalize must use the resolved version, including pins from files or lockfiles. + ports.setVariable("SETUP_VP_RESOLVED_VERSION", version); const versionOutput = inputs.nodeManager === false || inputs.packageManager !== undefined @@ -113,7 +116,11 @@ export async function runPrepare( const runtimePath = path.resolve(process.argv[1] || ""); ports.setVariable("SETUP_VP_RUNTIME_PATH", runtimePath); - if (inputs.sfw && ports.parseRunInstall(inputs.runInstall).length > 0) { + if ( + inputs.sfw && + !pkgPrNewCommitSha(version) && + ports.parseRunInstall(inputs.runInstall).length > 0 + ) { try { const asset = getSfwAssetName(process.platform, process.arch, isMuslLinux()); const sfwCache = path.join(env.PIPELINE_WORKSPACE || inputs.workspaceRoot, ".setup-vp-sfw"); @@ -183,6 +190,8 @@ export async function runFinalize( const installCommand = await ports.setupSfw(runInstallEntries, { env, sfwEnabled: inputs.sfw, + vitePlusVersion: env.SETUP_VP_RESOLVED_VERSION || inputs.version, + logWarning: ports.logWarning, exportVariable: (name, value) => { if (value === undefined) return; if (name === "PATH") ports.prependPath(value.split(path.delimiter)[0]!); diff --git a/src/azure/parity.test.ts b/src/azure/parity.test.ts index 9d235dd..d568e84 100644 --- a/src/azure/parity.test.ts +++ b/src/azure/parity.test.ts @@ -3,6 +3,7 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vite-plus/test"; import { configureAuth } from "../ci/auth.js"; +import { setupSfw } from "../ci/install-sfw.js"; import { parseRunInstall } from "../ci/run-install.js"; import { runPrepare, runFinalize } from "./index.js"; import type { AzurePorts } from "./index.js"; @@ -21,7 +22,7 @@ function fixture() { installVitePlus: vi.fn(async () => {}), prepareCacheMetadata: vi.fn(() => ({ ready: false })), configureAuth: vi.fn(configureAuth), - setupSfw: vi.fn(async () => "vp" as const), + setupSfw: vi.fn().mockResolvedValue("vp"), parseRunInstall, runInstall: vi.fn(), getCommandOutput: vi.fn((): string | undefined => "vp v0.3.1"), @@ -100,6 +101,48 @@ describe("Azure parity", () => { ); }); + it.each(["explicit", "package.json", "version-file"])( + "disables sfw and its cache for a preview resolved from %s", + async (source) => { + const { project, env, ports } = fixture(); + const version = "0.0.0-commit.7d848b3da1987fa60b4cf18487fcc36a2a697e94"; + const target: NodeJS.ProcessEnv = { ...env, SETUP_VP_SFW: "true" }; + if (source === "explicit") target.SETUP_VP_VERSION = version; + else if (source === "version-file") { + writeFileSync( + path.join(project, "pnpm-workspace.yaml"), + `catalog:\n vite-plus: ${version}\n`, + ); + target.SETUP_VP_VERSION_FILE = "pnpm-workspace.yaml"; + } else { + writeFileSync( + path.join(project, "package.json"), + JSON.stringify({ devDependencies: { "vite-plus": version } }), + ); + } + // Azure carries task.setvariable values into the following task's environment. + ports.setVariable.mockImplementation((name, value) => { + target[name] = value; + }); + ports.setupSfw.mockImplementation(setupSfw); + + await runPrepare(target, ports); + + expect(ports.installVitePlus).toHaveBeenCalledWith(version, expect.any(Object)); + expect(target.SETUP_VP_SFW_READY).toBe("false"); + expect(target.SETUP_VP_SFW_CACHE_DIR).toBeUndefined(); + expect(target.SETUP_VP_RESOLVED_VERSION).toBe(version); + // Finalize has the original sfw input but does not receive version-file from the template. + delete target.SETUP_VP_VERSION_FILE; + await runFinalize(target, ports); + + expect(ports.runInstall).toHaveBeenCalledWith([{}], project, "vp", target); + expect(ports.logWarning).toHaveBeenCalledExactlyOnceWith( + expect.stringContaining(`automatically disabled for Vite+ preview build ${version}`), + ); + }, + ); + it.each(["$(CUSTOM_TOKEN)", "$(MISSING_SECRET)"])( "removes an unresolved custom auth macro %s before install", async (value) => { diff --git a/src/ci/install-sfw.test.ts b/src/ci/install-sfw.test.ts index 0d747b2..d316fa5 100644 --- a/src/ci/install-sfw.test.ts +++ b/src/ci/install-sfw.test.ts @@ -3,13 +3,67 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vite-plus/test"; import { setupSfw, SFW_VERSION } from "./install-sfw.js"; +import { commandPath } from "./process.js"; -vi.mock("./process.js", () => ({ commandPath: () => undefined })); +vi.mock("./process.js", () => ({ commandPath: vi.fn() })); const directories: string[] = []; afterEach(() => { + vi.resetAllMocks(); for (const dir of directories.splice(0)) rmSync(dir, { recursive: true, force: true }); }); +describe("portable sfw preview handling", () => { + const vitePlusVersion = "0.0.0-commit.7d848b3da1987fa60b4cf18487fcc36a2a697e94"; + + it.each(["linux", "darwin", "win32"] as const)( + "skips sfw lookup, downloads, and exports for previews on %s", + async (platform) => { + vi.mocked(commandPath).mockReturnValue("/bin/sfw"); + const download = vi.fn(); + const exportVariable = vi.fn(); + const logWarning = vi.fn(); + const env = { SETUP_VP_SFW: "true", PATH: "/bin" }; + + expect( + await setupSfw([{}], { + env, + vitePlusVersion, + platform, + download, + exportVariable, + logWarning, + }), + ).toBe("vp"); + + expect(logWarning).toHaveBeenCalledExactlyOnceWith( + `sfw was requested but is automatically disabled for Vite+ preview build ${vitePlusVersion}; Socket Firewall Free will not be used.`, + ); + expect(commandPath).not.toHaveBeenCalled(); + expect(download).not.toHaveBeenCalled(); + expect(exportVariable).not.toHaveBeenCalled(); + expect(env.PATH).toBe("/bin"); + }, + ); + + it("does not warn when sfw is already disabled for a preview", async () => { + const logWarning = vi.fn(); + expect(await setupSfw([{}], { sfwEnabled: false, vitePlusVersion, logWarning })).toBe("vp"); + expect(logWarning).not.toHaveBeenCalled(); + }); + + it.each(["0.3.2", "0.3.3-alpha.1", "latest", "next"])( + "keeps sfw enabled for %s", + async (version) => { + vi.mocked(commandPath).mockReturnValue("/bin/sfw"); + const logWarning = vi.fn(); + expect(await setupSfw([{}], { sfwEnabled: true, vitePlusVersion: version, logWarning })).toBe( + "sfw", + ); + expect(logWarning).not.toHaveBeenCalled(); + }, + ); +}); + describe("portable sfw cache", () => { it("reuses a complete versioned asset without a second download", async () => { const cacheDirectory = mkdtempSync(path.join(tmpdir(), "setup-vp-sfw-cache-")); diff --git a/src/ci/install-sfw.ts b/src/ci/install-sfw.ts index cafa695..9f2c7ae 100644 --- a/src/ci/install-sfw.ts +++ b/src/ci/install-sfw.ts @@ -5,7 +5,8 @@ import type { get as httpGet } from "node:http"; import { tmpdir } from "node:os"; import path from "node:path"; import { commandPath } from "./process.js"; -import type { ExportVariable, InstallCommand, RunInstallEntry } from "./types.js"; +import { resolveSfwEnabled } from "./sfw.js"; +import type { ExportVariable, InstallCommand, LogFn, RunInstallEntry } from "./types.js"; export const SFW_VERSION = "v1.15.1"; const SFW_RELEASE_BASE = `https://github.com/SocketDev/sfw-free/releases/download/${SFW_VERSION}`; @@ -152,6 +153,8 @@ export async function setupSfw( options: { env?: NodeJS.ProcessEnv; sfwEnabled?: boolean; + vitePlusVersion?: string; + logWarning?: LogFn; exportVariable?: ExportVariable; platform?: NodeJS.Platform; arch?: string; @@ -167,7 +170,15 @@ export async function setupSfw( const isMusl = options.isMusl ?? isMuslLinux(); const download = options.download ?? downloadFile; - if (!sfwEnabled) return "vp"; + if ( + !resolveSfwEnabled( + sfwEnabled, + options.vitePlusVersion ?? "", + options.logWarning ?? console.warn, + ) + ) { + return "vp"; + } if (runInstallEntries.length === 0) { console.log( diff --git a/src/ci/sfw.ts b/src/ci/sfw.ts new file mode 100644 index 0000000..5387136 --- /dev/null +++ b/src/ci/sfw.ts @@ -0,0 +1,12 @@ +import { pkgPrNewCommitSha } from "./install-script-urls.js"; +import type { LogFn } from "./types.js"; + +export function resolveSfwEnabled(enabled: boolean, version: string, logWarning: LogFn): boolean { + if (!enabled) return false; + if (!pkgPrNewCommitSha(version)) return true; + + logWarning( + `sfw was requested but is automatically disabled for Vite+ preview build ${version}; Socket Firewall Free will not be used.`, + ); + return false; +} diff --git a/src/gitlab/index.test.ts b/src/gitlab/index.test.ts index 0b9be30..d99e7d6 100644 --- a/src/gitlab/index.test.ts +++ b/src/gitlab/index.test.ts @@ -6,7 +6,7 @@ import { afterEach, describe, expect, it, vi } from "vite-plus/test"; import { installVitePlus } from "../ci/install-viteplus.js"; import { setupSfw } from "../ci/install-sfw.js"; import { run } from "../ci/process.js"; -import { getCommandOutput } from "../ci/process.js"; +import { commandPath, getCommandOutput, runWithOutput } from "../ci/process.js"; import { applyEnvironmentModes, isEntrypoint, main } from "./index.js"; vi.mock("../ci/process.js", () => ({ @@ -25,6 +25,8 @@ const directories: string[] = []; afterEach(() => { vi.unstubAllEnvs(); vi.clearAllMocks(); + vi.mocked(commandPath).mockReset(); + vi.restoreAllMocks(); for (const dir of directories.splice(0)) rmSync(dir, { recursive: true, force: true }); }); @@ -95,6 +97,38 @@ describe("GitLab setup parity", () => { expect(run).toHaveBeenCalledWith("vp", ["env", "use", "22"], expect.any(Object)); }); + it.each(["explicit", "package.json"])( + "disables sfw for a preview resolved from %s and warns once", + async (source) => { + const root = fixture(); + const version = "0.0.0-commit.7d848b3da1987fa60b4cf18487fcc36a2a697e94"; + if (source === "explicit") vi.stubEnv("SETUP_VP_VERSION", version); + else + writeFileSync( + path.join(root, "app/package.json"), + JSON.stringify({ devDependencies: { "vite-plus": version } }), + ); + vi.stubEnv("SETUP_VP_SFW", "true"); + vi.stubEnv("SETUP_VP_RUN_INSTALL", "true"); + vi.mocked(commandPath).mockReturnValue("/bin/sfw"); + vi.mocked(getCommandOutput).mockReturnValue(`vp v${version}`); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + + await main(); + + expect(installVitePlus).toHaveBeenCalledWith(version, expect.any(Object)); + expect(commandPath).not.toHaveBeenCalled(); + expect(runWithOutput).toHaveBeenCalledExactlyOnceWith( + "vp", + ["install"], + expect.objectContaining({ cwd: path.join(root, "app") }), + ); + expect(warn).toHaveBeenCalledExactlyOnceWith( + expect.stringContaining(`automatically disabled for Vite+ preview build ${version}`), + ); + }, + ); + it("rejects Node opt-out conflicts before installation", async () => { fixture(); vi.stubEnv("SETUP_VP_NODE_MANAGER", "false"); diff --git a/src/gitlab/index.ts b/src/gitlab/index.ts index e1ebc44..9797afd 100644 --- a/src/gitlab/index.ts +++ b/src/gitlab/index.ts @@ -110,7 +110,7 @@ export async function main(phase = "setup"): Promise { copyFileSync(process.argv[1]!, path.join(workspaceRoot, ".setup-vp-runtime.mjs")); } - const installCommand = await setupSfw(runInstallEntries); + const installCommand = await setupSfw(runInstallEntries, env, version); await runInstall(runInstallEntries, projectDir, installCommand); if (cacheSaveEnabled) cache.save(); diff --git a/src/gitlab/install-sfw.ts b/src/gitlab/install-sfw.ts index 2474b8a..93ee89a 100644 --- a/src/gitlab/install-sfw.ts +++ b/src/gitlab/install-sfw.ts @@ -13,9 +13,11 @@ export { downloadFile, getSfwAssetName, isMuslLinux, SFW_VERSION }; export async function setupSfw( runInstallEntries: RunInstallEntry[], env: NodeJS.ProcessEnv = process.env, + vitePlusVersion = "", ): Promise { return setupSfwCore(runInstallEntries, { env, + vitePlusVersion, exportVariable: (name, value) => exportShellEnv(name, value, env), }); } diff --git a/src/index.test.ts b/src/index.test.ts index aa08b5f..d27ee95 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -6,6 +6,8 @@ vi.mock("@actions/core", async (importOriginal) => { ...actual, getState: vi.fn(() => "true"), info: vi.fn(), + saveState: vi.fn(), + setOutput: vi.fn(), }; }); vi.mock("./inputs.js", () => ({ @@ -20,10 +22,26 @@ vi.mock("./inputs.js", () => ({ vi.mock("./cache-save.js", () => ({ saveCache: vi.fn(), })); +vi.mock("@actions/exec", () => ({ + exec: vi.fn(), + getExecOutput: vi.fn(async () => ({ stdout: "vp v0.3.2" })), +})); +vi.mock("./install-viteplus.js", () => ({ installVitePlus: vi.fn() })); +vi.mock("./install-sfw.js", () => ({ setupSfw: vi.fn() })); +vi.mock("./run-install.js", () => ({ runViteInstall: vi.fn() })); +vi.mock("./auth.js", () => ({ + configAuthentication: vi.fn(), + propagateProjectNpmrcAuth: vi.fn(), +})); +vi.mock("./version-file.js", () => ({ resolveVitePlusVersion: vi.fn() })); import { info } from "@actions/core"; import { saveCache } from "./cache-save.js"; -import { runPost } from "./index.js"; +import { runMain, runPost } from "./index.js"; +import { installVitePlus } from "./install-viteplus.js"; +import { setupSfw } from "./install-sfw.js"; +import { runViteInstall } from "./run-install.js"; +import { resolveVitePlusVersion } from "./version-file.js"; import type { Inputs } from "./types.js"; const mockedInfo = vi.mocked(info); @@ -37,6 +55,21 @@ const inputs = (cache: boolean, cacheSave: boolean): Inputs => ({ cacheSave, }); +describe("runMain sfw", () => { + it("passes the resolved preview version to sfw setup and installs without sfw", async () => { + const version = "0.0.0-commit.7d848b3da1987fa60b4cf18487fcc36a2a697e94"; + vi.mocked(resolveVitePlusVersion).mockReturnValue(version); + vi.mocked(setupSfw).mockResolvedValue(false); + const requested = { ...inputs(false, true), sfw: true, runInstall: [{}] }; + + await runMain(requested); + + expect(installVitePlus).toHaveBeenCalledWith({ ...requested, version }); + expect(setupSfw).toHaveBeenCalledWith({ ...requested, version }); + expect(runViteInstall).toHaveBeenCalledWith({ ...requested, sfw: false }); + }); +}); + describe("runPost", () => { beforeEach(() => { vi.clearAllMocks(); diff --git a/src/index.ts b/src/index.ts index 8fa4f5e..a02fc4b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -15,7 +15,7 @@ import { resolveVitePlusVersion } from "./version-file.js"; import { configAuthentication, propagateProjectNpmrcAuth } from "./auth.js"; import { getConfiguredProjectDir, parseInstalledVpVersion } from "./utils.js"; -async function runMain(inputs: Inputs): Promise { +export async function runMain(inputs: Inputs): Promise { // Mark that post action should run saveState(State.IsPost, "true"); const projectDir = getConfiguredProjectDir(inputs); @@ -64,10 +64,10 @@ async function runMain(inputs: Inputs): Promise { } // Step 6: Install Socket Firewall Free if requested (must run before vp install). - // setupSfw centralizes all the decision branches: run-install disabled, sfw + // setupSfw centralizes all the decision branches: preview build, run-install disabled, sfw // already on PATH (e.g. via socketdev/action@), supported platform // (downloads our pinned binary), unsupported platform (falls back). - const effectiveSfw = await setupSfw(inputs); + const effectiveSfw = await setupSfw({ ...inputs, version }); // Step 7: Run vp install if requested if (inputs.runInstall.length > 0) { diff --git a/src/install-sfw.test.ts b/src/install-sfw.test.ts index f3e6cc3..2f08ba3 100644 --- a/src/install-sfw.test.ts +++ b/src/install-sfw.test.ts @@ -172,6 +172,40 @@ describe("setupSfw", () => { expect(warning).not.toHaveBeenCalled(); }); + it.each(["linux", "darwin", "win32"] as const)( + "disables sfw for preview builds on %s even when sfw is on PATH", + async (platform) => { + stubPlatform(platform, "x64"); + vi.mocked(execFileSync).mockReturnValue("/usr/bin/sfw\n"); + const version = "0.0.0-commit.7d848b3da1987fa60b4cf18487fcc36a2a697e94"; + + expect(await setupSfw(makeInputs({ version }))).toBe(false); + + expect(warning).toHaveBeenCalledExactlyOnceWith( + `sfw was requested but is automatically disabled for Vite+ preview build ${version}; Socket Firewall Free will not be used.`, + ); + expect(execFileSync).not.toHaveBeenCalled(); + expect(restoreCache).not.toHaveBeenCalled(); + expect(exec).not.toHaveBeenCalled(); + expect(addPath).not.toHaveBeenCalled(); + }, + ); + + it("does not warn about preview builds when sfw is already disabled", async () => { + const version = "0.0.0-commit.7d848b3da1987fa60b4cf18487fcc36a2a697e94"; + expect(await setupSfw(makeInputs({ sfw: false, version }))).toBe(false); + expect(warning).not.toHaveBeenCalled(); + }); + + it.each(["0.3.2", "0.3.3-alpha.1", "latest", "next"])( + "keeps sfw enabled for %s", + async (version) => { + vi.mocked(execFileSync).mockReturnValue("/usr/bin/sfw\n"); + expect(await setupSfw(makeInputs({ version }))).toBe(true); + expect(warning).not.toHaveBeenCalled(); + }, + ); + it("returns false with an info log when run-install is empty", async () => { expect(await setupSfw(makeInputs({ runInstall: [] }))).toBe(false); expect(info).toHaveBeenCalledWith(expect.stringContaining("`run-install` is disabled")); diff --git a/src/install-sfw.ts b/src/install-sfw.ts index bb7b2aa..800f8ac 100644 --- a/src/install-sfw.ts +++ b/src/install-sfw.ts @@ -5,6 +5,7 @@ import { execFileSync } from "node:child_process"; import { chmodSync, existsSync, mkdirSync } from "node:fs"; import { join } from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; +import { resolveSfwEnabled } from "./ci/sfw.js"; import type { Inputs } from "./types.js"; // Pin sfw so a re-run of the same commit gets the same binary. Renovate @@ -183,7 +184,7 @@ export function findSfwOnPath(): string | null { // fail the handshake; that's a documented requirement, not something we guard // against here. export async function setupSfw(inputs: Inputs): Promise { - if (!inputs.sfw) return false; + if (!resolveSfwEnabled(inputs.sfw, inputs.version, warning)) return false; if (inputs.runInstall.length === 0) { info("sfw was requested but `run-install` is disabled; sfw will not be invoked."); From 3b8ec9df47e0b83282c130d2b5640d67a6122fac Mon Sep 17 00:00:00 2001 From: MK Date: Wed, 16 Sep 2026 15:03:32 +0800 Subject: [PATCH 3/3] refactor: simplify sfw preview handling --- src/azure/parity.test.ts | 5 +++-- src/ci/install-sfw.test.ts | 19 +++++++++---------- src/ci/install-sfw.ts | 15 ++++++--------- src/gitlab/index.test.ts | 9 +++++---- src/index.ts | 4 +--- src/install-sfw.test.ts | 10 +++++----- 6 files changed, 29 insertions(+), 33 deletions(-) diff --git a/src/azure/parity.test.ts b/src/azure/parity.test.ts index d568e84..4be6081 100644 --- a/src/azure/parity.test.ts +++ b/src/azure/parity.test.ts @@ -107,8 +107,9 @@ describe("Azure parity", () => { const { project, env, ports } = fixture(); const version = "0.0.0-commit.7d848b3da1987fa60b4cf18487fcc36a2a697e94"; const target: NodeJS.ProcessEnv = { ...env, SETUP_VP_SFW: "true" }; - if (source === "explicit") target.SETUP_VP_VERSION = version; - else if (source === "version-file") { + if (source === "explicit") { + target.SETUP_VP_VERSION = version; + } else if (source === "version-file") { writeFileSync( path.join(project, "pnpm-workspace.yaml"), `catalog:\n vite-plus: ${version}\n`, diff --git a/src/ci/install-sfw.test.ts b/src/ci/install-sfw.test.ts index d316fa5..eb4a3b7 100644 --- a/src/ci/install-sfw.test.ts +++ b/src/ci/install-sfw.test.ts @@ -24,17 +24,16 @@ describe("portable sfw preview handling", () => { const logWarning = vi.fn(); const env = { SETUP_VP_SFW: "true", PATH: "/bin" }; - expect( - await setupSfw([{}], { - env, - vitePlusVersion, - platform, - download, - exportVariable, - logWarning, - }), - ).toBe("vp"); + const installCommand = await setupSfw([{}], { + env, + vitePlusVersion, + platform, + download, + exportVariable, + logWarning, + }); + expect(installCommand).toBe("vp"); expect(logWarning).toHaveBeenCalledExactlyOnceWith( `sfw was requested but is automatically disabled for Vite+ preview build ${vitePlusVersion}; Socket Firewall Free will not be used.`, ); diff --git a/src/ci/install-sfw.ts b/src/ci/install-sfw.ts index 9f2c7ae..927f9f3 100644 --- a/src/ci/install-sfw.ts +++ b/src/ci/install-sfw.ts @@ -170,15 +170,12 @@ export async function setupSfw( const isMusl = options.isMusl ?? isMuslLinux(); const download = options.download ?? downloadFile; - if ( - !resolveSfwEnabled( - sfwEnabled, - options.vitePlusVersion ?? "", - options.logWarning ?? console.warn, - ) - ) { - return "vp"; - } + const effectiveSfw = resolveSfwEnabled( + sfwEnabled, + options.vitePlusVersion ?? "", + options.logWarning ?? console.warn, + ); + if (!effectiveSfw) return "vp"; if (runInstallEntries.length === 0) { console.log( diff --git a/src/gitlab/index.test.ts b/src/gitlab/index.test.ts index d99e7d6..2acba69 100644 --- a/src/gitlab/index.test.ts +++ b/src/gitlab/index.test.ts @@ -5,8 +5,7 @@ import { tmpdir } from "node:os"; import { afterEach, describe, expect, it, vi } from "vite-plus/test"; import { installVitePlus } from "../ci/install-viteplus.js"; import { setupSfw } from "../ci/install-sfw.js"; -import { run } from "../ci/process.js"; -import { commandPath, getCommandOutput, runWithOutput } from "../ci/process.js"; +import { commandPath, getCommandOutput, run, runWithOutput } from "../ci/process.js"; import { applyEnvironmentModes, isEntrypoint, main } from "./index.js"; vi.mock("../ci/process.js", () => ({ @@ -102,12 +101,14 @@ describe("GitLab setup parity", () => { async (source) => { const root = fixture(); const version = "0.0.0-commit.7d848b3da1987fa60b4cf18487fcc36a2a697e94"; - if (source === "explicit") vi.stubEnv("SETUP_VP_VERSION", version); - else + if (source === "explicit") { + vi.stubEnv("SETUP_VP_VERSION", version); + } else { writeFileSync( path.join(root, "app/package.json"), JSON.stringify({ devDependencies: { "vite-plus": version } }), ); + } vi.stubEnv("SETUP_VP_SFW", "true"); vi.stubEnv("SETUP_VP_RUN_INSTALL", "true"); vi.mocked(commandPath).mockReturnValue("/bin/sfw"); diff --git a/src/index.ts b/src/index.ts index a02fc4b..a21a71d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -64,9 +64,7 @@ export async function runMain(inputs: Inputs): Promise { } // Step 6: Install Socket Firewall Free if requested (must run before vp install). - // setupSfw centralizes all the decision branches: preview build, run-install disabled, sfw - // already on PATH (e.g. via socketdev/action@), supported platform - // (downloads our pinned binary), unsupported platform (falls back). + // Use the resolved version so preview pins in files also disable sfw. const effectiveSfw = await setupSfw({ ...inputs, version }); // Step 7: Run vp install if requested diff --git a/src/install-sfw.test.ts b/src/install-sfw.test.ts index 2f08ba3..c6390bb 100644 --- a/src/install-sfw.test.ts +++ b/src/install-sfw.test.ts @@ -152,6 +152,8 @@ function makeInputs(overrides: Partial = {}): Inputs { } describe("setupSfw", () => { + const previewVersion = "0.0.0-commit.7d848b3da1987fa60b4cf18487fcc36a2a697e94"; + beforeEach(() => { vi.resetAllMocks(); stubPlatform("linux", "x64"); @@ -177,12 +179,11 @@ describe("setupSfw", () => { async (platform) => { stubPlatform(platform, "x64"); vi.mocked(execFileSync).mockReturnValue("/usr/bin/sfw\n"); - const version = "0.0.0-commit.7d848b3da1987fa60b4cf18487fcc36a2a697e94"; - expect(await setupSfw(makeInputs({ version }))).toBe(false); + expect(await setupSfw(makeInputs({ version: previewVersion }))).toBe(false); expect(warning).toHaveBeenCalledExactlyOnceWith( - `sfw was requested but is automatically disabled for Vite+ preview build ${version}; Socket Firewall Free will not be used.`, + `sfw was requested but is automatically disabled for Vite+ preview build ${previewVersion}; Socket Firewall Free will not be used.`, ); expect(execFileSync).not.toHaveBeenCalled(); expect(restoreCache).not.toHaveBeenCalled(); @@ -192,8 +193,7 @@ describe("setupSfw", () => { ); it("does not warn about preview builds when sfw is already disabled", async () => { - const version = "0.0.0-commit.7d848b3da1987fa60b4cf18487fcc36a2a697e94"; - expect(await setupSfw(makeInputs({ sfw: false, version }))).toBe(false); + expect(await setupSfw(makeInputs({ sfw: false, version: previewVersion }))).toBe(false); expect(warning).not.toHaveBeenCalled(); });