@stacksjs/registry 0.11.10 → 0.11.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/server.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -13426,7 +13426,7 @@ host:${o}`:`host:${o}`,w=[e,a,g,y,"",h,"UNSIGNED-PAYLOAD"].join(`
|
|
|
13426
13426
|
`),x=((k,C,T,_)=>{let E=rn.createHmac("sha256",`AWS4${k}`).update(C).digest(),A=rn.createHmac("sha256",E).update(T).digest(),$=rn.createHmac("sha256",A).update(_).digest();return rn.createHmac("sha256",$).update("aws4_request").digest()})(s.secretAccessKey,u,this.region,"s3"),S=rn.createHmac("sha256",x).update(b).digest("hex");return m.set("X-Amz-Signature",S),`https://${o}${a}?${m.toString()}`}}var wB={aws:"us-east-1",backblaze:"us-west-004",hetzner:"fsn1"};function bB(e,t){switch(e){case"backblaze":return`s3.${t}.backblazeb2.com`;case"hetzner":return`${t}.your-objectstorage.com`;default:return}}function _n(...e){for(let t of e){let n=process.env[t];if(n)return n}return}function vB(e){let t,n;if(e==="backblaze")t=_n("B2_APPLICATION_KEY_ID","B2_KEY_ID","S3_ACCESS_KEY_ID","AWS_ACCESS_KEY_ID"),n=_n("B2_APPLICATION_KEY","B2_SECRET_KEY","S3_SECRET_ACCESS_KEY","AWS_SECRET_ACCESS_KEY");else if(e==="hetzner")t=_n("HETZNER_S3_ACCESS_KEY","HETZNER_ACCESS_KEY","S3_ACCESS_KEY_ID","AWS_ACCESS_KEY_ID"),n=_n("HETZNER_S3_SECRET_KEY","HETZNER_SECRET_KEY","S3_SECRET_ACCESS_KEY","AWS_SECRET_ACCESS_KEY");else t=_n("S3_ACCESS_KEY_ID"),n=_n("S3_SECRET_ACCESS_KEY");if(t&&n)return{accessKeyId:t,secretAccessKey:n,sessionToken:_n("AWS_SESSION_TOKEN")};return}function ot(e={}){let t=e.provider||_n("STORAGE_PROVIDER","OBJECT_STORAGE_PROVIDER")||"aws",n=e.region||(t==="backblaze"?_n("B2_REGION"):void 0)||(t==="hetzner"?_n("HETZNER_S3_REGION","HETZNER_REGION"):void 0)||_n("S3_REGION","AWS_REGION","AWS_DEFAULT_REGION")||wB[t],r=e.endpoint||_n("S3_ENDPOINT")||bB(t,n),i=e.forcePathStyle??_n("S3_FORCE_PATH_STYLE")==="true",s=vB(t);return{provider:t,region:n,endpoint:r,forcePathStyle:i,credentials:s,publicBaseUrl:(a)=>{let l=r||`s3.${n}.amazonaws.com`;return i?`https://${l}/${a}`:`https://${a}.${l}`}}}function et(e){return new sg(e.region,{endpoint:e.endpoint,forcePathStyle:e.forcePathStyle,credentials:e.credentials})}import{resolve as xB,relative as SB}from"path";function kB(e,t){let n=(s)=>{let o=s.indexOf("-");return{num:(o===-1?s:s.slice(0,o)).replace(/^v/,"").split(".").map((l)=>Number.parseInt(l,10)||0),pre:o===-1?null:s.slice(o+1)}},r=n(e),i=n(t);for(let s=0;s<Math.max(r.num.length,i.num.length);s++){let o=r.num[s]??0,a=i.num[s]??0;if(o!==a)return a-o}if(r.pre===null&&i.pre!==null)return-1;if(r.pre!==null&&i.pre===null)return 1;return(i.pre||"").localeCompare(r.pre||"")}function As(e){let t=e.replaceAll("@","").replaceAll("/","-");if(!t||t.length>214||t.includes("..")||/^[.\-]|[.\-]$/.test(t)||!/^[a-zA-Z0-9._-]+$/.test(t))throw Error(`Invalid package name: ${e}`);return t}class Ru{bucket;baseUrl;s3;constructor(e,t=ot(),n){this.bucket=e,this.baseUrl=n||t.publicBaseUrl(e),this.s3=et(t)}getKey(e,t){let n=As(e);if(!/^[a-zA-Z0-9._+-]+$/.test(t))throw Error(`Invalid version: ${t}`);return`packages/pantry/${n}/${t}/${n}-${t}.tgz`}async upload(e,t){return await this.s3.putObject({bucket:this.bucket,key:e,body:Buffer.from(t),contentType:"application/gzip"}),this.getUrl(e)}async download(e){let t=await this.s3.getObjectBuffer(this.bucket,e);if(!t||t.byteLength===0)throw Error(`S3 download returned empty data for key: ${e}`);return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}async exists(e){try{return await this.s3.headObject(this.bucket,e),!0}catch{return!1}}async delete(e){await this.s3.deleteObject(this.bucket,e)}getUrl(e){return`${this.baseUrl}/${e}`}async uploadPackage(e,t,n){let r=this.getKey(e,t);return this.upload(r,n)}async downloadPackage(e,t){let n=this.getKey(e,t);return this.download(n)}async packageExists(e,t){let n=this.getKey(e,t);return this.exists(n)}getPackageUrl(e,t){let n=this.getKey(e,t);return this.getUrl(n)}async listPackageVersions(e){let n=`packages/pantry/${e.replaceAll("@","").replaceAll("/","-")}/`,r=await this.s3.list({bucket:this.bucket,prefix:n}),i=new Set;for(let s of r){let o=s.Key?.match(/packages\/pantry\/[^/]+\/([^/]+)\//);if(o)i.add(o[1])}return Array.from(i).sort(kB)}getPresignedDownloadUrl(e,t,n=3600){let r=this.getKey(e,t);return this.s3.generatePresignedGetUrl(this.bucket,r,n)}getPresignedUploadUrl(e,t,n=3600){let r=this.getKey(e,t);return this.s3.generatePresignedPutUrl(this.bucket,r,"application/gzip",n)}async list(e){return(await this.s3.list({bucket:this.bucket,prefix:e,maxKeys:1000})).map((n)=>n.Key).filter(Boolean)}}class Lu{basePath;baseUrl;constructor(e,t){this.basePath=e,this.baseUrl=t}getFilePath(e){if(/[\x00-\x1f]/.test(e))throw Error(`Invalid characters in key: ${e}`);let t=xB(this.basePath,e);if(SB(this.basePath,t).startsWith(".."))throw Error(`Path traversal detected: ${e}`);return t}async upload(e,t){let n=this.getFilePath(e),r=n.substring(0,n.lastIndexOf("/"));if(r)await(await import("fs/promises")).mkdir(r,{recursive:!0}).catch((s)=>console.warn(`LocalStorage: mkdir failed for ${r}:`,s));return await Bun.write(n,t),this.getUrl(e)}async download(e){let t=this.getFilePath(e);return Bun.file(t).arrayBuffer()}async exists(e){let t=this.getFilePath(e);return Bun.file(t).exists()}async delete(e){let t=this.getFilePath(e);await(await import("fs/promises")).unlink(t).catch((r)=>{if(r.code!=="ENOENT")console.warn(`LocalStorage: delete failed for ${t}:`,r)})}getUrl(e){return`${this.baseUrl}/storage/${e}`}async list(e){let t=await import("fs/promises"),n=await import("path"),r=this.getFilePath(e),i=e.endsWith("/"),s=i?r:n.dirname(r),o=i?"":n.basename(r);try{let a=await t.readdir(s,{withFileTypes:!0}),l=[];for(let c of a){if(o&&!c.name.startsWith(o))continue;let u=n.join(s,c.name),f=i?e:e.slice(0,e.length-o.length);if(c.isDirectory()){let d=await t.readdir(u,{recursive:!0});for(let h of d)l.push(`${f}${c.name}/${h}`)}else l.push(`${f}${c.name}`)}return l}catch{return[]}}}import{createConnection as c_}from"net";import{createHash as zu}from"crypto";import{gunzipSync as _B}from"zlib";var h_=30000,p_=1073741824,m_=65536,EB=8192,u_=65536,AB=1048576,$B=536870912,CB=1e5;class Iu extends Error{observedSha256;constructor(e,t){super(e);this.observedSha256=t}}var at={total:0,byVerdict:{clean:0,blocked:0,review:0,error:0},bySurface:{package:0,commit:0,zig:0,php:0,binary:0,pkgx:0},durationMs:{total:0,max:0,average:0}};function Fu(e,t){if(!e)return t;let n=Number.parseInt(e,10);return Number.isSafeInteger(n)&&n>0?n:t}function Bu(e){return zu("sha256").update(Buffer.from(e)).digest("hex")}function Ar(e){return Math.max(0,Math.round(performance.now()-e))}function zn(e){return e.replace(/[\u0000-\u001f\u007f]/g," ").trim().slice(0,256)}function f_(e){if(!e||/^(?:COMMAND UNAVAILABLE|UNKNOWN COMMAND)$/i.test(e))return{};let[t,n]=e.split("/");return{engineVersion:zn(t),databaseVersion:n?zn(n):void 0}}function $r(e,t){return new Promise((n,r)=>{e.write(t,(i)=>i?r(i):n())})}class ag{enabled=!0;required=!0;socketPath;host;port;timeoutMs;maxBytes;chunkBytes;cachedVersion=null;constructor(e={}){this.socketPath=e.socketPath?.trim()||void 0,this.host=e.host||"127.0.0.1",this.port=e.port||3310,this.timeoutMs=e.timeoutMs||h_,this.maxBytes=e.maxBytes||p_,this.chunkBytes=e.chunkBytes||m_}async scan(e,t){let n=performance.now(),r=new Date().toISOString(),i=Bu(e);if(e.byteLength>this.maxBytes)return{verdict:"error",engine:"clamav",scannedAt:r,durationMs:Ar(n),artifactSha256:i,reason:`artifact exceeds scanner limit of ${this.maxBytes} bytes`};try{let s=await this.instream(new Uint8Array(e)),o=await this.version().catch(()=>{return}),a=f_(o);if(s==="stream: OK")return{verdict:"clean",engine:"clamav",scannedAt:r,durationMs:Ar(n),artifactSha256:i,...a};let l=s.match(/^stream:\s+(.+)\s+FOUND$/);if(l)return{verdict:"blocked",engine:"clamav",scannedAt:r,durationMs:Ar(n),artifactSha256:i,signature:zn(l[1]),...a};return{verdict:"error",engine:"clamav",scannedAt:r,durationMs:Ar(n),artifactSha256:i,...a,reason:`unexpected scanner response: ${zn(s)}`}}catch(s){return{verdict:"error",engine:"clamav",scannedAt:r,durationMs:Ar(n),artifactSha256:i,reason:zn(s.message||"scanner unavailable")}}}async scanStream(e,t,n){let r=performance.now(),i=new Date().toISOString();if(n.size>this.maxBytes)return{verdict:"error",engine:"clamav",scannedAt:i,durationMs:Ar(r),artifactSha256:n.sha256,reason:`artifact exceeds scanner limit of ${this.maxBytes} bytes`};try{let s=await this.instreamChunks(e,n),o=await this.version().catch(()=>{return}),a=f_(o);if(s==="stream: OK")return{verdict:"clean",engine:"clamav",scannedAt:i,durationMs:Ar(r),artifactSha256:n.sha256,...a};let l=s.match(/^stream:\s+(.+)\s+FOUND$/);if(l)return{verdict:"blocked",engine:"clamav",scannedAt:i,durationMs:Ar(r),artifactSha256:n.sha256,signature:zn(l[1]),...a};return{verdict:"error",engine:"clamav",scannedAt:i,durationMs:Ar(r),artifactSha256:n.sha256,reason:`unexpected scanner response: ${zn(s)}`,...a}}catch(s){let o=s instanceof Iu?s.observedSha256:n.sha256;return{verdict:"error",engine:"clamav",scannedAt:i,durationMs:Ar(r),artifactSha256:o,reason:zn(s.message||"scanner unavailable")}}}async health(){try{await this.ping();let e=await this.version(!0).catch(()=>{return}),t=e&&!/^(?:COMMAND UNAVAILABLE|UNKNOWN COMMAND)$/i.test(e)?e:void 0;return{enabled:!0,required:!0,ready:!0,engine:"clamav",...t?{version:t}:{}}}catch(e){return{enabled:!0,required:!0,ready:!1,engine:"clamav",reason:zn(e.message||"scanner unavailable")}}}async instream(e){let t=await this.connect();try{await $r(t,new TextEncoder().encode("zINSTREAM\x00"));for(let n=0;n<e.byteLength;n+=this.chunkBytes){let r=e.subarray(n,Math.min(n+this.chunkBytes,e.byteLength)),i=new Uint8Array(4);new DataView(i.buffer).setUint32(0,r.byteLength,!1),await $r(t,i),await $r(t,r)}return await $r(t,new Uint8Array(4)),await this.readResponse(t)}finally{t.destroy()}}async instreamChunks(e,t){let n=await this.connect(),r=zu("sha256"),i=0;try{await $r(n,new TextEncoder().encode("zINSTREAM\x00"));for await(let o of e){let a=o instanceof Uint8Array?o:new Uint8Array(o);if(i+=a.byteLength,i>this.maxBytes||i>t.size)throw Error("streamed artifact exceeded its declared size");r.update(a);for(let l=0;l<a.byteLength;l+=this.chunkBytes){let c=a.subarray(l,Math.min(l+this.chunkBytes,a.byteLength)),u=new Uint8Array(4);new DataView(u.buffer).setUint32(0,c.byteLength,!1),await $r(n,u),await $r(n,c)}}let s=r.digest("hex");if(i!==t.size)throw new Iu("streamed artifact size did not match the declared size",s);if(s!==t.sha256)throw new Iu("streamed artifact SHA-256 did not match the declared digest",s);return await $r(n,new Uint8Array(4)),await this.readResponse(n)}finally{n.destroy()}}async version(e=!1){if(!e&&this.cachedVersion&&this.cachedVersion.expiresAt>Date.now())return this.cachedVersion.value;let t=await this.connect();try{await $r(t,new TextEncoder().encode("zVERSION\x00"));let n=zn(await this.readResponse(t));return this.cachedVersion={value:n,expiresAt:Date.now()+300000},n}finally{t.destroy()}}async ping(){let e=await this.connect();try{await $r(e,new TextEncoder().encode("zPING\x00"));let t=await this.readResponse(e);if(t!=="PONG")throw Error(`unexpected scanner ping response: ${zn(t)}`)}finally{e.destroy()}}connect(){return new Promise((e,t)=>{let n=this.socketPath?c_(this.socketPath):c_({host:this.host,port:this.port}),r=setTimeout(()=>{n.destroy(),t(Error(`scanner connection timed out after ${this.timeoutMs}ms`))},this.timeoutMs);n.once("connect",()=>{clearTimeout(r),n.setTimeout(this.timeoutMs),n.on("timeout",()=>n.destroy(Error(`scanner timed out after ${this.timeoutMs}ms`))),e(n)}),n.once("error",(i)=>{clearTimeout(r),t(i)})})}readResponse(e){return new Promise((t,n)=>{let r=[],i=0,s=()=>{let o=Buffer.concat(r).toString("utf8").replace(/\0.*$/,"").trim();o?t(o):n(Error("empty scanner response"))};e.on("data",(o)=>{if(i+=o.byteLength,i>EB){n(Error("scanner response exceeded limit")),e.destroy();return}if(r.push(o),o.includes(0))s()}),e.once("end",s),e.once("error",n)})}}class lg{enabled=!1;required=!1;async scan(e){return{verdict:"clean",engine:"development-bypass",scannedAt:new Date().toISOString(),durationMs:0,artifactSha256:Bu(e)}}async scanStream(e,t,n){let r=zu("sha256"),i=0;for await(let a of e)r.update(a),i+=a.byteLength;let s=r.digest("hex"),o=i===n.size&&s===n.sha256;return{verdict:o?"clean":"error",engine:"development-bypass",scannedAt:new Date().toISOString(),durationMs:0,artifactSha256:s,...!o?{reason:"streamed artifact did not match its declared digest or size"}:{}}}async health(){return{enabled:!1,required:!1,ready:!0,engine:"development-bypass"}}}class Du{enabled=!1;required=!0;reason;constructor(e){this.reason=zn(e)}async scan(e){return{verdict:"error",engine:"unavailable",scannedAt:new Date().toISOString(),durationMs:0,artifactSha256:Bu(e),reason:this.reason}}async scanStream(e,t,n){return{verdict:"error",engine:"unavailable",scannedAt:new Date().toISOString(),durationMs:0,artifactSha256:n.sha256,reason:this.reason}}async health(){return{enabled:!1,required:!0,ready:!1,engine:"unavailable",reason:this.reason}}}function Wu(e=process.env){let t=e.NODE_ENV==="production",n=(e.PANTRY_MALWARE_SCANNING||(t?"required":"disabled")).toLowerCase();if(n==="disabled"){if(t&&e.PANTRY_ALLOW_UNSCANNED_PUBLISH!=="true")return new Du("malware scanning is disabled in production; set PANTRY_MALWARE_SCANNING=required or explicitly acknowledge PANTRY_ALLOW_UNSCANNED_PUBLISH=true");return new lg}if(n!=="required"&&n!=="clamav")return new Du(`unsupported PANTRY_MALWARE_SCANNING mode: ${n}`);return new ag({socketPath:e.CLAMD_SOCKET,host:e.CLAMD_HOST||"127.0.0.1",port:Fu(e.CLAMD_PORT,3310),timeoutMs:Fu(e.CLAMD_TIMEOUT_MS,h_),maxBytes:Fu(e.CLAMD_MAX_BYTES,p_),chunkBytes:Fu(e.CLAMD_CHUNK_BYTES,m_)})}class He extends Error{}function og(e,t,n){return Buffer.from(e.subarray(t,t+n)).toString("utf8").replace(/\0.*$/,"")}function TB(e,t){let n=og(e,t+124,12).trim();if(!/^[0-7]*$/.test(n))throw new He("archive contains an invalid tar size");let r=Number.parseInt(n||"0",8);if(!Number.isSafeInteger(r)||r<0)throw new He("archive contains an invalid tar size");return r}function MB(e){let t=e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+/g,"/");if(!t||t.startsWith("/")||t.split("/").includes(".."))throw new He("archive contains an unsafe path");return t}function OB(e){let t;try{t=_B(Buffer.from(e),{maxOutputLength:$B})}catch{throw new He("dual-use package must be a valid gzip-compressed tar archive")}let n=[],r=0;while(r+512<=t.byteLength){let i=t.subarray(r,r+512);if(i.every((d)=>d===0))break;let s=og(i,0,100),o=og(i,345,155),a=MB(o?`${o}/${s}`:s),l=String.fromCharCode(i[156]||48),c=TB(i,0),u=r+512,f=u+c;if(f>t.byteLength)throw new He("archive entry exceeds archive bounds");if(l==="0"||l==="\x00")n.push({name:a,data:t.subarray(u,f)});if(n.length>CB)throw new He("archive contains too many files");r=u+Math.ceil(c/512)*512}return n}function _l(e){if(Array.isArray(e))return`[${e.map(_l).join(",")}]`;if(e&&typeof e==="object"){let t=e;return`{${Object.keys(t).sort().map((n)=>`${JSON.stringify(n)}:${_l(t[n])}`).join(",")}}`}return JSON.stringify(e)}function d_(e){if(e===void 0)return;if(e===null||typeof e==="function"||typeof e==="symbol")throw new He("contentPolicy must be a non-null JSON value");let t=_l(e);if(!t||Buffer.byteLength(t)>4096)throw new He("contentPolicy exceeds 4096 bytes")}function cg(e,t,n){if(e===void 0){if(n)throw new He("contentPolicy and DISCLOSURE are required because this package previously declared dual-use content");return}d_(e);let r=OB(t),i=r.filter((c)=>c.name==="package.json"||c.name==="package/package.json");if(i.length!==1)throw new He("dual-use package must contain exactly one root package.json");if(i[0].data.byteLength>AB)throw new He("package.json exceeds 1MB");let s;try{s=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i[0].data))}catch{throw new He("package.json must contain valid UTF-8 JSON")}if(s.contentPolicy===void 0)throw new He("packaged package.json is missing contentPolicy");if(d_(s.contentPolicy),_l(s.contentPolicy)!==_l(e))throw new He("metadata contentPolicy does not match packaged package.json");let o=r.filter((c)=>c.name==="DISCLOSURE"||c.name==="package/DISCLOSURE");if(o.length!==1)throw new He("dual-use package must contain exactly one root DISCLOSURE file");let a=o[0].data;if(a.byteLength===0||a.byteLength>u_)throw new He(`DISCLOSURE must contain 1-${u_} bytes`);if(a.includes(0))throw new He("DISCLOSURE must contain text only");let l;try{l=new TextDecoder("utf-8",{fatal:!0}).decode(a)}catch{throw new He("DISCLOSURE must contain valid UTF-8 text")}if(!l.trim())throw new He("DISCLOSURE must not be blank");return{contentPolicy:e,disclosure:{sha256:zu("sha256").update(a).digest("hex"),size:a.byteLength}}}function pt(e){let{reason:t,...n}=e;return n}function g_(e,t){console.info(JSON.stringify({event:"package_malware_scan",surface:e.surface,package:e.name.slice(0,214),version:e.version?.slice(0,64),commit:e.commit?.slice(0,40),publisher:e.publisher?.slice(0,320),verdict:t.verdict,engine:t.engine,engineVersion:t.engineVersion,databaseVersion:t.databaseVersion,signature:t.signature,reason:t.reason,artifactSha256:t.artifactSha256,durationMs:t.durationMs,scannedAt:t.scannedAt}))}async function Bn(e,t,n){let r=await e.scan(t,n);return at.total++,at.byVerdict[r.verdict]++,at.bySurface[n.surface]++,at.durationMs.total+=r.durationMs,at.durationMs.max=Math.max(at.durationMs.max,r.durationMs),at.durationMs.average=Math.round(at.durationMs.total/at.total*100)/100,at.lastScanAt=r.scannedAt,g_(n,r),r}async function Uu(e,t,n,r){if(!e.scanStream)throw Error("configured malware scanner does not support streamed artifacts");let i=await e.scanStream(t,n,r);return at.total++,at.byVerdict[i.verdict]++,at.bySurface[n.surface]++,at.durationMs.total+=i.durationMs,at.durationMs.max=Math.max(at.durationMs.max,i.durationMs),at.durationMs.average=Math.round(at.durationMs.total/at.total*100)/100,at.lastScanAt=i.scannedAt,g_(n,i),i}function ug(){return structuredClone(at)}function y_(e=process.env){let t=e.PANTRY_REQUIRE_MALWARE_SCAN_ATTESTATION;if(t!==void 0)return["1","true","yes","on"].includes(t.trim().toLowerCase());return e.NODE_ENV==="production"}function Wn(e,t,n=process.env){if(!y_(n))return;let r=Bu(t);if(!e||e.verdict!=="clean"||e.artifactSha256!==r)throw Error("clean malware-scan attestation for the exact artifact bytes is required")}function Ii(e,t={}){if(e.verdict==="review")return Response.json({error:"Package requires security review before it can be published",code:"PACKAGE_REQUIRES_REVIEW",retryable:!1,scan:pt(e)},{status:202,headers:t});if(e.verdict==="blocked")return Response.json({error:"Package blocked by malware scanning",code:"MALWARE_DETECTED",retryable:!1,scan:pt(e)},{status:422,headers:t});return Response.json({error:"Package malware scanning is temporarily unavailable",code:"MALWARE_SCAN_UNAVAILABLE",retryable:!0,scan:pt(e)},{status:503,headers:{...t,"Retry-After":"60"}})}function jB(e){return typeof e==="string"&&e.length>0&&e.length<=64&&/^[a-zA-Z0-9._+-]+$/.test(e)}function NB(e){let t=e.toLowerCase();if(["localhost","0.0.0.0","[::1]","[::]"].includes(t))return!0;if(/^127\./.test(t))return!0;if(/^10\./.test(t))return!0;if(/^172\.(1[6-9]|2\d|3[01])\./.test(t))return!0;if(/^192\.168\./.test(t))return!0;if(/^169\.254\./.test(t))return!0;if(t.startsWith("[fc")||t.startsWith("[fd")||t==="[::1]")return!0;return!1}class El{config;tarballStorage;metadataStorage;get tarball(){return this.tarballStorage}constructor(e){this.config=e;let t=e.localStoragePath||"./.registry",r=Boolean(e.s3Bucket&&e.s3Bucket!=="local")?ot({provider:e.storageProvider,region:e.s3Region,endpoint:e.s3Endpoint,forcePathStyle:e.forcePathStyle}):void 0;if(r)this.tarballStorage=new Ru(e.s3Bucket,r,e.baseUrl);else this.tarballStorage=new Lu(w_(t,"tarballs"),e.baseUrl);let i=e.metadataBackend??(r&&r.provider!=="aws"?"object":void 0)??(e.dynamoTable&&e.dynamoTable!=="local"?"dynamodb":"file");if(i==="object"&&r)this.metadataStorage=new ig(et(r),e.s3Bucket,e.metadataKey);else if(i==="dynamodb"&&e.dynamoTable&&e.dynamoTable!=="local")this.metadataStorage=new kl(e.dynamoTable,e.s3Region||"us-east-1");else this.metadataStorage=new ju(w_(t,"metadata.json"))}async getPackage(e,t){let n=t?await this.metadataStorage.getPackageVersion(e,t):await this.getLatestVersion(e);if(n)return n;if(this.config.npmFallback)return Ou(e,t);return null}async getLatestVersion(e){let t=await this.metadataStorage.getPackage(e);if(!t)return null;return this.metadataStorage.getPackageVersion(e,t.latestVersion)}async listVersions(e){let t=await this.metadataStorage.listVersions(e);if(t.length>0)return t;if(this.config.npmFallback)return tg(e);return[]}async search(e,t=20){let n=e.slice(0,256),r=Math.min(Math.max(t,1),100),i=await this.metadataStorage.search(n,r);if(i.length>=t||!this.config.npmFallback)return i;let s=await ng(e,t-i.length),o=new Set(i.map((a)=>a.name));for(let a of s)if(!o.has(a.name))i.push(a);return i.slice(0,t)}async downloadTarball(e,t){let n=await this.metadataStorage.getPackageVersion(e,t);if(n?.tarballUrl)try{if(await this.metadataStorage.incrementDownloads(e,t),n.tarballUrl.startsWith(this.config.baseUrl)){let s=As(e),o=`packages/pantry/${s}/${t}/${s}-${t}.tgz`;return this.tarballStorage.download(o)}let r=new URL(n.tarballUrl);if(r.protocol!=="https:"||NB(r.hostname))throw Error(`Blocked tarball URL: ${r.hostname}`);let i=await fetch(n.tarballUrl);if(i.ok)return i.arrayBuffer()}catch{}if(this.config.npmFallback)return rg(e,t);return null}async publish(e,t,n){Wn(e.malwareScan,t);let r=As(e.name);if(!jB(e.version))throw Error(`Invalid package version: ${e.version}`);let i=`packages/pantry/${r}/${e.version}/${r}-${e.version}.tgz`;await this.tarballStorage.upload(i,t);let s=`${this.config.baseUrl}/packages/${encodeURIComponent(e.name)}/${e.version}/tarball`,o=await crypto.subtle.digest("SHA-256",t),l=`sha256:${Array.from(new Uint8Array(o)).map((c)=>c.toString(16).padStart(2,"0")).join("")}`;if(await this.metadataStorage.putVersion(e.name,e.version,{...e,tarballUrl:s,checksum:l,publishedAt:new Date().toISOString(),size:t.byteLength}),n&&n!=="_admin")await this.metadataStorage.setPackagePublisher(e.name,n)}async listPublisherPackages(e,t=50,n=!1){if(n)return this.metadataStorage.listAllRegistryPackages(t);return this.metadataStorage.listPackagesByPublisher(e,t)}async updatePublisherPackage(e,t,n,r=!1){let i=r?"_admin":t;return this.metadataStorage.updatePublisherPackage(e,i,n)}async getPublisherPackageRecord(e){return this.metadataStorage.getPackage(e)}async claimPublisherPackage(e,t){await this.metadataStorage.setPackagePublisher(e,t)}async exists(e,t){return await this.metadataStorage.getPackageVersion(e,t)!==null}async publishCommit(e,t,n,r){Wn(r?.malwareScan,n);let i=As(e);if(!/^[a-f0-9]{7,40}$/i.test(t))throw Error(`Invalid commit SHA: ${t}`);let s=`commits/${t}/${i}/${i}.tgz`,o=await this.tarballStorage.upload(s,n),a=await crypto.subtle.digest("SHA-256",n),c=`sha256:${Array.from(new Uint8Array(a)).map((f)=>f.toString(16).padStart(2,"0")).join("")}`,u={name:e,sha:t,tarballUrl:o,checksum:c,publishedAt:new Date().toISOString(),repository:r?.repository,packageDir:r?.packageDir,version:r?.version,size:n.byteLength,publishedBy:r?.publishedBy,malwareScan:r?.malwareScan};if(await this.metadataStorage.putCommitPublish(u),r?.publishedBy&&r.publishedBy!=="_admin")await this.metadataStorage.setCommitPublisher(e,t,r.publishedBy);return u}async getCommitPackage(e,t){try{let n=await this.metadataStorage.getCommitPublish(e,t);if(n)return n}catch{}if(e.length<40&&e.length>=7&&/^[a-f0-9]+$/i.test(e))try{let n=As(t),r=`commits/${e}`,s=(await this.tarballStorage.list(r)).find((o)=>o.includes(`/${n}/`));if(s){let a=s.split("/")[1];if(a&&a.startsWith(e)){let l=await this.metadataStorage.getCommitPublish(a,t).catch(()=>null);if(l)return l;return{name:t,sha:a,tarballUrl:this.tarballStorage.getUrl(s),checksum:"",publishedAt:new Date().toISOString()}}}}catch{}return null}async downloadCommitTarball(e,t){let n=await this.getCommitPackage(e,t);if(!n)return null;let r=As(t),i=n.sha||e;if(!/^[a-f0-9]{7,40}$/i.test(i))return null;let s=`commits/${i}/${r}/${r}.tgz`;try{return await this.tarballStorage.download(s)}catch{return null}}async getCommitPackages(e){let t=await this.metadataStorage.getCommitPackages(e);if(t.length===0)return null;return{sha:e,repository:t[0]?.repository,publishedAt:t[0]?.publishedAt||new Date().toISOString(),packages:t}}async getPackageCommits(e,t=20){return this.metadataStorage.getPackageCommits(e,t)}getStorageBackends(){return{tarball:this.tarballStorage,metadata:this.metadataStorage}}get metadata(){return this.metadataStorage}}function RB(e="http://localhost:3000"){return new El({s3Bucket:"local",dynamoTable:"local",baseUrl:e,npmFallback:!0,port:3000})}function LB(e){return new El({s3Bucket:e.s3Bucket,s3Region:e.region,storageProvider:e.storageProvider,s3Endpoint:e.s3Endpoint,forcePathStyle:e.forcePathStyle,dynamoTable:e.dynamoTable,metadataBackend:e.metadataBackend,baseUrl:e.baseUrl,npmFallback:e.npmFallback??!0})}function FB(){let e=process.env.S3_BUCKET||"local",t=process.env.DYNAMODB_TABLE||"pantry-registry",n=process.env.BASE_URL||"http://localhost:3000",r=process.env.NPM_FALLBACK!=="false";return new El({s3Bucket:e,s3Region:process.env.S3_REGION||process.env.AWS_REGION,storageProvider:process.env.STORAGE_PROVIDER,s3Endpoint:process.env.S3_ENDPOINT,forcePathStyle:process.env.S3_FORCE_PATH_STYLE==="true",dynamoTable:t,metadataBackend:process.env.METADATA_BACKEND,metadataKey:process.env.METADATA_KEY,baseUrl:n,npmFallback:r})}import{resolve as Bt,dirname as Qm,relative as D4}from"path";import{readFileSync as lge}from"fs";import{fileURLToPath as Hm}from"url";function IB(e){return e.toLocaleString("en-US")}function v_(e){let t=new Date,n=t.toISOString().split("T")[0],r=[];for(let i=e-1;i>=0;i--){let s=new Date(t.getTime()-i*24*60*60*1000);r.push(s.toISOString().split("T")[0])}return{startDate:r[0],endDate:n,dates:r}}function b_(e){switch(e){case"install":return"PACKAGE#";case"install_on_request":return"INSTALL_ON_REQUEST#";case"build_error":return"BUILD_ERROR#"}}function x_(e,t,n,r="install"){let i=Array.from(e.entries()).sort((o,a)=>a[1]-o[1]),s=i.reduce((o,[,a])=>o+a,0);return{category:r,total_items:i.length,start_date:t,end_date:n,total_count:s,items:i.map(([o,a],l)=>({number:l+1,formula:o,count:IB(a),percent:s>0?(a/s*100).toFixed(2):"0.00"}))}}class fg{db;tableName;constructor(e,t="us-east-1"){this.tableName=e,this.db=new V(t)}async trackEvent(e){let{packageName:t,category:n,timestamp:r}=e,i=r.split("T")[0],s=b_(n);await this.db.updateItem({TableName:this.tableName,Key:{PK:{S:`DAILY#${i}`},SK:{S:`${s}${t}`}},UpdateExpression:"SET downloads = if_not_exists(downloads, :zero) + :one, packageName = :name",ExpressionAttributeValues:{":zero":{N:"0"},":one":{N:"1"},":name":{S:t}}})}async trackDownload(e){let{packageName:t,version:n,timestamp:r}=e,i=r.split("T")[0];await this.db.updateItem({TableName:this.tableName,Key:{PK:{S:`PACKAGE#${t}`},SK:{S:"STATS"}},UpdateExpression:"SET totalDownloads = if_not_exists(totalDownloads, :zero) + :one, lastDownload = :ts, packageName = :name",ExpressionAttributeValues:{":zero":{N:"0"},":one":{N:"1"},":ts":{S:r},":name":{S:t}}}),await this.db.updateItem({TableName:this.tableName,Key:{PK:{S:`PACKAGE#${t}`},SK:{S:`VERSION#${n}`}},UpdateExpression:"SET downloads = if_not_exists(downloads, :zero) + :one, version = :ver",ExpressionAttributeValues:{":zero":{N:"0"},":one":{N:"1"},":ver":{S:n}}}),await this.db.updateItem({TableName:this.tableName,Key:{PK:{S:`DAILY#${i}`},SK:{S:`PACKAGE#${t}`}},UpdateExpression:"SET downloads = if_not_exists(downloads, :zero) + :one, packageName = :name",ExpressionAttributeValues:{":zero":{N:"0"},":one":{N:"1"},":name":{S:t}}})}async getPackageStats(e){let t=await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`PACKAGE#${e}`},SK:{S:"STATS"}}});if(!t.Item)return null;let n=V.unmarshal(t.Item),r=await this.db.query({TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :prefix)",ExpressionAttributeValues:{":pk":{S:`PACKAGE#${e}`},":prefix":{S:"VERSION#"}}}),i={};for(let l of r.Items){let c=V.unmarshal(l);if(c.version)i[c.version]=c.downloads||0}let s=new Date,o=0,a=0;for(let l=0;l<30;l++){let u=new Date(s.getTime()-l*24*60*60*1000).toISOString().split("T")[0];try{let f=await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`DAILY#${u}`},SK:{S:`PACKAGE#${e}`}}});if(f.Item){let h=V.unmarshal(f.Item).downloads||0;if(a+=h,l<7)o+=h}}catch(f){console.warn(`Warning: failed to fetch daily stats for ${e} on ${u}:`,f)}}return{packageName:e,totalDownloads:n.totalDownloads||0,weeklyDownloads:o,monthlyDownloads:a,versionDownloads:i,lastDownload:n.lastDownload}}async getTopPackages(e=10){let t=Math.max(1,Math.min(e,1000)),n=[],r;for(let i=0;i<20;i++){let s=await this.db.scan({TableName:this.tableName,FilterExpression:"SK = :stats",ExpressionAttributeValues:{":stats":{S:"STATS"}},Limit:100,ExclusiveStartKey:r});for(let o of s.Items){let a=V.unmarshal(o);n.push({name:a.packageName,downloads:a.totalDownloads||0})}if(!s.LastEvaluatedKey)break;r=s.LastEvaluatedKey}return n.sort((i,s)=>s.downloads-i.downloads),n.slice(0,t)}async getDownloadTimeline(e,t=30){let n=[],r=new Date;for(let i=t-1;i>=0;i--){let o=new Date(r.getTime()-i*24*60*60*1000).toISOString().split("T")[0];try{let a=await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`DAILY#${o}`},SK:{S:`PACKAGE#${e}`}}}),l=a.Item?V.unmarshal(a.Item).downloads||0:0;n.push({date:o,count:l})}catch{n.push({date:o,count:0})}}return n}async getCategoryAnalytics(e,t){let{startDate:n,endDate:r,dates:i}=v_(t),s=new Map,o=b_(e),a=25;for(let l=0;l<i.length;l+=25){let c=i.slice(l,l+25),u=await Promise.all(c.map((f)=>this.db.query({TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :prefix)",ExpressionAttributeValues:{":pk":{S:`DAILY#${f}`},":prefix":{S:o}}}).catch(()=>({Items:[],Count:0}))));for(let f of u)for(let d of f.Items){let h=V.unmarshal(d);if(h.packageName)s.set(h.packageName,(s.get(h.packageName)||0)+(h.downloads||0))}}return x_(s,n,r,e)}async trackMissingVersion(e,t,n,r){let i=new Date,s=Math.floor(i.getTime()/1000)+7776000;await this.db.updateItem({TableName:this.tableName,Key:{PK:{S:`VERSION_REQUEST#${e}`},SK:{S:`VERSION#${t}`}},UpdateExpression:"SET requestCount = if_not_exists(requestCount, :zero) + :one, lastRequestedAt = :ts, packageName = :name, version = :ver, #t = :ttl, isKnownVersion = :known",ExpressionAttributeNames:{"#t":"ttl"},ExpressionAttributeValues:{":zero":{N:"0"},":one":{N:"1"},":ts":{S:i.toISOString()},":name":{S:e},":ver":{S:t},":ttl":{N:String(s)},":known":{BOOL:r??!1}}})}async getMissingVersionRequests(e,t=20){let r=(await this.db.query({TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :prefix)",ExpressionAttributeValues:{":pk":{S:`VERSION_REQUEST#${e}`},":prefix":{S:"VERSION#"}}})).Items.map((i)=>{let s=V.unmarshal(i);return{packageName:s.packageName,version:s.version,requestCount:s.requestCount||0,lastRequestedAt:s.lastRequestedAt||"",isKnownVersion:s.isKnownVersion??!1}});return r.sort((i,s)=>s.requestCount-i.requestCount),r.slice(0,t)}async getAllMissingVersionRequests(e=100){let t=Math.max(1,Math.min(e,1000)),n=[],r;for(let i=0;i<20;i++){let s=await this.db.scan({TableName:this.tableName,FilterExpression:"begins_with(PK, :prefix)",ExpressionAttributeValues:{":prefix":{S:"VERSION_REQUEST#"}},Limit:500,ExclusiveStartKey:r});for(let o of s.Items){let a=V.unmarshal(o);n.push({packageName:a.packageName,version:a.version,requestCount:a.requestCount||0,lastRequestedAt:a.lastRequestedAt||"",isKnownVersion:a.isKnownVersion??!1})}if(!s.LastEvaluatedKey)break;r=s.LastEvaluatedKey}return n.sort((i,s)=>s.requestCount-i.requestCount),n.slice(0,t)}async getInstallAnalytics(e){return this.getCategoryAnalytics("install",e)}}class Pu{downloads=[];packageStats=new Map;dailyStats=new Map;categoryDailyStats=new Map;missingVersionRequests=new Map;onMutate(){}async trackEvent(e){let t=e.timestamp.split("T")[0],n=`${e.category}:${t}`;if(!this.categoryDailyStats.has(n))this.categoryDailyStats.set(n,new Map);let r=this.categoryDailyStats.get(n);r.set(e.packageName,(r.get(e.packageName)||0)+1),this.onMutate()}async trackDownload(e){if(this.downloads.push(e),this.downloads.length>1e4)this.downloads=this.downloads.slice(-5000);let t=this.packageStats.get(e.packageName)||{total:0,versions:{}};t.total++,t.versions[e.version]=(t.versions[e.version]||0)+1,t.lastDownload=e.timestamp,this.packageStats.set(e.packageName,t);let n=e.timestamp.split("T")[0];if(!this.dailyStats.has(n))this.dailyStats.set(n,new Map);let r=this.dailyStats.get(n);r.set(e.packageName,(r.get(e.packageName)||0)+1);let i=`install:${n}`;if(!this.categoryDailyStats.has(i))this.categoryDailyStats.set(i,new Map);let s=this.categoryDailyStats.get(i);s.set(e.packageName,(s.get(e.packageName)||0)+1),this.onMutate()}async getPackageStats(e){let t=this.packageStats.get(e);if(!t)return null;let n=new Date,r=0,i=0;for(let s=0;s<30;s++){let a=new Date(n.getTime()-s*24*60*60*1000).toISOString().split("T")[0],c=this.dailyStats.get(a)?.get(e)||0;if(i+=c,s<7)r+=c}return{packageName:e,totalDownloads:t.total,weeklyDownloads:r,monthlyDownloads:i,versionDownloads:t.versions,lastDownload:t.lastDownload}}async getTopPackages(e=10){return Array.from(this.packageStats.entries()).map(([n,r])=>({name:n,downloads:r.total})).sort((n,r)=>r.downloads-n.downloads).slice(0,e)}async getDownloadTimeline(e,t=30){let n=[],r=new Date;for(let i=t-1;i>=0;i--){let o=new Date(r.getTime()-i*24*60*60*1000).toISOString().split("T")[0],l=this.dailyStats.get(o)?.get(e)||0;n.push({date:o,count:l})}return n}async getCategoryAnalytics(e,t){let{startDate:n,endDate:r,dates:i}=v_(t),s=new Map;for(let o of i){let a=`${e}:${o}`,l=this.categoryDailyStats.get(a);if(l)for(let[c,u]of l)s.set(c,(s.get(c)||0)+u)}return x_(s,n,r,e)}async trackMissingVersion(e,t,n,r){let i=`${e}@${t}`,s=this.missingVersionRequests.get(i);if(s)s.requestCount++,s.lastRequestedAt=new Date().toISOString();else this.missingVersionRequests.set(i,{packageName:e,version:t,requestCount:1,lastRequestedAt:new Date().toISOString(),isKnownVersion:r??!1});if(this.missingVersionRequests.size>5000){let o=[...this.missingVersionRequests.entries()];for(let a=0;a<1000;a++)this.missingVersionRequests.delete(o[a][0])}this.onMutate()}async getMissingVersionRequests(e,t=20){let n=[];for(let[,r]of this.missingVersionRequests)if(r.packageName===e)n.push(r);return n.sort((r,i)=>i.requestCount-r.requestCount),n.slice(0,t)}async getAllMissingVersionRequests(e=100){let t=Array.from(this.missingVersionRequests.values());return t.sort((n,r)=>r.requestCount-n.requestCount),t.slice(0,e)}async getInstallAnalytics(e){return this.getCategoryAnalytics("install",e)}captureAnalyticsState(){let e=(t)=>Object.fromEntries([...t].map(([n,r])=>[n,Object.fromEntries(r)]));return{version:1,packageStats:Object.fromEntries(this.packageStats),dailyStats:e(this.dailyStats),categoryDailyStats:e(this.categoryDailyStats),missingVersionRequests:Object.fromEntries(this.missingVersionRequests)}}applyAnalyticsState(e){if(!e||typeof e!=="object")return;let t=(n)=>new Map(Object.entries(n??{}).map(([r,i])=>[r,new Map(Object.entries(i))]));if(e.packageStats)this.packageStats=new Map(Object.entries(e.packageStats));if(this.dailyStats=t(e.dailyStats),this.categoryDailyStats=t(e.categoryDailyStats),e.missingVersionRequests)this.missingVersionRequests=new Map(Object.entries(e.missingVersionRequests))}}function dg(e){if(e?.tableName)return new fg(e.tableName,e.region);return new Pu}import*as S_ from"crypto";class Cr{s3;bucket;key;getState;saveTimeout=null;savePromise=null;constructor(e,t,n,r){this.s3=e;this.bucket=t;this.key=n;this.getState=r}async load(){try{let e=await this.s3.getObjectBuffer(this.bucket,this.key);if(!e||e.byteLength===0)return null;return JSON.parse(e.toString("utf-8"))}catch(e){let t=e.message||"";if(!/\b40[34]\b/.test(t))console.error(`ObjectSnapshot: failed to load ${this.bucket}/${this.key}: ${t}. Starting empty.`);return null}}scheduleSave(){if(this.saveTimeout)clearTimeout(this.saveTimeout);this.saveTimeout=setTimeout(()=>{this.saveTimeout=null,this.save().catch((e)=>console.error(`ObjectSnapshot save failed (${this.key}):`,e.message))},1000)}async save(){while(this.savePromise)await this.savePromise;this.savePromise=this.s3.putObject({bucket:this.bucket,key:this.key,body:JSON.stringify(this.getState()),contentType:"application/json"}).then(()=>{});try{await this.savePromise}finally{this.savePromise=null}}async flush(){if(this.saveTimeout)clearTimeout(this.saveTimeout),this.saveTimeout=null;await this.save()}}function pg(e){let t=Buffer.isBuffer(e)?e:Buffer.from(e);return`1220${S_.createHash("sha256").update(t).digest("hex")}`}function DB(e){return/^1220[a-f0-9]{64}$/i.test(e)}function mg(e){let t={name:"",version:""},n=e.match(/\.name\s*=\s*(?:\.@"([^"]+)"|\.(\w+)|"([^"]+)")/);if(n)t.name=n[1]||n[2]||n[3];let r=e.match(/\.version\s*=\s*"([^"]+)"/);if(r)t.version=r[1];let i=e.match(/\.fingerprint\s*=\s*(0x[a-fA-F0-9]+)/);if(i)t.fingerprint=i[1];let s=e.match(/\.minimum_zig_version\s*=\s*"([^"]+)"/);if(s)t.minimum_zig_version=s[1];let o=e.match(/\.paths\s*=\s*\.{([\s\S]*?)}/);if(o){let l=o[1].match(/"([^"]+)"/g);if(l)t.paths=l.map((c)=>c.replace(/"/g,""))}if(!t.name)throw Error("Invalid build.zig.zon: missing .name field");if(!t.version)throw Error("Invalid build.zig.zon: missing .version field");return t}function yo(e,t,n){let r=t.replace(/\\/g,"\\\\").replace(/"/g,"\\\""),i=n.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");return`.${e} = .{
|
|
13427
13427
|
.url = "${r}",
|
|
13428
13428
|
.hash = "${i}",
|
|
13429
|
-
},`}function Al(e){return`zig fetch --save '${e.replace(/'/g,"'\\''")}'`}class qu{packages=new Map;tarballs=new Map;hashIndex=new Map;async count(){return this.packages.size}async getPackage(e,t){let n=this.packages.get(e);if(!n)return null;let r=t||n.latest;return n.versions[r]||null}async listVersions(e){let t=this.packages.get(e);if(!t)return[];return Object.keys(t.versions).sort((n,r)=>{let i=(l)=>{let c=l.indexOf("-"),u=(c===-1?l:l.slice(0,c)).split(".").map((d)=>{let h=Number.parseInt(d,10);return Number.isNaN(h)?0:h}),f=c===-1?null:l.slice(c+1);return{numeric:u,prerelease:f}},s=i(n),o=i(r),a=Math.max(s.numeric.length,o.numeric.length);for(let l=0;l<a;l++){let c=(o.numeric[l]??0)-(s.numeric[l]??0);if(c!==0)return c}if(s.prerelease===null&&o.prerelease!==null)return-1;if(s.prerelease!==null&&o.prerelease===null)return 1;if(s.prerelease!==null&&o.prerelease!==null)return s.prerelease<o.prerelease?1:s.prerelease>o.prerelease?-1:0;return 0})}async search(e,t=20){let n=e.toLowerCase(),r=[];for(let i of this.packages.values())if(i.name.toLowerCase().includes(n)||i.description?.toLowerCase().includes(n)||i.keywords?.some((s)=>s.toLowerCase().includes(n))){if(r.push(i),r.length>=t)break}return r}async publish(e,t){Wn(e.malwareScan,t),this.upsertRecord(e),this.tarballs.set(`${e.name}@${e.version}`,t),this.onMutate()}upsertRecord(e){let{name:t,version:n}=e,r=this.packages.get(t);if(!r)r={name:t,description:e.description,license:e.license,repository:e.repository,homepage:e.homepage,author:e.author,keywords:e.keywords,versions:{},latest:n,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};r.versions[n]=e,r.latest=n,r.updatedAt=new Date().toISOString(),this.packages.set(t,r),this.hashIndex.set(e.hash,{name:t,version:n})}onMutate(){}captureState(){return{packages:Object.fromEntries(this.packages),hashIndex:Object.fromEntries(this.hashIndex)}}applyState(e){if(e?.packages)this.packages=new Map(Object.entries(e.packages));if(e?.hashIndex)this.hashIndex=new Map(Object.entries(e.hashIndex))}async exists(e,t){return this.packages.get(e)?.versions[t]!==void 0}async downloadTarball(e,t){let n=`${e}@${t}`;return this.tarballs.get(n)||null}async getByHash(e){let t=this.hashIndex.get(e);if(!t)return null;let n=await this.getPackage(t.name,t.version);if(!n)return null;return{name:t.name,version:t.version,tarballUrl:n.tarballUrl}}async deletePackage(e){let t=this.packages.get(e);if(t){for(let n of Object.keys(t.versions)){let r=`${e}@${n}`;this.tarballs.delete(r);let i=t.versions[n];if(i?.hash)this.hashIndex.delete(i.hash)}this.packages.delete(e),this.onMutate()}}}function hg(e,t){let n=e.replaceAll("@","").replaceAll("/","-");if(!/^[a-z0-9._\-]+$/i.test(n)||n.includes(".."))throw Error(`Invalid package name: ${e}`);return`zig-packages/${n}/${t}/${n}-${t}.tar.gz`}class gg{tableName;db;s3;bucket;baseUrl;constructor(e){this.tableName=e.tableName,this.bucket=e.bucket,this.baseUrl=e.baseUrl,this.db=new V(e.region||"us-east-1"),this.s3=et(ot({region:e.region}))}marshal(e){return V.marshal(e)}unmarshal(e){return V.unmarshal(e)}s3Key(e,t){let n=e.replaceAll("@","").replaceAll("/","-");if(!/^[a-zA-Z0-9._\-]+$/.test(n)||n.includes(".."))throw Error(`Invalid package name: ${e}`);return`zig-packages/${n}/${t}/${n}-${t}.tar.gz`}async count(){return(await this.db.scan({TableName:this.tableName,FilterExpression:"begins_with(PK, :prefix) AND SK = :sk",ExpressionAttributeValues:{":prefix":{S:"ZIG_PACKAGE#"},":sk":{S:"METADATA"}},ProjectionExpression:"PK"})).Count||0}async getPackage(e,t){if(t){let i=await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`ZIG_PACKAGE#${e}`},SK:{S:`VERSION#${t}`}}});if(!i.Item)return null;let s=this.unmarshal(i.Item);return{name:s.name,version:s.version,description:s.description,tarballUrl:s.tarballUrl,hash:s.hash,publishedAt:s.publishedAt,license:s.license,repository:s.repository,homepage:s.homepage,author:s.author,keywords:s.keywords,malwareScan:s.malwareScan}}let n=await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`ZIG_PACKAGE#${e}`},SK:{S:"METADATA"}}});if(!n.Item)return null;let r=this.unmarshal(n.Item);if(!r.latest)return null;return this.getPackage(e,r.latest)}async listVersions(e){return(await this.db.query({TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :prefix)",ExpressionAttributeValues:{":pk":{S:`ZIG_PACKAGE#${e}`},":prefix":{S:"VERSION#"}}})).Items.map((n)=>{return this.unmarshal(n).version}).sort((n,r)=>{let i=(l)=>{let c=l.indexOf("-"),u=(c===-1?l:l.slice(0,c)).split(".").map((d)=>{let h=Number.parseInt(d,10);return Number.isNaN(h)?0:h}),f=c===-1?null:l.slice(c+1);return{numeric:u,prerelease:f}},s=i(n),o=i(r),a=Math.max(s.numeric.length,o.numeric.length);for(let l=0;l<a;l++){let c=(o.numeric[l]??0)-(s.numeric[l]??0);if(c!==0)return c}if(s.prerelease===null&&o.prerelease!==null)return-1;if(s.prerelease!==null&&o.prerelease===null)return 1;if(s.prerelease!==null&&o.prerelease!==null)return s.prerelease<o.prerelease?1:s.prerelease>o.prerelease?-1:0;return 0})}async search(e,t=20){let n=e.toLowerCase(),r=await this.db.scan({TableName:this.tableName,FilterExpression:"begins_with(PK, :prefix) AND SK = :sk",ExpressionAttributeValues:{":prefix":{S:"ZIG_PACKAGE#"},":sk":{S:"METADATA"}}}),i=[];for(let s of r.Items){let o=this.unmarshal(s),a=[o.name,o.description,...o.keywords||[]].filter(Boolean).join(" ").toLowerCase();if(!n||a.includes(n)){let l=await this.listVersions(o.name),c={};for(let u of l.slice(0,10)){let f=await this.getPackage(o.name,u);if(f)c[u]=f}if(i.push({name:o.name,description:o.description,license:o.license,repository:o.repository,homepage:o.homepage,author:o.author,keywords:o.keywords,versions:c,latest:o.latest,createdAt:o.createdAt,updatedAt:o.updatedAt}),i.length>=t)break}}return i}async publish(e,t){Wn(e.malwareScan,t);let{name:n,version:r}=e,i=new Date().toISOString(),s=this.s3Key(n,r);await this.s3.putObject({bucket:this.bucket,key:s,body:Buffer.from(t),contentType:"application/gzip"});let o=e.tarballUrl||`${this.baseUrl}/zig/packages/${encodeURIComponent(n)}/${r}/tarball`;await this.db.putItem({TableName:this.tableName,Item:this.marshal({PK:`ZIG_PACKAGE#${n}`,SK:`VERSION#${r}`,name:n,version:r,tarballUrl:o,hash:e.hash,description:e.description||"",license:e.license||"",repository:e.repository||"",homepage:e.homepage||"",author:e.author||"",keywords:e.keywords||[],publishedAt:e.publishedAt||i,malwareScan:e.malwareScan})}),await this.db.putItem({TableName:this.tableName,Item:this.marshal({PK:`ZIG_PACKAGE#${n}`,SK:"METADATA",name:n,latest:r,description:e.description||"",license:e.license||"",repository:e.repository||"",homepage:e.homepage||"",author:e.author||"",keywords:e.keywords||[],createdAt:i,updatedAt:i})}),await this.db.putItem({TableName:this.tableName,Item:this.marshal({PK:`ZIG_HASH#${e.hash}`,SK:"ZIG_HASH",name:n,version:r,tarballUrl:o})})}async exists(e,t){return(await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`ZIG_PACKAGE#${e}`},SK:{S:`VERSION#${t}`}}})).Item!==void 0}async downloadTarball(e,t){let n=this.s3Key(e,t);try{let r=await this.s3.getObjectBuffer(this.bucket,n);return r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)}catch{return null}}async getByHash(e){let t=await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`ZIG_HASH#${e}`},SK:{S:"ZIG_HASH"}}});if(!t.Item)return null;let n=this.unmarshal(t.Item);return{name:n.name,version:n.version,tarballUrl:n.tarballUrl}}async deletePackage(e){let t=await this.db.query({TableName:this.tableName,KeyConditionExpression:"PK = :pk",ExpressionAttributeValues:{":pk":{S:`ZIG_PACKAGE#${e}`}}});for(let n of t.Items){let r=this.unmarshal(n);if(r.hash)await this.db.deleteItem({TableName:this.tableName,Key:{PK:{S:`ZIG_HASH#${r.hash}`},SK:{S:"ZIG_HASH"}}});if(r.version){let i=this.s3Key(e,r.version);try{await this.s3.deleteObject(this.bucket,i)}catch{}}await this.db.deleteItem({TableName:this.tableName,Key:{PK:{S:`ZIG_PACKAGE#${e}`},SK:n.SK}})}}}class k_ extends qu{s3;bucket;baseUrl;snapshot;loaded;constructor(e){super();this.s3=e.s3,this.bucket=e.bucket,this.baseUrl=e.baseUrl,this.snapshot=new Cr(this.s3,this.bucket,e.key||"zig-packages/registry-index.json",()=>this.captureState()),this.loaded=this.snapshot.load().then((t)=>{if(t)this.applyState(t)})}ready(){return this.loaded}onMutate(){this.snapshot.scheduleSave()}async flush(){await this.snapshot.flush()}async publish(e,t){Wn(e.malwareScan,t);let n=hg(e.name,e.version);await this.s3.putObject({bucket:this.bucket,key:n,body:Buffer.from(t),contentType:"application/gzip"});let r=e;if(!r.tarballUrl)r={...e,tarballUrl:`${this.baseUrl}/zig/packages/${encodeURIComponent(e.name)}/${e.version}/tarball`};this.upsertRecord(r),this.onMutate()}async downloadTarball(e,t){try{let n=await this.s3.getObjectBuffer(this.bucket,hg(e,t));return n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}catch{return null}}async deletePackage(e){let t=await this.listVersions(e);for(let n of t)try{await this.s3.deleteObject(this.bucket,hg(e,n))}catch{}await super.deletePackage(e)}}function Gu(){let e=process.env.S3_BUCKET,t=process.env.BASE_URL||"http://localhost:3000";if(!e||e==="local")return new qu;let n=ot(),r=process.env.DYNAMODB_TABLE;if(n.provider==="aws"&&r&&r!=="local")return new gg({tableName:r,bucket:e,region:n.region,baseUrl:t});return new k_({s3:et(n),bucket:e,baseUrl:t})}async function __(e,t,n,r,i,s,o,a){let l=e.replace(/^\/zig/,"");if(l==="/search"&&t.method==="GET"){let d=n.searchParams.get("q")||"";if(d.length>256)return Response.json({error:"Search query too long"},{status:400,headers:s});let h=Math.min(Number.parseInt(n.searchParams.get("limit")||"20",10),100),p=await r.search(d,h);return Response.json({results:p.map((m)=>({name:m.name,version:m.latest,description:m.description,keywords:m.keywords,author:m.author}))},{headers:s})}let c=l.match(/^\/hash\/([a-f0-9]+)$/i);if(c&&t.method==="GET"){let d=c[1],h=await r.getByHash(d);if(!h)return Response.json({error:"Package not found for this hash"},{status:404,headers:s});return Response.json({...h,hash:d,dependency:yo(h.name,h.tarballUrl,d)},{headers:s})}if(l==="/publish"&&t.method==="POST"){if(!a)throw Error("malware scanner is required for publishing");return BB(t,r,i,s,o,a)}let u=l.match(/^\/packages\/([^/]+)$/);if(u&&t.method==="DELETE"){let d=E_(t.headers.get("authorization"));if(!d.valid)return Response.json({error:d.error},{status:401,headers:s});let h=decodeURIComponent(u[1]);if(h.includes("..")||/[\x00-\x1f]/.test(h))return Response.json({error:"Invalid package name"},{status:400,headers:s});return await r.deletePackage(h),Response.json({success:!0,message:`Deleted ${h}`},{headers:s})}let f=l.match(/^\/packages\/([^/]+)(?:\/(.+))?$/);if(f){let d=decodeURIComponent(f[1]);if(d.includes("..")||/[\x00-\x1f]/.test(d))return Response.json({error:"Invalid package name"},{status:400,headers:s});let h=f[2];if(h==="versions"&&t.method==="GET"){let p=await r.listVersions(d);return Response.json({name:d,versions:p},{headers:s})}if(h?.endsWith("/tarball")&&t.method==="GET"){let p=h.replace("/tarball",""),m=await r.downloadTarball(d,p);if(!m)return Response.json({error:"Package not found"},{status:404,headers:s});return o?.trackDownload({packageName:d,version:p,timestamp:new Date().toISOString(),userAgent:t.headers.get("user-agent")||void 0}).catch((g)=>console.warn("Analytics tracking failed:",g)),new Response(m,{headers:{...s,"Content-Type":"application/gzip","Content-Disposition":`attachment; filename="${d}-${p}.tar.gz"`}})}if(h&&!h.includes("/")&&t.method==="GET"){let p=await r.getPackage(d,h);if(!p)return Response.json({error:"Package version not found"},{status:404,headers:s});return Response.json({...p,fetchCommand:Al(p.tarballUrl),dependency:yo(d,p.tarballUrl,p.hash)},{headers:s})}if(!h&&t.method==="GET"){let p=await r.getPackage(d);if(!p)return Response.json({error:"Package not found"},{status:404,headers:s});return Response.json({...p,fetchCommand:Al(p.tarballUrl),dependency:yo(d,p.tarballUrl,p.hash)},{headers:s})}}return null}function zB(){return process.env.PANTRY_REGISTRY_TOKEN||process.env.PANTRY_TOKEN}function E_(e){let t=zB();if(!t)return{valid:!1,error:"Server misconfigured \u2014 no registry token set"};if(!e)return{valid:!1,error:"Authorization required"};let n=e.startsWith("Bearer ")?e.slice(7):e,r=Math.max(n.length,t.length),i=Buffer.alloc(r),s=Buffer.alloc(r);if(Buffer.from(n).copy(i),Buffer.from(t).copy(s),!Q("crypto").timingSafeEqual(i,s)||n.length!==t.length)return{valid:!1,error:"Invalid token"};return{valid:!0}}async function BB(e,t,n,r,i,s){let o=e.headers.get("content-type")||"",a=e.headers.get("authorization"),l=E_(a);if(!l.valid)return Response.json({error:l.error},{status:401,headers:r});if(o.includes("multipart/form-data")){let c=await e.formData(),u=c.get("tarball"),f=c.get("manifest"),d=c.get("description");if(!u||!(u instanceof File))return Response.json({error:"Missing tarball"},{status:400,headers:r});if(u.size>52428800)return Response.json({error:"Tarball exceeds maximum size of 50MB"},{status:413,headers:r});let h=await u.arrayBuffer(),p=pg(h),m,g;if(f&&typeof f==="string"){let x=mg(f);m=x.name,g=x.version}else{let S=u.name.match(/^(.+)-(\d+\.\d+\.\d+)\.tar\.gz$/);if(!S)return Response.json({error:"Could not determine package name/version. Provide manifest or use name-version.tar.gz filename."},{status:400,headers:r});m=S[1],g=S[2]}if(m=m.replace(/_/g,"-"),await t.exists(m,g))return Response.json({error:"Version already exists"},{status:409,headers:r});if(!s)throw Error("malware scanner is required for publishing");let w=await Bn(s,h,{surface:"zig",name:m,version:g,publisher:"_admin"});if(w.verdict!=="clean")return Ii(w,r);let b=`${n}/zig/packages/${encodeURIComponent(m)}/${g}/tarball`,v={name:m,version:g,description:typeof d==="string"?d:void 0,tarballUrl:b,hash:p,publishedAt:new Date().toISOString(),malwareScan:w};return await t.publish(v,h),i?.trackEvent({packageName:m,category:"install_on_request",timestamp:new Date().toISOString(),version:g}).catch((x)=>console.warn("Analytics tracking failed:",x)),Response.json({success:!0,message:`Published ${m}@${g}`,hash:p,tarballUrl:b,fetchCommand:Al(b),dependency:yo(m,b,p),scan:pt(w)},{status:201,headers:r})}return Response.json({error:"Unsupported content type. Use multipart/form-data."},{status:415,headers:r})}import*as A_ from"crypto";function wg(e){let t=Buffer.isBuffer(e)?e:Buffer.from(e);return A_.createHash("sha256").update(t).digest("hex")}function bg(e){let t;try{t=JSON.parse(e)}catch{throw Error("Invalid composer.json: malformed JSON")}if(!t.name||typeof t.name!=="string"||!t.name.includes("/"))throw Error("Invalid composer.json: missing or invalid name (must be vendor/package format)");let n={name:t.name};if(t.version)n.version=t.version;if(t.description)n.description=t.description;if(t.license)n.license=t.license;if(t.type)n.type=t.type;if(t.keywords)n.keywords=t.keywords;if(t.authors)n.authors=t.authors;if(t.require)n.require=t.require;if(t["require-dev"])n["require-dev"]=t["require-dev"];if(t.autoload)n.autoload=t.autoload;if(t.homepage)n.homepage=t.homepage;if(t["minimum-stability"])n["minimum-stability"]=t["minimum-stability"];return n}function $l(e,t){let n=e.replace(/[^a-z0-9/_.-]/gi,""),r=t.replace(/[^a-z0-9._-]/gi,"");return`composer require '${n}:^${r}'`}class Xu{packages=new Map;tarballs=new Map;isNewerPhpVersion(e,t){let n=(s)=>{let o=s.indexOf("-"),a=(o===-1?s:s.slice(0,o)).replace(/^v/,"").split(".").map((c)=>Number.parseInt(c,10)||0),l=o===-1?null:s.slice(o+1);return{numeric:a,prerelease:l}},r=n(e),i=n(t);for(let s=0;s<Math.max(r.numeric.length,i.numeric.length);s++){let o=r.numeric[s]??0,a=i.numeric[s]??0;if(o!==a)return o>a}if(r.prerelease===null&&i.prerelease!==null)return!0;if(r.prerelease!==null&&i.prerelease===null)return!1;return!1}async count(){return this.packages.size}async getPackage(e,t){let n=this.packages.get(e);if(!n)return null;let r=t||n.latest;return n.versions[r]||null}async listVersions(e){let t=this.packages.get(e);if(!t)return[];return Object.keys(t.versions).sort((n,r)=>{let[i,s,o]=n.split(".").map(Number),[a,l,c]=r.split(".").map(Number);if(i!==a)return a-i;if(s!==l)return l-s;return c-o})}async search(e,t=20){let n=e.toLowerCase(),r=[];for(let i of this.packages.values())if(i.name.toLowerCase().includes(n)||i.description?.toLowerCase().includes(n)||i.keywords?.some((s)=>s.toLowerCase().includes(n))){if(r.push(i),r.length>=t)break}return r}async publish(e,t){Wn(e.malwareScan,t),this.upsertRecord(e),this.tarballs.set(`${e.name}@${e.version}`,t),this.onMutate()}upsertRecord(e){let{name:t,version:n}=e,r=this.packages.get(t);if(!r)r={name:t,description:e.description,license:e.license,type:e.type,keywords:e.keywords,authors:e.authors,homepage:e.homepage,repository:e.repository,versions:{},latest:n,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};if(r.versions[n]=e,!r.latest||this.isNewerPhpVersion(n,r.latest))r.latest=n;r.updatedAt=new Date().toISOString(),this.packages.set(t,r)}onMutate(){}captureState(){return{packages:Object.fromEntries(this.packages)}}applyState(e){if(e?.packages)this.packages=new Map(Object.entries(e.packages))}async exists(e,t){return this.packages.get(e)?.versions[t]!==void 0}async downloadTarball(e,t){let n=`${e}@${t}`;return this.tarballs.get(n)||null}async deletePackage(e){let t=this.packages.get(e);if(t){for(let n of Object.keys(t.versions)){let r=`${e}@${n}`;this.tarballs.delete(r)}this.packages.delete(e),this.onMutate()}}}function yg(e,t){let n=e.replaceAll("/","-").replaceAll("@","");return`php-packages/${n}/${t}/${n}-${t}.tar.gz`}class vg{tableName;db;s3;bucket;baseUrl;constructor(e){this.tableName=e.tableName,this.bucket=e.bucket,this.baseUrl=e.baseUrl,this.db=new V(e.region||"us-east-1"),this.s3=et(ot({region:e.region}))}marshal(e){return V.marshal(e)}unmarshal(e){return V.unmarshal(e)}s3Key(e,t){let n=e.replaceAll("/","-").replaceAll("@","");return`php-packages/${n}/${t}/${n}-${t}.tar.gz`}async count(){return(await this.db.scan({TableName:this.tableName,FilterExpression:"begins_with(PK, :prefix) AND SK = :sk",ExpressionAttributeValues:{":prefix":{S:"PHP_PACKAGE#"},":sk":{S:"METADATA"}},ProjectionExpression:"PK"})).Count||0}async getPackage(e,t){if(t){let i=await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`PHP_PACKAGE#${e}`},SK:{S:`VERSION#${t}`}}});if(!i.Item)return null;let s=this.unmarshal(i.Item);return{name:s.name,version:s.version,description:s.description,tarballUrl:s.tarballUrl,checksum:s.checksum,publishedAt:s.publishedAt,license:s.license,type:s.type,keywords:s.keywords,authors:s.authors,homepage:s.homepage,repository:s.repository,require:s.require,malwareScan:s.malwareScan}}let n=await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`PHP_PACKAGE#${e}`},SK:{S:"METADATA"}}});if(!n.Item)return null;let r=this.unmarshal(n.Item);if(!r.latest)return null;return this.getPackage(e,r.latest)}async listVersions(e){return(await this.db.query({TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :prefix)",ExpressionAttributeValues:{":pk":{S:`PHP_PACKAGE#${e}`},":prefix":{S:"VERSION#"}}})).Items.map((n)=>{return this.unmarshal(n).version}).sort((n,r)=>{let[i,s,o]=n.split(".").map(Number),[a,l,c]=r.split(".").map(Number);return a!==i?a-i:l!==s?l-s:c-o})}async search(e,t=20){let n=e.toLowerCase(),r=await this.db.scan({TableName:this.tableName,FilterExpression:"begins_with(PK, :prefix) AND SK = :sk",ExpressionAttributeValues:{":prefix":{S:"PHP_PACKAGE#"},":sk":{S:"METADATA"}}}),i=[];for(let s of r.Items){let o=this.unmarshal(s),a=[o.name,o.description,...o.keywords||[]].filter(Boolean).join(" ").toLowerCase();if(!n||a.includes(n)){let l=await this.listVersions(o.name),c={};for(let u of l.slice(0,10)){let f=await this.getPackage(o.name,u);if(f)c[u]=f}if(i.push({name:o.name,description:o.description,license:o.license,type:o.type,keywords:o.keywords,authors:o.authors,homepage:o.homepage,repository:o.repository,versions:c,latest:o.latest,createdAt:o.createdAt,updatedAt:o.updatedAt}),i.length>=t)break}}return i}async publish(e,t){Wn(e.malwareScan,t);let{name:n,version:r}=e,i=new Date().toISOString(),s=this.s3Key(n,r);await this.s3.putObject({bucket:this.bucket,key:s,body:Buffer.from(t),contentType:"application/gzip"});let o=n.split("/").map(encodeURIComponent).join("/"),a=e.tarballUrl||`${this.baseUrl}/php/packages/${o}/${r}/tarball`;await this.db.putItem({TableName:this.tableName,Item:this.marshal({PK:`PHP_PACKAGE#${n}`,SK:`VERSION#${r}`,name:n,version:r,tarballUrl:a,checksum:e.checksum,description:e.description||"",license:e.license||"",type:e.type||"",keywords:e.keywords||[],authors:e.authors||[],homepage:e.homepage||"",repository:e.repository||"",require:e.require||{},publishedAt:e.publishedAt||i,malwareScan:e.malwareScan})}),await this.db.putItem({TableName:this.tableName,Item:this.marshal({PK:`PHP_PACKAGE#${n}`,SK:"METADATA",name:n,latest:r,description:e.description||"",license:e.license||"",type:e.type||"",keywords:e.keywords||[],authors:e.authors||[],homepage:e.homepage||"",repository:e.repository||"",createdAt:i,updatedAt:i})})}async exists(e,t){return(await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`PHP_PACKAGE#${e}`},SK:{S:`VERSION#${t}`}}})).Item!==void 0}async downloadTarball(e,t){let n=this.s3Key(e,t);try{let r=await this.s3.getObjectBuffer(this.bucket,n);return r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)}catch{return null}}async deletePackage(e){let t=await this.db.query({TableName:this.tableName,KeyConditionExpression:"PK = :pk",ExpressionAttributeValues:{":pk":{S:`PHP_PACKAGE#${e}`}}});for(let n of t.Items){let r=this.unmarshal(n);if(r.version){let i=this.s3Key(e,r.version);try{await this.s3.deleteObject(this.bucket,i)}catch{}}await this.db.deleteItem({TableName:this.tableName,Key:{PK:{S:`PHP_PACKAGE#${e}`},SK:n.SK}})}}}class $_ extends Xu{s3;bucket;baseUrl;snapshot;loaded;constructor(e){super();this.s3=e.s3,this.bucket=e.bucket,this.baseUrl=e.baseUrl,this.snapshot=new Cr(this.s3,this.bucket,e.key||"php-packages/registry-index.json",()=>this.captureState()),this.loaded=this.snapshot.load().then((t)=>{if(t)this.applyState(t)})}ready(){return this.loaded}onMutate(){this.snapshot.scheduleSave()}async flush(){await this.snapshot.flush()}async publish(e,t){Wn(e.malwareScan,t);let n=yg(e.name,e.version);await this.s3.putObject({bucket:this.bucket,key:n,body:Buffer.from(t),contentType:"application/gzip"});let r=e;if(!r.tarballUrl){let i=e.name.split("/").map(encodeURIComponent).join("/");r={...e,tarballUrl:`${this.baseUrl}/php/packages/${i}/${e.version}/tarball`}}this.upsertRecord(r),this.onMutate()}async downloadTarball(e,t){try{let n=await this.s3.getObjectBuffer(this.bucket,yg(e,t));return n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}catch{return null}}async deletePackage(e){let t=await this.listVersions(e);for(let n of t)try{await this.s3.deleteObject(this.bucket,yg(e,n))}catch{}await super.deletePackage(e)}}function Vu(){let e=process.env.S3_BUCKET,t=process.env.BASE_URL||"http://localhost:3000";if(!e||e==="local")return new Xu;let n=ot(),r=process.env.DYNAMODB_TABLE;if(n.provider==="aws"&&r&&r!=="local")return new vg({tableName:r,bucket:e,region:n.region,baseUrl:t});return new $_({s3:et(n),bucket:e,baseUrl:t})}async function C_(e,t,n,r,i,s,o,a){let l=e.replace(/^\/php/,"");if(l==="/search"&&t.method==="GET"){let f=n.searchParams.get("q")||"",d=Math.min(Number.parseInt(n.searchParams.get("limit")||"20",10),100),h=await r.search(f,d);return Response.json({results:h.map((p)=>({name:p.name,version:p.latest,description:p.description,keywords:p.keywords,authors:p.authors,type:p.type}))},{headers:s})}if(l==="/publish"&&t.method==="POST"){if(!a)throw Error("malware scanner is required for publishing");return UB(t,r,i,s,o,a)}let c=l.match(/^\/packages\/([^/]+)\/([^/]+)$/);if(c&&t.method==="DELETE"){let f=T_(t.headers.get("authorization"));if(!f.valid)return Response.json({error:f.error},{status:401,headers:s});let d=`${decodeURIComponent(c[1])}/${decodeURIComponent(c[2])}`;return await r.deletePackage(d),Response.json({success:!0,message:`Deleted ${d}`},{headers:s})}let u=l.match(/^\/packages\/([^/]+)\/([^/]+)(?:\/(.+))?$/);if(u){let f=`${decodeURIComponent(u[1])}/${decodeURIComponent(u[2])}`,d=u[3];if(d==="versions"&&t.method==="GET"){let h=await r.listVersions(f);return Response.json({name:f,versions:h},{headers:s})}if(d?.endsWith("/tarball")&&t.method==="GET"){let h=d.replace("/tarball",""),p=await r.downloadTarball(f,h);if(!p)return Response.json({error:"Package not found"},{status:404,headers:s});return o?.trackDownload({packageName:f,version:h,timestamp:new Date().toISOString(),userAgent:t.headers.get("user-agent")||void 0}).catch((m)=>console.warn("Analytics tracking failed:",m)),new Response(p,{headers:{...s,"Content-Type":"application/gzip","Content-Disposition":`attachment; filename="${f.replace("/","-")}-${h}.tar.gz"`}})}if(d&&!d.includes("/")&&t.method==="GET"){let h=await r.getPackage(f,d);if(!h)return Response.json({error:"Package version not found"},{status:404,headers:s});return Response.json({...h,composerRequire:$l(f,h.version)},{headers:s})}if(!d&&t.method==="GET"){let h=await r.getPackage(f);if(!h)return Response.json({error:"Package not found"},{status:404,headers:s});return Response.json({...h,composerRequire:$l(f,h.version)},{headers:s})}}return null}function WB(){return process.env.PANTRY_REGISTRY_TOKEN||process.env.PANTRY_TOKEN}function T_(e){let t=WB();if(!t)return{valid:!1,error:"Server misconfigured \u2014 no registry token set"};if(!e)return{valid:!1,error:"Authorization required"};let n=e.startsWith("Bearer ")?e.slice(7):e,r=Q("crypto"),i=Math.max(n.length,t.length),s=Buffer.alloc(i),o=Buffer.alloc(i);if(Buffer.from(n).copy(s),Buffer.from(t).copy(o),!r.timingSafeEqual(s,o)||n.length!==t.length)return{valid:!1,error:"Invalid token"};return{valid:!0}}async function UB(e,t,n,r,i,s){let o=e.headers.get("content-type")||"",a=e.headers.get("authorization"),l=T_(a);if(!l.valid)return Response.json({error:l.error},{status:401,headers:r});if(o.includes("multipart/form-data")){let c=await e.formData(),u=c.get("tarball"),f=c.get("manifest"),d=c.get("description");if(!u||!(u instanceof File))return Response.json({error:"Missing tarball"},{status:400,headers:r});let h=await u.arrayBuffer(),p=wg(h),m,g,y,w,b,v,x;if(f&&typeof f==="string"){let E=bg(f);m=E.name,g=E.version||"",y=E.type,w=E.license,b=E.homepage,v=E.authors,x=E.keywords}else{let A=u.name.match(/^(.+)-(\d+\.\d+\.\d+)\.tar\.gz$/);if(!A)return Response.json({error:"Could not determine package name/version. Provide manifest or use vendor-package-version.tar.gz filename."},{status:400,headers:r});m=A[1].replace("-","/"),g=A[2]}if(await t.exists(m,g))return Response.json({error:"Version already exists"},{status:409,headers:r});if(!s)throw Error("malware scanner is required for publishing");let k=await Bn(s,h,{surface:"php",name:m,version:g,publisher:"_admin"});if(k.verdict!=="clean")return Ii(k,r);let C=m.split("/").map(encodeURIComponent).join("/"),T=`${n}/php/packages/${C}/${g}/tarball`,_={name:m,version:g,description:typeof d==="string"?d:void 0,type:y,license:w,homepage:b,authors:v,keywords:x,tarballUrl:T,checksum:p,publishedAt:new Date().toISOString(),malwareScan:k};return await t.publish(_,h),i?.trackEvent({packageName:m,category:"install_on_request",timestamp:new Date().toISOString(),version:g}).catch((E)=>console.warn("Analytics tracking failed:",E)),Response.json({success:!0,message:`Published ${m}@${g}`,checksum:p,tarballUrl:T,composerRequire:$l(m,g),scan:pt(k)},{status:201,headers:r})}return Response.json({error:"Unsupported content type. Use multipart/form-data."},{status:415,headers:r})}async function xg(e,t=20){try{let n=`https://packagist.org/search.json?q=${encodeURIComponent(e)}&per_page=${Math.min(t,30)}`,r=await fetch(n,{headers:{"User-Agent":"pantry-registry/1.0"}});if(!r.ok)return[];return((await r.json()).results||[]).slice(0,t).map((s)=>({name:s.name,description:s.description||"",url:s.url||"",repository:s.repository||"",downloads:s.downloads||0,favers:s.favers||0}))}catch{return[]}}async function Sg(e){try{if(!/^[a-z0-9]([a-z0-9._-]*[a-z0-9])?\/[a-z0-9]([a-z0-9._-]*[a-z0-9])?$/i.test(e))return null;let t=await fetch(`https://packagist.org/packages/${encodeURIComponent(e)}.json`,{headers:{"User-Agent":"pantry-registry/1.0"}});if(!t.ok)return null;let r=(await t.json()).package;if(!r)return null;let i=Object.keys(r.versions||{}),o=i.filter((l)=>!l.includes("dev")&&!l.includes("alpha")&&!l.includes("beta")&&!l.includes("RC")).sort((l,c)=>{let u=l.replace(/^v/,"").split(".").map(Number),f=c.replace(/^v/,"").split(".").map(Number);for(let d=0;d<Math.max(u.length,f.length);d++){let h=(f[d]??0)-(u[d]??0);if(h!==0)return h}return 0})[0]||i[0]||"",a=r.versions?.[o]||{};return{name:r.name,description:r.description||"",version:a.version_normalized||a.version||o.replace(/^v/,"")||"unknown",license:a.license||[],homepage:a.homepage||r.repository||"",repository:r.repository||"",downloads:r.downloads?.total||0,favers:r.favers||0,type:r.type||a.type||"library",versions:i.map((l)=>l.replace(/^v/,"")).filter((l)=>/^\d/.test(l)).slice(0,50),require:a.require||{}}}catch{return null}}var wo=null;async function kg(){if(wo&&Date.now()-wo.timestamp<3600000)return wo.count;try{let e=await fetch("https://packagist.org/statistics.json",{headers:{"User-Agent":"pantry-registry/1.0"}});if(!e.ok)return wo?.count||350000;let n=(await e.json()).totals?.packages||350000;return wo={count:n,timestamp:Date.now()},n}catch{return wo?.count||350000}}import{createHash as PB}from"crypto";import{execSync as M_}from"child_process";import{createReadStream as qB,createWriteStream as GB,existsSync as Eg,mkdirSync as XB,mkdtempSync as VB,readdirSync as YB,rmSync as JB,statSync as KB}from"fs";import{tmpdir as QB}from"os";import{join as $s}from"path";import{Readable as HB}from"stream";import{pipeline as ZB}from"stream/promises";class Yr{maxEntries;ttlMs;now;maxWeight;weightOf;entries=new Map;currentWeight=0;constructor(e,t,n=Date.now,r=Number.POSITIVE_INFINITY,i=()=>1){this.maxEntries=e;this.ttlMs=t;this.now=n;this.maxWeight=r;this.weightOf=i;if(!Number.isInteger(e)||e<1)throw RangeError("maxEntries must be a positive integer");if(!Number.isFinite(t)||t<1)throw RangeError("ttlMs must be a positive number");if(r<=0)throw RangeError("maxWeight must be a positive number")}get size(){return this.entries.size}get weight(){return this.currentWeight}get(e){let t=this.entries.get(e);if(!t)return;if(t.expiresAt<=this.now()){this.remove(e,t);return}return this.entries.delete(e),this.entries.set(e,t),t.value}set(e,t){let n=this.entries.get(e);if(n)this.remove(e,n);let r=Math.max(0,this.weightOf(t));if(!Number.isFinite(r)||r>this.maxWeight)return;this.entries.set(e,{value:t,expiresAt:this.now()+this.ttlMs,weight:r}),this.currentWeight+=r;while(this.entries.size>this.maxEntries||this.currentWeight>this.maxWeight){let i=this.entries.keys().next().value;if(i===void 0)break;let s=this.entries.get(i);if(s)this.remove(i,s)}}delete(e){let t=this.entries.get(e);if(!t)return!1;return this.remove(e,t),!0}clear(){this.entries.clear(),this.currentWeight=0}remove(e,t){this.entries.delete(e),this.currentWeight-=t.weight}}class _g{cache;inFlight=new Map;constructor(e,t,n=Date.now,r=Number.POSITIVE_INFINITY,i=()=>1){this.cache=new Yr(e,t,n,r,i)}get size(){return this.cache.size}async getOrCreate(e,t){let n=this.cache.get(e);if(n!==void 0)return n;let r=this.inFlight.get(e);if(r)return r;let i=t().then((s)=>{return this.cache.set(e,s),s}).finally(()=>{this.inFlight.delete(e)});return this.inFlight.set(e,i),i}clear(){this.cache.clear(),this.inFlight.clear()}}var O_=["darwin-arm64","darwin-x86-64","linux-x86-64","linux-arm64"],Cg=new Set(["php.net","postgresql.org"]);function eW(e){let t=e.indexOf("-"),n=t>0?e.slice(0,t):"",r=t>0?e.slice(t+1):"",i=r==="arm64"?"aarch64":r==="x86-64"?"x86-64":"";if(n!=="darwin"&&n!=="linux"||!i)return null;return{os:n,arch:i}}function N_(e,t,n){let r=eW(n);if(!r)return null;return`https://dist.pkgx.dev/${e}/${r.os}/${r.arch}/v${t}.tar.xz`}function R_(e,t,n){return`binaries/${e}/${t}/${n}/${e.replace(/\//g,"-")}-${t}.tar.gz`}function tW(e,t){let n=e.split(/[.+-]/),r=t.split(/[.+-]/);for(let i=0;i<Math.max(n.length,r.length);i++){let s=Number(n[i]),o=Number(r[i]);if(Number.isNaN(s)||Number.isNaN(o)){let a=(r[i]||"").localeCompare(n[i]||"");if(a!==0)return a}else if(s!==o)return o-s}return 0}var nW=21600000,j_=new Yr(20000,nW);async function rW(e,t,n){if(Cg.has(e))return!1;let r=N_(e,t,n);if(!r)return!1;let i=`${e}@${t}#${n}`,s=j_.get(i);if(s!==void 0)return s;let o=!1;try{o=(await fetch(r,{method:"HEAD",signal:AbortSignal.timeout(8000)})).ok}catch{o=!1}return j_.set(i,o),o}var Tg=new Set;function Mg(e,t,n){return`${e}@${t}#${n}`}function Yu(e,t,n){return Tg.has(Mg(e,t,n))}var iW=1800000,$g=new Yr(1000,iW),sW=20;async function Og(e,t,n){if(Cg.has(e))return t;let r=t?`${t.updatedAt||""}:${t.latestVersion||""}:${Object.keys(t.versions||{}).length}`:"unpublished",i=$g.get(e);if(i&&i.sourceFingerprint===r)return i.data;let s=t?{...t,versions:{...t.versions||{}}}:{name:e,latestVersion:"",versions:{},updatedAt:new Date().toISOString()};s.versions??={};let o=n.filter((a)=>a&&a!=="999.999.999"&&a!=="0.0.0").sort(tW).filter((a)=>{let l=s.versions[a]?.platforms;return!l||O_.some((c)=>!l[c])}).slice(0,sW);return await Promise.all(o.map(async(a)=>{let l=s.versions[a]?.platforms||{},c=O_.filter((d)=>!l[d]),f=(await Promise.all(c.map(async(d)=>({p:d,ok:await rW(e,a,d)})))).filter((d)=>d.ok);if(f.length===0)return;s.versions[a]??={platforms:{}},s.versions[a].platforms??={};for(let{p:d}of f)s.versions[a].platforms[d]={tarball:R_(e,a,d),sha256:"",size:0,uploadedAt:""},Tg.add(Mg(e,a,d))})),$g.set(e,{sourceFingerprint:r,data:s}),s}var Ag=new Map;async function oW(e){let t=PB("sha256");for await(let n of qB(e))t.update(n);return t.digest("hex")}async function L_(e,t,n,r){if(Cg.has(e))return null;let i=`${e}@${t}#${n}`,s=Ag.get(i);if(s)return s;let o=(async()=>{let a=N_(e,t,n);if(!a)return null;let l=e.replace(/\//g,"-"),c=R_(e,t,n),u=VB($s(QB(),`pkgx-${l}-`));try{let f=$s(u,"pkg.tar.xz");try{let b=await fetch(a,{signal:AbortSignal.timeout(120000)});if(!b.ok||!b.body)return null;await ZB(HB.fromWeb(b.body),GB(f))}catch{return null}let d=$s(u,"ex");XB(d,{recursive:!0}),M_(`tar -xJf "${f}" -C "${d}"`,{stdio:"pipe"});let h=$s(d,e,`v${t}`);if(!Eg(h)){let b=$s(d,e),v=Eg(b)?YB(b).filter((x)=>x.startsWith("v")):[];if(v.length===1)h=$s(b,v[0])}if(!Eg(h))return null;let p=$s(u,"out.tar.gz");M_(`tar -czf "${p}" -C "${h}" .`,{stdio:"pipe"});let m=KB(p).size,g=await oW(p),y=r.initiate({domain:e,version:t,platforms:[n],filename:`${l}-${t}.tar.gz`,size:m,sha256:g}),w=await fetch(y.uploadUrl,{method:"PUT",headers:{...y.uploadHeaders,"Content-Length":String(m)},body:Bun.file(p)});if(!w.ok)throw Error(`pkgx staged upload failed with HTTP ${w.status}`);return await r.complete(y.uploadId,"_pkgx","pkgx"),$g.delete(e),Tg.delete(Mg(e,t,n)),{tarballKey:c,sha256:g,size:m}}catch(f){return console.error(`pkgx materialize failed for ${i}:`,f.message),null}finally{try{JB(u,{recursive:!0,force:!0})}catch{}}})();Ag.set(i,o);try{return await o}finally{Ag.delete(i)}}var Hu=["darwin-arm64","darwin-x86-64","linux-x86-64","linux-arm64"],F_=new Set(Hu),Ju=400,Cl=2000,aW=400,Ku=500,lW=600000,I_=21600000,D_=50,z_=5000;class jg{s3;bucket;building=new Map;recent=[];queue=[];unavailable=new Map;snapshot;coverageSnapshot;coverage=new Map;coverageLastBuilt=new Map;coverageAt=0;coveragePromise=null;subscribers=new Set;knownVersions=new Map;supportedPlatforms=new Map;logs=new Map;constructor(e,t){this.s3=e;this.bucket=t;this.snapshot=new Cr(e,t,"build-status/status.json",()=>this.captureState()),this.coverageSnapshot=new Cr(e,t,"build-status/coverage.json",()=>this.captureCoverage())}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}emit(){if(this.subscribers.size===0)return;let e=this.getStatus();for(let t of this.subscribers)try{t(e)}catch{}}get subscriberCount(){return this.subscribers.size}setKnownPackages(e){this.knownVersions=e}setSupportedPlatforms(e){this.supportedPlatforms=e}getLogs(e){return[...this.logs.get(e)||[]]}recordLogs(e,t,n){if(!e||!n?.length)return;let r=this.touchLogBuf(e),i=Date.now();for(let s of n)r.push({ts:i,platform:t||"",state:"building",text:String(s).slice(0,Cl)});if(r.length>Ju)r.splice(0,r.length-Ju);for(let[,s]of this.building)if(s.domain===e&&(!t||!s.platform||s.platform===t))s.ts=i;this.evictOldLogDomains(),this.emit()}touchLogBuf(e){let t=this.logs.get(e);if(t)this.logs.delete(e);else t=[];return this.logs.set(e,t),t}appendLog(e,t){if(!t)return;let n=this.touchLogBuf(e.domain);if(n.push({ts:e.ts,platform:e.platform,state:e.state,text:t.slice(0,Cl)}),n.length>Ju)n.splice(0,n.length-Ju);this.evictOldLogDomains()}evictOldLogDomains(){while(this.logs.size>aW){let e=this.logs.keys().next().value;if(e===void 0)break;this.logs.delete(e)}}async load(){let[e,t]=await Promise.all([this.snapshot.load(),this.coverageSnapshot.load()]);if(e)this.building=new Map((e.building||[]).filter((n)=>bo(n?.domain)).map((n)=>[this.key(n),n])),this.recent=(e.recent||[]).filter((n)=>bo(n?.domain)).slice(0,Ku),this.queue=(e.queue||[]).filter((n)=>bo(n)),this.unavailable=new Map((e.unavailable||[]).filter((n)=>n&&bo(n.domain)&&n.version&&n.platform).map((n)=>[this.key(n),{domain:String(n.domain),version:String(n.version),platform:String(n.platform),reason:n.reason?String(n.reason).slice(0,Cl):void 0,lastSeen:Number(n.lastSeen)||Date.now()}])),this.capUnavailable();if(t)this.restoreCoverage(t);for(let n of this.recent)if(n.state==="built"&&n.version)this.mergeCoverage(n.domain,n.version,n.platform,new Date(n.ts).toISOString())}key(e){return`${e.domain}|${e.version}|${e.platform}`}captureState(){return{version:1,building:[...this.building.values()],recent:this.recent.slice(0,Ku),queue:this.queue,unavailable:[...this.unavailable.values()]}}captureCoverage(){return{version:1,at:this.coverageAt,packages:[...this.coverage].map(([e,t])=>[e,[...t].map(([n,r])=>[n,[...r]]),this.coverageLastBuilt.get(e)])}}restoreCoverage(e){if(e.version!==1||!Array.isArray(e.packages))return;let t=new Map,n=new Map;for(let[r,i,s]of e.packages){if(!bo(r)||!Array.isArray(i))continue;let o=new Map;for(let[a,l]of i)if(a&&Array.isArray(l))o.set(a,new Set(l.filter((c)=>F_.has(c))));if(o.size>0)t.set(r,o);if(s)n.set(r,s)}this.coverage=t,this.coverageLastBuilt=n,this.coverageAt=Math.min(Number(e.at)||0,Date.now())}mergeCoverage(e,t,n,r){let i=this.coverage.get(e);if(!i)i=new Map,this.coverage.set(e,i);let s=i.get(t);if(!s)s=new Set,i.set(t,s);s.add(n),this.coverageLastBuilt.set(e,r)}record(e){if(!e.domain||!e.platform||!e.state)return null;if(!bo(String(e.domain)))return null;let t={domain:String(e.domain),version:String(e.version||""),platform:String(e.platform),state:e.state,host:e.host?String(e.host).slice(0,64):void 0,ts:Date.now(),message:e.message?String(e.message).slice(0,Cl):void 0,error:e.error?String(e.error).slice(0,Cl):void 0,hostKind:e.hostKind?String(e.hostKind).slice(0,16):void 0,hostUrl:e.hostUrl?String(e.hostUrl).slice(0,300):void 0},n=this.key(t);if(t.state==="unavailable")return this.building.delete(n),this.recordUnavailable(t),this.appendLog(t,t.error||`${t.platform}: unavailable (no source upstream)`),this.snapshot.scheduleSave(),this.emit(),t;if(t.state==="building")this.building.set(n,t);else{if(this.building.delete(n),this.recent.unshift(t),this.recent.length>Ku)this.recent.length=Ku;if(t.state==="built"&&t.version)this.reconcileUnavailable(t.domain,t.version);if(t.state==="built"&&t.version)this.mergeCoverage(t.domain,t.version,t.platform,new Date().toISOString());this.coverageAt=0}return this.appendLog(t,t.error||t.message||`${t.platform}: ${t.state}`),this.snapshot.scheduleSave(),this.emit(),t}recordUnavailable(e){if(!e.version)return;let t=this.key(e);this.unavailable.set(t,{domain:e.domain,version:e.version,platform:e.platform,reason:e.error,lastSeen:e.ts}),this.capUnavailable()}reconcileUnavailable(e,t){let n=!1;for(let[r,i]of this.unavailable)if(i.domain===e&&i.version===t)this.unavailable.delete(r),n=!0;if(n)this.snapshot.scheduleSave()}capUnavailable(){let e=new Map;for(let t of this.unavailable.values()){let n=e.get(t.domain);if(!n)n=[],e.set(t.domain,n);n.push(t)}for(let[,t]of e){if(t.length<=D_)continue;t.sort((n,r)=>n.lastSeen-r.lastSeen);for(let n of t.slice(0,t.length-D_))this.unavailable.delete(this.key(n))}if(this.unavailable.size>z_){let t=[...this.unavailable.values()].sort((n,r)=>n.lastSeen-r.lastSeen);for(let n of t.slice(0,this.unavailable.size-z_))this.unavailable.delete(this.key(n))}}getUnavailableVersions(){return[...this.unavailable.values()].sort((e,t)=>t.lastSeen-e.lastSeen)}pruneStaleBuilding(){let e=Date.now()-lW,t=!1;for(let[n,r]of this.building)if(r.ts<e)this.building.delete(n),t=!0;if(t)this.snapshot.scheduleSave()}requestRebuild(e,t=!1){let n=String(e||"").trim();if(!n)return!1;let r=this.queue.indexOf(n);if(r!==-1){if(!t||r===0)return!1;return this.queue.splice(r,1),this.queue.unshift(n),this.snapshot.scheduleSave(),this.emit(),!0}if(t)this.queue.unshift(n);else this.queue.push(n);return this.snapshot.scheduleSave(),this.emit(),!0}getQueue(){return[...this.queue]}clearQueue(e){if(!e)this.queue=[];else{let t=new Set(e);this.queue=this.queue.filter((n)=>!t.has(n))}this.snapshot.scheduleSave(),this.emit()}getStatus(){return this.pruneStaleBuilding(),{building:[...this.building.values()].sort((e,t)=>t.ts-e.ts),recent:this.recent.slice(0,100),queue:[...this.queue]}}parseKey(e){let t=e.split("/");if(t.length<5||t[0]!=="binaries")return null;let n=t[t.length-2];if(!F_.has(n))return null;let r=t[t.length-3],i=t.slice(1,t.length-3).join("/");if(!i||!r)return null;return{domain:i,version:r,platform:n}}async refreshCoverage(e=!1){if(!e&&Date.now()-this.coverageAt<I_)return;if(this.coveragePromise)return this.coveragePromise;return this.coveragePromise=(async()=>{let t=await this.s3.list({bucket:this.bucket,prefix:"binaries/",maxKeys:1e6}),n=new Map,r=new Map;for(let i of t){let s=this.parseKey(i.Key);if(!s)continue;let{domain:o,version:a,platform:l}=s,c=n.get(o);if(!c)c=new Map,n.set(o,c);let u=c.get(a);if(!u)u=new Set,c.set(a,u);if(u.add(l),i.LastModified&&(!r.has(o)||i.LastModified>r.get(o)))r.set(o,i.LastModified)}if(this.coverage.size>=50&&n.size<this.coverage.size*0.5){this.coverageAt=Date.now();return}this.coverage=n,this.coverageLastBuilt=r,this.coverageAt=Date.now(),await this.coverageSnapshot.flush()})().finally(()=>{this.coveragePromise=null}),this.coveragePromise}latestVersion(e){let t=null;for(let n of e.keys())if(t===null||Qu(n,t)>0)t=n;return t}async getPackages(){if(this.coverage.size===0)await this.refreshCoverage(!0);else if(Date.now()-this.coverageAt>I_)this.refreshCoverage();this.pruneStaleBuilding();let e=new Map;for(let a of this.building.values()){let l=e.get(a.domain);if(!l)l=new Set,e.set(a.domain,l);l.add(a.platform)}let t=new Map,n=new Map;for(let a of this.recent)if(!t.has(a.domain)){t.set(a.domain,a.state);let l=a.error||a.message;if(l)n.set(a.domain,l)}for(let a of this.building.values())if(a.message)n.set(a.domain,a.message);let r=new Set([...this.coverage.keys(),...e.keys(),...t.keys(),...this.knownVersions.keys()]),i=[];for(let a of r){let l=this.coverage.get(a),c=!!l&&l.size>0,u=l?this.latestVersion(l):(this.knownVersions.get(a)||[]).reduce((p,m)=>p===null||Qu(m,p)>0?m:p,null),f=u&&l?l.get(u)??new Set:new Set,d={};for(let p of Hu)d[p]=f.has(p);let h=(this.knownVersions.get(a)||[]).reduce((p,m)=>p===null||Qu(m,p)>0?m:p,null);i.push({domain:a,latestVersion:u,platforms:d,lastBuilt:this.coverageLastBuilt.get(a)||null,building:[...e.get(a)||[]],lastState:t.get(a),published:c,lastMessage:n.get(a),supportedPlatforms:this.supportedPlatforms.get(a)||[...Hu],newestVersion:h??u,hasUpdate:c&&!!h&&!!u&&Qu(h,u)>0})}i.sort((a,l)=>a.domain.localeCompare(l.domain));let s=0,o=0;for(let[a,l]of this.coverage){let c=this.supportedPlatforms.get(a)||[...Hu];for(let u of l.values()){if(u.size===0)continue;if(o+=u.size,c.length>0&&c.every((f)=>u.has(f)))s++}}return{packages:i,generatedAt:new Date().toISOString(),totals:{publishedVersions:s,publishedArtifacts:o}}}async flush(){await this.snapshot.flush()}}function bo(e){if(typeof e!=="string")return!1;let t=e.trim();if(t.length===0||t.length>200)return!1;return/^[a-z0-9][a-z0-9.+-]*\.[a-z0-9][\w.+/-]*$/i.test(t)}function Qu(e,t){let n=e.replace(/^v/,"").split(/[.\-+]/),r=t.replace(/^v/,"").split(/[.\-+]/),i=Math.max(n.length,r.length);for(let s=0;s<i;s++){let o=Number.parseInt(n[s]??"0",10),a=Number.parseInt(r[s]??"0",10);if(Number.isNaN(o)||Number.isNaN(a)){let l=(n[s]??"").localeCompare(r[s]??"");if(l!==0)return l}else if(o!==a)return o-a}return 0}var Tl={free:{id:"free",name:"Free",price:0,commissionBps:1000,analyticsRetentionDays:30,maxArtifactBytes:52428800,privatePackages:!1,priorityBuilds:!1,seats:1,buildInsurance:!1,securityAlerts:!1,sbomExport:!1,teamEntitlements:!1},pro:{id:"pro",name:"Pro",price:900,commissionBps:500,analyticsRetentionDays:3650,maxArtifactBytes:262144000,privatePackages:!0,priorityBuilds:!0,seats:1,buildInsurance:!0,securityAlerts:!0,sbomExport:!0,teamEntitlements:!1,stripeLookupKey:"pantry_pro_monthly"},team:{id:"team",name:"Team",price:2900,commissionBps:500,analyticsRetentionDays:3650,maxArtifactBytes:1073741824,privatePackages:!0,priorityBuilds:!0,seats:10,buildInsurance:!0,securityAlerts:!0,sbomExport:!0,teamEntitlements:!0,stripeLookupKey:"pantry_team_monthly"}},Zu=300;function Ml(e){if(e==="pro"||e==="team")return e;return"free"}function tr(e){return Tl[e]}function B_(e,t=new Date){if(!e||e.tier==="free")return"free";switch(e.status){case"active":case"trialing":case"past_due":return e.tier;case"canceled":return e.currentPeriodEnd&&new Date(e.currentPeriodEnd)>t?e.tier:"free";default:return"free"}}function W_(e){let t=tr(e.sellerTier).commissionBps,n=e.discoveredOnSite?300:0,r=Math.min(t+n,3000),i=Math.max(0,Math.min(Math.floor(e.amount*r/1e4),e.amount));return{amount:e.amount,commissionBps:t,discoveryBps:n,totalBps:r,applicationFee:i,sellerNet:e.amount-i}}function Di(e){let t=e/100;return`${Number.isInteger(t)?t:t.toFixed(2)}%`}function U_(e){return e==="site"}function q_(){return process.env.STRIPE_SECRET_KEY||""}function G_(){return process.env.STRIPE_WEBHOOK_SECRET||""}function nr(){return q_().length>0}function Fg(e,t=""){let n=[];for(let[r,i]of Object.entries(e)){if(i===void 0||i===null)continue;let s=t?`${t}[${r}]`:r;if(Array.isArray(i))i.forEach((o,a)=>{if(o!==null&&typeof o==="object")n.push(...Fg(o,`${s}[${a}]`));else n.push([`${s}[${a}]`,String(o)])});else if(typeof i==="object")n.push(...Fg(i,s));else n.push([s,String(i)])}return n}async function zi(e,t,n){let r=q_();if(!r)throw Error("STRIPE_SECRET_KEY not configured");let i=`https://api.stripe.com/v1${t}`,s={Authorization:`Bearer ${r}`},o;if(n)s["Content-Type"]="application/x-www-form-urlencoded",o=new URLSearchParams(Fg(n)).toString();let a=await fetch(i,{method:e,headers:s,body:o});if(!a.ok){let l=await a.text();throw console.error(`Stripe ${e} ${t} failed (${a.status}):`,l),Error(`Payment service error (${a.status})`)}return a.json()}function Ig(e){return`user:${e.toLowerCase().trim()}`}async function Dg(e,t,n,r,i){let s=await e.getPaywall(t);if(!s||!s.enabled)return{allowed:!0,reason:"no-paywall"};if(s.freeVersions?.includes(n))return{allowed:!0,paywall:s,reason:"free-version"};if(r.admin)return{allowed:!0,paywall:s,reason:"admin"};let o=r.userId?.toLowerCase().trim(),a=i?.toLowerCase().trim();if(a&&(o===a||r.org?.toLowerCase().trim()===a))return{allowed:!0,paywall:s,reason:"owner"};for(let l of[o,r.org?.toLowerCase().trim()]){if(!l)continue;let c=await e.getAccessGrant(t,Ig(l));if(c){if(c.expiresAt&&new Date(c.expiresAt)<new Date)return{allowed:!1,paywall:s,reason:"expired"};return{allowed:!0,paywall:s,reason:l===o?"entitled":"team-entitled"}}}if(r.token){if(await e.getAccessGrant(t,r.token))return{allowed:!0,paywall:s,reason:"entitled"}}return{allowed:!1,paywall:s,reason:o||r.token?"payment-required":"unauthenticated"}}async function cW(e,t,n,r){let i=await Dg(e,t,n,{token:r});return{allowed:i.allowed,paywall:i.paywall,reason:i.allowed?void 0:i.reason==="unauthenticated"?"Authentication required for paid package":"Payment required"}}async function ef(e,t,n,r){for(let i of[n,r]){if(!i)continue;let s=await e.getAccessGrant(t,Ig(i));if(!s)continue;if(s.expiresAt&&new Date(s.expiresAt)<new Date)continue;return!0}return!1}var P_=new Set(["usd","eur","gbp","cad","aud","chf","jpy","sek","nok","dkk"]),Ng=100,Rg=1e7;function tf(e){if(typeof e.price!=="number"||!Number.isInteger(e.price))return"Price must be a whole number of cents (e.g. 900 for $9.00)";if(e.price<Ng)return`Price must be at least ${Ng} cents ($${(Ng/100).toFixed(2)})`;if(e.price>Rg)return`Price must be at most ${Rg} cents ($${(Rg/100).toFixed(2)})`;let t=(e.currency||"usd").toLowerCase();if(!P_.has(t))return`Unsupported currency "${t}" \u2014 one of: ${[...P_].join(", ")}`;if(e.freeVersions&&!Array.isArray(e.freeVersions))return"freeVersions must be an array of version strings";if(e.freeVersions?.some((n)=>typeof n!=="string"||n.length>64))return"freeVersions must be version strings";if(e.payoutAccountId&&!/^acct_[A-Za-z0-9]+$/.test(e.payoutAccountId))return"payoutAccountId must be a Stripe Connect account id (acct_\u2026)";if(e.trialDays!==void 0&&(!Number.isInteger(e.trialDays)||e.trialDays<0||e.trialDays>365))return"trialDays must be a whole number of days between 0 and 365";return null}async function nf(e,t,n){let r=tf(n);if(r)throw Error(r);let i=new Date().toISOString(),s=await e.getPaywall(t),o=(n.currency||s?.currency||"usd").toLowerCase(),a=s?.stripeProductId,l=s?.stripePriceId;if(nr()){if(!a)a=(await zi("POST","/products",{name:t,description:`Access to ${t} on the pantry registry`,metadata:{pantry_package:t}})).id;if(!l||s?.price!==n.price||s?.currency?.toLowerCase()!==o)l=(await zi("POST","/prices",{product:a,unit_amount:String(n.price),currency:o})).id}let c={name:t,enabled:!0,price:n.price,currency:o,stripeProductId:a,stripePriceId:l,stripeAccountId:n.payoutAccountId??s?.stripeAccountId,freeVersions:n.freeVersions??s?.freeVersions,trialDays:n.trialDays??s?.trialDays,createdAt:s?.createdAt||i,updatedAt:i};return await e.putPaywall(c),c}async function rf(e,t){let{packageName:n,email:r,baseUrl:i}=t,s=await e.getPaywall(n);if(!s||!s.enabled)throw Error("This package is not for sale");if(!nr())throw Error("Payments are not configured on this registry");if(!s.stripePriceId)throw Error("This package has a price but no Stripe price \u2014 the publisher should save it again");let o=encodeURIComponent(n),a=t.origin||"cli",l=W_({amount:s.price,sellerTier:t.sellerTier||"free",discoveredOnSite:U_(a)});return{url:(await zi("POST","/checkout/sessions",{mode:"payment","line_items[0][price]":s.stripePriceId,"line_items[0][quantity]":"1",customer_email:r,client_reference_id:`${n}:${r}`,success_url:`${i}/packages/${o}/checkout/success`,cancel_url:`${i}/pkg/${o}`,"metadata[package_name]":n,"metadata[buyer_email]":(t.org||r).toLowerCase().trim(),"metadata[purchased_by]":r,"metadata[sale_origin]":a,"metadata[fee_bps]":String(l.totalBps),"metadata[seller_tier]":t.sellerTier||"free",...s.stripeAccountId?{"payment_intent_data[transfer_data][destination]":s.stripeAccountId,"payment_intent_data[on_behalf_of]":s.stripeAccountId,...l.applicationFee>0?{"payment_intent_data[application_fee_amount]":String(l.applicationFee)}:{}}:{}})).url}}var Lg=new Map;async function uW(e){if(!e.stripeLookupKey)throw Error(`${e.name} is not a paid tier`);let t=Lg.get(e.stripeLookupKey);if(t)return t;let n=await zi("GET",`/prices?lookup_keys[]=${encodeURIComponent(e.stripeLookupKey)}&active=true&limit=1`);if(n?.data?.length>0)return Lg.set(e.stripeLookupKey,n.data[0].id),n.data[0].id;let r=await zi("POST","/products",{name:`pantry ${e.name}`,description:`pantry registry ${e.name} plan`,metadata:{pantry_tier:e.id}}),i=await zi("POST","/prices",{product:r.id,unit_amount:String(e.price),currency:"usd",recurring:{interval:"month"},lookup_key:e.stripeLookupKey});return Lg.set(e.stripeLookupKey,i.id),i.id}async function X_(e){if(!nr())throw Error("Payments are not configured on this registry");if(!e.tier.stripeLookupKey)throw Error("The free plan does not need a subscription");let t=await uW(e.tier);return{url:(await zi("POST","/checkout/sessions",{mode:"subscription","line_items[0][price]":t,"line_items[0][quantity]":"1",...e.stripeCustomerId?{customer:e.stripeCustomerId}:{customer_email:e.email},success_url:`${e.baseUrl}/account?subscribed=${e.tier.id}`,cancel_url:`${e.baseUrl}/pricing`,"metadata[pantry_tier]":e.tier.id,"metadata[account_email]":e.email,"subscription_data[metadata][pantry_tier]":e.tier.id,"subscription_data[metadata][account_email]":e.email})).url}}async function V_(e,t){if(!nr())throw Error("Payments are not configured on this registry");return{url:(await zi("POST","/billing_portal/sessions",{customer:e,return_url:t})).url}}function fW(e){let t=e?.metadata?.account_email,n=e?.metadata?.pantry_tier;if(!t||!n)return null;return{email:t,tier:n,status:e.cancel_at_period_end&&e.status==="active"?"canceled":e.status||"none",stripeCustomerId:typeof e.customer==="string"?e.customer:e.customer?.id,stripeSubscriptionId:e.id,currentPeriodEnd:e.current_period_end?new Date(e.current_period_end*1000).toISOString():void 0}}var Ol=new Map,dW=600000;async function zg(e,t,n,r){if(!G_())throw Error("STRIPE_WEBHOOK_SECRET not configured");let i=await hW(t,n);if(i.id){if(Ol.has(i.id))return{processed:!0};if(Ol.set(i.id,Date.now()),Ol.size>100){let s=Date.now();for(let[o,a]of Ol)if(s-a>dW)Ol.delete(o)}}if(i.type?.startsWith("customer.subscription.")&&r){let s=fW(i.data.object);if(s){let o=i.type==="customer.subscription.deleted"?{...s,status:"canceled"}:s;return await r(o),{processed:!0,subscription:`${o.email}:${o.tier}:${o.status}`}}return{processed:!1}}if(i.type==="checkout.session.completed"){let s=i.data.object;if(s.mode==="subscription"&&r){let u=s.metadata?.account_email,f=s.metadata?.pantry_tier;if(u&&f)return await r({email:u,tier:f,status:"active",stripeCustomerId:typeof s.customer==="string"?s.customer:s.customer?.id,stripeSubscriptionId:typeof s.subscription==="string"?s.subscription:s.subscription?.id}),{processed:!0,subscription:`${u}:${f}:active`};return{processed:!1}}let o=s.metadata?.package_name,a=s.metadata?.buyer_email,l=!s.payment_status||s.payment_status==="paid"||s.payment_status==="no_payment_required";if(o&&a&&l){let u={packageName:o,token:Ig(a),stripePaymentId:s.payment_intent||s.id,grantedAt:new Date().toISOString()};return await e.putAccessGrant(u),{processed:!0,granted:a}}let c=s.metadata?.access_token;if(o&&c&&l)return await e.putAccessGrant({packageName:o,token:c,stripePaymentId:s.payment_intent||s.id,grantedAt:new Date().toISOString()}),{processed:!0}}return{processed:!1}}async function hW(e,t){let n=t.split(",").reduce((d,h)=>{let[p,m]=h.split("=");return d[p]=m,d},{}),r=n.t,i=n.v1;if(!r||!i)throw Error("Invalid Stripe signature format");let s=`${r}.${e}`,o=await crypto.subtle.importKey("raw",new TextEncoder().encode(G_()),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await crypto.subtle.sign("HMAC",o,new TextEncoder().encode(s)),l=Array.from(new Uint8Array(a)).map((d)=>d.toString(16).padStart(2,"0")).join(""),c=Buffer.from(l),u=Buffer.from(i);if(c.length!==u.length||!crypto.timingSafeEqual(c,u))throw Error("Stripe webhook signature verification failed");if(Math.abs(Date.now()/1000-Number(r))>300)throw Error("Stripe webhook timestamp too old");try{return JSON.parse(e)}catch{throw Error("Invalid webhook body JSON")}}var pW={usd:"$",eur:"\u20AC",gbp:"\xA3",cad:"CA$",aud:"A$",jpy:"\xA5"},mW=new Set(["jpy"]);function Bi(e,t){let n=(t||"usd").toLowerCase(),r=pW[n]||`${n.toUpperCase()} `;if(mW.has(n))return`${r}${e}`;return`${r}${(e/100).toFixed(2)}`}function cf(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function gW(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function OE(e){let t,n,r;if(e.length!==2)t=cf,n=(a,l)=>cf(e(a),l),r=(a,l)=>e(a)-l;else t=e===cf||e===gW?e:yW,n=e,r=e;function i(a,l,c=0,u=a.length){if(c<u){if(t(l,l)!==0)return u;do{let f=c+u>>>1;if(n(a[f],l)<0)c=f+1;else u=f}while(c<u)}return c}function s(a,l,c=0,u=a.length){if(c<u){if(t(l,l)!==0)return u;do{let f=c+u>>>1;if(n(a[f],l)<=0)c=f+1;else u=f}while(c<u)}return c}function o(a,l,c=0,u=a.length){let f=i(a,l,c,u-1);return f>c&&r(a[f-1],l)>-r(a[f],l)?f-1:f}return{left:i,center:o,right:s}}function yW(){return 0}function wW(e){return e===null?NaN:+e}var jE=OE(cf),bW=jE.right,Eye=jE.left,Aye=OE(wW).center,vW=bW,$ye=NE(RE),Cye=NE(xW);function NE(e){return function(t,n,r=n){if(!((n=+n)>=0))throw RangeError("invalid rx");if(!((r=+r)>=0))throw RangeError("invalid ry");let{data:i,width:s,height:o}=t;if(!((s=Math.floor(s))>=0))throw RangeError("invalid width");if(!((o=Math.floor(o!==void 0?o:i.length/s))>=0))throw RangeError("invalid height");if(!s||!o||!n&&!r)return t;let a=n&&e(n),l=r&&e(r),c=i.slice();if(a&&l)vo(a,c,i,s,o),vo(a,i,c,s,o),vo(a,c,i,s,o),xo(l,i,c,s,o),xo(l,c,i,s,o),xo(l,i,c,s,o);else if(a)vo(a,i,c,s,o),vo(a,c,i,s,o),vo(a,i,c,s,o);else if(l)xo(l,i,c,s,o),xo(l,c,i,s,o),xo(l,i,c,s,o);return t}}function vo(e,t,n,r,i){for(let s=0,o=r*i;s<o;)e(t,n,s,s+=r,1)}function xo(e,t,n,r,i){for(let s=0,o=r*i;s<r;++s)e(t,n,s,s+o,r)}function xW(e){let t=RE(e);return(n,r,i,s,o)=>{i<<=2,s<<=2,o<<=2,t(n,r,i+0,s+0,o),t(n,r,i+1,s+1,o),t(n,r,i+2,s+2,o),t(n,r,i+3,s+3,o)}}function RE(e){let t=Math.floor(e);if(t===e)return SW(e);let n=e-t,r=2*e+1;return(i,s,o,a,l)=>{if(!((a-=l)>=o))return;let c=t*s[o],u=l*t,f=u+l;for(let d=o,h=o+u;d<h;d+=l)c+=s[Math.min(a,d)];for(let d=o,h=a;d<=h;d+=l)c+=s[Math.min(a,d+u)],i[d]=(c+n*(s[Math.max(o,d-f)]+s[Math.min(a,d+f)]))/r,c-=s[Math.max(o,d-u)]}}function SW(e){let t=2*e+1;return(n,r,i,s,o)=>{if(!((s-=o)>=i))return;let a=e*r[i],l=o*e;for(let c=i,u=i+l;c<u;c+=o)a+=r[Math.min(s,c)];for(let c=i,u=s;c<=u;c+=o)a+=r[Math.min(s,c+l)],n[c]=a/t,a-=r[Math.max(i,c-l)]}}var LE=Array.prototype,Tye=LE.slice,Mye=LE.map,kW=Math.sqrt(50),_W=Math.sqrt(10),EW=Math.sqrt(2);function df(e,t,n){let r=(t-e)/Math.max(0,n),i=Math.floor(Math.log10(r)),s=r/Math.pow(10,i),o=s>=kW?10:s>=_W?5:s>=EW?2:1,a,l,c;if(i<0){if(c=Math.pow(10,-i)/o,a=Math.round(e*c),l=Math.round(t*c),a/c<e)++a;if(l/c>t)--l;c=-c}else{if(c=Math.pow(10,i)*o,a=Math.round(e/c),l=Math.round(t/c),a*c<e)++a;if(l*c>t)--l}if(l<a&&0.5<=n&&n<2)return df(e,t,n*2);return[a,l,c]}function AW(e,t,n){if(t=+t,e=+e,n=+n,!(n>0))return[];if(e===t)return[e];let r=t<e,[i,s,o]=r?df(t,e,n):df(e,t,n);if(!(s>=i))return[];let a=s-i+1,l=Array(a);if(r)if(o<0)for(let c=0;c<a;++c)l[c]=(s-c)/-o;else for(let c=0;c<a;++c)l[c]=(s-c)*o;else if(o<0)for(let c=0;c<a;++c)l[c]=(i+c)/-o;else for(let c=0;c<a;++c)l[c]=(i+c)*o;return l}function e0(e,t,n){return t=+t,e=+e,n=+n,df(e,t,n)[2]}function $W(e,t,n){t=+t,e=+e,n=+n;let r=t<e,i=r?e0(t,e,n):e0(e,t,n);return(r?-1:1)*(i<0?1/-i:i)}function CW(e){return function(t,n=0,r=t.length){let i=r-(n=+n);while(i){let s=e()*i--|0,o=t[i+n];t[i+n]=t[s+n],t[s+n]=o}return t}}var Oye=CW(Math.random);function FE(e,t){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(t).domain(e);break}return this}var jye=Symbol("implicit");var Y_=0.7,J_=1.4285714285714286,TW=/^#([0-9a-f]{3,8})$/,MW=new RegExp("^rgb\\(\\s*([+-]?\\d+)\\s*,\\s*([+-]?\\d+)\\s*,\\s*([+-]?\\d+)\\s*\\)$"),OW=new RegExp("^rgb\\(\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*\\)$"),jW=new RegExp("^rgba\\(\\s*([+-]?\\d+)\\s*,\\s*([+-]?\\d+)\\s*,\\s*([+-]?\\d+)\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*\\)$"),NW=new RegExp("^rgba\\(\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*\\)$"),RW=new RegExp("^hsl\\(\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*\\)$"),LW=new RegExp("^hsla\\(\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*\\)$"),K_={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};function hf(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Ts(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Cs(e){return e=Ts(e),(e<16?"0":"")+e.toString(16)}function Q_(e){return e=(e||0)%360,e<0?e+360:e}function sf(e){return Math.max(0,Math.min(1,e||0))}function Bg(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}class or{opacity;copy(e){return Object.assign(Object.create(Object.getPrototypeOf(this)),this,e)}displayable(){return this.rgb().displayable()}formatHex(){return this.rgb().formatHex()}formatHex8(){return this.rgb().formatHex8()}formatHsl(){return IE(this).formatHsl()}formatRgb(){return this.rgb().formatRgb()}toString(){return this.rgb().formatRgb()}rgb(){return this.rgb()}hex(){return this.formatHex()}}or.prototype.hex=or.prototype.formatHex;class dt extends or{r;g;b;constructor(e,t,n,r){super();this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}brighter(e){return e=e==null?1.4285714285714286:Math.pow(1.4285714285714286,e),new dt(this.r*e,this.g*e,this.b*e,this.opacity)}darker(e){return e=e==null?0.7:Math.pow(0.7,e),new dt(this.r*e,this.g*e,this.b*e,this.opacity)}rgb(){return this}clamp(){return new dt(Ts(this.r),Ts(this.g),Ts(this.b),hf(this.opacity))}displayable(){return-0.5<=this.r&&this.r<255.5&&(-0.5<=this.g&&this.g<255.5)&&(-0.5<=this.b&&this.b<255.5)&&(0<=this.opacity&&this.opacity<=1)}formatHex(){return`#${Cs(this.r)}${Cs(this.g)}${Cs(this.b)}`}hex(){return this.formatHex()}formatHex8(){return`#${Cs(this.r)}${Cs(this.g)}${Cs(this.b)}${Cs((isNaN(this.opacity)?1:this.opacity)*255)}`}formatRgb(){let e=hf(this.opacity);return`${e===1?"rgb(":"rgba("}${Ts(this.r)}, ${Ts(this.g)}, ${Ts(this.b)}${e===1?")":`, ${e})`}`}toString(){return this.formatRgb()}}dt.prototype.hex=dt.prototype.formatHex;class rr extends or{h;s;l;constructor(e,t,n,r){super();this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}brighter(e){return e=e==null?1.4285714285714286:Math.pow(1.4285714285714286,e),new rr(this.h,this.s,this.l*e,this.opacity)}darker(e){return e=e==null?0.7:Math.pow(0.7,e),new rr(this.h,this.s,this.l*e,this.opacity)}rgb(){let e=this.h%360+(this.h<0?360:0),t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<0.5?n:1-n)*t,i=2*n-r;return new dt(Bg(e>=240?e-240:e+120,i,r),Bg(e,i,r),Bg(e<120?e+240:e-120,i,r),this.opacity)}clamp(){return new rr(Q_(this.h),sf(this.s),sf(this.l),hf(this.opacity))}displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&(0<=this.l&&this.l<=1)&&(0<=this.opacity&&this.opacity<=1)}formatHsl(){let e=hf(this.opacity);return`${e===1?"hsl(":"hsla("}${Q_(this.h)}, ${sf(this.s)*100}%, ${sf(this.l)*100}%${e===1?")":`, ${e})`}`}}function H_(e){return new dt(e>>16&255,e>>8&255,e&255,1)}function of(e,t,n,r){if(r<=0)e=t=n=NaN;return new dt(e,t,n,r)}function Z_(e,t,n,r){if(r<=0)e=t=n=NaN;else if(n<=0||n>=1)e=t=NaN;else if(t<=0)e=NaN;return new rr(e,t,n,r)}function o0(e){let t;if(e=`${e}`.trim().toLowerCase(),t=TW.exec(e)){let n=t[1].length,r=parseInt(t[1],16);if(n===6)return H_(r);if(n===3)return new dt(r>>8&15|r>>4&240,r>>4&15|r&240,(r&15)<<4|r&15,1);if(n===8)return of(r>>24&255,r>>16&255,r>>8&255,(r&255)/255);if(n===4)return of(r>>12&15|r>>8&240,r>>8&15|r>>4&240,r>>4&15|r&240,((r&15)<<4|r&15)/255);return null}if(t=MW.exec(e))return new dt(+t[1],+t[2],+t[3],1);if(t=OW.exec(e))return new dt(+t[1]*255/100,+t[2]*255/100,+t[3]*255/100,1);if(t=jW.exec(e))return of(+t[1],+t[2],+t[3],+t[4]);if(t=NW.exec(e))return of(+t[1]*255/100,+t[2]*255/100,+t[3]*255/100,+t[4]);if(t=RW.exec(e))return Z_(+t[1],+t[2]/100,+t[3]/100,1);if(t=LW.exec(e))return Z_(+t[1],+t[2]/100,+t[3]/100,+t[4]);if(Object.prototype.hasOwnProperty.call(K_,e))return H_(K_[e]);if(e==="transparent")return new dt(NaN,NaN,NaN,0);return null}function a0(e){if(!(e instanceof or))e=o0(e);if(!e)return new dt(NaN,NaN,NaN,NaN);let t=e.rgb();return new dt(t.r,t.g,t.b,t.opacity)}function t0(e,t,n,r){if(t===void 0&&n===void 0)return a0(e);return new dt(e,t,n,r==null?1:r)}function IE(e){if(e instanceof rr)return new rr(e.h,e.s,e.l,e.opacity);if(!(e instanceof or))e=o0(e);if(!e)return new rr(NaN,NaN,NaN,NaN);if(e instanceof rr)return e;let t=e.rgb(),n=t.r/255,r=t.g/255,i=t.b/255,s=Math.min(n,r,i),o=Math.max(n,r,i),a=NaN,l=o-s,c=(o+s)/2;if(l){if(n===o)a=(r-i)/l+(r<i?6:0);else if(r===o)a=(i-n)/l+2;else a=(n-r)/l+4;l/=c<0.5?o+s:2-o-s,a*=60}else l=c>0&&c<1?0:a;return new rr(a,l,c,t.opacity)}function eE(e,t,n,r){if(t===void 0&&n===void 0)return IE(e);return new rr(e,t,n,r==null?1:r)}var DE=Math.PI/180,zE=180/Math.PI,pf=18,BE=0.96422,WE=1,UE=0.82521,PE=0.13793103448275862,To=0.20689655172413793,qE=3*To*To,FW=To*To*To;function Wg(e){return e>FW?Math.pow(e,0.3333333333333333):e/qE+PE}function Ug(e){return e>To?e*e*e:qE*(e-PE)}function Pg(e){return 255*(e<=0.0031308?12.92*e:1.055*Math.pow(e,0.4166666666666667)-0.055)}function qg(e){return(e/=255)<=0.04045?e/12.92:Math.pow((e+0.055)/1.055,2.4)}function IW(e){if(e instanceof Kr)return new Kr(e.l,e.a,e.b,e.opacity);if(e instanceof Jr)return GE(e);if(!(e instanceof dt))e=a0(e);let t=e,n=qg(t.r),r=qg(t.g),i=qg(t.b),s=Wg((0.2225045*n+0.7168786*r+0.0606169*i)/WE),o,a;if(n===r&&r===i)o=a=s;else o=Wg((0.4360747*n+0.3850649*r+0.1430804*i)/BE),a=Wg((0.0139322*n+0.0971045*r+0.7141733*i)/UE);return new Kr(116*s-16,500*(o-s),200*(s-a),t.opacity)}class Kr extends or{l;a;b;constructor(e,t,n,r){super();this.l=+e,this.a=+t,this.b=+n,this.opacity=+r}brighter(e){return new Kr(this.l+pf*(e==null?1:e),this.a,this.b,this.opacity)}darker(e){return new Kr(this.l-pf*(e==null?1:e),this.a,this.b,this.opacity)}rgb(){let e=(this.l+16)/116,t=isNaN(this.a)?e:e+this.a/500,n=isNaN(this.b)?e:e-this.b/200,r=BE*Ug(t),i=WE*Ug(e),s=UE*Ug(n);return new dt(Pg(3.1338561*r-1.6168667*i-0.4906146*s),Pg(-0.9787684*r+1.9161415*i+0.033454*s),Pg(0.0719453*r-0.2289914*i+1.4052427*s),this.opacity)}}function DW(e){if(e instanceof Jr)return new Jr(e.h,e.c,e.l,e.opacity);if(!(e instanceof Kr))e=IW(e);let t=e;if(t.a===0&&t.b===0)return new Jr(NaN,0<t.l&&t.l<100?0:NaN,t.l,t.opacity);let n=Math.atan2(t.b,t.a)*zE;return new Jr(n<0?n+360:n,Math.sqrt(t.a*t.a+t.b*t.b),t.l,t.opacity)}function tE(e,t,n,r){if(t===void 0&&n===void 0)return DW(e);return new Jr(e,t,n,r==null?1:r)}function GE(e){if(isNaN(e.h))return new Kr(e.l,0,0,e.opacity);let t=e.h*DE;return new Kr(e.l,Math.cos(t)*e.c,Math.sin(t)*e.c,e.opacity)}class Jr extends or{h;c;l;constructor(e,t,n,r){super();this.h=+e,this.c=+t,this.l=+n,this.opacity=+r}brighter(e){return new Jr(this.h,this.c,this.l+pf*(e==null?1:e),this.opacity)}darker(e){return new Jr(this.h,this.c,this.l-pf*(e==null?1:e),this.opacity)}rgb(){return GE(this).rgb()}}var XE=-0.14861,l0=1.78277,c0=-0.29227,vf=-0.90649,Il=1.97294,nE=Il*vf,rE=Il*l0,iE=l0*c0-vf*XE;function zW(e){if(e instanceof Ms)return new Ms(e.h,e.s,e.l,e.opacity);if(!(e instanceof dt))e=a0(e);let t=e,n=t.r/255,r=t.g/255,i=t.b/255,s=(iE*i+nE*n-rE*r)/(iE+nE-rE),o=i-s,a=(Il*(r-s)-c0*o)/vf,l=Math.sqrt(a*a+o*o)/(Il*s*(1-s)),c=l?Math.atan2(a,o)*zE-120:NaN;return new Ms(c<0?c+360:c,l,s,t.opacity)}function sE(e,t,n,r){if(t===void 0&&n===void 0)return zW(e);return new Ms(e,t,n,r==null?1:r)}class Ms extends or{h;s;l;constructor(e,t,n,r){super();this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}brighter(e){return e=e==null?J_:Math.pow(J_,e),new Ms(this.h,this.s,this.l*e,this.opacity)}darker(e){return e=e==null?Y_:Math.pow(Y_,e),new Ms(this.h,this.s,this.l*e,this.opacity)}rgb(){let e=isNaN(this.h)?0:(this.h+120)*DE,t=+this.l,n=isNaN(this.s)?0:this.s*t*(1-t),r=Math.cos(e),i=Math.sin(e);return new dt(255*(t+n*(XE*r+l0*i)),255*(t+n*(c0*r+vf*i)),255*(t+n*(Il*r)),this.opacity)}}function VE(e,t,n,r,i){let s=e*e,o=s*e;return((1-3*e+3*s-o)*t+(4-6*s+3*o)*n+(1+3*e+3*s-3*o)*r+o*i)/6}function BW(e){let t=e.length-1;return function(n){let r=n<=0?n=0:n>=1?(n=1,t-1):Math.floor(n*t),i=e[r],s=e[r+1],o=r>0?e[r-1]:2*i-s,a=r<t-1?e[r+2]:2*s-i;return VE((n-r/t)*t,o,i,s,a)}}function WW(e){let t=e.length;return function(n){let r=Math.floor(((n%=1)<0?++n:n)*t),i=e[(r+t-1)%t],s=e[r%t],o=e[(r+1)%t],a=e[(r+2)%t];return VE((n-r/t)*t,i,s,o,a)}}var UW=(e)=>()=>e,xf=UW;function YE(e,t){return function(n){return e+n*t}}function PW(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}function u0(e,t){let n=t-e;return n?YE(e,n>180||n<-180?n-360*Math.round(n/360):n):xf(isNaN(e)?t:e)}function qW(e){return(e=+e)===1?xn:function(t,n){return n-t?PW(t,n,e):xf(isNaN(t)?n:t)}}function xn(e,t){let n=t-e;return n?YE(e,n):xf(isNaN(e)?t:e)}var oE=function e(t){let n=qW(t);function r(i,s){let o=t0(i),a=t0(s),l=n(o.r,a.r),c=n(o.g,a.g),u=n(o.b,a.b),f=xn(o.opacity,a.opacity);return function(d){return o.r=l(d),o.g=c(d),o.b=u(d),o.opacity=f(d),`${o}`}}return r.gamma=e,r}(1);function JE(e){return function(t){let n=t.length,r=Array(n),i=Array(n),s=Array(n),o,a;for(o=0;o<n;++o)a=t0(t[o]),r[o]=a.r||0,i[o]=a.g||0,s[o]=a.b||0;let l=e(r),c=e(i),u=e(s);return a.opacity=1,function(f){return a.r=l(f),a.g=c(f),a.b=u(f),`${a}`}}}var Nye=JE(BW),Rye=JE(WW);function GW(e,t){if(!t)t=[];let n=e?Math.min(t.length,e.length):0,r=ArrayBuffer.isView(t)?new t.constructor(t):Array.prototype.slice.call(t),i;return function(s){for(i=0;i<n;++i)r[i]=e[i]*(1-s)+t[i]*s;return r}}function XW(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function VW(e,t){let n=t?t.length:0,r=e?Math.min(n,e.length):0,i=Array(r),s=Array(n),o;for(o=0;o<r;++o)i[o]=f0(e[o],t[o]);for(;o<n;++o)s[o]=t[o];return function(a){for(o=0;o<r;++o)s[o]=i[o](a);return s}}function YW(e,t){let n=new Date,r=+e,i=+t;return function(s){return n.setTime(r*(1-s)+i*s),n}}function Tr(e,t){let n=+e,r=+t;return function(i){return n*(1-i)+r*i}}function JW(e,t){let n={},r={},i;if(e===null||typeof e!=="object")e={};if(t===null||typeof t!=="object")t={};for(i in t)if(i in e)n[i]=f0(e[i],t[i]);else r[i]=t[i];return function(s){for(i in n)r[i]=n[i](s);return r}}var n0=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Gg=new RegExp(n0.source,"g");function KW(e){return function(){return e}}function QW(e){return function(t){return`${e(t)}`}}function HW(e,t){let n=n0.lastIndex=Gg.lastIndex=0,r,i,s,o=-1,a=[],l=[],c=`${e}`,u=`${t}`;while((r=n0.exec(c))&&(i=Gg.exec(u))){if((s=i.index)>n)if(s=u.slice(n,s),a[o])a[o]+=s;else a[++o]=s;if(r===i)if(a[o])a[o]+=i[0];else a[++o]=i[0];else a[++o]=null,l.push({i:o,x:Tr(+r[0],+i[0])});n=Gg.lastIndex}if(n<u.length)if(s=u.slice(n),a[o])a[o]+=s;else a[++o]=s;return a.length<2?l[0]?QW(l[0].x):KW(u):(u=l.length,function(f){for(let d=0,h;d<u;++d)a[(h=l[d]).i]=h.x(f);return a.join("")})}function f0(e,t){let n=typeof t,r;return t==null||n==="boolean"?xf(t):(n==="number"?Tr:n==="string"?(r=o0(t))?(t=r,oE):HW:t instanceof or?oE:t instanceof Date?YW:XW(t)?GW:Array.isArray(t)?VW:typeof t.valueOf!=="function"&&typeof t.toString!=="function"||isNaN(t)?JW:Tr)(e,t)}function ZW(e,t){let n=+e,r=+t;return function(i){return Math.round(n*(1-i)+r*i)}}var aE=180/Math.PI,r0={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function KE(e,t,n,r,i,s){let o,a,l;if(o=Math.sqrt(e*e+t*t))e/=o,t/=o;if(l=e*n+t*r)n-=e*l,r-=t*l;if(a=Math.sqrt(n*n+r*r))n/=a,r/=a,l/=a;if(e*r<t*n)e=-e,t=-t,l=-l,o=-o;return{translateX:i,translateY:s,rotate:Math.atan2(t,e)*aE,skewX:Math.atan(l)*aE,scaleX:o,scaleY:a}}var af;function eU(e){let t=new(typeof DOMMatrix==="function"?DOMMatrix:globalThis.WebKitCSSMatrix)(`${e}`);return t.isIdentity?r0:KE(t.a,t.b,t.c,t.d,t.e,t.f)}function tU(e){if(e==null)return r0;if(!af)af=document.createElementNS("http://www.w3.org/2000/svg","g");af.setAttribute("transform",e);let t=af.transform.baseVal.consolidate();if(!t)return r0;let n=t.matrix;return KE(n.a,n.b,n.c,n.d,n.e,n.f)}function QE(e,t,n,r){function i(c){return c.length?`${c.pop()} `:""}function s(c,u,f,d,h,p){if(c!==f||u!==d){let m=h.push("translate(",null,t,null,n);p.push({i:m-4,x:Tr(c,f)},{i:m-2,x:Tr(u,d)})}else if(f||d)h.push(`translate(${f}${t}${d}${n}`)}function o(c,u,f,d){if(c!==u){if(c-u>180)u+=360;else if(u-c>180)c+=360;d.push({i:f.push(`${i(f)}rotate(`,null,r)-2,x:Tr(c,u)})}else if(u)f.push(`${i(f)}rotate(${u}${r}`)}function a(c,u,f,d){if(c!==u)d.push({i:f.push(`${i(f)}skewX(`,null,r)-2,x:Tr(c,u)});else if(u)f.push(`${i(f)}skewX(${u}${r}`)}function l(c,u,f,d,h,p){if(c!==f||u!==d){let m=h.push(`${i(h)}scale(`,null,",",null,")");p.push({i:m-4,x:Tr(c,f)},{i:m-2,x:Tr(u,d)})}else if(f!==1||d!==1)h.push(`${i(h)}scale(${f},${d})`)}return function(c,u){let f=[],d=[],h=e(c),p=e(u);return s(h.translateX,h.translateY,p.translateX,p.translateY,f,d),o(h.rotate,p.rotate,f,d),a(h.skewX,p.skewX,f,d),l(h.scaleX,h.scaleY,p.scaleX,p.scaleY,f,d),function(m){let g=-1,y=d.length,w;while(++g<y)f[(w=d[g]).i]=w.x(m);return f.join("")}}}var Lye=QE(eU,"px, ","px)","deg)"),Fye=QE(tU,", ",")",")");function lE(e){return((e=Math.exp(e))+1/e)/2}function nU(e){return((e=Math.exp(e))-1/e)/2}function rU(e){return((e=Math.exp(2*e))-1)/(e+1)}var Iye=function e(t,n,r){function i(s,o){let a=s[0],l=s[1],c=s[2],u=o[0],f=o[1],d=o[2],h=u-a,p=f-l,m=h*h+p*p,g,y;if(m<0.000000000001)y=Math.log(d/c)/t,g=function(w){return[a+w*h,l+w*p,c*Math.exp(t*w*y)]};else{let w=Math.sqrt(m),b=(d*d-c*c+r*m)/(2*c*n*w),v=(d*d-c*c-r*m)/(2*d*n*w),x=Math.log(Math.sqrt(b*b+1)-b);y=(Math.log(Math.sqrt(v*v+1)-v)-x)/t,g=function(S){let k=S*y,C=lE(x),T=c/(n*w)*(C*rU(t*k+x)-nU(x));return[a+T*h,l+T*p,c*C/lE(t*k+x)]}}return g.duration=y*1000*t/Math.SQRT2,g}return i.rho=function(s){let o=Math.max(0.001,+s),a=o*o,l=a*a;return e(o,a,l)},i}(Math.SQRT2,2,4);function HE(e){return function(t,n){let r=eE(t),i=eE(n),s=e(r.h,i.h),o=xn(r.s,i.s),a=xn(r.l,i.l),l=xn(r.opacity,i.opacity);return function(c){return r.h=s(c),r.s=o(c),r.l=a(c),r.opacity=l(c),`${r}`}}}var Dye=HE(u0),zye=HE(xn);function ZE(e){return function(t,n){let r=tE(t),i=tE(n),s=e(r.h,i.h),o=xn(r.c,i.c),a=xn(r.l,i.l),l=xn(r.opacity,i.opacity);return function(c){return r.h=s(c),r.c=o(c),r.l=a(c),r.opacity=l(c),`${r}`}}}var Bye=ZE(u0),Wye=ZE(xn);function e2(e){return function t(n){n=+n;function r(i,s){let o=sE(i),a=sE(s),l=e(o.h,a.h),c=xn(o.s,a.s),u=xn(o.l,a.l),f=xn(o.opacity,a.opacity);return function(d){return o.h=l(d),o.s=c(d),o.l=u(Math.pow(d,n)),o.opacity=f(d),`${o}`}}return r.gamma=t,r}(1)}var Uye=e2(u0),Pye=e2(xn);function iU(e){return function(){return e}}function sU(e){return+e}var cE=[0,1];function $o(e){return e}function i0(e,t){return(t-=e=+e)?function(n){return(n-e)/t}:iU(isNaN(t)?NaN:0.5)}function oU(e,t){let n;if(e>t)n=e,e=t,t=n;return function(r){return Math.max(e,Math.min(t,r))}}function aU(e,t,n){let r=e[0],i=e[1],s=t[0],o=t[1],a,l;if(i<r)a=i0(i,r),l=n(o,s);else a=i0(r,i),l=n(s,o);return function(c){return l(a(c))}}function lU(e,t,n){let r=Math.min(e.length,t.length)-1,i=Array(r),s=Array(r),o=-1;if(e[r]<e[0])e=e.slice().reverse(),t=t.slice().reverse();while(++o<r)i[o]=i0(e[o],e[o+1]),s[o]=n(t[o],t[o+1]);return function(a){let l=vW(e,a,1,r)-1;return s[l](i[l](a))}}function t2(e,t){return t.domain(e.domain()).range(e.range()).interpolate(e.interpolate()).clamp(e.clamp()).unknown(e.unknown())}function cU(){let e=cE,t=cE,n=f0,r,i,s,o=$o,a,l,c;function u(){let d=Math.min(e.length,t.length);if(o!==$o)o=oU(e[0],e[d-1]);return a=d>2?lU:aU,l=c=null,f}function f(d){return d==null||isNaN(d=+d)?s:(l||(l=a(e.map(r),t,n)))(r(o(d)))}return f.invert=function(d){return o(i((c||(c=a(t,e.map(r),Tr)))(d)))},f.domain=function(d){return arguments.length?(e=Array.from(d,sU),u()):e.slice()},f.range=function(d){return arguments.length?(t=Array.from(d),u()):t.slice()},f.rangeRound=function(d){return t=Array.from(d),n=ZW,u()},f.clamp=function(d){return arguments.length?(o=d?!0:$o,u()):o!==$o},f.interpolate=function(d){return arguments.length?(n=d,u()):n},f.unknown=function(d){return arguments.length?(s=d,f):s},function(d,h){return r=d,i=h,u()}}function n2(){return cU()($o,$o)}function uU(e){return Math.abs(e=Math.round(e))>=1000000000000000000000?e.toLocaleString("en").replace(/,/g,""):e.toString(10)}function mf(e,t){if(!isFinite(e)||e===0)return null;let n=t?e.toExponential(t-1):e.toExponential(),r=n.indexOf("e"),i=n.slice(0,r);return[i.length>1?i[0]+i.slice(2):i,+n.slice(r+1)]}function Mo(e){let t=mf(Math.abs(e));return t?t[1]:NaN}function fU(e,t){return function(n,r){let i=n.length,s=[],o=0,a=e[0],l=0;while(i>0&&a>0){if(l+a+1>r)a=Math.max(1,r-l);if(s.push(n.substring(i-=a,i+a)),(l+=a+1)>r)break;a=e[o=(o+1)%e.length]}return s.reverse().join(t)}}function dU(e){return function(t){return t.replace(/[0-9]/g,function(n){return e[+n]})}}var hU=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;class d0{fill;align;sign;symbol;zero;width;comma;precision;trim;type;constructor(e){this.fill=e.fill===void 0?" ":`${e.fill}`,this.align=e.align===void 0?">":`${e.align}`,this.sign=e.sign===void 0?"-":`${e.sign}`,this.symbol=e.symbol===void 0?"":`${e.symbol}`,this.zero=!!e.zero,this.width=e.width===void 0?void 0:+e.width,this.comma=!!e.comma,this.precision=e.precision===void 0?void 0:+e.precision,this.trim=!!e.trim,this.type=e.type===void 0?"":`${e.type}`}toString(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":`.${Math.max(0,this.precision|0)}`)+(this.trim?"~":"")+this.type}}function r2(e){let t=hU.exec(e);if(!t)throw Error(`invalid format: ${e}`);return new d0({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}r2.prototype=d0.prototype;var pU=r2,s0=pU;function mU(e){let t=-1,n=0;e:for(let r=e.length,i=1;i<r;++i)switch(e[i]){case".":t=n=i;break;case"0":if(t===0)t=i;n=i;break;default:if(!+e[i])break e;if(t>0)t=0;break}return t>0?e.slice(0,t)+e.slice(n+1):e}var Fl;function gU(e,t){let n=mf(e,t);if(!n)return Fl=void 0,e.toPrecision(t);let r=n[0],i=n[1];Fl=Math.max(-8,Math.min(8,Math.floor(i/3)))*3;let s=i-Fl+1,o=r.length;return s===o?r:s>o?`${r}${Array(s-o+1).join("0")}`:s>0?`${r.slice(0,s)}.${r.slice(s)}`:`0.${Array(1-s).join("0")}${mf(e,Math.max(0,t+s-1))[0]}`}function uE(e,t){let n=mf(e,t);if(!n)return`${e}`;let r=n[0],i=n[1];return i<0?`0.${Array(-i).join("0")}${r}`:r.length>i+1?`${r.slice(0,i+1)}.${r.slice(i+1)}`:`${r}${Array(i-r.length+2).join("0")}`}var yU={"%":(e,t)=>(e*100).toFixed(t),b:(e)=>Math.round(e).toString(2),c:(e)=>`${e}`,d:uU,e:(e,t)=>e.toExponential(t),f:(e,t)=>e.toFixed(t),g:(e,t)=>e.toPrecision(t),o:(e)=>Math.round(e).toString(8),p:(e,t)=>uE(e*100,t),r:uE,s:gU,X:(e)=>Math.round(e).toString(16).toUpperCase(),x:(e)=>Math.round(e).toString(16)},fE=yU;function dE(e){return e}var hE=Array.prototype.map,pE=["y","z","a","f","p","n","\xB5","m","","k","M","G","T","P","E","Z","Y"];function wU(e){let t=e.grouping===void 0||e.thousands===void 0?dE:fU(hE.call(e.grouping,Number),`${e.thousands}`),n=e.currency===void 0?"":e.currency[0]+"",r=e.currency===void 0?"":e.currency[1]+"",i=e.decimal===void 0?".":`${e.decimal}`,s=e.numerals===void 0?dE:dU(hE.call(e.numerals,String)),o=e.percent===void 0?"%":`${e.percent}`,a=e.minus===void 0?"\u2212":`${e.minus}`,l=e.nan===void 0?"NaN":`${e.nan}`;function c(f,d){let h=s0(f),p=h.fill,m=h.align,g=h.sign,y=h.symbol,w=h.zero,b=h.width,v=h.comma,x=h.precision,S=h.trim,k=h.type;if(k==="n")v=!0,k="g";else if(!fE[k]){if(x===void 0)x=12;S=!0,k="g"}if(w||p==="0"&&m==="=")w=!0,p="0",m="=";let C=(d&&d.prefix!==void 0?d.prefix:"")+(y==="$"?n:y==="#"&&/[boxX]/.test(k)?`0${k.toLowerCase()}`:""),T=(y==="$"?r:/[%p]/.test(k)?o:"")+(d&&d.suffix!==void 0?d.suffix:""),_=fE[k],E=/[defgprs%]/.test(k);x=x===void 0?6:/[gprs]/.test(k)?Math.max(1,Math.min(21,x)):Math.max(0,Math.min(20,x));function A($){let M=C,O=T,j,I,D;if(k==="c")O=_($)+O,$="";else{$=+$;let K=$<0||1/$<0;if($=isNaN($)?l:_(Math.abs($),x),S)$=mU($);if(K&&+$===0&&g!=="+")K=!1;if(M=(K?g==="("?g:a:g==="-"||g==="("?"":g)+M,O=(k==="s"&&!isNaN($)&&Fl!==void 0?pE[8+Fl/3]:"")+O+(K&&g==="("?")":""),E){j=-1,I=$.length;while(++j<I)if(D=$.charCodeAt(j),48>D||D>57){O=(D===46?i+$.slice(j+1):$.slice(j))+O,$=$.slice(0,j);break}}}if(v&&!w)$=t($,1/0);let W=M.length+$.length+O.length,G=W<(b??0)?Array((b??0)-W+1).join(p):"";if(v&&w)$=t(G+$,G.length?(b??0)-O.length:1/0),G="";switch(m){case"<":$=M+$+O+G;break;case"=":$=M+G+$+O;break;case"^":{let K=G.length>>1;$=G.slice(0,K)+M+$+O+G.slice(K);break}default:$=G+M+$+O;break}return s($)}return A.toString=function(){return`${h}`},A}function u(f,d){let h=s0(f);h.type="f";let p=Math.max(-8,Math.min(8,Math.floor(Mo(d)/3)))*3,m=Math.pow(10,-p),g=c(`${h}`,{suffix:pE[8+p/3]});return function(y){return g(m*y)}}return{format:c,formatPrefix:u}}var lf,i2,s2;bU({thousands:",",grouping:[3],currency:["$",""]});function bU(e){return lf=wU(e),i2=lf.format,s2=lf.formatPrefix,lf}function vU(e){return Math.max(0,-Mo(Math.abs(e)))}function xU(e,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(Mo(t)/3)))*3-Mo(Math.abs(e)))}function SU(e,t){return e=Math.abs(e),t=Math.abs(t)-e,Math.max(0,Mo(t)-Mo(e))+1}function kU(e,t,n,r){let i=$W(e,t,n),s,o=s0(r==null?",f":r);switch(o.type){case"s":{let a=Math.max(Math.abs(e),Math.abs(t));if(o.precision==null&&!isNaN(s=xU(i,a)))o.precision=s;return s2(o.toString(),a)}case"":case"e":case"g":case"p":case"r":{if(o.precision==null&&!isNaN(s=SU(i,Math.max(Math.abs(e),Math.abs(t)))))o.precision=s-(o.type==="e"?1:0);break}case"f":case"%":{if(o.precision==null&&!isNaN(s=vU(i)))o.precision=s-(o.type==="%"?1:0)*2;break}}return i2(o.toString())}function _U(e){let t=e.domain;return e.ticks=function(n){let r=t();return AW(r[0],r[r.length-1],n==null?10:n)},e.tickFormat=function(n,r){let i=t();return kU(i[0],i[i.length-1],n==null?10:n,r)},e.nice=function(n){if(n==null)n=10;let r=t(),i=0,s=r.length-1,o=r[i],a=r[s],l,c,u=10;if(a<o)c=o,o=a,a=c,c=i,i=s,s=c;while(u-- >0){if(c=e0(o,a,n),c===l)return r[i]=o,r[s]=a,e.domain(r);else if(c>0)o=Math.floor(o/c)*c,a=Math.ceil(a/c)*c;else if(c<0)o=Math.ceil(o*c)/c,a=Math.floor(a*c)/c;else break;l=c}return e},e}function Os(...e){let t=n2();return t.copy=function(){return t2(t,Os())},FE.apply(t,arguments),_U(t)}function EU(e,t){e=e.slice();let n=0,r=e.length-1,i=e[n],s=e[r],o;if(s<i)o=n,n=r,r=o,o=i,i=s,s=o;return e[n]=t.floor(i),e[r]=t.ceil(s),e}var Xg=new Date,Vg=new Date;function mt(e,t,n,r){function i(s){let o=s==null?new Date:new Date(+s);return e(o),o}if(i.floor=(s)=>{let o=new Date(+s);return e(o),o},i.ceil=(s)=>{let o=new Date(+s-1);return e(o),t(o,1),e(o),o},i.round=(s)=>{let o=i(s),a=i.ceil(s);return+s-+o<+a-+s?o:a},i.offset=(s,o)=>{let a=new Date(+s);return t(a,o==null?1:Math.floor(o)),a},i.range=(s,o,a)=>{let l=[],c=i.ceil(s),u=a==null?1:Math.floor(a);if(!(c<new Date(+o))||!(u>0))return l;let f;do f=new Date(+c),l.push(f),t(c,u),e(c);while(f<c&&c<new Date(+o));return l},i.filter=(s)=>{return mt((o)=>{if(o>=o)while(e(o),!s(o))o.setTime(+o-1)},(o,a)=>{if(o>=o)if(a<0)while(++a<=0)while(t(o,-1),!s(o));else while(--a>=0)while(t(o,1),!s(o));})},n)i.count=(s,o)=>{return Xg.setTime(+s),Vg.setTime(+o),e(Xg),e(Vg),Math.floor(n(Xg,Vg))},i.every=(s)=>{return s=Math.floor(s),!isFinite(s)||!(s>0)?null:!(s>1)?i:i.filter(r?(o)=>r(o)%s===0:(o)=>i.count(0,o)%s===0)};return i}var gf=mt(()=>{},(e,t)=>{e.setTime(+e+t)},(e,t)=>{return+t-+e});gf.every=(e)=>{if(e=Math.floor(e),!isFinite(e)||!(e>0))return null;if(!(e>1))return gf;return mt((t)=>{t.setTime(Math.floor(+t/e)*e)},(t,n)=>{t.setTime(+t+n*e)},(t,n)=>{return(+n-+t)/e})};var qye=gf.range,Wi=1000,ir=60000,Ui=3600000,Oo=86400000,h0=604800000,mE=2592000000,Yg=31536000000,Co=mt((e)=>{e.setTime(+e-e.getMilliseconds())},(e,t)=>{e.setTime(+e+t*Wi)},(e,t)=>{return(+t-+e)/Wi},(e)=>{return e.getUTCSeconds()}),Gye=Co.range,p0=mt((e)=>{e.setTime(+e-e.getMilliseconds()-e.getSeconds()*Wi)},(e,t)=>{e.setTime(+e+t*ir)},(e,t)=>{return(+t-+e)/ir},(e)=>{return e.getMinutes()}),Xye=p0.range,o2=mt((e)=>{e.setUTCSeconds(0,0)},(e,t)=>{e.setTime(+e+t*ir)},(e,t)=>{return(+t-+e)/ir},(e)=>{return e.getUTCMinutes()}),Vye=o2.range,m0=mt((e)=>{e.setTime(+e-e.getMilliseconds()-e.getSeconds()*Wi-e.getMinutes()*ir)},(e,t)=>{e.setTime(+e+t*Ui)},(e,t)=>{return(+t-+e)/Ui},(e)=>{return e.getHours()}),Yye=m0.range,a2=mt((e)=>{e.setUTCMinutes(0,0,0)},(e,t)=>{e.setTime(+e+t*Ui)},(e,t)=>{return(+t-+e)/Ui},(e)=>{return e.getUTCHours()}),Jye=a2.range,g0=mt((e)=>{e.setHours(0,0,0,0)},(e,t)=>{e.setDate(e.getDate()+t)},(e,t)=>(+t-+e-(t.getTimezoneOffset()-e.getTimezoneOffset())*ir)/Oo,(e)=>e.getDate()-1),Kye=g0.range,AU=mt((e)=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>{return(+t-+e)/Oo},(e)=>{return e.getUTCDate()-1}),Qye=AU.range,l2=mt((e)=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>{return(+t-+e)/Oo},(e)=>{return Math.floor(+e/Oo)}),Hye=l2.range;function js(e){return mt((t)=>{t.setDate(t.getDate()-(t.getDay()+7-e)%7),t.setHours(0,0,0,0)},(t,n)=>{t.setDate(t.getDate()+n*7)},(t,n)=>{return(+n-+t-(n.getTimezoneOffset()-t.getTimezoneOffset())*ir)/h0})}var y0=js(0),$U=js(1),CU=js(2),TU=js(3),MU=js(4),OU=js(5),jU=js(6),Zye=y0.range,ewe=$U.range,twe=CU.range,nwe=TU.range,rwe=MU.range,iwe=OU.range,swe=jU.range;function Ns(e){return mt((t)=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-e)%7),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCDate(t.getUTCDate()+n*7)},(t,n)=>{return(+n-+t)/h0})}var c2=Ns(0),NU=Ns(1),RU=Ns(2),LU=Ns(3),FU=Ns(4),IU=Ns(5),DU=Ns(6),owe=c2.range,awe=NU.range,lwe=RU.range,cwe=LU.range,uwe=FU.range,fwe=IU.range,dwe=DU.range,w0=mt((e)=>{e.setDate(1),e.setHours(0,0,0,0)},(e,t)=>{e.setMonth(e.getMonth()+t)},(e,t)=>{return t.getMonth()-e.getMonth()+(t.getFullYear()-e.getFullYear())*12},(e)=>{return e.getMonth()}),hwe=w0.range,u2=mt((e)=>{e.setUTCDate(1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCMonth(e.getUTCMonth()+t)},(e,t)=>{return t.getUTCMonth()-e.getUTCMonth()+(t.getUTCFullYear()-e.getUTCFullYear())*12},(e)=>{return e.getUTCMonth()}),pwe=u2.range,Sf=mt((e)=>{e.setMonth(0,1),e.setHours(0,0,0,0)},(e,t)=>{e.setFullYear(e.getFullYear()+t)},(e,t)=>{return t.getFullYear()-e.getFullYear()},(e)=>{return e.getFullYear()});Sf.every=(e)=>{return e=Math.floor(e),!isFinite(e)||!(e>0)?null:mt((t)=>{t.setFullYear(Math.floor(t.getFullYear()/e)*e),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,n)=>{t.setFullYear(t.getFullYear()+n*e)})};var mwe=Sf.range,b0=mt((e)=>{e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCFullYear(e.getUTCFullYear()+t)},(e,t)=>{return t.getUTCFullYear()-e.getUTCFullYear()},(e)=>{return e.getUTCFullYear()});b0.every=(e)=>{return e=Math.floor(e),!isFinite(e)||!(e>0)?null:mt((t)=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/e)*e),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCFullYear(t.getUTCFullYear()+n*e)})};var gwe=b0.range;function uf(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function zU(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function v0(e){let t,n,r;if(e.length!==2)t=uf,n=(a,l)=>uf(e(a),l),r=(a,l)=>e(a)-l;else t=e===uf||e===zU?e:BU,n=e,r=e;function i(a,l,c=0,u=a.length){if(c<u){if(t(l,l)!==0)return u;do{let f=c+u>>>1;if(n(a[f],l)<0)c=f+1;else u=f}while(c<u)}return c}function s(a,l,c=0,u=a.length){if(c<u){if(t(l,l)!==0)return u;do{let f=c+u>>>1;if(n(a[f],l)<=0)c=f+1;else u=f}while(c<u)}return c}function o(a,l,c=0,u=a.length){let f=i(a,l,c,u-1);return f>c&&r(a[f-1],l)>-r(a[f],l)?f-1:f}return{left:i,center:o,right:s}}function BU(){return 0}function WU(e){return e===null?NaN:+e}var f2=v0(uf),ywe=f2.right,wwe=f2.left,bwe=v0(WU).center,vwe=d2(h2),xwe=d2(UU);function d2(e){return function(t,n,r=n){if(!((n=+n)>=0))throw RangeError("invalid rx");if(!((r=+r)>=0))throw RangeError("invalid ry");let{data:i,width:s,height:o}=t;if(!((s=Math.floor(s))>=0))throw RangeError("invalid width");if(!((o=Math.floor(o!==void 0?o:i.length/s))>=0))throw RangeError("invalid height");if(!s||!o||!n&&!r)return t;let a=n&&e(n),l=r&&e(r),c=i.slice();if(a&&l)So(a,c,i,s,o),So(a,i,c,s,o),So(a,c,i,s,o),ko(l,i,c,s,o),ko(l,c,i,s,o),ko(l,i,c,s,o);else if(a)So(a,i,c,s,o),So(a,c,i,s,o),So(a,i,c,s,o);else if(l)ko(l,i,c,s,o),ko(l,c,i,s,o),ko(l,i,c,s,o);return t}}function So(e,t,n,r,i){for(let s=0,o=r*i;s<o;)e(t,n,s,s+=r,1)}function ko(e,t,n,r,i){for(let s=0,o=r*i;s<r;++s)e(t,n,s,s+o,r)}function UU(e){let t=h2(e);return(n,r,i,s,o)=>{i<<=2,s<<=2,o<<=2,t(n,r,i+0,s+0,o),t(n,r,i+1,s+1,o),t(n,r,i+2,s+2,o),t(n,r,i+3,s+3,o)}}function h2(e){let t=Math.floor(e);if(t===e)return PU(e);let n=e-t,r=2*e+1;return(i,s,o,a,l)=>{if(!((a-=l)>=o))return;let c=t*s[o],u=l*t,f=u+l;for(let d=o,h=o+u;d<h;d+=l)c+=s[Math.min(a,d)];for(let d=o,h=a;d<=h;d+=l)c+=s[Math.min(a,d+u)],i[d]=(c+n*(s[Math.max(o,d-f)]+s[Math.min(a,d+f)]))/r,c-=s[Math.max(o,d-u)]}}function PU(e){let t=2*e+1;return(n,r,i,s,o)=>{if(!((s-=o)>=i))return;let a=e*r[i],l=o*e;for(let c=i,u=i+l;c<u;c+=o)a+=r[Math.min(s,c)];for(let c=i,u=s;c<=u;c+=o)a+=r[Math.min(s,c+l)],n[c]=a/t,a-=r[Math.max(i,c-l)]}}var p2=Array.prototype,Swe=p2.slice,kwe=p2.map,qU=Math.sqrt(50),GU=Math.sqrt(10),XU=Math.sqrt(2);function m2(e,t,n){let r=(t-e)/Math.max(0,n),i=Math.floor(Math.log10(r)),s=r/Math.pow(10,i),o=s>=qU?10:s>=GU?5:s>=XU?2:1,a,l,c;if(i<0){if(c=Math.pow(10,-i)/o,a=Math.round(e*c),l=Math.round(t*c),a/c<e)++a;if(l/c>t)--l;c=-c}else{if(c=Math.pow(10,i)*o,a=Math.round(e/c),l=Math.round(t/c),a*c<e)++a;if(l*c>t)--l}if(l<a&&0.5<=n&&n<2)return m2(e,t,n*2);return[a,l,c]}function gE(e,t,n){return t=+t,e=+e,n=+n,m2(e,t,n)[2]}function yE(e,t,n){t=+t,e=+e,n=+n;let r=t<e,i=r?gE(t,e,n):gE(e,t,n);return(r?-1:1)*(i<0?1/-i:i)}function VU(e){return function(t,n=0,r=t.length){let i=r-(n=+n);while(i){let s=e()*i--|0,o=t[i+n];t[i+n]=t[s+n],t[s+n]=o}return t}}var _we=VU(Math.random);function g2(e,t,n,r,i,s){let o=[[Co,1,Wi],[Co,5,5*Wi],[Co,15,15*Wi],[Co,30,30*Wi],[s,1,ir],[s,5,5*ir],[s,15,15*ir],[s,30,30*ir],[i,1,Ui],[i,3,3*Ui],[i,6,6*Ui],[i,12,12*Ui],[r,1,Oo],[r,2,2*Oo],[n,1,h0],[t,1,mE],[t,3,3*mE],[e,1,Yg]];function a(c,u,f){let d=u<c;if(d)[c,u]=[u,c];let h=f&&typeof f.range==="function"?f:l(c,u,f),p=h?h.range(c,+u+1):[];return d?p.reverse():p}function l(c,u,f){let d=Math.abs(+u-+c)/f,h=v0(([,,g])=>g).right(o,d);if(h===o.length)return e.every(yE(+c/Yg,+u/Yg,f));if(h===0)return gf.every(Math.max(yE(+c,+u,f),1));let[p,m]=o[d/o[h-1][2]<o[h][2]/d?h-1:h];return p.every(m)}return[a,l]}var y2=g2(b0,u2,c2,l2,a2,o2),w2=g2(Sf,w0,y0,g0,m0,p0),Ewe=y2[0],Awe=y2[1],YU=w2[0],JU=w2[1],Jg=new Date,Kg=new Date;function gt(e,t,n,r){function i(s){let o=s==null?new Date:new Date(+s);return e(o),o}if(i.floor=(s)=>{let o=new Date(+s);return e(o),o},i.ceil=(s)=>{let o=new Date(+s-1);return e(o),t(o,1),e(o),o},i.round=(s)=>{let o=i(s),a=i.ceil(s);return+s-+o<+a-+s?o:a},i.offset=(s,o)=>{let a=new Date(+s);return t(a,o==null?1:Math.floor(o)),a},i.range=(s,o,a)=>{let l=[],c=i.ceil(s),u=a==null?1:Math.floor(a);if(!(c<new Date(+o))||!(u>0))return l;let f;do f=new Date(+c),l.push(f),t(c,u),e(c);while(f<c&&c<new Date(+o));return l},i.filter=(s)=>{return gt((o)=>{if(o>=o)while(e(o),!s(o))o.setTime(+o-1)},(o,a)=>{if(o>=o)if(a<0)while(++a<=0)while(t(o,-1),!s(o));else while(--a>=0)while(t(o,1),!s(o));})},n)i.count=(s,o)=>{return Jg.setTime(+s),Kg.setTime(+o),e(Jg),e(Kg),Math.floor(n(Jg,Kg))},i.every=(s)=>{return s=Math.floor(s),!isFinite(s)||!(s>0)?null:!(s>1)?i:i.filter(r?(o)=>r(o)%s===0:(o)=>i.count(0,o)%s===0)};return i}var yf=gt(()=>{},(e,t)=>{e.setTime(+e+t)},(e,t)=>{return+t-+e});yf.every=(e)=>{if(e=Math.floor(e),!isFinite(e)||!(e>0))return null;if(!(e>1))return yf;return gt((t)=>{t.setTime(Math.floor(+t/e)*e)},(t,n)=>{t.setTime(+t+n*e)},(t,n)=>{return(+n-+t)/e})};var $we=yf.range,Pi=1000,sr=60000,qi=3600000,jo=86400000,x0=604800000,wE=2592000000,Qg=31536000000,Ll=gt((e)=>{e.setTime(+e-e.getMilliseconds())},(e,t)=>{e.setTime(+e+t*Pi)},(e,t)=>{return(+t-+e)/Pi},(e)=>{return e.getUTCSeconds()}),Cwe=Ll.range,b2=gt((e)=>{e.setTime(+e-e.getMilliseconds()-e.getSeconds()*Pi)},(e,t)=>{e.setTime(+e+t*sr)},(e,t)=>{return(+t-+e)/sr},(e)=>{return e.getMinutes()}),Twe=b2.range,v2=gt((e)=>{e.setUTCSeconds(0,0)},(e,t)=>{e.setTime(+e+t*sr)},(e,t)=>{return(+t-+e)/sr},(e)=>{return e.getUTCMinutes()}),Mwe=v2.range,x2=gt((e)=>{e.setTime(+e-e.getMilliseconds()-e.getSeconds()*Pi-e.getMinutes()*sr)},(e,t)=>{e.setTime(+e+t*qi)},(e,t)=>{return(+t-+e)/qi},(e)=>{return e.getHours()}),Owe=x2.range,S2=gt((e)=>{e.setUTCMinutes(0,0,0)},(e,t)=>{e.setTime(+e+t*qi)},(e,t)=>{return(+t-+e)/qi},(e)=>{return e.getUTCHours()}),jwe=S2.range,kf=gt((e)=>{e.setHours(0,0,0,0)},(e,t)=>{e.setDate(e.getDate()+t)},(e,t)=>(+t-+e-(t.getTimezoneOffset()-e.getTimezoneOffset())*sr)/jo,(e)=>e.getDate()-1),Nwe=kf.range,S0=gt((e)=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>{return(+t-+e)/jo},(e)=>{return e.getUTCDate()-1}),Rwe=S0.range,k2=gt((e)=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>{return(+t-+e)/jo},(e)=>{return Math.floor(+e/jo)}),Lwe=k2.range;function Rs(e){return gt((t)=>{t.setDate(t.getDate()-(t.getDay()+7-e)%7),t.setHours(0,0,0,0)},(t,n)=>{t.setDate(t.getDate()+n*7)},(t,n)=>{return(+n-+t-(n.getTimezoneOffset()-t.getTimezoneOffset())*sr)/x0})}var k0=Rs(0),wf=Rs(1),KU=Rs(2),QU=Rs(3),No=Rs(4),HU=Rs(5),ZU=Rs(6),Fwe=k0.range,Iwe=wf.range,Dwe=KU.range,zwe=QU.range,Bwe=No.range,Wwe=HU.range,Uwe=ZU.range;function Ls(e){return gt((t)=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-e)%7),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCDate(t.getUTCDate()+n*7)},(t,n)=>{return(+n-+t)/x0})}var _0=Ls(0),bf=Ls(1),eP=Ls(2),tP=Ls(3),Ro=Ls(4),nP=Ls(5),rP=Ls(6),Pwe=_0.range,qwe=bf.range,Gwe=eP.range,Xwe=tP.range,Vwe=Ro.range,Ywe=nP.range,Jwe=rP.range,_2=gt((e)=>{e.setDate(1),e.setHours(0,0,0,0)},(e,t)=>{e.setMonth(e.getMonth()+t)},(e,t)=>{return t.getMonth()-e.getMonth()+(t.getFullYear()-e.getFullYear())*12},(e)=>{return e.getMonth()}),Kwe=_2.range,E2=gt((e)=>{e.setUTCDate(1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCMonth(e.getUTCMonth()+t)},(e,t)=>{return t.getUTCMonth()-e.getUTCMonth()+(t.getUTCFullYear()-e.getUTCFullYear())*12},(e)=>{return e.getUTCMonth()}),Qwe=E2.range,Gi=gt((e)=>{e.setMonth(0,1),e.setHours(0,0,0,0)},(e,t)=>{e.setFullYear(e.getFullYear()+t)},(e,t)=>{return t.getFullYear()-e.getFullYear()},(e)=>{return e.getFullYear()});Gi.every=(e)=>{return e=Math.floor(e),!isFinite(e)||!(e>0)?null:gt((t)=>{t.setFullYear(Math.floor(t.getFullYear()/e)*e),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,n)=>{t.setFullYear(t.getFullYear()+n*e)})};var Hwe=Gi.range,Xi=gt((e)=>{e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCFullYear(e.getUTCFullYear()+t)},(e,t)=>{return t.getUTCFullYear()-e.getUTCFullYear()},(e)=>{return e.getUTCFullYear()});Xi.every=(e)=>{return e=Math.floor(e),!isFinite(e)||!(e>0)?null:gt((t)=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/e)*e),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCFullYear(t.getUTCFullYear()+n*e)})};var Zwe=Xi.range;function ff(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function iP(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function E0(e){let t,n,r;if(e.length!==2)t=ff,n=(a,l)=>ff(e(a),l),r=(a,l)=>e(a)-l;else t=e===ff||e===iP?e:sP,n=e,r=e;function i(a,l,c=0,u=a.length){if(c<u){if(t(l,l)!==0)return u;do{let f=c+u>>>1;if(n(a[f],l)<0)c=f+1;else u=f}while(c<u)}return c}function s(a,l,c=0,u=a.length){if(c<u){if(t(l,l)!==0)return u;do{let f=c+u>>>1;if(n(a[f],l)<=0)c=f+1;else u=f}while(c<u)}return c}function o(a,l,c=0,u=a.length){let f=i(a,l,c,u-1);return f>c&&r(a[f-1],l)>-r(a[f],l)?f-1:f}return{left:i,center:o,right:s}}function sP(){return 0}function oP(e){return e===null?NaN:+e}var A2=E0(ff),ebe=A2.right,tbe=A2.left,nbe=E0(oP).center,rbe=$2(C2),ibe=$2(aP);function $2(e){return function(t,n,r=n){if(!((n=+n)>=0))throw RangeError("invalid rx");if(!((r=+r)>=0))throw RangeError("invalid ry");let{data:i,width:s,height:o}=t;if(!((s=Math.floor(s))>=0))throw RangeError("invalid width");if(!((o=Math.floor(o!==void 0?o:i.length/s))>=0))throw RangeError("invalid height");if(!s||!o||!n&&!r)return t;let a=n&&e(n),l=r&&e(r),c=i.slice();if(a&&l)_o(a,c,i,s,o),_o(a,i,c,s,o),_o(a,c,i,s,o),Eo(l,i,c,s,o),Eo(l,c,i,s,o),Eo(l,i,c,s,o);else if(a)_o(a,i,c,s,o),_o(a,c,i,s,o),_o(a,i,c,s,o);else if(l)Eo(l,i,c,s,o),Eo(l,c,i,s,o),Eo(l,i,c,s,o);return t}}function _o(e,t,n,r,i){for(let s=0,o=r*i;s<o;)e(t,n,s,s+=r,1)}function Eo(e,t,n,r,i){for(let s=0,o=r*i;s<r;++s)e(t,n,s,s+o,r)}function aP(e){let t=C2(e);return(n,r,i,s,o)=>{i<<=2,s<<=2,o<<=2,t(n,r,i+0,s+0,o),t(n,r,i+1,s+1,o),t(n,r,i+2,s+2,o),t(n,r,i+3,s+3,o)}}function C2(e){let t=Math.floor(e);if(t===e)return lP(e);let n=e-t,r=2*e+1;return(i,s,o,a,l)=>{if(!((a-=l)>=o))return;let c=t*s[o],u=l*t,f=u+l;for(let d=o,h=o+u;d<h;d+=l)c+=s[Math.min(a,d)];for(let d=o,h=a;d<=h;d+=l)c+=s[Math.min(a,d+u)],i[d]=(c+n*(s[Math.max(o,d-f)]+s[Math.min(a,d+f)]))/r,c-=s[Math.max(o,d-u)]}}function lP(e){let t=2*e+1;return(n,r,i,s,o)=>{if(!((s-=o)>=i))return;let a=e*r[i],l=o*e;for(let c=i,u=i+l;c<u;c+=o)a+=r[Math.min(s,c)];for(let c=i,u=s;c<=u;c+=o)a+=r[Math.min(s,c+l)],n[c]=a/t,a-=r[Math.max(i,c-l)]}}var T2=Array.prototype,sbe=T2.slice,obe=T2.map,cP=Math.sqrt(50),uP=Math.sqrt(10),fP=Math.sqrt(2);function M2(e,t,n){let r=(t-e)/Math.max(0,n),i=Math.floor(Math.log10(r)),s=r/Math.pow(10,i),o=s>=cP?10:s>=uP?5:s>=fP?2:1,a,l,c;if(i<0){if(c=Math.pow(10,-i)/o,a=Math.round(e*c),l=Math.round(t*c),a/c<e)++a;if(l/c>t)--l;c=-c}else{if(c=Math.pow(10,i)*o,a=Math.round(e/c),l=Math.round(t/c),a*c<e)++a;if(l*c>t)--l}if(l<a&&0.5<=n&&n<2)return M2(e,t,n*2);return[a,l,c]}function bE(e,t,n){return t=+t,e=+e,n=+n,M2(e,t,n)[2]}function vE(e,t,n){t=+t,e=+e,n=+n;let r=t<e,i=r?bE(t,e,n):bE(e,t,n);return(r?-1:1)*(i<0?1/-i:i)}function dP(e){return function(t,n=0,r=t.length){let i=r-(n=+n);while(i){let s=e()*i--|0,o=t[i+n];t[i+n]=t[s+n],t[s+n]=o}return t}}var abe=dP(Math.random);function O2(e,t,n,r,i,s){let o=[[Ll,1,Pi],[Ll,5,5*Pi],[Ll,15,15*Pi],[Ll,30,30*Pi],[s,1,sr],[s,5,5*sr],[s,15,15*sr],[s,30,30*sr],[i,1,qi],[i,3,3*qi],[i,6,6*qi],[i,12,12*qi],[r,1,jo],[r,2,2*jo],[n,1,x0],[t,1,wE],[t,3,3*wE],[e,1,Qg]];function a(c,u,f){let d=u<c;if(d)[c,u]=[u,c];let h=f&&typeof f.range==="function"?f:l(c,u,f),p=h?h.range(c,+u+1):[];return d?p.reverse():p}function l(c,u,f){let d=Math.abs(+u-+c)/f,h=E0(([,,g])=>g).right(o,d);if(h===o.length)return e.every(vE(+c/Qg,+u/Qg,f));if(h===0)return yf.every(Math.max(vE(+c,+u,f),1));let[p,m]=o[d/o[h-1][2]<o[h][2]/d?h-1:h];return p.every(m)}return[a,l]}var j2=O2(Xi,E2,_0,k2,S2,v2),N2=O2(Gi,_2,k0,kf,x2,b2),lbe=j2[0],cbe=j2[1],ube=N2[0],fbe=N2[1];function Hg(e){if(0<=e.y&&e.y<100){let t=new Date(-1,e.m,e.d,e.H,e.M,e.S,e.L);return t.setFullYear(e.y),t}return new Date(e.y,e.m,e.d,e.H,e.M,e.S,e.L)}function Zg(e){if(0<=e.y&&e.y<100){let t=new Date(Date.UTC(-1,e.m,e.d,e.H,e.M,e.S,e.L));return t.setUTCFullYear(e.y),t}return new Date(Date.UTC(e.y,e.m,e.d,e.H,e.M,e.S,e.L))}function jl(e,t,n){return{y:e,m:t,d:n,H:0,M:0,S:0,L:0}}function hP(e){let{dateTime:t,date:n,time:r,periods:i,days:s,shortDays:o,months:a,shortMonths:l}=e,c=Nl(i),u=Rl(i),f=Nl(s),d=Rl(s),h=Nl(o),p=Rl(o),m=Nl(a),g=Rl(a),y=Nl(l),w=Rl(l),b={a:I,A:D,b:W,B:G,c:null,d:AE,e:AE,f:FP,g:XP,G:YP,H:NP,I:RP,j:LP,L:R2,m:IP,M:DP,p:K,q:_e,Q:TE,s:ME,S:zP,u:BP,U:WP,V:UP,w:PP,W:qP,x:null,X:null,y:GP,Y:VP,Z:JP,"%":CE},v={a:se,A:P,b:ee,B:fe,c:null,d:$E,e:$E,f:ZP,g:c8,G:f8,H:KP,I:QP,j:HP,L:F2,m:e8,M:t8,p:q,q:F,Q:TE,s:ME,S:n8,u:r8,U:i8,V:s8,w:o8,W:a8,x:null,X:null,y:l8,Y:u8,Z:d8,"%":CE},x={a:_,A:E,b:A,B:$,c:M,d:_E,e:_E,f:TP,g:kE,G:SE,H:EE,I:EE,j:EP,L:CP,m:_P,M:AP,p:T,q:kP,Q:OP,s:jP,S:$P,u:wP,U:bP,V:vP,w:yP,W:xP,x:O,X:j,y:kE,Y:SE,Z:SP,"%":MP};b.x=S(n,b),b.X=S(r,b),b.c=S(t,b),v.x=S(n,v),v.X=S(r,v),v.c=S(t,v);function S(N,L){return function(z){let R=[],X=-1,Y=0,te=N.length,me,nn,Ne;if(!(z instanceof Date))z=new Date(+z);while(++X<te)if(N.charCodeAt(X)===37){if(R.push(N.slice(Y,X)),(nn=xE[me=N.charAt(++X)])!=null)me=N.charAt(++X);else nn=me==="e"?" ":"0";if(Ne=L[me])me=Ne(z,nn);R.push(me),Y=X+1}return R.push(N.slice(Y,X)),R.join("")}}function k(N,L){return function(z){let R=jl(1900,void 0,1),X=C(R,N,z+="",0),Y,te;if(X!=z.length)return null;if("Q"in R)return new Date(R.Q);if("s"in R)return new Date(R.s*1000+("L"in R?R.L:0));if(L&&!("Z"in R))R.Z=0;if("p"in R)R.H=R.H%12+R.p*12;if(R.m===void 0)R.m="q"in R?R.q:0;if("V"in R){if(R.V<1||R.V>53)return null;if(!("w"in R))R.w=1;if("Z"in R)Y=Zg(jl(R.y,0,1)),te=Y.getUTCDay(),Y=te>4||te===0?bf.ceil(Y):bf(Y),Y=S0.offset(Y,(R.V-1)*7),R.y=Y.getUTCFullYear(),R.m=Y.getUTCMonth(),R.d=Y.getUTCDate()+(R.w+6)%7;else Y=Hg(jl(R.y,0,1)),te=Y.getDay(),Y=te>4||te===0?wf.ceil(Y):wf(Y),Y=kf.offset(Y,(R.V-1)*7),R.y=Y.getFullYear(),R.m=Y.getMonth(),R.d=Y.getDate()+(R.w+6)%7}else if("W"in R||"U"in R){if(!("w"in R))R.w="u"in R?R.u%7:("W"in R)?1:0;te="Z"in R?Zg(jl(R.y,0,1)).getUTCDay():Hg(jl(R.y,0,1)).getDay(),R.m=0,R.d="W"in R?(R.w+6)%7+R.W*7-(te+5)%7:R.w+R.U*7-(te+6)%7}if("Z"in R)return R.H+=R.Z/100|0,R.M+=R.Z%100,Zg(R);return Hg(R)}}function C(N,L,z,R){let X=0,Y=L.length,te=z.length,me,nn;while(X<Y){if(R>=te)return-1;if(me=L.charCodeAt(X++),me===37){if(me=L.charAt(X++),nn=x[me in xE?L.charAt(X++):me],!nn||(R=nn(N,z,R))<0)return-1}else if(me!=z.charCodeAt(R++))return-1}return R}function T(N,L,z){let R=c.exec(L.slice(z));return R?(N.p=u.get(R[0].toLowerCase()),z+R[0].length):-1}function _(N,L,z){let R=h.exec(L.slice(z));return R?(N.w=p.get(R[0].toLowerCase()),z+R[0].length):-1}function E(N,L,z){let R=f.exec(L.slice(z));return R?(N.w=d.get(R[0].toLowerCase()),z+R[0].length):-1}function A(N,L,z){let R=y.exec(L.slice(z));return R?(N.m=w.get(R[0].toLowerCase()),z+R[0].length):-1}function $(N,L,z){let R=m.exec(L.slice(z));return R?(N.m=g.get(R[0].toLowerCase()),z+R[0].length):-1}function M(N,L,z){return C(N,t,L,z)}function O(N,L,z){return C(N,n,L,z)}function j(N,L,z){return C(N,r,L,z)}function I(N){return o[N.getDay()]}function D(N){return s[N.getDay()]}function W(N){return l[N.getMonth()]}function G(N){return a[N.getMonth()]}function K(N){return i[+(N.getHours()>=12)]}function _e(N){return 1+~~(N.getMonth()/3)}function se(N){return o[N.getUTCDay()]}function P(N){return s[N.getUTCDay()]}function ee(N){return l[N.getUTCMonth()]}function fe(N){return a[N.getUTCMonth()]}function q(N){return i[+(N.getUTCHours()>=12)]}function F(N){return 1+~~(N.getUTCMonth()/3)}return{format(N){let L=S(N+="",b);return Object.assign(L,{toString(){return N}})},parse(N){let L=k(N+="",!1);return Object.assign(L,{toString(){return N}})},utcFormat(N){let L=S(N+="",v);return Object.assign(L,{toString(){return N}})},utcParse(N){let L=k(N+="",!0);return Object.assign(L,{toString(){return N}})}}}var xE={"-":"",_:" ","0":"0"},Nt=/^\s*\d+/,pP=/^%/,mP=/[\\^$*+?|[\]().{}]/g;function ve(e,t,n){let r=e<0?"-":"",i=`${r?-e:e}`,s=i.length;return r+(s<n?Array(n-s+1).join(t)+i:i)}function gP(e){return e.replace(mP,"\\$&")}function Nl(e){return new RegExp(`^(?:${e.map(gP).join("|")})`,"i")}function Rl(e){return new Map(e.map((t,n)=>[t.toLowerCase(),n]))}function yP(e,t,n){let r=Nt.exec(t.slice(n,n+1));return r?(e.w=+r[0],n+r[0].length):-1}function wP(e,t,n){let r=Nt.exec(t.slice(n,n+1));return r?(e.u=+r[0],n+r[0].length):-1}function bP(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.U=+r[0],n+r[0].length):-1}function vP(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.V=+r[0],n+r[0].length):-1}function xP(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.W=+r[0],n+r[0].length):-1}function SE(e,t,n){let r=Nt.exec(t.slice(n,n+4));return r?(e.y=+r[0],n+r[0].length):-1}function kE(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.y=+r[0]+(+r[0]>68?1900:2000),n+r[0].length):-1}function SP(e,t,n){let r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(n,n+6));return r?(e.Z=r[1]?0:-+(r[2]+(r[3]||"00")),n+r[0].length):-1}function kP(e,t,n){let r=Nt.exec(t.slice(n,n+1));return r?(e.q=+r[0]*3-3,n+r[0].length):-1}function _P(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.m=+r[0]-1,n+r[0].length):-1}function _E(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.d=+r[0],n+r[0].length):-1}function EP(e,t,n){let r=Nt.exec(t.slice(n,n+3));return r?(e.m=0,e.d=+r[0],n+r[0].length):-1}function EE(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.H=+r[0],n+r[0].length):-1}function AP(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.M=+r[0],n+r[0].length):-1}function $P(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.S=+r[0],n+r[0].length):-1}function CP(e,t,n){let r=Nt.exec(t.slice(n,n+3));return r?(e.L=+r[0],n+r[0].length):-1}function TP(e,t,n){let r=Nt.exec(t.slice(n,n+6));return r?(e.L=Math.floor(+r[0]/1000),n+r[0].length):-1}function MP(e,t,n){let r=pP.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function OP(e,t,n){let r=Nt.exec(t.slice(n));return r?(e.Q=+r[0],n+r[0].length):-1}function jP(e,t,n){let r=Nt.exec(t.slice(n));return r?(e.s=+r[0],n+r[0].length):-1}function AE(e,t){return ve(e.getDate(),t,2)}function NP(e,t){return ve(e.getHours(),t,2)}function RP(e,t){return ve(e.getHours()%12||12,t,2)}function LP(e,t){return ve(1+kf.count(Gi(e),e),t,3)}function R2(e,t){return ve(e.getMilliseconds(),t,3)}function FP(e,t){return`${R2(e,t)}000`}function IP(e,t){return ve(e.getMonth()+1,t,2)}function DP(e,t){return ve(e.getMinutes(),t,2)}function zP(e,t){return ve(e.getSeconds(),t,2)}function BP(e){let t=e.getDay();return t===0?7:t}function WP(e,t){return ve(k0.count(Gi(e).getTime()-1,e),t,2)}function L2(e){let t=e.getDay();return t>=4||t===0?No(e):No.ceil(e)}function UP(e,t){return e=L2(e),ve(No.count(Gi(e),e)+(Gi(e).getDay()===4?1:0),t,2)}function PP(e){return e.getDay()}function qP(e,t){return ve(wf.count(Gi(e).getTime()-1,e),t,2)}function GP(e,t){return ve(e.getFullYear()%100,t,2)}function XP(e,t){return e=L2(e),ve(e.getFullYear()%100,t,2)}function VP(e,t){return ve(e.getFullYear()%1e4,t,4)}function YP(e,t){let n=e.getDay();return e=n>=4||n===0?No(e):No.ceil(e),ve(e.getFullYear()%1e4,t,4)}function JP(e){let t=e.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+ve(t/60|0,"0",2)+ve(t%60,"0",2)}function $E(e,t){return ve(e.getUTCDate(),t,2)}function KP(e,t){return ve(e.getUTCHours(),t,2)}function QP(e,t){return ve(e.getUTCHours()%12||12,t,2)}function HP(e,t){return ve(1+S0.count(Xi(e),e),t,3)}function F2(e,t){return ve(e.getUTCMilliseconds(),t,3)}function ZP(e,t){return`${F2(e,t)}000`}function e8(e,t){return ve(e.getUTCMonth()+1,t,2)}function t8(e,t){return ve(e.getUTCMinutes(),t,2)}function n8(e,t){return ve(e.getUTCSeconds(),t,2)}function r8(e){let t=e.getUTCDay();return t===0?7:t}function i8(e,t){return ve(_0.count(Xi(e).getTime()-1,e),t,2)}function I2(e){let t=e.getUTCDay();return t>=4||t===0?Ro(e):Ro.ceil(e)}function s8(e,t){return e=I2(e),ve(Ro.count(Xi(e),e)+(Xi(e).getUTCDay()===4?1:0),t,2)}function o8(e){return e.getUTCDay()}function a8(e,t){return ve(bf.count(Xi(e).getTime()-1,e),t,2)}function l8(e,t){return ve(e.getUTCFullYear()%100,t,2)}function c8(e,t){return e=I2(e),ve(e.getUTCFullYear()%100,t,2)}function u8(e,t){return ve(e.getUTCFullYear()%1e4,t,4)}function f8(e,t){let n=e.getUTCDay();return e=n>=4||n===0?Ro(e):Ro.ceil(e),ve(e.getUTCFullYear()%1e4,t,4)}function d8(){return"+0000"}function CE(){return"%"}function TE(e){return+e}function ME(e){return Math.floor(+e/1000)}var Ao,D2,h8,z2,B2;p8({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function p8(e){return Ao=hP(e),D2=Ao.format,h8=Ao.parse,z2=Ao.utcFormat,B2=Ao.utcParse,Ao}var W2="%Y-%m-%dT%H:%M:%S.%LZ";function m8(e){return e.toISOString()}var dbe=typeof Date.prototype.toISOString==="function"?m8:z2(W2);function g8(e){let t=new Date(e);return isNaN(+t)?null:t}var hbe=+new Date("2000-01-01T00:00:00.000Z")?g8:B2(W2);function y8(e){return new Date(e)}function w8(e){return e instanceof Date?+e:+new Date(+e)}function U2(e,t,n,r,i,s,o,a,l,c){let u=n2(),f=u.invert,d=u.domain,h=c(".%L"),p=c(":%S"),m=c("%I:%M"),g=c("%I %p"),y=c("%a %d"),w=c("%b %d"),b=c("%B"),v=c("%Y");function x(S){return(l(S)<S?h:a(S)<S?p:o(S)<S?m:s(S)<S?g:r(S)<S?i(S)<S?y:w:n(S)<S?b:v)(S)}return u.invert=function(S){return new Date(f(S))},u.domain=function(S){return arguments.length?d(Array.from(S,w8)):d().map(y8)},u.ticks=function(S){let k=d();return e(k[0],k[k.length-1],S==null?10:S)},u.tickFormat=function(S,k){return k==null?x:c(k)},u.nice=function(S){let k=d(),C=S;if(!C||typeof C.range!=="function")C=t(k[0],k[k.length-1],S==null?10:S);return C?d(EU(k,C)):u},u.copy=function(){return t2(u,U2(e,t,n,r,i,s,o,a,l,c))},u}function A0(){let e=U2(YU,JU,Sf,w0,y0,g0,m0,p0,Co,D2).domain([new Date(2000,0,1),new Date(2000,0,2)]);return FE.apply(e,arguments)}function Rt(e){return function(){return e}}var{abs:mbe,atan2:gbe,cos:b8,max:ybe,min:wbe,sin:C0,sqrt:Io}=Math,P2=0.000000000001,_f=Math.PI,bbe=_f/2,Y2=2*_f;var T0=Math.PI,M0=2*T0,v8=M0-0.000001;function J2(e,...t){this._+=e[0];for(let n=1,r=e.length;n<r;++n)this._+=t[n-1]+e[n]}function x8(e){let t=Math.floor(e);if(!(t>=0))throw Error(`invalid digits: ${e}`);if(t>15)return J2;let n=10**t;return function(r,...i){this._+=r[0];for(let s=1,o=r.length;s<o;++s)this._+=Math.round(i[s-1]*n)/n+r[s]}}class Ef{_x0;_y0;_x1;_y1;_;_append;constructor(e){this._x0=this._y0=this._x1=this._y1=null,this._="",this._append=e==null?J2:x8(e)}moveTo(e,t){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+t}`}closePath(){if(this._x1!==null)this._x1=this._x0,this._y1=this._y0,this._append`Z`}lineTo(e,t){this._append`L${this._x1=+e},${this._y1=+t}`}quadraticCurveTo(e,t,n,r){this._append`Q${+e},${+t},${this._x1=+n},${this._y1=+r}`}bezierCurveTo(e,t,n,r,i,s){this._append`C${+e},${+t},${+n},${+r},${this._x1=+i},${this._y1=+s}`}arcTo(e,t,n,r,i){if(e=+e,t=+t,n=+n,r=+r,i=+i,i<0)throw Error(`negative radius: ${i}`);let s=this._x1,o=this._y1,a=n-e,l=r-t,c=s-e,u=o-t,f=c*c+u*u;if(this._x1===null)this._append`M${this._x1=e},${this._y1=t}`;else if(!(f>0.000001));else if(!(Math.abs(u*a-l*c)>0.000001)||!i)this._append`L${this._x1=e},${this._y1=t}`;else{let d=n-s,h=r-o,p=a*a+l*l,m=d*d+h*h,g=Math.sqrt(p),y=Math.sqrt(f),w=i*Math.tan((T0-Math.acos((p+f-m)/(2*g*y)))/2),b=w/y,v=w/g;if(Math.abs(b-1)>0.000001)this._append`L${e+b*c},${t+b*u}`;this._append`A${i},${i},0,0,${+(u*d>c*h)},${this._x1=e+v*a},${this._y1=t+v*l}`}}arc(e,t,n,r,i,s){if(e=+e,t=+t,n=+n,s=!!s,n<0)throw Error(`negative radius: ${n}`);let o=n*Math.cos(r),a=n*Math.sin(r),l=e+o,c=t+a,u=1^s,f=s?r-i:i-r;if(this._x1===null)this._append`M${l},${c}`;else if(Math.abs(this._x1-l)>0.000001||Math.abs(this._y1-c)>0.000001)this._append`L${l},${c}`;if(!n)return;if(f<0)f=f%M0+M0;if(f>v8)this._append`A${n},${n},0,1,${u},${e-o},${t-a}A${n},${n},0,1,${u},${this._x1=l},${this._y1=c}`;else if(f>0.000001)this._append`A${n},${n},0,${+(f>=T0)},${u},${this._x1=e+n*Math.cos(i)},${this._y1=t+n*Math.sin(i)}`}rect(e,t,n,r){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+t}h${n=+n}v${+r}h${-n}Z`}toString(){return this._}}function S8(){return new Ef}Object.defineProperty(S8,Symbol.hasInstance,{value:(e)=>e instanceof Ef});function K2(e){let t=3;return e.digits=function(n){if(!arguments.length)return t;if(n==null)t=null;else{let r=Math.floor(n);if(!(r>=0))throw RangeError(`invalid digits: ${n}`);t=r}return e},()=>new Ef(t)}var vbe=Array.prototype.slice;function Q2(e){return typeof e==="object"&&"length"in e?e:Array.from(e)}function H2(e){this._context=e}H2.prototype={areaStart(){this._line=0},areaEnd(){this._line=NaN},lineStart(){this._point=0},lineEnd(){if(this._line||this._line!==0&&this._point===1)this._context.closePath();this._line=1-this._line},point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2,this._context.lineTo(e,t);break;default:this._context.lineTo(e,t);break}}};function O0(e){return new H2(e)}function Z2(e){return e[0]}function eA(e){return e[1]}function zl(e,t){let n=Rt(!0),r=null,i=O0,s=null,o=K2(a);e=typeof e==="function"?e:e===void 0?Z2:Rt(e),t=typeof t==="function"?t:t===void 0?eA:Rt(t);function a(l){let c,u=(l=Q2(l)).length,f,d=!1,h;if(r==null)s=i(h=o());for(c=0;c<=u;++c){if(!(c<u&&n(f=l[c],c,l))===d)if(d=!d)s.lineStart();else s.lineEnd();if(d)s.point(+e(f,c,l),+t(f,c,l))}if(h)return s=null,h+""||null}return a.x=function(l){return arguments.length?(e=typeof l==="function"?l:Rt(+l),a):e},a.y=function(l){return arguments.length?(t=typeof l==="function"?l:Rt(+l),a):t},a.defined=function(l){return arguments.length?(n=typeof l==="function"?l:Rt(!!l),a):n},a.curve=function(l){return arguments.length?(i=l,r!=null&&(s=i(r)),a):i},a.context=function(l){return arguments.length?(l==null?r=s=null:s=i(r=l),a):r},a}function j0(e,t,n){let r=null,i=Rt(!0),s=null,o=O0,a=null,l=K2(c);e=typeof e==="function"?e:e===void 0?Z2:Rt(+e),t=typeof t==="function"?t:t===void 0?Rt(0):Rt(+t),n=typeof n==="function"?n:n===void 0?eA:Rt(+n);function c(f){let d,h=0,p,m=(f=Q2(f)).length,g,y=!1,w,b=Array(m),v=Array(m);if(s==null)a=o(w=l());for(d=0;d<=m;++d){if(!(d<m&&i(g=f[d],d,f))===y)if(y=!y)h=d,a.areaStart(),a.lineStart();else{a.lineEnd(),a.lineStart();for(p=d-1;p>=h;--p)a.point(b[p],v[p]);a.lineEnd(),a.areaEnd()}if(y)b[d]=+e(g,d,f),v[d]=+t(g,d,f),a.point(r?+r(g,d,f):b[d],n?+n(g,d,f):v[d])}if(w)return a=null,`${w}`||null}function u(){return zl().defined(i).curve(o).context(s)}return c.x=function(f){return arguments.length?(e=typeof f==="function"?f:Rt(+f),r=null,c):e},c.x0=function(f){return arguments.length?(e=typeof f==="function"?f:Rt(+f),c):e},c.x1=function(f){return arguments.length?(r=f==null?null:typeof f==="function"?f:Rt(+f),c):r},c.y=function(f){return arguments.length?(t=typeof f==="function"?f:Rt(+f),n=null,c):t},c.y0=function(f){return arguments.length?(t=typeof f==="function"?f:Rt(+f),c):t},c.y1=function(f){return arguments.length?(n=f==null?null:typeof f==="function"?f:Rt(+f),c):n},c.lineX0=c.lineY0=function(){return u().x(e).y(t)},c.lineY1=function(){return u().x(e).y(n)},c.lineX1=function(){return u().x(r).y(t)},c.defined=function(f){return arguments.length?(i=typeof f==="function"?f:Rt(!!f),c):i},c.curve=function(f){return arguments.length?(o=f,s!=null&&(a=o(s)),c):o},c.context=function(f){return arguments.length?(f==null?s=a=null:a=o(s=f),c):s},c}function tA(e){this._curve=e}tA.prototype={areaStart(){this._curve.areaStart()},areaEnd(){this._curve.areaEnd()},lineStart(){this._curve.lineStart()},lineEnd(){this._curve.lineEnd()},point(e,t){this._curve.point(t*Math.sin(e),t*-Math.cos(e))}};function k8(e){function t(n){return new tA(e(n))}return t._curve=e,t}var xbe=k8(O0);var Sbe=Io(3);var _8=Io(0.3333333333333333),kbe=_8*2;var nA=C0(_f/10)/C0(7*_f/10),_be=C0(Y2/10)*nA,Ebe=-b8(Y2/10)*nA;var Abe=Io(3);var $be=Io(3);var Cbe=Io(3)/2,E8=1/Io(12),Tbe=(E8/2+1)*3;function Vi(){}function Lo(e,t,n){e._context.bezierCurveTo((2*e._x0+e._x1)/3,(2*e._y0+e._y1)/3,(e._x0+2*e._x1)/3,(e._y0+2*e._y1)/3,(e._x0+4*e._x1+t)/6,(e._y0+4*e._y1+n)/6)}function N0(e){this._context=e}N0.prototype={areaStart(){this._line=0},areaEnd(){this._line=NaN},lineStart(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd(){switch(this._point){case 3:Lo(this,this._x1,this._y1),this._context.lineTo(this._x1,this._y1);break;case 2:this._context.lineTo(this._x1,this._y1);break}if(this._line||this._line!==0&&this._point===1)this._context.closePath();this._line=1-this._line},point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6),Lo(this,e,t);break;default:Lo(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function A8(e){this._context=e}A8.prototype={areaStart:Vi,areaEnd:Vi,lineStart(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd(){switch(this._point){case 1:{this._context.moveTo(this._x2,this._y2),this._context.closePath();break}case 2:{this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break}case 3:{this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}}},point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._x2=e,this._y2=t;break;case 1:this._point=2,this._x3=e,this._y3=t;break;case 2:this._point=3,this._x4=e,this._y4=t,this._context.moveTo((this._x0+4*this._x1+e)/6,(this._y0+4*this._y1+t)/6);break;default:Lo(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function $8(e){this._context=e}$8.prototype={areaStart(){this._line=0},areaEnd(){this._line=NaN},lineStart(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd(){if(this._line||this._line!==0&&this._point===3)this._context.closePath();this._line=1-this._line},point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;{let n=(this._x0+4*this._x1+e)/6,r=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break}case 3:this._point=4,Lo(this,e,t);break;default:Lo(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function rA(e,t){this._basis=new N0(e),this._beta=t}rA.prototype={lineStart(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd(){let e=this._x,t=this._y,n=e.length-1;if(n>0){let r=e[0],i=t[0],s=e[n]-r,o=t[n]-i,a=-1,l;while(++a<=n)l=a/n,this._basis.point(this._beta*e[a]+(1-this._beta)*(r+l*s),this._beta*t[a]+(1-this._beta)*(i+l*o))}this._x=this._y=null,this._basis.lineEnd()},point(e,t){this._x.push(+e),this._y.push(+t)}};var Mbe=function e(t){function n(r){return t===1?new N0(r):new rA(r,t)}return n.beta=function(r){return e(+r)},n}(0.85);function Fo(e,t,n){e._context.bezierCurveTo(e._x1+e._k*(e._x2-e._x0),e._y1+e._k*(e._y2-e._y0),e._x2+e._k*(e._x1-t),e._y2+e._k*(e._y1-n),e._x2,e._y2)}function R0(e,t){this._context=e,this._k=(1-t)/6}R0.prototype={areaStart(){this._line=0},areaEnd(){this._line=NaN},lineStart(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:Fo(this,this._x1,this._y1);break}if(this._line||this._line!==0&&this._point===1)this._context.closePath();this._line=1-this._line},point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2,this._x1=e,this._y1=t;break;case 2:this._point=3,Fo(this,e,t);break;default:Fo(this,e,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var Obe=function e(t){function n(r){return new R0(r,t)}return n.tension=function(r){return e(+r)},n}(0);function L0(e,t){this._context=e,this._k=(1-t)/6}L0.prototype={areaStart:Vi,areaEnd:Vi,lineStart(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd(){switch(this._point){case 1:{this._context.moveTo(this._x3,this._y3),this._context.closePath();break}case 2:{this._context.lineTo(this._x3,this._y3),this._context.closePath();break}case 3:{this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);break}}},point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._x3=e,this._y3=t;break;case 1:this._point=2,this._context.moveTo(this._x4=e,this._y4=t);break;case 2:this._point=3,this._x5=e,this._y5=t;break;default:Fo(this,e,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var jbe=function e(t){function n(r){return new L0(r,t)}return n.tension=function(r){return e(+r)},n}(0);function F0(e,t){this._context=e,this._k=(1-t)/6}F0.prototype={areaStart(){this._line=0},areaEnd(){this._line=NaN},lineStart(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd(){if(this._line||this._line!==0&&this._point===3)this._context.closePath();this._line=1-this._line},point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4,Fo(this,e,t);break;default:Fo(this,e,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var Nbe=function e(t){function n(r){return new F0(r,t)}return n.tension=function(r){return e(+r)},n}(0);function Dl(e,t,n){let{_x1:r,_y1:i,_x2:s,_y2:o}=e;if(e._l01_a>P2){let a=2*e._l01_2a+3*e._l01_a*e._l12_a+e._l12_2a,l=3*e._l01_a*(e._l01_a+e._l12_a);r=(r*a-e._x0*e._l12_2a+e._x2*e._l01_2a)/l,i=(i*a-e._y0*e._l12_2a+e._y2*e._l01_2a)/l}if(e._l23_a>P2){let a=2*e._l23_2a+3*e._l23_a*e._l12_a+e._l12_2a,l=3*e._l23_a*(e._l23_a+e._l12_a);s=(s*a+e._x1*e._l23_2a-t*e._l12_2a)/l,o=(o*a+e._y1*e._l23_2a-n*e._l12_2a)/l}e._context.bezierCurveTo(r,i,s,o,e._x2,e._y2)}function iA(e,t){this._context=e,this._alpha=t}iA.prototype={areaStart(){this._line=0},areaEnd(){this._line=NaN},lineStart(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2);break}if(this._line||this._line!==0&&this._point===1)this._context.closePath();this._line=1-this._line},point(e,t){if(e=+e,t=+t,this._point){let n=this._x2-e,r=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,Dl(this,e,t);break;default:Dl(this,e,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var Rbe=function e(t){function n(r){return t?new iA(r,t):new R0(r,0)}return n.alpha=function(r){return e(+r)},n}(0.5);function sA(e,t){this._context=e,this._alpha=t}sA.prototype={areaStart:Vi,areaEnd:Vi,lineStart(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd(){switch(this._point){case 1:{this._context.moveTo(this._x3,this._y3),this._context.closePath();break}case 2:{this._context.lineTo(this._x3,this._y3),this._context.closePath();break}case 3:{this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);break}}},point(e,t){if(e=+e,t=+t,this._point){let n=this._x2-e,r=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._x3=e,this._y3=t;break;case 1:this._point=2,this._context.moveTo(this._x4=e,this._y4=t);break;case 2:this._point=3,this._x5=e,this._y5=t;break;default:Dl(this,e,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var Lbe=function e(t){function n(r){return t?new sA(r,t):new L0(r,0)}return n.alpha=function(r){return e(+r)},n}(0.5);function oA(e,t){this._context=e,this._alpha=t}oA.prototype={areaStart(){this._line=0},areaEnd(){this._line=NaN},lineStart(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd(){if(this._line||this._line!==0&&this._point===3)this._context.closePath();this._line=1-this._line},point(e,t){if(e=+e,t=+t,this._point){let n=this._x2-e,r=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4,Dl(this,e,t);break;default:Dl(this,e,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var Fbe=function e(t){function n(r){return t?new oA(r,t):new F0(r,0)}return n.alpha=function(r){return e(+r)},n}(0.5);function C8(e){this._context=e}C8.prototype={areaStart:Vi,areaEnd:Vi,lineStart(){this._point=0},lineEnd(){if(this._point)this._context.closePath()},point(e,t){if(e=+e,t=+t,this._point)this._context.lineTo(e,t);else this._point=1,this._context.moveTo(e,t)}};function q2(e){return e<0?-1:1}function G2(e,t,n){let r=e._x1-e._x0,i=t-e._x1,s=(e._y1-e._y0)/(r||(i<0?-0:0)),o=(n-e._y1)/(i||(r<0?-0:0)),a=(s*i+o*r)/(r+i);return(q2(s)+q2(o))*Math.min(Math.abs(s),Math.abs(o),0.5*Math.abs(a))||0}function X2(e,t){let n=e._x1-e._x0;return n?(3*(e._y1-e._y0)/n-t)/2:t}function $0(e,t,n){let{_x0:r,_y0:i,_x1:s,_y1:o}=e,a=(s-r)/3;e._context.bezierCurveTo(r+a,i+a*t,s-a,o-a*n,s,o)}function I0(e){this._context=e}I0.prototype={areaStart(){this._line=0},areaEnd(){this._line=NaN},lineStart(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:$0(this,this._t0,X2(this,this._t0));break}if(this._line||this._line!==0&&this._point===1)this._context.closePath();this._line=1-this._line},point(e,t){let n=NaN;if(e=+e,t=+t,e===this._x1&&t===this._y1)return;switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,$0(this,X2(this,n=G2(this,e,t)),n);break;default:$0(this,this._t0,n=G2(this,e,t));break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t,this._t0=n}};function aA(e){this._context=new lA(e)}aA.prototype=Object.create(I0.prototype);aA.prototype.point=function(e,t){I0.prototype.point.call(this,t,e)};function lA(e){this._context=e}lA.prototype={moveTo(e,t){this._context.moveTo(t,e)},closePath(){this._context.closePath()},lineTo(e,t){this._context.lineTo(t,e)},bezierCurveTo(e,t,n,r,i,s){this._context.bezierCurveTo(t,e,r,n,s,i)}};function T8(e){this._context=e}T8.prototype={areaStart(){this._line=0},areaEnd(){this._line=NaN},lineStart(){this._x=[],this._y=[]},lineEnd(){let e=this._x,t=this._y,n=e.length;if(n)if(this._line?this._context.lineTo(e[0],t[0]):this._context.moveTo(e[0],t[0]),n===2)this._context.lineTo(e[1],t[1]);else{let r=V2(e),i=V2(t);for(let s=0,o=1;o<n;++s,++o)this._context.bezierCurveTo(r[0][s],i[0][s],r[1][s],i[1][s],e[o],t[o])}if(this._line||this._line!==0&&n===1)this._context.closePath();this._line=1-this._line,this._x=this._y=null},point(e,t){this._x.push(+e),this._y.push(+t)}};function V2(e){let t,n=e.length-1,r,i=Array(n),s=Array(n),o=Array(n);i[0]=0,s[0]=2,o[0]=e[0]+2*e[1];for(t=1;t<n-1;++t)i[t]=1,s[t]=4,o[t]=4*e[t]+2*e[t+1];i[n-1]=2,s[n-1]=7,o[n-1]=8*e[n-1]+e[n];for(t=1;t<n;++t)r=i[t]/s[t-1],s[t]-=r,o[t]-=r*o[t-1];i[n-1]=o[n-1]/s[n-1];for(t=n-2;t>=0;--t)i[t]=(o[t]-i[t+1])/s[t];s[n-1]=(e[n]+i[n-1])/2;for(t=0;t<n-1;++t)s[t]=2*e[t+1]-i[t+1];return[i,s]}function M8(e,t){this._context=e,this._t=t}M8.prototype={areaStart(){this._line=0},areaEnd(){this._line=NaN},lineStart(){this._x=this._y=NaN,this._point=0},lineEnd(){if(0<this._t&&this._t<1&&this._point===2)this._context.lineTo(this._x,this._y);if(this._line||this._line!==0&&this._point===1)this._context.closePath();if(this._line>=0)this._t=1-this._t,this._line=1-this._line},point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:{if(this._point=2,this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(e,t);else{let n=this._x*(1-this._t)+e*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,t)}break}default:{if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(e,t);else{let n=this._x*(1-this._t)+e*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,t)}break}}this._x=e,this._y=t}};function Af(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function O8(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function cA(e){let t,n,r;if(e.length!==2)t=Af,n=(a,l)=>Af(e(a),l),r=(a,l)=>e(a)-l;else t=e===Af||e===O8?e:j8,n=e,r=e;function i(a,l,c=0,u=a.length){if(c<u){if(t(l,l)!==0)return u;do{let f=c+u>>>1;if(n(a[f],l)<0)c=f+1;else u=f}while(c<u)}return c}function s(a,l,c=0,u=a.length){if(c<u){if(t(l,l)!==0)return u;do{let f=c+u>>>1;if(n(a[f],l)<=0)c=f+1;else u=f}while(c<u)}return c}function o(a,l,c=0,u=a.length){let f=i(a,l,c,u-1);return f>c&&r(a[f-1],l)>-r(a[f],l)?f-1:f}return{left:i,center:o,right:s}}function j8(){return 0}function N8(e){return e===null?NaN:+e}var uA=cA(Af),Dbe=uA.right,zbe=uA.left,Bbe=cA(N8).center;var Wbe=fA(dA),Ube=fA(R8);function fA(e){return function(t,n,r=n){if(!((n=+n)>=0))throw RangeError("invalid rx");if(!((r=+r)>=0))throw RangeError("invalid ry");let{data:i,width:s,height:o}=t;if(!((s=Math.floor(s))>=0))throw RangeError("invalid width");if(!((o=Math.floor(o!==void 0?o:i.length/s))>=0))throw RangeError("invalid height");if(!s||!o||!n&&!r)return t;let a=n&&e(n),l=r&&e(r),c=i.slice();if(a&&l)Do(a,c,i,s,o),Do(a,i,c,s,o),Do(a,c,i,s,o),zo(l,i,c,s,o),zo(l,c,i,s,o),zo(l,i,c,s,o);else if(a)Do(a,i,c,s,o),Do(a,c,i,s,o),Do(a,i,c,s,o);else if(l)zo(l,i,c,s,o),zo(l,c,i,s,o),zo(l,i,c,s,o);return t}}function Do(e,t,n,r,i){for(let s=0,o=r*i;s<o;)e(t,n,s,s+=r,1)}function zo(e,t,n,r,i){for(let s=0,o=r*i;s<r;++s)e(t,n,s,s+o,r)}function R8(e){let t=dA(e);return(n,r,i,s,o)=>{i<<=2,s<<=2,o<<=2,t(n,r,i+0,s+0,o),t(n,r,i+1,s+1,o),t(n,r,i+2,s+2,o),t(n,r,i+3,s+3,o)}}function dA(e){let t=Math.floor(e);if(t===e)return L8(e);let n=e-t,r=2*e+1;return(i,s,o,a,l)=>{if(!((a-=l)>=o))return;let c=t*s[o],u=l*t,f=u+l;for(let d=o,h=o+u;d<h;d+=l)c+=s[Math.min(a,d)];for(let d=o,h=a;d<=h;d+=l)c+=s[Math.min(a,d+u)],i[d]=(c+n*(s[Math.max(o,d-f)]+s[Math.min(a,d+f)]))/r,c-=s[Math.max(o,d-u)]}}function L8(e){let t=2*e+1;return(n,r,i,s,o)=>{if(!((s-=o)>=i))return;let a=e*r[i],l=o*e;for(let c=i,u=i+l;c<u;c+=o)a+=r[Math.min(s,c)];for(let c=i,u=s;c<=u;c+=o)a+=r[Math.min(s,c+l)],n[c]=a/t,a-=r[Math.max(i,c-l)]}}function $f(e,t){let n,r;if(t===void 0){for(let i of e)if(i!=null)if(n===void 0){if(i>=i)n=r=i}else{if(n>i)n=i;if(r<i)r=i}}else{let i=-1;for(let s of e)if((s=t(s,++i,e))!=null)if(n===void 0){if(s>=s)n=r=s}else{if(n>s)n=s;if(r<s)r=s}}return[n,r]}var hA=Array.prototype,Pbe=hA.slice,qbe=hA.map;var Gbe=Math.sqrt(50),Xbe=Math.sqrt(10),Vbe=Math.sqrt(2);function D0(e,t){let n;if(t===void 0){for(let r of e)if(r!=null&&(n<r||n===void 0&&r>=r))n=r}else{let r=-1;for(let i of e)if((i=t(i,++r,e))!=null&&(n<i||n===void 0&&i>=i))n=i}return n}function F8(e){return function(t,n=0,r=t.length){let i=r-(n=+n);while(i){let s=e()*i--|0,o=t[i+n];t[i+n]=t[s+n],t[s+n]=o}return t}}var Ybe=F8(Math.random);function I8(e){return Math.abs(e=Math.round(e))>=1000000000000000000000?e.toLocaleString("en").replace(/,/g,""):e.toString(10)}function Tf(e,t){if(!isFinite(e)||e===0)return null;let n=t?e.toExponential(t-1):e.toExponential(),r=n.indexOf("e"),i=n.slice(0,r);return[i.length>1?i[0]+i.slice(2):i,+n.slice(r+1)]}function D8(e){let t=Tf(Math.abs(e));return t?t[1]:NaN}function z8(e,t){return function(n,r){let i=n.length,s=[],o=0,a=e[0],l=0;while(i>0&&a>0){if(l+a+1>r)a=Math.max(1,r-l);if(s.push(n.substring(i-=a,i+a)),(l+=a+1)>r)break;a=e[o=(o+1)%e.length]}return s.reverse().join(t)}}function B8(e){return function(t){return t.replace(/[0-9]/g,function(n){return e[+n]})}}var W8=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;class z0{fill;align;sign;symbol;zero;width;comma;precision;trim;type;constructor(e){this.fill=e.fill===void 0?" ":`${e.fill}`,this.align=e.align===void 0?">":`${e.align}`,this.sign=e.sign===void 0?"-":`${e.sign}`,this.symbol=e.symbol===void 0?"":`${e.symbol}`,this.zero=!!e.zero,this.width=e.width===void 0?void 0:+e.width,this.comma=!!e.comma,this.precision=e.precision===void 0?void 0:+e.precision,this.trim=!!e.trim,this.type=e.type===void 0?"":`${e.type}`}toString(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":`.${Math.max(0,this.precision|0)}`)+(this.trim?"~":"")+this.type}}function vA(e){let t=W8.exec(e);if(!t)throw Error(`invalid format: ${e}`);return new z0({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}vA.prototype=z0.prototype;var U8=vA,pA=U8;function P8(e){let t=-1,n=0;e:for(let r=e.length,i=1;i<r;++i)switch(e[i]){case".":t=n=i;break;case"0":if(t===0)t=i;n=i;break;default:if(!+e[i])break e;if(t>0)t=0;break}return t>0?e.slice(0,t)+e.slice(n+1):e}var Bl;function q8(e,t){let n=Tf(e,t);if(!n)return Bl=void 0,e.toPrecision(t);let r=n[0],i=n[1];Bl=Math.max(-8,Math.min(8,Math.floor(i/3)))*3;let s=i-Bl+1,o=r.length;return s===o?r:s>o?`${r}${Array(s-o+1).join("0")}`:s>0?`${r.slice(0,s)}.${r.slice(s)}`:`0.${Array(1-s).join("0")}${Tf(e,Math.max(0,t+s-1))[0]}`}function mA(e,t){let n=Tf(e,t);if(!n)return`${e}`;let r=n[0],i=n[1];return i<0?`0.${Array(-i).join("0")}${r}`:r.length>i+1?`${r.slice(0,i+1)}.${r.slice(i+1)}`:`${r}${Array(i-r.length+2).join("0")}`}var G8={"%":(e,t)=>(e*100).toFixed(t),b:(e)=>Math.round(e).toString(2),c:(e)=>`${e}`,d:I8,e:(e,t)=>e.toExponential(t),f:(e,t)=>e.toFixed(t),g:(e,t)=>e.toPrecision(t),o:(e)=>Math.round(e).toString(8),p:(e,t)=>mA(e*100,t),r:mA,s:q8,X:(e)=>Math.round(e).toString(16).toUpperCase(),x:(e)=>Math.round(e).toString(16)},gA=G8;function yA(e){return e}var wA=Array.prototype.map,bA=["y","z","a","f","p","n","\xB5","m","","k","M","G","T","P","E","Z","Y"];function X8(e){let t=e.grouping===void 0||e.thousands===void 0?yA:z8(wA.call(e.grouping,Number),`${e.thousands}`),n=e.currency===void 0?"":e.currency[0]+"",r=e.currency===void 0?"":e.currency[1]+"",i=e.decimal===void 0?".":`${e.decimal}`,s=e.numerals===void 0?yA:B8(wA.call(e.numerals,String)),o=e.percent===void 0?"%":`${e.percent}`,a=e.minus===void 0?"\u2212":`${e.minus}`,l=e.nan===void 0?"NaN":`${e.nan}`;function c(f,d){let h=pA(f),p=h.fill,m=h.align,g=h.sign,y=h.symbol,w=h.zero,b=h.width,v=h.comma,x=h.precision,S=h.trim,k=h.type;if(k==="n")v=!0,k="g";else if(!gA[k]){if(x===void 0)x=12;S=!0,k="g"}if(w||p==="0"&&m==="=")w=!0,p="0",m="=";let C=(d&&d.prefix!==void 0?d.prefix:"")+(y==="$"?n:y==="#"&&/[boxX]/.test(k)?`0${k.toLowerCase()}`:""),T=(y==="$"?r:/[%p]/.test(k)?o:"")+(d&&d.suffix!==void 0?d.suffix:""),_=gA[k],E=/[defgprs%]/.test(k);x=x===void 0?6:/[gprs]/.test(k)?Math.max(1,Math.min(21,x)):Math.max(0,Math.min(20,x));function A($){let M=C,O=T,j,I,D;if(k==="c")O=_($)+O,$="";else{$=+$;let K=$<0||1/$<0;if($=isNaN($)?l:_(Math.abs($),x),S)$=P8($);if(K&&+$===0&&g!=="+")K=!1;if(M=(K?g==="("?g:a:g==="-"||g==="("?"":g)+M,O=(k==="s"&&!isNaN($)&&Bl!==void 0?bA[8+Bl/3]:"")+O+(K&&g==="("?")":""),E){j=-1,I=$.length;while(++j<I)if(D=$.charCodeAt(j),48>D||D>57){O=(D===46?i+$.slice(j+1):$.slice(j))+O,$=$.slice(0,j);break}}}if(v&&!w)$=t($,1/0);let W=M.length+$.length+O.length,G=W<(b??0)?Array((b??0)-W+1).join(p):"";if(v&&w)$=t(G+$,G.length?(b??0)-O.length:1/0),G="";switch(m){case"<":$=M+$+O+G;break;case"=":$=M+G+$+O;break;case"^":{let K=G.length>>1;$=G.slice(0,K)+M+$+O+G.slice(K);break}default:$=G+M+$+O;break}return s($)}return A.toString=function(){return`${h}`},A}function u(f,d){let h=pA(f);h.type="f";let p=Math.max(-8,Math.min(8,Math.floor(D8(d)/3)))*3,m=Math.pow(10,-p),g=c(`${h}`,{suffix:bA[8+p/3]});return function(y){return g(m*y)}}return{format:c,formatPrefix:u}}var Cf,Mf,V8;Y8({thousands:",",grouping:[3],currency:["$",""]});function Y8(e){return Cf=X8(e),Mf=Cf.format,V8=Cf.formatPrefix,Cf}var Of=["#5b9cf5","#6dd97a","#e6c84d","#e25c5c","#c084fc","#f97316","#06b6d4","#ec4899"];function Wl(e,t=120,n=32,r=2){if(e.length===0)return{path:"",areaPath:"",width:t,height:n,minVal:0,maxVal:0};let i=Os().domain([0,Math.max(e.length-1,1)]).range([r,t-r]),[s,o]=$f(e),a=Os().domain([Math.min(s,0),Math.max(o,1)]).range([n-r,r]),l=zl().x((u,f)=>i(f)).y((u)=>a(u)),c=j0().x((u,f)=>i(f)).y0(n-r).y1((u)=>a(u));return{path:l(e)||"",areaPath:c(e)||"",width:t,height:n,minVal:s,maxVal:o}}function Qr(e,t=700,n=200,r={top:10,right:10,bottom:24,left:45}){let i={linePath:"",areaPath:"",points:[],xLabels:[],yLabels:[],width:t,height:n,maxValue:0};if(e.length===0)return i;let s=t-r.left-r.right,o=n-r.top-r.bottom,a=e.map((S)=>new Date(S.date)),l=e.map((S)=>S.count),c=$f(a),u=A0().domain(c).range([r.left,r.left+s]),f=D0(l)||1,d=Os().domain([0,f*1.1]).range([r.top+o,r.top]).nice(),h=zl().x((S)=>u(S.date)).y((S)=>d(S.count)),p=j0().x((S)=>u(S.date)).y0(r.top+o).y1((S)=>d(S.count)),m=e.map((S,k)=>({date:a[k],count:S.count})),g=m.map((S)=>({x:u(S.date),y:d(S.count),label:S.date.toLocaleDateString("en-US",{month:"short",day:"numeric"}),value:S.count})),w=u.ticks(5).map((S)=>({x:u(S),label:S.toLocaleDateString("en-US",{month:"short",day:"numeric"})})),b=d.ticks(4),v=Mf(".2s"),x=b.map((S)=>({y:d(S),label:S>=1000?v(S):String(S)}));return{linePath:h(m)||"",areaPath:p(m)||"",points:g,xLabels:w,yLabels:x,width:t,height:n,maxValue:f}}function Ul(e,t=400,n=28,r=6,i=120){if(e.length===0)return{bars:[],chartWidth:t,chartHeight:0};let s=e.length*(n+r),o=t-i-10,a=D0(e,(f)=>f.value)||1,l=e.reduce((f,d)=>f+d.value,0)||1,c=Os().domain([0,a]).range([0,o]);return{bars:e.map((f,d)=>({x:i,y:d*(n+r),width:Math.max(c(f.value),2),height:n,label:f.label,value:f.value,formattedValue:lt(f.value),percentage:`${(f.value/l*100).toFixed(1)}%`,color:Of[d%Of.length]})),chartWidth:t,chartHeight:s}}function xA(e,t=700,n=250,r={top:10,right:10,bottom:24,left:45}){let i={datasets:[],xLabels:[],yLabels:[],width:t,height:n};if(e.length===0)return i;let s=t-r.left-r.right,o=n-r.top-r.bottom,a=[],l=0;for(let w of e)for(let b of w.timeline)if(a.push(new Date(b.date)),b.count>l)l=b.count;if(a.length===0)return i;let c=$f(a),u=A0().domain(c).range([r.left,r.left+s]),f=Os().domain([0,Math.max(l*1.1,1)]).range([r.top+o,r.top]).nice(),d=e.map((w,b)=>{let v=w.timeline.map((k)=>({date:new Date(k.date),count:k.count})),x=zl().x((k)=>u(k.date)).y((k)=>f(k.count)),S=v.map((k)=>({x:u(k.date),y:f(k.count),label:k.date.toLocaleDateString("en-US",{month:"short",day:"numeric"}),value:k.count}));return{label:w.label,color:Of[b%Of.length],path:x(v)||"",points:S}}),p=u.ticks(5).map((w)=>({x:u(w),label:w.toLocaleDateString("en-US",{month:"short",day:"numeric"})})),m=f.ticks(4),g=Mf(".2s"),y=m.map((w)=>({y:f(w),label:w>=1000?g(w):String(w)}));return{datasets:d,xLabels:p,yLabels:y,width:t,height:n}}function lt(e){if(!Number.isFinite(e)||e<0)return"0";if(e>=1e6)return`${(e/1e6).toFixed(1)}M`;if(e>=1000)return`${(e/1000).toFixed(1)}K`;return String(Math.round(e))}import*as Fs from"crypto";var SA="ptry_";function kA(){let e=Fs.randomBytes(32).toString("hex");return`${SA}${e}`}function _A(){return Fs.randomBytes(32).toString("hex")}function Bo(e){return Fs.createHash("sha256").update(e).digest("hex")}function Nf(e){return e.startsWith(SA)}async function jf(e){return Bun.password.hash(e,{algorithm:"argon2id"})}async function EA(e,t){return Bun.password.verify(e,t)}class Rf{storage;constructor(e){this.storage=e}async signup(e,t,n){let r=e.toLowerCase().trim();if(!r||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r))throw new Re("Invalid email address",400);if(!t||t.trim().length===0)throw new Re("Name is required",400);if(!n||n.length<8)throw new Re("Password must be at least 8 characters",400);if(await this.storage.getUser(r))throw new Re("An account with this email already exists",409);let s=new Date().toISOString(),o=await jf(n),a={email:r,name:t.trim(),passwordHash:o,role:"user",createdAt:s,updatedAt:s};try{await this.storage.putUser(a)}catch(l){if(l.message?.includes("ConditionalCheckFailed"))throw new Re("An account with this email already exists",409);throw l}return{email:a.email,name:a.name,role:a.role||"user",createdAt:a.createdAt,updatedAt:a.updatedAt}}async upsertAdminUser(e,t,n){return this.upsertUserAccount(e,t,n,"admin")}async upsertUserAccount(e,t,n,r="user"){let i=e.toLowerCase().trim();if(!i||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i))throw new Re("Invalid email address",400);if(!n||n.length<8)throw new Re("Password must be at least 8 characters",400);let s=await this.storage.getUser(i),o=new Date().toISOString(),a=await jf(n),l={email:i,name:(t||s?.name||(r==="admin"?"Admin":i.split("@")[0])).trim(),passwordHash:a,role:r,createdAt:s?.createdAt||o,updatedAt:o};return await this.storage.upsertUser(l),{email:l.email,name:l.name,role:r,createdAt:l.createdAt,updatedAt:l.updatedAt}}async login(e,t){let n=e.toLowerCase().trim(),r=await this.storage.getUser(n);if(!r)throw await jf("dummy-password-for-timing-normalization"),new Re("Invalid email or password",401);if(!await EA(t,r.passwordHash))throw new Re("Invalid email or password",401);let s=_A(),o={tokenHash:Bo(s),userId:r.email,createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+2592000000).toISOString()};return await this.storage.putSession(o),{sessionToken:s,user:{email:r.email,name:r.name,role:r.role||"user",createdAt:r.createdAt,updatedAt:r.updatedAt}}}async logout(e){await this.storage.deleteSession(Bo(e))}async validateSession(e){let t=await this.storage.getSession(Bo(e));if(!t)return null;if(new Date(t.expiresAt)<new Date)return await this.storage.deleteSession(t.tokenHash),null;let n=await this.storage.getUser(t.userId);if(!n)return null;return{email:n.email,name:n.name,role:n.role||"user",createdAt:n.createdAt,updatedAt:n.updatedAt}}async createApiToken(e,t,n){if(!t||t.trim().length===0)throw new Re("Token name is required",400);if(t.length>255)throw new Re("Token name must be 255 characters or fewer",400);let r=kA(),i=new Date().toISOString(),s=n?.expiresInDays?new Date(Date.now()+n.expiresInDays*24*60*60*1000).toISOString():void 0,o={id:`${r.slice(0,8)}...${r.slice(-4)}`,name:t.trim(),userId:e,tokenHash:Bo(r),permissions:n?.permissions||["publish","read"],createdAt:i,expiresAt:s};return await this.storage.putApiToken(o),{token:r,info:{id:o.id,name:o.name,permissions:o.permissions,createdAt:o.createdAt,expiresAt:o.expiresAt}}}async listApiTokens(e){return(await this.storage.listApiTokens(e)).map((n)=>({id:n.id,name:n.name,permissions:n.permissions,createdAt:n.createdAt,lastUsedAt:n.lastUsedAt,expiresAt:n.expiresAt}))}async deleteApiToken(e,t){await this.storage.deleteApiToken(e,t)}async validatePublishToken(e,t){return this.validateAccessToken(e,t,"publish")}async validateAccessToken(e,t,n){if(t){let r=Math.max(e.length,t.length),i=Buffer.alloc(r),s=Buffer.alloc(r);if(Buffer.from(e).copy(i),Buffer.from(t).copy(s),Fs.timingSafeEqual(i,s)&&e.length===t.length)return{valid:!0,userId:"_admin"}}if(Nf(e)){let r=await this.storage.getApiTokenByHash(Bo(e));if(!r)return{valid:!1,error:"Invalid token"};if(r.expiresAt&&new Date(r.expiresAt)<new Date)return{valid:!1,error:"Token has expired"};if(!(n==="read"?r.permissions.includes("read")||r.permissions.includes("publish"):r.permissions.includes("publish")))return{valid:!1,error:`Token does not have ${n} permission`};return this.storage.updateTokenLastUsed(r.tokenHash).catch((s)=>console.warn("Failed to update token last-used:",s)),{valid:!0,userId:r.userId,tokenId:r.id}}return{valid:!1,error:"Invalid token"}}async findUser(e){let t=await this.storage.getUser(e.toLowerCase().trim());if(!t)return null;return{email:t.email,name:t.name,role:t.role||"user",subscription:t.subscription,createdAt:t.createdAt,updatedAt:t.updatedAt}}async getSubscription(e){let t=await this.storage.getUser(e.toLowerCase().trim());if(!t?.subscription)return null;return{tier:Ml(t.subscription.tier),status:t.subscription.status||"none",stripeCustomerId:t.subscription.stripeCustomerId,stripeSubscriptionId:t.subscription.stripeSubscriptionId,currentPeriodEnd:t.subscription.currentPeriodEnd,updatedAt:t.subscription.updatedAt}}async getTier(e){if(!e||e==="_admin")return"free";return B_(await this.getSubscription(e))}async setSubscription(e,t){let n=e.toLowerCase().trim(),r=await this.storage.getUser(n);if(!r)throw new Re(`No such account: ${e}`,404);let i={...r,updatedAt:new Date().toISOString()};if(!t||t.tier==="free")delete i.subscription;else i.subscription={tier:t.tier,status:t.status,stripeCustomerId:t.stripeCustomerId,stripeSubscriptionId:t.stripeSubscriptionId,currentPeriodEnd:t.currentPeriodEnd,updatedAt:new Date().toISOString()};await this.storage.upsertUser(i)}async getTeamMembers(e){return(await this.storage.getUser(e.toLowerCase().trim()))?.team?.members??[]}async getTeamOwner(e){return(await this.storage.getUser(e.toLowerCase().trim()))?.teamOwner??null}async canActFor(e,t){if(!e||!t)return!1;let n=e.toLowerCase().trim(),r=t.toLowerCase().trim();if(n===r)return!0;return await this.getTeamOwner(n)===r}async addTeamMember(e,t,n){let r=e.toLowerCase().trim(),i=t.toLowerCase().trim();if(i===r)throw new Re("You are already on your own team",400);let s=await this.storage.getUser(r);if(!s)throw new Re("No such account",404);let o=await this.storage.getUser(i);if(!o)throw new Re(`${t} does not have an account yet \u2014 they need to sign up first`,404);if(o.teamOwner&&o.teamOwner!==r)throw new Re(`${t} is already on another team`,409);if(o.team?.members?.length)throw new Re(`${t} runs their own team`,409);let a=s.team?.members??[];if(a.includes(i))return a;if(a.length+1>=n)throw new Re(`That plan includes ${n} seats, and they are all taken`,402);let l=[...a,i];return await this.storage.upsertUser({...s,team:{members:l,updatedAt:new Date().toISOString()},updatedAt:new Date().toISOString()}),await this.storage.upsertUser({...o,teamOwner:r,updatedAt:new Date().toISOString()}),l}async removeTeamMember(e,t){let n=e.toLowerCase().trim(),r=t.toLowerCase().trim(),i=await this.storage.getUser(n);if(!i)throw new Re("No such account",404);let s=(i.team?.members??[]).filter((a)=>a!==r);await this.storage.upsertUser({...i,team:{members:s,updatedAt:new Date().toISOString()},updatedAt:new Date().toISOString()});let o=await this.storage.getUser(r);if(o?.teamOwner===n){let a={...o,updatedAt:new Date().toISOString()};delete a.teamOwner,await this.storage.upsertUser(a)}return s}async findByStripeCustomer(e,t){if(t){let n=await this.getSubscription(t);if(n?.stripeCustomerId===e||!n?.stripeCustomerId){let r=await this.storage.getUser(t.toLowerCase().trim());if(r)return r.email}}return null}}class Re extends Error{status;constructor(e,t=400){super(e);this.name="AuthError",this.status=t}}class Lf{users=new Map;apiTokensByHash=new Map;apiTokensByUser=new Map;sessions=new Map;async getUser(e){return this.users.get(e.toLowerCase())||null}async putUser(e){this.users.set(e.email.toLowerCase(),e),this.onMutate()}async upsertUser(e){this.users.set(e.email.toLowerCase(),e),this.onMutate()}async getUserByEmail(e){return this.getUser(e)}async putApiToken(e){this.apiTokensByHash.set(e.tokenHash,e);let t=this.apiTokensByUser.get(e.userId)||[];t.push(e),this.apiTokensByUser.set(e.userId,t),this.onMutate()}async getApiTokenByHash(e){return this.apiTokensByHash.get(e)||null}async listApiTokens(e){return this.apiTokensByUser.get(e)||[]}async deleteApiToken(e,t){let n=this.apiTokensByUser.get(e)||[],r=n.find((i)=>i.id===t);if(r)this.apiTokensByHash.delete(r.tokenHash),this.apiTokensByUser.set(e,n.filter((i)=>i.id!==t)),this.onMutate()}async updateTokenLastUsed(e){let t=this.apiTokensByHash.get(e);if(t)t.lastUsedAt=new Date().toISOString(),this.onMutate()}async putSession(e){this.sessions.set(e.tokenHash,e),this.onMutate()}async getSession(e){return this.sessions.get(e)||null}async deleteSession(e){this.sessions.delete(e),this.onMutate()}onMutate(){}captureState(){return{users:Object.fromEntries(this.users),apiTokens:[...this.apiTokensByHash.values()],sessions:Object.fromEntries(this.sessions)}}applyState(e){if(e?.users)this.users=new Map(Object.entries(e.users));if(e?.sessions)this.sessions=new Map(Object.entries(e.sessions));if(e?.apiTokens){this.apiTokensByHash=new Map,this.apiTokensByUser=new Map;for(let t of e.apiTokens){this.apiTokensByHash.set(t.tokenHash,t);let n=this.apiTokensByUser.get(t.userId)||[];n.push(t),this.apiTokensByUser.set(t.userId,n)}}}}class B0{db;tableName;constructor(e,t="us-east-1"){this.tableName=e,this.db=new V(t)}async getUser(e){let t=await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`USER#${e.toLowerCase()}`},SK:{S:"PROFILE"}}});if(!t.Item)return null;let n=V.unmarshal(t.Item);return{email:n.email,name:n.name,passwordHash:n.passwordHash,role:n.role==="admin"?"admin":"user",...n.subscription?{subscription:JSON.parse(n.subscription)}:{},...n.team?{team:JSON.parse(n.team)}:{},...n.teamOwner?{teamOwner:n.teamOwner}:{},createdAt:n.createdAt,updatedAt:n.updatedAt}}async putUser(e){await this.db.putItem({TableName:this.tableName,Item:V.marshal({PK:`USER#${e.email.toLowerCase()}`,SK:"PROFILE",email:e.email,name:e.name,passwordHash:e.passwordHash,role:e.role||"user",...e.subscription?{subscription:JSON.stringify(e.subscription)}:{},...e.team?{team:JSON.stringify(e.team)}:{},...e.teamOwner?{teamOwner:e.teamOwner}:{},createdAt:e.createdAt,updatedAt:e.updatedAt}),ConditionExpression:"attribute_not_exists(PK)"})}async upsertUser(e){await this.db.putItem({TableName:this.tableName,Item:V.marshal({PK:`USER#${e.email.toLowerCase()}`,SK:"PROFILE",email:e.email,name:e.name,passwordHash:e.passwordHash,role:e.role||"user",...e.subscription?{subscription:JSON.stringify(e.subscription)}:{},...e.team?{team:JSON.stringify(e.team)}:{},...e.teamOwner?{teamOwner:e.teamOwner}:{},createdAt:e.createdAt,updatedAt:e.updatedAt})})}async getUserByEmail(e){return this.getUser(e)}async putApiToken(e){await this.db.putItem({TableName:this.tableName,Item:V.marshal({PK:`USER#${e.userId}`,SK:`API_TOKEN#${e.id}`,id:e.id,name:e.name,userId:e.userId,tokenHash:e.tokenHash,permissions:e.permissions,createdAt:e.createdAt,...e.lastUsedAt?{lastUsedAt:e.lastUsedAt}:{},...e.expiresAt?{expiresAt:e.expiresAt}:{}})}),await this.db.putItem({TableName:this.tableName,Item:V.marshal({PK:`TOKEN_HASH#${e.tokenHash}`,SK:"METADATA",id:e.id,name:e.name,userId:e.userId,tokenHash:e.tokenHash,permissions:e.permissions,createdAt:e.createdAt,...e.lastUsedAt?{lastUsedAt:e.lastUsedAt}:{},...e.expiresAt?{expiresAt:e.expiresAt}:{}})})}async getApiTokenByHash(e){let t=await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`TOKEN_HASH#${e}`},SK:{S:"METADATA"}}});if(!t.Item)return null;let n=V.unmarshal(t.Item);return{id:n.id,name:n.name,userId:n.userId,tokenHash:n.tokenHash,permissions:n.permissions||["publish","read"],createdAt:n.createdAt,lastUsedAt:n.lastUsedAt||void 0,expiresAt:n.expiresAt||void 0}}async listApiTokens(e){return(await this.db.query({TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :prefix)",ExpressionAttributeValues:{":pk":{S:`USER#${e}`},":prefix":{S:"API_TOKEN#"}}})).Items.map((n)=>{let r=V.unmarshal(n);return{id:r.id,name:r.name,userId:r.userId,tokenHash:r.tokenHash,permissions:r.permissions||["publish","read"],createdAt:r.createdAt,lastUsedAt:r.lastUsedAt||void 0,expiresAt:r.expiresAt||void 0}})}async deleteApiToken(e,t){let n=await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`USER#${e}`},SK:{S:`API_TOKEN#${t}`}}});if(n.Item){let r=V.unmarshal(n.Item);if(r.tokenHash)await this.db.deleteItem({TableName:this.tableName,Key:{PK:{S:`TOKEN_HASH#${r.tokenHash}`},SK:{S:"METADATA"}}});await this.db.deleteItem({TableName:this.tableName,Key:{PK:{S:`USER#${e}`},SK:{S:`API_TOKEN#${t}`}}})}}async updateTokenLastUsed(e){let t=new Date().toISOString();await this.db.updateItem({TableName:this.tableName,Key:{PK:{S:`TOKEN_HASH#${e}`},SK:{S:"METADATA"}},UpdateExpression:"SET lastUsedAt = :now",ExpressionAttributeValues:{":now":{S:t}}})}async putSession(e){await this.db.putItem({TableName:this.tableName,Item:V.marshal({PK:`SESSION#${e.tokenHash}`,SK:"METADATA",tokenHash:e.tokenHash,userId:e.userId,createdAt:e.createdAt,expiresAt:e.expiresAt})})}async getSession(e){let t=await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`SESSION#${e}`},SK:{S:"METADATA"}}});if(!t.Item)return null;let n=V.unmarshal(t.Item);if(n.expiresAt&&new Date(n.expiresAt)<new Date)return await this.deleteSession(e),null;return{tokenHash:n.tokenHash,userId:n.userId,createdAt:n.createdAt,expiresAt:n.expiresAt}}async deleteSession(e){await this.db.deleteItem({TableName:this.tableName,Key:{PK:{S:`SESSION#${e}`},SK:{S:"METADATA"}}})}}class AA extends Lf{snapshot;loaded;constructor(e){super();this.snapshot=new Cr(e.s3,e.bucket,e.key||"auth/registry-auth.json",()=>this.captureState()),this.loaded=this.snapshot.load().then((t)=>{if(t)this.applyState(t)})}ready(){return this.loaded}onMutate(){this.snapshot.scheduleSave()}async flush(){await this.snapshot.flush()}}function W0(e,t){let n=process.env.S3_BUCKET,r=ot();if(r.provider!=="aws"&&n&&n!=="local")return new AA({s3:et(r),bucket:n});let i=e||process.env.DYNAMODB_TABLE||"local";if(i&&i!=="local")return new B0(i,t||process.env.AWS_REGION||"us-east-1");return new Lf}function $A(e=process.env){return(e.REGISTRY_PLUGINS||"").split(",").map((t)=>t.trim()).filter(Boolean)}function J8(e,t){if(!e||typeof e!=="object"||typeof e.name!=="string")throw TypeError(`Registry plugin "${t}" must default-export an object with a \`name\` (or a function returning one)`);return e}async function CA(e){let t=e.startsWith(".")?new URL(e,`file://${process.cwd()}/`).href:e,n;try{n=await import(t)}catch(s){throw Error(`Failed to load registry plugin "${e}": ${s.message}`)}let r=n.default,i=typeof r==="function"?await r():r;return J8(i,e)}var Wo=null;function Pl(e=process.env){if(Wo)return Wo;let t=$A(e);return Wo=t.length===0?Promise.resolve([]):Promise.all(t.map(CA)).then((n)=>{return console.log(`Loaded ${n.length} registry plugin(s): ${n.map((r)=>r.name).join(", ")}`),n}),Wo}function K8(e){Wo=Promise.resolve(e)}function Q8(){Wo=null}async function U0(){return(await Pl()).some((t)=>typeof t.authorizeRead==="function")}async function P0(e){let t=await Pl(),n;for(let r of t){if(!r.authorizeRead)continue;let i;try{i=await r.authorizeRead(e)}catch(s){return console.error(`Registry plugin "${r.name}" authorizeRead threw:`,s),"deny"}if(i==="deny")return"deny";if(i==="allow")n="allow"}return n}async function q0(e,t){let n=await Pl();for(let r of n){if(!r.handleRequest)continue;try{let i=await r.handleRequest(e,t);if(i)return i}catch(i){return console.error(`Registry plugin "${r.name}" handleRequest threw:`,i),Response.json({error:"Plugin error"},{status:500})}}return null}function Ff(e){Pl().then((t)=>{for(let n of t){if(!n.onEvent)continue;try{let r=n.onEvent(e);if(r&&typeof r.catch==="function")r.catch((i)=>console.error(`Registry plugin "${n.name}" onEvent rejected:`,i))}catch(r){console.error(`Registry plugin "${n.name}" onEvent threw:`,r)}}}).catch(()=>{})}function TA(e){if(!e)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function H8(e){if(e==null)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"}function Is(e=process.env){let t=(e.REGISTRY_VISIBILITY??e.PANTRY_REGISTRY_VISIBILITY??"").trim().toLowerCase();if(t==="private")return"private";if(t==="public")return"public";if(TA(e.REGISTRY_PRIVATE))return"private";return"public"}function Uo(e=process.env,t=Is(e)){let n=e.REGISTRY_ALLOW_SIGNUP;if(TA(n))return!0;if(H8(n))return!1;return t==="public"}function MA(e=process.env){return(e.REGISTRY_SIGNUP_DOMAINS||"").split(",").map((t)=>t.trim().toLowerCase().replace(/^@/,"")).filter(Boolean)}function G0(e,t=process.env){let n=MA(t);if(n.length===0)return!0;let r=e.toLowerCase().trim().split("@")[1]||"";return n.includes(r)}var Z8=new Set(["/health","/ready","/api/registry-info","/login","/signup","/auth/login","/auth/logout","/auth/signup","/auth/me","/favicon.ico","/robots.txt","/webhooks/stripe"]);function OA(e=process.env){return(e.REGISTRY_PUBLIC_PATHS||"").split(",").map((t)=>t.trim()).filter(Boolean)}function jA(e,t=process.env){if(Z8.has(e))return!0;for(let n of OA(t)){if(n==="/"){if(e==="/")return!0;continue}if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return!0}return!1}function e6(e){if(e.method!=="GET")return!1;return(e.headers.get("accept")||"").includes("text/html")}async function X0(e,t,n){let r=n.env??process.env,i=n.visibility??Is(r),s=t.pathname,o=n.corsHeaders??{},a=i==="public"||jA(s,r),l={authenticated:!1,userId:null},c=a&&!await U0()?l:await n.identify(e),u=await P0({req:e,url:t,path:s,method:e.method,visibility:i,userId:c.userId});if(u==="allow")return null;if(u!=="deny"){if(a)return null;if(c.authenticated)return Ff({type:"access-granted",path:s,method:e.method,userId:c.userId}),null}let f=u==="deny"?"Denied by access policy":"Authentication required";if(Ff({type:"access-denied",path:s,method:e.method,reason:f}),e6(e)&&u!=="deny")return new Response(null,{status:302,headers:{...o,Location:`/login?next=${encodeURIComponent(s+t.search)}`}});let d=r.BASE_URL||t.origin;return Response.json({error:f,...u==="deny"?{}:{hint:`This registry is private. Store a token with: pantry token set --registry ${d}`,docs:"https://pantry.dev/self-hosting"}},{status:u==="deny"?403:401,headers:{...o,...u==="deny"?{}:{"WWW-Authenticate":'Bearer realm="pantry-registry"'}}})}function V0(e=process.env,t){let n=Is(e),r=(t||e.BASE_URL||"").replace(/\/$/,"");return{visibility:n,requiresAuth:n==="private",signupsEnabled:Uo(e,n),...r?{loginUrl:`${r}/login`}:{},docs:"https://pantry.dev/self-hosting"}}function If(e){return e.toLowerCase().trim().replace(/[^a-z0-9._@-]/g,"_").replace(/@/g,"_at_")}function NA(e){let t=String(e||"").trim();if(!t||t.length>200)return null;if(t.includes("..")||t.startsWith("/"))return null;if(!/^[\w@./+-]+$/.test(t))return null;return t.replace(/\//g,"_")}async function t6(e){let t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map((n)=>n.toString(16).padStart(2,"0")).join("")}function n6(e,t){if(!e)return!0;let[n,r]=e.split("-");if(n!=="sha256"||!r)return!0;try{return Array.from(Buffer.from(r,"base64")).map((s)=>s.toString(16).padStart(2,"0")).join("")===t}catch{return!0}}var r6=async(e)=>{let t=await fetch(e,{redirect:"follow"});if(!t.ok)throw Error(`HTTP ${t.status}`);return t.arrayBuffer()};class Y0{storage;fetcher;maxArtifactBytes;maxEntries;constructor(e,t={}){this.storage=e,this.fetcher=t.fetcher||r6,this.maxArtifactBytes=t.maxArtifactBytes??209715200,this.maxEntries=t.maxEntries??2000}indexKey(e){return`mirror/${If(e)}/index.json`}async getIndex(e){try{let t=await this.storage.download(this.indexKey(e)),n=JSON.parse(new TextDecoder().decode(t));if(n&&Array.isArray(n.entries))return n}catch{}return{org:e,updatedAt:new Date().toISOString(),entries:[]}}async putIndex(e){let t=new TextEncoder().encode(JSON.stringify(e)).buffer;await this.storage.upload(this.indexKey(e.org),t)}async snapshot(e,t){let n=await this.getIndex(e),r=new Map(n.entries.map((c)=>[`${c.name}@${c.version}:${c.integrity||""}`,c])),i=0,s=0,o=0,a=[];for(let c of t.slice(0,this.maxEntries)){let u=NA(c.name),f=NA(c.version);if(!u||!f){o++;continue}let d=`${c.name}@${c.version}:${c.integrity||""}`,h=r.get(d);if(h?.key){s++,a.push(h);continue}let p={...c,mirroredAt:new Date().toISOString()};if(!c.resolved){p.error="no download URL",o++,r.set(d,p),a.push(p);continue}try{let m=await this.fetcher(c.resolved);if(m.byteLength>this.maxArtifactBytes)p.error=`artifact is larger than the ${Math.round(this.maxArtifactBytes/1048576)}MB mirror limit`,o++;else{let g=await t6(m);if(!n6(c.integrity,g))p.error="integrity mismatch \u2014 upstream bytes differ from the lockfile",o++;else{let y=`mirror/${If(e)}/${u}/${f}/${g.slice(0,32)}.tgz`;await this.storage.upload(y,m),p.key=y,p.size=m.byteLength,p.sha256=g,i++}}}catch(m){p.error=m.message,o++}r.set(d,p),a.push(p)}let l={org:e,updatedAt:new Date().toISOString(),entries:[...r.values()]};return await this.putIndex(l),{mirrored:i,skipped:s,failed:o,entries:a}}async fetchArtifact(e,t,n){let i=(await this.getIndex(e)).entries.filter((s)=>s.name===t&&s.version===n&&s.key).sort((s,o)=>o.mirroredAt.localeCompare(s.mirroredAt));for(let s of i)try{return{bytes:await this.storage.download(s.key),record:s}}catch{}return null}async list(e){return[...(await this.getIndex(e)).entries].sort((n,r)=>r.mirroredAt.localeCompare(n.mirroredAt))}async stats(e){let t=await this.list(e);return{artifacts:t.length,stored:t.filter((n)=>n.key).length,bytes:t.reduce((n,r)=>n+(r.size||0),0),failed:t.filter((n)=>n.error).length}}}function J0(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=="object")continue;let r=n;if(typeof r.name!=="string"||typeof r.version!=="string")continue;t.push({name:r.name,version:r.version,resolved:typeof r.resolved==="string"?r.resolved:void 0,integrity:typeof r.integrity==="string"?r.integrity:void 0,ecosystem:typeof r.ecosystem==="string"?r.ecosystem:void 0,license:typeof r.license==="string"?r.license:void 0})}return t}var RA={critical:0,high:1,moderate:2,low:3,unknown:4};function i6(e){switch((e||"npm").toLowerCase()){case"npm":return"npm";case"pypi":case"python":return"PyPI";case"cargo":case"crates":return"crates.io";case"go":return"Go";case"composer":case"packagist":return"Packagist";case"rubygems":case"gem":return"RubyGems";case"maven":return"Maven";case"nuget":return"NuGet";default:return""}}function s6(e){let t=e?.database_specific?.severity||e?.affected?.[0]?.database_specific?.severity;if(typeof t==="string"){let r=t.toLowerCase();if(r==="critical"||r==="high"||r==="moderate"||r==="low")return r;if(r==="medium")return"moderate"}let n=e?.severity?.find((r)=>r.type?.startsWith("CVSS"))?.score;if(typeof n==="string"){let r=n.match(/\/(?:AV|A):/)?null:Number.parseFloat(n);if(r!==null&&Number.isFinite(r)){if(r>=9)return"critical";if(r>=7)return"high";if(r>=4)return"moderate";if(r>0)return"low"}}return"unknown"}function o6(e){for(let t of e?.affected||[])for(let n of t?.ranges||[])for(let r of n?.events||[])if(r?.fixed)return String(r.fixed);return}var a6=async(e)=>{let t=e.map((i)=>({entry:i,ecosystem:i6(i.ecosystem)})).filter((i)=>i.ecosystem),n=new Map;if(t.length===0)return n;let r=500;for(let i=0;i<t.length;i+=r){let s=t.slice(i,i+r),o=await fetch("https://api.osv.dev/v1/querybatch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({queries:s.map((c)=>({package:{name:c.entry.name,ecosystem:c.ecosystem},version:c.entry.version}))})});if(!o.ok)throw Error(`OSV responded ${o.status}`);let l=(await o.json()).results||[];for(let c=0;c<s.length;c++){let u=(l[c]?.vulns||[]).map((d)=>d.id).slice(0,25);if(u.length===0)continue;let f=[];for(let d of u)try{let h=await fetch(`https://api.osv.dev/v1/vulns/${encodeURIComponent(d)}`),p=h.ok?await h.json():null;f.push({type:"vulnerability",package:s[c].entry.name,version:s[c].entry.version,ecosystem:s[c].ecosystem,id:d,severity:p?s6(p):"unknown",summary:p?.summary||p?.details?.slice(0,200)||d,url:`https://osv.dev/vulnerability/${d}`,fixedIn:p?o6(p):void 0})}catch{f.push({type:"vulnerability",package:s[c].entry.name,version:s[c].entry.version,ecosystem:s[c].ecosystem,id:d,severity:"unknown",summary:d,url:`https://osv.dev/vulnerability/${d}`})}n.set(`${s[c].entry.name}@${s[c].entry.version}`,f)}}return n};function K0(e){return e.trim().toUpperCase()}function l6(e,t){if(!t||!t.allow?.length&&!t.deny?.length)return null;let n=e.license?.trim();if(!n){if(!t.allow?.length)return null;return{type:"license",package:e.name,version:e.version,license:"unknown",reason:"unknown",summary:`${e.name}@${e.version} does not declare a licence, and your policy allows only: ${t.allow.join(", ")}`}}let r=K0(n);if(t.deny?.some((i)=>K0(i)===r))return{type:"license",package:e.name,version:e.version,license:n,reason:"denied",summary:`${e.name}@${e.version} is ${n}, which your policy denies`};if(t.allow?.length&&!t.allow.some((i)=>K0(i)===r))return{type:"license",package:e.name,version:e.version,license:n,reason:"not-allowed",summary:`${e.name}@${e.version} is ${n}, which is not in your allowed list`};return null}class Q0{storage;fetcher;constructor(e,t=a6){this.storage=e;this.fetcher=t}key(e){return`security/${If(e)}/watch.json`}async getWatchList(e){try{let t=await this.storage.download(this.key(e)),n=JSON.parse(new TextDecoder().decode(t));if(n&&Array.isArray(n.entries))return n}catch{}return{org:e,entries:[],updatedAt:new Date().toISOString()}}async setWatchList(e,t,n){let r=await this.getWatchList(e),i={org:e,entries:t,policy:n??r.policy,updatedAt:new Date().toISOString()},s=new TextEncoder().encode(JSON.stringify(i)).buffer;return await this.storage.upload(this.key(e),s),i}async setPolicy(e,t){let n=await this.getWatchList(e);return this.setWatchList(e,n.entries,t)}async report(e){let t=await this.getWatchList(e),n=[],r;try{let s=await this.fetcher(t.entries);for(let o of s.values())n.push(...o)}catch(s){r=`advisory lookup failed: ${s.message}`}for(let s of t.entries){let o=l6(s,t.policy);if(o)n.push(o)}n.sort((s,o)=>{let a=s.type==="vulnerability"?RA[s.severity]:5,l=o.type==="vulnerability"?RA[o.severity]:5;return a-l||s.package.localeCompare(o.package)});let i={critical:0,high:0,moderate:0,low:0,license:0};for(let s of n)if(s.type==="license")i.license++;else if(s.severity!=="unknown")i[s.severity]++;return{org:e,generatedAt:new Date().toISOString(),watched:t.entries.length,alerts:n,counts:i,...r?{degraded:r}:{}}}}function H0(e){if(!e||typeof e!=="object")return;let t=e,n=(s)=>Array.isArray(s)?s.filter((o)=>typeof o==="string"&&o.length<100).slice(0,200):void 0,r=n(t.allow),i=n(t.deny);if(!r&&!i)return;return{...r?{allow:r}:{},...i?{deny:i}:{}}}function FA(e){let t=(e.ecosystem||"npm").toLowerCase(),[n,r]=e.name.startsWith("@")?[e.name.slice(0,e.name.indexOf("/")),e.name.slice(e.name.indexOf("/")+1)]:[null,e.name],i=n?`${encodeURIComponent(n)}/`:"";return`pkg:${t}/${i}${encodeURIComponent(r)}@${encodeURIComponent(e.version)}`}function LA(e){let t=[];if(e.sha256)t.push({alg:"SHA-256",content:e.sha256});if(e.integrity?.startsWith("sha512-"))try{let n=Array.from(Buffer.from(e.integrity.slice(7),"base64")).map((r)=>r.toString(16).padStart(2,"0")).join("");t.push({alg:"SHA-512",content:n})}catch{}return t}function c6(e,t){let n=t.timestamp||new Date().toISOString();return{bomFormat:"CycloneDX",specVersion:"1.5",serialNumber:`urn:uuid:${t.documentId||zA(t.org,n)}`,version:1,metadata:{timestamp:n,tools:[{vendor:"pantry",name:"pantry-registry",version:"1"}],component:{type:"application",name:t.subject||t.org,version:n.slice(0,10)}},components:e.map((r)=>({type:"library",name:r.name,version:r.version,purl:FA(r),...r.license?{licenses:[{license:{id:r.license}}]}:{},...LA(r).length?{hashes:LA(r)}:{},...r.resolved?{externalReferences:[{type:"distribution",url:r.resolved}]}:{},properties:[{name:"pantry:mirrored",value:r.key?"true":"false"},...r.mirroredAt?[{name:"pantry:mirroredAt",value:r.mirroredAt}]:[]]}))}}function u6(e,t){let n=t.timestamp||new Date().toISOString(),r=t.subject||t.org,i=e.map((s,o)=>({SPDXID:`SPDXRef-Package-${o}`,name:s.name,versionInfo:s.version,downloadLocation:s.resolved||"NOASSERTION",filesAnalyzed:!1,licenseConcluded:s.license||"NOASSERTION",licenseDeclared:s.license||"NOASSERTION",copyrightText:"NOASSERTION",externalRefs:[{referenceCategory:"PACKAGE-MANAGER",referenceType:"purl",referenceLocator:FA(s)}],...s.sha256?{checksums:[{algorithm:"SHA256",checksumValue:s.sha256}]}:{}}));return{spdxVersion:"SPDX-2.3",dataLicense:"CC0-1.0",SPDXID:"SPDXRef-DOCUMENT",name:r,documentNamespace:`https://pantry.dev/sbom/${encodeURIComponent(t.org)}/${t.documentId||zA(t.org,n)}`,creationInfo:{created:n,creators:["Tool: pantry-registry"]},packages:i,relationships:i.map((s)=>({spdxElementId:"SPDXRef-DOCUMENT",relatedSpdxElement:s.SPDXID,relationshipType:"DESCRIBES"}))}}function IA(e,t,n){return t==="spdx"?u6(e,n):c6(e,n)}function DA(e){return String(e||"").toLowerCase()==="spdx"?"spdx":"cyclonedx"}function zA(e,t){let n=`${e}:${t}`,r=2166136261,i=16777619;for(let u=0;u<n.length;u++)r=Math.imul(r^n.charCodeAt(u),16777619)>>>0,i=Math.imul(i+n.charCodeAt(u)+u,2246822507)>>>0;let s=(u)=>u.toString(16).padStart(8,"0"),o=s(r),a=s(i),l=s((r^i)>>>0),c=s(r+i>>>0);return`${o}-${a.slice(0,4)}-4${a.slice(5,8)}-a${l.slice(1,4)}-${l.slice(4)}${c}`}import{readdirSync as f6,readFileSync as BA}from"fs";import{join as d6,relative as h6,sep as Z0}from"path";var WA=["darwin-arm64","darwin-x86-64","linux-x86-64","linux-arm64"];function UA(e){let t=[],n=(r)=>{for(let i of f6(r,{withFileTypes:!0})){let s=d6(r,i.name);if(i.isDirectory())n(s);else if(i.isFile()&&i.name.endsWith(".ts"))t.push(s)}};return n(e),t}function p6(e){let t=e.match(/\bdomain:\s*(['"])([^'"]+)\1\s+as const/)?.[2],n=e.match(/\bversions:\s*\[([\s\S]*?)\]\s+as const/)?.[1];if(!t||n===void 0)return null;let r=[...n.matchAll(/['"]([^'"]+)['"]/g)].map((i)=>i[1]);return{domain:t,versions:r}}function PA(e){let t=new Map;for(let n of UA(e)){if(n.endsWith(`${Z0}index.ts`)||n.endsWith(`${Z0}aliases.ts`))continue;let r=p6(BA(n,"utf8"));if(r)t.set(r.domain,new Set(r.versions))}return t}function m6(e){let t=new Set;for(let n of e){let r=n.trim().replace(/^['"]|['"]$/g,"");if(!r)continue;let[i,s]=r.split("/"),o=s==="aarch64"||s==="arm64"?"arm64":s==="x86-64"||s==="x86_64"?"x86-64":s;if(i==="darwin")if(o)t.add(`darwin-${o}`);else t.add("darwin-arm64"),t.add("darwin-x86-64");else if(i==="linux")if(o)t.add(`linux-${o}`);else t.add("linux-arm64"),t.add("linux-x86-64")}return[...t].filter((n)=>WA.includes(n))}function qA(e){let t=new Map;for(let n of UA(e)){let i=BA(n,"utf8").match(/platforms:\s*\[([^\]]*)\]/);if(!i)continue;let s=m6(i[1].split(","));if(s.length>0&&s.length<WA.length){let o=h6(e,n).replace(/\.ts$/,"").split(Z0).join("/");t.set(o,s)}}return t}import{createHmac as g6,randomUUID as y6,timingSafeEqual as w6}from"crypto";var VA=1073741824,b6=3600,YA=16,ey=".pantry-staging/malware";class zf{s3;bucket;constructor(e,t){this.s3=e;this.bucket=t}getObject(e){return this.s3.getObjectBuffer(this.bucket,e)}async getObjectStream(e){let{body:t}=await this.s3.getObjectStream(this.bucket,e),n=t[Symbol.asyncIterator];if(typeof n==="function")return{[Symbol.asyncIterator]:()=>n.call(t)};return{async*[Symbol.asyncIterator](){let r=t.getReader();try{while(!0){let i=await r.read();if(i.done)break;yield i.value}}finally{r.releaseLock?.()}}}}putObject(e,t,n){return this.s3.putObject({bucket:this.bucket,key:e,body:t,contentType:n})}copyObject(e,t){return this.s3.copyObject(this.bucket,e,t)}deleteObject(e){return this.s3.deleteObject(this.bucket,e)}headObject(e){return this.s3.headObject(this.bucket,e)}createUploadUrl(e,t,n){return this.s3.generatePresignedPutUrl(this.bucket,e,t,n)}}class ie extends Error{status;code;scan;constructor(e,t,n,r){super(e);this.status=t;this.code=n;this.scan=r}}var JA=/^[a-z0-9](?:[a-z0-9._-]|\/(?=[a-z0-9])){0,213}$/i,KA=/^[a-z0-9._+-]{1,64}$/i,QA=/^(?:darwin|linux|windows|freebsd)-(?:arm64|x86-64|x86|riscv64)$/,v6=/^[a-z0-9][a-z0-9._+-]{0,239}\.tar\.gz$/i,HA=/^[a-f0-9]{64}$/;function Df(e,t=VA){if(!e||typeof e!=="object")throw new ie("Publish request must be an object",400,"INVALID_BINARY_PUBLISH");let n=e,r=typeof n.domain==="string"?n.domain.trim():"",i=typeof n.version==="string"?n.version.trim():"",s=typeof n.filename==="string"?n.filename.trim():"",o=typeof n.sha256==="string"?n.sha256.toLowerCase():"",a=typeof n.size==="number"?n.size:Number.NaN,l=Array.isArray(n.platforms)?[...new Set(n.platforms.filter((c)=>typeof c==="string").map((c)=>c.trim()))]:[];if(!JA.test(r)||r.includes("..")||r.endsWith("/"))throw new ie("Invalid binary package domain",422,"INVALID_BINARY_DOMAIN");if(!KA.test(i))throw new ie("Invalid binary package version",422,"INVALID_BINARY_VERSION");if(!v6.test(s)||s.includes(".."))throw new ie("Invalid binary artifact filename",422,"INVALID_BINARY_FILENAME");if(l.length===0||l.length>YA||l.some((c)=>!QA.test(c)))throw new ie("One or more binary platforms are invalid",422,"INVALID_BINARY_PLATFORM");if(!Number.isSafeInteger(a)||a<=0||a>t)throw new ie(`Binary artifact size must be between 1 and ${t} bytes`,413,"INVALID_BINARY_SIZE");if(!HA.test(o))throw new ie("Binary artifact SHA-256 must be 64 lowercase hexadecimal characters",422,"INVALID_BINARY_SHA256");return{domain:r,version:i,platforms:l,filename:s,size:a,sha256:o}}function x6(e){if(!e||typeof e!=="object")throw new ie("Rescan request must be an object",400,"INVALID_BINARY_RESCAN");let t=e,n=typeof t.domain==="string"?t.domain.trim():"",r=typeof t.version==="string"?t.version.trim():"",i=Array.isArray(t.platforms)?[...new Set(t.platforms.filter((s)=>typeof s==="string").map((s)=>s.trim()))]:[];if(!JA.test(n)||n.includes("..")||n.endsWith("/"))throw new ie("Invalid binary package domain",422,"INVALID_BINARY_DOMAIN");if(!KA.test(r))throw new ie("Invalid binary package version",422,"INVALID_BINARY_VERSION");if(i.length===0||i.length>YA||i.some((s)=>!QA.test(s)))throw new ie("One or more binary platforms are invalid",422,"INVALID_BINARY_PLATFORM");return{domain:n,version:r,platforms:i}}function ty(e){try{return decodeURIComponent(new URL(e).pathname.replace(/^\/+/,""))}catch{return decodeURIComponent(e.replace(/^\/+/,""))}}function S6(e){return Buffer.from(e).toString("base64url")}function k6(e){return Buffer.from(e,"base64url").toString("utf8")}function GA(e,t){return g6("sha256",t).update(e).digest("base64url")}function _6(e,t){let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&w6(n,r)}function XA(e){let t=e["content-length"]||e["Content-Length"];if(!t)return null;let n=Number.parseInt(t,10);return Number.isSafeInteger(n)&&n>=0?n:null}function E6(e,t){let n=e.split(/[.+_-]/),r=t.split(/[.+_-]/);for(let i=0;i<Math.max(n.length,r.length);i++){let s=Number(n[i]||0),o=Number(r[i]||0);if(Number.isFinite(s)&&Number.isFinite(o)&&s!==o)return s>o;let a=(n[i]||"").localeCompare(r[i]||"");if(a!==0)return a>0}return!1}function Ds(e){return`${e}.scan.json`}function ny(e,t=()=>!1){let n=structuredClone(e);n.versions||={};for(let[r,i]of Object.entries(n.versions)){let s=i.platforms||{};for(let[o,a]of Object.entries(s))if(!t(n.name,r,o)&&a?.malwareScan?.verdict!=="clean")delete s[o];if(Object.keys(s).length===0)delete n.versions[r]}if(!n.versions[n.latestVersion])n.latestVersion=Object.keys(n.versions).sort((r,i)=>i.localeCompare(r,void 0,{numeric:!0})).at(0)||"";return n}class Bf{store;scanner;options;maxBytes;stagingTtlSeconds;now;locks=new Map;constructor(e,t,n){this.store=e;this.scanner=t;this.options=n;if(!n.tokenSecret||n.tokenSecret.length<16)throw Error("binary staging token secret must contain at least 16 characters");this.maxBytes=n.maxBytes||VA,this.stagingTtlSeconds=n.stagingTtlSeconds||b6,this.now=n.now||Date.now}initiate(e){let t=Df(e,this.maxBytes),n={...t,stagingKey:`${ey}/${y6()}/${t.filename}`,expiresAt:this.now()+this.stagingTtlSeconds*1000},r=S6(JSON.stringify(n)),i=GA(r,this.options.tokenSecret);return{uploadId:`${r}.${i}`,uploadUrl:this.store.createUploadUrl(n.stagingKey,"application/gzip",this.stagingTtlSeconds),uploadHeaders:{"Content-Type":"application/gzip"},expiresAt:new Date(n.expiresAt).toISOString()}}async complete(e,t,n="binary"){let r=this.verifyClaim(e),i=r.stagingKey.replace(`${ey}/`,".pantry-staging/sealed/"),s=!0;try{let o=await this.store.headObject(r.stagingKey),a=XA(o);if(a!==null&&a!==r.size)throw new ie("Staged artifact size does not match the initiated upload",422,"BINARY_SIZE_MISMATCH")}catch(o){if(o instanceof ie)throw o;s=!1}if(!s){let o=await this.findCompleted(r);if(o)return o;throw new ie("Staged artifact was not found or has expired",404,"BINARY_STAGING_NOT_FOUND")}try{await this.store.copyObject(r.stagingKey,i),await this.store.deleteObject(r.stagingKey);let o={surface:n,name:r.domain,version:r.version,publisher:t},a;if(this.store.getObjectStream&&this.scanner.scanStream)a=await Uu(this.scanner,await this.store.getObjectStream(i),o,{sha256:r.sha256,size:r.size});else{let c=await this.store.getObject(i);if(c.byteLength!==r.size)throw new ie("Staged artifact size does not match the initiated upload",422,"BINARY_SIZE_MISMATCH");a=await Bn(this.scanner,Uint8Array.from(c).buffer,o)}if(a.artifactSha256!==r.sha256)throw new ie("Staged artifact SHA-256 does not match the initiated upload",422,"BINARY_SHA256_MISMATCH",a);if(a.verdict==="blocked")throw new ie("Binary artifact blocked by malware scanning",422,"MALWARE_DETECTED",a);if(a.verdict==="review")throw new ie("Binary artifact requires security review",202,"PACKAGE_REQUIRES_REVIEW",a);if(a.verdict!=="clean")throw new ie("Binary artifact malware scanning is temporarily unavailable",503,"MALWARE_SCAN_UNAVAILABLE",a);let l=await this.withDomainLock(r.domain,()=>this.promote(r,i,a));return await this.options.onPublished?.(l),l}finally{await this.store.deleteObject(r.stagingKey).catch(()=>{}),await this.store.deleteObject(i).catch(()=>{})}}async publishBuffer(e,t,n,r="binary"){let i=Df(e,this.maxBytes);if(t.byteLength!==i.size)throw new ie("Artifact buffer size does not match the publish request",422,"BINARY_SIZE_MISMATCH");let s=this.initiate(i),o=this.verifyClaim(s.uploadId);return await this.store.putObject(o.stagingKey,t,"application/gzip"),this.complete(s.uploadId,n,r)}async rescanExisting(e,t){let n=x6(e);return this.withDomainLock(n.domain,async()=>{let r=`binaries/${n.domain}/metadata.json`,i;try{i=JSON.parse((await this.store.getObject(r)).toString("utf8"))}catch{throw new ie("Binary package metadata was not found",404,"BINARY_METADATA_NOT_FOUND")}let s={};for(let g of n.platforms){let y=i.versions?.[n.version]?.platforms?.[g];if(!y)throw new ie(`Binary platform was not found: ${g}`,404,"BINARY_PLATFORM_NOT_FOUND");s[g]=y}let o=[...new Set(Object.values(s).map((g)=>ty(g.tarball)))];if(o.length!==1)throw new ie("Rescan platforms must reference the same retained artifact",422,"BINARY_RESCAN_ARTIFACT_MISMATCH");let a=o[0];if(!a.startsWith(`binaries/${n.domain}/${n.version}/`))throw new ie("Retained artifact is outside its package namespace",422,"BINARY_RESCAN_ARTIFACT_MISMATCH");if(Object.values(s).every((g)=>g.malwareScan?.verdict==="clean"&&g.malwareScan.artifactSha256===g.sha256))try{let g=JSON.parse((await this.store.getObject(Ds(a))).toString("utf8"));if(g?.scan?.verdict==="clean"&&g.scan.artifactSha256===Object.values(s)[0].sha256)return{action:"already-clean",domain:n.domain,version:n.version,tarball:a,platforms:s,scan:pt(Object.values(s)[0].malwareScan)}}catch{}let c;try{let g=await this.store.headObject(a);c=XA(g)??Object.values(s)[0].size}catch{throw new ie("Retained binary artifact was not found",404,"BINARY_ARTIFACT_NOT_FOUND")}if(!Number.isSafeInteger(c)||c<=0||c>this.maxBytes)throw new ie(`Retained binary artifact size must be between 1 and ${this.maxBytes} bytes`,413,"INVALID_BINARY_SIZE");let u=Object.values(s).map((g)=>g.sha256).find((g)=>HA.test(g||""));if(!u)try{u=(await this.store.getObject(`${a}.sha256`)).toString("utf8").match(/\b[a-f0-9]{64}\b/i)?.[0]?.toLowerCase()}catch{}if(!u)throw new ie("Retained binary artifact has no valid SHA-256",422,"BINARY_SHA256_MISSING");let f={surface:"binary",name:n.domain,version:n.version,publisher:t},d;if(this.store.getObjectStream&&this.scanner.scanStream)d=await Uu(this.scanner,await this.store.getObjectStream(a),f,{sha256:u,size:c});else{let g=await this.store.getObject(a);if(g.byteLength!==c)throw new ie("Retained artifact size does not match metadata",422,"BINARY_SIZE_MISMATCH");d=await Bn(this.scanner,Uint8Array.from(g).buffer,f)}if(d.artifactSha256!==u)throw new ie("Retained artifact SHA-256 does not match metadata",422,"BINARY_SHA256_MISMATCH",d);if(d.verdict==="error")throw new ie("Binary artifact malware scanning is temporarily unavailable",503,"MALWARE_SCAN_UNAVAILABLE",d);if(d.verdict==="blocked"||d.verdict==="review")return this.quarantineExisting(r,i,n,a,d);if(d.verdict!=="clean")throw new ie("Binary artifact malware scanning is temporarily unavailable",503,"MALWARE_SCAN_UNAVAILABLE",d);let h=new Date(this.now()).toISOString(),p={};for(let[g,y]of Object.entries(i.versions||{}))for(let[w,b]of Object.entries(y.platforms||{})){if(ty(b.tarball)!==a)continue;if(b.tarball=a,b.sha256=u,b.size=c,b.malwareScan=d,!b.uploadedAt)b.uploadedAt=h;if(g===n.version)p[w]=b}await this.store.putObject(`${a}.sha256`,`${u} ${a.split("/").at(-1)}
|
|
13429
|
+
},`}function Al(e){return`zig fetch --save '${e.replace(/'/g,"'\\''")}'`}class qu{packages=new Map;tarballs=new Map;hashIndex=new Map;async count(){return this.packages.size}async getPackage(e,t){let n=this.packages.get(e);if(!n)return null;let r=t||n.latest;return n.versions[r]||null}async listVersions(e){let t=this.packages.get(e);if(!t)return[];return Object.keys(t.versions).sort((n,r)=>{let i=(l)=>{let c=l.indexOf("-"),u=(c===-1?l:l.slice(0,c)).split(".").map((d)=>{let h=Number.parseInt(d,10);return Number.isNaN(h)?0:h}),f=c===-1?null:l.slice(c+1);return{numeric:u,prerelease:f}},s=i(n),o=i(r),a=Math.max(s.numeric.length,o.numeric.length);for(let l=0;l<a;l++){let c=(o.numeric[l]??0)-(s.numeric[l]??0);if(c!==0)return c}if(s.prerelease===null&&o.prerelease!==null)return-1;if(s.prerelease!==null&&o.prerelease===null)return 1;if(s.prerelease!==null&&o.prerelease!==null)return s.prerelease<o.prerelease?1:s.prerelease>o.prerelease?-1:0;return 0})}async search(e,t=20){let n=e.toLowerCase(),r=[];for(let i of this.packages.values())if(i.name.toLowerCase().includes(n)||i.description?.toLowerCase().includes(n)||i.keywords?.some((s)=>s.toLowerCase().includes(n))){if(r.push(i),r.length>=t)break}return r}async publish(e,t){Wn(e.malwareScan,t),this.upsertRecord(e),this.tarballs.set(`${e.name}@${e.version}`,t),this.onMutate()}upsertRecord(e){let{name:t,version:n}=e,r=this.packages.get(t);if(!r)r={name:t,description:e.description,license:e.license,repository:e.repository,homepage:e.homepage,author:e.author,keywords:e.keywords,versions:{},latest:n,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};r.versions[n]=e,r.latest=n,r.updatedAt=new Date().toISOString(),this.packages.set(t,r),this.hashIndex.set(e.hash,{name:t,version:n})}onMutate(){}captureState(){return{packages:Object.fromEntries(this.packages),hashIndex:Object.fromEntries(this.hashIndex)}}applyState(e){if(e?.packages)this.packages=new Map(Object.entries(e.packages));if(e?.hashIndex)this.hashIndex=new Map(Object.entries(e.hashIndex))}async exists(e,t){return this.packages.get(e)?.versions[t]!==void 0}async downloadTarball(e,t){let n=`${e}@${t}`;return this.tarballs.get(n)||null}async getByHash(e){let t=this.hashIndex.get(e);if(!t)return null;let n=await this.getPackage(t.name,t.version);if(!n)return null;return{name:t.name,version:t.version,tarballUrl:n.tarballUrl}}async deletePackage(e){let t=this.packages.get(e);if(t){for(let n of Object.keys(t.versions)){let r=`${e}@${n}`;this.tarballs.delete(r);let i=t.versions[n];if(i?.hash)this.hashIndex.delete(i.hash)}this.packages.delete(e),this.onMutate()}}}function hg(e,t){let n=e.replaceAll("@","").replaceAll("/","-");if(!/^[a-z0-9._\-]+$/i.test(n)||n.includes(".."))throw Error(`Invalid package name: ${e}`);return`zig-packages/${n}/${t}/${n}-${t}.tar.gz`}class gg{tableName;db;s3;bucket;baseUrl;constructor(e){this.tableName=e.tableName,this.bucket=e.bucket,this.baseUrl=e.baseUrl,this.db=new V(e.region||"us-east-1"),this.s3=et(ot({region:e.region}))}marshal(e){return V.marshal(e)}unmarshal(e){return V.unmarshal(e)}s3Key(e,t){let n=e.replaceAll("@","").replaceAll("/","-");if(!/^[a-zA-Z0-9._\-]+$/.test(n)||n.includes(".."))throw Error(`Invalid package name: ${e}`);return`zig-packages/${n}/${t}/${n}-${t}.tar.gz`}async count(){return(await this.db.scan({TableName:this.tableName,FilterExpression:"begins_with(PK, :prefix) AND SK = :sk",ExpressionAttributeValues:{":prefix":{S:"ZIG_PACKAGE#"},":sk":{S:"METADATA"}},ProjectionExpression:"PK"})).Count||0}async getPackage(e,t){if(t){let i=await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`ZIG_PACKAGE#${e}`},SK:{S:`VERSION#${t}`}}});if(!i.Item)return null;let s=this.unmarshal(i.Item);return{name:s.name,version:s.version,description:s.description,tarballUrl:s.tarballUrl,hash:s.hash,publishedAt:s.publishedAt,license:s.license,repository:s.repository,homepage:s.homepage,author:s.author,keywords:s.keywords,malwareScan:s.malwareScan}}let n=await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`ZIG_PACKAGE#${e}`},SK:{S:"METADATA"}}});if(!n.Item)return null;let r=this.unmarshal(n.Item);if(!r.latest)return null;return this.getPackage(e,r.latest)}async listVersions(e){return(await this.db.query({TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :prefix)",ExpressionAttributeValues:{":pk":{S:`ZIG_PACKAGE#${e}`},":prefix":{S:"VERSION#"}}})).Items.map((n)=>{return this.unmarshal(n).version}).sort((n,r)=>{let i=(l)=>{let c=l.indexOf("-"),u=(c===-1?l:l.slice(0,c)).split(".").map((d)=>{let h=Number.parseInt(d,10);return Number.isNaN(h)?0:h}),f=c===-1?null:l.slice(c+1);return{numeric:u,prerelease:f}},s=i(n),o=i(r),a=Math.max(s.numeric.length,o.numeric.length);for(let l=0;l<a;l++){let c=(o.numeric[l]??0)-(s.numeric[l]??0);if(c!==0)return c}if(s.prerelease===null&&o.prerelease!==null)return-1;if(s.prerelease!==null&&o.prerelease===null)return 1;if(s.prerelease!==null&&o.prerelease!==null)return s.prerelease<o.prerelease?1:s.prerelease>o.prerelease?-1:0;return 0})}async search(e,t=20){let n=e.toLowerCase(),r=await this.db.scan({TableName:this.tableName,FilterExpression:"begins_with(PK, :prefix) AND SK = :sk",ExpressionAttributeValues:{":prefix":{S:"ZIG_PACKAGE#"},":sk":{S:"METADATA"}}}),i=[];for(let s of r.Items){let o=this.unmarshal(s),a=[o.name,o.description,...o.keywords||[]].filter(Boolean).join(" ").toLowerCase();if(!n||a.includes(n)){let l=await this.listVersions(o.name),c={};for(let u of l.slice(0,10)){let f=await this.getPackage(o.name,u);if(f)c[u]=f}if(i.push({name:o.name,description:o.description,license:o.license,repository:o.repository,homepage:o.homepage,author:o.author,keywords:o.keywords,versions:c,latest:o.latest,createdAt:o.createdAt,updatedAt:o.updatedAt}),i.length>=t)break}}return i}async publish(e,t){Wn(e.malwareScan,t);let{name:n,version:r}=e,i=new Date().toISOString(),s=this.s3Key(n,r);await this.s3.putObject({bucket:this.bucket,key:s,body:Buffer.from(t),contentType:"application/gzip"});let o=e.tarballUrl||`${this.baseUrl}/zig/packages/${encodeURIComponent(n)}/${r}/tarball`;await this.db.putItem({TableName:this.tableName,Item:this.marshal({PK:`ZIG_PACKAGE#${n}`,SK:`VERSION#${r}`,name:n,version:r,tarballUrl:o,hash:e.hash,description:e.description||"",license:e.license||"",repository:e.repository||"",homepage:e.homepage||"",author:e.author||"",keywords:e.keywords||[],publishedAt:e.publishedAt||i,malwareScan:e.malwareScan})}),await this.db.putItem({TableName:this.tableName,Item:this.marshal({PK:`ZIG_PACKAGE#${n}`,SK:"METADATA",name:n,latest:r,description:e.description||"",license:e.license||"",repository:e.repository||"",homepage:e.homepage||"",author:e.author||"",keywords:e.keywords||[],createdAt:i,updatedAt:i})}),await this.db.putItem({TableName:this.tableName,Item:this.marshal({PK:`ZIG_HASH#${e.hash}`,SK:"ZIG_HASH",name:n,version:r,tarballUrl:o})})}async exists(e,t){return(await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`ZIG_PACKAGE#${e}`},SK:{S:`VERSION#${t}`}}})).Item!==void 0}async downloadTarball(e,t){let n=this.s3Key(e,t);try{let r=await this.s3.getObjectBuffer(this.bucket,n);return r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)}catch{return null}}async getByHash(e){let t=await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`ZIG_HASH#${e}`},SK:{S:"ZIG_HASH"}}});if(!t.Item)return null;let n=this.unmarshal(t.Item);return{name:n.name,version:n.version,tarballUrl:n.tarballUrl}}async deletePackage(e){let t=await this.db.query({TableName:this.tableName,KeyConditionExpression:"PK = :pk",ExpressionAttributeValues:{":pk":{S:`ZIG_PACKAGE#${e}`}}});for(let n of t.Items){let r=this.unmarshal(n);if(r.hash)await this.db.deleteItem({TableName:this.tableName,Key:{PK:{S:`ZIG_HASH#${r.hash}`},SK:{S:"ZIG_HASH"}}});if(r.version){let i=this.s3Key(e,r.version);try{await this.s3.deleteObject(this.bucket,i)}catch{}}await this.db.deleteItem({TableName:this.tableName,Key:{PK:{S:`ZIG_PACKAGE#${e}`},SK:n.SK}})}}}class k_ extends qu{s3;bucket;baseUrl;snapshot;loaded;constructor(e){super();this.s3=e.s3,this.bucket=e.bucket,this.baseUrl=e.baseUrl,this.snapshot=new Cr(this.s3,this.bucket,e.key||"zig-packages/registry-index.json",()=>this.captureState()),this.loaded=this.snapshot.load().then((t)=>{if(t)this.applyState(t)})}ready(){return this.loaded}onMutate(){this.snapshot.scheduleSave()}async flush(){await this.snapshot.flush()}async publish(e,t){Wn(e.malwareScan,t);let n=hg(e.name,e.version);await this.s3.putObject({bucket:this.bucket,key:n,body:Buffer.from(t),contentType:"application/gzip"});let r=e;if(!r.tarballUrl)r={...e,tarballUrl:`${this.baseUrl}/zig/packages/${encodeURIComponent(e.name)}/${e.version}/tarball`};this.upsertRecord(r),this.onMutate()}async downloadTarball(e,t){try{let n=await this.s3.getObjectBuffer(this.bucket,hg(e,t));return n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}catch{return null}}async deletePackage(e){let t=await this.listVersions(e);for(let n of t)try{await this.s3.deleteObject(this.bucket,hg(e,n))}catch{}await super.deletePackage(e)}}function Gu(){let e=process.env.S3_BUCKET,t=process.env.BASE_URL||"http://localhost:3000";if(!e||e==="local")return new qu;let n=ot(),r=process.env.DYNAMODB_TABLE;if(n.provider==="aws"&&r&&r!=="local")return new gg({tableName:r,bucket:e,region:n.region,baseUrl:t});return new k_({s3:et(n),bucket:e,baseUrl:t})}async function __(e,t,n,r,i,s,o,a){let l=e.replace(/^\/zig/,"");if(l==="/search"&&t.method==="GET"){let d=n.searchParams.get("q")||"";if(d.length>256)return Response.json({error:"Search query too long"},{status:400,headers:s});let h=Math.min(Number.parseInt(n.searchParams.get("limit")||"20",10),100),p=await r.search(d,h);return Response.json({results:p.map((m)=>({name:m.name,version:m.latest,description:m.description,keywords:m.keywords,author:m.author}))},{headers:s})}let c=l.match(/^\/hash\/([a-f0-9]+)$/i);if(c&&t.method==="GET"){let d=c[1],h=await r.getByHash(d);if(!h)return Response.json({error:"Package not found for this hash"},{status:404,headers:s});return Response.json({...h,hash:d,dependency:yo(h.name,h.tarballUrl,d)},{headers:s})}if(l==="/publish"&&t.method==="POST"){if(!a)throw Error("malware scanner is required for publishing");return BB(t,r,i,s,o,a)}let u=l.match(/^\/packages\/([^/]+)$/);if(u&&t.method==="DELETE"){let d=E_(t.headers.get("authorization"));if(!d.valid)return Response.json({error:d.error},{status:401,headers:s});let h=decodeURIComponent(u[1]);if(h.includes("..")||/[\x00-\x1f]/.test(h))return Response.json({error:"Invalid package name"},{status:400,headers:s});return await r.deletePackage(h),Response.json({success:!0,message:`Deleted ${h}`},{headers:s})}let f=l.match(/^\/packages\/([^/]+)(?:\/(.+))?$/);if(f){let d=decodeURIComponent(f[1]);if(d.includes("..")||/[\x00-\x1f]/.test(d))return Response.json({error:"Invalid package name"},{status:400,headers:s});let h=f[2];if(h==="versions"&&t.method==="GET"){let p=await r.listVersions(d);return Response.json({name:d,versions:p},{headers:s})}if(h?.endsWith("/tarball")&&t.method==="GET"){let p=h.replace("/tarball",""),m=await r.downloadTarball(d,p);if(!m)return Response.json({error:"Package not found"},{status:404,headers:s});return o?.trackDownload({packageName:d,version:p,timestamp:new Date().toISOString(),userAgent:t.headers.get("user-agent")||void 0}).catch((g)=>console.warn("Analytics tracking failed:",g)),new Response(m,{headers:{...s,"Content-Type":"application/gzip","Content-Disposition":`attachment; filename="${d}-${p}.tar.gz"`}})}if(h&&!h.includes("/")&&t.method==="GET"){let p=await r.getPackage(d,h);if(!p)return Response.json({error:"Package version not found"},{status:404,headers:s});return Response.json({...p,fetchCommand:Al(p.tarballUrl),dependency:yo(d,p.tarballUrl,p.hash)},{headers:s})}if(!h&&t.method==="GET"){let p=await r.getPackage(d);if(!p)return Response.json({error:"Package not found"},{status:404,headers:s});return Response.json({...p,fetchCommand:Al(p.tarballUrl),dependency:yo(d,p.tarballUrl,p.hash)},{headers:s})}}return null}function zB(){return process.env.PANTRY_REGISTRY_TOKEN||process.env.PANTRY_TOKEN}function E_(e){let t=zB();if(!t)return{valid:!1,error:"Server misconfigured \u2014 no registry token set"};if(!e)return{valid:!1,error:"Authorization required"};let n=e.startsWith("Bearer ")?e.slice(7):e,r=Math.max(n.length,t.length),i=Buffer.alloc(r),s=Buffer.alloc(r);if(Buffer.from(n).copy(i),Buffer.from(t).copy(s),!Q("crypto").timingSafeEqual(i,s)||n.length!==t.length)return{valid:!1,error:"Invalid token"};return{valid:!0}}async function BB(e,t,n,r,i,s){let o=e.headers.get("content-type")||"",a=e.headers.get("authorization"),l=E_(a);if(!l.valid)return Response.json({error:l.error},{status:401,headers:r});if(o.includes("multipart/form-data")){let c=await e.formData(),u=c.get("tarball"),f=c.get("manifest"),d=c.get("description");if(!u||!(u instanceof File))return Response.json({error:"Missing tarball"},{status:400,headers:r});if(u.size>52428800)return Response.json({error:"Tarball exceeds maximum size of 50MB"},{status:413,headers:r});let h=await u.arrayBuffer(),p=pg(h),m,g;if(f&&typeof f==="string"){let x=mg(f);m=x.name,g=x.version}else{let S=u.name.match(/^(.+)-(\d+\.\d+\.\d+)\.tar\.gz$/);if(!S)return Response.json({error:"Could not determine package name/version. Provide manifest or use name-version.tar.gz filename."},{status:400,headers:r});m=S[1],g=S[2]}if(m=m.replace(/_/g,"-"),await t.exists(m,g))return Response.json({error:"Version already exists"},{status:409,headers:r});if(!s)throw Error("malware scanner is required for publishing");let w=await Bn(s,h,{surface:"zig",name:m,version:g,publisher:"_admin"});if(w.verdict!=="clean")return Ii(w,r);let b=`${n}/zig/packages/${encodeURIComponent(m)}/${g}/tarball`,v={name:m,version:g,description:typeof d==="string"?d:void 0,tarballUrl:b,hash:p,publishedAt:new Date().toISOString(),malwareScan:w};return await t.publish(v,h),i?.trackEvent({packageName:m,category:"install_on_request",timestamp:new Date().toISOString(),version:g}).catch((x)=>console.warn("Analytics tracking failed:",x)),Response.json({success:!0,message:`Published ${m}@${g}`,hash:p,tarballUrl:b,fetchCommand:Al(b),dependency:yo(m,b,p),scan:pt(w)},{status:201,headers:r})}return Response.json({error:"Unsupported content type. Use multipart/form-data."},{status:415,headers:r})}import*as A_ from"crypto";function wg(e){let t=Buffer.isBuffer(e)?e:Buffer.from(e);return A_.createHash("sha256").update(t).digest("hex")}function bg(e){let t;try{t=JSON.parse(e)}catch{throw Error("Invalid composer.json: malformed JSON")}if(!t.name||typeof t.name!=="string"||!t.name.includes("/"))throw Error("Invalid composer.json: missing or invalid name (must be vendor/package format)");let n={name:t.name};if(t.version)n.version=t.version;if(t.description)n.description=t.description;if(t.license)n.license=t.license;if(t.type)n.type=t.type;if(t.keywords)n.keywords=t.keywords;if(t.authors)n.authors=t.authors;if(t.require)n.require=t.require;if(t["require-dev"])n["require-dev"]=t["require-dev"];if(t.autoload)n.autoload=t.autoload;if(t.homepage)n.homepage=t.homepage;if(t["minimum-stability"])n["minimum-stability"]=t["minimum-stability"];return n}function $l(e,t){let n=e.replace(/[^a-z0-9/_.-]/gi,""),r=t.replace(/[^a-z0-9._-]/gi,"");return`composer require '${n}:^${r}'`}class Xu{packages=new Map;tarballs=new Map;isNewerPhpVersion(e,t){let n=(s)=>{let o=s.indexOf("-"),a=(o===-1?s:s.slice(0,o)).replace(/^v/,"").split(".").map((c)=>Number.parseInt(c,10)||0),l=o===-1?null:s.slice(o+1);return{numeric:a,prerelease:l}},r=n(e),i=n(t);for(let s=0;s<Math.max(r.numeric.length,i.numeric.length);s++){let o=r.numeric[s]??0,a=i.numeric[s]??0;if(o!==a)return o>a}if(r.prerelease===null&&i.prerelease!==null)return!0;if(r.prerelease!==null&&i.prerelease===null)return!1;return!1}async count(){return this.packages.size}async getPackage(e,t){let n=this.packages.get(e);if(!n)return null;let r=t||n.latest;return n.versions[r]||null}async listVersions(e){let t=this.packages.get(e);if(!t)return[];return Object.keys(t.versions).sort((n,r)=>{let[i,s,o]=n.split(".").map(Number),[a,l,c]=r.split(".").map(Number);if(i!==a)return a-i;if(s!==l)return l-s;return c-o})}async search(e,t=20){let n=e.toLowerCase(),r=[];for(let i of this.packages.values())if(i.name.toLowerCase().includes(n)||i.description?.toLowerCase().includes(n)||i.keywords?.some((s)=>s.toLowerCase().includes(n))){if(r.push(i),r.length>=t)break}return r}async publish(e,t){Wn(e.malwareScan,t),this.upsertRecord(e),this.tarballs.set(`${e.name}@${e.version}`,t),this.onMutate()}upsertRecord(e){let{name:t,version:n}=e,r=this.packages.get(t);if(!r)r={name:t,description:e.description,license:e.license,type:e.type,keywords:e.keywords,authors:e.authors,homepage:e.homepage,repository:e.repository,versions:{},latest:n,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};if(r.versions[n]=e,!r.latest||this.isNewerPhpVersion(n,r.latest))r.latest=n;r.updatedAt=new Date().toISOString(),this.packages.set(t,r)}onMutate(){}captureState(){return{packages:Object.fromEntries(this.packages)}}applyState(e){if(e?.packages)this.packages=new Map(Object.entries(e.packages))}async exists(e,t){return this.packages.get(e)?.versions[t]!==void 0}async downloadTarball(e,t){let n=`${e}@${t}`;return this.tarballs.get(n)||null}async deletePackage(e){let t=this.packages.get(e);if(t){for(let n of Object.keys(t.versions)){let r=`${e}@${n}`;this.tarballs.delete(r)}this.packages.delete(e),this.onMutate()}}}function yg(e,t){let n=e.replaceAll("/","-").replaceAll("@","");return`php-packages/${n}/${t}/${n}-${t}.tar.gz`}class vg{tableName;db;s3;bucket;baseUrl;constructor(e){this.tableName=e.tableName,this.bucket=e.bucket,this.baseUrl=e.baseUrl,this.db=new V(e.region||"us-east-1"),this.s3=et(ot({region:e.region}))}marshal(e){return V.marshal(e)}unmarshal(e){return V.unmarshal(e)}s3Key(e,t){let n=e.replaceAll("/","-").replaceAll("@","");return`php-packages/${n}/${t}/${n}-${t}.tar.gz`}async count(){return(await this.db.scan({TableName:this.tableName,FilterExpression:"begins_with(PK, :prefix) AND SK = :sk",ExpressionAttributeValues:{":prefix":{S:"PHP_PACKAGE#"},":sk":{S:"METADATA"}},ProjectionExpression:"PK"})).Count||0}async getPackage(e,t){if(t){let i=await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`PHP_PACKAGE#${e}`},SK:{S:`VERSION#${t}`}}});if(!i.Item)return null;let s=this.unmarshal(i.Item);return{name:s.name,version:s.version,description:s.description,tarballUrl:s.tarballUrl,checksum:s.checksum,publishedAt:s.publishedAt,license:s.license,type:s.type,keywords:s.keywords,authors:s.authors,homepage:s.homepage,repository:s.repository,require:s.require,malwareScan:s.malwareScan}}let n=await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`PHP_PACKAGE#${e}`},SK:{S:"METADATA"}}});if(!n.Item)return null;let r=this.unmarshal(n.Item);if(!r.latest)return null;return this.getPackage(e,r.latest)}async listVersions(e){return(await this.db.query({TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :prefix)",ExpressionAttributeValues:{":pk":{S:`PHP_PACKAGE#${e}`},":prefix":{S:"VERSION#"}}})).Items.map((n)=>{return this.unmarshal(n).version}).sort((n,r)=>{let[i,s,o]=n.split(".").map(Number),[a,l,c]=r.split(".").map(Number);return a!==i?a-i:l!==s?l-s:c-o})}async search(e,t=20){let n=e.toLowerCase(),r=await this.db.scan({TableName:this.tableName,FilterExpression:"begins_with(PK, :prefix) AND SK = :sk",ExpressionAttributeValues:{":prefix":{S:"PHP_PACKAGE#"},":sk":{S:"METADATA"}}}),i=[];for(let s of r.Items){let o=this.unmarshal(s),a=[o.name,o.description,...o.keywords||[]].filter(Boolean).join(" ").toLowerCase();if(!n||a.includes(n)){let l=await this.listVersions(o.name),c={};for(let u of l.slice(0,10)){let f=await this.getPackage(o.name,u);if(f)c[u]=f}if(i.push({name:o.name,description:o.description,license:o.license,type:o.type,keywords:o.keywords,authors:o.authors,homepage:o.homepage,repository:o.repository,versions:c,latest:o.latest,createdAt:o.createdAt,updatedAt:o.updatedAt}),i.length>=t)break}}return i}async publish(e,t){Wn(e.malwareScan,t);let{name:n,version:r}=e,i=new Date().toISOString(),s=this.s3Key(n,r);await this.s3.putObject({bucket:this.bucket,key:s,body:Buffer.from(t),contentType:"application/gzip"});let o=n.split("/").map(encodeURIComponent).join("/"),a=e.tarballUrl||`${this.baseUrl}/php/packages/${o}/${r}/tarball`;await this.db.putItem({TableName:this.tableName,Item:this.marshal({PK:`PHP_PACKAGE#${n}`,SK:`VERSION#${r}`,name:n,version:r,tarballUrl:a,checksum:e.checksum,description:e.description||"",license:e.license||"",type:e.type||"",keywords:e.keywords||[],authors:e.authors||[],homepage:e.homepage||"",repository:e.repository||"",require:e.require||{},publishedAt:e.publishedAt||i,malwareScan:e.malwareScan})}),await this.db.putItem({TableName:this.tableName,Item:this.marshal({PK:`PHP_PACKAGE#${n}`,SK:"METADATA",name:n,latest:r,description:e.description||"",license:e.license||"",type:e.type||"",keywords:e.keywords||[],authors:e.authors||[],homepage:e.homepage||"",repository:e.repository||"",createdAt:i,updatedAt:i})})}async exists(e,t){return(await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`PHP_PACKAGE#${e}`},SK:{S:`VERSION#${t}`}}})).Item!==void 0}async downloadTarball(e,t){let n=this.s3Key(e,t);try{let r=await this.s3.getObjectBuffer(this.bucket,n);return r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)}catch{return null}}async deletePackage(e){let t=await this.db.query({TableName:this.tableName,KeyConditionExpression:"PK = :pk",ExpressionAttributeValues:{":pk":{S:`PHP_PACKAGE#${e}`}}});for(let n of t.Items){let r=this.unmarshal(n);if(r.version){let i=this.s3Key(e,r.version);try{await this.s3.deleteObject(this.bucket,i)}catch{}}await this.db.deleteItem({TableName:this.tableName,Key:{PK:{S:`PHP_PACKAGE#${e}`},SK:n.SK}})}}}class $_ extends Xu{s3;bucket;baseUrl;snapshot;loaded;constructor(e){super();this.s3=e.s3,this.bucket=e.bucket,this.baseUrl=e.baseUrl,this.snapshot=new Cr(this.s3,this.bucket,e.key||"php-packages/registry-index.json",()=>this.captureState()),this.loaded=this.snapshot.load().then((t)=>{if(t)this.applyState(t)})}ready(){return this.loaded}onMutate(){this.snapshot.scheduleSave()}async flush(){await this.snapshot.flush()}async publish(e,t){Wn(e.malwareScan,t);let n=yg(e.name,e.version);await this.s3.putObject({bucket:this.bucket,key:n,body:Buffer.from(t),contentType:"application/gzip"});let r=e;if(!r.tarballUrl){let i=e.name.split("/").map(encodeURIComponent).join("/");r={...e,tarballUrl:`${this.baseUrl}/php/packages/${i}/${e.version}/tarball`}}this.upsertRecord(r),this.onMutate()}async downloadTarball(e,t){try{let n=await this.s3.getObjectBuffer(this.bucket,yg(e,t));return n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}catch{return null}}async deletePackage(e){let t=await this.listVersions(e);for(let n of t)try{await this.s3.deleteObject(this.bucket,yg(e,n))}catch{}await super.deletePackage(e)}}function Vu(){let e=process.env.S3_BUCKET,t=process.env.BASE_URL||"http://localhost:3000";if(!e||e==="local")return new Xu;let n=ot(),r=process.env.DYNAMODB_TABLE;if(n.provider==="aws"&&r&&r!=="local")return new vg({tableName:r,bucket:e,region:n.region,baseUrl:t});return new $_({s3:et(n),bucket:e,baseUrl:t})}async function C_(e,t,n,r,i,s,o,a){let l=e.replace(/^\/php/,"");if(l==="/search"&&t.method==="GET"){let f=n.searchParams.get("q")||"",d=Math.min(Number.parseInt(n.searchParams.get("limit")||"20",10),100),h=await r.search(f,d);return Response.json({results:h.map((p)=>({name:p.name,version:p.latest,description:p.description,keywords:p.keywords,authors:p.authors,type:p.type}))},{headers:s})}if(l==="/publish"&&t.method==="POST"){if(!a)throw Error("malware scanner is required for publishing");return UB(t,r,i,s,o,a)}let c=l.match(/^\/packages\/([^/]+)\/([^/]+)$/);if(c&&t.method==="DELETE"){let f=T_(t.headers.get("authorization"));if(!f.valid)return Response.json({error:f.error},{status:401,headers:s});let d=`${decodeURIComponent(c[1])}/${decodeURIComponent(c[2])}`;return await r.deletePackage(d),Response.json({success:!0,message:`Deleted ${d}`},{headers:s})}let u=l.match(/^\/packages\/([^/]+)\/([^/]+)(?:\/(.+))?$/);if(u){let f=`${decodeURIComponent(u[1])}/${decodeURIComponent(u[2])}`,d=u[3];if(d==="versions"&&t.method==="GET"){let h=await r.listVersions(f);return Response.json({name:f,versions:h},{headers:s})}if(d?.endsWith("/tarball")&&t.method==="GET"){let h=d.replace("/tarball",""),p=await r.downloadTarball(f,h);if(!p)return Response.json({error:"Package not found"},{status:404,headers:s});return o?.trackDownload({packageName:f,version:h,timestamp:new Date().toISOString(),userAgent:t.headers.get("user-agent")||void 0}).catch((m)=>console.warn("Analytics tracking failed:",m)),new Response(p,{headers:{...s,"Content-Type":"application/gzip","Content-Disposition":`attachment; filename="${f.replace("/","-")}-${h}.tar.gz"`}})}if(d&&!d.includes("/")&&t.method==="GET"){let h=await r.getPackage(f,d);if(!h)return Response.json({error:"Package version not found"},{status:404,headers:s});return Response.json({...h,composerRequire:$l(f,h.version)},{headers:s})}if(!d&&t.method==="GET"){let h=await r.getPackage(f);if(!h)return Response.json({error:"Package not found"},{status:404,headers:s});return Response.json({...h,composerRequire:$l(f,h.version)},{headers:s})}}return null}function WB(){return process.env.PANTRY_REGISTRY_TOKEN||process.env.PANTRY_TOKEN}function T_(e){let t=WB();if(!t)return{valid:!1,error:"Server misconfigured \u2014 no registry token set"};if(!e)return{valid:!1,error:"Authorization required"};let n=e.startsWith("Bearer ")?e.slice(7):e,r=Q("crypto"),i=Math.max(n.length,t.length),s=Buffer.alloc(i),o=Buffer.alloc(i);if(Buffer.from(n).copy(s),Buffer.from(t).copy(o),!r.timingSafeEqual(s,o)||n.length!==t.length)return{valid:!1,error:"Invalid token"};return{valid:!0}}async function UB(e,t,n,r,i,s){let o=e.headers.get("content-type")||"",a=e.headers.get("authorization"),l=T_(a);if(!l.valid)return Response.json({error:l.error},{status:401,headers:r});if(o.includes("multipart/form-data")){let c=await e.formData(),u=c.get("tarball"),f=c.get("manifest"),d=c.get("description");if(!u||!(u instanceof File))return Response.json({error:"Missing tarball"},{status:400,headers:r});let h=await u.arrayBuffer(),p=wg(h),m,g,y,w,b,v,x;if(f&&typeof f==="string"){let E=bg(f);m=E.name,g=E.version||"",y=E.type,w=E.license,b=E.homepage,v=E.authors,x=E.keywords}else{let A=u.name.match(/^(.+)-(\d+\.\d+\.\d+)\.tar\.gz$/);if(!A)return Response.json({error:"Could not determine package name/version. Provide manifest or use vendor-package-version.tar.gz filename."},{status:400,headers:r});m=A[1].replace("-","/"),g=A[2]}if(await t.exists(m,g))return Response.json({error:"Version already exists"},{status:409,headers:r});if(!s)throw Error("malware scanner is required for publishing");let k=await Bn(s,h,{surface:"php",name:m,version:g,publisher:"_admin"});if(k.verdict!=="clean")return Ii(k,r);let C=m.split("/").map(encodeURIComponent).join("/"),T=`${n}/php/packages/${C}/${g}/tarball`,_={name:m,version:g,description:typeof d==="string"?d:void 0,type:y,license:w,homepage:b,authors:v,keywords:x,tarballUrl:T,checksum:p,publishedAt:new Date().toISOString(),malwareScan:k};return await t.publish(_,h),i?.trackEvent({packageName:m,category:"install_on_request",timestamp:new Date().toISOString(),version:g}).catch((E)=>console.warn("Analytics tracking failed:",E)),Response.json({success:!0,message:`Published ${m}@${g}`,checksum:p,tarballUrl:T,composerRequire:$l(m,g),scan:pt(k)},{status:201,headers:r})}return Response.json({error:"Unsupported content type. Use multipart/form-data."},{status:415,headers:r})}async function xg(e,t=20){try{let n=`https://packagist.org/search.json?q=${encodeURIComponent(e)}&per_page=${Math.min(t,30)}`,r=await fetch(n,{headers:{"User-Agent":"pantry-registry/1.0"}});if(!r.ok)return[];return((await r.json()).results||[]).slice(0,t).map((s)=>({name:s.name,description:s.description||"",url:s.url||"",repository:s.repository||"",downloads:s.downloads||0,favers:s.favers||0}))}catch{return[]}}async function Sg(e){try{if(!/^[a-z0-9]([a-z0-9._-]*[a-z0-9])?\/[a-z0-9]([a-z0-9._-]*[a-z0-9])?$/i.test(e))return null;let t=await fetch(`https://packagist.org/packages/${encodeURIComponent(e)}.json`,{headers:{"User-Agent":"pantry-registry/1.0"}});if(!t.ok)return null;let r=(await t.json()).package;if(!r)return null;let i=Object.keys(r.versions||{}),o=i.filter((l)=>!l.includes("dev")&&!l.includes("alpha")&&!l.includes("beta")&&!l.includes("RC")).sort((l,c)=>{let u=l.replace(/^v/,"").split(".").map(Number),f=c.replace(/^v/,"").split(".").map(Number);for(let d=0;d<Math.max(u.length,f.length);d++){let h=(f[d]??0)-(u[d]??0);if(h!==0)return h}return 0})[0]||i[0]||"",a=r.versions?.[o]||{};return{name:r.name,description:r.description||"",version:a.version_normalized||a.version||o.replace(/^v/,"")||"unknown",license:a.license||[],homepage:a.homepage||r.repository||"",repository:r.repository||"",downloads:r.downloads?.total||0,favers:r.favers||0,type:r.type||a.type||"library",versions:i.map((l)=>l.replace(/^v/,"")).filter((l)=>/^\d/.test(l)).slice(0,50),require:a.require||{}}}catch{return null}}var wo=null;async function kg(){if(wo&&Date.now()-wo.timestamp<3600000)return wo.count;try{let e=await fetch("https://packagist.org/statistics.json",{headers:{"User-Agent":"pantry-registry/1.0"}});if(!e.ok)return wo?.count||350000;let n=(await e.json()).totals?.packages||350000;return wo={count:n,timestamp:Date.now()},n}catch{return wo?.count||350000}}import{createHash as PB}from"crypto";import{execSync as M_}from"child_process";import{createReadStream as qB,createWriteStream as GB,existsSync as Eg,mkdirSync as XB,mkdtempSync as VB,readdirSync as YB,rmSync as JB,statSync as KB}from"fs";import{tmpdir as QB}from"os";import{join as $s}from"path";import{Readable as HB}from"stream";import{pipeline as ZB}from"stream/promises";class Yr{maxEntries;ttlMs;now;maxWeight;weightOf;entries=new Map;currentWeight=0;constructor(e,t,n=Date.now,r=Number.POSITIVE_INFINITY,i=()=>1){this.maxEntries=e;this.ttlMs=t;this.now=n;this.maxWeight=r;this.weightOf=i;if(!Number.isInteger(e)||e<1)throw RangeError("maxEntries must be a positive integer");if(!Number.isFinite(t)||t<1)throw RangeError("ttlMs must be a positive number");if(r<=0)throw RangeError("maxWeight must be a positive number")}get size(){return this.entries.size}get weight(){return this.currentWeight}get(e){let t=this.entries.get(e);if(!t)return;if(t.expiresAt<=this.now()){this.remove(e,t);return}return this.entries.delete(e),this.entries.set(e,t),t.value}set(e,t){let n=this.entries.get(e);if(n)this.remove(e,n);let r=Math.max(0,this.weightOf(t));if(!Number.isFinite(r)||r>this.maxWeight)return;this.entries.set(e,{value:t,expiresAt:this.now()+this.ttlMs,weight:r}),this.currentWeight+=r;while(this.entries.size>this.maxEntries||this.currentWeight>this.maxWeight){let i=this.entries.keys().next().value;if(i===void 0)break;let s=this.entries.get(i);if(s)this.remove(i,s)}}delete(e){let t=this.entries.get(e);if(!t)return!1;return this.remove(e,t),!0}clear(){this.entries.clear(),this.currentWeight=0}remove(e,t){this.entries.delete(e),this.currentWeight-=t.weight}}class _g{cache;inFlight=new Map;constructor(e,t,n=Date.now,r=Number.POSITIVE_INFINITY,i=()=>1){this.cache=new Yr(e,t,n,r,i)}get size(){return this.cache.size}async getOrCreate(e,t){let n=this.cache.get(e);if(n!==void 0)return n;let r=this.inFlight.get(e);if(r)return r;let i=t().then((s)=>{return this.cache.set(e,s),s}).finally(()=>{this.inFlight.delete(e)});return this.inFlight.set(e,i),i}clear(){this.cache.clear(),this.inFlight.clear()}}var O_=["darwin-arm64","darwin-x86-64","linux-x86-64","linux-arm64"],Cg=new Set(["php.net","postgresql.org"]);function eW(e){let t=e.indexOf("-"),n=t>0?e.slice(0,t):"",r=t>0?e.slice(t+1):"",i=r==="arm64"?"aarch64":r==="x86-64"?"x86-64":"";if(n!=="darwin"&&n!=="linux"||!i)return null;return{os:n,arch:i}}function N_(e,t,n){let r=eW(n);if(!r)return null;return`https://dist.pkgx.dev/${e}/${r.os}/${r.arch}/v${t}.tar.xz`}function R_(e,t,n){return`binaries/${e}/${t}/${n}/${e.replace(/\//g,"-")}-${t}.tar.gz`}function tW(e,t){let n=e.split(/[.+-]/),r=t.split(/[.+-]/);for(let i=0;i<Math.max(n.length,r.length);i++){let s=Number(n[i]),o=Number(r[i]);if(Number.isNaN(s)||Number.isNaN(o)){let a=(r[i]||"").localeCompare(n[i]||"");if(a!==0)return a}else if(s!==o)return o-s}return 0}var nW=21600000,j_=new Yr(20000,nW);async function rW(e,t,n){if(Cg.has(e))return!1;let r=N_(e,t,n);if(!r)return!1;let i=`${e}@${t}#${n}`,s=j_.get(i);if(s!==void 0)return s;let o=!1;try{o=(await fetch(r,{method:"HEAD",signal:AbortSignal.timeout(8000)})).ok}catch{o=!1}return j_.set(i,o),o}var Tg=new Set;function Mg(e,t,n){return`${e}@${t}#${n}`}function Yu(e,t,n){return Tg.has(Mg(e,t,n))}var iW=1800000,$g=new Yr(1000,iW),sW=20;async function Og(e,t,n){if(Cg.has(e))return t;let r=t?`${t.updatedAt||""}:${t.latestVersion||""}:${Object.keys(t.versions||{}).length}`:"unpublished",i=$g.get(e);if(i&&i.sourceFingerprint===r)return i.data;let s=t?{...t,versions:{...t.versions||{}}}:{name:e,latestVersion:"",versions:{},updatedAt:new Date().toISOString()};s.versions??={};let o=n.filter((a)=>a&&a!=="999.999.999"&&a!=="0.0.0").sort(tW).filter((a)=>{let l=s.versions[a]?.platforms;return!l||O_.some((c)=>!l[c])}).slice(0,sW);return await Promise.all(o.map(async(a)=>{let l=s.versions[a]?.platforms||{},c=O_.filter((d)=>!l[d]),f=(await Promise.all(c.map(async(d)=>({p:d,ok:await rW(e,a,d)})))).filter((d)=>d.ok);if(f.length===0)return;s.versions[a]??={platforms:{}},s.versions[a].platforms??={};for(let{p:d}of f)s.versions[a].platforms[d]={tarball:R_(e,a,d),sha256:"",size:0,uploadedAt:""},Tg.add(Mg(e,a,d))})),$g.set(e,{sourceFingerprint:r,data:s}),s}var Ag=new Map;async function oW(e){let t=PB("sha256");for await(let n of qB(e))t.update(n);return t.digest("hex")}async function L_(e,t,n,r){if(Cg.has(e))return null;let i=`${e}@${t}#${n}`,s=Ag.get(i);if(s)return s;let o=(async()=>{let a=N_(e,t,n);if(!a)return null;let l=e.replace(/\//g,"-"),c=R_(e,t,n),u=VB($s(QB(),`pkgx-${l}-`));try{let f=$s(u,"pkg.tar.xz");try{let b=await fetch(a,{signal:AbortSignal.timeout(120000)});if(!b.ok||!b.body)return null;await ZB(HB.fromWeb(b.body),GB(f))}catch{return null}let d=$s(u,"ex");XB(d,{recursive:!0}),M_(`tar -xJf "${f}" -C "${d}"`,{stdio:"pipe"});let h=$s(d,e,`v${t}`);if(!Eg(h)){let b=$s(d,e),v=Eg(b)?YB(b).filter((x)=>x.startsWith("v")):[];if(v.length===1)h=$s(b,v[0])}if(!Eg(h))return null;let p=$s(u,"out.tar.gz");M_(`tar -czf "${p}" -C "${h}" .`,{stdio:"pipe"});let m=KB(p).size,g=await oW(p),y=r.initiate({domain:e,version:t,platforms:[n],filename:`${l}-${t}.tar.gz`,size:m,sha256:g}),w=await fetch(y.uploadUrl,{method:"PUT",headers:{...y.uploadHeaders,"Content-Length":String(m)},body:Bun.file(p)});if(!w.ok)throw Error(`pkgx staged upload failed with HTTP ${w.status}`);return await r.complete(y.uploadId,"_pkgx","pkgx"),$g.delete(e),Tg.delete(Mg(e,t,n)),{tarballKey:c,sha256:g,size:m}}catch(f){return console.error(`pkgx materialize failed for ${i}:`,f.message),null}finally{try{JB(u,{recursive:!0,force:!0})}catch{}}})();Ag.set(i,o);try{return await o}finally{Ag.delete(i)}}var Hu=["darwin-arm64","darwin-x86-64","linux-x86-64","linux-arm64"],F_=new Set(Hu),Ju=400,Cl=2000,aW=400,Ku=500,lW=600000,I_=21600000,D_=50,z_=5000;class jg{s3;bucket;building=new Map;recent=[];queue=[];unavailable=new Map;snapshot;coverageSnapshot;coverage=new Map;coverageLastBuilt=new Map;coverageAt=0;coveragePromise=null;subscribers=new Set;knownVersions=new Map;supportedPlatforms=new Map;logs=new Map;constructor(e,t){this.s3=e;this.bucket=t;this.snapshot=new Cr(e,t,"build-status/status.json",()=>this.captureState()),this.coverageSnapshot=new Cr(e,t,"build-status/coverage.json",()=>this.captureCoverage())}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}emit(){if(this.subscribers.size===0)return;let e=this.getStatus();for(let t of this.subscribers)try{t(e)}catch{}}get subscriberCount(){return this.subscribers.size}setKnownPackages(e){this.knownVersions=e}setSupportedPlatforms(e){this.supportedPlatforms=e}getLogs(e){return[...this.logs.get(e)||[]]}recordLogs(e,t,n){if(!e||!n?.length)return;let r=this.touchLogBuf(e),i=Date.now();for(let s of n)r.push({ts:i,platform:t||"",state:"building",text:String(s).slice(0,Cl)});if(r.length>Ju)r.splice(0,r.length-Ju);for(let[,s]of this.building)if(s.domain===e&&(!t||!s.platform||s.platform===t))s.ts=i;this.evictOldLogDomains(),this.emit()}touchLogBuf(e){let t=this.logs.get(e);if(t)this.logs.delete(e);else t=[];return this.logs.set(e,t),t}appendLog(e,t){if(!t)return;let n=this.touchLogBuf(e.domain);if(n.push({ts:e.ts,platform:e.platform,state:e.state,text:t.slice(0,Cl)}),n.length>Ju)n.splice(0,n.length-Ju);this.evictOldLogDomains()}evictOldLogDomains(){while(this.logs.size>aW){let e=this.logs.keys().next().value;if(e===void 0)break;this.logs.delete(e)}}async load(){let[e,t]=await Promise.all([this.snapshot.load(),this.coverageSnapshot.load()]);if(e)this.building=new Map((e.building||[]).filter((n)=>bo(n?.domain)).map((n)=>[this.key(n),n])),this.recent=(e.recent||[]).filter((n)=>bo(n?.domain)).slice(0,Ku),this.queue=(e.queue||[]).filter((n)=>bo(n)),this.unavailable=new Map((e.unavailable||[]).filter((n)=>n&&bo(n.domain)&&n.version&&n.platform).map((n)=>[this.key(n),{domain:String(n.domain),version:String(n.version),platform:String(n.platform),reason:n.reason?String(n.reason).slice(0,Cl):void 0,lastSeen:Number(n.lastSeen)||Date.now()}])),this.capUnavailable();if(t)this.restoreCoverage(t);for(let n of this.recent)if(n.state==="built"&&n.version)this.mergeCoverage(n.domain,n.version,n.platform,new Date(n.ts).toISOString())}key(e){return`${e.domain}|${e.version}|${e.platform}`}captureState(){return{version:1,building:[...this.building.values()],recent:this.recent.slice(0,Ku),queue:this.queue,unavailable:[...this.unavailable.values()]}}captureCoverage(){return{version:1,at:this.coverageAt,packages:[...this.coverage].map(([e,t])=>[e,[...t].map(([n,r])=>[n,[...r]]),this.coverageLastBuilt.get(e)])}}restoreCoverage(e){if(e.version!==1||!Array.isArray(e.packages))return;let t=new Map,n=new Map;for(let[r,i,s]of e.packages){if(!bo(r)||!Array.isArray(i))continue;let o=new Map;for(let[a,l]of i)if(a&&Array.isArray(l))o.set(a,new Set(l.filter((c)=>F_.has(c))));if(o.size>0)t.set(r,o);if(s)n.set(r,s)}this.coverage=t,this.coverageLastBuilt=n,this.coverageAt=Math.min(Number(e.at)||0,Date.now())}mergeCoverage(e,t,n,r){let i=this.coverage.get(e);if(!i)i=new Map,this.coverage.set(e,i);let s=i.get(t);if(!s)s=new Set,i.set(t,s);s.add(n),this.coverageLastBuilt.set(e,r)}record(e){if(!e.domain||!e.platform||!e.state)return null;if(!bo(String(e.domain)))return null;let t={domain:String(e.domain),version:String(e.version||""),platform:String(e.platform),state:e.state,host:e.host?String(e.host).slice(0,64):void 0,ts:Date.now(),message:e.message?String(e.message).slice(0,Cl):void 0,error:e.error?String(e.error).slice(0,Cl):void 0,hostKind:e.hostKind?String(e.hostKind).slice(0,16):void 0,hostUrl:e.hostUrl?String(e.hostUrl).slice(0,300):void 0},n=this.key(t);if(t.state==="unavailable")return this.building.delete(n),this.recordUnavailable(t),this.appendLog(t,t.error||`${t.platform}: unavailable (no source upstream)`),this.snapshot.scheduleSave(),this.emit(),t;if(t.state==="building")this.building.set(n,t);else{if(this.building.delete(n),this.recent.unshift(t),this.recent.length>Ku)this.recent.length=Ku;if(t.state==="built"&&t.version)this.reconcileUnavailable(t.domain,t.version);if(t.state==="built"&&t.version)this.mergeCoverage(t.domain,t.version,t.platform,new Date().toISOString());this.coverageAt=0}return this.appendLog(t,t.error||t.message||`${t.platform}: ${t.state}`),this.snapshot.scheduleSave(),this.emit(),t}recordUnavailable(e){if(!e.version)return;let t=this.key(e);this.unavailable.set(t,{domain:e.domain,version:e.version,platform:e.platform,reason:e.error,lastSeen:e.ts}),this.capUnavailable()}reconcileUnavailable(e,t){let n=!1;for(let[r,i]of this.unavailable)if(i.domain===e&&i.version===t)this.unavailable.delete(r),n=!0;if(n)this.snapshot.scheduleSave()}capUnavailable(){let e=new Map;for(let t of this.unavailable.values()){let n=e.get(t.domain);if(!n)n=[],e.set(t.domain,n);n.push(t)}for(let[,t]of e){if(t.length<=D_)continue;t.sort((n,r)=>n.lastSeen-r.lastSeen);for(let n of t.slice(0,t.length-D_))this.unavailable.delete(this.key(n))}if(this.unavailable.size>z_){let t=[...this.unavailable.values()].sort((n,r)=>n.lastSeen-r.lastSeen);for(let n of t.slice(0,this.unavailable.size-z_))this.unavailable.delete(this.key(n))}}getUnavailableVersions(){return[...this.unavailable.values()].sort((e,t)=>t.lastSeen-e.lastSeen)}pruneStaleBuilding(){let e=Date.now()-lW,t=!1;for(let[n,r]of this.building)if(r.ts<e)this.building.delete(n),t=!0;if(t)this.snapshot.scheduleSave()}requestRebuild(e,t=!1){let n=String(e||"").trim();if(!n)return!1;let r=this.queue.indexOf(n);if(r!==-1){if(!t||r===0)return!1;return this.queue.splice(r,1),this.queue.unshift(n),this.snapshot.scheduleSave(),this.emit(),!0}if(t)this.queue.unshift(n);else this.queue.push(n);return this.snapshot.scheduleSave(),this.emit(),!0}getQueue(){return[...this.queue]}clearQueue(e){if(!e)this.queue=[];else{let t=new Set(e);this.queue=this.queue.filter((n)=>!t.has(n))}this.snapshot.scheduleSave(),this.emit()}getStatus(){return this.pruneStaleBuilding(),{building:[...this.building.values()].sort((e,t)=>t.ts-e.ts),recent:this.recent.slice(0,100),queue:[...this.queue]}}parseKey(e){let t=e.split("/");if(t.length<5||t[0]!=="binaries")return null;let n=t[t.length-2];if(!F_.has(n))return null;let r=t[t.length-3],i=t.slice(1,t.length-3).join("/");if(!i||!r)return null;return{domain:i,version:r,platform:n}}async refreshCoverage(e=!1){if(!e&&Date.now()-this.coverageAt<I_)return;if(this.coveragePromise)return this.coveragePromise;return this.coveragePromise=(async()=>{let t=await this.s3.list({bucket:this.bucket,prefix:"binaries/",maxKeys:1e6}),n=new Map,r=new Map;for(let i of t){let s=this.parseKey(i.Key);if(!s)continue;let{domain:o,version:a,platform:l}=s,c=n.get(o);if(!c)c=new Map,n.set(o,c);let u=c.get(a);if(!u)u=new Set,c.set(a,u);if(u.add(l),i.LastModified&&(!r.has(o)||i.LastModified>r.get(o)))r.set(o,i.LastModified)}if(this.coverage.size>=50&&n.size<this.coverage.size*0.5){this.coverageAt=Date.now();return}this.coverage=n,this.coverageLastBuilt=r,this.coverageAt=Date.now(),await this.coverageSnapshot.flush()})().finally(()=>{this.coveragePromise=null}),this.coveragePromise}latestVersion(e){let t=null;for(let n of e.keys())if(t===null||Qu(n,t)>0)t=n;return t}async getPackages(){if(this.coverage.size===0)await this.refreshCoverage(!0);else if(Date.now()-this.coverageAt>I_)this.refreshCoverage();this.pruneStaleBuilding();let e=new Map;for(let a of this.building.values()){let l=e.get(a.domain);if(!l)l=new Set,e.set(a.domain,l);l.add(a.platform)}let t=new Map,n=new Map;for(let a of this.recent)if(!t.has(a.domain)){t.set(a.domain,a.state);let l=a.error||a.message;if(l)n.set(a.domain,l)}for(let a of this.building.values())if(a.message)n.set(a.domain,a.message);let r=new Set([...this.coverage.keys(),...e.keys(),...t.keys(),...this.knownVersions.keys()]),i=[];for(let a of r){let l=this.coverage.get(a),c=!!l&&l.size>0,u=l?this.latestVersion(l):(this.knownVersions.get(a)||[]).reduce((p,m)=>p===null||Qu(m,p)>0?m:p,null),f=u&&l?l.get(u)??new Set:new Set,d={};for(let p of Hu)d[p]=f.has(p);let h=(this.knownVersions.get(a)||[]).reduce((p,m)=>p===null||Qu(m,p)>0?m:p,null);i.push({domain:a,latestVersion:u,platforms:d,lastBuilt:this.coverageLastBuilt.get(a)||null,building:[...e.get(a)||[]],lastState:t.get(a),published:c,lastMessage:n.get(a),supportedPlatforms:this.supportedPlatforms.get(a)||[...Hu],newestVersion:h??u,hasUpdate:c&&!!h&&!!u&&Qu(h,u)>0})}i.sort((a,l)=>a.domain.localeCompare(l.domain));let s=0,o=0;for(let[a,l]of this.coverage){let c=this.supportedPlatforms.get(a)||[...Hu];for(let u of l.values()){if(u.size===0)continue;if(o+=u.size,c.length>0&&c.every((f)=>u.has(f)))s++}}return{packages:i,generatedAt:new Date().toISOString(),totals:{publishedVersions:s,publishedArtifacts:o}}}async flush(){await this.snapshot.flush()}}function bo(e){if(typeof e!=="string")return!1;let t=e.trim();if(t.length===0||t.length>200)return!1;return/^[a-z0-9][a-z0-9.+-]*\.[a-z0-9][\w.+/-]*$/i.test(t)}function Qu(e,t){let n=e.replace(/^v/,"").split(/[.\-+]/),r=t.replace(/^v/,"").split(/[.\-+]/),i=Math.max(n.length,r.length);for(let s=0;s<i;s++){let o=Number.parseInt(n[s]??"0",10),a=Number.parseInt(r[s]??"0",10);if(Number.isNaN(o)||Number.isNaN(a)){let l=(n[s]??"").localeCompare(r[s]??"");if(l!==0)return l}else if(o!==a)return o-a}return 0}var Tl={free:{id:"free",name:"Free",price:0,commissionBps:1000,analyticsRetentionDays:30,maxArtifactBytes:52428800,privatePackages:!1,priorityBuilds:!1,seats:1,buildInsurance:!1,securityAlerts:!1,sbomExport:!1,teamEntitlements:!1},pro:{id:"pro",name:"Pro",price:900,commissionBps:500,analyticsRetentionDays:3650,maxArtifactBytes:262144000,privatePackages:!0,priorityBuilds:!0,seats:1,buildInsurance:!0,securityAlerts:!0,sbomExport:!0,teamEntitlements:!1,stripeLookupKey:"pantry_pro_monthly"},team:{id:"team",name:"Team",price:2900,commissionBps:500,analyticsRetentionDays:3650,maxArtifactBytes:1073741824,privatePackages:!0,priorityBuilds:!0,seats:10,buildInsurance:!0,securityAlerts:!0,sbomExport:!0,teamEntitlements:!0,stripeLookupKey:"pantry_team_monthly"}},Zu=300;function Ml(e){if(e==="pro"||e==="team")return e;return"free"}function tr(e){return Tl[e]}function B_(e,t=new Date){if(!e||e.tier==="free")return"free";switch(e.status){case"active":case"trialing":case"past_due":return e.tier;case"canceled":return e.currentPeriodEnd&&new Date(e.currentPeriodEnd)>t?e.tier:"free";default:return"free"}}function W_(e){let t=tr(e.sellerTier).commissionBps,n=e.discoveredOnSite?300:0,r=Math.min(t+n,3000),i=Math.max(0,Math.min(Math.floor(e.amount*r/1e4),e.amount));return{amount:e.amount,commissionBps:t,discoveryBps:n,totalBps:r,applicationFee:i,sellerNet:e.amount-i}}function Di(e){let t=e/100;return`${Number.isInteger(t)?t:t.toFixed(2)}%`}function U_(e){return e==="site"}function q_(){return process.env.STRIPE_SECRET_KEY||""}function G_(){return process.env.STRIPE_WEBHOOK_SECRET||""}function nr(){return q_().length>0}function Fg(e,t=""){let n=[];for(let[r,i]of Object.entries(e)){if(i===void 0||i===null)continue;let s=t?`${t}[${r}]`:r;if(Array.isArray(i))i.forEach((o,a)=>{if(o!==null&&typeof o==="object")n.push(...Fg(o,`${s}[${a}]`));else n.push([`${s}[${a}]`,String(o)])});else if(typeof i==="object")n.push(...Fg(i,s));else n.push([s,String(i)])}return n}async function zi(e,t,n){let r=q_();if(!r)throw Error("STRIPE_SECRET_KEY not configured");let i=`https://api.stripe.com/v1${t}`,s={Authorization:`Bearer ${r}`},o;if(n)s["Content-Type"]="application/x-www-form-urlencoded",o=new URLSearchParams(Fg(n)).toString();let a=await fetch(i,{method:e,headers:s,body:o});if(!a.ok){let l=await a.text();throw console.error(`Stripe ${e} ${t} failed (${a.status}):`,l),Error(`Payment service error (${a.status})`)}return a.json()}function Ig(e){return`user:${e.toLowerCase().trim()}`}async function Dg(e,t,n,r,i){let s=await e.getPaywall(t);if(!s||!s.enabled)return{allowed:!0,reason:"no-paywall"};if(s.freeVersions?.includes(n))return{allowed:!0,paywall:s,reason:"free-version"};if(r.admin)return{allowed:!0,paywall:s,reason:"admin"};let o=r.userId?.toLowerCase().trim(),a=i?.toLowerCase().trim();if(a&&(o===a||r.org?.toLowerCase().trim()===a))return{allowed:!0,paywall:s,reason:"owner"};for(let l of[o,r.org?.toLowerCase().trim()]){if(!l)continue;let c=await e.getAccessGrant(t,Ig(l));if(c){if(c.expiresAt&&new Date(c.expiresAt)<new Date)return{allowed:!1,paywall:s,reason:"expired"};return{allowed:!0,paywall:s,reason:l===o?"entitled":"team-entitled"}}}if(r.token){if(await e.getAccessGrant(t,r.token))return{allowed:!0,paywall:s,reason:"entitled"}}return{allowed:!1,paywall:s,reason:o||r.token?"payment-required":"unauthenticated"}}async function cW(e,t,n,r){let i=await Dg(e,t,n,{token:r});return{allowed:i.allowed,paywall:i.paywall,reason:i.allowed?void 0:i.reason==="unauthenticated"?"Authentication required for paid package":"Payment required"}}async function ef(e,t,n,r){for(let i of[n,r]){if(!i)continue;let s=await e.getAccessGrant(t,Ig(i));if(!s)continue;if(s.expiresAt&&new Date(s.expiresAt)<new Date)continue;return!0}return!1}var P_=new Set(["usd","eur","gbp","cad","aud","chf","jpy","sek","nok","dkk"]),Ng=100,Rg=1e7;function tf(e){if(typeof e.price!=="number"||!Number.isInteger(e.price))return"Price must be a whole number of cents (e.g. 900 for $9.00)";if(e.price<Ng)return`Price must be at least ${Ng} cents ($${(Ng/100).toFixed(2)})`;if(e.price>Rg)return`Price must be at most ${Rg} cents ($${(Rg/100).toFixed(2)})`;let t=(e.currency||"usd").toLowerCase();if(!P_.has(t))return`Unsupported currency "${t}" \u2014 one of: ${[...P_].join(", ")}`;if(e.freeVersions&&!Array.isArray(e.freeVersions))return"freeVersions must be an array of version strings";if(e.freeVersions?.some((n)=>typeof n!=="string"||n.length>64))return"freeVersions must be version strings";if(e.payoutAccountId&&!/^acct_[A-Za-z0-9]+$/.test(e.payoutAccountId))return"payoutAccountId must be a Stripe Connect account id (acct_\u2026)";if(e.trialDays!==void 0&&(!Number.isInteger(e.trialDays)||e.trialDays<0||e.trialDays>365))return"trialDays must be a whole number of days between 0 and 365";return null}async function nf(e,t,n){let r=tf(n);if(r)throw Error(r);let i=new Date().toISOString(),s=await e.getPaywall(t),o=(n.currency||s?.currency||"usd").toLowerCase(),a=s?.stripeProductId,l=s?.stripePriceId;if(nr()){if(!a)a=(await zi("POST","/products",{name:t,description:`Access to ${t} on the pantry registry`,metadata:{pantry_package:t}})).id;if(!l||s?.price!==n.price||s?.currency?.toLowerCase()!==o)l=(await zi("POST","/prices",{product:a,unit_amount:String(n.price),currency:o})).id}let c={name:t,enabled:!0,price:n.price,currency:o,stripeProductId:a,stripePriceId:l,stripeAccountId:n.payoutAccountId??s?.stripeAccountId,freeVersions:n.freeVersions??s?.freeVersions,trialDays:n.trialDays??s?.trialDays,createdAt:s?.createdAt||i,updatedAt:i};return await e.putPaywall(c),c}async function rf(e,t){let{packageName:n,email:r,baseUrl:i}=t,s=await e.getPaywall(n);if(!s||!s.enabled)throw Error("This package is not for sale");if(!nr())throw Error("Payments are not configured on this registry");if(!s.stripePriceId)throw Error("This package has a price but no Stripe price \u2014 the publisher should save it again");let o=encodeURIComponent(n),a=t.origin||"cli",l=W_({amount:s.price,sellerTier:t.sellerTier||"free",discoveredOnSite:U_(a)});return{url:(await zi("POST","/checkout/sessions",{mode:"payment","line_items[0][price]":s.stripePriceId,"line_items[0][quantity]":"1",customer_email:r,client_reference_id:`${n}:${r}`,success_url:`${i}/packages/${o}/checkout/success`,cancel_url:`${i}/pkg/${o}`,"metadata[package_name]":n,"metadata[buyer_email]":(t.org||r).toLowerCase().trim(),"metadata[purchased_by]":r,"metadata[sale_origin]":a,"metadata[fee_bps]":String(l.totalBps),"metadata[seller_tier]":t.sellerTier||"free",...s.stripeAccountId?{"payment_intent_data[transfer_data][destination]":s.stripeAccountId,"payment_intent_data[on_behalf_of]":s.stripeAccountId,...l.applicationFee>0?{"payment_intent_data[application_fee_amount]":String(l.applicationFee)}:{}}:{}})).url}}var Lg=new Map;async function uW(e){if(!e.stripeLookupKey)throw Error(`${e.name} is not a paid tier`);let t=Lg.get(e.stripeLookupKey);if(t)return t;let n=await zi("GET",`/prices?lookup_keys[]=${encodeURIComponent(e.stripeLookupKey)}&active=true&limit=1`);if(n?.data?.length>0)return Lg.set(e.stripeLookupKey,n.data[0].id),n.data[0].id;let r=await zi("POST","/products",{name:`pantry ${e.name}`,description:`pantry registry ${e.name} plan`,metadata:{pantry_tier:e.id}}),i=await zi("POST","/prices",{product:r.id,unit_amount:String(e.price),currency:"usd",recurring:{interval:"month"},lookup_key:e.stripeLookupKey});return Lg.set(e.stripeLookupKey,i.id),i.id}async function X_(e){if(!nr())throw Error("Payments are not configured on this registry");if(!e.tier.stripeLookupKey)throw Error("The free plan does not need a subscription");let t=await uW(e.tier);return{url:(await zi("POST","/checkout/sessions",{mode:"subscription","line_items[0][price]":t,"line_items[0][quantity]":"1",...e.stripeCustomerId?{customer:e.stripeCustomerId}:{customer_email:e.email},success_url:`${e.baseUrl}/account?subscribed=${e.tier.id}`,cancel_url:`${e.baseUrl}/pricing`,"metadata[pantry_tier]":e.tier.id,"metadata[account_email]":e.email,"subscription_data[metadata][pantry_tier]":e.tier.id,"subscription_data[metadata][account_email]":e.email})).url}}async function V_(e,t){if(!nr())throw Error("Payments are not configured on this registry");return{url:(await zi("POST","/billing_portal/sessions",{customer:e,return_url:t})).url}}function fW(e){let t=e?.metadata?.account_email,n=e?.metadata?.pantry_tier;if(!t||!n)return null;return{email:t,tier:n,status:e.cancel_at_period_end&&e.status==="active"?"canceled":e.status||"none",stripeCustomerId:typeof e.customer==="string"?e.customer:e.customer?.id,stripeSubscriptionId:e.id,currentPeriodEnd:e.current_period_end?new Date(e.current_period_end*1000).toISOString():void 0}}var Ol=new Map,dW=600000;async function zg(e,t,n,r){if(!G_())throw Error("STRIPE_WEBHOOK_SECRET not configured");let i=await hW(t,n);if(i.id){if(Ol.has(i.id))return{processed:!0};if(Ol.set(i.id,Date.now()),Ol.size>100){let s=Date.now();for(let[o,a]of Ol)if(s-a>dW)Ol.delete(o)}}if(i.type?.startsWith("customer.subscription.")&&r){let s=fW(i.data.object);if(s){let o=i.type==="customer.subscription.deleted"?{...s,status:"canceled"}:s;return await r(o),{processed:!0,subscription:`${o.email}:${o.tier}:${o.status}`}}return{processed:!1}}if(i.type==="checkout.session.completed"){let s=i.data.object;if(s.mode==="subscription"&&r){let u=s.metadata?.account_email,f=s.metadata?.pantry_tier;if(u&&f)return await r({email:u,tier:f,status:"active",stripeCustomerId:typeof s.customer==="string"?s.customer:s.customer?.id,stripeSubscriptionId:typeof s.subscription==="string"?s.subscription:s.subscription?.id}),{processed:!0,subscription:`${u}:${f}:active`};return{processed:!1}}let o=s.metadata?.package_name,a=s.metadata?.buyer_email,l=!s.payment_status||s.payment_status==="paid"||s.payment_status==="no_payment_required";if(o&&a&&l){let u={packageName:o,token:Ig(a),stripePaymentId:s.payment_intent||s.id,grantedAt:new Date().toISOString()};return await e.putAccessGrant(u),{processed:!0,granted:a}}let c=s.metadata?.access_token;if(o&&c&&l)return await e.putAccessGrant({packageName:o,token:c,stripePaymentId:s.payment_intent||s.id,grantedAt:new Date().toISOString()}),{processed:!0}}return{processed:!1}}async function hW(e,t){let n=t.split(",").reduce((d,h)=>{let[p,m]=h.split("=");return d[p]=m,d},{}),r=n.t,i=n.v1;if(!r||!i)throw Error("Invalid Stripe signature format");let s=`${r}.${e}`,o=await crypto.subtle.importKey("raw",new TextEncoder().encode(G_()),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await crypto.subtle.sign("HMAC",o,new TextEncoder().encode(s)),l=Array.from(new Uint8Array(a)).map((d)=>d.toString(16).padStart(2,"0")).join(""),c=Buffer.from(l),u=Buffer.from(i);if(c.length!==u.length||!crypto.timingSafeEqual(c,u))throw Error("Stripe webhook signature verification failed");if(Math.abs(Date.now()/1000-Number(r))>300)throw Error("Stripe webhook timestamp too old");try{return JSON.parse(e)}catch{throw Error("Invalid webhook body JSON")}}var pW={usd:"$",eur:"\u20AC",gbp:"\xA3",cad:"CA$",aud:"A$",jpy:"\xA5"},mW=new Set(["jpy"]);function Bi(e,t){let n=(t||"usd").toLowerCase(),r=pW[n]||`${n.toUpperCase()} `;if(mW.has(n))return`${r}${e}`;return`${r}${(e/100).toFixed(2)}`}function cf(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function gW(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function OE(e){let t,n,r;if(e.length!==2)t=cf,n=(a,l)=>cf(e(a),l),r=(a,l)=>e(a)-l;else t=e===cf||e===gW?e:yW,n=e,r=e;function i(a,l,c=0,u=a.length){if(c<u){if(t(l,l)!==0)return u;do{let f=c+u>>>1;if(n(a[f],l)<0)c=f+1;else u=f}while(c<u)}return c}function s(a,l,c=0,u=a.length){if(c<u){if(t(l,l)!==0)return u;do{let f=c+u>>>1;if(n(a[f],l)<=0)c=f+1;else u=f}while(c<u)}return c}function o(a,l,c=0,u=a.length){let f=i(a,l,c,u-1);return f>c&&r(a[f-1],l)>-r(a[f],l)?f-1:f}return{left:i,center:o,right:s}}function yW(){return 0}function wW(e){return e===null?NaN:+e}var jE=OE(cf),bW=jE.right,Eye=jE.left,Aye=OE(wW).center,vW=bW,$ye=NE(RE),Cye=NE(xW);function NE(e){return function(t,n,r=n){if(!((n=+n)>=0))throw RangeError("invalid rx");if(!((r=+r)>=0))throw RangeError("invalid ry");let{data:i,width:s,height:o}=t;if(!((s=Math.floor(s))>=0))throw RangeError("invalid width");if(!((o=Math.floor(o!==void 0?o:i.length/s))>=0))throw RangeError("invalid height");if(!s||!o||!n&&!r)return t;let a=n&&e(n),l=r&&e(r),c=i.slice();if(a&&l)vo(a,c,i,s,o),vo(a,i,c,s,o),vo(a,c,i,s,o),xo(l,i,c,s,o),xo(l,c,i,s,o),xo(l,i,c,s,o);else if(a)vo(a,i,c,s,o),vo(a,c,i,s,o),vo(a,i,c,s,o);else if(l)xo(l,i,c,s,o),xo(l,c,i,s,o),xo(l,i,c,s,o);return t}}function vo(e,t,n,r,i){for(let s=0,o=r*i;s<o;)e(t,n,s,s+=r,1)}function xo(e,t,n,r,i){for(let s=0,o=r*i;s<r;++s)e(t,n,s,s+o,r)}function xW(e){let t=RE(e);return(n,r,i,s,o)=>{i<<=2,s<<=2,o<<=2,t(n,r,i+0,s+0,o),t(n,r,i+1,s+1,o),t(n,r,i+2,s+2,o),t(n,r,i+3,s+3,o)}}function RE(e){let t=Math.floor(e);if(t===e)return SW(e);let n=e-t,r=2*e+1;return(i,s,o,a,l)=>{if(!((a-=l)>=o))return;let c=t*s[o],u=l*t,f=u+l;for(let d=o,h=o+u;d<h;d+=l)c+=s[Math.min(a,d)];for(let d=o,h=a;d<=h;d+=l)c+=s[Math.min(a,d+u)],i[d]=(c+n*(s[Math.max(o,d-f)]+s[Math.min(a,d+f)]))/r,c-=s[Math.max(o,d-u)]}}function SW(e){let t=2*e+1;return(n,r,i,s,o)=>{if(!((s-=o)>=i))return;let a=e*r[i],l=o*e;for(let c=i,u=i+l;c<u;c+=o)a+=r[Math.min(s,c)];for(let c=i,u=s;c<=u;c+=o)a+=r[Math.min(s,c+l)],n[c]=a/t,a-=r[Math.max(i,c-l)]}}var LE=Array.prototype,Tye=LE.slice,Mye=LE.map,kW=Math.sqrt(50),_W=Math.sqrt(10),EW=Math.sqrt(2);function df(e,t,n){let r=(t-e)/Math.max(0,n),i=Math.floor(Math.log10(r)),s=r/Math.pow(10,i),o=s>=kW?10:s>=_W?5:s>=EW?2:1,a,l,c;if(i<0){if(c=Math.pow(10,-i)/o,a=Math.round(e*c),l=Math.round(t*c),a/c<e)++a;if(l/c>t)--l;c=-c}else{if(c=Math.pow(10,i)*o,a=Math.round(e/c),l=Math.round(t/c),a*c<e)++a;if(l*c>t)--l}if(l<a&&0.5<=n&&n<2)return df(e,t,n*2);return[a,l,c]}function AW(e,t,n){if(t=+t,e=+e,n=+n,!(n>0))return[];if(e===t)return[e];let r=t<e,[i,s,o]=r?df(t,e,n):df(e,t,n);if(!(s>=i))return[];let a=s-i+1,l=Array(a);if(r)if(o<0)for(let c=0;c<a;++c)l[c]=(s-c)/-o;else for(let c=0;c<a;++c)l[c]=(s-c)*o;else if(o<0)for(let c=0;c<a;++c)l[c]=(i+c)/-o;else for(let c=0;c<a;++c)l[c]=(i+c)*o;return l}function e0(e,t,n){return t=+t,e=+e,n=+n,df(e,t,n)[2]}function $W(e,t,n){t=+t,e=+e,n=+n;let r=t<e,i=r?e0(t,e,n):e0(e,t,n);return(r?-1:1)*(i<0?1/-i:i)}function CW(e){return function(t,n=0,r=t.length){let i=r-(n=+n);while(i){let s=e()*i--|0,o=t[i+n];t[i+n]=t[s+n],t[s+n]=o}return t}}var Oye=CW(Math.random);function FE(e,t){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(t).domain(e);break}return this}var jye=Symbol("implicit");var Y_=0.7,J_=1.4285714285714286,TW=/^#([0-9a-f]{3,8})$/,MW=new RegExp("^rgb\\(\\s*([+-]?\\d+)\\s*,\\s*([+-]?\\d+)\\s*,\\s*([+-]?\\d+)\\s*\\)$"),OW=new RegExp("^rgb\\(\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*\\)$"),jW=new RegExp("^rgba\\(\\s*([+-]?\\d+)\\s*,\\s*([+-]?\\d+)\\s*,\\s*([+-]?\\d+)\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*\\)$"),NW=new RegExp("^rgba\\(\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*\\)$"),RW=new RegExp("^hsl\\(\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*\\)$"),LW=new RegExp("^hsla\\(\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*\\)$"),K_={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};function hf(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Ts(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Cs(e){return e=Ts(e),(e<16?"0":"")+e.toString(16)}function Q_(e){return e=(e||0)%360,e<0?e+360:e}function sf(e){return Math.max(0,Math.min(1,e||0))}function Bg(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}class or{opacity;copy(e){return Object.assign(Object.create(Object.getPrototypeOf(this)),this,e)}displayable(){return this.rgb().displayable()}formatHex(){return this.rgb().formatHex()}formatHex8(){return this.rgb().formatHex8()}formatHsl(){return IE(this).formatHsl()}formatRgb(){return this.rgb().formatRgb()}toString(){return this.rgb().formatRgb()}rgb(){return this.rgb()}hex(){return this.formatHex()}}or.prototype.hex=or.prototype.formatHex;class dt extends or{r;g;b;constructor(e,t,n,r){super();this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}brighter(e){return e=e==null?1.4285714285714286:Math.pow(1.4285714285714286,e),new dt(this.r*e,this.g*e,this.b*e,this.opacity)}darker(e){return e=e==null?0.7:Math.pow(0.7,e),new dt(this.r*e,this.g*e,this.b*e,this.opacity)}rgb(){return this}clamp(){return new dt(Ts(this.r),Ts(this.g),Ts(this.b),hf(this.opacity))}displayable(){return-0.5<=this.r&&this.r<255.5&&(-0.5<=this.g&&this.g<255.5)&&(-0.5<=this.b&&this.b<255.5)&&(0<=this.opacity&&this.opacity<=1)}formatHex(){return`#${Cs(this.r)}${Cs(this.g)}${Cs(this.b)}`}hex(){return this.formatHex()}formatHex8(){return`#${Cs(this.r)}${Cs(this.g)}${Cs(this.b)}${Cs((isNaN(this.opacity)?1:this.opacity)*255)}`}formatRgb(){let e=hf(this.opacity);return`${e===1?"rgb(":"rgba("}${Ts(this.r)}, ${Ts(this.g)}, ${Ts(this.b)}${e===1?")":`, ${e})`}`}toString(){return this.formatRgb()}}dt.prototype.hex=dt.prototype.formatHex;class rr extends or{h;s;l;constructor(e,t,n,r){super();this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}brighter(e){return e=e==null?1.4285714285714286:Math.pow(1.4285714285714286,e),new rr(this.h,this.s,this.l*e,this.opacity)}darker(e){return e=e==null?0.7:Math.pow(0.7,e),new rr(this.h,this.s,this.l*e,this.opacity)}rgb(){let e=this.h%360+(this.h<0?360:0),t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<0.5?n:1-n)*t,i=2*n-r;return new dt(Bg(e>=240?e-240:e+120,i,r),Bg(e,i,r),Bg(e<120?e+240:e-120,i,r),this.opacity)}clamp(){return new rr(Q_(this.h),sf(this.s),sf(this.l),hf(this.opacity))}displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&(0<=this.l&&this.l<=1)&&(0<=this.opacity&&this.opacity<=1)}formatHsl(){let e=hf(this.opacity);return`${e===1?"hsl(":"hsla("}${Q_(this.h)}, ${sf(this.s)*100}%, ${sf(this.l)*100}%${e===1?")":`, ${e})`}`}}function H_(e){return new dt(e>>16&255,e>>8&255,e&255,1)}function of(e,t,n,r){if(r<=0)e=t=n=NaN;return new dt(e,t,n,r)}function Z_(e,t,n,r){if(r<=0)e=t=n=NaN;else if(n<=0||n>=1)e=t=NaN;else if(t<=0)e=NaN;return new rr(e,t,n,r)}function o0(e){let t;if(e=`${e}`.trim().toLowerCase(),t=TW.exec(e)){let n=t[1].length,r=parseInt(t[1],16);if(n===6)return H_(r);if(n===3)return new dt(r>>8&15|r>>4&240,r>>4&15|r&240,(r&15)<<4|r&15,1);if(n===8)return of(r>>24&255,r>>16&255,r>>8&255,(r&255)/255);if(n===4)return of(r>>12&15|r>>8&240,r>>8&15|r>>4&240,r>>4&15|r&240,((r&15)<<4|r&15)/255);return null}if(t=MW.exec(e))return new dt(+t[1],+t[2],+t[3],1);if(t=OW.exec(e))return new dt(+t[1]*255/100,+t[2]*255/100,+t[3]*255/100,1);if(t=jW.exec(e))return of(+t[1],+t[2],+t[3],+t[4]);if(t=NW.exec(e))return of(+t[1]*255/100,+t[2]*255/100,+t[3]*255/100,+t[4]);if(t=RW.exec(e))return Z_(+t[1],+t[2]/100,+t[3]/100,1);if(t=LW.exec(e))return Z_(+t[1],+t[2]/100,+t[3]/100,+t[4]);if(Object.prototype.hasOwnProperty.call(K_,e))return H_(K_[e]);if(e==="transparent")return new dt(NaN,NaN,NaN,0);return null}function a0(e){if(!(e instanceof or))e=o0(e);if(!e)return new dt(NaN,NaN,NaN,NaN);let t=e.rgb();return new dt(t.r,t.g,t.b,t.opacity)}function t0(e,t,n,r){if(t===void 0&&n===void 0)return a0(e);return new dt(e,t,n,r==null?1:r)}function IE(e){if(e instanceof rr)return new rr(e.h,e.s,e.l,e.opacity);if(!(e instanceof or))e=o0(e);if(!e)return new rr(NaN,NaN,NaN,NaN);if(e instanceof rr)return e;let t=e.rgb(),n=t.r/255,r=t.g/255,i=t.b/255,s=Math.min(n,r,i),o=Math.max(n,r,i),a=NaN,l=o-s,c=(o+s)/2;if(l){if(n===o)a=(r-i)/l+(r<i?6:0);else if(r===o)a=(i-n)/l+2;else a=(n-r)/l+4;l/=c<0.5?o+s:2-o-s,a*=60}else l=c>0&&c<1?0:a;return new rr(a,l,c,t.opacity)}function eE(e,t,n,r){if(t===void 0&&n===void 0)return IE(e);return new rr(e,t,n,r==null?1:r)}var DE=Math.PI/180,zE=180/Math.PI,pf=18,BE=0.96422,WE=1,UE=0.82521,PE=0.13793103448275862,To=0.20689655172413793,qE=3*To*To,FW=To*To*To;function Wg(e){return e>FW?Math.pow(e,0.3333333333333333):e/qE+PE}function Ug(e){return e>To?e*e*e:qE*(e-PE)}function Pg(e){return 255*(e<=0.0031308?12.92*e:1.055*Math.pow(e,0.4166666666666667)-0.055)}function qg(e){return(e/=255)<=0.04045?e/12.92:Math.pow((e+0.055)/1.055,2.4)}function IW(e){if(e instanceof Kr)return new Kr(e.l,e.a,e.b,e.opacity);if(e instanceof Jr)return GE(e);if(!(e instanceof dt))e=a0(e);let t=e,n=qg(t.r),r=qg(t.g),i=qg(t.b),s=Wg((0.2225045*n+0.7168786*r+0.0606169*i)/WE),o,a;if(n===r&&r===i)o=a=s;else o=Wg((0.4360747*n+0.3850649*r+0.1430804*i)/BE),a=Wg((0.0139322*n+0.0971045*r+0.7141733*i)/UE);return new Kr(116*s-16,500*(o-s),200*(s-a),t.opacity)}class Kr extends or{l;a;b;constructor(e,t,n,r){super();this.l=+e,this.a=+t,this.b=+n,this.opacity=+r}brighter(e){return new Kr(this.l+pf*(e==null?1:e),this.a,this.b,this.opacity)}darker(e){return new Kr(this.l-pf*(e==null?1:e),this.a,this.b,this.opacity)}rgb(){let e=(this.l+16)/116,t=isNaN(this.a)?e:e+this.a/500,n=isNaN(this.b)?e:e-this.b/200,r=BE*Ug(t),i=WE*Ug(e),s=UE*Ug(n);return new dt(Pg(3.1338561*r-1.6168667*i-0.4906146*s),Pg(-0.9787684*r+1.9161415*i+0.033454*s),Pg(0.0719453*r-0.2289914*i+1.4052427*s),this.opacity)}}function DW(e){if(e instanceof Jr)return new Jr(e.h,e.c,e.l,e.opacity);if(!(e instanceof Kr))e=IW(e);let t=e;if(t.a===0&&t.b===0)return new Jr(NaN,0<t.l&&t.l<100?0:NaN,t.l,t.opacity);let n=Math.atan2(t.b,t.a)*zE;return new Jr(n<0?n+360:n,Math.sqrt(t.a*t.a+t.b*t.b),t.l,t.opacity)}function tE(e,t,n,r){if(t===void 0&&n===void 0)return DW(e);return new Jr(e,t,n,r==null?1:r)}function GE(e){if(isNaN(e.h))return new Kr(e.l,0,0,e.opacity);let t=e.h*DE;return new Kr(e.l,Math.cos(t)*e.c,Math.sin(t)*e.c,e.opacity)}class Jr extends or{h;c;l;constructor(e,t,n,r){super();this.h=+e,this.c=+t,this.l=+n,this.opacity=+r}brighter(e){return new Jr(this.h,this.c,this.l+pf*(e==null?1:e),this.opacity)}darker(e){return new Jr(this.h,this.c,this.l-pf*(e==null?1:e),this.opacity)}rgb(){return GE(this).rgb()}}var XE=-0.14861,l0=1.78277,c0=-0.29227,vf=-0.90649,Il=1.97294,nE=Il*vf,rE=Il*l0,iE=l0*c0-vf*XE;function zW(e){if(e instanceof Ms)return new Ms(e.h,e.s,e.l,e.opacity);if(!(e instanceof dt))e=a0(e);let t=e,n=t.r/255,r=t.g/255,i=t.b/255,s=(iE*i+nE*n-rE*r)/(iE+nE-rE),o=i-s,a=(Il*(r-s)-c0*o)/vf,l=Math.sqrt(a*a+o*o)/(Il*s*(1-s)),c=l?Math.atan2(a,o)*zE-120:NaN;return new Ms(c<0?c+360:c,l,s,t.opacity)}function sE(e,t,n,r){if(t===void 0&&n===void 0)return zW(e);return new Ms(e,t,n,r==null?1:r)}class Ms extends or{h;s;l;constructor(e,t,n,r){super();this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}brighter(e){return e=e==null?J_:Math.pow(J_,e),new Ms(this.h,this.s,this.l*e,this.opacity)}darker(e){return e=e==null?Y_:Math.pow(Y_,e),new Ms(this.h,this.s,this.l*e,this.opacity)}rgb(){let e=isNaN(this.h)?0:(this.h+120)*DE,t=+this.l,n=isNaN(this.s)?0:this.s*t*(1-t),r=Math.cos(e),i=Math.sin(e);return new dt(255*(t+n*(XE*r+l0*i)),255*(t+n*(c0*r+vf*i)),255*(t+n*(Il*r)),this.opacity)}}function VE(e,t,n,r,i){let s=e*e,o=s*e;return((1-3*e+3*s-o)*t+(4-6*s+3*o)*n+(1+3*e+3*s-3*o)*r+o*i)/6}function BW(e){let t=e.length-1;return function(n){let r=n<=0?n=0:n>=1?(n=1,t-1):Math.floor(n*t),i=e[r],s=e[r+1],o=r>0?e[r-1]:2*i-s,a=r<t-1?e[r+2]:2*s-i;return VE((n-r/t)*t,o,i,s,a)}}function WW(e){let t=e.length;return function(n){let r=Math.floor(((n%=1)<0?++n:n)*t),i=e[(r+t-1)%t],s=e[r%t],o=e[(r+1)%t],a=e[(r+2)%t];return VE((n-r/t)*t,i,s,o,a)}}var UW=(e)=>()=>e,xf=UW;function YE(e,t){return function(n){return e+n*t}}function PW(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}function u0(e,t){let n=t-e;return n?YE(e,n>180||n<-180?n-360*Math.round(n/360):n):xf(isNaN(e)?t:e)}function qW(e){return(e=+e)===1?xn:function(t,n){return n-t?PW(t,n,e):xf(isNaN(t)?n:t)}}function xn(e,t){let n=t-e;return n?YE(e,n):xf(isNaN(e)?t:e)}var oE=function e(t){let n=qW(t);function r(i,s){let o=t0(i),a=t0(s),l=n(o.r,a.r),c=n(o.g,a.g),u=n(o.b,a.b),f=xn(o.opacity,a.opacity);return function(d){return o.r=l(d),o.g=c(d),o.b=u(d),o.opacity=f(d),`${o}`}}return r.gamma=e,r}(1);function JE(e){return function(t){let n=t.length,r=Array(n),i=Array(n),s=Array(n),o,a;for(o=0;o<n;++o)a=t0(t[o]),r[o]=a.r||0,i[o]=a.g||0,s[o]=a.b||0;let l=e(r),c=e(i),u=e(s);return a.opacity=1,function(f){return a.r=l(f),a.g=c(f),a.b=u(f),`${a}`}}}var Nye=JE(BW),Rye=JE(WW);function GW(e,t){if(!t)t=[];let n=e?Math.min(t.length,e.length):0,r=ArrayBuffer.isView(t)?new t.constructor(t):Array.prototype.slice.call(t),i;return function(s){for(i=0;i<n;++i)r[i]=e[i]*(1-s)+t[i]*s;return r}}function XW(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function VW(e,t){let n=t?t.length:0,r=e?Math.min(n,e.length):0,i=Array(r),s=Array(n),o;for(o=0;o<r;++o)i[o]=f0(e[o],t[o]);for(;o<n;++o)s[o]=t[o];return function(a){for(o=0;o<r;++o)s[o]=i[o](a);return s}}function YW(e,t){let n=new Date,r=+e,i=+t;return function(s){return n.setTime(r*(1-s)+i*s),n}}function Tr(e,t){let n=+e,r=+t;return function(i){return n*(1-i)+r*i}}function JW(e,t){let n={},r={},i;if(e===null||typeof e!=="object")e={};if(t===null||typeof t!=="object")t={};for(i in t)if(i in e)n[i]=f0(e[i],t[i]);else r[i]=t[i];return function(s){for(i in n)r[i]=n[i](s);return r}}var n0=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Gg=new RegExp(n0.source,"g");function KW(e){return function(){return e}}function QW(e){return function(t){return`${e(t)}`}}function HW(e,t){let n=n0.lastIndex=Gg.lastIndex=0,r,i,s,o=-1,a=[],l=[],c=`${e}`,u=`${t}`;while((r=n0.exec(c))&&(i=Gg.exec(u))){if((s=i.index)>n)if(s=u.slice(n,s),a[o])a[o]+=s;else a[++o]=s;if(r===i)if(a[o])a[o]+=i[0];else a[++o]=i[0];else a[++o]=null,l.push({i:o,x:Tr(+r[0],+i[0])});n=Gg.lastIndex}if(n<u.length)if(s=u.slice(n),a[o])a[o]+=s;else a[++o]=s;return a.length<2?l[0]?QW(l[0].x):KW(u):(u=l.length,function(f){for(let d=0,h;d<u;++d)a[(h=l[d]).i]=h.x(f);return a.join("")})}function f0(e,t){let n=typeof t,r;return t==null||n==="boolean"?xf(t):(n==="number"?Tr:n==="string"?(r=o0(t))?(t=r,oE):HW:t instanceof or?oE:t instanceof Date?YW:XW(t)?GW:Array.isArray(t)?VW:typeof t.valueOf!=="function"&&typeof t.toString!=="function"||isNaN(t)?JW:Tr)(e,t)}function ZW(e,t){let n=+e,r=+t;return function(i){return Math.round(n*(1-i)+r*i)}}var aE=180/Math.PI,r0={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function KE(e,t,n,r,i,s){let o,a,l;if(o=Math.sqrt(e*e+t*t))e/=o,t/=o;if(l=e*n+t*r)n-=e*l,r-=t*l;if(a=Math.sqrt(n*n+r*r))n/=a,r/=a,l/=a;if(e*r<t*n)e=-e,t=-t,l=-l,o=-o;return{translateX:i,translateY:s,rotate:Math.atan2(t,e)*aE,skewX:Math.atan(l)*aE,scaleX:o,scaleY:a}}var af;function eU(e){let t=new(typeof DOMMatrix==="function"?DOMMatrix:globalThis.WebKitCSSMatrix)(`${e}`);return t.isIdentity?r0:KE(t.a,t.b,t.c,t.d,t.e,t.f)}function tU(e){if(e==null)return r0;if(!af)af=document.createElementNS("http://www.w3.org/2000/svg","g");af.setAttribute("transform",e);let t=af.transform.baseVal.consolidate();if(!t)return r0;let n=t.matrix;return KE(n.a,n.b,n.c,n.d,n.e,n.f)}function QE(e,t,n,r){function i(c){return c.length?`${c.pop()} `:""}function s(c,u,f,d,h,p){if(c!==f||u!==d){let m=h.push("translate(",null,t,null,n);p.push({i:m-4,x:Tr(c,f)},{i:m-2,x:Tr(u,d)})}else if(f||d)h.push(`translate(${f}${t}${d}${n}`)}function o(c,u,f,d){if(c!==u){if(c-u>180)u+=360;else if(u-c>180)c+=360;d.push({i:f.push(`${i(f)}rotate(`,null,r)-2,x:Tr(c,u)})}else if(u)f.push(`${i(f)}rotate(${u}${r}`)}function a(c,u,f,d){if(c!==u)d.push({i:f.push(`${i(f)}skewX(`,null,r)-2,x:Tr(c,u)});else if(u)f.push(`${i(f)}skewX(${u}${r}`)}function l(c,u,f,d,h,p){if(c!==f||u!==d){let m=h.push(`${i(h)}scale(`,null,",",null,")");p.push({i:m-4,x:Tr(c,f)},{i:m-2,x:Tr(u,d)})}else if(f!==1||d!==1)h.push(`${i(h)}scale(${f},${d})`)}return function(c,u){let f=[],d=[],h=e(c),p=e(u);return s(h.translateX,h.translateY,p.translateX,p.translateY,f,d),o(h.rotate,p.rotate,f,d),a(h.skewX,p.skewX,f,d),l(h.scaleX,h.scaleY,p.scaleX,p.scaleY,f,d),function(m){let g=-1,y=d.length,w;while(++g<y)f[(w=d[g]).i]=w.x(m);return f.join("")}}}var Lye=QE(eU,"px, ","px)","deg)"),Fye=QE(tU,", ",")",")");function lE(e){return((e=Math.exp(e))+1/e)/2}function nU(e){return((e=Math.exp(e))-1/e)/2}function rU(e){return((e=Math.exp(2*e))-1)/(e+1)}var Iye=function e(t,n,r){function i(s,o){let a=s[0],l=s[1],c=s[2],u=o[0],f=o[1],d=o[2],h=u-a,p=f-l,m=h*h+p*p,g,y;if(m<0.000000000001)y=Math.log(d/c)/t,g=function(w){return[a+w*h,l+w*p,c*Math.exp(t*w*y)]};else{let w=Math.sqrt(m),b=(d*d-c*c+r*m)/(2*c*n*w),v=(d*d-c*c-r*m)/(2*d*n*w),x=Math.log(Math.sqrt(b*b+1)-b);y=(Math.log(Math.sqrt(v*v+1)-v)-x)/t,g=function(S){let k=S*y,C=lE(x),T=c/(n*w)*(C*rU(t*k+x)-nU(x));return[a+T*h,l+T*p,c*C/lE(t*k+x)]}}return g.duration=y*1000*t/Math.SQRT2,g}return i.rho=function(s){let o=Math.max(0.001,+s),a=o*o,l=a*a;return e(o,a,l)},i}(Math.SQRT2,2,4);function HE(e){return function(t,n){let r=eE(t),i=eE(n),s=e(r.h,i.h),o=xn(r.s,i.s),a=xn(r.l,i.l),l=xn(r.opacity,i.opacity);return function(c){return r.h=s(c),r.s=o(c),r.l=a(c),r.opacity=l(c),`${r}`}}}var Dye=HE(u0),zye=HE(xn);function ZE(e){return function(t,n){let r=tE(t),i=tE(n),s=e(r.h,i.h),o=xn(r.c,i.c),a=xn(r.l,i.l),l=xn(r.opacity,i.opacity);return function(c){return r.h=s(c),r.c=o(c),r.l=a(c),r.opacity=l(c),`${r}`}}}var Bye=ZE(u0),Wye=ZE(xn);function e2(e){return function t(n){n=+n;function r(i,s){let o=sE(i),a=sE(s),l=e(o.h,a.h),c=xn(o.s,a.s),u=xn(o.l,a.l),f=xn(o.opacity,a.opacity);return function(d){return o.h=l(d),o.s=c(d),o.l=u(Math.pow(d,n)),o.opacity=f(d),`${o}`}}return r.gamma=t,r}(1)}var Uye=e2(u0),Pye=e2(xn);function iU(e){return function(){return e}}function sU(e){return+e}var cE=[0,1];function $o(e){return e}function i0(e,t){return(t-=e=+e)?function(n){return(n-e)/t}:iU(isNaN(t)?NaN:0.5)}function oU(e,t){let n;if(e>t)n=e,e=t,t=n;return function(r){return Math.max(e,Math.min(t,r))}}function aU(e,t,n){let r=e[0],i=e[1],s=t[0],o=t[1],a,l;if(i<r)a=i0(i,r),l=n(o,s);else a=i0(r,i),l=n(s,o);return function(c){return l(a(c))}}function lU(e,t,n){let r=Math.min(e.length,t.length)-1,i=Array(r),s=Array(r),o=-1;if(e[r]<e[0])e=e.slice().reverse(),t=t.slice().reverse();while(++o<r)i[o]=i0(e[o],e[o+1]),s[o]=n(t[o],t[o+1]);return function(a){let l=vW(e,a,1,r)-1;return s[l](i[l](a))}}function t2(e,t){return t.domain(e.domain()).range(e.range()).interpolate(e.interpolate()).clamp(e.clamp()).unknown(e.unknown())}function cU(){let e=cE,t=cE,n=f0,r,i,s,o=$o,a,l,c;function u(){let d=Math.min(e.length,t.length);if(o!==$o)o=oU(e[0],e[d-1]);return a=d>2?lU:aU,l=c=null,f}function f(d){return d==null||isNaN(d=+d)?s:(l||(l=a(e.map(r),t,n)))(r(o(d)))}return f.invert=function(d){return o(i((c||(c=a(t,e.map(r),Tr)))(d)))},f.domain=function(d){return arguments.length?(e=Array.from(d,sU),u()):e.slice()},f.range=function(d){return arguments.length?(t=Array.from(d),u()):t.slice()},f.rangeRound=function(d){return t=Array.from(d),n=ZW,u()},f.clamp=function(d){return arguments.length?(o=d?!0:$o,u()):o!==$o},f.interpolate=function(d){return arguments.length?(n=d,u()):n},f.unknown=function(d){return arguments.length?(s=d,f):s},function(d,h){return r=d,i=h,u()}}function n2(){return cU()($o,$o)}function uU(e){return Math.abs(e=Math.round(e))>=1000000000000000000000?e.toLocaleString("en").replace(/,/g,""):e.toString(10)}function mf(e,t){if(!isFinite(e)||e===0)return null;let n=t?e.toExponential(t-1):e.toExponential(),r=n.indexOf("e"),i=n.slice(0,r);return[i.length>1?i[0]+i.slice(2):i,+n.slice(r+1)]}function Mo(e){let t=mf(Math.abs(e));return t?t[1]:NaN}function fU(e,t){return function(n,r){let i=n.length,s=[],o=0,a=e[0],l=0;while(i>0&&a>0){if(l+a+1>r)a=Math.max(1,r-l);if(s.push(n.substring(i-=a,i+a)),(l+=a+1)>r)break;a=e[o=(o+1)%e.length]}return s.reverse().join(t)}}function dU(e){return function(t){return t.replace(/[0-9]/g,function(n){return e[+n]})}}var hU=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;class d0{fill;align;sign;symbol;zero;width;comma;precision;trim;type;constructor(e){this.fill=e.fill===void 0?" ":`${e.fill}`,this.align=e.align===void 0?">":`${e.align}`,this.sign=e.sign===void 0?"-":`${e.sign}`,this.symbol=e.symbol===void 0?"":`${e.symbol}`,this.zero=!!e.zero,this.width=e.width===void 0?void 0:+e.width,this.comma=!!e.comma,this.precision=e.precision===void 0?void 0:+e.precision,this.trim=!!e.trim,this.type=e.type===void 0?"":`${e.type}`}toString(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":`.${Math.max(0,this.precision|0)}`)+(this.trim?"~":"")+this.type}}function r2(e){let t=hU.exec(e);if(!t)throw Error(`invalid format: ${e}`);return new d0({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}r2.prototype=d0.prototype;var pU=r2,s0=pU;function mU(e){let t=-1,n=0;e:for(let r=e.length,i=1;i<r;++i)switch(e[i]){case".":t=n=i;break;case"0":if(t===0)t=i;n=i;break;default:if(!+e[i])break e;if(t>0)t=0;break}return t>0?e.slice(0,t)+e.slice(n+1):e}var Fl;function gU(e,t){let n=mf(e,t);if(!n)return Fl=void 0,e.toPrecision(t);let r=n[0],i=n[1];Fl=Math.max(-8,Math.min(8,Math.floor(i/3)))*3;let s=i-Fl+1,o=r.length;return s===o?r:s>o?`${r}${Array(s-o+1).join("0")}`:s>0?`${r.slice(0,s)}.${r.slice(s)}`:`0.${Array(1-s).join("0")}${mf(e,Math.max(0,t+s-1))[0]}`}function uE(e,t){let n=mf(e,t);if(!n)return`${e}`;let r=n[0],i=n[1];return i<0?`0.${Array(-i).join("0")}${r}`:r.length>i+1?`${r.slice(0,i+1)}.${r.slice(i+1)}`:`${r}${Array(i-r.length+2).join("0")}`}var yU={"%":(e,t)=>(e*100).toFixed(t),b:(e)=>Math.round(e).toString(2),c:(e)=>`${e}`,d:uU,e:(e,t)=>e.toExponential(t),f:(e,t)=>e.toFixed(t),g:(e,t)=>e.toPrecision(t),o:(e)=>Math.round(e).toString(8),p:(e,t)=>uE(e*100,t),r:uE,s:gU,X:(e)=>Math.round(e).toString(16).toUpperCase(),x:(e)=>Math.round(e).toString(16)},fE=yU;function dE(e){return e}var hE=Array.prototype.map,pE=["y","z","a","f","p","n","\xB5","m","","k","M","G","T","P","E","Z","Y"];function wU(e){let t=e.grouping===void 0||e.thousands===void 0?dE:fU(hE.call(e.grouping,Number),`${e.thousands}`),n=e.currency===void 0?"":e.currency[0]+"",r=e.currency===void 0?"":e.currency[1]+"",i=e.decimal===void 0?".":`${e.decimal}`,s=e.numerals===void 0?dE:dU(hE.call(e.numerals,String)),o=e.percent===void 0?"%":`${e.percent}`,a=e.minus===void 0?"\u2212":`${e.minus}`,l=e.nan===void 0?"NaN":`${e.nan}`;function c(f,d){let h=s0(f),p=h.fill,m=h.align,g=h.sign,y=h.symbol,w=h.zero,b=h.width,v=h.comma,x=h.precision,S=h.trim,k=h.type;if(k==="n")v=!0,k="g";else if(!fE[k]){if(x===void 0)x=12;S=!0,k="g"}if(w||p==="0"&&m==="=")w=!0,p="0",m="=";let C=(d&&d.prefix!==void 0?d.prefix:"")+(y==="$"?n:y==="#"&&/[boxX]/.test(k)?`0${k.toLowerCase()}`:""),T=(y==="$"?r:/[%p]/.test(k)?o:"")+(d&&d.suffix!==void 0?d.suffix:""),_=fE[k],E=/[defgprs%]/.test(k);x=x===void 0?6:/[gprs]/.test(k)?Math.max(1,Math.min(21,x)):Math.max(0,Math.min(20,x));function A($){let M=C,O=T,j,I,D;if(k==="c")O=_($)+O,$="";else{$=+$;let K=$<0||1/$<0;if($=isNaN($)?l:_(Math.abs($),x),S)$=mU($);if(K&&+$===0&&g!=="+")K=!1;if(M=(K?g==="("?g:a:g==="-"||g==="("?"":g)+M,O=(k==="s"&&!isNaN($)&&Fl!==void 0?pE[8+Fl/3]:"")+O+(K&&g==="("?")":""),E){j=-1,I=$.length;while(++j<I)if(D=$.charCodeAt(j),48>D||D>57){O=(D===46?i+$.slice(j+1):$.slice(j))+O,$=$.slice(0,j);break}}}if(v&&!w)$=t($,1/0);let W=M.length+$.length+O.length,G=W<(b??0)?Array((b??0)-W+1).join(p):"";if(v&&w)$=t(G+$,G.length?(b??0)-O.length:1/0),G="";switch(m){case"<":$=M+$+O+G;break;case"=":$=M+G+$+O;break;case"^":{let K=G.length>>1;$=G.slice(0,K)+M+$+O+G.slice(K);break}default:$=G+M+$+O;break}return s($)}return A.toString=function(){return`${h}`},A}function u(f,d){let h=s0(f);h.type="f";let p=Math.max(-8,Math.min(8,Math.floor(Mo(d)/3)))*3,m=Math.pow(10,-p),g=c(`${h}`,{suffix:pE[8+p/3]});return function(y){return g(m*y)}}return{format:c,formatPrefix:u}}var lf,i2,s2;bU({thousands:",",grouping:[3],currency:["$",""]});function bU(e){return lf=wU(e),i2=lf.format,s2=lf.formatPrefix,lf}function vU(e){return Math.max(0,-Mo(Math.abs(e)))}function xU(e,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(Mo(t)/3)))*3-Mo(Math.abs(e)))}function SU(e,t){return e=Math.abs(e),t=Math.abs(t)-e,Math.max(0,Mo(t)-Mo(e))+1}function kU(e,t,n,r){let i=$W(e,t,n),s,o=s0(r==null?",f":r);switch(o.type){case"s":{let a=Math.max(Math.abs(e),Math.abs(t));if(o.precision==null&&!isNaN(s=xU(i,a)))o.precision=s;return s2(o.toString(),a)}case"":case"e":case"g":case"p":case"r":{if(o.precision==null&&!isNaN(s=SU(i,Math.max(Math.abs(e),Math.abs(t)))))o.precision=s-(o.type==="e"?1:0);break}case"f":case"%":{if(o.precision==null&&!isNaN(s=vU(i)))o.precision=s-(o.type==="%"?1:0)*2;break}}return i2(o.toString())}function _U(e){let t=e.domain;return e.ticks=function(n){let r=t();return AW(r[0],r[r.length-1],n==null?10:n)},e.tickFormat=function(n,r){let i=t();return kU(i[0],i[i.length-1],n==null?10:n,r)},e.nice=function(n){if(n==null)n=10;let r=t(),i=0,s=r.length-1,o=r[i],a=r[s],l,c,u=10;if(a<o)c=o,o=a,a=c,c=i,i=s,s=c;while(u-- >0){if(c=e0(o,a,n),c===l)return r[i]=o,r[s]=a,e.domain(r);else if(c>0)o=Math.floor(o/c)*c,a=Math.ceil(a/c)*c;else if(c<0)o=Math.ceil(o*c)/c,a=Math.floor(a*c)/c;else break;l=c}return e},e}function Os(...e){let t=n2();return t.copy=function(){return t2(t,Os())},FE.apply(t,arguments),_U(t)}function EU(e,t){e=e.slice();let n=0,r=e.length-1,i=e[n],s=e[r],o;if(s<i)o=n,n=r,r=o,o=i,i=s,s=o;return e[n]=t.floor(i),e[r]=t.ceil(s),e}var Xg=new Date,Vg=new Date;function mt(e,t,n,r){function i(s){let o=s==null?new Date:new Date(+s);return e(o),o}if(i.floor=(s)=>{let o=new Date(+s);return e(o),o},i.ceil=(s)=>{let o=new Date(+s-1);return e(o),t(o,1),e(o),o},i.round=(s)=>{let o=i(s),a=i.ceil(s);return+s-+o<+a-+s?o:a},i.offset=(s,o)=>{let a=new Date(+s);return t(a,o==null?1:Math.floor(o)),a},i.range=(s,o,a)=>{let l=[],c=i.ceil(s),u=a==null?1:Math.floor(a);if(!(c<new Date(+o))||!(u>0))return l;let f;do f=new Date(+c),l.push(f),t(c,u),e(c);while(f<c&&c<new Date(+o));return l},i.filter=(s)=>{return mt((o)=>{if(o>=o)while(e(o),!s(o))o.setTime(+o-1)},(o,a)=>{if(o>=o)if(a<0)while(++a<=0)while(t(o,-1),!s(o));else while(--a>=0)while(t(o,1),!s(o));})},n)i.count=(s,o)=>{return Xg.setTime(+s),Vg.setTime(+o),e(Xg),e(Vg),Math.floor(n(Xg,Vg))},i.every=(s)=>{return s=Math.floor(s),!isFinite(s)||!(s>0)?null:!(s>1)?i:i.filter(r?(o)=>r(o)%s===0:(o)=>i.count(0,o)%s===0)};return i}var gf=mt(()=>{},(e,t)=>{e.setTime(+e+t)},(e,t)=>{return+t-+e});gf.every=(e)=>{if(e=Math.floor(e),!isFinite(e)||!(e>0))return null;if(!(e>1))return gf;return mt((t)=>{t.setTime(Math.floor(+t/e)*e)},(t,n)=>{t.setTime(+t+n*e)},(t,n)=>{return(+n-+t)/e})};var qye=gf.range,Wi=1000,ir=60000,Ui=3600000,Oo=86400000,h0=604800000,mE=2592000000,Yg=31536000000,Co=mt((e)=>{e.setTime(+e-e.getMilliseconds())},(e,t)=>{e.setTime(+e+t*Wi)},(e,t)=>{return(+t-+e)/Wi},(e)=>{return e.getUTCSeconds()}),Gye=Co.range,p0=mt((e)=>{e.setTime(+e-e.getMilliseconds()-e.getSeconds()*Wi)},(e,t)=>{e.setTime(+e+t*ir)},(e,t)=>{return(+t-+e)/ir},(e)=>{return e.getMinutes()}),Xye=p0.range,o2=mt((e)=>{e.setUTCSeconds(0,0)},(e,t)=>{e.setTime(+e+t*ir)},(e,t)=>{return(+t-+e)/ir},(e)=>{return e.getUTCMinutes()}),Vye=o2.range,m0=mt((e)=>{e.setTime(+e-e.getMilliseconds()-e.getSeconds()*Wi-e.getMinutes()*ir)},(e,t)=>{e.setTime(+e+t*Ui)},(e,t)=>{return(+t-+e)/Ui},(e)=>{return e.getHours()}),Yye=m0.range,a2=mt((e)=>{e.setUTCMinutes(0,0,0)},(e,t)=>{e.setTime(+e+t*Ui)},(e,t)=>{return(+t-+e)/Ui},(e)=>{return e.getUTCHours()}),Jye=a2.range,g0=mt((e)=>{e.setHours(0,0,0,0)},(e,t)=>{e.setDate(e.getDate()+t)},(e,t)=>(+t-+e-(t.getTimezoneOffset()-e.getTimezoneOffset())*ir)/Oo,(e)=>e.getDate()-1),Kye=g0.range,AU=mt((e)=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>{return(+t-+e)/Oo},(e)=>{return e.getUTCDate()-1}),Qye=AU.range,l2=mt((e)=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>{return(+t-+e)/Oo},(e)=>{return Math.floor(+e/Oo)}),Hye=l2.range;function js(e){return mt((t)=>{t.setDate(t.getDate()-(t.getDay()+7-e)%7),t.setHours(0,0,0,0)},(t,n)=>{t.setDate(t.getDate()+n*7)},(t,n)=>{return(+n-+t-(n.getTimezoneOffset()-t.getTimezoneOffset())*ir)/h0})}var y0=js(0),$U=js(1),CU=js(2),TU=js(3),MU=js(4),OU=js(5),jU=js(6),Zye=y0.range,ewe=$U.range,twe=CU.range,nwe=TU.range,rwe=MU.range,iwe=OU.range,swe=jU.range;function Ns(e){return mt((t)=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-e)%7),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCDate(t.getUTCDate()+n*7)},(t,n)=>{return(+n-+t)/h0})}var c2=Ns(0),NU=Ns(1),RU=Ns(2),LU=Ns(3),FU=Ns(4),IU=Ns(5),DU=Ns(6),owe=c2.range,awe=NU.range,lwe=RU.range,cwe=LU.range,uwe=FU.range,fwe=IU.range,dwe=DU.range,w0=mt((e)=>{e.setDate(1),e.setHours(0,0,0,0)},(e,t)=>{e.setMonth(e.getMonth()+t)},(e,t)=>{return t.getMonth()-e.getMonth()+(t.getFullYear()-e.getFullYear())*12},(e)=>{return e.getMonth()}),hwe=w0.range,u2=mt((e)=>{e.setUTCDate(1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCMonth(e.getUTCMonth()+t)},(e,t)=>{return t.getUTCMonth()-e.getUTCMonth()+(t.getUTCFullYear()-e.getUTCFullYear())*12},(e)=>{return e.getUTCMonth()}),pwe=u2.range,Sf=mt((e)=>{e.setMonth(0,1),e.setHours(0,0,0,0)},(e,t)=>{e.setFullYear(e.getFullYear()+t)},(e,t)=>{return t.getFullYear()-e.getFullYear()},(e)=>{return e.getFullYear()});Sf.every=(e)=>{return e=Math.floor(e),!isFinite(e)||!(e>0)?null:mt((t)=>{t.setFullYear(Math.floor(t.getFullYear()/e)*e),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,n)=>{t.setFullYear(t.getFullYear()+n*e)})};var mwe=Sf.range,b0=mt((e)=>{e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCFullYear(e.getUTCFullYear()+t)},(e,t)=>{return t.getUTCFullYear()-e.getUTCFullYear()},(e)=>{return e.getUTCFullYear()});b0.every=(e)=>{return e=Math.floor(e),!isFinite(e)||!(e>0)?null:mt((t)=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/e)*e),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCFullYear(t.getUTCFullYear()+n*e)})};var gwe=b0.range;function uf(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function zU(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function v0(e){let t,n,r;if(e.length!==2)t=uf,n=(a,l)=>uf(e(a),l),r=(a,l)=>e(a)-l;else t=e===uf||e===zU?e:BU,n=e,r=e;function i(a,l,c=0,u=a.length){if(c<u){if(t(l,l)!==0)return u;do{let f=c+u>>>1;if(n(a[f],l)<0)c=f+1;else u=f}while(c<u)}return c}function s(a,l,c=0,u=a.length){if(c<u){if(t(l,l)!==0)return u;do{let f=c+u>>>1;if(n(a[f],l)<=0)c=f+1;else u=f}while(c<u)}return c}function o(a,l,c=0,u=a.length){let f=i(a,l,c,u-1);return f>c&&r(a[f-1],l)>-r(a[f],l)?f-1:f}return{left:i,center:o,right:s}}function BU(){return 0}function WU(e){return e===null?NaN:+e}var f2=v0(uf),ywe=f2.right,wwe=f2.left,bwe=v0(WU).center,vwe=d2(h2),xwe=d2(UU);function d2(e){return function(t,n,r=n){if(!((n=+n)>=0))throw RangeError("invalid rx");if(!((r=+r)>=0))throw RangeError("invalid ry");let{data:i,width:s,height:o}=t;if(!((s=Math.floor(s))>=0))throw RangeError("invalid width");if(!((o=Math.floor(o!==void 0?o:i.length/s))>=0))throw RangeError("invalid height");if(!s||!o||!n&&!r)return t;let a=n&&e(n),l=r&&e(r),c=i.slice();if(a&&l)So(a,c,i,s,o),So(a,i,c,s,o),So(a,c,i,s,o),ko(l,i,c,s,o),ko(l,c,i,s,o),ko(l,i,c,s,o);else if(a)So(a,i,c,s,o),So(a,c,i,s,o),So(a,i,c,s,o);else if(l)ko(l,i,c,s,o),ko(l,c,i,s,o),ko(l,i,c,s,o);return t}}function So(e,t,n,r,i){for(let s=0,o=r*i;s<o;)e(t,n,s,s+=r,1)}function ko(e,t,n,r,i){for(let s=0,o=r*i;s<r;++s)e(t,n,s,s+o,r)}function UU(e){let t=h2(e);return(n,r,i,s,o)=>{i<<=2,s<<=2,o<<=2,t(n,r,i+0,s+0,o),t(n,r,i+1,s+1,o),t(n,r,i+2,s+2,o),t(n,r,i+3,s+3,o)}}function h2(e){let t=Math.floor(e);if(t===e)return PU(e);let n=e-t,r=2*e+1;return(i,s,o,a,l)=>{if(!((a-=l)>=o))return;let c=t*s[o],u=l*t,f=u+l;for(let d=o,h=o+u;d<h;d+=l)c+=s[Math.min(a,d)];for(let d=o,h=a;d<=h;d+=l)c+=s[Math.min(a,d+u)],i[d]=(c+n*(s[Math.max(o,d-f)]+s[Math.min(a,d+f)]))/r,c-=s[Math.max(o,d-u)]}}function PU(e){let t=2*e+1;return(n,r,i,s,o)=>{if(!((s-=o)>=i))return;let a=e*r[i],l=o*e;for(let c=i,u=i+l;c<u;c+=o)a+=r[Math.min(s,c)];for(let c=i,u=s;c<=u;c+=o)a+=r[Math.min(s,c+l)],n[c]=a/t,a-=r[Math.max(i,c-l)]}}var p2=Array.prototype,Swe=p2.slice,kwe=p2.map,qU=Math.sqrt(50),GU=Math.sqrt(10),XU=Math.sqrt(2);function m2(e,t,n){let r=(t-e)/Math.max(0,n),i=Math.floor(Math.log10(r)),s=r/Math.pow(10,i),o=s>=qU?10:s>=GU?5:s>=XU?2:1,a,l,c;if(i<0){if(c=Math.pow(10,-i)/o,a=Math.round(e*c),l=Math.round(t*c),a/c<e)++a;if(l/c>t)--l;c=-c}else{if(c=Math.pow(10,i)*o,a=Math.round(e/c),l=Math.round(t/c),a*c<e)++a;if(l*c>t)--l}if(l<a&&0.5<=n&&n<2)return m2(e,t,n*2);return[a,l,c]}function gE(e,t,n){return t=+t,e=+e,n=+n,m2(e,t,n)[2]}function yE(e,t,n){t=+t,e=+e,n=+n;let r=t<e,i=r?gE(t,e,n):gE(e,t,n);return(r?-1:1)*(i<0?1/-i:i)}function VU(e){return function(t,n=0,r=t.length){let i=r-(n=+n);while(i){let s=e()*i--|0,o=t[i+n];t[i+n]=t[s+n],t[s+n]=o}return t}}var _we=VU(Math.random);function g2(e,t,n,r,i,s){let o=[[Co,1,Wi],[Co,5,5*Wi],[Co,15,15*Wi],[Co,30,30*Wi],[s,1,ir],[s,5,5*ir],[s,15,15*ir],[s,30,30*ir],[i,1,Ui],[i,3,3*Ui],[i,6,6*Ui],[i,12,12*Ui],[r,1,Oo],[r,2,2*Oo],[n,1,h0],[t,1,mE],[t,3,3*mE],[e,1,Yg]];function a(c,u,f){let d=u<c;if(d)[c,u]=[u,c];let h=f&&typeof f.range==="function"?f:l(c,u,f),p=h?h.range(c,+u+1):[];return d?p.reverse():p}function l(c,u,f){let d=Math.abs(+u-+c)/f,h=v0(([,,g])=>g).right(o,d);if(h===o.length)return e.every(yE(+c/Yg,+u/Yg,f));if(h===0)return gf.every(Math.max(yE(+c,+u,f),1));let[p,m]=o[d/o[h-1][2]<o[h][2]/d?h-1:h];return p.every(m)}return[a,l]}var y2=g2(b0,u2,c2,l2,a2,o2),w2=g2(Sf,w0,y0,g0,m0,p0),Ewe=y2[0],Awe=y2[1],YU=w2[0],JU=w2[1],Jg=new Date,Kg=new Date;function gt(e,t,n,r){function i(s){let o=s==null?new Date:new Date(+s);return e(o),o}if(i.floor=(s)=>{let o=new Date(+s);return e(o),o},i.ceil=(s)=>{let o=new Date(+s-1);return e(o),t(o,1),e(o),o},i.round=(s)=>{let o=i(s),a=i.ceil(s);return+s-+o<+a-+s?o:a},i.offset=(s,o)=>{let a=new Date(+s);return t(a,o==null?1:Math.floor(o)),a},i.range=(s,o,a)=>{let l=[],c=i.ceil(s),u=a==null?1:Math.floor(a);if(!(c<new Date(+o))||!(u>0))return l;let f;do f=new Date(+c),l.push(f),t(c,u),e(c);while(f<c&&c<new Date(+o));return l},i.filter=(s)=>{return gt((o)=>{if(o>=o)while(e(o),!s(o))o.setTime(+o-1)},(o,a)=>{if(o>=o)if(a<0)while(++a<=0)while(t(o,-1),!s(o));else while(--a>=0)while(t(o,1),!s(o));})},n)i.count=(s,o)=>{return Jg.setTime(+s),Kg.setTime(+o),e(Jg),e(Kg),Math.floor(n(Jg,Kg))},i.every=(s)=>{return s=Math.floor(s),!isFinite(s)||!(s>0)?null:!(s>1)?i:i.filter(r?(o)=>r(o)%s===0:(o)=>i.count(0,o)%s===0)};return i}var yf=gt(()=>{},(e,t)=>{e.setTime(+e+t)},(e,t)=>{return+t-+e});yf.every=(e)=>{if(e=Math.floor(e),!isFinite(e)||!(e>0))return null;if(!(e>1))return yf;return gt((t)=>{t.setTime(Math.floor(+t/e)*e)},(t,n)=>{t.setTime(+t+n*e)},(t,n)=>{return(+n-+t)/e})};var $we=yf.range,Pi=1000,sr=60000,qi=3600000,jo=86400000,x0=604800000,wE=2592000000,Qg=31536000000,Ll=gt((e)=>{e.setTime(+e-e.getMilliseconds())},(e,t)=>{e.setTime(+e+t*Pi)},(e,t)=>{return(+t-+e)/Pi},(e)=>{return e.getUTCSeconds()}),Cwe=Ll.range,b2=gt((e)=>{e.setTime(+e-e.getMilliseconds()-e.getSeconds()*Pi)},(e,t)=>{e.setTime(+e+t*sr)},(e,t)=>{return(+t-+e)/sr},(e)=>{return e.getMinutes()}),Twe=b2.range,v2=gt((e)=>{e.setUTCSeconds(0,0)},(e,t)=>{e.setTime(+e+t*sr)},(e,t)=>{return(+t-+e)/sr},(e)=>{return e.getUTCMinutes()}),Mwe=v2.range,x2=gt((e)=>{e.setTime(+e-e.getMilliseconds()-e.getSeconds()*Pi-e.getMinutes()*sr)},(e,t)=>{e.setTime(+e+t*qi)},(e,t)=>{return(+t-+e)/qi},(e)=>{return e.getHours()}),Owe=x2.range,S2=gt((e)=>{e.setUTCMinutes(0,0,0)},(e,t)=>{e.setTime(+e+t*qi)},(e,t)=>{return(+t-+e)/qi},(e)=>{return e.getUTCHours()}),jwe=S2.range,kf=gt((e)=>{e.setHours(0,0,0,0)},(e,t)=>{e.setDate(e.getDate()+t)},(e,t)=>(+t-+e-(t.getTimezoneOffset()-e.getTimezoneOffset())*sr)/jo,(e)=>e.getDate()-1),Nwe=kf.range,S0=gt((e)=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>{return(+t-+e)/jo},(e)=>{return e.getUTCDate()-1}),Rwe=S0.range,k2=gt((e)=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>{return(+t-+e)/jo},(e)=>{return Math.floor(+e/jo)}),Lwe=k2.range;function Rs(e){return gt((t)=>{t.setDate(t.getDate()-(t.getDay()+7-e)%7),t.setHours(0,0,0,0)},(t,n)=>{t.setDate(t.getDate()+n*7)},(t,n)=>{return(+n-+t-(n.getTimezoneOffset()-t.getTimezoneOffset())*sr)/x0})}var k0=Rs(0),wf=Rs(1),KU=Rs(2),QU=Rs(3),No=Rs(4),HU=Rs(5),ZU=Rs(6),Fwe=k0.range,Iwe=wf.range,Dwe=KU.range,zwe=QU.range,Bwe=No.range,Wwe=HU.range,Uwe=ZU.range;function Ls(e){return gt((t)=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-e)%7),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCDate(t.getUTCDate()+n*7)},(t,n)=>{return(+n-+t)/x0})}var _0=Ls(0),bf=Ls(1),eP=Ls(2),tP=Ls(3),Ro=Ls(4),nP=Ls(5),rP=Ls(6),Pwe=_0.range,qwe=bf.range,Gwe=eP.range,Xwe=tP.range,Vwe=Ro.range,Ywe=nP.range,Jwe=rP.range,_2=gt((e)=>{e.setDate(1),e.setHours(0,0,0,0)},(e,t)=>{e.setMonth(e.getMonth()+t)},(e,t)=>{return t.getMonth()-e.getMonth()+(t.getFullYear()-e.getFullYear())*12},(e)=>{return e.getMonth()}),Kwe=_2.range,E2=gt((e)=>{e.setUTCDate(1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCMonth(e.getUTCMonth()+t)},(e,t)=>{return t.getUTCMonth()-e.getUTCMonth()+(t.getUTCFullYear()-e.getUTCFullYear())*12},(e)=>{return e.getUTCMonth()}),Qwe=E2.range,Gi=gt((e)=>{e.setMonth(0,1),e.setHours(0,0,0,0)},(e,t)=>{e.setFullYear(e.getFullYear()+t)},(e,t)=>{return t.getFullYear()-e.getFullYear()},(e)=>{return e.getFullYear()});Gi.every=(e)=>{return e=Math.floor(e),!isFinite(e)||!(e>0)?null:gt((t)=>{t.setFullYear(Math.floor(t.getFullYear()/e)*e),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,n)=>{t.setFullYear(t.getFullYear()+n*e)})};var Hwe=Gi.range,Xi=gt((e)=>{e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCFullYear(e.getUTCFullYear()+t)},(e,t)=>{return t.getUTCFullYear()-e.getUTCFullYear()},(e)=>{return e.getUTCFullYear()});Xi.every=(e)=>{return e=Math.floor(e),!isFinite(e)||!(e>0)?null:gt((t)=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/e)*e),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCFullYear(t.getUTCFullYear()+n*e)})};var Zwe=Xi.range;function ff(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function iP(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function E0(e){let t,n,r;if(e.length!==2)t=ff,n=(a,l)=>ff(e(a),l),r=(a,l)=>e(a)-l;else t=e===ff||e===iP?e:sP,n=e,r=e;function i(a,l,c=0,u=a.length){if(c<u){if(t(l,l)!==0)return u;do{let f=c+u>>>1;if(n(a[f],l)<0)c=f+1;else u=f}while(c<u)}return c}function s(a,l,c=0,u=a.length){if(c<u){if(t(l,l)!==0)return u;do{let f=c+u>>>1;if(n(a[f],l)<=0)c=f+1;else u=f}while(c<u)}return c}function o(a,l,c=0,u=a.length){let f=i(a,l,c,u-1);return f>c&&r(a[f-1],l)>-r(a[f],l)?f-1:f}return{left:i,center:o,right:s}}function sP(){return 0}function oP(e){return e===null?NaN:+e}var A2=E0(ff),ebe=A2.right,tbe=A2.left,nbe=E0(oP).center,rbe=$2(C2),ibe=$2(aP);function $2(e){return function(t,n,r=n){if(!((n=+n)>=0))throw RangeError("invalid rx");if(!((r=+r)>=0))throw RangeError("invalid ry");let{data:i,width:s,height:o}=t;if(!((s=Math.floor(s))>=0))throw RangeError("invalid width");if(!((o=Math.floor(o!==void 0?o:i.length/s))>=0))throw RangeError("invalid height");if(!s||!o||!n&&!r)return t;let a=n&&e(n),l=r&&e(r),c=i.slice();if(a&&l)_o(a,c,i,s,o),_o(a,i,c,s,o),_o(a,c,i,s,o),Eo(l,i,c,s,o),Eo(l,c,i,s,o),Eo(l,i,c,s,o);else if(a)_o(a,i,c,s,o),_o(a,c,i,s,o),_o(a,i,c,s,o);else if(l)Eo(l,i,c,s,o),Eo(l,c,i,s,o),Eo(l,i,c,s,o);return t}}function _o(e,t,n,r,i){for(let s=0,o=r*i;s<o;)e(t,n,s,s+=r,1)}function Eo(e,t,n,r,i){for(let s=0,o=r*i;s<r;++s)e(t,n,s,s+o,r)}function aP(e){let t=C2(e);return(n,r,i,s,o)=>{i<<=2,s<<=2,o<<=2,t(n,r,i+0,s+0,o),t(n,r,i+1,s+1,o),t(n,r,i+2,s+2,o),t(n,r,i+3,s+3,o)}}function C2(e){let t=Math.floor(e);if(t===e)return lP(e);let n=e-t,r=2*e+1;return(i,s,o,a,l)=>{if(!((a-=l)>=o))return;let c=t*s[o],u=l*t,f=u+l;for(let d=o,h=o+u;d<h;d+=l)c+=s[Math.min(a,d)];for(let d=o,h=a;d<=h;d+=l)c+=s[Math.min(a,d+u)],i[d]=(c+n*(s[Math.max(o,d-f)]+s[Math.min(a,d+f)]))/r,c-=s[Math.max(o,d-u)]}}function lP(e){let t=2*e+1;return(n,r,i,s,o)=>{if(!((s-=o)>=i))return;let a=e*r[i],l=o*e;for(let c=i,u=i+l;c<u;c+=o)a+=r[Math.min(s,c)];for(let c=i,u=s;c<=u;c+=o)a+=r[Math.min(s,c+l)],n[c]=a/t,a-=r[Math.max(i,c-l)]}}var T2=Array.prototype,sbe=T2.slice,obe=T2.map,cP=Math.sqrt(50),uP=Math.sqrt(10),fP=Math.sqrt(2);function M2(e,t,n){let r=(t-e)/Math.max(0,n),i=Math.floor(Math.log10(r)),s=r/Math.pow(10,i),o=s>=cP?10:s>=uP?5:s>=fP?2:1,a,l,c;if(i<0){if(c=Math.pow(10,-i)/o,a=Math.round(e*c),l=Math.round(t*c),a/c<e)++a;if(l/c>t)--l;c=-c}else{if(c=Math.pow(10,i)*o,a=Math.round(e/c),l=Math.round(t/c),a*c<e)++a;if(l*c>t)--l}if(l<a&&0.5<=n&&n<2)return M2(e,t,n*2);return[a,l,c]}function bE(e,t,n){return t=+t,e=+e,n=+n,M2(e,t,n)[2]}function vE(e,t,n){t=+t,e=+e,n=+n;let r=t<e,i=r?bE(t,e,n):bE(e,t,n);return(r?-1:1)*(i<0?1/-i:i)}function dP(e){return function(t,n=0,r=t.length){let i=r-(n=+n);while(i){let s=e()*i--|0,o=t[i+n];t[i+n]=t[s+n],t[s+n]=o}return t}}var abe=dP(Math.random);function O2(e,t,n,r,i,s){let o=[[Ll,1,Pi],[Ll,5,5*Pi],[Ll,15,15*Pi],[Ll,30,30*Pi],[s,1,sr],[s,5,5*sr],[s,15,15*sr],[s,30,30*sr],[i,1,qi],[i,3,3*qi],[i,6,6*qi],[i,12,12*qi],[r,1,jo],[r,2,2*jo],[n,1,x0],[t,1,wE],[t,3,3*wE],[e,1,Qg]];function a(c,u,f){let d=u<c;if(d)[c,u]=[u,c];let h=f&&typeof f.range==="function"?f:l(c,u,f),p=h?h.range(c,+u+1):[];return d?p.reverse():p}function l(c,u,f){let d=Math.abs(+u-+c)/f,h=E0(([,,g])=>g).right(o,d);if(h===o.length)return e.every(vE(+c/Qg,+u/Qg,f));if(h===0)return yf.every(Math.max(vE(+c,+u,f),1));let[p,m]=o[d/o[h-1][2]<o[h][2]/d?h-1:h];return p.every(m)}return[a,l]}var j2=O2(Xi,E2,_0,k2,S2,v2),N2=O2(Gi,_2,k0,kf,x2,b2),lbe=j2[0],cbe=j2[1],ube=N2[0],fbe=N2[1];function Hg(e){if(0<=e.y&&e.y<100){let t=new Date(-1,e.m,e.d,e.H,e.M,e.S,e.L);return t.setFullYear(e.y),t}return new Date(e.y,e.m,e.d,e.H,e.M,e.S,e.L)}function Zg(e){if(0<=e.y&&e.y<100){let t=new Date(Date.UTC(-1,e.m,e.d,e.H,e.M,e.S,e.L));return t.setUTCFullYear(e.y),t}return new Date(Date.UTC(e.y,e.m,e.d,e.H,e.M,e.S,e.L))}function jl(e,t,n){return{y:e,m:t,d:n,H:0,M:0,S:0,L:0}}function hP(e){let{dateTime:t,date:n,time:r,periods:i,days:s,shortDays:o,months:a,shortMonths:l}=e,c=Nl(i),u=Rl(i),f=Nl(s),d=Rl(s),h=Nl(o),p=Rl(o),m=Nl(a),g=Rl(a),y=Nl(l),w=Rl(l),b={a:I,A:D,b:W,B:G,c:null,d:AE,e:AE,f:FP,g:XP,G:YP,H:NP,I:RP,j:LP,L:R2,m:IP,M:DP,p:K,q:_e,Q:TE,s:ME,S:zP,u:BP,U:WP,V:UP,w:PP,W:qP,x:null,X:null,y:GP,Y:VP,Z:JP,"%":CE},v={a:se,A:P,b:ee,B:fe,c:null,d:$E,e:$E,f:ZP,g:c8,G:f8,H:KP,I:QP,j:HP,L:F2,m:e8,M:t8,p:q,q:F,Q:TE,s:ME,S:n8,u:r8,U:i8,V:s8,w:o8,W:a8,x:null,X:null,y:l8,Y:u8,Z:d8,"%":CE},x={a:_,A:E,b:A,B:$,c:M,d:_E,e:_E,f:TP,g:kE,G:SE,H:EE,I:EE,j:EP,L:CP,m:_P,M:AP,p:T,q:kP,Q:OP,s:jP,S:$P,u:wP,U:bP,V:vP,w:yP,W:xP,x:O,X:j,y:kE,Y:SE,Z:SP,"%":MP};b.x=S(n,b),b.X=S(r,b),b.c=S(t,b),v.x=S(n,v),v.X=S(r,v),v.c=S(t,v);function S(N,L){return function(z){let R=[],X=-1,Y=0,te=N.length,me,nn,Ne;if(!(z instanceof Date))z=new Date(+z);while(++X<te)if(N.charCodeAt(X)===37){if(R.push(N.slice(Y,X)),(nn=xE[me=N.charAt(++X)])!=null)me=N.charAt(++X);else nn=me==="e"?" ":"0";if(Ne=L[me])me=Ne(z,nn);R.push(me),Y=X+1}return R.push(N.slice(Y,X)),R.join("")}}function k(N,L){return function(z){let R=jl(1900,void 0,1),X=C(R,N,z+="",0),Y,te;if(X!=z.length)return null;if("Q"in R)return new Date(R.Q);if("s"in R)return new Date(R.s*1000+("L"in R?R.L:0));if(L&&!("Z"in R))R.Z=0;if("p"in R)R.H=R.H%12+R.p*12;if(R.m===void 0)R.m="q"in R?R.q:0;if("V"in R){if(R.V<1||R.V>53)return null;if(!("w"in R))R.w=1;if("Z"in R)Y=Zg(jl(R.y,0,1)),te=Y.getUTCDay(),Y=te>4||te===0?bf.ceil(Y):bf(Y),Y=S0.offset(Y,(R.V-1)*7),R.y=Y.getUTCFullYear(),R.m=Y.getUTCMonth(),R.d=Y.getUTCDate()+(R.w+6)%7;else Y=Hg(jl(R.y,0,1)),te=Y.getDay(),Y=te>4||te===0?wf.ceil(Y):wf(Y),Y=kf.offset(Y,(R.V-1)*7),R.y=Y.getFullYear(),R.m=Y.getMonth(),R.d=Y.getDate()+(R.w+6)%7}else if("W"in R||"U"in R){if(!("w"in R))R.w="u"in R?R.u%7:("W"in R)?1:0;te="Z"in R?Zg(jl(R.y,0,1)).getUTCDay():Hg(jl(R.y,0,1)).getDay(),R.m=0,R.d="W"in R?(R.w+6)%7+R.W*7-(te+5)%7:R.w+R.U*7-(te+6)%7}if("Z"in R)return R.H+=R.Z/100|0,R.M+=R.Z%100,Zg(R);return Hg(R)}}function C(N,L,z,R){let X=0,Y=L.length,te=z.length,me,nn;while(X<Y){if(R>=te)return-1;if(me=L.charCodeAt(X++),me===37){if(me=L.charAt(X++),nn=x[me in xE?L.charAt(X++):me],!nn||(R=nn(N,z,R))<0)return-1}else if(me!=z.charCodeAt(R++))return-1}return R}function T(N,L,z){let R=c.exec(L.slice(z));return R?(N.p=u.get(R[0].toLowerCase()),z+R[0].length):-1}function _(N,L,z){let R=h.exec(L.slice(z));return R?(N.w=p.get(R[0].toLowerCase()),z+R[0].length):-1}function E(N,L,z){let R=f.exec(L.slice(z));return R?(N.w=d.get(R[0].toLowerCase()),z+R[0].length):-1}function A(N,L,z){let R=y.exec(L.slice(z));return R?(N.m=w.get(R[0].toLowerCase()),z+R[0].length):-1}function $(N,L,z){let R=m.exec(L.slice(z));return R?(N.m=g.get(R[0].toLowerCase()),z+R[0].length):-1}function M(N,L,z){return C(N,t,L,z)}function O(N,L,z){return C(N,n,L,z)}function j(N,L,z){return C(N,r,L,z)}function I(N){return o[N.getDay()]}function D(N){return s[N.getDay()]}function W(N){return l[N.getMonth()]}function G(N){return a[N.getMonth()]}function K(N){return i[+(N.getHours()>=12)]}function _e(N){return 1+~~(N.getMonth()/3)}function se(N){return o[N.getUTCDay()]}function P(N){return s[N.getUTCDay()]}function ee(N){return l[N.getUTCMonth()]}function fe(N){return a[N.getUTCMonth()]}function q(N){return i[+(N.getUTCHours()>=12)]}function F(N){return 1+~~(N.getUTCMonth()/3)}return{format(N){let L=S(N+="",b);return Object.assign(L,{toString(){return N}})},parse(N){let L=k(N+="",!1);return Object.assign(L,{toString(){return N}})},utcFormat(N){let L=S(N+="",v);return Object.assign(L,{toString(){return N}})},utcParse(N){let L=k(N+="",!0);return Object.assign(L,{toString(){return N}})}}}var xE={"-":"",_:" ","0":"0"},Nt=/^\s*\d+/,pP=/^%/,mP=/[\\^$*+?|[\]().{}]/g;function ve(e,t,n){let r=e<0?"-":"",i=`${r?-e:e}`,s=i.length;return r+(s<n?Array(n-s+1).join(t)+i:i)}function gP(e){return e.replace(mP,"\\$&")}function Nl(e){return new RegExp(`^(?:${e.map(gP).join("|")})`,"i")}function Rl(e){return new Map(e.map((t,n)=>[t.toLowerCase(),n]))}function yP(e,t,n){let r=Nt.exec(t.slice(n,n+1));return r?(e.w=+r[0],n+r[0].length):-1}function wP(e,t,n){let r=Nt.exec(t.slice(n,n+1));return r?(e.u=+r[0],n+r[0].length):-1}function bP(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.U=+r[0],n+r[0].length):-1}function vP(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.V=+r[0],n+r[0].length):-1}function xP(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.W=+r[0],n+r[0].length):-1}function SE(e,t,n){let r=Nt.exec(t.slice(n,n+4));return r?(e.y=+r[0],n+r[0].length):-1}function kE(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.y=+r[0]+(+r[0]>68?1900:2000),n+r[0].length):-1}function SP(e,t,n){let r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(n,n+6));return r?(e.Z=r[1]?0:-+(r[2]+(r[3]||"00")),n+r[0].length):-1}function kP(e,t,n){let r=Nt.exec(t.slice(n,n+1));return r?(e.q=+r[0]*3-3,n+r[0].length):-1}function _P(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.m=+r[0]-1,n+r[0].length):-1}function _E(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.d=+r[0],n+r[0].length):-1}function EP(e,t,n){let r=Nt.exec(t.slice(n,n+3));return r?(e.m=0,e.d=+r[0],n+r[0].length):-1}function EE(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.H=+r[0],n+r[0].length):-1}function AP(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.M=+r[0],n+r[0].length):-1}function $P(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.S=+r[0],n+r[0].length):-1}function CP(e,t,n){let r=Nt.exec(t.slice(n,n+3));return r?(e.L=+r[0],n+r[0].length):-1}function TP(e,t,n){let r=Nt.exec(t.slice(n,n+6));return r?(e.L=Math.floor(+r[0]/1000),n+r[0].length):-1}function MP(e,t,n){let r=pP.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function OP(e,t,n){let r=Nt.exec(t.slice(n));return r?(e.Q=+r[0],n+r[0].length):-1}function jP(e,t,n){let r=Nt.exec(t.slice(n));return r?(e.s=+r[0],n+r[0].length):-1}function AE(e,t){return ve(e.getDate(),t,2)}function NP(e,t){return ve(e.getHours(),t,2)}function RP(e,t){return ve(e.getHours()%12||12,t,2)}function LP(e,t){return ve(1+kf.count(Gi(e),e),t,3)}function R2(e,t){return ve(e.getMilliseconds(),t,3)}function FP(e,t){return`${R2(e,t)}000`}function IP(e,t){return ve(e.getMonth()+1,t,2)}function DP(e,t){return ve(e.getMinutes(),t,2)}function zP(e,t){return ve(e.getSeconds(),t,2)}function BP(e){let t=e.getDay();return t===0?7:t}function WP(e,t){return ve(k0.count(Gi(e).getTime()-1,e),t,2)}function L2(e){let t=e.getDay();return t>=4||t===0?No(e):No.ceil(e)}function UP(e,t){return e=L2(e),ve(No.count(Gi(e),e)+(Gi(e).getDay()===4?1:0),t,2)}function PP(e){return e.getDay()}function qP(e,t){return ve(wf.count(Gi(e).getTime()-1,e),t,2)}function GP(e,t){return ve(e.getFullYear()%100,t,2)}function XP(e,t){return e=L2(e),ve(e.getFullYear()%100,t,2)}function VP(e,t){return ve(e.getFullYear()%1e4,t,4)}function YP(e,t){let n=e.getDay();return e=n>=4||n===0?No(e):No.ceil(e),ve(e.getFullYear()%1e4,t,4)}function JP(e){let t=e.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+ve(t/60|0,"0",2)+ve(t%60,"0",2)}function $E(e,t){return ve(e.getUTCDate(),t,2)}function KP(e,t){return ve(e.getUTCHours(),t,2)}function QP(e,t){return ve(e.getUTCHours()%12||12,t,2)}function HP(e,t){return ve(1+S0.count(Xi(e),e),t,3)}function F2(e,t){return ve(e.getUTCMilliseconds(),t,3)}function ZP(e,t){return`${F2(e,t)}000`}function e8(e,t){return ve(e.getUTCMonth()+1,t,2)}function t8(e,t){return ve(e.getUTCMinutes(),t,2)}function n8(e,t){return ve(e.getUTCSeconds(),t,2)}function r8(e){let t=e.getUTCDay();return t===0?7:t}function i8(e,t){return ve(_0.count(Xi(e).getTime()-1,e),t,2)}function I2(e){let t=e.getUTCDay();return t>=4||t===0?Ro(e):Ro.ceil(e)}function s8(e,t){return e=I2(e),ve(Ro.count(Xi(e),e)+(Xi(e).getUTCDay()===4?1:0),t,2)}function o8(e){return e.getUTCDay()}function a8(e,t){return ve(bf.count(Xi(e).getTime()-1,e),t,2)}function l8(e,t){return ve(e.getUTCFullYear()%100,t,2)}function c8(e,t){return e=I2(e),ve(e.getUTCFullYear()%100,t,2)}function u8(e,t){return ve(e.getUTCFullYear()%1e4,t,4)}function f8(e,t){let n=e.getUTCDay();return e=n>=4||n===0?Ro(e):Ro.ceil(e),ve(e.getUTCFullYear()%1e4,t,4)}function d8(){return"+0000"}function CE(){return"%"}function TE(e){return+e}function ME(e){return Math.floor(+e/1000)}var Ao,D2,h8,z2,B2;p8({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function p8(e){return Ao=hP(e),D2=Ao.format,h8=Ao.parse,z2=Ao.utcFormat,B2=Ao.utcParse,Ao}var W2="%Y-%m-%dT%H:%M:%S.%LZ";function m8(e){return e.toISOString()}var dbe=typeof Date.prototype.toISOString==="function"?m8:z2(W2);function g8(e){let t=new Date(e);return isNaN(+t)?null:t}var hbe=+new Date("2000-01-01T00:00:00.000Z")?g8:B2(W2);function y8(e){return new Date(e)}function w8(e){return e instanceof Date?+e:+new Date(+e)}function U2(e,t,n,r,i,s,o,a,l,c){let u=n2(),f=u.invert,d=u.domain,h=c(".%L"),p=c(":%S"),m=c("%I:%M"),g=c("%I %p"),y=c("%a %d"),w=c("%b %d"),b=c("%B"),v=c("%Y");function x(S){return(l(S)<S?h:a(S)<S?p:o(S)<S?m:s(S)<S?g:r(S)<S?i(S)<S?y:w:n(S)<S?b:v)(S)}return u.invert=function(S){return new Date(f(S))},u.domain=function(S){return arguments.length?d(Array.from(S,w8)):d().map(y8)},u.ticks=function(S){let k=d();return e(k[0],k[k.length-1],S==null?10:S)},u.tickFormat=function(S,k){return k==null?x:c(k)},u.nice=function(S){let k=d(),C=S;if(!C||typeof C.range!=="function")C=t(k[0],k[k.length-1],S==null?10:S);return C?d(EU(k,C)):u},u.copy=function(){return t2(u,U2(e,t,n,r,i,s,o,a,l,c))},u}function A0(){let e=U2(YU,JU,Sf,w0,y0,g0,m0,p0,Co,D2).domain([new Date(2000,0,1),new Date(2000,0,2)]);return FE.apply(e,arguments)}function Rt(e){return function(){return e}}var{abs:mbe,atan2:gbe,cos:b8,max:ybe,min:wbe,sin:C0,sqrt:Io}=Math,P2=0.000000000001,_f=Math.PI,bbe=_f/2,Y2=2*_f;var T0=Math.PI,M0=2*T0,v8=M0-0.000001;function J2(e,...t){this._+=e[0];for(let n=1,r=e.length;n<r;++n)this._+=t[n-1]+e[n]}function x8(e){let t=Math.floor(e);if(!(t>=0))throw Error(`invalid digits: ${e}`);if(t>15)return J2;let n=10**t;return function(r,...i){this._+=r[0];for(let s=1,o=r.length;s<o;++s)this._+=Math.round(i[s-1]*n)/n+r[s]}}class Ef{_x0;_y0;_x1;_y1;_;_append;constructor(e){this._x0=this._y0=this._x1=this._y1=null,this._="",this._append=e==null?J2:x8(e)}moveTo(e,t){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+t}`}closePath(){if(this._x1!==null)this._x1=this._x0,this._y1=this._y0,this._append`Z`}lineTo(e,t){this._append`L${this._x1=+e},${this._y1=+t}`}quadraticCurveTo(e,t,n,r){this._append`Q${+e},${+t},${this._x1=+n},${this._y1=+r}`}bezierCurveTo(e,t,n,r,i,s){this._append`C${+e},${+t},${+n},${+r},${this._x1=+i},${this._y1=+s}`}arcTo(e,t,n,r,i){if(e=+e,t=+t,n=+n,r=+r,i=+i,i<0)throw Error(`negative radius: ${i}`);let s=this._x1,o=this._y1,a=n-e,l=r-t,c=s-e,u=o-t,f=c*c+u*u;if(this._x1===null)this._append`M${this._x1=e},${this._y1=t}`;else if(!(f>0.000001));else if(!(Math.abs(u*a-l*c)>0.000001)||!i)this._append`L${this._x1=e},${this._y1=t}`;else{let d=n-s,h=r-o,p=a*a+l*l,m=d*d+h*h,g=Math.sqrt(p),y=Math.sqrt(f),w=i*Math.tan((T0-Math.acos((p+f-m)/(2*g*y)))/2),b=w/y,v=w/g;if(Math.abs(b-1)>0.000001)this._append`L${e+b*c},${t+b*u}`;this._append`A${i},${i},0,0,${+(u*d>c*h)},${this._x1=e+v*a},${this._y1=t+v*l}`}}arc(e,t,n,r,i,s){if(e=+e,t=+t,n=+n,s=!!s,n<0)throw Error(`negative radius: ${n}`);let o=n*Math.cos(r),a=n*Math.sin(r),l=e+o,c=t+a,u=1^s,f=s?r-i:i-r;if(this._x1===null)this._append`M${l},${c}`;else if(Math.abs(this._x1-l)>0.000001||Math.abs(this._y1-c)>0.000001)this._append`L${l},${c}`;if(!n)return;if(f<0)f=f%M0+M0;if(f>v8)this._append`A${n},${n},0,1,${u},${e-o},${t-a}A${n},${n},0,1,${u},${this._x1=l},${this._y1=c}`;else if(f>0.000001)this._append`A${n},${n},0,${+(f>=T0)},${u},${this._x1=e+n*Math.cos(i)},${this._y1=t+n*Math.sin(i)}`}rect(e,t,n,r){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+t}h${n=+n}v${+r}h${-n}Z`}toString(){return this._}}function S8(){return new Ef}Object.defineProperty(S8,Symbol.hasInstance,{value:(e)=>e instanceof Ef});function K2(e){let t=3;return e.digits=function(n){if(!arguments.length)return t;if(n==null)t=null;else{let r=Math.floor(n);if(!(r>=0))throw RangeError(`invalid digits: ${n}`);t=r}return e},()=>new Ef(t)}var vbe=Array.prototype.slice;function Q2(e){return typeof e==="object"&&"length"in e?e:Array.from(e)}function H2(e){this._context=e}H2.prototype={areaStart(){this._line=0},areaEnd(){this._line=NaN},lineStart(){this._point=0},lineEnd(){if(this._line||this._line!==0&&this._point===1)this._context.closePath();this._line=1-this._line},point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2,this._context.lineTo(e,t);break;default:this._context.lineTo(e,t);break}}};function O0(e){return new H2(e)}function Z2(e){return e[0]}function eA(e){return e[1]}function zl(e,t){let n=Rt(!0),r=null,i=O0,s=null,o=K2(a);e=typeof e==="function"?e:e===void 0?Z2:Rt(e),t=typeof t==="function"?t:t===void 0?eA:Rt(t);function a(l){let c,u=(l=Q2(l)).length,f,d=!1,h;if(r==null)s=i(h=o());for(c=0;c<=u;++c){if(!(c<u&&n(f=l[c],c,l))===d)if(d=!d)s.lineStart();else s.lineEnd();if(d)s.point(+e(f,c,l),+t(f,c,l))}if(h)return s=null,h+""||null}return a.x=function(l){return arguments.length?(e=typeof l==="function"?l:Rt(+l),a):e},a.y=function(l){return arguments.length?(t=typeof l==="function"?l:Rt(+l),a):t},a.defined=function(l){return arguments.length?(n=typeof l==="function"?l:Rt(!!l),a):n},a.curve=function(l){return arguments.length?(i=l,r!=null&&(s=i(r)),a):i},a.context=function(l){return arguments.length?(l==null?r=s=null:s=i(r=l),a):r},a}function j0(e,t,n){let r=null,i=Rt(!0),s=null,o=O0,a=null,l=K2(c);e=typeof e==="function"?e:e===void 0?Z2:Rt(+e),t=typeof t==="function"?t:t===void 0?Rt(0):Rt(+t),n=typeof n==="function"?n:n===void 0?eA:Rt(+n);function c(f){let d,h=0,p,m=(f=Q2(f)).length,g,y=!1,w,b=Array(m),v=Array(m);if(s==null)a=o(w=l());for(d=0;d<=m;++d){if(!(d<m&&i(g=f[d],d,f))===y)if(y=!y)h=d,a.areaStart(),a.lineStart();else{a.lineEnd(),a.lineStart();for(p=d-1;p>=h;--p)a.point(b[p],v[p]);a.lineEnd(),a.areaEnd()}if(y)b[d]=+e(g,d,f),v[d]=+t(g,d,f),a.point(r?+r(g,d,f):b[d],n?+n(g,d,f):v[d])}if(w)return a=null,`${w}`||null}function u(){return zl().defined(i).curve(o).context(s)}return c.x=function(f){return arguments.length?(e=typeof f==="function"?f:Rt(+f),r=null,c):e},c.x0=function(f){return arguments.length?(e=typeof f==="function"?f:Rt(+f),c):e},c.x1=function(f){return arguments.length?(r=f==null?null:typeof f==="function"?f:Rt(+f),c):r},c.y=function(f){return arguments.length?(t=typeof f==="function"?f:Rt(+f),n=null,c):t},c.y0=function(f){return arguments.length?(t=typeof f==="function"?f:Rt(+f),c):t},c.y1=function(f){return arguments.length?(n=f==null?null:typeof f==="function"?f:Rt(+f),c):n},c.lineX0=c.lineY0=function(){return u().x(e).y(t)},c.lineY1=function(){return u().x(e).y(n)},c.lineX1=function(){return u().x(r).y(t)},c.defined=function(f){return arguments.length?(i=typeof f==="function"?f:Rt(!!f),c):i},c.curve=function(f){return arguments.length?(o=f,s!=null&&(a=o(s)),c):o},c.context=function(f){return arguments.length?(f==null?s=a=null:a=o(s=f),c):s},c}function tA(e){this._curve=e}tA.prototype={areaStart(){this._curve.areaStart()},areaEnd(){this._curve.areaEnd()},lineStart(){this._curve.lineStart()},lineEnd(){this._curve.lineEnd()},point(e,t){this._curve.point(t*Math.sin(e),t*-Math.cos(e))}};function k8(e){function t(n){return new tA(e(n))}return t._curve=e,t}var xbe=k8(O0);var Sbe=Io(3);var _8=Io(0.3333333333333333),kbe=_8*2;var nA=C0(_f/10)/C0(7*_f/10),_be=C0(Y2/10)*nA,Ebe=-b8(Y2/10)*nA;var Abe=Io(3);var $be=Io(3);var Cbe=Io(3)/2,E8=1/Io(12),Tbe=(E8/2+1)*3;function Vi(){}function Lo(e,t,n){e._context.bezierCurveTo((2*e._x0+e._x1)/3,(2*e._y0+e._y1)/3,(e._x0+2*e._x1)/3,(e._y0+2*e._y1)/3,(e._x0+4*e._x1+t)/6,(e._y0+4*e._y1+n)/6)}function N0(e){this._context=e}N0.prototype={areaStart(){this._line=0},areaEnd(){this._line=NaN},lineStart(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd(){switch(this._point){case 3:Lo(this,this._x1,this._y1),this._context.lineTo(this._x1,this._y1);break;case 2:this._context.lineTo(this._x1,this._y1);break}if(this._line||this._line!==0&&this._point===1)this._context.closePath();this._line=1-this._line},point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6),Lo(this,e,t);break;default:Lo(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function A8(e){this._context=e}A8.prototype={areaStart:Vi,areaEnd:Vi,lineStart(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd(){switch(this._point){case 1:{this._context.moveTo(this._x2,this._y2),this._context.closePath();break}case 2:{this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break}case 3:{this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}}},point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._x2=e,this._y2=t;break;case 1:this._point=2,this._x3=e,this._y3=t;break;case 2:this._point=3,this._x4=e,this._y4=t,this._context.moveTo((this._x0+4*this._x1+e)/6,(this._y0+4*this._y1+t)/6);break;default:Lo(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function $8(e){this._context=e}$8.prototype={areaStart(){this._line=0},areaEnd(){this._line=NaN},lineStart(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd(){if(this._line||this._line!==0&&this._point===3)this._context.closePath();this._line=1-this._line},point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;{let n=(this._x0+4*this._x1+e)/6,r=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break}case 3:this._point=4,Lo(this,e,t);break;default:Lo(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function rA(e,t){this._basis=new N0(e),this._beta=t}rA.prototype={lineStart(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd(){let e=this._x,t=this._y,n=e.length-1;if(n>0){let r=e[0],i=t[0],s=e[n]-r,o=t[n]-i,a=-1,l;while(++a<=n)l=a/n,this._basis.point(this._beta*e[a]+(1-this._beta)*(r+l*s),this._beta*t[a]+(1-this._beta)*(i+l*o))}this._x=this._y=null,this._basis.lineEnd()},point(e,t){this._x.push(+e),this._y.push(+t)}};var Mbe=function e(t){function n(r){return t===1?new N0(r):new rA(r,t)}return n.beta=function(r){return e(+r)},n}(0.85);function Fo(e,t,n){e._context.bezierCurveTo(e._x1+e._k*(e._x2-e._x0),e._y1+e._k*(e._y2-e._y0),e._x2+e._k*(e._x1-t),e._y2+e._k*(e._y1-n),e._x2,e._y2)}function R0(e,t){this._context=e,this._k=(1-t)/6}R0.prototype={areaStart(){this._line=0},areaEnd(){this._line=NaN},lineStart(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:Fo(this,this._x1,this._y1);break}if(this._line||this._line!==0&&this._point===1)this._context.closePath();this._line=1-this._line},point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2,this._x1=e,this._y1=t;break;case 2:this._point=3,Fo(this,e,t);break;default:Fo(this,e,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var Obe=function e(t){function n(r){return new R0(r,t)}return n.tension=function(r){return e(+r)},n}(0);function L0(e,t){this._context=e,this._k=(1-t)/6}L0.prototype={areaStart:Vi,areaEnd:Vi,lineStart(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd(){switch(this._point){case 1:{this._context.moveTo(this._x3,this._y3),this._context.closePath();break}case 2:{this._context.lineTo(this._x3,this._y3),this._context.closePath();break}case 3:{this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);break}}},point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._x3=e,this._y3=t;break;case 1:this._point=2,this._context.moveTo(this._x4=e,this._y4=t);break;case 2:this._point=3,this._x5=e,this._y5=t;break;default:Fo(this,e,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var jbe=function e(t){function n(r){return new L0(r,t)}return n.tension=function(r){return e(+r)},n}(0);function F0(e,t){this._context=e,this._k=(1-t)/6}F0.prototype={areaStart(){this._line=0},areaEnd(){this._line=NaN},lineStart(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd(){if(this._line||this._line!==0&&this._point===3)this._context.closePath();this._line=1-this._line},point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4,Fo(this,e,t);break;default:Fo(this,e,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var Nbe=function e(t){function n(r){return new F0(r,t)}return n.tension=function(r){return e(+r)},n}(0);function Dl(e,t,n){let{_x1:r,_y1:i,_x2:s,_y2:o}=e;if(e._l01_a>P2){let a=2*e._l01_2a+3*e._l01_a*e._l12_a+e._l12_2a,l=3*e._l01_a*(e._l01_a+e._l12_a);r=(r*a-e._x0*e._l12_2a+e._x2*e._l01_2a)/l,i=(i*a-e._y0*e._l12_2a+e._y2*e._l01_2a)/l}if(e._l23_a>P2){let a=2*e._l23_2a+3*e._l23_a*e._l12_a+e._l12_2a,l=3*e._l23_a*(e._l23_a+e._l12_a);s=(s*a+e._x1*e._l23_2a-t*e._l12_2a)/l,o=(o*a+e._y1*e._l23_2a-n*e._l12_2a)/l}e._context.bezierCurveTo(r,i,s,o,e._x2,e._y2)}function iA(e,t){this._context=e,this._alpha=t}iA.prototype={areaStart(){this._line=0},areaEnd(){this._line=NaN},lineStart(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2);break}if(this._line||this._line!==0&&this._point===1)this._context.closePath();this._line=1-this._line},point(e,t){if(e=+e,t=+t,this._point){let n=this._x2-e,r=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,Dl(this,e,t);break;default:Dl(this,e,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var Rbe=function e(t){function n(r){return t?new iA(r,t):new R0(r,0)}return n.alpha=function(r){return e(+r)},n}(0.5);function sA(e,t){this._context=e,this._alpha=t}sA.prototype={areaStart:Vi,areaEnd:Vi,lineStart(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd(){switch(this._point){case 1:{this._context.moveTo(this._x3,this._y3),this._context.closePath();break}case 2:{this._context.lineTo(this._x3,this._y3),this._context.closePath();break}case 3:{this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);break}}},point(e,t){if(e=+e,t=+t,this._point){let n=this._x2-e,r=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._x3=e,this._y3=t;break;case 1:this._point=2,this._context.moveTo(this._x4=e,this._y4=t);break;case 2:this._point=3,this._x5=e,this._y5=t;break;default:Dl(this,e,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var Lbe=function e(t){function n(r){return t?new sA(r,t):new L0(r,0)}return n.alpha=function(r){return e(+r)},n}(0.5);function oA(e,t){this._context=e,this._alpha=t}oA.prototype={areaStart(){this._line=0},areaEnd(){this._line=NaN},lineStart(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd(){if(this._line||this._line!==0&&this._point===3)this._context.closePath();this._line=1-this._line},point(e,t){if(e=+e,t=+t,this._point){let n=this._x2-e,r=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4,Dl(this,e,t);break;default:Dl(this,e,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var Fbe=function e(t){function n(r){return t?new oA(r,t):new F0(r,0)}return n.alpha=function(r){return e(+r)},n}(0.5);function C8(e){this._context=e}C8.prototype={areaStart:Vi,areaEnd:Vi,lineStart(){this._point=0},lineEnd(){if(this._point)this._context.closePath()},point(e,t){if(e=+e,t=+t,this._point)this._context.lineTo(e,t);else this._point=1,this._context.moveTo(e,t)}};function q2(e){return e<0?-1:1}function G2(e,t,n){let r=e._x1-e._x0,i=t-e._x1,s=(e._y1-e._y0)/(r||(i<0?-0:0)),o=(n-e._y1)/(i||(r<0?-0:0)),a=(s*i+o*r)/(r+i);return(q2(s)+q2(o))*Math.min(Math.abs(s),Math.abs(o),0.5*Math.abs(a))||0}function X2(e,t){let n=e._x1-e._x0;return n?(3*(e._y1-e._y0)/n-t)/2:t}function $0(e,t,n){let{_x0:r,_y0:i,_x1:s,_y1:o}=e,a=(s-r)/3;e._context.bezierCurveTo(r+a,i+a*t,s-a,o-a*n,s,o)}function I0(e){this._context=e}I0.prototype={areaStart(){this._line=0},areaEnd(){this._line=NaN},lineStart(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:$0(this,this._t0,X2(this,this._t0));break}if(this._line||this._line!==0&&this._point===1)this._context.closePath();this._line=1-this._line},point(e,t){let n=NaN;if(e=+e,t=+t,e===this._x1&&t===this._y1)return;switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,$0(this,X2(this,n=G2(this,e,t)),n);break;default:$0(this,this._t0,n=G2(this,e,t));break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t,this._t0=n}};function aA(e){this._context=new lA(e)}aA.prototype=Object.create(I0.prototype);aA.prototype.point=function(e,t){I0.prototype.point.call(this,t,e)};function lA(e){this._context=e}lA.prototype={moveTo(e,t){this._context.moveTo(t,e)},closePath(){this._context.closePath()},lineTo(e,t){this._context.lineTo(t,e)},bezierCurveTo(e,t,n,r,i,s){this._context.bezierCurveTo(t,e,r,n,s,i)}};function T8(e){this._context=e}T8.prototype={areaStart(){this._line=0},areaEnd(){this._line=NaN},lineStart(){this._x=[],this._y=[]},lineEnd(){let e=this._x,t=this._y,n=e.length;if(n)if(this._line?this._context.lineTo(e[0],t[0]):this._context.moveTo(e[0],t[0]),n===2)this._context.lineTo(e[1],t[1]);else{let r=V2(e),i=V2(t);for(let s=0,o=1;o<n;++s,++o)this._context.bezierCurveTo(r[0][s],i[0][s],r[1][s],i[1][s],e[o],t[o])}if(this._line||this._line!==0&&n===1)this._context.closePath();this._line=1-this._line,this._x=this._y=null},point(e,t){this._x.push(+e),this._y.push(+t)}};function V2(e){let t,n=e.length-1,r,i=Array(n),s=Array(n),o=Array(n);i[0]=0,s[0]=2,o[0]=e[0]+2*e[1];for(t=1;t<n-1;++t)i[t]=1,s[t]=4,o[t]=4*e[t]+2*e[t+1];i[n-1]=2,s[n-1]=7,o[n-1]=8*e[n-1]+e[n];for(t=1;t<n;++t)r=i[t]/s[t-1],s[t]-=r,o[t]-=r*o[t-1];i[n-1]=o[n-1]/s[n-1];for(t=n-2;t>=0;--t)i[t]=(o[t]-i[t+1])/s[t];s[n-1]=(e[n]+i[n-1])/2;for(t=0;t<n-1;++t)s[t]=2*e[t+1]-i[t+1];return[i,s]}function M8(e,t){this._context=e,this._t=t}M8.prototype={areaStart(){this._line=0},areaEnd(){this._line=NaN},lineStart(){this._x=this._y=NaN,this._point=0},lineEnd(){if(0<this._t&&this._t<1&&this._point===2)this._context.lineTo(this._x,this._y);if(this._line||this._line!==0&&this._point===1)this._context.closePath();if(this._line>=0)this._t=1-this._t,this._line=1-this._line},point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:{if(this._point=2,this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(e,t);else{let n=this._x*(1-this._t)+e*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,t)}break}default:{if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(e,t);else{let n=this._x*(1-this._t)+e*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,t)}break}}this._x=e,this._y=t}};function Af(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function O8(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function cA(e){let t,n,r;if(e.length!==2)t=Af,n=(a,l)=>Af(e(a),l),r=(a,l)=>e(a)-l;else t=e===Af||e===O8?e:j8,n=e,r=e;function i(a,l,c=0,u=a.length){if(c<u){if(t(l,l)!==0)return u;do{let f=c+u>>>1;if(n(a[f],l)<0)c=f+1;else u=f}while(c<u)}return c}function s(a,l,c=0,u=a.length){if(c<u){if(t(l,l)!==0)return u;do{let f=c+u>>>1;if(n(a[f],l)<=0)c=f+1;else u=f}while(c<u)}return c}function o(a,l,c=0,u=a.length){let f=i(a,l,c,u-1);return f>c&&r(a[f-1],l)>-r(a[f],l)?f-1:f}return{left:i,center:o,right:s}}function j8(){return 0}function N8(e){return e===null?NaN:+e}var uA=cA(Af),Dbe=uA.right,zbe=uA.left,Bbe=cA(N8).center;var Wbe=fA(dA),Ube=fA(R8);function fA(e){return function(t,n,r=n){if(!((n=+n)>=0))throw RangeError("invalid rx");if(!((r=+r)>=0))throw RangeError("invalid ry");let{data:i,width:s,height:o}=t;if(!((s=Math.floor(s))>=0))throw RangeError("invalid width");if(!((o=Math.floor(o!==void 0?o:i.length/s))>=0))throw RangeError("invalid height");if(!s||!o||!n&&!r)return t;let a=n&&e(n),l=r&&e(r),c=i.slice();if(a&&l)Do(a,c,i,s,o),Do(a,i,c,s,o),Do(a,c,i,s,o),zo(l,i,c,s,o),zo(l,c,i,s,o),zo(l,i,c,s,o);else if(a)Do(a,i,c,s,o),Do(a,c,i,s,o),Do(a,i,c,s,o);else if(l)zo(l,i,c,s,o),zo(l,c,i,s,o),zo(l,i,c,s,o);return t}}function Do(e,t,n,r,i){for(let s=0,o=r*i;s<o;)e(t,n,s,s+=r,1)}function zo(e,t,n,r,i){for(let s=0,o=r*i;s<r;++s)e(t,n,s,s+o,r)}function R8(e){let t=dA(e);return(n,r,i,s,o)=>{i<<=2,s<<=2,o<<=2,t(n,r,i+0,s+0,o),t(n,r,i+1,s+1,o),t(n,r,i+2,s+2,o),t(n,r,i+3,s+3,o)}}function dA(e){let t=Math.floor(e);if(t===e)return L8(e);let n=e-t,r=2*e+1;return(i,s,o,a,l)=>{if(!((a-=l)>=o))return;let c=t*s[o],u=l*t,f=u+l;for(let d=o,h=o+u;d<h;d+=l)c+=s[Math.min(a,d)];for(let d=o,h=a;d<=h;d+=l)c+=s[Math.min(a,d+u)],i[d]=(c+n*(s[Math.max(o,d-f)]+s[Math.min(a,d+f)]))/r,c-=s[Math.max(o,d-u)]}}function L8(e){let t=2*e+1;return(n,r,i,s,o)=>{if(!((s-=o)>=i))return;let a=e*r[i],l=o*e;for(let c=i,u=i+l;c<u;c+=o)a+=r[Math.min(s,c)];for(let c=i,u=s;c<=u;c+=o)a+=r[Math.min(s,c+l)],n[c]=a/t,a-=r[Math.max(i,c-l)]}}function $f(e,t){let n,r;if(t===void 0){for(let i of e)if(i!=null)if(n===void 0){if(i>=i)n=r=i}else{if(n>i)n=i;if(r<i)r=i}}else{let i=-1;for(let s of e)if((s=t(s,++i,e))!=null)if(n===void 0){if(s>=s)n=r=s}else{if(n>s)n=s;if(r<s)r=s}}return[n,r]}var hA=Array.prototype,Pbe=hA.slice,qbe=hA.map;var Gbe=Math.sqrt(50),Xbe=Math.sqrt(10),Vbe=Math.sqrt(2);function D0(e,t){let n;if(t===void 0){for(let r of e)if(r!=null&&(n<r||n===void 0&&r>=r))n=r}else{let r=-1;for(let i of e)if((i=t(i,++r,e))!=null&&(n<i||n===void 0&&i>=i))n=i}return n}function F8(e){return function(t,n=0,r=t.length){let i=r-(n=+n);while(i){let s=e()*i--|0,o=t[i+n];t[i+n]=t[s+n],t[s+n]=o}return t}}var Ybe=F8(Math.random);function I8(e){return Math.abs(e=Math.round(e))>=1000000000000000000000?e.toLocaleString("en").replace(/,/g,""):e.toString(10)}function Tf(e,t){if(!isFinite(e)||e===0)return null;let n=t?e.toExponential(t-1):e.toExponential(),r=n.indexOf("e"),i=n.slice(0,r);return[i.length>1?i[0]+i.slice(2):i,+n.slice(r+1)]}function D8(e){let t=Tf(Math.abs(e));return t?t[1]:NaN}function z8(e,t){return function(n,r){let i=n.length,s=[],o=0,a=e[0],l=0;while(i>0&&a>0){if(l+a+1>r)a=Math.max(1,r-l);if(s.push(n.substring(i-=a,i+a)),(l+=a+1)>r)break;a=e[o=(o+1)%e.length]}return s.reverse().join(t)}}function B8(e){return function(t){return t.replace(/[0-9]/g,function(n){return e[+n]})}}var W8=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;class z0{fill;align;sign;symbol;zero;width;comma;precision;trim;type;constructor(e){this.fill=e.fill===void 0?" ":`${e.fill}`,this.align=e.align===void 0?">":`${e.align}`,this.sign=e.sign===void 0?"-":`${e.sign}`,this.symbol=e.symbol===void 0?"":`${e.symbol}`,this.zero=!!e.zero,this.width=e.width===void 0?void 0:+e.width,this.comma=!!e.comma,this.precision=e.precision===void 0?void 0:+e.precision,this.trim=!!e.trim,this.type=e.type===void 0?"":`${e.type}`}toString(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":`.${Math.max(0,this.precision|0)}`)+(this.trim?"~":"")+this.type}}function vA(e){let t=W8.exec(e);if(!t)throw Error(`invalid format: ${e}`);return new z0({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}vA.prototype=z0.prototype;var U8=vA,pA=U8;function P8(e){let t=-1,n=0;e:for(let r=e.length,i=1;i<r;++i)switch(e[i]){case".":t=n=i;break;case"0":if(t===0)t=i;n=i;break;default:if(!+e[i])break e;if(t>0)t=0;break}return t>0?e.slice(0,t)+e.slice(n+1):e}var Bl;function q8(e,t){let n=Tf(e,t);if(!n)return Bl=void 0,e.toPrecision(t);let r=n[0],i=n[1];Bl=Math.max(-8,Math.min(8,Math.floor(i/3)))*3;let s=i-Bl+1,o=r.length;return s===o?r:s>o?`${r}${Array(s-o+1).join("0")}`:s>0?`${r.slice(0,s)}.${r.slice(s)}`:`0.${Array(1-s).join("0")}${Tf(e,Math.max(0,t+s-1))[0]}`}function mA(e,t){let n=Tf(e,t);if(!n)return`${e}`;let r=n[0],i=n[1];return i<0?`0.${Array(-i).join("0")}${r}`:r.length>i+1?`${r.slice(0,i+1)}.${r.slice(i+1)}`:`${r}${Array(i-r.length+2).join("0")}`}var G8={"%":(e,t)=>(e*100).toFixed(t),b:(e)=>Math.round(e).toString(2),c:(e)=>`${e}`,d:I8,e:(e,t)=>e.toExponential(t),f:(e,t)=>e.toFixed(t),g:(e,t)=>e.toPrecision(t),o:(e)=>Math.round(e).toString(8),p:(e,t)=>mA(e*100,t),r:mA,s:q8,X:(e)=>Math.round(e).toString(16).toUpperCase(),x:(e)=>Math.round(e).toString(16)},gA=G8;function yA(e){return e}var wA=Array.prototype.map,bA=["y","z","a","f","p","n","\xB5","m","","k","M","G","T","P","E","Z","Y"];function X8(e){let t=e.grouping===void 0||e.thousands===void 0?yA:z8(wA.call(e.grouping,Number),`${e.thousands}`),n=e.currency===void 0?"":e.currency[0]+"",r=e.currency===void 0?"":e.currency[1]+"",i=e.decimal===void 0?".":`${e.decimal}`,s=e.numerals===void 0?yA:B8(wA.call(e.numerals,String)),o=e.percent===void 0?"%":`${e.percent}`,a=e.minus===void 0?"\u2212":`${e.minus}`,l=e.nan===void 0?"NaN":`${e.nan}`;function c(f,d){let h=pA(f),p=h.fill,m=h.align,g=h.sign,y=h.symbol,w=h.zero,b=h.width,v=h.comma,x=h.precision,S=h.trim,k=h.type;if(k==="n")v=!0,k="g";else if(!gA[k]){if(x===void 0)x=12;S=!0,k="g"}if(w||p==="0"&&m==="=")w=!0,p="0",m="=";let C=(d&&d.prefix!==void 0?d.prefix:"")+(y==="$"?n:y==="#"&&/[boxX]/.test(k)?`0${k.toLowerCase()}`:""),T=(y==="$"?r:/[%p]/.test(k)?o:"")+(d&&d.suffix!==void 0?d.suffix:""),_=gA[k],E=/[defgprs%]/.test(k);x=x===void 0?6:/[gprs]/.test(k)?Math.max(1,Math.min(21,x)):Math.max(0,Math.min(20,x));function A($){let M=C,O=T,j,I,D;if(k==="c")O=_($)+O,$="";else{$=+$;let K=$<0||1/$<0;if($=isNaN($)?l:_(Math.abs($),x),S)$=P8($);if(K&&+$===0&&g!=="+")K=!1;if(M=(K?g==="("?g:a:g==="-"||g==="("?"":g)+M,O=(k==="s"&&!isNaN($)&&Bl!==void 0?bA[8+Bl/3]:"")+O+(K&&g==="("?")":""),E){j=-1,I=$.length;while(++j<I)if(D=$.charCodeAt(j),48>D||D>57){O=(D===46?i+$.slice(j+1):$.slice(j))+O,$=$.slice(0,j);break}}}if(v&&!w)$=t($,1/0);let W=M.length+$.length+O.length,G=W<(b??0)?Array((b??0)-W+1).join(p):"";if(v&&w)$=t(G+$,G.length?(b??0)-O.length:1/0),G="";switch(m){case"<":$=M+$+O+G;break;case"=":$=M+G+$+O;break;case"^":{let K=G.length>>1;$=G.slice(0,K)+M+$+O+G.slice(K);break}default:$=G+M+$+O;break}return s($)}return A.toString=function(){return`${h}`},A}function u(f,d){let h=pA(f);h.type="f";let p=Math.max(-8,Math.min(8,Math.floor(D8(d)/3)))*3,m=Math.pow(10,-p),g=c(`${h}`,{suffix:bA[8+p/3]});return function(y){return g(m*y)}}return{format:c,formatPrefix:u}}var Cf,Mf,V8;Y8({thousands:",",grouping:[3],currency:["$",""]});function Y8(e){return Cf=X8(e),Mf=Cf.format,V8=Cf.formatPrefix,Cf}var Of=["#5b9cf5","#6dd97a","#e6c84d","#e25c5c","#c084fc","#f97316","#06b6d4","#ec4899"];function Wl(e,t=120,n=32,r=2){if(e.length===0)return{path:"",areaPath:"",width:t,height:n,minVal:0,maxVal:0};let i=Os().domain([0,Math.max(e.length-1,1)]).range([r,t-r]),[s,o]=$f(e),a=Os().domain([Math.min(s,0),Math.max(o,1)]).range([n-r,r]),l=zl().x((u,f)=>i(f)).y((u)=>a(u)),c=j0().x((u,f)=>i(f)).y0(n-r).y1((u)=>a(u));return{path:l(e)||"",areaPath:c(e)||"",width:t,height:n,minVal:s,maxVal:o}}function Qr(e,t=700,n=200,r={top:10,right:10,bottom:24,left:45}){let i={linePath:"",areaPath:"",points:[],xLabels:[],yLabels:[],width:t,height:n,maxValue:0};if(e.length===0)return i;let s=t-r.left-r.right,o=n-r.top-r.bottom,a=e.map((S)=>new Date(S.date)),l=e.map((S)=>S.count),c=$f(a),u=A0().domain(c).range([r.left,r.left+s]),f=D0(l)||1,d=Os().domain([0,f*1.1]).range([r.top+o,r.top]).nice(),h=zl().x((S)=>u(S.date)).y((S)=>d(S.count)),p=j0().x((S)=>u(S.date)).y0(r.top+o).y1((S)=>d(S.count)),m=e.map((S,k)=>({date:a[k],count:S.count})),g=m.map((S)=>({x:u(S.date),y:d(S.count),label:S.date.toLocaleDateString("en-US",{month:"short",day:"numeric"}),value:S.count})),w=u.ticks(5).map((S)=>({x:u(S),label:S.toLocaleDateString("en-US",{month:"short",day:"numeric"})})),b=d.ticks(4),v=Mf(".2s"),x=b.map((S)=>({y:d(S),label:S>=1000?v(S):String(S)}));return{linePath:h(m)||"",areaPath:p(m)||"",points:g,xLabels:w,yLabels:x,width:t,height:n,maxValue:f}}function Ul(e,t=400,n=28,r=6,i=120){if(e.length===0)return{bars:[],chartWidth:t,chartHeight:0};let s=e.length*(n+r),o=t-i-10,a=D0(e,(f)=>f.value)||1,l=e.reduce((f,d)=>f+d.value,0)||1,c=Os().domain([0,a]).range([0,o]);return{bars:e.map((f,d)=>({x:i,y:d*(n+r),width:Math.max(c(f.value),2),height:n,label:f.label,value:f.value,formattedValue:lt(f.value),percentage:`${(f.value/l*100).toFixed(1)}%`,color:Of[d%Of.length]})),chartWidth:t,chartHeight:s}}function xA(e,t=700,n=250,r={top:10,right:10,bottom:24,left:45}){let i={datasets:[],xLabels:[],yLabels:[],width:t,height:n};if(e.length===0)return i;let s=t-r.left-r.right,o=n-r.top-r.bottom,a=[],l=0;for(let w of e)for(let b of w.timeline)if(a.push(new Date(b.date)),b.count>l)l=b.count;if(a.length===0)return i;let c=$f(a),u=A0().domain(c).range([r.left,r.left+s]),f=Os().domain([0,Math.max(l*1.1,1)]).range([r.top+o,r.top]).nice(),d=e.map((w,b)=>{let v=w.timeline.map((k)=>({date:new Date(k.date),count:k.count})),x=zl().x((k)=>u(k.date)).y((k)=>f(k.count)),S=v.map((k)=>({x:u(k.date),y:f(k.count),label:k.date.toLocaleDateString("en-US",{month:"short",day:"numeric"}),value:k.count}));return{label:w.label,color:Of[b%Of.length],path:x(v)||"",points:S}}),p=u.ticks(5).map((w)=>({x:u(w),label:w.toLocaleDateString("en-US",{month:"short",day:"numeric"})})),m=f.ticks(4),g=Mf(".2s"),y=m.map((w)=>({y:f(w),label:w>=1000?g(w):String(w)}));return{datasets:d,xLabels:p,yLabels:y,width:t,height:n}}function lt(e){if(!Number.isFinite(e)||e<0)return"0";if(e>=1e6)return`${(e/1e6).toFixed(1)}M`;if(e>=1000)return`${(e/1000).toFixed(1)}K`;return String(Math.round(e))}import*as Fs from"crypto";var SA="ptry_";function kA(){let e=Fs.randomBytes(32).toString("hex");return`${SA}${e}`}function _A(){return Fs.randomBytes(32).toString("hex")}function Bo(e){return Fs.createHash("sha256").update(e).digest("hex")}function Nf(e){return e.startsWith(SA)}async function jf(e){return Bun.password.hash(e,{algorithm:"argon2id"})}async function EA(e,t){return Bun.password.verify(e,t)}class Rf{storage;constructor(e){this.storage=e}async signup(e,t,n){let r=e.toLowerCase().trim();if(!r||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r))throw new Re("Invalid email address",400);if(!t||t.trim().length===0)throw new Re("Name is required",400);if(!n||n.length<8)throw new Re("Password must be at least 8 characters",400);if(await this.storage.getUser(r))throw new Re("An account with this email already exists",409);let s=new Date().toISOString(),o=await jf(n),a={email:r,name:t.trim(),passwordHash:o,role:"user",createdAt:s,updatedAt:s};try{await this.storage.putUser(a)}catch(l){if(l.message?.includes("ConditionalCheckFailed"))throw new Re("An account with this email already exists",409);throw l}return{email:a.email,name:a.name,role:a.role||"user",createdAt:a.createdAt,updatedAt:a.updatedAt}}async upsertAdminUser(e,t,n){return this.upsertUserAccount(e,t,n,"admin")}async upsertUserAccount(e,t,n,r="user"){let i=e.toLowerCase().trim();if(!i||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i))throw new Re("Invalid email address",400);if(!n||n.length<8)throw new Re("Password must be at least 8 characters",400);let s=await this.storage.getUser(i),o=new Date().toISOString(),a=await jf(n),l={email:i,name:(t||s?.name||(r==="admin"?"Admin":i.split("@")[0])).trim(),passwordHash:a,role:r,createdAt:s?.createdAt||o,updatedAt:o};return await this.storage.upsertUser(l),{email:l.email,name:l.name,role:r,createdAt:l.createdAt,updatedAt:l.updatedAt}}async login(e,t){let n=e.toLowerCase().trim(),r=await this.storage.getUser(n);if(!r)throw await jf("dummy-password-for-timing-normalization"),new Re("Invalid email or password",401);if(!await EA(t,r.passwordHash))throw new Re("Invalid email or password",401);let s=_A(),o={tokenHash:Bo(s),userId:r.email,createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+2592000000).toISOString()};return await this.storage.putSession(o),{sessionToken:s,user:{email:r.email,name:r.name,role:r.role||"user",createdAt:r.createdAt,updatedAt:r.updatedAt}}}async logout(e){await this.storage.deleteSession(Bo(e))}async validateSession(e){let t=await this.storage.getSession(Bo(e));if(!t)return null;if(new Date(t.expiresAt)<new Date)return await this.storage.deleteSession(t.tokenHash),null;let n=await this.storage.getUser(t.userId);if(!n)return null;return{email:n.email,name:n.name,role:n.role||"user",createdAt:n.createdAt,updatedAt:n.updatedAt}}async createApiToken(e,t,n){if(!t||t.trim().length===0)throw new Re("Token name is required",400);if(t.length>255)throw new Re("Token name must be 255 characters or fewer",400);let r=kA(),i=new Date().toISOString(),s=n?.expiresInDays?new Date(Date.now()+n.expiresInDays*24*60*60*1000).toISOString():void 0,o={id:`${r.slice(0,8)}...${r.slice(-4)}`,name:t.trim(),userId:e,tokenHash:Bo(r),permissions:n?.permissions||["publish","read"],createdAt:i,expiresAt:s};return await this.storage.putApiToken(o),{token:r,info:{id:o.id,name:o.name,permissions:o.permissions,createdAt:o.createdAt,expiresAt:o.expiresAt}}}async listApiTokens(e){return(await this.storage.listApiTokens(e)).map((n)=>({id:n.id,name:n.name,permissions:n.permissions,createdAt:n.createdAt,lastUsedAt:n.lastUsedAt,expiresAt:n.expiresAt}))}async deleteApiToken(e,t){await this.storage.deleteApiToken(e,t)}async validatePublishToken(e,t){return this.validateAccessToken(e,t,"publish")}async validateAccessToken(e,t,n){if(t){let r=Math.max(e.length,t.length),i=Buffer.alloc(r),s=Buffer.alloc(r);if(Buffer.from(e).copy(i),Buffer.from(t).copy(s),Fs.timingSafeEqual(i,s)&&e.length===t.length)return{valid:!0,userId:"_admin"}}if(Nf(e)){let r=await this.storage.getApiTokenByHash(Bo(e));if(!r)return{valid:!1,error:"Invalid token"};if(r.expiresAt&&new Date(r.expiresAt)<new Date)return{valid:!1,error:"Token has expired"};if(!(n==="read"?r.permissions.includes("read")||r.permissions.includes("publish"):r.permissions.includes("publish")))return{valid:!1,error:`Token does not have ${n} permission`};return this.storage.updateTokenLastUsed(r.tokenHash).catch((s)=>console.warn("Failed to update token last-used:",s)),{valid:!0,userId:r.userId,tokenId:r.id}}return{valid:!1,error:"Invalid token"}}async findUser(e){let t=await this.storage.getUser(e.toLowerCase().trim());if(!t)return null;return{email:t.email,name:t.name,role:t.role||"user",subscription:t.subscription,createdAt:t.createdAt,updatedAt:t.updatedAt}}async getSubscription(e){let t=await this.storage.getUser(e.toLowerCase().trim());if(!t?.subscription)return null;return{tier:Ml(t.subscription.tier),status:t.subscription.status||"none",stripeCustomerId:t.subscription.stripeCustomerId,stripeSubscriptionId:t.subscription.stripeSubscriptionId,currentPeriodEnd:t.subscription.currentPeriodEnd,updatedAt:t.subscription.updatedAt}}async getTier(e){if(!e||e==="_admin")return"free";return B_(await this.getSubscription(e))}async setSubscription(e,t){let n=e.toLowerCase().trim(),r=await this.storage.getUser(n);if(!r)throw new Re(`No such account: ${e}`,404);let i={...r,updatedAt:new Date().toISOString()};if(!t||t.tier==="free")delete i.subscription;else i.subscription={tier:t.tier,status:t.status,stripeCustomerId:t.stripeCustomerId,stripeSubscriptionId:t.stripeSubscriptionId,currentPeriodEnd:t.currentPeriodEnd,updatedAt:new Date().toISOString()};await this.storage.upsertUser(i)}async getTeamMembers(e){return(await this.storage.getUser(e.toLowerCase().trim()))?.team?.members??[]}async getTeamOwner(e){return(await this.storage.getUser(e.toLowerCase().trim()))?.teamOwner??null}async canActFor(e,t){if(!e||!t)return!1;let n=e.toLowerCase().trim(),r=t.toLowerCase().trim();if(n===r)return!0;return await this.getTeamOwner(n)===r}async addTeamMember(e,t,n){let r=e.toLowerCase().trim(),i=t.toLowerCase().trim();if(i===r)throw new Re("You are already on your own team",400);let s=await this.storage.getUser(r);if(!s)throw new Re("No such account",404);let o=await this.storage.getUser(i);if(!o)throw new Re(`${t} does not have an account yet \u2014 they need to sign up first`,404);if(o.teamOwner&&o.teamOwner!==r)throw new Re(`${t} is already on another team`,409);if(o.team?.members?.length)throw new Re(`${t} runs their own team`,409);let a=s.team?.members??[];if(a.includes(i))return a;if(a.length+1>=n)throw new Re(`That plan includes ${n} seats, and they are all taken`,402);let l=[...a,i];return await this.storage.upsertUser({...s,team:{members:l,updatedAt:new Date().toISOString()},updatedAt:new Date().toISOString()}),await this.storage.upsertUser({...o,teamOwner:r,updatedAt:new Date().toISOString()}),l}async removeTeamMember(e,t){let n=e.toLowerCase().trim(),r=t.toLowerCase().trim(),i=await this.storage.getUser(n);if(!i)throw new Re("No such account",404);let s=(i.team?.members??[]).filter((a)=>a!==r);await this.storage.upsertUser({...i,team:{members:s,updatedAt:new Date().toISOString()},updatedAt:new Date().toISOString()});let o=await this.storage.getUser(r);if(o?.teamOwner===n){let a={...o,updatedAt:new Date().toISOString()};delete a.teamOwner,await this.storage.upsertUser(a)}return s}async findByStripeCustomer(e,t){if(t){let n=await this.getSubscription(t);if(n?.stripeCustomerId===e||!n?.stripeCustomerId){let r=await this.storage.getUser(t.toLowerCase().trim());if(r)return r.email}}return null}}class Re extends Error{status;constructor(e,t=400){super(e);this.name="AuthError",this.status=t}}class Lf{users=new Map;apiTokensByHash=new Map;apiTokensByUser=new Map;sessions=new Map;async getUser(e){return this.users.get(e.toLowerCase())||null}async putUser(e){this.users.set(e.email.toLowerCase(),e),this.onMutate()}async upsertUser(e){this.users.set(e.email.toLowerCase(),e),this.onMutate()}async getUserByEmail(e){return this.getUser(e)}async putApiToken(e){this.apiTokensByHash.set(e.tokenHash,e);let t=this.apiTokensByUser.get(e.userId)||[];t.push(e),this.apiTokensByUser.set(e.userId,t),this.onMutate()}async getApiTokenByHash(e){return this.apiTokensByHash.get(e)||null}async listApiTokens(e){return this.apiTokensByUser.get(e)||[]}async deleteApiToken(e,t){let n=this.apiTokensByUser.get(e)||[],r=n.find((i)=>i.id===t);if(r)this.apiTokensByHash.delete(r.tokenHash),this.apiTokensByUser.set(e,n.filter((i)=>i.id!==t)),this.onMutate()}async updateTokenLastUsed(e){let t=this.apiTokensByHash.get(e);if(t)t.lastUsedAt=new Date().toISOString(),this.onMutate()}async putSession(e){this.sessions.set(e.tokenHash,e),this.onMutate()}async getSession(e){return this.sessions.get(e)||null}async deleteSession(e){this.sessions.delete(e),this.onMutate()}onMutate(){}captureState(){return{users:Object.fromEntries(this.users),apiTokens:[...this.apiTokensByHash.values()],sessions:Object.fromEntries(this.sessions)}}applyState(e){if(e?.users)this.users=new Map(Object.entries(e.users));if(e?.sessions)this.sessions=new Map(Object.entries(e.sessions));if(e?.apiTokens){this.apiTokensByHash=new Map,this.apiTokensByUser=new Map;for(let t of e.apiTokens){this.apiTokensByHash.set(t.tokenHash,t);let n=this.apiTokensByUser.get(t.userId)||[];n.push(t),this.apiTokensByUser.set(t.userId,n)}}}}class B0{db;tableName;constructor(e,t="us-east-1"){this.tableName=e,this.db=new V(t)}async getUser(e){let t=await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`USER#${e.toLowerCase()}`},SK:{S:"PROFILE"}}});if(!t.Item)return null;let n=V.unmarshal(t.Item);return{email:n.email,name:n.name,passwordHash:n.passwordHash,role:n.role==="admin"?"admin":"user",...n.subscription?{subscription:JSON.parse(n.subscription)}:{},...n.team?{team:JSON.parse(n.team)}:{},...n.teamOwner?{teamOwner:n.teamOwner}:{},createdAt:n.createdAt,updatedAt:n.updatedAt}}async putUser(e){await this.db.putItem({TableName:this.tableName,Item:V.marshal({PK:`USER#${e.email.toLowerCase()}`,SK:"PROFILE",email:e.email,name:e.name,passwordHash:e.passwordHash,role:e.role||"user",...e.subscription?{subscription:JSON.stringify(e.subscription)}:{},...e.team?{team:JSON.stringify(e.team)}:{},...e.teamOwner?{teamOwner:e.teamOwner}:{},createdAt:e.createdAt,updatedAt:e.updatedAt}),ConditionExpression:"attribute_not_exists(PK)"})}async upsertUser(e){await this.db.putItem({TableName:this.tableName,Item:V.marshal({PK:`USER#${e.email.toLowerCase()}`,SK:"PROFILE",email:e.email,name:e.name,passwordHash:e.passwordHash,role:e.role||"user",...e.subscription?{subscription:JSON.stringify(e.subscription)}:{},...e.team?{team:JSON.stringify(e.team)}:{},...e.teamOwner?{teamOwner:e.teamOwner}:{},createdAt:e.createdAt,updatedAt:e.updatedAt})})}async getUserByEmail(e){return this.getUser(e)}async putApiToken(e){await this.db.putItem({TableName:this.tableName,Item:V.marshal({PK:`USER#${e.userId}`,SK:`API_TOKEN#${e.id}`,id:e.id,name:e.name,userId:e.userId,tokenHash:e.tokenHash,permissions:e.permissions,createdAt:e.createdAt,...e.lastUsedAt?{lastUsedAt:e.lastUsedAt}:{},...e.expiresAt?{expiresAt:e.expiresAt}:{}})}),await this.db.putItem({TableName:this.tableName,Item:V.marshal({PK:`TOKEN_HASH#${e.tokenHash}`,SK:"METADATA",id:e.id,name:e.name,userId:e.userId,tokenHash:e.tokenHash,permissions:e.permissions,createdAt:e.createdAt,...e.lastUsedAt?{lastUsedAt:e.lastUsedAt}:{},...e.expiresAt?{expiresAt:e.expiresAt}:{}})})}async getApiTokenByHash(e){let t=await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`TOKEN_HASH#${e}`},SK:{S:"METADATA"}}});if(!t.Item)return null;let n=V.unmarshal(t.Item);return{id:n.id,name:n.name,userId:n.userId,tokenHash:n.tokenHash,permissions:n.permissions||["publish","read"],createdAt:n.createdAt,lastUsedAt:n.lastUsedAt||void 0,expiresAt:n.expiresAt||void 0}}async listApiTokens(e){return(await this.db.query({TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :prefix)",ExpressionAttributeValues:{":pk":{S:`USER#${e}`},":prefix":{S:"API_TOKEN#"}}})).Items.map((n)=>{let r=V.unmarshal(n);return{id:r.id,name:r.name,userId:r.userId,tokenHash:r.tokenHash,permissions:r.permissions||["publish","read"],createdAt:r.createdAt,lastUsedAt:r.lastUsedAt||void 0,expiresAt:r.expiresAt||void 0}})}async deleteApiToken(e,t){let n=await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`USER#${e}`},SK:{S:`API_TOKEN#${t}`}}});if(n.Item){let r=V.unmarshal(n.Item);if(r.tokenHash)await this.db.deleteItem({TableName:this.tableName,Key:{PK:{S:`TOKEN_HASH#${r.tokenHash}`},SK:{S:"METADATA"}}});await this.db.deleteItem({TableName:this.tableName,Key:{PK:{S:`USER#${e}`},SK:{S:`API_TOKEN#${t}`}}})}}async updateTokenLastUsed(e){let t=new Date().toISOString();await this.db.updateItem({TableName:this.tableName,Key:{PK:{S:`TOKEN_HASH#${e}`},SK:{S:"METADATA"}},UpdateExpression:"SET lastUsedAt = :now",ExpressionAttributeValues:{":now":{S:t}}})}async putSession(e){await this.db.putItem({TableName:this.tableName,Item:V.marshal({PK:`SESSION#${e.tokenHash}`,SK:"METADATA",tokenHash:e.tokenHash,userId:e.userId,createdAt:e.createdAt,expiresAt:e.expiresAt})})}async getSession(e){let t=await this.db.getItem({TableName:this.tableName,Key:{PK:{S:`SESSION#${e}`},SK:{S:"METADATA"}}});if(!t.Item)return null;let n=V.unmarshal(t.Item);if(n.expiresAt&&new Date(n.expiresAt)<new Date)return await this.deleteSession(e),null;return{tokenHash:n.tokenHash,userId:n.userId,createdAt:n.createdAt,expiresAt:n.expiresAt}}async deleteSession(e){await this.db.deleteItem({TableName:this.tableName,Key:{PK:{S:`SESSION#${e}`},SK:{S:"METADATA"}}})}}class AA extends Lf{snapshot;loaded;constructor(e){super();this.snapshot=new Cr(e.s3,e.bucket,e.key||"auth/registry-auth.json",()=>this.captureState()),this.loaded=this.snapshot.load().then((t)=>{if(t)this.applyState(t)})}ready(){return this.loaded}onMutate(){this.snapshot.scheduleSave()}async flush(){await this.snapshot.flush()}}function W0(e,t){let n=process.env.S3_BUCKET,r=ot();if(r.provider!=="aws"&&n&&n!=="local")return new AA({s3:et(r),bucket:n});let i=e||process.env.DYNAMODB_TABLE||"local";if(i&&i!=="local")return new B0(i,t||process.env.AWS_REGION||"us-east-1");return new Lf}function $A(e=process.env){return(e.REGISTRY_PLUGINS||"").split(",").map((t)=>t.trim()).filter(Boolean)}function J8(e,t){if(!e||typeof e!=="object"||typeof e.name!=="string")throw TypeError(`Registry plugin "${t}" must default-export an object with a \`name\` (or a function returning one)`);return e}async function CA(e){let t=e.startsWith(".")?new URL(e,`file://${process.cwd()}/`).href:e,n;try{n=await import(t)}catch(s){throw Error(`Failed to load registry plugin "${e}": ${s.message}`)}let r=n.default,i=typeof r==="function"?await r():r;return J8(i,e)}var Wo=null;function Pl(e=process.env){if(Wo)return Wo;let t=$A(e);return Wo=t.length===0?Promise.resolve([]):Promise.all(t.map(CA)).then((n)=>{return console.log(`Loaded ${n.length} registry plugin(s): ${n.map((r)=>r.name).join(", ")}`),n}),Wo}function K8(e){Wo=Promise.resolve(e)}function Q8(){Wo=null}async function U0(){return(await Pl()).some((t)=>typeof t.authorizeRead==="function")}async function P0(e){let t=await Pl(),n;for(let r of t){if(!r.authorizeRead)continue;let i;try{i=await r.authorizeRead(e)}catch(s){return console.error(`Registry plugin "${r.name}" authorizeRead threw:`,s),"deny"}if(i==="deny")return"deny";if(i==="allow")n="allow"}return n}async function q0(e,t){let n=await Pl();for(let r of n){if(!r.handleRequest)continue;try{let i=await r.handleRequest(e,t);if(i)return i}catch(i){return console.error(`Registry plugin "${r.name}" handleRequest threw:`,i),Response.json({error:"Plugin error"},{status:500})}}return null}function Ff(e){Pl().then((t)=>{for(let n of t){if(!n.onEvent)continue;try{let r=n.onEvent(e);if(r&&typeof r.catch==="function")r.catch((i)=>console.error(`Registry plugin "${n.name}" onEvent rejected:`,i))}catch(r){console.error(`Registry plugin "${n.name}" onEvent threw:`,r)}}}).catch(()=>{})}function TA(e){if(!e)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function H8(e){if(e==null)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"}function Is(e=process.env){let t=(e.REGISTRY_VISIBILITY??e.PANTRY_REGISTRY_VISIBILITY??"").trim().toLowerCase();if(t==="private")return"private";if(t==="public")return"public";if(TA(e.REGISTRY_PRIVATE))return"private";return"public"}function Uo(e=process.env,t=Is(e)){let n=e.REGISTRY_ALLOW_SIGNUP;if(TA(n))return!0;if(H8(n))return!1;return t==="public"}function MA(e=process.env){return(e.REGISTRY_SIGNUP_DOMAINS||"").split(",").map((t)=>t.trim().toLowerCase().replace(/^@/,"")).filter(Boolean)}function G0(e,t=process.env){let n=MA(t);if(n.length===0)return!0;let r=e.toLowerCase().trim().split("@")[1]||"";return n.includes(r)}var Z8=new Set(["/health","/ready","/api/registry-info","/login","/signup","/auth/login","/auth/logout","/auth/signup","/auth/me","/favicon.ico","/robots.txt","/webhooks/stripe"]);function OA(e=process.env){return(e.REGISTRY_PUBLIC_PATHS||"").split(",").map((t)=>t.trim()).filter(Boolean)}function jA(e,t=process.env){if(Z8.has(e))return!0;for(let n of OA(t)){if(n==="/"){if(e==="/")return!0;continue}if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return!0}return!1}function e6(e){if(e.method!=="GET")return!1;return(e.headers.get("accept")||"").includes("text/html")}async function X0(e,t,n){let r=n.env??process.env,i=n.visibility??Is(r),s=t.pathname,o=n.corsHeaders??{},a=i==="public"||jA(s,r),l={authenticated:!1,userId:null},c=a&&!await U0()?l:await n.identify(e),u=await P0({req:e,url:t,path:s,method:e.method,visibility:i,userId:c.userId});if(u==="allow")return null;if(u!=="deny"){if(a)return null;if(c.authenticated)return Ff({type:"access-granted",path:s,method:e.method,userId:c.userId}),null}let f=u==="deny"?"Denied by access policy":"Authentication required";if(Ff({type:"access-denied",path:s,method:e.method,reason:f}),e6(e)&&u!=="deny")return new Response(null,{status:302,headers:{...o,Location:`/login?next=${encodeURIComponent(s+t.search)}`}});let d=r.BASE_URL||t.origin;return Response.json({error:f,...u==="deny"?{}:{hint:`This registry is private. Store a token with: pantry token set --registry ${d}`,docs:"https://pantry.dev/self-hosting"}},{status:u==="deny"?403:401,headers:{...o,...u==="deny"?{}:{"WWW-Authenticate":'Bearer realm="pantry-registry"'}}})}function V0(e=process.env,t){let n=Is(e),r=(t||e.BASE_URL||"").replace(/\/$/,"");return{visibility:n,requiresAuth:n==="private",signupsEnabled:Uo(e,n),...r?{loginUrl:`${r}/login`}:{},docs:"https://pantry.dev/self-hosting"}}function If(e){return e.toLowerCase().trim().replace(/[^a-z0-9._@-]/g,"_").replace(/@/g,"_at_")}function NA(e){let t=String(e||"").trim();if(!t||t.length>200)return null;if(t.includes("..")||t.startsWith("/"))return null;if(!/^[\w@./+-]+$/.test(t))return null;return t.replace(/\//g,"_")}async function t6(e){let t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map((n)=>n.toString(16).padStart(2,"0")).join("")}function n6(e,t){if(!e)return!0;let[n,r]=e.split("-");if(n!=="sha256"||!r)return!0;try{return Array.from(Buffer.from(r,"base64")).map((s)=>s.toString(16).padStart(2,"0")).join("")===t}catch{return!0}}var r6=async(e)=>{let t=await fetch(e,{redirect:"follow"});if(!t.ok)throw Error(`HTTP ${t.status}`);return t.arrayBuffer()};class Y0{storage;fetcher;maxArtifactBytes;maxEntries;constructor(e,t={}){this.storage=e,this.fetcher=t.fetcher||r6,this.maxArtifactBytes=t.maxArtifactBytes??209715200,this.maxEntries=t.maxEntries??2000}indexKey(e){return`mirror/${If(e)}/index.json`}async getIndex(e){try{let t=await this.storage.download(this.indexKey(e)),n=JSON.parse(new TextDecoder().decode(t));if(n&&Array.isArray(n.entries))return n}catch{}return{org:e,updatedAt:new Date().toISOString(),entries:[]}}async putIndex(e){let t=new TextEncoder().encode(JSON.stringify(e)).buffer;await this.storage.upload(this.indexKey(e.org),t)}async snapshot(e,t){let n=await this.getIndex(e),r=new Map(n.entries.map((c)=>[`${c.name}@${c.version}:${c.integrity||""}`,c])),i=0,s=0,o=0,a=[];for(let c of t.slice(0,this.maxEntries)){let u=NA(c.name),f=NA(c.version);if(!u||!f){o++;continue}let d=`${c.name}@${c.version}:${c.integrity||""}`,h=r.get(d);if(h?.key){s++,a.push(h);continue}let p={...c,mirroredAt:new Date().toISOString()};if(!c.resolved){p.error="no download URL",o++,r.set(d,p),a.push(p);continue}try{let m=await this.fetcher(c.resolved);if(m.byteLength>this.maxArtifactBytes)p.error=`artifact is larger than the ${Math.round(this.maxArtifactBytes/1048576)}MB mirror limit`,o++;else{let g=await t6(m);if(!n6(c.integrity,g))p.error="integrity mismatch \u2014 upstream bytes differ from the lockfile",o++;else{let y=`mirror/${If(e)}/${u}/${f}/${g.slice(0,32)}.tgz`;await this.storage.upload(y,m),p.key=y,p.size=m.byteLength,p.sha256=g,i++}}}catch(m){p.error=m.message,o++}r.set(d,p),a.push(p)}let l={org:e,updatedAt:new Date().toISOString(),entries:[...r.values()]};return await this.putIndex(l),{mirrored:i,skipped:s,failed:o,entries:a}}async fetchArtifact(e,t,n){let i=(await this.getIndex(e)).entries.filter((s)=>s.name===t&&s.version===n&&s.key).sort((s,o)=>o.mirroredAt.localeCompare(s.mirroredAt));for(let s of i)try{return{bytes:await this.storage.download(s.key),record:s}}catch{}return null}async list(e){return[...(await this.getIndex(e)).entries].sort((n,r)=>r.mirroredAt.localeCompare(n.mirroredAt))}async stats(e){let t=await this.list(e);return{artifacts:t.length,stored:t.filter((n)=>n.key).length,bytes:t.reduce((n,r)=>n+(r.size||0),0),failed:t.filter((n)=>n.error).length}}}function J0(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=="object")continue;let r=n;if(typeof r.name!=="string"||typeof r.version!=="string")continue;t.push({name:r.name,version:r.version,resolved:typeof r.resolved==="string"?r.resolved:void 0,integrity:typeof r.integrity==="string"?r.integrity:void 0,ecosystem:typeof r.ecosystem==="string"?r.ecosystem:void 0,license:typeof r.license==="string"?r.license:void 0})}return t}var RA={critical:0,high:1,moderate:2,low:3,unknown:4};function i6(e){switch((e||"npm").toLowerCase()){case"npm":return"npm";case"pypi":case"python":return"PyPI";case"cargo":case"crates":return"crates.io";case"go":return"Go";case"composer":case"packagist":return"Packagist";case"rubygems":case"gem":return"RubyGems";case"maven":return"Maven";case"nuget":return"NuGet";default:return""}}function s6(e){let t=e?.database_specific?.severity||e?.affected?.[0]?.database_specific?.severity;if(typeof t==="string"){let r=t.toLowerCase();if(r==="critical"||r==="high"||r==="moderate"||r==="low")return r;if(r==="medium")return"moderate"}let n=e?.severity?.find((r)=>r.type?.startsWith("CVSS"))?.score;if(typeof n==="string"){let r=n.match(/\/(?:AV|A):/)?null:Number.parseFloat(n);if(r!==null&&Number.isFinite(r)){if(r>=9)return"critical";if(r>=7)return"high";if(r>=4)return"moderate";if(r>0)return"low"}}return"unknown"}function o6(e){for(let t of e?.affected||[])for(let n of t?.ranges||[])for(let r of n?.events||[])if(r?.fixed)return String(r.fixed);return}var a6=async(e)=>{let t=e.map((i)=>({entry:i,ecosystem:i6(i.ecosystem)})).filter((i)=>i.ecosystem),n=new Map;if(t.length===0)return n;let r=500;for(let i=0;i<t.length;i+=r){let s=t.slice(i,i+r),o=await fetch("https://api.osv.dev/v1/querybatch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({queries:s.map((c)=>({package:{name:c.entry.name,ecosystem:c.ecosystem},version:c.entry.version}))})});if(!o.ok)throw Error(`OSV responded ${o.status}`);let l=(await o.json()).results||[];for(let c=0;c<s.length;c++){let u=(l[c]?.vulns||[]).map((d)=>d.id).slice(0,25);if(u.length===0)continue;let f=[];for(let d of u)try{let h=await fetch(`https://api.osv.dev/v1/vulns/${encodeURIComponent(d)}`),p=h.ok?await h.json():null;f.push({type:"vulnerability",package:s[c].entry.name,version:s[c].entry.version,ecosystem:s[c].ecosystem,id:d,severity:p?s6(p):"unknown",summary:p?.summary||p?.details?.slice(0,200)||d,url:`https://osv.dev/vulnerability/${d}`,fixedIn:p?o6(p):void 0})}catch{f.push({type:"vulnerability",package:s[c].entry.name,version:s[c].entry.version,ecosystem:s[c].ecosystem,id:d,severity:"unknown",summary:d,url:`https://osv.dev/vulnerability/${d}`})}n.set(`${s[c].entry.name}@${s[c].entry.version}`,f)}}return n};function K0(e){return e.trim().toUpperCase()}function l6(e,t){if(!t||!t.allow?.length&&!t.deny?.length)return null;let n=e.license?.trim();if(!n){if(!t.allow?.length)return null;return{type:"license",package:e.name,version:e.version,license:"unknown",reason:"unknown",summary:`${e.name}@${e.version} does not declare a licence, and your policy allows only: ${t.allow.join(", ")}`}}let r=K0(n);if(t.deny?.some((i)=>K0(i)===r))return{type:"license",package:e.name,version:e.version,license:n,reason:"denied",summary:`${e.name}@${e.version} is ${n}, which your policy denies`};if(t.allow?.length&&!t.allow.some((i)=>K0(i)===r))return{type:"license",package:e.name,version:e.version,license:n,reason:"not-allowed",summary:`${e.name}@${e.version} is ${n}, which is not in your allowed list`};return null}class Q0{storage;fetcher;constructor(e,t=a6){this.storage=e;this.fetcher=t}key(e){return`security/${If(e)}/watch.json`}async getWatchList(e){try{let t=await this.storage.download(this.key(e)),n=JSON.parse(new TextDecoder().decode(t));if(n&&Array.isArray(n.entries))return n}catch{}return{org:e,entries:[],updatedAt:new Date().toISOString()}}async setWatchList(e,t,n){let r=await this.getWatchList(e),i={org:e,entries:t,policy:n??r.policy,updatedAt:new Date().toISOString()},s=new TextEncoder().encode(JSON.stringify(i)).buffer;return await this.storage.upload(this.key(e),s),i}async setPolicy(e,t){let n=await this.getWatchList(e);return this.setWatchList(e,n.entries,t)}async report(e){let t=await this.getWatchList(e),n=[],r;try{let s=await this.fetcher(t.entries);for(let o of s.values())n.push(...o)}catch(s){r=`advisory lookup failed: ${s.message}`}for(let s of t.entries){let o=l6(s,t.policy);if(o)n.push(o)}n.sort((s,o)=>{let a=s.type==="vulnerability"?RA[s.severity]:5,l=o.type==="vulnerability"?RA[o.severity]:5;return a-l||s.package.localeCompare(o.package)});let i={critical:0,high:0,moderate:0,low:0,license:0};for(let s of n)if(s.type==="license")i.license++;else if(s.severity!=="unknown")i[s.severity]++;return{org:e,generatedAt:new Date().toISOString(),watched:t.entries.length,alerts:n,counts:i,...r?{degraded:r}:{}}}}function H0(e){if(!e||typeof e!=="object")return;let t=e,n=(s)=>Array.isArray(s)?s.filter((o)=>typeof o==="string"&&o.length<100).slice(0,200):void 0,r=n(t.allow),i=n(t.deny);if(!r&&!i)return;return{...r?{allow:r}:{},...i?{deny:i}:{}}}function FA(e){let t=(e.ecosystem||"npm").toLowerCase(),[n,r]=e.name.startsWith("@")?[e.name.slice(0,e.name.indexOf("/")),e.name.slice(e.name.indexOf("/")+1)]:[null,e.name],i=n?`${encodeURIComponent(n)}/`:"";return`pkg:${t}/${i}${encodeURIComponent(r)}@${encodeURIComponent(e.version)}`}function LA(e){let t=[];if(e.sha256)t.push({alg:"SHA-256",content:e.sha256});if(e.integrity?.startsWith("sha512-"))try{let n=Array.from(Buffer.from(e.integrity.slice(7),"base64")).map((r)=>r.toString(16).padStart(2,"0")).join("");t.push({alg:"SHA-512",content:n})}catch{}return t}function c6(e,t){let n=t.timestamp||new Date().toISOString();return{bomFormat:"CycloneDX",specVersion:"1.5",serialNumber:`urn:uuid:${t.documentId||zA(t.org,n)}`,version:1,metadata:{timestamp:n,tools:[{vendor:"pantry",name:"pantry-registry",version:"1"}],component:{type:"application",name:t.subject||t.org,version:n.slice(0,10)}},components:e.map((r)=>({type:"library",name:r.name,version:r.version,purl:FA(r),...r.license?{licenses:[{license:{id:r.license}}]}:{},...LA(r).length?{hashes:LA(r)}:{},...r.resolved?{externalReferences:[{type:"distribution",url:r.resolved}]}:{},properties:[{name:"pantry:mirrored",value:r.key?"true":"false"},...r.mirroredAt?[{name:"pantry:mirroredAt",value:r.mirroredAt}]:[]]}))}}function u6(e,t){let n=t.timestamp||new Date().toISOString(),r=t.subject||t.org,i=e.map((s,o)=>({SPDXID:`SPDXRef-Package-${o}`,name:s.name,versionInfo:s.version,downloadLocation:s.resolved||"NOASSERTION",filesAnalyzed:!1,licenseConcluded:s.license||"NOASSERTION",licenseDeclared:s.license||"NOASSERTION",copyrightText:"NOASSERTION",externalRefs:[{referenceCategory:"PACKAGE-MANAGER",referenceType:"purl",referenceLocator:FA(s)}],...s.sha256?{checksums:[{algorithm:"SHA256",checksumValue:s.sha256}]}:{}}));return{spdxVersion:"SPDX-2.3",dataLicense:"CC0-1.0",SPDXID:"SPDXRef-DOCUMENT",name:r,documentNamespace:`https://pantry.dev/sbom/${encodeURIComponent(t.org)}/${t.documentId||zA(t.org,n)}`,creationInfo:{created:n,creators:["Tool: pantry-registry"]},packages:i,relationships:i.map((s)=>({spdxElementId:"SPDXRef-DOCUMENT",relatedSpdxElement:s.SPDXID,relationshipType:"DESCRIBES"}))}}function IA(e,t,n){return t==="spdx"?u6(e,n):c6(e,n)}function DA(e){return String(e||"").toLowerCase()==="spdx"?"spdx":"cyclonedx"}function zA(e,t){let n=`${e}:${t}`,r=2166136261,i=16777619;for(let u=0;u<n.length;u++)r=Math.imul(r^n.charCodeAt(u),16777619)>>>0,i=Math.imul(i+n.charCodeAt(u)+u,2246822507)>>>0;let s=(u)=>u.toString(16).padStart(8,"0"),o=s(r),a=s(i),l=s((r^i)>>>0),c=s(r+i>>>0);return`${o}-${a.slice(0,4)}-4${a.slice(5,8)}-a${l.slice(1,4)}-${l.slice(4)}${c}`}import{readdirSync as f6,readFileSync as BA}from"fs";import{join as d6,relative as h6,sep as Z0}from"path";var WA=["darwin-arm64","darwin-x86-64","linux-x86-64","linux-arm64"];function UA(e){let t=[],n=(r)=>{for(let i of f6(r,{withFileTypes:!0})){let s=d6(r,i.name);if(i.isDirectory())n(s);else if(i.isFile()&&i.name.endsWith(".ts"))t.push(s)}};return n(e),t}function p6(e){let t=e.match(/\bdomain:\s*(['"])([^'"]+)\1\s+as const/)?.[2],n=e.match(/\bversions:\s*\[([\s\S]*?)\]\s+as const/)?.[1];if(!t||n===void 0)return null;let r=[...n.matchAll(/['"]([^'"]+)['"]/g)].map((i)=>i[1]);return{domain:t,versions:r}}function PA(e){let t=new Map;for(let n of UA(e)){if(n.endsWith(`${Z0}index.ts`)||n.endsWith(`${Z0}aliases.ts`))continue;let r=p6(BA(n,"utf8"));if(r)t.set(r.domain,new Set(r.versions))}return t}function m6(e){let t=new Set;for(let n of e){let r=n.trim().replace(/^['"]|['"]$/g,"");if(!r)continue;let[i,s]=r.split("/"),o=s==="aarch64"||s==="arm64"?"arm64":s==="x86-64"||s==="x86_64"?"x86-64":s;if(i==="darwin")if(o)t.add(`darwin-${o}`);else t.add("darwin-arm64"),t.add("darwin-x86-64");else if(i==="linux")if(o)t.add(`linux-${o}`);else t.add("linux-arm64"),t.add("linux-x86-64")}return[...t].filter((n)=>WA.includes(n))}function qA(e){let t=new Map;for(let n of UA(e)){let i=BA(n,"utf8").match(/platforms:\s*\[([^\]]*)\]/);if(!i)continue;let s=m6(i[1].split(","));if(s.length>0&&s.length<WA.length){let o=h6(e,n).replace(/\.ts$/,"").split(Z0).join("/");t.set(o,s)}}return t}import{createHmac as g6,randomUUID as y6,timingSafeEqual as w6}from"crypto";var VA=1073741824,b6=3600,YA=16,ey=".pantry-staging/malware";class zf{s3;bucket;constructor(e,t){this.s3=e;this.bucket=t}getObject(e){return this.s3.getObjectBuffer(this.bucket,e)}async getObjectStream(e){let{body:t}=await this.s3.getObjectStream(this.bucket,e);return{async*[Symbol.asyncIterator](){let n=t.getReader();try{while(!0){let r=await n.read();if(r.done)break;yield r.value}}finally{n.releaseLock?.()}}}}putObject(e,t,n){return this.s3.putObject({bucket:this.bucket,key:e,body:t,contentType:n})}copyObject(e,t){return this.s3.copyObject(this.bucket,e,t)}deleteObject(e){return this.s3.deleteObject(this.bucket,e)}headObject(e){return this.s3.headObject(this.bucket,e)}createUploadUrl(e,t,n){return this.s3.generatePresignedPutUrl(this.bucket,e,t,n)}}class ie extends Error{status;code;scan;constructor(e,t,n,r){super(e);this.status=t;this.code=n;this.scan=r}}var JA=/^[a-z0-9](?:[a-z0-9._-]|\/(?=[a-z0-9])){0,213}$/i,KA=/^[a-z0-9._+-]{1,64}$/i,QA=/^(?:darwin|linux|windows|freebsd)-(?:arm64|x86-64|x86|riscv64)$/,v6=/^[a-z0-9][a-z0-9._+-]{0,239}\.tar\.gz$/i,HA=/^[a-f0-9]{64}$/;function Df(e,t=VA){if(!e||typeof e!=="object")throw new ie("Publish request must be an object",400,"INVALID_BINARY_PUBLISH");let n=e,r=typeof n.domain==="string"?n.domain.trim():"",i=typeof n.version==="string"?n.version.trim():"",s=typeof n.filename==="string"?n.filename.trim():"",o=typeof n.sha256==="string"?n.sha256.toLowerCase():"",a=typeof n.size==="number"?n.size:Number.NaN,l=Array.isArray(n.platforms)?[...new Set(n.platforms.filter((c)=>typeof c==="string").map((c)=>c.trim()))]:[];if(!JA.test(r)||r.includes("..")||r.endsWith("/"))throw new ie("Invalid binary package domain",422,"INVALID_BINARY_DOMAIN");if(!KA.test(i))throw new ie("Invalid binary package version",422,"INVALID_BINARY_VERSION");if(!v6.test(s)||s.includes(".."))throw new ie("Invalid binary artifact filename",422,"INVALID_BINARY_FILENAME");if(l.length===0||l.length>YA||l.some((c)=>!QA.test(c)))throw new ie("One or more binary platforms are invalid",422,"INVALID_BINARY_PLATFORM");if(!Number.isSafeInteger(a)||a<=0||a>t)throw new ie(`Binary artifact size must be between 1 and ${t} bytes`,413,"INVALID_BINARY_SIZE");if(!HA.test(o))throw new ie("Binary artifact SHA-256 must be 64 lowercase hexadecimal characters",422,"INVALID_BINARY_SHA256");return{domain:r,version:i,platforms:l,filename:s,size:a,sha256:o}}function x6(e){if(!e||typeof e!=="object")throw new ie("Rescan request must be an object",400,"INVALID_BINARY_RESCAN");let t=e,n=typeof t.domain==="string"?t.domain.trim():"",r=typeof t.version==="string"?t.version.trim():"",i=Array.isArray(t.platforms)?[...new Set(t.platforms.filter((s)=>typeof s==="string").map((s)=>s.trim()))]:[];if(!JA.test(n)||n.includes("..")||n.endsWith("/"))throw new ie("Invalid binary package domain",422,"INVALID_BINARY_DOMAIN");if(!KA.test(r))throw new ie("Invalid binary package version",422,"INVALID_BINARY_VERSION");if(i.length===0||i.length>YA||i.some((s)=>!QA.test(s)))throw new ie("One or more binary platforms are invalid",422,"INVALID_BINARY_PLATFORM");return{domain:n,version:r,platforms:i}}function ty(e){try{return decodeURIComponent(new URL(e).pathname.replace(/^\/+/,""))}catch{return decodeURIComponent(e.replace(/^\/+/,""))}}function S6(e){return Buffer.from(e).toString("base64url")}function k6(e){return Buffer.from(e,"base64url").toString("utf8")}function GA(e,t){return g6("sha256",t).update(e).digest("base64url")}function _6(e,t){let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&w6(n,r)}function XA(e){let t=e["content-length"]||e["Content-Length"];if(!t)return null;let n=Number.parseInt(t,10);return Number.isSafeInteger(n)&&n>=0?n:null}function E6(e,t){let n=e.split(/[.+_-]/),r=t.split(/[.+_-]/);for(let i=0;i<Math.max(n.length,r.length);i++){let s=Number(n[i]||0),o=Number(r[i]||0);if(Number.isFinite(s)&&Number.isFinite(o)&&s!==o)return s>o;let a=(n[i]||"").localeCompare(r[i]||"");if(a!==0)return a>0}return!1}function Ds(e){return`${e}.scan.json`}function ny(e,t=()=>!1){let n=structuredClone(e);n.versions||={};for(let[r,i]of Object.entries(n.versions)){let s=i.platforms||{};for(let[o,a]of Object.entries(s))if(!t(n.name,r,o)&&a?.malwareScan?.verdict!=="clean")delete s[o];if(Object.keys(s).length===0)delete n.versions[r]}if(!n.versions[n.latestVersion])n.latestVersion=Object.keys(n.versions).sort((r,i)=>i.localeCompare(r,void 0,{numeric:!0})).at(0)||"";return n}class Bf{store;scanner;options;maxBytes;stagingTtlSeconds;now;locks=new Map;constructor(e,t,n){this.store=e;this.scanner=t;this.options=n;if(!n.tokenSecret||n.tokenSecret.length<16)throw Error("binary staging token secret must contain at least 16 characters");this.maxBytes=n.maxBytes||VA,this.stagingTtlSeconds=n.stagingTtlSeconds||b6,this.now=n.now||Date.now}initiate(e){let t=Df(e,this.maxBytes),n={...t,stagingKey:`${ey}/${y6()}/${t.filename}`,expiresAt:this.now()+this.stagingTtlSeconds*1000},r=S6(JSON.stringify(n)),i=GA(r,this.options.tokenSecret);return{uploadId:`${r}.${i}`,uploadUrl:this.store.createUploadUrl(n.stagingKey,"application/gzip",this.stagingTtlSeconds),uploadHeaders:{"Content-Type":"application/gzip"},expiresAt:new Date(n.expiresAt).toISOString()}}async complete(e,t,n="binary"){let r=this.verifyClaim(e),i=r.stagingKey.replace(`${ey}/`,".pantry-staging/sealed/"),s=!0;try{let o=await this.store.headObject(r.stagingKey),a=XA(o);if(a!==null&&a!==r.size)throw new ie("Staged artifact size does not match the initiated upload",422,"BINARY_SIZE_MISMATCH")}catch(o){if(o instanceof ie)throw o;s=!1}if(!s){let o=await this.findCompleted(r);if(o)return o;throw new ie("Staged artifact was not found or has expired",404,"BINARY_STAGING_NOT_FOUND")}try{await this.store.copyObject(r.stagingKey,i),await this.store.deleteObject(r.stagingKey);let o={surface:n,name:r.domain,version:r.version,publisher:t},a;if(this.store.getObjectStream&&this.scanner.scanStream)a=await Uu(this.scanner,await this.store.getObjectStream(i),o,{sha256:r.sha256,size:r.size});else{let c=await this.store.getObject(i);if(c.byteLength!==r.size)throw new ie("Staged artifact size does not match the initiated upload",422,"BINARY_SIZE_MISMATCH");a=await Bn(this.scanner,Uint8Array.from(c).buffer,o)}if(a.artifactSha256!==r.sha256)throw new ie("Staged artifact SHA-256 does not match the initiated upload",422,"BINARY_SHA256_MISMATCH",a);if(a.verdict==="blocked")throw new ie("Binary artifact blocked by malware scanning",422,"MALWARE_DETECTED",a);if(a.verdict==="review")throw new ie("Binary artifact requires security review",202,"PACKAGE_REQUIRES_REVIEW",a);if(a.verdict!=="clean")throw new ie("Binary artifact malware scanning is temporarily unavailable",503,"MALWARE_SCAN_UNAVAILABLE",a);let l=await this.withDomainLock(r.domain,()=>this.promote(r,i,a));return await this.options.onPublished?.(l),l}finally{await this.store.deleteObject(r.stagingKey).catch(()=>{}),await this.store.deleteObject(i).catch(()=>{})}}async publishBuffer(e,t,n,r="binary"){let i=Df(e,this.maxBytes);if(t.byteLength!==i.size)throw new ie("Artifact buffer size does not match the publish request",422,"BINARY_SIZE_MISMATCH");let s=this.initiate(i),o=this.verifyClaim(s.uploadId);return await this.store.putObject(o.stagingKey,t,"application/gzip"),this.complete(s.uploadId,n,r)}async rescanExisting(e,t){let n=x6(e);return this.withDomainLock(n.domain,async()=>{let r=`binaries/${n.domain}/metadata.json`,i;try{i=JSON.parse((await this.store.getObject(r)).toString("utf8"))}catch{throw new ie("Binary package metadata was not found",404,"BINARY_METADATA_NOT_FOUND")}let s={};for(let g of n.platforms){let y=i.versions?.[n.version]?.platforms?.[g];if(!y)throw new ie(`Binary platform was not found: ${g}`,404,"BINARY_PLATFORM_NOT_FOUND");s[g]=y}let o=[...new Set(Object.values(s).map((g)=>ty(g.tarball)))];if(o.length!==1)throw new ie("Rescan platforms must reference the same retained artifact",422,"BINARY_RESCAN_ARTIFACT_MISMATCH");let a=o[0];if(!a.startsWith(`binaries/${n.domain}/${n.version}/`))throw new ie("Retained artifact is outside its package namespace",422,"BINARY_RESCAN_ARTIFACT_MISMATCH");if(Object.values(s).every((g)=>g.malwareScan?.verdict==="clean"&&g.malwareScan.artifactSha256===g.sha256))try{let g=JSON.parse((await this.store.getObject(Ds(a))).toString("utf8"));if(g?.scan?.verdict==="clean"&&g.scan.artifactSha256===Object.values(s)[0].sha256)return{action:"already-clean",domain:n.domain,version:n.version,tarball:a,platforms:s,scan:pt(Object.values(s)[0].malwareScan)}}catch{}let c;try{let g=await this.store.headObject(a);c=XA(g)??Object.values(s)[0].size}catch{throw new ie("Retained binary artifact was not found",404,"BINARY_ARTIFACT_NOT_FOUND")}if(!Number.isSafeInteger(c)||c<=0||c>this.maxBytes)throw new ie(`Retained binary artifact size must be between 1 and ${this.maxBytes} bytes`,413,"INVALID_BINARY_SIZE");let u=Object.values(s).map((g)=>g.sha256).find((g)=>HA.test(g||""));if(!u)try{u=(await this.store.getObject(`${a}.sha256`)).toString("utf8").match(/\b[a-f0-9]{64}\b/i)?.[0]?.toLowerCase()}catch{}if(!u)throw new ie("Retained binary artifact has no valid SHA-256",422,"BINARY_SHA256_MISSING");let f={surface:"binary",name:n.domain,version:n.version,publisher:t},d;if(this.store.getObjectStream&&this.scanner.scanStream)d=await Uu(this.scanner,await this.store.getObjectStream(a),f,{sha256:u,size:c});else{let g=await this.store.getObject(a);if(g.byteLength!==c)throw new ie("Retained artifact size does not match metadata",422,"BINARY_SIZE_MISMATCH");d=await Bn(this.scanner,Uint8Array.from(g).buffer,f)}if(d.artifactSha256!==u)throw new ie("Retained artifact SHA-256 does not match metadata",422,"BINARY_SHA256_MISMATCH",d);if(d.verdict==="error")throw new ie("Binary artifact malware scanning is temporarily unavailable",503,"MALWARE_SCAN_UNAVAILABLE",d);if(d.verdict==="blocked"||d.verdict==="review")return this.quarantineExisting(r,i,n,a,d);if(d.verdict!=="clean")throw new ie("Binary artifact malware scanning is temporarily unavailable",503,"MALWARE_SCAN_UNAVAILABLE",d);let h=new Date(this.now()).toISOString(),p={};for(let[g,y]of Object.entries(i.versions||{}))for(let[w,b]of Object.entries(y.platforms||{})){if(ty(b.tarball)!==a)continue;if(b.tarball=a,b.sha256=u,b.size=c,b.malwareScan=d,!b.uploadedAt)b.uploadedAt=h;if(g===n.version)p[w]=b}await this.store.putObject(`${a}.sha256`,`${u} ${a.split("/").at(-1)}
|
|
13430
13430
|
`,"text/plain"),await this.store.putObject(Ds(a),JSON.stringify({domain:n.domain,version:n.version,platforms:Object.keys(p),filename:a.split("/").at(-1),scan:d}),"application/json"),i.updatedAt=h,await this.store.putObject(r,JSON.stringify(i,null,2),"application/json");let m={domain:n.domain,version:n.version,platforms:p,scan:pt(d)};return await this.options.onPublished?.(m),{action:"attested",tarball:a,...m}})}async quarantineExisting(e,t,n,r,i){let s=`.pantry-quarantine/malware/${n.domain}/${n.version}/${i.artifactSha256}/${r.split("/").at(-1)}`;await this.store.copyObject(r,s),await this.store.putObject(`${s}.scan.json`,JSON.stringify({quarantinedAt:new Date(this.now()).toISOString(),originalKey:r,domain:n.domain,version:n.version,scan:i}),"application/json");for(let[o,a]of Object.entries(t.versions||{})){for(let[l,c]of Object.entries(a.platforms||{}))if(ty(c.tarball)===r)delete a.platforms[l];if(Object.keys(a.platforms||{}).length===0)delete t.versions[o]}if(!t.versions[t.latestVersion])t.latestVersion=Object.keys(t.versions).sort((o,a)=>a.localeCompare(o,void 0,{numeric:!0})).at(0)||"";return t.updatedAt=new Date(this.now()).toISOString(),await this.store.putObject(e,JSON.stringify(t,null,2),"application/json"),await this.store.deleteObject(r),await this.store.deleteObject(`${r}.sha256`).catch(()=>{}),await this.store.deleteObject(Ds(r)).catch(()=>{}),{action:"quarantined",domain:n.domain,version:n.version,tarball:r,platforms:{},scan:pt(i)}}verifyClaim(e){let[t,n,r]=e.split(".");if(!t||!n||r||!_6(GA(t,this.options.tokenSecret),n))throw new ie("Invalid binary staging upload ID",401,"INVALID_BINARY_UPLOAD_ID");let i;try{i=JSON.parse(k6(t))}catch{throw new ie("Invalid binary staging upload ID",401,"INVALID_BINARY_UPLOAD_ID")}let s=Df(i,this.maxBytes),o=i;if(typeof o.stagingKey!=="string"||!o.stagingKey.startsWith(`${ey}/`)||typeof o.expiresAt!=="number")throw new ie("Invalid binary staging upload ID",401,"INVALID_BINARY_UPLOAD_ID");if(o.expiresAt<this.now())throw new ie("Binary staging upload has expired",410,"BINARY_UPLOAD_EXPIRED");return{...s,stagingKey:o.stagingKey,expiresAt:o.expiresAt}}async promote(e,t,n){let r=new Date(this.now()).toISOString(),i={};for(let a of e.platforms){let l=`binaries/${e.domain}/${e.version}/${a}/${e.filename}`;await this.store.copyObject(t,l),await this.store.putObject(`${l}.sha256`,`${e.sha256} ${e.filename}
|
|
13431
13431
|
`,"text/plain"),await this.store.putObject(Ds(l),JSON.stringify({domain:e.domain,version:e.version,platform:a,filename:e.filename,scan:n}),"application/json"),i[a]={tarball:l,sha256:e.sha256,size:e.size,uploadedAt:r,malwareScan:n}}let s=`binaries/${e.domain}/metadata.json`,o={name:e.domain,latestVersion:e.version,versions:{},updatedAt:r};try{o=JSON.parse((await this.store.getObject(s)).toString("utf8"))}catch{}if(o.name=e.domain,o.versions||={},o.versions[e.version]||={platforms:{}},o.versions[e.version].platforms||={},Object.assign(o.versions[e.version].platforms,i),!o.latestVersion||E6(e.version,o.latestVersion))o.latestVersion=e.version;return o.updatedAt=r,await this.store.putObject(s,JSON.stringify(o,null,2),"application/json"),{domain:e.domain,version:e.version,platforms:i,scan:pt(n)}}async findCompleted(e){try{let t=JSON.parse((await this.store.getObject(`binaries/${e.domain}/metadata.json`)).toString("utf8")),n={};for(let i of e.platforms){let s=t.versions?.[e.version]?.platforms?.[i];if(!s||s.sha256!==e.sha256||s.malwareScan?.verdict!=="clean")return null;n[i]=s}let r=n[e.platforms[0]].malwareScan;return{domain:e.domain,version:e.version,platforms:n,scan:pt(r)}}catch{return null}}async withDomainLock(e,t){let n=this.locks.get(e)||Promise.resolve(),r,i=new Promise((o)=>r=o),s=n.then(()=>i);this.locks.set(e,s),await n;try{return await t()}finally{if(r(),this.locks.get(e)===s)this.locks.delete(e)}}}function ql(e,t={}){return Response.json({error:e.message,code:e.code,retryable:e.status===503,scan:e.scan?pt(e.scan):void 0},{status:e.status,headers:e.status===503?{...t,"Retry-After":"60"}:t})}var Xm=new Map;function cge(){try{let e=Bt(typeof import.meta.dirname==="string"?import.meta.dirname:Qm(Hm(import.meta.url)),"../../ts-pantry/src/packages/aliases.ts"),t=lge(e,"utf8");Xm.clear();for(let n of t.matchAll(/['"]([^'"\n]+)['"]\s*:\s*['"]([^'"\n]+)['"]/g))Xm.set(n[1],n[2]);console.log(`Loaded ${Xm.size} package aliases`)}catch(e){console.warn("Could not load package aliases:",e)}}cge();var Li=new Map;async function z4(){try{let e=Bt(typeof import.meta.dirname==="string"?import.meta.dirname:Qm(Hm(import.meta.url)),"../../ts-pantry/src/packages"),t=PA(e);Li.clear();for(let[n,r]of t)Li.set(n,r);console.log(`Loaded ${Li.size} packages for version validation`)}catch(e){console.warn("Could not load ts-pantry package metadata for version validation:",e)}}await z4();var Vm=new Map;async function B4(){try{let e=Bt(typeof import.meta.dirname==="string"?import.meta.dirname:Qm(Hm(import.meta.url)),"../../ts-pantry/src/recipes"),t=qA(e);Vm.clear();for(let[n,r]of t)Vm.set(n,r);console.log(`Loaded ${Vm.size} platform-constrained packages`)}catch(e){console.warn("Could not load recipe platform constraints:",e)}}await B4();process.on("SIGUSR2",()=>{console.log("SIGUSR2 received \u2014 reloading known versions map"),Promise.all([z4(),B4()]).then(()=>{if(bl)q4(bl)}).catch((e)=>console.error("Reload failed:",e))});function uge(e,t){let n=Li.get(e);if(!n)return!1;return n.has(t)}var vl=typeof import.meta.dirname==="string"?import.meta.dirname:Qm(Hm(import.meta.url)),fge=Bt(vl,"../dashboard/pages"),W4=Bt(vl,"../site/pages"),dge=Bt(W4,"layout.stx"),hge=Bt(vl,"../site/components"),Su=[{domain:"code.visualstudio.com",label:"Visual Studio Code",desc:"Source code editor by Microsoft",category:"Development"},{domain:"cursor.com",label:"Cursor",desc:"AI-powered code editor",category:"Development"},{domain:"zed.dev",label:"Zed",desc:"High-performance code editor",category:"Development"},{domain:"ghostty.org",label:"Ghostty",desc:"Fast, native terminal emulator",category:"Development"},{domain:"warp.dev",label:"Warp",desc:"Modern terminal with AI",category:"Development"},{domain:"iterm2.com",label:"iTerm2",desc:"Terminal emulator for macOS",category:"Development"},{domain:"docker.com/desktop",label:"Docker Desktop",desc:"Container development platform",category:"Development"},{domain:"orbstack.dev",label:"OrbStack",desc:"Fast Docker & Linux on macOS",category:"Development"},{domain:"tableplus.com",label:"TablePlus",desc:"Database management GUI",category:"Development"},{domain:"dbeaver.io",label:"DBeaver",desc:"Universal database tool",category:"Development"},{domain:"postman.com",label:"Postman",desc:"API development platform",category:"Development"},{domain:"bruno.app",label:"Bruno",desc:"Open-source API client",category:"Development"},{domain:"firefox.org",label:"Firefox",desc:"Open-source web browser",category:"Browsers"},{domain:"brave.com",label:"Brave",desc:"Privacy-focused browser",category:"Browsers"},{domain:"arc.net",label:"Arc",desc:"Browser built for power users",category:"Browsers"},{domain:"discord.com",label:"Discord",desc:"Voice, video & text chat",category:"Communication"},{domain:"slack.com",label:"Slack",desc:"Team messaging platform",category:"Communication"},{domain:"signal.org",label:"Signal",desc:"Private messaging",category:"Communication"},{domain:"telegram.org",label:"Telegram",desc:"Cloud-based messaging",category:"Communication"},{domain:"whatsapp.com",label:"WhatsApp",desc:"Messaging app",category:"Communication"},{domain:"element.io",label:"Element",desc:"Matrix messaging client",category:"Communication"},{domain:"ollama.com",label:"Ollama",desc:"Run LLMs locally",category:"AI"},{domain:"lmstudio.ai",label:"LM Studio",desc:"Desktop LLM app",category:"AI"},{domain:"obsidian.md",label:"Obsidian",desc:"Knowledge base & notes",category:"Productivity"},{domain:"notion.so",label:"Notion",desc:"All-in-one workspace",category:"Productivity"},{domain:"linear.app",label:"Linear",desc:"Project management tool",category:"Productivity"},{domain:"raycast.com",label:"Raycast",desc:"Productivity launcher",category:"Productivity"},{domain:"1password.com",label:"1Password",desc:"Password manager",category:"Security"},{domain:"bitwarden.com",label:"Bitwarden",desc:"Open-source password manager",category:"Security"},{domain:"keepassxc.org",label:"KeePassXC",desc:"Offline password manager",category:"Security"},{domain:"spotify.com",label:"Spotify",desc:"Music streaming",category:"Media"},{domain:"vlc.app",label:"VLC",desc:"Media player",category:"Media"},{domain:"iina.io",label:"IINA",desc:"Modern media player for macOS",category:"Media"},{domain:"handbrake.fr",label:"HandBrake",desc:"Video transcoder",category:"Media"},{domain:"figma.com",label:"Figma",desc:"Collaborative design tool",category:"Design"},{domain:"inkscape.org",label:"Inkscape",desc:"Vector graphics editor",category:"Design"},{domain:"gimp.org",label:"GIMP",desc:"Image editor",category:"Design"},{domain:"blender.org",label:"Blender",desc:"3D creation suite",category:"Design"},{domain:"rectangle.app",label:"Rectangle",desc:"Window management",category:"Utilities"},{domain:"karabiner-elements.pqrs.org",label:"Karabiner-Elements",desc:"Keyboard customizer",category:"Utilities"},{domain:"cleanshot.com",label:"CleanShot X",desc:"Screenshot tool",category:"Utilities"},{domain:"alttab.app",label:"AltTab",desc:"Window switcher",category:"Utilities"},{domain:"stats.app",label:"Stats",desc:"System monitor in menu bar",category:"Utilities"},{domain:"maccy.app",label:"Maccy",desc:"Clipboard manager",category:"Utilities"},{domain:"monitorcontrol.app",label:"MonitorControl",desc:"Display brightness control",category:"Utilities"},{domain:"hiddenbar.app",label:"Hidden Bar",desc:"Hide menu bar items",category:"Utilities"},{domain:"meetingbar.app",label:"MeetingBar",desc:"Calendar in menu bar",category:"Utilities"},{domain:"keka.io",label:"Keka",desc:"File archiver",category:"Utilities"},{domain:"libreoffice.org",label:"LibreOffice",desc:"Office suite",category:"Office"},{domain:"tunnelblick.net",label:"Tunnelblick",desc:"OpenVPN client",category:"VPN & Security"}],Gk=[{domain:"jetbrains-mono",label:"JetBrains Mono",desc:"Typeface for developers",category:"Monospace"},{domain:"fira-code",label:"Fira Code",desc:"Monospaced font with programming ligatures",category:"Monospace"},{domain:"cascadia-code",label:"Cascadia Code",desc:"Microsoft's monospaced coding font",category:"Monospace"},{domain:"source-code-pro",label:"Source Code Pro",desc:"Adobe's monospaced coding font",category:"Monospace"},{domain:"hack",label:"Hack",desc:"A typeface designed for source code",category:"Monospace"},{domain:"ibm-plex-mono",label:"IBM Plex Mono",desc:"IBM's monospaced typeface",category:"Monospace"},{domain:"geist-mono",label:"Geist Mono",desc:"Vercel's monospaced typeface",category:"Monospace"},{domain:"meslo-lg-nerd-font",label:"MesloLG Nerd Font",desc:"Meslo patched with Nerd Font glyphs",category:"Nerd Fonts"},{domain:"jetbrains-mono-nerd-font",label:"JetBrainsMono Nerd Font",desc:"JetBrains Mono patched with Nerd Font glyphs",category:"Nerd Fonts"},{domain:"inter",label:"Inter",desc:"Typeface designed for screens",category:"Sans Serif"},{domain:"geist",label:"Geist",desc:"Vercel's sans-serif typeface",category:"Sans Serif"},{domain:"roboto",label:"Roboto",desc:"Google's signature sans-serif",category:"Sans Serif"},{domain:"open-sans",label:"Open Sans",desc:"Humanist sans-serif typeface",category:"Sans Serif"},{domain:"lato",label:"Lato",desc:"Sans-serif typeface family",category:"Sans Serif"},{domain:"ibm-plex-sans",label:"IBM Plex Sans",desc:"IBM's sans-serif typeface",category:"Sans Serif"}],g4=[{domain:"bun.sh",label:"Bun",desc:"JavaScript runtime & toolkit"},{domain:"curl.se",label:"curl",desc:"Command line data transfer"},{domain:"python.org",label:"Python",desc:"Programming language"},{domain:"nodejs.org",label:"Node.js",desc:"JavaScript runtime"},{domain:"go.dev",label:"Go",desc:"Programming language"},{domain:"ruby-lang.org",label:"Ruby",desc:"Programming language"},{domain:"cmake.org",label:"CMake",desc:"Build system generator"},{domain:"openssl.org",label:"OpenSSL",desc:"TLS/SSL toolkit"},{domain:"redis.io",label:"Redis",desc:"In-memory data store"},{domain:"postgresql.org",label:"PostgreSQL",desc:"Relational database"},{domain:"nginx.org",label:"nginx",desc:"Web server & reverse proxy"},{domain:"sqlite.org",label:"SQLite",desc:"Embedded SQL database"},{domain:"ffmpeg.org",label:"FFmpeg",desc:"Multimedia framework"},{domain:"rust-lang.org",label:"Rust",desc:"Systems programming language"},{domain:"deno.land",label:"Deno",desc:"Secure JavaScript runtime"},{domain:"git-scm.org",label:"Git",desc:"Version control system"}],y4={promise:null};function U4(){return y4.promise??=m4().then(() => p4).then((e)=>e.renderTemplate),y4.promise}async function st(e,t={}){let n=t.title||"pantry",i=await(await U4())(Bt(W4,e),{context:{...t,title:n},layout:dge,options:{componentsDir:hge},injectCSS:!0,wrapInDocument:!1});return i=i.replace(/^<meta[^>]*content="A website built with stx templating engine"[^>]*>\n?/gm,""),i=i.replace(/^<meta property="og:title" content="[^"]*">\n?/gm,""),i=i.replace(/^<meta name="twitter:title" content="[^"]*">\n?/gm,""),i}async function vu(e,t={}){return(await U4())(Bt(fge,e),{context:t,injectCSS:!0})}function Pe(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}var pge=new Set(["__proto__","constructor","prototype","node_modules","favicon.ico"]);function w4(e){if(!e||typeof e!=="string"||!e.trim())return"Package name is required";if(e.length>214)return"Package name exceeds 214 characters";if(!/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i.test(e))return"Package name contains invalid characters";if(pge.has(e.toLowerCase()))return"Package name is reserved";return null}function b4(e){if(!e||typeof e!=="string"||!e.trim())return"Package version is required";if(e.length>64)return"Version string exceeds 64 characters";if(!/^[a-zA-Z0-9._+-]+$/.test(e))return"Version contains invalid characters";return null}function v4(e){if(e.description&&typeof e.description==="string"&&e.description.length>2000)return"Description exceeds 2000 characters";if(e.keywords){if(!Array.isArray(e.keywords))return"keywords must be an array";if(e.keywords.length>50)return"keywords array exceeds 50 entries";for(let t of e.keywords)if(typeof t!=="string"||t.length>50)return"each keyword must be a string of at most 50 characters"}if(e.homepage&&typeof e.homepage==="string"&&e.homepage.length>512)return"homepage URL exceeds 512 characters";return null}function ks(e){if(!e)return"";let t=e.trim(),n=t.toLowerCase();if(n.startsWith("javascript:")||n.startsWith("data:")||n.startsWith("vbscript:"))return"";return t}function it(e,t=200){return new Response(e,{status:t,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"public, max-age=60","X-Content-Type-Options":"nosniff","X-Frame-Options":"SAMEORIGIN","Strict-Transport-Security":"max-age=31536000; includeSubDomains","Referrer-Policy":"strict-origin-when-cross-origin","Permissions-Policy":"geolocation=(), microphone=(), camera=()"}})}var mge=16777216,gge=new _g(128,60000,Date.now,mge,(e)=>(e.body.length+e.headers.reduce((t,[n,r])=>t+n.length+r.length,0))*2);async function Ur(e,t){let n=await gge.getOrCreate(e,async()=>{let r=await t();return{body:await r.text(),headers:[...r.headers.entries()],status:r.status,statusText:r.statusText}});return new Response(n.body,{headers:n.headers,status:n.status,statusText:n.statusText})}var P4={install:"install","install-on-request":"install_on_request","build-error":"build_error"},bl=null;function q4(e){let t=new Map;for(let[n,r]of Li)t.set(n,[...r]);e.setKnownPackages(t),e.setSupportedPlatforms(new Map(Vm))}function qr(){if(!bl){let e=ot();bl=new jg(et(e),process.env.S3_BUCKET||"pantry-registry");let t=bl;q4(t),t.load().then(()=>t.refreshCoverage()).catch((n)=>console.error("build-status init failed:",n.message))}return bl}var Wm=null,yge=30000;function wge(e){let t=qr().getStatus(),n=new Map,r=[...Array.isArray(t.building)?t.building:[],...Array.isArray(t.recent)?t.recent:[]];for(let s of r){if(s.hostKind!=="github"||!s.hostUrl)continue;let o=Number(s.hostUrl.match(/\/actions\/runs\/(\d+)/)?.[1]||0);if(!o)continue;let a=n.get(s.hostUrl),l=new Date(s.ts||Date.now()).toISOString(),c=s.state==="building",u=s.state==="failed"?"failure":s.state==="built"?"success":null,f={id:o,name:"Build Download Recipes",displayTitle:"Build Download Recipes",status:c?"in_progress":"completed",conclusion:u,headSha:"",createdAt:l,htmlUrl:s.hostUrl};if(!a||new Date(a.createdAt).getTime()<(s.ts||0)){if(a?.status==="in_progress"&&!c)f.status="in_progress",f.conclusion=null;n.set(s.hostUrl,f)}}let i=[...n.values()].sort((s,o)=>new Date(o.createdAt).getTime()-new Date(s.createdAt).getTime()).slice(0,12);if(i.length===0)return null;return{repository:e,running:i.filter((s)=>s.status==="in_progress").length,queued:0,recent:i,generatedAt:new Date().toISOString(),error:"GitHub API unavailable; using build-event fallback"}}async function x4(){let e=Date.now();if(Wm&&e-Wm.at<yge)return Wm.data;let t=process.env.GITHUB_REPOSITORY||process.env.PANTRY_GITHUB_REPOSITORY||"pantry-pm/pantry",n={repository:t,running:0,queued:0,recent:[],generatedAt:new Date(e).toISOString()},r=[],i;try{let o=process.env.GITHUB_TOKEN||process.env.PAT_TOKEN||process.env.GH_TOKEN,a={Accept:"application/vnd.github+json","User-Agent":"pantry-registry-build-status","X-GitHub-Api-Version":"2022-11-28"};if(o)a.Authorization=`Bearer ${o}`;let l=await fetch(`https://api.github.com/repos/${t}/actions/runs?branch=main&per_page=12`,{headers:a});if(!l.ok)throw Error(`GitHub API ${l.status}`);let c=await l.json();r=(Array.isArray(c.workflow_runs)?c.workflow_runs:[]).map((f)=>({id:Number(f.id||0),name:String(f.name||""),displayTitle:String(f.display_title||f.name||""),status:String(f.status||""),conclusion:f.conclusion==null?null:String(f.conclusion),headSha:String(f.head_sha||""),createdAt:String(f.created_at||""),htmlUrl:String(f.html_url||"")})).filter((f)=>f.id&&f.status),n.queued=r.filter((f)=>f.status==="queued"||f.status==="waiting"||f.status==="requested").length}catch(o){i=o.message}let s=new Map;for(let o of[...r,...wge(t)?.recent||[]]){let a=s.get(o.id);if(!a||a.status!=="in_progress"&&o.status==="in_progress")s.set(o.id,o)}if(n.recent=[...s.values()].sort((o,a)=>new Date(a.createdAt).getTime()-new Date(o.createdAt).getTime()).slice(0,12),n.running=n.recent.filter((o)=>o.status==="in_progress").length,i&&n.recent.length===0)n.error=i;return Wm={at:e,data:n},n}var Xk=null;async function bge(){if(Xk===null)Xk=await st("packages.stx",{title:"Packages & Builds",metaDescription:"Browse every pantry package, see per-platform build coverage and live build activity, and trigger rebuilds.",canonicalUrl:"https://pantry.dev/packages"});return Xk}function G4(e,t,n,r,i,s,o,a=r,l=Wu(),c){let u=c,f=()=>{if(u)return u;let d=process.env.PANTRY_BINARY_STAGING_SECRET||_u()||"",h=ot(),p=new zf(et(h),process.env.S3_BUCKET||"pantry-registry");return u=new Bf(p,l,{tokenSecret:d,maxBytes:Number.parseInt(process.env.CLAMD_MAX_BYTES||"",10)||void 0,onPublished:async(m)=>{let g=Object.values(m.platforms)[0];for(let y of Object.values(m.platforms))Km.delete(y.tarball);await e.metadata.putVersion(m.domain,m.version,{name:m.domain,version:m.version,tarballUrl:`${r}/${g.tarball}`,checksum:g.sha256,publishedAt:g.uploadedAt,size:g.size,malwareScan:g.malwareScan})}}),u};return async(d)=>{let h=new URL(d.url),p=h.pathname,m={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization"};if(d.method==="OPTIONS")return new Response(null,{headers:m});try{if(p==="/api/registry-info"&&d.method==="GET")return Response.json(V0(process.env,r),{headers:{...m,"Cache-Control":"no-store"}});let g=await X0(d,h,{identify:go,corsHeaders:m});if(g)return g;let y=await q0(d,{url:h,path:p,method:d.method,visibility:Is()});if(y)return y;let w=d.headers.get("user-agent")||"";if((/^(curl|wget|httpie|fetch|libfetch|powershell)/i.test(w)||!w)&&(p==="/"||p===""))try{let _=await Bun.file(Bt(vl,"../../../public/install.sh")).text();return new Response(_,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch{return new Response("Install script not found",{status:404})}if(p==="/health")return Response.json({status:"ok",timestamp:new Date().toISOString(),malwareScanning:{enabled:l.enabled,required:l.required}},{headers:m});if(p==="/ready"){let _=await l.health(),E=!_.required||_.ready;return Response.json({status:E?"ready":"not-ready",timestamp:new Date().toISOString(),malwareScanning:_},{status:E?200:503,headers:{...m,"Cache-Control":"no-store"}})}if(p==="/api/security/malware-scanning"&&d.method==="GET")return Response.json({metrics:ug(),health:await l.health()},{headers:{...m,"Cache-Control":"no-store"}});if(p==="/api/v1/binaries/uploads"&&d.method==="POST")return Tge(d,f,m);if(p==="/api/v1/binaries/uploads/complete"&&d.method==="POST")return Mge(d,f,m);if(p==="/api/v1/binaries/rescan"&&d.method==="POST")return Oge(d,f,m);if(p==="/api/packages"&&d.method==="GET"){let _=await qr().getPackages();return Response.json(_,{headers:{...m,"Cache-Control":"public, max-age=15"}})}if(p==="/api/build-status"&&d.method==="GET")return Response.json({...qr().getStatus(),githubActions:await x4()},{headers:{...m,"Cache-Control":"no-store"}});if(p==="/api/github-actions-status"&&d.method==="GET")return Response.json(await x4(),{headers:{...m,"Cache-Control":"no-store"}});if(p==="/api/build-events-stream"&&d.method==="GET"){let _=qr(),E=new TextEncoder,A=null,$=null,M=()=>{if(A)A(),A=null;if($)clearInterval($),$=null},O=new ReadableStream({start(j){let I=(D)=>{try{return j.enqueue(E.encode(`data: ${JSON.stringify(D)}
|
|
13432
13432
|
|