From e0114a9f1531f24dde32c47f6885645d0e8701e9 Mon Sep 17 00:00:00 2001 From: Ryan Cao <70191398+ryanccn@users.noreply.github.com> Date: Wed, 19 Jul 2023 10:02:52 +0800 Subject: [PATCH] fix: use `StringStream` --- action.yml | 1 + dist/index.js | 4 ++-- dist/post.js | 4 ++-- src/utils.ts | 30 ++++++++++++++++++------------ 4 files changed, 23 insertions(+), 16 deletions(-) diff --git a/action.yml b/action.yml index c13439c..518d8d7 100644 --- a/action.yml +++ b/action.yml @@ -19,3 +19,4 @@ runs: using: "node16" main: "dist/index.js" post: "dist/post.js" + post-if: "success()" diff --git a/dist/index.js b/dist/index.js index d6c08dd..513c03c 100644 --- a/dist/index.js +++ b/dist/index.js @@ -18,8 +18,8 @@ Content-Type: ${v.type||"application/octet-stream"}\r `)),c.push(`--${b}--`),new B(c,{type:"multipart/form-data; boundary="+b})}async function consumeBody(data){if(data[INTERNALS$2].disturbed)throw new TypeError(`body used already for: ${data.url}`);if(data[INTERNALS$2].disturbed=!0,data[INTERNALS$2].error)throw data[INTERNALS$2].error;let{body}=data;if(body===null)return import_node_buffer.Buffer.alloc(0);if(!(body instanceof import_node_stream.default))return import_node_buffer.Buffer.alloc(0);let accum=[],accumBytes=0;try{for await(let chunk of body){if(data.size>0&&accumBytes+chunk.length>data.size){let error=new FetchError(`content size at ${data.url} over limit: ${data.size}`,"max-size");throw body.destroy(error),error}accumBytes+=chunk.length,accum.push(chunk)}}catch(error){throw error instanceof FetchBaseError?error:new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error.message}`,"system",error)}if(body.readableEnded===!0||body._readableState.ended===!0)try{return accum.every(c=>typeof c=="string")?import_node_buffer.Buffer.from(accum.join("")):import_node_buffer.Buffer.concat(accum,accumBytes)}catch(error){throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error.message}`,"system",error)}else throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`)}function fromRawHeaders(headers=[]){return new Headers(headers.reduce((result,value,index,array)=>(index%2===0&&result.push(array.slice(index,index+2)),result),[]).filter(([name,value])=>{try{return validateHeaderName(name),validateHeaderValue(name,String(value)),!0}catch{return!1}}))}function stripURLForUseAsAReferrer(url,originOnly=!1){return url==null||(url=new URL(url),/^(about|blob|data):$/.test(url.protocol))?"no-referrer":(url.username="",url.password="",url.hash="",originOnly&&(url.pathname="",url.search=""),url)}function validateReferrerPolicy(referrerPolicy){if(!ReferrerPolicy.has(referrerPolicy))throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);return referrerPolicy}function isOriginPotentiallyTrustworthy(url){if(/^(http|ws)s:$/.test(url.protocol))return!0;let hostIp=url.host.replace(/(^\[)|(]$)/g,""),hostIPVersion=(0,import_node_net.isIP)(hostIp);return hostIPVersion===4&&/^127\./.test(hostIp)||hostIPVersion===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)?!0:url.host==="localhost"||url.host.endsWith(".localhost")?!1:url.protocol==="file:"}function isUrlPotentiallyTrustworthy(url){return/^about:(blank|srcdoc)$/.test(url)||url.protocol==="data:"||/^(blob|filesystem):$/.test(url.protocol)?!0:isOriginPotentiallyTrustworthy(url)}function determineRequestsReferrer(request,{referrerURLCallback,referrerOriginCallback}={}){if(request.referrer==="no-referrer"||request.referrerPolicy==="")return null;let policy=request.referrerPolicy;if(request.referrer==="about:client")return"no-referrer";let referrerSource=request.referrer,referrerURL=stripURLForUseAsAReferrer(referrerSource),referrerOrigin=stripURLForUseAsAReferrer(referrerSource,!0);referrerURL.toString().length>4096&&(referrerURL=referrerOrigin),referrerURLCallback&&(referrerURL=referrerURLCallback(referrerURL)),referrerOriginCallback&&(referrerOrigin=referrerOriginCallback(referrerOrigin));let currentURL=new URL(request.url);switch(policy){case"no-referrer":return"no-referrer";case"origin":return referrerOrigin;case"unsafe-url":return referrerURL;case"strict-origin":return isUrlPotentiallyTrustworthy(referrerURL)&&!isUrlPotentiallyTrustworthy(currentURL)?"no-referrer":referrerOrigin.toString();case"strict-origin-when-cross-origin":return referrerURL.origin===currentURL.origin?referrerURL:isUrlPotentiallyTrustworthy(referrerURL)&&!isUrlPotentiallyTrustworthy(currentURL)?"no-referrer":referrerOrigin;case"same-origin":return referrerURL.origin===currentURL.origin?referrerURL:"no-referrer";case"origin-when-cross-origin":return referrerURL.origin===currentURL.origin?referrerURL:referrerOrigin;case"no-referrer-when-downgrade":return isUrlPotentiallyTrustworthy(referrerURL)&&!isUrlPotentiallyTrustworthy(currentURL)?"no-referrer":referrerURL;default:throw new TypeError(`Invalid referrerPolicy: ${policy}`)}}function parseReferrerPolicyFromHeader(headers){let policyTokens=(headers.get("referrer-policy")||"").split(/[,\s]+/),policy="";for(let token of policyTokens)token&&ReferrerPolicy.has(token)&&(policy=token);return policy}async function fetch(url,options_){return new Promise((resolve,reject)=>{let request=new Request(url,options_),{parsedURL,options}=getNodeRequestOptions(request);if(!supportedSchemas.has(parsedURL.protocol))throw new TypeError(`node-fetch cannot load ${url}. URL scheme "${parsedURL.protocol.replace(/:$/,"")}" is not supported.`);if(parsedURL.protocol==="data:"){let data=dataUriToBuffer(request.url),response2=new Response(data,{headers:{"Content-Type":data.typeFull}});resolve(response2);return}let send=(parsedURL.protocol==="https:"?import_node_https.default:import_node_http.default).request,{signal}=request,response=null,abort=()=>{let error=new AbortError("The operation was aborted.");reject(error),request.body&&request.body instanceof import_node_stream.default.Readable&&request.body.destroy(error),!(!response||!response.body)&&response.body.emit("error",error)};if(signal&&signal.aborted){abort();return}let abortAndFinalize=()=>{abort(),finalize()},request_=send(parsedURL.toString(),options);signal&&signal.addEventListener("abort",abortAndFinalize);let finalize=()=>{request_.abort(),signal&&signal.removeEventListener("abort",abortAndFinalize)};request_.on("error",error=>{reject(new FetchError(`request to ${request.url} failed, reason: ${error.message}`,"system",error)),finalize()}),fixResponseChunkedTransferBadEnding(request_,error=>{response&&response.body&&response.body.destroy(error)}),process.version<"v14"&&request_.on("socket",s2=>{let endedWithEventsCount;s2.prependListener("end",()=>{endedWithEventsCount=s2._eventsCount}),s2.prependListener("close",hadError=>{if(response&&endedWithEventsCount{request_.setTimeout(0);let headers=fromRawHeaders(response_.rawHeaders);if(isRedirect(response_.statusCode)){let location=headers.get("Location"),locationURL=null;try{locationURL=location===null?null:new URL(location,request.url)}catch{if(request.redirect!=="manual"){reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`,"invalid-redirect")),finalize();return}}switch(request.redirect){case"error":reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`,"no-redirect")),finalize();return;case"manual":break;case"follow":{if(locationURL===null)break;if(request.counter>=request.follow){reject(new FetchError(`maximum redirect reached at: ${request.url}`,"max-redirect")),finalize();return}let requestOptions={headers:new Headers(request.headers),follow:request.follow,counter:request.counter+1,agent:request.agent,compress:request.compress,method:request.method,body:clone(request),signal:request.signal,size:request.size,referrer:request.referrer,referrerPolicy:request.referrerPolicy};if(!isDomainOrSubdomain(request.url,locationURL)||!isSameProtocol(request.url,locationURL))for(let name of["authorization","www-authenticate","cookie","cookie2"])requestOptions.headers.delete(name);if(response_.statusCode!==303&&request.body&&options_.body instanceof import_node_stream.default.Readable){reject(new FetchError("Cannot follow redirect with body being a readable stream","unsupported-redirect")),finalize();return}(response_.statusCode===303||(response_.statusCode===301||response_.statusCode===302)&&request.method==="POST")&&(requestOptions.method="GET",requestOptions.body=void 0,requestOptions.headers.delete("content-length"));let responseReferrerPolicy=parseReferrerPolicyFromHeader(headers);responseReferrerPolicy&&(requestOptions.referrerPolicy=responseReferrerPolicy),resolve(fetch(new Request(locationURL,requestOptions))),finalize();return}default:return reject(new TypeError(`Redirect option '${request.redirect}' is not a valid value of RequestRedirect`))}}signal&&response_.once("end",()=>{signal.removeEventListener("abort",abortAndFinalize)});let body=(0,import_node_stream.pipeline)(response_,new import_node_stream.PassThrough,error=>{error&&reject(error)});process.version<"v12.10"&&response_.on("aborted",abortAndFinalize);let responseOptions={url:request.url,status:response_.statusCode,statusText:response_.statusMessage,headers,size:request.size,counter:request.counter,highWaterMark:request.highWaterMark},codings=headers.get("Content-Encoding");if(!request.compress||request.method==="HEAD"||codings===null||response_.statusCode===204||response_.statusCode===304){response=new Response(body,responseOptions),resolve(response);return}let zlibOptions={flush:import_node_zlib.default.Z_SYNC_FLUSH,finishFlush:import_node_zlib.default.Z_SYNC_FLUSH};if(codings==="gzip"||codings==="x-gzip"){body=(0,import_node_stream.pipeline)(body,import_node_zlib.default.createGunzip(zlibOptions),error=>{error&&reject(error)}),response=new Response(body,responseOptions),resolve(response);return}if(codings==="deflate"||codings==="x-deflate"){let raw=(0,import_node_stream.pipeline)(response_,new import_node_stream.PassThrough,error=>{error&&reject(error)});raw.once("data",chunk=>{(chunk[0]&15)===8?body=(0,import_node_stream.pipeline)(body,import_node_zlib.default.createInflate(),error=>{error&&reject(error)}):body=(0,import_node_stream.pipeline)(body,import_node_zlib.default.createInflateRaw(),error=>{error&&reject(error)}),response=new Response(body,responseOptions),resolve(response)}),raw.once("end",()=>{response||(response=new Response(body,responseOptions),resolve(response))});return}if(codings==="br"){body=(0,import_node_stream.pipeline)(body,import_node_zlib.default.createBrotliDecompress(),error=>{error&&reject(error)}),response=new Response(body,responseOptions),resolve(response);return}response=new Response(body,responseOptions),resolve(response)}),writeToStream(request_,request).catch(reject)})}function fixResponseChunkedTransferBadEnding(request,errorCallback){let LAST_CHUNK=import_node_buffer.Buffer.from(`0\r \r `),isChunkedTransfer=!1,properLastChunkReceived=!1,previousChunk;request.on("response",response=>{let{headers}=response;isChunkedTransfer=headers["transfer-encoding"]==="chunked"&&!headers["content-length"]}),request.on("socket",socket=>{let onSocketClose=()=>{if(isChunkedTransfer&&!properLastChunkReceived){let error=new Error("Premature close");error.code="ERR_STREAM_PREMATURE_CLOSE",errorCallback(error)}},onData=buf=>{properLastChunkReceived=import_node_buffer.Buffer.compare(buf.slice(-5),LAST_CHUNK)===0,!properLastChunkReceived&&previousChunk&&(properLastChunkReceived=import_node_buffer.Buffer.compare(previousChunk.slice(-3),LAST_CHUNK.slice(0,3))===0&&import_node_buffer.Buffer.compare(buf.slice(-2),LAST_CHUNK.slice(3))===0),previousChunk=buf};socket.prependListener("close",onSocketClose),socket.on("data",onData),request.on("close",()=>{socket.removeListener("close",onSocketClose),socket.removeListener("data",onData)})})}function pd(event){let retv=privateData.get(event);return console.assert(retv!=null,"'this' is expected an Event object, but got",event),retv}function setCancelFlag(data){if(data.passiveListener!=null){typeof console<"u"&&typeof console.error=="function"&&console.error("Unable to preventDefault inside passive event listener invocation.",data.passiveListener);return}data.event.cancelable&&(data.canceled=!0,typeof data.event.preventDefault=="function"&&data.event.preventDefault())}function Event(eventTarget,event){privateData.set(this,{eventTarget,event,eventPhase:2,currentTarget:eventTarget,canceled:!1,stopped:!1,immediateStopped:!1,passiveListener:null,timeStamp:event.timeStamp||Date.now()}),Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});let keys=Object.keys(event);for(let i2=0;i20){let types2=new Array(arguments.length);for(let i2=0;i2{},Object.assign(globalThis,require("node:stream/web")),process2.emitWarning=emitWarning}catch(error){throw process2.emitWarning=emitWarning,error}}catch{Object.assign(globalThis,requirePonyfill_es2018())}try{let{Blob:Blob4}=require("buffer");Blob4&&!Blob4.prototype.stream&&(Blob4.prototype.stream=function(params){let position=0,blob=this;return new ReadableStream({type:"bytes",async pull(ctrl){let buffer=await blob.slice(position,Math.min(blob.size,position+POOL_SIZE$1)).arrayBuffer();position+=buffer.byteLength,ctrl.enqueue(new Uint8Array(buffer)),position===blob.size&&ctrl.close()}})})}catch{}POOL_SIZE=65536;_Blob=class Blob{#parts=[];#type="";#size=0;#endings="transparent";constructor(blobParts=[],options={}){if(typeof blobParts!="object"||blobParts===null)throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if(typeof blobParts[Symbol.iterator]!="function")throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if(typeof options!="object"&&typeof options!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");options===null&&(options={});let encoder=new TextEncoder;for(let element of blobParts){let part;ArrayBuffer.isView(element)?part=new Uint8Array(element.buffer.slice(element.byteOffset,element.byteOffset+element.byteLength)):element instanceof ArrayBuffer?part=new Uint8Array(element.slice(0)):element instanceof Blob?part=element:part=encoder.encode(`${element}`),this.#size+=ArrayBuffer.isView(part)?part.byteLength:part.size,this.#parts.push(part)}this.#endings=`${options.endings===void 0?"transparent":options.endings}`;let type=options.type===void 0?"":String(options.type);this.#type=/^[\x20-\x7E]*$/.test(type)?type:""}get size(){return this.#size}get type(){return this.#type}async text(){let decoder=new TextDecoder,str="";for await(let part of toIterator(this.#parts,!1))str+=decoder.decode(part,{stream:!0});return str+=decoder.decode(),str}async arrayBuffer(){let data=new Uint8Array(this.size),offset=0;for await(let chunk of toIterator(this.#parts,!1))data.set(chunk,offset),offset+=chunk.length;return data.buffer}stream(){let it=toIterator(this.#parts,!0);return new globalThis.ReadableStream({type:"bytes",async pull(ctrl){let chunk=await it.next();chunk.done?ctrl.close():ctrl.enqueue(chunk.value)},async cancel(){await it.return()}})}slice(start=0,end=this.size,type=""){let{size}=this,relativeStart=start<0?Math.max(size+start,0):Math.min(start,size),relativeEnd=end<0?Math.max(size+end,0):Math.min(end,size),span=Math.max(relativeEnd-relativeStart,0),parts=this.#parts,blobParts=[],added=0;for(let part of parts){if(added>=span)break;let size2=ArrayBuffer.isView(part)?part.byteLength:part.size;if(relativeStart&&size2<=relativeStart)relativeStart-=size2,relativeEnd-=size2;else{let chunk;ArrayBuffer.isView(part)?(chunk=part.subarray(relativeStart,Math.min(size2,relativeEnd)),added+=chunk.byteLength):(chunk=part.slice(relativeStart,Math.min(size2,relativeEnd)),added+=chunk.size),relativeEnd-=size2,blobParts.push(chunk),relativeStart=0}}let blob=new Blob([],{type:String(type).toLowerCase()});return blob.#size=span,blob.#parts=blobParts,blob}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](object){return object&&typeof object=="object"&&typeof object.constructor=="function"&&(typeof object.stream=="function"||typeof object.arrayBuffer=="function")&&/^(Blob|File)$/.test(object[Symbol.toStringTag])}};Object.defineProperties(_Blob.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Blob2=_Blob,_Blob$1=Blob2,_File=class extends _Blob$1{#lastModified=0;#name="";constructor(fileBits,fileName,options={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(fileBits,options),options===null&&(options={});let lastModified=options.lastModified===void 0?Date.now():Number(options.lastModified);Number.isNaN(lastModified)||(this.#lastModified=lastModified),this.#name=String(fileName)}get name(){return this.#name}get lastModified(){return this.#lastModified}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](object){return!!object&&object instanceof _Blob$1&&/^(File)$/.test(object[Symbol.toStringTag])}},File2=_File,File$1=File2;({toStringTag:t,iterator:i,hasInstance:h}=Symbol),r=Math.random,m="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),f2=(a,b,c)=>(a+="",/^(Blob|File)$/.test(b&&b[t])?[(c=c!==void 0?c+"":b[t]=="File"?b.name:"blob",a),b.name!==c||b[t]=="blob"?new File$1([b],c,b):b]:[a,b+""]),e=(c,f3)=>(f3?c:c.replace(/\r?\n|\r/g,`\r -`)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),x=(n,a,e2)=>{if(a.lengthtypeof o[m2]!="function")}append(...a){x("append",arguments,2),this.#d.push(f2(...a))}delete(a){x("delete",arguments,1),a+="",this.#d=this.#d.filter(([b])=>b!==a)}get(a){x("get",arguments,1),a+="";for(var b=this.#d,l=b.length,c=0;cc[0]===a&&b.push(c[1])),b}has(a){return x("has",arguments,1),a+="",this.#d.some(b=>b[0]===a)}forEach(a,b){x("forEach",arguments,1);for(var[c,d]of this)a.call(b,d,c,this)}set(...a){x("set",arguments,2);var b=[],c=!0;a=f2(...a),this.#d.forEach(d=>{d[0]===a[0]?c&&(c=!b.push(a)):b.push(d)}),c&&b.push(a),this.#d=b}*entries(){yield*this.#d}*keys(){for(var[a]of this)yield a}*values(){for(var[,a]of this)yield a}};FetchBaseError=class extends Error{constructor(message,type){super(message),Error.captureStackTrace(this,this.constructor),this.type=type}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}},FetchError=class extends FetchBaseError{constructor(message,type,systemError){super(message,type),systemError&&(this.code=this.errno=systemError.code,this.erroredSysCall=systemError.syscall)}},NAME=Symbol.toStringTag,isURLSearchParameters=object=>typeof object=="object"&&typeof object.append=="function"&&typeof object.delete=="function"&&typeof object.get=="function"&&typeof object.getAll=="function"&&typeof object.has=="function"&&typeof object.set=="function"&&typeof object.sort=="function"&&object[NAME]==="URLSearchParams",isBlob=object=>object&&typeof object=="object"&&typeof object.arrayBuffer=="function"&&typeof object.type=="string"&&typeof object.stream=="function"&&typeof object.constructor=="function"&&/^(Blob|File)$/.test(object[NAME]),isAbortSignal=object=>typeof object=="object"&&(object[NAME]==="AbortSignal"||object[NAME]==="EventTarget"),isDomainOrSubdomain=(destination,original)=>{let orig=new URL(original).hostname,dest=new URL(destination).hostname;return orig===dest||orig.endsWith(`.${dest}`)},isSameProtocol=(destination,original)=>{let orig=new URL(original).protocol,dest=new URL(destination).protocol;return orig===dest},pipeline=(0,import_node_util.promisify)(import_node_stream.default.pipeline),INTERNALS$2=Symbol("Body internals"),Body=class{constructor(body,{size=0}={}){let boundary=null;body===null?body=null:isURLSearchParameters(body)?body=import_node_buffer.Buffer.from(body.toString()):isBlob(body)||import_node_buffer.Buffer.isBuffer(body)||(import_node_util.types.isAnyArrayBuffer(body)?body=import_node_buffer.Buffer.from(body):ArrayBuffer.isView(body)?body=import_node_buffer.Buffer.from(body.buffer,body.byteOffset,body.byteLength):body instanceof import_node_stream.default||(body instanceof FormData?(body=formDataToBlob(body),boundary=body.type.split("=")[1]):body=import_node_buffer.Buffer.from(String(body))));let stream=body;import_node_buffer.Buffer.isBuffer(body)?stream=import_node_stream.default.Readable.from(body):isBlob(body)&&(stream=import_node_stream.default.Readable.from(body.stream())),this[INTERNALS$2]={body,stream,boundary,disturbed:!1,error:null},this.size=size,body instanceof import_node_stream.default&&body.on("error",error_=>{let error=error_ instanceof FetchBaseError?error_:new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`,"system",error_);this[INTERNALS$2].error=error})}get body(){return this[INTERNALS$2].stream}get bodyUsed(){return this[INTERNALS$2].disturbed}async arrayBuffer(){let{buffer,byteOffset,byteLength}=await consumeBody(this);return buffer.slice(byteOffset,byteOffset+byteLength)}async formData(){let ct=this.headers.get("content-type");if(ct.startsWith("application/x-www-form-urlencoded")){let formData=new FormData,parameters=new URLSearchParams(await this.text());for(let[name,value]of parameters)formData.append(name,value);return formData}let{toFormData:toFormData2}=await Promise.resolve().then(()=>(init_multipart_parser(),multipart_parser_exports));return toFormData2(this.body,ct)}async blob(){let ct=this.headers&&this.headers.get("content-type")||this[INTERNALS$2].body&&this[INTERNALS$2].body.type||"",buf=await this.arrayBuffer();return new _Blob$1([buf],{type:ct})}async json(){let text=await this.text();return JSON.parse(text)}async text(){let buffer=await consumeBody(this);return new TextDecoder().decode(buffer)}buffer(){return consumeBody(this)}};Body.prototype.buffer=(0,import_node_util.deprecate)(Body.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(Body.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:(0,import_node_util.deprecate)(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});clone=(instance,highWaterMark)=>{let p1,p2,{body}=instance[INTERNALS$2];if(instance.bodyUsed)throw new Error("cannot clone body after it is used");return body instanceof import_node_stream.default&&typeof body.getBoundary!="function"&&(p1=new import_node_stream.PassThrough({highWaterMark}),p2=new import_node_stream.PassThrough({highWaterMark}),body.pipe(p1),body.pipe(p2),instance[INTERNALS$2].stream=p1,body=p2),body},getNonSpecFormDataBoundary=(0,import_node_util.deprecate)(body=>body.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),extractContentType=(body,request)=>body===null?null:typeof body=="string"?"text/plain;charset=UTF-8":isURLSearchParameters(body)?"application/x-www-form-urlencoded;charset=UTF-8":isBlob(body)?body.type||null:import_node_buffer.Buffer.isBuffer(body)||import_node_util.types.isAnyArrayBuffer(body)||ArrayBuffer.isView(body)?null:body instanceof FormData?`multipart/form-data; boundary=${request[INTERNALS$2].boundary}`:body&&typeof body.getBoundary=="function"?`multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`:body instanceof import_node_stream.default?null:"text/plain;charset=UTF-8",getTotalBytes=request=>{let{body}=request[INTERNALS$2];return body===null?0:isBlob(body)?body.size:import_node_buffer.Buffer.isBuffer(body)?body.length:body&&typeof body.getLengthSync=="function"&&body.hasKnownLength&&body.hasKnownLength()?body.getLengthSync():null},writeToStream=async(dest,{body})=>{body===null?dest.end():await pipeline(body,dest)},validateHeaderName=typeof import_node_http.default.validateHeaderName=="function"?import_node_http.default.validateHeaderName:name=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)){let error=new TypeError(`Header name must be a valid HTTP token [${name}]`);throw Object.defineProperty(error,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),error}},validateHeaderValue=typeof import_node_http.default.validateHeaderValue=="function"?import_node_http.default.validateHeaderValue:(name,value)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)){let error=new TypeError(`Invalid character in header content ["${name}"]`);throw Object.defineProperty(error,"code",{value:"ERR_INVALID_CHAR"}),error}},Headers=class _Headers extends URLSearchParams{constructor(init){let result=[];if(init instanceof _Headers){let raw=init.raw();for(let[name,values]of Object.entries(raw))result.push(...values.map(value=>[name,value]))}else if(init!=null)if(typeof init=="object"&&!import_node_util.types.isBoxedPrimitive(init)){let method=init[Symbol.iterator];if(method==null)result.push(...Object.entries(init));else{if(typeof method!="function")throw new TypeError("Header pairs must be iterable");result=[...init].map(pair=>{if(typeof pair!="object"||import_node_util.types.isBoxedPrimitive(pair))throw new TypeError("Each header pair must be an iterable object");return[...pair]}).map(pair=>{if(pair.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return[...pair]})}}else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence> or record)");return result=result.length>0?result.map(([name,value])=>(validateHeaderName(name),validateHeaderValue(name,String(value)),[String(name).toLowerCase(),String(value)])):void 0,super(result),new Proxy(this,{get(target,p,receiver){switch(p){case"append":case"set":return(name,value)=>(validateHeaderName(name),validateHeaderValue(name,String(value)),URLSearchParams.prototype[p].call(target,String(name).toLowerCase(),String(value)));case"delete":case"has":case"getAll":return name=>(validateHeaderName(name),URLSearchParams.prototype[p].call(target,String(name).toLowerCase()));case"keys":return()=>(target.sort(),new Set(URLSearchParams.prototype.keys.call(target)).keys());default:return Reflect.get(target,p,receiver)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(name){let values=this.getAll(name);if(values.length===0)return null;let value=values.join(", ");return/^content-encoding$/i.test(name)&&(value=value.toLowerCase()),value}forEach(callback,thisArg=void 0){for(let name of this.keys())Reflect.apply(callback,thisArg,[this.get(name),name,this])}*values(){for(let name of this.keys())yield this.get(name)}*entries(){for(let name of this.keys())yield[name,this.get(name)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((result,key)=>(result[key]=this.getAll(key),result),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((result,key)=>{let values=this.getAll(key);return key==="host"?result[key]=values[0]:result[key]=values.length>1?values:values[0],result},{})}};Object.defineProperties(Headers.prototype,["get","entries","forEach","values"].reduce((result,property)=>(result[property]={enumerable:!0},result),{}));redirectStatus=new Set([301,302,303,307,308]),isRedirect=code=>redirectStatus.has(code),INTERNALS$1=Symbol("Response internals"),Response=class _Response extends Body{constructor(body=null,options={}){super(body,options);let status=options.status!=null?options.status:200,headers=new Headers(options.headers);if(body!==null&&!headers.has("Content-Type")){let contentType=extractContentType(body,this);contentType&&headers.append("Content-Type",contentType)}this[INTERNALS$1]={type:"default",url:options.url,status,statusText:options.statusText||"",headers,counter:options.counter,highWaterMark:options.highWaterMark}}get type(){return this[INTERNALS$1].type}get url(){return this[INTERNALS$1].url||""}get status(){return this[INTERNALS$1].status}get ok(){return this[INTERNALS$1].status>=200&&this[INTERNALS$1].status<300}get redirected(){return this[INTERNALS$1].counter>0}get statusText(){return this[INTERNALS$1].statusText}get headers(){return this[INTERNALS$1].headers}get highWaterMark(){return this[INTERNALS$1].highWaterMark}clone(){return new _Response(clone(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(url,status=302){if(!isRedirect(status))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new _Response(null,{headers:{location:new URL(url).toString()},status})}static error(){let response=new _Response(null,{status:0,statusText:""});return response[INTERNALS$1].type="error",response}static json(data=void 0,init={}){let body=JSON.stringify(data);if(body===void 0)throw new TypeError("data is not JSON serializable");let headers=new Headers(init&&init.headers);return headers.has("content-type")||headers.set("content-type","application/json"),new _Response(body,{...init,headers})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(Response.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});getSearch=parsedURL=>{if(parsedURL.search)return parsedURL.search;let lastOffset=parsedURL.href.length-1,hash=parsedURL.hash||(parsedURL.href[lastOffset]==="#"?"#":"");return parsedURL.href[lastOffset-hash.length]==="?"?"?":""};ReferrerPolicy=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),DEFAULT_REFERRER_POLICY="strict-origin-when-cross-origin";INTERNALS=Symbol("Request internals"),isRequest=object=>typeof object=="object"&&typeof object[INTERNALS]=="object",doBadDataWarn=(0,import_node_util.deprecate)(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Request=class _Request extends Body{constructor(input,init={}){let parsedURL;if(isRequest(input)?parsedURL=new URL(input.url):(parsedURL=new URL(input),input={}),parsedURL.username!==""||parsedURL.password!=="")throw new TypeError(`${parsedURL} is an url with embedded credentials.`);let method=init.method||input.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(method)&&(method=method.toUpperCase()),!isRequest(init)&&"data"in init&&doBadDataWarn(),(init.body!=null||isRequest(input)&&input.body!==null)&&(method==="GET"||method==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let inputBody=init.body?init.body:isRequest(input)&&input.body!==null?clone(input):null;super(inputBody,{size:init.size||input.size||0});let headers=new Headers(init.headers||input.headers||{});if(inputBody!==null&&!headers.has("Content-Type")){let contentType=extractContentType(inputBody,this);contentType&&headers.set("Content-Type",contentType)}let signal=isRequest(input)?input.signal:null;if("signal"in init&&(signal=init.signal),signal!=null&&!isAbortSignal(signal))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let referrer=init.referrer==null?input.referrer:init.referrer;if(referrer==="")referrer="no-referrer";else if(referrer){let parsedReferrer=new URL(referrer);referrer=/^about:(\/\/)?client$/.test(parsedReferrer)?"client":parsedReferrer}else referrer=void 0;this[INTERNALS]={method,redirect:init.redirect||input.redirect||"follow",headers,parsedURL,signal,referrer},this.follow=init.follow===void 0?input.follow===void 0?20:input.follow:init.follow,this.compress=init.compress===void 0?input.compress===void 0?!0:input.compress:init.compress,this.counter=init.counter||input.counter||0,this.agent=init.agent||input.agent,this.highWaterMark=init.highWaterMark||input.highWaterMark||16384,this.insecureHTTPParser=init.insecureHTTPParser||input.insecureHTTPParser||!1,this.referrerPolicy=init.referrerPolicy||input.referrerPolicy||""}get method(){return this[INTERNALS].method}get url(){return(0,import_node_url.format)(this[INTERNALS].parsedURL)}get headers(){return this[INTERNALS].headers}get redirect(){return this[INTERNALS].redirect}get signal(){return this[INTERNALS].signal}get referrer(){if(this[INTERNALS].referrer==="no-referrer")return"";if(this[INTERNALS].referrer==="client")return"about:client";if(this[INTERNALS].referrer)return this[INTERNALS].referrer.toString()}get referrerPolicy(){return this[INTERNALS].referrerPolicy}set referrerPolicy(referrerPolicy){this[INTERNALS].referrerPolicy=validateReferrerPolicy(referrerPolicy)}clone(){return new _Request(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(Request.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});getNodeRequestOptions=request=>{let{parsedURL}=request[INTERNALS],headers=new Headers(request[INTERNALS].headers);headers.has("Accept")||headers.set("Accept","*/*");let contentLengthValue=null;if(request.body===null&&/^(post|put)$/i.test(request.method)&&(contentLengthValue="0"),request.body!==null){let totalBytes=getTotalBytes(request);typeof totalBytes=="number"&&!Number.isNaN(totalBytes)&&(contentLengthValue=String(totalBytes))}contentLengthValue&&headers.set("Content-Length",contentLengthValue),request.referrerPolicy===""&&(request.referrerPolicy=DEFAULT_REFERRER_POLICY),request.referrer&&request.referrer!=="no-referrer"?request[INTERNALS].referrer=determineRequestsReferrer(request):request[INTERNALS].referrer="no-referrer",request[INTERNALS].referrer instanceof URL&&headers.set("Referer",request.referrer),headers.has("User-Agent")||headers.set("User-Agent","node-fetch"),request.compress&&!headers.has("Accept-Encoding")&&headers.set("Accept-Encoding","gzip, deflate, br");let{agent}=request;typeof agent=="function"&&(agent=agent(parsedURL)),!headers.has("Connection")&&!agent&&headers.set("Connection","close");let search=getSearch(parsedURL),options={path:parsedURL.pathname+search,method:request.method,headers:headers[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:request.insecureHTTPParser,agent};return{parsedURL,options}},AbortError=class extends FetchBaseError{constructor(message,type="aborted"){super(message,type)}};if(!globalThis.DOMException)try{let{MessageChannel}=require("worker_threads"),port=new MessageChannel().port1,ab=new ArrayBuffer;port.postMessage(ab,[ab,ab])}catch(err){err.constructor.name==="DOMException"&&(globalThis.DOMException=err.constructor)}nodeDomexception=globalThis.DOMException,DOMException$1=getDefaultExportFromCjs(nodeDomexception),supportedSchemas=new Set(["data:","http:","https:"]);privateData=new WeakMap,wrappers=new WeakMap;Event.prototype={get type(){return pd(this).event.type},get target(){return pd(this).eventTarget},get currentTarget(){return pd(this).currentTarget},composedPath(){let currentTarget=pd(this).currentTarget;return currentTarget==null?[]:[currentTarget]},get NONE(){return 0},get CAPTURING_PHASE(){return 1},get AT_TARGET(){return 2},get BUBBLING_PHASE(){return 3},get eventPhase(){return pd(this).eventPhase},stopPropagation(){let data=pd(this);data.stopped=!0,typeof data.event.stopPropagation=="function"&&data.event.stopPropagation()},stopImmediatePropagation(){let data=pd(this);data.stopped=!0,data.immediateStopped=!0,typeof data.event.stopImmediatePropagation=="function"&&data.event.stopImmediatePropagation()},get bubbles(){return!!pd(this).event.bubbles},get cancelable(){return!!pd(this).event.cancelable},preventDefault(){setCancelFlag(pd(this))},get defaultPrevented(){return pd(this).canceled},get composed(){return!!pd(this).event.composed},get timeStamp(){return pd(this).timeStamp},get srcElement(){return pd(this).eventTarget},get cancelBubble(){return pd(this).stopped},set cancelBubble(value){if(!value)return;let data=pd(this);data.stopped=!0,typeof data.event.cancelBubble=="boolean"&&(data.event.cancelBubble=!0)},get returnValue(){return!pd(this).canceled},set returnValue(value){value||setCancelFlag(pd(this))},initEvent(){}};Object.defineProperty(Event.prototype,"constructor",{value:Event,configurable:!0,writable:!0});typeof window<"u"&&typeof window.Event<"u"&&(Object.setPrototypeOf(Event.prototype,window.Event.prototype),wrappers.set(window.Event.prototype,Event));listenersMap=new WeakMap,CAPTURE=1,BUBBLE=2,ATTRIBUTE=3;EventTarget.prototype={addEventListener(eventName,listener,options){if(listener==null)return;if(typeof listener!="function"&&!isObject(listener))throw new TypeError("'listener' should be a function or an object.");let listeners=getListeners(this),optionsIsObj=isObject(options),listenerType=(optionsIsObj?!!options.capture:!!options)?CAPTURE:BUBBLE,newNode={listener,listenerType,passive:optionsIsObj&&!!options.passive,once:optionsIsObj&&!!options.once,next:null},node=listeners.get(eventName);if(node===void 0){listeners.set(eventName,newNode);return}let prev=null;for(;node!=null;){if(node.listener===listener&&node.listenerType===listenerType)return;prev=node,node=node.next}prev.next=newNode},removeEventListener(eventName,listener,options){if(listener==null)return;let listeners=getListeners(this),listenerType=(isObject(options)?!!options.capture:!!options)?CAPTURE:BUBBLE,prev=null,node=listeners.get(eventName);for(;node!=null;){if(node.listener===listener&&node.listenerType===listenerType){prev!==null?prev.next=node.next:node.next!==null?listeners.set(eventName,node.next):listeners.delete(eventName);return}prev=node,node=node.next}},dispatchEvent(event){if(event==null||typeof event.type!="string")throw new TypeError('"event.type" should be a string.');let listeners=getListeners(this),eventName=event.type,node=listeners.get(eventName);if(node==null)return!0;let wrappedEvent=wrapEvent(this,event),prev=null;for(;node!=null;){if(node.once?prev!==null?prev.next=node.next:node.next!==null?listeners.set(eventName,node.next):listeners.delete(eventName):prev=node,setPassiveListener(wrappedEvent,node.passive?node.listener:null),typeof node.listener=="function")try{node.listener.call(this,wrappedEvent)}catch(err){typeof console<"u"&&typeof console.error=="function"&&console.error(err)}else node.listenerType!==ATTRIBUTE&&typeof node.listener.handleEvent=="function"&&node.listener.handleEvent(wrappedEvent);if(isStopped(wrappedEvent))break;node=node.next}return setPassiveListener(wrappedEvent,null),setEventPhase(wrappedEvent,0),setCurrentTarget(wrappedEvent,null),!wrappedEvent.defaultPrevented}};Object.defineProperty(EventTarget.prototype,"constructor",{value:EventTarget,configurable:!0,writable:!0});typeof window<"u"&&typeof window.EventTarget<"u"&&Object.setPrototypeOf(EventTarget.prototype,window.EventTarget.prototype);AbortSignal=class extends EventTarget{constructor(){throw super(),new TypeError("AbortSignal cannot be constructed directly")}get aborted(){let aborted=abortedFlags.get(this);if(typeof aborted!="boolean")throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this===null?"null":typeof this}`);return aborted}};defineEventAttribute(AbortSignal.prototype,"abort");abortedFlags=new WeakMap;Object.defineProperties(AbortSignal.prototype,{aborted:{enumerable:!0}});typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(AbortSignal.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortSignal"});AbortController$1=class{constructor(){signals.set(this,createAbortSignal())}get signal(){return getSignal(this)}abort(){abortSignal(getSignal(this))}},signals=new WeakMap;Object.defineProperties(AbortController$1.prototype,{signal:{enumerable:!0},abort:{enumerable:!0}});typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(AbortController$1.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortController"})}});var core=__toESM(require_core()),import_exec=__toESM(require_exec());var import_node_http2=__toESM(require("node:http"),1),import_node_https2=__toESM(require("node:https"),1);init_node_fetch_native_d7878b77();init_node_fetch_native_d7878b77();var import_node_fs=require("node:fs");init_node_fetch_native_d7878b77();var{stat}=import_node_fs.promises;var BlobDataItem=class _BlobDataItem{#path;#start;constructor(options){this.#path=options.path,this.#start=options.start,this.size=options.size,this.lastModified=options.lastModified}slice(start,end){return new _BlobDataItem({path:this.#path,lastModified:this.lastModified,size:end-start,start:this.#start+start})}async*stream(){let{mtimeMs}=await stat(this.#path);if(mtimeMs>this.lastModified)throw new DOMException$1("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.","NotReadableError");yield*(0,import_node_fs.createReadStream)(this.#path,{start:this.#start,end:this.#start+this.size-1})}get[Symbol.toStringTag](){return"Blob"}};var _forceNodeFetch=typeof process!==void 0&&typeof process.env!==void 0&&process.env.FORCE_NODE_FETCH;function _getFetch(){return!_forceNodeFetch&&globalThis.fetch?globalThis.fetch:fetch}var fetch2=_getFetch(),Blob3=!_forceNodeFetch&&globalThis.Blob||_Blob$1,File3=!_forceNodeFetch&&globalThis.File||File$1,FormData3=!_forceNodeFetch&&globalThis.FormData||FormData,Headers2=!_forceNodeFetch&&globalThis.Headers||Headers,Request2=!_forceNodeFetch&&globalThis.Request||Request,Response2=!_forceNodeFetch&&globalThis.Response||Response,AbortController3=!_forceNodeFetch&&globalThis.AbortController||AbortController$1;var suspectProtoRx=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,suspectConstructorRx=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,JsonSigRx=/^\s*["[{]|^\s*-?\d[\d.]{0,14}\s*$/;function jsonParseTransform(key,value){if(key==="__proto__"||key==="constructor"&&value&&typeof value=="object"&&"prototype"in value){warnKeyDropped(key);return}return value}function warnKeyDropped(key){console.warn(`[destr] Dropping "${key}" key to prevent prototype pollution.`)}function destr(value,options={}){if(typeof value!="string")return value;let _value=value.trim();if(value[0]==='"'&&value[value.length-1]==='"')return _value.slice(1,-1);let _lval=_value.toLowerCase();if(_lval==="true")return!0;if(_lval==="false")return!1;if(_lval!=="undefined"){if(_lval==="null")return null;if(_lval==="nan")return Number.NaN;if(_lval==="infinity")return Number.POSITIVE_INFINITY;if(_lval==="-infinity")return Number.NEGATIVE_INFINITY;if(!JsonSigRx.test(value)){if(options.strict)throw new SyntaxError("[destr] Invalid JSON");return value}try{if(suspectProtoRx.test(value)||suspectConstructorRx.test(value)){if(options.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(value,jsonParseTransform)}return JSON.parse(value)}catch(error){if(options.strict)throw error;return value}}}var r2=String.fromCharCode;var HASH_RE=/#/g,AMPERSAND_RE=/&/g;var EQUAL_RE=/=/g;var PLUS_RE=/\+/g,ENC_CARET_RE=/%5e/gi,ENC_BACKTICK_RE=/%60/gi;var ENC_PIPE_RE=/%7c/gi;var ENC_SPACE_RE=/%20/gi;function encode(text){return encodeURI(""+text).replace(ENC_PIPE_RE,"|")}function encodeQueryValue(input){return encode(typeof input=="string"?input:JSON.stringify(input)).replace(PLUS_RE,"%2B").replace(ENC_SPACE_RE,"+").replace(HASH_RE,"%23").replace(AMPERSAND_RE,"%26").replace(ENC_BACKTICK_RE,"`").replace(ENC_CARET_RE,"^")}function encodeQueryKey(text){return encodeQueryValue(text).replace(EQUAL_RE,"%3D")}function decode(text=""){try{return decodeURIComponent(""+text)}catch{return""+text}}function decodeQueryValue(text){return decode(text.replace(PLUS_RE," "))}function parseQuery(parametersString=""){let object={};parametersString[0]==="?"&&(parametersString=parametersString.slice(1));for(let parameter of parametersString.split("&")){let s2=parameter.match(/([^=]+)=?(.*)/)||[];if(s2.length<2)continue;let key=decode(s2[1]);if(key==="__proto__"||key==="constructor")continue;let value=decodeQueryValue(s2[2]||"");typeof object[key]<"u"?Array.isArray(object[key])?object[key].push(value):object[key]=[object[key],value]:object[key]=value}return object}function encodeQueryItem(key,value){return(typeof value=="number"||typeof value=="boolean")&&(value=String(value)),value?Array.isArray(value)?value.map(_value=>`${encodeQueryKey(key)}=${encodeQueryValue(_value)}`).join("&"):`${encodeQueryKey(key)}=${encodeQueryValue(value)}`:encodeQueryKey(key)}function stringifyQuery(query){return Object.keys(query).filter(k=>query[k]!==void 0).map(k=>encodeQueryItem(k,query[k])).join("&")}var PROTOCOL_STRICT_REGEX=/^\w{2,}:([/\\]{1,2})/,PROTOCOL_REGEX=/^\w{2,}:([/\\]{2})?/,PROTOCOL_RELATIVE_REGEX=/^([/\\]\s*){2,}[^/\\]/;function hasProtocol(inputString,opts={}){return typeof opts=="boolean"&&(opts={acceptRelative:opts}),opts.strict?PROTOCOL_STRICT_REGEX.test(inputString):PROTOCOL_REGEX.test(inputString)||(opts.acceptRelative?PROTOCOL_RELATIVE_REGEX.test(inputString):!1)}var TRAILING_SLASH_RE=/\/$|\/\?/;function hasTrailingSlash(input="",queryParameters=!1){return queryParameters?TRAILING_SLASH_RE.test(input):input.endsWith("/")}function withoutTrailingSlash(input="",queryParameters=!1){if(!queryParameters)return(hasTrailingSlash(input)?input.slice(0,-1):input)||"/";if(!hasTrailingSlash(input,!0))return input||"/";let[s0,...s2]=input.split("?");return(s0.slice(0,-1)||"/")+(s2.length>0?`?${s2.join("?")}`:"")}function withTrailingSlash(input="",queryParameters=!1){if(!queryParameters)return input.endsWith("/")?input:input+"/";if(hasTrailingSlash(input,!0))return input||"/";let[s0,...s2]=input.split("?");return s0+"/"+(s2.length>0?`?${s2.join("?")}`:"")}function hasLeadingSlash(input=""){return input.startsWith("/")}function withoutLeadingSlash(input=""){return(hasLeadingSlash(input)?input.slice(1):input)||"/"}function withBase(input,base){if(isEmptyURL(base)||hasProtocol(input))return input;let _base=withoutTrailingSlash(base);return input.startsWith(_base)?input:joinURL(_base,input)}function withQuery(input,query){let parsed=parseURL(input),mergedQuery={...parseQuery(parsed.search),...query};return parsed.search=stringifyQuery(mergedQuery),stringifyParsedURL(parsed)}function isEmptyURL(url){return!url||url==="/"}function isNonEmptyURL(url){return url&&url!=="/"}function joinURL(base,...input){let url=base||"";for(let index of input.filter(url2=>isNonEmptyURL(url2)))url=url?withTrailingSlash(url)+withoutLeadingSlash(index):index;return url}function parseURL(input="",defaultProto){if(!hasProtocol(input,{acceptRelative:!0}))return defaultProto?parseURL(defaultProto+input):parsePath(input);let[protocol="",auth,hostAndPath=""]=(input.replace(/\\/g,"/").match(/([^/:]+:)?\/\/([^/@]+@)?(.*)/)||[]).splice(1),[host="",path=""]=(hostAndPath.match(/([^#/?]*)(.*)?/)||[]).splice(1),{pathname,search,hash}=parsePath(path.replace(/\/(?=[A-Za-z]:)/,""));return{protocol,auth:auth?auth.slice(0,Math.max(0,auth.length-1)):"",host,pathname,search,hash}}function parsePath(input=""){let[pathname="",search="",hash=""]=(input.match(/([^#?]*)(\?[^#]*)?(#.*)?/)||[]).splice(1);return{pathname,search,hash}}function stringifyParsedURL(parsed){let fullpath=parsed.pathname+(parsed.search?(parsed.search.startsWith("?")?"":"?")+parsed.search:"")+parsed.hash;return parsed.protocol?parsed.protocol+"//"+(parsed.auth?parsed.auth+"@":"")+parsed.host+fullpath:fullpath}var FetchError2=class extends Error{constructor(){super(...arguments),this.name="FetchError"}};function createFetchError(request,error,response){let message="";error&&(message=error.message),request&&response?message=`${message} (${response.status} ${response.statusText} (${request.toString()}))`:request&&(message=`${message} (${request.toString()})`);let fetchError=new FetchError2(message);return Object.defineProperty(fetchError,"request",{get(){return request}}),Object.defineProperty(fetchError,"response",{get(){return response}}),Object.defineProperty(fetchError,"data",{get(){return response&&response._data}}),Object.defineProperty(fetchError,"status",{get(){return response&&response.status}}),Object.defineProperty(fetchError,"statusText",{get(){return response&&response.statusText}}),Object.defineProperty(fetchError,"statusCode",{get(){return response&&response.status}}),Object.defineProperty(fetchError,"statusMessage",{get(){return response&&response.statusText}}),fetchError}var payloadMethods=new Set(Object.freeze(["PATCH","POST","PUT","DELETE"]));function isPayloadMethod(method="GET"){return payloadMethods.has(method.toUpperCase())}function isJSONSerializable(value){if(value===void 0)return!1;let t2=typeof value;return t2==="string"||t2==="number"||t2==="boolean"||t2===null?!0:t2!=="object"?!1:Array.isArray(value)?!0:value.constructor&&value.constructor.name==="Object"||typeof value.toJSON=="function"}var textTypes=new Set(["image/svg","application/xml","application/xhtml","application/html"]),JSON_RE=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function detectResponseType(_contentType=""){if(!_contentType)return"json";let contentType=_contentType.split(";").shift()||"";return JSON_RE.test(contentType)?"json":textTypes.has(contentType)||contentType.startsWith("text/")?"text":"blob"}function mergeFetchOptions(input,defaults,Headers4=globalThis.Headers){let merged={...defaults,...input};if(defaults?.params&&input?.params&&(merged.params={...defaults?.params,...input?.params}),defaults?.query&&input?.query&&(merged.query={...defaults?.query,...input?.query}),defaults?.headers&&input?.headers){merged.headers=new Headers4(defaults?.headers||{});for(let[key,value]of new Headers4(input?.headers||{}))merged.headers.set(key,value)}return merged}var retryStatusCodes=new Set([408,409,425,429,500,502,503,504]);function createFetch(globalOptions){let{fetch:fetch4,Headers:Headers4}=globalOptions;function onError(context){let isAbort=context.error&&context.error.name==="AbortError"||!1;if(context.options.retry!==!1&&!isAbort){let retries;typeof context.options.retry=="number"?retries=context.options.retry:retries=isPayloadMethod(context.options.method)?0:1;let responseCode=context.response&&context.response.status||500;if(retries>0&&retryStatusCodes.has(responseCode))return $fetchRaw(context.request,{...context.options,retry:retries-1})}let error=createFetchError(context.request,context.error,context.response);throw Error.captureStackTrace&&Error.captureStackTrace(error,$fetchRaw),error}let $fetchRaw=async function(_request,_options={}){let context={request:_request,options:mergeFetchOptions(_options,globalOptions.defaults,Headers4),response:void 0,error:void 0};context.options.onRequest&&await context.options.onRequest(context),typeof context.request=="string"&&(context.options.baseURL&&(context.request=withBase(context.request,context.options.baseURL)),(context.options.query||context.options.params)&&(context.request=withQuery(context.request,{...context.options.params,...context.options.query})),context.options.body&&isPayloadMethod(context.options.method)&&isJSONSerializable(context.options.body)&&(context.options.body=typeof context.options.body=="string"?context.options.body:JSON.stringify(context.options.body),context.options.headers=new Headers4(context.options.headers||{}),context.options.headers.has("content-type")||context.options.headers.set("content-type","application/json"),context.options.headers.has("accept")||context.options.headers.set("accept","application/json")));try{context.response=await fetch4(context.request,context.options)}catch(error){return context.error=error,context.options.onRequestError&&await context.options.onRequestError(context),await onError(context)}let responseType=(context.options.parseResponse?"json":context.options.responseType)||detectResponseType(context.response.headers.get("content-type")||"");if(responseType==="json"){let data=await context.response.text(),parseFunction=context.options.parseResponse||destr;context.response._data=parseFunction(data)}else responseType==="stream"?context.response._data=context.response.body:context.response._data=await context.response[responseType]();return context.options.onResponse&&await context.options.onResponse(context),!context.options.ignoreResponseError&&context.response.status>=400&&context.response.status<600?(context.options.onResponseError&&await context.options.onResponseError(context),await onError(context)):context.response},$fetch=async function(request,options){return(await $fetchRaw(request,options))._data};return $fetch.raw=$fetchRaw,$fetch.native=fetch4,$fetch.create=(defaultOptions={})=>createFetch({...globalOptions,defaults:{...globalOptions.defaults,...defaultOptions}}),$fetch}function createNodeFetch(){if(!JSON.parse(process.env.FETCH_KEEP_ALIVE||"false"))return fetch2;let agentOptions={keepAlive:!0},httpAgent=new import_node_http2.default.Agent(agentOptions),httpsAgent=new import_node_https2.default.Agent(agentOptions),nodeFetchOptions={agent(parsedURL){return parsedURL.protocol==="http:"?httpAgent:httpsAgent}};return function(input,init){return fetch2(input,{...nodeFetchOptions,...init})}}var fetch3=globalThis.fetch||createNodeFetch(),Headers3=globalThis.Headers||Headers2,ofetch=createFetch({fetch:fetch3,Headers:Headers3});var import_promises=require("node:fs/promises"),import_node_os=require("node:os"),import_node_path=require("node:path"),install=async()=>{core.startGroup("Install attic"),core.info("Installing attic");let installScript=await fetch3("https://raw.githubusercontent.com/zhaofengli/attic/main/.github/install-attic-ci.sh").then(r3=>(r3.ok||(core.setFailed(`Action failed with error: ${r3.statusText}`),core.endGroup(),process.exit(1)),r3.text()));try{let installScriptPath=(0,import_node_path.join)((0,import_node_os.tmpdir)(),"install-attic-ci.sh");await(0,import_promises.writeFile)(installScriptPath,installScript),core.info("Running install script"),await(0,import_exec.exec)("bash",[installScriptPath])}catch(e2){core.setFailed(`Action failed with error: ${e2}`)}core.endGroup()};var core2=__toESM(require_core()),import_exec3=__toESM(require_exec());var import_exec2=__toESM(require_exec()),import_node_stream2=require("node:stream"),streamToString=stream=>{let chunks=[];return new Promise((resolve,reject)=>{stream.on("data",chunk=>chunks.push(Buffer.from(chunk))),stream.on("error",err=>reject(err)),stream.on("end",()=>resolve(Buffer.concat(chunks).toString("utf8")))})},getStorePaths=async()=>{let outStream=new import_node_stream2.Writable;return await(0,import_exec2.exec)("nix",["path-info","--all"],{outStream}),await streamToString(outStream).then(res=>res.split(` -`)).then(paths2=>paths2.filter(Boolean))};var configure=async()=>{core2.startGroup("Configure attic");try{let endpoint=core2.getInput("endpoint"),cache=core2.getInput("cache"),token=core2.getInput("token");core2.info("Logging in to attic cache"),await(0,import_exec3.exec)("attic",["login","--set-default",cache,endpoint,token]),core2.info("Collecting store paths before build");let paths=await getStorePaths();core2.saveState("initial-paths",JSON.stringify(paths))}catch(e2){core2.setFailed(`Action failed with error: ${e2}`)}core2.endGroup()};var main=async()=>{await install(),await configure()};main(); +`)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),x=(n,a,e2)=>{if(a.lengthtypeof o[m2]!="function")}append(...a){x("append",arguments,2),this.#d.push(f2(...a))}delete(a){x("delete",arguments,1),a+="",this.#d=this.#d.filter(([b])=>b!==a)}get(a){x("get",arguments,1),a+="";for(var b=this.#d,l=b.length,c=0;cc[0]===a&&b.push(c[1])),b}has(a){return x("has",arguments,1),a+="",this.#d.some(b=>b[0]===a)}forEach(a,b){x("forEach",arguments,1);for(var[c,d]of this)a.call(b,d,c,this)}set(...a){x("set",arguments,2);var b=[],c=!0;a=f2(...a),this.#d.forEach(d=>{d[0]===a[0]?c&&(c=!b.push(a)):b.push(d)}),c&&b.push(a),this.#d=b}*entries(){yield*this.#d}*keys(){for(var[a]of this)yield a}*values(){for(var[,a]of this)yield a}};FetchBaseError=class extends Error{constructor(message,type){super(message),Error.captureStackTrace(this,this.constructor),this.type=type}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}},FetchError=class extends FetchBaseError{constructor(message,type,systemError){super(message,type),systemError&&(this.code=this.errno=systemError.code,this.erroredSysCall=systemError.syscall)}},NAME=Symbol.toStringTag,isURLSearchParameters=object=>typeof object=="object"&&typeof object.append=="function"&&typeof object.delete=="function"&&typeof object.get=="function"&&typeof object.getAll=="function"&&typeof object.has=="function"&&typeof object.set=="function"&&typeof object.sort=="function"&&object[NAME]==="URLSearchParams",isBlob=object=>object&&typeof object=="object"&&typeof object.arrayBuffer=="function"&&typeof object.type=="string"&&typeof object.stream=="function"&&typeof object.constructor=="function"&&/^(Blob|File)$/.test(object[NAME]),isAbortSignal=object=>typeof object=="object"&&(object[NAME]==="AbortSignal"||object[NAME]==="EventTarget"),isDomainOrSubdomain=(destination,original)=>{let orig=new URL(original).hostname,dest=new URL(destination).hostname;return orig===dest||orig.endsWith(`.${dest}`)},isSameProtocol=(destination,original)=>{let orig=new URL(original).protocol,dest=new URL(destination).protocol;return orig===dest},pipeline=(0,import_node_util.promisify)(import_node_stream.default.pipeline),INTERNALS$2=Symbol("Body internals"),Body=class{constructor(body,{size=0}={}){let boundary=null;body===null?body=null:isURLSearchParameters(body)?body=import_node_buffer.Buffer.from(body.toString()):isBlob(body)||import_node_buffer.Buffer.isBuffer(body)||(import_node_util.types.isAnyArrayBuffer(body)?body=import_node_buffer.Buffer.from(body):ArrayBuffer.isView(body)?body=import_node_buffer.Buffer.from(body.buffer,body.byteOffset,body.byteLength):body instanceof import_node_stream.default||(body instanceof FormData?(body=formDataToBlob(body),boundary=body.type.split("=")[1]):body=import_node_buffer.Buffer.from(String(body))));let stream=body;import_node_buffer.Buffer.isBuffer(body)?stream=import_node_stream.default.Readable.from(body):isBlob(body)&&(stream=import_node_stream.default.Readable.from(body.stream())),this[INTERNALS$2]={body,stream,boundary,disturbed:!1,error:null},this.size=size,body instanceof import_node_stream.default&&body.on("error",error_=>{let error=error_ instanceof FetchBaseError?error_:new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`,"system",error_);this[INTERNALS$2].error=error})}get body(){return this[INTERNALS$2].stream}get bodyUsed(){return this[INTERNALS$2].disturbed}async arrayBuffer(){let{buffer,byteOffset,byteLength}=await consumeBody(this);return buffer.slice(byteOffset,byteOffset+byteLength)}async formData(){let ct=this.headers.get("content-type");if(ct.startsWith("application/x-www-form-urlencoded")){let formData=new FormData,parameters=new URLSearchParams(await this.text());for(let[name,value]of parameters)formData.append(name,value);return formData}let{toFormData:toFormData2}=await Promise.resolve().then(()=>(init_multipart_parser(),multipart_parser_exports));return toFormData2(this.body,ct)}async blob(){let ct=this.headers&&this.headers.get("content-type")||this[INTERNALS$2].body&&this[INTERNALS$2].body.type||"",buf=await this.arrayBuffer();return new _Blob$1([buf],{type:ct})}async json(){let text=await this.text();return JSON.parse(text)}async text(){let buffer=await consumeBody(this);return new TextDecoder().decode(buffer)}buffer(){return consumeBody(this)}};Body.prototype.buffer=(0,import_node_util.deprecate)(Body.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(Body.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:(0,import_node_util.deprecate)(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});clone=(instance,highWaterMark)=>{let p1,p2,{body}=instance[INTERNALS$2];if(instance.bodyUsed)throw new Error("cannot clone body after it is used");return body instanceof import_node_stream.default&&typeof body.getBoundary!="function"&&(p1=new import_node_stream.PassThrough({highWaterMark}),p2=new import_node_stream.PassThrough({highWaterMark}),body.pipe(p1),body.pipe(p2),instance[INTERNALS$2].stream=p1,body=p2),body},getNonSpecFormDataBoundary=(0,import_node_util.deprecate)(body=>body.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),extractContentType=(body,request)=>body===null?null:typeof body=="string"?"text/plain;charset=UTF-8":isURLSearchParameters(body)?"application/x-www-form-urlencoded;charset=UTF-8":isBlob(body)?body.type||null:import_node_buffer.Buffer.isBuffer(body)||import_node_util.types.isAnyArrayBuffer(body)||ArrayBuffer.isView(body)?null:body instanceof FormData?`multipart/form-data; boundary=${request[INTERNALS$2].boundary}`:body&&typeof body.getBoundary=="function"?`multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`:body instanceof import_node_stream.default?null:"text/plain;charset=UTF-8",getTotalBytes=request=>{let{body}=request[INTERNALS$2];return body===null?0:isBlob(body)?body.size:import_node_buffer.Buffer.isBuffer(body)?body.length:body&&typeof body.getLengthSync=="function"&&body.hasKnownLength&&body.hasKnownLength()?body.getLengthSync():null},writeToStream=async(dest,{body})=>{body===null?dest.end():await pipeline(body,dest)},validateHeaderName=typeof import_node_http.default.validateHeaderName=="function"?import_node_http.default.validateHeaderName:name=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)){let error=new TypeError(`Header name must be a valid HTTP token [${name}]`);throw Object.defineProperty(error,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),error}},validateHeaderValue=typeof import_node_http.default.validateHeaderValue=="function"?import_node_http.default.validateHeaderValue:(name,value)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)){let error=new TypeError(`Invalid character in header content ["${name}"]`);throw Object.defineProperty(error,"code",{value:"ERR_INVALID_CHAR"}),error}},Headers=class _Headers extends URLSearchParams{constructor(init){let result=[];if(init instanceof _Headers){let raw=init.raw();for(let[name,values]of Object.entries(raw))result.push(...values.map(value=>[name,value]))}else if(init!=null)if(typeof init=="object"&&!import_node_util.types.isBoxedPrimitive(init)){let method=init[Symbol.iterator];if(method==null)result.push(...Object.entries(init));else{if(typeof method!="function")throw new TypeError("Header pairs must be iterable");result=[...init].map(pair=>{if(typeof pair!="object"||import_node_util.types.isBoxedPrimitive(pair))throw new TypeError("Each header pair must be an iterable object");return[...pair]}).map(pair=>{if(pair.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return[...pair]})}}else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence> or record)");return result=result.length>0?result.map(([name,value])=>(validateHeaderName(name),validateHeaderValue(name,String(value)),[String(name).toLowerCase(),String(value)])):void 0,super(result),new Proxy(this,{get(target,p,receiver){switch(p){case"append":case"set":return(name,value)=>(validateHeaderName(name),validateHeaderValue(name,String(value)),URLSearchParams.prototype[p].call(target,String(name).toLowerCase(),String(value)));case"delete":case"has":case"getAll":return name=>(validateHeaderName(name),URLSearchParams.prototype[p].call(target,String(name).toLowerCase()));case"keys":return()=>(target.sort(),new Set(URLSearchParams.prototype.keys.call(target)).keys());default:return Reflect.get(target,p,receiver)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(name){let values=this.getAll(name);if(values.length===0)return null;let value=values.join(", ");return/^content-encoding$/i.test(name)&&(value=value.toLowerCase()),value}forEach(callback,thisArg=void 0){for(let name of this.keys())Reflect.apply(callback,thisArg,[this.get(name),name,this])}*values(){for(let name of this.keys())yield this.get(name)}*entries(){for(let name of this.keys())yield[name,this.get(name)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((result,key)=>(result[key]=this.getAll(key),result),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((result,key)=>{let values=this.getAll(key);return key==="host"?result[key]=values[0]:result[key]=values.length>1?values:values[0],result},{})}};Object.defineProperties(Headers.prototype,["get","entries","forEach","values"].reduce((result,property)=>(result[property]={enumerable:!0},result),{}));redirectStatus=new Set([301,302,303,307,308]),isRedirect=code=>redirectStatus.has(code),INTERNALS$1=Symbol("Response internals"),Response=class _Response extends Body{constructor(body=null,options={}){super(body,options);let status=options.status!=null?options.status:200,headers=new Headers(options.headers);if(body!==null&&!headers.has("Content-Type")){let contentType=extractContentType(body,this);contentType&&headers.append("Content-Type",contentType)}this[INTERNALS$1]={type:"default",url:options.url,status,statusText:options.statusText||"",headers,counter:options.counter,highWaterMark:options.highWaterMark}}get type(){return this[INTERNALS$1].type}get url(){return this[INTERNALS$1].url||""}get status(){return this[INTERNALS$1].status}get ok(){return this[INTERNALS$1].status>=200&&this[INTERNALS$1].status<300}get redirected(){return this[INTERNALS$1].counter>0}get statusText(){return this[INTERNALS$1].statusText}get headers(){return this[INTERNALS$1].headers}get highWaterMark(){return this[INTERNALS$1].highWaterMark}clone(){return new _Response(clone(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(url,status=302){if(!isRedirect(status))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new _Response(null,{headers:{location:new URL(url).toString()},status})}static error(){let response=new _Response(null,{status:0,statusText:""});return response[INTERNALS$1].type="error",response}static json(data=void 0,init={}){let body=JSON.stringify(data);if(body===void 0)throw new TypeError("data is not JSON serializable");let headers=new Headers(init&&init.headers);return headers.has("content-type")||headers.set("content-type","application/json"),new _Response(body,{...init,headers})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(Response.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});getSearch=parsedURL=>{if(parsedURL.search)return parsedURL.search;let lastOffset=parsedURL.href.length-1,hash=parsedURL.hash||(parsedURL.href[lastOffset]==="#"?"#":"");return parsedURL.href[lastOffset-hash.length]==="?"?"?":""};ReferrerPolicy=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),DEFAULT_REFERRER_POLICY="strict-origin-when-cross-origin";INTERNALS=Symbol("Request internals"),isRequest=object=>typeof object=="object"&&typeof object[INTERNALS]=="object",doBadDataWarn=(0,import_node_util.deprecate)(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Request=class _Request extends Body{constructor(input,init={}){let parsedURL;if(isRequest(input)?parsedURL=new URL(input.url):(parsedURL=new URL(input),input={}),parsedURL.username!==""||parsedURL.password!=="")throw new TypeError(`${parsedURL} is an url with embedded credentials.`);let method=init.method||input.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(method)&&(method=method.toUpperCase()),!isRequest(init)&&"data"in init&&doBadDataWarn(),(init.body!=null||isRequest(input)&&input.body!==null)&&(method==="GET"||method==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let inputBody=init.body?init.body:isRequest(input)&&input.body!==null?clone(input):null;super(inputBody,{size:init.size||input.size||0});let headers=new Headers(init.headers||input.headers||{});if(inputBody!==null&&!headers.has("Content-Type")){let contentType=extractContentType(inputBody,this);contentType&&headers.set("Content-Type",contentType)}let signal=isRequest(input)?input.signal:null;if("signal"in init&&(signal=init.signal),signal!=null&&!isAbortSignal(signal))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let referrer=init.referrer==null?input.referrer:init.referrer;if(referrer==="")referrer="no-referrer";else if(referrer){let parsedReferrer=new URL(referrer);referrer=/^about:(\/\/)?client$/.test(parsedReferrer)?"client":parsedReferrer}else referrer=void 0;this[INTERNALS]={method,redirect:init.redirect||input.redirect||"follow",headers,parsedURL,signal,referrer},this.follow=init.follow===void 0?input.follow===void 0?20:input.follow:init.follow,this.compress=init.compress===void 0?input.compress===void 0?!0:input.compress:init.compress,this.counter=init.counter||input.counter||0,this.agent=init.agent||input.agent,this.highWaterMark=init.highWaterMark||input.highWaterMark||16384,this.insecureHTTPParser=init.insecureHTTPParser||input.insecureHTTPParser||!1,this.referrerPolicy=init.referrerPolicy||input.referrerPolicy||""}get method(){return this[INTERNALS].method}get url(){return(0,import_node_url.format)(this[INTERNALS].parsedURL)}get headers(){return this[INTERNALS].headers}get redirect(){return this[INTERNALS].redirect}get signal(){return this[INTERNALS].signal}get referrer(){if(this[INTERNALS].referrer==="no-referrer")return"";if(this[INTERNALS].referrer==="client")return"about:client";if(this[INTERNALS].referrer)return this[INTERNALS].referrer.toString()}get referrerPolicy(){return this[INTERNALS].referrerPolicy}set referrerPolicy(referrerPolicy){this[INTERNALS].referrerPolicy=validateReferrerPolicy(referrerPolicy)}clone(){return new _Request(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(Request.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});getNodeRequestOptions=request=>{let{parsedURL}=request[INTERNALS],headers=new Headers(request[INTERNALS].headers);headers.has("Accept")||headers.set("Accept","*/*");let contentLengthValue=null;if(request.body===null&&/^(post|put)$/i.test(request.method)&&(contentLengthValue="0"),request.body!==null){let totalBytes=getTotalBytes(request);typeof totalBytes=="number"&&!Number.isNaN(totalBytes)&&(contentLengthValue=String(totalBytes))}contentLengthValue&&headers.set("Content-Length",contentLengthValue),request.referrerPolicy===""&&(request.referrerPolicy=DEFAULT_REFERRER_POLICY),request.referrer&&request.referrer!=="no-referrer"?request[INTERNALS].referrer=determineRequestsReferrer(request):request[INTERNALS].referrer="no-referrer",request[INTERNALS].referrer instanceof URL&&headers.set("Referer",request.referrer),headers.has("User-Agent")||headers.set("User-Agent","node-fetch"),request.compress&&!headers.has("Accept-Encoding")&&headers.set("Accept-Encoding","gzip, deflate, br");let{agent}=request;typeof agent=="function"&&(agent=agent(parsedURL)),!headers.has("Connection")&&!agent&&headers.set("Connection","close");let search=getSearch(parsedURL),options={path:parsedURL.pathname+search,method:request.method,headers:headers[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:request.insecureHTTPParser,agent};return{parsedURL,options}},AbortError=class extends FetchBaseError{constructor(message,type="aborted"){super(message,type)}};if(!globalThis.DOMException)try{let{MessageChannel}=require("worker_threads"),port=new MessageChannel().port1,ab=new ArrayBuffer;port.postMessage(ab,[ab,ab])}catch(err){err.constructor.name==="DOMException"&&(globalThis.DOMException=err.constructor)}nodeDomexception=globalThis.DOMException,DOMException$1=getDefaultExportFromCjs(nodeDomexception),supportedSchemas=new Set(["data:","http:","https:"]);privateData=new WeakMap,wrappers=new WeakMap;Event.prototype={get type(){return pd(this).event.type},get target(){return pd(this).eventTarget},get currentTarget(){return pd(this).currentTarget},composedPath(){let currentTarget=pd(this).currentTarget;return currentTarget==null?[]:[currentTarget]},get NONE(){return 0},get CAPTURING_PHASE(){return 1},get AT_TARGET(){return 2},get BUBBLING_PHASE(){return 3},get eventPhase(){return pd(this).eventPhase},stopPropagation(){let data=pd(this);data.stopped=!0,typeof data.event.stopPropagation=="function"&&data.event.stopPropagation()},stopImmediatePropagation(){let data=pd(this);data.stopped=!0,data.immediateStopped=!0,typeof data.event.stopImmediatePropagation=="function"&&data.event.stopImmediatePropagation()},get bubbles(){return!!pd(this).event.bubbles},get cancelable(){return!!pd(this).event.cancelable},preventDefault(){setCancelFlag(pd(this))},get defaultPrevented(){return pd(this).canceled},get composed(){return!!pd(this).event.composed},get timeStamp(){return pd(this).timeStamp},get srcElement(){return pd(this).eventTarget},get cancelBubble(){return pd(this).stopped},set cancelBubble(value){if(!value)return;let data=pd(this);data.stopped=!0,typeof data.event.cancelBubble=="boolean"&&(data.event.cancelBubble=!0)},get returnValue(){return!pd(this).canceled},set returnValue(value){value||setCancelFlag(pd(this))},initEvent(){}};Object.defineProperty(Event.prototype,"constructor",{value:Event,configurable:!0,writable:!0});typeof window<"u"&&typeof window.Event<"u"&&(Object.setPrototypeOf(Event.prototype,window.Event.prototype),wrappers.set(window.Event.prototype,Event));listenersMap=new WeakMap,CAPTURE=1,BUBBLE=2,ATTRIBUTE=3;EventTarget.prototype={addEventListener(eventName,listener,options){if(listener==null)return;if(typeof listener!="function"&&!isObject(listener))throw new TypeError("'listener' should be a function or an object.");let listeners=getListeners(this),optionsIsObj=isObject(options),listenerType=(optionsIsObj?!!options.capture:!!options)?CAPTURE:BUBBLE,newNode={listener,listenerType,passive:optionsIsObj&&!!options.passive,once:optionsIsObj&&!!options.once,next:null},node=listeners.get(eventName);if(node===void 0){listeners.set(eventName,newNode);return}let prev=null;for(;node!=null;){if(node.listener===listener&&node.listenerType===listenerType)return;prev=node,node=node.next}prev.next=newNode},removeEventListener(eventName,listener,options){if(listener==null)return;let listeners=getListeners(this),listenerType=(isObject(options)?!!options.capture:!!options)?CAPTURE:BUBBLE,prev=null,node=listeners.get(eventName);for(;node!=null;){if(node.listener===listener&&node.listenerType===listenerType){prev!==null?prev.next=node.next:node.next!==null?listeners.set(eventName,node.next):listeners.delete(eventName);return}prev=node,node=node.next}},dispatchEvent(event){if(event==null||typeof event.type!="string")throw new TypeError('"event.type" should be a string.');let listeners=getListeners(this),eventName=event.type,node=listeners.get(eventName);if(node==null)return!0;let wrappedEvent=wrapEvent(this,event),prev=null;for(;node!=null;){if(node.once?prev!==null?prev.next=node.next:node.next!==null?listeners.set(eventName,node.next):listeners.delete(eventName):prev=node,setPassiveListener(wrappedEvent,node.passive?node.listener:null),typeof node.listener=="function")try{node.listener.call(this,wrappedEvent)}catch(err){typeof console<"u"&&typeof console.error=="function"&&console.error(err)}else node.listenerType!==ATTRIBUTE&&typeof node.listener.handleEvent=="function"&&node.listener.handleEvent(wrappedEvent);if(isStopped(wrappedEvent))break;node=node.next}return setPassiveListener(wrappedEvent,null),setEventPhase(wrappedEvent,0),setCurrentTarget(wrappedEvent,null),!wrappedEvent.defaultPrevented}};Object.defineProperty(EventTarget.prototype,"constructor",{value:EventTarget,configurable:!0,writable:!0});typeof window<"u"&&typeof window.EventTarget<"u"&&Object.setPrototypeOf(EventTarget.prototype,window.EventTarget.prototype);AbortSignal=class extends EventTarget{constructor(){throw super(),new TypeError("AbortSignal cannot be constructed directly")}get aborted(){let aborted=abortedFlags.get(this);if(typeof aborted!="boolean")throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this===null?"null":typeof this}`);return aborted}};defineEventAttribute(AbortSignal.prototype,"abort");abortedFlags=new WeakMap;Object.defineProperties(AbortSignal.prototype,{aborted:{enumerable:!0}});typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(AbortSignal.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortSignal"});AbortController$1=class{constructor(){signals.set(this,createAbortSignal())}get signal(){return getSignal(this)}abort(){abortSignal(getSignal(this))}},signals=new WeakMap;Object.defineProperties(AbortController$1.prototype,{signal:{enumerable:!0},abort:{enumerable:!0}});typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(AbortController$1.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortController"})}});var core=__toESM(require_core()),import_exec=__toESM(require_exec());var import_node_http2=__toESM(require("node:http"),1),import_node_https2=__toESM(require("node:https"),1);init_node_fetch_native_d7878b77();init_node_fetch_native_d7878b77();var import_node_fs=require("node:fs");init_node_fetch_native_d7878b77();var{stat}=import_node_fs.promises;var BlobDataItem=class _BlobDataItem{#path;#start;constructor(options){this.#path=options.path,this.#start=options.start,this.size=options.size,this.lastModified=options.lastModified}slice(start,end){return new _BlobDataItem({path:this.#path,lastModified:this.lastModified,size:end-start,start:this.#start+start})}async*stream(){let{mtimeMs}=await stat(this.#path);if(mtimeMs>this.lastModified)throw new DOMException$1("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.","NotReadableError");yield*(0,import_node_fs.createReadStream)(this.#path,{start:this.#start,end:this.#start+this.size-1})}get[Symbol.toStringTag](){return"Blob"}};var _forceNodeFetch=typeof process!==void 0&&typeof process.env!==void 0&&process.env.FORCE_NODE_FETCH;function _getFetch(){return!_forceNodeFetch&&globalThis.fetch?globalThis.fetch:fetch}var fetch2=_getFetch(),Blob3=!_forceNodeFetch&&globalThis.Blob||_Blob$1,File3=!_forceNodeFetch&&globalThis.File||File$1,FormData3=!_forceNodeFetch&&globalThis.FormData||FormData,Headers2=!_forceNodeFetch&&globalThis.Headers||Headers,Request2=!_forceNodeFetch&&globalThis.Request||Request,Response2=!_forceNodeFetch&&globalThis.Response||Response,AbortController3=!_forceNodeFetch&&globalThis.AbortController||AbortController$1;var suspectProtoRx=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,suspectConstructorRx=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,JsonSigRx=/^\s*["[{]|^\s*-?\d[\d.]{0,14}\s*$/;function jsonParseTransform(key,value){if(key==="__proto__"||key==="constructor"&&value&&typeof value=="object"&&"prototype"in value){warnKeyDropped(key);return}return value}function warnKeyDropped(key){console.warn(`[destr] Dropping "${key}" key to prevent prototype pollution.`)}function destr(value,options={}){if(typeof value!="string")return value;let _value=value.trim();if(value[0]==='"'&&value[value.length-1]==='"')return _value.slice(1,-1);let _lval=_value.toLowerCase();if(_lval==="true")return!0;if(_lval==="false")return!1;if(_lval!=="undefined"){if(_lval==="null")return null;if(_lval==="nan")return Number.NaN;if(_lval==="infinity")return Number.POSITIVE_INFINITY;if(_lval==="-infinity")return Number.NEGATIVE_INFINITY;if(!JsonSigRx.test(value)){if(options.strict)throw new SyntaxError("[destr] Invalid JSON");return value}try{if(suspectProtoRx.test(value)||suspectConstructorRx.test(value)){if(options.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(value,jsonParseTransform)}return JSON.parse(value)}catch(error){if(options.strict)throw error;return value}}}var r2=String.fromCharCode;var HASH_RE=/#/g,AMPERSAND_RE=/&/g;var EQUAL_RE=/=/g;var PLUS_RE=/\+/g,ENC_CARET_RE=/%5e/gi,ENC_BACKTICK_RE=/%60/gi;var ENC_PIPE_RE=/%7c/gi;var ENC_SPACE_RE=/%20/gi;function encode(text){return encodeURI(""+text).replace(ENC_PIPE_RE,"|")}function encodeQueryValue(input){return encode(typeof input=="string"?input:JSON.stringify(input)).replace(PLUS_RE,"%2B").replace(ENC_SPACE_RE,"+").replace(HASH_RE,"%23").replace(AMPERSAND_RE,"%26").replace(ENC_BACKTICK_RE,"`").replace(ENC_CARET_RE,"^")}function encodeQueryKey(text){return encodeQueryValue(text).replace(EQUAL_RE,"%3D")}function decode(text=""){try{return decodeURIComponent(""+text)}catch{return""+text}}function decodeQueryValue(text){return decode(text.replace(PLUS_RE," "))}function parseQuery(parametersString=""){let object={};parametersString[0]==="?"&&(parametersString=parametersString.slice(1));for(let parameter of parametersString.split("&")){let s2=parameter.match(/([^=]+)=?(.*)/)||[];if(s2.length<2)continue;let key=decode(s2[1]);if(key==="__proto__"||key==="constructor")continue;let value=decodeQueryValue(s2[2]||"");typeof object[key]<"u"?Array.isArray(object[key])?object[key].push(value):object[key]=[object[key],value]:object[key]=value}return object}function encodeQueryItem(key,value){return(typeof value=="number"||typeof value=="boolean")&&(value=String(value)),value?Array.isArray(value)?value.map(_value=>`${encodeQueryKey(key)}=${encodeQueryValue(_value)}`).join("&"):`${encodeQueryKey(key)}=${encodeQueryValue(value)}`:encodeQueryKey(key)}function stringifyQuery(query){return Object.keys(query).filter(k=>query[k]!==void 0).map(k=>encodeQueryItem(k,query[k])).join("&")}var PROTOCOL_STRICT_REGEX=/^\w{2,}:([/\\]{1,2})/,PROTOCOL_REGEX=/^\w{2,}:([/\\]{2})?/,PROTOCOL_RELATIVE_REGEX=/^([/\\]\s*){2,}[^/\\]/;function hasProtocol(inputString,opts={}){return typeof opts=="boolean"&&(opts={acceptRelative:opts}),opts.strict?PROTOCOL_STRICT_REGEX.test(inputString):PROTOCOL_REGEX.test(inputString)||(opts.acceptRelative?PROTOCOL_RELATIVE_REGEX.test(inputString):!1)}var TRAILING_SLASH_RE=/\/$|\/\?/;function hasTrailingSlash(input="",queryParameters=!1){return queryParameters?TRAILING_SLASH_RE.test(input):input.endsWith("/")}function withoutTrailingSlash(input="",queryParameters=!1){if(!queryParameters)return(hasTrailingSlash(input)?input.slice(0,-1):input)||"/";if(!hasTrailingSlash(input,!0))return input||"/";let[s0,...s2]=input.split("?");return(s0.slice(0,-1)||"/")+(s2.length>0?`?${s2.join("?")}`:"")}function withTrailingSlash(input="",queryParameters=!1){if(!queryParameters)return input.endsWith("/")?input:input+"/";if(hasTrailingSlash(input,!0))return input||"/";let[s0,...s2]=input.split("?");return s0+"/"+(s2.length>0?`?${s2.join("?")}`:"")}function hasLeadingSlash(input=""){return input.startsWith("/")}function withoutLeadingSlash(input=""){return(hasLeadingSlash(input)?input.slice(1):input)||"/"}function withBase(input,base){if(isEmptyURL(base)||hasProtocol(input))return input;let _base=withoutTrailingSlash(base);return input.startsWith(_base)?input:joinURL(_base,input)}function withQuery(input,query){let parsed=parseURL(input),mergedQuery={...parseQuery(parsed.search),...query};return parsed.search=stringifyQuery(mergedQuery),stringifyParsedURL(parsed)}function isEmptyURL(url){return!url||url==="/"}function isNonEmptyURL(url){return url&&url!=="/"}function joinURL(base,...input){let url=base||"";for(let index of input.filter(url2=>isNonEmptyURL(url2)))url=url?withTrailingSlash(url)+withoutLeadingSlash(index):index;return url}function parseURL(input="",defaultProto){if(!hasProtocol(input,{acceptRelative:!0}))return defaultProto?parseURL(defaultProto+input):parsePath(input);let[protocol="",auth,hostAndPath=""]=(input.replace(/\\/g,"/").match(/([^/:]+:)?\/\/([^/@]+@)?(.*)/)||[]).splice(1),[host="",path=""]=(hostAndPath.match(/([^#/?]*)(.*)?/)||[]).splice(1),{pathname,search,hash}=parsePath(path.replace(/\/(?=[A-Za-z]:)/,""));return{protocol,auth:auth?auth.slice(0,Math.max(0,auth.length-1)):"",host,pathname,search,hash}}function parsePath(input=""){let[pathname="",search="",hash=""]=(input.match(/([^#?]*)(\?[^#]*)?(#.*)?/)||[]).splice(1);return{pathname,search,hash}}function stringifyParsedURL(parsed){let fullpath=parsed.pathname+(parsed.search?(parsed.search.startsWith("?")?"":"?")+parsed.search:"")+parsed.hash;return parsed.protocol?parsed.protocol+"//"+(parsed.auth?parsed.auth+"@":"")+parsed.host+fullpath:fullpath}var FetchError2=class extends Error{constructor(){super(...arguments),this.name="FetchError"}};function createFetchError(request,error,response){let message="";error&&(message=error.message),request&&response?message=`${message} (${response.status} ${response.statusText} (${request.toString()}))`:request&&(message=`${message} (${request.toString()})`);let fetchError=new FetchError2(message);return Object.defineProperty(fetchError,"request",{get(){return request}}),Object.defineProperty(fetchError,"response",{get(){return response}}),Object.defineProperty(fetchError,"data",{get(){return response&&response._data}}),Object.defineProperty(fetchError,"status",{get(){return response&&response.status}}),Object.defineProperty(fetchError,"statusText",{get(){return response&&response.statusText}}),Object.defineProperty(fetchError,"statusCode",{get(){return response&&response.status}}),Object.defineProperty(fetchError,"statusMessage",{get(){return response&&response.statusText}}),fetchError}var payloadMethods=new Set(Object.freeze(["PATCH","POST","PUT","DELETE"]));function isPayloadMethod(method="GET"){return payloadMethods.has(method.toUpperCase())}function isJSONSerializable(value){if(value===void 0)return!1;let t2=typeof value;return t2==="string"||t2==="number"||t2==="boolean"||t2===null?!0:t2!=="object"?!1:Array.isArray(value)?!0:value.constructor&&value.constructor.name==="Object"||typeof value.toJSON=="function"}var textTypes=new Set(["image/svg","application/xml","application/xhtml","application/html"]),JSON_RE=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function detectResponseType(_contentType=""){if(!_contentType)return"json";let contentType=_contentType.split(";").shift()||"";return JSON_RE.test(contentType)?"json":textTypes.has(contentType)||contentType.startsWith("text/")?"text":"blob"}function mergeFetchOptions(input,defaults,Headers4=globalThis.Headers){let merged={...defaults,...input};if(defaults?.params&&input?.params&&(merged.params={...defaults?.params,...input?.params}),defaults?.query&&input?.query&&(merged.query={...defaults?.query,...input?.query}),defaults?.headers&&input?.headers){merged.headers=new Headers4(defaults?.headers||{});for(let[key,value]of new Headers4(input?.headers||{}))merged.headers.set(key,value)}return merged}var retryStatusCodes=new Set([408,409,425,429,500,502,503,504]);function createFetch(globalOptions){let{fetch:fetch4,Headers:Headers4}=globalOptions;function onError(context){let isAbort=context.error&&context.error.name==="AbortError"||!1;if(context.options.retry!==!1&&!isAbort){let retries;typeof context.options.retry=="number"?retries=context.options.retry:retries=isPayloadMethod(context.options.method)?0:1;let responseCode=context.response&&context.response.status||500;if(retries>0&&retryStatusCodes.has(responseCode))return $fetchRaw(context.request,{...context.options,retry:retries-1})}let error=createFetchError(context.request,context.error,context.response);throw Error.captureStackTrace&&Error.captureStackTrace(error,$fetchRaw),error}let $fetchRaw=async function(_request,_options={}){let context={request:_request,options:mergeFetchOptions(_options,globalOptions.defaults,Headers4),response:void 0,error:void 0};context.options.onRequest&&await context.options.onRequest(context),typeof context.request=="string"&&(context.options.baseURL&&(context.request=withBase(context.request,context.options.baseURL)),(context.options.query||context.options.params)&&(context.request=withQuery(context.request,{...context.options.params,...context.options.query})),context.options.body&&isPayloadMethod(context.options.method)&&isJSONSerializable(context.options.body)&&(context.options.body=typeof context.options.body=="string"?context.options.body:JSON.stringify(context.options.body),context.options.headers=new Headers4(context.options.headers||{}),context.options.headers.has("content-type")||context.options.headers.set("content-type","application/json"),context.options.headers.has("accept")||context.options.headers.set("accept","application/json")));try{context.response=await fetch4(context.request,context.options)}catch(error){return context.error=error,context.options.onRequestError&&await context.options.onRequestError(context),await onError(context)}let responseType=(context.options.parseResponse?"json":context.options.responseType)||detectResponseType(context.response.headers.get("content-type")||"");if(responseType==="json"){let data=await context.response.text(),parseFunction=context.options.parseResponse||destr;context.response._data=parseFunction(data)}else responseType==="stream"?context.response._data=context.response.body:context.response._data=await context.response[responseType]();return context.options.onResponse&&await context.options.onResponse(context),!context.options.ignoreResponseError&&context.response.status>=400&&context.response.status<600?(context.options.onResponseError&&await context.options.onResponseError(context),await onError(context)):context.response},$fetch=async function(request,options){return(await $fetchRaw(request,options))._data};return $fetch.raw=$fetchRaw,$fetch.native=fetch4,$fetch.create=(defaultOptions={})=>createFetch({...globalOptions,defaults:{...globalOptions.defaults,...defaultOptions}}),$fetch}function createNodeFetch(){if(!JSON.parse(process.env.FETCH_KEEP_ALIVE||"false"))return fetch2;let agentOptions={keepAlive:!0},httpAgent=new import_node_http2.default.Agent(agentOptions),httpsAgent=new import_node_https2.default.Agent(agentOptions),nodeFetchOptions={agent(parsedURL){return parsedURL.protocol==="http:"?httpAgent:httpsAgent}};return function(input,init){return fetch2(input,{...nodeFetchOptions,...init})}}var fetch3=globalThis.fetch||createNodeFetch(),Headers3=globalThis.Headers||Headers2,ofetch=createFetch({fetch:fetch3,Headers:Headers3});var import_promises=require("node:fs/promises"),import_node_os=require("node:os"),import_node_path=require("node:path"),install=async()=>{core.startGroup("Install attic"),core.info("Installing attic");let installScript=await fetch3("https://raw.githubusercontent.com/zhaofengli/attic/main/.github/install-attic-ci.sh").then(r3=>(r3.ok||(core.setFailed(`Action failed with error: ${r3.statusText}`),core.endGroup(),process.exit(1)),r3.text()));try{let installScriptPath=(0,import_node_path.join)((0,import_node_os.tmpdir)(),"install-attic-ci.sh");await(0,import_promises.writeFile)(installScriptPath,installScript),core.info("Running install script"),await(0,import_exec.exec)("bash",[installScriptPath])}catch(e2){core.setFailed(`Action failed with error: ${e2}`)}core.endGroup()};var core2=__toESM(require_core()),import_exec3=__toESM(require_exec());var import_exec2=__toESM(require_exec()),import_node_stream2=require("node:stream"),StringStream=class extends import_node_stream2.Writable{chunks=[];_write(chunk,_enc,next){this.chunks.push(Buffer.from(chunk)),next()}string(){return Buffer.concat(this.chunks).toString("utf-8")}},getStorePaths=async()=>{let outStream=new StringStream;return await(0,import_exec2.exec)("nix",["path-info","--all"],{outStream}),outStream.string().split(` +`).filter(Boolean)};var configure=async()=>{core2.startGroup("Configure attic");try{let endpoint=core2.getInput("endpoint"),cache=core2.getInput("cache"),token=core2.getInput("token");core2.info("Logging in to attic cache"),await(0,import_exec3.exec)("attic",["login","--set-default",cache,endpoint,token]),core2.info("Collecting store paths before build");let paths=await getStorePaths();core2.saveState("initial-paths",JSON.stringify(paths))}catch(e2){core2.setFailed(`Action failed with error: ${e2}`)}core2.endGroup()};var main=async()=>{await install(),await configure()};main(); /*! Bundled license information: node-fetch-native/dist/shared/node-fetch-native.d7878b77.mjs: diff --git a/dist/post.js b/dist/post.js index b11d789..cfb738b 100644 --- a/dist/post.js +++ b/dist/post.js @@ -5,5 +5,5 @@ Error Message: ${error.result.message}`)})).result)===null||_a===void 0?void 0:_a.value;if(!id_token)throw new Error("Response json body do not have ID Token field");return id_token})}static getIDToken(audience){return __awaiter(this,void 0,void 0,function*(){try{let id_token_url=_OidcClient.getIDTokenUrl();if(audience){let encodedAudience=encodeURIComponent(audience);id_token_url=`${id_token_url}&audience=${encodedAudience}`}core_1.debug(`ID token url is ${id_token_url}`);let id_token=yield _OidcClient.getCall(id_token_url);return core_1.setSecret(id_token),id_token}catch(error){throw new Error(`Error message: ${error.message}`)}})}};exports.OidcClient=OidcClient}});var require_summary=__commonJS({"node_modules/.pnpm/@actions+core@1.10.0/node_modules/@actions/core/lib/summary.js"(exports){"use strict";var __awaiter=exports&&exports.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0});exports.summary=exports.markdownSummary=exports.SUMMARY_DOCS_URL=exports.SUMMARY_ENV_VAR=void 0;var os_1=require("os"),fs_1=require("fs"),{access,appendFile,writeFile}=fs_1.promises;exports.SUMMARY_ENV_VAR="GITHUB_STEP_SUMMARY";exports.SUMMARY_DOCS_URL="https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary";var Summary=class{constructor(){this._buffer=""}filePath(){return __awaiter(this,void 0,void 0,function*(){if(this._filePath)return this._filePath;let pathFromEnv=process.env[exports.SUMMARY_ENV_VAR];if(!pathFromEnv)throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`);try{yield access(pathFromEnv,fs_1.constants.R_OK|fs_1.constants.W_OK)}catch{throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`)}return this._filePath=pathFromEnv,this._filePath})}wrap(tag,content,attrs={}){let htmlAttrs=Object.entries(attrs).map(([key,value])=>` ${key}="${value}"`).join("");return content?`<${tag}${htmlAttrs}>${content}`:`<${tag}${htmlAttrs}>`}write(options){return __awaiter(this,void 0,void 0,function*(){let overwrite=!!options?.overwrite,filePath=yield this.filePath();return yield(overwrite?writeFile:appendFile)(filePath,this._buffer,{encoding:"utf8"}),this.emptyBuffer()})}clear(){return __awaiter(this,void 0,void 0,function*(){return this.emptyBuffer().write({overwrite:!0})})}stringify(){return this._buffer}isEmptyBuffer(){return this._buffer.length===0}emptyBuffer(){return this._buffer="",this}addRaw(text,addEOL=!1){return this._buffer+=text,addEOL?this.addEOL():this}addEOL(){return this.addRaw(os_1.EOL)}addCodeBlock(code,lang){let attrs=Object.assign({},lang&&{lang}),element=this.wrap("pre",this.wrap("code",code),attrs);return this.addRaw(element).addEOL()}addList(items,ordered=!1){let tag=ordered?"ol":"ul",listItems=items.map(item=>this.wrap("li",item)).join(""),element=this.wrap(tag,listItems);return this.addRaw(element).addEOL()}addTable(rows){let tableBody=rows.map(row=>{let cells=row.map(cell=>{if(typeof cell=="string")return this.wrap("td",cell);let{header,data,colspan,rowspan}=cell,tag=header?"th":"td",attrs=Object.assign(Object.assign({},colspan&&{colspan}),rowspan&&{rowspan});return this.wrap(tag,data,attrs)}).join("");return this.wrap("tr",cells)}).join(""),element=this.wrap("table",tableBody);return this.addRaw(element).addEOL()}addDetails(label,content){let element=this.wrap("details",this.wrap("summary",label)+content);return this.addRaw(element).addEOL()}addImage(src,alt,options){let{width,height}=options||{},attrs=Object.assign(Object.assign({},width&&{width}),height&&{height}),element=this.wrap("img",null,Object.assign({src,alt},attrs));return this.addRaw(element).addEOL()}addHeading(text,level){let tag=`h${level}`,allowedTag=["h1","h2","h3","h4","h5","h6"].includes(tag)?tag:"h1",element=this.wrap(allowedTag,text);return this.addRaw(element).addEOL()}addSeparator(){let element=this.wrap("hr",null);return this.addRaw(element).addEOL()}addBreak(){let element=this.wrap("br",null);return this.addRaw(element).addEOL()}addQuote(text,cite){let attrs=Object.assign({},cite&&{cite}),element=this.wrap("blockquote",text,attrs);return this.addRaw(element).addEOL()}addLink(text,href){let element=this.wrap("a",text,{href});return this.addRaw(element).addEOL()}},_summary=new Summary;exports.markdownSummary=_summary;exports.summary=_summary}});var require_path_utils=__commonJS({"node_modules/.pnpm/@actions+core@1.10.0/node_modules/@actions/core/lib/path-utils.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){k2===void 0&&(k2=k),Object.defineProperty(o,k2,{enumerable:!0,get:function(){return m[k]}})}:function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]}),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result};Object.defineProperty(exports,"__esModule",{value:!0});exports.toPlatformPath=exports.toWin32Path=exports.toPosixPath=void 0;var path=__importStar(require("path"));function toPosixPath(pth){return pth.replace(/[\\]/g,"/")}exports.toPosixPath=toPosixPath;function toWin32Path(pth){return pth.replace(/[/]/g,"\\")}exports.toWin32Path=toWin32Path;function toPlatformPath(pth){return pth.replace(/[/\\]/g,path.sep)}exports.toPlatformPath=toPlatformPath}});var require_core=__commonJS({"node_modules/.pnpm/@actions+core@1.10.0/node_modules/@actions/core/lib/core.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){k2===void 0&&(k2=k),Object.defineProperty(o,k2,{enumerable:!0,get:function(){return m[k]}})}:function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]}),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__awaiter=exports&&exports.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0});exports.getIDToken=exports.getState=exports.saveState=exports.group=exports.endGroup=exports.startGroup=exports.info=exports.notice=exports.warning=exports.error=exports.debug=exports.isDebug=exports.setFailed=exports.setCommandEcho=exports.setOutput=exports.getBooleanInput=exports.getMultilineInput=exports.getInput=exports.addPath=exports.setSecret=exports.exportVariable=exports.ExitCode=void 0;var command_1=require_command(),file_command_1=require_file_command(),utils_1=require_utils(),os=__importStar(require("os")),path=__importStar(require("path")),oidc_utils_1=require_oidc_utils(),ExitCode;(function(ExitCode2){ExitCode2[ExitCode2.Success=0]="Success",ExitCode2[ExitCode2.Failure=1]="Failure"})(ExitCode=exports.ExitCode||(exports.ExitCode={}));function exportVariable(name,val){let convertedVal=utils_1.toCommandValue(val);if(process.env[name]=convertedVal,process.env.GITHUB_ENV||"")return file_command_1.issueFileCommand("ENV",file_command_1.prepareKeyValueMessage(name,val));command_1.issueCommand("set-env",{name},convertedVal)}exports.exportVariable=exportVariable;function setSecret(secret){command_1.issueCommand("add-mask",{},secret)}exports.setSecret=setSecret;function addPath(inputPath){process.env.GITHUB_PATH||""?file_command_1.issueFileCommand("PATH",inputPath):command_1.issueCommand("add-path",{},inputPath),process.env.PATH=`${inputPath}${path.delimiter}${process.env.PATH}`}exports.addPath=addPath;function getInput2(name,options){let val=process.env[`INPUT_${name.replace(/ /g,"_").toUpperCase()}`]||"";if(options&&options.required&&!val)throw new Error(`Input required and not supplied: ${name}`);return options&&options.trimWhitespace===!1?val:val.trim()}exports.getInput=getInput2;function getMultilineInput(name,options){let inputs=getInput2(name,options).split(` `).filter(x=>x!=="");return options&&options.trimWhitespace===!1?inputs:inputs.map(input=>input.trim())}exports.getMultilineInput=getMultilineInput;function getBooleanInput(name,options){let trueValue=["true","True","TRUE"],falseValue=["false","False","FALSE"],val=getInput2(name,options);if(trueValue.includes(val))return!0;if(falseValue.includes(val))return!1;throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name} -Support boolean input list: \`true | True | TRUE | false | False | FALSE\``)}exports.getBooleanInput=getBooleanInput;function setOutput(name,value){if(process.env.GITHUB_OUTPUT||"")return file_command_1.issueFileCommand("OUTPUT",file_command_1.prepareKeyValueMessage(name,value));process.stdout.write(os.EOL),command_1.issueCommand("set-output",{name},utils_1.toCommandValue(value))}exports.setOutput=setOutput;function setCommandEcho(enabled){command_1.issue("echo",enabled?"on":"off")}exports.setCommandEcho=setCommandEcho;function setFailed2(message){process.exitCode=ExitCode.Failure,error(message)}exports.setFailed=setFailed2;function isDebug(){return process.env.RUNNER_DEBUG==="1"}exports.isDebug=isDebug;function debug(message){command_1.issueCommand("debug",{},message)}exports.debug=debug;function error(message,properties={}){command_1.issueCommand("error",utils_1.toCommandProperties(properties),message instanceof Error?message.toString():message)}exports.error=error;function warning(message,properties={}){command_1.issueCommand("warning",utils_1.toCommandProperties(properties),message instanceof Error?message.toString():message)}exports.warning=warning;function notice(message,properties={}){command_1.issueCommand("notice",utils_1.toCommandProperties(properties),message instanceof Error?message.toString():message)}exports.notice=notice;function info2(message){process.stdout.write(message+os.EOL)}exports.info=info2;function startGroup2(name){command_1.issue("group",name)}exports.startGroup=startGroup2;function endGroup2(){command_1.issue("endgroup")}exports.endGroup=endGroup2;function group(name,fn){return __awaiter(this,void 0,void 0,function*(){startGroup2(name);let result;try{result=yield fn()}finally{endGroup2()}return result})}exports.group=group;function saveState(name,value){if(process.env.GITHUB_STATE||"")return file_command_1.issueFileCommand("STATE",file_command_1.prepareKeyValueMessage(name,value));command_1.issueCommand("save-state",{name},utils_1.toCommandValue(value))}exports.saveState=saveState;function getState2(name){return process.env[`STATE_${name}`]||""}exports.getState=getState2;function getIDToken(aud){return __awaiter(this,void 0,void 0,function*(){return yield oidc_utils_1.OidcClient.getIDToken(aud)})}exports.getIDToken=getIDToken;var summary_1=require_summary();Object.defineProperty(exports,"summary",{enumerable:!0,get:function(){return summary_1.summary}});var summary_2=require_summary();Object.defineProperty(exports,"markdownSummary",{enumerable:!0,get:function(){return summary_2.markdownSummary}});var path_utils_1=require_path_utils();Object.defineProperty(exports,"toPosixPath",{enumerable:!0,get:function(){return path_utils_1.toPosixPath}});Object.defineProperty(exports,"toWin32Path",{enumerable:!0,get:function(){return path_utils_1.toWin32Path}});Object.defineProperty(exports,"toPlatformPath",{enumerable:!0,get:function(){return path_utils_1.toPlatformPath}})}});var require_io_util=__commonJS({"node_modules/.pnpm/@actions+io@1.1.3/node_modules/@actions/io/lib/io-util.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){k2===void 0&&(k2=k),Object.defineProperty(o,k2,{enumerable:!0,get:function(){return m[k]}})}:function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]}),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__awaiter=exports&&exports.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})},_a;Object.defineProperty(exports,"__esModule",{value:!0});exports.getCmdPath=exports.tryGetExecutablePath=exports.isRooted=exports.isDirectory=exports.exists=exports.READONLY=exports.UV_FS_O_EXLOCK=exports.IS_WINDOWS=exports.unlink=exports.symlink=exports.stat=exports.rmdir=exports.rm=exports.rename=exports.readlink=exports.readdir=exports.open=exports.mkdir=exports.lstat=exports.copyFile=exports.chmod=void 0;var fs=__importStar(require("fs")),path=__importStar(require("path"));_a=fs.promises,exports.chmod=_a.chmod,exports.copyFile=_a.copyFile,exports.lstat=_a.lstat,exports.mkdir=_a.mkdir,exports.open=_a.open,exports.readdir=_a.readdir,exports.readlink=_a.readlink,exports.rename=_a.rename,exports.rm=_a.rm,exports.rmdir=_a.rmdir,exports.stat=_a.stat,exports.symlink=_a.symlink,exports.unlink=_a.unlink;exports.IS_WINDOWS=process.platform==="win32";exports.UV_FS_O_EXLOCK=268435456;exports.READONLY=fs.constants.O_RDONLY;function exists(fsPath){return __awaiter(this,void 0,void 0,function*(){try{yield exports.stat(fsPath)}catch(err){if(err.code==="ENOENT")return!1;throw err}return!0})}exports.exists=exists;function isDirectory(fsPath,useStat=!1){return __awaiter(this,void 0,void 0,function*(){return(useStat?yield exports.stat(fsPath):yield exports.lstat(fsPath)).isDirectory()})}exports.isDirectory=isDirectory;function isRooted(p){if(p=normalizeSeparators(p),!p)throw new Error('isRooted() parameter "p" cannot be empty');return exports.IS_WINDOWS?p.startsWith("\\")||/^[A-Z]:/i.test(p):p.startsWith("/")}exports.isRooted=isRooted;function tryGetExecutablePath(filePath,extensions){return __awaiter(this,void 0,void 0,function*(){let stats;try{stats=yield exports.stat(filePath)}catch(err){err.code!=="ENOENT"&&console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`)}if(stats&&stats.isFile()){if(exports.IS_WINDOWS){let upperExt=path.extname(filePath).toUpperCase();if(extensions.some(validExt=>validExt.toUpperCase()===upperExt))return filePath}else if(isUnixExecutable(stats))return filePath}let originalFilePath=filePath;for(let extension of extensions){filePath=originalFilePath+extension,stats=void 0;try{stats=yield exports.stat(filePath)}catch(err){err.code!=="ENOENT"&&console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`)}if(stats&&stats.isFile()){if(exports.IS_WINDOWS){try{let directory=path.dirname(filePath),upperName=path.basename(filePath).toUpperCase();for(let actualName of yield exports.readdir(directory))if(upperName===actualName.toUpperCase()){filePath=path.join(directory,actualName);break}}catch(err){console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`)}return filePath}else if(isUnixExecutable(stats))return filePath}}return""})}exports.tryGetExecutablePath=tryGetExecutablePath;function normalizeSeparators(p){return p=p||"",exports.IS_WINDOWS?(p=p.replace(/\//g,"\\"),p.replace(/\\\\+/g,"\\")):p.replace(/\/\/+/g,"/")}function isUnixExecutable(stats){return(stats.mode&1)>0||(stats.mode&8)>0&&stats.gid===process.getgid()||(stats.mode&64)>0&&stats.uid===process.getuid()}function getCmdPath(){var _a2;return(_a2=process.env.COMSPEC)!==null&&_a2!==void 0?_a2:"cmd.exe"}exports.getCmdPath=getCmdPath}});var require_io=__commonJS({"node_modules/.pnpm/@actions+io@1.1.3/node_modules/@actions/io/lib/io.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){k2===void 0&&(k2=k),Object.defineProperty(o,k2,{enumerable:!0,get:function(){return m[k]}})}:function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]}),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__awaiter=exports&&exports.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0});exports.findInPath=exports.which=exports.mkdirP=exports.rmRF=exports.mv=exports.cp=void 0;var assert_1=require("assert"),path=__importStar(require("path")),ioUtil=__importStar(require_io_util());function cp(source,dest,options={}){return __awaiter(this,void 0,void 0,function*(){let{force,recursive,copySourceDirectory}=readCopyOptions(options),destStat=(yield ioUtil.exists(dest))?yield ioUtil.stat(dest):null;if(destStat&&destStat.isFile()&&!force)return;let newDest=destStat&&destStat.isDirectory()&©SourceDirectory?path.join(dest,path.basename(source)):dest;if(!(yield ioUtil.exists(source)))throw new Error(`no such file or directory: ${source}`);if((yield ioUtil.stat(source)).isDirectory())if(recursive)yield cpDirRecursive(source,newDest,0,force);else throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`);else{if(path.relative(source,newDest)==="")throw new Error(`'${newDest}' and '${source}' are the same file`);yield copyFile(source,newDest,force)}})}exports.cp=cp;function mv(source,dest,options={}){return __awaiter(this,void 0,void 0,function*(){if(yield ioUtil.exists(dest)){let destExists=!0;if((yield ioUtil.isDirectory(dest))&&(dest=path.join(dest,path.basename(source)),destExists=yield ioUtil.exists(dest)),destExists)if(options.force==null||options.force)yield rmRF(dest);else throw new Error("Destination already exists")}yield mkdirP(path.dirname(dest)),yield ioUtil.rename(source,dest)})}exports.mv=mv;function rmRF(inputPath){return __awaiter(this,void 0,void 0,function*(){if(ioUtil.IS_WINDOWS&&/[*"<>|]/.test(inputPath))throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows');try{yield ioUtil.rm(inputPath,{force:!0,maxRetries:3,recursive:!0,retryDelay:300})}catch(err){throw new Error(`File was unable to be removed ${err}`)}})}exports.rmRF=rmRF;function mkdirP(fsPath){return __awaiter(this,void 0,void 0,function*(){assert_1.ok(fsPath,"a path argument must be provided"),yield ioUtil.mkdir(fsPath,{recursive:!0})})}exports.mkdirP=mkdirP;function which(tool,check){return __awaiter(this,void 0,void 0,function*(){if(!tool)throw new Error("parameter 'tool' is required");if(check){let result=yield which(tool,!1);if(!result)throw ioUtil.IS_WINDOWS?new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`):new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`);return result}let matches=yield findInPath(tool);return matches&&matches.length>0?matches[0]:""})}exports.which=which;function findInPath(tool){return __awaiter(this,void 0,void 0,function*(){if(!tool)throw new Error("parameter 'tool' is required");let extensions=[];if(ioUtil.IS_WINDOWS&&process.env.PATHEXT)for(let extension of process.env.PATHEXT.split(path.delimiter))extension&&extensions.push(extension);if(ioUtil.isRooted(tool)){let filePath=yield ioUtil.tryGetExecutablePath(tool,extensions);return filePath?[filePath]:[]}if(tool.includes(path.sep))return[];let directories=[];if(process.env.PATH)for(let p of process.env.PATH.split(path.delimiter))p&&directories.push(p);let matches=[];for(let directory of directories){let filePath=yield ioUtil.tryGetExecutablePath(path.join(directory,tool),extensions);filePath&&matches.push(filePath)}return matches})}exports.findInPath=findInPath;function readCopyOptions(options){let force=options.force==null?!0:options.force,recursive=!!options.recursive,copySourceDirectory=options.copySourceDirectory==null?!0:!!options.copySourceDirectory;return{force,recursive,copySourceDirectory}}function cpDirRecursive(sourceDir,destDir,currentDepth,force){return __awaiter(this,void 0,void 0,function*(){if(currentDepth>=255)return;currentDepth++,yield mkdirP(destDir);let files=yield ioUtil.readdir(sourceDir);for(let fileName of files){let srcFile=`${sourceDir}/${fileName}`,destFile=`${destDir}/${fileName}`;(yield ioUtil.lstat(srcFile)).isDirectory()?yield cpDirRecursive(srcFile,destFile,currentDepth,force):yield copyFile(srcFile,destFile,force)}yield ioUtil.chmod(destDir,(yield ioUtil.stat(sourceDir)).mode)})}function copyFile(srcFile,destFile,force){return __awaiter(this,void 0,void 0,function*(){if((yield ioUtil.lstat(srcFile)).isSymbolicLink()){try{yield ioUtil.lstat(destFile),yield ioUtil.unlink(destFile)}catch(e){e.code==="EPERM"&&(yield ioUtil.chmod(destFile,"0666"),yield ioUtil.unlink(destFile))}let symlinkFull=yield ioUtil.readlink(srcFile);yield ioUtil.symlink(symlinkFull,destFile,ioUtil.IS_WINDOWS?"junction":null)}else(!(yield ioUtil.exists(destFile))||force)&&(yield ioUtil.copyFile(srcFile,destFile))})}}});var require_toolrunner=__commonJS({"node_modules/.pnpm/@actions+exec@1.1.1/node_modules/@actions/exec/lib/toolrunner.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){k2===void 0&&(k2=k),Object.defineProperty(o,k2,{enumerable:!0,get:function(){return m[k]}})}:function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]}),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__awaiter=exports&&exports.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0});exports.argStringToArray=exports.ToolRunner=void 0;var os=__importStar(require("os")),events=__importStar(require("events")),child=__importStar(require("child_process")),path=__importStar(require("path")),io=__importStar(require_io()),ioUtil=__importStar(require_io_util()),timers_1=require("timers"),IS_WINDOWS=process.platform==="win32",ToolRunner=class extends events.EventEmitter{constructor(toolPath,args,options){if(super(),!toolPath)throw new Error("Parameter 'toolPath' cannot be null or empty.");this.toolPath=toolPath,this.args=args||[],this.options=options||{}}_debug(message){this.options.listeners&&this.options.listeners.debug&&this.options.listeners.debug(message)}_getCommandString(options,noPrefix){let toolPath=this._getSpawnFileName(),args=this._getSpawnArgs(options),cmd=noPrefix?"":"[command]";if(IS_WINDOWS)if(this._isCmdFile()){cmd+=toolPath;for(let a of args)cmd+=` ${a}`}else if(options.windowsVerbatimArguments){cmd+=`"${toolPath}"`;for(let a of args)cmd+=` ${a}`}else{cmd+=this._windowsQuoteCmdArg(toolPath);for(let a of args)cmd+=` ${this._windowsQuoteCmdArg(a)}`}else{cmd+=toolPath;for(let a of args)cmd+=` ${a}`}return cmd}_processLineBuffer(data,strBuffer,onLine){try{let s=strBuffer+data.toString(),n=s.indexOf(os.EOL);for(;n>-1;){let line=s.substring(0,n);onLine(line),s=s.substring(n+os.EOL.length),n=s.indexOf(os.EOL)}return s}catch(err){return this._debug(`error processing line. Failed with error ${err}`),""}}_getSpawnFileName(){return IS_WINDOWS&&this._isCmdFile()?process.env.COMSPEC||"cmd.exe":this.toolPath}_getSpawnArgs(options){if(IS_WINDOWS&&this._isCmdFile()){let argline=`/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`;for(let a of this.args)argline+=" ",argline+=options.windowsVerbatimArguments?a:this._windowsQuoteCmdArg(a);return argline+='"',[argline]}return this.args}_endsWith(str,end){return str.endsWith(end)}_isCmdFile(){let upperToolPath=this.toolPath.toUpperCase();return this._endsWith(upperToolPath,".CMD")||this._endsWith(upperToolPath,".BAT")}_windowsQuoteCmdArg(arg){if(!this._isCmdFile())return this._uvQuoteCmdArg(arg);if(!arg)return'""';let cmdSpecialChars=[" "," ","&","(",")","[","]","{","}","^","=",";","!","'","+",",","`","~","|","<",">",'"'],needsQuotes=!1;for(let char of arg)if(cmdSpecialChars.some(x=>x===char)){needsQuotes=!0;break}if(!needsQuotes)return arg;let reverse='"',quoteHit=!0;for(let i=arg.length;i>0;i--)reverse+=arg[i-1],quoteHit&&arg[i-1]==="\\"?reverse+="\\":arg[i-1]==='"'?(quoteHit=!0,reverse+='"'):quoteHit=!1;return reverse+='"',reverse.split("").reverse().join("")}_uvQuoteCmdArg(arg){if(!arg)return'""';if(!arg.includes(" ")&&!arg.includes(" ")&&!arg.includes('"'))return arg;if(!arg.includes('"')&&!arg.includes("\\"))return`"${arg}"`;let reverse='"',quoteHit=!0;for(let i=arg.length;i>0;i--)reverse+=arg[i-1],quoteHit&&arg[i-1]==="\\"?reverse+="\\":arg[i-1]==='"'?(quoteHit=!0,reverse+="\\"):quoteHit=!1;return reverse+='"',reverse.split("").reverse().join("")}_cloneExecOptions(options){options=options||{};let result={cwd:options.cwd||process.cwd(),env:options.env||process.env,silent:options.silent||!1,windowsVerbatimArguments:options.windowsVerbatimArguments||!1,failOnStdErr:options.failOnStdErr||!1,ignoreReturnCode:options.ignoreReturnCode||!1,delay:options.delay||1e4};return result.outStream=options.outStream||process.stdout,result.errStream=options.errStream||process.stderr,result}_getSpawnOptions(options,toolPath){options=options||{};let result={};return result.cwd=options.cwd,result.env=options.env,result.windowsVerbatimArguments=options.windowsVerbatimArguments||this._isCmdFile(),options.windowsVerbatimArguments&&(result.argv0=`"${toolPath}"`),result}exec(){return __awaiter(this,void 0,void 0,function*(){return!ioUtil.isRooted(this.toolPath)&&(this.toolPath.includes("/")||IS_WINDOWS&&this.toolPath.includes("\\"))&&(this.toolPath=path.resolve(process.cwd(),this.options.cwd||process.cwd(),this.toolPath)),this.toolPath=yield io.which(this.toolPath,!0),new Promise((resolve,reject)=>__awaiter(this,void 0,void 0,function*(){this._debug(`exec tool: ${this.toolPath}`),this._debug("arguments:");for(let arg of this.args)this._debug(` ${arg}`);let optionsNonNull=this._cloneExecOptions(this.options);!optionsNonNull.silent&&optionsNonNull.outStream&&optionsNonNull.outStream.write(this._getCommandString(optionsNonNull)+os.EOL);let state=new ExecState(optionsNonNull,this.toolPath);if(state.on("debug",message=>{this._debug(message)}),this.options.cwd&&!(yield ioUtil.exists(this.options.cwd)))return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`));let fileName=this._getSpawnFileName(),cp=child.spawn(fileName,this._getSpawnArgs(optionsNonNull),this._getSpawnOptions(this.options,fileName)),stdbuffer="";cp.stdout&&cp.stdout.on("data",data=>{this.options.listeners&&this.options.listeners.stdout&&this.options.listeners.stdout(data),!optionsNonNull.silent&&optionsNonNull.outStream&&optionsNonNull.outStream.write(data),stdbuffer=this._processLineBuffer(data,stdbuffer,line=>{this.options.listeners&&this.options.listeners.stdline&&this.options.listeners.stdline(line)})});let errbuffer="";if(cp.stderr&&cp.stderr.on("data",data=>{state.processStderr=!0,this.options.listeners&&this.options.listeners.stderr&&this.options.listeners.stderr(data),!optionsNonNull.silent&&optionsNonNull.errStream&&optionsNonNull.outStream&&(optionsNonNull.failOnStdErr?optionsNonNull.errStream:optionsNonNull.outStream).write(data),errbuffer=this._processLineBuffer(data,errbuffer,line=>{this.options.listeners&&this.options.listeners.errline&&this.options.listeners.errline(line)})}),cp.on("error",err=>{state.processError=err.message,state.processExited=!0,state.processClosed=!0,state.CheckComplete()}),cp.on("exit",code=>{state.processExitCode=code,state.processExited=!0,this._debug(`Exit code ${code} received from tool '${this.toolPath}'`),state.CheckComplete()}),cp.on("close",code=>{state.processExitCode=code,state.processExited=!0,state.processClosed=!0,this._debug(`STDIO streams have closed for tool '${this.toolPath}'`),state.CheckComplete()}),state.on("done",(error,exitCode)=>{stdbuffer.length>0&&this.emit("stdline",stdbuffer),errbuffer.length>0&&this.emit("errline",errbuffer),cp.removeAllListeners(),error?reject(error):resolve(exitCode)}),this.options.input){if(!cp.stdin)throw new Error("child process missing stdin");cp.stdin.end(this.options.input)}}))})}};exports.ToolRunner=ToolRunner;function argStringToArray(argString){let args=[],inQuotes=!1,escaped=!1,arg="";function append(c){escaped&&c!=='"'&&(arg+="\\"),arg+=c,escaped=!1}for(let i=0;i0&&(args.push(arg),arg="");continue}append(c)}return arg.length>0&&args.push(arg.trim()),args}exports.argStringToArray=argStringToArray;var ExecState=class _ExecState extends events.EventEmitter{constructor(options,toolPath){if(super(),this.processClosed=!1,this.processError="",this.processExitCode=0,this.processExited=!1,this.processStderr=!1,this.delay=1e4,this.done=!1,this.timeout=null,!toolPath)throw new Error("toolPath must not be empty");this.options=options,this.toolPath=toolPath,options.delay&&(this.delay=options.delay)}CheckComplete(){this.done||(this.processClosed?this._setResult():this.processExited&&(this.timeout=timers_1.setTimeout(_ExecState.HandleTimeout,this.delay,this)))}_debug(message){this.emit("debug",message)}_setResult(){let error;this.processExited&&(this.processError?error=new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`):this.processExitCode!==0&&!this.options.ignoreReturnCode?error=new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`):this.processStderr&&this.options.failOnStdErr&&(error=new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`))),this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.done=!0,this.emit("done",error,this.processExitCode)}static HandleTimeout(state){if(!state.done){if(!state.processClosed&&state.processExited){let message=`The STDIO streams did not close within ${state.delay/1e3} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`;state._debug(message)}state._setResult()}}}}});var require_exec=__commonJS({"node_modules/.pnpm/@actions+exec@1.1.1/node_modules/@actions/exec/lib/exec.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){k2===void 0&&(k2=k),Object.defineProperty(o,k2,{enumerable:!0,get:function(){return m[k]}})}:function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]}),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__awaiter=exports&&exports.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0});exports.getExecOutput=exports.exec=void 0;var string_decoder_1=require("string_decoder"),tr=__importStar(require_toolrunner());function exec3(commandLine,args,options){return __awaiter(this,void 0,void 0,function*(){let commandArgs=tr.argStringToArray(commandLine);if(commandArgs.length===0)throw new Error("Parameter 'commandLine' cannot be null or empty.");let toolPath=commandArgs[0];return args=commandArgs.slice(1).concat(args||[]),new tr.ToolRunner(toolPath,args,options).exec()})}exports.exec=exec3;function getExecOutput(commandLine,args,options){var _a,_b;return __awaiter(this,void 0,void 0,function*(){let stdout="",stderr="",stdoutDecoder=new string_decoder_1.StringDecoder("utf8"),stderrDecoder=new string_decoder_1.StringDecoder("utf8"),originalStdoutListener=(_a=options?.listeners)===null||_a===void 0?void 0:_a.stdout,originalStdErrListener=(_b=options?.listeners)===null||_b===void 0?void 0:_b.stderr,stdErrListener=data=>{stderr+=stderrDecoder.write(data),originalStdErrListener&&originalStdErrListener(data)},stdOutListener=data=>{stdout+=stdoutDecoder.write(data),originalStdoutListener&&originalStdoutListener(data)},listeners=Object.assign(Object.assign({},options?.listeners),{stdout:stdOutListener,stderr:stdErrListener}),exitCode=yield exec3(commandLine,args,Object.assign(Object.assign({},options),{listeners}));return stdout+=stdoutDecoder.end(),stderr+=stderrDecoder.end(),{exitCode,stdout,stderr}})}exports.getExecOutput=getExecOutput}});var core=__toESM(require_core()),import_exec2=__toESM(require_exec());var import_exec=__toESM(require_exec()),import_node_stream=require("node:stream"),streamToString=stream=>{let chunks=[];return new Promise((resolve,reject)=>{stream.on("data",chunk=>chunks.push(Buffer.from(chunk))),stream.on("error",err=>reject(err)),stream.on("end",()=>resolve(Buffer.concat(chunks).toString("utf8")))})},getStorePaths=async()=>{let outStream=new import_node_stream.Writable;return await(0,import_exec.exec)("nix",["path-info","--all"],{outStream}),await streamToString(outStream).then(res=>res.split(` -`)).then(paths2=>paths2.filter(Boolean))};var push=async()=>{core.startGroup("Push to Attic");try{if(core.getInput("skip-push")==="true")core.info("Pushing to cache is disabled by skip-push");else{let cache=core.getInput("cache");core.info("Pushing to cache");let oldPaths=JSON.parse(core.getState("initial-paths")),addedPaths=(await getStorePaths()).filter(p=>!oldPaths.includes(p));await(0,import_exec2.exec)("attic",["push",cache,...addedPaths])}}catch(e){core.setFailed(`Action failed with error: ${e}`)}core.endGroup()};var main=async()=>{await push()};main(); +Support boolean input list: \`true | True | TRUE | false | False | FALSE\``)}exports.getBooleanInput=getBooleanInput;function setOutput(name,value){if(process.env.GITHUB_OUTPUT||"")return file_command_1.issueFileCommand("OUTPUT",file_command_1.prepareKeyValueMessage(name,value));process.stdout.write(os.EOL),command_1.issueCommand("set-output",{name},utils_1.toCommandValue(value))}exports.setOutput=setOutput;function setCommandEcho(enabled){command_1.issue("echo",enabled?"on":"off")}exports.setCommandEcho=setCommandEcho;function setFailed2(message){process.exitCode=ExitCode.Failure,error(message)}exports.setFailed=setFailed2;function isDebug(){return process.env.RUNNER_DEBUG==="1"}exports.isDebug=isDebug;function debug(message){command_1.issueCommand("debug",{},message)}exports.debug=debug;function error(message,properties={}){command_1.issueCommand("error",utils_1.toCommandProperties(properties),message instanceof Error?message.toString():message)}exports.error=error;function warning(message,properties={}){command_1.issueCommand("warning",utils_1.toCommandProperties(properties),message instanceof Error?message.toString():message)}exports.warning=warning;function notice(message,properties={}){command_1.issueCommand("notice",utils_1.toCommandProperties(properties),message instanceof Error?message.toString():message)}exports.notice=notice;function info2(message){process.stdout.write(message+os.EOL)}exports.info=info2;function startGroup2(name){command_1.issue("group",name)}exports.startGroup=startGroup2;function endGroup2(){command_1.issue("endgroup")}exports.endGroup=endGroup2;function group(name,fn){return __awaiter(this,void 0,void 0,function*(){startGroup2(name);let result;try{result=yield fn()}finally{endGroup2()}return result})}exports.group=group;function saveState(name,value){if(process.env.GITHUB_STATE||"")return file_command_1.issueFileCommand("STATE",file_command_1.prepareKeyValueMessage(name,value));command_1.issueCommand("save-state",{name},utils_1.toCommandValue(value))}exports.saveState=saveState;function getState2(name){return process.env[`STATE_${name}`]||""}exports.getState=getState2;function getIDToken(aud){return __awaiter(this,void 0,void 0,function*(){return yield oidc_utils_1.OidcClient.getIDToken(aud)})}exports.getIDToken=getIDToken;var summary_1=require_summary();Object.defineProperty(exports,"summary",{enumerable:!0,get:function(){return summary_1.summary}});var summary_2=require_summary();Object.defineProperty(exports,"markdownSummary",{enumerable:!0,get:function(){return summary_2.markdownSummary}});var path_utils_1=require_path_utils();Object.defineProperty(exports,"toPosixPath",{enumerable:!0,get:function(){return path_utils_1.toPosixPath}});Object.defineProperty(exports,"toWin32Path",{enumerable:!0,get:function(){return path_utils_1.toWin32Path}});Object.defineProperty(exports,"toPlatformPath",{enumerable:!0,get:function(){return path_utils_1.toPlatformPath}})}});var require_io_util=__commonJS({"node_modules/.pnpm/@actions+io@1.1.3/node_modules/@actions/io/lib/io-util.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){k2===void 0&&(k2=k),Object.defineProperty(o,k2,{enumerable:!0,get:function(){return m[k]}})}:function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]}),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__awaiter=exports&&exports.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})},_a;Object.defineProperty(exports,"__esModule",{value:!0});exports.getCmdPath=exports.tryGetExecutablePath=exports.isRooted=exports.isDirectory=exports.exists=exports.READONLY=exports.UV_FS_O_EXLOCK=exports.IS_WINDOWS=exports.unlink=exports.symlink=exports.stat=exports.rmdir=exports.rm=exports.rename=exports.readlink=exports.readdir=exports.open=exports.mkdir=exports.lstat=exports.copyFile=exports.chmod=void 0;var fs=__importStar(require("fs")),path=__importStar(require("path"));_a=fs.promises,exports.chmod=_a.chmod,exports.copyFile=_a.copyFile,exports.lstat=_a.lstat,exports.mkdir=_a.mkdir,exports.open=_a.open,exports.readdir=_a.readdir,exports.readlink=_a.readlink,exports.rename=_a.rename,exports.rm=_a.rm,exports.rmdir=_a.rmdir,exports.stat=_a.stat,exports.symlink=_a.symlink,exports.unlink=_a.unlink;exports.IS_WINDOWS=process.platform==="win32";exports.UV_FS_O_EXLOCK=268435456;exports.READONLY=fs.constants.O_RDONLY;function exists(fsPath){return __awaiter(this,void 0,void 0,function*(){try{yield exports.stat(fsPath)}catch(err){if(err.code==="ENOENT")return!1;throw err}return!0})}exports.exists=exists;function isDirectory(fsPath,useStat=!1){return __awaiter(this,void 0,void 0,function*(){return(useStat?yield exports.stat(fsPath):yield exports.lstat(fsPath)).isDirectory()})}exports.isDirectory=isDirectory;function isRooted(p){if(p=normalizeSeparators(p),!p)throw new Error('isRooted() parameter "p" cannot be empty');return exports.IS_WINDOWS?p.startsWith("\\")||/^[A-Z]:/i.test(p):p.startsWith("/")}exports.isRooted=isRooted;function tryGetExecutablePath(filePath,extensions){return __awaiter(this,void 0,void 0,function*(){let stats;try{stats=yield exports.stat(filePath)}catch(err){err.code!=="ENOENT"&&console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`)}if(stats&&stats.isFile()){if(exports.IS_WINDOWS){let upperExt=path.extname(filePath).toUpperCase();if(extensions.some(validExt=>validExt.toUpperCase()===upperExt))return filePath}else if(isUnixExecutable(stats))return filePath}let originalFilePath=filePath;for(let extension of extensions){filePath=originalFilePath+extension,stats=void 0;try{stats=yield exports.stat(filePath)}catch(err){err.code!=="ENOENT"&&console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`)}if(stats&&stats.isFile()){if(exports.IS_WINDOWS){try{let directory=path.dirname(filePath),upperName=path.basename(filePath).toUpperCase();for(let actualName of yield exports.readdir(directory))if(upperName===actualName.toUpperCase()){filePath=path.join(directory,actualName);break}}catch(err){console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`)}return filePath}else if(isUnixExecutable(stats))return filePath}}return""})}exports.tryGetExecutablePath=tryGetExecutablePath;function normalizeSeparators(p){return p=p||"",exports.IS_WINDOWS?(p=p.replace(/\//g,"\\"),p.replace(/\\\\+/g,"\\")):p.replace(/\/\/+/g,"/")}function isUnixExecutable(stats){return(stats.mode&1)>0||(stats.mode&8)>0&&stats.gid===process.getgid()||(stats.mode&64)>0&&stats.uid===process.getuid()}function getCmdPath(){var _a2;return(_a2=process.env.COMSPEC)!==null&&_a2!==void 0?_a2:"cmd.exe"}exports.getCmdPath=getCmdPath}});var require_io=__commonJS({"node_modules/.pnpm/@actions+io@1.1.3/node_modules/@actions/io/lib/io.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){k2===void 0&&(k2=k),Object.defineProperty(o,k2,{enumerable:!0,get:function(){return m[k]}})}:function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]}),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__awaiter=exports&&exports.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0});exports.findInPath=exports.which=exports.mkdirP=exports.rmRF=exports.mv=exports.cp=void 0;var assert_1=require("assert"),path=__importStar(require("path")),ioUtil=__importStar(require_io_util());function cp(source,dest,options={}){return __awaiter(this,void 0,void 0,function*(){let{force,recursive,copySourceDirectory}=readCopyOptions(options),destStat=(yield ioUtil.exists(dest))?yield ioUtil.stat(dest):null;if(destStat&&destStat.isFile()&&!force)return;let newDest=destStat&&destStat.isDirectory()&©SourceDirectory?path.join(dest,path.basename(source)):dest;if(!(yield ioUtil.exists(source)))throw new Error(`no such file or directory: ${source}`);if((yield ioUtil.stat(source)).isDirectory())if(recursive)yield cpDirRecursive(source,newDest,0,force);else throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`);else{if(path.relative(source,newDest)==="")throw new Error(`'${newDest}' and '${source}' are the same file`);yield copyFile(source,newDest,force)}})}exports.cp=cp;function mv(source,dest,options={}){return __awaiter(this,void 0,void 0,function*(){if(yield ioUtil.exists(dest)){let destExists=!0;if((yield ioUtil.isDirectory(dest))&&(dest=path.join(dest,path.basename(source)),destExists=yield ioUtil.exists(dest)),destExists)if(options.force==null||options.force)yield rmRF(dest);else throw new Error("Destination already exists")}yield mkdirP(path.dirname(dest)),yield ioUtil.rename(source,dest)})}exports.mv=mv;function rmRF(inputPath){return __awaiter(this,void 0,void 0,function*(){if(ioUtil.IS_WINDOWS&&/[*"<>|]/.test(inputPath))throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows');try{yield ioUtil.rm(inputPath,{force:!0,maxRetries:3,recursive:!0,retryDelay:300})}catch(err){throw new Error(`File was unable to be removed ${err}`)}})}exports.rmRF=rmRF;function mkdirP(fsPath){return __awaiter(this,void 0,void 0,function*(){assert_1.ok(fsPath,"a path argument must be provided"),yield ioUtil.mkdir(fsPath,{recursive:!0})})}exports.mkdirP=mkdirP;function which(tool,check){return __awaiter(this,void 0,void 0,function*(){if(!tool)throw new Error("parameter 'tool' is required");if(check){let result=yield which(tool,!1);if(!result)throw ioUtil.IS_WINDOWS?new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`):new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`);return result}let matches=yield findInPath(tool);return matches&&matches.length>0?matches[0]:""})}exports.which=which;function findInPath(tool){return __awaiter(this,void 0,void 0,function*(){if(!tool)throw new Error("parameter 'tool' is required");let extensions=[];if(ioUtil.IS_WINDOWS&&process.env.PATHEXT)for(let extension of process.env.PATHEXT.split(path.delimiter))extension&&extensions.push(extension);if(ioUtil.isRooted(tool)){let filePath=yield ioUtil.tryGetExecutablePath(tool,extensions);return filePath?[filePath]:[]}if(tool.includes(path.sep))return[];let directories=[];if(process.env.PATH)for(let p of process.env.PATH.split(path.delimiter))p&&directories.push(p);let matches=[];for(let directory of directories){let filePath=yield ioUtil.tryGetExecutablePath(path.join(directory,tool),extensions);filePath&&matches.push(filePath)}return matches})}exports.findInPath=findInPath;function readCopyOptions(options){let force=options.force==null?!0:options.force,recursive=!!options.recursive,copySourceDirectory=options.copySourceDirectory==null?!0:!!options.copySourceDirectory;return{force,recursive,copySourceDirectory}}function cpDirRecursive(sourceDir,destDir,currentDepth,force){return __awaiter(this,void 0,void 0,function*(){if(currentDepth>=255)return;currentDepth++,yield mkdirP(destDir);let files=yield ioUtil.readdir(sourceDir);for(let fileName of files){let srcFile=`${sourceDir}/${fileName}`,destFile=`${destDir}/${fileName}`;(yield ioUtil.lstat(srcFile)).isDirectory()?yield cpDirRecursive(srcFile,destFile,currentDepth,force):yield copyFile(srcFile,destFile,force)}yield ioUtil.chmod(destDir,(yield ioUtil.stat(sourceDir)).mode)})}function copyFile(srcFile,destFile,force){return __awaiter(this,void 0,void 0,function*(){if((yield ioUtil.lstat(srcFile)).isSymbolicLink()){try{yield ioUtil.lstat(destFile),yield ioUtil.unlink(destFile)}catch(e){e.code==="EPERM"&&(yield ioUtil.chmod(destFile,"0666"),yield ioUtil.unlink(destFile))}let symlinkFull=yield ioUtil.readlink(srcFile);yield ioUtil.symlink(symlinkFull,destFile,ioUtil.IS_WINDOWS?"junction":null)}else(!(yield ioUtil.exists(destFile))||force)&&(yield ioUtil.copyFile(srcFile,destFile))})}}});var require_toolrunner=__commonJS({"node_modules/.pnpm/@actions+exec@1.1.1/node_modules/@actions/exec/lib/toolrunner.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){k2===void 0&&(k2=k),Object.defineProperty(o,k2,{enumerable:!0,get:function(){return m[k]}})}:function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]}),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__awaiter=exports&&exports.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0});exports.argStringToArray=exports.ToolRunner=void 0;var os=__importStar(require("os")),events=__importStar(require("events")),child=__importStar(require("child_process")),path=__importStar(require("path")),io=__importStar(require_io()),ioUtil=__importStar(require_io_util()),timers_1=require("timers"),IS_WINDOWS=process.platform==="win32",ToolRunner=class extends events.EventEmitter{constructor(toolPath,args,options){if(super(),!toolPath)throw new Error("Parameter 'toolPath' cannot be null or empty.");this.toolPath=toolPath,this.args=args||[],this.options=options||{}}_debug(message){this.options.listeners&&this.options.listeners.debug&&this.options.listeners.debug(message)}_getCommandString(options,noPrefix){let toolPath=this._getSpawnFileName(),args=this._getSpawnArgs(options),cmd=noPrefix?"":"[command]";if(IS_WINDOWS)if(this._isCmdFile()){cmd+=toolPath;for(let a of args)cmd+=` ${a}`}else if(options.windowsVerbatimArguments){cmd+=`"${toolPath}"`;for(let a of args)cmd+=` ${a}`}else{cmd+=this._windowsQuoteCmdArg(toolPath);for(let a of args)cmd+=` ${this._windowsQuoteCmdArg(a)}`}else{cmd+=toolPath;for(let a of args)cmd+=` ${a}`}return cmd}_processLineBuffer(data,strBuffer,onLine){try{let s=strBuffer+data.toString(),n=s.indexOf(os.EOL);for(;n>-1;){let line=s.substring(0,n);onLine(line),s=s.substring(n+os.EOL.length),n=s.indexOf(os.EOL)}return s}catch(err){return this._debug(`error processing line. Failed with error ${err}`),""}}_getSpawnFileName(){return IS_WINDOWS&&this._isCmdFile()?process.env.COMSPEC||"cmd.exe":this.toolPath}_getSpawnArgs(options){if(IS_WINDOWS&&this._isCmdFile()){let argline=`/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`;for(let a of this.args)argline+=" ",argline+=options.windowsVerbatimArguments?a:this._windowsQuoteCmdArg(a);return argline+='"',[argline]}return this.args}_endsWith(str,end){return str.endsWith(end)}_isCmdFile(){let upperToolPath=this.toolPath.toUpperCase();return this._endsWith(upperToolPath,".CMD")||this._endsWith(upperToolPath,".BAT")}_windowsQuoteCmdArg(arg){if(!this._isCmdFile())return this._uvQuoteCmdArg(arg);if(!arg)return'""';let cmdSpecialChars=[" "," ","&","(",")","[","]","{","}","^","=",";","!","'","+",",","`","~","|","<",">",'"'],needsQuotes=!1;for(let char of arg)if(cmdSpecialChars.some(x=>x===char)){needsQuotes=!0;break}if(!needsQuotes)return arg;let reverse='"',quoteHit=!0;for(let i=arg.length;i>0;i--)reverse+=arg[i-1],quoteHit&&arg[i-1]==="\\"?reverse+="\\":arg[i-1]==='"'?(quoteHit=!0,reverse+='"'):quoteHit=!1;return reverse+='"',reverse.split("").reverse().join("")}_uvQuoteCmdArg(arg){if(!arg)return'""';if(!arg.includes(" ")&&!arg.includes(" ")&&!arg.includes('"'))return arg;if(!arg.includes('"')&&!arg.includes("\\"))return`"${arg}"`;let reverse='"',quoteHit=!0;for(let i=arg.length;i>0;i--)reverse+=arg[i-1],quoteHit&&arg[i-1]==="\\"?reverse+="\\":arg[i-1]==='"'?(quoteHit=!0,reverse+="\\"):quoteHit=!1;return reverse+='"',reverse.split("").reverse().join("")}_cloneExecOptions(options){options=options||{};let result={cwd:options.cwd||process.cwd(),env:options.env||process.env,silent:options.silent||!1,windowsVerbatimArguments:options.windowsVerbatimArguments||!1,failOnStdErr:options.failOnStdErr||!1,ignoreReturnCode:options.ignoreReturnCode||!1,delay:options.delay||1e4};return result.outStream=options.outStream||process.stdout,result.errStream=options.errStream||process.stderr,result}_getSpawnOptions(options,toolPath){options=options||{};let result={};return result.cwd=options.cwd,result.env=options.env,result.windowsVerbatimArguments=options.windowsVerbatimArguments||this._isCmdFile(),options.windowsVerbatimArguments&&(result.argv0=`"${toolPath}"`),result}exec(){return __awaiter(this,void 0,void 0,function*(){return!ioUtil.isRooted(this.toolPath)&&(this.toolPath.includes("/")||IS_WINDOWS&&this.toolPath.includes("\\"))&&(this.toolPath=path.resolve(process.cwd(),this.options.cwd||process.cwd(),this.toolPath)),this.toolPath=yield io.which(this.toolPath,!0),new Promise((resolve,reject)=>__awaiter(this,void 0,void 0,function*(){this._debug(`exec tool: ${this.toolPath}`),this._debug("arguments:");for(let arg of this.args)this._debug(` ${arg}`);let optionsNonNull=this._cloneExecOptions(this.options);!optionsNonNull.silent&&optionsNonNull.outStream&&optionsNonNull.outStream.write(this._getCommandString(optionsNonNull)+os.EOL);let state=new ExecState(optionsNonNull,this.toolPath);if(state.on("debug",message=>{this._debug(message)}),this.options.cwd&&!(yield ioUtil.exists(this.options.cwd)))return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`));let fileName=this._getSpawnFileName(),cp=child.spawn(fileName,this._getSpawnArgs(optionsNonNull),this._getSpawnOptions(this.options,fileName)),stdbuffer="";cp.stdout&&cp.stdout.on("data",data=>{this.options.listeners&&this.options.listeners.stdout&&this.options.listeners.stdout(data),!optionsNonNull.silent&&optionsNonNull.outStream&&optionsNonNull.outStream.write(data),stdbuffer=this._processLineBuffer(data,stdbuffer,line=>{this.options.listeners&&this.options.listeners.stdline&&this.options.listeners.stdline(line)})});let errbuffer="";if(cp.stderr&&cp.stderr.on("data",data=>{state.processStderr=!0,this.options.listeners&&this.options.listeners.stderr&&this.options.listeners.stderr(data),!optionsNonNull.silent&&optionsNonNull.errStream&&optionsNonNull.outStream&&(optionsNonNull.failOnStdErr?optionsNonNull.errStream:optionsNonNull.outStream).write(data),errbuffer=this._processLineBuffer(data,errbuffer,line=>{this.options.listeners&&this.options.listeners.errline&&this.options.listeners.errline(line)})}),cp.on("error",err=>{state.processError=err.message,state.processExited=!0,state.processClosed=!0,state.CheckComplete()}),cp.on("exit",code=>{state.processExitCode=code,state.processExited=!0,this._debug(`Exit code ${code} received from tool '${this.toolPath}'`),state.CheckComplete()}),cp.on("close",code=>{state.processExitCode=code,state.processExited=!0,state.processClosed=!0,this._debug(`STDIO streams have closed for tool '${this.toolPath}'`),state.CheckComplete()}),state.on("done",(error,exitCode)=>{stdbuffer.length>0&&this.emit("stdline",stdbuffer),errbuffer.length>0&&this.emit("errline",errbuffer),cp.removeAllListeners(),error?reject(error):resolve(exitCode)}),this.options.input){if(!cp.stdin)throw new Error("child process missing stdin");cp.stdin.end(this.options.input)}}))})}};exports.ToolRunner=ToolRunner;function argStringToArray(argString){let args=[],inQuotes=!1,escaped=!1,arg="";function append(c){escaped&&c!=='"'&&(arg+="\\"),arg+=c,escaped=!1}for(let i=0;i0&&(args.push(arg),arg="");continue}append(c)}return arg.length>0&&args.push(arg.trim()),args}exports.argStringToArray=argStringToArray;var ExecState=class _ExecState extends events.EventEmitter{constructor(options,toolPath){if(super(),this.processClosed=!1,this.processError="",this.processExitCode=0,this.processExited=!1,this.processStderr=!1,this.delay=1e4,this.done=!1,this.timeout=null,!toolPath)throw new Error("toolPath must not be empty");this.options=options,this.toolPath=toolPath,options.delay&&(this.delay=options.delay)}CheckComplete(){this.done||(this.processClosed?this._setResult():this.processExited&&(this.timeout=timers_1.setTimeout(_ExecState.HandleTimeout,this.delay,this)))}_debug(message){this.emit("debug",message)}_setResult(){let error;this.processExited&&(this.processError?error=new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`):this.processExitCode!==0&&!this.options.ignoreReturnCode?error=new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`):this.processStderr&&this.options.failOnStdErr&&(error=new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`))),this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.done=!0,this.emit("done",error,this.processExitCode)}static HandleTimeout(state){if(!state.done){if(!state.processClosed&&state.processExited){let message=`The STDIO streams did not close within ${state.delay/1e3} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`;state._debug(message)}state._setResult()}}}}});var require_exec=__commonJS({"node_modules/.pnpm/@actions+exec@1.1.1/node_modules/@actions/exec/lib/exec.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){k2===void 0&&(k2=k),Object.defineProperty(o,k2,{enumerable:!0,get:function(){return m[k]}})}:function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]}),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__awaiter=exports&&exports.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0});exports.getExecOutput=exports.exec=void 0;var string_decoder_1=require("string_decoder"),tr=__importStar(require_toolrunner());function exec3(commandLine,args,options){return __awaiter(this,void 0,void 0,function*(){let commandArgs=tr.argStringToArray(commandLine);if(commandArgs.length===0)throw new Error("Parameter 'commandLine' cannot be null or empty.");let toolPath=commandArgs[0];return args=commandArgs.slice(1).concat(args||[]),new tr.ToolRunner(toolPath,args,options).exec()})}exports.exec=exec3;function getExecOutput(commandLine,args,options){var _a,_b;return __awaiter(this,void 0,void 0,function*(){let stdout="",stderr="",stdoutDecoder=new string_decoder_1.StringDecoder("utf8"),stderrDecoder=new string_decoder_1.StringDecoder("utf8"),originalStdoutListener=(_a=options?.listeners)===null||_a===void 0?void 0:_a.stdout,originalStdErrListener=(_b=options?.listeners)===null||_b===void 0?void 0:_b.stderr,stdErrListener=data=>{stderr+=stderrDecoder.write(data),originalStdErrListener&&originalStdErrListener(data)},stdOutListener=data=>{stdout+=stdoutDecoder.write(data),originalStdoutListener&&originalStdoutListener(data)},listeners=Object.assign(Object.assign({},options?.listeners),{stdout:stdOutListener,stderr:stdErrListener}),exitCode=yield exec3(commandLine,args,Object.assign(Object.assign({},options),{listeners}));return stdout+=stdoutDecoder.end(),stderr+=stderrDecoder.end(),{exitCode,stdout,stderr}})}exports.getExecOutput=getExecOutput}});var core=__toESM(require_core()),import_exec2=__toESM(require_exec());var import_exec=__toESM(require_exec()),import_node_stream=require("node:stream"),StringStream=class extends import_node_stream.Writable{chunks=[];_write(chunk,_enc,next){this.chunks.push(Buffer.from(chunk)),next()}string(){return Buffer.concat(this.chunks).toString("utf-8")}},getStorePaths=async()=>{let outStream=new StringStream;return await(0,import_exec.exec)("nix",["path-info","--all"],{outStream}),outStream.string().split(` +`).filter(Boolean)};var push=async()=>{core.startGroup("Push to Attic");try{if(core.getInput("skip-push")==="true")core.info("Pushing to cache is disabled by skip-push");else{let cache=core.getInput("cache");core.info("Pushing to cache");let oldPaths=JSON.parse(core.getState("initial-paths")),addedPaths=(await getStorePaths()).filter(p=>!oldPaths.includes(p));await(0,import_exec2.exec)("attic",["push",cache,...addedPaths])}}catch(e){core.setFailed(`Action failed with error: ${e}`)}core.endGroup()};var main=async()=>{await push()};main(); diff --git a/src/utils.ts b/src/utils.ts index c7d433c..20f3862 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,21 +1,27 @@ import { exec } from "@actions/exec"; import { Writable } from "node:stream"; -const streamToString = (stream: Writable): Promise => { - const chunks: Buffer[] = []; - return new Promise((resolve, reject) => { - stream.on("data", (chunk) => chunks.push(Buffer.from(chunk))); - stream.on("error", (err) => reject(err)); - stream.on("end", () => resolve(Buffer.concat(chunks).toString("utf8"))); - }); -}; +class StringStream extends Writable { + chunks: Buffer[] = []; + + _write( + chunk: WithImplicitCoercion, + _enc: unknown, + next: () => unknown + ) { + this.chunks.push(Buffer.from(chunk)); + next(); + } + + string() { + return Buffer.concat(this.chunks).toString("utf-8"); + } +} export const getStorePaths = async () => { - const outStream = new Writable(); + const outStream = new StringStream(); await exec("nix", ["path-info", "--all"], { outStream }); - const paths = await streamToString(outStream) - .then((res) => res.split("\n")) - .then((paths) => paths.filter(Boolean)); + const paths = outStream.string().split("\n").filter(Boolean); return paths; };