@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/server.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 X4={aws:"us-east-1",backblaze:"us-west-004",hetzner:"fsn1"};function V4(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 Y4(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 et(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")||X4[t],r=e.endpoint||_n("S3_ENDPOINT")||V4(t,n),i=e.forcePathStyle??_n("S3_FORCE_PATH_STYLE")==="true",s=Y4(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 He(e){return new Rm(e.region,{endpoint:e.endpoint,forcePathStyle:e.forcePathStyle,credentials:e.credentials})}import{resolve as J4,relative as K4}from"path";function Q4(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 Es(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 Lm{bucket;baseUrl;s3;constructor(e,t=et(),n){this.bucket=e,this.baseUrl=n||t.publicBaseUrl(e),this.s3=He(t)}getKey(e,t){let n=Es(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(Q4)}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 Fm{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=J4(this.basePath,e);if(K4(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 jk}from"net";import{createHash as _u}from"crypto";import{gunzipSync as H4}from"zlib";var Fk=30000,Ik=1073741824,Dk=65536,Z4=8192,Nk=65536,eB=1048576,tB=536870912,nB=1e5;class ku 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 Su(e,t){if(!e)return t;let n=Number.parseInt(e,10);return Number.isSafeInteger(n)&&n>0?n:t}function Eu(e){return _u("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 Rk(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 zk{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||Fk,this.maxBytes=e.maxBytes||Ik,this.chunkBytes=e.chunkBytes||Dk}async scan(e,t){let n=performance.now(),r=new Date().toISOString(),i=Eu(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=Rk(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=Rk(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 ku?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=_u("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 ku("streamed artifact size did not match the declared size",s);if(s!==t.sha256)throw new ku("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?jk(this.socketPath):jk({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>Z4){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 Bk{enabled=!1;required=!1;async scan(e){return{verdict:"clean",engine:"development-bypass",scannedAt:new Date().toISOString(),durationMs:0,artifactSha256:Eu(e)}}async scanStream(e,t,n){let r=_u("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 Im{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:Eu(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 zm(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 Im("malware scanning is disabled in production; set PANTRY_MALWARE_SCANNING=required or explicitly acknowledge PANTRY_ALLOW_UNSCANNED_PUBLISH=true");return new Bk}if(n!=="required"&&n!=="clamav")return new Im(`unsupported PANTRY_MALWARE_SCANNING mode: ${n}`);return new zk({socketPath:e.CLAMD_SOCKET,host:e.CLAMD_HOST||"127.0.0.1",port:Su(e.CLAMD_PORT,3310),timeoutMs:Su(e.CLAMD_TIMEOUT_MS,Fk),maxBytes:Su(e.CLAMD_MAX_BYTES,Ik),chunkBytes:Su(e.CLAMD_CHUNK_BYTES,Dk)})}class tt extends Error{}function Dm(e,t,n){return Buffer.from(e.subarray(t,t+n)).toString("utf8").replace(/\0.*$/,"")}function rB(e,t){let n=Dm(e,t+124,12).trim();if(!/^[0-7]*$/.test(n))throw new tt("archive contains an invalid tar size");let r=Number.parseInt(n||"0",8);if(!Number.isSafeInteger(r)||r<0)throw new tt("archive contains an invalid tar size");return r}function iB(e){let t=e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+/g,"/");if(!t||t.startsWith("/")||t.split("/").includes(".."))throw new tt("archive contains an unsafe path");return t}function sB(e){let t;try{t=H4(Buffer.from(e),{maxOutputLength:tB})}catch{throw new tt("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=Dm(i,0,100),o=Dm(i,345,155),a=iB(o?`${o}/${s}`:s),l=String.fromCharCode(i[156]||48),c=rB(i,0),u=r+512,f=u+c;if(f>t.byteLength)throw new tt("archive entry exceeds archive bounds");if(l==="0"||l==="\x00")n.push({name:a,data:t.subarray(u,f)});if(n.length>nB)throw new tt("archive contains too many files");r=u+Math.ceil(c/512)*512}return n}function wl(e){if(Array.isArray(e))return`[${e.map(wl).join(",")}]`;if(e&&typeof e==="object"){let t=e;return`{${Object.keys(t).sort().map((n)=>`${JSON.stringify(n)}:${wl(t[n])}`).join(",")}}`}return JSON.stringify(e)}function Lk(e){if(e===void 0)return;if(e===null||typeof e==="function"||typeof e==="symbol")throw new tt("contentPolicy must be a non-null JSON value");let t=wl(e);if(!t||Buffer.byteLength(t)>4096)throw new tt("contentPolicy exceeds 4096 bytes")}function Wk(e,t,n){if(e===void 0){if(n)throw new tt("contentPolicy and DISCLOSURE are required because this package previously declared dual-use content");return}Lk(e);let r=sB(t),i=r.filter((c)=>c.name==="package.json"||c.name==="package/package.json");if(i.length!==1)throw new tt("dual-use package must contain exactly one root package.json");if(i[0].data.byteLength>eB)throw new tt("package.json exceeds 1MB");let s;try{s=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i[0].data))}catch{throw new tt("package.json must contain valid UTF-8 JSON")}if(s.contentPolicy===void 0)throw new tt("packaged package.json is missing contentPolicy");if(Lk(s.contentPolicy),wl(s.contentPolicy)!==wl(e))throw new tt("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 tt("dual-use package must contain exactly one root DISCLOSURE file");let a=o[0].data;if(a.byteLength===0||a.byteLength>Nk)throw new tt(`DISCLOSURE must contain 1-${Nk} bytes`);if(a.includes(0))throw new tt("DISCLOSURE must contain text only");let l;try{l=new TextDecoder("utf-8",{fatal:!0}).decode(a)}catch{throw new tt("DISCLOSURE must contain valid UTF-8 text")}if(!l.trim())throw new tt("DISCLOSURE must not be blank");return{contentPolicy:e,disclosure:{sha256:_u("sha256").update(a).digest("hex"),size:a.byteLength}}}function pt(e){let{reason:t,...n}=e;return n}function Pk(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 Zn(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,Pk(n,r),r}async function Bm(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,Pk(n,i),i}function Uk(){return structuredClone(at)}function oB(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 er(e,t,n=process.env){if(!oB(n))return;let r=Eu(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 aB(e){return typeof e==="string"&&e.length>0&&e.length<=64&&/^[a-zA-Z0-9._+-]+$/.test(e)}function lB(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 Gk{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")?et({provider:e.storageProvider,region:e.s3Region,endpoint:e.s3Endpoint,forcePathStyle:e.forcePathStyle}):void 0;if(r)this.tarballStorage=new Lm(e.s3Bucket,r,e.baseUrl);else this.tarballStorage=new Fm(qk(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 Nm(He(r),e.s3Bucket,e.metadataKey);else if(i==="dynamodb"&&e.dynamoTable&&e.dynamoTable!=="local")this.metadataStorage=new jm(e.dynamoTable,e.s3Region||"us-east-1");else this.metadataStorage=new Om(qk(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 Mm(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 Tk(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 Mk(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=Es(e),o=`packages/pantry/${s}/${t}/${s}-${t}.tgz`;return this.tarballStorage.download(o)}let r=new URL(n.tarballUrl);if(r.protocol!=="https:"||lB(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 Ok(e,t);return null}async publish(e,t,n){er(e.malwareScan,t);let r=Es(e.name);if(!aB(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){er(r?.malwareScan,n);let i=Es(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=Es(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=Es(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 Xk(){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 Gk({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})}function cB(e){return e.toLocaleString("en-US")}function Yk(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 Vk(e){switch(e){case"install":return"PACKAGE#";case"install_on_request":return"INSTALL_ON_REQUEST#";case"build_error":return"BUILD_ERROR#"}}function Jk(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:cB(a),percent:s>0?(a/s*100).toFixed(2):"0.00"}))}}class Kk{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=Vk(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}=Yk(t),s=new Map,o=Vk(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 Jk(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 Au{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}=Yk(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 Jk(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 Wm(e){if(e?.tableName)return new Kk(e.tableName,e.region);return new Au}import*as Qk 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 Hk(e){let t=Buffer.isBuffer(e)?e:Buffer.from(e);return`1220${Qk.createHash("sha256").update(t).digest("hex")}`}function Zk(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 bl(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 $u(e){return`zig fetch --save '${e.replace(/'/g,"'\\''")}'`}class Um{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){er(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 Pm(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 e_{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=He(et({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){er(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 t_ extends Um{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){er(e.malwareScan,t);let n=Pm(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,Pm(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,Pm(e,n))}catch{}await super.deletePackage(e)}}function qm(){let e=process.env.S3_BUCKET,t=process.env.BASE_URL||"http://localhost:3000";if(!e||e==="local")return new Um;let n=et(),r=process.env.DYNAMODB_TABLE;if(n.provider==="aws"&&r&&r!=="local")return new e_({tableName:r,bucket:e,region:n.region,baseUrl:t});return new t_({s3:He(n),bucket:e,baseUrl:t})}async function n_(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:bl(h.name,h.tarballUrl,d)},{headers:s})}if(l==="/publish"&&t.method==="POST"){if(!a)throw Error("malware scanner is required for publishing");return fB(t,r,i,s,o,a)}let u=l.match(/^\/packages\/([^/]+)$/);if(u&&t.method==="DELETE"){let d=r_(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:$u(p.tarballUrl),dependency:bl(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:$u(p.tarballUrl),dependency:bl(d,p.tarballUrl,p.hash)},{headers:s})}}return null}function uB(){return process.env.PANTRY_REGISTRY_TOKEN||process.env.PANTRY_TOKEN}function r_(e){let t=uB();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 fB(e,t,n,r,i,s){let o=e.headers.get("content-type")||"",a=e.headers.get("authorization"),l=r_(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=Hk(h),m,g;if(f&&typeof f==="string"){let x=Zk(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 Zn(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:$u(b),dependency:bl(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 i_ from"crypto";function s_(e){let t=Buffer.isBuffer(e)?e:Buffer.from(e);return i_.createHash("sha256").update(t).digest("hex")}function o_(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 Cu(e,t){let n=e.replace(/[^a-z0-9/_.-]/gi,""),r=t.replace(/[^a-z0-9._-]/gi,"");return`composer require '${n}:^${r}'`}class Xm{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){er(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 Gm(e,t){let n=e.replaceAll("/","-").replaceAll("@","");return`php-packages/${n}/${t}/${n}-${t}.tar.gz`}class a_{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=He(et({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){er(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 l_ extends Xm{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){er(e.malwareScan,t);let n=Gm(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,Gm(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,Gm(e,n))}catch{}await super.deletePackage(e)}}function Vm(){let e=process.env.S3_BUCKET,t=process.env.BASE_URL||"http://localhost:3000";if(!e||e==="local")return new Xm;let n=et(),r=process.env.DYNAMODB_TABLE;if(n.provider==="aws"&&r&&r!=="local")return new a_({tableName:r,bucket:e,region:n.region,baseUrl:t});return new l_({s3:He(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 hB(t,r,i,s,o,a)}let c=l.match(/^\/packages\/([^/]+)\/([^/]+)$/);if(c&&t.method==="DELETE"){let f=u_(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:Cu(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:Cu(f,h.version)},{headers:s})}}return null}function dB(){return process.env.PANTRY_REGISTRY_TOKEN||process.env.PANTRY_TOKEN}function u_(e){let t=dB();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 hB(e,t,n,r,i,s){let o=e.headers.get("content-type")||"",a=e.headers.get("authorization"),l=u_(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=s_(h),m,g,y,w,b,v,x;if(f&&typeof f==="string"){let E=o_(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 Zn(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:Cu(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 f_(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 d_(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 mo=null;async function h_(){if(mo&&Date.now()-mo.timestamp<3600000)return mo.count;try{let e=await fetch("https://packagist.org/statistics.json",{headers:{"User-Agent":"pantry-registry/1.0"}});if(!e.ok)return mo?.count||350000;let n=(await e.json()).totals?.packages||350000;return mo={count:n,timestamp:Date.now()},n}catch{return mo?.count||350000}}import{createHash as pB}from"crypto";import{execSync as p_}from"child_process";import{createReadStream as mB,createWriteStream as gB,existsSync as Jm,mkdirSync as yB,mkdtempSync as wB,readdirSync as bB,rmSync as vB,statSync as xB}from"fs";import{tmpdir as SB}from"os";import{join as As}from"path";import{Readable as kB}from"stream";import{pipeline as _B}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 Ym{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 m_=["darwin-arm64","darwin-x86-64","linux-x86-64","linux-arm64"],Hm=new Set(["php.net","postgresql.org"]);function EB(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 y_(e,t,n){let r=EB(n);if(!r)return null;return`https://dist.pkgx.dev/${e}/${r.os}/${r.arch}/v${t}.tar.xz`}function w_(e,t,n){return`binaries/${e}/${t}/${n}/${e.replace(/\//g,"-")}-${t}.tar.gz`}function AB(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 $B=21600000,g_=new Yr(20000,$B);async function CB(e,t,n){if(Hm.has(e))return!1;let r=y_(e,t,n);if(!r)return!1;let i=`${e}@${t}#${n}`,s=g_.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 g_.set(i,o),o}var Zm=new Set;function eg(e,t,n){return`${e}@${t}#${n}`}function Tu(e,t,n){return Zm.has(eg(e,t,n))}var TB=1800000,Qm=new Yr(1000,TB),MB=20;async function tg(e,t,n){if(Hm.has(e))return t;let r=t?`${t.updatedAt||""}:${t.latestVersion||""}:${Object.keys(t.versions||{}).length}`:"unpublished",i=Qm.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(AB).filter((a)=>{let l=s.versions[a]?.platforms;return!l||m_.some((c)=>!l[c])}).slice(0,MB);return await Promise.all(o.map(async(a)=>{let l=s.versions[a]?.platforms||{},c=m_.filter((d)=>!l[d]),f=(await Promise.all(c.map(async(d)=>({p:d,ok:await CB(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:w_(e,a,d),sha256:"",size:0,uploadedAt:""},Zm.add(eg(e,a,d))})),Qm.set(e,{sourceFingerprint:r,data:s}),s}var Km=new Map;async function OB(e){let t=pB("sha256");for await(let n of mB(e))t.update(n);return t.digest("hex")}async function b_(e,t,n,r){if(Hm.has(e))return null;let i=`${e}@${t}#${n}`,s=Km.get(i);if(s)return s;let o=(async()=>{let a=y_(e,t,n);if(!a)return null;let l=e.replace(/\//g,"-"),c=w_(e,t,n),u=wB(As(SB(),`pkgx-${l}-`));try{let f=As(u,"pkg.tar.xz");try{let b=await fetch(a,{signal:AbortSignal.timeout(120000)});if(!b.ok||!b.body)return null;await _B(kB.fromWeb(b.body),gB(f))}catch{return null}let d=As(u,"ex");yB(d,{recursive:!0}),p_(`tar -xJf "${f}" -C "${d}"`,{stdio:"pipe"});let h=As(d,e,`v${t}`);if(!Jm(h)){let b=As(d,e),v=Jm(b)?bB(b).filter((x)=>x.startsWith("v")):[];if(v.length===1)h=As(b,v[0])}if(!Jm(h))return null;let p=As(u,"out.tar.gz");p_(`tar -czf "${p}" -C "${h}" .`,{stdio:"pipe"});let m=xB(p).size,g=await OB(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"),Qm.delete(e),Zm.delete(eg(e,t,n)),{tarballKey:c,sha256:g,size:m}}catch(f){return console.error(`pkgx materialize failed for ${i}:`,f.message),null}finally{try{vB(u,{recursive:!0,force:!0})}catch{}}})();Km.set(i,o);try{return await o}finally{Km.delete(i)}}class ng extends Au{s3;bucket;key;loaded;saveTimeout=null;savePromise=null;constructor(e,t,n="analytics/registry-analytics.json"){super();this.s3=e,this.bucket=t,this.key=n,this.loaded=this.load()}ready(){return this.loaded}async load(){try{let e=await this.s3.getObjectBuffer(this.bucket,this.key);if(!e||e.byteLength===0)return;this.applyAnalyticsState(JSON.parse(e.toString("utf-8")))}catch(e){let t=e.message||"";if(!/\b40[34]\b/.test(t))console.error(`ObjectAnalytics: failed to load ${this.bucket}/${this.key}: ${t}. Starting empty.`)}}onMutate(){if(this.saveTimeout)return;this.saveTimeout=setTimeout(()=>{this.saveTimeout=null,this.save().catch((e)=>console.error("ObjectAnalytics save failed:",e.message))},5000)}async save(){while(this.savePromise)await this.savePromise;this.savePromise=this.doSave();try{await this.savePromise}finally{this.savePromise=null}}async doSave(){let e=JSON.stringify(this.captureAnalyticsState());await this.s3.putObject({bucket:this.bucket,key:this.key,body:e,contentType:"application/json"})}async flush(){if(this.saveTimeout)clearTimeout(this.saveTimeout),this.saveTimeout=null;await this.save()}}var Nu=["darwin-arm64","darwin-x86-64","linux-x86-64","linux-arm64"],v_=new Set(Nu),Mu=400,vl=2000,jB=400,Ou=500,NB=600000,x_=21600000,S_=50,k_=5000;class rg{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,vl)});if(r.length>Mu)r.splice(0,r.length-Mu);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,vl)}),n.length>Mu)n.splice(0,n.length-Mu);this.evictOldLogDomains()}evictOldLogDomains(){while(this.logs.size>jB){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)=>go(n?.domain)).map((n)=>[this.key(n),n])),this.recent=(e.recent||[]).filter((n)=>go(n?.domain)).slice(0,Ou),this.queue=(e.queue||[]).filter((n)=>go(n)),this.unavailable=new Map((e.unavailable||[]).filter((n)=>n&&go(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,vl):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,Ou),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(!go(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)=>v_.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(!go(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,vl):void 0,error:e.error?String(e.error).slice(0,vl):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>Ou)this.recent.length=Ou;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<=S_)continue;t.sort((n,r)=>n.lastSeen-r.lastSeen);for(let n of t.slice(0,t.length-S_))this.unavailable.delete(this.key(n))}if(this.unavailable.size>k_){let t=[...this.unavailable.values()].sort((n,r)=>n.lastSeen-r.lastSeen);for(let n of t.slice(0,this.unavailable.size-k_))this.unavailable.delete(this.key(n))}}getUnavailableVersions(){return[...this.unavailable.values()].sort((e,t)=>t.lastSeen-e.lastSeen)}pruneStaleBuilding(){let e=Date.now()-NB,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(!v_.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<x_)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||ju(n,t)>0)t=n;return t}async getPackages(){if(this.coverage.size===0)await this.refreshCoverage(!0);else if(Date.now()-this.coverageAt>x_)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||ju(m,p)>0?m:p,null),f=u&&l?l.get(u)??new Set:new Set,d={};for(let p of Nu)d[p]=f.has(p);let h=(this.knownVersions.get(a)||[]).reduce((p,m)=>p===null||ju(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)||[...Nu],newestVersion:h??u,hasUpdate:c&&!!h&&!!u&&ju(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)||[...Nu];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 go(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 ju(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 xl={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"}},Ru=300;function Sl(e){if(e==="pro"||e==="team")return e;return"free"}function tr(e){return xl[e]}function __(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 E_(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 A_(e){return e==="site"}function C_(){return process.env.STRIPE_SECRET_KEY||""}function T_(){return process.env.STRIPE_WEBHOOK_SECRET||""}function nr(){return C_().length>0}function ag(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(...ag(o,`${s}[${a}]`));else n.push([`${s}[${a}]`,String(o)])});else if(typeof i==="object")n.push(...ag(i,s));else n.push([s,String(i)])}return n}async function zi(e,t,n){let r=C_();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(ag(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 lg(e){return`user:${e.toLowerCase().trim()}`}async function M_(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,lg(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 Lu(e,t,n,r){for(let i of[n,r]){if(!i)continue;let s=await e.getAccessGrant(t,lg(i));if(!s)continue;if(s.expiresAt&&new Date(s.expiresAt)<new Date)continue;return!0}return!1}var $_=new Set(["usd","eur","gbp","cad","aud","chf","jpy","sek","nok","dkk"]),ig=100,sg=1e7;function Fu(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<ig)return`Price must be at least ${ig} cents ($${(ig/100).toFixed(2)})`;if(e.price>sg)return`Price must be at most ${sg} cents ($${(sg/100).toFixed(2)})`;let t=(e.currency||"usd").toLowerCase();if(!$_.has(t))return`Unsupported currency "${t}" \u2014 one of: ${[...$_].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 cg(e,t,n){let r=Fu(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 ug(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=E_({amount:s.price,sellerTier:t.sellerTier||"free",discoveredOnSite:A_(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 og=new Map;async function RB(e){if(!e.stripeLookupKey)throw Error(`${e.name} is not a paid tier`);let t=og.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 og.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 og.set(e.stripeLookupKey,i.id),i.id}async function O_(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 RB(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 j_(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 LB(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 kl=new Map,FB=600000;async function N_(e,t,n,r){if(!T_())throw Error("STRIPE_WEBHOOK_SECRET not configured");let i=await IB(t,n);if(i.id){if(kl.has(i.id))return{processed:!0};if(kl.set(i.id,Date.now()),kl.size>100){let s=Date.now();for(let[o,a]of kl)if(s-a>FB)kl.delete(o)}}if(i.type?.startsWith("customer.subscription.")&&r){let s=LB(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:lg(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 IB(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(T_()),{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 DB={usd:"$",eur:"\u20AC",gbp:"\xA3",cad:"CA$",aud:"A$",jpy:"\xA5"},zB=new Set(["jpy"]);function $s(e,t){let n=(t||"usd").toLowerCase(),r=DB[n]||`${n.toUpperCase()} `;if(zB.has(n))return`${r}${e}`;return`${r}${(e/100).toFixed(2)}`}function Wu(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function BB(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function yE(e){let t,n,r;if(e.length!==2)t=Wu,n=(a,l)=>Wu(e(a),l),r=(a,l)=>e(a)-l;else t=e===Wu||e===BB?e:WB,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 WB(){return 0}function PB(e){return e===null?NaN:+e}var wE=yE(Wu),UB=wE.right,K0e=wE.left,Q0e=yE(PB).center,qB=UB,H0e=bE(vE),Z0e=bE(GB);function bE(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)yo(a,c,i,s,o),yo(a,i,c,s,o),yo(a,c,i,s,o),wo(l,i,c,s,o),wo(l,c,i,s,o),wo(l,i,c,s,o);else if(a)yo(a,i,c,s,o),yo(a,c,i,s,o),yo(a,i,c,s,o);else if(l)wo(l,i,c,s,o),wo(l,c,i,s,o),wo(l,i,c,s,o);return t}}function yo(e,t,n,r,i){for(let s=0,o=r*i;s<o;)e(t,n,s,s+=r,1)}function wo(e,t,n,r,i){for(let s=0,o=r*i;s<r;++s)e(t,n,s,s+o,r)}function GB(e){let t=vE(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 vE(e){let t=Math.floor(e);if(t===e)return XB(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 XB(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 xE=Array.prototype,eye=xE.slice,tye=xE.map,VB=Math.sqrt(50),YB=Math.sqrt(10),JB=Math.sqrt(2);function qu(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>=VB?10:s>=YB?5:s>=JB?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 qu(e,t,n*2);return[a,l,c]}function KB(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?qu(t,e,n):qu(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 Eg(e,t,n){return t=+t,e=+e,n=+n,qu(e,t,n)[2]}function QB(e,t,n){t=+t,e=+e,n=+n;let r=t<e,i=r?Eg(t,e,n):Eg(e,t,n);return(r?-1:1)*(i<0?1/-i:i)}function HB(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 nye=HB(Math.random);function SE(e,t){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(t).domain(e);break}return this}var rye=Symbol("implicit");var R_=0.7,L_=1.4285714285714286,ZB=/^#([0-9a-f]{3,8})$/,eW=new RegExp("^rgb\\(\\s*([+-]?\\d+)\\s*,\\s*([+-]?\\d+)\\s*,\\s*([+-]?\\d+)\\s*\\)$"),tW=new RegExp("^rgb\\(\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*\\)$"),nW=new RegExp("^rgba\\(\\s*([+-]?\\d+)\\s*,\\s*([+-]?\\d+)\\s*,\\s*([+-]?\\d+)\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*\\)$"),rW=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*\\)$"),iW=new RegExp("^hsl\\(\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*\\)$"),sW=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*\\)$"),F_={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 Gu(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 I_(e){return e=(e||0)%360,e<0?e+360:e}function Iu(e){return Math.max(0,Math.min(1,e||0))}function fg(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 kE(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),Gu(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=Gu(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(fg(e>=240?e-240:e+120,i,r),fg(e,i,r),fg(e<120?e+240:e-120,i,r),this.opacity)}clamp(){return new rr(I_(this.h),Iu(this.s),Iu(this.l),Gu(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=Gu(this.opacity);return`${e===1?"hsl(":"hsla("}${I_(this.h)}, ${Iu(this.s)*100}%, ${Iu(this.l)*100}%${e===1?")":`, ${e})`}`}}function D_(e){return new dt(e>>16&255,e>>8&255,e&255,1)}function Du(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 Og(e){let t;if(e=`${e}`.trim().toLowerCase(),t=ZB.exec(e)){let n=t[1].length,r=parseInt(t[1],16);if(n===6)return D_(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 Du(r>>24&255,r>>16&255,r>>8&255,(r&255)/255);if(n===4)return Du(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=eW.exec(e))return new dt(+t[1],+t[2],+t[3],1);if(t=tW.exec(e))return new dt(+t[1]*255/100,+t[2]*255/100,+t[3]*255/100,1);if(t=nW.exec(e))return Du(+t[1],+t[2],+t[3],+t[4]);if(t=rW.exec(e))return Du(+t[1]*255/100,+t[2]*255/100,+t[3]*255/100,+t[4]);if(t=iW.exec(e))return z_(+t[1],+t[2]/100,+t[3]/100,1);if(t=sW.exec(e))return z_(+t[1],+t[2]/100,+t[3]/100,+t[4]);if(Object.prototype.hasOwnProperty.call(F_,e))return D_(F_[e]);if(e==="transparent")return new dt(NaN,NaN,NaN,0);return null}function jg(e){if(!(e instanceof or))e=Og(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 Ag(e,t,n,r){if(t===void 0&&n===void 0)return jg(e);return new dt(e,t,n,r==null?1:r)}function kE(e){if(e instanceof rr)return new rr(e.h,e.s,e.l,e.opacity);if(!(e instanceof or))e=Og(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 B_(e,t,n,r){if(t===void 0&&n===void 0)return kE(e);return new rr(e,t,n,r==null?1:r)}var _E=Math.PI/180,EE=180/Math.PI,Xu=18,AE=0.96422,$E=1,CE=0.82521,TE=0.13793103448275862,Ao=0.20689655172413793,ME=3*Ao*Ao,oW=Ao*Ao*Ao;function dg(e){return e>oW?Math.pow(e,0.3333333333333333):e/ME+TE}function hg(e){return e>Ao?e*e*e:ME*(e-TE)}function pg(e){return 255*(e<=0.0031308?12.92*e:1.055*Math.pow(e,0.4166666666666667)-0.055)}function mg(e){return(e/=255)<=0.04045?e/12.92:Math.pow((e+0.055)/1.055,2.4)}function aW(e){if(e instanceof Kr)return new Kr(e.l,e.a,e.b,e.opacity);if(e instanceof Jr)return OE(e);if(!(e instanceof dt))e=jg(e);let t=e,n=mg(t.r),r=mg(t.g),i=mg(t.b),s=dg((0.2225045*n+0.7168786*r+0.0606169*i)/$E),o,a;if(n===r&&r===i)o=a=s;else o=dg((0.4360747*n+0.3850649*r+0.1430804*i)/AE),a=dg((0.0139322*n+0.0971045*r+0.7141733*i)/CE);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+Xu*(e==null?1:e),this.a,this.b,this.opacity)}darker(e){return new Kr(this.l-Xu*(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=AE*hg(t),i=$E*hg(e),s=CE*hg(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 lW(e){if(e instanceof Jr)return new Jr(e.h,e.c,e.l,e.opacity);if(!(e instanceof Kr))e=aW(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)*EE;return new Jr(n<0?n+360:n,Math.sqrt(t.a*t.a+t.b*t.b),t.l,t.opacity)}function W_(e,t,n,r){if(t===void 0&&n===void 0)return lW(e);return new Jr(e,t,n,r==null?1:r)}function OE(e){if(isNaN(e.h))return new Kr(e.l,0,0,e.opacity);let t=e.h*_E;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+Xu*(e==null?1:e),this.opacity)}darker(e){return new Jr(this.h,this.c,this.l-Xu*(e==null?1:e),this.opacity)}rgb(){return OE(this).rgb()}}var jE=-0.14861,Ng=1.78277,Rg=-0.29227,Hu=-0.90649,Tl=1.97294,P_=Tl*Hu,U_=Tl*Ng,q_=Ng*Rg-Hu*jE;function cW(e){if(e instanceof Ms)return new Ms(e.h,e.s,e.l,e.opacity);if(!(e instanceof dt))e=jg(e);let t=e,n=t.r/255,r=t.g/255,i=t.b/255,s=(q_*i+P_*n-U_*r)/(q_+P_-U_),o=i-s,a=(Tl*(r-s)-Rg*o)/Hu,l=Math.sqrt(a*a+o*o)/(Tl*s*(1-s)),c=l?Math.atan2(a,o)*EE-120:NaN;return new Ms(c<0?c+360:c,l,s,t.opacity)}function G_(e,t,n,r){if(t===void 0&&n===void 0)return cW(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?L_:Math.pow(L_,e),new Ms(this.h,this.s,this.l*e,this.opacity)}darker(e){return e=e==null?R_:Math.pow(R_,e),new Ms(this.h,this.s,this.l*e,this.opacity)}rgb(){let e=isNaN(this.h)?0:(this.h+120)*_E,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*(jE*r+Ng*i)),255*(t+n*(Rg*r+Hu*i)),255*(t+n*(Tl*r)),this.opacity)}}function NE(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 uW(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 NE((n-r/t)*t,o,i,s,a)}}function fW(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 NE((n-r/t)*t,i,s,o,a)}}var dW=(e)=>()=>e,Zu=dW;function RE(e,t){return function(n){return e+n*t}}function hW(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 Lg(e,t){let n=t-e;return n?RE(e,n>180||n<-180?n-360*Math.round(n/360):n):Zu(isNaN(e)?t:e)}function pW(e){return(e=+e)===1?xn:function(t,n){return n-t?hW(t,n,e):Zu(isNaN(t)?n:t)}}function xn(e,t){let n=t-e;return n?RE(e,n):Zu(isNaN(e)?t:e)}var X_=function e(t){let n=pW(t);function r(i,s){let o=Ag(i),a=Ag(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 LE(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=Ag(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 iye=LE(uW),sye=LE(fW);function mW(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 gW(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function yW(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]=Fg(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 wW(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 bW(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]=Fg(e[i],t[i]);else r[i]=t[i];return function(s){for(i in n)r[i]=n[i](s);return r}}var $g=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,gg=new RegExp($g.source,"g");function vW(e){return function(){return e}}function xW(e){return function(t){return`${e(t)}`}}function SW(e,t){let n=$g.lastIndex=gg.lastIndex=0,r,i,s,o=-1,a=[],l=[],c=`${e}`,u=`${t}`;while((r=$g.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]?xW(l[0].x):vW(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 Fg(e,t){let n=typeof t,r;return t==null||n==="boolean"?Zu(t):(n==="number"?Tr:n==="string"?(r=Og(t))?(t=r,X_):SW:t instanceof or?X_:t instanceof Date?wW:gW(t)?mW:Array.isArray(t)?yW:typeof t.valueOf!=="function"&&typeof t.toString!=="function"||isNaN(t)?bW:Tr)(e,t)}function kW(e,t){let n=+e,r=+t;return function(i){return Math.round(n*(1-i)+r*i)}}var V_=180/Math.PI,Cg={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function FE(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)*V_,skewX:Math.atan(l)*V_,scaleX:o,scaleY:a}}var zu;function _W(e){let t=new(typeof DOMMatrix==="function"?DOMMatrix:globalThis.WebKitCSSMatrix)(`${e}`);return t.isIdentity?Cg:FE(t.a,t.b,t.c,t.d,t.e,t.f)}function EW(e){if(e==null)return Cg;if(!zu)zu=document.createElementNS("http://www.w3.org/2000/svg","g");zu.setAttribute("transform",e);let t=zu.transform.baseVal.consolidate();if(!t)return Cg;let n=t.matrix;return FE(n.a,n.b,n.c,n.d,n.e,n.f)}function IE(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 oye=IE(_W,"px, ","px)","deg)"),aye=IE(EW,", ",")",")");function Y_(e){return((e=Math.exp(e))+1/e)/2}function AW(e){return((e=Math.exp(e))-1/e)/2}function $W(e){return((e=Math.exp(2*e))-1)/(e+1)}var lye=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=Y_(x),T=c/(n*w)*(C*$W(t*k+x)-AW(x));return[a+T*h,l+T*p,c*C/Y_(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 DE(e){return function(t,n){let r=B_(t),i=B_(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 cye=DE(Lg),uye=DE(xn);function zE(e){return function(t,n){let r=W_(t),i=W_(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 fye=zE(Lg),dye=zE(xn);function BE(e){return function t(n){n=+n;function r(i,s){let o=G_(i),a=G_(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 hye=BE(Lg),pye=BE(xn);function CW(e){return function(){return e}}function TW(e){return+e}var J_=[0,1];function _o(e){return e}function Tg(e,t){return(t-=e=+e)?function(n){return(n-e)/t}:CW(isNaN(t)?NaN:0.5)}function MW(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 OW(e,t,n){let r=e[0],i=e[1],s=t[0],o=t[1],a,l;if(i<r)a=Tg(i,r),l=n(o,s);else a=Tg(r,i),l=n(s,o);return function(c){return l(a(c))}}function jW(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]=Tg(e[o],e[o+1]),s[o]=n(t[o],t[o+1]);return function(a){let l=qB(e,a,1,r)-1;return s[l](i[l](a))}}function WE(e,t){return t.domain(e.domain()).range(e.range()).interpolate(e.interpolate()).clamp(e.clamp()).unknown(e.unknown())}function NW(){let e=J_,t=J_,n=Fg,r,i,s,o=_o,a,l,c;function u(){let d=Math.min(e.length,t.length);if(o!==_o)o=MW(e[0],e[d-1]);return a=d>2?jW:OW,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,TW),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=kW,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 PE(){return NW()(_o,_o)}function RW(e){return Math.abs(e=Math.round(e))>=1000000000000000000000?e.toLocaleString("en").replace(/,/g,""):e.toString(10)}function Vu(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 $o(e){let t=Vu(Math.abs(e));return t?t[1]:NaN}function LW(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 FW(e){return function(t){return t.replace(/[0-9]/g,function(n){return e[+n]})}}var IW=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;class Ig{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 UE(e){let t=IW.exec(e);if(!t)throw Error(`invalid format: ${e}`);return new Ig({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]})}UE.prototype=Ig.prototype;var DW=UE,Mg=DW;function zW(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 Cl;function BW(e,t){let n=Vu(e,t);if(!n)return Cl=void 0,e.toPrecision(t);let r=n[0],i=n[1];Cl=Math.max(-8,Math.min(8,Math.floor(i/3)))*3;let s=i-Cl+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")}${Vu(e,Math.max(0,t+s-1))[0]}`}function K_(e,t){let n=Vu(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 WW={"%":(e,t)=>(e*100).toFixed(t),b:(e)=>Math.round(e).toString(2),c:(e)=>`${e}`,d:RW,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)=>K_(e*100,t),r:K_,s:BW,X:(e)=>Math.round(e).toString(16).toUpperCase(),x:(e)=>Math.round(e).toString(16)},Q_=WW;function H_(e){return e}var Z_=Array.prototype.map,eE=["y","z","a","f","p","n","\xB5","m","","k","M","G","T","P","E","Z","Y"];function PW(e){let t=e.grouping===void 0||e.thousands===void 0?H_:LW(Z_.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?H_:FW(Z_.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=Mg(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(!Q_[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:""),_=Q_[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)$=zW($);if(K&&+$===0&&g!=="+")K=!1;if(M=(K?g==="("?g:a:g==="-"||g==="("?"":g)+M,O=(k==="s"&&!isNaN($)&&Cl!==void 0?eE[8+Cl/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=Mg(f);h.type="f";let p=Math.max(-8,Math.min(8,Math.floor($o(d)/3)))*3,m=Math.pow(10,-p),g=c(`${h}`,{suffix:eE[8+p/3]});return function(y){return g(m*y)}}return{format:c,formatPrefix:u}}var Bu,qE,GE;UW({thousands:",",grouping:[3],currency:["$",""]});function UW(e){return Bu=PW(e),qE=Bu.format,GE=Bu.formatPrefix,Bu}function qW(e){return Math.max(0,-$o(Math.abs(e)))}function GW(e,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor($o(t)/3)))*3-$o(Math.abs(e)))}function XW(e,t){return e=Math.abs(e),t=Math.abs(t)-e,Math.max(0,$o(t)-$o(e))+1}function VW(e,t,n,r){let i=QB(e,t,n),s,o=Mg(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=GW(i,a)))o.precision=s;return GE(o.toString(),a)}case"":case"e":case"g":case"p":case"r":{if(o.precision==null&&!isNaN(s=XW(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=qW(i)))o.precision=s-(o.type==="%"?1:0)*2;break}}return qE(o.toString())}function YW(e){let t=e.domain;return e.ticks=function(n){let r=t();return KB(r[0],r[r.length-1],n==null?10:n)},e.tickFormat=function(n,r){let i=t();return VW(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=Eg(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=PE();return t.copy=function(){return WE(t,Os())},SE.apply(t,arguments),YW(t)}function JW(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 yg=new Date,wg=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 yg.setTime(+s),wg.setTime(+o),e(yg),e(wg),Math.floor(n(yg,wg))},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 Yu=mt(()=>{},(e,t)=>{e.setTime(+e+t)},(e,t)=>{return+t-+e});Yu.every=(e)=>{if(e=Math.floor(e),!isFinite(e)||!(e>0))return null;if(!(e>1))return Yu;return mt((t)=>{t.setTime(Math.floor(+t/e)*e)},(t,n)=>{t.setTime(+t+n*e)},(t,n)=>{return(+n-+t)/e})};var mye=Yu.range,Bi=1000,ir=60000,Wi=3600000,Co=86400000,Dg=604800000,tE=2592000000,bg=31536000000,Eo=mt((e)=>{e.setTime(+e-e.getMilliseconds())},(e,t)=>{e.setTime(+e+t*Bi)},(e,t)=>{return(+t-+e)/Bi},(e)=>{return e.getUTCSeconds()}),gye=Eo.range,zg=mt((e)=>{e.setTime(+e-e.getMilliseconds()-e.getSeconds()*Bi)},(e,t)=>{e.setTime(+e+t*ir)},(e,t)=>{return(+t-+e)/ir},(e)=>{return e.getMinutes()}),yye=zg.range,XE=mt((e)=>{e.setUTCSeconds(0,0)},(e,t)=>{e.setTime(+e+t*ir)},(e,t)=>{return(+t-+e)/ir},(e)=>{return e.getUTCMinutes()}),wye=XE.range,Bg=mt((e)=>{e.setTime(+e-e.getMilliseconds()-e.getSeconds()*Bi-e.getMinutes()*ir)},(e,t)=>{e.setTime(+e+t*Wi)},(e,t)=>{return(+t-+e)/Wi},(e)=>{return e.getHours()}),bye=Bg.range,VE=mt((e)=>{e.setUTCMinutes(0,0,0)},(e,t)=>{e.setTime(+e+t*Wi)},(e,t)=>{return(+t-+e)/Wi},(e)=>{return e.getUTCHours()}),vye=VE.range,Wg=mt((e)=>{e.setHours(0,0,0,0)},(e,t)=>{e.setDate(e.getDate()+t)},(e,t)=>(+t-+e-(t.getTimezoneOffset()-e.getTimezoneOffset())*ir)/Co,(e)=>e.getDate()-1),xye=Wg.range,KW=mt((e)=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>{return(+t-+e)/Co},(e)=>{return e.getUTCDate()-1}),Sye=KW.range,YE=mt((e)=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>{return(+t-+e)/Co},(e)=>{return Math.floor(+e/Co)}),kye=YE.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)/Dg})}var Pg=js(0),QW=js(1),HW=js(2),ZW=js(3),eP=js(4),tP=js(5),nP=js(6),_ye=Pg.range,Eye=QW.range,Aye=HW.range,$ye=ZW.range,Cye=eP.range,Tye=tP.range,Mye=nP.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)/Dg})}var JE=Ns(0),rP=Ns(1),iP=Ns(2),sP=Ns(3),oP=Ns(4),aP=Ns(5),lP=Ns(6),Oye=JE.range,jye=rP.range,Nye=iP.range,Rye=sP.range,Lye=oP.range,Fye=aP.range,Iye=lP.range,Ug=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()}),Dye=Ug.range,KE=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()}),zye=KE.range,ef=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()});ef.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 Bye=ef.range,qg=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()});qg.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 Wye=qg.range;function Pu(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function cP(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function Gg(e){let t,n,r;if(e.length!==2)t=Pu,n=(a,l)=>Pu(e(a),l),r=(a,l)=>e(a)-l;else t=e===Pu||e===cP?e:uP,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 uP(){return 0}function fP(e){return e===null?NaN:+e}var QE=Gg(Pu),Pye=QE.right,Uye=QE.left,qye=Gg(fP).center,Gye=HE(ZE),Xye=HE(dP);function HE(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)bo(a,c,i,s,o),bo(a,i,c,s,o),bo(a,c,i,s,o),vo(l,i,c,s,o),vo(l,c,i,s,o),vo(l,i,c,s,o);else if(a)bo(a,i,c,s,o),bo(a,c,i,s,o),bo(a,i,c,s,o);else if(l)vo(l,i,c,s,o),vo(l,c,i,s,o),vo(l,i,c,s,o);return t}}function bo(e,t,n,r,i){for(let s=0,o=r*i;s<o;)e(t,n,s,s+=r,1)}function vo(e,t,n,r,i){for(let s=0,o=r*i;s<r;++s)e(t,n,s,s+o,r)}function dP(e){let t=ZE(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 ZE(e){let t=Math.floor(e);if(t===e)return hP(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 hP(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 e2=Array.prototype,Vye=e2.slice,Yye=e2.map,pP=Math.sqrt(50),mP=Math.sqrt(10),gP=Math.sqrt(2);function t2(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>=pP?10:s>=mP?5:s>=gP?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 t2(e,t,n*2);return[a,l,c]}function nE(e,t,n){return t=+t,e=+e,n=+n,t2(e,t,n)[2]}function rE(e,t,n){t=+t,e=+e,n=+n;let r=t<e,i=r?nE(t,e,n):nE(e,t,n);return(r?-1:1)*(i<0?1/-i:i)}function yP(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 Jye=yP(Math.random);function n2(e,t,n,r,i,s){let o=[[Eo,1,Bi],[Eo,5,5*Bi],[Eo,15,15*Bi],[Eo,30,30*Bi],[s,1,ir],[s,5,5*ir],[s,15,15*ir],[s,30,30*ir],[i,1,Wi],[i,3,3*Wi],[i,6,6*Wi],[i,12,12*Wi],[r,1,Co],[r,2,2*Co],[n,1,Dg],[t,1,tE],[t,3,3*tE],[e,1,bg]];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=Gg(([,,g])=>g).right(o,d);if(h===o.length)return e.every(rE(+c/bg,+u/bg,f));if(h===0)return Yu.every(Math.max(rE(+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 r2=n2(qg,KE,JE,YE,VE,XE),i2=n2(ef,Ug,Pg,Wg,Bg,zg),Kye=r2[0],Qye=r2[1],wP=i2[0],bP=i2[1],vg=new Date,xg=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 vg.setTime(+s),xg.setTime(+o),e(vg),e(xg),Math.floor(n(vg,xg))},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 Ju=gt(()=>{},(e,t)=>{e.setTime(+e+t)},(e,t)=>{return+t-+e});Ju.every=(e)=>{if(e=Math.floor(e),!isFinite(e)||!(e>0))return null;if(!(e>1))return Ju;return gt((t)=>{t.setTime(Math.floor(+t/e)*e)},(t,n)=>{t.setTime(+t+n*e)},(t,n)=>{return(+n-+t)/e})};var Hye=Ju.range,Pi=1000,sr=60000,Ui=3600000,To=86400000,Xg=604800000,iE=2592000000,Sg=31536000000,$l=gt((e)=>{e.setTime(+e-e.getMilliseconds())},(e,t)=>{e.setTime(+e+t*Pi)},(e,t)=>{return(+t-+e)/Pi},(e)=>{return e.getUTCSeconds()}),Zye=$l.range,s2=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()}),ewe=s2.range,o2=gt((e)=>{e.setUTCSeconds(0,0)},(e,t)=>{e.setTime(+e+t*sr)},(e,t)=>{return(+t-+e)/sr},(e)=>{return e.getUTCMinutes()}),twe=o2.range,a2=gt((e)=>{e.setTime(+e-e.getMilliseconds()-e.getSeconds()*Pi-e.getMinutes()*sr)},(e,t)=>{e.setTime(+e+t*Ui)},(e,t)=>{return(+t-+e)/Ui},(e)=>{return e.getHours()}),nwe=a2.range,l2=gt((e)=>{e.setUTCMinutes(0,0,0)},(e,t)=>{e.setTime(+e+t*Ui)},(e,t)=>{return(+t-+e)/Ui},(e)=>{return e.getUTCHours()}),rwe=l2.range,tf=gt((e)=>{e.setHours(0,0,0,0)},(e,t)=>{e.setDate(e.getDate()+t)},(e,t)=>(+t-+e-(t.getTimezoneOffset()-e.getTimezoneOffset())*sr)/To,(e)=>e.getDate()-1),iwe=tf.range,Vg=gt((e)=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>{return(+t-+e)/To},(e)=>{return e.getUTCDate()-1}),swe=Vg.range,c2=gt((e)=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>{return(+t-+e)/To},(e)=>{return Math.floor(+e/To)}),owe=c2.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)/Xg})}var Yg=Rs(0),Ku=Rs(1),vP=Rs(2),xP=Rs(3),Mo=Rs(4),SP=Rs(5),kP=Rs(6),awe=Yg.range,lwe=Ku.range,cwe=vP.range,uwe=xP.range,fwe=Mo.range,dwe=SP.range,hwe=kP.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)/Xg})}var Jg=Ls(0),Qu=Ls(1),_P=Ls(2),EP=Ls(3),Oo=Ls(4),AP=Ls(5),$P=Ls(6),pwe=Jg.range,mwe=Qu.range,gwe=_P.range,ywe=EP.range,wwe=Oo.range,bwe=AP.range,vwe=$P.range,u2=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()}),xwe=u2.range,f2=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()}),Swe=f2.range,qi=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()});qi.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 kwe=qi.range,Gi=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()});Gi.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 _we=Gi.range;function Uu(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function CP(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function Kg(e){let t,n,r;if(e.length!==2)t=Uu,n=(a,l)=>Uu(e(a),l),r=(a,l)=>e(a)-l;else t=e===Uu||e===CP?e:TP,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 TP(){return 0}function MP(e){return e===null?NaN:+e}var d2=Kg(Uu),Ewe=d2.right,Awe=d2.left,$we=Kg(MP).center,Cwe=h2(p2),Twe=h2(OP);function h2(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)xo(a,c,i,s,o),xo(a,i,c,s,o),xo(a,c,i,s,o),So(l,i,c,s,o),So(l,c,i,s,o),So(l,i,c,s,o);else if(a)xo(a,i,c,s,o),xo(a,c,i,s,o),xo(a,i,c,s,o);else if(l)So(l,i,c,s,o),So(l,c,i,s,o),So(l,i,c,s,o);return t}}function xo(e,t,n,r,i){for(let s=0,o=r*i;s<o;)e(t,n,s,s+=r,1)}function So(e,t,n,r,i){for(let s=0,o=r*i;s<r;++s)e(t,n,s,s+o,r)}function OP(e){let t=p2(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 p2(e){let t=Math.floor(e);if(t===e)return jP(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 jP(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 m2=Array.prototype,Mwe=m2.slice,Owe=m2.map,NP=Math.sqrt(50),RP=Math.sqrt(10),LP=Math.sqrt(2);function g2(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>=NP?10:s>=RP?5:s>=LP?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 g2(e,t,n*2);return[a,l,c]}function sE(e,t,n){return t=+t,e=+e,n=+n,g2(e,t,n)[2]}function oE(e,t,n){t=+t,e=+e,n=+n;let r=t<e,i=r?sE(t,e,n):sE(e,t,n);return(r?-1:1)*(i<0?1/-i:i)}function FP(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 jwe=FP(Math.random);function y2(e,t,n,r,i,s){let o=[[$l,1,Pi],[$l,5,5*Pi],[$l,15,15*Pi],[$l,30,30*Pi],[s,1,sr],[s,5,5*sr],[s,15,15*sr],[s,30,30*sr],[i,1,Ui],[i,3,3*Ui],[i,6,6*Ui],[i,12,12*Ui],[r,1,To],[r,2,2*To],[n,1,Xg],[t,1,iE],[t,3,3*iE],[e,1,Sg]];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=Kg(([,,g])=>g).right(o,d);if(h===o.length)return e.every(oE(+c/Sg,+u/Sg,f));if(h===0)return Ju.every(Math.max(oE(+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 w2=y2(Gi,f2,Jg,c2,l2,o2),b2=y2(qi,u2,Yg,tf,a2,s2),Nwe=w2[0],Rwe=w2[1],Lwe=b2[0],Fwe=b2[1];function kg(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 _g(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 _l(e,t,n){return{y:e,m:t,d:n,H:0,M:0,S:0,L:0}}function IP(e){let{dateTime:t,date:n,time:r,periods:i,days:s,shortDays:o,months:a,shortMonths:l}=e,c=El(i),u=Al(i),f=El(s),d=Al(s),h=El(o),p=Al(o),m=El(a),g=Al(a),y=El(l),w=Al(l),b={a:I,A:D,b:W,B:G,c:null,d:dE,e:dE,f:oU,g:gU,G:wU,H:rU,I:iU,j:sU,L:v2,m:aU,M:lU,p:K,q:_e,Q:mE,s:gE,S:cU,u:uU,U:fU,V:dU,w:hU,W:pU,x:null,X:null,y:mU,Y:yU,Z:bU,"%":pE},v={a:ie,A:U,b:ee,B:fe,c:null,d:hE,e:hE,f:kU,g:NU,G:LU,H:vU,I:xU,j:SU,L:S2,m:_U,M:EU,p:q,q:F,Q:mE,s:gE,S:AU,u:$U,U:CU,V:TU,w:MU,W:OU,x:null,X:null,y:jU,Y:RU,Z:FU,"%":pE},x={a:_,A:E,b:A,B:$,c:M,d:uE,e:uE,f:ZP,g:cE,G:lE,H:fE,I:fE,j:JP,L:HP,m:YP,M:KP,p:T,q:VP,Q:tU,s:nU,S:QP,u:PP,U:UP,V:qP,w:WP,W:GP,x:O,X:j,y:cE,Y:lE,Z:XP,"%":eU};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=aE[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=_l(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=_g(_l(R.y,0,1)),te=Y.getUTCDay(),Y=te>4||te===0?Qu.ceil(Y):Qu(Y),Y=Vg.offset(Y,(R.V-1)*7),R.y=Y.getUTCFullYear(),R.m=Y.getUTCMonth(),R.d=Y.getUTCDate()+(R.w+6)%7;else Y=kg(_l(R.y,0,1)),te=Y.getDay(),Y=te>4||te===0?Ku.ceil(Y):Ku(Y),Y=tf.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?_g(_l(R.y,0,1)).getUTCDay():kg(_l(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,_g(R);return kg(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 aE?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 ie(N){return o[N.getUTCDay()]}function U(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 aE={"-":"",_:" ","0":"0"},Nt=/^\s*\d+/,DP=/^%/,zP=/[\\^$*+?|[\]().{}]/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 BP(e){return e.replace(zP,"\\$&")}function El(e){return new RegExp(`^(?:${e.map(BP).join("|")})`,"i")}function Al(e){return new Map(e.map((t,n)=>[t.toLowerCase(),n]))}function WP(e,t,n){let r=Nt.exec(t.slice(n,n+1));return r?(e.w=+r[0],n+r[0].length):-1}function PP(e,t,n){let r=Nt.exec(t.slice(n,n+1));return r?(e.u=+r[0],n+r[0].length):-1}function UP(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.U=+r[0],n+r[0].length):-1}function qP(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.V=+r[0],n+r[0].length):-1}function GP(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.W=+r[0],n+r[0].length):-1}function lE(e,t,n){let r=Nt.exec(t.slice(n,n+4));return r?(e.y=+r[0],n+r[0].length):-1}function cE(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 XP(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 VP(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 YP(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 uE(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.d=+r[0],n+r[0].length):-1}function JP(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 fE(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.H=+r[0],n+r[0].length):-1}function KP(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.M=+r[0],n+r[0].length):-1}function QP(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.S=+r[0],n+r[0].length):-1}function HP(e,t,n){let r=Nt.exec(t.slice(n,n+3));return r?(e.L=+r[0],n+r[0].length):-1}function ZP(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 eU(e,t,n){let r=DP.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function tU(e,t,n){let r=Nt.exec(t.slice(n));return r?(e.Q=+r[0],n+r[0].length):-1}function nU(e,t,n){let r=Nt.exec(t.slice(n));return r?(e.s=+r[0],n+r[0].length):-1}function dE(e,t){return ve(e.getDate(),t,2)}function rU(e,t){return ve(e.getHours(),t,2)}function iU(e,t){return ve(e.getHours()%12||12,t,2)}function sU(e,t){return ve(1+tf.count(qi(e),e),t,3)}function v2(e,t){return ve(e.getMilliseconds(),t,3)}function oU(e,t){return`${v2(e,t)}000`}function aU(e,t){return ve(e.getMonth()+1,t,2)}function lU(e,t){return ve(e.getMinutes(),t,2)}function cU(e,t){return ve(e.getSeconds(),t,2)}function uU(e){let t=e.getDay();return t===0?7:t}function fU(e,t){return ve(Yg.count(qi(e).getTime()-1,e),t,2)}function x2(e){let t=e.getDay();return t>=4||t===0?Mo(e):Mo.ceil(e)}function dU(e,t){return e=x2(e),ve(Mo.count(qi(e),e)+(qi(e).getDay()===4?1:0),t,2)}function hU(e){return e.getDay()}function pU(e,t){return ve(Ku.count(qi(e).getTime()-1,e),t,2)}function mU(e,t){return ve(e.getFullYear()%100,t,2)}function gU(e,t){return e=x2(e),ve(e.getFullYear()%100,t,2)}function yU(e,t){return ve(e.getFullYear()%1e4,t,4)}function wU(e,t){let n=e.getDay();return e=n>=4||n===0?Mo(e):Mo.ceil(e),ve(e.getFullYear()%1e4,t,4)}function bU(e){let t=e.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+ve(t/60|0,"0",2)+ve(t%60,"0",2)}function hE(e,t){return ve(e.getUTCDate(),t,2)}function vU(e,t){return ve(e.getUTCHours(),t,2)}function xU(e,t){return ve(e.getUTCHours()%12||12,t,2)}function SU(e,t){return ve(1+Vg.count(Gi(e),e),t,3)}function S2(e,t){return ve(e.getUTCMilliseconds(),t,3)}function kU(e,t){return`${S2(e,t)}000`}function _U(e,t){return ve(e.getUTCMonth()+1,t,2)}function EU(e,t){return ve(e.getUTCMinutes(),t,2)}function AU(e,t){return ve(e.getUTCSeconds(),t,2)}function $U(e){let t=e.getUTCDay();return t===0?7:t}function CU(e,t){return ve(Jg.count(Gi(e).getTime()-1,e),t,2)}function k2(e){let t=e.getUTCDay();return t>=4||t===0?Oo(e):Oo.ceil(e)}function TU(e,t){return e=k2(e),ve(Oo.count(Gi(e),e)+(Gi(e).getUTCDay()===4?1:0),t,2)}function MU(e){return e.getUTCDay()}function OU(e,t){return ve(Qu.count(Gi(e).getTime()-1,e),t,2)}function jU(e,t){return ve(e.getUTCFullYear()%100,t,2)}function NU(e,t){return e=k2(e),ve(e.getUTCFullYear()%100,t,2)}function RU(e,t){return ve(e.getUTCFullYear()%1e4,t,4)}function LU(e,t){let n=e.getUTCDay();return e=n>=4||n===0?Oo(e):Oo.ceil(e),ve(e.getUTCFullYear()%1e4,t,4)}function FU(){return"+0000"}function pE(){return"%"}function mE(e){return+e}function gE(e){return Math.floor(+e/1000)}var ko,_2,IU,E2,A2;DU({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 DU(e){return ko=IP(e),_2=ko.format,IU=ko.parse,E2=ko.utcFormat,A2=ko.utcParse,ko}var $2="%Y-%m-%dT%H:%M:%S.%LZ";function zU(e){return e.toISOString()}var Iwe=typeof Date.prototype.toISOString==="function"?zU:E2($2);function BU(e){let t=new Date(e);return isNaN(+t)?null:t}var Dwe=+new Date("2000-01-01T00:00:00.000Z")?BU:A2($2);function WU(e){return new Date(e)}function PU(e){return e instanceof Date?+e:+new Date(+e)}function C2(e,t,n,r,i,s,o,a,l,c){let u=PE(),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,PU)):d().map(WU)},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(JW(k,C)):u},u.copy=function(){return WE(u,C2(e,t,n,r,i,s,o,a,l,c))},u}function Qg(){let e=C2(wP,bP,ef,Ug,Pg,Wg,Bg,zg,Eo,_2).domain([new Date(2000,0,1),new Date(2000,0,2)]);return SE.apply(e,arguments)}function Rt(e){return function(){return e}}var{abs:Bwe,atan2:Wwe,cos:UU,max:Pwe,min:Uwe,sin:Zg,sqrt:Ro}=Math,T2=0.000000000001,nf=Math.PI,qwe=nf/2,R2=2*nf;var e0=Math.PI,t0=2*e0,qU=t0-0.000001;function L2(e,...t){this._+=e[0];for(let n=1,r=e.length;n<r;++n)this._+=t[n-1]+e[n]}function GU(e){let t=Math.floor(e);if(!(t>=0))throw Error(`invalid digits: ${e}`);if(t>15)return L2;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 rf{_x0;_y0;_x1;_y1;_;_append;constructor(e){this._x0=this._y0=this._x1=this._y1=null,this._="",this._append=e==null?L2:GU(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((e0-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%t0+t0;if(f>qU)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>=e0)},${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 XU(){return new rf}Object.defineProperty(XU,Symbol.hasInstance,{value:(e)=>e instanceof rf});function F2(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 rf(t)}var Gwe=Array.prototype.slice;function I2(e){return typeof e==="object"&&"length"in e?e:Array.from(e)}function D2(e){this._context=e}D2.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 n0(e){return new D2(e)}function z2(e){return e[0]}function B2(e){return e[1]}function Ol(e,t){let n=Rt(!0),r=null,i=n0,s=null,o=F2(a);e=typeof e==="function"?e:e===void 0?z2:Rt(e),t=typeof t==="function"?t:t===void 0?B2:Rt(t);function a(l){let c,u=(l=I2(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 r0(e,t,n){let r=null,i=Rt(!0),s=null,o=n0,a=null,l=F2(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?B2:Rt(+n);function c(f){let d,h=0,p,m=(f=I2(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 Ol().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 W2(e){this._curve=e}W2.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 VU(e){function t(n){return new W2(e(n))}return t._curve=e,t}var Xwe=VU(n0);var Vwe=Ro(3);var YU=Ro(0.3333333333333333),Ywe=YU*2;var P2=Zg(nf/10)/Zg(7*nf/10),Jwe=Zg(R2/10)*P2,Kwe=-UU(R2/10)*P2;var Qwe=Ro(3);var Hwe=Ro(3);var Zwe=Ro(3)/2,JU=1/Ro(12),ebe=(JU/2+1)*3;function Xi(){}function jo(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 i0(e){this._context=e}i0.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:jo(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),jo(this,e,t);break;default:jo(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function KU(e){this._context=e}KU.prototype={areaStart:Xi,areaEnd:Xi,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:jo(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function QU(e){this._context=e}QU.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,jo(this,e,t);break;default:jo(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function U2(e,t){this._basis=new i0(e),this._beta=t}U2.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 tbe=function e(t){function n(r){return t===1?new i0(r):new U2(r,t)}return n.beta=function(r){return e(+r)},n}(0.85);function No(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 s0(e,t){this._context=e,this._k=(1-t)/6}s0.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:No(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,No(this,e,t);break;default:No(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 s0(r,t)}return n.tension=function(r){return e(+r)},n}(0);function o0(e,t){this._context=e,this._k=(1-t)/6}o0.prototype={areaStart:Xi,areaEnd:Xi,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:No(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 rbe=function e(t){function n(r){return new o0(r,t)}return n.tension=function(r){return e(+r)},n}(0);function a0(e,t){this._context=e,this._k=(1-t)/6}a0.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,No(this,e,t);break;default:No(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 ibe=function e(t){function n(r){return new a0(r,t)}return n.tension=function(r){return e(+r)},n}(0);function Ml(e,t,n){let{_x1:r,_y1:i,_x2:s,_y2:o}=e;if(e._l01_a>T2){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>T2){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 q2(e,t){this._context=e,this._alpha=t}q2.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,Ml(this,e,t);break;default:Ml(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 sbe=function e(t){function n(r){return t?new q2(r,t):new s0(r,0)}return n.alpha=function(r){return e(+r)},n}(0.5);function G2(e,t){this._context=e,this._alpha=t}G2.prototype={areaStart:Xi,areaEnd:Xi,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:Ml(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 obe=function e(t){function n(r){return t?new G2(r,t):new o0(r,0)}return n.alpha=function(r){return e(+r)},n}(0.5);function X2(e,t){this._context=e,this._alpha=t}X2.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,Ml(this,e,t);break;default:Ml(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 abe=function e(t){function n(r){return t?new X2(r,t):new a0(r,0)}return n.alpha=function(r){return e(+r)},n}(0.5);function HU(e){this._context=e}HU.prototype={areaStart:Xi,areaEnd:Xi,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 M2(e){return e<0?-1:1}function O2(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(M2(s)+M2(o))*Math.min(Math.abs(s),Math.abs(o),0.5*Math.abs(a))||0}function j2(e,t){let n=e._x1-e._x0;return n?(3*(e._y1-e._y0)/n-t)/2:t}function Hg(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 l0(e){this._context=e}l0.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:Hg(this,this._t0,j2(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,Hg(this,j2(this,n=O2(this,e,t)),n);break;default:Hg(this,this._t0,n=O2(this,e,t));break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t,this._t0=n}};function V2(e){this._context=new Y2(e)}V2.prototype=Object.create(l0.prototype);V2.prototype.point=function(e,t){l0.prototype.point.call(this,t,e)};function Y2(e){this._context=e}Y2.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 ZU(e){this._context=e}ZU.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=N2(e),i=N2(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 N2(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 e8(e,t){this._context=e,this._t=t}e8.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 sf(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function t8(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function J2(e){let t,n,r;if(e.length!==2)t=sf,n=(a,l)=>sf(e(a),l),r=(a,l)=>e(a)-l;else t=e===sf||e===t8?e:n8,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 n8(){return 0}function r8(e){return e===null?NaN:+e}var K2=J2(sf),cbe=K2.right,ube=K2.left,fbe=J2(r8).center;var dbe=Q2(H2),hbe=Q2(i8);function Q2(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)Lo(a,c,i,s,o),Lo(a,i,c,s,o),Lo(a,c,i,s,o),Fo(l,i,c,s,o),Fo(l,c,i,s,o),Fo(l,i,c,s,o);else if(a)Lo(a,i,c,s,o),Lo(a,c,i,s,o),Lo(a,i,c,s,o);else if(l)Fo(l,i,c,s,o),Fo(l,c,i,s,o),Fo(l,i,c,s,o);return t}}function Lo(e,t,n,r,i){for(let s=0,o=r*i;s<o;)e(t,n,s,s+=r,1)}function Fo(e,t,n,r,i){for(let s=0,o=r*i;s<r;++s)e(t,n,s,s+o,r)}function i8(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 s8(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 s8(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 of(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 Z2=Array.prototype,pbe=Z2.slice,mbe=Z2.map;var gbe=Math.sqrt(50),ybe=Math.sqrt(10),wbe=Math.sqrt(2);function c0(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 o8(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 bbe=o8(Math.random);function a8(e){return Math.abs(e=Math.round(e))>=1000000000000000000000?e.toLocaleString("en").replace(/,/g,""):e.toString(10)}function lf(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 l8(e){let t=lf(Math.abs(e));return t?t[1]:NaN}function c8(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 u8(e){return function(t){return t.replace(/[0-9]/g,function(n){return e[+n]})}}var f8=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;class u0{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 oA(e){let t=f8.exec(e);if(!t)throw Error(`invalid format: ${e}`);return new u0({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]})}oA.prototype=u0.prototype;var d8=oA,eA=d8;function h8(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 jl;function p8(e,t){let n=lf(e,t);if(!n)return jl=void 0,e.toPrecision(t);let r=n[0],i=n[1];jl=Math.max(-8,Math.min(8,Math.floor(i/3)))*3;let s=i-jl+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")}${lf(e,Math.max(0,t+s-1))[0]}`}function tA(e,t){let n=lf(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 m8={"%":(e,t)=>(e*100).toFixed(t),b:(e)=>Math.round(e).toString(2),c:(e)=>`${e}`,d:a8,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)=>tA(e*100,t),r:tA,s:p8,X:(e)=>Math.round(e).toString(16).toUpperCase(),x:(e)=>Math.round(e).toString(16)},nA=m8;function rA(e){return e}var iA=Array.prototype.map,sA=["y","z","a","f","p","n","\xB5","m","","k","M","G","T","P","E","Z","Y"];function g8(e){let t=e.grouping===void 0||e.thousands===void 0?rA:c8(iA.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?rA:u8(iA.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=eA(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(!nA[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:""),_=nA[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)$=h8($);if(K&&+$===0&&g!=="+")K=!1;if(M=(K?g==="("?g:a:g==="-"||g==="("?"":g)+M,O=(k==="s"&&!isNaN($)&&jl!==void 0?sA[8+jl/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=eA(f);h.type="f";let p=Math.max(-8,Math.min(8,Math.floor(l8(d)/3)))*3,m=Math.pow(10,-p),g=c(`${h}`,{suffix:sA[8+p/3]});return function(y){return g(m*y)}}return{format:c,formatPrefix:u}}var af,cf,y8;w8({thousands:",",grouping:[3],currency:["$",""]});function w8(e){return af=g8(e),cf=af.format,y8=af.formatPrefix,af}var uf=["#5b9cf5","#6dd97a","#e6c84d","#e25c5c","#c084fc","#f97316","#06b6d4","#ec4899"];function Nl(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]=of(e),a=Os().domain([Math.min(s,0),Math.max(o,1)]).range([n-r,r]),l=Ol().x((u,f)=>i(f)).y((u)=>a(u)),c=r0().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=of(a),u=Qg().domain(c).range([r.left,r.left+s]),f=c0(l)||1,d=Os().domain([0,f*1.1]).range([r.top+o,r.top]).nice(),h=Ol().x((S)=>u(S.date)).y((S)=>d(S.count)),p=r0().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=cf(".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 Rl(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=c0(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:uf[d%uf.length]})),chartWidth:t,chartHeight:s}}function aA(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=of(a),u=Qg().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=Ol().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:uf[b%uf.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=cf(".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 lA="ptry_";function b8(){let e=Fs.randomBytes(32).toString("hex");return`${lA}${e}`}function v8(){return Fs.randomBytes(32).toString("hex")}function Ll(e){return Fs.createHash("sha256").update(e).digest("hex")}function d0(e){return e.startsWith(lA)}async function f0(e){return Bun.password.hash(e,{algorithm:"argon2id"})}async function x8(e,t){return Bun.password.verify(e,t)}class h0{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 Pe("Invalid email address",400);if(!t||t.trim().length===0)throw new Pe("Name is required",400);if(!n||n.length<8)throw new Pe("Password must be at least 8 characters",400);if(await this.storage.getUser(r))throw new Pe("An account with this email already exists",409);let s=new Date().toISOString(),o=await f0(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 Pe("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 Pe("Invalid email address",400);if(!n||n.length<8)throw new Pe("Password must be at least 8 characters",400);let s=await this.storage.getUser(i),o=new Date().toISOString(),a=await f0(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 f0("dummy-password-for-timing-normalization"),new Pe("Invalid email or password",401);if(!await x8(t,r.passwordHash))throw new Pe("Invalid email or password",401);let s=v8(),o={tokenHash:Ll(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(Ll(e))}async validateSession(e){let t=await this.storage.getSession(Ll(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 Pe("Token name is required",400);if(t.length>255)throw new Pe("Token name must be 255 characters or fewer",400);let r=b8(),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:Ll(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(d0(e)){let r=await this.storage.getApiTokenByHash(Ll(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:Sl(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 __(await this.getSubscription(e))}async setSubscription(e,t){let n=e.toLowerCase().trim(),r=await this.storage.getUser(n);if(!r)throw new Pe(`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 Pe("You are already on your own team",400);let s=await this.storage.getUser(r);if(!s)throw new Pe("No such account",404);let o=await this.storage.getUser(i);if(!o)throw new Pe(`${t} does not have an account yet \u2014 they need to sign up first`,404);if(o.teamOwner&&o.teamOwner!==r)throw new Pe(`${t} is already on another team`,409);if(o.team?.members?.length)throw new Pe(`${t} runs their own team`,409);let a=s.team?.members??[];if(a.includes(i))return a;if(a.length+1>=n)throw new Pe(`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 Pe("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 Pe extends Error{status;constructor(e,t=400){super(e);this.name="AuthError",this.status=t}}class p0{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 cA{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 uA extends p0{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 m0(e,t){let n=process.env.S3_BUCKET,r=et();if(r.provider!=="aws"&&n&&n!=="local")return new uA({s3:He(r),bucket:n});let i=e||process.env.DYNAMODB_TABLE||"local";if(i&&i!=="local")return new cA(i,t||process.env.AWS_REGION||"us-east-1");return new p0}function S8(e=process.env){return(e.REGISTRY_PLUGINS||"").split(",").map((t)=>t.trim()).filter(Boolean)}function k8(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 _8(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 k8(i,e)}var ff=null;function df(e=process.env){if(ff)return ff;let t=S8(e);return ff=t.length===0?Promise.resolve([]):Promise.all(t.map(_8)).then((n)=>{return console.log(`Loaded ${n.length} registry plugin(s): ${n.map((r)=>r.name).join(", ")}`),n}),ff}async function fA(){return(await df()).some((t)=>typeof t.authorizeRead==="function")}async function dA(e){let t=await df(),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 hA(e,t){let n=await df();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 g0(e){df().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 pA(e){if(!e)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function E8(e){if(e==null)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"}function Io(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(pA(e.REGISTRY_PRIVATE))return"private";return"public"}function Fl(e=process.env,t=Io(e)){let n=e.REGISTRY_ALLOW_SIGNUP;if(pA(n))return!0;if(E8(n))return!1;return t==="public"}function A8(e=process.env){return(e.REGISTRY_SIGNUP_DOMAINS||"").split(",").map((t)=>t.trim().toLowerCase().replace(/^@/,"")).filter(Boolean)}function mA(e,t=process.env){let n=A8(t);if(n.length===0)return!0;let r=e.toLowerCase().trim().split("@")[1]||"";return n.includes(r)}var $8=new Set(["/health","/ready","/api/registry-info","/login","/signup","/auth/login","/auth/logout","/auth/signup","/auth/me","/favicon.ico","/robots.txt","/webhooks/stripe"]);function C8(e=process.env){return(e.REGISTRY_PUBLIC_PATHS||"").split(",").map((t)=>t.trim()).filter(Boolean)}function T8(e,t=process.env){if($8.has(e))return!0;for(let n of C8(t)){if(n==="/"){if(e==="/")return!0;continue}if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return!0}return!1}function M8(e){if(e.method!=="GET")return!1;return(e.headers.get("accept")||"").includes("text/html")}async function gA(e,t,n){let r=n.env??process.env,i=n.visibility??Io(r),s=t.pathname,o=n.corsHeaders??{},a=i==="public"||T8(s,r),l={authenticated:!1,userId:null},c=a&&!await fA()?l:await n.identify(e),u=await dA({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 g0({type:"access-granted",path:s,method:e.method,userId:c.userId}),null}let f=u==="deny"?"Denied by access policy":"Authentication required";if(g0({type:"access-denied",path:s,method:e.method,reason:f}),M8(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 yA(e=process.env,t){let n=Io(e),r=(t||e.BASE_URL||"").replace(/\/$/,"");return{visibility:n,requiresAuth:n==="private",signupsEnabled:Fl(e,n),...r?{loginUrl:`${r}/login`}:{},docs:"https://pantry.dev/self-hosting"}}function hf(e){return e.toLowerCase().trim().replace(/[^a-z0-9._@-]/g,"_").replace(/@/g,"_at_")}function wA(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 O8(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 j8(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 N8=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||N8,this.maxArtifactBytes=t.maxArtifactBytes??209715200,this.maxEntries=t.maxEntries??2000}indexKey(e){return`mirror/${hf(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=wA(c.name),f=wA(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 O8(m);if(!j8(c.integrity,g))p.error="integrity mismatch \u2014 upstream bytes differ from the lockfile",o++;else{let y=`mirror/${hf(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 w0(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 bA={critical:0,high:1,moderate:2,low:3,unknown:4};function R8(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 L8(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 F8(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 I8=async(e)=>{let t=e.map((i)=>({entry:i,ecosystem:R8(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?L8(p):"unknown",summary:p?.summary||p?.details?.slice(0,200)||d,url:`https://osv.dev/vulnerability/${d}`,fixedIn:p?F8(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 b0(e){return e.trim().toUpperCase()}function D8(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=b0(n);if(t.deny?.some((i)=>b0(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)=>b0(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 v0{storage;fetcher;constructor(e,t=I8){this.storage=e;this.fetcher=t}key(e){return`security/${hf(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=D8(s,t.policy);if(o)n.push(o)}n.sort((s,o)=>{let a=s.type==="vulnerability"?bA[s.severity]:5,l=o.type==="vulnerability"?bA[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 x0(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 xA(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 vA(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 z8(e,t){let n=t.timestamp||new Date().toISOString();return{bomFormat:"CycloneDX",specVersion:"1.5",serialNumber:`urn:uuid:${t.documentId||_A(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:xA(r),...r.license?{licenses:[{license:{id:r.license}}]}:{},...vA(r).length?{hashes:vA(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 B8(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:xA(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||_A(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 SA(e,t,n){return t==="spdx"?B8(e,n):z8(e,n)}function kA(e){return String(e||"").toLowerCase()==="spdx"?"spdx":"cyclonedx"}function _A(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 W8,readFileSync as EA}from"fs";import{join as P8,relative as U8,sep as S0}from"path";var AA=["darwin-arm64","darwin-x86-64","linux-x86-64","linux-arm64"];function $A(e){let t=[],n=(r)=>{for(let i of W8(r,{withFileTypes:!0})){let s=P8(r,i.name);if(i.isDirectory())n(s);else if(i.isFile()&&i.name.endsWith(".ts"))t.push(s)}};return n(e),t}function q8(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 CA(e){let t=new Map;for(let n of $A(e)){if(n.endsWith(`${S0}index.ts`)||n.endsWith(`${S0}aliases.ts`))continue;let r=q8(EA(n,"utf8"));if(r)t.set(r.domain,new Set(r.versions))}return t}function G8(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)=>AA.includes(n))}function TA(e){let t=new Map;for(let n of $A(e)){let i=EA(n,"utf8").match(/platforms:\s*\[([^\]]*)\]/);if(!i)continue;let s=G8(i[1].split(","));if(s.length>0&&s.length<AA.length){let o=U8(e,n).replace(/\.ts$/,"").split(S0).join("/");t.set(o,s)}}return t}import{createHmac as X8,randomUUID as V8,timingSafeEqual as Y8}from"crypto";var jA=1073741824,J8=3600,NA=16,k0=".pantry-staging/malware";class A0{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 se extends Error{status;code;scan;constructor(e,t,n,r){super(e);this.status=t;this.code=n;this.scan=r}}var RA=/^[a-z0-9](?:[a-z0-9._-]|\/(?=[a-z0-9])){0,213}$/i,LA=/^[a-z0-9._+-]{1,64}$/i,FA=/^(?:darwin|linux|windows|freebsd)-(?:arm64|x86-64|x86|riscv64)$/,K8=/^[a-z0-9][a-z0-9._+-]{0,239}\.tar\.gz$/i,IA=/^[a-f0-9]{64}$/;function _0(e,t=jA){if(!e||typeof e!=="object")throw new se("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(!RA.test(r)||r.includes("..")||r.endsWith("/"))throw new se("Invalid binary package domain",422,"INVALID_BINARY_DOMAIN");if(!LA.test(i))throw new se("Invalid binary package version",422,"INVALID_BINARY_VERSION");if(!K8.test(s)||s.includes(".."))throw new se("Invalid binary artifact filename",422,"INVALID_BINARY_FILENAME");if(l.length===0||l.length>NA||l.some((c)=>!FA.test(c)))throw new se("One or more binary platforms are invalid",422,"INVALID_BINARY_PLATFORM");if(!Number.isSafeInteger(a)||a<=0||a>t)throw new se(`Binary artifact size must be between 1 and ${t} bytes`,413,"INVALID_BINARY_SIZE");if(!IA.test(o))throw new se("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 Q8(e){if(!e||typeof e!=="object")throw new se("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(!RA.test(n)||n.includes("..")||n.endsWith("/"))throw new se("Invalid binary package domain",422,"INVALID_BINARY_DOMAIN");if(!LA.test(r))throw new se("Invalid binary package version",422,"INVALID_BINARY_VERSION");if(i.length===0||i.length>NA||i.some((s)=>!FA.test(s)))throw new se("One or more binary platforms are invalid",422,"INVALID_BINARY_PLATFORM");return{domain:n,version:r,platforms:i}}function E0(e){try{return decodeURIComponent(new URL(e).pathname.replace(/^\/+/,""))}catch{return decodeURIComponent(e.replace(/^\/+/,""))}}function H8(e){return Buffer.from(e).toString("base64url")}function Z8(e){return Buffer.from(e,"base64url").toString("utf8")}function MA(e,t){return X8("sha256",t).update(e).digest("base64url")}function e6(e,t){let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&Y8(n,r)}function OA(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 t6(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 Do(e){return`${e}.scan.json`}function DA(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 $0{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||jA,this.stagingTtlSeconds=n.stagingTtlSeconds||J8,this.now=n.now||Date.now}initiate(e){let t=_0(e,this.maxBytes),n={...t,stagingKey:`${k0}/${V8()}/${t.filename}`,expiresAt:this.now()+this.stagingTtlSeconds*1000},r=H8(JSON.stringify(n)),i=MA(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(`${k0}/`,".pantry-staging/sealed/"),s=!0;try{let o=await this.store.headObject(r.stagingKey),a=OA(o);if(a!==null&&a!==r.size)throw new se("Staged artifact size does not match the initiated upload",422,"BINARY_SIZE_MISMATCH")}catch(o){if(o instanceof se)throw o;s=!1}if(!s){let o=await this.findCompleted(r);if(o)return o;throw new se("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 Bm(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 se("Staged artifact size does not match the initiated upload",422,"BINARY_SIZE_MISMATCH");a=await Zn(this.scanner,Uint8Array.from(c).buffer,o)}if(a.artifactSha256!==r.sha256)throw new se("Staged artifact SHA-256 does not match the initiated upload",422,"BINARY_SHA256_MISMATCH",a);if(a.verdict==="blocked")throw new se("Binary artifact blocked by malware scanning",422,"MALWARE_DETECTED",a);if(a.verdict==="review")throw new se("Binary artifact requires security review",202,"PACKAGE_REQUIRES_REVIEW",a);if(a.verdict!=="clean")throw new se("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=_0(e,this.maxBytes);if(t.byteLength!==i.size)throw new se("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=Q8(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 se("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 se(`Binary platform was not found: ${g}`,404,"BINARY_PLATFORM_NOT_FOUND");s[g]=y}let o=[...new Set(Object.values(s).map((g)=>E0(g.tarball)))];if(o.length!==1)throw new se("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 se("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(Do(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=OA(g)??Object.values(s)[0].size}catch{throw new se("Retained binary artifact was not found",404,"BINARY_ARTIFACT_NOT_FOUND")}if(!Number.isSafeInteger(c)||c<=0||c>this.maxBytes)throw new se(`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)=>IA.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 se("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 Bm(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 se("Retained artifact size does not match metadata",422,"BINARY_SIZE_MISMATCH");d=await Zn(this.scanner,Uint8Array.from(g).buffer,f)}if(d.artifactSha256!==u)throw new se("Retained artifact SHA-256 does not match metadata",422,"BINARY_SHA256_MISMATCH",d);if(d.verdict==="error")throw new se("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 se("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(E0(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 $u(e){return`zig fetch --save '${e.replace(/'/g,"'\\''")}'`}class Um{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){er(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 Pm(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 e_{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=He(et({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){er(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 t_ extends Um{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){er(e.malwareScan,t);let n=Pm(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,Pm(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,Pm(e,n))}catch{}await super.deletePackage(e)}}function qm(){let e=process.env.S3_BUCKET,t=process.env.BASE_URL||"http://localhost:3000";if(!e||e==="local")return new Um;let n=et(),r=process.env.DYNAMODB_TABLE;if(n.provider==="aws"&&r&&r!=="local")return new e_({tableName:r,bucket:e,region:n.region,baseUrl:t});return new t_({s3:He(n),bucket:e,baseUrl:t})}async function n_(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:bl(h.name,h.tarballUrl,d)},{headers:s})}if(l==="/publish"&&t.method==="POST"){if(!a)throw Error("malware scanner is required for publishing");return fB(t,r,i,s,o,a)}let u=l.match(/^\/packages\/([^/]+)$/);if(u&&t.method==="DELETE"){let d=r_(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:$u(p.tarballUrl),dependency:bl(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:$u(p.tarballUrl),dependency:bl(d,p.tarballUrl,p.hash)},{headers:s})}}return null}function uB(){return process.env.PANTRY_REGISTRY_TOKEN||process.env.PANTRY_TOKEN}function r_(e){let t=uB();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 fB(e,t,n,r,i,s){let o=e.headers.get("content-type")||"",a=e.headers.get("authorization"),l=r_(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=Hk(h),m,g;if(f&&typeof f==="string"){let x=Zk(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 Zn(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:$u(b),dependency:bl(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 i_ from"crypto";function s_(e){let t=Buffer.isBuffer(e)?e:Buffer.from(e);return i_.createHash("sha256").update(t).digest("hex")}function o_(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 Cu(e,t){let n=e.replace(/[^a-z0-9/_.-]/gi,""),r=t.replace(/[^a-z0-9._-]/gi,"");return`composer require '${n}:^${r}'`}class Xm{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){er(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 Gm(e,t){let n=e.replaceAll("/","-").replaceAll("@","");return`php-packages/${n}/${t}/${n}-${t}.tar.gz`}class a_{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=He(et({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){er(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 l_ extends Xm{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){er(e.malwareScan,t);let n=Gm(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,Gm(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,Gm(e,n))}catch{}await super.deletePackage(e)}}function Vm(){let e=process.env.S3_BUCKET,t=process.env.BASE_URL||"http://localhost:3000";if(!e||e==="local")return new Xm;let n=et(),r=process.env.DYNAMODB_TABLE;if(n.provider==="aws"&&r&&r!=="local")return new a_({tableName:r,bucket:e,region:n.region,baseUrl:t});return new l_({s3:He(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 hB(t,r,i,s,o,a)}let c=l.match(/^\/packages\/([^/]+)\/([^/]+)$/);if(c&&t.method==="DELETE"){let f=u_(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:Cu(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:Cu(f,h.version)},{headers:s})}}return null}function dB(){return process.env.PANTRY_REGISTRY_TOKEN||process.env.PANTRY_TOKEN}function u_(e){let t=dB();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 hB(e,t,n,r,i,s){let o=e.headers.get("content-type")||"",a=e.headers.get("authorization"),l=u_(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=s_(h),m,g,y,w,b,v,x;if(f&&typeof f==="string"){let E=o_(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 Zn(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:Cu(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 f_(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 d_(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 mo=null;async function h_(){if(mo&&Date.now()-mo.timestamp<3600000)return mo.count;try{let e=await fetch("https://packagist.org/statistics.json",{headers:{"User-Agent":"pantry-registry/1.0"}});if(!e.ok)return mo?.count||350000;let n=(await e.json()).totals?.packages||350000;return mo={count:n,timestamp:Date.now()},n}catch{return mo?.count||350000}}import{createHash as pB}from"crypto";import{execSync as p_}from"child_process";import{createReadStream as mB,createWriteStream as gB,existsSync as Jm,mkdirSync as yB,mkdtempSync as wB,readdirSync as bB,rmSync as vB,statSync as xB}from"fs";import{tmpdir as SB}from"os";import{join as As}from"path";import{Readable as kB}from"stream";import{pipeline as _B}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 Ym{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 m_=["darwin-arm64","darwin-x86-64","linux-x86-64","linux-arm64"],Hm=new Set(["php.net","postgresql.org"]);function EB(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 y_(e,t,n){let r=EB(n);if(!r)return null;return`https://dist.pkgx.dev/${e}/${r.os}/${r.arch}/v${t}.tar.xz`}function w_(e,t,n){return`binaries/${e}/${t}/${n}/${e.replace(/\//g,"-")}-${t}.tar.gz`}function AB(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 $B=21600000,g_=new Yr(20000,$B);async function CB(e,t,n){if(Hm.has(e))return!1;let r=y_(e,t,n);if(!r)return!1;let i=`${e}@${t}#${n}`,s=g_.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 g_.set(i,o),o}var Zm=new Set;function eg(e,t,n){return`${e}@${t}#${n}`}function Tu(e,t,n){return Zm.has(eg(e,t,n))}var TB=1800000,Qm=new Yr(1000,TB),MB=20;async function tg(e,t,n){if(Hm.has(e))return t;let r=t?`${t.updatedAt||""}:${t.latestVersion||""}:${Object.keys(t.versions||{}).length}`:"unpublished",i=Qm.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(AB).filter((a)=>{let l=s.versions[a]?.platforms;return!l||m_.some((c)=>!l[c])}).slice(0,MB);return await Promise.all(o.map(async(a)=>{let l=s.versions[a]?.platforms||{},c=m_.filter((d)=>!l[d]),f=(await Promise.all(c.map(async(d)=>({p:d,ok:await CB(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:w_(e,a,d),sha256:"",size:0,uploadedAt:""},Zm.add(eg(e,a,d))})),Qm.set(e,{sourceFingerprint:r,data:s}),s}var Km=new Map;async function OB(e){let t=pB("sha256");for await(let n of mB(e))t.update(n);return t.digest("hex")}async function b_(e,t,n,r){if(Hm.has(e))return null;let i=`${e}@${t}#${n}`,s=Km.get(i);if(s)return s;let o=(async()=>{let a=y_(e,t,n);if(!a)return null;let l=e.replace(/\//g,"-"),c=w_(e,t,n),u=wB(As(SB(),`pkgx-${l}-`));try{let f=As(u,"pkg.tar.xz");try{let b=await fetch(a,{signal:AbortSignal.timeout(120000)});if(!b.ok||!b.body)return null;await _B(kB.fromWeb(b.body),gB(f))}catch{return null}let d=As(u,"ex");yB(d,{recursive:!0}),p_(`tar -xJf "${f}" -C "${d}"`,{stdio:"pipe"});let h=As(d,e,`v${t}`);if(!Jm(h)){let b=As(d,e),v=Jm(b)?bB(b).filter((x)=>x.startsWith("v")):[];if(v.length===1)h=As(b,v[0])}if(!Jm(h))return null;let p=As(u,"out.tar.gz");p_(`tar -czf "${p}" -C "${h}" .`,{stdio:"pipe"});let m=xB(p).size,g=await OB(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"),Qm.delete(e),Zm.delete(eg(e,t,n)),{tarballKey:c,sha256:g,size:m}}catch(f){return console.error(`pkgx materialize failed for ${i}:`,f.message),null}finally{try{vB(u,{recursive:!0,force:!0})}catch{}}})();Km.set(i,o);try{return await o}finally{Km.delete(i)}}class ng extends Au{s3;bucket;key;loaded;saveTimeout=null;savePromise=null;constructor(e,t,n="analytics/registry-analytics.json"){super();this.s3=e,this.bucket=t,this.key=n,this.loaded=this.load()}ready(){return this.loaded}async load(){try{let e=await this.s3.getObjectBuffer(this.bucket,this.key);if(!e||e.byteLength===0)return;this.applyAnalyticsState(JSON.parse(e.toString("utf-8")))}catch(e){let t=e.message||"";if(!/\b40[34]\b/.test(t))console.error(`ObjectAnalytics: failed to load ${this.bucket}/${this.key}: ${t}. Starting empty.`)}}onMutate(){if(this.saveTimeout)return;this.saveTimeout=setTimeout(()=>{this.saveTimeout=null,this.save().catch((e)=>console.error("ObjectAnalytics save failed:",e.message))},5000)}async save(){while(this.savePromise)await this.savePromise;this.savePromise=this.doSave();try{await this.savePromise}finally{this.savePromise=null}}async doSave(){let e=JSON.stringify(this.captureAnalyticsState());await this.s3.putObject({bucket:this.bucket,key:this.key,body:e,contentType:"application/json"})}async flush(){if(this.saveTimeout)clearTimeout(this.saveTimeout),this.saveTimeout=null;await this.save()}}var Nu=["darwin-arm64","darwin-x86-64","linux-x86-64","linux-arm64"],v_=new Set(Nu),Mu=400,vl=2000,jB=400,Ou=500,NB=600000,x_=21600000,S_=50,k_=5000;class rg{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,vl)});if(r.length>Mu)r.splice(0,r.length-Mu);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,vl)}),n.length>Mu)n.splice(0,n.length-Mu);this.evictOldLogDomains()}evictOldLogDomains(){while(this.logs.size>jB){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)=>go(n?.domain)).map((n)=>[this.key(n),n])),this.recent=(e.recent||[]).filter((n)=>go(n?.domain)).slice(0,Ou),this.queue=(e.queue||[]).filter((n)=>go(n)),this.unavailable=new Map((e.unavailable||[]).filter((n)=>n&&go(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,vl):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,Ou),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(!go(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)=>v_.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(!go(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,vl):void 0,error:e.error?String(e.error).slice(0,vl):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>Ou)this.recent.length=Ou;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<=S_)continue;t.sort((n,r)=>n.lastSeen-r.lastSeen);for(let n of t.slice(0,t.length-S_))this.unavailable.delete(this.key(n))}if(this.unavailable.size>k_){let t=[...this.unavailable.values()].sort((n,r)=>n.lastSeen-r.lastSeen);for(let n of t.slice(0,this.unavailable.size-k_))this.unavailable.delete(this.key(n))}}getUnavailableVersions(){return[...this.unavailable.values()].sort((e,t)=>t.lastSeen-e.lastSeen)}pruneStaleBuilding(){let e=Date.now()-NB,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(!v_.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<x_)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||ju(n,t)>0)t=n;return t}async getPackages(){if(this.coverage.size===0)await this.refreshCoverage(!0);else if(Date.now()-this.coverageAt>x_)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||ju(m,p)>0?m:p,null),f=u&&l?l.get(u)??new Set:new Set,d={};for(let p of Nu)d[p]=f.has(p);let h=(this.knownVersions.get(a)||[]).reduce((p,m)=>p===null||ju(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)||[...Nu],newestVersion:h??u,hasUpdate:c&&!!h&&!!u&&ju(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)||[...Nu];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 go(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 ju(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 xl={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"}},Ru=300;function Sl(e){if(e==="pro"||e==="team")return e;return"free"}function tr(e){return xl[e]}function __(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 E_(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 A_(e){return e==="site"}function C_(){return process.env.STRIPE_SECRET_KEY||""}function T_(){return process.env.STRIPE_WEBHOOK_SECRET||""}function nr(){return C_().length>0}function ag(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(...ag(o,`${s}[${a}]`));else n.push([`${s}[${a}]`,String(o)])});else if(typeof i==="object")n.push(...ag(i,s));else n.push([s,String(i)])}return n}async function zi(e,t,n){let r=C_();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(ag(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 lg(e){return`user:${e.toLowerCase().trim()}`}async function M_(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,lg(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 Lu(e,t,n,r){for(let i of[n,r]){if(!i)continue;let s=await e.getAccessGrant(t,lg(i));if(!s)continue;if(s.expiresAt&&new Date(s.expiresAt)<new Date)continue;return!0}return!1}var $_=new Set(["usd","eur","gbp","cad","aud","chf","jpy","sek","nok","dkk"]),ig=100,sg=1e7;function Fu(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<ig)return`Price must be at least ${ig} cents ($${(ig/100).toFixed(2)})`;if(e.price>sg)return`Price must be at most ${sg} cents ($${(sg/100).toFixed(2)})`;let t=(e.currency||"usd").toLowerCase();if(!$_.has(t))return`Unsupported currency "${t}" \u2014 one of: ${[...$_].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 cg(e,t,n){let r=Fu(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 ug(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=E_({amount:s.price,sellerTier:t.sellerTier||"free",discoveredOnSite:A_(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 og=new Map;async function RB(e){if(!e.stripeLookupKey)throw Error(`${e.name} is not a paid tier`);let t=og.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 og.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 og.set(e.stripeLookupKey,i.id),i.id}async function O_(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 RB(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 j_(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 LB(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 kl=new Map,FB=600000;async function N_(e,t,n,r){if(!T_())throw Error("STRIPE_WEBHOOK_SECRET not configured");let i=await IB(t,n);if(i.id){if(kl.has(i.id))return{processed:!0};if(kl.set(i.id,Date.now()),kl.size>100){let s=Date.now();for(let[o,a]of kl)if(s-a>FB)kl.delete(o)}}if(i.type?.startsWith("customer.subscription.")&&r){let s=LB(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:lg(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 IB(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(T_()),{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 DB={usd:"$",eur:"\u20AC",gbp:"\xA3",cad:"CA$",aud:"A$",jpy:"\xA5"},zB=new Set(["jpy"]);function $s(e,t){let n=(t||"usd").toLowerCase(),r=DB[n]||`${n.toUpperCase()} `;if(zB.has(n))return`${r}${e}`;return`${r}${(e/100).toFixed(2)}`}function Wu(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function BB(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function yE(e){let t,n,r;if(e.length!==2)t=Wu,n=(a,l)=>Wu(e(a),l),r=(a,l)=>e(a)-l;else t=e===Wu||e===BB?e:WB,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 WB(){return 0}function PB(e){return e===null?NaN:+e}var wE=yE(Wu),UB=wE.right,K0e=wE.left,Q0e=yE(PB).center,qB=UB,H0e=bE(vE),Z0e=bE(GB);function bE(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)yo(a,c,i,s,o),yo(a,i,c,s,o),yo(a,c,i,s,o),wo(l,i,c,s,o),wo(l,c,i,s,o),wo(l,i,c,s,o);else if(a)yo(a,i,c,s,o),yo(a,c,i,s,o),yo(a,i,c,s,o);else if(l)wo(l,i,c,s,o),wo(l,c,i,s,o),wo(l,i,c,s,o);return t}}function yo(e,t,n,r,i){for(let s=0,o=r*i;s<o;)e(t,n,s,s+=r,1)}function wo(e,t,n,r,i){for(let s=0,o=r*i;s<r;++s)e(t,n,s,s+o,r)}function GB(e){let t=vE(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 vE(e){let t=Math.floor(e);if(t===e)return XB(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 XB(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 xE=Array.prototype,eye=xE.slice,tye=xE.map,VB=Math.sqrt(50),YB=Math.sqrt(10),JB=Math.sqrt(2);function qu(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>=VB?10:s>=YB?5:s>=JB?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 qu(e,t,n*2);return[a,l,c]}function KB(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?qu(t,e,n):qu(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 Eg(e,t,n){return t=+t,e=+e,n=+n,qu(e,t,n)[2]}function QB(e,t,n){t=+t,e=+e,n=+n;let r=t<e,i=r?Eg(t,e,n):Eg(e,t,n);return(r?-1:1)*(i<0?1/-i:i)}function HB(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 nye=HB(Math.random);function SE(e,t){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(t).domain(e);break}return this}var rye=Symbol("implicit");var R_=0.7,L_=1.4285714285714286,ZB=/^#([0-9a-f]{3,8})$/,eW=new RegExp("^rgb\\(\\s*([+-]?\\d+)\\s*,\\s*([+-]?\\d+)\\s*,\\s*([+-]?\\d+)\\s*\\)$"),tW=new RegExp("^rgb\\(\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*\\)$"),nW=new RegExp("^rgba\\(\\s*([+-]?\\d+)\\s*,\\s*([+-]?\\d+)\\s*,\\s*([+-]?\\d+)\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*\\)$"),rW=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*\\)$"),iW=new RegExp("^hsl\\(\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*,\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*\\)$"),sW=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*\\)$"),F_={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 Gu(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 I_(e){return e=(e||0)%360,e<0?e+360:e}function Iu(e){return Math.max(0,Math.min(1,e||0))}function fg(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 kE(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),Gu(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=Gu(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(fg(e>=240?e-240:e+120,i,r),fg(e,i,r),fg(e<120?e+240:e-120,i,r),this.opacity)}clamp(){return new rr(I_(this.h),Iu(this.s),Iu(this.l),Gu(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=Gu(this.opacity);return`${e===1?"hsl(":"hsla("}${I_(this.h)}, ${Iu(this.s)*100}%, ${Iu(this.l)*100}%${e===1?")":`, ${e})`}`}}function D_(e){return new dt(e>>16&255,e>>8&255,e&255,1)}function Du(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 Og(e){let t;if(e=`${e}`.trim().toLowerCase(),t=ZB.exec(e)){let n=t[1].length,r=parseInt(t[1],16);if(n===6)return D_(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 Du(r>>24&255,r>>16&255,r>>8&255,(r&255)/255);if(n===4)return Du(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=eW.exec(e))return new dt(+t[1],+t[2],+t[3],1);if(t=tW.exec(e))return new dt(+t[1]*255/100,+t[2]*255/100,+t[3]*255/100,1);if(t=nW.exec(e))return Du(+t[1],+t[2],+t[3],+t[4]);if(t=rW.exec(e))return Du(+t[1]*255/100,+t[2]*255/100,+t[3]*255/100,+t[4]);if(t=iW.exec(e))return z_(+t[1],+t[2]/100,+t[3]/100,1);if(t=sW.exec(e))return z_(+t[1],+t[2]/100,+t[3]/100,+t[4]);if(Object.prototype.hasOwnProperty.call(F_,e))return D_(F_[e]);if(e==="transparent")return new dt(NaN,NaN,NaN,0);return null}function jg(e){if(!(e instanceof or))e=Og(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 Ag(e,t,n,r){if(t===void 0&&n===void 0)return jg(e);return new dt(e,t,n,r==null?1:r)}function kE(e){if(e instanceof rr)return new rr(e.h,e.s,e.l,e.opacity);if(!(e instanceof or))e=Og(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 B_(e,t,n,r){if(t===void 0&&n===void 0)return kE(e);return new rr(e,t,n,r==null?1:r)}var _E=Math.PI/180,EE=180/Math.PI,Xu=18,AE=0.96422,$E=1,CE=0.82521,TE=0.13793103448275862,Ao=0.20689655172413793,ME=3*Ao*Ao,oW=Ao*Ao*Ao;function dg(e){return e>oW?Math.pow(e,0.3333333333333333):e/ME+TE}function hg(e){return e>Ao?e*e*e:ME*(e-TE)}function pg(e){return 255*(e<=0.0031308?12.92*e:1.055*Math.pow(e,0.4166666666666667)-0.055)}function mg(e){return(e/=255)<=0.04045?e/12.92:Math.pow((e+0.055)/1.055,2.4)}function aW(e){if(e instanceof Kr)return new Kr(e.l,e.a,e.b,e.opacity);if(e instanceof Jr)return OE(e);if(!(e instanceof dt))e=jg(e);let t=e,n=mg(t.r),r=mg(t.g),i=mg(t.b),s=dg((0.2225045*n+0.7168786*r+0.0606169*i)/$E),o,a;if(n===r&&r===i)o=a=s;else o=dg((0.4360747*n+0.3850649*r+0.1430804*i)/AE),a=dg((0.0139322*n+0.0971045*r+0.7141733*i)/CE);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+Xu*(e==null?1:e),this.a,this.b,this.opacity)}darker(e){return new Kr(this.l-Xu*(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=AE*hg(t),i=$E*hg(e),s=CE*hg(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 lW(e){if(e instanceof Jr)return new Jr(e.h,e.c,e.l,e.opacity);if(!(e instanceof Kr))e=aW(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)*EE;return new Jr(n<0?n+360:n,Math.sqrt(t.a*t.a+t.b*t.b),t.l,t.opacity)}function W_(e,t,n,r){if(t===void 0&&n===void 0)return lW(e);return new Jr(e,t,n,r==null?1:r)}function OE(e){if(isNaN(e.h))return new Kr(e.l,0,0,e.opacity);let t=e.h*_E;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+Xu*(e==null?1:e),this.opacity)}darker(e){return new Jr(this.h,this.c,this.l-Xu*(e==null?1:e),this.opacity)}rgb(){return OE(this).rgb()}}var jE=-0.14861,Ng=1.78277,Rg=-0.29227,Hu=-0.90649,Tl=1.97294,P_=Tl*Hu,U_=Tl*Ng,q_=Ng*Rg-Hu*jE;function cW(e){if(e instanceof Ms)return new Ms(e.h,e.s,e.l,e.opacity);if(!(e instanceof dt))e=jg(e);let t=e,n=t.r/255,r=t.g/255,i=t.b/255,s=(q_*i+P_*n-U_*r)/(q_+P_-U_),o=i-s,a=(Tl*(r-s)-Rg*o)/Hu,l=Math.sqrt(a*a+o*o)/(Tl*s*(1-s)),c=l?Math.atan2(a,o)*EE-120:NaN;return new Ms(c<0?c+360:c,l,s,t.opacity)}function G_(e,t,n,r){if(t===void 0&&n===void 0)return cW(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?L_:Math.pow(L_,e),new Ms(this.h,this.s,this.l*e,this.opacity)}darker(e){return e=e==null?R_:Math.pow(R_,e),new Ms(this.h,this.s,this.l*e,this.opacity)}rgb(){let e=isNaN(this.h)?0:(this.h+120)*_E,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*(jE*r+Ng*i)),255*(t+n*(Rg*r+Hu*i)),255*(t+n*(Tl*r)),this.opacity)}}function NE(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 uW(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 NE((n-r/t)*t,o,i,s,a)}}function fW(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 NE((n-r/t)*t,i,s,o,a)}}var dW=(e)=>()=>e,Zu=dW;function RE(e,t){return function(n){return e+n*t}}function hW(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 Lg(e,t){let n=t-e;return n?RE(e,n>180||n<-180?n-360*Math.round(n/360):n):Zu(isNaN(e)?t:e)}function pW(e){return(e=+e)===1?xn:function(t,n){return n-t?hW(t,n,e):Zu(isNaN(t)?n:t)}}function xn(e,t){let n=t-e;return n?RE(e,n):Zu(isNaN(e)?t:e)}var X_=function e(t){let n=pW(t);function r(i,s){let o=Ag(i),a=Ag(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 LE(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=Ag(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 iye=LE(uW),sye=LE(fW);function mW(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 gW(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function yW(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]=Fg(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 wW(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 bW(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]=Fg(e[i],t[i]);else r[i]=t[i];return function(s){for(i in n)r[i]=n[i](s);return r}}var $g=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,gg=new RegExp($g.source,"g");function vW(e){return function(){return e}}function xW(e){return function(t){return`${e(t)}`}}function SW(e,t){let n=$g.lastIndex=gg.lastIndex=0,r,i,s,o=-1,a=[],l=[],c=`${e}`,u=`${t}`;while((r=$g.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]?xW(l[0].x):vW(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 Fg(e,t){let n=typeof t,r;return t==null||n==="boolean"?Zu(t):(n==="number"?Tr:n==="string"?(r=Og(t))?(t=r,X_):SW:t instanceof or?X_:t instanceof Date?wW:gW(t)?mW:Array.isArray(t)?yW:typeof t.valueOf!=="function"&&typeof t.toString!=="function"||isNaN(t)?bW:Tr)(e,t)}function kW(e,t){let n=+e,r=+t;return function(i){return Math.round(n*(1-i)+r*i)}}var V_=180/Math.PI,Cg={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function FE(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)*V_,skewX:Math.atan(l)*V_,scaleX:o,scaleY:a}}var zu;function _W(e){let t=new(typeof DOMMatrix==="function"?DOMMatrix:globalThis.WebKitCSSMatrix)(`${e}`);return t.isIdentity?Cg:FE(t.a,t.b,t.c,t.d,t.e,t.f)}function EW(e){if(e==null)return Cg;if(!zu)zu=document.createElementNS("http://www.w3.org/2000/svg","g");zu.setAttribute("transform",e);let t=zu.transform.baseVal.consolidate();if(!t)return Cg;let n=t.matrix;return FE(n.a,n.b,n.c,n.d,n.e,n.f)}function IE(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 oye=IE(_W,"px, ","px)","deg)"),aye=IE(EW,", ",")",")");function Y_(e){return((e=Math.exp(e))+1/e)/2}function AW(e){return((e=Math.exp(e))-1/e)/2}function $W(e){return((e=Math.exp(2*e))-1)/(e+1)}var lye=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=Y_(x),T=c/(n*w)*(C*$W(t*k+x)-AW(x));return[a+T*h,l+T*p,c*C/Y_(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 DE(e){return function(t,n){let r=B_(t),i=B_(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 cye=DE(Lg),uye=DE(xn);function zE(e){return function(t,n){let r=W_(t),i=W_(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 fye=zE(Lg),dye=zE(xn);function BE(e){return function t(n){n=+n;function r(i,s){let o=G_(i),a=G_(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 hye=BE(Lg),pye=BE(xn);function CW(e){return function(){return e}}function TW(e){return+e}var J_=[0,1];function _o(e){return e}function Tg(e,t){return(t-=e=+e)?function(n){return(n-e)/t}:CW(isNaN(t)?NaN:0.5)}function MW(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 OW(e,t,n){let r=e[0],i=e[1],s=t[0],o=t[1],a,l;if(i<r)a=Tg(i,r),l=n(o,s);else a=Tg(r,i),l=n(s,o);return function(c){return l(a(c))}}function jW(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]=Tg(e[o],e[o+1]),s[o]=n(t[o],t[o+1]);return function(a){let l=qB(e,a,1,r)-1;return s[l](i[l](a))}}function WE(e,t){return t.domain(e.domain()).range(e.range()).interpolate(e.interpolate()).clamp(e.clamp()).unknown(e.unknown())}function NW(){let e=J_,t=J_,n=Fg,r,i,s,o=_o,a,l,c;function u(){let d=Math.min(e.length,t.length);if(o!==_o)o=MW(e[0],e[d-1]);return a=d>2?jW:OW,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,TW),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=kW,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 PE(){return NW()(_o,_o)}function RW(e){return Math.abs(e=Math.round(e))>=1000000000000000000000?e.toLocaleString("en").replace(/,/g,""):e.toString(10)}function Vu(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 $o(e){let t=Vu(Math.abs(e));return t?t[1]:NaN}function LW(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 FW(e){return function(t){return t.replace(/[0-9]/g,function(n){return e[+n]})}}var IW=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;class Ig{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 UE(e){let t=IW.exec(e);if(!t)throw Error(`invalid format: ${e}`);return new Ig({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]})}UE.prototype=Ig.prototype;var DW=UE,Mg=DW;function zW(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 Cl;function BW(e,t){let n=Vu(e,t);if(!n)return Cl=void 0,e.toPrecision(t);let r=n[0],i=n[1];Cl=Math.max(-8,Math.min(8,Math.floor(i/3)))*3;let s=i-Cl+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")}${Vu(e,Math.max(0,t+s-1))[0]}`}function K_(e,t){let n=Vu(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 WW={"%":(e,t)=>(e*100).toFixed(t),b:(e)=>Math.round(e).toString(2),c:(e)=>`${e}`,d:RW,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)=>K_(e*100,t),r:K_,s:BW,X:(e)=>Math.round(e).toString(16).toUpperCase(),x:(e)=>Math.round(e).toString(16)},Q_=WW;function H_(e){return e}var Z_=Array.prototype.map,eE=["y","z","a","f","p","n","\xB5","m","","k","M","G","T","P","E","Z","Y"];function PW(e){let t=e.grouping===void 0||e.thousands===void 0?H_:LW(Z_.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?H_:FW(Z_.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=Mg(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(!Q_[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:""),_=Q_[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)$=zW($);if(K&&+$===0&&g!=="+")K=!1;if(M=(K?g==="("?g:a:g==="-"||g==="("?"":g)+M,O=(k==="s"&&!isNaN($)&&Cl!==void 0?eE[8+Cl/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=Mg(f);h.type="f";let p=Math.max(-8,Math.min(8,Math.floor($o(d)/3)))*3,m=Math.pow(10,-p),g=c(`${h}`,{suffix:eE[8+p/3]});return function(y){return g(m*y)}}return{format:c,formatPrefix:u}}var Bu,qE,GE;UW({thousands:",",grouping:[3],currency:["$",""]});function UW(e){return Bu=PW(e),qE=Bu.format,GE=Bu.formatPrefix,Bu}function qW(e){return Math.max(0,-$o(Math.abs(e)))}function GW(e,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor($o(t)/3)))*3-$o(Math.abs(e)))}function XW(e,t){return e=Math.abs(e),t=Math.abs(t)-e,Math.max(0,$o(t)-$o(e))+1}function VW(e,t,n,r){let i=QB(e,t,n),s,o=Mg(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=GW(i,a)))o.precision=s;return GE(o.toString(),a)}case"":case"e":case"g":case"p":case"r":{if(o.precision==null&&!isNaN(s=XW(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=qW(i)))o.precision=s-(o.type==="%"?1:0)*2;break}}return qE(o.toString())}function YW(e){let t=e.domain;return e.ticks=function(n){let r=t();return KB(r[0],r[r.length-1],n==null?10:n)},e.tickFormat=function(n,r){let i=t();return VW(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=Eg(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=PE();return t.copy=function(){return WE(t,Os())},SE.apply(t,arguments),YW(t)}function JW(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 yg=new Date,wg=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 yg.setTime(+s),wg.setTime(+o),e(yg),e(wg),Math.floor(n(yg,wg))},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 Yu=mt(()=>{},(e,t)=>{e.setTime(+e+t)},(e,t)=>{return+t-+e});Yu.every=(e)=>{if(e=Math.floor(e),!isFinite(e)||!(e>0))return null;if(!(e>1))return Yu;return mt((t)=>{t.setTime(Math.floor(+t/e)*e)},(t,n)=>{t.setTime(+t+n*e)},(t,n)=>{return(+n-+t)/e})};var mye=Yu.range,Bi=1000,ir=60000,Wi=3600000,Co=86400000,Dg=604800000,tE=2592000000,bg=31536000000,Eo=mt((e)=>{e.setTime(+e-e.getMilliseconds())},(e,t)=>{e.setTime(+e+t*Bi)},(e,t)=>{return(+t-+e)/Bi},(e)=>{return e.getUTCSeconds()}),gye=Eo.range,zg=mt((e)=>{e.setTime(+e-e.getMilliseconds()-e.getSeconds()*Bi)},(e,t)=>{e.setTime(+e+t*ir)},(e,t)=>{return(+t-+e)/ir},(e)=>{return e.getMinutes()}),yye=zg.range,XE=mt((e)=>{e.setUTCSeconds(0,0)},(e,t)=>{e.setTime(+e+t*ir)},(e,t)=>{return(+t-+e)/ir},(e)=>{return e.getUTCMinutes()}),wye=XE.range,Bg=mt((e)=>{e.setTime(+e-e.getMilliseconds()-e.getSeconds()*Bi-e.getMinutes()*ir)},(e,t)=>{e.setTime(+e+t*Wi)},(e,t)=>{return(+t-+e)/Wi},(e)=>{return e.getHours()}),bye=Bg.range,VE=mt((e)=>{e.setUTCMinutes(0,0,0)},(e,t)=>{e.setTime(+e+t*Wi)},(e,t)=>{return(+t-+e)/Wi},(e)=>{return e.getUTCHours()}),vye=VE.range,Wg=mt((e)=>{e.setHours(0,0,0,0)},(e,t)=>{e.setDate(e.getDate()+t)},(e,t)=>(+t-+e-(t.getTimezoneOffset()-e.getTimezoneOffset())*ir)/Co,(e)=>e.getDate()-1),xye=Wg.range,KW=mt((e)=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>{return(+t-+e)/Co},(e)=>{return e.getUTCDate()-1}),Sye=KW.range,YE=mt((e)=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>{return(+t-+e)/Co},(e)=>{return Math.floor(+e/Co)}),kye=YE.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)/Dg})}var Pg=js(0),QW=js(1),HW=js(2),ZW=js(3),eP=js(4),tP=js(5),nP=js(6),_ye=Pg.range,Eye=QW.range,Aye=HW.range,$ye=ZW.range,Cye=eP.range,Tye=tP.range,Mye=nP.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)/Dg})}var JE=Ns(0),rP=Ns(1),iP=Ns(2),sP=Ns(3),oP=Ns(4),aP=Ns(5),lP=Ns(6),Oye=JE.range,jye=rP.range,Nye=iP.range,Rye=sP.range,Lye=oP.range,Fye=aP.range,Iye=lP.range,Ug=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()}),Dye=Ug.range,KE=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()}),zye=KE.range,ef=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()});ef.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 Bye=ef.range,qg=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()});qg.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 Wye=qg.range;function Pu(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function cP(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function Gg(e){let t,n,r;if(e.length!==2)t=Pu,n=(a,l)=>Pu(e(a),l),r=(a,l)=>e(a)-l;else t=e===Pu||e===cP?e:uP,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 uP(){return 0}function fP(e){return e===null?NaN:+e}var QE=Gg(Pu),Pye=QE.right,Uye=QE.left,qye=Gg(fP).center,Gye=HE(ZE),Xye=HE(dP);function HE(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)bo(a,c,i,s,o),bo(a,i,c,s,o),bo(a,c,i,s,o),vo(l,i,c,s,o),vo(l,c,i,s,o),vo(l,i,c,s,o);else if(a)bo(a,i,c,s,o),bo(a,c,i,s,o),bo(a,i,c,s,o);else if(l)vo(l,i,c,s,o),vo(l,c,i,s,o),vo(l,i,c,s,o);return t}}function bo(e,t,n,r,i){for(let s=0,o=r*i;s<o;)e(t,n,s,s+=r,1)}function vo(e,t,n,r,i){for(let s=0,o=r*i;s<r;++s)e(t,n,s,s+o,r)}function dP(e){let t=ZE(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 ZE(e){let t=Math.floor(e);if(t===e)return hP(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 hP(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 e2=Array.prototype,Vye=e2.slice,Yye=e2.map,pP=Math.sqrt(50),mP=Math.sqrt(10),gP=Math.sqrt(2);function t2(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>=pP?10:s>=mP?5:s>=gP?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 t2(e,t,n*2);return[a,l,c]}function nE(e,t,n){return t=+t,e=+e,n=+n,t2(e,t,n)[2]}function rE(e,t,n){t=+t,e=+e,n=+n;let r=t<e,i=r?nE(t,e,n):nE(e,t,n);return(r?-1:1)*(i<0?1/-i:i)}function yP(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 Jye=yP(Math.random);function n2(e,t,n,r,i,s){let o=[[Eo,1,Bi],[Eo,5,5*Bi],[Eo,15,15*Bi],[Eo,30,30*Bi],[s,1,ir],[s,5,5*ir],[s,15,15*ir],[s,30,30*ir],[i,1,Wi],[i,3,3*Wi],[i,6,6*Wi],[i,12,12*Wi],[r,1,Co],[r,2,2*Co],[n,1,Dg],[t,1,tE],[t,3,3*tE],[e,1,bg]];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=Gg(([,,g])=>g).right(o,d);if(h===o.length)return e.every(rE(+c/bg,+u/bg,f));if(h===0)return Yu.every(Math.max(rE(+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 r2=n2(qg,KE,JE,YE,VE,XE),i2=n2(ef,Ug,Pg,Wg,Bg,zg),Kye=r2[0],Qye=r2[1],wP=i2[0],bP=i2[1],vg=new Date,xg=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 vg.setTime(+s),xg.setTime(+o),e(vg),e(xg),Math.floor(n(vg,xg))},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 Ju=gt(()=>{},(e,t)=>{e.setTime(+e+t)},(e,t)=>{return+t-+e});Ju.every=(e)=>{if(e=Math.floor(e),!isFinite(e)||!(e>0))return null;if(!(e>1))return Ju;return gt((t)=>{t.setTime(Math.floor(+t/e)*e)},(t,n)=>{t.setTime(+t+n*e)},(t,n)=>{return(+n-+t)/e})};var Hye=Ju.range,Pi=1000,sr=60000,Ui=3600000,To=86400000,Xg=604800000,iE=2592000000,Sg=31536000000,$l=gt((e)=>{e.setTime(+e-e.getMilliseconds())},(e,t)=>{e.setTime(+e+t*Pi)},(e,t)=>{return(+t-+e)/Pi},(e)=>{return e.getUTCSeconds()}),Zye=$l.range,s2=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()}),ewe=s2.range,o2=gt((e)=>{e.setUTCSeconds(0,0)},(e,t)=>{e.setTime(+e+t*sr)},(e,t)=>{return(+t-+e)/sr},(e)=>{return e.getUTCMinutes()}),twe=o2.range,a2=gt((e)=>{e.setTime(+e-e.getMilliseconds()-e.getSeconds()*Pi-e.getMinutes()*sr)},(e,t)=>{e.setTime(+e+t*Ui)},(e,t)=>{return(+t-+e)/Ui},(e)=>{return e.getHours()}),nwe=a2.range,l2=gt((e)=>{e.setUTCMinutes(0,0,0)},(e,t)=>{e.setTime(+e+t*Ui)},(e,t)=>{return(+t-+e)/Ui},(e)=>{return e.getUTCHours()}),rwe=l2.range,tf=gt((e)=>{e.setHours(0,0,0,0)},(e,t)=>{e.setDate(e.getDate()+t)},(e,t)=>(+t-+e-(t.getTimezoneOffset()-e.getTimezoneOffset())*sr)/To,(e)=>e.getDate()-1),iwe=tf.range,Vg=gt((e)=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>{return(+t-+e)/To},(e)=>{return e.getUTCDate()-1}),swe=Vg.range,c2=gt((e)=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>{return(+t-+e)/To},(e)=>{return Math.floor(+e/To)}),owe=c2.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)/Xg})}var Yg=Rs(0),Ku=Rs(1),vP=Rs(2),xP=Rs(3),Mo=Rs(4),SP=Rs(5),kP=Rs(6),awe=Yg.range,lwe=Ku.range,cwe=vP.range,uwe=xP.range,fwe=Mo.range,dwe=SP.range,hwe=kP.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)/Xg})}var Jg=Ls(0),Qu=Ls(1),_P=Ls(2),EP=Ls(3),Oo=Ls(4),AP=Ls(5),$P=Ls(6),pwe=Jg.range,mwe=Qu.range,gwe=_P.range,ywe=EP.range,wwe=Oo.range,bwe=AP.range,vwe=$P.range,u2=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()}),xwe=u2.range,f2=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()}),Swe=f2.range,qi=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()});qi.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 kwe=qi.range,Gi=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()});Gi.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 _we=Gi.range;function Uu(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function CP(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function Kg(e){let t,n,r;if(e.length!==2)t=Uu,n=(a,l)=>Uu(e(a),l),r=(a,l)=>e(a)-l;else t=e===Uu||e===CP?e:TP,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 TP(){return 0}function MP(e){return e===null?NaN:+e}var d2=Kg(Uu),Ewe=d2.right,Awe=d2.left,$we=Kg(MP).center,Cwe=h2(p2),Twe=h2(OP);function h2(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)xo(a,c,i,s,o),xo(a,i,c,s,o),xo(a,c,i,s,o),So(l,i,c,s,o),So(l,c,i,s,o),So(l,i,c,s,o);else if(a)xo(a,i,c,s,o),xo(a,c,i,s,o),xo(a,i,c,s,o);else if(l)So(l,i,c,s,o),So(l,c,i,s,o),So(l,i,c,s,o);return t}}function xo(e,t,n,r,i){for(let s=0,o=r*i;s<o;)e(t,n,s,s+=r,1)}function So(e,t,n,r,i){for(let s=0,o=r*i;s<r;++s)e(t,n,s,s+o,r)}function OP(e){let t=p2(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 p2(e){let t=Math.floor(e);if(t===e)return jP(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 jP(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 m2=Array.prototype,Mwe=m2.slice,Owe=m2.map,NP=Math.sqrt(50),RP=Math.sqrt(10),LP=Math.sqrt(2);function g2(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>=NP?10:s>=RP?5:s>=LP?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 g2(e,t,n*2);return[a,l,c]}function sE(e,t,n){return t=+t,e=+e,n=+n,g2(e,t,n)[2]}function oE(e,t,n){t=+t,e=+e,n=+n;let r=t<e,i=r?sE(t,e,n):sE(e,t,n);return(r?-1:1)*(i<0?1/-i:i)}function FP(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 jwe=FP(Math.random);function y2(e,t,n,r,i,s){let o=[[$l,1,Pi],[$l,5,5*Pi],[$l,15,15*Pi],[$l,30,30*Pi],[s,1,sr],[s,5,5*sr],[s,15,15*sr],[s,30,30*sr],[i,1,Ui],[i,3,3*Ui],[i,6,6*Ui],[i,12,12*Ui],[r,1,To],[r,2,2*To],[n,1,Xg],[t,1,iE],[t,3,3*iE],[e,1,Sg]];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=Kg(([,,g])=>g).right(o,d);if(h===o.length)return e.every(oE(+c/Sg,+u/Sg,f));if(h===0)return Ju.every(Math.max(oE(+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 w2=y2(Gi,f2,Jg,c2,l2,o2),b2=y2(qi,u2,Yg,tf,a2,s2),Nwe=w2[0],Rwe=w2[1],Lwe=b2[0],Fwe=b2[1];function kg(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 _g(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 _l(e,t,n){return{y:e,m:t,d:n,H:0,M:0,S:0,L:0}}function IP(e){let{dateTime:t,date:n,time:r,periods:i,days:s,shortDays:o,months:a,shortMonths:l}=e,c=El(i),u=Al(i),f=El(s),d=Al(s),h=El(o),p=Al(o),m=El(a),g=Al(a),y=El(l),w=Al(l),b={a:I,A:D,b:W,B:G,c:null,d:dE,e:dE,f:oU,g:gU,G:wU,H:rU,I:iU,j:sU,L:v2,m:aU,M:lU,p:K,q:_e,Q:mE,s:gE,S:cU,u:uU,U:fU,V:dU,w:hU,W:pU,x:null,X:null,y:mU,Y:yU,Z:bU,"%":pE},v={a:ie,A:U,b:ee,B:fe,c:null,d:hE,e:hE,f:kU,g:NU,G:LU,H:vU,I:xU,j:SU,L:S2,m:_U,M:EU,p:q,q:F,Q:mE,s:gE,S:AU,u:$U,U:CU,V:TU,w:MU,W:OU,x:null,X:null,y:jU,Y:RU,Z:FU,"%":pE},x={a:_,A:E,b:A,B:$,c:M,d:uE,e:uE,f:ZP,g:cE,G:lE,H:fE,I:fE,j:JP,L:HP,m:YP,M:KP,p:T,q:VP,Q:tU,s:nU,S:QP,u:PP,U:UP,V:qP,w:WP,W:GP,x:O,X:j,y:cE,Y:lE,Z:XP,"%":eU};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=aE[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=_l(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=_g(_l(R.y,0,1)),te=Y.getUTCDay(),Y=te>4||te===0?Qu.ceil(Y):Qu(Y),Y=Vg.offset(Y,(R.V-1)*7),R.y=Y.getUTCFullYear(),R.m=Y.getUTCMonth(),R.d=Y.getUTCDate()+(R.w+6)%7;else Y=kg(_l(R.y,0,1)),te=Y.getDay(),Y=te>4||te===0?Ku.ceil(Y):Ku(Y),Y=tf.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?_g(_l(R.y,0,1)).getUTCDay():kg(_l(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,_g(R);return kg(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 aE?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 ie(N){return o[N.getUTCDay()]}function U(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 aE={"-":"",_:" ","0":"0"},Nt=/^\s*\d+/,DP=/^%/,zP=/[\\^$*+?|[\]().{}]/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 BP(e){return e.replace(zP,"\\$&")}function El(e){return new RegExp(`^(?:${e.map(BP).join("|")})`,"i")}function Al(e){return new Map(e.map((t,n)=>[t.toLowerCase(),n]))}function WP(e,t,n){let r=Nt.exec(t.slice(n,n+1));return r?(e.w=+r[0],n+r[0].length):-1}function PP(e,t,n){let r=Nt.exec(t.slice(n,n+1));return r?(e.u=+r[0],n+r[0].length):-1}function UP(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.U=+r[0],n+r[0].length):-1}function qP(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.V=+r[0],n+r[0].length):-1}function GP(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.W=+r[0],n+r[0].length):-1}function lE(e,t,n){let r=Nt.exec(t.slice(n,n+4));return r?(e.y=+r[0],n+r[0].length):-1}function cE(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 XP(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 VP(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 YP(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 uE(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.d=+r[0],n+r[0].length):-1}function JP(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 fE(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.H=+r[0],n+r[0].length):-1}function KP(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.M=+r[0],n+r[0].length):-1}function QP(e,t,n){let r=Nt.exec(t.slice(n,n+2));return r?(e.S=+r[0],n+r[0].length):-1}function HP(e,t,n){let r=Nt.exec(t.slice(n,n+3));return r?(e.L=+r[0],n+r[0].length):-1}function ZP(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 eU(e,t,n){let r=DP.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function tU(e,t,n){let r=Nt.exec(t.slice(n));return r?(e.Q=+r[0],n+r[0].length):-1}function nU(e,t,n){let r=Nt.exec(t.slice(n));return r?(e.s=+r[0],n+r[0].length):-1}function dE(e,t){return ve(e.getDate(),t,2)}function rU(e,t){return ve(e.getHours(),t,2)}function iU(e,t){return ve(e.getHours()%12||12,t,2)}function sU(e,t){return ve(1+tf.count(qi(e),e),t,3)}function v2(e,t){return ve(e.getMilliseconds(),t,3)}function oU(e,t){return`${v2(e,t)}000`}function aU(e,t){return ve(e.getMonth()+1,t,2)}function lU(e,t){return ve(e.getMinutes(),t,2)}function cU(e,t){return ve(e.getSeconds(),t,2)}function uU(e){let t=e.getDay();return t===0?7:t}function fU(e,t){return ve(Yg.count(qi(e).getTime()-1,e),t,2)}function x2(e){let t=e.getDay();return t>=4||t===0?Mo(e):Mo.ceil(e)}function dU(e,t){return e=x2(e),ve(Mo.count(qi(e),e)+(qi(e).getDay()===4?1:0),t,2)}function hU(e){return e.getDay()}function pU(e,t){return ve(Ku.count(qi(e).getTime()-1,e),t,2)}function mU(e,t){return ve(e.getFullYear()%100,t,2)}function gU(e,t){return e=x2(e),ve(e.getFullYear()%100,t,2)}function yU(e,t){return ve(e.getFullYear()%1e4,t,4)}function wU(e,t){let n=e.getDay();return e=n>=4||n===0?Mo(e):Mo.ceil(e),ve(e.getFullYear()%1e4,t,4)}function bU(e){let t=e.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+ve(t/60|0,"0",2)+ve(t%60,"0",2)}function hE(e,t){return ve(e.getUTCDate(),t,2)}function vU(e,t){return ve(e.getUTCHours(),t,2)}function xU(e,t){return ve(e.getUTCHours()%12||12,t,2)}function SU(e,t){return ve(1+Vg.count(Gi(e),e),t,3)}function S2(e,t){return ve(e.getUTCMilliseconds(),t,3)}function kU(e,t){return`${S2(e,t)}000`}function _U(e,t){return ve(e.getUTCMonth()+1,t,2)}function EU(e,t){return ve(e.getUTCMinutes(),t,2)}function AU(e,t){return ve(e.getUTCSeconds(),t,2)}function $U(e){let t=e.getUTCDay();return t===0?7:t}function CU(e,t){return ve(Jg.count(Gi(e).getTime()-1,e),t,2)}function k2(e){let t=e.getUTCDay();return t>=4||t===0?Oo(e):Oo.ceil(e)}function TU(e,t){return e=k2(e),ve(Oo.count(Gi(e),e)+(Gi(e).getUTCDay()===4?1:0),t,2)}function MU(e){return e.getUTCDay()}function OU(e,t){return ve(Qu.count(Gi(e).getTime()-1,e),t,2)}function jU(e,t){return ve(e.getUTCFullYear()%100,t,2)}function NU(e,t){return e=k2(e),ve(e.getUTCFullYear()%100,t,2)}function RU(e,t){return ve(e.getUTCFullYear()%1e4,t,4)}function LU(e,t){let n=e.getUTCDay();return e=n>=4||n===0?Oo(e):Oo.ceil(e),ve(e.getUTCFullYear()%1e4,t,4)}function FU(){return"+0000"}function pE(){return"%"}function mE(e){return+e}function gE(e){return Math.floor(+e/1000)}var ko,_2,IU,E2,A2;DU({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 DU(e){return ko=IP(e),_2=ko.format,IU=ko.parse,E2=ko.utcFormat,A2=ko.utcParse,ko}var $2="%Y-%m-%dT%H:%M:%S.%LZ";function zU(e){return e.toISOString()}var Iwe=typeof Date.prototype.toISOString==="function"?zU:E2($2);function BU(e){let t=new Date(e);return isNaN(+t)?null:t}var Dwe=+new Date("2000-01-01T00:00:00.000Z")?BU:A2($2);function WU(e){return new Date(e)}function PU(e){return e instanceof Date?+e:+new Date(+e)}function C2(e,t,n,r,i,s,o,a,l,c){let u=PE(),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,PU)):d().map(WU)},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(JW(k,C)):u},u.copy=function(){return WE(u,C2(e,t,n,r,i,s,o,a,l,c))},u}function Qg(){let e=C2(wP,bP,ef,Ug,Pg,Wg,Bg,zg,Eo,_2).domain([new Date(2000,0,1),new Date(2000,0,2)]);return SE.apply(e,arguments)}function Rt(e){return function(){return e}}var{abs:Bwe,atan2:Wwe,cos:UU,max:Pwe,min:Uwe,sin:Zg,sqrt:Ro}=Math,T2=0.000000000001,nf=Math.PI,qwe=nf/2,R2=2*nf;var e0=Math.PI,t0=2*e0,qU=t0-0.000001;function L2(e,...t){this._+=e[0];for(let n=1,r=e.length;n<r;++n)this._+=t[n-1]+e[n]}function GU(e){let t=Math.floor(e);if(!(t>=0))throw Error(`invalid digits: ${e}`);if(t>15)return L2;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 rf{_x0;_y0;_x1;_y1;_;_append;constructor(e){this._x0=this._y0=this._x1=this._y1=null,this._="",this._append=e==null?L2:GU(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((e0-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%t0+t0;if(f>qU)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>=e0)},${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 XU(){return new rf}Object.defineProperty(XU,Symbol.hasInstance,{value:(e)=>e instanceof rf});function F2(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 rf(t)}var Gwe=Array.prototype.slice;function I2(e){return typeof e==="object"&&"length"in e?e:Array.from(e)}function D2(e){this._context=e}D2.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 n0(e){return new D2(e)}function z2(e){return e[0]}function B2(e){return e[1]}function Ol(e,t){let n=Rt(!0),r=null,i=n0,s=null,o=F2(a);e=typeof e==="function"?e:e===void 0?z2:Rt(e),t=typeof t==="function"?t:t===void 0?B2:Rt(t);function a(l){let c,u=(l=I2(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 r0(e,t,n){let r=null,i=Rt(!0),s=null,o=n0,a=null,l=F2(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?B2:Rt(+n);function c(f){let d,h=0,p,m=(f=I2(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 Ol().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 W2(e){this._curve=e}W2.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 VU(e){function t(n){return new W2(e(n))}return t._curve=e,t}var Xwe=VU(n0);var Vwe=Ro(3);var YU=Ro(0.3333333333333333),Ywe=YU*2;var P2=Zg(nf/10)/Zg(7*nf/10),Jwe=Zg(R2/10)*P2,Kwe=-UU(R2/10)*P2;var Qwe=Ro(3);var Hwe=Ro(3);var Zwe=Ro(3)/2,JU=1/Ro(12),ebe=(JU/2+1)*3;function Xi(){}function jo(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 i0(e){this._context=e}i0.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:jo(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),jo(this,e,t);break;default:jo(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function KU(e){this._context=e}KU.prototype={areaStart:Xi,areaEnd:Xi,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:jo(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function QU(e){this._context=e}QU.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,jo(this,e,t);break;default:jo(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function U2(e,t){this._basis=new i0(e),this._beta=t}U2.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 tbe=function e(t){function n(r){return t===1?new i0(r):new U2(r,t)}return n.beta=function(r){return e(+r)},n}(0.85);function No(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 s0(e,t){this._context=e,this._k=(1-t)/6}s0.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:No(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,No(this,e,t);break;default:No(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 s0(r,t)}return n.tension=function(r){return e(+r)},n}(0);function o0(e,t){this._context=e,this._k=(1-t)/6}o0.prototype={areaStart:Xi,areaEnd:Xi,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:No(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 rbe=function e(t){function n(r){return new o0(r,t)}return n.tension=function(r){return e(+r)},n}(0);function a0(e,t){this._context=e,this._k=(1-t)/6}a0.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,No(this,e,t);break;default:No(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 ibe=function e(t){function n(r){return new a0(r,t)}return n.tension=function(r){return e(+r)},n}(0);function Ml(e,t,n){let{_x1:r,_y1:i,_x2:s,_y2:o}=e;if(e._l01_a>T2){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>T2){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 q2(e,t){this._context=e,this._alpha=t}q2.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,Ml(this,e,t);break;default:Ml(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 sbe=function e(t){function n(r){return t?new q2(r,t):new s0(r,0)}return n.alpha=function(r){return e(+r)},n}(0.5);function G2(e,t){this._context=e,this._alpha=t}G2.prototype={areaStart:Xi,areaEnd:Xi,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:Ml(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 obe=function e(t){function n(r){return t?new G2(r,t):new o0(r,0)}return n.alpha=function(r){return e(+r)},n}(0.5);function X2(e,t){this._context=e,this._alpha=t}X2.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,Ml(this,e,t);break;default:Ml(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 abe=function e(t){function n(r){return t?new X2(r,t):new a0(r,0)}return n.alpha=function(r){return e(+r)},n}(0.5);function HU(e){this._context=e}HU.prototype={areaStart:Xi,areaEnd:Xi,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 M2(e){return e<0?-1:1}function O2(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(M2(s)+M2(o))*Math.min(Math.abs(s),Math.abs(o),0.5*Math.abs(a))||0}function j2(e,t){let n=e._x1-e._x0;return n?(3*(e._y1-e._y0)/n-t)/2:t}function Hg(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 l0(e){this._context=e}l0.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:Hg(this,this._t0,j2(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,Hg(this,j2(this,n=O2(this,e,t)),n);break;default:Hg(this,this._t0,n=O2(this,e,t));break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t,this._t0=n}};function V2(e){this._context=new Y2(e)}V2.prototype=Object.create(l0.prototype);V2.prototype.point=function(e,t){l0.prototype.point.call(this,t,e)};function Y2(e){this._context=e}Y2.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 ZU(e){this._context=e}ZU.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=N2(e),i=N2(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 N2(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 e8(e,t){this._context=e,this._t=t}e8.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 sf(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function t8(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function J2(e){let t,n,r;if(e.length!==2)t=sf,n=(a,l)=>sf(e(a),l),r=(a,l)=>e(a)-l;else t=e===sf||e===t8?e:n8,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 n8(){return 0}function r8(e){return e===null?NaN:+e}var K2=J2(sf),cbe=K2.right,ube=K2.left,fbe=J2(r8).center;var dbe=Q2(H2),hbe=Q2(i8);function Q2(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)Lo(a,c,i,s,o),Lo(a,i,c,s,o),Lo(a,c,i,s,o),Fo(l,i,c,s,o),Fo(l,c,i,s,o),Fo(l,i,c,s,o);else if(a)Lo(a,i,c,s,o),Lo(a,c,i,s,o),Lo(a,i,c,s,o);else if(l)Fo(l,i,c,s,o),Fo(l,c,i,s,o),Fo(l,i,c,s,o);return t}}function Lo(e,t,n,r,i){for(let s=0,o=r*i;s<o;)e(t,n,s,s+=r,1)}function Fo(e,t,n,r,i){for(let s=0,o=r*i;s<r;++s)e(t,n,s,s+o,r)}function i8(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 s8(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 s8(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 of(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 Z2=Array.prototype,pbe=Z2.slice,mbe=Z2.map;var gbe=Math.sqrt(50),ybe=Math.sqrt(10),wbe=Math.sqrt(2);function c0(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 o8(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 bbe=o8(Math.random);function a8(e){return Math.abs(e=Math.round(e))>=1000000000000000000000?e.toLocaleString("en").replace(/,/g,""):e.toString(10)}function lf(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 l8(e){let t=lf(Math.abs(e));return t?t[1]:NaN}function c8(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 u8(e){return function(t){return t.replace(/[0-9]/g,function(n){return e[+n]})}}var f8=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;class u0{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 oA(e){let t=f8.exec(e);if(!t)throw Error(`invalid format: ${e}`);return new u0({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]})}oA.prototype=u0.prototype;var d8=oA,eA=d8;function h8(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 jl;function p8(e,t){let n=lf(e,t);if(!n)return jl=void 0,e.toPrecision(t);let r=n[0],i=n[1];jl=Math.max(-8,Math.min(8,Math.floor(i/3)))*3;let s=i-jl+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")}${lf(e,Math.max(0,t+s-1))[0]}`}function tA(e,t){let n=lf(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 m8={"%":(e,t)=>(e*100).toFixed(t),b:(e)=>Math.round(e).toString(2),c:(e)=>`${e}`,d:a8,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)=>tA(e*100,t),r:tA,s:p8,X:(e)=>Math.round(e).toString(16).toUpperCase(),x:(e)=>Math.round(e).toString(16)},nA=m8;function rA(e){return e}var iA=Array.prototype.map,sA=["y","z","a","f","p","n","\xB5","m","","k","M","G","T","P","E","Z","Y"];function g8(e){let t=e.grouping===void 0||e.thousands===void 0?rA:c8(iA.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?rA:u8(iA.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=eA(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(!nA[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:""),_=nA[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)$=h8($);if(K&&+$===0&&g!=="+")K=!1;if(M=(K?g==="("?g:a:g==="-"||g==="("?"":g)+M,O=(k==="s"&&!isNaN($)&&jl!==void 0?sA[8+jl/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=eA(f);h.type="f";let p=Math.max(-8,Math.min(8,Math.floor(l8(d)/3)))*3,m=Math.pow(10,-p),g=c(`${h}`,{suffix:sA[8+p/3]});return function(y){return g(m*y)}}return{format:c,formatPrefix:u}}var af,cf,y8;w8({thousands:",",grouping:[3],currency:["$",""]});function w8(e){return af=g8(e),cf=af.format,y8=af.formatPrefix,af}var uf=["#5b9cf5","#6dd97a","#e6c84d","#e25c5c","#c084fc","#f97316","#06b6d4","#ec4899"];function Nl(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]=of(e),a=Os().domain([Math.min(s,0),Math.max(o,1)]).range([n-r,r]),l=Ol().x((u,f)=>i(f)).y((u)=>a(u)),c=r0().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=of(a),u=Qg().domain(c).range([r.left,r.left+s]),f=c0(l)||1,d=Os().domain([0,f*1.1]).range([r.top+o,r.top]).nice(),h=Ol().x((S)=>u(S.date)).y((S)=>d(S.count)),p=r0().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=cf(".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 Rl(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=c0(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:uf[d%uf.length]})),chartWidth:t,chartHeight:s}}function aA(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=of(a),u=Qg().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=Ol().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:uf[b%uf.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=cf(".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 lA="ptry_";function b8(){let e=Fs.randomBytes(32).toString("hex");return`${lA}${e}`}function v8(){return Fs.randomBytes(32).toString("hex")}function Ll(e){return Fs.createHash("sha256").update(e).digest("hex")}function d0(e){return e.startsWith(lA)}async function f0(e){return Bun.password.hash(e,{algorithm:"argon2id"})}async function x8(e,t){return Bun.password.verify(e,t)}class h0{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 Pe("Invalid email address",400);if(!t||t.trim().length===0)throw new Pe("Name is required",400);if(!n||n.length<8)throw new Pe("Password must be at least 8 characters",400);if(await this.storage.getUser(r))throw new Pe("An account with this email already exists",409);let s=new Date().toISOString(),o=await f0(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 Pe("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 Pe("Invalid email address",400);if(!n||n.length<8)throw new Pe("Password must be at least 8 characters",400);let s=await this.storage.getUser(i),o=new Date().toISOString(),a=await f0(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 f0("dummy-password-for-timing-normalization"),new Pe("Invalid email or password",401);if(!await x8(t,r.passwordHash))throw new Pe("Invalid email or password",401);let s=v8(),o={tokenHash:Ll(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(Ll(e))}async validateSession(e){let t=await this.storage.getSession(Ll(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 Pe("Token name is required",400);if(t.length>255)throw new Pe("Token name must be 255 characters or fewer",400);let r=b8(),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:Ll(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(d0(e)){let r=await this.storage.getApiTokenByHash(Ll(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:Sl(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 __(await this.getSubscription(e))}async setSubscription(e,t){let n=e.toLowerCase().trim(),r=await this.storage.getUser(n);if(!r)throw new Pe(`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 Pe("You are already on your own team",400);let s=await this.storage.getUser(r);if(!s)throw new Pe("No such account",404);let o=await this.storage.getUser(i);if(!o)throw new Pe(`${t} does not have an account yet \u2014 they need to sign up first`,404);if(o.teamOwner&&o.teamOwner!==r)throw new Pe(`${t} is already on another team`,409);if(o.team?.members?.length)throw new Pe(`${t} runs their own team`,409);let a=s.team?.members??[];if(a.includes(i))return a;if(a.length+1>=n)throw new Pe(`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 Pe("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 Pe extends Error{status;constructor(e,t=400){super(e);this.name="AuthError",this.status=t}}class p0{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 cA{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 uA extends p0{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 m0(e,t){let n=process.env.S3_BUCKET,r=et();if(r.provider!=="aws"&&n&&n!=="local")return new uA({s3:He(r),bucket:n});let i=e||process.env.DYNAMODB_TABLE||"local";if(i&&i!=="local")return new cA(i,t||process.env.AWS_REGION||"us-east-1");return new p0}function S8(e=process.env){return(e.REGISTRY_PLUGINS||"").split(",").map((t)=>t.trim()).filter(Boolean)}function k8(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 _8(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 k8(i,e)}var ff=null;function df(e=process.env){if(ff)return ff;let t=S8(e);return ff=t.length===0?Promise.resolve([]):Promise.all(t.map(_8)).then((n)=>{return console.log(`Loaded ${n.length} registry plugin(s): ${n.map((r)=>r.name).join(", ")}`),n}),ff}async function fA(){return(await df()).some((t)=>typeof t.authorizeRead==="function")}async function dA(e){let t=await df(),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 hA(e,t){let n=await df();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 g0(e){df().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 pA(e){if(!e)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function E8(e){if(e==null)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"}function Io(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(pA(e.REGISTRY_PRIVATE))return"private";return"public"}function Fl(e=process.env,t=Io(e)){let n=e.REGISTRY_ALLOW_SIGNUP;if(pA(n))return!0;if(E8(n))return!1;return t==="public"}function A8(e=process.env){return(e.REGISTRY_SIGNUP_DOMAINS||"").split(",").map((t)=>t.trim().toLowerCase().replace(/^@/,"")).filter(Boolean)}function mA(e,t=process.env){let n=A8(t);if(n.length===0)return!0;let r=e.toLowerCase().trim().split("@")[1]||"";return n.includes(r)}var $8=new Set(["/health","/ready","/api/registry-info","/login","/signup","/auth/login","/auth/logout","/auth/signup","/auth/me","/favicon.ico","/robots.txt","/webhooks/stripe"]);function C8(e=process.env){return(e.REGISTRY_PUBLIC_PATHS||"").split(",").map((t)=>t.trim()).filter(Boolean)}function T8(e,t=process.env){if($8.has(e))return!0;for(let n of C8(t)){if(n==="/"){if(e==="/")return!0;continue}if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return!0}return!1}function M8(e){if(e.method!=="GET")return!1;return(e.headers.get("accept")||"").includes("text/html")}async function gA(e,t,n){let r=n.env??process.env,i=n.visibility??Io(r),s=t.pathname,o=n.corsHeaders??{},a=i==="public"||T8(s,r),l={authenticated:!1,userId:null},c=a&&!await fA()?l:await n.identify(e),u=await dA({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 g0({type:"access-granted",path:s,method:e.method,userId:c.userId}),null}let f=u==="deny"?"Denied by access policy":"Authentication required";if(g0({type:"access-denied",path:s,method:e.method,reason:f}),M8(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 yA(e=process.env,t){let n=Io(e),r=(t||e.BASE_URL||"").replace(/\/$/,"");return{visibility:n,requiresAuth:n==="private",signupsEnabled:Fl(e,n),...r?{loginUrl:`${r}/login`}:{},docs:"https://pantry.dev/self-hosting"}}function hf(e){return e.toLowerCase().trim().replace(/[^a-z0-9._@-]/g,"_").replace(/@/g,"_at_")}function wA(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 O8(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 j8(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 N8=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||N8,this.maxArtifactBytes=t.maxArtifactBytes??209715200,this.maxEntries=t.maxEntries??2000}indexKey(e){return`mirror/${hf(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=wA(c.name),f=wA(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 O8(m);if(!j8(c.integrity,g))p.error="integrity mismatch \u2014 upstream bytes differ from the lockfile",o++;else{let y=`mirror/${hf(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 w0(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 bA={critical:0,high:1,moderate:2,low:3,unknown:4};function R8(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 L8(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 F8(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 I8=async(e)=>{let t=e.map((i)=>({entry:i,ecosystem:R8(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?L8(p):"unknown",summary:p?.summary||p?.details?.slice(0,200)||d,url:`https://osv.dev/vulnerability/${d}`,fixedIn:p?F8(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 b0(e){return e.trim().toUpperCase()}function D8(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=b0(n);if(t.deny?.some((i)=>b0(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)=>b0(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 v0{storage;fetcher;constructor(e,t=I8){this.storage=e;this.fetcher=t}key(e){return`security/${hf(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=D8(s,t.policy);if(o)n.push(o)}n.sort((s,o)=>{let a=s.type==="vulnerability"?bA[s.severity]:5,l=o.type==="vulnerability"?bA[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 x0(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 xA(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 vA(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 z8(e,t){let n=t.timestamp||new Date().toISOString();return{bomFormat:"CycloneDX",specVersion:"1.5",serialNumber:`urn:uuid:${t.documentId||_A(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:xA(r),...r.license?{licenses:[{license:{id:r.license}}]}:{},...vA(r).length?{hashes:vA(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 B8(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:xA(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||_A(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 SA(e,t,n){return t==="spdx"?B8(e,n):z8(e,n)}function kA(e){return String(e||"").toLowerCase()==="spdx"?"spdx":"cyclonedx"}function _A(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 W8,readFileSync as EA}from"fs";import{join as P8,relative as U8,sep as S0}from"path";var AA=["darwin-arm64","darwin-x86-64","linux-x86-64","linux-arm64"];function $A(e){let t=[],n=(r)=>{for(let i of W8(r,{withFileTypes:!0})){let s=P8(r,i.name);if(i.isDirectory())n(s);else if(i.isFile()&&i.name.endsWith(".ts"))t.push(s)}};return n(e),t}function q8(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 CA(e){let t=new Map;for(let n of $A(e)){if(n.endsWith(`${S0}index.ts`)||n.endsWith(`${S0}aliases.ts`))continue;let r=q8(EA(n,"utf8"));if(r)t.set(r.domain,new Set(r.versions))}return t}function G8(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)=>AA.includes(n))}function TA(e){let t=new Map;for(let n of $A(e)){let i=EA(n,"utf8").match(/platforms:\s*\[([^\]]*)\]/);if(!i)continue;let s=G8(i[1].split(","));if(s.length>0&&s.length<AA.length){let o=U8(e,n).replace(/\.ts$/,"").split(S0).join("/");t.set(o,s)}}return t}import{createHmac as X8,randomUUID as V8,timingSafeEqual as Y8}from"crypto";var jA=1073741824,J8=3600,NA=16,k0=".pantry-staging/malware";class A0{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 se extends Error{status;code;scan;constructor(e,t,n,r){super(e);this.status=t;this.code=n;this.scan=r}}var RA=/^[a-z0-9](?:[a-z0-9._-]|\/(?=[a-z0-9])){0,213}$/i,LA=/^[a-z0-9._+-]{1,64}$/i,FA=/^(?:darwin|linux|windows|freebsd)-(?:arm64|x86-64|x86|riscv64)$/,K8=/^[a-z0-9][a-z0-9._+-]{0,239}\.tar\.gz$/i,IA=/^[a-f0-9]{64}$/;function _0(e,t=jA){if(!e||typeof e!=="object")throw new se("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(!RA.test(r)||r.includes("..")||r.endsWith("/"))throw new se("Invalid binary package domain",422,"INVALID_BINARY_DOMAIN");if(!LA.test(i))throw new se("Invalid binary package version",422,"INVALID_BINARY_VERSION");if(!K8.test(s)||s.includes(".."))throw new se("Invalid binary artifact filename",422,"INVALID_BINARY_FILENAME");if(l.length===0||l.length>NA||l.some((c)=>!FA.test(c)))throw new se("One or more binary platforms are invalid",422,"INVALID_BINARY_PLATFORM");if(!Number.isSafeInteger(a)||a<=0||a>t)throw new se(`Binary artifact size must be between 1 and ${t} bytes`,413,"INVALID_BINARY_SIZE");if(!IA.test(o))throw new se("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 Q8(e){if(!e||typeof e!=="object")throw new se("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(!RA.test(n)||n.includes("..")||n.endsWith("/"))throw new se("Invalid binary package domain",422,"INVALID_BINARY_DOMAIN");if(!LA.test(r))throw new se("Invalid binary package version",422,"INVALID_BINARY_VERSION");if(i.length===0||i.length>NA||i.some((s)=>!FA.test(s)))throw new se("One or more binary platforms are invalid",422,"INVALID_BINARY_PLATFORM");return{domain:n,version:r,platforms:i}}function E0(e){try{return decodeURIComponent(new URL(e).pathname.replace(/^\/+/,""))}catch{return decodeURIComponent(e.replace(/^\/+/,""))}}function H8(e){return Buffer.from(e).toString("base64url")}function Z8(e){return Buffer.from(e,"base64url").toString("utf8")}function MA(e,t){return X8("sha256",t).update(e).digest("base64url")}function e6(e,t){let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&Y8(n,r)}function OA(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 t6(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 Do(e){return`${e}.scan.json`}function DA(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 $0{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||jA,this.stagingTtlSeconds=n.stagingTtlSeconds||J8,this.now=n.now||Date.now}initiate(e){let t=_0(e,this.maxBytes),n={...t,stagingKey:`${k0}/${V8()}/${t.filename}`,expiresAt:this.now()+this.stagingTtlSeconds*1000},r=H8(JSON.stringify(n)),i=MA(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(`${k0}/`,".pantry-staging/sealed/"),s=!0;try{let o=await this.store.headObject(r.stagingKey),a=OA(o);if(a!==null&&a!==r.size)throw new se("Staged artifact size does not match the initiated upload",422,"BINARY_SIZE_MISMATCH")}catch(o){if(o instanceof se)throw o;s=!1}if(!s){let o=await this.findCompleted(r);if(o)return o;throw new se("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 Bm(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 se("Staged artifact size does not match the initiated upload",422,"BINARY_SIZE_MISMATCH");a=await Zn(this.scanner,Uint8Array.from(c).buffer,o)}if(a.artifactSha256!==r.sha256)throw new se("Staged artifact SHA-256 does not match the initiated upload",422,"BINARY_SHA256_MISMATCH",a);if(a.verdict==="blocked")throw new se("Binary artifact blocked by malware scanning",422,"MALWARE_DETECTED",a);if(a.verdict==="review")throw new se("Binary artifact requires security review",202,"PACKAGE_REQUIRES_REVIEW",a);if(a.verdict!=="clean")throw new se("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=_0(e,this.maxBytes);if(t.byteLength!==i.size)throw new se("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=Q8(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 se("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 se(`Binary platform was not found: ${g}`,404,"BINARY_PLATFORM_NOT_FOUND");s[g]=y}let o=[...new Set(Object.values(s).map((g)=>E0(g.tarball)))];if(o.length!==1)throw new se("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 se("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(Do(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=OA(g)??Object.values(s)[0].size}catch{throw new se("Retained binary artifact was not found",404,"BINARY_ARTIFACT_NOT_FOUND")}if(!Number.isSafeInteger(c)||c<=0||c>this.maxBytes)throw new se(`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)=>IA.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 se("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 Bm(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 se("Retained artifact size does not match metadata",422,"BINARY_SIZE_MISMATCH");d=await Zn(this.scanner,Uint8Array.from(g).buffer,f)}if(d.artifactSha256!==u)throw new se("Retained artifact SHA-256 does not match metadata",422,"BINARY_SHA256_MISMATCH",d);if(d.verdict==="error")throw new se("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 se("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(E0(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(Do(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(E0(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(Do(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||!e6(MA(t,this.options.tokenSecret),n))throw new se("Invalid binary staging upload ID",401,"INVALID_BINARY_UPLOAD_ID");let i;try{i=JSON.parse(Z8(t))}catch{throw new se("Invalid binary staging upload ID",401,"INVALID_BINARY_UPLOAD_ID")}let s=_0(i,this.maxBytes),o=i;if(typeof o.stagingKey!=="string"||!o.stagingKey.startsWith(`${k0}/`)||typeof o.expiresAt!=="number")throw new se("Invalid binary staging upload ID",401,"INVALID_BINARY_UPLOAD_ID");if(o.expiresAt<this.now())throw new se("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(Do(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||t6(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 pf(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 vm=new Map;function zme(){try{let e=Bt(typeof import.meta.dirname==="string"?import.meta.dirname:$m(Cm(import.meta.url)),"../../ts-pantry/src/packages/aliases.ts"),t=Dme(e,"utf8");vm.clear();for(let n of t.matchAll(/['"]([^'"\n]+)['"]\s*:\s*['"]([^'"\n]+)['"]/g))vm.set(n[1],n[2]);console.log(`Loaded ${vm.size} package aliases`)}catch(e){console.warn("Could not load package aliases:",e)}}zme();var Li=new Map;async function E4(){try{let e=Bt(typeof import.meta.dirname==="string"?import.meta.dirname:$m(Cm(import.meta.url)),"../../ts-pantry/src/packages"),t=CA(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 E4();var xm=new Map;async function A4(){try{let e=Bt(typeof import.meta.dirname==="string"?import.meta.dirname:$m(Cm(import.meta.url)),"../../ts-pantry/src/recipes"),t=TA(e);xm.clear();for(let[n,r]of t)xm.set(n,r);console.log(`Loaded ${xm.size} platform-constrained packages`)}catch(e){console.warn("Could not load recipe platform constraints:",e)}}await A4();process.on("SIGUSR2",()=>{console.log("SIGUSR2 received \u2014 reloading known versions map"),Promise.all([E4(),A4()]).then(()=>{if(ml)M4(ml)}).catch((e)=>console.error("Reload failed:",e))});function Bme(e,t){let n=Li.get(e);if(!n)return!1;return n.has(t)}var gl=typeof import.meta.dirname==="string"?import.meta.dirname:$m(Cm(import.meta.url)),Wme=Bt(gl,"../dashboard/pages"),$4=Bt(gl,"../site/pages"),Pme=Bt($4,"layout.stx"),Ume=Bt(gl,"../site/components"),pu=[{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"}],n4=[{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"}],r4={promise:null};function C4(){return r4.promise??=t4().then(() => e4).then((e)=>e.renderTemplate),r4.promise}async function ot(e,t={}){let n=t.title||"pantry",i=await(await C4())(Bt($4,e),{context:{...t,title:n},layout:Pme,options:{componentsDir:Ume},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 du(e,t={}){return(await C4())(Bt(Wme,e),{context:t,injectCSS:!0})}function Ue(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}var qme=new Set(["__proto__","constructor","prototype","node_modules","favicon.ico"]);function i4(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(qme.has(e.toLowerCase()))return"Package name is reserved";return null}function s4(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 o4(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 Ss(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 st(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 Gme=16777216,Xme=new Ym(128,60000,Date.now,Gme,(e)=>(e.body.length+e.headers.reduce((t,[n,r])=>t+n.length+r.length,0))*2);async function Pr(e,t){let n=await Xme.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 T4={install:"install","install-on-request":"install_on_request","build-error":"build_error"},ml=null;function M4(e){let t=new Map;for(let[n,r]of Li)t.set(n,[...r]);e.setKnownPackages(t),e.setSupportedPlatforms(new Map(xm))}function qr(){if(!ml){let e=et();ml=new rg(He(e),process.env.S3_BUCKET||"pantry-registry");let t=ml;M4(t),t.load().then(()=>t.refreshCoverage()).catch((n)=>console.error("build-status init failed:",n.message))}return ml}var mm=null,Vme=30000;function Yme(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 a4(){let e=Date.now();if(mm&&e-mm.at<Vme)return mm.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,...Yme(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 mm={at:e,data:n},n}var yk=null;async function Jme(){if(yk===null)yk=await ot("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 yk}function Kme(e,t,n,r,i,s,o,a=r,l=zm(),c){let u=c,f=()=>{if(u)return u;let d=process.env.PANTRY_BINARY_STAGING_SECRET||gu()||"",h=et(),p=new A0(He(h),process.env.S3_BUCKET||"pantry-registry");return u=new $0(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))Am.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(yA(process.env,r),{headers:{...m,"Cache-Control":"no-store"}});let g=await gA(d,h,{identify:po,corsHeaders:m});if(g)return g;let y=await hA(d,{url:h,path:p,method:d.method,visibility:Io()});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(gl,"../../../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:Uk(),health:await l.health()},{headers:{...m,"Cache-Control":"no-store"}});if(p==="/api/v1/binaries/uploads"&&d.method==="POST")return oge(d,f,m);if(p==="/api/v1/binaries/uploads/complete"&&d.method==="POST")return age(d,f,m);if(p==="/api/v1/binaries/rescan"&&d.method==="POST")return lge(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 a4()},{headers:{...m,"Cache-Control":"no-store"}});if(p==="/api/github-actions-status"&&d.method==="GET")return Response.json(await a4(),{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