@ai-development-environment/server 0.0.70 → 0.0.71

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.
Files changed (41) hide show
  1. package/package.json +1 -1
  2. package/standalone/.next/BUILD_ID +1 -1
  3. package/standalone/.next/build-manifest.json +3 -3
  4. package/standalone/.next/prerender-manifest.json +3 -3
  5. package/standalone/.next/server/app/[locale]/comments/page_client-reference-manifest.js +1 -1
  6. package/standalone/.next/server/app/[locale]/pull-requests/page_client-reference-manifest.js +1 -1
  7. package/standalone/.next/server/app/_global-error.html +1 -1
  8. package/standalone/.next/server/app/_global-error.rsc +1 -1
  9. package/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  10. package/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  11. package/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  12. package/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  13. package/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  14. package/standalone/.next/server/app/_not-found.html +1 -1
  15. package/standalone/.next/server/app/_not-found.rsc +1 -1
  16. package/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  17. package/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  18. package/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  19. package/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  20. package/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  21. package/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  22. package/standalone/.next/server/chunks/_01qtprx._.js +1 -1
  23. package/standalone/.next/server/chunks/_0l44maw._.js +2 -2
  24. package/standalone/.next/server/chunks/_0zi1rzc._.js +1 -1
  25. package/standalone/.next/server/chunks/_1czfvql._.js +2 -2
  26. package/standalone/.next/server/chunks/_1gtcfbz._.js +1 -1
  27. package/standalone/.next/server/chunks/_1kemdff._.js +2 -2
  28. package/standalone/.next/server/chunks/_21blfei._.js +2 -2
  29. package/standalone/.next/server/chunks/ssr/_1zd970o._.js +1 -1
  30. package/standalone/.next/server/chunks/ssr/src_components_github_pull-requests-page_tsx_1il3ga-._.js +3 -3
  31. package/standalone/.next/server/middleware-build-manifest.js +3 -3
  32. package/standalone/.next/server/pages/404.html +1 -1
  33. package/standalone/.next/server/pages/500.html +1 -1
  34. package/standalone/.next/server/server-reference-manifest.js +1 -1
  35. package/standalone/.next/server/server-reference-manifest.json +1 -1
  36. package/standalone/.next/static/chunks/{19dkpj43f8v40.js → 0y408zh4mof6_.js} +7 -7
  37. package/standalone/.next/static/chunks/{3_rbnqkar9gd5.js → 3eqo76t2qsipq.js} +1 -1
  38. package/standalone/package.json +6 -5
  39. /package/standalone/.next/static/{YhSq1ZgYFJAvNO3aIVj__ → BzIPghFM13wueh4Fuo7y-}/_buildManifest.js +0 -0
  40. /package/standalone/.next/static/{YhSq1ZgYFJAvNO3aIVj__ → BzIPghFM13wueh4Fuo7y-}/_clientMiddlewareManifest.js +0 -0
  41. /package/standalone/.next/static/{YhSq1ZgYFJAvNO3aIVj__ → BzIPghFM13wueh4Fuo7y-}/_ssgManifest.js +0 -0
@@ -22,7 +22,7 @@ pyQPbp8orlXe+tA8JA==
22
22
  -----END CERTIFICATE-----`;function v8(e){return e instanceof ArrayBuffer?e:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}function v5(e){let t=tD(lO.decodeFirst(e));if(-1===t.offset)throw Error("Certificate is invalid DER");return new m9({schema:t.result})}async function v9(e,t=new Date){let r=await eK.webcrypto.subtle.generateKey(v4,!0,["sign","verify"]),i=new Date(t.getTime()-6e4),a=new Date(t);a.setUTCFullYear(a.getUTCFullYear()+10);let n=await l7.createSelfSigned({name:`CN=${e.replaceAll(/[,+="<>#;]/g,"_")} Device Enrollment`,keys:r,notBefore:i,notAfter:a,signingAlgorithm:v4,extensions:[new lB(!1,void 0,!0),new lL(eE.digitalSignature,!0),await lq.create(r.publicKey,!1,v2)]},v2),s=await eK.webcrypto.subtle.exportKey("pkcs8",r.privateKey),o=Buffer.from(await eK.webcrypto.subtle.digest("SHA-256",n.rawData)).toString("hex").toUpperCase();return{certificatePem:n.toString("pem"),privateKeyPem:lO.encode(s,"PRIVATE KEY"),fingerprint:o,createdAt:i,expiresAt:a}}async function v7(e,t,r){let i=v5(t),a=await eK.webcrypto.subtle.importKey("pkcs8",lO.decodeFirst(r),v4,!1,["sign"]),n=v0.encode(e),s=await eK.webcrypto.subtle.digest("SHA-256",v8(n)),o=new bG({version:1,sid:new gf({issuer:i.issuer,serialNumber:i.serialNumber}),signedAttrs:new bR({type:0,attributes:[new cg({type:"1.2.840.113549.1.9.3",values:[new tz({value:mR.DATA})]}),new cg({type:"1.2.840.113549.1.9.5",values:[new ru({valueDate:new Date})]}),new cg({type:"1.2.840.113549.1.9.4",values:[new tq({valueHex:s})]})]})}),l=new vv({encapContentInfo:new wZ({eContentType:mR.DATA,eContent:new tq({valueHex:v8(n)})}),signerInfos:[o],certificates:[i]});return await l.sign(a,0,"SHA-256",void 0,v3),o.signatureAlgorithm=new cu({algorithmId:"1.2.840.113549.1.1.1",algorithmParams:new tU}),new Uint8Array(new mR({contentType:mR.SIGNED_DATA,content:l.toSchema(!0)}).toSchema().toBER(!1))}async function ke(e,t=v6){let r=mR.fromBER(v8(e));if(r.contentType!==mR.SIGNED_DATA)throw Error("Device response is not CMS SignedData");let i=new vv({schema:r.content});if(1!==i.signerInfos.length)throw Error("Device response must contain one signer");let a=await i.verify({signer:0,checkChain:!1,extendedMode:!0},v3);if(!0!==a.signatureVerified||!a.signerCertificate)throw Error("Device response CMS signature is invalid");let n=v5(t);if(!await a.signerCertificate.verify(n,v3))throw Error("Device identity was not issued by Apple iPhone Device CA");let s=i.encapContentInfo.eContent;if(!(s instanceof tq))throw Error("Device response does not contain an XML plist");return v1.decode(function e(t){if(!t.valueBlock.isConstructed)return new Uint8Array(t.valueBlock.valueHexView);let r=t.valueBlock.value.map(t=>e(t)),i=new Uint8Array(r.reduce((e,t)=>e+t.byteLength,0)),a=0;for(let e of r)i.set(e,a),a+=e.byteLength;return i}(s))}e.s(["generateProfileSigner",0,v9,"randomEnrollmentToken",0,function(){return(0,eK.randomBytes)(32).toString("base64url")},"sha256",0,function(e){let t=("string"==typeof e||e instanceof ArrayBuffer,Buffer.from(e));return(0,eK.createHash)("sha256").update(t).digest("hex")},"signMobileConfig",0,v7,"verifyAppleDeviceResponse",0,ke],791001)},682954,e=>{"use strict";function t(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}let r={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function i(e,t){let r=t;for(;;){let t=e.indexOf("<",r);if(t<0)return null;if(e.startsWith("<!--",t)){let i=e.indexOf("-->",t);if(i<0)return null;r=i+3;continue}if(e.startsWith("<?",t)||e.startsWith("<!",t)){let i=e.indexOf(">",t);if(i<0)return null;r=i+1;continue}let i=e.indexOf(">",t);if(i<0)return null;let a=e.slice(t+1,i),n=a.startsWith("/"),s=a.endsWith("/");return{name:a.slice(+!!n,s?a.length-1:a.length).trim().split(/\s/)[0],closing:n,selfClosing:s,end:i+1}}}function a(e,t,i){let a=e.indexOf(`</${i}`,t);if(a<0)throw Error(`Unterminated <${i}> in plist`);let n=e.indexOf(">",a);return[e.slice(t,a).replace(/&(#x?[0-9a-fA-F]+|[a-z]+);/g,(e,t)=>t.startsWith("#x")||t.startsWith("#X")?String.fromCodePoint(Number.parseInt(t.slice(2),16)):t.startsWith("#")?String.fromCodePoint(Number.parseInt(t.slice(1),10)):r[t]??e),n+1]}e.s(["parsePlist",0,function(e){let t=e.indexOf("<plist"),r=t<0?0:e.indexOf(">",t)+1;return function e(t,r,n){if(n>64)throw Error("plist nesting is too deep");let s=i(t,r);if(!s||s.closing)throw Error("Expected a plist value");if(s.selfClosing)switch(s.name){case"true":return[!0,s.end];case"false":return[!1,s.end];case"dict":return[{},s.end];case"array":return[[],s.end];default:return["",s.end]}switch(s.name){case"dict":{let r={},o=s.end;for(;;){let s=i(t,o);if(!s)throw Error("Unterminated <dict> in plist");if(s.closing&&"dict"===s.name)return[r,s.end];if("key"!==s.name)throw Error("Expected <key> in <dict>");let[l,u]=a(t,s.end,"key"),[c,d]=e(t,u,n+1);r[l]=c,o=d}}case"array":{let r=[],a=s.end;for(;;){let s=i(t,a);if(!s)throw Error("Unterminated <array> in plist");if(s.closing&&"array"===s.name)return[r,s.end];let[o,l]=e(t,a,n+1);r.push(o),a=l}}case"integer":case"real":{let[e,r]=a(t,s.end,s.name);return[Number(e.trim()),r]}case"string":case"date":case"data":{let[e,r]=a(t,s.end,s.name);return["string"===s.name?e:e.trim(),r]}default:{let[,e]=a(t,s.end,s.name);return[null,e]}}}(e,r,0)[0]},"plistDocument",0,function(e){return`<?xml version="1.0" encoding="UTF-8"?>
23
23
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
24
24
  <plist version="1.0">${function e(r){if("boolean"==typeof r)return r?"<true/>":"<false/>";if("string"==typeof r)return`<string>${t(r)}</string>`;if("number"==typeof r&&Number.isInteger(r))return`<integer>${r}</integer>`;if(Array.isArray(r))return`<array>${r.map(t=>e(t)).join("")}</array>`;if(r&&"object"==typeof r)return`<dict>${Object.entries(r).map(([r,i])=>`<key>${t(r)}</key>${e(i)}`).join("")}</dict>`;throw Error("Unsupported plist value")}(e)}</plist>
25
- `}])},115354,49172,493015,149721,e=>{"use strict";e.i(867695);var t=e.i(791001),r=e.i(666680),i=e.i(682954),a=e.i(243783);e.i(582482);var n=e.i(318905),s=e.i(91022),o=e.i(661983),l=e.i(397554),u=e.i(827957);class c extends Error{status;errors;constructor(e,t,r){super(e),this.status=t,this.errors=r,this.name="AppleDeveloperRequestError"}}async function d(e=new s.CredentialService){let t=await (0,a.getPrismaClient)(),r=await t.iosDeviceSettings.findUnique({where:{id:"default"},select:{appStoreConnectIssuerId:!0,appStoreConnectKeyId:!0}});if(!r?.appStoreConnectIssuerId||!r.appStoreConnectKeyId)throw Error("App Store Connect API credentials are not configured");let i=await e.getText(n.CREDENTIALS.appStoreConnectPrivateKey);if(!i)throw Error("App Store Connect API credentials are not configured");return{issuerId:r.appStoreConnectIssuerId,keyId:r.appStoreConnectKeyId,privateKey:i}}class p{credentials;fetcher;constructor(e,t=fetch){this.credentials=e,this.fetcher=t}async token(){let e;try{e=await (0,l.importPKCS8)(this.credentials.privateKey,"ES256")}catch{throw Error("The App Store Connect key must be an ES256 PKCS#8 private key")}return new u.SignJWT({}).setProtectedHeader({alg:"ES256",kid:this.credentials.keyId,typ:"JWT"}).setIssuer(this.credentials.issuerId).setAudience("appstoreconnect-v1").setIssuedAt().setExpirationTime("15m").sign(e)}async request(e,t={}){let r,i=await this.token(),a=e.startsWith("http")?e:`https://api.appstoreconnect.apple.com${e}`;try{r=await this.fetcher(a,{...t,signal:t.signal??AbortSignal.timeout(2e4),headers:{accept:"application/json",authorization:`Bearer ${i}`,...t.body?{"content-type":"application/json"}:{},...t.headers}})}catch(e){if(e instanceof Error&&("TimeoutError"===e.name||"AbortError"===e.name))throw Error("Apple Developer API timed out; retry the operation");throw Error("Could not connect to the Apple Developer API")}if(204===r.status)return;let n=await r.json().catch(()=>({}));if(!r.ok){let e=n.errors?.map(e=>e.detail||e.title||e.code).filter(Boolean).join("; ");throw new c(401===r.status||403===r.status?"Apple rejected the API key or it lacks Certificates, Identifiers & Profiles permission":e||`Apple Developer API returned HTTP ${r.status}`,r.status,n.errors??[])}return n}async list(e){let t=[],r=e;for(;r;){let e=await this.request(r);t.push(...e.data),r=e.links?.next??null}return t}listProfiles(){return this.list("/v1/profiles?limit=200&include=bundleId,certificates,devices")}listCertificates(){return this.list("/v1/certificates?limit=200")}listBundleIds(){return this.list("/v1/bundleIds?limit=200")}listDevices(){return this.list("/v1/devices?limit=200")}async createProfile(e){let t={bundleId:{data:{type:"bundleIds",id:e.bundleIdId}},certificates:{data:e.certificateIds.map(e=>({type:"certificates",id:e}))}};return e.deviceIds?.length&&(t.devices={data:e.deviceIds.map(e=>({type:"devices",id:e}))}),this.request("/v1/profiles",{method:"POST",body:JSON.stringify({data:{type:"profiles",attributes:{name:e.name,profileType:e.profileType},relationships:t}})})}deleteProfile(e){return this.request(`/v1/profiles/${encodeURIComponent(e)}`,{method:"DELETE"})}revokeCertificate(e){return this.request(`/v1/certificates/${encodeURIComponent(e)}`,{method:"DELETE"})}}e.s(["AppleDeveloperClient",0,p,"AppleDeveloperRequestError",0,c,"storedAppleDeveloperCredentials",0,d],49172),e.s([],493015);let h=/^[A-Za-z]+\d+,\d+$/;function m(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`IPSW.me returned an invalid ${t}`);return e}function f(e,t,r){if("string"!=typeof e||!e.trim())throw Error(`IPSW.me returned an invalid ${t}`);let i=e.trim();if(i.length>r)throw Error(`IPSW.me returned an invalid ${t}`);return i}async function g(e,t=fetch){let r,i;if(!h.test(e))throw Error("Device product identifier is invalid");try{r=await t(`https://api.ipsw.me/v4/device/${encodeURIComponent(e)}`,{headers:{accept:"application/json"},signal:AbortSignal.timeout(1e4)})}catch{throw Error("Could not connect to IPSW.me")}if(!r.ok)throw Error(404===r.status?"IPSW.me does not recognize this device model":`IPSW.me returned HTTP ${r.status}`);try{i=await r.json()}catch{throw Error("IPSW.me returned invalid JSON")}let a=m(i,"device response"),n=f(a.identifier,"device identifier",50);if(n!==e)throw Error("IPSW.me returned a different device");if(!Array.isArray(a.firmwares))throw Error("IPSW.me returned an invalid firmware list");return{name:f(a.name,"device name",100),identifier:n,firmwares:a.firmwares.slice(0,1e3).map(e=>(function(e,t){let r,i=m(e,"firmware entry");if(f(i.identifier,"firmware identifier",50)!==t)throw Error("IPSW.me returned firmware for a different device");let a=i.filesize;if("number"!=typeof a||!Number.isSafeInteger(a)||a<0)throw Error("IPSW.me returned an invalid firmware size");let n=f(i.url,"firmware URL",2048);try{r=new URL(n)}catch{throw Error("IPSW.me returned an invalid firmware URL")}if("https:"!==r.protocol)throw Error("IPSW.me returned an insecure firmware URL");let s=new Date(f(i.releasedate,"release date",100));if(Number.isNaN(s.getTime()))throw Error("IPSW.me returned an invalid release date");if("boolean"!=typeof i.signed)throw Error("IPSW.me returned an invalid signing status");return{version:f(i.version,"firmware version",50),buildId:f(i.buildid,"firmware build",50),fileSize:a,url:r.toString(),releaseDate:s.toISOString(),signed:i.signed}})(e,n)).sort((e,t)=>Date.parse(t.releaseDate)-Date.parse(e.releaseDate))}}let y="default";class w extends Error{status;code;constructor(e,t,r){super(e),this.status=t,this.code=r,this.name="IosEnrollmentError"}}function b(e,t,r){let i=e.trim();if(!i)throw Error(`${t} is required`);if(i.length>r)throw Error(`${t} is too long`);return i}function v(e,t,r){if(null==e)return null;if("string"!=typeof e)throw Error(`${t} must be a string`);let i=e.trim();if(i.length>r)throw Error(`${t} is too long`);return i||null}function k(e){return e.replace(/[\t\r\n]/g," ").trim()}e.s(["IosDevicesService",0,class{fetcher;credentials;firmwareCache;constructor(e=fetch,t=new s.CredentialService){this.fetcher=e,this.credentials=t,this.firmwareCache=new Map}changed(e=null){o.agentEventBus.publish(o.IOS_DEVICES_CHANGED_TOPIC,{id:e})}subscribe(){return o.agentEventBus.iterate(o.IOS_DEVICES_CHANGED_TOPIC)}async rawSettings(){return(await (0,a.getPrismaClient)()).iosDeviceSettings.upsert({where:{id:y},create:{id:y},update:{}})}async getSettings(){let[e,t,r]=await Promise.all([this.rawSettings(),this.credentials.isConfigured(n.CREDENTIALS.iosProfileSignerPrivateKey),this.credentials.isConfigured(n.CREDENTIALS.appStoreConnectPrivateKey)]);return{organizationName:e.organizationName,profileIdentifier:e.profileIdentifier,signerConfigured:!!(e.signerCertificatePem&&t),signerFingerprint:e.signerFingerprint,signerCreatedAt:e.signerCreatedAt?.toISOString()??null,signerExpiresAt:e.signerExpiresAt?.toISOString()??null,appStoreConnectConfigured:!!(e.appStoreConnectIssuerId&&e.appStoreConnectKeyId&&r&&e.appStoreConnectVerifiedAt),appStoreConnectIssuerId:e.appStoreConnectIssuerId,appStoreConnectKeyId:e.appStoreConnectKeyId,appStoreConnectPrivateKeyConfigured:!!r,appStoreConnectPrivateKeyFingerprint:e.appStoreConnectPrivateKeyFingerprint,appStoreConnectVerifiedAt:e.appStoreConnectVerifiedAt?.toISOString()??null,appStoreConnectLastTestedAt:e.appStoreConnectLastTestedAt?.toISOString()??null,appStoreConnectVerificationError:e.appStoreConnectVerificationError,updatedAt:e.updatedAt.toISOString()}}async saveProfileSettings(e){let t=b(e.organizationName,"Organization name",100),r=b(e.profileIdentifier,"Profile identifier",200);if(!/^[A-Za-z0-9.-]+$/.test(r))throw Error("Profile identifier may contain only letters, numbers, dots, and hyphens");let i=await (0,a.getPrismaClient)();return await i.iosDeviceSettings.upsert({where:{id:y},create:{id:y,organizationName:t,profileIdentifier:r},update:{organizationName:t,profileIdentifier:r}}),this.getSettings()}async ensureProfileSigner(){let e=await this.rawSettings(),t=e.signerCertificatePem?await this.credentials.getText(n.CREDENTIALS.iosProfileSignerPrivateKey):null;return e.signerCertificatePem&&t?{...e,signerPrivateKeyPem:t}:this.regenerateProfileSigner()}async regenerateProfileSigner(){let e=await this.rawSettings(),r=await (0,t.generateProfileSigner)(e.organizationName);return await this.credentials.setText(n.CREDENTIALS.iosProfileSignerPrivateKey,r.privateKeyPem,async e=>{await e.iosDeviceSettings.update({where:{id:y},data:{signerCertificatePem:r.certificatePem,signerFingerprint:r.fingerprint,signerCreatedAt:r.createdAt,signerExpiresAt:r.expiresAt}})}),{...await this.rawSettings(),signerPrivateKeyPem:r.privateKeyPem}}async regenerateProfileSignerView(){return await this.regenerateProfileSigner(),this.getSettings()}async purgeExpiredEnrollments(e=new Date){let t=await (0,a.getPrismaClient)();await t.iosDeviceEnrollment.updateMany({where:{status:{in:["ISSUED","DOWNLOADED"]},expiresAt:{lt:e}},data:{status:"EXPIRED",failureCode:"TOKEN_EXPIRED"}}),await t.iosDeviceEnrollment.deleteMany({where:{deviceId:null,expiresAt:{lt:new Date(e.getTime()-6048e5)}}})}async createEnrollment(e){let i=b(e,"Device label",100);await this.purgeExpiredEnrollments(),await this.ensureProfileSigner();let n=(0,t.randomEnrollmentToken)(),s=new Date(Date.now()+18e5),o=await (0,a.getPrismaClient)();return{id:(await o.iosDeviceEnrollment.create({data:{id:(0,r.randomUUID)(),tokenHash:(0,t.sha256)(n),displayName:i,expiresAt:s}})).id,token:n,expiresAt:s}}async enrollmentForToken(e){if(!/^[A-Za-z0-9_-]{40,64}$/.test(e))throw new w("Enrollment token is invalid",404,"INVALID_TOKEN");let r=await (0,a.getPrismaClient)(),i=await r.iosDeviceEnrollment.findUnique({where:{tokenHash:(0,t.sha256)(e)}});if(!i)throw new w("Enrollment token is invalid",404,"INVALID_TOKEN");if(!i.consumedAt&&i.expiresAt.getTime()<Date.now())throw await r.iosDeviceEnrollment.update({where:{id:i.id},data:{status:"EXPIRED",failureCode:"TOKEN_EXPIRED"}}),new w("Enrollment token has expired",410,"TOKEN_EXPIRED");return i}async recordIp(e,t,i,n){if(!i)return;let s=await (0,a.getPrismaClient)();await s.iosDeviceIpObservation.upsert({where:{enrollmentId_source_ipAddress:{enrollmentId:e,source:t,ipAddress:i.address}},create:{id:(0,r.randomUUID)(),enrollmentId:e,deviceId:n??null,source:t,ipAddress:i.address,headerSource:i.source},update:{deviceId:n??void 0,headerSource:i.source}})}async enrollmentProfile(e,n,s){let o=await this.enrollmentForToken(e);if(o.consumedAt)throw new w("Enrollment has already completed",410,"TOKEN_CONSUMED");let l=await this.ensureProfileSigner();if(!l.signerCertificatePem||!l.signerPrivateKeyPem)throw new w("Profile signer is unavailable",503,"SIGNER_UNAVAILABLE");let u=function({token:e,publicOrigin:t,organizationName:a,profileIdentifier:n,payloadUuid:s=(0,r.randomUUID)().toUpperCase()}){let o=`${t}/api/public/ios/profile-response?token=${encodeURIComponent(e)}`;return(0,i.plistDocument)({PayloadContent:{URL:o,DeviceAttributes:["UDID","PRODUCT","VERSION"],Challenge:e},PayloadType:"Profile Service",PayloadVersion:1,PayloadIdentifier:n,PayloadUUID:s,PayloadDisplayName:`Register device for ${a}`,PayloadDescription:"Shares this device's identifier, product, and software version for development registration.",PayloadOrganization:a})}({token:e,publicOrigin:n,organizationName:l.organizationName,profileIdentifier:l.profileIdentifier}),c=await (0,t.signMobileConfig)(u,l.signerCertificatePem,l.signerPrivateKeyPem),d=await (0,a.getPrismaClient)();return await d.iosDeviceEnrollment.update({where:{id:o.id},data:{status:"DOWNLOADED",downloadedAt:o.downloadedAt??new Date,failureCode:null}}),await this.recordIp(o.id,"PROFILE_DOWNLOAD",s),c}async completeEnrollment(e,n,s){let o,l,u,c=await this.enrollmentForToken(e),d=(0,t.sha256)(n);if(c.consumedAt){if(c.responseDigest===d&&c.deviceId){let e=await (0,a.getPrismaClient)(),t=await e.iosDevice.findUnique({where:{id:c.deviceId},include:{enrollments:{orderBy:{createdAt:"desc"}},ipObservations:{orderBy:{observedAt:"desc"}}}});if(t)return t}throw new w("Enrollment token has already been consumed",409,"TOKEN_CONSUMED")}try{let r=function(e){if(!e||"object"!=typeof e||Array.isArray(e))throw Error("Device response plist must be a dictionary");return e}((0,i.parsePlist)(await (0,t.verifyAppleDeviceResponse)(n)));if(r.CHALLENGE!==e)throw Error("Device response challenge does not match");o=function(e){if("string"!=typeof e)throw Error("UDID is missing");let t=e.trim().toUpperCase();if(!/^(?:[A-F0-9]{40}|[A-F0-9]{8}-[A-F0-9]{16})$/.test(t))throw Error("UDID has an invalid format");return t}(r.UDID),l=v(r.PRODUCT,"Product",100),u=v(r.VERSION,"Software version",50)}catch(t){let e=await (0,a.getPrismaClient)();if(1!==(await e.iosDeviceEnrollment.updateMany({where:{id:c.id,consumedAt:null},data:{status:"FAILED",failureCode:"INVALID_DEVICE_RESPONSE"}})).count)throw new w("Enrollment token has already been consumed",409,"TOKEN_CONSUMED");throw new w(t instanceof Error?t.message:"Device response is invalid",400,"INVALID_DEVICE_RESPONSE")}let p=new Date,h=await (0,a.getPrismaClient)(),m=await h.$transaction(async e=>{if(1!==(await e.iosDeviceEnrollment.updateMany({where:{id:c.id,consumedAt:null},data:{status:"PROCESSING",consumedAt:p,responseDigest:d,failureCode:null}})).count){let t=await e.iosDeviceEnrollment.findUnique({where:{id:c.id}});if(t?.responseDigest===d&&t.deviceId){let r=await e.iosDevice.findUnique({where:{id:t.deviceId}});if(r)return r}throw new w("Enrollment token has already been consumed",409,"TOKEN_CONSUMED")}let t=await e.iosDevice.findUnique({where:{udid:o}}),i=t?await e.iosDevice.update({where:{id:t.id},data:{product:l,osVersion:u,lastSeenAt:p}}):await e.iosDevice.create({data:{id:(0,r.randomUUID)(),udid:o,displayName:c.displayName,product:l,osVersion:u,lastSeenAt:p}});return await e.iosDeviceEnrollment.update({where:{id:c.id},data:{deviceId:i.id,status:"COMPLETED",failureCode:null}}),await e.iosDeviceIpObservation.updateMany({where:{enrollmentId:c.id},data:{deviceId:i.id}}),s&&await e.iosDeviceIpObservation.upsert({where:{enrollmentId_source_ipAddress:{enrollmentId:c.id,source:"PROFILE_RESPONSE",ipAddress:s.address}},create:{id:(0,r.randomUUID)(),enrollmentId:c.id,deviceId:i.id,source:"PROFILE_RESPONSE",ipAddress:s.address,headerSource:s.source},update:{deviceId:i.id,headerSource:s.source}}),i});return this.changed(m.id),this.device(m.id)}async devices(e){return await this.purgeExpiredEnrollments(),await this.recoverStaleRegistrationClaims(),(await (0,a.getPrismaClient)()).iosDevice.findMany({where:e?{status:e}:void 0,include:{ipObservations:{orderBy:{observedAt:"desc"},take:1}},orderBy:[{createdAt:"desc"},{displayName:"asc"}]})}async device(e){return await this.recoverStaleRegistrationClaims(),(await (0,a.getPrismaClient)()).iosDevice.findUnique({where:{id:e},include:{enrollments:{orderBy:{createdAt:"desc"}},ipObservations:{orderBy:{observedAt:"desc"}}}})}async deviceFirmware(e){let t=await (0,a.getPrismaClient)(),r=await t.iosDevice.findUnique({where:{id:e},select:{product:!0}});if(!r)throw Error("Device not found");if(!r.product)return null;let i=this.firmwareCache.get(r.product);if(i&&i.expiresAt>Date.now())return i.value;let n=await g(r.product,this.fetcher);return this.firmwareCache.set(r.product,{expiresAt:Date.now()+9e5,value:n}),n}async renameDevice(e,t){let r=await (0,a.getPrismaClient)();return await r.iosDevice.update({where:{id:e},data:{displayName:b(t,"Device label",100)}}),this.changed(e),this.device(e)}async rejectDevice(e){let t=await (0,a.getPrismaClient)();if(1!==(await t.iosDevice.updateMany({where:{id:e,status:{in:["PENDING","REGISTRATION_FAILED"]}},data:{status:"REJECTED",registrationError:null}})).count)throw Error("This device cannot be rejected in its current state");return this.changed(e),this.device(e)}async deleteDevice(e){await this.recoverStaleRegistrationClaims();let t=await (0,a.getPrismaClient)(),r=await t.iosDevice.findUnique({where:{id:e}});if(!r)throw Error("Device not found");if("REGISTERING"===r.status||1!==(await t.iosDevice.deleteMany({where:{id:e,status:{not:"REGISTERING"}}})).count)throw Error("Wait for Apple registration to finish before deleting");return this.changed(e),!0}async appleDeveloperCredentials(e){let t=await this.credentials.getText(n.CREDENTIALS.appStoreConnectPrivateKey);if(!e.appStoreConnectIssuerId||!e.appStoreConnectKeyId||!t)throw Error("App Store Connect API credentials are not configured");return{issuerId:e.appStoreConnectIssuerId,keyId:e.appStoreConnectKeyId,privateKey:t}}async appleRequest(e,t,r={},i=""){try{return await new p(e,this.fetcher).request(t,r)}catch(n){let e;if(!(n instanceof c)){if(n instanceof Error&&n.message.includes("timed out"))throw Error("App Store Connect timed out; retry to reconcile the device");if(n instanceof Error&&n.message.includes("ES256 PKCS#8"))throw n;throw Error("Could not connect to App Store Connect")}let t=n.errors?.map(e=>e.detail||e.title||e.code).filter(Boolean).join("; "),r=`${n.errors?.map(e=>`${e.code??""} ${e.title??""} ${e.detail??""}`).join(" ")??""}`.toLowerCase(),a=401===n.status||403===n.status?"App Store Connect rejected the API key or its Certificates, Identifiers & Profiles access":429===n.status?"Apple rate-limited device registration; wait and retry":/maximum|device.?limit|limit.?reached/.test(r)?"The Apple Developer account has reached its annual device limit for this platform":/duplicate|already (?:exists|registered)/.test(r)?"Apple reports that this device already exists; retry registration to reconcile it":/invalid.{0,30}udid|udid.{0,30}invalid/.test(r)?"Apple rejected the UDID as invalid; re-enroll the device and try again":422===n.status?`Apple rejected the device data${t?`: ${t}`:""}`:t||`App Store Connect returned HTTP ${n.status}`;throw Error(i?(e=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a.replace(RegExp(e,"gi"),"[REDACTED]")):a)}}async verifyAppStoreCredentials(e){await this.appleRequest(e,"/v1/devices?limit=1")}async saveAppStoreConnectSettings(e){await this.rawSettings();let r=b(e.issuerId,"Issuer ID",100),i=b(e.keyId,"Key ID",100),a=e.privateKey?.trim()||await this.credentials.getText(n.CREDENTIALS.appStoreConnectPrivateKey);if(!a)throw Error("A .p8 private key is required");if(!a.includes("-----BEGIN PRIVATE KEY-----")||!a.includes("-----END PRIVATE KEY-----"))throw Error("The App Store Connect key must be a PKCS#8 .p8 private key");return await this.verifyAppStoreCredentials({issuerId:r,keyId:i,privateKey:a}),await this.credentials.setText(n.CREDENTIALS.appStoreConnectPrivateKey,a,async e=>{await e.iosDeviceSettings.update({where:{id:y},data:{appStoreConnectIssuerId:r,appStoreConnectKeyId:i,appStoreConnectPrivateKeyFingerprint:(0,t.sha256)(a).toUpperCase(),appStoreConnectVerifiedAt:new Date,appStoreConnectLastTestedAt:new Date,appStoreConnectVerificationError:null}})}),this.getSettings()}async testAppStoreConnectSettings(){let e=await this.rawSettings();if(!e.appStoreConnectIssuerId||!e.appStoreConnectKeyId)throw Error("App Store Connect API credentials are not configured");let t=await (0,a.getPrismaClient)();try{await this.verifyAppStoreCredentials(await this.appleDeveloperCredentials(e))}catch(r){let e=r instanceof Error?r.message:"Credential verification failed";throw await t.iosDeviceSettings.update({where:{id:y},data:{appStoreConnectVerifiedAt:null,appStoreConnectLastTestedAt:new Date,appStoreConnectVerificationError:e}}),Error(e)}return await t.iosDeviceSettings.update({where:{id:y},data:{appStoreConnectVerifiedAt:new Date,appStoreConnectLastTestedAt:new Date,appStoreConnectVerificationError:null}}),this.getSettings()}async clearAppStoreConnectSettings(){return await this.credentials.delete(n.CREDENTIALS.appStoreConnectPrivateKey,async e=>{await e.iosDeviceSettings.upsert({where:{id:y},create:{id:y},update:{appStoreConnectIssuerId:null,appStoreConnectKeyId:null,appStoreConnectPrivateKeyFingerprint:null,appStoreConnectVerifiedAt:null,appStoreConnectLastTestedAt:null,appStoreConnectVerificationError:null}})}),this.getSettings()}async registerDevice(e){await this.recoverStaleRegistrationClaims();let t=await this.rawSettings();if(!t.appStoreConnectIssuerId||!t.appStoreConnectKeyId||!t.appStoreConnectVerifiedAt)throw Error("Configure and verify an App Store Connect API key in Settings first");let r=await this.appleDeveloperCredentials(t),i=await (0,a.getPrismaClient)(),n=await i.iosDevice.findUnique({where:{id:e}});if(!n)throw Error("Device not found");let s=new Date;if(1!==(await i.iosDevice.updateMany({where:{id:e,status:{in:["PENDING","REGISTRATION_FAILED"]}},data:{status:"REGISTERING",registrationClaimedAt:s,registrationError:null}})).count)throw Error("This device cannot be registered in its current state");this.changed(e);try{let t=encodeURIComponent(n.udid),a=(await this.appleRequest(r,`/v1/devices?filter%5Budid%5D=${t}&limit=1`,{},n.udid)).data[0]??(await this.appleRequest(r,"/v1/devices",{method:"POST",body:JSON.stringify({data:{type:"devices",attributes:{name:n.displayName,platform:"IOS",udid:n.udid}}})},n.udid)).data;await i.iosDevice.updateMany({where:{id:e,status:"REGISTERING",registrationClaimedAt:s},data:{status:"REGISTERED",registrationClaimedAt:null,appleDeviceId:a.id,appleStatus:a.attributes.status??"ENABLED",registeredAt:new Date,registrationError:null}})}catch(r){let t=r instanceof Error?r.message:"Apple registration failed";throw await i.iosDevice.updateMany({where:{id:e,status:"REGISTERING",registrationClaimedAt:s},data:{status:"REGISTRATION_FAILED",registrationClaimedAt:null,registrationError:t}}),this.changed(e),Error(t)}return this.changed(e),this.device(e)}async exportTsv(){let e=await (0,a.getPrismaClient)();return["Device ID Device Name Device Platform",...(await e.iosDevice.findMany({where:{status:{not:"REJECTED"}},orderBy:{displayName:"asc"}})).map(e=>`${k(e.udid)} ${k(e.displayName)} ios`)].join("\n")}async recoverStaleRegistrationClaims(e=new Date){let t=await (0,a.getPrismaClient)();(await t.iosDevice.updateMany({where:{status:"REGISTERING",OR:[{registrationClaimedAt:null},{registrationClaimedAt:{lt:new Date(e.getTime()-3e5)}}]},data:{status:"REGISTRATION_FAILED",registrationClaimedAt:null,registrationError:"The previous Apple registration attempt was interrupted; retry registration"}})).count&&this.changed()}},"IosEnrollmentError",0,w],149721),e.s([],115354)},735255,e=>{"use strict";let t=Symbol("unattributed");function r(){return{inputTokens:0,outputTokens:0,cacheCreationTokens:0,cacheReadTokens:0,totalTokens:0,totalCost:0}}function i(e,t){e.inputTokens+=t.inputTokens,e.outputTokens+=t.outputTokens,e.cacheCreationTokens+=t.cacheCreationTokens,e.cacheReadTokens+=t.cacheReadTokens,e.totalTokens+=t.totalTokens,e.totalCost+=t.totalCost}function a(e,t){return t.totalCost-e.totalCost||t.totalTokens-e.totalTokens||(e.modelName??e.agentName??"").localeCompare(t.modelName??t.agentName??"")}e.s(["aggregateUsage",0,function(e){let n=new Map,s=r();for(let{agent:a,report:o}of e)for(let e of(i(s,o.totals),o.daily)){let s=n.get(e.period);s||(s={...r(),period:e.period,models:new Map,sourceSet:new Set},n.set(e.period,s)),i(s,e),e.metadata.agents.forEach(e=>s.sourceSet.add(e));let o=0;for(let t of e.modelBreakdowns){let n={inputTokens:t.inputTokens,outputTokens:t.outputTokens,cacheCreationTokens:t.cacheCreationTokens,cacheReadTokens:t.cacheReadTokens,totalTokens:t.inputTokens+t.outputTokens+t.cacheCreationTokens+t.cacheReadTokens,totalCost:t.cost};o+=n.totalTokens;let l=s.models.get(t.modelName);l||(l={...r(),modelName:t.modelName,agents:new Map},s.models.set(t.modelName,l)),i(l,n);let u=l.agents.get(a.id);u||(u={...r(),agentId:a.id,agentName:a.name,hostname:a.hostname,sources:[],sourceSet:new Set},l.agents.set(a.id,u)),i(u,n),e.metadata.agents.forEach(e=>u.sourceSet.add(e))}!function(e,i,a,n){if(n<=0)return;let s=e.models.get(t);s||(s={...r(),modelName:"Unattributed tokens",agents:new Map,unattributed:!0},e.models.set(t,s)),s.totalTokens+=n;let o=s.agents.get(i.id);o||(o={...r(),agentId:i.id,agentName:i.name,hostname:i.hostname,sources:[],sourceSet:new Set},s.agents.set(i.id,o)),o.totalTokens+=n,a.forEach(e=>o.sourceSet.add(e))}(s,a,e.metadata.agents,e.totalTokens-o)}return{totals:s,days:[...n.values()].sort((e,t)=>t.period.localeCompare(e.period)).map(e=>({inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheCreationTokens:e.cacheCreationTokens,cacheReadTokens:e.cacheReadTokens,totalTokens:e.totalTokens,totalCost:e.totalCost,period:e.period,sources:[...e.sourceSet].sort(),models:[...e.models.values()].sort(a).map(e=>({inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheCreationTokens:e.cacheCreationTokens,cacheReadTokens:e.cacheReadTokens,totalTokens:e.totalTokens,totalCost:e.totalCost,modelName:e.modelName,...e.unattributed?{unattributed:!0}:{},agents:[...e.agents.values()].sort(a).map(e=>({inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheCreationTokens:e.cacheCreationTokens,cacheReadTokens:e.cacheReadTokens,totalTokens:e.totalTokens,totalCost:e.totalCost,agentId:e.agentId,agentName:e.agentName,hostname:e.hostname,sources:[...e.sourceSet].sort()}))}))}))}},"filterUsageByDays",0,function(e,t,a=new Date){let n;if(null===t)return e;let s=new Date(a);s.setHours(0,0,0,0),s.setDate(s.getDate()-(t-1));let o=(n=e=>String(e).padStart(2,"0"),`${s.getFullYear()}-${n(s.getMonth()+1)}-${n(s.getDate())}`),l=e.days.filter(e=>e.period>=o),u=r();return l.forEach(e=>i(u,e)),{days:l,totals:u}}])},121717,483024,988349,e=>{"use strict";var t=e.i(666680),r=e.i(986847),i=e.i(735255),a=e.i(243783);e.i(805422);var n=e.i(694355),s=e.i(661983);let o=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]);e.s(["CcusageService",0,class{agentControlService;now;deadlineTimers;initialized;initializationPromise;completionObservers;constructor(e,t=()=>new Date){this.agentControlService=e,this.now=t,this.deadlineTimers=new Map,this.initialized=!1,this.initializationPromise=null,this.completionObservers=new Set}async initialize(){if(!this.initialized)return this.initializationPromise||(this.initializationPromise=this.restoreCollections().then(()=>{this.initialized=!0}).finally(()=>{this.initializationPromise=null})),this.initializationPromise}async restoreCollections(){let e=await (0,a.getPrismaClient)(),t=await e.ccusageCollection.findMany({where:{finishedAt:null},select:{id:!0}});await Promise.all(t.map(async({id:e})=>{await this.ensureJobs(e),await this.getCollection(e)}))}async collect(e){let r=e?.trim()||(0,t.randomUUID)();await this.ensureCollection(r);let i=await this.waitForCompletion(r);for(let e of this.completionObservers)try{await e(i)}catch(e){console.error("ccusage completion observer failed:",e instanceof Error?e.message:e)}return i}registerCompletionObserver(e){return this.completionObservers.add(e),()=>this.completionObservers.delete(e)}async getCollection(e){let t=await this.loadCollection(e);if(!t)return null;null===t.finishedAt&&t.deadlineAt.getTime()<=this.now().getTime()&&(await this.timeoutMembersWithoutJobs(t),await this.agentControlService.timeoutCollectionJobs(e),t=await this.loadCollection(e)??t);let r=this.snapshot(t);if("COMPLETED"===r.status&&null===t.finishedAt){let t=this.now(),i=await (0,a.getPrismaClient)();await i.ccusageCollection.updateMany({where:{id:e,finishedAt:null},data:{finishedAt:t}}),r.finishedAt=t.toISOString(),this.clearDeadline(e)}else"COLLECTING"===r.status&&this.scheduleDeadline(t);return r}async *subscribe(e){let t=s.agentEventBus.iterate((0,s.ccusageCollectionChangedTopic)(e));try{let r=await this.getCollection(e);for(r&&(yield r);;){if((await t.next()).done)return;let r=await this.getCollection(e);r&&(yield r)}}finally{await t.return?.()}}async ensureCollection(e){let t=await (0,a.getPrismaClient)(),i=await t.ccusageCollection.findUnique({where:{id:e},select:{id:!0}});if(!i){let a=await this.agentControlService.listAgents();try{i=await t.ccusageCollection.create({data:{id:e,deadlineAt:new Date(this.now().getTime()+15e4),agents:{create:a.map(e=>{var t;return{agentId:e.id,initialStatus:(t=this.now().getTime(),null!==e.lastSeenAt&&t-e.lastSeenAt.getTime()<=(0,n.agentOnlineWindowMs)(e)&&null===e.disconnectedAt?(function(e){try{let t=JSON.parse(e.capabilitiesJson);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}})(e).includes(r.CCUSAGE_REPORT_JOB_KIND)?"QUEUING":"UNSUPPORTED":"OFFLINE")}})}},select:{id:!0}}),this.publish(e)}catch(r){if(!(i=await t.ccusageCollection.findUnique({where:{id:e},select:{id:!0}})))throw r}}await this.ensureJobs(e);let s=await this.getCollection(e);if(s?.status==="COLLECTING"){let r=await t.ccusageCollection.findUnique({where:{id:e},select:{id:!0,deadlineAt:!0,finishedAt:!0}});r&&this.scheduleDeadline(r)}}async ensureJobs(e){let t=await (0,a.getPrismaClient)(),i=await t.ccusageCollection.findUnique({where:{id:e},select:{deadlineAt:!0,finishedAt:!0}});if(!i||i.finishedAt||i.deadlineAt.getTime()<=this.now().getTime())return;let n=await t.ccusageCollectionAgent.findMany({where:{collectionId:e,initialStatus:"QUEUING"},select:{agentId:!0}}),s=new Set((await t.agentJob.findMany({where:{ccusageCollectionId:e},select:{agentId:!0}})).map(({agentId:e})=>e));await Promise.all(n.filter(({agentId:e})=>!s.has(e)).map(async({agentId:i})=>{try{await this.agentControlService.createJob({agentId:i,kind:r.CCUSAGE_REPORT_JOB_KIND,payload:{},idempotencyKey:`ccusage:${e}`,timeoutSeconds:120,ccusageCollectionId:e})}catch(r){await t.ccusageCollectionAgent.update({where:{collectionId_agentId:{collectionId:e,agentId:i}},data:{initialStatus:"FAILED",error:r instanceof Error?r.message:String(r)}}),this.publish(e)}}))}async waitForCompletion(e){let t=s.agentEventBus.iterate((0,s.ccusageCollectionChangedTopic)(e));try{for(;;){let r=await this.getCollection(e);if(!r)throw Error("ccusage collection disappeared");if("COMPLETED"===r.status)return r;let i=Math.max(1,new Date(r.deadlineAt).getTime()-this.now().getTime()+25);await Promise.race([t.next(),new Promise(e=>setTimeout(e,i))])}}finally{await t.return?.()}}async loadCollection(e){return(await (0,a.getPrismaClient)()).ccusageCollection.findUnique({where:{id:e},include:{agents:{include:{agent:!0}},jobs:!0}})}async timeoutMembersWithoutJobs(e){let t=new Set(e.jobs.map(({agentId:e})=>e)),r=e.agents.filter(({agentId:e,initialStatus:r})=>"QUEUING"===r&&!t.has(e)).map(({agentId:e})=>e);if(0===r.length)return;let i=await (0,a.getPrismaClient)();(await i.ccusageCollectionAgent.updateMany({where:{collectionId:e.id,agentId:{in:r},initialStatus:"QUEUING"},data:{initialStatus:"TIMED_OUT"}})).count>0&&this.publish(e.id)}snapshot(e){let t=new Map(e.jobs.map(e=>[e.agentId,e])),a=e.agents.map(e=>(function(e,t){let i={agent:e.agent,jobId:t?.id??null};if("QUEUING"!==e.initialStatus)return{progress:{...i,status:e.initialStatus,error:e.error}};if(!t)return{progress:{...i,status:"QUEUING",error:e.error}};if("SUCCEEDED"!==t.status)return{progress:{...i,status:t.status,error:t.error}};try{let e=(0,r.parseCcusageJobResult)(null===t.resultJson?null:JSON.parse(t.resultJson));return{progress:{...i,status:"SUCCEEDED",error:null},report:e.report}}catch(e){return{progress:{...i,status:"INVALID",error:e instanceof Error?e.message:String(e)}}}})(e,t.get(e.agentId))),n=a.map(({progress:e})=>e),s=n.filter(({status:e})=>"OFFLINE"!==e&&"UNSUPPORTED"!==e),l=s.filter(({status:e})=>"INVALID"===e||o.has(e)),u=a.flatMap(({progress:e,report:t})=>t?[{agent:{id:e.agent.id,name:e.agent.name,hostname:e.agent.hostname},report:t}]:[]);return{id:e.id,status:l.length===s.length?"COMPLETED":"COLLECTING",createdAt:e.createdAt.toISOString(),deadlineAt:e.deadlineAt.toISOString(),finishedAt:e.finishedAt?.toISOString()??null,progress:{eligibleCount:s.length,finishedCount:l.length,successfulCount:s.filter(({status:e})=>"SUCCEEDED"===e).length,agents:n},aggregate:(0,i.aggregateUsage)(u)}}scheduleDeadline(e){if(e.finishedAt||this.deadlineTimers.has(e.id))return;let t=setTimeout(()=>{this.deadlineTimers.delete(e.id),this.expire(e.id)},Math.max(0,e.deadlineAt.getTime()-this.now().getTime()));t.unref?.(),this.deadlineTimers.set(e.id,t)}async expire(e){try{await this.agentControlService.timeoutCollectionJobs(e),await this.getCollection(e),this.publish(e)}catch(t){console.error(`Could not expire ccusage collection ${e}:`,t instanceof Error?t.message:t)}}clearDeadline(e){let t=this.deadlineTimers.get(e);t&&clearTimeout(t),this.deadlineTimers.delete(e)}publish(e){s.agentEventBus.publish((0,s.ccusageCollectionChangedTopic)(e),{ccusageCollectionChanged:{id:e}})}}],483024),e.s([],121717),e.s(["CodebaseBusyError",0,class extends Error{constructor(e="Another operation is active for this codebase"){super(e),this.name="CodebaseBusyError"}},"isCodebaseBusyError",0,function(e){return e instanceof Error&&"CodebaseBusyError"===e.name}],988349)},469719,733137,334512,e=>{"use strict";var t,r=e.i(127438),i=e.i(486618);function a(){let e,t,r;return{localeError:(e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}},t={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;return`Invalid input: expected ${e}, received ${n}`}case"invalid_value":if(1===a.values.length)return`Invalid input: expected ${i.stringifyPrimitive(a.values[0])}`;return`Invalid option: expected one of ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Too big: expected ${a.origin??"value"} to have ${t}${a.maximum.toString()} ${r.unit??"elements"}`;return`Too big: expected ${a.origin??"value"} to be ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Too small: expected ${a.origin} to have ${t}${a.minimum.toString()} ${r.unit}`;return`Too small: expected ${a.origin} to be ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Invalid string: must start with "${a.prefix}"`;if("ends_with"===a.format)return`Invalid string: must end with "${a.suffix}"`;if("includes"===a.format)return`Invalid string: must include "${a.includes}"`;if("regex"===a.format)return`Invalid string: must match pattern ${a.pattern}`;return`Invalid ${t[a.format]??a.format}`;case"not_multiple_of":return`Invalid number: must be a multiple of ${a.divisor}`;case"unrecognized_keys":return`Unrecognized key${a.keys.length>1?"s":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Invalid key in ${a.origin}`;case"invalid_union":if(a.options&&Array.isArray(a.options)&&a.options.length>0){let e=a.options.map(e=>`'${e}'`).join(" | ");return`Invalid discriminator value. Expected ${e}`}return"Invalid input";case"invalid_element":return`Invalid value in ${a.origin}`;default:return"Invalid input"}})}}(0,r.config)(a()),e.s([],654048),e.i(654048),e.s([],482811),e.i(482811);var n=e.i(715143),s=e.i(67021),o=e.i(639510);e.s(["$ZodAny",()=>o.$ZodAny,"$ZodArray",()=>o.$ZodArray,"$ZodBase64",()=>o.$ZodBase64,"$ZodBase64URL",()=>o.$ZodBase64URL,"$ZodBigInt",()=>o.$ZodBigInt,"$ZodBigIntFormat",()=>o.$ZodBigIntFormat,"$ZodBoolean",()=>o.$ZodBoolean,"$ZodCIDRv4",()=>o.$ZodCIDRv4,"$ZodCIDRv6",()=>o.$ZodCIDRv6,"$ZodCUID",()=>o.$ZodCUID,"$ZodCUID2",()=>o.$ZodCUID2,"$ZodCatch",()=>o.$ZodCatch,"$ZodCodec",()=>o.$ZodCodec,"$ZodCustom",()=>o.$ZodCustom,"$ZodCustomStringFormat",()=>o.$ZodCustomStringFormat,"$ZodDate",()=>o.$ZodDate,"$ZodDefault",()=>o.$ZodDefault,"$ZodDiscriminatedUnion",()=>o.$ZodDiscriminatedUnion,"$ZodE164",()=>o.$ZodE164,"$ZodEmail",()=>o.$ZodEmail,"$ZodEmoji",()=>o.$ZodEmoji,"$ZodEnum",()=>o.$ZodEnum,"$ZodExactOptional",()=>o.$ZodExactOptional,"$ZodFile",()=>o.$ZodFile,"$ZodFunction",()=>o.$ZodFunction,"$ZodGUID",()=>o.$ZodGUID,"$ZodIPv4",()=>o.$ZodIPv4,"$ZodIPv6",()=>o.$ZodIPv6,"$ZodISODate",()=>o.$ZodISODate,"$ZodISODateTime",()=>o.$ZodISODateTime,"$ZodISODuration",()=>o.$ZodISODuration,"$ZodISOTime",()=>o.$ZodISOTime,"$ZodIntersection",()=>o.$ZodIntersection,"$ZodJWT",()=>o.$ZodJWT,"$ZodKSUID",()=>o.$ZodKSUID,"$ZodLazy",()=>o.$ZodLazy,"$ZodLiteral",()=>o.$ZodLiteral,"$ZodMAC",()=>o.$ZodMAC,"$ZodMap",()=>o.$ZodMap,"$ZodNaN",()=>o.$ZodNaN,"$ZodNanoID",()=>o.$ZodNanoID,"$ZodNever",()=>o.$ZodNever,"$ZodNonOptional",()=>o.$ZodNonOptional,"$ZodNull",()=>o.$ZodNull,"$ZodNullable",()=>o.$ZodNullable,"$ZodNumber",()=>o.$ZodNumber,"$ZodNumberFormat",()=>o.$ZodNumberFormat,"$ZodObject",()=>o.$ZodObject,"$ZodObjectJIT",()=>o.$ZodObjectJIT,"$ZodOptional",()=>o.$ZodOptional,"$ZodPipe",()=>o.$ZodPipe,"$ZodPrefault",()=>o.$ZodPrefault,"$ZodPreprocess",()=>o.$ZodPreprocess,"$ZodPromise",()=>o.$ZodPromise,"$ZodReadonly",()=>o.$ZodReadonly,"$ZodRecord",()=>o.$ZodRecord,"$ZodSet",()=>o.$ZodSet,"$ZodString",()=>o.$ZodString,"$ZodStringFormat",()=>o.$ZodStringFormat,"$ZodSuccess",()=>o.$ZodSuccess,"$ZodSymbol",()=>o.$ZodSymbol,"$ZodTemplateLiteral",()=>o.$ZodTemplateLiteral,"$ZodTransform",()=>o.$ZodTransform,"$ZodTuple",()=>o.$ZodTuple,"$ZodType",()=>o.$ZodType,"$ZodULID",()=>o.$ZodULID,"$ZodURL",()=>o.$ZodURL,"$ZodUUID",()=>o.$ZodUUID,"$ZodUndefined",()=>o.$ZodUndefined,"$ZodUnion",()=>o.$ZodUnion,"$ZodUnknown",()=>o.$ZodUnknown,"$ZodVoid",()=>o.$ZodVoid,"$ZodXID",()=>o.$ZodXID,"$ZodXor",()=>o.$ZodXor,"clone",()=>i.clone,"isValidBase64",()=>o.isValidBase64,"isValidBase64URL",()=>o.isValidBase64URL,"isValidJWT",()=>o.isValidJWT],662429),e.i(662429);var l=e.i(236608),u=e.i(622824),c=e.i(486618),d=e.i(421131);function p(e,t,r,i){let a=Math.abs(e),n=a%10,s=a%100;return s>=11&&s<=19?i:1===n?t:n>=2&&n<=4?r:i}function h(e,t,r){return 1===Math.abs(e)?t:r}function m(e){if(!e)return"";let t=e[e.length-1];return e+(["ա","ե","ը","ի","ո","ու","օ"].includes(t)?"ն":"ը")}function f(){let e,t,r;return{localeError:(e={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}},t={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"},r={nan:"NaN",number:"លេខ",array:"អារេ (Array)",null:"គ្មានតម្លៃ (null)"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${a.expected} ប៉ុន្តែទទួលបាន ${n}`;return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${e} ប៉ុន្តែទទួលបាន ${n}`}case"invalid_value":if(1===a.values.length)return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${i.stringifyPrimitive(a.values[0])}`;return`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`ធំពេក៖ ត្រូវការ ${a.origin??"តម្លៃ"} ${t} ${a.maximum.toString()} ${r.unit??"ធាតុ"}`;return`ធំពេក៖ ត្រូវការ ${a.origin??"តម្លៃ"} ${t} ${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`តូចពេក៖ ត្រូវការ ${a.origin} ${t} ${a.minimum.toString()} ${r.unit}`;return`តូចពេក៖ ត្រូវការ ${a.origin} ${t} ${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${a.prefix}"`;if("ends_with"===a.format)return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${a.suffix}"`;if("includes"===a.format)return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${a.includes}"`;if("regex"===a.format)return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${a.pattern}`;return`មិនត្រឹមត្រូវ៖ ${t[a.format]??a.format}`;case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${a.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${a.origin}`;case"invalid_union":default:return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${a.origin}`}})}}e.s([],879113),e.i(879113);let g=e=>e.charAt(0).toUpperCase()+e.slice(1);function y(e){let t=Math.abs(e),r=t%10,i=t%100;return i>=11&&i<=19||0===r?"many":1===r?"one":"few"}function w(e,t,r,i){let a=Math.abs(e),n=a%10,s=a%100;return s>=11&&s<=19?i:1===n?t:n>=2&&n<=4?r:i}function b(){let e,t,r;return{localeError:(e={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}},t={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"},r={nan:"NaN",number:"число",array:"масив"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Неправильні вхідні дані: очікується instanceof ${a.expected}, отримано ${n}`;return`Неправильні вхідні дані: очікується ${e}, отримано ${n}`}case"invalid_value":if(1===a.values.length)return`Неправильні вхідні дані: очікується ${i.stringifyPrimitive(a.values[0])}`;return`Неправильна опція: очікується одне з ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Занадто велике: очікується, що ${a.origin??"значення"} ${r.verb} ${t}${a.maximum.toString()} ${r.unit??"елементів"}`;return`Занадто велике: очікується, що ${a.origin??"значення"} буде ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Занадто мале: очікується, що ${a.origin} ${r.verb} ${t}${a.minimum.toString()} ${r.unit}`;return`Занадто мале: очікується, що ${a.origin} буде ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Неправильний рядок: повинен починатися з "${a.prefix}"`;if("ends_with"===a.format)return`Неправильний рядок: повинен закінчуватися на "${a.suffix}"`;if("includes"===a.format)return`Неправильний рядок: повинен містити "${a.includes}"`;if("regex"===a.format)return`Неправильний рядок: повинен відповідати шаблону ${a.pattern}`;return`Неправильний ${t[a.format]??a.format}`;case"not_multiple_of":return`Неправильне число: повинно бути кратним ${a.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${a.keys.length>1?"і":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${a.origin}`;case"invalid_union":default:return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${a.origin}`}})}}e.s(["ar",0,function(){let e,t,r;return{localeError:(e={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}},t={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`مدخلات غير مقبولة: يفترض إدخال instanceof ${a.expected}، ولكن تم إدخال ${n}`;return`مدخلات غير مقبولة: يفترض إدخال ${e}، ولكن تم إدخال ${n}`}case"invalid_value":if(1===a.values.length)return`مدخلات غير مقبولة: يفترض إدخال ${i.stringifyPrimitive(a.values[0])}`;return`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return` أكبر من اللازم: يفترض أن تكون ${a.origin??"القيمة"} ${t} ${a.maximum.toString()} ${r.unit??"عنصر"}`;return`أكبر من اللازم: يفترض أن تكون ${a.origin??"القيمة"} ${t} ${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`أصغر من اللازم: يفترض لـ ${a.origin} أن يكون ${t} ${a.minimum.toString()} ${r.unit}`;return`أصغر من اللازم: يفترض لـ ${a.origin} أن يكون ${t} ${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`نَص غير مقبول: يجب أن يبدأ بـ "${a.prefix}"`;if("ends_with"===a.format)return`نَص غير مقبول: يجب أن ينتهي بـ "${a.suffix}"`;if("includes"===a.format)return`نَص غير مقبول: يجب أن يتضمَّن "${a.includes}"`;if("regex"===a.format)return`نَص غير مقبول: يجب أن يطابق النمط ${a.pattern}`;return`${t[a.format]??a.format} غير مقبول`;case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${a.divisor}`;case"unrecognized_keys":return`معرف${a.keys.length>1?"ات":""} غريب${a.keys.length>1?"ة":""}: ${i.joinValues(a.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${a.origin}`;case"invalid_union":default:return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${a.origin}`}})}},"az",0,function(){let e,t,r;return{localeError:(e={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}},t={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Yanlış dəyər: g\xf6zlənilən instanceof ${a.expected}, daxil olan ${n}`;return`Yanlış dəyər: g\xf6zlənilən ${e}, daxil olan ${n}`}case"invalid_value":if(1===a.values.length)return`Yanlış dəyər: g\xf6zlənilən ${i.stringifyPrimitive(a.values[0])}`;return`Yanlış se\xe7im: aşağıdakılardan biri olmalıdır: ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`\xc7ox b\xf6y\xfck: g\xf6zlənilən ${a.origin??"dəyər"} ${t}${a.maximum.toString()} ${r.unit??"element"}`;return`\xc7ox b\xf6y\xfck: g\xf6zlənilən ${a.origin??"dəyər"} ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`\xc7ox ki\xe7ik: g\xf6zlənilən ${a.origin} ${t}${a.minimum.toString()} ${r.unit}`;return`\xc7ox ki\xe7ik: g\xf6zlənilən ${a.origin} ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Yanlış mətn: "${a.prefix}" ilə başlamalıdır`;if("ends_with"===a.format)return`Yanlış mətn: "${a.suffix}" ilə bitməlidir`;if("includes"===a.format)return`Yanlış mətn: "${a.includes}" daxil olmalıdır`;if("regex"===a.format)return`Yanlış mətn: ${a.pattern} şablonuna uyğun olmalıdır`;return`Yanlış ${t[a.format]??a.format}`;case"not_multiple_of":return`Yanlış ədəd: ${a.divisor} ilə b\xf6l\xfcnə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan a\xe7ar${a.keys.length>1?"lar":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`${a.origin} daxilində yanlış a\xe7ar`;case"invalid_union":default:return"Yanlış dəyər";case"invalid_element":return`${a.origin} daxilində yanlış dəyər`}})}},"be",0,function(){let e,t,r;return{localeError:(e={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}},t={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"},r={nan:"NaN",number:"лік",array:"масіў"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Няправільны ўвод: чакаўся instanceof ${a.expected}, атрымана ${n}`;return`Няправільны ўвод: чакаўся ${e}, атрымана ${n}`}case"invalid_value":if(1===a.values.length)return`Няправільны ўвод: чакалася ${i.stringifyPrimitive(a.values[0])}`;return`Няправільны варыянт: чакаўся адзін з ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r){let e=p(Number(a.maximum),r.unit.one,r.unit.few,r.unit.many);return`Занадта вялікі: чакалася, што ${a.origin??"значэнне"} павінна ${r.verb} ${t}${a.maximum.toString()} ${e}`}return`Занадта вялікі: чакалася, што ${a.origin??"значэнне"} павінна быць ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r){let e=p(Number(a.minimum),r.unit.one,r.unit.few,r.unit.many);return`Занадта малы: чакалася, што ${a.origin} павінна ${r.verb} ${t}${a.minimum.toString()} ${e}`}return`Занадта малы: чакалася, што ${a.origin} павінна быць ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Няправільны радок: павінен пачынацца з "${a.prefix}"`;if("ends_with"===a.format)return`Няправільны радок: павінен заканчвацца на "${a.suffix}"`;if("includes"===a.format)return`Няправільны радок: павінен змяшчаць "${a.includes}"`;if("regex"===a.format)return`Няправільны радок: павінен адпавядаць шаблону ${a.pattern}`;return`Няправільны ${t[a.format]??a.format}`;case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${a.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${a.keys.length>1?"ключы":"ключ"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${a.origin}`;case"invalid_union":default:return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${a.origin}`}})}},"bg",0,function(){let e,t,r;return{localeError:(e={string:{unit:"символа",verb:"да съдържа"},file:{unit:"байта",verb:"да съдържа"},array:{unit:"елемента",verb:"да съдържа"},set:{unit:"елемента",verb:"да съдържа"}},t={regex:"вход",email:"имейл адрес",url:"URL",emoji:"емоджи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO време",date:"ISO дата",time:"ISO време",duration:"ISO продължителност",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"base64-кодиран низ",base64url:"base64url-кодиран низ",json_string:"JSON низ",e164:"E.164 номер",jwt:"JWT",template_literal:"вход"},r={nan:"NaN",number:"число",array:"масив"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Невалиден вход: очакван instanceof ${a.expected}, получен ${n}`;return`Невалиден вход: очакван ${e}, получен ${n}`}case"invalid_value":if(1===a.values.length)return`Невалиден вход: очакван ${i.stringifyPrimitive(a.values[0])}`;return`Невалидна опция: очаквано едно от ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Твърде голямо: очаква се ${a.origin??"стойност"} да съдържа ${t}${a.maximum.toString()} ${r.unit??"елемента"}`;return`Твърде голямо: очаква се ${a.origin??"стойност"} да бъде ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Твърде малко: очаква се ${a.origin} да съдържа ${t}${a.minimum.toString()} ${r.unit}`;return`Твърде малко: очаква се ${a.origin} да бъде ${t}${a.minimum.toString()}`}case"invalid_format":{if("starts_with"===a.format)return`Невалиден низ: трябва да започва с "${a.prefix}"`;if("ends_with"===a.format)return`Невалиден низ: трябва да завършва с "${a.suffix}"`;if("includes"===a.format)return`Невалиден низ: трябва да включва "${a.includes}"`;if("regex"===a.format)return`Невалиден низ: трябва да съвпада с ${a.pattern}`;let e="Невалиден";return"emoji"===a.format&&(e="Невалидно"),"datetime"===a.format&&(e="Невалидно"),"date"===a.format&&(e="Невалидна"),"time"===a.format&&(e="Невалидно"),"duration"===a.format&&(e="Невалидна"),`${e} ${t[a.format]??a.format}`}case"not_multiple_of":return`Невалидно число: трябва да бъде кратно на ${a.divisor}`;case"unrecognized_keys":return`Неразпознат${a.keys.length>1?"и":""} ключ${a.keys.length>1?"ове":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Невалиден ключ в ${a.origin}`;case"invalid_union":default:return"Невалиден вход";case"invalid_element":return`Невалидна стойност в ${a.origin}`}})}},"ca",0,function(){let e,t,r;return{localeError:(e={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}},t={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Tipus inv\xe0lid: s'esperava instanceof ${a.expected}, s'ha rebut ${n}`;return`Tipus inv\xe0lid: s'esperava ${e}, s'ha rebut ${n}`}case"invalid_value":if(1===a.values.length)return`Valor inv\xe0lid: s'esperava ${i.stringifyPrimitive(a.values[0])}`;return`Opci\xf3 inv\xe0lida: s'esperava una de ${i.joinValues(a.values," o ")}`;case"too_big":{let t=a.inclusive?"com a màxim":"menys de",r=e[a.origin]??null;if(r)return`Massa gran: s'esperava que ${a.origin??"el valor"} contingu\xe9s ${t} ${a.maximum.toString()} ${r.unit??"elements"}`;return`Massa gran: s'esperava que ${a.origin??"el valor"} fos ${t} ${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?"com a mínim":"més de",r=e[a.origin]??null;if(r)return`Massa petit: s'esperava que ${a.origin} contingu\xe9s ${t} ${a.minimum.toString()} ${r.unit}`;return`Massa petit: s'esperava que ${a.origin} fos ${t} ${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Format inv\xe0lid: ha de comen\xe7ar amb "${a.prefix}"`;if("ends_with"===a.format)return`Format inv\xe0lid: ha d'acabar amb "${a.suffix}"`;if("includes"===a.format)return`Format inv\xe0lid: ha d'incloure "${a.includes}"`;if("regex"===a.format)return`Format inv\xe0lid: ha de coincidir amb el patr\xf3 ${a.pattern}`;return`Format inv\xe0lid per a ${t[a.format]??a.format}`;case"not_multiple_of":return`N\xfamero inv\xe0lid: ha de ser m\xfaltiple de ${a.divisor}`;case"unrecognized_keys":return`Clau${a.keys.length>1?"s":""} no reconeguda${a.keys.length>1?"s":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Clau inv\xe0lida a ${a.origin}`;case"invalid_union":default:return"Entrada invàlida";case"invalid_element":return`Element inv\xe0lid a ${a.origin}`}})}},"cs",0,function(){let e,t,r;return{localeError:(e={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}},t={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"},r={nan:"NaN",number:"číslo",string:"řetězec",function:"funkce",array:"pole"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Neplatn\xfd vstup: oček\xe1v\xe1no instanceof ${a.expected}, obdrženo ${n}`;return`Neplatn\xfd vstup: oček\xe1v\xe1no ${e}, obdrženo ${n}`}case"invalid_value":if(1===a.values.length)return`Neplatn\xfd vstup: oček\xe1v\xe1no ${i.stringifyPrimitive(a.values[0])}`;return`Neplatn\xe1 možnost: oček\xe1v\xe1na jedna z hodnot ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Hodnota je př\xedliš velk\xe1: ${a.origin??"hodnota"} mus\xed m\xedt ${t}${a.maximum.toString()} ${r.unit??"prvků"}`;return`Hodnota je př\xedliš velk\xe1: ${a.origin??"hodnota"} mus\xed b\xfdt ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Hodnota je př\xedliš mal\xe1: ${a.origin??"hodnota"} mus\xed m\xedt ${t}${a.minimum.toString()} ${r.unit??"prvků"}`;return`Hodnota je př\xedliš mal\xe1: ${a.origin??"hodnota"} mus\xed b\xfdt ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Neplatn\xfd řetězec: mus\xed zač\xednat na "${a.prefix}"`;if("ends_with"===a.format)return`Neplatn\xfd řetězec: mus\xed končit na "${a.suffix}"`;if("includes"===a.format)return`Neplatn\xfd řetězec: mus\xed obsahovat "${a.includes}"`;if("regex"===a.format)return`Neplatn\xfd řetězec: mus\xed odpov\xeddat vzoru ${a.pattern}`;return`Neplatn\xfd form\xe1t ${t[a.format]??a.format}`;case"not_multiple_of":return`Neplatn\xe9 č\xedslo: mus\xed b\xfdt n\xe1sobkem ${a.divisor}`;case"unrecognized_keys":return`Nezn\xe1m\xe9 kl\xedče: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Neplatn\xfd kl\xedč v ${a.origin}`;case"invalid_union":default:return"Neplatný vstup";case"invalid_element":return`Neplatn\xe1 hodnota v ${a.origin}`}})}},"da",0,function(){let e,t,r;return{localeError:(e={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}},t={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},r={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Ugyldigt input: forventede instanceof ${a.expected}, fik ${n}`;return`Ugyldigt input: forventede ${e}, fik ${n}`}case"invalid_value":if(1===a.values.length)return`Ugyldig v\xe6rdi: forventede ${i.stringifyPrimitive(a.values[0])}`;return`Ugyldigt valg: forventede en af f\xf8lgende ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",i=e[a.origin]??null,n=r[a.origin]??a.origin;if(i)return`For stor: forventede ${n??"value"} ${i.verb} ${t} ${a.maximum.toString()} ${i.unit??"elementer"}`;return`For stor: forventede ${n??"value"} havde ${t} ${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",i=e[a.origin]??null,n=r[a.origin]??a.origin;if(i)return`For lille: forventede ${n} ${i.verb} ${t} ${a.minimum.toString()} ${i.unit}`;return`For lille: forventede ${n} havde ${t} ${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Ugyldig streng: skal starte med "${a.prefix}"`;if("ends_with"===a.format)return`Ugyldig streng: skal ende med "${a.suffix}"`;if("includes"===a.format)return`Ugyldig streng: skal indeholde "${a.includes}"`;if("regex"===a.format)return`Ugyldig streng: skal matche m\xf8nsteret ${a.pattern}`;return`Ugyldig ${t[a.format]??a.format}`;case"not_multiple_of":return`Ugyldigt tal: skal v\xe6re deleligt med ${a.divisor}`;case"unrecognized_keys":return`${a.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Ugyldig n\xf8gle i ${a.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig v\xe6rdi i ${a.origin}`;default:return"Ugyldigt input"}})}},"de",0,function(){let e,t,r;return{localeError:(e={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}},t={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},r={nan:"NaN",number:"Zahl",array:"Array"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Ung\xfcltige Eingabe: erwartet instanceof ${a.expected}, erhalten ${n}`;return`Ung\xfcltige Eingabe: erwartet ${e}, erhalten ${n}`}case"invalid_value":if(1===a.values.length)return`Ung\xfcltige Eingabe: erwartet ${i.stringifyPrimitive(a.values[0])}`;return`Ung\xfcltige Option: erwartet eine von ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Zu gro\xdf: erwartet, dass ${a.origin??"Wert"} ${t}${a.maximum.toString()} ${r.unit??"Elemente"} hat`;return`Zu gro\xdf: erwartet, dass ${a.origin??"Wert"} ${t}${a.maximum.toString()} ist`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Zu klein: erwartet, dass ${a.origin} ${t}${a.minimum.toString()} ${r.unit} hat`;return`Zu klein: erwartet, dass ${a.origin} ${t}${a.minimum.toString()} ist`}case"invalid_format":if("starts_with"===a.format)return`Ung\xfcltiger String: muss mit "${a.prefix}" beginnen`;if("ends_with"===a.format)return`Ung\xfcltiger String: muss mit "${a.suffix}" enden`;if("includes"===a.format)return`Ung\xfcltiger String: muss "${a.includes}" enthalten`;if("regex"===a.format)return`Ung\xfcltiger String: muss dem Muster ${a.pattern} entsprechen`;return`Ung\xfcltig: ${t[a.format]??a.format}`;case"not_multiple_of":return`Ung\xfcltige Zahl: muss ein Vielfaches von ${a.divisor} sein`;case"unrecognized_keys":return`${a.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Ung\xfcltiger Schl\xfcssel in ${a.origin}`;case"invalid_union":default:return"Ungültige Eingabe";case"invalid_element":return`Ung\xfcltiger Wert in ${a.origin}`}})}},"el",0,function(){let e,t,r;return{localeError:(e={string:{unit:"χαρακτήρες",verb:"να έχει"},file:{unit:"bytes",verb:"να έχει"},array:{unit:"στοιχεία",verb:"να έχει"},set:{unit:"στοιχεία",verb:"να έχει"},map:{unit:"καταχωρήσεις",verb:"να έχει"}},t={regex:"είσοδος",email:"διεύθυνση email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ημερομηνία και ώρα",date:"ISO ημερομηνία",time:"ISO ώρα",duration:"ISO διάρκεια",ipv4:"διεύθυνση IPv4",ipv6:"διεύθυνση IPv6",mac:"διεύθυνση MAC",cidrv4:"εύρος IPv4",cidrv6:"εύρος IPv6",base64:"συμβολοσειρά κωδικοποιημένη σε base64",base64url:"συμβολοσειρά κωδικοποιημένη σε base64url",json_string:"συμβολοσειρά JSON",e164:"αριθμός E.164",jwt:"JWT",template_literal:"είσοδος"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if("string"==typeof a.expected&&/^[A-Z]/.test(a.expected))return`Μη έγκυρη είσοδος: αναμενόταν instanceof ${a.expected}, λήφθηκε ${n}`;return`Μη έγκυρη είσοδος: αναμενόταν ${e}, λήφθηκε ${n}`}case"invalid_value":if(1===a.values.length)return`Μη έγκυρη είσοδος: αναμενόταν ${i.stringifyPrimitive(a.values[0])}`;return`Μη έγκυρη επιλογή: αναμενόταν ένα από ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Πολύ μεγάλο: αναμενόταν ${a.origin??"τιμή"} να έχει ${t}${a.maximum.toString()} ${r.unit??"στοιχεία"}`;return`Πολύ μεγάλο: αναμενόταν ${a.origin??"τιμή"} να είναι ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Πολύ μικρό: αναμενόταν ${a.origin} να έχει ${t}${a.minimum.toString()} ${r.unit}`;return`Πολύ μικρό: αναμενόταν ${a.origin} να είναι ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Μη έγκυρη συμβολοσειρά: πρέπει να ξεκινά με "${a.prefix}"`;if("ends_with"===a.format)return`Μη έγκυρη συμβολοσειρά: πρέπει να τελειώνει με "${a.suffix}"`;if("includes"===a.format)return`Μη έγκυρη συμβολοσειρά: πρέπει να περιέχει "${a.includes}"`;if("regex"===a.format)return`Μη έγκυρη συμβολοσειρά: πρέπει να ταιριάζει με το μοτίβο ${a.pattern}`;return`Μη έγκυρο: ${t[a.format]??a.format}`;case"not_multiple_of":return`Μη έγκυρος αριθμός: πρέπει να είναι πολλαπλάσιο του ${a.divisor}`;case"unrecognized_keys":return`Άγνωστ${a.keys.length>1?"α":"ο"} κλειδ${a.keys.length>1?"ιά":"ί"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Μη έγκυρο κλειδί στο ${a.origin}`;case"invalid_union":default:return"Μη έγκυρη είσοδος";case"invalid_element":return`Μη έγκυρη τιμή στο ${a.origin}`}})}},"en",0,a,"eo",0,function(){let e,t,r;return{localeError:(e={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}},t={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},r={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Nevalida enigo: atendiĝis instanceof ${a.expected}, riceviĝis ${n}`;return`Nevalida enigo: atendiĝis ${e}, riceviĝis ${n}`}case"invalid_value":if(1===a.values.length)return`Nevalida enigo: atendiĝis ${i.stringifyPrimitive(a.values[0])}`;return`Nevalida opcio: atendiĝis unu el ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Tro granda: atendiĝis ke ${a.origin??"valoro"} havu ${t}${a.maximum.toString()} ${r.unit??"elementojn"}`;return`Tro granda: atendiĝis ke ${a.origin??"valoro"} havu ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Tro malgranda: atendiĝis ke ${a.origin} havu ${t}${a.minimum.toString()} ${r.unit}`;return`Tro malgranda: atendiĝis ke ${a.origin} estu ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Nevalida karaktraro: devas komenciĝi per "${a.prefix}"`;if("ends_with"===a.format)return`Nevalida karaktraro: devas finiĝi per "${a.suffix}"`;if("includes"===a.format)return`Nevalida karaktraro: devas inkluzivi "${a.includes}"`;if("regex"===a.format)return`Nevalida karaktraro: devas kongrui kun la modelo ${a.pattern}`;return`Nevalida ${t[a.format]??a.format}`;case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${a.divisor}`;case"unrecognized_keys":return`Nekonata${a.keys.length>1?"j":""} ŝlosilo${a.keys.length>1?"j":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${a.origin}`;case"invalid_union":default:return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${a.origin}`}})}},"es",0,function(){let e,t,r;return{localeError:(e={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}},t={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},r={nan:"NaN",string:"texto",number:"número",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"número grande",symbol:"símbolo",undefined:"indefinido",null:"nulo",function:"función",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeración",union:"unión",literal:"literal",promise:"promesa",void:"vacío",never:"nunca",unknown:"desconocido",any:"cualquiera"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Entrada inv\xe1lida: se esperaba instanceof ${a.expected}, recibido ${n}`;return`Entrada inv\xe1lida: se esperaba ${e}, recibido ${n}`}case"invalid_value":if(1===a.values.length)return`Entrada inv\xe1lida: se esperaba ${i.stringifyPrimitive(a.values[0])}`;return`Opci\xf3n inv\xe1lida: se esperaba una de ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",i=e[a.origin]??null,n=r[a.origin]??a.origin;if(i)return`Demasiado grande: se esperaba que ${n??"valor"} tuviera ${t}${a.maximum.toString()} ${i.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${n??"valor"} fuera ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",i=e[a.origin]??null,n=r[a.origin]??a.origin;if(i)return`Demasiado peque\xf1o: se esperaba que ${n} tuviera ${t}${a.minimum.toString()} ${i.unit}`;return`Demasiado peque\xf1o: se esperaba que ${n} fuera ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Cadena inv\xe1lida: debe comenzar con "${a.prefix}"`;if("ends_with"===a.format)return`Cadena inv\xe1lida: debe terminar en "${a.suffix}"`;if("includes"===a.format)return`Cadena inv\xe1lida: debe incluir "${a.includes}"`;if("regex"===a.format)return`Cadena inv\xe1lida: debe coincidir con el patr\xf3n ${a.pattern}`;return`Inv\xe1lido ${t[a.format]??a.format}`;case"not_multiple_of":return`N\xfamero inv\xe1lido: debe ser m\xfaltiplo de ${a.divisor}`;case"unrecognized_keys":return`Llave${a.keys.length>1?"s":""} desconocida${a.keys.length>1?"s":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Llave inv\xe1lida en ${r[a.origin]??a.origin}`;case"invalid_union":default:return"Entrada inválida";case"invalid_element":return`Valor inv\xe1lido en ${r[a.origin]??a.origin}`}})}},"fa",0,function(){let e,t,r;return{localeError:(e={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}},t={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"},r={nan:"NaN",number:"عدد",array:"آرایه"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`ورودی نامعتبر: می‌بایست instanceof ${a.expected} می‌بود، ${n} دریافت شد`;return`ورودی نامعتبر: می‌بایست ${e} می‌بود، ${n} دریافت شد`}case"invalid_value":if(1===a.values.length)return`ورودی نامعتبر: می‌بایست ${i.stringifyPrimitive(a.values[0])} می‌بود`;return`گزینه نامعتبر: می‌بایست یکی از ${i.joinValues(a.values,"|")} می‌بود`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`خیلی بزرگ: ${a.origin??"مقدار"} باید ${t}${a.maximum.toString()} ${r.unit??"عنصر"} باشد`;return`خیلی بزرگ: ${a.origin??"مقدار"} باید ${t}${a.maximum.toString()} باشد`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`خیلی کوچک: ${a.origin} باید ${t}${a.minimum.toString()} ${r.unit} باشد`;return`خیلی کوچک: ${a.origin} باید ${t}${a.minimum.toString()} باشد`}case"invalid_format":if("starts_with"===a.format)return`رشته نامعتبر: باید با "${a.prefix}" شروع شود`;if("ends_with"===a.format)return`رشته نامعتبر: باید با "${a.suffix}" تمام شود`;if("includes"===a.format)return`رشته نامعتبر: باید شامل "${a.includes}" باشد`;if("regex"===a.format)return`رشته نامعتبر: باید با الگوی ${a.pattern} مطابقت داشته باشد`;return`${t[a.format]??a.format} نامعتبر`;case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${a.divisor} باشد`;case"unrecognized_keys":return`کلید${a.keys.length>1?"های":""} ناشناس: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${a.origin}`;case"invalid_union":default:return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${a.origin}`}})}},"fi",0,function(){let e,t,r;return{localeError:(e={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}},t={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Virheellinen tyyppi: odotettiin instanceof ${a.expected}, oli ${n}`;return`Virheellinen tyyppi: odotettiin ${e}, oli ${n}`}case"invalid_value":if(1===a.values.length)return`Virheellinen sy\xf6te: t\xe4ytyy olla ${i.stringifyPrimitive(a.values[0])}`;return`Virheellinen valinta: t\xe4ytyy olla yksi seuraavista: ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Liian suuri: ${r.subject} t\xe4ytyy olla ${t}${a.maximum.toString()} ${r.unit}`.trim();return`Liian suuri: arvon t\xe4ytyy olla ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Liian pieni: ${r.subject} t\xe4ytyy olla ${t}${a.minimum.toString()} ${r.unit}`.trim();return`Liian pieni: arvon t\xe4ytyy olla ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Virheellinen sy\xf6te: t\xe4ytyy alkaa "${a.prefix}"`;if("ends_with"===a.format)return`Virheellinen sy\xf6te: t\xe4ytyy loppua "${a.suffix}"`;if("includes"===a.format)return`Virheellinen sy\xf6te: t\xe4ytyy sis\xe4lt\xe4\xe4 "${a.includes}"`;if("regex"===a.format)return`Virheellinen sy\xf6te: t\xe4ytyy vastata s\xe4\xe4nn\xf6llist\xe4 lauseketta ${a.pattern}`;return`Virheellinen ${t[a.format]??a.format}`;case"not_multiple_of":return`Virheellinen luku: t\xe4ytyy olla luvun ${a.divisor} monikerta`;case"unrecognized_keys":return`${a.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}})}},"fr",0,function(){let e,t,r;return{localeError:(e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}},t={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},r={string:"chaîne",number:"nombre",int:"entier",boolean:"booléen",bigint:"grand entier",symbol:"symbole",undefined:"indéfini",null:"null",never:"jamais",void:"vide",date:"date",array:"tableau",object:"objet",tuple:"tuple",record:"enregistrement",map:"carte",set:"ensemble",file:"fichier",nonoptional:"non-optionnel",nan:"NaN",function:"fonction"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Entr\xe9e invalide : instanceof ${a.expected} attendu, ${n} re\xe7u`;return`Entr\xe9e invalide : ${e} attendu, ${n} re\xe7u`}case"invalid_value":if(1===a.values.length)return`Entr\xe9e invalide : ${i.stringifyPrimitive(a.values[0])} attendu`;return`Option invalide : une valeur parmi ${i.joinValues(a.values,"|")} attendue`;case"too_big":{let t=a.inclusive?"<=":"<",i=e[a.origin]??null;if(i)return`Trop grand : ${r[a.origin]??"valeur"} doit ${i.verb} ${t}${a.maximum.toString()} ${i.unit??"élément(s)"}`;return`Trop grand : ${r[a.origin]??"valeur"} doit \xeatre ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",i=e[a.origin]??null;if(i)return`Trop petit : ${r[a.origin]??"valeur"} doit ${i.verb} ${t}${a.minimum.toString()} ${i.unit}`;return`Trop petit : ${r[a.origin]??"valeur"} doit \xeatre ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Cha\xeene invalide : doit commencer par "${a.prefix}"`;if("ends_with"===a.format)return`Cha\xeene invalide : doit se terminer par "${a.suffix}"`;if("includes"===a.format)return`Cha\xeene invalide : doit inclure "${a.includes}"`;if("regex"===a.format)return`Cha\xeene invalide : doit correspondre au mod\xe8le ${a.pattern}`;return`${t[a.format]??a.format} invalide`;case"not_multiple_of":return`Nombre invalide : doit \xeatre un multiple de ${a.divisor}`;case"unrecognized_keys":return`Cl\xe9${a.keys.length>1?"s":""} non reconnue${a.keys.length>1?"s":""} : ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Cl\xe9 invalide dans ${a.origin}`;case"invalid_union":default:return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${a.origin}`}})}},"frCA",0,function(){let e,t,r;return{localeError:(e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}},t={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Entr\xe9e invalide : attendu instanceof ${a.expected}, re\xe7u ${n}`;return`Entr\xe9e invalide : attendu ${e}, re\xe7u ${n}`}case"invalid_value":if(1===a.values.length)return`Entr\xe9e invalide : attendu ${i.stringifyPrimitive(a.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"≤":"<",r=e[a.origin]??null;if(r)return`Trop grand : attendu que ${a.origin??"la valeur"} ait ${t}${a.maximum.toString()} ${r.unit}`;return`Trop grand : attendu que ${a.origin??"la valeur"} soit ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?"≥":">",r=e[a.origin]??null;if(r)return`Trop petit : attendu que ${a.origin} ait ${t}${a.minimum.toString()} ${r.unit}`;return`Trop petit : attendu que ${a.origin} soit ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Cha\xeene invalide : doit commencer par "${a.prefix}"`;if("ends_with"===a.format)return`Cha\xeene invalide : doit se terminer par "${a.suffix}"`;if("includes"===a.format)return`Cha\xeene invalide : doit inclure "${a.includes}"`;if("regex"===a.format)return`Cha\xeene invalide : doit correspondre au motif ${a.pattern}`;return`${t[a.format]??a.format} invalide`;case"not_multiple_of":return`Nombre invalide : doit \xeatre un multiple de ${a.divisor}`;case"unrecognized_keys":return`Cl\xe9${a.keys.length>1?"s":""} non reconnue${a.keys.length>1?"s":""} : ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Cl\xe9 invalide dans ${a.origin}`;case"invalid_union":default:return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${a.origin}`}})}},"he",0,function(){let e,t,r,a,n,s,o,l,u;return{localeError:(e={string:{label:"מחרוזת",gender:"f"},number:{label:"מספר",gender:"m"},boolean:{label:"ערך בוליאני",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"תאריך",gender:"m"},array:{label:"מערך",gender:"m"},object:{label:"אובייקט",gender:"m"},null:{label:"ערך ריק (null)",gender:"m"},undefined:{label:"ערך לא מוגדר (undefined)",gender:"m"},symbol:{label:"סימבול (Symbol)",gender:"m"},function:{label:"פונקציה",gender:"f"},map:{label:"מפה (Map)",gender:"f"},set:{label:"קבוצה (Set)",gender:"f"},file:{label:"קובץ",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"ערך לא ידוע",gender:"m"},value:{label:"ערך",gender:"m"}},t={string:{unit:"תווים",shortLabel:"קצר",longLabel:"ארוך"},file:{unit:"בייטים",shortLabel:"קטן",longLabel:"גדול"},array:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},set:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},number:{unit:"",shortLabel:"קטן",longLabel:"גדול"}},r=t=>t?e[t]:void 0,a=t=>{let i=r(t);return i?i.label:t??e.unknown.label},n=e=>`ה${a(e)}`,s=e=>{let t=r(e);return"f"===(t?.gender??"m")?"צריכה להיות":"צריך להיות"},o=e=>e?t[e]??null:null,l={regex:{label:"קלט",gender:"m"},email:{label:"כתובת אימייל",gender:"f"},url:{label:"כתובת רשת",gender:"f"},emoji:{label:"אימוג'י",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"תאריך וזמן ISO",gender:"m"},date:{label:"תאריך ISO",gender:"m"},time:{label:"זמן ISO",gender:"m"},duration:{label:"משך זמן ISO",gender:"m"},ipv4:{label:"כתובת IPv4",gender:"f"},ipv6:{label:"כתובת IPv6",gender:"f"},cidrv4:{label:"טווח IPv4",gender:"m"},cidrv6:{label:"טווח IPv6",gender:"m"},base64:{label:"מחרוזת בבסיס 64",gender:"f"},base64url:{label:"מחרוזת בבסיס 64 לכתובות רשת",gender:"f"},json_string:{label:"מחרוזת JSON",gender:"f"},e164:{label:"מספר E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"קלט",gender:"m"},includes:{label:"קלט",gender:"m"},lowercase:{label:"קלט",gender:"m"},starts_with:{label:"קלט",gender:"m"},uppercase:{label:"קלט",gender:"m"}},u={nan:"NaN"},t=>{switch(t.code){case"invalid_type":{let r=t.expected,n=u[r??""]??a(r),s=i.parsedType(t.input),o=u[s]??e[s]?.label??s;if(/^[A-Z]/.test(t.expected))return`קלט לא תקין: צריך להיות instanceof ${t.expected}, התקבל ${o}`;return`קלט לא תקין: צריך להיות ${n}, התקבל ${o}`}case"invalid_value":{if(1===t.values.length)return`ערך לא תקין: הערך חייב להיות ${i.stringifyPrimitive(t.values[0])}`;let e=t.values.map(e=>i.stringifyPrimitive(e));if(2===t.values.length)return`ערך לא תקין: האפשרויות המתאימות הן ${e[0]} או ${e[1]}`;let r=e[e.length-1],a=e.slice(0,-1).join(", ");return`ערך לא תקין: האפשרויות המתאימות הן ${a} או ${r}`}case"too_big":{let e=o(t.origin),r=n(t.origin??"value");if("string"===t.origin)return`${e?.longLabel??"ארוך"} מדי: ${r} צריכה להכיל ${t.maximum.toString()} ${e?.unit??""} ${t.inclusive?"או פחות":"לכל היותר"}`.trim();if("number"===t.origin){let e=t.inclusive?`קטן או שווה ל-${t.maximum}`:`קטן מ-${t.maximum}`;return`גדול מדי: ${r} צריך להיות ${e}`}if("array"===t.origin||"set"===t.origin){let i="set"===t.origin?"צריכה":"צריך",a=t.inclusive?`${t.maximum} ${e?.unit??""} או פחות`:`פחות מ-${t.maximum} ${e?.unit??""}`;return`גדול מדי: ${r} ${i} להכיל ${a}`.trim()}let i=t.inclusive?"<=":"<",a=s(t.origin??"value");if(e?.unit)return`${e.longLabel} מדי: ${r} ${a} ${i}${t.maximum.toString()} ${e.unit}`;return`${e?.longLabel??"גדול"} מדי: ${r} ${a} ${i}${t.maximum.toString()}`}case"too_small":{let e=o(t.origin),r=n(t.origin??"value");if("string"===t.origin)return`${e?.shortLabel??"קצר"} מדי: ${r} צריכה להכיל ${t.minimum.toString()} ${e?.unit??""} ${t.inclusive?"או יותר":"לפחות"}`.trim();if("number"===t.origin){let e=t.inclusive?`גדול או שווה ל-${t.minimum}`:`גדול מ-${t.minimum}`;return`קטן מדי: ${r} צריך להיות ${e}`}if("array"===t.origin||"set"===t.origin){let i="set"===t.origin?"צריכה":"צריך";if(1===t.minimum&&t.inclusive){let e=(t.origin,"לפחות פריט אחד");return`קטן מדי: ${r} ${i} להכיל ${e}`}let a=t.inclusive?`${t.minimum} ${e?.unit??""} או יותר`:`יותר מ-${t.minimum} ${e?.unit??""}`;return`קטן מדי: ${r} ${i} להכיל ${a}`.trim()}let i=t.inclusive?">=":">",a=s(t.origin??"value");if(e?.unit)return`${e.shortLabel} מדי: ${r} ${a} ${i}${t.minimum.toString()} ${e.unit}`;return`${e?.shortLabel??"קטן"} מדי: ${r} ${a} ${i}${t.minimum.toString()}`}case"invalid_format":{if("starts_with"===t.format)return`המחרוזת חייבת להתחיל ב "${t.prefix}"`;if("ends_with"===t.format)return`המחרוזת חייבת להסתיים ב "${t.suffix}"`;if("includes"===t.format)return`המחרוזת חייבת לכלול "${t.includes}"`;if("regex"===t.format)return`המחרוזת חייבת להתאים לתבנית ${t.pattern}`;let e=l[t.format],r=e?.label??t.format,i=e?.gender??"m";return`${r} לא ${"f"===i?"תקינה":"תקין"}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${t.divisor}`;case"unrecognized_keys":return`מפתח${t.keys.length>1?"ות":""} לא מזוה${t.keys.length>1?"ים":"ה"}: ${i.joinValues(t.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":default:return"קלט לא תקין";case"invalid_element":{let e=n(t.origin??"array");return`ערך לא תקין ב${e}`}}})}},"hr",0,function(){let e,t,r;return{localeError:(e={string:{unit:"znakova",verb:"imati"},file:{unit:"bajtova",verb:"imati"},array:{unit:"stavki",verb:"imati"},set:{unit:"stavki",verb:"imati"}},t={regex:"unos",email:"email adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum i vrijeme",date:"ISO datum",time:"ISO vrijeme",duration:"ISO trajanje",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"IPv4 raspon",cidrv6:"IPv6 raspon",base64:"base64 kodirani tekst",base64url:"base64url kodirani tekst",json_string:"JSON tekst",e164:"E.164 broj",jwt:"JWT",template_literal:"unos"},r={nan:"NaN",string:"tekst",number:"broj",boolean:"boolean",array:"niz",object:"objekt",set:"skup",file:"datoteka",date:"datum",bigint:"bigint",symbol:"simbol",undefined:"undefined",null:"null",function:"funkcija",map:"mapa"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Neispravan unos: očekuje se instanceof ${a.expected}, a primljeno je ${n}`;return`Neispravan unos: očekuje se ${e}, a primljeno je ${n}`}case"invalid_value":if(1===a.values.length)return`Neispravna vrijednost: očekivano ${i.stringifyPrimitive(a.values[0])}`;return`Neispravna opcija: očekivano jedno od ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",i=e[a.origin]??null,n=r[a.origin]??a.origin;if(i)return`Preveliko: očekivano da ${n??"vrijednost"} ima ${t}${a.maximum.toString()} ${i.unit??"elemenata"}`;return`Preveliko: očekivano da ${n??"vrijednost"} bude ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",i=e[a.origin]??null,n=r[a.origin]??a.origin;if(i)return`Premalo: očekivano da ${n} ima ${t}${a.minimum.toString()} ${i.unit}`;return`Premalo: očekivano da ${n} bude ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Neispravan tekst: mora započinjati s "${a.prefix}"`;if("ends_with"===a.format)return`Neispravan tekst: mora završavati s "${a.suffix}"`;if("includes"===a.format)return`Neispravan tekst: mora sadržavati "${a.includes}"`;if("regex"===a.format)return`Neispravan tekst: mora odgovarati uzorku ${a.pattern}`;return`Neispravna ${t[a.format]??a.format}`;case"not_multiple_of":return`Neispravan broj: mora biti višekratnik od ${a.divisor}`;case"unrecognized_keys":return`Neprepoznat${a.keys.length>1?"i ključevi":" ključ"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Neispravan ključ u ${r[a.origin]??a.origin}`;case"invalid_union":default:return"Neispravan unos";case"invalid_element":return`Neispravna vrijednost u ${r[a.origin]??a.origin}`}})}},"hu",0,function(){let e,t,r;return{localeError:(e={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}},t={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"},r={nan:"NaN",number:"szám",array:"tömb"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`\xc9rv\xe9nytelen bemenet: a v\xe1rt \xe9rt\xe9k instanceof ${a.expected}, a kapott \xe9rt\xe9k ${n}`;return`\xc9rv\xe9nytelen bemenet: a v\xe1rt \xe9rt\xe9k ${e}, a kapott \xe9rt\xe9k ${n}`}case"invalid_value":if(1===a.values.length)return`\xc9rv\xe9nytelen bemenet: a v\xe1rt \xe9rt\xe9k ${i.stringifyPrimitive(a.values[0])}`;return`\xc9rv\xe9nytelen opci\xf3: valamelyik \xe9rt\xe9k v\xe1rt ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`T\xfal nagy: ${a.origin??"érték"} m\xe9rete t\xfal nagy ${t}${a.maximum.toString()} ${r.unit??"elem"}`;return`T\xfal nagy: a bemeneti \xe9rt\xe9k ${a.origin??"érték"} t\xfal nagy: ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`T\xfal kicsi: a bemeneti \xe9rt\xe9k ${a.origin} m\xe9rete t\xfal kicsi ${t}${a.minimum.toString()} ${r.unit}`;return`T\xfal kicsi: a bemeneti \xe9rt\xe9k ${a.origin} t\xfal kicsi ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`\xc9rv\xe9nytelen string: "${a.prefix}" \xe9rt\xe9kkel kell kezdődnie`;if("ends_with"===a.format)return`\xc9rv\xe9nytelen string: "${a.suffix}" \xe9rt\xe9kkel kell v\xe9gződnie`;if("includes"===a.format)return`\xc9rv\xe9nytelen string: "${a.includes}" \xe9rt\xe9ket kell tartalmaznia`;if("regex"===a.format)return`\xc9rv\xe9nytelen string: ${a.pattern} mint\xe1nak kell megfelelnie`;return`\xc9rv\xe9nytelen ${t[a.format]??a.format}`;case"not_multiple_of":return`\xc9rv\xe9nytelen sz\xe1m: ${a.divisor} t\xf6bbsz\xf6r\xf6s\xe9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${a.keys.length>1?"s":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`\xc9rv\xe9nytelen kulcs ${a.origin}`;case"invalid_union":default:return"Érvénytelen bemenet";case"invalid_element":return`\xc9rv\xe9nytelen \xe9rt\xe9k: ${a.origin}`}})}},"hy",0,function(){let e,t,r;return{localeError:(e={string:{unit:{one:"նշան",many:"նշաններ"},verb:"ունենալ"},file:{unit:{one:"բայթ",many:"բայթեր"},verb:"ունենալ"},array:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"},set:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"}},t={regex:"մուտք",email:"էլ. հասցե",url:"URL",emoji:"էմոջի",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ամսաթիվ և ժամ",date:"ISO ամսաթիվ",time:"ISO ժամ",duration:"ISO տևողություն",ipv4:"IPv4 հասցե",ipv6:"IPv6 հասցե",cidrv4:"IPv4 միջակայք",cidrv6:"IPv6 միջակայք",base64:"base64 ձևաչափով տող",base64url:"base64url ձևաչափով տող",json_string:"JSON տող",e164:"E.164 համար",jwt:"JWT",template_literal:"մուտք"},r={nan:"NaN",number:"թիվ",array:"զանգված"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Սխալ մուտքագրում․ սպասվում էր instanceof ${a.expected}, ստացվել է ${n}`;return`Սխալ մուտքագրում․ սպասվում էր ${e}, ստացվել է ${n}`}case"invalid_value":if(1===a.values.length)return`Սխալ մուտքագրում․ սպասվում էր ${i.stringifyPrimitive(a.values[1])}`;return`Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r){let e=h(Number(a.maximum),r.unit.one,r.unit.many);return`Չափազանց մեծ արժեք․ սպասվում է, որ ${m(a.origin??"արժեք")} կունենա ${t}${a.maximum.toString()} ${e}`}return`Չափազանց մեծ արժեք․ սպասվում է, որ ${m(a.origin??"արժեք")} լինի ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r){let e=h(Number(a.minimum),r.unit.one,r.unit.many);return`Չափազանց փոքր արժեք․ սպասվում է, որ ${m(a.origin)} կունենա ${t}${a.minimum.toString()} ${e}`}return`Չափազանց փոքր արժեք․ սպասվում է, որ ${m(a.origin)} լինի ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Սխալ տող․ պետք է սկսվի "${a.prefix}"-ով`;if("ends_with"===a.format)return`Սխալ տող․ պետք է ավարտվի "${a.suffix}"-ով`;if("includes"===a.format)return`Սխալ տող․ պետք է պարունակի "${a.includes}"`;if("regex"===a.format)return`Սխալ տող․ պետք է համապատասխանի ${a.pattern} ձևաչափին`;return`Սխալ ${t[a.format]??a.format}`;case"not_multiple_of":return`Սխալ թիվ․ պետք է բազմապատիկ լինի ${a.divisor}-ի`;case"unrecognized_keys":return`Չճանաչված բանալի${a.keys.length>1?"ներ":""}. ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Սխալ բանալի ${m(a.origin)}-ում`;case"invalid_union":default:return"Սխալ մուտքագրում";case"invalid_element":return`Սխալ արժեք ${m(a.origin)}-ում`}})}},"id",0,function(){let e,t,r;return{localeError:(e={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}},t={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Input tidak valid: diharapkan instanceof ${a.expected}, diterima ${n}`;return`Input tidak valid: diharapkan ${e}, diterima ${n}`}case"invalid_value":if(1===a.values.length)return`Input tidak valid: diharapkan ${i.stringifyPrimitive(a.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Terlalu besar: diharapkan ${a.origin??"value"} memiliki ${t}${a.maximum.toString()} ${r.unit??"elemen"}`;return`Terlalu besar: diharapkan ${a.origin??"value"} menjadi ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Terlalu kecil: diharapkan ${a.origin} memiliki ${t}${a.minimum.toString()} ${r.unit}`;return`Terlalu kecil: diharapkan ${a.origin} menjadi ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`String tidak valid: harus dimulai dengan "${a.prefix}"`;if("ends_with"===a.format)return`String tidak valid: harus berakhir dengan "${a.suffix}"`;if("includes"===a.format)return`String tidak valid: harus menyertakan "${a.includes}"`;if("regex"===a.format)return`String tidak valid: harus sesuai pola ${a.pattern}`;return`${t[a.format]??a.format} tidak valid`;case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${a.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${a.keys.length>1?"s":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${a.origin}`;case"invalid_union":default:return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${a.origin}`}})}},"is",0,function(){let e,t,r;return{localeError:(e={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}},t={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"},r={nan:"NaN",number:"númer",array:"fylki"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Rangt gildi: \xde\xfa sl\xf3st inn ${n} \xfear sem \xe1 a\xf0 vera instanceof ${a.expected}`;return`Rangt gildi: \xde\xfa sl\xf3st inn ${n} \xfear sem \xe1 a\xf0 vera ${e}`}case"invalid_value":if(1===a.values.length)return`Rangt gildi: gert r\xe1\xf0 fyrir ${i.stringifyPrimitive(a.values[0])}`;return`\xd3gilt val: m\xe1 vera eitt af eftirfarandi ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Of st\xf3rt: gert er r\xe1\xf0 fyrir a\xf0 ${a.origin??"gildi"} hafi ${t}${a.maximum.toString()} ${r.unit??"hluti"}`;return`Of st\xf3rt: gert er r\xe1\xf0 fyrir a\xf0 ${a.origin??"gildi"} s\xe9 ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Of l\xedti\xf0: gert er r\xe1\xf0 fyrir a\xf0 ${a.origin} hafi ${t}${a.minimum.toString()} ${r.unit}`;return`Of l\xedti\xf0: gert er r\xe1\xf0 fyrir a\xf0 ${a.origin} s\xe9 ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`\xd3gildur strengur: ver\xf0ur a\xf0 byrja \xe1 "${a.prefix}"`;if("ends_with"===a.format)return`\xd3gildur strengur: ver\xf0ur a\xf0 enda \xe1 "${a.suffix}"`;if("includes"===a.format)return`\xd3gildur strengur: ver\xf0ur a\xf0 innihalda "${a.includes}"`;if("regex"===a.format)return`\xd3gildur strengur: ver\xf0ur a\xf0 fylgja mynstri ${a.pattern}`;return`Rangt ${t[a.format]??a.format}`;case"not_multiple_of":return`R\xf6ng tala: ver\xf0ur a\xf0 vera margfeldi af ${a.divisor}`;case"unrecognized_keys":return`\xd3\xfeekkt ${a.keys.length>1?"ir lyklar":"ur lykill"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Rangur lykill \xed ${a.origin}`;case"invalid_union":default:return"Rangt gildi";case"invalid_element":return`Rangt gildi \xed ${a.origin}`}})}},"it",0,function(){let e,t,r;return{localeError:(e={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}},t={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},r={nan:"NaN",number:"numero",array:"vettore"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Input non valido: atteso instanceof ${a.expected}, ricevuto ${n}`;return`Input non valido: atteso ${e}, ricevuto ${n}`}case"invalid_value":if(1===a.values.length)return`Input non valido: atteso ${i.stringifyPrimitive(a.values[0])}`;return`Opzione non valida: atteso uno tra ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Troppo grande: ${a.origin??"valore"} deve avere ${t}${a.maximum.toString()} ${r.unit??"elementi"}`;return`Troppo grande: ${a.origin??"valore"} deve essere ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Troppo piccolo: ${a.origin} deve avere ${t}${a.minimum.toString()} ${r.unit}`;return`Troppo piccolo: ${a.origin} deve essere ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Stringa non valida: deve iniziare con "${a.prefix}"`;if("ends_with"===a.format)return`Stringa non valida: deve terminare con "${a.suffix}"`;if("includes"===a.format)return`Stringa non valida: deve includere "${a.includes}"`;if("regex"===a.format)return`Stringa non valida: deve corrispondere al pattern ${a.pattern}`;return`Input non valido: ${t[a.format]??a.format}`;case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${a.divisor}`;case"unrecognized_keys":return`Chiav${a.keys.length>1?"i":"e"} non riconosciut${a.keys.length>1?"e":"a"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${a.origin}`;case"invalid_union":default:return"Input non valido";case"invalid_element":return`Valore non valido in ${a.origin}`}})}},"ja",0,function(){let e,t,r;return{localeError:(e={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}},t={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"},r={nan:"NaN",number:"数値",array:"配列"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`無効な入力: instanceof ${a.expected}が期待されましたが、${n}が入力されました`;return`無効な入力: ${e}が期待されましたが、${n}が入力されました`}case"invalid_value":if(1===a.values.length)return`無効な入力: ${i.stringifyPrimitive(a.values[0])}が期待されました`;return`無効な選択: ${i.joinValues(a.values,"、")}のいずれかである必要があります`;case"too_big":{let t=a.inclusive?"以下である":"より小さい",r=e[a.origin]??null;if(r)return`大きすぎる値: ${a.origin??"値"}は${a.maximum.toString()}${r.unit??"要素"}${t}必要があります`;return`大きすぎる値: ${a.origin??"値"}は${a.maximum.toString()}${t}必要があります`}case"too_small":{let t=a.inclusive?"以上である":"より大きい",r=e[a.origin]??null;if(r)return`小さすぎる値: ${a.origin}は${a.minimum.toString()}${r.unit}${t}必要があります`;return`小さすぎる値: ${a.origin}は${a.minimum.toString()}${t}必要があります`}case"invalid_format":if("starts_with"===a.format)return`無効な文字列: "${a.prefix}"で始まる必要があります`;if("ends_with"===a.format)return`無効な文字列: "${a.suffix}"で終わる必要があります`;if("includes"===a.format)return`無効な文字列: "${a.includes}"を含む必要があります`;if("regex"===a.format)return`無効な文字列: パターン${a.pattern}に一致する必要があります`;return`無効な${t[a.format]??a.format}`;case"not_multiple_of":return`無効な数値: ${a.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${a.keys.length>1?"群":""}: ${i.joinValues(a.keys,"、")}`;case"invalid_key":return`${a.origin}内の無効なキー`;case"invalid_union":default:return"無効な入力";case"invalid_element":return`${a.origin}内の無効な値`}})}},"ka",0,function(){let e,t,r;return{localeError:(e={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}},t={regex:"შეყვანა",email:"ელ-ფოსტის მისამართი",url:"URL",emoji:"ემოჯი",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"თარიღი-დრო",date:"თარიღი",time:"დრო",duration:"ხანგრძლივობა",ipv4:"IPv4 მისამართი",ipv6:"IPv6 მისამართი",cidrv4:"IPv4 დიაპაზონი",cidrv6:"IPv6 დიაპაზონი",base64:"base64-კოდირებული ველი",base64url:"base64url-კოდირებული ველი",json_string:"JSON ველი",e164:"E.164 ნომერი",jwt:"JWT",template_literal:"შეყვანა"},r={nan:"NaN",number:"რიცხვი",string:"ველი",boolean:"ბულეანი",function:"ფუნქცია",array:"მასივი"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`არასწორი შეყვანა: მოსალოდნელი instanceof ${a.expected}, მიღებული ${n}`;return`არასწორი შეყვანა: მოსალოდნელი ${e}, მიღებული ${n}`}case"invalid_value":if(1===a.values.length)return`არასწორი შეყვანა: მოსალოდნელი ${i.stringifyPrimitive(a.values[0])}`;return`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${i.joinValues(a.values,"|")}-დან`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`ზედმეტად დიდი: მოსალოდნელი ${a.origin??"მნიშვნელობა"} ${r.verb} ${t}${a.maximum.toString()} ${r.unit}`;return`ზედმეტად დიდი: მოსალოდნელი ${a.origin??"მნიშვნელობა"} იყოს ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`ზედმეტად პატარა: მოსალოდნელი ${a.origin} ${r.verb} ${t}${a.minimum.toString()} ${r.unit}`;return`ზედმეტად პატარა: მოსალოდნელი ${a.origin} იყოს ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`არასწორი ველი: უნდა იწყებოდეს "${a.prefix}"-ით`;if("ends_with"===a.format)return`არასწორი ველი: უნდა მთავრდებოდეს "${a.suffix}"-ით`;if("includes"===a.format)return`არასწორი ველი: უნდა შეიცავდეს "${a.includes}"-ს`;if("regex"===a.format)return`არასწორი ველი: უნდა შეესაბამებოდეს შაბლონს ${a.pattern}`;return`არასწორი ${t[a.format]??a.format}`;case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${a.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${a.keys.length>1?"ები":"ი"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${a.origin}-ში`;case"invalid_union":default:return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${a.origin}-ში`}})}},"kh",0,function(){return f()},"km",0,f,"ko",0,function(){let e,t,r;return{localeError:(e={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}},t={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`잘못된 입력: 예상 타입은 instanceof ${a.expected}, 받은 타입은 ${n}입니다`;return`잘못된 입력: 예상 타입은 ${e}, 받은 타입은 ${n}입니다`}case"invalid_value":if(1===a.values.length)return`잘못된 입력: 값은 ${i.stringifyPrimitive(a.values[0])} 이어야 합니다`;return`잘못된 옵션: ${i.joinValues(a.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{let t=a.inclusive?"이하":"미만",r="미만"===t?"이어야 합니다":"여야 합니다",i=e[a.origin]??null,n=i?.unit??"요소";if(i)return`${a.origin??"값"}이 너무 큽니다: ${a.maximum.toString()}${n} ${t}${r}`;return`${a.origin??"값"}이 너무 큽니다: ${a.maximum.toString()} ${t}${r}`}case"too_small":{let t=a.inclusive?"이상":"초과",r="이상"===t?"이어야 합니다":"여야 합니다",i=e[a.origin]??null,n=i?.unit??"요소";if(i)return`${a.origin??"값"}이 너무 작습니다: ${a.minimum.toString()}${n} ${t}${r}`;return`${a.origin??"값"}이 너무 작습니다: ${a.minimum.toString()} ${t}${r}`}case"invalid_format":if("starts_with"===a.format)return`잘못된 문자열: "${a.prefix}"(으)로 시작해야 합니다`;if("ends_with"===a.format)return`잘못된 문자열: "${a.suffix}"(으)로 끝나야 합니다`;if("includes"===a.format)return`잘못된 문자열: "${a.includes}"을(를) 포함해야 합니다`;if("regex"===a.format)return`잘못된 문자열: 정규식 ${a.pattern} 패턴과 일치해야 합니다`;return`잘못된 ${t[a.format]??a.format}`;case"not_multiple_of":return`잘못된 숫자: ${a.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`잘못된 키: ${a.origin}`;case"invalid_union":default:return"잘못된 입력";case"invalid_element":return`잘못된 값: ${a.origin}`}})}},"lt",0,function(){return{localeError:(()=>{let e={string:{unit:{one:"simbolis",few:"simboliai",many:"simbolių"},verb:{smaller:{inclusive:"turi būti ne ilgesnė kaip",notInclusive:"turi būti trumpesnė kaip"},bigger:{inclusive:"turi būti ne trumpesnė kaip",notInclusive:"turi būti ilgesnė kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"baitų"},verb:{smaller:{inclusive:"turi būti ne didesnis kaip",notInclusive:"turi būti mažesnis kaip"},bigger:{inclusive:"turi būti ne mažesnis kaip",notInclusive:"turi būti didesnis kaip"}}},array:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}},set:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}}};function t(t,r,i,a){let n=e[t]??null;return null===n?n:{unit:n.unit[r],verb:n.verb[a][i?"inclusive":"notInclusive"]}}let r={regex:"įvestis",email:"el. pašto adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukmė",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 užkoduota eilutė",base64url:"base64url užkoduota eilutė",json_string:"JSON eilutė",e164:"E.164 numeris",jwt:"JWT",template_literal:"įvestis"},a={nan:"NaN",number:"skaičius",bigint:"sveikasis skaičius",string:"eilutė",boolean:"loginė reikšmė",undefined:"neapibrėžta reikšmė",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulinė reikšmė"};return e=>{switch(e.code){case"invalid_type":{let t=a[e.expected]??e.expected,r=i.parsedType(e.input),n=a[r]??r;if(/^[A-Z]/.test(e.expected))return`Gautas tipas ${n}, o tikėtasi - instanceof ${e.expected}`;return`Gautas tipas ${n}, o tikėtasi - ${t}`}case"invalid_value":if(1===e.values.length)return`Privalo būti ${i.stringifyPrimitive(e.values[0])}`;return`Privalo būti vienas iš ${i.joinValues(e.values,"|")} pasirinkimų`;case"too_big":{let r=a[e.origin]??e.origin,i=t(e.origin,y(Number(e.maximum)),e.inclusive??!1,"smaller");if(i?.verb)return`${g(r??e.origin??"reikšmė")} ${i.verb} ${e.maximum.toString()} ${i.unit??"elementų"}`;let n=e.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${g(r??e.origin??"reikšmė")} turi būti ${n} ${e.maximum.toString()} ${i?.unit}`}case"too_small":{let r=a[e.origin]??e.origin,i=t(e.origin,y(Number(e.minimum)),e.inclusive??!1,"bigger");if(i?.verb)return`${g(r??e.origin??"reikšmė")} ${i.verb} ${e.minimum.toString()} ${i.unit??"elementų"}`;let n=e.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${g(r??e.origin??"reikšmė")} turi būti ${n} ${e.minimum.toString()} ${i?.unit}`}case"invalid_format":if("starts_with"===e.format)return`Eilutė privalo prasidėti "${e.prefix}"`;if("ends_with"===e.format)return`Eilutė privalo pasibaigti "${e.suffix}"`;if("includes"===e.format)return`Eilutė privalo įtraukti "${e.includes}"`;if("regex"===e.format)return`Eilutė privalo atitikti ${e.pattern}`;return`Neteisingas ${r[e.format]??e.format}`;case"not_multiple_of":return`Skaičius privalo būti ${e.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${e.keys.length>1?"i":"as"} rakt${e.keys.length>1?"ai":"as"}: ${i.joinValues(e.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":default:return"Klaidinga įvestis";case"invalid_element":{let t=a[e.origin]??e.origin;return`${g(t??e.origin??"reikšmė")} turi klaidingą įvestį`}}}})()}},"mk",0,function(){let e,t,r;return{localeError:(e={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}},t={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"},r={nan:"NaN",number:"број",array:"низа"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Грешен внес: се очекува instanceof ${a.expected}, примено ${n}`;return`Грешен внес: се очекува ${e}, примено ${n}`}case"invalid_value":if(1===a.values.length)return`Invalid input: expected ${i.stringifyPrimitive(a.values[0])}`;return`Грешана опција: се очекува една ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Премногу голем: се очекува ${a.origin??"вредноста"} да има ${t}${a.maximum.toString()} ${r.unit??"елементи"}`;return`Премногу голем: се очекува ${a.origin??"вредноста"} да биде ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Премногу мал: се очекува ${a.origin} да има ${t}${a.minimum.toString()} ${r.unit}`;return`Премногу мал: се очекува ${a.origin} да биде ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Неважечка низа: мора да започнува со "${a.prefix}"`;if("ends_with"===a.format)return`Неважечка низа: мора да завршува со "${a.suffix}"`;if("includes"===a.format)return`Неважечка низа: мора да вклучува "${a.includes}"`;if("regex"===a.format)return`Неважечка низа: мора да одгоара на патернот ${a.pattern}`;return`Invalid ${t[a.format]??a.format}`;case"not_multiple_of":return`Грешен број: мора да биде делив со ${a.divisor}`;case"unrecognized_keys":return`${a.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${a.origin}`;case"invalid_union":default:return"Грешен внес";case"invalid_element":return`Грешна вредност во ${a.origin}`}})}},"ms",0,function(){let e,t,r;return{localeError:(e={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}},t={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},r={nan:"NaN",number:"nombor"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Input tidak sah: dijangka instanceof ${a.expected}, diterima ${n}`;return`Input tidak sah: dijangka ${e}, diterima ${n}`}case"invalid_value":if(1===a.values.length)return`Input tidak sah: dijangka ${i.stringifyPrimitive(a.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Terlalu besar: dijangka ${a.origin??"nilai"} ${r.verb} ${t}${a.maximum.toString()} ${r.unit??"elemen"}`;return`Terlalu besar: dijangka ${a.origin??"nilai"} adalah ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Terlalu kecil: dijangka ${a.origin} ${r.verb} ${t}${a.minimum.toString()} ${r.unit}`;return`Terlalu kecil: dijangka ${a.origin} adalah ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`String tidak sah: mesti bermula dengan "${a.prefix}"`;if("ends_with"===a.format)return`String tidak sah: mesti berakhir dengan "${a.suffix}"`;if("includes"===a.format)return`String tidak sah: mesti mengandungi "${a.includes}"`;if("regex"===a.format)return`String tidak sah: mesti sepadan dengan corak ${a.pattern}`;return`${t[a.format]??a.format} tidak sah`;case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${a.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${a.origin}`;case"invalid_union":default:return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${a.origin}`}})}},"nl",0,function(){let e,t,r;return{localeError:(e={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}},t={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},r={nan:"NaN",number:"getal"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Ongeldige invoer: verwacht instanceof ${a.expected}, ontving ${n}`;return`Ongeldige invoer: verwacht ${e}, ontving ${n}`}case"invalid_value":if(1===a.values.length)return`Ongeldige invoer: verwacht ${i.stringifyPrimitive(a.values[0])}`;return`Ongeldige optie: verwacht \xe9\xe9n van ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null,i="date"===a.origin?"laat":"string"===a.origin?"lang":"groot";if(r)return`Te ${i}: verwacht dat ${a.origin??"waarde"} ${t}${a.maximum.toString()} ${r.unit??"elementen"} ${r.verb}`;return`Te ${i}: verwacht dat ${a.origin??"waarde"} ${t}${a.maximum.toString()} is`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null,i="date"===a.origin?"vroeg":"string"===a.origin?"kort":"klein";if(r)return`Te ${i}: verwacht dat ${a.origin} ${t}${a.minimum.toString()} ${r.unit} ${r.verb}`;return`Te ${i}: verwacht dat ${a.origin} ${t}${a.minimum.toString()} is`}case"invalid_format":if("starts_with"===a.format)return`Ongeldige tekst: moet met "${a.prefix}" beginnen`;if("ends_with"===a.format)return`Ongeldige tekst: moet op "${a.suffix}" eindigen`;if("includes"===a.format)return`Ongeldige tekst: moet "${a.includes}" bevatten`;if("regex"===a.format)return`Ongeldige tekst: moet overeenkomen met patroon ${a.pattern}`;return`Ongeldig: ${t[a.format]??a.format}`;case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${a.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${a.keys.length>1?"s":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${a.origin}`;case"invalid_union":default:return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${a.origin}`}})}},"no",0,function(){let e,t,r;return{localeError:(e={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}},t={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},r={nan:"NaN",number:"tall",array:"liste"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Ugyldig input: forventet instanceof ${a.expected}, fikk ${n}`;return`Ugyldig input: forventet ${e}, fikk ${n}`}case"invalid_value":if(1===a.values.length)return`Ugyldig verdi: forventet ${i.stringifyPrimitive(a.values[0])}`;return`Ugyldig valg: forventet en av ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`For stor(t): forventet ${a.origin??"value"} til \xe5 ha ${t}${a.maximum.toString()} ${r.unit??"elementer"}`;return`For stor(t): forventet ${a.origin??"value"} til \xe5 ha ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`For lite(n): forventet ${a.origin} til \xe5 ha ${t}${a.minimum.toString()} ${r.unit}`;return`For lite(n): forventet ${a.origin} til \xe5 ha ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Ugyldig streng: m\xe5 starte med "${a.prefix}"`;if("ends_with"===a.format)return`Ugyldig streng: m\xe5 ende med "${a.suffix}"`;if("includes"===a.format)return`Ugyldig streng: m\xe5 inneholde "${a.includes}"`;if("regex"===a.format)return`Ugyldig streng: m\xe5 matche m\xf8nsteret ${a.pattern}`;return`Ugyldig ${t[a.format]??a.format}`;case"not_multiple_of":return`Ugyldig tall: m\xe5 v\xe6re et multiplum av ${a.divisor}`;case"unrecognized_keys":return`${a.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Ugyldig n\xf8kkel i ${a.origin}`;case"invalid_union":default:return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${a.origin}`}})}},"ota",0,function(){let e,t,r;return{localeError:(e={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}},t={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"},r={nan:"NaN",number:"numara",array:"saf",null:"gayb"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`F\xe2sit giren: umulan instanceof ${a.expected}, alınan ${n}`;return`F\xe2sit giren: umulan ${e}, alınan ${n}`}case"invalid_value":if(1===a.values.length)return`F\xe2sit giren: umulan ${i.stringifyPrimitive(a.values[0])}`;return`F\xe2sit tercih: m\xfbteberler ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Fazla b\xfcy\xfck: ${a.origin??"value"}, ${t}${a.maximum.toString()} ${r.unit??"elements"} sahip olmalıydı.`;return`Fazla b\xfcy\xfck: ${a.origin??"value"}, ${t}${a.maximum.toString()} olmalıydı.`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Fazla k\xfc\xe7\xfck: ${a.origin}, ${t}${a.minimum.toString()} ${r.unit} sahip olmalıydı.`;return`Fazla k\xfc\xe7\xfck: ${a.origin}, ${t}${a.minimum.toString()} olmalıydı.`}case"invalid_format":if("starts_with"===a.format)return`F\xe2sit metin: "${a.prefix}" ile başlamalı.`;if("ends_with"===a.format)return`F\xe2sit metin: "${a.suffix}" ile bitmeli.`;if("includes"===a.format)return`F\xe2sit metin: "${a.includes}" ihtiv\xe2 etmeli.`;if("regex"===a.format)return`F\xe2sit metin: ${a.pattern} nakşına uymalı.`;return`F\xe2sit ${t[a.format]??a.format}`;case"not_multiple_of":return`F\xe2sit sayı: ${a.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${a.keys.length>1?"s":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`${a.origin} i\xe7in tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${a.origin} i\xe7in tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}})}},"pl",0,function(){let e,t,r;return{localeError:(e={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}},t={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"},r={nan:"NaN",number:"liczba",array:"tablica"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Nieprawidłowe dane wejściowe: oczekiwano instanceof ${a.expected}, otrzymano ${n}`;return`Nieprawidłowe dane wejściowe: oczekiwano ${e}, otrzymano ${n}`}case"invalid_value":if(1===a.values.length)return`Nieprawidłowe dane wejściowe: oczekiwano ${i.stringifyPrimitive(a.values[0])}`;return`Nieprawidłowa opcja: oczekiwano jednej z wartości ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Za duża wartość: oczekiwano, że ${a.origin??"wartość"} będzie mieć ${t}${a.maximum.toString()} ${r.unit??"elementów"}`;return`Zbyt duż(y/a/e): oczekiwano, że ${a.origin??"wartość"} będzie wynosić ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Za mała wartość: oczekiwano, że ${a.origin??"wartość"} będzie mieć ${t}${a.minimum.toString()} ${r.unit??"elementów"}`;return`Zbyt mał(y/a/e): oczekiwano, że ${a.origin??"wartość"} będzie wynosić ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Nieprawidłowy ciąg znak\xf3w: musi zaczynać się od "${a.prefix}"`;if("ends_with"===a.format)return`Nieprawidłowy ciąg znak\xf3w: musi kończyć się na "${a.suffix}"`;if("includes"===a.format)return`Nieprawidłowy ciąg znak\xf3w: musi zawierać "${a.includes}"`;if("regex"===a.format)return`Nieprawidłowy ciąg znak\xf3w: musi odpowiadać wzorcowi ${a.pattern}`;return`Nieprawidłow(y/a/e) ${t[a.format]??a.format}`;case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${a.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${a.keys.length>1?"s":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${a.origin}`;case"invalid_union":default:return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${a.origin}`}})}},"ps",0,function(){let e,t,r;return{localeError:(e={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}},t={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"},r={nan:"NaN",number:"عدد",array:"ارې"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`ناسم ورودي: باید instanceof ${a.expected} وای, مګر ${n} ترلاسه شو`;return`ناسم ورودي: باید ${e} وای, مګر ${n} ترلاسه شو`}case"invalid_value":if(1===a.values.length)return`ناسم ورودي: باید ${i.stringifyPrimitive(a.values[0])} وای`;return`ناسم انتخاب: باید یو له ${i.joinValues(a.values,"|")} څخه وای`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`ډیر لوی: ${a.origin??"ارزښت"} باید ${t}${a.maximum.toString()} ${r.unit??"عنصرونه"} ولري`;return`ډیر لوی: ${a.origin??"ارزښت"} باید ${t}${a.maximum.toString()} وي`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`ډیر کوچنی: ${a.origin} باید ${t}${a.minimum.toString()} ${r.unit} ولري`;return`ډیر کوچنی: ${a.origin} باید ${t}${a.minimum.toString()} وي`}case"invalid_format":if("starts_with"===a.format)return`ناسم متن: باید د "${a.prefix}" سره پیل شي`;if("ends_with"===a.format)return`ناسم متن: باید د "${a.suffix}" سره پای ته ورسيږي`;if("includes"===a.format)return`ناسم متن: باید "${a.includes}" ولري`;if("regex"===a.format)return`ناسم متن: باید د ${a.pattern} سره مطابقت ولري`;return`${t[a.format]??a.format} ناسم دی`;case"not_multiple_of":return`ناسم عدد: باید د ${a.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${a.keys.length>1?"کلیډونه":"کلیډ"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${a.origin} کې`;case"invalid_union":default:return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${a.origin} کې`}})}},"pt",0,function(){let e,t,r;return{localeError:(e={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}},t={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},r={nan:"NaN",number:"número",null:"nulo"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Tipo inv\xe1lido: esperado instanceof ${a.expected}, recebido ${n}`;return`Tipo inv\xe1lido: esperado ${e}, recebido ${n}`}case"invalid_value":if(1===a.values.length)return`Entrada inv\xe1lida: esperado ${i.stringifyPrimitive(a.values[0])}`;return`Op\xe7\xe3o inv\xe1lida: esperada uma das ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Muito grande: esperado que ${a.origin??"valor"} tivesse ${t}${a.maximum.toString()} ${r.unit??"elementos"}`;return`Muito grande: esperado que ${a.origin??"valor"} fosse ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Muito pequeno: esperado que ${a.origin} tivesse ${t}${a.minimum.toString()} ${r.unit}`;return`Muito pequeno: esperado que ${a.origin} fosse ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Texto inv\xe1lido: deve come\xe7ar com "${a.prefix}"`;if("ends_with"===a.format)return`Texto inv\xe1lido: deve terminar com "${a.suffix}"`;if("includes"===a.format)return`Texto inv\xe1lido: deve incluir "${a.includes}"`;if("regex"===a.format)return`Texto inv\xe1lido: deve corresponder ao padr\xe3o ${a.pattern}`;return`${t[a.format]??a.format} inv\xe1lido`;case"not_multiple_of":return`N\xfamero inv\xe1lido: deve ser m\xfaltiplo de ${a.divisor}`;case"unrecognized_keys":return`Chave${a.keys.length>1?"s":""} desconhecida${a.keys.length>1?"s":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Chave inv\xe1lida em ${a.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inv\xe1lido em ${a.origin}`;default:return"Campo inválido"}})}},"ro",0,function(){let e,t,r;return{localeError:(e={string:{unit:"caractere",verb:"să aibă"},file:{unit:"octeți",verb:"să aibă"},array:{unit:"elemente",verb:"să aibă"},set:{unit:"elemente",verb:"să aibă"},map:{unit:"intrări",verb:"să aibă"}},t={regex:"intrare",email:"adresă de email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"dată și oră ISO",date:"dată ISO",time:"oră ISO",duration:"durată ISO",ipv4:"adresă IPv4",ipv6:"adresă IPv6",mac:"adresă MAC",cidrv4:"interval IPv4",cidrv6:"interval IPv6",base64:"șir codat base64",base64url:"șir codat base64url",json_string:"șir JSON",e164:"număr E.164",jwt:"JWT",template_literal:"intrare"},r={nan:"NaN",string:"șir",number:"număr",boolean:"boolean",function:"funcție",array:"matrice",object:"obiect",undefined:"nedefinit",symbol:"simbol",bigint:"număr mare",void:"void",never:"never",map:"hartă",set:"set"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;return`Intrare invalidă: așteptat ${e}, primit ${n}`}case"invalid_value":if(1===a.values.length)return`Intrare invalidă: așteptat ${i.stringifyPrimitive(a.values[0])}`;return`Opțiune invalidă: așteptat una dintre ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Prea mare: așteptat ca ${a.origin??"valoarea"} ${r.verb} ${t}${a.maximum.toString()} ${r.unit??"elemente"}`;return`Prea mare: așteptat ca ${a.origin??"valoarea"} să fie ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Prea mic: așteptat ca ${a.origin} ${r.verb} ${t}${a.minimum.toString()} ${r.unit}`;return`Prea mic: așteptat ca ${a.origin} să fie ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Șir invalid: trebuie să \xeenceapă cu "${a.prefix}"`;if("ends_with"===a.format)return`Șir invalid: trebuie să se termine cu "${a.suffix}"`;if("includes"===a.format)return`Șir invalid: trebuie să includă "${a.includes}"`;if("regex"===a.format)return`Șir invalid: trebuie să se potrivească cu modelul ${a.pattern}`;return`Format invalid: ${t[a.format]??a.format}`;case"not_multiple_of":return`Număr invalid: trebuie să fie multiplu de ${a.divisor}`;case"unrecognized_keys":return`Chei nerecunoscute: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Cheie invalidă \xeen ${a.origin}`;case"invalid_union":default:return"Intrare invalidă";case"invalid_element":return`Valoare invalidă \xeen ${a.origin}`}})}},"ru",0,function(){let e,t,r;return{localeError:(e={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}},t={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"},r={nan:"NaN",number:"число",array:"массив"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Неверный ввод: ожидалось instanceof ${a.expected}, получено ${n}`;return`Неверный ввод: ожидалось ${e}, получено ${n}`}case"invalid_value":if(1===a.values.length)return`Неверный ввод: ожидалось ${i.stringifyPrimitive(a.values[0])}`;return`Неверный вариант: ожидалось одно из ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r){let e=w(Number(a.maximum),r.unit.one,r.unit.few,r.unit.many);return`Слишком большое значение: ожидалось, что ${a.origin??"значение"} будет иметь ${t}${a.maximum.toString()} ${e}`}return`Слишком большое значение: ожидалось, что ${a.origin??"значение"} будет ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r){let e=w(Number(a.minimum),r.unit.one,r.unit.few,r.unit.many);return`Слишком маленькое значение: ожидалось, что ${a.origin} будет иметь ${t}${a.minimum.toString()} ${e}`}return`Слишком маленькое значение: ожидалось, что ${a.origin} будет ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Неверная строка: должна начинаться с "${a.prefix}"`;if("ends_with"===a.format)return`Неверная строка: должна заканчиваться на "${a.suffix}"`;if("includes"===a.format)return`Неверная строка: должна содержать "${a.includes}"`;if("regex"===a.format)return`Неверная строка: должна соответствовать шаблону ${a.pattern}`;return`Неверный ${t[a.format]??a.format}`;case"not_multiple_of":return`Неверное число: должно быть кратным ${a.divisor}`;case"unrecognized_keys":return`Нераспознанн${a.keys.length>1?"ые":"ый"} ключ${a.keys.length>1?"и":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${a.origin}`;case"invalid_union":default:return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${a.origin}`}})}},"sl",0,function(){let e,t,r;return{localeError:(e={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}},t={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"},r={nan:"NaN",number:"število",array:"tabela"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Neveljaven vnos: pričakovano instanceof ${a.expected}, prejeto ${n}`;return`Neveljaven vnos: pričakovano ${e}, prejeto ${n}`}case"invalid_value":if(1===a.values.length)return`Neveljaven vnos: pričakovano ${i.stringifyPrimitive(a.values[0])}`;return`Neveljavna možnost: pričakovano eno izmed ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Preveliko: pričakovano, da bo ${a.origin??"vrednost"} imelo ${t}${a.maximum.toString()} ${r.unit??"elementov"}`;return`Preveliko: pričakovano, da bo ${a.origin??"vrednost"} ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Premajhno: pričakovano, da bo ${a.origin} imelo ${t}${a.minimum.toString()} ${r.unit}`;return`Premajhno: pričakovano, da bo ${a.origin} ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Neveljaven niz: mora se začeti z "${a.prefix}"`;if("ends_with"===a.format)return`Neveljaven niz: mora se končati z "${a.suffix}"`;if("includes"===a.format)return`Neveljaven niz: mora vsebovati "${a.includes}"`;if("regex"===a.format)return`Neveljaven niz: mora ustrezati vzorcu ${a.pattern}`;return`Neveljaven ${t[a.format]??a.format}`;case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${a.divisor}`;case"unrecognized_keys":return`Neprepoznan${a.keys.length>1?"i ključi":" ključ"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${a.origin}`;case"invalid_union":default:return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${a.origin}`}})}},"sv",0,function(){let e,t,r;return{localeError:(e={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}},t={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},r={nan:"NaN",number:"antal",array:"lista"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Ogiltig inmatning: f\xf6rv\xe4ntat instanceof ${a.expected}, fick ${n}`;return`Ogiltig inmatning: f\xf6rv\xe4ntat ${e}, fick ${n}`}case"invalid_value":if(1===a.values.length)return`Ogiltig inmatning: f\xf6rv\xe4ntat ${i.stringifyPrimitive(a.values[0])}`;return`Ogiltigt val: f\xf6rv\xe4ntade en av ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`F\xf6r stor(t): f\xf6rv\xe4ntade ${a.origin??"värdet"} att ha ${t}${a.maximum.toString()} ${r.unit??"element"}`;return`F\xf6r stor(t): f\xf6rv\xe4ntat ${a.origin??"värdet"} att ha ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`F\xf6r lite(t): f\xf6rv\xe4ntade ${a.origin??"värdet"} att ha ${t}${a.minimum.toString()} ${r.unit}`;return`F\xf6r lite(t): f\xf6rv\xe4ntade ${a.origin??"värdet"} att ha ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Ogiltig str\xe4ng: m\xe5ste b\xf6rja med "${a.prefix}"`;if("ends_with"===a.format)return`Ogiltig str\xe4ng: m\xe5ste sluta med "${a.suffix}"`;if("includes"===a.format)return`Ogiltig str\xe4ng: m\xe5ste inneh\xe5lla "${a.includes}"`;if("regex"===a.format)return`Ogiltig str\xe4ng: m\xe5ste matcha m\xf6nstret "${a.pattern}"`;return`Ogiltig(t) ${t[a.format]??a.format}`;case"not_multiple_of":return`Ogiltigt tal: m\xe5ste vara en multipel av ${a.divisor}`;case"unrecognized_keys":return`${a.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${a.origin??"värdet"}`;case"invalid_union":default:return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xe4rde i ${a.origin??"värdet"}`}})}},"ta",0,function(){let e,t,r;return{localeError:(e={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}},t={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"},r={nan:"NaN",number:"எண்",array:"அணி",null:"வெறுமை"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${a.expected}, பெறப்பட்டது ${n}`;return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${e}, பெறப்பட்டது ${n}`}case"invalid_value":if(1===a.values.length)return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${i.stringifyPrimitive(a.values[0])}`;return`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${i.joinValues(a.values,"|")} இல் ஒன்று`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${a.origin??"மதிப்பு"} ${t}${a.maximum.toString()} ${r.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`;return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${a.origin??"மதிப்பு"} ${t}${a.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${a.origin} ${t}${a.minimum.toString()} ${r.unit} ஆக இருக்க வேண்டும்`;return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${a.origin} ${t}${a.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":if("starts_with"===a.format)return`தவறான சரம்: "${a.prefix}" இல் தொடங்க வேண்டும்`;if("ends_with"===a.format)return`தவறான சரம்: "${a.suffix}" இல் முடிவடைய வேண்டும்`;if("includes"===a.format)return`தவறான சரம்: "${a.includes}" ஐ உள்ளடக்க வேண்டும்`;if("regex"===a.format)return`தவறான சரம்: ${a.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`;return`தவறான ${t[a.format]??a.format}`;case"not_multiple_of":return`தவறான எண்: ${a.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${a.keys.length>1?"கள்":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`${a.origin} இல் தவறான விசை`;case"invalid_union":default:return"தவறான உள்ளீடு";case"invalid_element":return`${a.origin} இல் தவறான மதிப்பு`}})}},"th",0,function(){let e,t,r;return{localeError:(e={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}},t={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"},r={nan:"NaN",number:"ตัวเลข",array:"อาร์เรย์ (Array)",null:"ไม่มีค่า (null)"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${a.expected} แต่ได้รับ ${n}`;return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${e} แต่ได้รับ ${n}`}case"invalid_value":if(1===a.values.length)return`ค่าไม่ถูกต้อง: ควรเป็น ${i.stringifyPrimitive(a.values[0])}`;return`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"ไม่เกิน":"น้อยกว่า",r=e[a.origin]??null;if(r)return`เกินกำหนด: ${a.origin??"ค่า"} ควรมี${t} ${a.maximum.toString()} ${r.unit??"รายการ"}`;return`เกินกำหนด: ${a.origin??"ค่า"} ควรมี${t} ${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?"อย่างน้อย":"มากกว่า",r=e[a.origin]??null;if(r)return`น้อยกว่ากำหนด: ${a.origin} ควรมี${t} ${a.minimum.toString()} ${r.unit}`;return`น้อยกว่ากำหนด: ${a.origin} ควรมี${t} ${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${a.prefix}"`;if("ends_with"===a.format)return`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${a.suffix}"`;if("includes"===a.format)return`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${a.includes}" อยู่ในข้อความ`;if("regex"===a.format)return`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${a.pattern}`;return`รูปแบบไม่ถูกต้อง: ${t[a.format]??a.format}`;case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${a.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${a.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${a.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}})}},"tr",0,function(){let e,t,r;return{localeError:(e={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}},t={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Ge\xe7ersiz değer: beklenen instanceof ${a.expected}, alınan ${n}`;return`Ge\xe7ersiz değer: beklenen ${e}, alınan ${n}`}case"invalid_value":if(1===a.values.length)return`Ge\xe7ersiz değer: beklenen ${i.stringifyPrimitive(a.values[0])}`;return`Ge\xe7ersiz se\xe7enek: aşağıdakilerden biri olmalı: ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`\xc7ok b\xfcy\xfck: beklenen ${a.origin??"değer"} ${t}${a.maximum.toString()} ${r.unit??"öğe"}`;return`\xc7ok b\xfcy\xfck: beklenen ${a.origin??"değer"} ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`\xc7ok k\xfc\xe7\xfck: beklenen ${a.origin} ${t}${a.minimum.toString()} ${r.unit}`;return`\xc7ok k\xfc\xe7\xfck: beklenen ${a.origin} ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Ge\xe7ersiz metin: "${a.prefix}" ile başlamalı`;if("ends_with"===a.format)return`Ge\xe7ersiz metin: "${a.suffix}" ile bitmeli`;if("includes"===a.format)return`Ge\xe7ersiz metin: "${a.includes}" i\xe7ermeli`;if("regex"===a.format)return`Ge\xe7ersiz metin: ${a.pattern} desenine uymalı`;return`Ge\xe7ersiz ${t[a.format]??a.format}`;case"not_multiple_of":return`Ge\xe7ersiz sayı: ${a.divisor} ile tam b\xf6l\xfcnebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${a.keys.length>1?"lar":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`${a.origin} i\xe7inde ge\xe7ersiz anahtar`;case"invalid_union":default:return"Geçersiz değer";case"invalid_element":return`${a.origin} i\xe7inde ge\xe7ersiz değer`}})}},"ua",0,function(){return b()},"uk",0,b,"ur",0,function(){let e,t,r;return{localeError:(e={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}},t={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"},r={nan:"NaN",number:"نمبر",array:"آرے",null:"نل"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`غلط ان پٹ: instanceof ${a.expected} متوقع تھا، ${n} موصول ہوا`;return`غلط ان پٹ: ${e} متوقع تھا، ${n} موصول ہوا`}case"invalid_value":if(1===a.values.length)return`غلط ان پٹ: ${i.stringifyPrimitive(a.values[0])} متوقع تھا`;return`غلط آپشن: ${i.joinValues(a.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`بہت بڑا: ${a.origin??"ویلیو"} کے ${t}${a.maximum.toString()} ${r.unit??"عناصر"} ہونے متوقع تھے`;return`بہت بڑا: ${a.origin??"ویلیو"} کا ${t}${a.maximum.toString()} ہونا متوقع تھا`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`بہت چھوٹا: ${a.origin} کے ${t}${a.minimum.toString()} ${r.unit} ہونے متوقع تھے`;return`بہت چھوٹا: ${a.origin} کا ${t}${a.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":if("starts_with"===a.format)return`غلط سٹرنگ: "${a.prefix}" سے شروع ہونا چاہیے`;if("ends_with"===a.format)return`غلط سٹرنگ: "${a.suffix}" پر ختم ہونا چاہیے`;if("includes"===a.format)return`غلط سٹرنگ: "${a.includes}" شامل ہونا چاہیے`;if("regex"===a.format)return`غلط سٹرنگ: پیٹرن ${a.pattern} سے میچ ہونا چاہیے`;return`غلط ${t[a.format]??a.format}`;case"not_multiple_of":return`غلط نمبر: ${a.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${a.keys.length>1?"ز":""}: ${i.joinValues(a.keys,"، ")}`;case"invalid_key":return`${a.origin} میں غلط کی`;case"invalid_union":default:return"غلط ان پٹ";case"invalid_element":return`${a.origin} میں غلط ویلیو`}})}},"uz",0,function(){let e,t,r;return{localeError:(e={string:{unit:"belgi",verb:"bo‘lishi kerak"},file:{unit:"bayt",verb:"bo‘lishi kerak"},array:{unit:"element",verb:"bo‘lishi kerak"},set:{unit:"element",verb:"bo‘lishi kerak"},map:{unit:"yozuv",verb:"bo‘lishi kerak"}},t={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},r={nan:"NaN",number:"raqam",array:"massiv"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Noto‘g‘ri kirish: kutilgan instanceof ${a.expected}, qabul qilingan ${n}`;return`Noto‘g‘ri kirish: kutilgan ${e}, qabul qilingan ${n}`}case"invalid_value":if(1===a.values.length)return`Noto‘g‘ri kirish: kutilgan ${i.stringifyPrimitive(a.values[0])}`;return`Noto‘g‘ri variant: quyidagilardan biri kutilgan ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Juda katta: kutilgan ${a.origin??"qiymat"} ${t}${a.maximum.toString()} ${r.unit} ${r.verb}`;return`Juda katta: kutilgan ${a.origin??"qiymat"} ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Juda kichik: kutilgan ${a.origin} ${t}${a.minimum.toString()} ${r.unit} ${r.verb}`;return`Juda kichik: kutilgan ${a.origin} ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Noto‘g‘ri satr: "${a.prefix}" bilan boshlanishi kerak`;if("ends_with"===a.format)return`Noto‘g‘ri satr: "${a.suffix}" bilan tugashi kerak`;if("includes"===a.format)return`Noto‘g‘ri satr: "${a.includes}" ni o‘z ichiga olishi kerak`;if("regex"===a.format)return`Noto‘g‘ri satr: ${a.pattern} shabloniga mos kelishi kerak`;return`Noto‘g‘ri ${t[a.format]??a.format}`;case"not_multiple_of":return`Noto‘g‘ri raqam: ${a.divisor} ning karralisi bo‘lishi kerak`;case"unrecognized_keys":return`Noma’lum kalit${a.keys.length>1?"lar":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`${a.origin} dagi kalit noto‘g‘ri`;case"invalid_union":default:return"Noto‘g‘ri kirish";case"invalid_element":return`${a.origin} da noto‘g‘ri qiymat`}})}},"vi",0,function(){let e,t,r;return{localeError:(e={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}},t={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"},r={nan:"NaN",number:"số",array:"mảng"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Đầu v\xe0o kh\xf4ng hợp lệ: mong đợi instanceof ${a.expected}, nhận được ${n}`;return`Đầu v\xe0o kh\xf4ng hợp lệ: mong đợi ${e}, nhận được ${n}`}case"invalid_value":if(1===a.values.length)return`Đầu v\xe0o kh\xf4ng hợp lệ: mong đợi ${i.stringifyPrimitive(a.values[0])}`;return`T\xf9y chọn kh\xf4ng hợp lệ: mong đợi một trong c\xe1c gi\xe1 trị ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Qu\xe1 lớn: mong đợi ${a.origin??"giá trị"} ${r.verb} ${t}${a.maximum.toString()} ${r.unit??"phần tử"}`;return`Qu\xe1 lớn: mong đợi ${a.origin??"giá trị"} ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Qu\xe1 nhỏ: mong đợi ${a.origin} ${r.verb} ${t}${a.minimum.toString()} ${r.unit}`;return`Qu\xe1 nhỏ: mong đợi ${a.origin} ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Chuỗi kh\xf4ng hợp lệ: phải bắt đầu bằng "${a.prefix}"`;if("ends_with"===a.format)return`Chuỗi kh\xf4ng hợp lệ: phải kết th\xfac bằng "${a.suffix}"`;if("includes"===a.format)return`Chuỗi kh\xf4ng hợp lệ: phải bao gồm "${a.includes}"`;if("regex"===a.format)return`Chuỗi kh\xf4ng hợp lệ: phải khớp với mẫu ${a.pattern}`;return`${t[a.format]??a.format} kh\xf4ng hợp lệ`;case"not_multiple_of":return`Số kh\xf4ng hợp lệ: phải l\xe0 bội số của ${a.divisor}`;case"unrecognized_keys":return`Kh\xf3a kh\xf4ng được nhận dạng: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Kh\xf3a kh\xf4ng hợp lệ trong ${a.origin}`;case"invalid_union":default:return"Đầu vào không hợp lệ";case"invalid_element":return`Gi\xe1 trị kh\xf4ng hợp lệ trong ${a.origin}`}})}},"yo",0,function(){let e,t,r;return{localeError:(e={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}},t={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"},r={nan:"NaN",number:"nọ́mbà",array:"akopọ"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`\xccb\xe1wọl\xe9 aṣ\xecṣe: a n\xed l\xe1ti fi instanceof ${a.expected}, \xe0mọ̀ a r\xed ${n}`;return`\xccb\xe1wọl\xe9 aṣ\xecṣe: a n\xed l\xe1ti fi ${e}, \xe0mọ̀ a r\xed ${n}`}case"invalid_value":if(1===a.values.length)return`\xccb\xe1wọl\xe9 aṣ\xecṣe: a n\xed l\xe1ti fi ${i.stringifyPrimitive(a.values[0])}`;return`\xc0ṣ\xe0y\xe0n aṣ\xecṣe: yan ọ̀kan l\xe1ra ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`T\xf3 pọ̀ j\xf9: a n\xed l\xe1ti jẹ́ p\xe9 ${a.origin??"iye"} ${r.verb} ${t}${a.maximum} ${r.unit}`;return`T\xf3 pọ̀ j\xf9: a n\xed l\xe1ti jẹ́ ${t}${a.maximum}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`K\xe9r\xe9 ju: a n\xed l\xe1ti jẹ́ p\xe9 ${a.origin} ${r.verb} ${t}${a.minimum} ${r.unit}`;return`K\xe9r\xe9 ju: a n\xed l\xe1ti jẹ́ ${t}${a.minimum}`}case"invalid_format":if("starts_with"===a.format)return`Ọ̀rọ̀ aṣ\xecṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀l\xfa "${a.prefix}"`;if("ends_with"===a.format)return`Ọ̀rọ̀ aṣ\xecṣe: gbọ́dọ̀ par\xed pẹ̀l\xfa "${a.suffix}"`;if("includes"===a.format)return`Ọ̀rọ̀ aṣ\xecṣe: gbọ́dọ̀ n\xed "${a.includes}"`;if("regex"===a.format)return`Ọ̀rọ̀ aṣ\xecṣe: gbọ́dọ̀ b\xe1 \xe0pẹẹrẹ mu ${a.pattern}`;return`Aṣ\xecṣe: ${t[a.format]??a.format}`;case"not_multiple_of":return`Nọ́mb\xe0 aṣ\xecṣe: gbọ́dọ̀ jẹ́ \xe8y\xe0 p\xedp\xedn ti ${a.divisor}`;case"unrecognized_keys":return`Bọt\xecn\xec \xe0\xecmọ̀: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Bọt\xecn\xec aṣ\xecṣe n\xedn\xfa ${a.origin}`;case"invalid_union":default:return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣ\xecṣe n\xedn\xfa ${a.origin}`}})}},"zhCN",0,function(){let e,t,r;return{localeError:(e={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}},t={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"},r={nan:"NaN",number:"数字",array:"数组",null:"空值(null)"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`无效输入:期望 instanceof ${a.expected},实际接收 ${n}`;return`无效输入:期望 ${e},实际接收 ${n}`}case"invalid_value":if(1===a.values.length)return`无效输入:期望 ${i.stringifyPrimitive(a.values[0])}`;return`无效选项:期望以下之一 ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`数值过大:期望 ${a.origin??"值"} ${t}${a.maximum.toString()} ${r.unit??"个元素"}`;return`数值过大:期望 ${a.origin??"值"} ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`数值过小:期望 ${a.origin} ${t}${a.minimum.toString()} ${r.unit}`;return`数值过小:期望 ${a.origin} ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`无效字符串:必须以 "${a.prefix}" 开头`;if("ends_with"===a.format)return`无效字符串:必须以 "${a.suffix}" 结尾`;if("includes"===a.format)return`无效字符串:必须包含 "${a.includes}"`;if("regex"===a.format)return`无效字符串:必须满足正则表达式 ${a.pattern}`;return`无效${t[a.format]??a.format}`;case"not_multiple_of":return`无效数字:必须是 ${a.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`${a.origin} 中的键(key)无效`;case"invalid_union":default:return"无效输入";case"invalid_element":return`${a.origin} 中包含无效值(value)`}})}},"zhTW",0,function(){let e,t,r;return{localeError:(e={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}},t={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`無效的輸入值:預期為 instanceof ${a.expected},但收到 ${n}`;return`無效的輸入值:預期為 ${e},但收到 ${n}`}case"invalid_value":if(1===a.values.length)return`無效的輸入值:預期為 ${i.stringifyPrimitive(a.values[0])}`;return`無效的選項:預期為以下其中之一 ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`數值過大:預期 ${a.origin??"值"} 應為 ${t}${a.maximum.toString()} ${r.unit??"個元素"}`;return`數值過大:預期 ${a.origin??"值"} 應為 ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`數值過小:預期 ${a.origin} 應為 ${t}${a.minimum.toString()} ${r.unit}`;return`數值過小:預期 ${a.origin} 應為 ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`無效的字串:必須以 "${a.prefix}" 開頭`;if("ends_with"===a.format)return`無效的字串:必須以 "${a.suffix}" 結尾`;if("includes"===a.format)return`無效的字串:必須包含 "${a.includes}"`;if("regex"===a.format)return`無效的字串:必須符合格式 ${a.pattern}`;return`無效的 ${t[a.format]??a.format}`;case"not_multiple_of":return`無效的數字:必須為 ${a.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${a.keys.length>1?"們":""}:${i.joinValues(a.keys,"、")}`;case"invalid_key":return`${a.origin} 中有無效的鍵值`;case"invalid_union":default:return"無效的輸入值";case"invalid_element":return`${a.origin} 中有無效的值`}})}}],860544);var v=e.i(860544),k=e.i(52637),S=e.i(173911),E=e.i(862061),I=e.i(207159),x=e.i(865889);e.s([],233145);var A=e.i(233145);e.s(["$ZodAny",()=>o.$ZodAny,"$ZodArray",()=>o.$ZodArray,"$ZodAsyncError",()=>r.$ZodAsyncError,"$ZodBase64",()=>o.$ZodBase64,"$ZodBase64URL",()=>o.$ZodBase64URL,"$ZodBigInt",()=>o.$ZodBigInt,"$ZodBigIntFormat",()=>o.$ZodBigIntFormat,"$ZodBoolean",()=>o.$ZodBoolean,"$ZodCIDRv4",()=>o.$ZodCIDRv4,"$ZodCIDRv6",()=>o.$ZodCIDRv6,"$ZodCUID",()=>o.$ZodCUID,"$ZodCUID2",()=>o.$ZodCUID2,"$ZodCatch",()=>o.$ZodCatch,"$ZodCheck",()=>l.$ZodCheck,"$ZodCheckBigIntFormat",()=>l.$ZodCheckBigIntFormat,"$ZodCheckEndsWith",()=>l.$ZodCheckEndsWith,"$ZodCheckGreaterThan",()=>l.$ZodCheckGreaterThan,"$ZodCheckIncludes",()=>l.$ZodCheckIncludes,"$ZodCheckLengthEquals",()=>l.$ZodCheckLengthEquals,"$ZodCheckLessThan",()=>l.$ZodCheckLessThan,"$ZodCheckLowerCase",()=>l.$ZodCheckLowerCase,"$ZodCheckMaxLength",()=>l.$ZodCheckMaxLength,"$ZodCheckMaxSize",()=>l.$ZodCheckMaxSize,"$ZodCheckMimeType",()=>l.$ZodCheckMimeType,"$ZodCheckMinLength",()=>l.$ZodCheckMinLength,"$ZodCheckMinSize",()=>l.$ZodCheckMinSize,"$ZodCheckMultipleOf",()=>l.$ZodCheckMultipleOf,"$ZodCheckNumberFormat",()=>l.$ZodCheckNumberFormat,"$ZodCheckOverwrite",()=>l.$ZodCheckOverwrite,"$ZodCheckProperty",()=>l.$ZodCheckProperty,"$ZodCheckRegex",()=>l.$ZodCheckRegex,"$ZodCheckSizeEquals",()=>l.$ZodCheckSizeEquals,"$ZodCheckStartsWith",()=>l.$ZodCheckStartsWith,"$ZodCheckStringFormat",()=>l.$ZodCheckStringFormat,"$ZodCheckUpperCase",()=>l.$ZodCheckUpperCase,"$ZodCodec",()=>o.$ZodCodec,"$ZodCustom",()=>o.$ZodCustom,"$ZodCustomStringFormat",()=>o.$ZodCustomStringFormat,"$ZodDate",()=>o.$ZodDate,"$ZodDefault",()=>o.$ZodDefault,"$ZodDiscriminatedUnion",()=>o.$ZodDiscriminatedUnion,"$ZodE164",()=>o.$ZodE164,"$ZodEmail",()=>o.$ZodEmail,"$ZodEmoji",()=>o.$ZodEmoji,"$ZodEncodeError",()=>r.$ZodEncodeError,"$ZodEnum",()=>o.$ZodEnum,"$ZodError",()=>s.$ZodError,"$ZodExactOptional",()=>o.$ZodExactOptional,"$ZodFile",()=>o.$ZodFile,"$ZodFunction",()=>o.$ZodFunction,"$ZodGUID",()=>o.$ZodGUID,"$ZodIPv4",()=>o.$ZodIPv4,"$ZodIPv6",()=>o.$ZodIPv6,"$ZodISODate",()=>o.$ZodISODate,"$ZodISODateTime",()=>o.$ZodISODateTime,"$ZodISODuration",()=>o.$ZodISODuration,"$ZodISOTime",()=>o.$ZodISOTime,"$ZodIntersection",()=>o.$ZodIntersection,"$ZodJWT",()=>o.$ZodJWT,"$ZodKSUID",()=>o.$ZodKSUID,"$ZodLazy",()=>o.$ZodLazy,"$ZodLiteral",()=>o.$ZodLiteral,"$ZodMAC",()=>o.$ZodMAC,"$ZodMap",()=>o.$ZodMap,"$ZodNaN",()=>o.$ZodNaN,"$ZodNanoID",()=>o.$ZodNanoID,"$ZodNever",()=>o.$ZodNever,"$ZodNonOptional",()=>o.$ZodNonOptional,"$ZodNull",()=>o.$ZodNull,"$ZodNullable",()=>o.$ZodNullable,"$ZodNumber",()=>o.$ZodNumber,"$ZodNumberFormat",()=>o.$ZodNumberFormat,"$ZodObject",()=>o.$ZodObject,"$ZodObjectJIT",()=>o.$ZodObjectJIT,"$ZodOptional",()=>o.$ZodOptional,"$ZodPipe",()=>o.$ZodPipe,"$ZodPrefault",()=>o.$ZodPrefault,"$ZodPreprocess",()=>o.$ZodPreprocess,"$ZodPromise",()=>o.$ZodPromise,"$ZodReadonly",()=>o.$ZodReadonly,"$ZodRealError",()=>s.$ZodRealError,"$ZodRecord",()=>o.$ZodRecord,"$ZodRegistry",()=>k.$ZodRegistry,"$ZodSet",()=>o.$ZodSet,"$ZodString",()=>o.$ZodString,"$ZodStringFormat",()=>o.$ZodStringFormat,"$ZodSuccess",()=>o.$ZodSuccess,"$ZodSymbol",()=>o.$ZodSymbol,"$ZodTemplateLiteral",()=>o.$ZodTemplateLiteral,"$ZodTransform",()=>o.$ZodTransform,"$ZodTuple",()=>o.$ZodTuple,"$ZodType",()=>o.$ZodType,"$ZodULID",()=>o.$ZodULID,"$ZodURL",()=>o.$ZodURL,"$ZodUUID",()=>o.$ZodUUID,"$ZodUndefined",()=>o.$ZodUndefined,"$ZodUnion",()=>o.$ZodUnion,"$ZodUnknown",()=>o.$ZodUnknown,"$ZodVoid",()=>o.$ZodVoid,"$ZodXID",()=>o.$ZodXID,"$ZodXor",()=>o.$ZodXor,"$brand",()=>r.$brand,"$constructor",()=>r.$constructor,"$input",()=>k.$input,"$output",()=>k.$output,"Doc",()=>S.Doc,"JSONSchema",0,A,"JSONSchemaGenerator",0,class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let t=e?.target??"draft-2020-12";"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),this.ctx=(0,I.initializeContext)({processors:x.allProcessors,target:t,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,t={path:[],schemaPath:[]}){return(0,I.process)(e,this.ctx,t)}emit(e,t){t&&(t.cycles&&(this.ctx.cycles=t.cycles),t.reused&&(this.ctx.reused=t.reused),t.external&&(this.ctx.external=t.external)),(0,I.extractDefs)(this.ctx,e);let{"~standard":r,...i}=(0,I.finalize)(this.ctx,e);return i}},"NEVER",()=>r.NEVER,"TimePrecision",()=>E.TimePrecision,"_any",()=>E._any,"_array",()=>E._array,"_base64",()=>E._base64,"_base64url",()=>E._base64url,"_bigint",()=>E._bigint,"_boolean",()=>E._boolean,"_catch",()=>E._catch,"_check",()=>E._check,"_cidrv4",()=>E._cidrv4,"_cidrv6",()=>E._cidrv6,"_coercedBigint",()=>E._coercedBigint,"_coercedBoolean",()=>E._coercedBoolean,"_coercedDate",()=>E._coercedDate,"_coercedNumber",()=>E._coercedNumber,"_coercedString",()=>E._coercedString,"_cuid",()=>E._cuid,"_cuid2",()=>E._cuid2,"_custom",()=>E._custom,"_date",()=>E._date,"_decode",()=>n._decode,"_decodeAsync",()=>n._decodeAsync,"_default",()=>E._default,"_discriminatedUnion",()=>E._discriminatedUnion,"_e164",()=>E._e164,"_email",()=>E._email,"_emoji",()=>E._emoji,"_encode",()=>n._encode,"_encodeAsync",()=>n._encodeAsync,"_endsWith",()=>E._endsWith,"_enum",()=>E._enum,"_file",()=>E._file,"_float32",()=>E._float32,"_float64",()=>E._float64,"_gt",()=>E._gt,"_gte",()=>E._gte,"_guid",()=>E._guid,"_includes",()=>E._includes,"_int",()=>E._int,"_int32",()=>E._int32,"_int64",()=>E._int64,"_intersection",()=>E._intersection,"_ipv4",()=>E._ipv4,"_ipv6",()=>E._ipv6,"_isoDate",()=>E._isoDate,"_isoDateTime",()=>E._isoDateTime,"_isoDuration",()=>E._isoDuration,"_isoTime",()=>E._isoTime,"_jwt",()=>E._jwt,"_ksuid",()=>E._ksuid,"_lazy",()=>E._lazy,"_length",()=>E._length,"_literal",()=>E._literal,"_lowercase",()=>E._lowercase,"_lt",()=>E._lt,"_lte",()=>E._lte,"_mac",()=>E._mac,"_map",()=>E._map,"_max",()=>E._max,"_maxLength",()=>E._maxLength,"_maxSize",()=>E._maxSize,"_mime",()=>E._mime,"_min",()=>E._min,"_minLength",()=>E._minLength,"_minSize",()=>E._minSize,"_multipleOf",()=>E._multipleOf,"_nan",()=>E._nan,"_nanoid",()=>E._nanoid,"_nativeEnum",()=>E._nativeEnum,"_negative",()=>E._negative,"_never",()=>E._never,"_nonnegative",()=>E._nonnegative,"_nonoptional",()=>E._nonoptional,"_nonpositive",()=>E._nonpositive,"_normalize",()=>E._normalize,"_null",()=>E._null,"_nullable",()=>E._nullable,"_number",()=>E._number,"_optional",()=>E._optional,"_overwrite",()=>E._overwrite,"_parse",()=>n._parse,"_parseAsync",()=>n._parseAsync,"_pipe",()=>E._pipe,"_positive",()=>E._positive,"_promise",()=>E._promise,"_property",()=>E._property,"_readonly",()=>E._readonly,"_record",()=>E._record,"_refine",()=>E._refine,"_regex",()=>E._regex,"_safeDecode",()=>n._safeDecode,"_safeDecodeAsync",()=>n._safeDecodeAsync,"_safeEncode",()=>n._safeEncode,"_safeEncodeAsync",()=>n._safeEncodeAsync,"_safeParse",()=>n._safeParse,"_safeParseAsync",()=>n._safeParseAsync,"_set",()=>E._set,"_size",()=>E._size,"_slugify",()=>E._slugify,"_startsWith",()=>E._startsWith,"_string",()=>E._string,"_stringFormat",()=>E._stringFormat,"_stringbool",()=>E._stringbool,"_success",()=>E._success,"_superRefine",()=>E._superRefine,"_symbol",()=>E._symbol,"_templateLiteral",()=>E._templateLiteral,"_toLowerCase",()=>E._toLowerCase,"_toUpperCase",()=>E._toUpperCase,"_transform",()=>E._transform,"_trim",()=>E._trim,"_tuple",()=>E._tuple,"_uint32",()=>E._uint32,"_uint64",()=>E._uint64,"_ulid",()=>E._ulid,"_undefined",()=>E._undefined,"_union",()=>E._union,"_unknown",()=>E._unknown,"_uppercase",()=>E._uppercase,"_url",()=>E._url,"_uuid",()=>E._uuid,"_uuidv4",()=>E._uuidv4,"_uuidv6",()=>E._uuidv6,"_uuidv7",()=>E._uuidv7,"_void",()=>E._void,"_xid",()=>E._xid,"_xor",()=>E._xor,"clone",()=>i.clone,"config",()=>r.config,"createStandardJSONSchemaMethod",()=>I.createStandardJSONSchemaMethod,"createToJSONSchemaMethod",()=>I.createToJSONSchemaMethod,"decode",()=>n.decode,"decodeAsync",()=>n.decodeAsync,"describe",()=>E.describe,"encode",()=>n.encode,"encodeAsync",()=>n.encodeAsync,"extractDefs",()=>I.extractDefs,"finalize",()=>I.finalize,"flattenError",()=>s.flattenError,"formatError",()=>s.formatError,"globalConfig",()=>r.globalConfig,"globalRegistry",()=>k.globalRegistry,"initializeContext",()=>I.initializeContext,"isValidBase64",()=>o.isValidBase64,"isValidBase64URL",()=>o.isValidBase64URL,"isValidJWT",()=>o.isValidJWT,"locales",0,v,"meta",()=>E.meta,"parse",()=>n.parse,"parseAsync",()=>n.parseAsync,"prettifyError",()=>s.prettifyError,"process",()=>I.process,"regexes",0,d,"registry",()=>k.registry,"safeDecode",()=>n.safeDecode,"safeDecodeAsync",()=>n.safeDecodeAsync,"safeEncode",()=>n.safeEncode,"safeEncodeAsync",()=>n.safeEncodeAsync,"safeParse",()=>n.safeParse,"safeParseAsync",()=>n.safeParseAsync,"toDotPath",()=>s.toDotPath,"toJSONSchema",()=>x.toJSONSchema,"treeifyError",()=>s.treeifyError,"util",0,c,"version",()=>u.version],113007);var _=e.i(113007),C=e.i(907855);e.s([],664328),e.i(664328),e.s(["endsWith",()=>E._endsWith,"gt",()=>E._gt,"gte",()=>E._gte,"includes",()=>E._includes,"length",()=>E._length,"lowercase",()=>E._lowercase,"lt",()=>E._lt,"lte",()=>E._lte,"maxLength",()=>E._maxLength,"maxSize",()=>E._maxSize,"mime",()=>E._mime,"minLength",()=>E._minLength,"minSize",()=>E._minSize,"multipleOf",()=>E._multipleOf,"negative",()=>E._negative,"nonnegative",()=>E._nonnegative,"nonpositive",()=>E._nonpositive,"normalize",()=>E._normalize,"overwrite",()=>E._overwrite,"positive",()=>E._positive,"property",()=>E._property,"regex",()=>E._regex,"size",()=>E._size,"slugify",()=>E._slugify,"startsWith",()=>E._startsWith,"toLowerCase",()=>E._toLowerCase,"toUpperCase",()=>E._toUpperCase,"trim",()=>E._trim,"uppercase",()=>E._uppercase],185648);var R=e.i(185648),T=e.i(915874),D=e.i(248804);let N={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function O(e){r.config({customError:e})}function P(){return r.config().customError}t||(t={}),e.s(["ZodFirstPartyTypeKind",0,t,"ZodIssueCode",0,N,"getErrorMap",0,P,"setErrorMap",0,O],733137),e.i(733137),e.s(["$brand",()=>r.$brand,"ZodFirstPartyTypeKind",0,t,"ZodIssueCode",0,N,"config",()=>r.config,"getErrorMap",0,P,"setErrorMap",0,O],863203),e.i(863203);var $=e.i(467662),U=e.i(862061),B=e.i(628343),j=e.i(551047);let L={...C,...R,iso:j},q=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);e.s(["bigint",0,function(e){return E._coercedBigint(C.ZodBigInt,e)},"boolean",0,function(e){return E._coercedBoolean(C.ZodBoolean,e)},"date",0,function(e){return E._coercedDate(C.ZodDate,e)},"number",0,function(e){return E._coercedNumber(C.ZodNumber,e)},"string",0,function(e){return E._coercedString(C.ZodString,e)}],334512);var M=e.i(334512);e.s(["$brand",()=>r.$brand,"$input",()=>k.$input,"$output",()=>k.$output,"NEVER",()=>r.NEVER,"TimePrecision",()=>U.TimePrecision,"ZodAny",()=>C.ZodAny,"ZodArray",()=>C.ZodArray,"ZodBase64",()=>C.ZodBase64,"ZodBase64URL",()=>C.ZodBase64URL,"ZodBigInt",()=>C.ZodBigInt,"ZodBigIntFormat",()=>C.ZodBigIntFormat,"ZodBoolean",()=>C.ZodBoolean,"ZodCIDRv4",()=>C.ZodCIDRv4,"ZodCIDRv6",()=>C.ZodCIDRv6,"ZodCUID",()=>C.ZodCUID,"ZodCUID2",()=>C.ZodCUID2,"ZodCatch",()=>C.ZodCatch,"ZodCodec",()=>C.ZodCodec,"ZodCustom",()=>C.ZodCustom,"ZodCustomStringFormat",()=>C.ZodCustomStringFormat,"ZodDate",()=>C.ZodDate,"ZodDefault",()=>C.ZodDefault,"ZodDiscriminatedUnion",()=>C.ZodDiscriminatedUnion,"ZodE164",()=>C.ZodE164,"ZodEmail",()=>C.ZodEmail,"ZodEmoji",()=>C.ZodEmoji,"ZodEnum",()=>C.ZodEnum,"ZodError",()=>T.ZodError,"ZodExactOptional",()=>C.ZodExactOptional,"ZodFile",()=>C.ZodFile,"ZodFirstPartyTypeKind",0,t,"ZodFunction",()=>C.ZodFunction,"ZodGUID",()=>C.ZodGUID,"ZodIPv4",()=>C.ZodIPv4,"ZodIPv6",()=>C.ZodIPv6,"ZodISODate",()=>j.ZodISODate,"ZodISODateTime",()=>j.ZodISODateTime,"ZodISODuration",()=>j.ZodISODuration,"ZodISOTime",()=>j.ZodISOTime,"ZodIntersection",()=>C.ZodIntersection,"ZodIssueCode",0,N,"ZodJWT",()=>C.ZodJWT,"ZodKSUID",()=>C.ZodKSUID,"ZodLazy",()=>C.ZodLazy,"ZodLiteral",()=>C.ZodLiteral,"ZodMAC",()=>C.ZodMAC,"ZodMap",()=>C.ZodMap,"ZodNaN",()=>C.ZodNaN,"ZodNanoID",()=>C.ZodNanoID,"ZodNever",()=>C.ZodNever,"ZodNonOptional",()=>C.ZodNonOptional,"ZodNull",()=>C.ZodNull,"ZodNullable",()=>C.ZodNullable,"ZodNumber",()=>C.ZodNumber,"ZodNumberFormat",()=>C.ZodNumberFormat,"ZodObject",()=>C.ZodObject,"ZodOptional",()=>C.ZodOptional,"ZodPipe",()=>C.ZodPipe,"ZodPrefault",()=>C.ZodPrefault,"ZodPreprocess",()=>C.ZodPreprocess,"ZodPromise",()=>C.ZodPromise,"ZodReadonly",()=>C.ZodReadonly,"ZodRealError",()=>T.ZodRealError,"ZodRecord",()=>C.ZodRecord,"ZodSet",()=>C.ZodSet,"ZodString",()=>C.ZodString,"ZodStringFormat",()=>C.ZodStringFormat,"ZodSuccess",()=>C.ZodSuccess,"ZodSymbol",()=>C.ZodSymbol,"ZodTemplateLiteral",()=>C.ZodTemplateLiteral,"ZodTransform",()=>C.ZodTransform,"ZodTuple",()=>C.ZodTuple,"ZodType",()=>C.ZodType,"ZodULID",()=>C.ZodULID,"ZodURL",()=>C.ZodURL,"ZodUUID",()=>C.ZodUUID,"ZodUndefined",()=>C.ZodUndefined,"ZodUnion",()=>C.ZodUnion,"ZodUnknown",()=>C.ZodUnknown,"ZodVoid",()=>C.ZodVoid,"ZodXID",()=>C.ZodXID,"ZodXor",()=>C.ZodXor,"_ZodString",()=>C._ZodString,"_default",()=>C._default,"_function",()=>C._function,"any",()=>C.any,"array",()=>C.array,"base64",()=>C.base64,"base64url",()=>C.base64url,"bigint",()=>C.bigint,"boolean",()=>C.boolean,"catch",()=>C.catch,"check",()=>C.check,"cidrv4",()=>C.cidrv4,"cidrv6",()=>C.cidrv6,"clone",()=>i.clone,"codec",()=>C.codec,"coerce",0,M,"config",()=>r.config,"core",0,_,"cuid",()=>C.cuid,"cuid2",()=>C.cuid2,"custom",()=>C.custom,"date",()=>C.date,"decode",()=>D.decode,"decodeAsync",()=>D.decodeAsync,"describe",()=>C.describe,"discriminatedUnion",()=>C.discriminatedUnion,"e164",()=>C.e164,"email",()=>C.email,"emoji",()=>C.emoji,"encode",()=>D.encode,"encodeAsync",()=>D.encodeAsync,"endsWith",()=>E._endsWith,"enum",()=>C.enum,"exactOptional",()=>C.exactOptional,"file",()=>C.file,"flattenError",()=>s.flattenError,"float32",()=>C.float32,"float64",()=>C.float64,"formatError",()=>s.formatError,"fromJSONSchema",0,function(e,t){var r,i;let a,n;if("boolean"==typeof e)return e?L.any():L.never();try{a=JSON.parse(JSON.stringify(e))}catch{throw Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let s={version:(r=a,i=t?.defaultTarget,"https://json-schema.org/draft/2020-12/schema"===(n=r.$schema)?"draft-2020-12":"http://json-schema.org/draft-07/schema#"===n?"draft-7":"http://json-schema.org/draft-04/schema#"===n?"draft-4":i??"draft-2020-12"),defs:a.$defs||a.definitions||{},refs:new Map,processing:new Set,rootSchema:a,registry:t?.registry??k.globalRegistry};return function e(t,r){if("boolean"==typeof t)return t?L.any():L.never();let i=function t(r,i){let a;if(void 0!==r.not){if("object"==typeof r.not&&0===Object.keys(r.not).length)return L.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if(void 0!==r.unevaluatedItems)throw Error("unevaluatedItems is not supported");if(void 0!==r.unevaluatedProperties)throw Error("unevaluatedProperties is not supported");if(void 0!==r.if||void 0!==r.then||void 0!==r.else)throw Error("Conditional schemas (if/then/else) are not supported");if(void 0!==r.dependentSchemas||void 0!==r.dependentRequired)throw Error("dependentSchemas and dependentRequired are not supported");if(r.$ref){let t=r.$ref;if(i.refs.has(t))return i.refs.get(t);if(i.processing.has(t))return L.lazy(()=>{if(!i.refs.has(t))throw Error(`Circular reference not resolved: ${t}`);return i.refs.get(t)});i.processing.add(t);let a=e(function(e,t){if(!e.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let r=e.slice(1).split("/").filter(Boolean);if(0===r.length)return t.rootSchema;let i="draft-2020-12"===t.version?"$defs":"definitions";if(r[0]===i){let i=r[1];if(!i||!t.defs[i])throw Error(`Reference not found: ${e}`);return t.defs[i]}throw Error(`Reference not found: ${e}`)}(t,i),i);return i.refs.set(t,a),i.processing.delete(t),a}if(void 0!==r.enum){let e=r.enum;if("openapi-3.0"===i.version&&!0===r.nullable&&1===e.length&&null===e[0])return L.null();if(0===e.length)return L.never();if(1===e.length)return L.literal(e[0]);if(e.every(e=>"string"==typeof e))return L.enum(e);let t=e.map(e=>L.literal(e));return t.length<2?t[0]:L.union([t[0],t[1],...t.slice(2)])}if(void 0!==r.const)return L.literal(r.const);let n=r.type;if(Array.isArray(n)){let e=n.map(e=>t({...r,type:e},i));return 0===e.length?L.never():1===e.length?e[0]:L.union(e)}if(!n)return L.any();switch(n){case"string":{let e=L.string();if(r.format){let t=r.format;"email"===t?e=e.check(L.email()):"uri"===t||"uri-reference"===t?e=e.check(L.url()):"uuid"===t||"guid"===t?e=e.check(L.uuid()):"date-time"===t?e=e.check(L.iso.datetime()):"date"===t?e=e.check(L.iso.date()):"time"===t?e=e.check(L.iso.time()):"duration"===t?e=e.check(L.iso.duration()):"ipv4"===t?e=e.check(L.ipv4()):"ipv6"===t?e=e.check(L.ipv6()):"mac"===t?e=e.check(L.mac()):"cidr"===t?e=e.check(L.cidrv4()):"cidr-v6"===t?e=e.check(L.cidrv6()):"base64"===t?e=e.check(L.base64()):"base64url"===t?e=e.check(L.base64url()):"e164"===t?e=e.check(L.e164()):"jwt"===t?e=e.check(L.jwt()):"emoji"===t?e=e.check(L.emoji()):"nanoid"===t?e=e.check(L.nanoid()):"cuid"===t?e=e.check(L.cuid()):"cuid2"===t?e=e.check(L.cuid2()):"ulid"===t?e=e.check(L.ulid()):"xid"===t?e=e.check(L.xid()):"ksuid"===t&&(e=e.check(L.ksuid()))}"number"==typeof r.minLength&&(e=e.min(r.minLength)),"number"==typeof r.maxLength&&(e=e.max(r.maxLength)),r.pattern&&(e=e.regex(new RegExp(r.pattern))),a=e;break}case"number":case"integer":{let e="integer"===n?L.number().int():L.number();"number"==typeof r.minimum&&(e=e.min(r.minimum)),"number"==typeof r.maximum&&(e=e.max(r.maximum)),"number"==typeof r.exclusiveMinimum?e=e.gt(r.exclusiveMinimum):!0===r.exclusiveMinimum&&"number"==typeof r.minimum&&(e=e.gt(r.minimum)),"number"==typeof r.exclusiveMaximum?e=e.lt(r.exclusiveMaximum):!0===r.exclusiveMaximum&&"number"==typeof r.maximum&&(e=e.lt(r.maximum)),"number"==typeof r.multipleOf&&(e=e.multipleOf(r.multipleOf)),a=e;break}case"boolean":a=L.boolean();break;case"null":a=L.null();break;case"object":{let t={},n=r.properties||{},s=new Set(r.required||[]);for(let[r,a]of Object.entries(n)){let n=e(a,i);t[r]=s.has(r)?n:n.optional()}if(r.propertyNames){let n=e(r.propertyNames,i),s=r.additionalProperties&&"object"==typeof r.additionalProperties?e(r.additionalProperties,i):L.any();if(0===Object.keys(t).length){a=L.record(n,s);break}let o=L.object(t).passthrough(),l=L.looseRecord(n,s);a=L.intersection(o,l);break}if(r.patternProperties){let n=r.patternProperties,s=Object.keys(n),o=[];for(let t of s){let r=e(n[t],i),a=L.string().regex(new RegExp(t));o.push(L.looseRecord(a,r))}let l=[];if(Object.keys(t).length>0&&l.push(L.object(t).passthrough()),l.push(...o),0===l.length)a=L.object({}).passthrough();else if(1===l.length)a=l[0];else{let e=L.intersection(l[0],l[1]);for(let t=2;t<l.length;t++)e=L.intersection(e,l[t]);a=e}break}let o=L.object(t);a=!1===r.additionalProperties?o.strict():"object"==typeof r.additionalProperties?o.catchall(e(r.additionalProperties,i)):o.passthrough();break}case"array":{let t=r.prefixItems,n=r.items;if(t&&Array.isArray(t)){let s=t.map(t=>e(t,i)),o=n&&"object"==typeof n&&!Array.isArray(n)?e(n,i):void 0;a=o?L.tuple(s).rest(o):L.tuple(s),"number"==typeof r.minItems&&(a=a.check(L.minLength(r.minItems))),"number"==typeof r.maxItems&&(a=a.check(L.maxLength(r.maxItems)))}else if(Array.isArray(n)){let t=n.map(t=>e(t,i)),s=r.additionalItems&&"object"==typeof r.additionalItems?e(r.additionalItems,i):void 0;a=s?L.tuple(t).rest(s):L.tuple(t),"number"==typeof r.minItems&&(a=a.check(L.minLength(r.minItems))),"number"==typeof r.maxItems&&(a=a.check(L.maxLength(r.maxItems)))}else if(void 0!==n){let t=e(n,i),s=L.array(t);"number"==typeof r.minItems&&(s=s.min(r.minItems)),"number"==typeof r.maxItems&&(s=s.max(r.maxItems)),a=s}else a=L.array(L.any());break}default:throw Error(`Unsupported type: ${n}`)}return a}(t,r),a=t.type||void 0!==t.enum||void 0!==t.const;if(t.anyOf&&Array.isArray(t.anyOf)){let n=t.anyOf.map(t=>e(t,r)),s=L.union(n);i=a?L.intersection(i,s):s}if(t.oneOf&&Array.isArray(t.oneOf)){let n=t.oneOf.map(t=>e(t,r)),s=L.xor(n);i=a?L.intersection(i,s):s}if(t.allOf&&Array.isArray(t.allOf))if(0===t.allOf.length)i=a?i:L.any();else{let n=a?i:e(t.allOf[0],r),s=+!a;for(let i=s;i<t.allOf.length;i++)n=L.intersection(n,e(t.allOf[i],r));i=n}!0===t.nullable&&"openapi-3.0"===r.version&&(i=L.nullable(i)),!0===t.readOnly&&(i=L.readonly(i)),void 0!==t.default&&(i=i.default(t.default));let n={};for(let e of["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"])e in t&&(n[e]=t[e]);for(let e of["contentEncoding","contentMediaType","contentSchema"])e in t&&(n[e]=t[e]);for(let e of Object.keys(t))q.has(e)||(n[e]=t[e]);return Object.keys(n).length>0&&r.registry.add(i,n),t.description&&(i=i.describe(t.description)),i}(a,s)},"function",()=>C.function,"getErrorMap",0,P,"globalRegistry",()=>k.globalRegistry,"gt",()=>E._gt,"gte",()=>E._gte,"guid",()=>C.guid,"hash",()=>C.hash,"hex",()=>C.hex,"hostname",()=>C.hostname,"httpUrl",()=>C.httpUrl,"includes",()=>E._includes,"instanceof",()=>C.instanceof,"int",()=>C.int,"int32",()=>C.int32,"int64",()=>C.int64,"intersection",()=>C.intersection,"invertCodec",()=>C.invertCodec,"ipv4",()=>C.ipv4,"ipv6",()=>C.ipv6,"iso",0,j,"json",()=>C.json,"jwt",()=>C.jwt,"keyof",()=>C.keyof,"ksuid",()=>C.ksuid,"lazy",()=>C.lazy,"length",()=>E._length,"literal",()=>C.literal,"locales",0,v,"looseObject",()=>C.looseObject,"looseRecord",()=>C.looseRecord,"lowercase",()=>E._lowercase,"lt",()=>E._lt,"lte",()=>E._lte,"mac",()=>C.mac,"map",()=>C.map,"maxLength",()=>E._maxLength,"maxSize",()=>E._maxSize,"meta",()=>C.meta,"mime",()=>E._mime,"minLength",()=>E._minLength,"minSize",()=>E._minSize,"multipleOf",()=>E._multipleOf,"nan",()=>C.nan,"nanoid",()=>C.nanoid,"nativeEnum",()=>C.nativeEnum,"negative",()=>E._negative,"never",()=>C.never,"nonnegative",()=>E._nonnegative,"nonoptional",()=>C.nonoptional,"nonpositive",()=>E._nonpositive,"normalize",()=>E._normalize,"null",()=>C.null,"nullable",()=>C.nullable,"nullish",()=>C.nullish,"number",()=>C.number,"object",()=>C.object,"optional",()=>C.optional,"overwrite",()=>E._overwrite,"parse",()=>D.parse,"parseAsync",()=>D.parseAsync,"partialRecord",()=>C.partialRecord,"pipe",()=>C.pipe,"positive",()=>E._positive,"prefault",()=>C.prefault,"preprocess",()=>C.preprocess,"prettifyError",()=>s.prettifyError,"promise",()=>C.promise,"property",()=>E._property,"readonly",()=>C.readonly,"record",()=>C.record,"refine",()=>C.refine,"regex",()=>E._regex,"regexes",()=>$.regexes,"registry",()=>k.registry,"safeDecode",()=>D.safeDecode,"safeDecodeAsync",()=>D.safeDecodeAsync,"safeEncode",()=>D.safeEncode,"safeEncodeAsync",()=>D.safeEncodeAsync,"safeParse",()=>D.safeParse,"safeParseAsync",()=>D.safeParseAsync,"set",()=>C.set,"setErrorMap",0,O,"size",()=>E._size,"slugify",()=>E._slugify,"startsWith",()=>E._startsWith,"strictObject",()=>C.strictObject,"string",()=>C.string,"stringFormat",()=>C.stringFormat,"stringbool",()=>C.stringbool,"success",()=>C.success,"superRefine",()=>C.superRefine,"symbol",()=>C.symbol,"templateLiteral",()=>C.templateLiteral,"toJSONSchema",()=>x.toJSONSchema,"toLowerCase",()=>E._toLowerCase,"toUpperCase",()=>E._toUpperCase,"transform",()=>C.transform,"treeifyError",()=>s.treeifyError,"trim",()=>E._trim,"tuple",()=>C.tuple,"uint32",()=>C.uint32,"uint64",()=>C.uint64,"ulid",()=>C.ulid,"undefined",()=>C.undefined,"union",()=>C.union,"unknown",()=>C.unknown,"uppercase",()=>E._uppercase,"url",()=>C.url,"util",()=>B.util,"uuid",()=>C.uuid,"uuidv4",()=>C.uuidv4,"uuidv6",()=>C.uuidv6,"uuidv7",()=>C.uuidv7,"void",()=>C.void,"xid",()=>C.xid,"xor",()=>C.xor],562810);var F=e.i(562810);e.s(["z",0,F],469719)},497800,835544,499162,248626,e=>{"use strict";var t=e.i(469719),r=e.i(807055),i=e.i(184015),a=e.i(119909);let n=["JIRA_LOAD_TICKET","JIRA_TRANSITION","JIRA_COMMENT","JIRA_ASSIGN","JIRA_UPDATE_FIELDS","JIRA_RESOLVE_BRANCH","GITHUB_LOAD_PR","GITHUB_MERGE_PR","GITHUB_COLLECT_REVIEW_THREADS","GITHUB_REPLY_REVIEW_THREAD","GITHUB_SET_REVIEW_THREAD_RESOLVED","GITHUB_CREATE_PR","GITHUB_SET_PR_LABELS","GITHUB_RETRY_PIPELINE","GITHUB_RETRY_JOB","GITHUB_CANCEL_WORKFLOW_RUN","GITHUB_SAVE_AUTO_RETRY","GITHUB_WAIT_CHECKS","WORKTREE_CREATE","WORKTREE_CHANGE_BRANCH","WORKTREE_REFRESH_PULL_REQUEST","WORKTREE_OPERATION","WORKTREE_SET_AUTO_SYNC","WORKTREE_SET_AUTO_MERGE","WORKTREE_DELETE","WORKTREE_MOVE","WORKTREE_INSPECT","WORKTREE_INSPECT_GIT","WORKTREE_GIT_OPERATION","WORKTREE_WAIT_PUSH_READY","WORKTREE_SNAPSHOT","CODEBASE_FETCH_REFRESH","CODEBASE_INSPECT_GIT","CODEBASE_GIT_OPERATION","BUILD_START","BUILD_READ_TEST_RESULTS","BUILD_READ_COVERAGE","BUILD_IMPORT_COVERAGE","BUILD_EXPORT","BUILD_DEPLOY","BUILD_CANCEL","DISK_SPACE_LOAD","DISK_SPACE_REFRESH","DISK_SPACE_UPDATE_THRESHOLDS","DISK_SPACE_SET_MONITORING","DISK_SPACE_SET_PRESSURE_MODE","SKILL_APPLY","RUN_CREATE_PLAN","RUN_CREATE_SESSION","RUN_PLAY_PLAN","RUN_FOLLOW_UP","RUN_STEER","RUN_ANSWER","RUN_PAUSE","RUN_CONTINUE","RUN_CANCEL","RUN_REVISE_ANSWER","RUN_READ_RESULT","RUN_CAPTURE_CHECKPOINT","RUN_ARCHIVE_DELETE","NOTIFICATION_SEND","IOS_PUSH_SEND","HUMAN_CONFIRM","HUMAN_CHOICE","CONTROL_IF","CONTROL_JOIN","CONTROL_DELAY","CONTROL_WAIT_UNTIL","CONTROL_FOR_EACH","CONTROL_TRY","CONTROL_SET_VARIABLE","CONTROL_SUBWORKFLOW","SAVED_COMMAND","CUSTOM_COMMAND","COMMAND_RERUN","COMMAND_TERMINATE","COMMAND_READ_OUTPUT","WORKTREE_INSPECT_DIFF","WORKTREE_UPDATE_METADATA","WORKTREE_MOVE_CONTROL","BUILD_REBUILD","BUILD_GENERATE_REPORT","BUILD_DELETE","SKILL_PREPARE_SYNC","SKILL_RESOLVE_SYNC","SKILL_SKIP_SYNC","BUILD_DATA_REFRESH","BUILD_DATA_DELETE","BUILD_DATA_SET_LOCK","SIGNING_REFRESH","SIGNING_SYNC_PROFILE","SIGNING_DELETE_EXPIRED","IOS_DEVICE_REGISTER","IOS_DEVICE_REJECT","AGENT_RECONCILE","AGENT_UPDATE_CADENCE","CCUSAGE_COLLECT","MODEL_COST_REFRESH","GITHUB_UPDATE_PR","GITHUB_SUBMIT_REVIEW","GITHUB_REQUEST_REVIEWERS","GITHUB_DISPATCH_WORKFLOW","JIRA_CREATE_TICKET","JIRA_ADD_WORKLOG","JIRA_LINK_TICKETS","TERMINAL_RUN","MCP_CALL"],s=["MANUAL","MANUAL_CHOICE","RESOURCE_MANUAL","RESOURCE_MANUAL_CHOICE","SCHEDULE","WORKFLOW_FINISHED","GITHUB_PR_STATE","GITHUB_REVIEW_CHANGES_REQUESTED","GITHUB_REVIEW_COMMENT","GITHUB_PR_CLOSED","GITHUB_CHECK_FAILED","GITHUB_PUSH_DEFAULT","GITHUB_WORKFLOW_SUCCEEDED","GITHUB_ISSUE_COMMAND","GITHUB_ACTIONS_RESULT","GITHUB_PR_LABEL","BUILD_RESULT","BUILD_TEST_THRESHOLD","BUILD_COVERAGE_THRESHOLD","BUILD_HOOK_FAILED","AGENT_CONNECTION","AGENT_JOB_FAILED","AGENT_DISK_REPORT","AGENT_DISK_THRESHOLD","AGENT_DISK_STATE_CHANGED","AGENT_DISK_CLEANUP_RESULT","CCUSAGE_THRESHOLD","WORKTREE_CREATED","WORKTREE_BEHIND","WORKTREE_CONFLICT","WORKTREE_MISSING","WORKTREE_DIVERGED","WORKTREE_DIRTY_DURATION","WORKTREE_NEW_COMMIT","CODEBASE_REMOTE_BRANCH","JIRA_STATUS","JIRA_LABEL","JIRA_ASSIGNED_SELF","JIRA_SOURCE_NEW_TICKET","JIRA_MENTION","JIRA_SPRINT_STARTED","JIRA_ISSUE_CREATED","JIRA_ISSUE_DELETED","JIRA_ISSUE_COMMAND","JIRA_ATTACHMENT_ADDED","JIRA_ISSUE_LINKED","RUN_STARTED","RUN_COMPLETED","RUN_QUESTION_NEEDED","RUN_QUESTION_ANSWERED","RUN_PAUSED","RUN_CONTINUED","RUN_FAILED","RUN_CANCELLED","RUN_PLAN_PLAYED","RUN_FOLLOW_UP","RUN_IMPORTED","RUN_USAGE_THRESHOLD","RUN_EVENT_MATCH","COMMAND_RUN_RESULT","COMMAND_OUTPUT_MATCH","SKILL_SYNC_RESULT","SKILL_SYNC_CONFLICT","GITHUB_PIPELINE_STATUS_CHANGED","GITHUB_PR_SYNCHRONIZED","GITHUB_REVIEW_APPROVED","JIRA_TICKET_UPDATED","JIRA_COMMENT_ADDED","JIRA_WORKLOG_ADDED","JIRA_SPRINT_ENDED","CODEBASE_SYNC_STATE_CHANGED","CODEBASE_OPERATION_FAILED","WORKTREE_SYNC_STATE_CHANGED","WORKTREE_AUTOMATION_RESULT","WORKTREE_CLEAN","PUSH_NOTIFICATION_RESULT","IOS_DEVICE_ENROLLED","IOS_DEVICE_REGISTRATION_RESULT","SIGNING_OPERATION_RESULT","SIGNING_ASSET_EXPIRING","BUILD_DATA_THRESHOLD","BUILD_DATA_CLEANUP_RESULT","POLLING_OPERATION_STATE","MODEL_COST_CATALOG_CHANGED","CREDENTIAL_STORE_DEGRADED","AGENT_RESOURCE_THRESHOLD","AGENT_VERSION_CHANGED","TOOL_CALL_RESULT"],o=["BUILD","CODEBASE","JIRA_TICKET","AGENT_RUN","GITHUB_PIPELINE","GITHUB_JOB","PULL_REQUEST","WORKTREE","COMMAND_RUN","SKILL","SKILL_SYNC","IOS_DEVICE","SIGNING_PROFILE","PUSH_NOTIFICATION_BATCH","BUILD_DATA_COLLECTION"],l=new Set(["MANUAL_CHOICE","RESOURCE_MANUAL_CHOICE"]),u=new Set(["RESOURCE_MANUAL","RESOURCE_MANUAL_CHOICE"]);function c(e){return l.has(e)}function d(e){return u.has(e)}let p=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function h(e){return"string"==typeof e&&p.test(e)}function m(e){return c(e)?[]:"CONTROL_IF"===e?["true","false"]:"CONTROL_FOR_EACH"===e?["body","empty"]:"CONTROL_TRY"===e?["success","catch"]:["success","failure"]}e.s(["WORKFLOW_CHOICE_KEY_PATTERN",0,p,"WORKFLOW_QUICK_ACTION_KINDS",0,["STANDARD","MERGE_CONFLICT","GITHUB_ACTIONS","NONE"],"WORKFLOW_RESOURCE_KINDS",0,o,"WORKFLOW_STEP_KINDS",0,n,"WORKFLOW_TRIGGER_KINDS",0,s,"isChoiceTriggerKind",0,c,"isResourceTriggerKind",0,d,"isWorkflowChoiceKey",0,h,"workflowStaticSourceHandles",0,m],835544);let f=/^([A-Za-z0-9_-]+)(?:\[(\d+)\])?$/,g=/^[A-Za-z0-9_-]+(?:\[\d+\])?(?:\.[A-Za-z0-9_-]+(?:\[\d+\])?)*$/,y=/\{\{\s*([A-Za-z0-9_-]+(?:\[\d+\])?(?:\.[A-Za-z0-9_-]+(?:\[\d+\])?)*)\s*\}\}/g,w=/\{\{([^{}]*)\}\}/g;function b(e){return e.split(".").flatMap(t=>{let r=f.exec(t);if(!r)throw Error(`Invalid session path: ${e}`);return void 0===r[2]?[r[1]]:[r[1],Number(r[2])]})}function v(e,t){let r=e;for(let e of b(t)){if(null==r)return;if("number"==typeof e){if(!Array.isArray(r))return;r=r[e]}else{if("object"!=typeof r||Array.isArray(r))return;r=r[e]}}return r}function k(e,t){var r,i;return e&&"object"==typeof e&&!Array.isArray(e)&&"SESSION"===e.source&&"string"==typeof e.path?v(t,e.path):e&&"object"==typeof e&&!Array.isArray(e)&&"LITERAL"===e.source?e.value:Array.isArray(e)?e.map(e=>k(e,t)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,r])=>[e,k(r,t)])):"string"==typeof e?(r=e,i=t,r.replace(y,(e,t)=>{let r=v(i,t);return null==r?"":"string"==typeof r?r:JSON.stringify(r)})):e}function S(e,t=new Set){if(Array.isArray(e))for(let r of e)S(r,t);else if(e&&"object"==typeof e)for(let r of("SESSION"===e.source&&"string"==typeof e.path&&g.test(e.path)&&t.add(e.path),Object.values(e)))S(r,t);else if("string"==typeof e)for(let r of e.matchAll(y))t.add(r[1]);return t}function E(e,t=[]){if(Array.isArray(e))for(let r of e)E(r,t);else if(e&&"object"==typeof e)for(let r of("SESSION"!==e.source||"string"==typeof e.path&&g.test(e.path)||t.push("Session bindings require a valid dotted path"),Object.values(e)))E(r,t);else if("string"==typeof e&&/\{\{|\}\}/.test(e)){let r=e.replace(w,"");for(let i of(/\{\{|\}\}/.test(r)&&t.push("Text interpolation contains unmatched braces"),e.matchAll(w)))g.test(i[1].trim())||t.push("Text interpolation requires a valid dotted path")}return t}function I(e){return null===e||["string","number","boolean"].includes(typeof e)?e:JSON.stringify(e)}function x(e){return{kind:"static",options:e.map(e=>({value:e,label:e.charAt(0)+e.slice(1).toLowerCase().replace(/_/g," ")}))}}function A(e){return{kind:"static",options:e}}e.s(["evaluateWorkflowCondition",0,function e(t,r){if("ALL"===t.op)return t.conditions.every(t=>e(t,r));if("ANY"===t.op)return t.conditions.some(t=>e(t,r));if("NOT"===t.op)return!e(t.condition,r);if(!("left"in t))return!1;let i=k(t.left,r),a=k(t.right,r);switch(t.op){case"EXISTS":return null!=i;case"EQ":return JSON.stringify(i)===JSON.stringify(a);case"NE":return JSON.stringify(i)!==JSON.stringify(a);case"GT":return I(i)>I(a);case"GTE":return I(i)>=I(a);case"LT":return I(i)<I(a);case"LTE":return I(i)<=I(a);case"CONTAINS":return Array.isArray(i)?i.some(e=>JSON.stringify(e)===JSON.stringify(a)):String(i??"").includes(String(a??""));case"MATCHES":return new RegExp(String(a??"")).test(String(i??""))}},"getSessionValue",0,v,"hasSessionValue",0,function(e,t){return void 0!==v(e,t)},"invalidWorkflowValueBindings",0,E,"mergeSessionData",0,function(e,t){let r=(e,t)=>{if(e&&t&&"object"==typeof e&&"object"==typeof t&&!Array.isArray(e)&&!Array.isArray(t)){let i={...e};for(let[e,a]of Object.entries(t))i[e]=r(i[e],a);return i}return structuredClone(t)};return r(e,t)},"resolveWorkflowValue",0,k,"setSessionValue",0,function(e,t,r){let i=structuredClone(e),a=b(t),n=i;return a.forEach((e,i)=>{if(i===a.length-1){if("number"==typeof e){if(!Array.isArray(n))throw Error(`Expected an array at ${t}`);n[e]=r}else{if(Array.isArray(n))throw Error(`Expected an object at ${t}`);n[e]=r}return}let s="number"==typeof a[i+1];if("number"==typeof e){if(!Array.isArray(n))throw Error(`Expected an array at ${t}`);let r=n[e];r&&"object"==typeof r||(n[e]=s?[]:{}),n=n[e]}else{if(Array.isArray(n))throw Error(`Expected an object at ${t}`);let r=n[e];r&&"object"==typeof r||(n[e]=s?[]:{}),n=n[e]}}),i},"workflowSessionData",0,function(e){let t=JSON.parse(e);if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Workflow session data must be a JSON object");return t},"workflowValueSessionPaths",0,S],499162);let _={agent:"agent.id",codebase:"codebase.id",worktree:"worktree.id",githubRepository:"repo.id",githubPullRequest:"pr.number",jiraTicket:"ticket.key",agentRun:"run.id",githubWorkflowRun:"pipeline.runId"};function C(e,t){return{kind:"resource",resource:e,scopeFrom:t,sessionPath:_[e]}}let R=["literal","session","interpolation"],T=["literal","interpolation"],D=(e,t,r={})=>({key:e,label:t,control:"text",valueModes:R,...r}),N=(e,t,r={})=>D(e,t,{multiline:!0,...r}),O=(e,t,r={})=>({key:e,label:t,control:"number",valueModes:["literal","session"],...r}),P=(e,t,r={})=>({key:e,label:t,control:"boolean",...r}),$=(e,t,r,i={})=>({key:e,label:t,control:"enum",options:r,...i}),U=(e,t,r,i={})=>{let{scopeFrom:a,...n}=i;return{key:e,label:t,control:"resource",options:C(r,a),valueModes:R,...n}},B=(e,t,r,i={})=>{let{scopeFrom:a,...n}=i;return{key:e,label:t,control:"resourceMulti",options:C(r,a),valueModes:T,...n}},j=(e,t,r={})=>({key:e,label:t,control:"stringList",valueModes:T,...r}),L=e=>({key:"mcpPresetIds",label:"MCP tool presets",control:"mcpPresetMulti",presetKind:e,default:[]}),q=(e,t,r={})=>({key:e,label:t,control:"record",valueModes:T,...r}),M=(e,t,r={})=>({key:e,label:t,control:"json",valueModes:T,...r}),F=(e,t,r={})=>({key:e,label:t,control:"triggerChoices",...r}),K=A([{value:"EQ",label:"Equals"},{value:"NE",label:"Not equal"},{value:"GT",label:"Greater than"},{value:"GTE",label:"Greater or equal"},{value:"LT",label:"Less than"},{value:"LTE",label:"Less or equal"},{value:"CONTAINS",label:"Contains"},{value:"MATCHES",label:"Matches regex"},{value:"EXISTS",label:"Exists"}]),V=x(a.WORKTREE_OPERATIONS.filter(e=>"OPEN_EDITOR"!==e)),G=()=>[D("owner","Repository owner",{placeholder:"octocat",help:"Defaults to the repository from session data."}),D("name","Repository name",{placeholder:"hello-world"})],H=e=>[U("worktreeId","Worktree","worktree"),U("jiraIssueKey","Jira issue key","jiraTicket",{placeholder:"APP-123"}),{key:"model",label:"Model",control:"model",required:!0,valueModes:["literal","session"],modelKeys:{provider:"provider",model:"model",effort:"effort",scopeFrom:"worktreeId"}},P("webSearchEnabled","Enable web search"),L(e),O("worktreeConcurrencyLimit","Worktree concurrency limit",{default:"PLAN"===e?0:"SESSION"===e?1:void 0,minimum:0,maximum:32,integer:!0,help:"PLAN"===e?"Maximum plans admitted on this worktree. Use 0 for unlimited.":"SESSION"===e?"Maximum sessions admitted on this worktree. Use 0 for unlimited.":"Maximum same-kind runs admitted on this worktree. Use 0 for unlimited; leave empty for the source kind's default."}),N("prompt","Prompt",{required:!0}),j("attachmentIds","Attachment IDs")],W={JIRA_LOAD_TICKET:{fields:[U("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),P("force","Bypass cache")]},JIRA_TRANSITION:{fields:[U("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),D("transitionId","Transition ID",{required:!0})]},JIRA_COMMENT:{fields:[U("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),N("content","Comment",{required:!0}),$("format","Format",A([{value:"MARKDOWN",label:"Markdown"},{value:"JIRA_WIKI",label:"Jira wiki"}]))]},JIRA_ASSIGN:{fields:[U("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),U("accountId","Assignee","jiraUser",{scopeFrom:"issueKey",help:"Leave empty to unassign the ticket."})]},JIRA_UPDATE_FIELDS:{fields:[U("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),M("fields","Fields",{placeholder:'{ "labels": ["ready"] }'})]},JIRA_RESOLVE_BRANCH:{fields:[U("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),U("codebaseId","Codebase","codebase")]},GITHUB_LOAD_PR:{fields:[...G(),O("number","Pull request number")]},GITHUB_MERGE_PR:{fields:[...G(),O("number","Pull request number"),$("method","Merge method",A([{value:"SQUASH",label:"Squash"},{value:"MERGE",label:"Merge"},{value:"REBASE",label:"Rebase"}])),D("commitHeadline","Commit headline"),N("commitBody","Commit body"),D("authorEmail","Author email")]},GITHUB_COLLECT_REVIEW_THREADS:{fields:[...G(),O("number","Pull request number")]},GITHUB_REPLY_REVIEW_THREAD:{fields:[D("threadId","Review thread ID",{required:!0}),N("body","Reply",{required:!0})]},GITHUB_SET_REVIEW_THREAD_RESOLVED:{fields:[D("threadId","Review thread ID",{required:!0}),P("resolved","Mark resolved")]},GITHUB_CREATE_PR:{fields:[...G(),D("baseRefName","Base branch"),D("headRefName","Head branch"),D("title","Title"),N("body","Body"),P("draft","Open as draft")]},GITHUB_SET_PR_LABELS:{fields:[...G(),O("number","Pull request number"),j("labels","Labels")]},GITHUB_RETRY_PIPELINE:{fields:[U("repositoryId","Repository","githubRepository"),D("checkSuiteId","Check suite ID")]},GITHUB_RETRY_JOB:{fields:[U("repositoryId","Repository","githubRepository"),D("checkSuiteId","Check suite ID",{required:!0}),D("jobId","Workflow job ID",{required:!0})]},GITHUB_CANCEL_WORKFLOW_RUN:{fields:[D("codebaseRepositoryId","Codebase repository ID"),U("workflowRunId","Workflow run","githubWorkflowRun",{scopeFrom:"codebaseRepositoryId"}),P("force","Force cancel")]},GITHUB_SAVE_AUTO_RETRY:{fields:[M("input","Auto-retry rule",{required:!0})]},GITHUB_WAIT_CHECKS:{fields:[D("repositoryId","Repository ID"),D("workflowRunId","Workflow run ID")]},WORKTREE_CREATE:{fields:[U("codebaseId","Codebase","codebase"),$("mode","Branch mode",x(["NEW","EXISTING","TICKET"])),D("branchName","Branch name"),D("ticketKey","Ticket key",{placeholder:"APP-123"}),D("baseBranch","Base branch")]},WORKTREE_CHANGE_BRANCH:{fields:[U("worktreeId","Worktree","worktree"),$("mode","Branch mode",x(["NEW","EXISTING","TICKET"])),D("branchName","Branch name"),D("ticketKey","Ticket key",{placeholder:"APP-123"}),D("baseBranch","Base branch"),P("stashOnFailure","Stash on failure")]},WORKTREE_REFRESH_PULL_REQUEST:{fields:[U("worktreeId","Worktree","worktree")]},WORKTREE_OPERATION:{fields:[U("worktreeId","Worktree","worktree"),$("operation","Operation",V)]},WORKTREE_SET_AUTO_SYNC:{fields:[U("worktreeId","Worktree","worktree"),$("action","Action",x(["ENABLE","RETRY","CANCEL"])),D("conflictWorkflowId","Conflict workflow ID"),D("conflictWorkflowChoice","Conflict workflow choice")]},WORKTREE_SET_AUTO_MERGE:{fields:[U("worktreeId","Worktree","worktree"),$("action","Action",x(["ENABLE","RETRY","CANCEL"])),D("repositoryNameWithOwner","Repository",{placeholder:"owner/repository"}),O("pullRequestNumber","Pull request number"),$("method","Merge method",x(["MERGE","REBASE","SQUASH"])),D("commitHeadline","Commit headline"),N("commitBody","Commit body"),D("authorEmail","Author email"),P("deleteWorktree","Delete worktree after merge"),P("moveTicketToDone","Move Jira ticket to done")]},WORKTREE_DELETE:{fields:[U("worktreeId","Worktree","worktree"),P("deleteRemoteBranch","Delete remote branch")]},WORKTREE_MOVE:{fields:[U("worktreeId","Source worktree","worktree"),U("targetCodebaseId","Target codebase","codebase",{required:!0}),U("targetWorktreeId","Target worktree","worktree"),P("deleteSource","Delete source")]},WORKTREE_INSPECT:{fields:[U("worktreeId","Worktree","worktree")]},WORKTREE_INSPECT_GIT:{fields:[U("worktreeId","Worktree","worktree")]},WORKTREE_GIT_OPERATION:{fields:[U("worktreeId","Worktree","worktree"),$("operation","Operation",x(a.WORKTREE_GIT_OPERATIONS)),D("branch","Branch"),D("stashOid","Stash OID"),P("stashChanges","Stash changes first")]},WORKTREE_WAIT_PUSH_READY:{fields:[U("worktreeId","Worktree","worktree")]},WORKTREE_SNAPSHOT:{fields:[D("kind","Checkpoint kind",{placeholder:"STEP"})]},CODEBASE_FETCH_REFRESH:{fields:[U("codebaseId","Codebase","codebase"),$("operation","Operation",x(["FETCH","REFRESH"]))]},CODEBASE_INSPECT_GIT:{fields:[U("codebaseId","Codebase","codebase")]},CODEBASE_GIT_OPERATION:{fields:[U("codebaseId","Codebase","codebase"),$("operation","Operation",x(i.CODEBASE_GIT_OPERATIONS)),D("branch","Branch"),D("stashOid","Stash OID"),P("stashChanges","Stash changes first")]},BUILD_START:{fields:[U("worktreeId","Worktree","worktree"),D("configurationId","Build configuration ID",{required:!0}),$("action","Action",x(r.BUILD_ACTIONS)),M("destination","Destination"),B("scriptIds","Build scripts","buildScript"),M("advancedSettings","Advanced settings"),P("exportWhenComplete","Export when complete"),M("exportSettings","Export settings"),P("worktreeCoverage","Collect worktree coverage")]},BUILD_READ_TEST_RESULTS:{fields:[D("buildId","Build ID")]},BUILD_READ_COVERAGE:{fields:[D("buildId","Build ID")]},BUILD_IMPORT_COVERAGE:{fields:[U("worktreeId","Worktree","worktree"),D("buildName","Build name",{default:"{{workflow.name}}",help:"Name shown on the build and coverage pages. Defaults to the workflow name."}),D("reportPath","Coverage file",{required:!0,default:"coverage/lcov.info",help:"Path inside the worktree, written by whichever test command ran first."}),$("format","Coverage format",x(["AUTO","LCOV","ISTANBUL"]))]},BUILD_EXPORT:{fields:[D("buildId","Build ID"),M("settings","Export settings",{required:!0})]},BUILD_DEPLOY:{fields:[D("buildId","Build ID"),M("destinations","Destinations")]},BUILD_CANCEL:{fields:[D("buildId","Build ID")]},DISK_SPACE_LOAD:{fields:[U("agentId","Agent","agent")]},DISK_SPACE_REFRESH:{fields:[U("agentId","Agent","agent")]},DISK_SPACE_UPDATE_THRESHOLDS:{fields:[O("normalThresholdGiB","Normal threshold (GiB)",{required:!0}),O("pressureThresholdGiB","Pressure threshold (GiB)",{required:!0})]},DISK_SPACE_SET_MONITORING:{fields:[U("agentId","Agent","agent"),P("enabled","Monitoring enabled",{required:!0,default:!0})]},DISK_SPACE_SET_PRESSURE_MODE:{fields:[U("agentId","Agent","agent"),P("enabled","Manual pressure mode",{required:!0,default:!0})]},SKILL_APPLY:{fields:[U("groupId","Skill group","skillGroup",{help:"Leave empty to sync all skills."})]},NOTIFICATION_SEND:{fields:[D("title","Title",{required:!0}),N("body","Body",{required:!0}),D("href","Link")]},IOS_PUSH_SEND:{fields:[$("targetMode","Target mode",x(["ALL","DEVICES","BROADCAST","DIRECT"])),B("registrationIds","Registrations","apnsRegistration"),U("channelId","Broadcast channel","apnsChannel"),M("editor","Notification editor"),D("directToken","Direct device token"),$("directTokenEncoding","Token encoding",x(["HEX","BASE64"])),$("directEnvironment","Environment",x(["SANDBOX","PRODUCTION"]))]},COMMAND_RERUN:{fields:[D("commandRunId","Command run ID",{required:!0})]},COMMAND_TERMINATE:{fields:[D("commandRunId","Command run ID",{required:!0})]},COMMAND_READ_OUTPUT:{fields:[D("commandRunId","Command run ID",{required:!0}),O("first","Maximum chunks")]},WORKTREE_INSPECT_DIFF:{fields:[D("worktreeId","Worktree ID"),D("scope","Diff scope",{required:!0}),D("path","Path"),D("previousPath","Previous path"),D("commitSha","Commit SHA")]},WORKTREE_UPDATE_METADATA:{fields:[D("worktreeId","Worktree ID"),D("baseBranch","Base branch"),D("highlightColor","Highlight color")]},WORKTREE_MOVE_CONTROL:{fields:[D("moveId","Move ID",{required:!0}),$("operation","Operation",x(["RETRY_WITH_STASH","CANCEL"]))]},BUILD_REBUILD:{fields:[D("buildId","Build ID")]},BUILD_GENERATE_REPORT:{fields:[D("buildId","Build ID"),$("reportKind","Report kind",x(["TEST_RESULTS","CODE_COVERAGE"]))]},BUILD_DELETE:{fields:[j("buildIds","Build IDs")]},SKILL_PREPARE_SYNC:{fields:[$("syncKind","Sync kind",x(["ALL","GROUP"])),D("groupId","Skill group ID")]},SKILL_RESOLVE_SYNC:{fields:[D("runId","Sync run ID",{required:!0}),D("itemId","Conflict item ID",{required:!0}),$("resolution","Resolution",x(["LOCAL","REMOTE","SKIP"]))]},SKILL_SKIP_SYNC:{fields:[D("runId","Sync run ID",{required:!0})]},BUILD_DATA_REFRESH:{fields:[]},BUILD_DATA_DELETE:{fields:[D("collectionId","Collection ID",{required:!0}),j("entryIds","Entry IDs"),P("overrideProtection","Override protection")]},BUILD_DATA_SET_LOCK:{fields:[D("collectionId","Collection ID",{required:!0}),D("entryId","Entry ID",{required:!0}),P("locked","Locked")]},SIGNING_REFRESH:{fields:[j("agentIds","Agent IDs")]},SIGNING_SYNC_PROFILE:{fields:[D("uuid","Profile UUID",{required:!0}),D("sourceAgentId","Source agent ID",{required:!0}),j("targetAgentIds","Target agent IDs")]},SIGNING_DELETE_EXPIRED:{fields:[j("agentIds","Agent IDs")]},IOS_DEVICE_REGISTER:{fields:[D("deviceId","Device ID",{required:!0})]},IOS_DEVICE_REJECT:{fields:[D("deviceId","Device ID",{required:!0})]},AGENT_RECONCILE:{fields:[j("agentIds","Agent IDs")]},AGENT_UPDATE_CADENCE:{fields:[D("agentId","Agent ID",{required:!0}),M("settings","Cadence settings")]},CCUSAGE_COLLECT:{fields:[]},MODEL_COST_REFRESH:{fields:[]},GITHUB_UPDATE_PR:{fields:[D("owner","Owner",{required:!0}),D("name","Repository",{required:!0}),O("number","Pull request number",{required:!0}),D("title","Title"),N("body","Body"),P("draft","Draft")]},GITHUB_SUBMIT_REVIEW:{fields:[D("owner","Owner",{required:!0}),D("name","Repository",{required:!0}),O("number","Pull request number",{required:!0}),$("event","Review event",x(["APPROVE","REQUEST_CHANGES","COMMENT"])),N("body","Body")]},GITHUB_REQUEST_REVIEWERS:{fields:[D("owner","Owner",{required:!0}),D("name","Repository",{required:!0}),O("number","Pull request number",{required:!0}),j("reviewers","Reviewers"),j("teamReviewers","Team reviewers")]},GITHUB_DISPATCH_WORKFLOW:{fields:[D("repositoryId","Repository ID",{required:!0}),D("workflowId","Workflow ID",{required:!0}),D("ref","Git ref",{required:!0}),q("inputs","Workflow inputs")]},JIRA_CREATE_TICKET:{fields:[D("projectKey","Project key",{required:!0}),D("issueTypeId","Issue type ID",{required:!0}),D("summary","Summary",{required:!0}),N("description","Description"),M("fields","Additional fields")]},JIRA_ADD_WORKLOG:{fields:[D("issueKey","Issue key"),O("timeSpentSeconds","Time spent (seconds)",{required:!0}),D("startedAt","Started at"),N("comment","Comment")]},JIRA_LINK_TICKETS:{fields:[D("inwardIssueKey","Inward issue key",{required:!0}),D("outwardIssueKey","Outward issue key",{required:!0}),D("linkType","Link type",{required:!0})]},MCP_CALL:{fields:[U("groupId","MCP server","mcpServer",{required:!0}),D("name","Tool name",{required:!0}),M("arguments","Arguments")]},RUN_CREATE_PLAN:{fields:H("PLAN")},RUN_CREATE_SESSION:{fields:H("SESSION")},RUN_PLAY_PLAN:{fields:[D("runId","Plan run ID"),L("SESSION"),O("worktreeConcurrencyLimit","Worktree concurrency limit",{default:1,minimum:0,maximum:32,integer:!0,help:"Maximum sessions admitted on this worktree. Use 0 for unlimited."})]},RUN_FOLLOW_UP:{fields:[D("runId","Source run ID"),...H(null),$("followUpMode","Follow-up mode",x(["RESUME","FRESH","RESEND"])),D("contextMode","Context mode")]},RUN_STEER:{fields:[D("runId","Run ID"),N("prompt","Steering prompt",{required:!0}),j("attachmentIds","Attachment IDs")]},RUN_ANSWER:{fields:[D("batchId","Question batch ID",{required:!0}),M("answers","Answers")]},RUN_PAUSE:{fields:[D("runId","Run ID")]},RUN_CONTINUE:{fields:[D("runId","Run ID")]},RUN_CANCEL:{fields:[D("runId","Run ID")]},RUN_REVISE_ANSWER:{fields:[D("batchId","Question batch ID",{required:!0}),M("answers","Answers"),P("stash","Stash before revision"),P("rollback","Roll back to the question")]},RUN_READ_RESULT:{fields:[D("runId","Run ID")]},RUN_CAPTURE_CHECKPOINT:{fields:[D("runId","Run ID")]},RUN_ARCHIVE_DELETE:{fields:[D("runId","Run ID"),P("delete","Delete permanently"),P("archived","Archive")]},HUMAN_CONFIRM:{fields:[N("prompt","Prompt")]},HUMAN_CHOICE:{fields:[N("prompt","Prompt"),P("multiSelect","Allow multiple selections"),P("allowCustom","Allow a custom answer"),((e,t,r={})=>({key:e,label:t,control:"choiceOptions",valueModes:T,...r}))("options","Buttons")]},CONTROL_IF:{fields:[((e,t,r={})=>({key:e,label:t,control:"condition",valueModes:T,...r}))("condition","Condition",{required:!0})]},CONTROL_JOIN:{fields:[$("mode","Join mode",A([{value:"ALL",label:"All — wait for every branch"},{value:"ANY",label:"Any — continue on the first branch"}]),{help:"All (default) waits until every incoming branch has finished before continuing. Any continues as soon as the first incoming branch arrives, and the remaining branches keep running on their own. Either way, branches that were skipped do not block the join, and the join itself is skipped when no branch reaches it."})]},CONTROL_DELAY:{fields:[O("seconds","Delay (seconds)",{required:!0})]},CONTROL_WAIT_UNTIL:{fields:[M("condition","Condition",{required:!0})]},CONTROL_FOR_EACH:{fields:[D("listPath","List session path",{placeholder:"pr.unresolvedThreads"}),M("items","Inline items"),$("errorMode","Error handling",A([{value:"FAIL_FAST",label:"Fail fast"},{value:"COLLECT_ERRORS",label:"Collect errors"}]))]},CONTROL_TRY:{fields:[]},CONTROL_SET_VARIABLE:{fields:[D("path","Output path",{required:!0,placeholder:"flags.ready"}),M("value","Value"),N("script","Script")]},CONTROL_SUBWORKFLOW:{fields:[D("versionId","Sub-workflow version ID",{required:!0}),M("inputMapping","Input mapping")]},SAVED_COMMAND:{fields:[D("commandId","Saved command ID",{required:!0}),$("completionMode","Completion",x(["WAIT_FOR_EXIT","FIRE_AND_FORGET"])),$("targetMode","Target",x(["CONTEXT","FIXED_AGENT","FIXED_WORKTREE"])),D("agentId","Fixed agent ID",{visibleWhen:{key:"targetMode",equals:"FIXED_AGENT"}}),D("worktreeId","Fixed worktree ID",{visibleWhen:{key:"targetMode",equals:"FIXED_WORKTREE"}})]},CUSTOM_COMMAND:{fields:[N("script","Script",{required:!0}),$("completionMode","Completion",x(["WAIT_FOR_EXIT","FIRE_AND_FORGET"])),$("targetMode","Target",x(["CONTEXT","FIXED_AGENT","FIXED_WORKTREE"])),D("agentId","Fixed agent ID",{visibleWhen:{key:"targetMode",equals:"FIXED_AGENT"}}),D("worktreeId","Fixed worktree ID",{visibleWhen:{key:"targetMode",equals:"FIXED_WORKTREE"}})]},TERMINAL_RUN:{fields:[N("script","Script",{required:!0}),$("interpreter","Interpreter",x(["SHELL","NODE"])),q("environment","Environment variables"),M("credentials","Credential environment",{help:"JSON array of { name, credential: { id, kind, ownerId } } entries."})]}},J=()=>O("timeoutSeconds","Timeout (seconds)",{help:"How long to keep waiting before the step fails. Leave empty to wait for as long as the work takes."});function z(e,t){for(let r of e){let e=W[r];if(!e)continue;let i=new Set(e.fields.map(({key:e})=>e));e.fields=[...e.fields,...t().filter(({key:e})=>!i.has(e))]}}function Z(e=[]){return{fields:[...e,q("filters","Filters",{help:"Match when each session path equals the given value.",recordValueType:"json"})]}}z(["WORKTREE_CREATE","WORKTREE_CHANGE_BRANCH","WORKTREE_OPERATION","WORKTREE_DELETE","WORKTREE_GIT_OPERATION","WORKTREE_MOVE","WORKTREE_WAIT_PUSH_READY","WORKTREE_SNAPSHOT","CODEBASE_FETCH_REFRESH","CODEBASE_GIT_OPERATION","BUILD_START","BUILD_IMPORT_COVERAGE","BUILD_EXPORT","BUILD_DEPLOY","DISK_SPACE_REFRESH","TERMINAL_RUN","RUN_CREATE_PLAN","RUN_CREATE_SESSION","RUN_PLAY_PLAN","RUN_FOLLOW_UP","RUN_REVISE_ANSWER","SAVED_COMMAND","CUSTOM_COMMAND","COMMAND_RERUN","BUILD_REBUILD","BUILD_DATA_REFRESH","SIGNING_REFRESH","SIGNING_SYNC_PROFILE","SIGNING_DELETE_EXPIRED","SKILL_APPLY","GITHUB_WAIT_CHECKS","CONTROL_SUBWORKFLOW","CONTROL_WAIT_UNTIL"],()=>[O("cadenceSeconds","Poll cadence (seconds)",{help:"How often to check whether the work has finished. Leave empty for this step's default."}),J()]),z(["HUMAN_CONFIRM","HUMAN_CHOICE"],()=>[J()]);let Y=["BUILD_TEST_THRESHOLD","BUILD_COVERAGE_THRESHOLD","AGENT_DISK_THRESHOLD","CCUSAGE_THRESHOLD","RUN_USAGE_THRESHOLD","BUILD_DATA_THRESHOLD","AGENT_RESOURCE_THRESHOLD","SIGNING_ASSET_EXPIRING"],Q=Object.fromEntries(["MANUAL","MANUAL_CHOICE","RESOURCE_MANUAL","RESOURCE_MANUAL_CHOICE","SCHEDULE","WORKFLOW_FINISHED","GITHUB_PR_STATE","GITHUB_REVIEW_CHANGES_REQUESTED","GITHUB_REVIEW_COMMENT","GITHUB_PR_CLOSED","GITHUB_CHECK_FAILED","GITHUB_PUSH_DEFAULT","GITHUB_WORKFLOW_SUCCEEDED","GITHUB_ISSUE_COMMAND","GITHUB_ACTIONS_RESULT","GITHUB_PR_LABEL","BUILD_RESULT","BUILD_TEST_THRESHOLD","BUILD_COVERAGE_THRESHOLD","BUILD_HOOK_FAILED","AGENT_CONNECTION","AGENT_JOB_FAILED","AGENT_DISK_REPORT","AGENT_DISK_THRESHOLD","AGENT_DISK_STATE_CHANGED","AGENT_DISK_CLEANUP_RESULT","CCUSAGE_THRESHOLD","WORKTREE_CREATED","WORKTREE_BEHIND","WORKTREE_CONFLICT","WORKTREE_MISSING","WORKTREE_DIVERGED","WORKTREE_DIRTY_DURATION","WORKTREE_NEW_COMMIT","CODEBASE_REMOTE_BRANCH","JIRA_STATUS","JIRA_LABEL","JIRA_ASSIGNED_SELF","JIRA_SOURCE_NEW_TICKET","JIRA_MENTION","JIRA_SPRINT_STARTED","JIRA_ISSUE_CREATED","JIRA_ISSUE_DELETED","JIRA_ISSUE_COMMAND","JIRA_ATTACHMENT_ADDED","JIRA_ISSUE_LINKED","RUN_STARTED","RUN_COMPLETED","RUN_QUESTION_NEEDED","RUN_QUESTION_ANSWERED","RUN_PAUSED","RUN_CONTINUED","RUN_FAILED","RUN_CANCELLED","RUN_PLAN_PLAYED","RUN_FOLLOW_UP","RUN_IMPORTED","RUN_USAGE_THRESHOLD","RUN_EVENT_MATCH","COMMAND_RUN_RESULT","COMMAND_OUTPUT_MATCH","SKILL_SYNC_RESULT","SKILL_SYNC_CONFLICT","GITHUB_PIPELINE_STATUS_CHANGED","GITHUB_PR_SYNCHRONIZED","GITHUB_REVIEW_APPROVED","JIRA_TICKET_UPDATED","JIRA_COMMENT_ADDED","JIRA_WORKLOG_ADDED","JIRA_SPRINT_ENDED","CODEBASE_SYNC_STATE_CHANGED","CODEBASE_OPERATION_FAILED","WORKTREE_SYNC_STATE_CHANGED","WORKTREE_AUTOMATION_RESULT","WORKTREE_CLEAN","PUSH_NOTIFICATION_RESULT","IOS_DEVICE_ENROLLED","IOS_DEVICE_REGISTRATION_RESULT","SIGNING_OPERATION_RESULT","SIGNING_ASSET_EXPIRING","BUILD_DATA_THRESHOLD","BUILD_DATA_CLEANUP_RESULT","POLLING_OPERATION_STATE","MODEL_COST_CATALOG_CHANGED","CREDENTIAL_STORE_DEGRADED","AGENT_RESOURCE_THRESHOLD","AGENT_VERSION_CHANGED","TOOL_CALL_RESULT"].map(e=>"RESOURCE_MANUAL"===e||"RESOURCE_MANUAL_CHOICE"===e?[e,Z([$("resourceKind","Resource kind",x(o),{required:!0}),..."RESOURCE_MANUAL_CHOICE"===e?[F("choices","Choices",{required:!0})]:[]])]:"MANUAL_CHOICE"===e?[e,Z([F("choices","Choices",{required:!0})])]:"SCHEDULE"===e?[e,Z([O("cadenceSeconds","Cadence (seconds)",{required:!0})])]:"GITHUB_ISSUE_COMMAND"===e?[e,Z([j("allowedLogins","Allowed logins",{placeholder:"octocat",required:!0}),D("commandPattern","Command pattern (regex)",{placeholder:"^/deploy\\b$",required:!0,valueModes:["literal","interpolation"]})])]:"JIRA_ISSUE_COMMAND"===e?[e,Z([j("allowedAccountIds","Allowed account IDs",{placeholder:"5b10a2844c20165700ede21g",required:!0}),D("commandPattern","Command pattern (regex)",{placeholder:"^/deploy\\b$",required:!0,valueModes:["literal","interpolation"]})])]:"COMMAND_OUTPUT_MATCH"===e?[e,Z([D("outputPattern","Output pattern (regex)",{placeholder:"error|failed",required:!0,valueModes:["literal","interpolation"]})])]:Y.includes(e)?[e,Z([D("thresholdPath","Threshold path",{placeholder:"build.testSummary.failed"}),$("thresholdOperator","Operator",K),M("thresholdValue","Threshold value")])]:[e,Z()]));function X(e,t){return"step"===t?W[e]:Q[e]}function ee(e,t,r){let i=function(e,t){let r=X(e,t);if(!r)return null;let i=new Set,a=new Set;for(let e of r.fields){for(let t of"model"===e.control&&e.modelKeys?[e.modelKeys.provider,e.modelKeys.model,e.modelKeys.effort]:[e.key])i.add(t);e.required&&a.add(e.key)}return{described:i,required:a}}(e,t);if(!i||!r||"object"!=typeof r||Array.isArray(r))return S(r);let a=new Set;for(let[e,t]of Object.entries(r))(!i.described.has(e)||i.required.has(e))&&S(t,a);return a}e.s(["getConfigDescriptor",0,X,"requiredConfigSessionPaths",0,ee],248626);let et=["EQ","NE","GT","GTE","LT","LTE","CONTAINS","MATCHES","EXISTS"],er={type:"object",title:"Session binding",description:"Reads the value from run session data at `path` instead of hard-coding it.",properties:{source:{const:"SESSION"},path:{type:"string",description:"Dotted session path, e.g. `ticket.key` or `pr.number`."}},required:["source","path"],additionalProperties:!1},ei={type:"object",title:"Literal wrapper",description:"An explicit constant. Equivalent to writing the value directly; the editor uses it to record that a field was pinned rather than bound.",properties:{source:{const:"LITERAL"},value:{}},required:["source"],additionalProperties:!1};function ea(e,t,r){let i=r.valueModes??[],a=[i.includes("session")?"May also be a session binding.":null,i.includes("interpolation")?"Strings here — including strings nested inside the value — may carry `{{path}}` interpolation tokens, e.g. `{{worktree.baseBranch}}`.":null].filter(Boolean),n=a.length?{...t,description:[t.description,...a].filter(Boolean).join(" ")}:t;return i.includes("session")?{anyOf:[e,er,ei],...n}:{...e,...n}}function en(e){let t=e.options?function(e){if("static"===e.kind){let t=e.options.filter(({label:e})=>e);return t.length?t.map(({value:e,label:t})=>`\`${e}\` — ${t}`).join("; "):null}let t=e.scopeFrom?` Scoped by the sibling \`${e.scopeFrom}\` value.`:"",r=e.sessionPath?` Usually bound to \`${e.sessionPath}\`.`:"";return`Identifier of a ${e.resource} known to the control plane.${r}${t}`}(e.options):null,r={description:[e.label,e.help,t].filter(Boolean).join(" — ")};return e.placeholder&&(r.examples=[e.placeholder]),void 0!==e.default&&(r.default=e.default),ea(function(e){switch(e.control){case"number":return{type:e.integer?"integer":"number",...void 0===e.minimum?{}:{minimum:e.minimum},...void 0===e.maximum?{}:{maximum:e.maximum}};case"boolean":return{type:"boolean"};case"enum":{let t=e.options;if(t?.kind==="static")return{type:"string",enum:t.options.map(({value:e})=>e)};return{type:"string"}}case"resource":case"model":case"text":default:return{type:"string"};case"resourceMulti":case"stringList":case"mcpPresetMulti":return{type:"array",items:{type:"string"}};case"record":return{type:"object",additionalProperties:"json"===e.recordValueType?{}:{type:"string"}};case"condition":return{$ref:"#/$defs/condition"};case"choiceOptions":return{type:"array",description:"Buttons offered to the person answering.",items:{type:"object",properties:{label:{type:"string"},description:{type:"string"}},required:["label"],additionalProperties:!1}};case"triggerChoices":return{type:"array",minItems:1,description:"Options this trigger offers. Each `key` names an outgoing handle on the trigger, so edges stay attached when a label is renamed.",items:{type:"object",properties:{key:{type:"string",pattern:p.source},label:{type:"string"},description:{type:"string"}},required:["key","label"],additionalProperties:!1}};case"json":return{}}}(e),r,e)}function es(e,t){let r=X(e,t);if(!r)return{type:"object",additionalProperties:!0};let i={},a=[],n=!1;for(let e of r.fields){for(let[t,r]of("condition"===e.control&&(n=!0),"model"===e.control?function(e){let t=e.modelKeys;if(!t)return[[e.key,en(e)]];let r=(t,r)=>[t,ea({type:"string"},{description:r},e)];return[r(t.provider,"AI provider that serves the model."),r(t.model,"Model identifier, as listed by the provider catalog."),r(t.effort,"Reasoning effort, when the model supports it.")]}(e):[[e.key,en(e)]]))i[t]=r;e.required&&a.push(e.key)}let s={type:"object",properties:i,additionalProperties:!0};return a.length&&(s.required=a),n&&(s.$defs={condition:{type:"object",description:"A condition tree. `ALL`/`ANY` combine nested conditions, `NOT` negates one, and the comparison operators test `left` against `right`.",anyOf:[{properties:{op:{enum:["ALL","ANY"]},conditions:{type:"array",items:{$ref:"#/$defs/condition"}}},required:["op","conditions"]},{properties:{op:{const:"NOT"},condition:{$ref:"#/$defs/condition"}},required:["op","condition"]},{properties:{op:{enum:[...et]},left:{description:"Value to test — usually a session binding. `EXISTS` needs only this side."},right:{description:"Value to compare against."}},required:["op","left"]}]}}),s}let eo="aide.workflow";function el(e){let t=e?.choices;if(!Array.isArray(t))return[];let r=[],i=new Set;for(let e of t)!(!e||"object"!=typeof e||Array.isArray(e))&&(!h(e.key)||i.has(e.key)||(i.add(e.key),r.push({key:e.key,label:"string"==typeof e.label&&e.label.trim()?e.label:e.key,description:"string"==typeof e.description?e.description:""})));return r}let eu={BUILD:["build.*","worktree.*","codebase.*","agent.*","repo.*","ticket.*"],CODEBASE:["codebase.*","agent.*","repo.*"],JIRA_TICKET:["ticket.*","comment.*"],AGENT_RUN:["run.*","worktree.*","codebase.*","agent.*","repo.*","ticket.*"],GITHUB_PIPELINE:["pipeline.*","repo.*","pr.*","worktree.*","codebase.*","agent.*","ticket.*"],GITHUB_JOB:["job.*","pipeline.*","repo.*","pr.*","worktree.*","codebase.*","agent.*","ticket.*"],PULL_REQUEST:["pr.number","repo.displayOrigin"],WORKTREE:["worktree.*","codebase.*","agent.*","repo.*","ticket.*","pr.*"],COMMAND_RUN:["command.*","agent.*","worktree.*","codebase.*","repo.*"],SKILL:["skill.*","repo.*","codebase.*"],SKILL_SYNC:["skillSync.*","skill.*","repo.*","codebase.*","worktree.*"],IOS_DEVICE:["device.*"],SIGNING_PROFILE:["signingProfile.*","device.*","agent.*"],PUSH_NOTIFICATION_BATCH:["pushBatch.*"],BUILD_DATA_COLLECTION:["buildData.*","agent.*","worktree.*","codebase.*"]};function ec(e){let t=e?.resourceKind;return"string"==typeof t&&o.includes(t)?t:null}function ed(e,t){if(!d(e))return[];let r=ec(t);return r?eu[r]:[]}let ep=(e,t,r,i,a,n,s)=>({kind:e,category:t,label:r,description:s.description,details:s.details,execution:i,configSchema:es(e,"step"),capabilityFlags:[i,...s.mutatesExternal?["MUTATES_EXTERNAL"]:[],...s.mutatesWorktree?["MUTATES_WORKTREE"]:[]],requiredPaths:a,providedPaths:n,sourceHandles:m(e),mutatesExternal:s.mutatesExternal??!1,mutatesWorktree:s.mutatesWorktree??!1}),eh=["worktree.*","codebase.*","agent.*","repo.*","ticket.*","pr.*"],em=["codebase.*","agent.*","repo.*"],ef=(e,t,r,i=[],a=["steps.<stepId>.*"],n={})=>ep(e,t,r,"SERVER",i,a,{description:`${r} using the control plane's typed service API.`,details:`${r} is a first-class action with validated configuration, audit-friendly output, resource links where available, and normal workflow failure routing.`,...n}),eg=[ef("COMMAND_RERUN","Commands","Rerun command",["command.id"],["command.*"]),ef("COMMAND_TERMINATE","Commands","Terminate command",["command.id"],["command.*"]),ef("COMMAND_READ_OUTPUT","Commands","Read command output",["command.id"],["command.*"]),ef("WORKTREE_INSPECT_DIFF","Worktrees","Inspect worktree diff",["worktree.id"],["worktree.diff.*"]),ef("WORKTREE_UPDATE_METADATA","Worktrees","Update worktree metadata",["worktree.id"],eh),ef("WORKTREE_MOVE_CONTROL","Worktrees","Control worktree move",[],eh,{mutatesWorktree:!0}),ef("BUILD_REBUILD","Builds","Rebuild build",["build.id"],["build.*"]),ef("BUILD_GENERATE_REPORT","Builds","Generate build report",["build.id"],["build.*"]),ef("BUILD_DELETE","Builds","Delete builds",[],["build.*"]),ef("SKILL_PREPARE_SYNC","Skills","Prepare skill sync",[],["skillSync.*"]),ef("SKILL_RESOLVE_SYNC","Skills","Resolve skill sync conflict",["skillSync.id"],["skillSync.*"]),ef("SKILL_SKIP_SYNC","Skills","Skip skill sync",["skillSync.id"],["skillSync.*"]),ef("BUILD_DATA_REFRESH","Build Data","Refresh build data",[],["buildData.*"]),ef("BUILD_DATA_DELETE","Build Data","Delete build data",["buildData.id"],["buildData.*"]),ef("BUILD_DATA_SET_LOCK","Build Data","Set build-data lock",["buildData.id"],["buildData.*"]),ef("SIGNING_REFRESH","Signing","Refresh signing assets",[],["signing.*"]),ef("SIGNING_SYNC_PROFILE","Signing","Sync signing profile",["signingProfile.id"],["signing.*"]),ef("SIGNING_DELETE_EXPIRED","Signing","Delete expired profiles",[],["signing.*"]),ef("IOS_DEVICE_REGISTER","Devices","Register iOS device",["device.id"],["device.*"],{mutatesExternal:!0}),ef("IOS_DEVICE_REJECT","Devices","Reject iOS device",["device.id"],["device.*"],{mutatesExternal:!0}),ef("AGENT_RECONCILE","Agents","Reconcile agents",[],["agent.*"]),ef("AGENT_UPDATE_CADENCE","Agents","Update agent cadence",["agent.id"],["agent.*"]),ef("CCUSAGE_COLLECT","Operations","Collect usage",[],["usage.*"]),ef("MODEL_COST_REFRESH","Operations","Refresh model costs",[],["modelCosts.*"],{mutatesExternal:!0}),ef("GITHUB_UPDATE_PR","GitHub","Update pull request",["pr.number","repo.*"],["pr.*"],{mutatesExternal:!0}),ef("GITHUB_SUBMIT_REVIEW","GitHub","Submit pull request review",["pr.number","repo.*"],["pr.*"],{mutatesExternal:!0}),ef("GITHUB_REQUEST_REVIEWERS","GitHub","Request pull request reviewers",["pr.number","repo.*"],["pr.*"],{mutatesExternal:!0}),ef("GITHUB_DISPATCH_WORKFLOW","GitHub","Dispatch GitHub workflow",["repo.*"],["pipeline.*"],{mutatesExternal:!0}),ef("JIRA_CREATE_TICKET","Jira","Create Jira ticket",[],["ticket.*"],{mutatesExternal:!0}),ef("JIRA_ADD_WORKLOG","Jira","Add Jira worklog",["ticket.key"],["ticket.*"],{mutatesExternal:!0}),ef("JIRA_LINK_TICKETS","Jira","Link Jira tickets",["ticket.key"],["ticket.*"],{mutatesExternal:!0})],ey=[ep("JIRA_LOAD_TICKET","Jira","Load Jira ticket","SERVER",[],["ticket.*"],{description:"Reads a Jira issue and puts its fields — key, title, type, status, assignee, labels — into session data as `ticket.*`.",details:'Needs a configured Jira credential. Leave the identifier unset to take it from session data. Results are served from cache unless "Bypass cache" is set, so a step that reads a ticket right after changing it should force a refresh. Fails when the issue does not exist or the credential cannot see it. Read-only: it changes nothing in Jira.'}),ep("JIRA_TRANSITION","Jira","Transition Jira ticket","SERVER",["ticket.key"],["ticket.*"],{description:"Moves a ticket to another status by applying one of its workflow transitions.",details:"Takes a transition id, not a status name — the ids are board-specific, so read them from the ticket's available transitions rather than hard-coding a guess. Fails when the transition is not currently available on that issue, which is what happens if an earlier step already moved it. Refreshes `ticket.*` from the response.",mutatesExternal:!0}),ep("JIRA_COMMENT","Jira","Add Jira comment","SERVER",["ticket.key"],["ticket.*"],{description:"Posts a comment on a Jira issue, written in Markdown or Jira wiki markup.",details:"The comment body is converted from Markdown by default; choose Jira wiki format to pass markup through untouched. Comments are never deduplicated, so a step that runs twice comments twice — guard it with a condition if the workflow can retry. Refreshes `ticket.*` from the response.",mutatesExternal:!0}),ep("JIRA_ASSIGN","Jira","Assign Jira ticket","SERVER",["ticket.key"],["ticket.*"],{description:"Sets the assignee of a Jira issue, or clears it when no account is given.",details:"Takes a Jira account id rather than a display name or email. Leaving the assignee empty unassigns the ticket. Fails when the account cannot be assigned on that project. Refreshes `ticket.*` from the response.",mutatesExternal:!0}),ep("JIRA_UPDATE_FIELDS","Jira","Update Jira fields","SERVER",["ticket.key"],["ticket.*"],{description:"Patches arbitrary fields on a Jira issue — labels, summary, custom fields — from a JSON object.",details:"The escape hatch for anything the dedicated Jira steps do not cover. Keys are passed to the Jira update API as given, so an unknown or screen-hidden field fails the step. Prefer the specific steps for status and assignee. Refreshes `ticket.*` from the response.",mutatesExternal:!0}),ep("JIRA_RESOLVE_BRANCH","Jira","Resolve ticket branch","SERVER",["ticket.key","ticket.title","ticket.type"],["worktree.branch","ticket.key","ticket.title","ticket.type"],{description:"Works out the branch name a ticket would get under the codebase's naming convention, without creating anything.",details:"A preview step: it writes `worktree.branch` plus the ticket key, title, and type into session data and touches neither Git nor Jira. Use it before Create worktree when you want the branch name available to earlier steps — for a worktree keyed off a ticket, Create worktree in TICKET mode derives the same name on its own."}),ep("GITHUB_LOAD_PR","GitHub","Load pull request","SERVER",[],["pr.*"],{description:"Reads a pull request and puts its state, branches, labels, checks, and review threads into session data as `pr.*`.",details:"Needs a configured GitHub credential. Owner and repository default to the repository already in session data, and the number to `pr.number`. Fails when the pull request does not exist or the credential cannot see it. Read-only."}),ep("GITHUB_MERGE_PR","GitHub","Merge pull request","SERVER",["pr.number"],["pr.state"],{description:"Merges an open pull request using squash, merge, or rebase, optionally overriding the commit message.",details:"Checks mergeability first and fails with GitHub's own blocking reason — conflicts, failing required checks, missing approvals, an already-closed pull request — rather than forcing the merge. Commit headline and body default to what GitHub would use. Squash is the default method. Irreversible, and repository policy may delete the head branch as a side effect, which strands any worktree still on it. Writes `pr.state`.",mutatesExternal:!0}),ep("GITHUB_COLLECT_REVIEW_THREADS","GitHub","Collect review comments","SERVER",["pr.number"],["pr.unresolvedThreads"],{description:"Gathers the unresolved review threads on a pull request into `pr.unresolvedThreads`.",details:"Resolved threads are filtered out. The result is a list, so it pairs with For each to work through the comments one at a time — the reply and resolve steps take a single thread id from the iteration. Read-only."}),ep("GITHUB_REPLY_REVIEW_THREAD","GitHub","Reply to review thread","SERVER",["pr.unresolvedThreads"],[],{description:"Posts a reply into an existing pull request review thread.",details:"Takes the thread id from Collect review comments, usually inside a For each. Replies are not deduplicated, so a retried step comments twice. Replying does not resolve the thread — follow with Resolve review thread when that is the intent.",mutatesExternal:!0}),ep("GITHUB_SET_REVIEW_THREAD_RESOLVED","GitHub","Resolve review thread","SERVER",["pr.unresolvedThreads"],[],{description:"Marks a pull request review thread resolved, or reopens it.",details:"Takes the thread id from Collect review comments. Resolving is the default; clear the flag to unresolve. Reviewers see this as the bot resolving their comment, so it is usually paired with a reply that explains what changed.",mutatesExternal:!0}),ep("GITHUB_CREATE_PR","GitHub","Open pull request","SERVER",["worktree.branch","worktree.baseBranch"],["pr.*"],{description:"Opens a pull request from the worktree's branch, optionally as a draft.",details:"Head branch defaults to `worktree.branch`, base to `worktree.baseBranch`, and the title to `ticket.title`. The head branch must already be pushed — put Wait for push-ready or a push operation in front of this step. Fails when a pull request is already open for the same branch pair. Writes the new pull request to `pr.*`.",mutatesExternal:!0}),ep("GITHUB_SET_PR_LABELS","GitHub","Set pull request labels","SERVER",["pr.number"],["pr.labels"],{description:"Replaces the labels on a pull request with the given list.",details:"This sets rather than adds — labels not in the list are removed, so include the ones you want to keep. Labels must already exist in the repository. Writes `pr.labels`.",mutatesExternal:!0}),ep("GITHUB_RETRY_PIPELINE","GitHub Actions","Retry failed pipeline","SERVER",["pipeline.runId"],["pipeline.status"],{description:"Re-runs the failed jobs of a check suite, leaving the jobs that passed alone.",details:"Targets a check suite rather than a single job — use Retry workflow job for that. Re-running consumes Actions minutes and re-executes whatever those jobs do, including deployments. Pair it with a Time delay and a retry limit so a permanently broken pipeline is not retried forever. Writes `pipeline.status`.",mutatesExternal:!0}),ep("GITHUB_RETRY_JOB","GitHub Actions","Retry workflow job","SERVER",["pipeline.failedJobs"],[],{description:"Re-runs one job of a GitHub Actions workflow run.",details:"Needs the repository, check suite, and job ids together — typically read out of `pipeline.failedJobs` inside a For each. Use Retry failed pipeline to re-run every failed job at once instead.",mutatesExternal:!0}),ep("GITHUB_CANCEL_WORKFLOW_RUN","GitHub Actions","Cancel workflow run","SERVER",["pipeline.runId"],["pipeline.status"],{description:"Cancels an in-progress GitHub Actions workflow run.",details:"Falls back to `repo.id` and `pipeline.runId` from session data. Force-cancel skips the graceful shutdown that lets `always()` cleanup jobs finish, so leave it off unless a run is stuck. Cancelling a run that has already finished is an error. Writes `pipeline.status`.",mutatesExternal:!0}),ep("GITHUB_SAVE_AUTO_RETRY","GitHub Actions","Install auto-retry rule","SERVER",["pipeline.runId"],[],{description:"Saves a standing rule that automatically retries matching GitHub Actions failures.",details:"Persists configuration rather than acting once — the rule keeps applying after this run ends, and stays until something removes it. Takes the rule as a JSON object. Treat it as a settings change, not a step you re-run casually.",mutatesExternal:!0}),ep("GITHUB_WAIT_CHECKS","GitHub Actions","Wait for checks","WAIT",["pipeline.runId"],["pipeline.status","pipeline.conclusion","pipeline.jobs"],{description:"Parks the run until a GitHub Actions workflow run finishes, then continues on its conclusion.",details:"Polls until the run reaches a terminal status. Anything other than success fails the step, so route the failure handle to the recovery path — or set the step's failure policy to continue and branch on `pipeline.conclusion` yourself. Also refreshes `pipeline.jobs`. Without a timeout the wait is open-ended; a hung pipeline holds the workflow run indefinitely. Falls back to `repo.id` and `pipeline.runId`."}),ep("WORKTREE_CREATE","Worktrees","Create worktree","SERVER",["codebase.id"],eh,{description:"Creates a Git worktree on the agent for a new, existing, or ticket-derived branch.",details:"Dispatches a job to the agent that owns the codebase and waits for it, so the agent must be online. Branch mode NEW cuts a branch from the base, EXISTING checks one out, and TICKET derives the name from `ticket.key`. Base branch falls back to `worktree.baseBranch` then `repo.defaultBranch`. Refreshes the created worktree, codebase, owning agent, repository, and any linked ticket. Creates real directories on disk.",mutatesWorktree:!0}),ep("WORKTREE_CHANGE_BRANCH","Worktrees","Change worktree branch","SERVER",["worktree.id"],eh,{description:"Switches an existing worktree to a different branch, creating it if needed.",details:'Same branch modes as Create worktree. Uncommitted changes block the switch unless "Stash on failure" is set, which stashes them and retries — the stash is left for a human to deal with. Refreshes the worktree and all of its related resource context.',mutatesWorktree:!0}),ep("WORKTREE_REFRESH_PULL_REQUEST","Worktrees","Refresh pull request","SERVER",["worktree.id"],["pr.*"],{description:"Forces exact-branch pull request discovery and refreshes the worktree's persisted pull request context.",details:"Uses the configured worktree, falling back to `worktree.id`. The step succeeds with `found: false` and clears `pr` when the branch has no open pull request.",mutatesWorktree:!0,mutatesExternal:!1}),ep("WORKTREE_OPERATION","Worktrees","Run worktree operation","SERVER",["worktree.id"],eh,{description:"Runs one of the built-in worktree maintenance operations, such as syncing with the base branch or pushing.",details:"Dispatches an agent job and waits for it. Opening an editor is rejected here — it needs a human at the machine. Sync and push touch the remote and can conflict; check `worktree.pushStatus` afterwards or follow with Inspect worktree Git state.",mutatesWorktree:!0}),ep("WORKTREE_SET_AUTO_SYNC","Worktrees","Set worktree Auto Sync","SERVER",["worktree.id"],["worktree.autoSync"],{description:"Enables, updates, retries, or cancels persistent Auto Sync for a worktree.",details:"An enabled rule rebases on the target branch whenever it changes and force-pushes with lease. A merge-conflict quick-action workflow can be selected as the automatic recovery path; unresolved conflicts pause the rule.",mutatesWorktree:!0,mutatesExternal:!0}),ep("WORKTREE_SET_AUTO_MERGE","Worktrees","Set worktree Auto Merge","SERVER",["worktree.id"],["worktree.autoMerge"],{description:"Enables, updates, retries, or cancels GitHub-native Auto Merge for a worktree.",details:"GitHub remains the authority for required checks and reviews. Optional post-merge actions can move the linked Jira ticket to its configured done status and safely delete a clean linked worktree.",mutatesWorktree:!0,mutatesExternal:!0}),ep("WORKTREE_DELETE","Worktrees","Delete worktree","SERVER",["worktree.id"],em,{description:"Removes a worktree from the agent, optionally deleting its remote branch too.",details:"Destroys the directory and any uncommitted work in it — there is no undo. Deleting the remote branch as well affects everyone, and closes any pull request from that branch. Do not put this before steps that still read `worktree.*`.",mutatesWorktree:!0}),ep("WORKTREE_MOVE","Worktrees","Move worktree","SERVER",["worktree.id"],eh,{description:"Moves a worktree's branch and changes into another codebase, optionally deleting the source.",details:"Waits for the move job to finish. Used when a branch was started against the wrong checkout. Deleting the source destroys the original directory; leaving it keeps both, which means two worktrees on one branch. Refreshes `worktree.*` to point at wherever the work now lives.",mutatesWorktree:!0}),ep("WORKTREE_INSPECT","Worktrees","Inspect worktree","SERVER",["worktree.id"],["worktree.commits","worktree.changes","worktree.branchChanges","worktree.commitsTruncated","worktree.changesTruncated","worktree.branchChangesTruncated"],{description:"Reads the worktree's commits and changed files into `worktree.commits` and `worktree.changes`.",details:"Read-only. Use it to give a later condition or AI prompt something concrete to work from — for example to skip opening a pull request when nothing changed. For push/dirty state use Inspect worktree Git state instead, which is cheaper."}),ep("WORKTREE_INSPECT_GIT","Worktrees","Inspect worktree Git state","SERVER",["worktree.id"],["worktree.*"],{description:"Reads the worktree's Git status — dirty flag, ahead/behind counts, push status, conflicts — into `worktree.*`.",details:"Read-only and the cheap way to branch on repository state: gate a commit on `worktree.dirty`, or a sync on the worktree being behind. Use Inspect worktree when you need the actual commits and diffs."}),ep("WORKTREE_GIT_OPERATION","Worktrees","Run worktree Git operation","SERVER",["worktree.id"],eh,{description:"Runs a specific Git operation in the worktree — pull, push, rebase, stash, and the rest.",details:'Dispatches an agent job and waits for it. Operations that rewrite history or touch the remote can fail on conflicts; "Stash changes first" clears the way for operations that need a clean tree. Prefer Run worktree operation for the higher-level sync and push flows, which handle more of the edge cases.',mutatesWorktree:!0}),ep("WORKTREE_WAIT_PUSH_READY","Worktrees","Wait for push-ready","WAIT",["worktree.id"],eh,{description:"Parks the run until the worktree's branch is pushed and tracking a remote.",details:"The step to put between an AI session that commits and Open pull request, which needs the branch to exist on the remote. Resolves as soon as the branch is push-ready; without a timeout it waits indefinitely, so set one if a human may never push. Writes `worktree.pushStatus`."}),ep("WORKTREE_SNAPSHOT","Worktrees","Snapshot Git state","AGENT",["worktree.path"],["steps.<stepId>.snapshotId"],{description:"Captures a restorable checkpoint of the worktree's Git state before a risky step.",details:"Runs on the agent, so it needs `worktree.path` and an online agent. The snapshot id it writes is what run replay restores from, which makes this the step to place before anything that rewrites the tree. Snapshots cost disk on the agent."}),ep("CODEBASE_FETCH_REFRESH","Codebases","Fetch or refresh codebase","SERVER",["codebase.id"],em,{description:"Fetches remote refs for a codebase, or fully refreshes its cached metadata.",details:"Fetch updates remote-tracking branches; refresh re-reads the whole checkout and is slower. Runs as an agent job and waits. Fails when the agent skips the operation — usually because the codebase is missing or already busy. Put a fetch in front of steps that check whether a remote branch exists.",mutatesWorktree:!0}),ep("CODEBASE_INSPECT_GIT","Codebases","Inspect codebase Git state","SERVER",["codebase.id"],["codebase.*"],{description:"Reads the codebase checkout's Git status into `codebase.*`.",details:"Read-only. This is the primary checkout, not a worktree — use Inspect worktree Git state for per-branch work. Useful for refusing to start work when the base checkout is dirty or on an unexpected branch."}),ep("CODEBASE_GIT_OPERATION","Codebases","Run codebase Git operation","SERVER",["codebase.id"],em,{description:"Runs a Git operation against the codebase's primary checkout.",details:'Same operations as the worktree version, aimed at the main checkout that every worktree branches from — so a bad rebase or reset here affects all of them. "Stash changes first" clears local modifications out of the way. Runs as an agent job and waits.',mutatesWorktree:!0}),ep("BUILD_START","Builds","Start build or test","SERVER",["codebase.id","worktree.id"],["build.*"],{description:"Queues an iOS build, test, or archive run on the agent and waits for it to finish.",details:"Needs a build configuration id and an online agent; the destination and build scripts are optional. The step parks until the build reaches a terminal status, so a long test suite holds the workflow run. Failing builds fail the step — route the failure handle if you want to read the results anyway. Writes `build.*`, which the read-results and coverage steps then consume.",mutatesExternal:!0}),ep("BUILD_READ_TEST_RESULTS","Builds","Read test results","SERVER",["build.id"],["build.testSummary","build.tests"],{description:"Reads a finished build's test report into `build.testSummary` and `build.tests`.",details:"Fails outright when the report is not ready, so it belongs after Start build or test rather than in parallel with it. The summary carries the passed/failed counts a condition can branch on; the per-test list is the detail an AI prompt can be pointed at. Read-only."}),ep("BUILD_READ_COVERAGE","Builds","Read code coverage","SERVER",["build.id"],["build.coverageSummary","build.coverageFiles","build.changedCoverageFiles"],{description:"Reads a finished build's coverage report into `build.coverageSummary` and the per-file breakdowns.",details:'Fails when the coverage report is not ready — the build must have been run with coverage collection on. Also writes the changed-files breakdown, which is what a "coverage on this branch\'s changes" gate should read rather than the whole-project number. Read-only.'}),ep("BUILD_IMPORT_COVERAGE","Builds","Import coverage report","SERVER",["worktree.id"],["build.id","build.coverageSummary"],{description:"Reads a coverage file a test command wrote in the worktree and records it as a coverage report.",details:"Pair it with a Terminal command step that runs the test suite first: this step only reads what that run left behind, at the path given in `Coverage file`. The build name defaults to the workflow name and can be overridden. LCOV and Istanbul (`coverage-final.json`) are both understood, and AUTO tells them apart by the file itself. Runs as an agent job and waits. The report is attached to a new build record of its own, so it shows up on that build's coverage page and in the coverage picker on Changes; changed-line coverage is measured against the worktree's base branch, and is left out when that branch cannot be resolved. Writes the totals to `build.coverageSummary` and the new id to `build.id` — follow with Read code coverage for the per-file breakdown. Fails when the file is missing, unreadable, or describes no files."}),ep("BUILD_EXPORT","Builds","Export archive","SERVER",["build.id"],["build.exportId",...eh],{description:"Exports a finished archive build into a distributable package on the agent.",details:"Needs export settings and an archive-action build. Runs as an agent job and waits. Writes files to the agent's disk and may talk to Apple's servers for signing, so it can fail on expired certificates or provisioning profiles.",mutatesExternal:!0}),ep("BUILD_DEPLOY","Builds","Deploy build","SERVER",["build.id"],eh,{description:"Installs and launches an existing build on its destinations without rebuilding.",details:"Reuses the artifacts from a previous build, so it is much faster than building again. Destinations default to the ones the build already targeted. Waits for the deployment job. This puts the app on real or simulated devices — treat it as an external effect.",mutatesExternal:!0}),ep("BUILD_CANCEL","Builds","Cancel build","SERVER",["build.id"],["build.id","build.status"],{description:"Cancels a queued or running build.",details:"Aimed at a different build from the one this run started — Start build or test already waits for its own. Cancelling an already-finished build is a no-op rather than an error. Writes `build.status`.",mutatesExternal:!0}),ep("DISK_SPACE_LOAD","Disk space","Load disk-space monitor","SERVER",[],["agent.*","disk.*"],{description:"Loads the current Derived Data disk-space monitor snapshot for an agent.",details:"Targets the configured agent, then falls back to `agent.id` or `codebase.agentId`. The least-free monitored Derived Data volume supplies `disk.freeBytes`, `disk.freeGiB`, and the percentage fields; root and base-repository volumes remain in `disk.volumes` for context only. Read-only and does not request a new report."}),ep("DISK_SPACE_REFRESH","Disk space","Refresh disk-space monitor","WAIT",[],["agent.*","disk.*"],{description:"Requests an immediate disk report from an agent and waits for fresh telemetry.",details:"Targets the configured agent, then falls back to `agent.id` or `codebase.agentId`. Monitoring must be enabled. The step waits until `lastReportedAt` advances, then refreshes `agent.*` and `disk.*`; by default it polls every two seconds and times out after 180 seconds."}),ep("DISK_SPACE_UPDATE_THRESHOLDS","Disk space","Update disk thresholds","SERVER",[],["disk.normalThresholdGiB","disk.pressureThresholdGiB","disk.pollIntervalSeconds","disk.staleAfterSeconds"],{description:"Updates the global normal and pressure free-space thresholds.",details:"Changes the thresholds used for every monitored agent, automatic cleanup, and admission control. The pressure threshold must be positive and lower than the normal threshold. Writes the resulting global settings into `disk.*`."}),ep("DISK_SPACE_SET_MONITORING","Disk space","Set agent disk monitoring","SERVER",[],["agent.*","disk.*"],{description:"Enables or disables Derived Data disk-space monitoring for an agent.",details:"Targets the configured agent, then falls back to `agent.id` or `codebase.agentId`. Disabling monitoring also clears manual and automatic pressure mode and releases cleanup leases that have not started a job. Refreshes `agent.*` and `disk.*`."}),ep("DISK_SPACE_SET_PRESSURE_MODE","Disk space","Set disk pressure mode","SERVER",[],["agent.*","disk.*"],{description:"Enables or clears manual disk pressure mode for an agent.",details:"Targets the configured agent, then falls back to `agent.id` or `codebase.agentId`. Manual pressure mode uses the lower pressure threshold; automatic pressure mode remains controlled by cleanup availability. Refreshes `agent.*` and `disk.*`."}),ep("SKILL_APPLY","Skills","Apply skill group","SERVER",["worktree.id","repo.id"],["steps.<stepId>.status"],{description:"Syncs a skill group's files into the target checkout, or every skill when no group is chosen.",details:"Starts a skill sync run and waits for it. Writes skill files into the repository, which shows up as uncommitted changes — commit or discard them before a step that needs a clean tree. Leave the group empty to sync everything.",mutatesWorktree:!0}),ep("RUN_CREATE_PLAN","AI runs","Create plan and wait","SERVER",["worktree.id"],["run.<stepId>.*"],{description:"Starts an AI planning run against the worktree and waits for the plan to be produced.",details:"Requires a worktree, a provider/model, and a prompt. Plans use a separate FIFO worktree queue and allow unlimited concurrent plans by default; set the worktree concurrency limit to 1–32 to cap them, or 0 for unlimited. Planning inspects the code but does not change it — use Run AI session and wait to actually make edits, or follow with Run completed plan. If the run asks a question it parks until someone answers, so pair long workflows with a question-needed trigger. Writes the run under `run.<stepId>.*`, which later steps reference by this step's id."}),ep("RUN_CREATE_SESSION","AI runs","Run AI session and wait","SERVER",["worktree.id"],["run.<stepId>.*"],{description:"Starts an AI coding session against the worktree and waits for it to finish.",details:"The workhorse step: the agent edits files in the worktree, so the tree is dirty afterwards and the changes still need committing and pushing. Sessions use a separate FIFO worktree queue with one active session by default; set the worktree concurrency limit to 2–32 for parallel sessions or 0 for unlimited. Requires a worktree, a provider/model, and a prompt; attachments and web search are optional. Parks on questions until answered. Writes `run.<stepId>.*`.",mutatesWorktree:!0}),ep("RUN_PLAY_PLAN","AI runs","Run completed plan","SERVER",[],["run.<stepId>.*"],{description:"Executes a plan that has already been produced, turning it into real code changes.",details:"Takes the plan's run id — usually `run.<planStepId>.id` from an earlier Create plan step. The plan must have completed. The resulting Session joins the worktree's FIFO Session queue, which allows one active Session by default; use 0 for unlimited or 2–32 for a larger limit. This is the half of the plan/execute split that touches the worktree. Writes a new run under `run.<stepId>.*`.",mutatesWorktree:!0}),ep("RUN_FOLLOW_UP","AI runs","Follow up run","SERVER",[],["run.<stepId>.*"],{description:"Starts a new AI run that continues from an existing one, resuming its context or starting fresh.",details:'RESUME keeps the previous conversation, FRESH starts over in the same worktree, and RESEND replays the original prompt. The new run joins the source kind\'s separate FIFO worktree queue and defaults to unlimited concurrency for Plans or one active run for Sessions; use 0 for unlimited or 1–32 for a finite limit. Needs the source run id plus a new prompt. The natural step for "fix the review comments" loops after a first session. Writes `run.<stepId>.*`.'}),ep("RUN_STEER","AI runs","Steer active run","SERVER",[],["run.<stepId>.*"],{description:"Sends extra instructions into a run that is already in progress.",details:"Only affects a run that is still going — it does not restart a finished one, which is what Follow up run is for. Because the steps in this workflow that start runs also wait for them, steering usually targets a run started elsewhere, reached through a run trigger."}),ep("RUN_ANSWER","AI runs","Answer run question","SERVER",[],["run.<stepId>.*"],{description:"Answers a question an AI run is blocked on so it can carry on.",details:"Needs the question batch id, typically from `run.questions` seeded by a run-needs-an-answer trigger, and answers keyed by question id. This answers questions asked by an AI run — the Request confirmation and Ask user to choose steps ask questions of a human about the workflow itself."}),ep("RUN_PAUSE","AI runs","Pause run","SERVER",[],["run.<stepId>.*"],{description:"Pauses an in-progress AI run.",details:"The run stops at its next checkpoint and stays paused until something continues it. Falls back to `run.id`. Pausing an already-finished run fails."}),ep("RUN_CONTINUE","AI runs","Continue run","SERVER",[],["run.<stepId>.*"],{description:"Resumes a paused AI run.",details:"The counterpart to Pause run. Fails when the run is not paused. Falls back to `run.id`."}),ep("RUN_CANCEL","AI runs","Cancel run","SERVER",[],["run.<stepId>.*"],{description:"Cancels an AI run, stopping its work.",details:"Whatever the run already wrote to the worktree stays — cancelling stops further work, it does not roll anything back. Falls back to `run.id`."}),ep("RUN_REVISE_ANSWER","AI runs","Revise answer and rewind","SERVER",[],["run.<stepId>.*"],{description:"Rewinds a run to an earlier question, replaces the answer, and replays from there.",details:"Two-phase: the step prepares the revision, parks, and applies it once the run is ready. Rolling back restores the worktree to the checkpoint at that question, discarding work done since — stash first if that work matters. The heavy way to correct a wrong answer; Follow up run is usually enough.",mutatesWorktree:!0}),ep("RUN_READ_RESULT","AI runs","Read run result","SERVER",[],["run.<stepId>.*"],{description:"Loads a finished run's events, questions, token usage, and linked items into session data.",details:"Read-only. Gives later steps the run's actual output to work from — a summary to put in a Jira comment, usage figures to threshold on, or the linked pull request. Falls back to `run.id`."}),ep("RUN_CAPTURE_CHECKPOINT","AI runs","Capture run checkpoint","SERVER",[],["steps.<stepId>.snapshotId"],{description:"Records the run's most recent checkpoint so a later replay can restore from it.",details:"Reads an existing checkpoint rather than creating one, and fails when the run has none. Use Snapshot Git state to capture a fresh checkpoint of the worktree instead. Writes the checkpoint id to `steps.<stepId>.snapshotId`."}),ep("RUN_ARCHIVE_DELETE","AI runs","Archive or delete run","SERVER",[],[],{description:"Archives a run out of the active list, or permanently deletes it.",details:"Archiving is reversible; deleting removes the run and its history for good. Delete wins when both flags are set. Housekeeping for workflows that generate many short-lived runs.",mutatesExternal:!0}),ep("NOTIFICATION_SEND","Human loop","Send notification","SERVER",[],[],{description:"Posts a notification into the app's notification list with a title, body, and link.",details:"Deduplicated per run, step, and generation, so a retried attempt does not notify twice. The link defaults to this workflow run. Fire-and-forget: it tells a human something happened but does not wait — use Request confirmation when the workflow needs an answer.",mutatesExternal:!0}),ep("IOS_PUSH_SEND","Human loop","Push to iOS device","SERVER",[],[],{description:"Sends an Apple push notification to registered devices, a broadcast channel, or one raw device token.",details:"Needs APNs credentials. Target mode picks between all registrations, a chosen few, a broadcast channel, or a direct token — the direct mode also needs the token's encoding and whether it is a sandbox or production token. Leaves the device once delivered; nothing about the run waits on it.",mutatesExternal:!0}),ep("HUMAN_CONFIRM","Human loop","Request confirmation","WAIT",[],["steps.<stepId>.answer"],{description:"Parks the run and asks a human to confirm before continuing.",details:"The approval gate to put in front of anything irreversible. Without a timeout the run waits indefinitely; with one it fails when nobody answers in time, which the failure handle can route to a safe default. The answer lands in `steps.<stepId>.answer`."}),ep("HUMAN_CHOICE","Human loop","Ask user to choose","WAIT",[],["steps.<stepId>.answer"],{description:"Parks the run and asks a human to pick from a set of options, optionally allowing several or a free-text answer.",details:"Like Request confirmation but with named buttons — branch on `steps.<stepId>.answer` with an If step afterwards. Multi-select returns a list. Allowing a custom answer means the value may be anything the person typed, so handle the unexpected case."}),ep("CONTROL_IF","Control flow","If / else","CONTROL",[],[],{description:"Evaluates a condition and sends the run down its `true` or `false` branch.",details:"Exactly one branch is taken; steps on the other are skipped, and a skipped branch does not block a downstream join. Conditions compare session values with the usual operators and combine with ALL/ANY/NOT. Both branches may be left unconnected, which simply ends that path."}),ep("CONTROL_JOIN","Control flow","Join branches","CONTROL",[],[],{description:"Brings parallel branches back together, waiting for all of them or continuing on the first.",details:"Required wherever more than one branch reaches the same step — the validator rejects a plain step with several incoming edges. ALL waits for every branch, ANY continues on the first and lets the others keep running. Skipped branches never block it, and the join is skipped when no branch reaches it. A join that closes a For each also reports the iteration failures."}),ep("CONTROL_DELAY","Control flow","Time delay","WAIT",[],[],{description:"Pauses the run for a fixed number of seconds.",details:"Accepts up to a year. The run is parked rather than held open, so a long delay costs nothing while it waits. Use it to space out polling or to give an external system time to settle; use Wait until when you are waiting for a condition rather than a duration."}),ep("CONTROL_WAIT_UNTIL","Control flow","Wait until","WAIT",[],[],{description:"Parks the run until a condition over session data becomes true, re-checking on a cadence.",details:"Evaluates immediately and continues at once if the condition already holds. Session data only changes when a step writes it, so the condition must be able to become true through some other branch — otherwise the wait never resolves. Default cadence is 15 seconds; set a timeout to bound it."}),ep("CONTROL_FOR_EACH","Control flow","For each","CONTROL",[],["steps.<stepId>.items"],{description:"Runs its `body` branch once per item in a list, or takes the `empty` branch when there is nothing to iterate.",details:"Reads the list from a session path or from inline items, and caps at 1,000. Iterations run in parallel and each sees its own item. Fail-fast stops the whole run on the first failing iteration; collect-errors lets them all finish and reports failures at the closing join. Writes the items to `steps.<stepId>.items`."}),ep("CONTROL_TRY","Control flow","Try / catch","CONTROL",[],[],{description:"Marks the start of a protected region whose failures route out of the `catch` handle.",details:"Takes no config — the recovery path is drawn in the graph. Steps on the `success` branch run normally; when one of them fails, the run continues from `catch` instead of failing outright. Use a step's own failure handle for a single fallible step; reach for this when a whole sequence shares one recovery path."}),ep("CONTROL_SET_VARIABLE","Control flow","Set or compute variable","CONTROL",[],[],{description:"Writes a value into session data at a chosen path, either a constant or the result of a small script.",details:"The script runs in a sandboxed JavaScript interpreter with the session data available and no network or filesystem access; its return value is what gets written. Without a script the literal value is used. The path may be any dotted path — write under a namespace of your own to avoid colliding with what steps produce. Because the path comes from config, the catalog cannot advertise it: list it in this step's own `providedPaths` too, or a later step that binds it fails to publish with REQUIREMENT_UNSATISFIED."}),ep("CONTROL_SUBWORKFLOW","Control flow","Call sub-workflow","SERVER",[],[],{description:"Runs another published workflow as a child and waits for it to finish.",details:"Must pin a specific published version — the validator rejects an unpinned reference, so a sub-workflow cannot change under a caller. The input mapping seeds the child's session data. The child appears as a nested run; its failure fails this step."}),ep("SAVED_COMMAND","Extensibility","Run saved command","AGENT",[],["steps.<stepId>.*"],{description:"Starts a saved command on an eligible agent home or worktree target.",details:"Uses the saved command snapshot, target rules, output log, and restart policy. Wait for exit fails the workflow when the command ultimately fails or is cancelled; fire and forget succeeds after durable dispatch and remains independent if the workflow is later cancelled. Always-restart commands can only use fire and forget.",mutatesWorktree:!0}),ep("CUSTOM_COMMAND","Extensibility","Run custom command","AGENT",[],["steps.<stepId>.*"],{description:"Runs a one-off shell command on an agent home or worktree and records it in Commands run history.",details:"The script is retained only in the immutable command-run snapshot, not as a reusable saved command. Context targeting prefers the current worktree, then the current agent. Wait for exit fails the workflow when the command fails or is cancelled; fire and forget succeeds after durable dispatch.",mutatesWorktree:!0}),...eg,ep("TERMINAL_RUN","Extensibility","Run terminal script","AGENT",["worktree.path"],["steps.<stepId>.*"],{description:"Runs a shell or Node script on the agent inside the worktree, capturing its output.",details:"Needs `worktree.path` and an online agent. A non-zero exit fails the step. Named credentials can be injected as environment variables so secrets never sit in the definition — the validator rejects secret-looking literals in config. Arbitrary code on the agent's machine: it can change anything the agent user can reach. Writes stdout, stderr, and the exit code under `steps.<stepId>.*`; to publish anything else the script produces into a named path, declare it in this step's own `providedPaths`.",mutatesWorktree:!0}),ep("MCP_CALL","Extensibility","Call MCP tool","SERVER",[],["steps.<stepId>.output"],{description:"Calls a tool on a configured MCP server — built-in or external — with a JSON argument object.",details:"The general escape hatch to anything reachable over MCP. Needs the server (tool group) and the exact tool name; arguments must match that tool's own schema. What it does depends entirely on the tool, so treat it as externally mutating. The result lands in `steps.<stepId>.output`.",mutatesExternal:!0})],ew=new Map(ey.map(e=>[e.kind,e])),eb=["run.*","worktree.*","codebase.*","agent.*","repo.*","ticket.*"],ev=["build.*","worktree.*","codebase.*","agent.*","repo.*","ticket.*"],ek=["worktree.*","codebase.*","agent.*","repo.*","ticket.*","pr.*"],eS=["ticket.*","comment.*","changelog.*"],eE=["repo.*","pr.*","ticket.*","worktree.*","codebase.*","agent.*"],eI=[...eE,"comment.*"],ex="Filters narrow it further: each session path must equal the given value, or be one of a list of values.",eA="Set a threshold path, operator, and value to fire only on the crossing: it fires when the comparison first becomes true and stays quiet until it goes false again, so a metric hovering over the line does not fire repeatedly.",e_=(e,t,r,i,a)=>({kind:e,category:t,label:r,description:a.description,details:a.details,configSchema:es(e,"trigger"),capabilityFlags:["DURABLE","DEDUPLICATED"],seedPaths:i,sourceHandles:m(e)}),eC=(e,t,r,i)=>e_(e,t,r,i,{description:`${r} emits a normalized, filterable workflow event.`,details:`${r} uses the canonical domain event and deduplicates deliveries by subject and revision. ${ex}`}),eR=[eC("COMMAND_RUN_RESULT","Commands","Command run result",["command.*","agent.*","worktree.*"]),eC("COMMAND_OUTPUT_MATCH","Commands","Command output match",["command.*","output.*"]),eC("SKILL_SYNC_RESULT","Skills","Skill sync result",["skillSync.*","skill.*","repo.*"]),eC("SKILL_SYNC_CONFLICT","Skills","Skill sync conflict",["skillSync.*","skill.*","repo.*"]),eC("GITHUB_PIPELINE_STATUS_CHANGED","GitHub","Pipeline status changed",["pipeline.*","repo.*","pr.*","worktree.*","codebase.*","agent.*","ticket.*"]),eC("GITHUB_PR_SYNCHRONIZED","GitHub","Pull request synchronized",eE),eC("GITHUB_REVIEW_APPROVED","GitHub","Pull request review approved",eE),eC("JIRA_TICKET_UPDATED","Jira","Jira ticket updated",eS),eC("JIRA_COMMENT_ADDED","Jira","Jira comment added",eS),eC("JIRA_WORKLOG_ADDED","Jira","Jira worklog added",eS),eC("JIRA_SPRINT_ENDED","Jira","Jira sprint ended",eS),eC("CODEBASE_SYNC_STATE_CHANGED","Codebases","Codebase sync state changed",["codebase.*","agent.*","repo.*"]),eC("CODEBASE_OPERATION_FAILED","Codebases","Codebase operation failed",["codebase.*","agent.*","repo.*","operation.*"]),eC("WORKTREE_SYNC_STATE_CHANGED","Worktrees","Worktree sync state changed",ek),eC("WORKTREE_AUTOMATION_RESULT","Worktrees","Worktree automation result",[...ek,"automation.*"]),eC("WORKTREE_CLEAN","Worktrees","Worktree became clean",ek),eC("PUSH_NOTIFICATION_RESULT","Notifications","Push notification result",["pushBatch.*"]),eC("IOS_DEVICE_ENROLLED","Devices","iOS device enrolled",["device.*"]),eC("IOS_DEVICE_REGISTRATION_RESULT","Devices","iOS device registration result",["device.*"]),eC("SIGNING_OPERATION_RESULT","Signing","Signing operation result",["signing.*","signingProfile.*","agent.*"]),eC("SIGNING_ASSET_EXPIRING","Signing","Signing asset expiring",["signing.*","signingProfile.*","agent.*"]),eC("BUILD_DATA_THRESHOLD","Build Data","Build-data threshold",["buildData.*","agent.*","worktree.*"]),eC("BUILD_DATA_CLEANUP_RESULT","Build Data","Build-data cleanup result",["buildData.*","cleanup.*","agent.*"]),eC("POLLING_OPERATION_STATE","Operations","Polling operation state",["polling.*"]),eC("MODEL_COST_CATALOG_CHANGED","Operations","Model-cost catalog changed",["modelCosts.*"]),eC("CREDENTIAL_STORE_DEGRADED","Operations","Credential store degraded",["credentials.*"]),eC("AGENT_RESOURCE_THRESHOLD","Agents","Agent resource threshold",["agent.*"]),eC("AGENT_VERSION_CHANGED","Agents","Agent version changed",["agent.*"]),eC("TOOL_CALL_RESULT","Tools","Tool call result",["toolCall.*"])],eT=[e_("MANUAL","Manual","Manual run",[],{description:"Fires when someone presses Run on the workflow. The default entry point.",details:"Seeds nothing beyond `workflow.*`, so steps hanging off it can only bind to values that later steps produce. A caller may still pass session data explicitly when starting the run. A workflow that has only a choice trigger refuses a plain run."}),e_("MANUAL_CHOICE","Manual","Manual run with a choice",[],{description:"Fires when someone picks an option from the menu under the run button, and routes the run out of that option's own handle.",details:"Declare at least one option, each with a unique key — the key names the outgoing handle, so renaming a label leaves edges attached. One workflow can fan out into several entry paths without a step in front of them. Every edge must leave a handle that still exists, or publishing fails."}),e_("RESOURCE_MANUAL","Manual","Run from a resource",[],{description:"Fires when someone starts the workflow from a specific resource page — a worktree, pull request, build, codebase, ticket, or run.",details:"Must target exactly one resource kind; add a second trigger to accept another. The page seeds that resource's namespace into session data, so a worktree-launched run gets its worktree, codebase, owning agent, repository, and any linked ticket. Those seeds are an optimistic contract — an optional link that is absent resolves to nothing at run time. A worktree does not seed `pr.*`; use a pull-request trigger or Load pull request to bring one into session data. This is also what makes the workflow show up on that resource's page."}),e_("RESOURCE_MANUAL_CHOICE","Manual","Run from a resource with a choice",[],{description:"Fires from a resource page after the person picks an option, routing out of that option's handle.",details:"The resource and choice triggers combined: pick a resource kind and declare keyed options. Same rules as both — one resource kind per trigger, unique option keys, and every edge on a live handle."}),e_("SCHEDULE","Schedule","On a schedule",[],{description:"Fires repeatedly on a fixed cadence measured in seconds.",details:'A cadence, not a cron expression — there is no way to say "weekdays at 9am". The clock runs while the workflow is enabled, and pausing the workflow stops it. Seeds nothing, so scheduled workflows normally start by loading whatever they operate on. Mind the overlap policy: a cadence shorter than the run takes will queue or coalesce.'}),e_("WORKFLOW_FINISHED","Workflows","Another workflow finished",["workflow.*"],{description:"Fires when a different workflow run reaches a terminal state.",details:`Chains workflows without making one a sub-workflow of the other, so the two stay independently runnable. Filter on \`workflow.id\` to watch a specific one and on the finishing status to react only to failures. ${ex}`}),e_("GITHUB_PR_STATE","GitHub","Pull request opened or ready",eE,{description:"Fires when a pull request is opened, or when a draft is marked ready for review.",details:`Needs GitHub polling configured for the repository. Seeds \`pr.*\` and \`repo.*\`, so steps can act on the pull request straight away. ${ex} Filter on \`pr.isDraft\` or the base branch to avoid firing on every pull request in the repository.`}),e_("GITHUB_REVIEW_CHANGES_REQUESTED","GitHub","Changes requested",eE,{description:"Fires when a reviewer submits a review requesting changes.",details:`The entry point for an automated "address the review" loop: pair it with Collect review comments and an AI session. Approvals and plain comments do not fire it. ${ex}`}),e_("GITHUB_REVIEW_COMMENT","GitHub","Review comment created",eI,{description:"Fires when a new review comment is posted on a pull request.",details:`Fires per comment rather than per review, so a reviewer leaving five comments fires it five times — take care with steps that start AI runs. Use Changes requested when you want one event per review. ${ex}`}),e_("GITHUB_PR_CLOSED","GitHub","Pull request merged or closed",eE,{description:"Fires when a pull request is merged or closed without merging.",details:`Both outcomes fire it; branch on \`pr.state\` to tell them apart. The natural place to hang cleanup — deleting the worktree, moving the ticket on. ${ex}`}),e_("GITHUB_CHECK_FAILED","GitHub","Check suite or run failed",["repo.*","pipeline.*","worktree.*","codebase.*","agent.*","pr.*","ticket.*"],{description:"Fires when a check suite or check run reports a failure.",details:`Seeds \`pipeline.*\`, including the ids the retry and cancel steps need. Flaky suites fire this often, so gate an automatic retry on a count or a delay rather than retrying unconditionally. ${ex}`}),e_("GITHUB_PUSH_DEFAULT","GitHub","Push to default branch",["repo.*","push.*","ticket.*"],{description:"Fires when a commit lands on the repository's default branch.",details:`Seeds \`repo.*\` and \`push.*\`, plus a ticket key when the pushed branch contains one. There is no pull request or worktree in scope, so a workflow hanging off it usually starts by creating one. Fires on merges too, since a merge is a push. ${ex}`}),e_("GITHUB_WORKFLOW_SUCCEEDED","GitHub","Workflow run succeeded",["repo.*","pipeline.*","worktree.*","codebase.*","agent.*","pr.*","ticket.*"],{description:"Fires when a GitHub Actions workflow run completes successfully.",details:`The success counterpart to the failure triggers — useful for gating a deploy or a merge on a green pipeline. Filter on the workflow name so every unrelated Actions run does not start this workflow. ${ex}`}),e_("GITHUB_ISSUE_COMMAND","GitHub","Issue comment command",["repo.*","pr.*","ticket.*","comment.*"],{description:"Fires when a comment from an allow-listed GitHub user matches a command pattern, such as `/deploy`.",details:`The only trigger that lets outside text start a workflow, so it is deliberately strict: an explicit list of GitHub logins is required, and the pattern must be anchored with \`^\` and \`$\` — publishing fails otherwise. Both checks must pass. Keep the allow-list tight, since anyone on it can start whatever the workflow does. ${ex}`}),e_("GITHUB_ACTIONS_RESULT","GitHub Actions","Workflow result",["repo.*","pipeline.*","worktree.*","codebase.*","agent.*","pr.*","ticket.*"],{description:"Fires when a tracked GitHub Actions run finishes, whatever its conclusion.",details:`The richest of the Actions triggers: it correlates the run back to its worktree, owning agent, pull request, and ticket when those links exist. Branch on the conclusion rather than adding separate success and failure triggers. ${ex}`}),e_("GITHUB_PR_LABEL","GitHub","Pull request label set",eE,{description:"Fires when a label is applied to a pull request.",details:`Turns a label into a manual switch — label a pull request \`automerge\` and let a workflow take it from there. Filter on the label name, or every label change in the repository starts the workflow. ${ex}`}),e_("BUILD_RESULT","Builds","Build result",ev,{description:"Fires when a build finishes, succeeded or failed.",details:`Seeds \`build.*\` along with the worktree it ran in, so the read-results and coverage steps can follow directly. Branch on \`build.status\` to separate the outcomes. ${ex}`}),e_("BUILD_TEST_THRESHOLD","Builds","Test failure threshold",ev,{description:"Fires when a build's failing-test count crosses a threshold you set.",details:`Point the threshold path at \`build.testSummary.failed\` and pick an operator and value. ${eA} ${ex}`}),e_("BUILD_COVERAGE_THRESHOLD","Builds","Coverage threshold",ev,{description:"Fires when a build's code coverage crosses a threshold you set.",details:`Point the threshold path at the coverage summary — usually the changed-files percentage rather than the whole-project number — and compare with a less-than operator. ${eA} ${ex}`}),e_("BUILD_HOOK_FAILED","Builds","Build hook failed",ev,{description:"Fires when one of a build's pre- or post-build scripts fails.",details:`Distinguishes a broken build script from a genuine compile or test failure, which is what Build result reports. Seeds \`build.*\`. ${ex}`}),e_("AGENT_CONNECTION","Agents","Agent connection changed",["agent.*","codebase.agentId"],{description:"Fires when an agent comes online or goes offline.",details:`Seeds the agent id, name, connection state, and capacity metrics. A workflow hanging off it is usually about notifying a human rather than doing repository work — an offline agent cannot run agent steps anyway. Filter on the connection status to react to one direction only. ${ex}`}),e_("AGENT_JOB_FAILED","Agents","Agent job failed",["steps.trigger.*","agent.*","codebase.*","worktree.*","repo.*","ticket.*"],{description:"Fires when a job dispatched to an agent fails — a build, a Git operation, a terminal script.",details:`The failing job is seeded under \`steps.trigger.*\`, including its kind and error. When it targeted a worktree, the owning agent, codebase, repository, and ticket are included too. Catches infrastructure failures that a workflow's own failure handles never see, because the job belonged to a different run. ${ex}`}),e_("AGENT_DISK_REPORT","Agents","Agent disk report",["agent.*","codebase.agentId","disk.*"],{description:"Fires whenever the Derived Data monitor accepts a new agent disk report.",details:`Seeds the complete monitor snapshot under \`disk.*\`, while \`agent.diskFreeBytes\` remains the legacy root-disk inventory value. This can fire at the agent poll cadence; use filters when every report is not needed. ${ex}`}),e_("AGENT_DISK_THRESHOLD","Agents","Agent disk threshold",["agent.*","codebase.agentId","disk.*"],{description:"Fires when monitored Derived Data free space crosses a threshold you set.",details:`Use \`disk.freeGiB\`, \`disk.freeBytes\`, or \`disk.freePercent\` to evaluate the least-free monitored Derived Data volume. \`agent.diskFreeBytes\` remains available for older root-disk workflows. ${eA} ${ex}`}),e_("AGENT_DISK_STATE_CHANGED","Agents","Agent disk state changed",["agent.*","codebase.agentId","disk.*"],{description:"Fires when an agent's disk monitor changes status, pressure mode, health, or monitored volume.",details:`Filter on \`disk.status\`, \`disk.pressureMode\`, \`disk.enabled\`, or errors and warnings to react to a specific transition. Cleanup start appears as \`DELETING\`; recovery can be selected with \`IDLE\`. Repeated reports in the same state stay quiet. ${ex}`}),e_("AGENT_DISK_CLEANUP_RESULT","Agents","Automatic disk cleanup result",["agent.*","codebase.agentId","disk.*","cleanup.*"],{description:"Fires whenever a monitor-managed automatic Derived Data cleanup finishes.",details:`Seeds the terminal agent job under \`cleanup.*\`, including status, error, targets, and deleted entries. Every cleanup job is independent, so two successive successes both fire. Manual Build Data deletions remain outside this trigger. ${ex}`}),e_("CCUSAGE_THRESHOLD","Agents","Usage threshold",["run.usage.*","agent.*"],{description:"Fires when aggregate AI usage crosses a threshold you set.",details:`Watches usage across runs rather than one run's spend — Run usage threshold does that. The cost guardrail: notify, or pause workflows that start AI runs. ${eA} ${ex}`}),e_("WORKTREE_CREATED","Worktrees","Worktree created",ek,{description:"Fires after a new worktree is successfully created.",details:`Fires once after the created worktree is projected into the control plane. Seeds the worktree, repository, codebase, and owning agent, plus a linked pull request and Jira ticket when the branch resolves to them. ${ex}`}),e_("WORKTREE_BEHIND","Worktrees","Worktree behind base",ek,{description:"Fires when a worktree's branch falls behind the branch it was cut from.",details:`Pairs with a sync operation to keep long-lived branches current. Fires again as the base moves on, so a workflow that reacts should either sync or be filtered narrowly. ${ex}`}),e_("WORKTREE_CONFLICT","Worktrees","Worktree has conflicts",ek,{description:"Fires when a worktree is left with Git conflicts after a merge or rebase.",details:`Only fires when the worktree is genuinely marked conflicted. Conflicts need resolving before most other worktree steps will work, so this usually leads to a notification or an AI session pointed at the conflict. ${ex}`}),e_("WORKTREE_MISSING","Worktrees","Worktree missing",ek,{description:"Fires when a worktree the control plane knows about is no longer on disk.",details:`Only fires once the worktree is actually recorded as missing — usually someone deleted the directory by hand, or the agent's disk was cleaned. Steps that need the worktree will fail, so react by recreating it or clearing the record. ${ex}`}),e_("WORKTREE_DIVERGED","Worktrees","Worktree diverged",ek,{description:"Fires when a worktree's branch and its remote have both moved on independently.",details:`Only fires when the push status is genuinely diverged. Resolving it means a rebase, a merge, or a force push — all destructive enough that this usually routes to a human rather than to an automatic fix. ${ex}`}),e_("WORKTREE_DIRTY_DURATION","Worktrees","Worktree dirty too long",ek,{description:"Fires when a worktree has had uncommitted changes for longer than expected.",details:`Catches work that stalled — an AI session that edited files and was never followed up, or a human who wandered off. Usually a nudge rather than an automatic commit. ${ex}`}),e_("WORKTREE_NEW_COMMIT","Worktrees","New worktree commit",ek,{description:"Fires when a new commit lands in a worktree.",details:`Fires per commit, so a rebase or a batch of commits fires it repeatedly — keep the reaction cheap, or filter to one branch. Useful for kicking off a build or lint pass as work lands. ${ex}`}),e_("CODEBASE_REMOTE_BRANCH","Codebases","Matching remote branch",["codebase.*","agent.*","repo.*"],{description:"Fires when a remote branch matching the codebase's conventions appears.",details:`Lets a branch pushed from elsewhere pull work into this system — creating a worktree for it, or opening a pull request. Needs a fetch to have run for the branch to be visible. ${ex}`}),e_("JIRA_STATUS","Jira","Ticket status changed",eS,{description:"Fires when a Jira ticket moves to another status.",details:`Needs Jira polling configured. Seeds \`ticket.*\`. Filter on \`ticket.status\` to react to one column only — without a filter, every transition on every polled ticket starts the workflow. ${ex}`}),e_("JIRA_LABEL","Jira","Jira label set",eS,{description:"Fires when a label is applied to a Jira ticket.",details:`The Jira counterpart to the pull request label trigger: a label becomes a manual switch for automation. Filter on the label name. ${ex}`}),e_("JIRA_ASSIGNED_SELF","Jira","Ticket assigned to me",eS,{description:"Fires when a ticket is assigned to the account behind the configured Jira credential.",details:`"Me" is whoever the Jira credential authenticates as, not whoever is looking at the screen. The usual start of a "pick up my next ticket" workflow — create a worktree, start a plan. ${ex}`}),e_("JIRA_SOURCE_NEW_TICKET","Jira","New ticket in source",eS,{description:"Fires when a ticket appears in a configured Jira source — a saved JQL query or board.",details:`Fires on tickets newly matching the source, which includes existing tickets edited into range, not only freshly created ones. The source itself does the filtering, so keep its JQL tight. Seeds \`ticket.*\`. ${ex}`}),e_("JIRA_MENTION","Jira","Jira comment mention",eS,{description:"Fires when the configured Jira account is mentioned in a ticket comment.",details:`Lets someone pull automation into a conversation by mentioning the bot. The comment is seeded under \`comment.*\`, so an AI step can read what was actually asked — treat that text as untrusted input rather than instructions. ${ex}`}),e_("JIRA_SPRINT_STARTED","Jira","Sprint started",eS,{description:"Fires when a Jira sprint is started.",details:`Fires per ticket in the sprint, so a sprint of thirty tickets starts thirty runs — mind the workflow's concurrency settings. Good for sprint-opening bookkeeping. ${ex}`}),e_("JIRA_ISSUE_CREATED","Jira","Ticket created",eS,{description:"Fires when a Jira ticket is created.",details:`Needs the Jira webhook configured in Settings — the polled Jira triggers only observe tickets something already fetched, so they cannot see a brand-new one. Scope the webhook's JQL filter to the projects you care about, since every created ticket otherwise starts a run. ${ex}`}),e_("JIRA_ISSUE_DELETED","Jira","Ticket deleted",eS,{description:"Fires when a Jira ticket is deleted.",details:`Needs the Jira webhook. The ticket is gone by the time this runs, so only the payload's \`ticket.*\` snapshot is available — a step that loads the ticket will fail. Use it for cleanup: close the worktree, cancel the run, archive the branch. ${ex}`}),e_("JIRA_ISSUE_COMMAND","Jira","Ticket comment command",eS,{description:"Fires when a comment from an allow-listed Jira account matches a command pattern, such as `/deploy`.",details:`The Jira counterpart to the GitHub issue comment command, and just as strict: an explicit list of Jira account IDs is required, and the pattern must be anchored with \`^\` and \`$\` — publishing fails otherwise. Jira identifies people by opaque account ID, not display name, so copy the ID from the user's Jira profile URL. Treat the comment body as untrusted input rather than instructions. Needs the Jira webhook. ${ex}`}),e_("JIRA_ATTACHMENT_ADDED","Jira","Attachment added",[...eS,"attachment.*"],{description:"Fires when a file is attached to a Jira ticket.",details:`Needs the Jira webhook. Seeds \`attachment.*\` with the filename, MIME type, and author. Filter on \`attachment.mimeType\` to react to one kind of upload — a crash log, a design export. ${ex}`}),e_("JIRA_ISSUE_LINKED","Jira","Ticket linked",[...eS,"link.*"],{description:"Fires when a Jira issue link is created.",details:`Needs the Jira webhook. Seeds \`link.*\` with the link type and both issue IDs. Filter on \`link.type\` to react to one relationship — "blocks", "duplicates" — rather than every link. ${ex}`}),e_("RUN_STARTED","Plans and sessions","Run started",eb,{description:"Fires when an AI plan or session run begins.",details:`Every run trigger seeds the same shape — \`run.*\` plus the worktree, codebase, repository, and ticket it is attached to. Filter on \`run.kind\` to separate plans from sessions. ${ex}`}),e_("RUN_COMPLETED","Plans and sessions","Run completed",eb,{description:"Fires when an AI run finishes successfully.",details:`The place to hang everything that happens after the agent is done — committing, pushing, opening a pull request, moving the ticket. Filter on \`run.kind\` to react only to plans or only to sessions. ${ex}`}),e_("RUN_QUESTION_NEEDED","Plans and sessions","Run needs an answer",eb,{description:"Fires when an AI run pauses to ask a question, with the pending questions in session data.",details:`The questions arrive under \`run.questions\`, so the Answer run question step can respond without a human — the basis for unattended runs. Answer carefully: an automatic answer to a question the agent should have asked a person is how unwanted changes get made. ${ex}`}),e_("RUN_QUESTION_ANSWERED","Plans and sessions","Run question answered",eb,{description:"Fires when a pending question on an AI run is answered.",details:`Fires however the answer arrived — from a person or from another workflow. Use it to record decisions, or to resume work that was gated on the answer. ${ex}`}),e_("RUN_PAUSED","Plans and sessions","Run paused",eb,{description:"Fires when an AI run is paused.",details:`Covers pauses from any source, including a run that paused itself. A run needing an answer reports separately through Run needs an answer. ${ex}`}),e_("RUN_CONTINUED","Plans and sessions","Run continued",eb,{description:"Fires when a paused AI run resumes.",details:`The counterpart to Run paused. Fires on each resume, so a run that stops and starts repeatedly fires it repeatedly. ${ex}`}),e_("RUN_FAILED","Plans and sessions","Run failed",eb,{description:"Fires when an AI run ends in failure.",details:`The error is in the seeded run data, so a follow-up run can be pointed at what went wrong. Beware of loops — a workflow that reacts by starting another run that fails the same way will keep going. ${ex}`}),e_("RUN_CANCELLED","Plans and sessions","Run cancelled",eb,{description:"Fires when an AI run is cancelled.",details:`Cancellation leaves whatever the run already wrote in the worktree, so cleanup usually means inspecting or reverting rather than assuming nothing happened. ${ex}`}),e_("RUN_PLAN_PLAYED","Plans and sessions","Plan played",eb,{description:"Fires when a run is created by executing a previously completed plan.",details:`Distinguishes plan execution from an ordinary session, which Run started cannot. Lets a workflow treat planned work differently from ad-hoc work. ${ex}`}),e_("RUN_FOLLOW_UP","Plans and sessions","Run follow-up created",eb,{description:"Fires when a run is created as a follow-up to another run.",details:`Does not fire for plan execution, which reports through Plan played. The parent run is in the seeded data, so a workflow can count how deep a follow-up chain has gone and stop it. ${ex}`}),e_("RUN_IMPORTED","Plans and sessions","Provider run imported",eb,{description:"Fires when a run started outside this system is imported from a provider.",details:`Lets work begun in another tool pick up the same automation — labelling, ticket updates, pull requests. The run did not originate here, so its worktree and ticket links may be incomplete. ${ex}`}),e_("RUN_USAGE_THRESHOLD","Plans and sessions","Run usage threshold",eb,{description:"Fires when a single run's token or cost usage crosses a threshold you set.",details:`Scoped to one run, unlike the aggregate Usage threshold. Point the threshold path at the usage figure you care about — a runaway session can then be cancelled automatically. ${eA} ${ex}`}),e_("RUN_EVENT_MATCH","Plans and sessions","Run event or tool matched",eb,{description:"Fires on individual events inside an AI run, including each tool call it makes.",details:`The finest-grained run trigger, and by far the most talkative — a single run produces hundreds of events, and every one is a candidate. Always filter, on the event type or the tool name. Useful for reacting to a specific tool being used; a poor choice for anything expensive. ${ex}`}),...eR],eD=new Map(eT.map(e=>[e.kind,e])),eN=t.z.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/),eO=t.z.string().min(1).max(256).regex(/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_*\[\]-]+)*$/),eP=t.z.record(t.z.string(),t.z.unknown()).default({}),e$=t.z.object({id:eN,kind:t.z.enum(s),name:t.z.string().min(1).max(200).optional(),position:t.z.object({x:t.z.number().finite(),y:t.z.number().finite()}),config:eP}),eU=t.z.object({id:eN,kind:t.z.enum(n),name:t.z.string().min(1).max(200).optional(),position:t.z.object({x:t.z.number().finite(),y:t.z.number().finite()}),config:eP,requiredPaths:t.z.array(eO).max(100).default([]),providedPaths:t.z.array(eO).max(100).default([]),retry:t.z.object({maxAttempts:t.z.number().int().min(1).max(20).default(1),strategy:t.z.enum(["FIXED","EXPONENTIAL"]).default("EXPONENTIAL"),delaySeconds:t.z.number().int().min(1).max(86400).default(5)}).default({maxAttempts:1,strategy:"EXPONENTIAL",delaySeconds:5}),failurePolicy:t.z.enum(["FAIL","CONTINUE"]).default("FAIL")}),eB=t.z.object({id:eN,source:eN,target:eN,sourceHandle:t.z.string().min(1).max(100).default("success"),targetHandle:t.z.string().min(1).max(100).default("input")}),ej=t.z.object({format:t.z.literal(eo),schemaVersion:t.z.literal(1),name:t.z.string().min(1).max(200),description:t.z.string().max(2e3).default(""),triggers:t.z.array(e$).max(100).default([]),nodes:t.z.array(eU).max(1e3).default([]),edges:t.z.array(eB).max(5e3).default([]),editor:t.z.object({viewport:t.z.object({x:t.z.number(),y:t.z.number(),zoom:t.z.number().positive()}).optional(),handleLayout:t.z.enum(["SIDES","TOP_BOTTOM"]).default("SIDES"),displayLayout:t.z.enum(["REGULAR","BASIC"]).default("REGULAR")}).default({handleLayout:"SIDES",displayLayout:"REGULAR"})});function eL(e,t){return t.map(t=>t.replaceAll("<stepId>",e.id))}function eq(e,t){return e===t||"*"===e||e.endsWith(".*")&&t.startsWith(e.slice(0,-1))}function eM(e){return e.length?new Set([...e[0]].filter(t=>e.every(e=>e.has(t)))):new Set}function eF(e,t){return[...e].some(e=>eq(e,t))}let eK={stepPaths(e){let t=ew.get(e);return{requiredPaths:t?.requiredPaths??[],providedPaths:t?.providedPaths??[]}},triggerSeedPaths:e=>eD.get(e)?.seedPaths??[]};function eV(e,t=eK){let r=new Set(e.nodes.map(({id:e})=>e)),i=new Map(e.nodes.map(e=>[e.id,e])),a=new Map,n=new Map;for(let t of e.edges)a.set(t.source,[...a.get(t.source)??[],t.target]),n.set(t.target,[...n.get(t.target)??[],t.source]);let s=new Map(e.nodes.map(e=>[e.id,0]));for(let t of e.edges)r.has(t.source)&&r.has(t.target)&&s.set(t.target,(s.get(t.target)??0)+1);let o=[...s].filter(([,e])=>0===e).map(([e])=>e),l=[];for(;o.length;){let e=o.shift();for(let t of(l.push(e),a.get(e)??[])){if(!r.has(t))continue;let e=(s.get(t)??0)-1;s.set(t,e),0===e&&o.push(t)}}let u=e=>{let t=new Set,r=[...a.get(e)??[]];for(;r.length;){let e=r.shift();t.has(e)||(t.add(e),r.push(...a.get(e)??[]))}return t},c=new Map;for(let t of[...e.triggers,...e.nodes])c.set(t.id,u(t.id));let d=new Map;for(let r of e.nodes){let e=t.stepPaths(r.kind);d.set(r.id,[...eL(r,e.providedPaths),...r.providedPaths,`steps.${r.id}.*`])}let p=new Map,h=[];for(let r of e.triggers){let e=new Set(["workflow.*"]);for(let i of t.triggerSeedPaths(r.kind))e.add(i);for(let t of ed(r.kind,r.config))e.add(t);let a=new Map;for(let s of l){if(!c.get(r.id)?.has(s))continue;let o=i.get(s),l=(n.get(s)??[]).filter(e=>e===r.id||a.has(e));if(!l.length)continue;let u=eM(l.map(t=>t===r.id?e:a.get(t))),m=p.get(s);p.set(s,m?eM([m,u]):new Set(u));let f=new Set(d.get(s)??[]),g=[...ee(o.kind,"step",o.config)].filter(e=>!eF(f,e));for(let e of new Set([...eL(o,t.stepPaths(o.kind).requiredPaths),...o.requiredPaths,...g]))eF(u,e)||h.push({nodeId:o.id,triggerId:r.id,triggerName:r.name??r.kind,path:e});let y=new Set(u);for(let e of d.get(s)??[])y.add(e);a.set(s,y)}}return{availableBefore:new Map([...p].map(([e,t])=>[e,[...t]])),provides:d,requirementViolations:h}}function eG(e,t=""){return Array.isArray(e)?e.some(e=>eG(e,t)):e&&"object"==typeof e?Object.entries(e).some(([e,t])=>eG(t,e)):"string"==typeof e&&/(token|secret|password|passwd|private.?key|api.?key|authorization)/i.test(t)&&!/(credential.?id|credential.?ids)$/i.test(t)}function eH(e){return Array.isArray(e)?e.some(eH):!!e&&"object"==typeof e&&("UNRESOLVED"===e.referenceStatus||Object.values(e).some(eH))}e.s(["WORKFLOW_SCHEMA_VERSION",0,1,"WORKFLOW_STEP_BY_KIND",0,ew,"WORKFLOW_STEP_CATALOG",0,ey,"WORKFLOW_TRIGGER_CATALOG",0,eT,"computeWorkflowPathAvailability",0,eV,"emptyWorkflowDefinition",0,function(e="Untitled workflow"){return ej.parse({format:eo,schemaVersion:1,name:e,description:"",triggers:[{id:"manual",kind:"MANUAL",position:{x:0,y:100},config:{}}],nodes:[],edges:[],editor:{}})},"hasWorkflowErrors",0,function(e){return e.some(({severity:e})=>"ERROR"===e)},"parseWorkflowDefinition",0,function(e){return ej.parse(e)},"resourceManualSeedPaths",0,ed,"sanitizeWorkflowExportDefinition",0,function(e){let t=(e,r="")=>Array.isArray(e)?e.map(e=>t(e,r)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,r])=>[e,t(r,e)])):"string"==typeof e&&/(token|secret|password|passwd|private.?key|api.?key|authorization)/i.test(r)&&!/(credential.?id|credential.?ids)$/i.test(r)||"string"==typeof e&&/^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(e)&&/^(?:cwd|folder|path|directory)$/i.test(r)?null:e;return ej.parse(t(e))},"validateWorkflowDefinition",0,function(e){let t=ej.safeParse(e);if(!t.success)return{definition:null,diagnostics:t.error.issues.map(e=>({severity:"ERROR",code:"SCHEMA_INVALID",message:e.message,path:e.path.join(".")}))};let r=t.data,i=[],a=new Set;for(let e of[...r.triggers,...r.nodes])a.has(e.id)&&i.push({severity:"ERROR",code:"DUPLICATE_NODE_ID",message:`Duplicate graph id ${e.id}`,nodeId:e.id}),a.add(e.id);let n=new Set;for(let e of r.edges)n.has(e.id)&&i.push({severity:"ERROR",code:"DUPLICATE_EDGE_ID",message:`Duplicate edge id ${e.id}`}),n.add(e.id),a.has(e.source)&&a.has(e.target)||i.push({severity:"ERROR",code:"EDGE_ENDPOINT_MISSING",message:`Edge ${e.id} references a missing endpoint`}),r.triggers.some(({id:t})=>t===e.target)&&i.push({severity:"ERROR",code:"TRIGGER_HAS_INPUT",message:"Triggers cannot have incoming edges",triggerId:e.target});r.triggers.length||i.push({severity:"ERROR",code:"TRIGGER_REQUIRED",message:"At least one trigger is required"}),r.nodes.length||i.push({severity:"ERROR",code:"STEP_REQUIRED",message:"At least one step is required"});let s=new Set(r.nodes.map(({id:e})=>e)),o=new Map,l=new Map;for(let e of r.edges)o.set(e.source,[...o.get(e.source)??[],e.target]),l.set(e.target,[...l.get(e.target)??[],e.source]);for(let e of r.nodes)(l.get(e.id)??[]).filter(e=>s.has(e)).length>1&&"CONTROL_JOIN"!==e.kind&&i.push({severity:"ERROR",code:"EXPLICIT_JOIN_REQUIRED",message:"Nodes with multiple incoming branches must be explicit join nodes",nodeId:e.id});let u=new Map(r.nodes.map(e=>[e.id,0]));for(let e of r.edges)s.has(e.source)&&s.has(e.target)&&u.set(e.target,(u.get(e.target)??0)+1);let p=[...u].filter(([,e])=>0===e).map(([e])=>e),h=[];for(;p.length;){let e=p.shift();for(let t of(h.push(e),o.get(e)??[])){if(!s.has(t))continue;let e=(u.get(t)??0)-1;u.set(t,e),0===e&&p.push(t)}}h.length!==r.nodes.length&&i.push({severity:"ERROR",code:"DAG_CYCLE",message:"Workflow graphs cannot contain free-form cycles"});let m=new Map,f=e=>{let t=new Set,r=[...o.get(e)??[]];for(;r.length;){let e=r.shift();t.has(e)||(t.add(e),r.push(...o.get(e)??[]))}return t};for(let e of[...r.triggers,...r.nodes])m.set(e.id,f(e.id));for(let e of r.nodes){for(let t of(r.triggers.some(t=>m.get(t.id)?.has(e.id))||i.push({severity:"ERROR",code:"UNREACHABLE_STEP",message:"Step is not reachable from a trigger",nodeId:e.id}),eG(e.config)&&i.push({severity:"ERROR",code:"SECRET_LITERAL",message:"Store secrets as credential references, not workflow literals",nodeId:e.id}),eH(e.config)&&i.push({severity:"ERROR",code:"UNRESOLVED_REFERENCE",message:"Resolve imported references before publishing",nodeId:e.id}),new Set(E(e.config))))i.push({severity:"ERROR",code:"SESSION_BINDING_INVALID",message:t,nodeId:e.id});"CONTROL_SUBWORKFLOW"===e.kind&&"string"!=typeof e.config.versionId&&i.push({severity:"ERROR",code:"SUBWORKFLOW_VERSION_REQUIRED",message:"Sub-workflows must pin a published version",nodeId:e.id})}for(let e of r.triggers){for(let t of((o.get(e.id)??[]).length||i.push({severity:"ERROR",code:"TRIGGER_DISCONNECTED",message:"Trigger is not connected to a step",triggerId:e.id}),eG(e.config)&&i.push({severity:"ERROR",code:"SECRET_LITERAL",message:"Store secrets as credential references, not trigger literals",triggerId:e.id}),eH(e.config)&&i.push({severity:"ERROR",code:"UNRESOLVED_REFERENCE",message:"Resolve imported references before publishing",triggerId:e.id}),new Set(E(e.config))))i.push({severity:"ERROR",code:"SESSION_BINDING_INVALID",message:t,triggerId:e.id});if(d(e.kind)&&!ec(e.config)&&i.push({severity:"ERROR",code:"RESOURCE_KIND_REQUIRED",message:"Resource triggers must target a single resource kind; add one trigger per kind",triggerId:e.id}),c(e.kind)){let t=el(e.config),a=Array.isArray(e.config.choices)?e.config.choices.length:0;t.length&&t.length===a||i.push({severity:"ERROR",code:"TRIGGER_CHOICES_REQUIRED",message:"Choice triggers need at least one option, each with a unique key",triggerId:e.id});let n=new Set(t.map(({key:e})=>e));for(let t of r.edges)t.source===e.id&&(n.has(t.sourceHandle)||i.push({severity:"ERROR",code:"TRIGGER_CHOICE_HANDLE_UNKNOWN",message:`Connection ${t.id} leaves an option that no longer exists`,triggerId:e.id}))}if("GITHUB_ISSUE_COMMAND"===e.kind||"JIRA_ISSUE_COMMAND"===e.kind){let t="JIRA_ISSUE_COMMAND"===e.kind,r=t?e.config.allowedAccountIds:e.config.allowedLogins,a=e.config.commandPattern;(!Array.isArray(r)||!r.length||r.some(e=>"string"!=typeof e||!e.trim()))&&i.push({severity:"ERROR",code:"ISSUE_COMMAND_ALLOWLIST_REQUIRED",message:t?"Issue command triggers require an explicit Jira account ID allow-list":"Issue command triggers require an explicit GitHub login allow-list",triggerId:e.id}),"string"==typeof a&&a.startsWith("^")&&a.endsWith("$")||i.push({severity:"ERROR",code:"ISSUE_COMMAND_PATTERN_ANCHORED",message:"Issue command patterns must be anchored with ^ and $",triggerId:e.id})}}for(let e of eV(r).requirementViolations)i.push({severity:"ERROR",code:"REQUIREMENT_UNSATISFIED",message:`${e.path} is not guaranteed on the path from ${e.triggerName}`,nodeId:e.nodeId,triggerId:e.triggerId,path:e.path});for(let e=0;e<r.nodes.length;e+=1){let t=r.nodes[e],a=[...eL(t,ew.get(t.kind).providedPaths),...t.providedPaths].filter(e=>!e.startsWith(`steps.${t.id}.`));for(let n=e+1;n<r.nodes.length;n+=1){let e=r.nodes[n];if(m.get(t.id)?.has(e.id)||m.get(e.id)?.has(t.id))continue;let s=[...eL(e,ew.get(e.kind).providedPaths),...e.providedPaths].filter(t=>!t.startsWith(`steps.${e.id}.`));a.some(e=>s.some(t=>eq(e,t)||eq(t,e)))&&i.push({severity:"ERROR",code:"PARALLEL_WRITE_CONFLICT",message:`Parallel steps ${t.name??t.id} and ${e.name??e.id} can write the same session-data path`,nodeId:e.id})}}return{definition:r,diagnostics:i}},"workflowResourceKind",0,ec,"workflowTriggerChoices",0,el],497800)},107058,963910,112627,695248,e=>{"use strict";var t=e.i(666680),r=e.i(243783);e.i(582482);var i=e.i(318905),a=e.i(91022),n=e.i(397554),s=e.i(827957);function o(e){if(null===e||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function l(e){let t=o(e.get("x-ratelimit-limit")),r=o(e.get("x-ratelimit-remaining")),i=o(e.get("x-ratelimit-used")),a=o(e.get("x-ratelimit-reset")),n=e.get("x-ratelimit-resource")?.trim()??"";if(null===t||null===r||null===i||null===a||!n)return null;let s=new Date(1e3*a);return Number.isFinite(s.getTime())?{limit:t,remaining:r,used:i,resetAt:s,resource:n}:null}async function u(e,t){let i=l(t.headers);if(!i)return null;try{let t=await (0,r.getPrismaClient)(),a=`${e}:${i.resource}`,n=new Date;await t.gitHubRateLimitSnapshot.upsert({where:{authentication_resource:{authentication:e,resource:i.resource}},create:{id:a,authentication:e,observedAt:n,...i},update:{observedAt:n,...i}})}catch{}return i}async function c(){let e=await (0,r.getPrismaClient)();return(await e.gitHubRateLimitSnapshot.findMany({orderBy:[{resource:"asc"},{authentication:"asc"}]})).map(e=>({authentication:e.authentication,resource:e.resource,limit:e.limit,remaining:e.remaining,used:e.used,resetAt:e.resetAt.toISOString(),observedAt:e.observedAt.toISOString()}))}let d="actions.cancelWorkflowRun",p="actions.dispatchWorkflow",h="actions.forceCancelWorkflowRun",m="actions.getJobForWorkflowRun",f="actions.getWorkflowRun",g="actions.getWorkflowRunAttempt",y="actions.listJobsForWorkflowRun",w="actions.listJobsForWorkflowRunAttempt",b="actions.listRepoWorkflows",v="actions.listWorkflowRuns",k="actions.listWorkflowRunsForRepo",S="actions.reRunJobForWorkflowRun",E="actions.reRunWorkflow",I="actions.reRunWorkflowFailedJobs",x="apps.createInstallationAccessToken",A="apps.getAuthenticated",_="apps.getInstallation",C="apps.updateWebhookConfigForApp",R="repos.listPullRequestsAssociatedWithCommit",T="users.listEmailsForAuthenticatedUser";class D extends Error{code;githubRequestId;statusCode;rateLimit;constructor(e,t,r=null,i=null,a=null){super(t),this.code=e,this.githubRequestId=r,this.statusCode=i,this.rateLimit=a,this.name="GitHubAppError"}}let N=new Map,O=new Map;function P(e,t,r){let i=e.trim();if(!/^[1-9]\d*$/.test(i))throw new D(r,`${t} must be a positive integer`);return i}function $(e){let{privateKeyPkcs8:r,keyFingerprint:i}=function(e){try{let r=(0,t.createPrivateKey)({key:e.trim(),format:"pem"});if("rsa"!==r.asymmetricKeyType)throw Error("The key is not RSA");let i=r.export({format:"pem",type:"pkcs8"}).toString(),a=(0,t.createPublicKey)(r).export({format:"der",type:"spki"}),n=`SHA256:${(0,t.createHash)("sha256").update(a).digest("base64url")}`;return{key:r,privateKeyPkcs8:i,keyFingerprint:n}}catch{throw new D("INVALID_PRIVATE_KEY","The GitHub App private key is not a valid RSA PEM")}}(e.privateKey);return{...e,appId:P(e.appId,"GitHub App ID","INVALID_APP_ID"),installationId:P(e.installationId,"GitHub installation ID","INVALID_INSTALLATION_ID"),privateKeyPkcs8:r,keyFingerprint:i}}async function U(e){try{let t=await (0,n.importPKCS8)(e.privateKeyPkcs8,"RS256"),r=Math.floor(Date.now()/1e3);return await new s.SignJWT({}).setProtectedHeader({alg:"RS256",typ:"JWT"}).setIssuer(e.appId).setIssuedAt(r-60).setExpirationTime(r+540).sign(t)}catch{throw new D("INVALID_PRIVATE_KEY","The GitHub App private key could not sign an App JWT")}}function B(e){return`${e.appId}:${e.installationId}:${e.keyFingerprint}`}function j(e){return{accept:"application/vnd.github+json",authorization:e,"user-agent":"ai-development-environment","x-github-api-version":"2022-11-28"}}async function L(e,t,r,i,a){let n,s=Date.now(),o=(t.method??"GET").toUpperCase(),u=e===i?.graphqlUrl&&"string"==typeof t.body?t.body:null;try{n=await fetch(e,{...t,cache:"no-store"})}catch{throw i?.requestObserver&&await Promise.resolve(i.requestObserver({url:e,method:o,operation:r,requestSource:a,body:u,durationMs:Date.now()-s,statusCode:null,error:"GitHub could not be reached",rateLimit:null})).catch(()=>void 0),new D("GITHUB_APP_REQUEST_FAILED","GitHub could not be reached")}return i?.responseObserver&&await Promise.resolve(i.responseObserver(n)).catch(()=>void 0),i?.requestObserver&&await Promise.resolve(i.requestObserver({url:e,method:o,operation:r,requestSource:a,body:u,durationMs:Date.now()-s,statusCode:n.status,error:n.ok?null:`GitHub returned HTTP ${n.status}`,rateLimit:l(n.headers)})).catch(()=>void 0),n}async function q(e){try{return await e.json()}catch{return null}}function M(e){return e.headers.get("x-github-request-id")}function F(e,t,r=[]){let i=`GitHub returned HTTP ${t}`;for(let t of(e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message&&(i=e.message),r))t&&(i=i.split(t).join("[REDACTED]"));return i}async function K(e,t){let r=await L(`${e.apiBaseUrl}/app/installations/${e.installationId}`,{headers:j(`Bearer ${t}`)},_,e,"GITHUB_SETTINGS"),i=await q(r),a=M(r);if(401===r.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",a);if(404===r.status)throw new D("INSTALLATION_NOT_FOUND","The GitHub App installation was not found",a);if(!r.ok||!i||"object"!=typeof i)throw new D("GITHUB_APP_REQUEST_FAILED",F(i,r.status,[t,e.privateKey,e.privateKeyPkcs8]),a);if(String(i.app_id)!==e.appId)throw new D("APP_INSTALLATION_MISMATCH","The installation does not belong to the configured GitHub App",a);return i}async function V(e,t){let r=await L(`${e.apiBaseUrl}/app`,{headers:j(`Bearer ${t}`)},A,e,"GITHUB_SETTINGS"),i=await q(r),a=M(r);if(401===r.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",a);if(!r.ok||!i||"object"!=typeof i)throw new D("GITHUB_APP_REQUEST_FAILED",F(i,r.status,[t,e.privateKey,e.privateKeyPkcs8]),a);if(String(i.id)!==e.appId||!i.slug||!i.owner?.login||!i.owner.type)throw new D("GITHUB_APP_REQUEST_FAILED","GitHub returned incomplete GitHub App registration details",a);return{details:i,githubRequestId:a}}async function G(e){let t=$(e),r=await U(t),i=await V(t,r);return{appSlug:i.details.slug,appOwnerLogin:i.details.owner.login,appOwnerType:i.details.owner.type,githubRequestId:i.githubRequestId}}async function H(e,t,r){let i=r??await U(e),a=await L(`${e.apiBaseUrl}/app/installations/${e.installationId}/access_tokens`,{method:"POST",headers:j(`Bearer ${i}`)},x,e,t),n=await q(a),s=M(a);if(401===a.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",s);if(404===a.status)throw new D("INSTALLATION_NOT_FOUND","The GitHub App installation was not found",s);if(!a.ok||!n||"object"!=typeof n)throw new D("GITHUB_APP_REQUEST_FAILED",F(n,a.status,[i,e.privateKey,e.privateKeyPkcs8]),s);if("string"!=typeof n.token||!n.token||"string"!=typeof n.expires_at||Number.isNaN(Date.parse(n.expires_at)))throw new D("GITHUB_APP_REQUEST_FAILED","GitHub returned an invalid installation token response",s);if("write"!==(n.permissions?.actions??"none"))throw new D("ACTIONS_PERMISSION_REQUIRED","The GitHub App installation must grant Actions: read and write",s);return{token:n.token,expiresAt:new Date(n.expires_at),permissions:n.permissions??{},repositorySelection:n.repository_selection??"selected"}}async function W(e,t){let r=B(e),i=N.get(r);if(i&&i.expiresAt.getTime()-3e5>Date.now())return i;let a=O.get(r);if(a)return a;let n=H(e,t).then(e=>(N.set(r,e),e)).finally(()=>O.delete(r));return O.set(r,n),n}function J(){N.clear(),O.clear()}async function z(e,t,r){let i=$(e),a=await W(i,r),n=await t(a.token);return 401===n.status&&(N.delete(B(i)),a=await W(i,r),n=await t(a.token)),{response:n,token:a.token}}async function Z(e,t,r,i){let{response:a,token:n}=await z(e,a=>L(e.graphqlUrl,{method:"POST",headers:{...j(`Bearer ${a}`),"content-type":"application/json"},body:JSON.stringify({query:t,variables:r})},null,e,i),i),s=await q(a),o=M(a),u=l(a.headers);if(401===a.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",o,a.status,u);if(!a.ok||s?.errors?.length||!s?.data){let t=s?.errors?.map(e=>e.message).filter(Boolean).join("; ")||F(s,a.status,[n]);throw new D("GITHUB_APP_REQUEST_FAILED",F({message:t},a.status,[n,e.privateKey]),o,a.status,u)}return{data:s.data,githubRequestId:o,statusCode:a.status,rateLimit:u}}async function Y(e){let t=$(e),r=await U(t),[i,a]=await Promise.all([K(t,r),V(t,r)]),n=await H(t,"GITHUB_SETTINGS",r);N.set(B(t),n);let s=await Z(t,"query VerifyGitHubApp { viewer { login } }",{},"GITHUB_SETTINGS");return{appId:t.appId,installationId:t.installationId,keyFingerprint:t.keyFingerprint,appSlug:a.details.slug,appOwnerLogin:a.details.owner.login,appOwnerType:a.details.owner.type,accountLogin:i.account.login,repositorySelection:n.repositorySelection,actionsPermission:n.permissions.actions??"none",checksPermission:n.permissions.checks??"none",commitStatusesPermission:n.permissions.statuses??"none",webhookEvents:Array.isArray(i.events)?i.events:[],viewerLogin:s.data.viewer.login,verifiedAt:new Date,githubRequestId:s.githubRequestId}}async function Q(e,t){let r=$(e),i=await U(r),a=await L(`${r.apiBaseUrl}/app/hook/config`,{method:"PATCH",headers:{...j(`Bearer ${i}`),"content-type":"application/json"},body:JSON.stringify({url:t.url,content_type:"json",secret:t.secret,insecure_ssl:"0"})},C,r,"GITHUB_SETTINGS"),n=M(a);if(404===a.status)return{configured:!1,githubRequestId:n};if(!a.ok)throw new D("GITHUB_APP_REQUEST_FAILED",F(await q(a),a.status,[i,t.secret,r.privateKey]),n);return{configured:!0,githubRequestId:n}}async function X(e,t){let r=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/rerun`,{response:i,token:a}=await z(e,i=>L(r,{method:"POST",headers:j(`Bearer ${i}`)},E,e,t.requestSource),t.requestSource),n=M(i);if(401===i.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",n);if(!i.ok){let t=await q(i);throw new D(404===i.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===i.status?"The repository or workflow run is not available to this installation":F(t,i.status,[a,e.privateKey]),n)}return{githubRequestId:n}}async function ee(e,t){let r=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/rerun-failed-jobs`,{response:i,token:a}=await z(e,i=>L(r,{method:"POST",headers:j(`Bearer ${i}`)},I,e,t.requestSource),t.requestSource),n=M(i);if(!i.ok){let t=await q(i);throw new D(404===i.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===i.status?"The repository or workflow run is not available to this installation":F(t,i.status,[a,e.privateKey]),n)}return{githubRequestId:n}}async function et(e,t){let r=t.force?"force-cancel":"cancel",i=t.force?h:d,a=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/${r}`,{response:n,token:s}=await z(e,r=>L(a,{method:"POST",headers:j(`Bearer ${r}`)},i,e,t.requestSource),t.requestSource),o=M(n);if(401===n.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",o);if(!n.ok){let t=await q(n);throw new D(404===n.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===n.status?"The repository or workflow run is not available to this installation":F(t,n.status,[s,e.privateKey]),o)}return{githubRequestId:o}}async function er(e,t){let r=[],i=1,a=0;do{let n=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/jobs?filter=latest&per_page=100&page=${i}`,{response:s,token:o}=await z(e,r=>L(n,{headers:j(`Bearer ${r}`)},y,e,t.requestSource),t.requestSource),l=M(s);if(401===s.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",l);let u=await q(s);if(!s.ok||!u||"object"!=typeof u)throw new D("GITHUB_APP_REQUEST_FAILED",F(u,s.status,[o,e.privateKey]),l);if(!Number.isInteger(u.total_count)||!Array.isArray(u.jobs))throw new D("GITHUB_APP_REQUEST_FAILED","GitHub returned an invalid workflow jobs response",l);a=u.total_count??0,r.push(...u.jobs),i+=1}while(r.length<a)return r}async function ei(e,t){let r=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}`,i=`${r}/actions/jobs/${encodeURIComponent(t.jobId)}`,a=await z(e,r=>L(i,{headers:j(`Bearer ${r}`)},m,e,t.requestSource),t.requestSource),n=M(a.response);if(401===a.response.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",n);let s=await q(a.response);if(!a.response.ok||!s||"object"!=typeof s)throw new D(404===a.response.status?"ACTIONS_JOB_NOT_FOUND":"GITHUB_APP_REQUEST_FAILED",404===a.response.status?"The GitHub Actions job is not available to this installation":F(s,a.response.status,[a.token,e.privateKey]),n);if(String(s.run_id??"")!==t.workflowRunId)throw new D("ACTIONS_JOB_RUN_MISMATCH","The GitHub Actions job does not belong to the selected workflow run",n);if(s.status?.toLowerCase()!=="completed")throw new D("ACTIONS_JOB_NOT_COMPLETED","The GitHub Actions job must be completed before it can be retried",n);let o=await z(e,r=>L(`${i}/rerun`,{method:"POST",headers:j(`Bearer ${r}`)},S,e,t.requestSource),t.requestSource),l=M(o.response);if(401===o.response.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",l);if(!o.response.ok){let t=await q(o.response);throw new D(404===o.response.status?"ACTIONS_JOB_NOT_FOUND":"GITHUB_APP_REQUEST_FAILED",404===o.response.status?"The GitHub Actions job is not available to this installation":F(t,o.response.status,[o.token,e.privateKey]),l)}return{githubRequestId:l}}let ea=new Set(["FAILURE","ERROR","STARTUP_FAILURE","TIMED_OUT"]),en=new Set(["ACTION_REQUIRED","EXPECTED","IN_PROGRESS","PENDING","QUEUED"]),es=["COMPLETED","EXHAUSTED","STOPPED"],eo={WORKFLOW_RUN:4,PULL_REQUEST:3,WORKTREE_BRANCH:2,REPOSITORY:1},el="server:github-auto-retry";function eu(e){return e.toISOString()}function ec(e){return{...e,scope:e.scope,mode:e.mode,failureStrategy:e.failureStrategy,status:e.status,executions:e.executions.map(e=>({...e,lastStatus:e.lastStatus,updatedAt:eu(e.updatedAt)})),createdAt:eu(e.createdAt),updatedAt:eu(e.updatedAt)}}class ed{github;polling;timer;pollingTickRunning;rerunRequested;reconciling;constructor(e,t,r=!0){this.github=e,this.polling=t,this.timer=null,this.pollingTickRunning=!1,this.rerunRequested=!1,this.reconciling=!1,this.polling?.register({id:el,kind:"GITHUB_AUTO_RETRY",runtime:"SERVER",enabled:!0,cadenceSeconds:60,details:{}}),r&&queueMicrotask(()=>void this.pollReconcile())}schedule(e){this.timer&&clearTimeout(this.timer);let t=1e3*Math.max(30,e);this.timer=setTimeout(()=>void this.pollReconcile(),t),this.timer.unref(),this.polling?.schedule(el,new Date(Date.now()+t))}configurationChanged(){if(this.pollingTickRunning){this.rerunRequested=!0;return}this.timer&&clearTimeout(this.timer),this.timer=null,queueMicrotask(()=>void this.pollReconcile())}async pollReconcile(){if(this.pollingTickRunning)return;this.pollingTickRunning=!0;let e=60;try{let t=async()=>(e=(await (await (0,r.getPrismaClient)()).gitHubSettings.upsert({where:{id:"default"},create:{id:"default"},update:{}})).actionsNotificationPollIntervalSeconds,this.polling?.configure(el,{cadenceSeconds:e}),this.reconcile());this.polling?await this.polling.run(el,t,e=>({activeRules:e})):await t()}catch{}finally{this.pollingTickRunning=!1,this.rerunRequested?(this.rerunRequested=!1,queueMicrotask(()=>void this.pollReconcile())):this.schedule(e)}}include(){return{targets:{orderBy:{createdAt:"asc"}},executions:{orderBy:{updatedAt:"desc"}}}}async list(e){let t=await (0,r.getPrismaClient)(),i=e.codebaseRepositoryId?await this.github.autoRetryRepositoryId(e.codebaseRepositoryId):null;return(await t.gitHubAutoRetryRule.findMany({where:{...i?{codebaseRepositoryId:i}:{},...e.workflowRunId?{targets:{some:{workflowRunId:e.workflowRunId}}}:{}},include:this.include(),orderBy:{updatedAt:"desc"}})).map(ec)}validate(e){if(!e.codebaseRepositoryId.trim())throw Error("Codebase repository is required");if("COUNT"===e.mode&&null==e.retryLimit)throw Error("Count mode requires a retry limit");if(null!=e.retryLimit&&(!Number.isInteger(e.retryLimit)||e.retryLimit<1||e.retryLimit>100))throw Error("Retry limit must be an integer from 1 to 100");if("FAILURE"===e.mode&&void 0===e.retryLimit)throw Error("Failure retry limit must be a number or null");if("WORKFLOW_RUN"===e.scope){if(!e.targets.length||e.targets.some(e=>!e.workflowRunId))throw Error("Current-run rules require workflow run targets")}else if(!e.allWorkflows&&!e.targets.length)throw Error("Select at least one workflow or choose all workflows");if("WORKTREE_BRANCH"===e.scope&&!e.worktreeId)throw Error("Worktree future rules require a worktree");if("PULL_REQUEST"===e.scope&&!e.pullRequestNumber)throw Error("Pull request future rules require a pull request number")}async save(e){if(!await this.github.autoRetryCredentialsReady())throw Error("A GitHub token and verified GitHub App with Actions write access are required");e={...e,codebaseRepositoryId:await this.github.autoRetryRepositoryId(e.codebaseRepositoryId)},this.validate(e);let i=await (0,r.getPrismaClient)(),a=e.branch?.trim()||null;if("WORKTREE_BRANCH"===e.scope&&e.worktreeId){let t=await i.worktree.findUnique({where:{id:e.worktreeId},select:{branch:!0}});if(!(a=t?.branch??null))throw Error("The worktree does not have a branch")}let n=await i.gitHubAutoRetryRule.findMany({where:{id:e.id?{not:e.id}:void 0,enabled:!0,scope:e.scope,codebaseRepositoryId:e.codebaseRepositoryId},include:{targets:!0}}),s=new Set(e.targets.map(e=>e.workflowRunId).filter(e=>!!e));if(n.find(t=>"WORKFLOW_RUN"===e.scope?t.targets.some(e=>e.workflowRunId&&s.has(e.workflowRunId)):"WORKTREE_BRANCH"===e.scope?t.branch===a:"PULL_REQUEST"!==e.scope||t.pullRequestNumber===e.pullRequestNumber))throw Error("An enabled Auto Retry rule already exists for this scope");let o=e.id??(0,t.randomUUID)(),l=await i.$transaction(async r=>(await r.gitHubAutoRetryRule.upsert({where:{id:o},create:{id:o,scope:e.scope,codebaseRepositoryId:e.codebaseRepositoryId,repositoryGithubId:e.repositoryGithubId??null,worktreeId:e.worktreeId??null,branch:a,pullRequestNumber:e.pullRequestNumber??null,allWorkflows:e.allWorkflows,mode:e.mode,retryLimit:e.retryLimit??null,failureStrategy:e.failureStrategy,status:"ACTIVE",enabled:!0},update:{scope:e.scope,codebaseRepositoryId:e.codebaseRepositoryId,repositoryGithubId:e.repositoryGithubId??null,worktreeId:e.worktreeId??null,branch:a,pullRequestNumber:e.pullRequestNumber??null,allWorkflows:e.allWorkflows,mode:e.mode,retryLimit:e.retryLimit??null,failureStrategy:e.failureStrategy,status:"ACTIVE",enabled:!0,lastError:null,activatedAt:new Date}}),await r.gitHubAutoRetryTarget.deleteMany({where:{ruleId:o}}),e.targets.length&&await r.gitHubAutoRetryTarget.createMany({data:e.targets.map(e=>({id:(0,t.randomUUID)(),ruleId:o,workflowId:e.workflowId?.trim()||null,workflowRunId:e.workflowRunId?.trim()||null,jobName:e.jobName?.trim()||null}))}),await r.gitHubAutoRetryExecution.deleteMany({where:{ruleId:o}}),r.gitHubAutoRetryRule.findUniqueOrThrow({where:{id:o},include:this.include()})));return queueMicrotask(()=>void this.reconcile().catch(()=>void 0)),ec(l)}async setEnabled(e,t){let i=await (0,r.getPrismaClient)(),a=await i.$transaction(async r=>(t&&await r.gitHubAutoRetryExecution.updateMany({where:{ruleId:e,pendingFromAttempt:{not:null}},data:{pendingFromAttempt:null,observedAttempt:0,status:"WATCHING",lastError:null,finishedAt:null}}),r.gitHubAutoRetryRule.update({where:{id:e},data:{enabled:t,status:t?"ACTIVE":"PAUSED",lastError:null,...t?{activatedAt:new Date}:{}},include:this.include()})));return t&&queueMicrotask(()=>void this.reconcile().catch(()=>void 0)),ec(a)}async delete(e){return(await (await (0,r.getPrismaClient)()).gitHubAutoRetryRule.deleteMany({where:{id:e}})).count>0}matches(e,t,r=!1){if("WORKFLOW_RUN"!==e.scope){let i=en.has(t.status);if(!r&&!i&&Date.parse(t.createdAt)<e.activatedAt.getTime())return!1}return"WORKTREE_BRANCH"===e.scope?t.headBranch===e.branch:"PULL_REQUEST"!==e.scope||t.pullRequests.some(t=>t.number===e.pullRequestNumber)}async execution(e,i,a){return(await (0,r.getPrismaClient)()).gitHubAutoRetryExecution.upsert({where:{ruleId_workflowRunId_targetKey:{ruleId:e,workflowRunId:i.id,targetKey:a}},create:{id:(0,t.randomUUID)(),ruleId:e,workflowRunId:i.id,workflowId:i.workflowId,targetKey:a},update:{}})}targetKeys(e,t){if(e.allWorkflows)return["workflow"];let r=e.targets.filter(e=>e.workflowRunId===t.id||e.workflowId===t.workflowId);return r.some(e=>!e.jobName)||"FAILURE"===e.mode&&"ALL_JOBS"===e.failureStrategy?["workflow"]:r.flatMap(e=>e.jobName?[`job:${e.jobName}`]:[])}async finishExecution(e,t,i){await (await (0,r.getPrismaClient)()).gitHubAutoRetryExecution.update({where:{id:e},data:{status:i,observedAttempt:t.runAttempt,lastStatus:t.status,pendingFromAttempt:null,finishedAt:new Date,lastError:null}})}async trigger(e,t,i,a,n){let s=await (0,r.getPrismaClient)();await s.gitHubAutoRetryExecution.update({where:{id:t.id},data:{status:"RETRYING",pendingFromAttempt:i.runAttempt,observedAttempt:i.runAttempt,lastStatus:i.status,lastError:null}});try{await this.github.autoRetryRerun(e.codebaseRepositoryId,i.id,a,n,{actor:"auto-retry",ipAddress:null,autoRetryRuleId:e.id,autoRetryExecutionId:t.id}),await s.gitHubAutoRetryExecution.update({where:{id:t.id},data:{automaticRetries:{increment:1},lastError:null}})}catch(i){let r=i instanceof Error?i.message:String(i);await s.gitHubAutoRetryExecution.update({where:{id:t.id},data:{lastError:r}}),await s.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r}})}}async reconcileExecution(e,t,i,a){var n;let s,o=await this.execution(e.id,t,i);if(null!=o.pendingFromAttempt)if(t.runAttempt>o.pendingFromAttempt)await (await (0,r.getPrismaClient)()).gitHubAutoRetryExecution.update({where:{id:o.id},data:{pendingFromAttempt:null,status:"WATCHING",lastError:null}});else{if(Date.now()-o.updatedAt.getTime()<12e4)return!1;let t=await (0,r.getPrismaClient)(),i="GitHub did not report a new attempt after the rerun request; automatic retries are paused to prevent a duplicate rerun";return await t.$transaction(async t=>{await t.gitHubAutoRetryExecution.update({where:{id:o.id},data:{status:"ERROR",lastError:i}}),await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{enabled:!1,status:"PAUSED",lastError:i}})}),!1}if(o.observedAttempt===t.runAttempt&&null==o.pendingFromAttempt)return!1;let l=a?.status??t.status,u=(s=null!=(n={mode:e.mode,retryLimit:e.retryLimit,automaticRetries:o.automaticRetries,state:l}).retryLimit&&n.automaticRetries>=n.retryLimit,"COUNT"===n.mode?"SUCCESS"!==n.state?"STOP":s?"COMPLETE":"RETRY":"SUCCESS"===n.state?"COMPLETE":ea.has(n.state)?s?"EXHAUSTED":"RETRY":"STOP");return"COMPLETE"===u?(await this.finishExecution(o.id,t,"COMPLETED"),!1):"EXHAUSTED"===u?(await this.finishExecution(o.id,t,"EXHAUSTED"),!1):"STOP"===u?(await this.finishExecution(o.id,t,"STOPPED"),!1):("COUNT"===e.mode?await this.trigger(e,o,t,a?"JOB":"ALL_JOBS",a?.id??null):await this.trigger(e,o,t,a?"ALL_JOBS"===e.failureStrategy?"ALL_JOBS":"JOB":"ALL_JOBS"===e.failureStrategy?"ALL_JOBS":"FAILED_JOBS",a?.id??null),!0)}async reconcile(){if(this.reconciling)return 0;this.reconciling=!0;let e=0;try{let t=await (0,r.getPrismaClient)(),i=await t.gitHubAutoRetryRule.findMany({where:{enabled:!0,status:"ACTIVE"},include:{targets:!0},orderBy:{createdAt:"asc"}});e=i.length;let a=new Map,n=i.length?await t.gitHubAutoRetryExecution.findMany({where:{ruleId:{in:i.map(e=>e.id)},status:{notIn:es}},select:{ruleId:!0,workflowRunId:!0}}):[],s=new Map;for(let e of n){let t=s.get(e.ruleId)??new Set;t.add(e.workflowRunId),s.set(e.ruleId,t)}let o=new Map;for(let e of i){let r=a.get(e.codebaseRepositoryId);if(!r)try{r=await this.github.autoRetryRuns(e.codebaseRepositoryId),a.set(e.codebaseRepositoryId,r)}catch(r){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r instanceof Error?r.message:String(r)}});continue}let i=new Set(e.targets.map(e=>e.workflowRunId).filter(e=>!!e)),n=s.get(e.id)??new Set;for(let a of new Set([...i,...n]))if(!r.some(e=>e.id===a))try{r.push(await this.github.autoRetryRun(e.codebaseRepositoryId,a,!1))}catch(r){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r instanceof Error?r.message:String(r)}})}for(let t of r){if("WORKFLOW_RUN"===e.scope&&!i.has(t.id)||!this.matches(e,t,n.has(t.id))||!e.allWorkflows&&!e.targets.some(e=>e.workflowRunId===t.id||e.workflowId===t.workflowId))continue;let r=o.get(t.id);(!r||eo[e.scope]>eo[r.rule.scope])&&o.set(t.id,{rule:e,run:t})}}for(let{rule:e,run:r}of o.values()){let i=this.targetKeys(e,r);if(en.has(r.status)){await Promise.all(i.map(t=>this.execution(e.id,r,t)));continue}let a=r,n=e.allWorkflows?[{jobName:null}]:e.targets.filter(e=>e.workflowRunId===a.id||e.workflowId===a.workflowId);if(n.some(e=>!e.jobName)){await this.reconcileExecution(e,a,"workflow",null);continue}let s=await Promise.all(i.map(t=>this.execution(e.id,a,t)));if(!s.some(e=>e.observedAttempt!==a.runAttempt||null!=e.pendingFromAttempt&&a.runAttempt>e.pendingFromAttempt)){for(let t=0;t<s.length;t+=1)s[t]?.pendingFromAttempt!=null&&await this.reconcileExecution(e,a,i[t],null);continue}try{a=await this.github.autoRetryRun(e.codebaseRepositoryId,a.id)}catch(r){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r instanceof Error?r.message:String(r)}});continue}if("FAILURE"===e.mode&&"ALL_JOBS"===e.failureStrategy){let t=a.jobs.filter(e=>n.some(t=>t.jobName===e.name)),r=t.find(e=>ea.has(e.status))??t.find(e=>"SUCCESS"!==e.status)??t[0];r?await this.reconcileExecution(e,a,"workflow",r):s[0]&&await this.finishExecution(s[0].id,a,"STOPPED");continue}let o=new Map(i.map((e,t)=>[e,s[t]]));for(let t of n){let r=a.jobs.find(e=>e.name===t.jobName);if(!r){let e=o.get(`job:${t.jobName}`);e&&await this.finishExecution(e.id,a,"STOPPED");continue}if(await this.reconcileExecution(e,a,`job:${r.name}`,r))break}}for(let e of i.filter(e=>"WORKFLOW_RUN"===e.scope)){let r=await t.gitHubAutoRetryExecution.findMany({where:{ruleId:e.id},select:{status:!0}});r.length>0&&r.every(e=>es.includes(e.status))&&await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{enabled:!1,status:r.some(e=>"EXHAUSTED"===e.status)?"EXHAUSTED":"COMPLETED"}})}}finally{this.reconciling=!1}return e}}e.i(805422);var ep=e.i(661983);let eh={LEGACY:0,GRAPHQL:1,REST:2,WEBHOOK:3,MUTATION:4},em=new Set(["CANCELLED","FAILURE","STALE","STARTUP_FAILURE","TIMED_OUT"]),ef=new Set(["ACTION_REQUIRED","IN_PROGRESS","PENDING","QUEUED"]),eg=new Set(["SUCCESS","NEUTRAL","SKIPPED"]);function ey(e,t=null){return e.some(e=>"ERROR"===e)?"ERROR":e.some(e=>em.has(e))?"FAILURE":e.some(e=>ef.has(e))?"PENDING":e.some(e=>"EXPECTED"===e)||"EXPECTED"===t?"EXPECTED":e.length>0&&e.every(e=>eg.has(e))?"SUCCESS":0===e.length&&t?t:"NONE"}function ew(e,t){let r=(t||e||"NONE").toUpperCase();return ek(r)?r:"REQUESTED"===r||"WAITING"===r?"QUEUED":"NONE"}function eb(e){return ef.has(e)?1:2*("NONE"!==e&&"EXPECTED"!==e)}function ev(e,t,r){let i=e.runAttempt??0,a=t.runAttempt??0;if(a!==i)return a>i;let n=e.githubUpdatedAt?.getTime()??0,s=t.githubUpdatedAt?.getTime()??0;if(s!==n)return s>n;if("MUTATION"===e.source&&e.optimisticUntil&&e.optimisticUntil.getTime()>r.getTime())return"MUTATION"===t.source;let o="MUTATION"===e.source?eh.LEGACY:eh[e.source],l=eh[t.source];if("MUTATION"!==e.source&&"MUTATION"!==t.source&&e.status&&t.status){let r=eb(e.status),i=eb(t.status);if(i!==r)return i>r}return l===o||l>o}function ek(e){return"ACTION_REQUIRED"===e||"CANCELLED"===e||"ERROR"===e||"EXPECTED"===e||"FAILURE"===e||"IN_PROGRESS"===e||"NEUTRAL"===e||"PENDING"===e||"QUEUED"===e||"SKIPPED"===e||"STALE"===e||"STARTUP_FAILURE"===e||"SUCCESS"===e||"TIMED_OUT"===e||"NONE"===e}function eS(e){return"ERROR"===e||"EXPECTED"===e||"FAILURE"===e||"PENDING"===e||"SUCCESS"===e||"NONE"===e}function eE(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function eI(e){return"NONE"===e||"EXPECTED"===e?0:"ACTION_REQUIRED"===e||"PENDING"===e||"QUEUED"===e?1:"IN_PROGRESS"===e?2:3}function ex(e){return"GRAPHQL"===e||"REST"===e||"WEBHOOK"===e||"MUTATION"===e?e:"LEGACY"}function eA(e){return{id:e.githubPipelineId,name:e.name,status:ek(e.status)?e.status:"NONE",url:e.url,checkSuiteId:e.checkSuiteId,canRetry:e.canRetry,retryUnavailableReason:e.retryUnavailableReason,jobs:eE(e.jobsJson),workflowRunId:e.workflowRunId,workflowId:e.workflowId,runNumber:e.runNumber,runAttempt:e.runAttempt}}function e_(e,t){return{...eA(t),repositoryGithubId:e.repositoryGithubId,headSha:e.headSha,revision:e.revision,isCurrent:t.isCurrent}}function eC(e){return{repositoryGithubId:e.repositoryGithubId,repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,headSha:e.headSha,pipelineStatus:eS(e.pipelineStatus)?e.pipelineStatus:"NONE",pipelines:e.records.filter(e=>e.isCurrent).map(eA).sort((e,t)=>e.name.localeCompare(t.name)),revision:e.revision,updatedAt:e.updatedAt.toISOString()}}function eR(e){return JSON.stringify({identityKey:e.identityKey,githubPipelineId:e.githubPipelineId,name:e.name,status:e.status,url:e.url,checkSuiteId:e.checkSuiteId,workflowRunId:e.workflowRunId,workflowId:e.workflowId,runNumber:e.runNumber,runAttempt:e.runAttempt,canRetry:e.canRetry,retryUnavailableReason:e.retryUnavailableReason,jobsJson:e.jobsJson,isCurrent:e.isCurrent})}function eT(e){return JSON.stringify({repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,pipelineStatus:e.pipelineStatus,records:e.records.map(eR).sort((e,t)=>e.localeCompare(t))})}class eD{lastPrunedAt=0;async snapshot(e){let t=await (0,r.getPrismaClient)(),i=await t.gitHubPipelineSnapshot.findUnique({where:{repositoryGithubId_headSha:{repositoryGithubId:e.repositoryGithubId.trim(),headSha:e.headSha.trim()}},include:{records:!0}});return i?eC(i):null}async snapshots(e){let t=e.map(e=>({repositoryGithubId:e.repositoryGithubId.trim(),headSha:e.headSha.trim()})).filter(e=>e.repositoryGithubId&&e.headSha);if(0===t.length)return[];let i=await (0,r.getPrismaClient)();return(await i.gitHubPipelineSnapshot.findMany({where:{OR:t},include:{records:!0}})).map(eC)}async records(e){let t=e.map(e=>({repositoryGithubId:e.repositoryGithubId.trim(),workflowRunId:e.workflowRunId.trim()})).filter(e=>e.repositoryGithubId&&e.workflowRunId);if(0===t.length)return[];let i=await (0,r.getPrismaClient)();return(await i.gitHubPipelineRecord.findMany({where:{OR:t.map(e=>({workflowRunId:e.workflowRunId,snapshot:{repositoryGithubId:e.repositoryGithubId}}))},include:{snapshot:{include:{records:!0}}}})).map(e=>e_(e.snapshot,e))}async observeWorkflowRuns(e,t="REST",r=!0){let i=new Map;for(let t of e){if(!t.repositoryGithubId||!t.headSha)continue;let e=`${t.repositoryGithubId}\u0000${t.headSha}`,r=i.get(e)??[];r.push(t),i.set(e,r)}let a=new Map;for(let e of i.values()){let i=e[0];await this.observeSnapshot({repositoryGithubId:i.repositoryGithubId,repositoryNameWithOwner:i.repositoryNameWithOwner,repositoryUrl:i.repositoryUrl,headSha:i.headSha,pipelines:e.map(e=>(function(e,t,r=!0){return{id:e.id,name:e.name,status:e.status,url:e.url,checkSuiteId:e.checkSuiteId,workflowRunId:e.id,workflowId:e.workflowId,runNumber:e.runNumber,runAttempt:e.runAttempt,canRetry:e.canRetry,retryUnavailableReason:e.retryUnavailableReason,source:t,githubUpdatedAt:new Date(e.updatedAt),sourceFetchedAt:new Date,isCurrent:r}})(e,t,r))})}for(let t of(await this.records(e.map(e=>({repositoryGithubId:e.repositoryGithubId,workflowRunId:e.id})))))t.workflowRunId&&a.set(t.workflowRunId,t);return a}async observeJobs(e,t,i,a="REST",n=null){let s=await (0,r.getPrismaClient)(),o=await s.gitHubPipelineRecord.findFirst({where:{workflowRunId:t,...e?{snapshot:{repositoryGithubId:e}}:{}},include:{snapshot:!0},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!o)return null;let l=i.filter(e=>null==e.runAttempt||null==o.runAttempt||e.runAttempt===o.runAttempt);if(i.length>0&&0===l.length)return e_({...o.snapshot,records:[o]},o);let u=eE(o.jobsJson),c=new Map(u.map(e=>[e.id,e])),d=l.map(e=>(function(e,t){if(!e)return t;let r=e.runAttempt??0,i=t.runAttempt??0;if(i!==r)return i>r?t:e;let a=eI(e.status),n=eI(t.status);return n<a?e:n===a&&t.steps.length<e.steps.length?{...t,steps:e.steps}:t})(c.get(e.id),e)),p="WEBHOOK"===a?[...new Map([...u,...d].map(e=>[e.id,e])).values()]:d,h=ek(o.status)?o.status:"NONE",m="REST"===a&&l.length>0?ey(l.map(e=>e.status),null):"NONE",f=("ERROR"===m||"FAILURE"===m||"SUCCESS"===m)&&o.snapshot.graphqlRollupStatus===m?m:h;return(await this.observeSnapshot({repositoryGithubId:o.snapshot.repositoryGithubId,repositoryNameWithOwner:o.snapshot.repositoryNameWithOwner,repositoryUrl:o.snapshot.repositoryUrl,headSha:o.snapshot.headSha,pipelines:[{...eA(o),status:f,source:a,jobs:p,githubUpdatedAt:n??o.githubUpdatedAt,isCurrent:o.isCurrent}]})).changedPipeline}async optimisticByCheckSuite(e,t,r){return this.optimisticRecord({repositoryGithubId:e,checkSuiteId:t,workflowRunId:null},r)}async optimisticByWorkflowRun(e,t,r){return this.optimisticRecord({repositoryGithubId:e,checkSuiteId:null,workflowRunId:t},r)}async optimisticJobByCheckSuite(e,t,i){let a=await (0,r.getPrismaClient)(),n=await a.gitHubPipelineRecord.findFirst({where:{checkSuiteId:t,snapshot:{repositoryGithubId:e}},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!n)return null;let s=eE(n.jobsJson).map(e=>e.id===i?{...e,status:"QUEUED",canRetry:!1,retryUnavailableReason:"NOT_COMPLETED"}:e);return this.optimisticByCheckSuite(e,t,{status:"QUEUED",jobs:s})}async optimisticJobByWorkflowRun(e,t,i){let a=await (0,r.getPrismaClient)(),n=await a.gitHubPipelineRecord.findFirst({where:{workflowRunId:t,...e?{snapshot:{repositoryGithubId:e}}:{}},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!n)return null;let s=eE(n.jobsJson).map(e=>e.id===i?{...e,status:"QUEUED",canRetry:!1,retryUnavailableReason:"NOT_COMPLETED"}:e);return this.optimisticByWorkflowRun(e,t,{status:"QUEUED",jobs:s})}async optimisticRecord(e,t){let i=await (0,r.getPrismaClient)(),a=await i.gitHubPipelineRecord.findFirst({where:{...e.repositoryGithubId?{snapshot:{repositoryGithubId:e.repositoryGithubId}}:{},...e.checkSuiteId?{checkSuiteId:e.checkSuiteId}:{workflowRunId:e.workflowRunId}},include:{snapshot:!0},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!a)return null;let n=new Date;return(await this.observeSnapshot({repositoryGithubId:a.snapshot.repositoryGithubId,repositoryNameWithOwner:a.snapshot.repositoryNameWithOwner,repositoryUrl:a.snapshot.repositoryUrl,headSha:a.snapshot.headSha,pipelines:[{...eA(a),status:t.status,jobs:t.jobs,canRetry:!1,retryUnavailableReason:"NOT_COMPLETED",source:"MUTATION",githubUpdatedAt:a.githubUpdatedAt,sourceFetchedAt:n,optimisticUntil:new Date(n.getTime()+12e4),isCurrent:a.isCurrent}]})).changedPipeline}async observeSnapshot(e){let i=e.repositoryGithubId.trim(),a=e.headSha.trim();if(!i||!a)throw Error("GitHub repository ID and head SHA are required");let n=new Date,s=e.sourceFetchedAt??n,o=await (0,r.getPrismaClient)(),l=await o.$transaction(async r=>{let o=await r.gitHubPipelineSnapshot.upsert({where:{repositoryGithubId_headSha:{repositoryGithubId:i,headSha:a}},create:{id:(0,t.randomUUID)(),repositoryGithubId:i,repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,headSha:a,pipelineStatus:"NONE",graphqlRollupStatus:null,revision:0,lastGraphqlSyncAt:null,lastObservedAt:n},update:{lastObservedAt:n},include:{records:!0}}),l=eT(o),u=!!(e.completeGraphqlRollup&&(!o.lastGraphqlSyncAt||s.getTime()>=o.lastGraphqlSyncAt.getTime())),c=new Set,d=null;for(let i of e.pipelines){let e=function(e){var t;return(t={id:e.id,checkSuiteId:e.checkSuiteId,workflowRunId:e.workflowRunId,statusContext:e.statusContext}).checkSuiteId?`CHECK_SUITE:${t.checkSuiteId}`:t.workflowRunId?`WORKFLOW_RUN:${t.workflowRunId}`:t.statusContext?`STATUS_CONTEXT:${t.statusContext}`:`PIPELINE:${t.id}`}(i),a=(await r.gitHubPipelineRecord.findMany({where:{snapshotId:o.id}})).filter(t=>t.identityKey===e||i.checkSuiteId&&t.checkSuiteId===i.checkSuiteId||i.workflowRunId&&t.workflowRunId===i.workflowRunId),l=a[0]??null;for(let e of a.slice(1))l&&ev({runAttempt:l.runAttempt,githubUpdatedAt:l.githubUpdatedAt,source:ex(l.source),optimisticUntil:l.optimisticUntil,status:ek(l.status)?l.status:"NONE"},{runAttempt:e.runAttempt,githubUpdatedAt:e.githubUpdatedAt,source:ex(e.source),status:ek(e.status)?e.status:"NONE"},n)&&(l=e);for(let e of a)l&&e.id!==l.id&&(0===eE(l.jobsJson).length&&eE(e.jobsJson).length>0&&(l=await r.gitHubPipelineRecord.update({where:{id:l.id},data:{jobsJson:e.jobsJson}})),await r.gitHubPipelineRecord.delete({where:{id:e.id}}),d=l.id);let p=i.sourceFetchedAt??s,h=i.githubUpdatedAt??null,m=void 0===i.runAttempt?l?.runAttempt??null:i.runAttempt,f=void 0!==i.jobs?JSON.stringify(i.jobs):l&&(m??0)<=(l.runAttempt??0)?l.jobsJson:"[]",g=!!u||(!1===i.isCurrent?l?.isCurrent??!1:i.isCurrent??l?.isCurrent??!0);if(l){c.add(l.id);let t=eR(l),a=ev({runAttempt:l.runAttempt,githubUpdatedAt:l.githubUpdatedAt,source:ex(l.source),optimisticUntil:l.optimisticUntil,status:ek(l.status)?l.status:"NONE"},{runAttempt:m,githubUpdatedAt:h,source:i.source,status:i.status},n),s=!!(!a&&"MUTATION"===l.source&&l.optimisticUntil&&l.optimisticUntil.getTime()>n.getTime()&&"MUTATION"!==i.source);t!==eR(l=await r.gitHubPipelineRecord.update({where:{id:l.id},data:a?{identityKey:e,githubPipelineId:i.id,name:i.name,status:i.status,url:void 0===i.url?l.url:i.url,checkSuiteId:void 0===i.checkSuiteId?l.checkSuiteId:i.checkSuiteId,workflowRunId:void 0===i.workflowRunId?l.workflowRunId:i.workflowRunId,workflowId:void 0===i.workflowId?l.workflowId:i.workflowId,runNumber:void 0===i.runNumber?l.runNumber:i.runNumber,runAttempt:m,canRetry:void 0===i.canRetry?l.canRetry:i.canRetry,retryUnavailableReason:void 0===i.retryUnavailableReason?l.retryUnavailableReason:i.retryUnavailableReason,jobsJson:f,source:i.source,githubUpdatedAt:h,sourceFetchedAt:p,lastObservedAt:n,optimisticUntil:void 0===i.optimisticUntil?l.optimisticUntil:i.optimisticUntil,isCurrent:g}:{lastObservedAt:n,...void 0!==i.jobs&&!s?{jobsJson:f}:{},...u?{isCurrent:!0}:{}}}))&&(d=l.id)}else d=(l=await r.gitHubPipelineRecord.create({data:{id:(0,t.randomUUID)(),snapshotId:o.id,identityKey:e,githubPipelineId:i.id,name:i.name,status:i.status,url:i.url??null,checkSuiteId:i.checkSuiteId??null,workflowRunId:i.workflowRunId??null,workflowId:i.workflowId??null,runNumber:i.runNumber??null,runAttempt:m,canRetry:i.canRetry??!1,retryUnavailableReason:i.retryUnavailableReason??null,jobsJson:f,source:i.source,githubUpdatedAt:h,sourceFetchedAt:p,lastObservedAt:n,optimisticUntil:i.optimisticUntil??null,isCurrent:g}})).id;c.add(l.id)}if(u)for(let e of(await r.gitHubPipelineRecord.findMany({where:{snapshotId:o.id,isCurrent:!0}})))!c.has(e.id)&&e.sourceFetchedAt.getTime()<=s.getTime()&&(!e.optimisticUntil||e.optimisticUntil.getTime()<=n.getTime())&&(await r.gitHubPipelineRecord.update({where:{id:e.id},data:{isCurrent:!1}}),d??=e.id);let p=await r.gitHubPipelineRecord.findMany({where:{snapshotId:o.id}}),h=u?e.graphqlRollupStatus??null:o.graphqlRollupStatus,m=ey(p.filter(e=>e.isCurrent).map(e=>ek(e.status)?e.status:"NONE"),h&&eS(h)?h:null),f=l!==eT(o=await r.gitHubPipelineSnapshot.update({where:{id:o.id},data:{repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,pipelineStatus:m,graphqlRollupStatus:h,lastGraphqlSyncAt:u?s:o.lastGraphqlSyncAt,lastObservedAt:n},include:{records:!0}}))||null!==d;f&&(o=await r.gitHubPipelineSnapshot.update({where:{id:o.id},data:{revision:{increment:1}},include:{records:!0}}));let g=o,y=d?g.records.find(e=>e.id===d)??null:null;return{changed:f,change:{snapshot:eC(g),changedPipeline:y?e_(g,y):null}}});return l.changed&&ep.agentEventBus.publish(ep.GITHUB_PIPELINE_STATUS_CHANGED_TOPIC,{githubPipelineStatusChanged:l.change}),this.pruneIfNeeded().catch(()=>void 0),l.change}subscribe(){return ep.agentEventBus.iterate(ep.GITHUB_PIPELINE_STATUS_CHANGED_TOPIC)}async pruneIfNeeded(){let e=Date.now();if(e-this.lastPrunedAt<864e5)return;this.lastPrunedAt=e;let t=await (0,r.getPrismaClient)();await t.gitHubPipelineSnapshot.deleteMany({where:{lastObservedAt:{lt:new Date(e-2592e6)}}})}}e.s(["GitHubPipelineStatusService",0,eD],963910);let eN=/^[_A-Za-z][_0-9A-Za-z]*$/,eO=new Map([["GitHubWorktreePullRequestStatuses",60]]),eP=[{window:"5m",milliseconds:3e5},{window:"10m",milliseconds:6e5},{window:"1h",milliseconds:36e5},{window:"24h",milliseconds:864e5}];function e$(e){return JSON.stringify(function e(t){return Array.isArray(t)?t.map(e):t&&"object"==typeof t?Object.fromEntries(Object.keys(t).sort().map(r=>[r,e(t[r])])):t}(e))}let eU=/(?:authorization|password|private.?key|secret|token)$/i;function eB(e,t=""){return eU.test(t)?"[REDACTED]":Array.isArray(e)?e.map(e=>eB(e)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,eB(t,e)])):e}function ej(e){try{return JSON.parse(e)}catch{return null}}function eL(e){return e&&"object"==typeof e?{statusCode:"number"==typeof e.statusCode?e.statusCode:null,rateLimit:e.rateLimit&&"object"==typeof e.rateLimit?e.rateLimit:null}:{statusCode:null,rateLimit:null}}class eq{inFlight=new Map;cacheWrites=new Set;cacheGeneration=0;lastPrunedAt=0;cacheKey(e){return(0,t.createHash)("sha256").update(e$({authentication:e.authentication,endpoint:e.endpoint,query:e.normalizedQuery,variables:e.variables})).digest("hex")}inFlightKey(e,t,r){return[r,e,!0===t.force?"force":"normal",!1===t.allowStaleOnError?"strict":"stale"].join(":")}async defaultTtlSeconds(){let e=await (0,r.getPrismaClient)();return(await e.gitHubSettings.upsert({where:{id:"default"},create:{id:"default",cacheTtlSeconds:300},update:{}})).cacheTtlSeconds}async effectiveTtlSeconds(e){let t=await (0,r.getPrismaClient)(),[i,a]=await Promise.all([t.gitHubGraphqlCacheTtlOverride.findUnique({where:{operation:e}}),this.defaultTtlSeconds()]);return i?.ttlSeconds??a}async query(e){let i=this.cacheGeneration,a=await (0,r.getPrismaClient)(),n=this.cacheKey(e),s=this.inFlightKey(n,e,i),o=Date.now(),[l,u,c]=await Promise.all([a.gitHubGraphqlCacheEntry.findUnique({where:{cacheKey:n}}),this.effectiveTtlSeconds(e.operation),a.gitHubRateLimitSnapshot.findUnique({where:{authentication_resource:{authentication:e.authentication,resource:"graphql"}}})]);if(i!==this.cacheGeneration)return this.query(e);let d=null!==l&&Date.now()-l.fetchedAt.getTime()<1e3*u;if(!e.force&&d)return(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"CACHE",durationMs:Date.now()-o,pointCost:0,pointsAvoided:l.pointCost??0}).catch(()=>void 0),i!==this.cacheGeneration)?this.query(e):{data:ej(l.responseJson),source:"CACHE",stale:!1,fetchedAt:l.fetchedAt,entryId:l.id,pointCost:l.pointCost};let p=this.inFlight.get(s);if(p){let t=await p;return i!==this.cacheGeneration||(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"CACHE",durationMs:Date.now()-o,pointCost:0,pointsAvoided:t.pointCost??0}).catch(()=>void 0),i!==this.cacheGeneration)?this.query(e):{...t,source:"CACHE"}}if(c?.remaining===0&&c.resetAt.getTime()>Date.now()){let t=`GitHub GraphQL rate limit is exhausted until ${c.resetAt.toISOString()}`,r=null!==l&&!1!==e.allowStaleOnError;if(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-o,error:t,servedStale:r,pointCost:0,pointsAvoided:r?l.pointCost??0:0,rateLimit:{limit:c.limit,remaining:c.remaining,used:c.used,resetAt:c.resetAt,resource:c.resource}}).catch(()=>void 0),i!==this.cacheGeneration)return this.query(e);if(r)return{data:ej(l.responseJson),source:"ERROR",stale:!0,fetchedAt:l.fetchedAt,entryId:l.id,pointCost:l.pointCost};throw Error(t)}let h=(async()=>{try{let r=await e.fetcher(),s=new Date,l=null;if(i===this.cacheGeneration){let i=a.gitHubGraphqlCacheEntry.upsert({where:{cacheKey:n},create:{id:(0,t.randomUUID)(),cacheKey:n,authentication:e.authentication,endpoint:e.endpoint,operation:e.operation,query:e.query,variablesJson:e$(e.variables),responseJson:JSON.stringify(r.data),fetchedAt:s,pointCost:r.pointCost},update:{operation:e.operation,query:e.query,variablesJson:e$(e.variables),responseJson:JSON.stringify(r.data),fetchedAt:s,pointCost:r.pointCost}});this.cacheWrites.add(i);try{l=await i}finally{this.cacheWrites.delete(i)}}return await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"LIVE",durationMs:Date.now()-o,statusCode:r.statusCode,pointCost:r.pointCost,rateLimit:r.rateLimit}).catch(()=>void 0),{data:r.data,source:"LIVE",stale:!1,fetchedAt:s,entryId:i===this.cacheGeneration?l?.id??null:null,pointCost:r.pointCost}}catch(a){let t=eL(a),r=i===this.cacheGeneration&&null!==l&&!1!==e.allowStaleOnError;if(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-o,statusCode:t.statusCode,error:a instanceof Error?a.message:String(a),servedStale:r,pointsAvoided:r?l?.pointCost??0:0,rateLimit:t.rateLimit}).catch(()=>void 0),i!==this.cacheGeneration)throw a;if(r)return{data:ej(l.responseJson),source:"ERROR",stale:!0,fetchedAt:l.fetchedAt,entryId:l.id,pointCost:l.pointCost};throw a}})();this.inFlight.set(s,h);try{return await h}finally{this.inFlight.get(s)===h&&this.inFlight.delete(s)}}async mutation(e){let t,r=Date.now();try{t=await e.fetcher()}catch(i){let t=eL(i);throw await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-r,statusCode:t.statusCode,error:i instanceof Error?i.message:String(i),rateLimit:t.rateLimit}).catch(()=>void 0),i}return await this.clear(),await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"LIVE",durationMs:Date.now()-r,statusCode:t.statusCode,pointCost:null,rateLimit:t.rateLimit}).catch(()=>void 0),t.data}async updateTtl(e,t){if(!Number.isInteger(e)||e<1||e>1440)throw Error("Cache TTL must be an integer from 1 to 1440 minutes");let i=await (0,r.getPrismaClient)();return await i.gitHubSettings.upsert({where:{id:"default"},create:{id:"default",cacheTtlSeconds:60*e},update:{cacheTtlSeconds:60*e}}),t()}async ttlOverrides(){let e=await (0,r.getPrismaClient)();return(await e.gitHubGraphqlCacheTtlOverride.findMany({orderBy:{operation:"asc"}})).map(e=>({operation:e.operation,ttlSeconds:e.ttlSeconds,builtIn:eO.has(e.operation),createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))}async cacheableOperations(){let e=await (0,r.getPrismaClient)(),[t,i]=await Promise.all([e.gitHubGraphqlCacheTtlOverride.findMany({select:{operation:!0}}),e.gitHubGraphqlCacheEntry.findMany({distinct:["operation"],select:{operation:!0}})]);return[...new Set([...eO.keys(),...t.map(({operation:e})=>e),...i.map(({operation:e})=>e)])].sort((e,t)=>e.localeCompare(t))}async saveTtlOverride(e,t){let i=e.trim();if(!eN.test(i))throw Error("Operation must be a valid GraphQL operation name");if(!Number.isInteger(t)||t<1||t>86400)throw Error("Cache TTL must be an integer from 1 to 86400 seconds");let a=await (0,r.getPrismaClient)(),n=await a.gitHubGraphqlCacheTtlOverride.upsert({where:{operation:i},create:{operation:i,ttlSeconds:t},update:{ttlSeconds:t}});return{operation:n.operation,ttlSeconds:n.ttlSeconds,builtIn:eO.has(n.operation),createdAt:n.createdAt.toISOString(),updatedAt:n.updatedAt.toISOString()}}async deleteTtlOverride(e){let t=e.trim();if(eO.has(t))throw Error("Built-in cache TTL overrides cannot be deleted");let i=await (0,r.getPrismaClient)();return(await i.gitHubGraphqlCacheTtlOverride.deleteMany({where:{operation:t}})).count>0}async recordRestCall(e){let t=e.endpoint,r={};try{let i=new URL(e.endpoint);t=i.pathname,r={path:i.pathname,query:Object.fromEntries(i.searchParams)}}catch{r={endpoint:e.endpoint}}await this.log({authentication:e.authentication,apiType:"REST",method:e.method.toUpperCase(),endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:`${e.method.toUpperCase()} ${t}`,variables:r,source:e.error?"ERROR":"LIVE",durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,pointCost:1,rateLimit:e.rateLimit})}async recordGraphqlTransportCall(e){await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,requestSource:e.requestSource,source:e.error?"ERROR":"LIVE",durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,rateLimit:e.rateLimit})}async clear(){let{cacheWrites:e}=this.beginInvalidation();await Promise.allSettled(e);let t=await (0,r.getPrismaClient)();return await t.gitHubGraphqlCacheEntry.deleteMany(),!0}async clearForCredentialChange(e){let{cacheWrites:t,inFlight:i}=this.beginInvalidation();await Promise.allSettled(t);let a=await (0,r.getPrismaClient)();return await a.gitHubGraphqlCacheEntry.deleteMany(),await Promise.allSettled(i),await a.gitHubRateLimitSnapshot.deleteMany({where:{authentication:e}}),!0}async clearCalls(){let e=await (0,r.getPrismaClient)();return await e.gitHubApiCallLog.deleteMany(),!0}async delete(e){let t=await (0,r.getPrismaClient)();return(await t.gitHubGraphqlCacheEntry.deleteMany({where:{id:e}})).count>0}async entries(e=50,t=0){let i=this.pagination(e,t),a=await (0,r.getPrismaClient)(),[n,s,o,l]=await Promise.all([a.gitHubGraphqlCacheEntry.findMany({take:i.limit,skip:i.offset,orderBy:{fetchedAt:"desc"}}),a.gitHubGraphqlCacheEntry.count(),this.defaultTtlSeconds(),a.gitHubGraphqlCacheTtlOverride.findMany({select:{operation:!0,ttlSeconds:!0}})]),u=new Map(l.map(({operation:e,ttlSeconds:t})=>[e,t]));return{...i,total:s,items:n.map(e=>this.entryView(e,u.get(e.operation)??o))}}async entry(e){let t=await (0,r.getPrismaClient)(),i=await t.gitHubGraphqlCacheEntry.findUnique({where:{id:e}});if(!i)return null;let a=await this.effectiveTtlSeconds(i.operation);return{...this.entryView(i,a),query:i.query,variables:ej(i.variablesJson),response:ej(i.responseJson)}}async calls(e=50,t=0,i={}){let a=this.pagination(e,t);await this.pruneLogs();let n=await (0,r.getPrismaClient)(),s={...i.apiType?{apiType:i.apiType}:{},...i.requestSource?{requestSource:i.requestSource}:{},...i.source?{source:i.source}:{}},[o,l]=await Promise.all([n.gitHubApiCallLog.findMany({where:s,take:a.limit,skip:a.offset,orderBy:{createdAt:"desc"}}),n.gitHubApiCallLog.count({where:s})]);return{...a,total:l,items:o.map(e=>({id:e.id,authentication:e.authentication,apiType:e.apiType,method:e.method,endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:e.requestSummary,variables:ej(e.variablesJson),source:e.source,durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,servedStale:e.servedStale,pointCost:e.pointCost,pointsAvoided:e.pointsAvoided,rateLimitLimit:e.rateLimitLimit,rateLimitRemaining:e.rateLimitRemaining,rateLimitUsed:e.rateLimitUsed,rateLimitResetAt:e.rateLimitResetAt?.toISOString()??null,rateLimitResource:e.rateLimitResource,createdAt:e.createdAt.toISOString()}))}}async metrics(){await this.pruneLogs();let e=await (0,r.getPrismaClient)(),t=Date.now(),i=await e.gitHubApiCallLog.findMany({where:{createdAt:{gte:new Date(t-eP.at(-1).milliseconds)}},orderBy:{createdAt:"asc"}}),a=eP.map(e=>this.metricWindow(e.window,i.filter(r=>r.createdAt.getTime()>=t-e.milliseconds)));return{windows:a,apiTypes:["GRAPHQL","REST"].map(e=>({apiType:e,windows:eP.map(r=>this.metricWindow(r.window,i.filter(i=>i.apiType===e&&i.createdAt.getTime()>=t-r.milliseconds)))})),operations:[...new Set(i.map(e=>e.operation))].sort().map(e=>({operation:e,windows:eP.map(r=>this.metricWindow(r.window,i.filter(i=>i.operation===e&&i.createdAt.getTime()>=t-r.milliseconds)))})),requestSources:[...new Set(i.map(e=>e.requestSource))].sort().map(e=>({requestSource:e,windows:eP.map(r=>this.metricWindow(r.window,i.filter(i=>i.requestSource===e&&i.createdAt.getTime()>=t-r.milliseconds)))}))}}entryView(e,t){return{id:e.id,authentication:e.authentication,operation:e.operation,endpoint:e.endpoint,fetchedAt:e.fetchedAt.toISOString(),pointCost:e.pointCost,stale:Date.now()-e.fetchedAt.getTime()>=1e3*t}}metricWindow(e,t){let r=t.length;return{window:e,total:r,live:t.filter(e=>"LIVE"===e.source).length,cache:t.filter(e=>"CACHE"===e.source).length,errors:t.filter(e=>"ERROR"===e.source).length,averageMs:0===r?0:Math.round(t.reduce((e,t)=>e+t.durationMs,0)/r),pointsUsed:t.reduce((e,t)=>e+Math.max(0,t.pointCost??0),0),pointsAvoided:t.reduce((e,t)=>e+Math.max(0,t.pointsAvoided),0)}}pagination(e,t){if(!Number.isInteger(e)||e<1||e>100)throw Error("limit must be an integer from 1 to 100");if(!Number.isInteger(t)||t<0)throw Error("offset must be a non-negative integer");return{limit:e,offset:t}}beginInvalidation(){let e=[...this.cacheWrites],t=[...new Set(this.inFlight.values())];return this.cacheGeneration+=1,this.inFlight.clear(),{cacheWrites:e,inFlight:t}}graphqlContext(e){let t=eB(e.variables);return{apiType:"GRAPHQL",method:"POST",endpoint:e.endpoint,requestSource:e.requestSource,requestSummary:function(e){if(!e||"object"!=typeof e||Array.isArray(e))return"No variables";let t=Object.entries(e);return t.length?t.map(([e,t])=>{let r=("string"==typeof t?t:JSON.stringify(t))??String(t);return`${e}=${r.length>120?`${r.slice(0,117)}…`:r}`}).join(" · "):"No variables"}(t),variables:t}}async log(e){await this.pruneLogs();let i=await (0,r.getPrismaClient)();await i.gitHubApiCallLog.create({data:{id:(0,t.randomUUID)(),authentication:e.authentication,apiType:e.apiType,method:e.method,endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:e.requestSummary,variablesJson:e$(eB(e.variables)),source:e.source,durationMs:Math.max(0,Math.round(e.durationMs)),statusCode:e.statusCode??null,error:e.error?.slice(0,2e3)??null,servedStale:e.servedStale??!1,pointCost:e.pointCost??null,pointsAvoided:Math.max(0,e.pointsAvoided??0),rateLimitLimit:e.rateLimit?.limit??null,rateLimitRemaining:e.rateLimit?.remaining??null,rateLimitUsed:e.rateLimit?.used??null,rateLimitResetAt:e.rateLimit?.resetAt??null,rateLimitResource:e.rateLimit?.resource??null}})}async pruneLogs(){let e=Date.now();if(e-this.lastPrunedAt<36e5)return;this.lastPrunedAt=e;let t=await (0,r.getPrismaClient)();await t.gitHubApiCallLog.deleteMany({where:{createdAt:{lt:new Date(e-2592e6)}}})}}let eM=(process.env.GITHUB_API_BASE_URL||"https://api.github.com").replace(/\/+$/,""),eF=process.env.GITHUB_GRAPHQL_URL||`${eM}/graphql`;var eK=e.i(995702),eV=e.i(151112),eG=e.i(312851);let eH="_adeRateLimit";function eW(e){let t=(0,eV.parse)(e),r=t.definitions.filter(e=>e.kind===eK.Kind.OPERATION_DEFINITION);if(1!==r.length||!r[0])throw Error("GitHub GraphQL requests must contain one operation");let i=r[0],a=i.name?.value??("mutation"===i.operation?"AnonymousMutation":"AnonymousQuery"),n=(0,eG.print)(t);if("query"!==i.operation)return{kind:"mutation",operation:a,normalizedQuery:n,liveQuery:n};let s={...t,definitions:t.definitions.map(e=>e===i?{...i,selectionSet:{...i.selectionSet,selections:[...i.selectionSet.selections,{kind:eK.Kind.FIELD,alias:{kind:eK.Kind.NAME,value:eH},name:{kind:eK.Kind.NAME,value:"rateLimit"},arguments:[],directives:[],selectionSet:{kind:eK.Kind.SELECTION_SET,selections:[{kind:eK.Kind.FIELD,name:{kind:eK.Kind.NAME,value:"cost"},arguments:[],directives:[]}]}}]}}:e)};return{kind:"query",operation:a,normalizedQuery:n,liveQuery:(0,eG.print)(s)}}function eJ(e){if(!e||"object"!=typeof e||Array.isArray(e))return{data:e,pointCost:null};let t=e[eH],r=t&&"object"==typeof t&&!Array.isArray(t)&&Number.isSafeInteger(t.cost)?t.cost:null;if(!(eH in e))return{data:e,pointCost:r};let i={...e};return delete i[eH],{data:i,pointCost:r}}let ez="default",eZ="default",eY=String.raw`\b([A-Z][A-Z0-9_]*-\d+)\b`,eQ=["workflow_run","workflow_job","check_run","check_suite","status"];function eX(e){return"read"===e||"write"===e}function e0(e){let t=[];for(let r of(e.webhookConfigured||t.push("configure the signed webhook URL"),eX(e.actionsPermission)||t.push("grant Actions read permission"),eX(e.checksPermission)||t.push("grant Checks read permission"),eX(e.commitStatusesPermission)||t.push("grant Commit statuses read permission"),eQ))e.webhookEvents.includes(r)||t.push(`subscribe to the ${r} event`);return t}function e1(e){return"auto-retry"===e.actor?"AUTO_RETRY":"workflow"===e.actor?"WORKFLOW_AUTOMATION":"ACTIONS_PAGE"}class e2 extends Error{statusCode;rateLimit;constructor(e,t,r){super(e),this.statusCode=t,this.rateLimit=r,this.name="GitHubRequestError"}}let e3=`
25
+ `}])},115354,49172,493015,149721,e=>{"use strict";e.i(867695);var t=e.i(791001),r=e.i(666680),i=e.i(682954),a=e.i(243783);e.i(582482);var n=e.i(318905),s=e.i(91022),o=e.i(661983),l=e.i(397554),u=e.i(827957);class c extends Error{status;errors;constructor(e,t,r){super(e),this.status=t,this.errors=r,this.name="AppleDeveloperRequestError"}}async function d(e=new s.CredentialService){let t=await (0,a.getPrismaClient)(),r=await t.iosDeviceSettings.findUnique({where:{id:"default"},select:{appStoreConnectIssuerId:!0,appStoreConnectKeyId:!0}});if(!r?.appStoreConnectIssuerId||!r.appStoreConnectKeyId)throw Error("App Store Connect API credentials are not configured");let i=await e.getText(n.CREDENTIALS.appStoreConnectPrivateKey);if(!i)throw Error("App Store Connect API credentials are not configured");return{issuerId:r.appStoreConnectIssuerId,keyId:r.appStoreConnectKeyId,privateKey:i}}class p{credentials;fetcher;constructor(e,t=fetch){this.credentials=e,this.fetcher=t}async token(){let e;try{e=await (0,l.importPKCS8)(this.credentials.privateKey,"ES256")}catch{throw Error("The App Store Connect key must be an ES256 PKCS#8 private key")}return new u.SignJWT({}).setProtectedHeader({alg:"ES256",kid:this.credentials.keyId,typ:"JWT"}).setIssuer(this.credentials.issuerId).setAudience("appstoreconnect-v1").setIssuedAt().setExpirationTime("15m").sign(e)}async request(e,t={}){let r,i=await this.token(),a=e.startsWith("http")?e:`https://api.appstoreconnect.apple.com${e}`;try{r=await this.fetcher(a,{...t,signal:t.signal??AbortSignal.timeout(2e4),headers:{accept:"application/json",authorization:`Bearer ${i}`,...t.body?{"content-type":"application/json"}:{},...t.headers}})}catch(e){if(e instanceof Error&&("TimeoutError"===e.name||"AbortError"===e.name))throw Error("Apple Developer API timed out; retry the operation");throw Error("Could not connect to the Apple Developer API")}if(204===r.status)return;let n=await r.json().catch(()=>({}));if(!r.ok){let e=n.errors?.map(e=>e.detail||e.title||e.code).filter(Boolean).join("; ");throw new c(401===r.status||403===r.status?"Apple rejected the API key or it lacks Certificates, Identifiers & Profiles permission":e||`Apple Developer API returned HTTP ${r.status}`,r.status,n.errors??[])}return n}async list(e){let t=[],r=e;for(;r;){let e=await this.request(r);t.push(...e.data),r=e.links?.next??null}return t}listProfiles(){return this.list("/v1/profiles?limit=200&include=bundleId,certificates,devices")}listCertificates(){return this.list("/v1/certificates?limit=200")}listBundleIds(){return this.list("/v1/bundleIds?limit=200")}listDevices(){return this.list("/v1/devices?limit=200")}async createProfile(e){let t={bundleId:{data:{type:"bundleIds",id:e.bundleIdId}},certificates:{data:e.certificateIds.map(e=>({type:"certificates",id:e}))}};return e.deviceIds?.length&&(t.devices={data:e.deviceIds.map(e=>({type:"devices",id:e}))}),this.request("/v1/profiles",{method:"POST",body:JSON.stringify({data:{type:"profiles",attributes:{name:e.name,profileType:e.profileType},relationships:t}})})}deleteProfile(e){return this.request(`/v1/profiles/${encodeURIComponent(e)}`,{method:"DELETE"})}revokeCertificate(e){return this.request(`/v1/certificates/${encodeURIComponent(e)}`,{method:"DELETE"})}}e.s(["AppleDeveloperClient",0,p,"AppleDeveloperRequestError",0,c,"storedAppleDeveloperCredentials",0,d],49172),e.s([],493015);let h=/^[A-Za-z]+\d+,\d+$/;function m(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`IPSW.me returned an invalid ${t}`);return e}function f(e,t,r){if("string"!=typeof e||!e.trim())throw Error(`IPSW.me returned an invalid ${t}`);let i=e.trim();if(i.length>r)throw Error(`IPSW.me returned an invalid ${t}`);return i}async function g(e,t=fetch){let r,i;if(!h.test(e))throw Error("Device product identifier is invalid");try{r=await t(`https://api.ipsw.me/v4/device/${encodeURIComponent(e)}`,{headers:{accept:"application/json"},signal:AbortSignal.timeout(1e4)})}catch{throw Error("Could not connect to IPSW.me")}if(!r.ok)throw Error(404===r.status?"IPSW.me does not recognize this device model":`IPSW.me returned HTTP ${r.status}`);try{i=await r.json()}catch{throw Error("IPSW.me returned invalid JSON")}let a=m(i,"device response"),n=f(a.identifier,"device identifier",50);if(n!==e)throw Error("IPSW.me returned a different device");if(!Array.isArray(a.firmwares))throw Error("IPSW.me returned an invalid firmware list");return{name:f(a.name,"device name",100),identifier:n,firmwares:a.firmwares.slice(0,1e3).map(e=>(function(e,t){let r,i=m(e,"firmware entry");if(f(i.identifier,"firmware identifier",50)!==t)throw Error("IPSW.me returned firmware for a different device");let a=i.filesize;if("number"!=typeof a||!Number.isSafeInteger(a)||a<0)throw Error("IPSW.me returned an invalid firmware size");let n=f(i.url,"firmware URL",2048);try{r=new URL(n)}catch{throw Error("IPSW.me returned an invalid firmware URL")}if("https:"!==r.protocol)throw Error("IPSW.me returned an insecure firmware URL");let s=new Date(f(i.releasedate,"release date",100));if(Number.isNaN(s.getTime()))throw Error("IPSW.me returned an invalid release date");if("boolean"!=typeof i.signed)throw Error("IPSW.me returned an invalid signing status");return{version:f(i.version,"firmware version",50),buildId:f(i.buildid,"firmware build",50),fileSize:a,url:r.toString(),releaseDate:s.toISOString(),signed:i.signed}})(e,n)).sort((e,t)=>Date.parse(t.releaseDate)-Date.parse(e.releaseDate))}}let y="default";class w extends Error{status;code;constructor(e,t,r){super(e),this.status=t,this.code=r,this.name="IosEnrollmentError"}}function b(e,t,r){let i=e.trim();if(!i)throw Error(`${t} is required`);if(i.length>r)throw Error(`${t} is too long`);return i}function v(e,t,r){if(null==e)return null;if("string"!=typeof e)throw Error(`${t} must be a string`);let i=e.trim();if(i.length>r)throw Error(`${t} is too long`);return i||null}function k(e){return e.replace(/[\t\r\n]/g," ").trim()}e.s(["IosDevicesService",0,class{fetcher;credentials;firmwareCache;constructor(e=fetch,t=new s.CredentialService){this.fetcher=e,this.credentials=t,this.firmwareCache=new Map}changed(e=null){o.agentEventBus.publish(o.IOS_DEVICES_CHANGED_TOPIC,{id:e})}subscribe(){return o.agentEventBus.iterate(o.IOS_DEVICES_CHANGED_TOPIC)}async rawSettings(){return(await (0,a.getPrismaClient)()).iosDeviceSettings.upsert({where:{id:y},create:{id:y},update:{}})}async getSettings(){let[e,t,r]=await Promise.all([this.rawSettings(),this.credentials.isConfigured(n.CREDENTIALS.iosProfileSignerPrivateKey),this.credentials.isConfigured(n.CREDENTIALS.appStoreConnectPrivateKey)]);return{organizationName:e.organizationName,profileIdentifier:e.profileIdentifier,signerConfigured:!!(e.signerCertificatePem&&t),signerFingerprint:e.signerFingerprint,signerCreatedAt:e.signerCreatedAt?.toISOString()??null,signerExpiresAt:e.signerExpiresAt?.toISOString()??null,appStoreConnectConfigured:!!(e.appStoreConnectIssuerId&&e.appStoreConnectKeyId&&r&&e.appStoreConnectVerifiedAt),appStoreConnectIssuerId:e.appStoreConnectIssuerId,appStoreConnectKeyId:e.appStoreConnectKeyId,appStoreConnectPrivateKeyConfigured:!!r,appStoreConnectPrivateKeyFingerprint:e.appStoreConnectPrivateKeyFingerprint,appStoreConnectVerifiedAt:e.appStoreConnectVerifiedAt?.toISOString()??null,appStoreConnectLastTestedAt:e.appStoreConnectLastTestedAt?.toISOString()??null,appStoreConnectVerificationError:e.appStoreConnectVerificationError,updatedAt:e.updatedAt.toISOString()}}async saveProfileSettings(e){let t=b(e.organizationName,"Organization name",100),r=b(e.profileIdentifier,"Profile identifier",200);if(!/^[A-Za-z0-9.-]+$/.test(r))throw Error("Profile identifier may contain only letters, numbers, dots, and hyphens");let i=await (0,a.getPrismaClient)();return await i.iosDeviceSettings.upsert({where:{id:y},create:{id:y,organizationName:t,profileIdentifier:r},update:{organizationName:t,profileIdentifier:r}}),this.getSettings()}async ensureProfileSigner(){let e=await this.rawSettings(),t=e.signerCertificatePem?await this.credentials.getText(n.CREDENTIALS.iosProfileSignerPrivateKey):null;return e.signerCertificatePem&&t?{...e,signerPrivateKeyPem:t}:this.regenerateProfileSigner()}async regenerateProfileSigner(){let e=await this.rawSettings(),r=await (0,t.generateProfileSigner)(e.organizationName);return await this.credentials.setText(n.CREDENTIALS.iosProfileSignerPrivateKey,r.privateKeyPem,async e=>{await e.iosDeviceSettings.update({where:{id:y},data:{signerCertificatePem:r.certificatePem,signerFingerprint:r.fingerprint,signerCreatedAt:r.createdAt,signerExpiresAt:r.expiresAt}})}),{...await this.rawSettings(),signerPrivateKeyPem:r.privateKeyPem}}async regenerateProfileSignerView(){return await this.regenerateProfileSigner(),this.getSettings()}async purgeExpiredEnrollments(e=new Date){let t=await (0,a.getPrismaClient)();await t.iosDeviceEnrollment.updateMany({where:{status:{in:["ISSUED","DOWNLOADED"]},expiresAt:{lt:e}},data:{status:"EXPIRED",failureCode:"TOKEN_EXPIRED"}}),await t.iosDeviceEnrollment.deleteMany({where:{deviceId:null,expiresAt:{lt:new Date(e.getTime()-6048e5)}}})}async createEnrollment(e){let i=b(e,"Device label",100);await this.purgeExpiredEnrollments(),await this.ensureProfileSigner();let n=(0,t.randomEnrollmentToken)(),s=new Date(Date.now()+18e5),o=await (0,a.getPrismaClient)();return{id:(await o.iosDeviceEnrollment.create({data:{id:(0,r.randomUUID)(),tokenHash:(0,t.sha256)(n),displayName:i,expiresAt:s}})).id,token:n,expiresAt:s}}async enrollmentForToken(e){if(!/^[A-Za-z0-9_-]{40,64}$/.test(e))throw new w("Enrollment token is invalid",404,"INVALID_TOKEN");let r=await (0,a.getPrismaClient)(),i=await r.iosDeviceEnrollment.findUnique({where:{tokenHash:(0,t.sha256)(e)}});if(!i)throw new w("Enrollment token is invalid",404,"INVALID_TOKEN");if(!i.consumedAt&&i.expiresAt.getTime()<Date.now())throw await r.iosDeviceEnrollment.update({where:{id:i.id},data:{status:"EXPIRED",failureCode:"TOKEN_EXPIRED"}}),new w("Enrollment token has expired",410,"TOKEN_EXPIRED");return i}async recordIp(e,t,i,n){if(!i)return;let s=await (0,a.getPrismaClient)();await s.iosDeviceIpObservation.upsert({where:{enrollmentId_source_ipAddress:{enrollmentId:e,source:t,ipAddress:i.address}},create:{id:(0,r.randomUUID)(),enrollmentId:e,deviceId:n??null,source:t,ipAddress:i.address,headerSource:i.source},update:{deviceId:n??void 0,headerSource:i.source}})}async enrollmentProfile(e,n,s){let o=await this.enrollmentForToken(e);if(o.consumedAt)throw new w("Enrollment has already completed",410,"TOKEN_CONSUMED");let l=await this.ensureProfileSigner();if(!l.signerCertificatePem||!l.signerPrivateKeyPem)throw new w("Profile signer is unavailable",503,"SIGNER_UNAVAILABLE");let u=function({token:e,publicOrigin:t,organizationName:a,profileIdentifier:n,payloadUuid:s=(0,r.randomUUID)().toUpperCase()}){let o=`${t}/api/public/ios/profile-response?token=${encodeURIComponent(e)}`;return(0,i.plistDocument)({PayloadContent:{URL:o,DeviceAttributes:["UDID","PRODUCT","VERSION"],Challenge:e},PayloadType:"Profile Service",PayloadVersion:1,PayloadIdentifier:n,PayloadUUID:s,PayloadDisplayName:`Register device for ${a}`,PayloadDescription:"Shares this device's identifier, product, and software version for development registration.",PayloadOrganization:a})}({token:e,publicOrigin:n,organizationName:l.organizationName,profileIdentifier:l.profileIdentifier}),c=await (0,t.signMobileConfig)(u,l.signerCertificatePem,l.signerPrivateKeyPem),d=await (0,a.getPrismaClient)();return await d.iosDeviceEnrollment.update({where:{id:o.id},data:{status:"DOWNLOADED",downloadedAt:o.downloadedAt??new Date,failureCode:null}}),await this.recordIp(o.id,"PROFILE_DOWNLOAD",s),c}async completeEnrollment(e,n,s){let o,l,u,c=await this.enrollmentForToken(e),d=(0,t.sha256)(n);if(c.consumedAt){if(c.responseDigest===d&&c.deviceId){let e=await (0,a.getPrismaClient)(),t=await e.iosDevice.findUnique({where:{id:c.deviceId},include:{enrollments:{orderBy:{createdAt:"desc"}},ipObservations:{orderBy:{observedAt:"desc"}}}});if(t)return t}throw new w("Enrollment token has already been consumed",409,"TOKEN_CONSUMED")}try{let r=function(e){if(!e||"object"!=typeof e||Array.isArray(e))throw Error("Device response plist must be a dictionary");return e}((0,i.parsePlist)(await (0,t.verifyAppleDeviceResponse)(n)));if(r.CHALLENGE!==e)throw Error("Device response challenge does not match");o=function(e){if("string"!=typeof e)throw Error("UDID is missing");let t=e.trim().toUpperCase();if(!/^(?:[A-F0-9]{40}|[A-F0-9]{8}-[A-F0-9]{16})$/.test(t))throw Error("UDID has an invalid format");return t}(r.UDID),l=v(r.PRODUCT,"Product",100),u=v(r.VERSION,"Software version",50)}catch(t){let e=await (0,a.getPrismaClient)();if(1!==(await e.iosDeviceEnrollment.updateMany({where:{id:c.id,consumedAt:null},data:{status:"FAILED",failureCode:"INVALID_DEVICE_RESPONSE"}})).count)throw new w("Enrollment token has already been consumed",409,"TOKEN_CONSUMED");throw new w(t instanceof Error?t.message:"Device response is invalid",400,"INVALID_DEVICE_RESPONSE")}let p=new Date,h=await (0,a.getPrismaClient)(),m=await h.$transaction(async e=>{if(1!==(await e.iosDeviceEnrollment.updateMany({where:{id:c.id,consumedAt:null},data:{status:"PROCESSING",consumedAt:p,responseDigest:d,failureCode:null}})).count){let t=await e.iosDeviceEnrollment.findUnique({where:{id:c.id}});if(t?.responseDigest===d&&t.deviceId){let r=await e.iosDevice.findUnique({where:{id:t.deviceId}});if(r)return r}throw new w("Enrollment token has already been consumed",409,"TOKEN_CONSUMED")}let t=await e.iosDevice.findUnique({where:{udid:o}}),i=t?await e.iosDevice.update({where:{id:t.id},data:{product:l,osVersion:u,lastSeenAt:p}}):await e.iosDevice.create({data:{id:(0,r.randomUUID)(),udid:o,displayName:c.displayName,product:l,osVersion:u,lastSeenAt:p}});return await e.iosDeviceEnrollment.update({where:{id:c.id},data:{deviceId:i.id,status:"COMPLETED",failureCode:null}}),await e.iosDeviceIpObservation.updateMany({where:{enrollmentId:c.id},data:{deviceId:i.id}}),s&&await e.iosDeviceIpObservation.upsert({where:{enrollmentId_source_ipAddress:{enrollmentId:c.id,source:"PROFILE_RESPONSE",ipAddress:s.address}},create:{id:(0,r.randomUUID)(),enrollmentId:c.id,deviceId:i.id,source:"PROFILE_RESPONSE",ipAddress:s.address,headerSource:s.source},update:{deviceId:i.id,headerSource:s.source}}),i});return this.changed(m.id),this.device(m.id)}async devices(e){return await this.purgeExpiredEnrollments(),await this.recoverStaleRegistrationClaims(),(await (0,a.getPrismaClient)()).iosDevice.findMany({where:e?{status:e}:void 0,include:{ipObservations:{orderBy:{observedAt:"desc"},take:1}},orderBy:[{createdAt:"desc"},{displayName:"asc"}]})}async device(e){return await this.recoverStaleRegistrationClaims(),(await (0,a.getPrismaClient)()).iosDevice.findUnique({where:{id:e},include:{enrollments:{orderBy:{createdAt:"desc"}},ipObservations:{orderBy:{observedAt:"desc"}}}})}async deviceFirmware(e){let t=await (0,a.getPrismaClient)(),r=await t.iosDevice.findUnique({where:{id:e},select:{product:!0}});if(!r)throw Error("Device not found");if(!r.product)return null;let i=this.firmwareCache.get(r.product);if(i&&i.expiresAt>Date.now())return i.value;let n=await g(r.product,this.fetcher);return this.firmwareCache.set(r.product,{expiresAt:Date.now()+9e5,value:n}),n}async renameDevice(e,t){let r=await (0,a.getPrismaClient)();return await r.iosDevice.update({where:{id:e},data:{displayName:b(t,"Device label",100)}}),this.changed(e),this.device(e)}async rejectDevice(e){let t=await (0,a.getPrismaClient)();if(1!==(await t.iosDevice.updateMany({where:{id:e,status:{in:["PENDING","REGISTRATION_FAILED"]}},data:{status:"REJECTED",registrationError:null}})).count)throw Error("This device cannot be rejected in its current state");return this.changed(e),this.device(e)}async deleteDevice(e){await this.recoverStaleRegistrationClaims();let t=await (0,a.getPrismaClient)(),r=await t.iosDevice.findUnique({where:{id:e}});if(!r)throw Error("Device not found");if("REGISTERING"===r.status||1!==(await t.iosDevice.deleteMany({where:{id:e,status:{not:"REGISTERING"}}})).count)throw Error("Wait for Apple registration to finish before deleting");return this.changed(e),!0}async appleDeveloperCredentials(e){let t=await this.credentials.getText(n.CREDENTIALS.appStoreConnectPrivateKey);if(!e.appStoreConnectIssuerId||!e.appStoreConnectKeyId||!t)throw Error("App Store Connect API credentials are not configured");return{issuerId:e.appStoreConnectIssuerId,keyId:e.appStoreConnectKeyId,privateKey:t}}async appleRequest(e,t,r={},i=""){try{return await new p(e,this.fetcher).request(t,r)}catch(n){let e;if(!(n instanceof c)){if(n instanceof Error&&n.message.includes("timed out"))throw Error("App Store Connect timed out; retry to reconcile the device");if(n instanceof Error&&n.message.includes("ES256 PKCS#8"))throw n;throw Error("Could not connect to App Store Connect")}let t=n.errors?.map(e=>e.detail||e.title||e.code).filter(Boolean).join("; "),r=`${n.errors?.map(e=>`${e.code??""} ${e.title??""} ${e.detail??""}`).join(" ")??""}`.toLowerCase(),a=401===n.status||403===n.status?"App Store Connect rejected the API key or its Certificates, Identifiers & Profiles access":429===n.status?"Apple rate-limited device registration; wait and retry":/maximum|device.?limit|limit.?reached/.test(r)?"The Apple Developer account has reached its annual device limit for this platform":/duplicate|already (?:exists|registered)/.test(r)?"Apple reports that this device already exists; retry registration to reconcile it":/invalid.{0,30}udid|udid.{0,30}invalid/.test(r)?"Apple rejected the UDID as invalid; re-enroll the device and try again":422===n.status?`Apple rejected the device data${t?`: ${t}`:""}`:t||`App Store Connect returned HTTP ${n.status}`;throw Error(i?(e=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a.replace(RegExp(e,"gi"),"[REDACTED]")):a)}}async verifyAppStoreCredentials(e){await this.appleRequest(e,"/v1/devices?limit=1")}async saveAppStoreConnectSettings(e){await this.rawSettings();let r=b(e.issuerId,"Issuer ID",100),i=b(e.keyId,"Key ID",100),a=e.privateKey?.trim()||await this.credentials.getText(n.CREDENTIALS.appStoreConnectPrivateKey);if(!a)throw Error("A .p8 private key is required");if(!a.includes("-----BEGIN PRIVATE KEY-----")||!a.includes("-----END PRIVATE KEY-----"))throw Error("The App Store Connect key must be a PKCS#8 .p8 private key");return await this.verifyAppStoreCredentials({issuerId:r,keyId:i,privateKey:a}),await this.credentials.setText(n.CREDENTIALS.appStoreConnectPrivateKey,a,async e=>{await e.iosDeviceSettings.update({where:{id:y},data:{appStoreConnectIssuerId:r,appStoreConnectKeyId:i,appStoreConnectPrivateKeyFingerprint:(0,t.sha256)(a).toUpperCase(),appStoreConnectVerifiedAt:new Date,appStoreConnectLastTestedAt:new Date,appStoreConnectVerificationError:null}})}),this.getSettings()}async testAppStoreConnectSettings(){let e=await this.rawSettings();if(!e.appStoreConnectIssuerId||!e.appStoreConnectKeyId)throw Error("App Store Connect API credentials are not configured");let t=await (0,a.getPrismaClient)();try{await this.verifyAppStoreCredentials(await this.appleDeveloperCredentials(e))}catch(r){let e=r instanceof Error?r.message:"Credential verification failed";throw await t.iosDeviceSettings.update({where:{id:y},data:{appStoreConnectVerifiedAt:null,appStoreConnectLastTestedAt:new Date,appStoreConnectVerificationError:e}}),Error(e)}return await t.iosDeviceSettings.update({where:{id:y},data:{appStoreConnectVerifiedAt:new Date,appStoreConnectLastTestedAt:new Date,appStoreConnectVerificationError:null}}),this.getSettings()}async clearAppStoreConnectSettings(){return await this.credentials.delete(n.CREDENTIALS.appStoreConnectPrivateKey,async e=>{await e.iosDeviceSettings.upsert({where:{id:y},create:{id:y},update:{appStoreConnectIssuerId:null,appStoreConnectKeyId:null,appStoreConnectPrivateKeyFingerprint:null,appStoreConnectVerifiedAt:null,appStoreConnectLastTestedAt:null,appStoreConnectVerificationError:null}})}),this.getSettings()}async registerDevice(e){await this.recoverStaleRegistrationClaims();let t=await this.rawSettings();if(!t.appStoreConnectIssuerId||!t.appStoreConnectKeyId||!t.appStoreConnectVerifiedAt)throw Error("Configure and verify an App Store Connect API key in Settings first");let r=await this.appleDeveloperCredentials(t),i=await (0,a.getPrismaClient)(),n=await i.iosDevice.findUnique({where:{id:e}});if(!n)throw Error("Device not found");let s=new Date;if(1!==(await i.iosDevice.updateMany({where:{id:e,status:{in:["PENDING","REGISTRATION_FAILED"]}},data:{status:"REGISTERING",registrationClaimedAt:s,registrationError:null}})).count)throw Error("This device cannot be registered in its current state");this.changed(e);try{let t=encodeURIComponent(n.udid),a=(await this.appleRequest(r,`/v1/devices?filter%5Budid%5D=${t}&limit=1`,{},n.udid)).data[0]??(await this.appleRequest(r,"/v1/devices",{method:"POST",body:JSON.stringify({data:{type:"devices",attributes:{name:n.displayName,platform:"IOS",udid:n.udid}}})},n.udid)).data;await i.iosDevice.updateMany({where:{id:e,status:"REGISTERING",registrationClaimedAt:s},data:{status:"REGISTERED",registrationClaimedAt:null,appleDeviceId:a.id,appleStatus:a.attributes.status??"ENABLED",registeredAt:new Date,registrationError:null}})}catch(r){let t=r instanceof Error?r.message:"Apple registration failed";throw await i.iosDevice.updateMany({where:{id:e,status:"REGISTERING",registrationClaimedAt:s},data:{status:"REGISTRATION_FAILED",registrationClaimedAt:null,registrationError:t}}),this.changed(e),Error(t)}return this.changed(e),this.device(e)}async exportTsv(){let e=await (0,a.getPrismaClient)();return["Device ID Device Name Device Platform",...(await e.iosDevice.findMany({where:{status:{not:"REJECTED"}},orderBy:{displayName:"asc"}})).map(e=>`${k(e.udid)} ${k(e.displayName)} ios`)].join("\n")}async recoverStaleRegistrationClaims(e=new Date){let t=await (0,a.getPrismaClient)();(await t.iosDevice.updateMany({where:{status:"REGISTERING",OR:[{registrationClaimedAt:null},{registrationClaimedAt:{lt:new Date(e.getTime()-3e5)}}]},data:{status:"REGISTRATION_FAILED",registrationClaimedAt:null,registrationError:"The previous Apple registration attempt was interrupted; retry registration"}})).count&&this.changed()}},"IosEnrollmentError",0,w],149721),e.s([],115354)},735255,e=>{"use strict";let t=Symbol("unattributed");function r(){return{inputTokens:0,outputTokens:0,cacheCreationTokens:0,cacheReadTokens:0,totalTokens:0,totalCost:0}}function i(e,t){e.inputTokens+=t.inputTokens,e.outputTokens+=t.outputTokens,e.cacheCreationTokens+=t.cacheCreationTokens,e.cacheReadTokens+=t.cacheReadTokens,e.totalTokens+=t.totalTokens,e.totalCost+=t.totalCost}function a(e,t){return t.totalCost-e.totalCost||t.totalTokens-e.totalTokens||(e.modelName??e.agentName??"").localeCompare(t.modelName??t.agentName??"")}e.s(["aggregateUsage",0,function(e){let n=new Map,s=r();for(let{agent:a,report:o}of e)for(let e of(i(s,o.totals),o.daily)){let s=n.get(e.period);s||(s={...r(),period:e.period,models:new Map,sourceSet:new Set},n.set(e.period,s)),i(s,e),e.metadata.agents.forEach(e=>s.sourceSet.add(e));let o=0;for(let t of e.modelBreakdowns){let n={inputTokens:t.inputTokens,outputTokens:t.outputTokens,cacheCreationTokens:t.cacheCreationTokens,cacheReadTokens:t.cacheReadTokens,totalTokens:t.inputTokens+t.outputTokens+t.cacheCreationTokens+t.cacheReadTokens,totalCost:t.cost};o+=n.totalTokens;let l=s.models.get(t.modelName);l||(l={...r(),modelName:t.modelName,agents:new Map},s.models.set(t.modelName,l)),i(l,n);let u=l.agents.get(a.id);u||(u={...r(),agentId:a.id,agentName:a.name,hostname:a.hostname,sources:[],sourceSet:new Set},l.agents.set(a.id,u)),i(u,n),e.metadata.agents.forEach(e=>u.sourceSet.add(e))}!function(e,i,a,n){if(n<=0)return;let s=e.models.get(t);s||(s={...r(),modelName:"Unattributed tokens",agents:new Map,unattributed:!0},e.models.set(t,s)),s.totalTokens+=n;let o=s.agents.get(i.id);o||(o={...r(),agentId:i.id,agentName:i.name,hostname:i.hostname,sources:[],sourceSet:new Set},s.agents.set(i.id,o)),o.totalTokens+=n,a.forEach(e=>o.sourceSet.add(e))}(s,a,e.metadata.agents,e.totalTokens-o)}return{totals:s,days:[...n.values()].sort((e,t)=>t.period.localeCompare(e.period)).map(e=>({inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheCreationTokens:e.cacheCreationTokens,cacheReadTokens:e.cacheReadTokens,totalTokens:e.totalTokens,totalCost:e.totalCost,period:e.period,sources:[...e.sourceSet].sort(),models:[...e.models.values()].sort(a).map(e=>({inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheCreationTokens:e.cacheCreationTokens,cacheReadTokens:e.cacheReadTokens,totalTokens:e.totalTokens,totalCost:e.totalCost,modelName:e.modelName,...e.unattributed?{unattributed:!0}:{},agents:[...e.agents.values()].sort(a).map(e=>({inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheCreationTokens:e.cacheCreationTokens,cacheReadTokens:e.cacheReadTokens,totalTokens:e.totalTokens,totalCost:e.totalCost,agentId:e.agentId,agentName:e.agentName,hostname:e.hostname,sources:[...e.sourceSet].sort()}))}))}))}},"filterUsageByDays",0,function(e,t,a=new Date){let n;if(null===t)return e;let s=new Date(a);s.setHours(0,0,0,0),s.setDate(s.getDate()-(t-1));let o=(n=e=>String(e).padStart(2,"0"),`${s.getFullYear()}-${n(s.getMonth()+1)}-${n(s.getDate())}`),l=e.days.filter(e=>e.period>=o),u=r();return l.forEach(e=>i(u,e)),{days:l,totals:u}}])},121717,483024,988349,e=>{"use strict";var t=e.i(666680),r=e.i(986847),i=e.i(735255),a=e.i(243783);e.i(805422);var n=e.i(694355),s=e.i(661983);let o=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]);e.s(["CcusageService",0,class{agentControlService;now;deadlineTimers;initialized;initializationPromise;completionObservers;constructor(e,t=()=>new Date){this.agentControlService=e,this.now=t,this.deadlineTimers=new Map,this.initialized=!1,this.initializationPromise=null,this.completionObservers=new Set}async initialize(){if(!this.initialized)return this.initializationPromise||(this.initializationPromise=this.restoreCollections().then(()=>{this.initialized=!0}).finally(()=>{this.initializationPromise=null})),this.initializationPromise}async restoreCollections(){let e=await (0,a.getPrismaClient)(),t=await e.ccusageCollection.findMany({where:{finishedAt:null},select:{id:!0}});await Promise.all(t.map(async({id:e})=>{await this.ensureJobs(e),await this.getCollection(e)}))}async collect(e){let r=e?.trim()||(0,t.randomUUID)();await this.ensureCollection(r);let i=await this.waitForCompletion(r);for(let e of this.completionObservers)try{await e(i)}catch(e){console.error("ccusage completion observer failed:",e instanceof Error?e.message:e)}return i}registerCompletionObserver(e){return this.completionObservers.add(e),()=>this.completionObservers.delete(e)}async getCollection(e){let t=await this.loadCollection(e);if(!t)return null;null===t.finishedAt&&t.deadlineAt.getTime()<=this.now().getTime()&&(await this.timeoutMembersWithoutJobs(t),await this.agentControlService.timeoutCollectionJobs(e),t=await this.loadCollection(e)??t);let r=this.snapshot(t);if("COMPLETED"===r.status&&null===t.finishedAt){let t=this.now(),i=await (0,a.getPrismaClient)();await i.ccusageCollection.updateMany({where:{id:e,finishedAt:null},data:{finishedAt:t}}),r.finishedAt=t.toISOString(),this.clearDeadline(e)}else"COLLECTING"===r.status&&this.scheduleDeadline(t);return r}async *subscribe(e){let t=s.agentEventBus.iterate((0,s.ccusageCollectionChangedTopic)(e));try{let r=await this.getCollection(e);for(r&&(yield r);;){if((await t.next()).done)return;let r=await this.getCollection(e);r&&(yield r)}}finally{await t.return?.()}}async ensureCollection(e){let t=await (0,a.getPrismaClient)(),i=await t.ccusageCollection.findUnique({where:{id:e},select:{id:!0}});if(!i){let a=await this.agentControlService.listAgents();try{i=await t.ccusageCollection.create({data:{id:e,deadlineAt:new Date(this.now().getTime()+15e4),agents:{create:a.map(e=>{var t;return{agentId:e.id,initialStatus:(t=this.now().getTime(),null!==e.lastSeenAt&&t-e.lastSeenAt.getTime()<=(0,n.agentOnlineWindowMs)(e)&&null===e.disconnectedAt?(function(e){try{let t=JSON.parse(e.capabilitiesJson);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}})(e).includes(r.CCUSAGE_REPORT_JOB_KIND)?"QUEUING":"UNSUPPORTED":"OFFLINE")}})}},select:{id:!0}}),this.publish(e)}catch(r){if(!(i=await t.ccusageCollection.findUnique({where:{id:e},select:{id:!0}})))throw r}}await this.ensureJobs(e);let s=await this.getCollection(e);if(s?.status==="COLLECTING"){let r=await t.ccusageCollection.findUnique({where:{id:e},select:{id:!0,deadlineAt:!0,finishedAt:!0}});r&&this.scheduleDeadline(r)}}async ensureJobs(e){let t=await (0,a.getPrismaClient)(),i=await t.ccusageCollection.findUnique({where:{id:e},select:{deadlineAt:!0,finishedAt:!0}});if(!i||i.finishedAt||i.deadlineAt.getTime()<=this.now().getTime())return;let n=await t.ccusageCollectionAgent.findMany({where:{collectionId:e,initialStatus:"QUEUING"},select:{agentId:!0}}),s=new Set((await t.agentJob.findMany({where:{ccusageCollectionId:e},select:{agentId:!0}})).map(({agentId:e})=>e));await Promise.all(n.filter(({agentId:e})=>!s.has(e)).map(async({agentId:i})=>{try{await this.agentControlService.createJob({agentId:i,kind:r.CCUSAGE_REPORT_JOB_KIND,payload:{},idempotencyKey:`ccusage:${e}`,timeoutSeconds:120,ccusageCollectionId:e})}catch(r){await t.ccusageCollectionAgent.update({where:{collectionId_agentId:{collectionId:e,agentId:i}},data:{initialStatus:"FAILED",error:r instanceof Error?r.message:String(r)}}),this.publish(e)}}))}async waitForCompletion(e){let t=s.agentEventBus.iterate((0,s.ccusageCollectionChangedTopic)(e));try{for(;;){let r=await this.getCollection(e);if(!r)throw Error("ccusage collection disappeared");if("COMPLETED"===r.status)return r;let i=Math.max(1,new Date(r.deadlineAt).getTime()-this.now().getTime()+25);await Promise.race([t.next(),new Promise(e=>setTimeout(e,i))])}}finally{await t.return?.()}}async loadCollection(e){return(await (0,a.getPrismaClient)()).ccusageCollection.findUnique({where:{id:e},include:{agents:{include:{agent:!0}},jobs:!0}})}async timeoutMembersWithoutJobs(e){let t=new Set(e.jobs.map(({agentId:e})=>e)),r=e.agents.filter(({agentId:e,initialStatus:r})=>"QUEUING"===r&&!t.has(e)).map(({agentId:e})=>e);if(0===r.length)return;let i=await (0,a.getPrismaClient)();(await i.ccusageCollectionAgent.updateMany({where:{collectionId:e.id,agentId:{in:r},initialStatus:"QUEUING"},data:{initialStatus:"TIMED_OUT"}})).count>0&&this.publish(e.id)}snapshot(e){let t=new Map(e.jobs.map(e=>[e.agentId,e])),a=e.agents.map(e=>(function(e,t){let i={agent:e.agent,jobId:t?.id??null};if("QUEUING"!==e.initialStatus)return{progress:{...i,status:e.initialStatus,error:e.error}};if(!t)return{progress:{...i,status:"QUEUING",error:e.error}};if("SUCCEEDED"!==t.status)return{progress:{...i,status:t.status,error:t.error}};try{let e=(0,r.parseCcusageJobResult)(null===t.resultJson?null:JSON.parse(t.resultJson));return{progress:{...i,status:"SUCCEEDED",error:null},report:e.report}}catch(e){return{progress:{...i,status:"INVALID",error:e instanceof Error?e.message:String(e)}}}})(e,t.get(e.agentId))),n=a.map(({progress:e})=>e),s=n.filter(({status:e})=>"OFFLINE"!==e&&"UNSUPPORTED"!==e),l=s.filter(({status:e})=>"INVALID"===e||o.has(e)),u=a.flatMap(({progress:e,report:t})=>t?[{agent:{id:e.agent.id,name:e.agent.name,hostname:e.agent.hostname},report:t}]:[]);return{id:e.id,status:l.length===s.length?"COMPLETED":"COLLECTING",createdAt:e.createdAt.toISOString(),deadlineAt:e.deadlineAt.toISOString(),finishedAt:e.finishedAt?.toISOString()??null,progress:{eligibleCount:s.length,finishedCount:l.length,successfulCount:s.filter(({status:e})=>"SUCCEEDED"===e).length,agents:n},aggregate:(0,i.aggregateUsage)(u)}}scheduleDeadline(e){if(e.finishedAt||this.deadlineTimers.has(e.id))return;let t=setTimeout(()=>{this.deadlineTimers.delete(e.id),this.expire(e.id)},Math.max(0,e.deadlineAt.getTime()-this.now().getTime()));t.unref?.(),this.deadlineTimers.set(e.id,t)}async expire(e){try{await this.agentControlService.timeoutCollectionJobs(e),await this.getCollection(e),this.publish(e)}catch(t){console.error(`Could not expire ccusage collection ${e}:`,t instanceof Error?t.message:t)}}clearDeadline(e){let t=this.deadlineTimers.get(e);t&&clearTimeout(t),this.deadlineTimers.delete(e)}publish(e){s.agentEventBus.publish((0,s.ccusageCollectionChangedTopic)(e),{ccusageCollectionChanged:{id:e}})}}],483024),e.s([],121717),e.s(["CodebaseBusyError",0,class extends Error{constructor(e="Another operation is active for this codebase"){super(e),this.name="CodebaseBusyError"}},"isCodebaseBusyError",0,function(e){return e instanceof Error&&"CodebaseBusyError"===e.name}],988349)},469719,733137,334512,e=>{"use strict";var t,r=e.i(127438),i=e.i(486618);function a(){let e,t,r;return{localeError:(e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}},t={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;return`Invalid input: expected ${e}, received ${n}`}case"invalid_value":if(1===a.values.length)return`Invalid input: expected ${i.stringifyPrimitive(a.values[0])}`;return`Invalid option: expected one of ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Too big: expected ${a.origin??"value"} to have ${t}${a.maximum.toString()} ${r.unit??"elements"}`;return`Too big: expected ${a.origin??"value"} to be ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Too small: expected ${a.origin} to have ${t}${a.minimum.toString()} ${r.unit}`;return`Too small: expected ${a.origin} to be ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Invalid string: must start with "${a.prefix}"`;if("ends_with"===a.format)return`Invalid string: must end with "${a.suffix}"`;if("includes"===a.format)return`Invalid string: must include "${a.includes}"`;if("regex"===a.format)return`Invalid string: must match pattern ${a.pattern}`;return`Invalid ${t[a.format]??a.format}`;case"not_multiple_of":return`Invalid number: must be a multiple of ${a.divisor}`;case"unrecognized_keys":return`Unrecognized key${a.keys.length>1?"s":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Invalid key in ${a.origin}`;case"invalid_union":if(a.options&&Array.isArray(a.options)&&a.options.length>0){let e=a.options.map(e=>`'${e}'`).join(" | ");return`Invalid discriminator value. Expected ${e}`}return"Invalid input";case"invalid_element":return`Invalid value in ${a.origin}`;default:return"Invalid input"}})}}(0,r.config)(a()),e.s([],654048),e.i(654048),e.s([],482811),e.i(482811);var n=e.i(715143),s=e.i(67021),o=e.i(639510);e.s(["$ZodAny",()=>o.$ZodAny,"$ZodArray",()=>o.$ZodArray,"$ZodBase64",()=>o.$ZodBase64,"$ZodBase64URL",()=>o.$ZodBase64URL,"$ZodBigInt",()=>o.$ZodBigInt,"$ZodBigIntFormat",()=>o.$ZodBigIntFormat,"$ZodBoolean",()=>o.$ZodBoolean,"$ZodCIDRv4",()=>o.$ZodCIDRv4,"$ZodCIDRv6",()=>o.$ZodCIDRv6,"$ZodCUID",()=>o.$ZodCUID,"$ZodCUID2",()=>o.$ZodCUID2,"$ZodCatch",()=>o.$ZodCatch,"$ZodCodec",()=>o.$ZodCodec,"$ZodCustom",()=>o.$ZodCustom,"$ZodCustomStringFormat",()=>o.$ZodCustomStringFormat,"$ZodDate",()=>o.$ZodDate,"$ZodDefault",()=>o.$ZodDefault,"$ZodDiscriminatedUnion",()=>o.$ZodDiscriminatedUnion,"$ZodE164",()=>o.$ZodE164,"$ZodEmail",()=>o.$ZodEmail,"$ZodEmoji",()=>o.$ZodEmoji,"$ZodEnum",()=>o.$ZodEnum,"$ZodExactOptional",()=>o.$ZodExactOptional,"$ZodFile",()=>o.$ZodFile,"$ZodFunction",()=>o.$ZodFunction,"$ZodGUID",()=>o.$ZodGUID,"$ZodIPv4",()=>o.$ZodIPv4,"$ZodIPv6",()=>o.$ZodIPv6,"$ZodISODate",()=>o.$ZodISODate,"$ZodISODateTime",()=>o.$ZodISODateTime,"$ZodISODuration",()=>o.$ZodISODuration,"$ZodISOTime",()=>o.$ZodISOTime,"$ZodIntersection",()=>o.$ZodIntersection,"$ZodJWT",()=>o.$ZodJWT,"$ZodKSUID",()=>o.$ZodKSUID,"$ZodLazy",()=>o.$ZodLazy,"$ZodLiteral",()=>o.$ZodLiteral,"$ZodMAC",()=>o.$ZodMAC,"$ZodMap",()=>o.$ZodMap,"$ZodNaN",()=>o.$ZodNaN,"$ZodNanoID",()=>o.$ZodNanoID,"$ZodNever",()=>o.$ZodNever,"$ZodNonOptional",()=>o.$ZodNonOptional,"$ZodNull",()=>o.$ZodNull,"$ZodNullable",()=>o.$ZodNullable,"$ZodNumber",()=>o.$ZodNumber,"$ZodNumberFormat",()=>o.$ZodNumberFormat,"$ZodObject",()=>o.$ZodObject,"$ZodObjectJIT",()=>o.$ZodObjectJIT,"$ZodOptional",()=>o.$ZodOptional,"$ZodPipe",()=>o.$ZodPipe,"$ZodPrefault",()=>o.$ZodPrefault,"$ZodPreprocess",()=>o.$ZodPreprocess,"$ZodPromise",()=>o.$ZodPromise,"$ZodReadonly",()=>o.$ZodReadonly,"$ZodRecord",()=>o.$ZodRecord,"$ZodSet",()=>o.$ZodSet,"$ZodString",()=>o.$ZodString,"$ZodStringFormat",()=>o.$ZodStringFormat,"$ZodSuccess",()=>o.$ZodSuccess,"$ZodSymbol",()=>o.$ZodSymbol,"$ZodTemplateLiteral",()=>o.$ZodTemplateLiteral,"$ZodTransform",()=>o.$ZodTransform,"$ZodTuple",()=>o.$ZodTuple,"$ZodType",()=>o.$ZodType,"$ZodULID",()=>o.$ZodULID,"$ZodURL",()=>o.$ZodURL,"$ZodUUID",()=>o.$ZodUUID,"$ZodUndefined",()=>o.$ZodUndefined,"$ZodUnion",()=>o.$ZodUnion,"$ZodUnknown",()=>o.$ZodUnknown,"$ZodVoid",()=>o.$ZodVoid,"$ZodXID",()=>o.$ZodXID,"$ZodXor",()=>o.$ZodXor,"clone",()=>i.clone,"isValidBase64",()=>o.isValidBase64,"isValidBase64URL",()=>o.isValidBase64URL,"isValidJWT",()=>o.isValidJWT],662429),e.i(662429);var l=e.i(236608),u=e.i(622824),c=e.i(486618),d=e.i(421131);function p(e,t,r,i){let a=Math.abs(e),n=a%10,s=a%100;return s>=11&&s<=19?i:1===n?t:n>=2&&n<=4?r:i}function h(e,t,r){return 1===Math.abs(e)?t:r}function m(e){if(!e)return"";let t=e[e.length-1];return e+(["ա","ե","ը","ի","ո","ու","օ"].includes(t)?"ն":"ը")}function f(){let e,t,r;return{localeError:(e={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}},t={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"},r={nan:"NaN",number:"លេខ",array:"អារេ (Array)",null:"គ្មានតម្លៃ (null)"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${a.expected} ប៉ុន្តែទទួលបាន ${n}`;return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${e} ប៉ុន្តែទទួលបាន ${n}`}case"invalid_value":if(1===a.values.length)return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${i.stringifyPrimitive(a.values[0])}`;return`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`ធំពេក៖ ត្រូវការ ${a.origin??"តម្លៃ"} ${t} ${a.maximum.toString()} ${r.unit??"ធាតុ"}`;return`ធំពេក៖ ត្រូវការ ${a.origin??"តម្លៃ"} ${t} ${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`តូចពេក៖ ត្រូវការ ${a.origin} ${t} ${a.minimum.toString()} ${r.unit}`;return`តូចពេក៖ ត្រូវការ ${a.origin} ${t} ${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${a.prefix}"`;if("ends_with"===a.format)return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${a.suffix}"`;if("includes"===a.format)return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${a.includes}"`;if("regex"===a.format)return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${a.pattern}`;return`មិនត្រឹមត្រូវ៖ ${t[a.format]??a.format}`;case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${a.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${a.origin}`;case"invalid_union":default:return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${a.origin}`}})}}e.s([],879113),e.i(879113);let g=e=>e.charAt(0).toUpperCase()+e.slice(1);function y(e){let t=Math.abs(e),r=t%10,i=t%100;return i>=11&&i<=19||0===r?"many":1===r?"one":"few"}function w(e,t,r,i){let a=Math.abs(e),n=a%10,s=a%100;return s>=11&&s<=19?i:1===n?t:n>=2&&n<=4?r:i}function b(){let e,t,r;return{localeError:(e={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}},t={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"},r={nan:"NaN",number:"число",array:"масив"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Неправильні вхідні дані: очікується instanceof ${a.expected}, отримано ${n}`;return`Неправильні вхідні дані: очікується ${e}, отримано ${n}`}case"invalid_value":if(1===a.values.length)return`Неправильні вхідні дані: очікується ${i.stringifyPrimitive(a.values[0])}`;return`Неправильна опція: очікується одне з ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Занадто велике: очікується, що ${a.origin??"значення"} ${r.verb} ${t}${a.maximum.toString()} ${r.unit??"елементів"}`;return`Занадто велике: очікується, що ${a.origin??"значення"} буде ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Занадто мале: очікується, що ${a.origin} ${r.verb} ${t}${a.minimum.toString()} ${r.unit}`;return`Занадто мале: очікується, що ${a.origin} буде ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Неправильний рядок: повинен починатися з "${a.prefix}"`;if("ends_with"===a.format)return`Неправильний рядок: повинен закінчуватися на "${a.suffix}"`;if("includes"===a.format)return`Неправильний рядок: повинен містити "${a.includes}"`;if("regex"===a.format)return`Неправильний рядок: повинен відповідати шаблону ${a.pattern}`;return`Неправильний ${t[a.format]??a.format}`;case"not_multiple_of":return`Неправильне число: повинно бути кратним ${a.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${a.keys.length>1?"і":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${a.origin}`;case"invalid_union":default:return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${a.origin}`}})}}e.s(["ar",0,function(){let e,t,r;return{localeError:(e={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}},t={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`مدخلات غير مقبولة: يفترض إدخال instanceof ${a.expected}، ولكن تم إدخال ${n}`;return`مدخلات غير مقبولة: يفترض إدخال ${e}، ولكن تم إدخال ${n}`}case"invalid_value":if(1===a.values.length)return`مدخلات غير مقبولة: يفترض إدخال ${i.stringifyPrimitive(a.values[0])}`;return`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return` أكبر من اللازم: يفترض أن تكون ${a.origin??"القيمة"} ${t} ${a.maximum.toString()} ${r.unit??"عنصر"}`;return`أكبر من اللازم: يفترض أن تكون ${a.origin??"القيمة"} ${t} ${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`أصغر من اللازم: يفترض لـ ${a.origin} أن يكون ${t} ${a.minimum.toString()} ${r.unit}`;return`أصغر من اللازم: يفترض لـ ${a.origin} أن يكون ${t} ${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`نَص غير مقبول: يجب أن يبدأ بـ "${a.prefix}"`;if("ends_with"===a.format)return`نَص غير مقبول: يجب أن ينتهي بـ "${a.suffix}"`;if("includes"===a.format)return`نَص غير مقبول: يجب أن يتضمَّن "${a.includes}"`;if("regex"===a.format)return`نَص غير مقبول: يجب أن يطابق النمط ${a.pattern}`;return`${t[a.format]??a.format} غير مقبول`;case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${a.divisor}`;case"unrecognized_keys":return`معرف${a.keys.length>1?"ات":""} غريب${a.keys.length>1?"ة":""}: ${i.joinValues(a.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${a.origin}`;case"invalid_union":default:return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${a.origin}`}})}},"az",0,function(){let e,t,r;return{localeError:(e={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}},t={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Yanlış dəyər: g\xf6zlənilən instanceof ${a.expected}, daxil olan ${n}`;return`Yanlış dəyər: g\xf6zlənilən ${e}, daxil olan ${n}`}case"invalid_value":if(1===a.values.length)return`Yanlış dəyər: g\xf6zlənilən ${i.stringifyPrimitive(a.values[0])}`;return`Yanlış se\xe7im: aşağıdakılardan biri olmalıdır: ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`\xc7ox b\xf6y\xfck: g\xf6zlənilən ${a.origin??"dəyər"} ${t}${a.maximum.toString()} ${r.unit??"element"}`;return`\xc7ox b\xf6y\xfck: g\xf6zlənilən ${a.origin??"dəyər"} ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`\xc7ox ki\xe7ik: g\xf6zlənilən ${a.origin} ${t}${a.minimum.toString()} ${r.unit}`;return`\xc7ox ki\xe7ik: g\xf6zlənilən ${a.origin} ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Yanlış mətn: "${a.prefix}" ilə başlamalıdır`;if("ends_with"===a.format)return`Yanlış mətn: "${a.suffix}" ilə bitməlidir`;if("includes"===a.format)return`Yanlış mətn: "${a.includes}" daxil olmalıdır`;if("regex"===a.format)return`Yanlış mətn: ${a.pattern} şablonuna uyğun olmalıdır`;return`Yanlış ${t[a.format]??a.format}`;case"not_multiple_of":return`Yanlış ədəd: ${a.divisor} ilə b\xf6l\xfcnə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan a\xe7ar${a.keys.length>1?"lar":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`${a.origin} daxilində yanlış a\xe7ar`;case"invalid_union":default:return"Yanlış dəyər";case"invalid_element":return`${a.origin} daxilində yanlış dəyər`}})}},"be",0,function(){let e,t,r;return{localeError:(e={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}},t={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"},r={nan:"NaN",number:"лік",array:"масіў"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Няправільны ўвод: чакаўся instanceof ${a.expected}, атрымана ${n}`;return`Няправільны ўвод: чакаўся ${e}, атрымана ${n}`}case"invalid_value":if(1===a.values.length)return`Няправільны ўвод: чакалася ${i.stringifyPrimitive(a.values[0])}`;return`Няправільны варыянт: чакаўся адзін з ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r){let e=p(Number(a.maximum),r.unit.one,r.unit.few,r.unit.many);return`Занадта вялікі: чакалася, што ${a.origin??"значэнне"} павінна ${r.verb} ${t}${a.maximum.toString()} ${e}`}return`Занадта вялікі: чакалася, што ${a.origin??"значэнне"} павінна быць ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r){let e=p(Number(a.minimum),r.unit.one,r.unit.few,r.unit.many);return`Занадта малы: чакалася, што ${a.origin} павінна ${r.verb} ${t}${a.minimum.toString()} ${e}`}return`Занадта малы: чакалася, што ${a.origin} павінна быць ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Няправільны радок: павінен пачынацца з "${a.prefix}"`;if("ends_with"===a.format)return`Няправільны радок: павінен заканчвацца на "${a.suffix}"`;if("includes"===a.format)return`Няправільны радок: павінен змяшчаць "${a.includes}"`;if("regex"===a.format)return`Няправільны радок: павінен адпавядаць шаблону ${a.pattern}`;return`Няправільны ${t[a.format]??a.format}`;case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${a.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${a.keys.length>1?"ключы":"ключ"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${a.origin}`;case"invalid_union":default:return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${a.origin}`}})}},"bg",0,function(){let e,t,r;return{localeError:(e={string:{unit:"символа",verb:"да съдържа"},file:{unit:"байта",verb:"да съдържа"},array:{unit:"елемента",verb:"да съдържа"},set:{unit:"елемента",verb:"да съдържа"}},t={regex:"вход",email:"имейл адрес",url:"URL",emoji:"емоджи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO време",date:"ISO дата",time:"ISO време",duration:"ISO продължителност",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"base64-кодиран низ",base64url:"base64url-кодиран низ",json_string:"JSON низ",e164:"E.164 номер",jwt:"JWT",template_literal:"вход"},r={nan:"NaN",number:"число",array:"масив"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Невалиден вход: очакван instanceof ${a.expected}, получен ${n}`;return`Невалиден вход: очакван ${e}, получен ${n}`}case"invalid_value":if(1===a.values.length)return`Невалиден вход: очакван ${i.stringifyPrimitive(a.values[0])}`;return`Невалидна опция: очаквано едно от ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Твърде голямо: очаква се ${a.origin??"стойност"} да съдържа ${t}${a.maximum.toString()} ${r.unit??"елемента"}`;return`Твърде голямо: очаква се ${a.origin??"стойност"} да бъде ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Твърде малко: очаква се ${a.origin} да съдържа ${t}${a.minimum.toString()} ${r.unit}`;return`Твърде малко: очаква се ${a.origin} да бъде ${t}${a.minimum.toString()}`}case"invalid_format":{if("starts_with"===a.format)return`Невалиден низ: трябва да започва с "${a.prefix}"`;if("ends_with"===a.format)return`Невалиден низ: трябва да завършва с "${a.suffix}"`;if("includes"===a.format)return`Невалиден низ: трябва да включва "${a.includes}"`;if("regex"===a.format)return`Невалиден низ: трябва да съвпада с ${a.pattern}`;let e="Невалиден";return"emoji"===a.format&&(e="Невалидно"),"datetime"===a.format&&(e="Невалидно"),"date"===a.format&&(e="Невалидна"),"time"===a.format&&(e="Невалидно"),"duration"===a.format&&(e="Невалидна"),`${e} ${t[a.format]??a.format}`}case"not_multiple_of":return`Невалидно число: трябва да бъде кратно на ${a.divisor}`;case"unrecognized_keys":return`Неразпознат${a.keys.length>1?"и":""} ключ${a.keys.length>1?"ове":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Невалиден ключ в ${a.origin}`;case"invalid_union":default:return"Невалиден вход";case"invalid_element":return`Невалидна стойност в ${a.origin}`}})}},"ca",0,function(){let e,t,r;return{localeError:(e={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}},t={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Tipus inv\xe0lid: s'esperava instanceof ${a.expected}, s'ha rebut ${n}`;return`Tipus inv\xe0lid: s'esperava ${e}, s'ha rebut ${n}`}case"invalid_value":if(1===a.values.length)return`Valor inv\xe0lid: s'esperava ${i.stringifyPrimitive(a.values[0])}`;return`Opci\xf3 inv\xe0lida: s'esperava una de ${i.joinValues(a.values," o ")}`;case"too_big":{let t=a.inclusive?"com a màxim":"menys de",r=e[a.origin]??null;if(r)return`Massa gran: s'esperava que ${a.origin??"el valor"} contingu\xe9s ${t} ${a.maximum.toString()} ${r.unit??"elements"}`;return`Massa gran: s'esperava que ${a.origin??"el valor"} fos ${t} ${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?"com a mínim":"més de",r=e[a.origin]??null;if(r)return`Massa petit: s'esperava que ${a.origin} contingu\xe9s ${t} ${a.minimum.toString()} ${r.unit}`;return`Massa petit: s'esperava que ${a.origin} fos ${t} ${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Format inv\xe0lid: ha de comen\xe7ar amb "${a.prefix}"`;if("ends_with"===a.format)return`Format inv\xe0lid: ha d'acabar amb "${a.suffix}"`;if("includes"===a.format)return`Format inv\xe0lid: ha d'incloure "${a.includes}"`;if("regex"===a.format)return`Format inv\xe0lid: ha de coincidir amb el patr\xf3 ${a.pattern}`;return`Format inv\xe0lid per a ${t[a.format]??a.format}`;case"not_multiple_of":return`N\xfamero inv\xe0lid: ha de ser m\xfaltiple de ${a.divisor}`;case"unrecognized_keys":return`Clau${a.keys.length>1?"s":""} no reconeguda${a.keys.length>1?"s":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Clau inv\xe0lida a ${a.origin}`;case"invalid_union":default:return"Entrada invàlida";case"invalid_element":return`Element inv\xe0lid a ${a.origin}`}})}},"cs",0,function(){let e,t,r;return{localeError:(e={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}},t={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"},r={nan:"NaN",number:"číslo",string:"řetězec",function:"funkce",array:"pole"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Neplatn\xfd vstup: oček\xe1v\xe1no instanceof ${a.expected}, obdrženo ${n}`;return`Neplatn\xfd vstup: oček\xe1v\xe1no ${e}, obdrženo ${n}`}case"invalid_value":if(1===a.values.length)return`Neplatn\xfd vstup: oček\xe1v\xe1no ${i.stringifyPrimitive(a.values[0])}`;return`Neplatn\xe1 možnost: oček\xe1v\xe1na jedna z hodnot ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Hodnota je př\xedliš velk\xe1: ${a.origin??"hodnota"} mus\xed m\xedt ${t}${a.maximum.toString()} ${r.unit??"prvků"}`;return`Hodnota je př\xedliš velk\xe1: ${a.origin??"hodnota"} mus\xed b\xfdt ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Hodnota je př\xedliš mal\xe1: ${a.origin??"hodnota"} mus\xed m\xedt ${t}${a.minimum.toString()} ${r.unit??"prvků"}`;return`Hodnota je př\xedliš mal\xe1: ${a.origin??"hodnota"} mus\xed b\xfdt ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Neplatn\xfd řetězec: mus\xed zač\xednat na "${a.prefix}"`;if("ends_with"===a.format)return`Neplatn\xfd řetězec: mus\xed končit na "${a.suffix}"`;if("includes"===a.format)return`Neplatn\xfd řetězec: mus\xed obsahovat "${a.includes}"`;if("regex"===a.format)return`Neplatn\xfd řetězec: mus\xed odpov\xeddat vzoru ${a.pattern}`;return`Neplatn\xfd form\xe1t ${t[a.format]??a.format}`;case"not_multiple_of":return`Neplatn\xe9 č\xedslo: mus\xed b\xfdt n\xe1sobkem ${a.divisor}`;case"unrecognized_keys":return`Nezn\xe1m\xe9 kl\xedče: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Neplatn\xfd kl\xedč v ${a.origin}`;case"invalid_union":default:return"Neplatný vstup";case"invalid_element":return`Neplatn\xe1 hodnota v ${a.origin}`}})}},"da",0,function(){let e,t,r;return{localeError:(e={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}},t={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},r={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Ugyldigt input: forventede instanceof ${a.expected}, fik ${n}`;return`Ugyldigt input: forventede ${e}, fik ${n}`}case"invalid_value":if(1===a.values.length)return`Ugyldig v\xe6rdi: forventede ${i.stringifyPrimitive(a.values[0])}`;return`Ugyldigt valg: forventede en af f\xf8lgende ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",i=e[a.origin]??null,n=r[a.origin]??a.origin;if(i)return`For stor: forventede ${n??"value"} ${i.verb} ${t} ${a.maximum.toString()} ${i.unit??"elementer"}`;return`For stor: forventede ${n??"value"} havde ${t} ${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",i=e[a.origin]??null,n=r[a.origin]??a.origin;if(i)return`For lille: forventede ${n} ${i.verb} ${t} ${a.minimum.toString()} ${i.unit}`;return`For lille: forventede ${n} havde ${t} ${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Ugyldig streng: skal starte med "${a.prefix}"`;if("ends_with"===a.format)return`Ugyldig streng: skal ende med "${a.suffix}"`;if("includes"===a.format)return`Ugyldig streng: skal indeholde "${a.includes}"`;if("regex"===a.format)return`Ugyldig streng: skal matche m\xf8nsteret ${a.pattern}`;return`Ugyldig ${t[a.format]??a.format}`;case"not_multiple_of":return`Ugyldigt tal: skal v\xe6re deleligt med ${a.divisor}`;case"unrecognized_keys":return`${a.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Ugyldig n\xf8gle i ${a.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig v\xe6rdi i ${a.origin}`;default:return"Ugyldigt input"}})}},"de",0,function(){let e,t,r;return{localeError:(e={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}},t={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},r={nan:"NaN",number:"Zahl",array:"Array"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Ung\xfcltige Eingabe: erwartet instanceof ${a.expected}, erhalten ${n}`;return`Ung\xfcltige Eingabe: erwartet ${e}, erhalten ${n}`}case"invalid_value":if(1===a.values.length)return`Ung\xfcltige Eingabe: erwartet ${i.stringifyPrimitive(a.values[0])}`;return`Ung\xfcltige Option: erwartet eine von ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Zu gro\xdf: erwartet, dass ${a.origin??"Wert"} ${t}${a.maximum.toString()} ${r.unit??"Elemente"} hat`;return`Zu gro\xdf: erwartet, dass ${a.origin??"Wert"} ${t}${a.maximum.toString()} ist`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Zu klein: erwartet, dass ${a.origin} ${t}${a.minimum.toString()} ${r.unit} hat`;return`Zu klein: erwartet, dass ${a.origin} ${t}${a.minimum.toString()} ist`}case"invalid_format":if("starts_with"===a.format)return`Ung\xfcltiger String: muss mit "${a.prefix}" beginnen`;if("ends_with"===a.format)return`Ung\xfcltiger String: muss mit "${a.suffix}" enden`;if("includes"===a.format)return`Ung\xfcltiger String: muss "${a.includes}" enthalten`;if("regex"===a.format)return`Ung\xfcltiger String: muss dem Muster ${a.pattern} entsprechen`;return`Ung\xfcltig: ${t[a.format]??a.format}`;case"not_multiple_of":return`Ung\xfcltige Zahl: muss ein Vielfaches von ${a.divisor} sein`;case"unrecognized_keys":return`${a.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Ung\xfcltiger Schl\xfcssel in ${a.origin}`;case"invalid_union":default:return"Ungültige Eingabe";case"invalid_element":return`Ung\xfcltiger Wert in ${a.origin}`}})}},"el",0,function(){let e,t,r;return{localeError:(e={string:{unit:"χαρακτήρες",verb:"να έχει"},file:{unit:"bytes",verb:"να έχει"},array:{unit:"στοιχεία",verb:"να έχει"},set:{unit:"στοιχεία",verb:"να έχει"},map:{unit:"καταχωρήσεις",verb:"να έχει"}},t={regex:"είσοδος",email:"διεύθυνση email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ημερομηνία και ώρα",date:"ISO ημερομηνία",time:"ISO ώρα",duration:"ISO διάρκεια",ipv4:"διεύθυνση IPv4",ipv6:"διεύθυνση IPv6",mac:"διεύθυνση MAC",cidrv4:"εύρος IPv4",cidrv6:"εύρος IPv6",base64:"συμβολοσειρά κωδικοποιημένη σε base64",base64url:"συμβολοσειρά κωδικοποιημένη σε base64url",json_string:"συμβολοσειρά JSON",e164:"αριθμός E.164",jwt:"JWT",template_literal:"είσοδος"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if("string"==typeof a.expected&&/^[A-Z]/.test(a.expected))return`Μη έγκυρη είσοδος: αναμενόταν instanceof ${a.expected}, λήφθηκε ${n}`;return`Μη έγκυρη είσοδος: αναμενόταν ${e}, λήφθηκε ${n}`}case"invalid_value":if(1===a.values.length)return`Μη έγκυρη είσοδος: αναμενόταν ${i.stringifyPrimitive(a.values[0])}`;return`Μη έγκυρη επιλογή: αναμενόταν ένα από ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Πολύ μεγάλο: αναμενόταν ${a.origin??"τιμή"} να έχει ${t}${a.maximum.toString()} ${r.unit??"στοιχεία"}`;return`Πολύ μεγάλο: αναμενόταν ${a.origin??"τιμή"} να είναι ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Πολύ μικρό: αναμενόταν ${a.origin} να έχει ${t}${a.minimum.toString()} ${r.unit}`;return`Πολύ μικρό: αναμενόταν ${a.origin} να είναι ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Μη έγκυρη συμβολοσειρά: πρέπει να ξεκινά με "${a.prefix}"`;if("ends_with"===a.format)return`Μη έγκυρη συμβολοσειρά: πρέπει να τελειώνει με "${a.suffix}"`;if("includes"===a.format)return`Μη έγκυρη συμβολοσειρά: πρέπει να περιέχει "${a.includes}"`;if("regex"===a.format)return`Μη έγκυρη συμβολοσειρά: πρέπει να ταιριάζει με το μοτίβο ${a.pattern}`;return`Μη έγκυρο: ${t[a.format]??a.format}`;case"not_multiple_of":return`Μη έγκυρος αριθμός: πρέπει να είναι πολλαπλάσιο του ${a.divisor}`;case"unrecognized_keys":return`Άγνωστ${a.keys.length>1?"α":"ο"} κλειδ${a.keys.length>1?"ιά":"ί"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Μη έγκυρο κλειδί στο ${a.origin}`;case"invalid_union":default:return"Μη έγκυρη είσοδος";case"invalid_element":return`Μη έγκυρη τιμή στο ${a.origin}`}})}},"en",0,a,"eo",0,function(){let e,t,r;return{localeError:(e={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}},t={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},r={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Nevalida enigo: atendiĝis instanceof ${a.expected}, riceviĝis ${n}`;return`Nevalida enigo: atendiĝis ${e}, riceviĝis ${n}`}case"invalid_value":if(1===a.values.length)return`Nevalida enigo: atendiĝis ${i.stringifyPrimitive(a.values[0])}`;return`Nevalida opcio: atendiĝis unu el ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Tro granda: atendiĝis ke ${a.origin??"valoro"} havu ${t}${a.maximum.toString()} ${r.unit??"elementojn"}`;return`Tro granda: atendiĝis ke ${a.origin??"valoro"} havu ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Tro malgranda: atendiĝis ke ${a.origin} havu ${t}${a.minimum.toString()} ${r.unit}`;return`Tro malgranda: atendiĝis ke ${a.origin} estu ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Nevalida karaktraro: devas komenciĝi per "${a.prefix}"`;if("ends_with"===a.format)return`Nevalida karaktraro: devas finiĝi per "${a.suffix}"`;if("includes"===a.format)return`Nevalida karaktraro: devas inkluzivi "${a.includes}"`;if("regex"===a.format)return`Nevalida karaktraro: devas kongrui kun la modelo ${a.pattern}`;return`Nevalida ${t[a.format]??a.format}`;case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${a.divisor}`;case"unrecognized_keys":return`Nekonata${a.keys.length>1?"j":""} ŝlosilo${a.keys.length>1?"j":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${a.origin}`;case"invalid_union":default:return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${a.origin}`}})}},"es",0,function(){let e,t,r;return{localeError:(e={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}},t={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},r={nan:"NaN",string:"texto",number:"número",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"número grande",symbol:"símbolo",undefined:"indefinido",null:"nulo",function:"función",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeración",union:"unión",literal:"literal",promise:"promesa",void:"vacío",never:"nunca",unknown:"desconocido",any:"cualquiera"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Entrada inv\xe1lida: se esperaba instanceof ${a.expected}, recibido ${n}`;return`Entrada inv\xe1lida: se esperaba ${e}, recibido ${n}`}case"invalid_value":if(1===a.values.length)return`Entrada inv\xe1lida: se esperaba ${i.stringifyPrimitive(a.values[0])}`;return`Opci\xf3n inv\xe1lida: se esperaba una de ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",i=e[a.origin]??null,n=r[a.origin]??a.origin;if(i)return`Demasiado grande: se esperaba que ${n??"valor"} tuviera ${t}${a.maximum.toString()} ${i.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${n??"valor"} fuera ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",i=e[a.origin]??null,n=r[a.origin]??a.origin;if(i)return`Demasiado peque\xf1o: se esperaba que ${n} tuviera ${t}${a.minimum.toString()} ${i.unit}`;return`Demasiado peque\xf1o: se esperaba que ${n} fuera ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Cadena inv\xe1lida: debe comenzar con "${a.prefix}"`;if("ends_with"===a.format)return`Cadena inv\xe1lida: debe terminar en "${a.suffix}"`;if("includes"===a.format)return`Cadena inv\xe1lida: debe incluir "${a.includes}"`;if("regex"===a.format)return`Cadena inv\xe1lida: debe coincidir con el patr\xf3n ${a.pattern}`;return`Inv\xe1lido ${t[a.format]??a.format}`;case"not_multiple_of":return`N\xfamero inv\xe1lido: debe ser m\xfaltiplo de ${a.divisor}`;case"unrecognized_keys":return`Llave${a.keys.length>1?"s":""} desconocida${a.keys.length>1?"s":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Llave inv\xe1lida en ${r[a.origin]??a.origin}`;case"invalid_union":default:return"Entrada inválida";case"invalid_element":return`Valor inv\xe1lido en ${r[a.origin]??a.origin}`}})}},"fa",0,function(){let e,t,r;return{localeError:(e={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}},t={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"},r={nan:"NaN",number:"عدد",array:"آرایه"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`ورودی نامعتبر: می‌بایست instanceof ${a.expected} می‌بود، ${n} دریافت شد`;return`ورودی نامعتبر: می‌بایست ${e} می‌بود، ${n} دریافت شد`}case"invalid_value":if(1===a.values.length)return`ورودی نامعتبر: می‌بایست ${i.stringifyPrimitive(a.values[0])} می‌بود`;return`گزینه نامعتبر: می‌بایست یکی از ${i.joinValues(a.values,"|")} می‌بود`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`خیلی بزرگ: ${a.origin??"مقدار"} باید ${t}${a.maximum.toString()} ${r.unit??"عنصر"} باشد`;return`خیلی بزرگ: ${a.origin??"مقدار"} باید ${t}${a.maximum.toString()} باشد`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`خیلی کوچک: ${a.origin} باید ${t}${a.minimum.toString()} ${r.unit} باشد`;return`خیلی کوچک: ${a.origin} باید ${t}${a.minimum.toString()} باشد`}case"invalid_format":if("starts_with"===a.format)return`رشته نامعتبر: باید با "${a.prefix}" شروع شود`;if("ends_with"===a.format)return`رشته نامعتبر: باید با "${a.suffix}" تمام شود`;if("includes"===a.format)return`رشته نامعتبر: باید شامل "${a.includes}" باشد`;if("regex"===a.format)return`رشته نامعتبر: باید با الگوی ${a.pattern} مطابقت داشته باشد`;return`${t[a.format]??a.format} نامعتبر`;case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${a.divisor} باشد`;case"unrecognized_keys":return`کلید${a.keys.length>1?"های":""} ناشناس: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${a.origin}`;case"invalid_union":default:return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${a.origin}`}})}},"fi",0,function(){let e,t,r;return{localeError:(e={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}},t={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Virheellinen tyyppi: odotettiin instanceof ${a.expected}, oli ${n}`;return`Virheellinen tyyppi: odotettiin ${e}, oli ${n}`}case"invalid_value":if(1===a.values.length)return`Virheellinen sy\xf6te: t\xe4ytyy olla ${i.stringifyPrimitive(a.values[0])}`;return`Virheellinen valinta: t\xe4ytyy olla yksi seuraavista: ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Liian suuri: ${r.subject} t\xe4ytyy olla ${t}${a.maximum.toString()} ${r.unit}`.trim();return`Liian suuri: arvon t\xe4ytyy olla ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Liian pieni: ${r.subject} t\xe4ytyy olla ${t}${a.minimum.toString()} ${r.unit}`.trim();return`Liian pieni: arvon t\xe4ytyy olla ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Virheellinen sy\xf6te: t\xe4ytyy alkaa "${a.prefix}"`;if("ends_with"===a.format)return`Virheellinen sy\xf6te: t\xe4ytyy loppua "${a.suffix}"`;if("includes"===a.format)return`Virheellinen sy\xf6te: t\xe4ytyy sis\xe4lt\xe4\xe4 "${a.includes}"`;if("regex"===a.format)return`Virheellinen sy\xf6te: t\xe4ytyy vastata s\xe4\xe4nn\xf6llist\xe4 lauseketta ${a.pattern}`;return`Virheellinen ${t[a.format]??a.format}`;case"not_multiple_of":return`Virheellinen luku: t\xe4ytyy olla luvun ${a.divisor} monikerta`;case"unrecognized_keys":return`${a.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}})}},"fr",0,function(){let e,t,r;return{localeError:(e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}},t={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},r={string:"chaîne",number:"nombre",int:"entier",boolean:"booléen",bigint:"grand entier",symbol:"symbole",undefined:"indéfini",null:"null",never:"jamais",void:"vide",date:"date",array:"tableau",object:"objet",tuple:"tuple",record:"enregistrement",map:"carte",set:"ensemble",file:"fichier",nonoptional:"non-optionnel",nan:"NaN",function:"fonction"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Entr\xe9e invalide : instanceof ${a.expected} attendu, ${n} re\xe7u`;return`Entr\xe9e invalide : ${e} attendu, ${n} re\xe7u`}case"invalid_value":if(1===a.values.length)return`Entr\xe9e invalide : ${i.stringifyPrimitive(a.values[0])} attendu`;return`Option invalide : une valeur parmi ${i.joinValues(a.values,"|")} attendue`;case"too_big":{let t=a.inclusive?"<=":"<",i=e[a.origin]??null;if(i)return`Trop grand : ${r[a.origin]??"valeur"} doit ${i.verb} ${t}${a.maximum.toString()} ${i.unit??"élément(s)"}`;return`Trop grand : ${r[a.origin]??"valeur"} doit \xeatre ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",i=e[a.origin]??null;if(i)return`Trop petit : ${r[a.origin]??"valeur"} doit ${i.verb} ${t}${a.minimum.toString()} ${i.unit}`;return`Trop petit : ${r[a.origin]??"valeur"} doit \xeatre ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Cha\xeene invalide : doit commencer par "${a.prefix}"`;if("ends_with"===a.format)return`Cha\xeene invalide : doit se terminer par "${a.suffix}"`;if("includes"===a.format)return`Cha\xeene invalide : doit inclure "${a.includes}"`;if("regex"===a.format)return`Cha\xeene invalide : doit correspondre au mod\xe8le ${a.pattern}`;return`${t[a.format]??a.format} invalide`;case"not_multiple_of":return`Nombre invalide : doit \xeatre un multiple de ${a.divisor}`;case"unrecognized_keys":return`Cl\xe9${a.keys.length>1?"s":""} non reconnue${a.keys.length>1?"s":""} : ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Cl\xe9 invalide dans ${a.origin}`;case"invalid_union":default:return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${a.origin}`}})}},"frCA",0,function(){let e,t,r;return{localeError:(e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}},t={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Entr\xe9e invalide : attendu instanceof ${a.expected}, re\xe7u ${n}`;return`Entr\xe9e invalide : attendu ${e}, re\xe7u ${n}`}case"invalid_value":if(1===a.values.length)return`Entr\xe9e invalide : attendu ${i.stringifyPrimitive(a.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"≤":"<",r=e[a.origin]??null;if(r)return`Trop grand : attendu que ${a.origin??"la valeur"} ait ${t}${a.maximum.toString()} ${r.unit}`;return`Trop grand : attendu que ${a.origin??"la valeur"} soit ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?"≥":">",r=e[a.origin]??null;if(r)return`Trop petit : attendu que ${a.origin} ait ${t}${a.minimum.toString()} ${r.unit}`;return`Trop petit : attendu que ${a.origin} soit ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Cha\xeene invalide : doit commencer par "${a.prefix}"`;if("ends_with"===a.format)return`Cha\xeene invalide : doit se terminer par "${a.suffix}"`;if("includes"===a.format)return`Cha\xeene invalide : doit inclure "${a.includes}"`;if("regex"===a.format)return`Cha\xeene invalide : doit correspondre au motif ${a.pattern}`;return`${t[a.format]??a.format} invalide`;case"not_multiple_of":return`Nombre invalide : doit \xeatre un multiple de ${a.divisor}`;case"unrecognized_keys":return`Cl\xe9${a.keys.length>1?"s":""} non reconnue${a.keys.length>1?"s":""} : ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Cl\xe9 invalide dans ${a.origin}`;case"invalid_union":default:return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${a.origin}`}})}},"he",0,function(){let e,t,r,a,n,s,o,l,u;return{localeError:(e={string:{label:"מחרוזת",gender:"f"},number:{label:"מספר",gender:"m"},boolean:{label:"ערך בוליאני",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"תאריך",gender:"m"},array:{label:"מערך",gender:"m"},object:{label:"אובייקט",gender:"m"},null:{label:"ערך ריק (null)",gender:"m"},undefined:{label:"ערך לא מוגדר (undefined)",gender:"m"},symbol:{label:"סימבול (Symbol)",gender:"m"},function:{label:"פונקציה",gender:"f"},map:{label:"מפה (Map)",gender:"f"},set:{label:"קבוצה (Set)",gender:"f"},file:{label:"קובץ",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"ערך לא ידוע",gender:"m"},value:{label:"ערך",gender:"m"}},t={string:{unit:"תווים",shortLabel:"קצר",longLabel:"ארוך"},file:{unit:"בייטים",shortLabel:"קטן",longLabel:"גדול"},array:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},set:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},number:{unit:"",shortLabel:"קטן",longLabel:"גדול"}},r=t=>t?e[t]:void 0,a=t=>{let i=r(t);return i?i.label:t??e.unknown.label},n=e=>`ה${a(e)}`,s=e=>{let t=r(e);return"f"===(t?.gender??"m")?"צריכה להיות":"צריך להיות"},o=e=>e?t[e]??null:null,l={regex:{label:"קלט",gender:"m"},email:{label:"כתובת אימייל",gender:"f"},url:{label:"כתובת רשת",gender:"f"},emoji:{label:"אימוג'י",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"תאריך וזמן ISO",gender:"m"},date:{label:"תאריך ISO",gender:"m"},time:{label:"זמן ISO",gender:"m"},duration:{label:"משך זמן ISO",gender:"m"},ipv4:{label:"כתובת IPv4",gender:"f"},ipv6:{label:"כתובת IPv6",gender:"f"},cidrv4:{label:"טווח IPv4",gender:"m"},cidrv6:{label:"טווח IPv6",gender:"m"},base64:{label:"מחרוזת בבסיס 64",gender:"f"},base64url:{label:"מחרוזת בבסיס 64 לכתובות רשת",gender:"f"},json_string:{label:"מחרוזת JSON",gender:"f"},e164:{label:"מספר E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"קלט",gender:"m"},includes:{label:"קלט",gender:"m"},lowercase:{label:"קלט",gender:"m"},starts_with:{label:"קלט",gender:"m"},uppercase:{label:"קלט",gender:"m"}},u={nan:"NaN"},t=>{switch(t.code){case"invalid_type":{let r=t.expected,n=u[r??""]??a(r),s=i.parsedType(t.input),o=u[s]??e[s]?.label??s;if(/^[A-Z]/.test(t.expected))return`קלט לא תקין: צריך להיות instanceof ${t.expected}, התקבל ${o}`;return`קלט לא תקין: צריך להיות ${n}, התקבל ${o}`}case"invalid_value":{if(1===t.values.length)return`ערך לא תקין: הערך חייב להיות ${i.stringifyPrimitive(t.values[0])}`;let e=t.values.map(e=>i.stringifyPrimitive(e));if(2===t.values.length)return`ערך לא תקין: האפשרויות המתאימות הן ${e[0]} או ${e[1]}`;let r=e[e.length-1],a=e.slice(0,-1).join(", ");return`ערך לא תקין: האפשרויות המתאימות הן ${a} או ${r}`}case"too_big":{let e=o(t.origin),r=n(t.origin??"value");if("string"===t.origin)return`${e?.longLabel??"ארוך"} מדי: ${r} צריכה להכיל ${t.maximum.toString()} ${e?.unit??""} ${t.inclusive?"או פחות":"לכל היותר"}`.trim();if("number"===t.origin){let e=t.inclusive?`קטן או שווה ל-${t.maximum}`:`קטן מ-${t.maximum}`;return`גדול מדי: ${r} צריך להיות ${e}`}if("array"===t.origin||"set"===t.origin){let i="set"===t.origin?"צריכה":"צריך",a=t.inclusive?`${t.maximum} ${e?.unit??""} או פחות`:`פחות מ-${t.maximum} ${e?.unit??""}`;return`גדול מדי: ${r} ${i} להכיל ${a}`.trim()}let i=t.inclusive?"<=":"<",a=s(t.origin??"value");if(e?.unit)return`${e.longLabel} מדי: ${r} ${a} ${i}${t.maximum.toString()} ${e.unit}`;return`${e?.longLabel??"גדול"} מדי: ${r} ${a} ${i}${t.maximum.toString()}`}case"too_small":{let e=o(t.origin),r=n(t.origin??"value");if("string"===t.origin)return`${e?.shortLabel??"קצר"} מדי: ${r} צריכה להכיל ${t.minimum.toString()} ${e?.unit??""} ${t.inclusive?"או יותר":"לפחות"}`.trim();if("number"===t.origin){let e=t.inclusive?`גדול או שווה ל-${t.minimum}`:`גדול מ-${t.minimum}`;return`קטן מדי: ${r} צריך להיות ${e}`}if("array"===t.origin||"set"===t.origin){let i="set"===t.origin?"צריכה":"צריך";if(1===t.minimum&&t.inclusive){let e=(t.origin,"לפחות פריט אחד");return`קטן מדי: ${r} ${i} להכיל ${e}`}let a=t.inclusive?`${t.minimum} ${e?.unit??""} או יותר`:`יותר מ-${t.minimum} ${e?.unit??""}`;return`קטן מדי: ${r} ${i} להכיל ${a}`.trim()}let i=t.inclusive?">=":">",a=s(t.origin??"value");if(e?.unit)return`${e.shortLabel} מדי: ${r} ${a} ${i}${t.minimum.toString()} ${e.unit}`;return`${e?.shortLabel??"קטן"} מדי: ${r} ${a} ${i}${t.minimum.toString()}`}case"invalid_format":{if("starts_with"===t.format)return`המחרוזת חייבת להתחיל ב "${t.prefix}"`;if("ends_with"===t.format)return`המחרוזת חייבת להסתיים ב "${t.suffix}"`;if("includes"===t.format)return`המחרוזת חייבת לכלול "${t.includes}"`;if("regex"===t.format)return`המחרוזת חייבת להתאים לתבנית ${t.pattern}`;let e=l[t.format],r=e?.label??t.format,i=e?.gender??"m";return`${r} לא ${"f"===i?"תקינה":"תקין"}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${t.divisor}`;case"unrecognized_keys":return`מפתח${t.keys.length>1?"ות":""} לא מזוה${t.keys.length>1?"ים":"ה"}: ${i.joinValues(t.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":default:return"קלט לא תקין";case"invalid_element":{let e=n(t.origin??"array");return`ערך לא תקין ב${e}`}}})}},"hr",0,function(){let e,t,r;return{localeError:(e={string:{unit:"znakova",verb:"imati"},file:{unit:"bajtova",verb:"imati"},array:{unit:"stavki",verb:"imati"},set:{unit:"stavki",verb:"imati"}},t={regex:"unos",email:"email adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum i vrijeme",date:"ISO datum",time:"ISO vrijeme",duration:"ISO trajanje",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"IPv4 raspon",cidrv6:"IPv6 raspon",base64:"base64 kodirani tekst",base64url:"base64url kodirani tekst",json_string:"JSON tekst",e164:"E.164 broj",jwt:"JWT",template_literal:"unos"},r={nan:"NaN",string:"tekst",number:"broj",boolean:"boolean",array:"niz",object:"objekt",set:"skup",file:"datoteka",date:"datum",bigint:"bigint",symbol:"simbol",undefined:"undefined",null:"null",function:"funkcija",map:"mapa"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Neispravan unos: očekuje se instanceof ${a.expected}, a primljeno je ${n}`;return`Neispravan unos: očekuje se ${e}, a primljeno je ${n}`}case"invalid_value":if(1===a.values.length)return`Neispravna vrijednost: očekivano ${i.stringifyPrimitive(a.values[0])}`;return`Neispravna opcija: očekivano jedno od ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",i=e[a.origin]??null,n=r[a.origin]??a.origin;if(i)return`Preveliko: očekivano da ${n??"vrijednost"} ima ${t}${a.maximum.toString()} ${i.unit??"elemenata"}`;return`Preveliko: očekivano da ${n??"vrijednost"} bude ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",i=e[a.origin]??null,n=r[a.origin]??a.origin;if(i)return`Premalo: očekivano da ${n} ima ${t}${a.minimum.toString()} ${i.unit}`;return`Premalo: očekivano da ${n} bude ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Neispravan tekst: mora započinjati s "${a.prefix}"`;if("ends_with"===a.format)return`Neispravan tekst: mora završavati s "${a.suffix}"`;if("includes"===a.format)return`Neispravan tekst: mora sadržavati "${a.includes}"`;if("regex"===a.format)return`Neispravan tekst: mora odgovarati uzorku ${a.pattern}`;return`Neispravna ${t[a.format]??a.format}`;case"not_multiple_of":return`Neispravan broj: mora biti višekratnik od ${a.divisor}`;case"unrecognized_keys":return`Neprepoznat${a.keys.length>1?"i ključevi":" ključ"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Neispravan ključ u ${r[a.origin]??a.origin}`;case"invalid_union":default:return"Neispravan unos";case"invalid_element":return`Neispravna vrijednost u ${r[a.origin]??a.origin}`}})}},"hu",0,function(){let e,t,r;return{localeError:(e={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}},t={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"},r={nan:"NaN",number:"szám",array:"tömb"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`\xc9rv\xe9nytelen bemenet: a v\xe1rt \xe9rt\xe9k instanceof ${a.expected}, a kapott \xe9rt\xe9k ${n}`;return`\xc9rv\xe9nytelen bemenet: a v\xe1rt \xe9rt\xe9k ${e}, a kapott \xe9rt\xe9k ${n}`}case"invalid_value":if(1===a.values.length)return`\xc9rv\xe9nytelen bemenet: a v\xe1rt \xe9rt\xe9k ${i.stringifyPrimitive(a.values[0])}`;return`\xc9rv\xe9nytelen opci\xf3: valamelyik \xe9rt\xe9k v\xe1rt ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`T\xfal nagy: ${a.origin??"érték"} m\xe9rete t\xfal nagy ${t}${a.maximum.toString()} ${r.unit??"elem"}`;return`T\xfal nagy: a bemeneti \xe9rt\xe9k ${a.origin??"érték"} t\xfal nagy: ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`T\xfal kicsi: a bemeneti \xe9rt\xe9k ${a.origin} m\xe9rete t\xfal kicsi ${t}${a.minimum.toString()} ${r.unit}`;return`T\xfal kicsi: a bemeneti \xe9rt\xe9k ${a.origin} t\xfal kicsi ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`\xc9rv\xe9nytelen string: "${a.prefix}" \xe9rt\xe9kkel kell kezdődnie`;if("ends_with"===a.format)return`\xc9rv\xe9nytelen string: "${a.suffix}" \xe9rt\xe9kkel kell v\xe9gződnie`;if("includes"===a.format)return`\xc9rv\xe9nytelen string: "${a.includes}" \xe9rt\xe9ket kell tartalmaznia`;if("regex"===a.format)return`\xc9rv\xe9nytelen string: ${a.pattern} mint\xe1nak kell megfelelnie`;return`\xc9rv\xe9nytelen ${t[a.format]??a.format}`;case"not_multiple_of":return`\xc9rv\xe9nytelen sz\xe1m: ${a.divisor} t\xf6bbsz\xf6r\xf6s\xe9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${a.keys.length>1?"s":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`\xc9rv\xe9nytelen kulcs ${a.origin}`;case"invalid_union":default:return"Érvénytelen bemenet";case"invalid_element":return`\xc9rv\xe9nytelen \xe9rt\xe9k: ${a.origin}`}})}},"hy",0,function(){let e,t,r;return{localeError:(e={string:{unit:{one:"նշան",many:"նշաններ"},verb:"ունենալ"},file:{unit:{one:"բայթ",many:"բայթեր"},verb:"ունենալ"},array:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"},set:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"}},t={regex:"մուտք",email:"էլ. հասցե",url:"URL",emoji:"էմոջի",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ամսաթիվ և ժամ",date:"ISO ամսաթիվ",time:"ISO ժամ",duration:"ISO տևողություն",ipv4:"IPv4 հասցե",ipv6:"IPv6 հասցե",cidrv4:"IPv4 միջակայք",cidrv6:"IPv6 միջակայք",base64:"base64 ձևաչափով տող",base64url:"base64url ձևաչափով տող",json_string:"JSON տող",e164:"E.164 համար",jwt:"JWT",template_literal:"մուտք"},r={nan:"NaN",number:"թիվ",array:"զանգված"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Սխալ մուտքագրում․ սպասվում էր instanceof ${a.expected}, ստացվել է ${n}`;return`Սխալ մուտքագրում․ սպասվում էր ${e}, ստացվել է ${n}`}case"invalid_value":if(1===a.values.length)return`Սխալ մուտքագրում․ սպասվում էր ${i.stringifyPrimitive(a.values[1])}`;return`Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r){let e=h(Number(a.maximum),r.unit.one,r.unit.many);return`Չափազանց մեծ արժեք․ սպասվում է, որ ${m(a.origin??"արժեք")} կունենա ${t}${a.maximum.toString()} ${e}`}return`Չափազանց մեծ արժեք․ սպասվում է, որ ${m(a.origin??"արժեք")} լինի ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r){let e=h(Number(a.minimum),r.unit.one,r.unit.many);return`Չափազանց փոքր արժեք․ սպասվում է, որ ${m(a.origin)} կունենա ${t}${a.minimum.toString()} ${e}`}return`Չափազանց փոքր արժեք․ սպասվում է, որ ${m(a.origin)} լինի ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Սխալ տող․ պետք է սկսվի "${a.prefix}"-ով`;if("ends_with"===a.format)return`Սխալ տող․ պետք է ավարտվի "${a.suffix}"-ով`;if("includes"===a.format)return`Սխալ տող․ պետք է պարունակի "${a.includes}"`;if("regex"===a.format)return`Սխալ տող․ պետք է համապատասխանի ${a.pattern} ձևաչափին`;return`Սխալ ${t[a.format]??a.format}`;case"not_multiple_of":return`Սխալ թիվ․ պետք է բազմապատիկ լինի ${a.divisor}-ի`;case"unrecognized_keys":return`Չճանաչված բանալի${a.keys.length>1?"ներ":""}. ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Սխալ բանալի ${m(a.origin)}-ում`;case"invalid_union":default:return"Սխալ մուտքագրում";case"invalid_element":return`Սխալ արժեք ${m(a.origin)}-ում`}})}},"id",0,function(){let e,t,r;return{localeError:(e={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}},t={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Input tidak valid: diharapkan instanceof ${a.expected}, diterima ${n}`;return`Input tidak valid: diharapkan ${e}, diterima ${n}`}case"invalid_value":if(1===a.values.length)return`Input tidak valid: diharapkan ${i.stringifyPrimitive(a.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Terlalu besar: diharapkan ${a.origin??"value"} memiliki ${t}${a.maximum.toString()} ${r.unit??"elemen"}`;return`Terlalu besar: diharapkan ${a.origin??"value"} menjadi ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Terlalu kecil: diharapkan ${a.origin} memiliki ${t}${a.minimum.toString()} ${r.unit}`;return`Terlalu kecil: diharapkan ${a.origin} menjadi ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`String tidak valid: harus dimulai dengan "${a.prefix}"`;if("ends_with"===a.format)return`String tidak valid: harus berakhir dengan "${a.suffix}"`;if("includes"===a.format)return`String tidak valid: harus menyertakan "${a.includes}"`;if("regex"===a.format)return`String tidak valid: harus sesuai pola ${a.pattern}`;return`${t[a.format]??a.format} tidak valid`;case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${a.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${a.keys.length>1?"s":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${a.origin}`;case"invalid_union":default:return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${a.origin}`}})}},"is",0,function(){let e,t,r;return{localeError:(e={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}},t={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"},r={nan:"NaN",number:"númer",array:"fylki"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Rangt gildi: \xde\xfa sl\xf3st inn ${n} \xfear sem \xe1 a\xf0 vera instanceof ${a.expected}`;return`Rangt gildi: \xde\xfa sl\xf3st inn ${n} \xfear sem \xe1 a\xf0 vera ${e}`}case"invalid_value":if(1===a.values.length)return`Rangt gildi: gert r\xe1\xf0 fyrir ${i.stringifyPrimitive(a.values[0])}`;return`\xd3gilt val: m\xe1 vera eitt af eftirfarandi ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Of st\xf3rt: gert er r\xe1\xf0 fyrir a\xf0 ${a.origin??"gildi"} hafi ${t}${a.maximum.toString()} ${r.unit??"hluti"}`;return`Of st\xf3rt: gert er r\xe1\xf0 fyrir a\xf0 ${a.origin??"gildi"} s\xe9 ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Of l\xedti\xf0: gert er r\xe1\xf0 fyrir a\xf0 ${a.origin} hafi ${t}${a.minimum.toString()} ${r.unit}`;return`Of l\xedti\xf0: gert er r\xe1\xf0 fyrir a\xf0 ${a.origin} s\xe9 ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`\xd3gildur strengur: ver\xf0ur a\xf0 byrja \xe1 "${a.prefix}"`;if("ends_with"===a.format)return`\xd3gildur strengur: ver\xf0ur a\xf0 enda \xe1 "${a.suffix}"`;if("includes"===a.format)return`\xd3gildur strengur: ver\xf0ur a\xf0 innihalda "${a.includes}"`;if("regex"===a.format)return`\xd3gildur strengur: ver\xf0ur a\xf0 fylgja mynstri ${a.pattern}`;return`Rangt ${t[a.format]??a.format}`;case"not_multiple_of":return`R\xf6ng tala: ver\xf0ur a\xf0 vera margfeldi af ${a.divisor}`;case"unrecognized_keys":return`\xd3\xfeekkt ${a.keys.length>1?"ir lyklar":"ur lykill"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Rangur lykill \xed ${a.origin}`;case"invalid_union":default:return"Rangt gildi";case"invalid_element":return`Rangt gildi \xed ${a.origin}`}})}},"it",0,function(){let e,t,r;return{localeError:(e={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}},t={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},r={nan:"NaN",number:"numero",array:"vettore"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Input non valido: atteso instanceof ${a.expected}, ricevuto ${n}`;return`Input non valido: atteso ${e}, ricevuto ${n}`}case"invalid_value":if(1===a.values.length)return`Input non valido: atteso ${i.stringifyPrimitive(a.values[0])}`;return`Opzione non valida: atteso uno tra ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Troppo grande: ${a.origin??"valore"} deve avere ${t}${a.maximum.toString()} ${r.unit??"elementi"}`;return`Troppo grande: ${a.origin??"valore"} deve essere ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Troppo piccolo: ${a.origin} deve avere ${t}${a.minimum.toString()} ${r.unit}`;return`Troppo piccolo: ${a.origin} deve essere ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Stringa non valida: deve iniziare con "${a.prefix}"`;if("ends_with"===a.format)return`Stringa non valida: deve terminare con "${a.suffix}"`;if("includes"===a.format)return`Stringa non valida: deve includere "${a.includes}"`;if("regex"===a.format)return`Stringa non valida: deve corrispondere al pattern ${a.pattern}`;return`Input non valido: ${t[a.format]??a.format}`;case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${a.divisor}`;case"unrecognized_keys":return`Chiav${a.keys.length>1?"i":"e"} non riconosciut${a.keys.length>1?"e":"a"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${a.origin}`;case"invalid_union":default:return"Input non valido";case"invalid_element":return`Valore non valido in ${a.origin}`}})}},"ja",0,function(){let e,t,r;return{localeError:(e={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}},t={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"},r={nan:"NaN",number:"数値",array:"配列"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`無効な入力: instanceof ${a.expected}が期待されましたが、${n}が入力されました`;return`無効な入力: ${e}が期待されましたが、${n}が入力されました`}case"invalid_value":if(1===a.values.length)return`無効な入力: ${i.stringifyPrimitive(a.values[0])}が期待されました`;return`無効な選択: ${i.joinValues(a.values,"、")}のいずれかである必要があります`;case"too_big":{let t=a.inclusive?"以下である":"より小さい",r=e[a.origin]??null;if(r)return`大きすぎる値: ${a.origin??"値"}は${a.maximum.toString()}${r.unit??"要素"}${t}必要があります`;return`大きすぎる値: ${a.origin??"値"}は${a.maximum.toString()}${t}必要があります`}case"too_small":{let t=a.inclusive?"以上である":"より大きい",r=e[a.origin]??null;if(r)return`小さすぎる値: ${a.origin}は${a.minimum.toString()}${r.unit}${t}必要があります`;return`小さすぎる値: ${a.origin}は${a.minimum.toString()}${t}必要があります`}case"invalid_format":if("starts_with"===a.format)return`無効な文字列: "${a.prefix}"で始まる必要があります`;if("ends_with"===a.format)return`無効な文字列: "${a.suffix}"で終わる必要があります`;if("includes"===a.format)return`無効な文字列: "${a.includes}"を含む必要があります`;if("regex"===a.format)return`無効な文字列: パターン${a.pattern}に一致する必要があります`;return`無効な${t[a.format]??a.format}`;case"not_multiple_of":return`無効な数値: ${a.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${a.keys.length>1?"群":""}: ${i.joinValues(a.keys,"、")}`;case"invalid_key":return`${a.origin}内の無効なキー`;case"invalid_union":default:return"無効な入力";case"invalid_element":return`${a.origin}内の無効な値`}})}},"ka",0,function(){let e,t,r;return{localeError:(e={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}},t={regex:"შეყვანა",email:"ელ-ფოსტის მისამართი",url:"URL",emoji:"ემოჯი",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"თარიღი-დრო",date:"თარიღი",time:"დრო",duration:"ხანგრძლივობა",ipv4:"IPv4 მისამართი",ipv6:"IPv6 მისამართი",cidrv4:"IPv4 დიაპაზონი",cidrv6:"IPv6 დიაპაზონი",base64:"base64-კოდირებული ველი",base64url:"base64url-კოდირებული ველი",json_string:"JSON ველი",e164:"E.164 ნომერი",jwt:"JWT",template_literal:"შეყვანა"},r={nan:"NaN",number:"რიცხვი",string:"ველი",boolean:"ბულეანი",function:"ფუნქცია",array:"მასივი"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`არასწორი შეყვანა: მოსალოდნელი instanceof ${a.expected}, მიღებული ${n}`;return`არასწორი შეყვანა: მოსალოდნელი ${e}, მიღებული ${n}`}case"invalid_value":if(1===a.values.length)return`არასწორი შეყვანა: მოსალოდნელი ${i.stringifyPrimitive(a.values[0])}`;return`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${i.joinValues(a.values,"|")}-დან`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`ზედმეტად დიდი: მოსალოდნელი ${a.origin??"მნიშვნელობა"} ${r.verb} ${t}${a.maximum.toString()} ${r.unit}`;return`ზედმეტად დიდი: მოსალოდნელი ${a.origin??"მნიშვნელობა"} იყოს ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`ზედმეტად პატარა: მოსალოდნელი ${a.origin} ${r.verb} ${t}${a.minimum.toString()} ${r.unit}`;return`ზედმეტად პატარა: მოსალოდნელი ${a.origin} იყოს ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`არასწორი ველი: უნდა იწყებოდეს "${a.prefix}"-ით`;if("ends_with"===a.format)return`არასწორი ველი: უნდა მთავრდებოდეს "${a.suffix}"-ით`;if("includes"===a.format)return`არასწორი ველი: უნდა შეიცავდეს "${a.includes}"-ს`;if("regex"===a.format)return`არასწორი ველი: უნდა შეესაბამებოდეს შაბლონს ${a.pattern}`;return`არასწორი ${t[a.format]??a.format}`;case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${a.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${a.keys.length>1?"ები":"ი"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${a.origin}-ში`;case"invalid_union":default:return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${a.origin}-ში`}})}},"kh",0,function(){return f()},"km",0,f,"ko",0,function(){let e,t,r;return{localeError:(e={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}},t={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`잘못된 입력: 예상 타입은 instanceof ${a.expected}, 받은 타입은 ${n}입니다`;return`잘못된 입력: 예상 타입은 ${e}, 받은 타입은 ${n}입니다`}case"invalid_value":if(1===a.values.length)return`잘못된 입력: 값은 ${i.stringifyPrimitive(a.values[0])} 이어야 합니다`;return`잘못된 옵션: ${i.joinValues(a.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{let t=a.inclusive?"이하":"미만",r="미만"===t?"이어야 합니다":"여야 합니다",i=e[a.origin]??null,n=i?.unit??"요소";if(i)return`${a.origin??"값"}이 너무 큽니다: ${a.maximum.toString()}${n} ${t}${r}`;return`${a.origin??"값"}이 너무 큽니다: ${a.maximum.toString()} ${t}${r}`}case"too_small":{let t=a.inclusive?"이상":"초과",r="이상"===t?"이어야 합니다":"여야 합니다",i=e[a.origin]??null,n=i?.unit??"요소";if(i)return`${a.origin??"값"}이 너무 작습니다: ${a.minimum.toString()}${n} ${t}${r}`;return`${a.origin??"값"}이 너무 작습니다: ${a.minimum.toString()} ${t}${r}`}case"invalid_format":if("starts_with"===a.format)return`잘못된 문자열: "${a.prefix}"(으)로 시작해야 합니다`;if("ends_with"===a.format)return`잘못된 문자열: "${a.suffix}"(으)로 끝나야 합니다`;if("includes"===a.format)return`잘못된 문자열: "${a.includes}"을(를) 포함해야 합니다`;if("regex"===a.format)return`잘못된 문자열: 정규식 ${a.pattern} 패턴과 일치해야 합니다`;return`잘못된 ${t[a.format]??a.format}`;case"not_multiple_of":return`잘못된 숫자: ${a.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`잘못된 키: ${a.origin}`;case"invalid_union":default:return"잘못된 입력";case"invalid_element":return`잘못된 값: ${a.origin}`}})}},"lt",0,function(){return{localeError:(()=>{let e={string:{unit:{one:"simbolis",few:"simboliai",many:"simbolių"},verb:{smaller:{inclusive:"turi būti ne ilgesnė kaip",notInclusive:"turi būti trumpesnė kaip"},bigger:{inclusive:"turi būti ne trumpesnė kaip",notInclusive:"turi būti ilgesnė kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"baitų"},verb:{smaller:{inclusive:"turi būti ne didesnis kaip",notInclusive:"turi būti mažesnis kaip"},bigger:{inclusive:"turi būti ne mažesnis kaip",notInclusive:"turi būti didesnis kaip"}}},array:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}},set:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}}};function t(t,r,i,a){let n=e[t]??null;return null===n?n:{unit:n.unit[r],verb:n.verb[a][i?"inclusive":"notInclusive"]}}let r={regex:"įvestis",email:"el. pašto adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukmė",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 užkoduota eilutė",base64url:"base64url užkoduota eilutė",json_string:"JSON eilutė",e164:"E.164 numeris",jwt:"JWT",template_literal:"įvestis"},a={nan:"NaN",number:"skaičius",bigint:"sveikasis skaičius",string:"eilutė",boolean:"loginė reikšmė",undefined:"neapibrėžta reikšmė",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulinė reikšmė"};return e=>{switch(e.code){case"invalid_type":{let t=a[e.expected]??e.expected,r=i.parsedType(e.input),n=a[r]??r;if(/^[A-Z]/.test(e.expected))return`Gautas tipas ${n}, o tikėtasi - instanceof ${e.expected}`;return`Gautas tipas ${n}, o tikėtasi - ${t}`}case"invalid_value":if(1===e.values.length)return`Privalo būti ${i.stringifyPrimitive(e.values[0])}`;return`Privalo būti vienas iš ${i.joinValues(e.values,"|")} pasirinkimų`;case"too_big":{let r=a[e.origin]??e.origin,i=t(e.origin,y(Number(e.maximum)),e.inclusive??!1,"smaller");if(i?.verb)return`${g(r??e.origin??"reikšmė")} ${i.verb} ${e.maximum.toString()} ${i.unit??"elementų"}`;let n=e.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${g(r??e.origin??"reikšmė")} turi būti ${n} ${e.maximum.toString()} ${i?.unit}`}case"too_small":{let r=a[e.origin]??e.origin,i=t(e.origin,y(Number(e.minimum)),e.inclusive??!1,"bigger");if(i?.verb)return`${g(r??e.origin??"reikšmė")} ${i.verb} ${e.minimum.toString()} ${i.unit??"elementų"}`;let n=e.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${g(r??e.origin??"reikšmė")} turi būti ${n} ${e.minimum.toString()} ${i?.unit}`}case"invalid_format":if("starts_with"===e.format)return`Eilutė privalo prasidėti "${e.prefix}"`;if("ends_with"===e.format)return`Eilutė privalo pasibaigti "${e.suffix}"`;if("includes"===e.format)return`Eilutė privalo įtraukti "${e.includes}"`;if("regex"===e.format)return`Eilutė privalo atitikti ${e.pattern}`;return`Neteisingas ${r[e.format]??e.format}`;case"not_multiple_of":return`Skaičius privalo būti ${e.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${e.keys.length>1?"i":"as"} rakt${e.keys.length>1?"ai":"as"}: ${i.joinValues(e.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":default:return"Klaidinga įvestis";case"invalid_element":{let t=a[e.origin]??e.origin;return`${g(t??e.origin??"reikšmė")} turi klaidingą įvestį`}}}})()}},"mk",0,function(){let e,t,r;return{localeError:(e={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}},t={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"},r={nan:"NaN",number:"број",array:"низа"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Грешен внес: се очекува instanceof ${a.expected}, примено ${n}`;return`Грешен внес: се очекува ${e}, примено ${n}`}case"invalid_value":if(1===a.values.length)return`Invalid input: expected ${i.stringifyPrimitive(a.values[0])}`;return`Грешана опција: се очекува една ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Премногу голем: се очекува ${a.origin??"вредноста"} да има ${t}${a.maximum.toString()} ${r.unit??"елементи"}`;return`Премногу голем: се очекува ${a.origin??"вредноста"} да биде ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Премногу мал: се очекува ${a.origin} да има ${t}${a.minimum.toString()} ${r.unit}`;return`Премногу мал: се очекува ${a.origin} да биде ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Неважечка низа: мора да започнува со "${a.prefix}"`;if("ends_with"===a.format)return`Неважечка низа: мора да завршува со "${a.suffix}"`;if("includes"===a.format)return`Неважечка низа: мора да вклучува "${a.includes}"`;if("regex"===a.format)return`Неважечка низа: мора да одгоара на патернот ${a.pattern}`;return`Invalid ${t[a.format]??a.format}`;case"not_multiple_of":return`Грешен број: мора да биде делив со ${a.divisor}`;case"unrecognized_keys":return`${a.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${a.origin}`;case"invalid_union":default:return"Грешен внес";case"invalid_element":return`Грешна вредност во ${a.origin}`}})}},"ms",0,function(){let e,t,r;return{localeError:(e={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}},t={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},r={nan:"NaN",number:"nombor"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Input tidak sah: dijangka instanceof ${a.expected}, diterima ${n}`;return`Input tidak sah: dijangka ${e}, diterima ${n}`}case"invalid_value":if(1===a.values.length)return`Input tidak sah: dijangka ${i.stringifyPrimitive(a.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Terlalu besar: dijangka ${a.origin??"nilai"} ${r.verb} ${t}${a.maximum.toString()} ${r.unit??"elemen"}`;return`Terlalu besar: dijangka ${a.origin??"nilai"} adalah ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Terlalu kecil: dijangka ${a.origin} ${r.verb} ${t}${a.minimum.toString()} ${r.unit}`;return`Terlalu kecil: dijangka ${a.origin} adalah ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`String tidak sah: mesti bermula dengan "${a.prefix}"`;if("ends_with"===a.format)return`String tidak sah: mesti berakhir dengan "${a.suffix}"`;if("includes"===a.format)return`String tidak sah: mesti mengandungi "${a.includes}"`;if("regex"===a.format)return`String tidak sah: mesti sepadan dengan corak ${a.pattern}`;return`${t[a.format]??a.format} tidak sah`;case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${a.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${a.origin}`;case"invalid_union":default:return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${a.origin}`}})}},"nl",0,function(){let e,t,r;return{localeError:(e={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}},t={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},r={nan:"NaN",number:"getal"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Ongeldige invoer: verwacht instanceof ${a.expected}, ontving ${n}`;return`Ongeldige invoer: verwacht ${e}, ontving ${n}`}case"invalid_value":if(1===a.values.length)return`Ongeldige invoer: verwacht ${i.stringifyPrimitive(a.values[0])}`;return`Ongeldige optie: verwacht \xe9\xe9n van ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null,i="date"===a.origin?"laat":"string"===a.origin?"lang":"groot";if(r)return`Te ${i}: verwacht dat ${a.origin??"waarde"} ${t}${a.maximum.toString()} ${r.unit??"elementen"} ${r.verb}`;return`Te ${i}: verwacht dat ${a.origin??"waarde"} ${t}${a.maximum.toString()} is`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null,i="date"===a.origin?"vroeg":"string"===a.origin?"kort":"klein";if(r)return`Te ${i}: verwacht dat ${a.origin} ${t}${a.minimum.toString()} ${r.unit} ${r.verb}`;return`Te ${i}: verwacht dat ${a.origin} ${t}${a.minimum.toString()} is`}case"invalid_format":if("starts_with"===a.format)return`Ongeldige tekst: moet met "${a.prefix}" beginnen`;if("ends_with"===a.format)return`Ongeldige tekst: moet op "${a.suffix}" eindigen`;if("includes"===a.format)return`Ongeldige tekst: moet "${a.includes}" bevatten`;if("regex"===a.format)return`Ongeldige tekst: moet overeenkomen met patroon ${a.pattern}`;return`Ongeldig: ${t[a.format]??a.format}`;case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${a.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${a.keys.length>1?"s":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${a.origin}`;case"invalid_union":default:return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${a.origin}`}})}},"no",0,function(){let e,t,r;return{localeError:(e={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}},t={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},r={nan:"NaN",number:"tall",array:"liste"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Ugyldig input: forventet instanceof ${a.expected}, fikk ${n}`;return`Ugyldig input: forventet ${e}, fikk ${n}`}case"invalid_value":if(1===a.values.length)return`Ugyldig verdi: forventet ${i.stringifyPrimitive(a.values[0])}`;return`Ugyldig valg: forventet en av ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`For stor(t): forventet ${a.origin??"value"} til \xe5 ha ${t}${a.maximum.toString()} ${r.unit??"elementer"}`;return`For stor(t): forventet ${a.origin??"value"} til \xe5 ha ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`For lite(n): forventet ${a.origin} til \xe5 ha ${t}${a.minimum.toString()} ${r.unit}`;return`For lite(n): forventet ${a.origin} til \xe5 ha ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Ugyldig streng: m\xe5 starte med "${a.prefix}"`;if("ends_with"===a.format)return`Ugyldig streng: m\xe5 ende med "${a.suffix}"`;if("includes"===a.format)return`Ugyldig streng: m\xe5 inneholde "${a.includes}"`;if("regex"===a.format)return`Ugyldig streng: m\xe5 matche m\xf8nsteret ${a.pattern}`;return`Ugyldig ${t[a.format]??a.format}`;case"not_multiple_of":return`Ugyldig tall: m\xe5 v\xe6re et multiplum av ${a.divisor}`;case"unrecognized_keys":return`${a.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Ugyldig n\xf8kkel i ${a.origin}`;case"invalid_union":default:return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${a.origin}`}})}},"ota",0,function(){let e,t,r;return{localeError:(e={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}},t={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"},r={nan:"NaN",number:"numara",array:"saf",null:"gayb"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`F\xe2sit giren: umulan instanceof ${a.expected}, alınan ${n}`;return`F\xe2sit giren: umulan ${e}, alınan ${n}`}case"invalid_value":if(1===a.values.length)return`F\xe2sit giren: umulan ${i.stringifyPrimitive(a.values[0])}`;return`F\xe2sit tercih: m\xfbteberler ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Fazla b\xfcy\xfck: ${a.origin??"value"}, ${t}${a.maximum.toString()} ${r.unit??"elements"} sahip olmalıydı.`;return`Fazla b\xfcy\xfck: ${a.origin??"value"}, ${t}${a.maximum.toString()} olmalıydı.`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Fazla k\xfc\xe7\xfck: ${a.origin}, ${t}${a.minimum.toString()} ${r.unit} sahip olmalıydı.`;return`Fazla k\xfc\xe7\xfck: ${a.origin}, ${t}${a.minimum.toString()} olmalıydı.`}case"invalid_format":if("starts_with"===a.format)return`F\xe2sit metin: "${a.prefix}" ile başlamalı.`;if("ends_with"===a.format)return`F\xe2sit metin: "${a.suffix}" ile bitmeli.`;if("includes"===a.format)return`F\xe2sit metin: "${a.includes}" ihtiv\xe2 etmeli.`;if("regex"===a.format)return`F\xe2sit metin: ${a.pattern} nakşına uymalı.`;return`F\xe2sit ${t[a.format]??a.format}`;case"not_multiple_of":return`F\xe2sit sayı: ${a.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${a.keys.length>1?"s":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`${a.origin} i\xe7in tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${a.origin} i\xe7in tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}})}},"pl",0,function(){let e,t,r;return{localeError:(e={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}},t={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"},r={nan:"NaN",number:"liczba",array:"tablica"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Nieprawidłowe dane wejściowe: oczekiwano instanceof ${a.expected}, otrzymano ${n}`;return`Nieprawidłowe dane wejściowe: oczekiwano ${e}, otrzymano ${n}`}case"invalid_value":if(1===a.values.length)return`Nieprawidłowe dane wejściowe: oczekiwano ${i.stringifyPrimitive(a.values[0])}`;return`Nieprawidłowa opcja: oczekiwano jednej z wartości ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Za duża wartość: oczekiwano, że ${a.origin??"wartość"} będzie mieć ${t}${a.maximum.toString()} ${r.unit??"elementów"}`;return`Zbyt duż(y/a/e): oczekiwano, że ${a.origin??"wartość"} będzie wynosić ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Za mała wartość: oczekiwano, że ${a.origin??"wartość"} będzie mieć ${t}${a.minimum.toString()} ${r.unit??"elementów"}`;return`Zbyt mał(y/a/e): oczekiwano, że ${a.origin??"wartość"} będzie wynosić ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Nieprawidłowy ciąg znak\xf3w: musi zaczynać się od "${a.prefix}"`;if("ends_with"===a.format)return`Nieprawidłowy ciąg znak\xf3w: musi kończyć się na "${a.suffix}"`;if("includes"===a.format)return`Nieprawidłowy ciąg znak\xf3w: musi zawierać "${a.includes}"`;if("regex"===a.format)return`Nieprawidłowy ciąg znak\xf3w: musi odpowiadać wzorcowi ${a.pattern}`;return`Nieprawidłow(y/a/e) ${t[a.format]??a.format}`;case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${a.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${a.keys.length>1?"s":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${a.origin}`;case"invalid_union":default:return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${a.origin}`}})}},"ps",0,function(){let e,t,r;return{localeError:(e={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}},t={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"},r={nan:"NaN",number:"عدد",array:"ارې"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`ناسم ورودي: باید instanceof ${a.expected} وای, مګر ${n} ترلاسه شو`;return`ناسم ورودي: باید ${e} وای, مګر ${n} ترلاسه شو`}case"invalid_value":if(1===a.values.length)return`ناسم ورودي: باید ${i.stringifyPrimitive(a.values[0])} وای`;return`ناسم انتخاب: باید یو له ${i.joinValues(a.values,"|")} څخه وای`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`ډیر لوی: ${a.origin??"ارزښت"} باید ${t}${a.maximum.toString()} ${r.unit??"عنصرونه"} ولري`;return`ډیر لوی: ${a.origin??"ارزښت"} باید ${t}${a.maximum.toString()} وي`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`ډیر کوچنی: ${a.origin} باید ${t}${a.minimum.toString()} ${r.unit} ولري`;return`ډیر کوچنی: ${a.origin} باید ${t}${a.minimum.toString()} وي`}case"invalid_format":if("starts_with"===a.format)return`ناسم متن: باید د "${a.prefix}" سره پیل شي`;if("ends_with"===a.format)return`ناسم متن: باید د "${a.suffix}" سره پای ته ورسيږي`;if("includes"===a.format)return`ناسم متن: باید "${a.includes}" ولري`;if("regex"===a.format)return`ناسم متن: باید د ${a.pattern} سره مطابقت ولري`;return`${t[a.format]??a.format} ناسم دی`;case"not_multiple_of":return`ناسم عدد: باید د ${a.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${a.keys.length>1?"کلیډونه":"کلیډ"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${a.origin} کې`;case"invalid_union":default:return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${a.origin} کې`}})}},"pt",0,function(){let e,t,r;return{localeError:(e={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}},t={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},r={nan:"NaN",number:"número",null:"nulo"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Tipo inv\xe1lido: esperado instanceof ${a.expected}, recebido ${n}`;return`Tipo inv\xe1lido: esperado ${e}, recebido ${n}`}case"invalid_value":if(1===a.values.length)return`Entrada inv\xe1lida: esperado ${i.stringifyPrimitive(a.values[0])}`;return`Op\xe7\xe3o inv\xe1lida: esperada uma das ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Muito grande: esperado que ${a.origin??"valor"} tivesse ${t}${a.maximum.toString()} ${r.unit??"elementos"}`;return`Muito grande: esperado que ${a.origin??"valor"} fosse ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Muito pequeno: esperado que ${a.origin} tivesse ${t}${a.minimum.toString()} ${r.unit}`;return`Muito pequeno: esperado que ${a.origin} fosse ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Texto inv\xe1lido: deve come\xe7ar com "${a.prefix}"`;if("ends_with"===a.format)return`Texto inv\xe1lido: deve terminar com "${a.suffix}"`;if("includes"===a.format)return`Texto inv\xe1lido: deve incluir "${a.includes}"`;if("regex"===a.format)return`Texto inv\xe1lido: deve corresponder ao padr\xe3o ${a.pattern}`;return`${t[a.format]??a.format} inv\xe1lido`;case"not_multiple_of":return`N\xfamero inv\xe1lido: deve ser m\xfaltiplo de ${a.divisor}`;case"unrecognized_keys":return`Chave${a.keys.length>1?"s":""} desconhecida${a.keys.length>1?"s":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Chave inv\xe1lida em ${a.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inv\xe1lido em ${a.origin}`;default:return"Campo inválido"}})}},"ro",0,function(){let e,t,r;return{localeError:(e={string:{unit:"caractere",verb:"să aibă"},file:{unit:"octeți",verb:"să aibă"},array:{unit:"elemente",verb:"să aibă"},set:{unit:"elemente",verb:"să aibă"},map:{unit:"intrări",verb:"să aibă"}},t={regex:"intrare",email:"adresă de email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"dată și oră ISO",date:"dată ISO",time:"oră ISO",duration:"durată ISO",ipv4:"adresă IPv4",ipv6:"adresă IPv6",mac:"adresă MAC",cidrv4:"interval IPv4",cidrv6:"interval IPv6",base64:"șir codat base64",base64url:"șir codat base64url",json_string:"șir JSON",e164:"număr E.164",jwt:"JWT",template_literal:"intrare"},r={nan:"NaN",string:"șir",number:"număr",boolean:"boolean",function:"funcție",array:"matrice",object:"obiect",undefined:"nedefinit",symbol:"simbol",bigint:"număr mare",void:"void",never:"never",map:"hartă",set:"set"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;return`Intrare invalidă: așteptat ${e}, primit ${n}`}case"invalid_value":if(1===a.values.length)return`Intrare invalidă: așteptat ${i.stringifyPrimitive(a.values[0])}`;return`Opțiune invalidă: așteptat una dintre ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Prea mare: așteptat ca ${a.origin??"valoarea"} ${r.verb} ${t}${a.maximum.toString()} ${r.unit??"elemente"}`;return`Prea mare: așteptat ca ${a.origin??"valoarea"} să fie ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Prea mic: așteptat ca ${a.origin} ${r.verb} ${t}${a.minimum.toString()} ${r.unit}`;return`Prea mic: așteptat ca ${a.origin} să fie ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Șir invalid: trebuie să \xeenceapă cu "${a.prefix}"`;if("ends_with"===a.format)return`Șir invalid: trebuie să se termine cu "${a.suffix}"`;if("includes"===a.format)return`Șir invalid: trebuie să includă "${a.includes}"`;if("regex"===a.format)return`Șir invalid: trebuie să se potrivească cu modelul ${a.pattern}`;return`Format invalid: ${t[a.format]??a.format}`;case"not_multiple_of":return`Număr invalid: trebuie să fie multiplu de ${a.divisor}`;case"unrecognized_keys":return`Chei nerecunoscute: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Cheie invalidă \xeen ${a.origin}`;case"invalid_union":default:return"Intrare invalidă";case"invalid_element":return`Valoare invalidă \xeen ${a.origin}`}})}},"ru",0,function(){let e,t,r;return{localeError:(e={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}},t={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"},r={nan:"NaN",number:"число",array:"массив"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Неверный ввод: ожидалось instanceof ${a.expected}, получено ${n}`;return`Неверный ввод: ожидалось ${e}, получено ${n}`}case"invalid_value":if(1===a.values.length)return`Неверный ввод: ожидалось ${i.stringifyPrimitive(a.values[0])}`;return`Неверный вариант: ожидалось одно из ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r){let e=w(Number(a.maximum),r.unit.one,r.unit.few,r.unit.many);return`Слишком большое значение: ожидалось, что ${a.origin??"значение"} будет иметь ${t}${a.maximum.toString()} ${e}`}return`Слишком большое значение: ожидалось, что ${a.origin??"значение"} будет ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r){let e=w(Number(a.minimum),r.unit.one,r.unit.few,r.unit.many);return`Слишком маленькое значение: ожидалось, что ${a.origin} будет иметь ${t}${a.minimum.toString()} ${e}`}return`Слишком маленькое значение: ожидалось, что ${a.origin} будет ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Неверная строка: должна начинаться с "${a.prefix}"`;if("ends_with"===a.format)return`Неверная строка: должна заканчиваться на "${a.suffix}"`;if("includes"===a.format)return`Неверная строка: должна содержать "${a.includes}"`;if("regex"===a.format)return`Неверная строка: должна соответствовать шаблону ${a.pattern}`;return`Неверный ${t[a.format]??a.format}`;case"not_multiple_of":return`Неверное число: должно быть кратным ${a.divisor}`;case"unrecognized_keys":return`Нераспознанн${a.keys.length>1?"ые":"ый"} ключ${a.keys.length>1?"и":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${a.origin}`;case"invalid_union":default:return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${a.origin}`}})}},"sl",0,function(){let e,t,r;return{localeError:(e={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}},t={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"},r={nan:"NaN",number:"število",array:"tabela"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Neveljaven vnos: pričakovano instanceof ${a.expected}, prejeto ${n}`;return`Neveljaven vnos: pričakovano ${e}, prejeto ${n}`}case"invalid_value":if(1===a.values.length)return`Neveljaven vnos: pričakovano ${i.stringifyPrimitive(a.values[0])}`;return`Neveljavna možnost: pričakovano eno izmed ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Preveliko: pričakovano, da bo ${a.origin??"vrednost"} imelo ${t}${a.maximum.toString()} ${r.unit??"elementov"}`;return`Preveliko: pričakovano, da bo ${a.origin??"vrednost"} ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Premajhno: pričakovano, da bo ${a.origin} imelo ${t}${a.minimum.toString()} ${r.unit}`;return`Premajhno: pričakovano, da bo ${a.origin} ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Neveljaven niz: mora se začeti z "${a.prefix}"`;if("ends_with"===a.format)return`Neveljaven niz: mora se končati z "${a.suffix}"`;if("includes"===a.format)return`Neveljaven niz: mora vsebovati "${a.includes}"`;if("regex"===a.format)return`Neveljaven niz: mora ustrezati vzorcu ${a.pattern}`;return`Neveljaven ${t[a.format]??a.format}`;case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${a.divisor}`;case"unrecognized_keys":return`Neprepoznan${a.keys.length>1?"i ključi":" ključ"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${a.origin}`;case"invalid_union":default:return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${a.origin}`}})}},"sv",0,function(){let e,t,r;return{localeError:(e={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}},t={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},r={nan:"NaN",number:"antal",array:"lista"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Ogiltig inmatning: f\xf6rv\xe4ntat instanceof ${a.expected}, fick ${n}`;return`Ogiltig inmatning: f\xf6rv\xe4ntat ${e}, fick ${n}`}case"invalid_value":if(1===a.values.length)return`Ogiltig inmatning: f\xf6rv\xe4ntat ${i.stringifyPrimitive(a.values[0])}`;return`Ogiltigt val: f\xf6rv\xe4ntade en av ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`F\xf6r stor(t): f\xf6rv\xe4ntade ${a.origin??"värdet"} att ha ${t}${a.maximum.toString()} ${r.unit??"element"}`;return`F\xf6r stor(t): f\xf6rv\xe4ntat ${a.origin??"värdet"} att ha ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`F\xf6r lite(t): f\xf6rv\xe4ntade ${a.origin??"värdet"} att ha ${t}${a.minimum.toString()} ${r.unit}`;return`F\xf6r lite(t): f\xf6rv\xe4ntade ${a.origin??"värdet"} att ha ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Ogiltig str\xe4ng: m\xe5ste b\xf6rja med "${a.prefix}"`;if("ends_with"===a.format)return`Ogiltig str\xe4ng: m\xe5ste sluta med "${a.suffix}"`;if("includes"===a.format)return`Ogiltig str\xe4ng: m\xe5ste inneh\xe5lla "${a.includes}"`;if("regex"===a.format)return`Ogiltig str\xe4ng: m\xe5ste matcha m\xf6nstret "${a.pattern}"`;return`Ogiltig(t) ${t[a.format]??a.format}`;case"not_multiple_of":return`Ogiltigt tal: m\xe5ste vara en multipel av ${a.divisor}`;case"unrecognized_keys":return`${a.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${a.origin??"värdet"}`;case"invalid_union":default:return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xe4rde i ${a.origin??"värdet"}`}})}},"ta",0,function(){let e,t,r;return{localeError:(e={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}},t={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"},r={nan:"NaN",number:"எண்",array:"அணி",null:"வெறுமை"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${a.expected}, பெறப்பட்டது ${n}`;return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${e}, பெறப்பட்டது ${n}`}case"invalid_value":if(1===a.values.length)return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${i.stringifyPrimitive(a.values[0])}`;return`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${i.joinValues(a.values,"|")} இல் ஒன்று`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${a.origin??"மதிப்பு"} ${t}${a.maximum.toString()} ${r.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`;return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${a.origin??"மதிப்பு"} ${t}${a.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${a.origin} ${t}${a.minimum.toString()} ${r.unit} ஆக இருக்க வேண்டும்`;return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${a.origin} ${t}${a.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":if("starts_with"===a.format)return`தவறான சரம்: "${a.prefix}" இல் தொடங்க வேண்டும்`;if("ends_with"===a.format)return`தவறான சரம்: "${a.suffix}" இல் முடிவடைய வேண்டும்`;if("includes"===a.format)return`தவறான சரம்: "${a.includes}" ஐ உள்ளடக்க வேண்டும்`;if("regex"===a.format)return`தவறான சரம்: ${a.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`;return`தவறான ${t[a.format]??a.format}`;case"not_multiple_of":return`தவறான எண்: ${a.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${a.keys.length>1?"கள்":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`${a.origin} இல் தவறான விசை`;case"invalid_union":default:return"தவறான உள்ளீடு";case"invalid_element":return`${a.origin} இல் தவறான மதிப்பு`}})}},"th",0,function(){let e,t,r;return{localeError:(e={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}},t={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"},r={nan:"NaN",number:"ตัวเลข",array:"อาร์เรย์ (Array)",null:"ไม่มีค่า (null)"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${a.expected} แต่ได้รับ ${n}`;return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${e} แต่ได้รับ ${n}`}case"invalid_value":if(1===a.values.length)return`ค่าไม่ถูกต้อง: ควรเป็น ${i.stringifyPrimitive(a.values[0])}`;return`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"ไม่เกิน":"น้อยกว่า",r=e[a.origin]??null;if(r)return`เกินกำหนด: ${a.origin??"ค่า"} ควรมี${t} ${a.maximum.toString()} ${r.unit??"รายการ"}`;return`เกินกำหนด: ${a.origin??"ค่า"} ควรมี${t} ${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?"อย่างน้อย":"มากกว่า",r=e[a.origin]??null;if(r)return`น้อยกว่ากำหนด: ${a.origin} ควรมี${t} ${a.minimum.toString()} ${r.unit}`;return`น้อยกว่ากำหนด: ${a.origin} ควรมี${t} ${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${a.prefix}"`;if("ends_with"===a.format)return`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${a.suffix}"`;if("includes"===a.format)return`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${a.includes}" อยู่ในข้อความ`;if("regex"===a.format)return`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${a.pattern}`;return`รูปแบบไม่ถูกต้อง: ${t[a.format]??a.format}`;case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${a.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${a.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${a.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}})}},"tr",0,function(){let e,t,r;return{localeError:(e={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}},t={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Ge\xe7ersiz değer: beklenen instanceof ${a.expected}, alınan ${n}`;return`Ge\xe7ersiz değer: beklenen ${e}, alınan ${n}`}case"invalid_value":if(1===a.values.length)return`Ge\xe7ersiz değer: beklenen ${i.stringifyPrimitive(a.values[0])}`;return`Ge\xe7ersiz se\xe7enek: aşağıdakilerden biri olmalı: ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`\xc7ok b\xfcy\xfck: beklenen ${a.origin??"değer"} ${t}${a.maximum.toString()} ${r.unit??"öğe"}`;return`\xc7ok b\xfcy\xfck: beklenen ${a.origin??"değer"} ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`\xc7ok k\xfc\xe7\xfck: beklenen ${a.origin} ${t}${a.minimum.toString()} ${r.unit}`;return`\xc7ok k\xfc\xe7\xfck: beklenen ${a.origin} ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Ge\xe7ersiz metin: "${a.prefix}" ile başlamalı`;if("ends_with"===a.format)return`Ge\xe7ersiz metin: "${a.suffix}" ile bitmeli`;if("includes"===a.format)return`Ge\xe7ersiz metin: "${a.includes}" i\xe7ermeli`;if("regex"===a.format)return`Ge\xe7ersiz metin: ${a.pattern} desenine uymalı`;return`Ge\xe7ersiz ${t[a.format]??a.format}`;case"not_multiple_of":return`Ge\xe7ersiz sayı: ${a.divisor} ile tam b\xf6l\xfcnebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${a.keys.length>1?"lar":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`${a.origin} i\xe7inde ge\xe7ersiz anahtar`;case"invalid_union":default:return"Geçersiz değer";case"invalid_element":return`${a.origin} i\xe7inde ge\xe7ersiz değer`}})}},"ua",0,function(){return b()},"uk",0,b,"ur",0,function(){let e,t,r;return{localeError:(e={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}},t={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"},r={nan:"NaN",number:"نمبر",array:"آرے",null:"نل"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`غلط ان پٹ: instanceof ${a.expected} متوقع تھا، ${n} موصول ہوا`;return`غلط ان پٹ: ${e} متوقع تھا، ${n} موصول ہوا`}case"invalid_value":if(1===a.values.length)return`غلط ان پٹ: ${i.stringifyPrimitive(a.values[0])} متوقع تھا`;return`غلط آپشن: ${i.joinValues(a.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`بہت بڑا: ${a.origin??"ویلیو"} کے ${t}${a.maximum.toString()} ${r.unit??"عناصر"} ہونے متوقع تھے`;return`بہت بڑا: ${a.origin??"ویلیو"} کا ${t}${a.maximum.toString()} ہونا متوقع تھا`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`بہت چھوٹا: ${a.origin} کے ${t}${a.minimum.toString()} ${r.unit} ہونے متوقع تھے`;return`بہت چھوٹا: ${a.origin} کا ${t}${a.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":if("starts_with"===a.format)return`غلط سٹرنگ: "${a.prefix}" سے شروع ہونا چاہیے`;if("ends_with"===a.format)return`غلط سٹرنگ: "${a.suffix}" پر ختم ہونا چاہیے`;if("includes"===a.format)return`غلط سٹرنگ: "${a.includes}" شامل ہونا چاہیے`;if("regex"===a.format)return`غلط سٹرنگ: پیٹرن ${a.pattern} سے میچ ہونا چاہیے`;return`غلط ${t[a.format]??a.format}`;case"not_multiple_of":return`غلط نمبر: ${a.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${a.keys.length>1?"ز":""}: ${i.joinValues(a.keys,"، ")}`;case"invalid_key":return`${a.origin} میں غلط کی`;case"invalid_union":default:return"غلط ان پٹ";case"invalid_element":return`${a.origin} میں غلط ویلیو`}})}},"uz",0,function(){let e,t,r;return{localeError:(e={string:{unit:"belgi",verb:"bo‘lishi kerak"},file:{unit:"bayt",verb:"bo‘lishi kerak"},array:{unit:"element",verb:"bo‘lishi kerak"},set:{unit:"element",verb:"bo‘lishi kerak"},map:{unit:"yozuv",verb:"bo‘lishi kerak"}},t={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},r={nan:"NaN",number:"raqam",array:"massiv"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Noto‘g‘ri kirish: kutilgan instanceof ${a.expected}, qabul qilingan ${n}`;return`Noto‘g‘ri kirish: kutilgan ${e}, qabul qilingan ${n}`}case"invalid_value":if(1===a.values.length)return`Noto‘g‘ri kirish: kutilgan ${i.stringifyPrimitive(a.values[0])}`;return`Noto‘g‘ri variant: quyidagilardan biri kutilgan ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Juda katta: kutilgan ${a.origin??"qiymat"} ${t}${a.maximum.toString()} ${r.unit} ${r.verb}`;return`Juda katta: kutilgan ${a.origin??"qiymat"} ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Juda kichik: kutilgan ${a.origin} ${t}${a.minimum.toString()} ${r.unit} ${r.verb}`;return`Juda kichik: kutilgan ${a.origin} ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Noto‘g‘ri satr: "${a.prefix}" bilan boshlanishi kerak`;if("ends_with"===a.format)return`Noto‘g‘ri satr: "${a.suffix}" bilan tugashi kerak`;if("includes"===a.format)return`Noto‘g‘ri satr: "${a.includes}" ni o‘z ichiga olishi kerak`;if("regex"===a.format)return`Noto‘g‘ri satr: ${a.pattern} shabloniga mos kelishi kerak`;return`Noto‘g‘ri ${t[a.format]??a.format}`;case"not_multiple_of":return`Noto‘g‘ri raqam: ${a.divisor} ning karralisi bo‘lishi kerak`;case"unrecognized_keys":return`Noma’lum kalit${a.keys.length>1?"lar":""}: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`${a.origin} dagi kalit noto‘g‘ri`;case"invalid_union":default:return"Noto‘g‘ri kirish";case"invalid_element":return`${a.origin} da noto‘g‘ri qiymat`}})}},"vi",0,function(){let e,t,r;return{localeError:(e={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}},t={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"},r={nan:"NaN",number:"số",array:"mảng"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`Đầu v\xe0o kh\xf4ng hợp lệ: mong đợi instanceof ${a.expected}, nhận được ${n}`;return`Đầu v\xe0o kh\xf4ng hợp lệ: mong đợi ${e}, nhận được ${n}`}case"invalid_value":if(1===a.values.length)return`Đầu v\xe0o kh\xf4ng hợp lệ: mong đợi ${i.stringifyPrimitive(a.values[0])}`;return`T\xf9y chọn kh\xf4ng hợp lệ: mong đợi một trong c\xe1c gi\xe1 trị ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`Qu\xe1 lớn: mong đợi ${a.origin??"giá trị"} ${r.verb} ${t}${a.maximum.toString()} ${r.unit??"phần tử"}`;return`Qu\xe1 lớn: mong đợi ${a.origin??"giá trị"} ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`Qu\xe1 nhỏ: mong đợi ${a.origin} ${r.verb} ${t}${a.minimum.toString()} ${r.unit}`;return`Qu\xe1 nhỏ: mong đợi ${a.origin} ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`Chuỗi kh\xf4ng hợp lệ: phải bắt đầu bằng "${a.prefix}"`;if("ends_with"===a.format)return`Chuỗi kh\xf4ng hợp lệ: phải kết th\xfac bằng "${a.suffix}"`;if("includes"===a.format)return`Chuỗi kh\xf4ng hợp lệ: phải bao gồm "${a.includes}"`;if("regex"===a.format)return`Chuỗi kh\xf4ng hợp lệ: phải khớp với mẫu ${a.pattern}`;return`${t[a.format]??a.format} kh\xf4ng hợp lệ`;case"not_multiple_of":return`Số kh\xf4ng hợp lệ: phải l\xe0 bội số của ${a.divisor}`;case"unrecognized_keys":return`Kh\xf3a kh\xf4ng được nhận dạng: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Kh\xf3a kh\xf4ng hợp lệ trong ${a.origin}`;case"invalid_union":default:return"Đầu vào không hợp lệ";case"invalid_element":return`Gi\xe1 trị kh\xf4ng hợp lệ trong ${a.origin}`}})}},"yo",0,function(){let e,t,r;return{localeError:(e={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}},t={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"},r={nan:"NaN",number:"nọ́mbà",array:"akopọ"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`\xccb\xe1wọl\xe9 aṣ\xecṣe: a n\xed l\xe1ti fi instanceof ${a.expected}, \xe0mọ̀ a r\xed ${n}`;return`\xccb\xe1wọl\xe9 aṣ\xecṣe: a n\xed l\xe1ti fi ${e}, \xe0mọ̀ a r\xed ${n}`}case"invalid_value":if(1===a.values.length)return`\xccb\xe1wọl\xe9 aṣ\xecṣe: a n\xed l\xe1ti fi ${i.stringifyPrimitive(a.values[0])}`;return`\xc0ṣ\xe0y\xe0n aṣ\xecṣe: yan ọ̀kan l\xe1ra ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`T\xf3 pọ̀ j\xf9: a n\xed l\xe1ti jẹ́ p\xe9 ${a.origin??"iye"} ${r.verb} ${t}${a.maximum} ${r.unit}`;return`T\xf3 pọ̀ j\xf9: a n\xed l\xe1ti jẹ́ ${t}${a.maximum}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`K\xe9r\xe9 ju: a n\xed l\xe1ti jẹ́ p\xe9 ${a.origin} ${r.verb} ${t}${a.minimum} ${r.unit}`;return`K\xe9r\xe9 ju: a n\xed l\xe1ti jẹ́ ${t}${a.minimum}`}case"invalid_format":if("starts_with"===a.format)return`Ọ̀rọ̀ aṣ\xecṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀l\xfa "${a.prefix}"`;if("ends_with"===a.format)return`Ọ̀rọ̀ aṣ\xecṣe: gbọ́dọ̀ par\xed pẹ̀l\xfa "${a.suffix}"`;if("includes"===a.format)return`Ọ̀rọ̀ aṣ\xecṣe: gbọ́dọ̀ n\xed "${a.includes}"`;if("regex"===a.format)return`Ọ̀rọ̀ aṣ\xecṣe: gbọ́dọ̀ b\xe1 \xe0pẹẹrẹ mu ${a.pattern}`;return`Aṣ\xecṣe: ${t[a.format]??a.format}`;case"not_multiple_of":return`Nọ́mb\xe0 aṣ\xecṣe: gbọ́dọ̀ jẹ́ \xe8y\xe0 p\xedp\xedn ti ${a.divisor}`;case"unrecognized_keys":return`Bọt\xecn\xec \xe0\xecmọ̀: ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`Bọt\xecn\xec aṣ\xecṣe n\xedn\xfa ${a.origin}`;case"invalid_union":default:return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣ\xecṣe n\xedn\xfa ${a.origin}`}})}},"zhCN",0,function(){let e,t,r;return{localeError:(e={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}},t={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"},r={nan:"NaN",number:"数字",array:"数组",null:"空值(null)"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`无效输入:期望 instanceof ${a.expected},实际接收 ${n}`;return`无效输入:期望 ${e},实际接收 ${n}`}case"invalid_value":if(1===a.values.length)return`无效输入:期望 ${i.stringifyPrimitive(a.values[0])}`;return`无效选项:期望以下之一 ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`数值过大:期望 ${a.origin??"值"} ${t}${a.maximum.toString()} ${r.unit??"个元素"}`;return`数值过大:期望 ${a.origin??"值"} ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`数值过小:期望 ${a.origin} ${t}${a.minimum.toString()} ${r.unit}`;return`数值过小:期望 ${a.origin} ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`无效字符串:必须以 "${a.prefix}" 开头`;if("ends_with"===a.format)return`无效字符串:必须以 "${a.suffix}" 结尾`;if("includes"===a.format)return`无效字符串:必须包含 "${a.includes}"`;if("regex"===a.format)return`无效字符串:必须满足正则表达式 ${a.pattern}`;return`无效${t[a.format]??a.format}`;case"not_multiple_of":return`无效数字:必须是 ${a.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${i.joinValues(a.keys,", ")}`;case"invalid_key":return`${a.origin} 中的键(key)无效`;case"invalid_union":default:return"无效输入";case"invalid_element":return`${a.origin} 中包含无效值(value)`}})}},"zhTW",0,function(){let e,t,r;return{localeError:(e={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}},t={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"},r={nan:"NaN"},a=>{switch(a.code){case"invalid_type":{let e=r[a.expected]??a.expected,t=i.parsedType(a.input),n=r[t]??t;if(/^[A-Z]/.test(a.expected))return`無效的輸入值:預期為 instanceof ${a.expected},但收到 ${n}`;return`無效的輸入值:預期為 ${e},但收到 ${n}`}case"invalid_value":if(1===a.values.length)return`無效的輸入值:預期為 ${i.stringifyPrimitive(a.values[0])}`;return`無效的選項:預期為以下其中之一 ${i.joinValues(a.values,"|")}`;case"too_big":{let t=a.inclusive?"<=":"<",r=e[a.origin]??null;if(r)return`數值過大:預期 ${a.origin??"值"} 應為 ${t}${a.maximum.toString()} ${r.unit??"個元素"}`;return`數值過大:預期 ${a.origin??"值"} 應為 ${t}${a.maximum.toString()}`}case"too_small":{let t=a.inclusive?">=":">",r=e[a.origin]??null;if(r)return`數值過小:預期 ${a.origin} 應為 ${t}${a.minimum.toString()} ${r.unit}`;return`數值過小:預期 ${a.origin} 應為 ${t}${a.minimum.toString()}`}case"invalid_format":if("starts_with"===a.format)return`無效的字串:必須以 "${a.prefix}" 開頭`;if("ends_with"===a.format)return`無效的字串:必須以 "${a.suffix}" 結尾`;if("includes"===a.format)return`無效的字串:必須包含 "${a.includes}"`;if("regex"===a.format)return`無效的字串:必須符合格式 ${a.pattern}`;return`無效的 ${t[a.format]??a.format}`;case"not_multiple_of":return`無效的數字:必須為 ${a.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${a.keys.length>1?"們":""}:${i.joinValues(a.keys,"、")}`;case"invalid_key":return`${a.origin} 中有無效的鍵值`;case"invalid_union":default:return"無效的輸入值";case"invalid_element":return`${a.origin} 中有無效的值`}})}}],860544);var v=e.i(860544),k=e.i(52637),S=e.i(173911),E=e.i(862061),I=e.i(207159),x=e.i(865889);e.s([],233145);var A=e.i(233145);e.s(["$ZodAny",()=>o.$ZodAny,"$ZodArray",()=>o.$ZodArray,"$ZodAsyncError",()=>r.$ZodAsyncError,"$ZodBase64",()=>o.$ZodBase64,"$ZodBase64URL",()=>o.$ZodBase64URL,"$ZodBigInt",()=>o.$ZodBigInt,"$ZodBigIntFormat",()=>o.$ZodBigIntFormat,"$ZodBoolean",()=>o.$ZodBoolean,"$ZodCIDRv4",()=>o.$ZodCIDRv4,"$ZodCIDRv6",()=>o.$ZodCIDRv6,"$ZodCUID",()=>o.$ZodCUID,"$ZodCUID2",()=>o.$ZodCUID2,"$ZodCatch",()=>o.$ZodCatch,"$ZodCheck",()=>l.$ZodCheck,"$ZodCheckBigIntFormat",()=>l.$ZodCheckBigIntFormat,"$ZodCheckEndsWith",()=>l.$ZodCheckEndsWith,"$ZodCheckGreaterThan",()=>l.$ZodCheckGreaterThan,"$ZodCheckIncludes",()=>l.$ZodCheckIncludes,"$ZodCheckLengthEquals",()=>l.$ZodCheckLengthEquals,"$ZodCheckLessThan",()=>l.$ZodCheckLessThan,"$ZodCheckLowerCase",()=>l.$ZodCheckLowerCase,"$ZodCheckMaxLength",()=>l.$ZodCheckMaxLength,"$ZodCheckMaxSize",()=>l.$ZodCheckMaxSize,"$ZodCheckMimeType",()=>l.$ZodCheckMimeType,"$ZodCheckMinLength",()=>l.$ZodCheckMinLength,"$ZodCheckMinSize",()=>l.$ZodCheckMinSize,"$ZodCheckMultipleOf",()=>l.$ZodCheckMultipleOf,"$ZodCheckNumberFormat",()=>l.$ZodCheckNumberFormat,"$ZodCheckOverwrite",()=>l.$ZodCheckOverwrite,"$ZodCheckProperty",()=>l.$ZodCheckProperty,"$ZodCheckRegex",()=>l.$ZodCheckRegex,"$ZodCheckSizeEquals",()=>l.$ZodCheckSizeEquals,"$ZodCheckStartsWith",()=>l.$ZodCheckStartsWith,"$ZodCheckStringFormat",()=>l.$ZodCheckStringFormat,"$ZodCheckUpperCase",()=>l.$ZodCheckUpperCase,"$ZodCodec",()=>o.$ZodCodec,"$ZodCustom",()=>o.$ZodCustom,"$ZodCustomStringFormat",()=>o.$ZodCustomStringFormat,"$ZodDate",()=>o.$ZodDate,"$ZodDefault",()=>o.$ZodDefault,"$ZodDiscriminatedUnion",()=>o.$ZodDiscriminatedUnion,"$ZodE164",()=>o.$ZodE164,"$ZodEmail",()=>o.$ZodEmail,"$ZodEmoji",()=>o.$ZodEmoji,"$ZodEncodeError",()=>r.$ZodEncodeError,"$ZodEnum",()=>o.$ZodEnum,"$ZodError",()=>s.$ZodError,"$ZodExactOptional",()=>o.$ZodExactOptional,"$ZodFile",()=>o.$ZodFile,"$ZodFunction",()=>o.$ZodFunction,"$ZodGUID",()=>o.$ZodGUID,"$ZodIPv4",()=>o.$ZodIPv4,"$ZodIPv6",()=>o.$ZodIPv6,"$ZodISODate",()=>o.$ZodISODate,"$ZodISODateTime",()=>o.$ZodISODateTime,"$ZodISODuration",()=>o.$ZodISODuration,"$ZodISOTime",()=>o.$ZodISOTime,"$ZodIntersection",()=>o.$ZodIntersection,"$ZodJWT",()=>o.$ZodJWT,"$ZodKSUID",()=>o.$ZodKSUID,"$ZodLazy",()=>o.$ZodLazy,"$ZodLiteral",()=>o.$ZodLiteral,"$ZodMAC",()=>o.$ZodMAC,"$ZodMap",()=>o.$ZodMap,"$ZodNaN",()=>o.$ZodNaN,"$ZodNanoID",()=>o.$ZodNanoID,"$ZodNever",()=>o.$ZodNever,"$ZodNonOptional",()=>o.$ZodNonOptional,"$ZodNull",()=>o.$ZodNull,"$ZodNullable",()=>o.$ZodNullable,"$ZodNumber",()=>o.$ZodNumber,"$ZodNumberFormat",()=>o.$ZodNumberFormat,"$ZodObject",()=>o.$ZodObject,"$ZodObjectJIT",()=>o.$ZodObjectJIT,"$ZodOptional",()=>o.$ZodOptional,"$ZodPipe",()=>o.$ZodPipe,"$ZodPrefault",()=>o.$ZodPrefault,"$ZodPreprocess",()=>o.$ZodPreprocess,"$ZodPromise",()=>o.$ZodPromise,"$ZodReadonly",()=>o.$ZodReadonly,"$ZodRealError",()=>s.$ZodRealError,"$ZodRecord",()=>o.$ZodRecord,"$ZodRegistry",()=>k.$ZodRegistry,"$ZodSet",()=>o.$ZodSet,"$ZodString",()=>o.$ZodString,"$ZodStringFormat",()=>o.$ZodStringFormat,"$ZodSuccess",()=>o.$ZodSuccess,"$ZodSymbol",()=>o.$ZodSymbol,"$ZodTemplateLiteral",()=>o.$ZodTemplateLiteral,"$ZodTransform",()=>o.$ZodTransform,"$ZodTuple",()=>o.$ZodTuple,"$ZodType",()=>o.$ZodType,"$ZodULID",()=>o.$ZodULID,"$ZodURL",()=>o.$ZodURL,"$ZodUUID",()=>o.$ZodUUID,"$ZodUndefined",()=>o.$ZodUndefined,"$ZodUnion",()=>o.$ZodUnion,"$ZodUnknown",()=>o.$ZodUnknown,"$ZodVoid",()=>o.$ZodVoid,"$ZodXID",()=>o.$ZodXID,"$ZodXor",()=>o.$ZodXor,"$brand",()=>r.$brand,"$constructor",()=>r.$constructor,"$input",()=>k.$input,"$output",()=>k.$output,"Doc",()=>S.Doc,"JSONSchema",0,A,"JSONSchemaGenerator",0,class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let t=e?.target??"draft-2020-12";"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),this.ctx=(0,I.initializeContext)({processors:x.allProcessors,target:t,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,t={path:[],schemaPath:[]}){return(0,I.process)(e,this.ctx,t)}emit(e,t){t&&(t.cycles&&(this.ctx.cycles=t.cycles),t.reused&&(this.ctx.reused=t.reused),t.external&&(this.ctx.external=t.external)),(0,I.extractDefs)(this.ctx,e);let{"~standard":r,...i}=(0,I.finalize)(this.ctx,e);return i}},"NEVER",()=>r.NEVER,"TimePrecision",()=>E.TimePrecision,"_any",()=>E._any,"_array",()=>E._array,"_base64",()=>E._base64,"_base64url",()=>E._base64url,"_bigint",()=>E._bigint,"_boolean",()=>E._boolean,"_catch",()=>E._catch,"_check",()=>E._check,"_cidrv4",()=>E._cidrv4,"_cidrv6",()=>E._cidrv6,"_coercedBigint",()=>E._coercedBigint,"_coercedBoolean",()=>E._coercedBoolean,"_coercedDate",()=>E._coercedDate,"_coercedNumber",()=>E._coercedNumber,"_coercedString",()=>E._coercedString,"_cuid",()=>E._cuid,"_cuid2",()=>E._cuid2,"_custom",()=>E._custom,"_date",()=>E._date,"_decode",()=>n._decode,"_decodeAsync",()=>n._decodeAsync,"_default",()=>E._default,"_discriminatedUnion",()=>E._discriminatedUnion,"_e164",()=>E._e164,"_email",()=>E._email,"_emoji",()=>E._emoji,"_encode",()=>n._encode,"_encodeAsync",()=>n._encodeAsync,"_endsWith",()=>E._endsWith,"_enum",()=>E._enum,"_file",()=>E._file,"_float32",()=>E._float32,"_float64",()=>E._float64,"_gt",()=>E._gt,"_gte",()=>E._gte,"_guid",()=>E._guid,"_includes",()=>E._includes,"_int",()=>E._int,"_int32",()=>E._int32,"_int64",()=>E._int64,"_intersection",()=>E._intersection,"_ipv4",()=>E._ipv4,"_ipv6",()=>E._ipv6,"_isoDate",()=>E._isoDate,"_isoDateTime",()=>E._isoDateTime,"_isoDuration",()=>E._isoDuration,"_isoTime",()=>E._isoTime,"_jwt",()=>E._jwt,"_ksuid",()=>E._ksuid,"_lazy",()=>E._lazy,"_length",()=>E._length,"_literal",()=>E._literal,"_lowercase",()=>E._lowercase,"_lt",()=>E._lt,"_lte",()=>E._lte,"_mac",()=>E._mac,"_map",()=>E._map,"_max",()=>E._max,"_maxLength",()=>E._maxLength,"_maxSize",()=>E._maxSize,"_mime",()=>E._mime,"_min",()=>E._min,"_minLength",()=>E._minLength,"_minSize",()=>E._minSize,"_multipleOf",()=>E._multipleOf,"_nan",()=>E._nan,"_nanoid",()=>E._nanoid,"_nativeEnum",()=>E._nativeEnum,"_negative",()=>E._negative,"_never",()=>E._never,"_nonnegative",()=>E._nonnegative,"_nonoptional",()=>E._nonoptional,"_nonpositive",()=>E._nonpositive,"_normalize",()=>E._normalize,"_null",()=>E._null,"_nullable",()=>E._nullable,"_number",()=>E._number,"_optional",()=>E._optional,"_overwrite",()=>E._overwrite,"_parse",()=>n._parse,"_parseAsync",()=>n._parseAsync,"_pipe",()=>E._pipe,"_positive",()=>E._positive,"_promise",()=>E._promise,"_property",()=>E._property,"_readonly",()=>E._readonly,"_record",()=>E._record,"_refine",()=>E._refine,"_regex",()=>E._regex,"_safeDecode",()=>n._safeDecode,"_safeDecodeAsync",()=>n._safeDecodeAsync,"_safeEncode",()=>n._safeEncode,"_safeEncodeAsync",()=>n._safeEncodeAsync,"_safeParse",()=>n._safeParse,"_safeParseAsync",()=>n._safeParseAsync,"_set",()=>E._set,"_size",()=>E._size,"_slugify",()=>E._slugify,"_startsWith",()=>E._startsWith,"_string",()=>E._string,"_stringFormat",()=>E._stringFormat,"_stringbool",()=>E._stringbool,"_success",()=>E._success,"_superRefine",()=>E._superRefine,"_symbol",()=>E._symbol,"_templateLiteral",()=>E._templateLiteral,"_toLowerCase",()=>E._toLowerCase,"_toUpperCase",()=>E._toUpperCase,"_transform",()=>E._transform,"_trim",()=>E._trim,"_tuple",()=>E._tuple,"_uint32",()=>E._uint32,"_uint64",()=>E._uint64,"_ulid",()=>E._ulid,"_undefined",()=>E._undefined,"_union",()=>E._union,"_unknown",()=>E._unknown,"_uppercase",()=>E._uppercase,"_url",()=>E._url,"_uuid",()=>E._uuid,"_uuidv4",()=>E._uuidv4,"_uuidv6",()=>E._uuidv6,"_uuidv7",()=>E._uuidv7,"_void",()=>E._void,"_xid",()=>E._xid,"_xor",()=>E._xor,"clone",()=>i.clone,"config",()=>r.config,"createStandardJSONSchemaMethod",()=>I.createStandardJSONSchemaMethod,"createToJSONSchemaMethod",()=>I.createToJSONSchemaMethod,"decode",()=>n.decode,"decodeAsync",()=>n.decodeAsync,"describe",()=>E.describe,"encode",()=>n.encode,"encodeAsync",()=>n.encodeAsync,"extractDefs",()=>I.extractDefs,"finalize",()=>I.finalize,"flattenError",()=>s.flattenError,"formatError",()=>s.formatError,"globalConfig",()=>r.globalConfig,"globalRegistry",()=>k.globalRegistry,"initializeContext",()=>I.initializeContext,"isValidBase64",()=>o.isValidBase64,"isValidBase64URL",()=>o.isValidBase64URL,"isValidJWT",()=>o.isValidJWT,"locales",0,v,"meta",()=>E.meta,"parse",()=>n.parse,"parseAsync",()=>n.parseAsync,"prettifyError",()=>s.prettifyError,"process",()=>I.process,"regexes",0,d,"registry",()=>k.registry,"safeDecode",()=>n.safeDecode,"safeDecodeAsync",()=>n.safeDecodeAsync,"safeEncode",()=>n.safeEncode,"safeEncodeAsync",()=>n.safeEncodeAsync,"safeParse",()=>n.safeParse,"safeParseAsync",()=>n.safeParseAsync,"toDotPath",()=>s.toDotPath,"toJSONSchema",()=>x.toJSONSchema,"treeifyError",()=>s.treeifyError,"util",0,c,"version",()=>u.version],113007);var _=e.i(113007),C=e.i(907855);e.s([],664328),e.i(664328),e.s(["endsWith",()=>E._endsWith,"gt",()=>E._gt,"gte",()=>E._gte,"includes",()=>E._includes,"length",()=>E._length,"lowercase",()=>E._lowercase,"lt",()=>E._lt,"lte",()=>E._lte,"maxLength",()=>E._maxLength,"maxSize",()=>E._maxSize,"mime",()=>E._mime,"minLength",()=>E._minLength,"minSize",()=>E._minSize,"multipleOf",()=>E._multipleOf,"negative",()=>E._negative,"nonnegative",()=>E._nonnegative,"nonpositive",()=>E._nonpositive,"normalize",()=>E._normalize,"overwrite",()=>E._overwrite,"positive",()=>E._positive,"property",()=>E._property,"regex",()=>E._regex,"size",()=>E._size,"slugify",()=>E._slugify,"startsWith",()=>E._startsWith,"toLowerCase",()=>E._toLowerCase,"toUpperCase",()=>E._toUpperCase,"trim",()=>E._trim,"uppercase",()=>E._uppercase],185648);var R=e.i(185648),T=e.i(915874),D=e.i(248804);let N={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function O(e){r.config({customError:e})}function P(){return r.config().customError}t||(t={}),e.s(["ZodFirstPartyTypeKind",0,t,"ZodIssueCode",0,N,"getErrorMap",0,P,"setErrorMap",0,O],733137),e.i(733137),e.s(["$brand",()=>r.$brand,"ZodFirstPartyTypeKind",0,t,"ZodIssueCode",0,N,"config",()=>r.config,"getErrorMap",0,P,"setErrorMap",0,O],863203),e.i(863203);var $=e.i(467662),U=e.i(862061),B=e.i(628343),j=e.i(551047);let L={...C,...R,iso:j},q=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);e.s(["bigint",0,function(e){return E._coercedBigint(C.ZodBigInt,e)},"boolean",0,function(e){return E._coercedBoolean(C.ZodBoolean,e)},"date",0,function(e){return E._coercedDate(C.ZodDate,e)},"number",0,function(e){return E._coercedNumber(C.ZodNumber,e)},"string",0,function(e){return E._coercedString(C.ZodString,e)}],334512);var M=e.i(334512);e.s(["$brand",()=>r.$brand,"$input",()=>k.$input,"$output",()=>k.$output,"NEVER",()=>r.NEVER,"TimePrecision",()=>U.TimePrecision,"ZodAny",()=>C.ZodAny,"ZodArray",()=>C.ZodArray,"ZodBase64",()=>C.ZodBase64,"ZodBase64URL",()=>C.ZodBase64URL,"ZodBigInt",()=>C.ZodBigInt,"ZodBigIntFormat",()=>C.ZodBigIntFormat,"ZodBoolean",()=>C.ZodBoolean,"ZodCIDRv4",()=>C.ZodCIDRv4,"ZodCIDRv6",()=>C.ZodCIDRv6,"ZodCUID",()=>C.ZodCUID,"ZodCUID2",()=>C.ZodCUID2,"ZodCatch",()=>C.ZodCatch,"ZodCodec",()=>C.ZodCodec,"ZodCustom",()=>C.ZodCustom,"ZodCustomStringFormat",()=>C.ZodCustomStringFormat,"ZodDate",()=>C.ZodDate,"ZodDefault",()=>C.ZodDefault,"ZodDiscriminatedUnion",()=>C.ZodDiscriminatedUnion,"ZodE164",()=>C.ZodE164,"ZodEmail",()=>C.ZodEmail,"ZodEmoji",()=>C.ZodEmoji,"ZodEnum",()=>C.ZodEnum,"ZodError",()=>T.ZodError,"ZodExactOptional",()=>C.ZodExactOptional,"ZodFile",()=>C.ZodFile,"ZodFirstPartyTypeKind",0,t,"ZodFunction",()=>C.ZodFunction,"ZodGUID",()=>C.ZodGUID,"ZodIPv4",()=>C.ZodIPv4,"ZodIPv6",()=>C.ZodIPv6,"ZodISODate",()=>j.ZodISODate,"ZodISODateTime",()=>j.ZodISODateTime,"ZodISODuration",()=>j.ZodISODuration,"ZodISOTime",()=>j.ZodISOTime,"ZodIntersection",()=>C.ZodIntersection,"ZodIssueCode",0,N,"ZodJWT",()=>C.ZodJWT,"ZodKSUID",()=>C.ZodKSUID,"ZodLazy",()=>C.ZodLazy,"ZodLiteral",()=>C.ZodLiteral,"ZodMAC",()=>C.ZodMAC,"ZodMap",()=>C.ZodMap,"ZodNaN",()=>C.ZodNaN,"ZodNanoID",()=>C.ZodNanoID,"ZodNever",()=>C.ZodNever,"ZodNonOptional",()=>C.ZodNonOptional,"ZodNull",()=>C.ZodNull,"ZodNullable",()=>C.ZodNullable,"ZodNumber",()=>C.ZodNumber,"ZodNumberFormat",()=>C.ZodNumberFormat,"ZodObject",()=>C.ZodObject,"ZodOptional",()=>C.ZodOptional,"ZodPipe",()=>C.ZodPipe,"ZodPrefault",()=>C.ZodPrefault,"ZodPreprocess",()=>C.ZodPreprocess,"ZodPromise",()=>C.ZodPromise,"ZodReadonly",()=>C.ZodReadonly,"ZodRealError",()=>T.ZodRealError,"ZodRecord",()=>C.ZodRecord,"ZodSet",()=>C.ZodSet,"ZodString",()=>C.ZodString,"ZodStringFormat",()=>C.ZodStringFormat,"ZodSuccess",()=>C.ZodSuccess,"ZodSymbol",()=>C.ZodSymbol,"ZodTemplateLiteral",()=>C.ZodTemplateLiteral,"ZodTransform",()=>C.ZodTransform,"ZodTuple",()=>C.ZodTuple,"ZodType",()=>C.ZodType,"ZodULID",()=>C.ZodULID,"ZodURL",()=>C.ZodURL,"ZodUUID",()=>C.ZodUUID,"ZodUndefined",()=>C.ZodUndefined,"ZodUnion",()=>C.ZodUnion,"ZodUnknown",()=>C.ZodUnknown,"ZodVoid",()=>C.ZodVoid,"ZodXID",()=>C.ZodXID,"ZodXor",()=>C.ZodXor,"_ZodString",()=>C._ZodString,"_default",()=>C._default,"_function",()=>C._function,"any",()=>C.any,"array",()=>C.array,"base64",()=>C.base64,"base64url",()=>C.base64url,"bigint",()=>C.bigint,"boolean",()=>C.boolean,"catch",()=>C.catch,"check",()=>C.check,"cidrv4",()=>C.cidrv4,"cidrv6",()=>C.cidrv6,"clone",()=>i.clone,"codec",()=>C.codec,"coerce",0,M,"config",()=>r.config,"core",0,_,"cuid",()=>C.cuid,"cuid2",()=>C.cuid2,"custom",()=>C.custom,"date",()=>C.date,"decode",()=>D.decode,"decodeAsync",()=>D.decodeAsync,"describe",()=>C.describe,"discriminatedUnion",()=>C.discriminatedUnion,"e164",()=>C.e164,"email",()=>C.email,"emoji",()=>C.emoji,"encode",()=>D.encode,"encodeAsync",()=>D.encodeAsync,"endsWith",()=>E._endsWith,"enum",()=>C.enum,"exactOptional",()=>C.exactOptional,"file",()=>C.file,"flattenError",()=>s.flattenError,"float32",()=>C.float32,"float64",()=>C.float64,"formatError",()=>s.formatError,"fromJSONSchema",0,function(e,t){var r,i;let a,n;if("boolean"==typeof e)return e?L.any():L.never();try{a=JSON.parse(JSON.stringify(e))}catch{throw Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let s={version:(r=a,i=t?.defaultTarget,"https://json-schema.org/draft/2020-12/schema"===(n=r.$schema)?"draft-2020-12":"http://json-schema.org/draft-07/schema#"===n?"draft-7":"http://json-schema.org/draft-04/schema#"===n?"draft-4":i??"draft-2020-12"),defs:a.$defs||a.definitions||{},refs:new Map,processing:new Set,rootSchema:a,registry:t?.registry??k.globalRegistry};return function e(t,r){if("boolean"==typeof t)return t?L.any():L.never();let i=function t(r,i){let a;if(void 0!==r.not){if("object"==typeof r.not&&0===Object.keys(r.not).length)return L.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if(void 0!==r.unevaluatedItems)throw Error("unevaluatedItems is not supported");if(void 0!==r.unevaluatedProperties)throw Error("unevaluatedProperties is not supported");if(void 0!==r.if||void 0!==r.then||void 0!==r.else)throw Error("Conditional schemas (if/then/else) are not supported");if(void 0!==r.dependentSchemas||void 0!==r.dependentRequired)throw Error("dependentSchemas and dependentRequired are not supported");if(r.$ref){let t=r.$ref;if(i.refs.has(t))return i.refs.get(t);if(i.processing.has(t))return L.lazy(()=>{if(!i.refs.has(t))throw Error(`Circular reference not resolved: ${t}`);return i.refs.get(t)});i.processing.add(t);let a=e(function(e,t){if(!e.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let r=e.slice(1).split("/").filter(Boolean);if(0===r.length)return t.rootSchema;let i="draft-2020-12"===t.version?"$defs":"definitions";if(r[0]===i){let i=r[1];if(!i||!t.defs[i])throw Error(`Reference not found: ${e}`);return t.defs[i]}throw Error(`Reference not found: ${e}`)}(t,i),i);return i.refs.set(t,a),i.processing.delete(t),a}if(void 0!==r.enum){let e=r.enum;if("openapi-3.0"===i.version&&!0===r.nullable&&1===e.length&&null===e[0])return L.null();if(0===e.length)return L.never();if(1===e.length)return L.literal(e[0]);if(e.every(e=>"string"==typeof e))return L.enum(e);let t=e.map(e=>L.literal(e));return t.length<2?t[0]:L.union([t[0],t[1],...t.slice(2)])}if(void 0!==r.const)return L.literal(r.const);let n=r.type;if(Array.isArray(n)){let e=n.map(e=>t({...r,type:e},i));return 0===e.length?L.never():1===e.length?e[0]:L.union(e)}if(!n)return L.any();switch(n){case"string":{let e=L.string();if(r.format){let t=r.format;"email"===t?e=e.check(L.email()):"uri"===t||"uri-reference"===t?e=e.check(L.url()):"uuid"===t||"guid"===t?e=e.check(L.uuid()):"date-time"===t?e=e.check(L.iso.datetime()):"date"===t?e=e.check(L.iso.date()):"time"===t?e=e.check(L.iso.time()):"duration"===t?e=e.check(L.iso.duration()):"ipv4"===t?e=e.check(L.ipv4()):"ipv6"===t?e=e.check(L.ipv6()):"mac"===t?e=e.check(L.mac()):"cidr"===t?e=e.check(L.cidrv4()):"cidr-v6"===t?e=e.check(L.cidrv6()):"base64"===t?e=e.check(L.base64()):"base64url"===t?e=e.check(L.base64url()):"e164"===t?e=e.check(L.e164()):"jwt"===t?e=e.check(L.jwt()):"emoji"===t?e=e.check(L.emoji()):"nanoid"===t?e=e.check(L.nanoid()):"cuid"===t?e=e.check(L.cuid()):"cuid2"===t?e=e.check(L.cuid2()):"ulid"===t?e=e.check(L.ulid()):"xid"===t?e=e.check(L.xid()):"ksuid"===t&&(e=e.check(L.ksuid()))}"number"==typeof r.minLength&&(e=e.min(r.minLength)),"number"==typeof r.maxLength&&(e=e.max(r.maxLength)),r.pattern&&(e=e.regex(new RegExp(r.pattern))),a=e;break}case"number":case"integer":{let e="integer"===n?L.number().int():L.number();"number"==typeof r.minimum&&(e=e.min(r.minimum)),"number"==typeof r.maximum&&(e=e.max(r.maximum)),"number"==typeof r.exclusiveMinimum?e=e.gt(r.exclusiveMinimum):!0===r.exclusiveMinimum&&"number"==typeof r.minimum&&(e=e.gt(r.minimum)),"number"==typeof r.exclusiveMaximum?e=e.lt(r.exclusiveMaximum):!0===r.exclusiveMaximum&&"number"==typeof r.maximum&&(e=e.lt(r.maximum)),"number"==typeof r.multipleOf&&(e=e.multipleOf(r.multipleOf)),a=e;break}case"boolean":a=L.boolean();break;case"null":a=L.null();break;case"object":{let t={},n=r.properties||{},s=new Set(r.required||[]);for(let[r,a]of Object.entries(n)){let n=e(a,i);t[r]=s.has(r)?n:n.optional()}if(r.propertyNames){let n=e(r.propertyNames,i),s=r.additionalProperties&&"object"==typeof r.additionalProperties?e(r.additionalProperties,i):L.any();if(0===Object.keys(t).length){a=L.record(n,s);break}let o=L.object(t).passthrough(),l=L.looseRecord(n,s);a=L.intersection(o,l);break}if(r.patternProperties){let n=r.patternProperties,s=Object.keys(n),o=[];for(let t of s){let r=e(n[t],i),a=L.string().regex(new RegExp(t));o.push(L.looseRecord(a,r))}let l=[];if(Object.keys(t).length>0&&l.push(L.object(t).passthrough()),l.push(...o),0===l.length)a=L.object({}).passthrough();else if(1===l.length)a=l[0];else{let e=L.intersection(l[0],l[1]);for(let t=2;t<l.length;t++)e=L.intersection(e,l[t]);a=e}break}let o=L.object(t);a=!1===r.additionalProperties?o.strict():"object"==typeof r.additionalProperties?o.catchall(e(r.additionalProperties,i)):o.passthrough();break}case"array":{let t=r.prefixItems,n=r.items;if(t&&Array.isArray(t)){let s=t.map(t=>e(t,i)),o=n&&"object"==typeof n&&!Array.isArray(n)?e(n,i):void 0;a=o?L.tuple(s).rest(o):L.tuple(s),"number"==typeof r.minItems&&(a=a.check(L.minLength(r.minItems))),"number"==typeof r.maxItems&&(a=a.check(L.maxLength(r.maxItems)))}else if(Array.isArray(n)){let t=n.map(t=>e(t,i)),s=r.additionalItems&&"object"==typeof r.additionalItems?e(r.additionalItems,i):void 0;a=s?L.tuple(t).rest(s):L.tuple(t),"number"==typeof r.minItems&&(a=a.check(L.minLength(r.minItems))),"number"==typeof r.maxItems&&(a=a.check(L.maxLength(r.maxItems)))}else if(void 0!==n){let t=e(n,i),s=L.array(t);"number"==typeof r.minItems&&(s=s.min(r.minItems)),"number"==typeof r.maxItems&&(s=s.max(r.maxItems)),a=s}else a=L.array(L.any());break}default:throw Error(`Unsupported type: ${n}`)}return a}(t,r),a=t.type||void 0!==t.enum||void 0!==t.const;if(t.anyOf&&Array.isArray(t.anyOf)){let n=t.anyOf.map(t=>e(t,r)),s=L.union(n);i=a?L.intersection(i,s):s}if(t.oneOf&&Array.isArray(t.oneOf)){let n=t.oneOf.map(t=>e(t,r)),s=L.xor(n);i=a?L.intersection(i,s):s}if(t.allOf&&Array.isArray(t.allOf))if(0===t.allOf.length)i=a?i:L.any();else{let n=a?i:e(t.allOf[0],r),s=+!a;for(let i=s;i<t.allOf.length;i++)n=L.intersection(n,e(t.allOf[i],r));i=n}!0===t.nullable&&"openapi-3.0"===r.version&&(i=L.nullable(i)),!0===t.readOnly&&(i=L.readonly(i)),void 0!==t.default&&(i=i.default(t.default));let n={};for(let e of["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"])e in t&&(n[e]=t[e]);for(let e of["contentEncoding","contentMediaType","contentSchema"])e in t&&(n[e]=t[e]);for(let e of Object.keys(t))q.has(e)||(n[e]=t[e]);return Object.keys(n).length>0&&r.registry.add(i,n),t.description&&(i=i.describe(t.description)),i}(a,s)},"function",()=>C.function,"getErrorMap",0,P,"globalRegistry",()=>k.globalRegistry,"gt",()=>E._gt,"gte",()=>E._gte,"guid",()=>C.guid,"hash",()=>C.hash,"hex",()=>C.hex,"hostname",()=>C.hostname,"httpUrl",()=>C.httpUrl,"includes",()=>E._includes,"instanceof",()=>C.instanceof,"int",()=>C.int,"int32",()=>C.int32,"int64",()=>C.int64,"intersection",()=>C.intersection,"invertCodec",()=>C.invertCodec,"ipv4",()=>C.ipv4,"ipv6",()=>C.ipv6,"iso",0,j,"json",()=>C.json,"jwt",()=>C.jwt,"keyof",()=>C.keyof,"ksuid",()=>C.ksuid,"lazy",()=>C.lazy,"length",()=>E._length,"literal",()=>C.literal,"locales",0,v,"looseObject",()=>C.looseObject,"looseRecord",()=>C.looseRecord,"lowercase",()=>E._lowercase,"lt",()=>E._lt,"lte",()=>E._lte,"mac",()=>C.mac,"map",()=>C.map,"maxLength",()=>E._maxLength,"maxSize",()=>E._maxSize,"meta",()=>C.meta,"mime",()=>E._mime,"minLength",()=>E._minLength,"minSize",()=>E._minSize,"multipleOf",()=>E._multipleOf,"nan",()=>C.nan,"nanoid",()=>C.nanoid,"nativeEnum",()=>C.nativeEnum,"negative",()=>E._negative,"never",()=>C.never,"nonnegative",()=>E._nonnegative,"nonoptional",()=>C.nonoptional,"nonpositive",()=>E._nonpositive,"normalize",()=>E._normalize,"null",()=>C.null,"nullable",()=>C.nullable,"nullish",()=>C.nullish,"number",()=>C.number,"object",()=>C.object,"optional",()=>C.optional,"overwrite",()=>E._overwrite,"parse",()=>D.parse,"parseAsync",()=>D.parseAsync,"partialRecord",()=>C.partialRecord,"pipe",()=>C.pipe,"positive",()=>E._positive,"prefault",()=>C.prefault,"preprocess",()=>C.preprocess,"prettifyError",()=>s.prettifyError,"promise",()=>C.promise,"property",()=>E._property,"readonly",()=>C.readonly,"record",()=>C.record,"refine",()=>C.refine,"regex",()=>E._regex,"regexes",()=>$.regexes,"registry",()=>k.registry,"safeDecode",()=>D.safeDecode,"safeDecodeAsync",()=>D.safeDecodeAsync,"safeEncode",()=>D.safeEncode,"safeEncodeAsync",()=>D.safeEncodeAsync,"safeParse",()=>D.safeParse,"safeParseAsync",()=>D.safeParseAsync,"set",()=>C.set,"setErrorMap",0,O,"size",()=>E._size,"slugify",()=>E._slugify,"startsWith",()=>E._startsWith,"strictObject",()=>C.strictObject,"string",()=>C.string,"stringFormat",()=>C.stringFormat,"stringbool",()=>C.stringbool,"success",()=>C.success,"superRefine",()=>C.superRefine,"symbol",()=>C.symbol,"templateLiteral",()=>C.templateLiteral,"toJSONSchema",()=>x.toJSONSchema,"toLowerCase",()=>E._toLowerCase,"toUpperCase",()=>E._toUpperCase,"transform",()=>C.transform,"treeifyError",()=>s.treeifyError,"trim",()=>E._trim,"tuple",()=>C.tuple,"uint32",()=>C.uint32,"uint64",()=>C.uint64,"ulid",()=>C.ulid,"undefined",()=>C.undefined,"union",()=>C.union,"unknown",()=>C.unknown,"uppercase",()=>E._uppercase,"url",()=>C.url,"util",()=>B.util,"uuid",()=>C.uuid,"uuidv4",()=>C.uuidv4,"uuidv6",()=>C.uuidv6,"uuidv7",()=>C.uuidv7,"void",()=>C.void,"xid",()=>C.xid,"xor",()=>C.xor],562810);var F=e.i(562810);e.s(["z",0,F],469719)},497800,835544,499162,248626,e=>{"use strict";var t=e.i(469719),r=e.i(807055),i=e.i(184015),a=e.i(119909);let n=["JIRA_LOAD_TICKET","JIRA_TRANSITION","JIRA_COMMENT","JIRA_ASSIGN","JIRA_UPDATE_FIELDS","JIRA_RESOLVE_BRANCH","GITHUB_LOAD_PR","GITHUB_MERGE_PR","GITHUB_COLLECT_REVIEW_THREADS","GITHUB_REPLY_REVIEW_THREAD","GITHUB_SET_REVIEW_THREAD_RESOLVED","GITHUB_CREATE_PR","GITHUB_SET_PR_LABELS","GITHUB_RETRY_PIPELINE","GITHUB_RETRY_JOB","GITHUB_CANCEL_WORKFLOW_RUN","GITHUB_SAVE_AUTO_RETRY","GITHUB_WAIT_CHECKS","WORKTREE_CREATE","WORKTREE_CHANGE_BRANCH","WORKTREE_REFRESH_PULL_REQUEST","WORKTREE_OPERATION","WORKTREE_SET_AUTO_SYNC","WORKTREE_SET_AUTO_MERGE","WORKTREE_DELETE","WORKTREE_MOVE","WORKTREE_INSPECT","WORKTREE_INSPECT_GIT","WORKTREE_GIT_OPERATION","WORKTREE_WAIT_PUSH_READY","WORKTREE_SNAPSHOT","CODEBASE_FETCH_REFRESH","CODEBASE_INSPECT_GIT","CODEBASE_GIT_OPERATION","BUILD_START","BUILD_READ_TEST_RESULTS","BUILD_READ_COVERAGE","BUILD_IMPORT_COVERAGE","BUILD_EXPORT","BUILD_DEPLOY","BUILD_CANCEL","DISK_SPACE_LOAD","DISK_SPACE_REFRESH","DISK_SPACE_UPDATE_THRESHOLDS","DISK_SPACE_SET_MONITORING","DISK_SPACE_SET_PRESSURE_MODE","SKILL_APPLY","RUN_CREATE_PLAN","RUN_CREATE_SESSION","RUN_PLAY_PLAN","RUN_FOLLOW_UP","RUN_STEER","RUN_ANSWER","RUN_PAUSE","RUN_CONTINUE","RUN_CANCEL","RUN_REVISE_ANSWER","RUN_READ_RESULT","RUN_CAPTURE_CHECKPOINT","RUN_ARCHIVE_DELETE","NOTIFICATION_SEND","IOS_PUSH_SEND","HUMAN_CONFIRM","HUMAN_CHOICE","CONTROL_IF","CONTROL_JOIN","CONTROL_DELAY","CONTROL_WAIT_UNTIL","CONTROL_FOR_EACH","CONTROL_TRY","CONTROL_SET_VARIABLE","CONTROL_SUBWORKFLOW","SAVED_COMMAND","CUSTOM_COMMAND","COMMAND_RERUN","COMMAND_TERMINATE","COMMAND_READ_OUTPUT","WORKTREE_INSPECT_DIFF","WORKTREE_UPDATE_METADATA","WORKTREE_MOVE_CONTROL","BUILD_REBUILD","BUILD_GENERATE_REPORT","BUILD_DELETE","SKILL_PREPARE_SYNC","SKILL_RESOLVE_SYNC","SKILL_SKIP_SYNC","BUILD_DATA_REFRESH","BUILD_DATA_DELETE","BUILD_DATA_SET_LOCK","SIGNING_REFRESH","SIGNING_SYNC_PROFILE","SIGNING_DELETE_EXPIRED","IOS_DEVICE_REGISTER","IOS_DEVICE_REJECT","AGENT_RECONCILE","AGENT_UPDATE_CADENCE","CCUSAGE_COLLECT","MODEL_COST_REFRESH","GITHUB_UPDATE_PR","GITHUB_SUBMIT_REVIEW","GITHUB_REQUEST_REVIEWERS","GITHUB_DISPATCH_WORKFLOW","JIRA_CREATE_TICKET","JIRA_ADD_WORKLOG","JIRA_LINK_TICKETS","TERMINAL_RUN","MCP_CALL"],s=["MANUAL","MANUAL_CHOICE","RESOURCE_MANUAL","RESOURCE_MANUAL_CHOICE","SCHEDULE","WORKFLOW_FINISHED","GITHUB_PR_STATE","GITHUB_REVIEW_CHANGES_REQUESTED","GITHUB_REVIEW_COMMENT","GITHUB_PR_CLOSED","GITHUB_CHECK_FAILED","GITHUB_PUSH_DEFAULT","GITHUB_WORKFLOW_SUCCEEDED","GITHUB_ISSUE_COMMAND","GITHUB_ACTIONS_RESULT","GITHUB_PR_LABEL","BUILD_RESULT","BUILD_TEST_THRESHOLD","BUILD_COVERAGE_THRESHOLD","BUILD_HOOK_FAILED","AGENT_CONNECTION","AGENT_JOB_FAILED","AGENT_DISK_REPORT","AGENT_DISK_THRESHOLD","AGENT_DISK_STATE_CHANGED","AGENT_DISK_CLEANUP_RESULT","CCUSAGE_THRESHOLD","WORKTREE_CREATED","WORKTREE_BEHIND","WORKTREE_CONFLICT","WORKTREE_MISSING","WORKTREE_DIVERGED","WORKTREE_DIRTY_DURATION","WORKTREE_NEW_COMMIT","CODEBASE_REMOTE_BRANCH","JIRA_STATUS","JIRA_LABEL","JIRA_ASSIGNED_SELF","JIRA_SOURCE_NEW_TICKET","JIRA_MENTION","JIRA_SPRINT_STARTED","JIRA_ISSUE_CREATED","JIRA_ISSUE_DELETED","JIRA_ISSUE_COMMAND","JIRA_ATTACHMENT_ADDED","JIRA_ISSUE_LINKED","RUN_STARTED","RUN_COMPLETED","RUN_QUESTION_NEEDED","RUN_QUESTION_ANSWERED","RUN_PAUSED","RUN_CONTINUED","RUN_FAILED","RUN_CANCELLED","RUN_PLAN_PLAYED","RUN_FOLLOW_UP","RUN_IMPORTED","RUN_USAGE_THRESHOLD","RUN_EVENT_MATCH","COMMAND_RUN_RESULT","COMMAND_OUTPUT_MATCH","SKILL_SYNC_RESULT","SKILL_SYNC_CONFLICT","GITHUB_PIPELINE_STATUS_CHANGED","GITHUB_PR_SYNCHRONIZED","GITHUB_REVIEW_APPROVED","JIRA_TICKET_UPDATED","JIRA_COMMENT_ADDED","JIRA_WORKLOG_ADDED","JIRA_SPRINT_ENDED","CODEBASE_SYNC_STATE_CHANGED","CODEBASE_OPERATION_FAILED","WORKTREE_SYNC_STATE_CHANGED","WORKTREE_AUTOMATION_RESULT","WORKTREE_CLEAN","PUSH_NOTIFICATION_RESULT","IOS_DEVICE_ENROLLED","IOS_DEVICE_REGISTRATION_RESULT","SIGNING_OPERATION_RESULT","SIGNING_ASSET_EXPIRING","BUILD_DATA_THRESHOLD","BUILD_DATA_CLEANUP_RESULT","POLLING_OPERATION_STATE","MODEL_COST_CATALOG_CHANGED","CREDENTIAL_STORE_DEGRADED","AGENT_RESOURCE_THRESHOLD","AGENT_VERSION_CHANGED","TOOL_CALL_RESULT"],o=["BUILD","CODEBASE","JIRA_TICKET","AGENT_RUN","GITHUB_PIPELINE","GITHUB_JOB","PULL_REQUEST","WORKTREE","COMMAND_RUN","SKILL","SKILL_SYNC","IOS_DEVICE","SIGNING_PROFILE","PUSH_NOTIFICATION_BATCH","BUILD_DATA_COLLECTION"],l=new Set(["MANUAL_CHOICE","RESOURCE_MANUAL_CHOICE"]),u=new Set(["RESOURCE_MANUAL","RESOURCE_MANUAL_CHOICE"]);function c(e){return l.has(e)}function d(e){return u.has(e)}let p=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function h(e){return"string"==typeof e&&p.test(e)}function m(e){return c(e)?[]:"CONTROL_IF"===e?["true","false"]:"CONTROL_FOR_EACH"===e?["body","empty"]:"CONTROL_TRY"===e?["success","catch"]:["success","failure"]}e.s(["WORKFLOW_CHOICE_KEY_PATTERN",0,p,"WORKFLOW_QUICK_ACTION_KINDS",0,["STANDARD","MERGE_CONFLICT","GITHUB_ACTIONS","NONE"],"WORKFLOW_RESOURCE_KINDS",0,o,"WORKFLOW_STEP_KINDS",0,n,"WORKFLOW_TRIGGER_KINDS",0,s,"isChoiceTriggerKind",0,c,"isResourceTriggerKind",0,d,"isWorkflowChoiceKey",0,h,"workflowStaticSourceHandles",0,m],835544);let f=/^([A-Za-z0-9_-]+)(?:\[(\d+)\])?$/,g=/^[A-Za-z0-9_-]+(?:\[\d+\])?(?:\.[A-Za-z0-9_-]+(?:\[\d+\])?)*$/,y=/\{\{\s*([A-Za-z0-9_-]+(?:\[\d+\])?(?:\.[A-Za-z0-9_-]+(?:\[\d+\])?)*)\s*\}\}/g,w=/\{\{([^{}]*)\}\}/g;function b(e){return e.split(".").flatMap(t=>{let r=f.exec(t);if(!r)throw Error(`Invalid session path: ${e}`);return void 0===r[2]?[r[1]]:[r[1],Number(r[2])]})}function v(e,t){let r=e;for(let e of b(t)){if(null==r)return;if("number"==typeof e){if(!Array.isArray(r))return;r=r[e]}else{if("object"!=typeof r||Array.isArray(r))return;r=r[e]}}return r}function k(e,t){var r,i;return e&&"object"==typeof e&&!Array.isArray(e)&&"SESSION"===e.source&&"string"==typeof e.path?v(t,e.path):e&&"object"==typeof e&&!Array.isArray(e)&&"LITERAL"===e.source?e.value:Array.isArray(e)?e.map(e=>k(e,t)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,r])=>[e,k(r,t)])):"string"==typeof e?(r=e,i=t,r.replace(y,(e,t)=>{let r=v(i,t);return null==r?"":"string"==typeof r?r:JSON.stringify(r)})):e}function S(e,t=new Set){if(Array.isArray(e))for(let r of e)S(r,t);else if(e&&"object"==typeof e)for(let r of("SESSION"===e.source&&"string"==typeof e.path&&g.test(e.path)&&t.add(e.path),Object.values(e)))S(r,t);else if("string"==typeof e)for(let r of e.matchAll(y))t.add(r[1]);return t}function E(e,t=[]){if(Array.isArray(e))for(let r of e)E(r,t);else if(e&&"object"==typeof e)for(let r of("SESSION"!==e.source||"string"==typeof e.path&&g.test(e.path)||t.push("Session bindings require a valid dotted path"),Object.values(e)))E(r,t);else if("string"==typeof e&&/\{\{|\}\}/.test(e)){let r=e.replace(w,"");for(let i of(/\{\{|\}\}/.test(r)&&t.push("Text interpolation contains unmatched braces"),e.matchAll(w)))g.test(i[1].trim())||t.push("Text interpolation requires a valid dotted path")}return t}function I(e){return null===e||["string","number","boolean"].includes(typeof e)?e:JSON.stringify(e)}function x(e){return{kind:"static",options:e.map(e=>({value:e,label:e.charAt(0)+e.slice(1).toLowerCase().replace(/_/g," ")}))}}function A(e){return{kind:"static",options:e}}e.s(["evaluateWorkflowCondition",0,function e(t,r){if("ALL"===t.op)return t.conditions.every(t=>e(t,r));if("ANY"===t.op)return t.conditions.some(t=>e(t,r));if("NOT"===t.op)return!e(t.condition,r);if(!("left"in t))return!1;let i=k(t.left,r),a=k(t.right,r);switch(t.op){case"EXISTS":return null!=i;case"EQ":return JSON.stringify(i)===JSON.stringify(a);case"NE":return JSON.stringify(i)!==JSON.stringify(a);case"GT":return I(i)>I(a);case"GTE":return I(i)>=I(a);case"LT":return I(i)<I(a);case"LTE":return I(i)<=I(a);case"CONTAINS":return Array.isArray(i)?i.some(e=>JSON.stringify(e)===JSON.stringify(a)):String(i??"").includes(String(a??""));case"MATCHES":return new RegExp(String(a??"")).test(String(i??""))}},"getSessionValue",0,v,"hasSessionValue",0,function(e,t){return void 0!==v(e,t)},"invalidWorkflowValueBindings",0,E,"mergeSessionData",0,function(e,t){let r=(e,t)=>{if(e&&t&&"object"==typeof e&&"object"==typeof t&&!Array.isArray(e)&&!Array.isArray(t)){let i={...e};for(let[e,a]of Object.entries(t))i[e]=r(i[e],a);return i}return structuredClone(t)};return r(e,t)},"resolveWorkflowValue",0,k,"setSessionValue",0,function(e,t,r){let i=structuredClone(e),a=b(t),n=i;return a.forEach((e,i)=>{if(i===a.length-1){if("number"==typeof e){if(!Array.isArray(n))throw Error(`Expected an array at ${t}`);n[e]=r}else{if(Array.isArray(n))throw Error(`Expected an object at ${t}`);n[e]=r}return}let s="number"==typeof a[i+1];if("number"==typeof e){if(!Array.isArray(n))throw Error(`Expected an array at ${t}`);let r=n[e];r&&"object"==typeof r||(n[e]=s?[]:{}),n=n[e]}else{if(Array.isArray(n))throw Error(`Expected an object at ${t}`);let r=n[e];r&&"object"==typeof r||(n[e]=s?[]:{}),n=n[e]}}),i},"workflowSessionData",0,function(e){let t=JSON.parse(e);if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Workflow session data must be a JSON object");return t},"workflowValueSessionPaths",0,S],499162);let _={agent:"agent.id",codebase:"codebase.id",worktree:"worktree.id",githubRepository:"repo.id",githubPullRequest:"pr.number",jiraTicket:"ticket.key",agentRun:"run.id",githubWorkflowRun:"pipeline.runId"};function C(e,t){return{kind:"resource",resource:e,scopeFrom:t,sessionPath:_[e]}}let R=["literal","session","interpolation"],T=["literal","interpolation"],D=(e,t,r={})=>({key:e,label:t,control:"text",valueModes:R,...r}),N=(e,t,r={})=>D(e,t,{multiline:!0,...r}),O=(e,t,r={})=>({key:e,label:t,control:"number",valueModes:["literal","session"],...r}),P=(e,t,r={})=>({key:e,label:t,control:"boolean",...r}),$=(e,t,r,i={})=>({key:e,label:t,control:"enum",options:r,...i}),U=(e,t,r,i={})=>{let{scopeFrom:a,...n}=i;return{key:e,label:t,control:"resource",options:C(r,a),valueModes:R,...n}},B=(e,t,r,i={})=>{let{scopeFrom:a,...n}=i;return{key:e,label:t,control:"resourceMulti",options:C(r,a),valueModes:T,...n}},j=(e,t,r={})=>({key:e,label:t,control:"stringList",valueModes:T,...r}),L=e=>({key:"mcpPresetIds",label:"MCP tool presets",control:"mcpPresetMulti",presetKind:e,default:[]}),q=(e,t,r={})=>({key:e,label:t,control:"record",valueModes:T,...r}),M=(e,t,r={})=>({key:e,label:t,control:"json",valueModes:T,...r}),F=(e,t,r={})=>({key:e,label:t,control:"triggerChoices",...r}),K=A([{value:"EQ",label:"Equals"},{value:"NE",label:"Not equal"},{value:"GT",label:"Greater than"},{value:"GTE",label:"Greater or equal"},{value:"LT",label:"Less than"},{value:"LTE",label:"Less or equal"},{value:"CONTAINS",label:"Contains"},{value:"MATCHES",label:"Matches regex"},{value:"EXISTS",label:"Exists"}]),V=x(a.WORKTREE_OPERATIONS.filter(e=>"OPEN_EDITOR"!==e)),G=()=>[D("owner","Repository owner",{placeholder:"octocat",help:"Defaults to the repository from session data."}),D("name","Repository name",{placeholder:"hello-world"})],H=e=>[U("worktreeId","Worktree","worktree"),U("jiraIssueKey","Jira issue key","jiraTicket",{placeholder:"APP-123"}),{key:"model",label:"Model",control:"model",required:!0,valueModes:["literal","session"],modelKeys:{provider:"provider",model:"model",effort:"effort",scopeFrom:"worktreeId"}},P("webSearchEnabled","Enable web search"),L(e),O("worktreeConcurrencyLimit","Worktree concurrency limit",{default:"PLAN"===e?0:"SESSION"===e?1:void 0,minimum:0,maximum:32,integer:!0,help:"PLAN"===e?"Maximum plans admitted on this worktree. Use 0 for unlimited.":"SESSION"===e?"Maximum sessions admitted on this worktree. Use 0 for unlimited.":"Maximum same-kind runs admitted on this worktree. Use 0 for unlimited; leave empty for the source kind's default."}),N("prompt","Prompt",{required:!0}),j("attachmentIds","Attachment IDs")],W={JIRA_LOAD_TICKET:{fields:[U("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),P("force","Bypass cache")]},JIRA_TRANSITION:{fields:[U("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),D("transitionId","Transition ID",{required:!0})]},JIRA_COMMENT:{fields:[U("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),N("content","Comment",{required:!0}),$("format","Format",A([{value:"MARKDOWN",label:"Markdown"},{value:"JIRA_WIKI",label:"Jira wiki"}]))]},JIRA_ASSIGN:{fields:[U("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),U("accountId","Assignee","jiraUser",{scopeFrom:"issueKey",help:"Leave empty to unassign the ticket."})]},JIRA_UPDATE_FIELDS:{fields:[U("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),M("fields","Fields",{placeholder:'{ "labels": ["ready"] }'})]},JIRA_RESOLVE_BRANCH:{fields:[U("issueKey","Issue key","jiraTicket",{placeholder:"APP-123"}),U("codebaseId","Codebase","codebase")]},GITHUB_LOAD_PR:{fields:[...G(),O("number","Pull request number")]},GITHUB_MERGE_PR:{fields:[...G(),O("number","Pull request number"),$("method","Merge method",A([{value:"SQUASH",label:"Squash"},{value:"MERGE",label:"Merge"},{value:"REBASE",label:"Rebase"}])),D("commitHeadline","Commit headline"),N("commitBody","Commit body"),D("authorEmail","Author email")]},GITHUB_COLLECT_REVIEW_THREADS:{fields:[...G(),O("number","Pull request number")]},GITHUB_REPLY_REVIEW_THREAD:{fields:[D("threadId","Review thread ID",{required:!0}),N("body","Reply",{required:!0})]},GITHUB_SET_REVIEW_THREAD_RESOLVED:{fields:[D("threadId","Review thread ID",{required:!0}),P("resolved","Mark resolved")]},GITHUB_CREATE_PR:{fields:[...G(),D("baseRefName","Base branch"),D("headRefName","Head branch"),D("title","Title"),N("body","Body"),P("draft","Open as draft")]},GITHUB_SET_PR_LABELS:{fields:[...G(),O("number","Pull request number"),j("labels","Labels")]},GITHUB_RETRY_PIPELINE:{fields:[U("repositoryId","Repository","githubRepository"),D("checkSuiteId","Check suite ID")]},GITHUB_RETRY_JOB:{fields:[U("repositoryId","Repository","githubRepository"),D("checkSuiteId","Check suite ID",{required:!0}),D("jobId","Workflow job ID",{required:!0})]},GITHUB_CANCEL_WORKFLOW_RUN:{fields:[D("codebaseRepositoryId","Codebase repository ID"),U("workflowRunId","Workflow run","githubWorkflowRun",{scopeFrom:"codebaseRepositoryId"}),P("force","Force cancel")]},GITHUB_SAVE_AUTO_RETRY:{fields:[M("input","Auto-retry rule",{required:!0})]},GITHUB_WAIT_CHECKS:{fields:[D("repositoryId","Repository ID"),D("workflowRunId","Workflow run ID")]},WORKTREE_CREATE:{fields:[U("codebaseId","Codebase","codebase"),$("mode","Branch mode",x(["NEW","EXISTING","TICKET"])),D("branchName","Branch name"),D("ticketKey","Ticket key",{placeholder:"APP-123"}),D("baseBranch","Base branch")]},WORKTREE_CHANGE_BRANCH:{fields:[U("worktreeId","Worktree","worktree"),$("mode","Branch mode",x(["NEW","EXISTING","TICKET"])),D("branchName","Branch name"),D("ticketKey","Ticket key",{placeholder:"APP-123"}),D("baseBranch","Base branch"),P("stashOnFailure","Stash on failure")]},WORKTREE_REFRESH_PULL_REQUEST:{fields:[U("worktreeId","Worktree","worktree")]},WORKTREE_OPERATION:{fields:[U("worktreeId","Worktree","worktree"),$("operation","Operation",V)]},WORKTREE_SET_AUTO_SYNC:{fields:[U("worktreeId","Worktree","worktree"),$("action","Action",x(["ENABLE","RETRY","CANCEL"])),D("conflictWorkflowId","Conflict workflow ID"),D("conflictWorkflowChoice","Conflict workflow choice")]},WORKTREE_SET_AUTO_MERGE:{fields:[U("worktreeId","Worktree","worktree"),$("action","Action",x(["ENABLE","RETRY","CANCEL"])),D("repositoryNameWithOwner","Repository",{placeholder:"owner/repository"}),O("pullRequestNumber","Pull request number"),$("method","Merge method",x(["MERGE","REBASE","SQUASH"])),D("commitHeadline","Commit headline"),N("commitBody","Commit body"),D("authorEmail","Author email"),P("deleteWorktree","Delete worktree after merge"),P("moveTicketToDone","Move Jira ticket to done")]},WORKTREE_DELETE:{fields:[U("worktreeId","Worktree","worktree"),P("deleteRemoteBranch","Delete remote branch")]},WORKTREE_MOVE:{fields:[U("worktreeId","Source worktree","worktree"),U("targetCodebaseId","Target codebase","codebase",{required:!0}),U("targetWorktreeId","Target worktree","worktree"),P("deleteSource","Delete source")]},WORKTREE_INSPECT:{fields:[U("worktreeId","Worktree","worktree")]},WORKTREE_INSPECT_GIT:{fields:[U("worktreeId","Worktree","worktree")]},WORKTREE_GIT_OPERATION:{fields:[U("worktreeId","Worktree","worktree"),$("operation","Operation",x(a.WORKTREE_GIT_OPERATIONS)),D("branch","Branch"),D("stashOid","Stash OID"),P("stashChanges","Stash changes first")]},WORKTREE_WAIT_PUSH_READY:{fields:[U("worktreeId","Worktree","worktree")]},WORKTREE_SNAPSHOT:{fields:[D("kind","Checkpoint kind",{placeholder:"STEP"})]},CODEBASE_FETCH_REFRESH:{fields:[U("codebaseId","Codebase","codebase"),$("operation","Operation",x(["FETCH","REFRESH"]))]},CODEBASE_INSPECT_GIT:{fields:[U("codebaseId","Codebase","codebase")]},CODEBASE_GIT_OPERATION:{fields:[U("codebaseId","Codebase","codebase"),$("operation","Operation",x(i.CODEBASE_GIT_OPERATIONS)),D("branch","Branch"),D("stashOid","Stash OID"),P("stashChanges","Stash changes first")]},BUILD_START:{fields:[U("worktreeId","Worktree","worktree"),D("configurationId","Build configuration ID",{required:!0}),$("action","Action",x(r.BUILD_ACTIONS)),M("destination","Destination"),B("scriptIds","Build scripts","buildScript"),M("advancedSettings","Advanced settings"),P("exportWhenComplete","Export when complete"),M("exportSettings","Export settings"),P("worktreeCoverage","Collect worktree coverage")]},BUILD_READ_TEST_RESULTS:{fields:[D("buildId","Build ID")]},BUILD_READ_COVERAGE:{fields:[D("buildId","Build ID")]},BUILD_IMPORT_COVERAGE:{fields:[U("worktreeId","Worktree","worktree"),D("buildName","Build name",{default:"{{workflow.name}}",help:"Name shown on the build and coverage pages. Defaults to the workflow name."}),D("reportPath","Coverage file",{required:!0,default:"coverage/lcov.info",help:"Path inside the worktree, written by whichever test command ran first."}),$("format","Coverage format",x(["AUTO","LCOV","ISTANBUL"]))]},BUILD_EXPORT:{fields:[D("buildId","Build ID"),M("settings","Export settings",{required:!0})]},BUILD_DEPLOY:{fields:[D("buildId","Build ID"),M("destinations","Destinations")]},BUILD_CANCEL:{fields:[D("buildId","Build ID")]},DISK_SPACE_LOAD:{fields:[U("agentId","Agent","agent")]},DISK_SPACE_REFRESH:{fields:[U("agentId","Agent","agent")]},DISK_SPACE_UPDATE_THRESHOLDS:{fields:[O("normalThresholdGiB","Normal threshold (GiB)",{required:!0}),O("pressureThresholdGiB","Pressure threshold (GiB)",{required:!0})]},DISK_SPACE_SET_MONITORING:{fields:[U("agentId","Agent","agent"),P("enabled","Monitoring enabled",{required:!0,default:!0})]},DISK_SPACE_SET_PRESSURE_MODE:{fields:[U("agentId","Agent","agent"),P("enabled","Manual pressure mode",{required:!0,default:!0})]},SKILL_APPLY:{fields:[U("groupId","Skill group","skillGroup",{help:"Leave empty to sync all skills."})]},NOTIFICATION_SEND:{fields:[D("title","Title",{required:!0}),N("body","Body",{required:!0}),D("href","Link")]},IOS_PUSH_SEND:{fields:[$("targetMode","Target mode",x(["ALL","DEVICES","BROADCAST","DIRECT"])),B("registrationIds","Registrations","apnsRegistration"),U("channelId","Broadcast channel","apnsChannel"),M("editor","Notification editor"),D("directToken","Direct device token"),$("directTokenEncoding","Token encoding",x(["HEX","BASE64"])),$("directEnvironment","Environment",x(["SANDBOX","PRODUCTION"]))]},COMMAND_RERUN:{fields:[D("commandRunId","Command run ID",{required:!0})]},COMMAND_TERMINATE:{fields:[D("commandRunId","Command run ID",{required:!0})]},COMMAND_READ_OUTPUT:{fields:[D("commandRunId","Command run ID",{required:!0}),O("first","Maximum chunks")]},WORKTREE_INSPECT_DIFF:{fields:[D("worktreeId","Worktree ID"),D("scope","Diff scope",{required:!0}),D("path","Path"),D("previousPath","Previous path"),D("commitSha","Commit SHA")]},WORKTREE_UPDATE_METADATA:{fields:[D("worktreeId","Worktree ID"),D("baseBranch","Base branch"),D("highlightColor","Highlight color")]},WORKTREE_MOVE_CONTROL:{fields:[D("moveId","Move ID",{required:!0}),$("operation","Operation",x(["RETRY_WITH_STASH","CANCEL"]))]},BUILD_REBUILD:{fields:[D("buildId","Build ID")]},BUILD_GENERATE_REPORT:{fields:[D("buildId","Build ID"),$("reportKind","Report kind",x(["TEST_RESULTS","CODE_COVERAGE"]))]},BUILD_DELETE:{fields:[j("buildIds","Build IDs")]},SKILL_PREPARE_SYNC:{fields:[$("syncKind","Sync kind",x(["ALL","GROUP"])),D("groupId","Skill group ID")]},SKILL_RESOLVE_SYNC:{fields:[D("runId","Sync run ID",{required:!0}),D("itemId","Conflict item ID",{required:!0}),$("resolution","Resolution",x(["LOCAL","REMOTE","SKIP"]))]},SKILL_SKIP_SYNC:{fields:[D("runId","Sync run ID",{required:!0})]},BUILD_DATA_REFRESH:{fields:[]},BUILD_DATA_DELETE:{fields:[D("collectionId","Collection ID",{required:!0}),j("entryIds","Entry IDs"),P("overrideProtection","Override protection")]},BUILD_DATA_SET_LOCK:{fields:[D("collectionId","Collection ID",{required:!0}),D("entryId","Entry ID",{required:!0}),P("locked","Locked")]},SIGNING_REFRESH:{fields:[j("agentIds","Agent IDs")]},SIGNING_SYNC_PROFILE:{fields:[D("uuid","Profile UUID",{required:!0}),D("sourceAgentId","Source agent ID",{required:!0}),j("targetAgentIds","Target agent IDs")]},SIGNING_DELETE_EXPIRED:{fields:[j("agentIds","Agent IDs")]},IOS_DEVICE_REGISTER:{fields:[D("deviceId","Device ID",{required:!0})]},IOS_DEVICE_REJECT:{fields:[D("deviceId","Device ID",{required:!0})]},AGENT_RECONCILE:{fields:[j("agentIds","Agent IDs")]},AGENT_UPDATE_CADENCE:{fields:[D("agentId","Agent ID",{required:!0}),M("settings","Cadence settings")]},CCUSAGE_COLLECT:{fields:[]},MODEL_COST_REFRESH:{fields:[]},GITHUB_UPDATE_PR:{fields:[D("owner","Owner",{required:!0}),D("name","Repository",{required:!0}),O("number","Pull request number",{required:!0}),D("title","Title"),N("body","Body"),P("draft","Draft")]},GITHUB_SUBMIT_REVIEW:{fields:[D("owner","Owner",{required:!0}),D("name","Repository",{required:!0}),O("number","Pull request number",{required:!0}),$("event","Review event",x(["APPROVE","REQUEST_CHANGES","COMMENT"])),N("body","Body")]},GITHUB_REQUEST_REVIEWERS:{fields:[D("owner","Owner",{required:!0}),D("name","Repository",{required:!0}),O("number","Pull request number",{required:!0}),j("reviewers","Reviewers"),j("teamReviewers","Team reviewers")]},GITHUB_DISPATCH_WORKFLOW:{fields:[D("repositoryId","Repository ID",{required:!0}),D("workflowId","Workflow ID",{required:!0}),D("ref","Git ref",{required:!0}),q("inputs","Workflow inputs")]},JIRA_CREATE_TICKET:{fields:[D("projectKey","Project key",{required:!0}),D("issueTypeId","Issue type ID",{required:!0}),D("summary","Summary",{required:!0}),N("description","Description"),M("fields","Additional fields")]},JIRA_ADD_WORKLOG:{fields:[D("issueKey","Issue key"),O("timeSpentSeconds","Time spent (seconds)",{required:!0}),D("startedAt","Started at"),N("comment","Comment")]},JIRA_LINK_TICKETS:{fields:[D("inwardIssueKey","Inward issue key",{required:!0}),D("outwardIssueKey","Outward issue key",{required:!0}),D("linkType","Link type",{required:!0})]},MCP_CALL:{fields:[U("groupId","MCP server","mcpServer",{required:!0}),D("name","Tool name",{required:!0}),M("arguments","Arguments")]},RUN_CREATE_PLAN:{fields:H("PLAN")},RUN_CREATE_SESSION:{fields:H("SESSION")},RUN_PLAY_PLAN:{fields:[D("runId","Plan run ID"),L("SESSION"),O("worktreeConcurrencyLimit","Worktree concurrency limit",{default:1,minimum:0,maximum:32,integer:!0,help:"Maximum sessions admitted on this worktree. Use 0 for unlimited."})]},RUN_FOLLOW_UP:{fields:[D("runId","Source run ID"),...H(null),$("followUpMode","Follow-up mode",x(["RESUME","FRESH","RESEND"])),D("contextMode","Context mode")]},RUN_STEER:{fields:[D("runId","Run ID"),N("prompt","Steering prompt",{required:!0}),j("attachmentIds","Attachment IDs")]},RUN_ANSWER:{fields:[D("batchId","Question batch ID",{required:!0}),M("answers","Answers")]},RUN_PAUSE:{fields:[D("runId","Run ID")]},RUN_CONTINUE:{fields:[D("runId","Run ID")]},RUN_CANCEL:{fields:[D("runId","Run ID")]},RUN_REVISE_ANSWER:{fields:[D("batchId","Question batch ID",{required:!0}),M("answers","Answers"),P("stash","Stash before revision"),P("rollback","Roll back to the question")]},RUN_READ_RESULT:{fields:[D("runId","Run ID")]},RUN_CAPTURE_CHECKPOINT:{fields:[D("runId","Run ID")]},RUN_ARCHIVE_DELETE:{fields:[D("runId","Run ID"),P("delete","Delete permanently"),P("archived","Archive")]},HUMAN_CONFIRM:{fields:[N("prompt","Prompt")]},HUMAN_CHOICE:{fields:[N("prompt","Prompt"),P("multiSelect","Allow multiple selections"),P("allowCustom","Allow a custom answer"),((e,t,r={})=>({key:e,label:t,control:"choiceOptions",valueModes:T,...r}))("options","Buttons")]},CONTROL_IF:{fields:[((e,t,r={})=>({key:e,label:t,control:"condition",valueModes:T,...r}))("condition","Condition",{required:!0})]},CONTROL_JOIN:{fields:[$("mode","Join mode",A([{value:"ALL",label:"All — wait for every branch"},{value:"ANY",label:"Any — continue on the first branch"}]),{help:"All (default) waits until every incoming branch has finished before continuing. Any continues as soon as the first incoming branch arrives, and the remaining branches keep running on their own. Either way, branches that were skipped do not block the join, and the join itself is skipped when no branch reaches it."})]},CONTROL_DELAY:{fields:[O("seconds","Delay (seconds)",{required:!0})]},CONTROL_WAIT_UNTIL:{fields:[M("condition","Condition",{required:!0})]},CONTROL_FOR_EACH:{fields:[D("listPath","List session path",{placeholder:"pr.unresolvedThreads"}),M("items","Inline items"),$("errorMode","Error handling",A([{value:"FAIL_FAST",label:"Fail fast"},{value:"COLLECT_ERRORS",label:"Collect errors"}]))]},CONTROL_TRY:{fields:[]},CONTROL_SET_VARIABLE:{fields:[D("path","Output path",{required:!0,placeholder:"flags.ready"}),M("value","Value"),N("script","Script")]},CONTROL_SUBWORKFLOW:{fields:[D("versionId","Sub-workflow version ID",{required:!0}),M("inputMapping","Input mapping")]},SAVED_COMMAND:{fields:[D("commandId","Saved command ID",{required:!0}),$("completionMode","Completion",x(["WAIT_FOR_EXIT","FIRE_AND_FORGET"])),$("targetMode","Target",x(["CONTEXT","FIXED_AGENT","FIXED_WORKTREE"])),D("agentId","Fixed agent ID",{visibleWhen:{key:"targetMode",equals:"FIXED_AGENT"}}),D("worktreeId","Fixed worktree ID",{visibleWhen:{key:"targetMode",equals:"FIXED_WORKTREE"}})]},CUSTOM_COMMAND:{fields:[N("script","Script",{required:!0}),$("completionMode","Completion",x(["WAIT_FOR_EXIT","FIRE_AND_FORGET"])),$("targetMode","Target",x(["CONTEXT","FIXED_AGENT","FIXED_WORKTREE"])),D("agentId","Fixed agent ID",{visibleWhen:{key:"targetMode",equals:"FIXED_AGENT"}}),D("worktreeId","Fixed worktree ID",{visibleWhen:{key:"targetMode",equals:"FIXED_WORKTREE"}})]},TERMINAL_RUN:{fields:[N("script","Script",{required:!0}),$("interpreter","Interpreter",x(["SHELL","NODE"])),q("environment","Environment variables"),M("credentials","Credential environment",{help:"JSON array of { name, credential: { id, kind, ownerId } } entries."})]}},J=()=>O("timeoutSeconds","Timeout (seconds)",{help:"How long to keep waiting before the step fails. Leave empty to wait for as long as the work takes."});function z(e,t){for(let r of e){let e=W[r];if(!e)continue;let i=new Set(e.fields.map(({key:e})=>e));e.fields=[...e.fields,...t().filter(({key:e})=>!i.has(e))]}}function Z(e=[]){return{fields:[...e,q("filters","Filters",{help:"Match when each session path equals the given value.",recordValueType:"json"})]}}z(["WORKTREE_CREATE","WORKTREE_CHANGE_BRANCH","WORKTREE_OPERATION","WORKTREE_DELETE","WORKTREE_GIT_OPERATION","WORKTREE_MOVE","WORKTREE_WAIT_PUSH_READY","WORKTREE_SNAPSHOT","CODEBASE_FETCH_REFRESH","CODEBASE_GIT_OPERATION","BUILD_START","BUILD_IMPORT_COVERAGE","BUILD_EXPORT","BUILD_DEPLOY","DISK_SPACE_REFRESH","TERMINAL_RUN","RUN_CREATE_PLAN","RUN_CREATE_SESSION","RUN_PLAY_PLAN","RUN_FOLLOW_UP","RUN_REVISE_ANSWER","SAVED_COMMAND","CUSTOM_COMMAND","COMMAND_RERUN","BUILD_REBUILD","BUILD_DATA_REFRESH","SIGNING_REFRESH","SIGNING_SYNC_PROFILE","SIGNING_DELETE_EXPIRED","SKILL_APPLY","GITHUB_WAIT_CHECKS","CONTROL_SUBWORKFLOW","CONTROL_WAIT_UNTIL"],()=>[O("cadenceSeconds","Poll cadence (seconds)",{help:"How often to check whether the work has finished. Leave empty for this step's default."}),J()]),z(["HUMAN_CONFIRM","HUMAN_CHOICE"],()=>[J()]);let Y=["BUILD_TEST_THRESHOLD","BUILD_COVERAGE_THRESHOLD","AGENT_DISK_THRESHOLD","CCUSAGE_THRESHOLD","RUN_USAGE_THRESHOLD","BUILD_DATA_THRESHOLD","AGENT_RESOURCE_THRESHOLD","SIGNING_ASSET_EXPIRING"],Q=Object.fromEntries(["MANUAL","MANUAL_CHOICE","RESOURCE_MANUAL","RESOURCE_MANUAL_CHOICE","SCHEDULE","WORKFLOW_FINISHED","GITHUB_PR_STATE","GITHUB_REVIEW_CHANGES_REQUESTED","GITHUB_REVIEW_COMMENT","GITHUB_PR_CLOSED","GITHUB_CHECK_FAILED","GITHUB_PUSH_DEFAULT","GITHUB_WORKFLOW_SUCCEEDED","GITHUB_ISSUE_COMMAND","GITHUB_ACTIONS_RESULT","GITHUB_PR_LABEL","BUILD_RESULT","BUILD_TEST_THRESHOLD","BUILD_COVERAGE_THRESHOLD","BUILD_HOOK_FAILED","AGENT_CONNECTION","AGENT_JOB_FAILED","AGENT_DISK_REPORT","AGENT_DISK_THRESHOLD","AGENT_DISK_STATE_CHANGED","AGENT_DISK_CLEANUP_RESULT","CCUSAGE_THRESHOLD","WORKTREE_CREATED","WORKTREE_BEHIND","WORKTREE_CONFLICT","WORKTREE_MISSING","WORKTREE_DIVERGED","WORKTREE_DIRTY_DURATION","WORKTREE_NEW_COMMIT","CODEBASE_REMOTE_BRANCH","JIRA_STATUS","JIRA_LABEL","JIRA_ASSIGNED_SELF","JIRA_SOURCE_NEW_TICKET","JIRA_MENTION","JIRA_SPRINT_STARTED","JIRA_ISSUE_CREATED","JIRA_ISSUE_DELETED","JIRA_ISSUE_COMMAND","JIRA_ATTACHMENT_ADDED","JIRA_ISSUE_LINKED","RUN_STARTED","RUN_COMPLETED","RUN_QUESTION_NEEDED","RUN_QUESTION_ANSWERED","RUN_PAUSED","RUN_CONTINUED","RUN_FAILED","RUN_CANCELLED","RUN_PLAN_PLAYED","RUN_FOLLOW_UP","RUN_IMPORTED","RUN_USAGE_THRESHOLD","RUN_EVENT_MATCH","COMMAND_RUN_RESULT","COMMAND_OUTPUT_MATCH","SKILL_SYNC_RESULT","SKILL_SYNC_CONFLICT","GITHUB_PIPELINE_STATUS_CHANGED","GITHUB_PR_SYNCHRONIZED","GITHUB_REVIEW_APPROVED","JIRA_TICKET_UPDATED","JIRA_COMMENT_ADDED","JIRA_WORKLOG_ADDED","JIRA_SPRINT_ENDED","CODEBASE_SYNC_STATE_CHANGED","CODEBASE_OPERATION_FAILED","WORKTREE_SYNC_STATE_CHANGED","WORKTREE_AUTOMATION_RESULT","WORKTREE_CLEAN","PUSH_NOTIFICATION_RESULT","IOS_DEVICE_ENROLLED","IOS_DEVICE_REGISTRATION_RESULT","SIGNING_OPERATION_RESULT","SIGNING_ASSET_EXPIRING","BUILD_DATA_THRESHOLD","BUILD_DATA_CLEANUP_RESULT","POLLING_OPERATION_STATE","MODEL_COST_CATALOG_CHANGED","CREDENTIAL_STORE_DEGRADED","AGENT_RESOURCE_THRESHOLD","AGENT_VERSION_CHANGED","TOOL_CALL_RESULT"].map(e=>"RESOURCE_MANUAL"===e||"RESOURCE_MANUAL_CHOICE"===e?[e,Z([$("resourceKind","Resource kind",x(o),{required:!0}),..."RESOURCE_MANUAL_CHOICE"===e?[F("choices","Choices",{required:!0})]:[]])]:"MANUAL_CHOICE"===e?[e,Z([F("choices","Choices",{required:!0})])]:"SCHEDULE"===e?[e,Z([O("cadenceSeconds","Cadence (seconds)",{required:!0})])]:"GITHUB_ISSUE_COMMAND"===e?[e,Z([j("allowedLogins","Allowed logins",{placeholder:"octocat",required:!0}),D("commandPattern","Command pattern (regex)",{placeholder:"^/deploy\\b$",required:!0,valueModes:["literal","interpolation"]})])]:"JIRA_ISSUE_COMMAND"===e?[e,Z([j("allowedAccountIds","Allowed account IDs",{placeholder:"5b10a2844c20165700ede21g",required:!0}),D("commandPattern","Command pattern (regex)",{placeholder:"^/deploy\\b$",required:!0,valueModes:["literal","interpolation"]})])]:"COMMAND_OUTPUT_MATCH"===e?[e,Z([D("outputPattern","Output pattern (regex)",{placeholder:"error|failed",required:!0,valueModes:["literal","interpolation"]})])]:Y.includes(e)?[e,Z([D("thresholdPath","Threshold path",{placeholder:"build.testSummary.failed"}),$("thresholdOperator","Operator",K),M("thresholdValue","Threshold value")])]:[e,Z()]));function X(e,t){return"step"===t?W[e]:Q[e]}function ee(e,t,r){let i=function(e,t){let r=X(e,t);if(!r)return null;let i=new Set,a=new Set;for(let e of r.fields){for(let t of"model"===e.control&&e.modelKeys?[e.modelKeys.provider,e.modelKeys.model,e.modelKeys.effort]:[e.key])i.add(t);e.required&&a.add(e.key)}return{described:i,required:a}}(e,t);if(!i||!r||"object"!=typeof r||Array.isArray(r))return S(r);let a=new Set;for(let[e,t]of Object.entries(r))(!i.described.has(e)||i.required.has(e))&&S(t,a);return a}e.s(["getConfigDescriptor",0,X,"requiredConfigSessionPaths",0,ee],248626);let et=["EQ","NE","GT","GTE","LT","LTE","CONTAINS","MATCHES","EXISTS"],er={type:"object",title:"Session binding",description:"Reads the value from run session data at `path` instead of hard-coding it.",properties:{source:{const:"SESSION"},path:{type:"string",description:"Dotted session path, e.g. `ticket.key` or `pr.number`."}},required:["source","path"],additionalProperties:!1},ei={type:"object",title:"Literal wrapper",description:"An explicit constant. Equivalent to writing the value directly; the editor uses it to record that a field was pinned rather than bound.",properties:{source:{const:"LITERAL"},value:{}},required:["source"],additionalProperties:!1};function ea(e,t,r){let i=r.valueModes??[],a=[i.includes("session")?"May also be a session binding.":null,i.includes("interpolation")?"Strings here — including strings nested inside the value — may carry `{{path}}` interpolation tokens, e.g. `{{worktree.baseBranch}}`.":null].filter(Boolean),n=a.length?{...t,description:[t.description,...a].filter(Boolean).join(" ")}:t;return i.includes("session")?{anyOf:[e,er,ei],...n}:{...e,...n}}function en(e){let t=e.options?function(e){if("static"===e.kind){let t=e.options.filter(({label:e})=>e);return t.length?t.map(({value:e,label:t})=>`\`${e}\` — ${t}`).join("; "):null}let t=e.scopeFrom?` Scoped by the sibling \`${e.scopeFrom}\` value.`:"",r=e.sessionPath?` Usually bound to \`${e.sessionPath}\`.`:"";return`Identifier of a ${e.resource} known to the control plane.${r}${t}`}(e.options):null,r={description:[e.label,e.help,t].filter(Boolean).join(" — ")};return e.placeholder&&(r.examples=[e.placeholder]),void 0!==e.default&&(r.default=e.default),ea(function(e){switch(e.control){case"number":return{type:e.integer?"integer":"number",...void 0===e.minimum?{}:{minimum:e.minimum},...void 0===e.maximum?{}:{maximum:e.maximum}};case"boolean":return{type:"boolean"};case"enum":{let t=e.options;if(t?.kind==="static")return{type:"string",enum:t.options.map(({value:e})=>e)};return{type:"string"}}case"resource":case"model":case"text":default:return{type:"string"};case"resourceMulti":case"stringList":case"mcpPresetMulti":return{type:"array",items:{type:"string"}};case"record":return{type:"object",additionalProperties:"json"===e.recordValueType?{}:{type:"string"}};case"condition":return{$ref:"#/$defs/condition"};case"choiceOptions":return{type:"array",description:"Buttons offered to the person answering.",items:{type:"object",properties:{label:{type:"string"},description:{type:"string"}},required:["label"],additionalProperties:!1}};case"triggerChoices":return{type:"array",minItems:1,description:"Options this trigger offers. Each `key` names an outgoing handle on the trigger, so edges stay attached when a label is renamed.",items:{type:"object",properties:{key:{type:"string",pattern:p.source},label:{type:"string"},description:{type:"string"}},required:["key","label"],additionalProperties:!1}};case"json":return{}}}(e),r,e)}function es(e,t){let r=X(e,t);if(!r)return{type:"object",additionalProperties:!0};let i={},a=[],n=!1;for(let e of r.fields){for(let[t,r]of("condition"===e.control&&(n=!0),"model"===e.control?function(e){let t=e.modelKeys;if(!t)return[[e.key,en(e)]];let r=(t,r)=>[t,ea({type:"string"},{description:r},e)];return[r(t.provider,"AI provider that serves the model."),r(t.model,"Model identifier, as listed by the provider catalog."),r(t.effort,"Reasoning effort, when the model supports it.")]}(e):[[e.key,en(e)]]))i[t]=r;e.required&&a.push(e.key)}let s={type:"object",properties:i,additionalProperties:!0};return a.length&&(s.required=a),n&&(s.$defs={condition:{type:"object",description:"A condition tree. `ALL`/`ANY` combine nested conditions, `NOT` negates one, and the comparison operators test `left` against `right`.",anyOf:[{properties:{op:{enum:["ALL","ANY"]},conditions:{type:"array",items:{$ref:"#/$defs/condition"}}},required:["op","conditions"]},{properties:{op:{const:"NOT"},condition:{$ref:"#/$defs/condition"}},required:["op","condition"]},{properties:{op:{enum:[...et]},left:{description:"Value to test — usually a session binding. `EXISTS` needs only this side."},right:{description:"Value to compare against."}},required:["op","left"]}]}}),s}let eo="aide.workflow";function el(e){let t=e?.choices;if(!Array.isArray(t))return[];let r=[],i=new Set;for(let e of t)!(!e||"object"!=typeof e||Array.isArray(e))&&(!h(e.key)||i.has(e.key)||(i.add(e.key),r.push({key:e.key,label:"string"==typeof e.label&&e.label.trim()?e.label:e.key,description:"string"==typeof e.description?e.description:""})));return r}let eu={BUILD:["build.*","worktree.*","codebase.*","agent.*","repo.*","ticket.*"],CODEBASE:["codebase.*","agent.*","repo.*"],JIRA_TICKET:["ticket.*","comment.*"],AGENT_RUN:["run.*","worktree.*","codebase.*","agent.*","repo.*","ticket.*"],GITHUB_PIPELINE:["pipeline.*","repo.*","pr.*","worktree.*","codebase.*","agent.*","ticket.*"],GITHUB_JOB:["job.*","pipeline.*","repo.*","pr.*","worktree.*","codebase.*","agent.*","ticket.*"],PULL_REQUEST:["pr.number","repo.displayOrigin"],WORKTREE:["worktree.*","codebase.*","agent.*","repo.*","ticket.*","pr.*"],COMMAND_RUN:["command.*","agent.*","worktree.*","codebase.*","repo.*"],SKILL:["skill.*","repo.*","codebase.*"],SKILL_SYNC:["skillSync.*","skill.*","repo.*","codebase.*","worktree.*"],IOS_DEVICE:["device.*"],SIGNING_PROFILE:["signingProfile.*","device.*","agent.*"],PUSH_NOTIFICATION_BATCH:["pushBatch.*"],BUILD_DATA_COLLECTION:["buildData.*","agent.*","worktree.*","codebase.*"]};function ec(e){let t=e?.resourceKind;return"string"==typeof t&&o.includes(t)?t:null}function ed(e,t){if(!d(e))return[];let r=ec(t);return r?eu[r]:[]}let ep=(e,t,r,i,a,n,s)=>({kind:e,category:t,label:r,description:s.description,details:s.details,execution:i,configSchema:es(e,"step"),capabilityFlags:[i,...s.mutatesExternal?["MUTATES_EXTERNAL"]:[],...s.mutatesWorktree?["MUTATES_WORKTREE"]:[]],requiredPaths:a,providedPaths:n,sourceHandles:m(e),mutatesExternal:s.mutatesExternal??!1,mutatesWorktree:s.mutatesWorktree??!1}),eh=["worktree.*","codebase.*","agent.*","repo.*","ticket.*","pr.*"],em=["codebase.*","agent.*","repo.*"],ef=(e,t,r,i=[],a=["steps.<stepId>.*"],n={})=>ep(e,t,r,"SERVER",i,a,{description:`${r} using the control plane's typed service API.`,details:`${r} is a first-class action with validated configuration, audit-friendly output, resource links where available, and normal workflow failure routing.`,...n}),eg=[ef("COMMAND_RERUN","Commands","Rerun command",["command.id"],["command.*"]),ef("COMMAND_TERMINATE","Commands","Terminate command",["command.id"],["command.*"]),ef("COMMAND_READ_OUTPUT","Commands","Read command output",["command.id"],["command.*"]),ef("WORKTREE_INSPECT_DIFF","Worktrees","Inspect worktree diff",["worktree.id"],["worktree.diff.*"]),ef("WORKTREE_UPDATE_METADATA","Worktrees","Update worktree metadata",["worktree.id"],eh),ef("WORKTREE_MOVE_CONTROL","Worktrees","Control worktree move",[],eh,{mutatesWorktree:!0}),ef("BUILD_REBUILD","Builds","Rebuild build",["build.id"],["build.*"]),ef("BUILD_GENERATE_REPORT","Builds","Generate build report",["build.id"],["build.*"]),ef("BUILD_DELETE","Builds","Delete builds",[],["build.*"]),ef("SKILL_PREPARE_SYNC","Skills","Prepare skill sync",[],["skillSync.*"]),ef("SKILL_RESOLVE_SYNC","Skills","Resolve skill sync conflict",["skillSync.id"],["skillSync.*"]),ef("SKILL_SKIP_SYNC","Skills","Skip skill sync",["skillSync.id"],["skillSync.*"]),ef("BUILD_DATA_REFRESH","Build Data","Refresh build data",[],["buildData.*"]),ef("BUILD_DATA_DELETE","Build Data","Delete build data",["buildData.id"],["buildData.*"]),ef("BUILD_DATA_SET_LOCK","Build Data","Set build-data lock",["buildData.id"],["buildData.*"]),ef("SIGNING_REFRESH","Signing","Refresh signing assets",[],["signing.*"]),ef("SIGNING_SYNC_PROFILE","Signing","Sync signing profile",["signingProfile.id"],["signing.*"]),ef("SIGNING_DELETE_EXPIRED","Signing","Delete expired profiles",[],["signing.*"]),ef("IOS_DEVICE_REGISTER","Devices","Register iOS device",["device.id"],["device.*"],{mutatesExternal:!0}),ef("IOS_DEVICE_REJECT","Devices","Reject iOS device",["device.id"],["device.*"],{mutatesExternal:!0}),ef("AGENT_RECONCILE","Agents","Reconcile agents",[],["agent.*"]),ef("AGENT_UPDATE_CADENCE","Agents","Update agent cadence",["agent.id"],["agent.*"]),ef("CCUSAGE_COLLECT","Operations","Collect usage",[],["usage.*"]),ef("MODEL_COST_REFRESH","Operations","Refresh model costs",[],["modelCosts.*"],{mutatesExternal:!0}),ef("GITHUB_UPDATE_PR","GitHub","Update pull request",["pr.number","repo.*"],["pr.*"],{mutatesExternal:!0}),ef("GITHUB_SUBMIT_REVIEW","GitHub","Submit pull request review",["pr.number","repo.*"],["pr.*"],{mutatesExternal:!0}),ef("GITHUB_REQUEST_REVIEWERS","GitHub","Request pull request reviewers",["pr.number","repo.*"],["pr.*"],{mutatesExternal:!0}),ef("GITHUB_DISPATCH_WORKFLOW","GitHub","Dispatch GitHub workflow",["repo.*"],["pipeline.*"],{mutatesExternal:!0}),ef("JIRA_CREATE_TICKET","Jira","Create Jira ticket",[],["ticket.*"],{mutatesExternal:!0}),ef("JIRA_ADD_WORKLOG","Jira","Add Jira worklog",["ticket.key"],["ticket.*"],{mutatesExternal:!0}),ef("JIRA_LINK_TICKETS","Jira","Link Jira tickets",["ticket.key"],["ticket.*"],{mutatesExternal:!0})],ey=[ep("JIRA_LOAD_TICKET","Jira","Load Jira ticket","SERVER",[],["ticket.*"],{description:"Reads a Jira issue and puts its fields — key, title, type, status, assignee, labels — into session data as `ticket.*`.",details:'Needs a configured Jira credential. Leave the identifier unset to take it from session data. Results are served from cache unless "Bypass cache" is set, so a step that reads a ticket right after changing it should force a refresh. Fails when the issue does not exist or the credential cannot see it. Read-only: it changes nothing in Jira.'}),ep("JIRA_TRANSITION","Jira","Transition Jira ticket","SERVER",["ticket.key"],["ticket.*"],{description:"Moves a ticket to another status by applying one of its workflow transitions.",details:"Takes a transition id, not a status name — the ids are board-specific, so read them from the ticket's available transitions rather than hard-coding a guess. Fails when the transition is not currently available on that issue, which is what happens if an earlier step already moved it. Refreshes `ticket.*` from the response.",mutatesExternal:!0}),ep("JIRA_COMMENT","Jira","Add Jira comment","SERVER",["ticket.key"],["ticket.*"],{description:"Posts a comment on a Jira issue, written in Markdown or Jira wiki markup.",details:"The comment body is converted from Markdown by default; choose Jira wiki format to pass markup through untouched. Comments are never deduplicated, so a step that runs twice comments twice — guard it with a condition if the workflow can retry. Refreshes `ticket.*` from the response.",mutatesExternal:!0}),ep("JIRA_ASSIGN","Jira","Assign Jira ticket","SERVER",["ticket.key"],["ticket.*"],{description:"Sets the assignee of a Jira issue, or clears it when no account is given.",details:"Takes a Jira account id rather than a display name or email. Leaving the assignee empty unassigns the ticket. Fails when the account cannot be assigned on that project. Refreshes `ticket.*` from the response.",mutatesExternal:!0}),ep("JIRA_UPDATE_FIELDS","Jira","Update Jira fields","SERVER",["ticket.key"],["ticket.*"],{description:"Patches arbitrary fields on a Jira issue — labels, summary, custom fields — from a JSON object.",details:"The escape hatch for anything the dedicated Jira steps do not cover. Keys are passed to the Jira update API as given, so an unknown or screen-hidden field fails the step. Prefer the specific steps for status and assignee. Refreshes `ticket.*` from the response.",mutatesExternal:!0}),ep("JIRA_RESOLVE_BRANCH","Jira","Resolve ticket branch","SERVER",["ticket.key","ticket.title","ticket.type"],["worktree.branch","ticket.key","ticket.title","ticket.type"],{description:"Works out the branch name a ticket would get under the codebase's naming convention, without creating anything.",details:"A preview step: it writes `worktree.branch` plus the ticket key, title, and type into session data and touches neither Git nor Jira. Use it before Create worktree when you want the branch name available to earlier steps — for a worktree keyed off a ticket, Create worktree in TICKET mode derives the same name on its own."}),ep("GITHUB_LOAD_PR","GitHub","Load pull request","SERVER",[],["pr.*"],{description:"Reads a pull request and puts its state, branches, labels, checks, and review threads into session data as `pr.*`.",details:"Needs a configured GitHub credential. Owner and repository default to the repository already in session data, and the number to `pr.number`. Fails when the pull request does not exist or the credential cannot see it. Read-only."}),ep("GITHUB_MERGE_PR","GitHub","Merge pull request","SERVER",["pr.number"],["pr.state"],{description:"Merges an open pull request using squash, merge, or rebase, optionally overriding the commit message.",details:"Checks mergeability first and fails with GitHub's own blocking reason — conflicts, failing required checks, missing approvals, an already-closed pull request — rather than forcing the merge. Commit headline and body default to what GitHub would use. Squash is the default method. Irreversible, and repository policy may delete the head branch as a side effect, which strands any worktree still on it. Writes `pr.state`.",mutatesExternal:!0}),ep("GITHUB_COLLECT_REVIEW_THREADS","GitHub","Collect review comments","SERVER",["pr.number"],["pr.unresolvedThreads"],{description:"Gathers the unresolved review threads on a pull request into `pr.unresolvedThreads`.",details:"Resolved threads are filtered out. The result is a list, so it pairs with For each to work through the comments one at a time — the reply and resolve steps take a single thread id from the iteration. Read-only."}),ep("GITHUB_REPLY_REVIEW_THREAD","GitHub","Reply to review thread","SERVER",["pr.unresolvedThreads"],[],{description:"Posts a reply into an existing pull request review thread.",details:"Takes the thread id from Collect review comments, usually inside a For each. Replies are not deduplicated, so a retried step comments twice. Replying does not resolve the thread — follow with Resolve review thread when that is the intent.",mutatesExternal:!0}),ep("GITHUB_SET_REVIEW_THREAD_RESOLVED","GitHub","Resolve review thread","SERVER",["pr.unresolvedThreads"],[],{description:"Marks a pull request review thread resolved, or reopens it.",details:"Takes the thread id from Collect review comments. Resolving is the default; clear the flag to unresolve. Reviewers see this as the bot resolving their comment, so it is usually paired with a reply that explains what changed.",mutatesExternal:!0}),ep("GITHUB_CREATE_PR","GitHub","Open pull request","SERVER",["worktree.branch","worktree.baseBranch"],["pr.*"],{description:"Opens a pull request from the worktree's branch, optionally as a draft.",details:"Head branch defaults to `worktree.branch`, base to `worktree.baseBranch`, and the title to `ticket.title`. The head branch must already be pushed — put Wait for push-ready or a push operation in front of this step. Fails when a pull request is already open for the same branch pair. Writes the new pull request to `pr.*`.",mutatesExternal:!0}),ep("GITHUB_SET_PR_LABELS","GitHub","Set pull request labels","SERVER",["pr.number"],["pr.labels"],{description:"Replaces the labels on a pull request with the given list.",details:"This sets rather than adds — labels not in the list are removed, so include the ones you want to keep. Labels must already exist in the repository. Writes `pr.labels`.",mutatesExternal:!0}),ep("GITHUB_RETRY_PIPELINE","GitHub Actions","Retry failed pipeline","SERVER",["pipeline.runId"],["pipeline.status"],{description:"Re-runs the failed jobs of a check suite, leaving the jobs that passed alone.",details:"Targets a check suite rather than a single job — use Retry workflow job for that. Re-running consumes Actions minutes and re-executes whatever those jobs do, including deployments. Pair it with a Time delay and a retry limit so a permanently broken pipeline is not retried forever. Writes `pipeline.status`.",mutatesExternal:!0}),ep("GITHUB_RETRY_JOB","GitHub Actions","Retry workflow job","SERVER",["pipeline.failedJobs"],[],{description:"Re-runs one job of a GitHub Actions workflow run.",details:"Needs the repository, check suite, and job ids together — typically read out of `pipeline.failedJobs` inside a For each. Use Retry failed pipeline to re-run every failed job at once instead.",mutatesExternal:!0}),ep("GITHUB_CANCEL_WORKFLOW_RUN","GitHub Actions","Cancel workflow run","SERVER",["pipeline.runId"],["pipeline.status"],{description:"Cancels an in-progress GitHub Actions workflow run.",details:"Falls back to `repo.id` and `pipeline.runId` from session data. Force-cancel skips the graceful shutdown that lets `always()` cleanup jobs finish, so leave it off unless a run is stuck. Cancelling a run that has already finished is an error. Writes `pipeline.status`.",mutatesExternal:!0}),ep("GITHUB_SAVE_AUTO_RETRY","GitHub Actions","Install auto-retry rule","SERVER",["pipeline.runId"],[],{description:"Saves a standing rule that automatically retries matching GitHub Actions failures.",details:"Persists configuration rather than acting once — the rule keeps applying after this run ends, and stays until something removes it. Takes the rule as a JSON object. Treat it as a settings change, not a step you re-run casually.",mutatesExternal:!0}),ep("GITHUB_WAIT_CHECKS","GitHub Actions","Wait for checks","WAIT",["pipeline.runId"],["pipeline.status","pipeline.conclusion","pipeline.jobs"],{description:"Parks the run until a GitHub Actions workflow run finishes, then continues on its conclusion.",details:"Polls until the run reaches a terminal status. Anything other than success fails the step, so route the failure handle to the recovery path — or set the step's failure policy to continue and branch on `pipeline.conclusion` yourself. Also refreshes `pipeline.jobs`. Without a timeout the wait is open-ended; a hung pipeline holds the workflow run indefinitely. Falls back to `repo.id` and `pipeline.runId`."}),ep("WORKTREE_CREATE","Worktrees","Create worktree","SERVER",["codebase.id"],eh,{description:"Creates a Git worktree on the agent for a new, existing, or ticket-derived branch.",details:"Dispatches a job to the agent that owns the codebase and waits for it, so the agent must be online. Branch mode NEW cuts a branch from the base, EXISTING checks one out, and TICKET derives the name from `ticket.key`. Base branch falls back to `worktree.baseBranch` then `repo.defaultBranch`. Refreshes the created worktree, codebase, owning agent, repository, and any linked ticket. Creates real directories on disk.",mutatesWorktree:!0}),ep("WORKTREE_CHANGE_BRANCH","Worktrees","Change worktree branch","SERVER",["worktree.id"],eh,{description:"Switches an existing worktree to a different branch, creating it if needed.",details:'Same branch modes as Create worktree. Uncommitted changes block the switch unless "Stash on failure" is set, which stashes them and retries — the stash is left for a human to deal with. Refreshes the worktree and all of its related resource context.',mutatesWorktree:!0}),ep("WORKTREE_REFRESH_PULL_REQUEST","Worktrees","Refresh pull request","SERVER",["worktree.id"],["pr.*"],{description:"Forces exact-branch pull request discovery and refreshes the worktree's persisted pull request context.",details:"Uses the configured worktree, falling back to `worktree.id`. The step succeeds with `found: false` and clears `pr` when the branch has no open pull request.",mutatesWorktree:!0,mutatesExternal:!1}),ep("WORKTREE_OPERATION","Worktrees","Run worktree operation","SERVER",["worktree.id"],eh,{description:"Runs one of the built-in worktree maintenance operations, such as syncing with the base branch or pushing.",details:"Dispatches an agent job and waits for it. Opening an editor is rejected here — it needs a human at the machine. Sync and push touch the remote and can conflict; check `worktree.pushStatus` afterwards or follow with Inspect worktree Git state.",mutatesWorktree:!0}),ep("WORKTREE_SET_AUTO_SYNC","Worktrees","Set worktree Auto Sync","SERVER",["worktree.id"],["worktree.autoSync"],{description:"Enables, updates, retries, or cancels persistent Auto Sync for a worktree.",details:"An enabled rule rebases on the target branch whenever it changes and force-pushes with lease. A merge-conflict quick-action workflow can be selected as the automatic recovery path; unresolved conflicts pause the rule.",mutatesWorktree:!0,mutatesExternal:!0}),ep("WORKTREE_SET_AUTO_MERGE","Worktrees","Set worktree Auto Merge","SERVER",["worktree.id"],["worktree.autoMerge"],{description:"Enables, updates, retries, or cancels GitHub-native Auto Merge for a worktree.",details:"GitHub remains the authority for required checks and reviews. Optional post-merge actions can move the linked Jira ticket to its configured done status and safely delete a clean linked worktree.",mutatesWorktree:!0,mutatesExternal:!0}),ep("WORKTREE_DELETE","Worktrees","Delete worktree","SERVER",["worktree.id"],em,{description:"Removes a worktree from the agent, optionally deleting its remote branch too.",details:"Destroys the directory and any uncommitted work in it — there is no undo. Deleting the remote branch as well affects everyone, and closes any pull request from that branch. Do not put this before steps that still read `worktree.*`.",mutatesWorktree:!0}),ep("WORKTREE_MOVE","Worktrees","Move worktree","SERVER",["worktree.id"],eh,{description:"Moves a worktree's branch and changes into another codebase, optionally deleting the source.",details:"Waits for the move job to finish. Used when a branch was started against the wrong checkout. Deleting the source destroys the original directory; leaving it keeps both, which means two worktrees on one branch. Refreshes `worktree.*` to point at wherever the work now lives.",mutatesWorktree:!0}),ep("WORKTREE_INSPECT","Worktrees","Inspect worktree","SERVER",["worktree.id"],["worktree.commits","worktree.changes","worktree.branchChanges","worktree.commitsTruncated","worktree.changesTruncated","worktree.branchChangesTruncated"],{description:"Reads the worktree's commits and changed files into `worktree.commits` and `worktree.changes`.",details:"Read-only. Use it to give a later condition or AI prompt something concrete to work from — for example to skip opening a pull request when nothing changed. For push/dirty state use Inspect worktree Git state instead, which is cheaper."}),ep("WORKTREE_INSPECT_GIT","Worktrees","Inspect worktree Git state","SERVER",["worktree.id"],["worktree.*"],{description:"Reads the worktree's Git status — dirty flag, ahead/behind counts, push status, conflicts — into `worktree.*`.",details:"Read-only and the cheap way to branch on repository state: gate a commit on `worktree.dirty`, or a sync on the worktree being behind. Use Inspect worktree when you need the actual commits and diffs."}),ep("WORKTREE_GIT_OPERATION","Worktrees","Run worktree Git operation","SERVER",["worktree.id"],eh,{description:"Runs a specific Git operation in the worktree — pull, push, rebase, stash, and the rest.",details:'Dispatches an agent job and waits for it. Operations that rewrite history or touch the remote can fail on conflicts; "Stash changes first" clears the way for operations that need a clean tree. Prefer Run worktree operation for the higher-level sync and push flows, which handle more of the edge cases.',mutatesWorktree:!0}),ep("WORKTREE_WAIT_PUSH_READY","Worktrees","Wait for push-ready","WAIT",["worktree.id"],eh,{description:"Parks the run until the worktree's branch is pushed and tracking a remote.",details:"The step to put between an AI session that commits and Open pull request, which needs the branch to exist on the remote. Resolves as soon as the branch is push-ready; without a timeout it waits indefinitely, so set one if a human may never push. Writes `worktree.pushStatus`."}),ep("WORKTREE_SNAPSHOT","Worktrees","Snapshot Git state","AGENT",["worktree.path"],["steps.<stepId>.snapshotId"],{description:"Captures a restorable checkpoint of the worktree's Git state before a risky step.",details:"Runs on the agent, so it needs `worktree.path` and an online agent. The snapshot id it writes is what run replay restores from, which makes this the step to place before anything that rewrites the tree. Snapshots cost disk on the agent."}),ep("CODEBASE_FETCH_REFRESH","Codebases","Fetch or refresh codebase","SERVER",["codebase.id"],em,{description:"Fetches remote refs for a codebase, or fully refreshes its cached metadata.",details:"Fetch updates remote-tracking branches; refresh re-reads the whole checkout and is slower. Runs as an agent job and waits. Fails when the agent skips the operation — usually because the codebase is missing or already busy. Put a fetch in front of steps that check whether a remote branch exists.",mutatesWorktree:!0}),ep("CODEBASE_INSPECT_GIT","Codebases","Inspect codebase Git state","SERVER",["codebase.id"],["codebase.*"],{description:"Reads the codebase checkout's Git status into `codebase.*`.",details:"Read-only. This is the primary checkout, not a worktree — use Inspect worktree Git state for per-branch work. Useful for refusing to start work when the base checkout is dirty or on an unexpected branch."}),ep("CODEBASE_GIT_OPERATION","Codebases","Run codebase Git operation","SERVER",["codebase.id"],em,{description:"Runs a Git operation against the codebase's primary checkout.",details:'Same operations as the worktree version, aimed at the main checkout that every worktree branches from — so a bad rebase or reset here affects all of them. "Stash changes first" clears local modifications out of the way. Runs as an agent job and waits.',mutatesWorktree:!0}),ep("BUILD_START","Builds","Start build or test","SERVER",["codebase.id","worktree.id"],["build.*"],{description:"Queues an iOS build, test, or archive run on the agent and waits for it to finish.",details:"Needs a build configuration id and an online agent; the destination and build scripts are optional. The step parks until the build reaches a terminal status, so a long test suite holds the workflow run. Failing builds fail the step — route the failure handle if you want to read the results anyway. Writes `build.*`, which the read-results and coverage steps then consume.",mutatesExternal:!0}),ep("BUILD_READ_TEST_RESULTS","Builds","Read test results","SERVER",["build.id"],["build.testSummary","build.tests"],{description:"Reads a finished build's test report into `build.testSummary` and `build.tests`.",details:"Fails outright when the report is not ready, so it belongs after Start build or test rather than in parallel with it. The summary carries the passed/failed counts a condition can branch on; the per-test list is the detail an AI prompt can be pointed at. Read-only."}),ep("BUILD_READ_COVERAGE","Builds","Read code coverage","SERVER",["build.id"],["build.coverageSummary","build.coverageFiles","build.changedCoverageFiles"],{description:"Reads a finished build's coverage report into `build.coverageSummary` and the per-file breakdowns.",details:'Fails when the coverage report is not ready — the build must have been run with coverage collection on. Also writes the changed-files breakdown, which is what a "coverage on this branch\'s changes" gate should read rather than the whole-project number. Read-only.'}),ep("BUILD_IMPORT_COVERAGE","Builds","Import coverage report","SERVER",["worktree.id"],["build.id","build.coverageSummary"],{description:"Reads a coverage file a test command wrote in the worktree and records it as a coverage report.",details:"Pair it with a Terminal command step that runs the test suite first: this step only reads what that run left behind, at the path given in `Coverage file`. The build name defaults to the workflow name and can be overridden. LCOV and Istanbul (`coverage-final.json`) are both understood, and AUTO tells them apart by the file itself. Runs as an agent job and waits. The report is attached to a new build record of its own, so it shows up on that build's coverage page and in the coverage picker on Changes; changed-line coverage is measured against the worktree's base branch, and is left out when that branch cannot be resolved. Writes the totals to `build.coverageSummary` and the new id to `build.id` — follow with Read code coverage for the per-file breakdown. Fails when the file is missing, unreadable, or describes no files."}),ep("BUILD_EXPORT","Builds","Export archive","SERVER",["build.id"],["build.exportId",...eh],{description:"Exports a finished archive build into a distributable package on the agent.",details:"Needs export settings and an archive-action build. Runs as an agent job and waits. Writes files to the agent's disk and may talk to Apple's servers for signing, so it can fail on expired certificates or provisioning profiles.",mutatesExternal:!0}),ep("BUILD_DEPLOY","Builds","Deploy build","SERVER",["build.id"],eh,{description:"Installs and launches an existing build on its destinations without rebuilding.",details:"Reuses the artifacts from a previous build, so it is much faster than building again. Destinations default to the ones the build already targeted. Waits for the deployment job. This puts the app on real or simulated devices — treat it as an external effect.",mutatesExternal:!0}),ep("BUILD_CANCEL","Builds","Cancel build","SERVER",["build.id"],["build.id","build.status"],{description:"Cancels a queued or running build.",details:"Aimed at a different build from the one this run started — Start build or test already waits for its own. Cancelling an already-finished build is a no-op rather than an error. Writes `build.status`.",mutatesExternal:!0}),ep("DISK_SPACE_LOAD","Disk space","Load disk-space monitor","SERVER",[],["agent.*","disk.*"],{description:"Loads the current Derived Data disk-space monitor snapshot for an agent.",details:"Targets the configured agent, then falls back to `agent.id` or `codebase.agentId`. The least-free monitored Derived Data volume supplies `disk.freeBytes`, `disk.freeGiB`, and the percentage fields; root and base-repository volumes remain in `disk.volumes` for context only. Read-only and does not request a new report."}),ep("DISK_SPACE_REFRESH","Disk space","Refresh disk-space monitor","WAIT",[],["agent.*","disk.*"],{description:"Requests an immediate disk report from an agent and waits for fresh telemetry.",details:"Targets the configured agent, then falls back to `agent.id` or `codebase.agentId`. Monitoring must be enabled. The step waits until `lastReportedAt` advances, then refreshes `agent.*` and `disk.*`; by default it polls every two seconds and times out after 180 seconds."}),ep("DISK_SPACE_UPDATE_THRESHOLDS","Disk space","Update disk thresholds","SERVER",[],["disk.normalThresholdGiB","disk.pressureThresholdGiB","disk.pollIntervalSeconds","disk.staleAfterSeconds"],{description:"Updates the global normal and pressure free-space thresholds.",details:"Changes the thresholds used for every monitored agent, automatic cleanup, and admission control. The pressure threshold must be positive and lower than the normal threshold. Writes the resulting global settings into `disk.*`."}),ep("DISK_SPACE_SET_MONITORING","Disk space","Set agent disk monitoring","SERVER",[],["agent.*","disk.*"],{description:"Enables or disables Derived Data disk-space monitoring for an agent.",details:"Targets the configured agent, then falls back to `agent.id` or `codebase.agentId`. Disabling monitoring also clears manual and automatic pressure mode and releases cleanup leases that have not started a job. Refreshes `agent.*` and `disk.*`."}),ep("DISK_SPACE_SET_PRESSURE_MODE","Disk space","Set disk pressure mode","SERVER",[],["agent.*","disk.*"],{description:"Enables or clears manual disk pressure mode for an agent.",details:"Targets the configured agent, then falls back to `agent.id` or `codebase.agentId`. Manual pressure mode uses the lower pressure threshold; automatic pressure mode remains controlled by cleanup availability. Refreshes `agent.*` and `disk.*`."}),ep("SKILL_APPLY","Skills","Apply skill group","SERVER",["worktree.id","repo.id"],["steps.<stepId>.status"],{description:"Syncs a skill group's files into the target checkout, or every skill when no group is chosen.",details:"Starts a skill sync run and waits for it. Writes skill files into the repository, which shows up as uncommitted changes — commit or discard them before a step that needs a clean tree. Leave the group empty to sync everything.",mutatesWorktree:!0}),ep("RUN_CREATE_PLAN","AI runs","Create plan and wait","SERVER",["worktree.id"],["run.<stepId>.*"],{description:"Starts an AI planning run against the worktree and waits for the plan to be produced.",details:"Requires a worktree, a provider/model, and a prompt. Plans use a separate FIFO worktree queue and allow unlimited concurrent plans by default; set the worktree concurrency limit to 1–32 to cap them, or 0 for unlimited. Planning inspects the code but does not change it — use Run AI session and wait to actually make edits, or follow with Run completed plan. If the run asks a question it parks until someone answers, so pair long workflows with a question-needed trigger. Writes the run under `run.<stepId>.*`, which later steps reference by this step's id."}),ep("RUN_CREATE_SESSION","AI runs","Run AI session and wait","SERVER",["worktree.id"],["run.<stepId>.*"],{description:"Starts an AI coding session against the worktree and waits for it to finish.",details:"The workhorse step: the agent edits files in the worktree, so the tree is dirty afterwards and the changes still need committing and pushing. Sessions use a separate FIFO worktree queue with one active session by default; set the worktree concurrency limit to 2–32 for parallel sessions or 0 for unlimited. Requires a worktree, a provider/model, and a prompt; attachments and web search are optional. Parks on questions until answered. Writes `run.<stepId>.*`.",mutatesWorktree:!0}),ep("RUN_PLAY_PLAN","AI runs","Run completed plan","SERVER",[],["run.<stepId>.*"],{description:"Executes a plan that has already been produced, turning it into real code changes.",details:"Takes the plan's run id — usually `run.<planStepId>.id` from an earlier Create plan step. The plan must have completed. The resulting Session joins the worktree's FIFO Session queue, which allows one active Session by default; use 0 for unlimited or 2–32 for a larger limit. This is the half of the plan/execute split that touches the worktree. Writes a new run under `run.<stepId>.*`.",mutatesWorktree:!0}),ep("RUN_FOLLOW_UP","AI runs","Follow up run","SERVER",[],["run.<stepId>.*"],{description:"Starts a new AI run that continues from an existing one, resuming its context or starting fresh.",details:'RESUME keeps the previous conversation, FRESH starts over in the same worktree, and RESEND replays the original prompt. The new run joins the source kind\'s separate FIFO worktree queue and defaults to unlimited concurrency for Plans or one active run for Sessions; use 0 for unlimited or 1–32 for a finite limit. Needs the source run id plus a new prompt. The natural step for "fix the review comments" loops after a first session. Writes `run.<stepId>.*`.'}),ep("RUN_STEER","AI runs","Steer active run","SERVER",[],["run.<stepId>.*"],{description:"Sends extra instructions into a run that is already in progress.",details:"Only affects a run that is still going — it does not restart a finished one, which is what Follow up run is for. Because the steps in this workflow that start runs also wait for them, steering usually targets a run started elsewhere, reached through a run trigger."}),ep("RUN_ANSWER","AI runs","Answer run question","SERVER",[],["run.<stepId>.*"],{description:"Answers a question an AI run is blocked on so it can carry on.",details:"Needs the question batch id, typically from `run.questions` seeded by a run-needs-an-answer trigger, and answers keyed by question id. This answers questions asked by an AI run — the Request confirmation and Ask user to choose steps ask questions of a human about the workflow itself."}),ep("RUN_PAUSE","AI runs","Pause run","SERVER",[],["run.<stepId>.*"],{description:"Pauses an in-progress AI run.",details:"The run stops at its next checkpoint and stays paused until something continues it. Falls back to `run.id`. Pausing an already-finished run fails."}),ep("RUN_CONTINUE","AI runs","Continue run","SERVER",[],["run.<stepId>.*"],{description:"Resumes a paused AI run.",details:"The counterpart to Pause run. Fails when the run is not paused. Falls back to `run.id`."}),ep("RUN_CANCEL","AI runs","Cancel run","SERVER",[],["run.<stepId>.*"],{description:"Cancels an AI run, stopping its work.",details:"Whatever the run already wrote to the worktree stays — cancelling stops further work, it does not roll anything back. Falls back to `run.id`."}),ep("RUN_REVISE_ANSWER","AI runs","Revise answer and rewind","SERVER",[],["run.<stepId>.*"],{description:"Rewinds a run to an earlier question, replaces the answer, and replays from there.",details:"Two-phase: the step prepares the revision, parks, and applies it once the run is ready. Rolling back restores the worktree to the checkpoint at that question, discarding work done since — stash first if that work matters. The heavy way to correct a wrong answer; Follow up run is usually enough.",mutatesWorktree:!0}),ep("RUN_READ_RESULT","AI runs","Read run result","SERVER",[],["run.<stepId>.*"],{description:"Loads a finished run's events, questions, token usage, and linked items into session data.",details:"Read-only. Gives later steps the run's actual output to work from — a summary to put in a Jira comment, usage figures to threshold on, or the linked pull request. Falls back to `run.id`."}),ep("RUN_CAPTURE_CHECKPOINT","AI runs","Capture run checkpoint","SERVER",[],["steps.<stepId>.snapshotId"],{description:"Records the run's most recent checkpoint so a later replay can restore from it.",details:"Reads an existing checkpoint rather than creating one, and fails when the run has none. Use Snapshot Git state to capture a fresh checkpoint of the worktree instead. Writes the checkpoint id to `steps.<stepId>.snapshotId`."}),ep("RUN_ARCHIVE_DELETE","AI runs","Archive or delete run","SERVER",[],[],{description:"Archives a run out of the active list, or permanently deletes it.",details:"Archiving is reversible; deleting removes the run and its history for good. Delete wins when both flags are set. Housekeeping for workflows that generate many short-lived runs.",mutatesExternal:!0}),ep("NOTIFICATION_SEND","Human loop","Send notification","SERVER",[],[],{description:"Posts a notification into the app's notification list with a title, body, and link.",details:"Deduplicated per run, step, and generation, so a retried attempt does not notify twice. The link defaults to this workflow run. Fire-and-forget: it tells a human something happened but does not wait — use Request confirmation when the workflow needs an answer.",mutatesExternal:!0}),ep("IOS_PUSH_SEND","Human loop","Push to iOS device","SERVER",[],[],{description:"Sends an Apple push notification to registered devices, a broadcast channel, or one raw device token.",details:"Needs APNs credentials. Target mode picks between all registrations, a chosen few, a broadcast channel, or a direct token — the direct mode also needs the token's encoding and whether it is a sandbox or production token. Leaves the device once delivered; nothing about the run waits on it.",mutatesExternal:!0}),ep("HUMAN_CONFIRM","Human loop","Request confirmation","WAIT",[],["steps.<stepId>.answer"],{description:"Parks the run and asks a human to confirm before continuing.",details:"The approval gate to put in front of anything irreversible. Without a timeout the run waits indefinitely; with one it fails when nobody answers in time, which the failure handle can route to a safe default. The answer lands in `steps.<stepId>.answer`."}),ep("HUMAN_CHOICE","Human loop","Ask user to choose","WAIT",[],["steps.<stepId>.answer"],{description:"Parks the run and asks a human to pick from a set of options, optionally allowing several or a free-text answer.",details:"Like Request confirmation but with named buttons — branch on `steps.<stepId>.answer` with an If step afterwards. Multi-select returns a list. Allowing a custom answer means the value may be anything the person typed, so handle the unexpected case."}),ep("CONTROL_IF","Control flow","If / else","CONTROL",[],[],{description:"Evaluates a condition and sends the run down its `true` or `false` branch.",details:"Exactly one branch is taken; steps on the other are skipped, and a skipped branch does not block a downstream join. Conditions compare session values with the usual operators and combine with ALL/ANY/NOT. Both branches may be left unconnected, which simply ends that path."}),ep("CONTROL_JOIN","Control flow","Join branches","CONTROL",[],[],{description:"Brings parallel branches back together, waiting for all of them or continuing on the first.",details:"Required wherever more than one branch reaches the same step — the validator rejects a plain step with several incoming edges. ALL waits for every branch, ANY continues on the first and lets the others keep running. Skipped branches never block it, and the join is skipped when no branch reaches it. A join that closes a For each also reports the iteration failures."}),ep("CONTROL_DELAY","Control flow","Time delay","WAIT",[],[],{description:"Pauses the run for a fixed number of seconds.",details:"Accepts up to a year. The run is parked rather than held open, so a long delay costs nothing while it waits. Use it to space out polling or to give an external system time to settle; use Wait until when you are waiting for a condition rather than a duration."}),ep("CONTROL_WAIT_UNTIL","Control flow","Wait until","WAIT",[],[],{description:"Parks the run until a condition over session data becomes true, re-checking on a cadence.",details:"Evaluates immediately and continues at once if the condition already holds. Session data only changes when a step writes it, so the condition must be able to become true through some other branch — otherwise the wait never resolves. Default cadence is 15 seconds; set a timeout to bound it."}),ep("CONTROL_FOR_EACH","Control flow","For each","CONTROL",[],["steps.<stepId>.items"],{description:"Runs its `body` branch once per item in a list, or takes the `empty` branch when there is nothing to iterate.",details:"Reads the list from a session path or from inline items, and caps at 1,000. Iterations run in parallel and each sees its own item. Fail-fast stops the whole run on the first failing iteration; collect-errors lets them all finish and reports failures at the closing join. Writes the items to `steps.<stepId>.items`."}),ep("CONTROL_TRY","Control flow","Try / catch","CONTROL",[],[],{description:"Marks the start of a protected region whose failures route out of the `catch` handle.",details:"Takes no config — the recovery path is drawn in the graph. Steps on the `success` branch run normally; when one of them fails, the run continues from `catch` instead of failing outright. Use a step's own failure handle for a single fallible step; reach for this when a whole sequence shares one recovery path."}),ep("CONTROL_SET_VARIABLE","Control flow","Set or compute variable","CONTROL",[],[],{description:"Writes a value into session data at a chosen path, either a constant or the result of a small script.",details:"The script runs in a sandboxed JavaScript interpreter with the session data available and no network or filesystem access; its return value is what gets written. Without a script the literal value is used. The path may be any dotted path — write under a namespace of your own to avoid colliding with what steps produce. Because the path comes from config, the catalog cannot advertise it: list it in this step's own `providedPaths` too, or a later step that binds it fails to publish with REQUIREMENT_UNSATISFIED."}),ep("CONTROL_SUBWORKFLOW","Control flow","Call sub-workflow","SERVER",[],[],{description:"Runs another published workflow as a child and waits for it to finish.",details:"Must pin a specific published version — the validator rejects an unpinned reference, so a sub-workflow cannot change under a caller. The input mapping seeds the child's session data. The child appears as a nested run; its failure fails this step."}),ep("SAVED_COMMAND","Extensibility","Run saved command","AGENT",[],["steps.<stepId>.*"],{description:"Starts a saved command on an eligible agent home or worktree target.",details:"Uses the saved command snapshot, target rules, output log, and restart policy. Wait for exit fails the workflow when the command ultimately fails or is cancelled; fire and forget succeeds after durable dispatch and remains independent if the workflow is later cancelled. Always-restart commands can only use fire and forget.",mutatesWorktree:!0}),ep("CUSTOM_COMMAND","Extensibility","Run custom command","AGENT",[],["steps.<stepId>.*"],{description:"Runs a one-off shell command on an agent home or worktree and records it in Commands run history.",details:"The script is retained only in the immutable command-run snapshot, not as a reusable saved command. Context targeting prefers the current worktree, then the current agent. Wait for exit fails the workflow when the command fails or is cancelled; fire and forget succeeds after durable dispatch.",mutatesWorktree:!0}),...eg,ep("TERMINAL_RUN","Extensibility","Run terminal script","AGENT",["worktree.path"],["steps.<stepId>.*"],{description:"Runs a shell or Node script on the agent inside the worktree, capturing its output.",details:"Needs `worktree.path` and an online agent. A non-zero exit fails the step. Named credentials can be injected as environment variables so secrets never sit in the definition — the validator rejects secret-looking literals in config. Arbitrary code on the agent's machine: it can change anything the agent user can reach. Writes stdout, stderr, and the exit code under `steps.<stepId>.*`; to publish anything else the script produces into a named path, declare it in this step's own `providedPaths`.",mutatesWorktree:!0}),ep("MCP_CALL","Extensibility","Call MCP tool","SERVER",[],["steps.<stepId>.output"],{description:"Calls a tool on a configured MCP server — built-in or external — with a JSON argument object.",details:"The general escape hatch to anything reachable over MCP. Needs the server (tool group) and the exact tool name; arguments must match that tool's own schema. What it does depends entirely on the tool, so treat it as externally mutating. The result lands in `steps.<stepId>.output`.",mutatesExternal:!0})],ew=new Map(ey.map(e=>[e.kind,e])),eb=["run.*","worktree.*","codebase.*","agent.*","repo.*","ticket.*"],ev=["build.*","worktree.*","codebase.*","agent.*","repo.*","ticket.*"],ek=["worktree.*","codebase.*","agent.*","repo.*","ticket.*","pr.*"],eS=["ticket.*","comment.*","changelog.*"],eE=["repo.*","pr.*","ticket.*","worktree.*","codebase.*","agent.*"],eI=[...eE,"comment.*"],ex="Filters narrow it further: each session path must equal the given value, or be one of a list of values.",eA="Set a threshold path, operator, and value to fire only on the crossing: it fires when the comparison first becomes true and stays quiet until it goes false again, so a metric hovering over the line does not fire repeatedly.",e_=(e,t,r,i,a)=>({kind:e,category:t,label:r,description:a.description,details:a.details,configSchema:es(e,"trigger"),capabilityFlags:["DURABLE","DEDUPLICATED"],seedPaths:i,sourceHandles:m(e)}),eC=(e,t,r,i)=>e_(e,t,r,i,{description:`${r} emits a normalized, filterable workflow event.`,details:`${r} uses the canonical domain event and deduplicates deliveries by subject and revision. ${ex}`}),eR=[eC("COMMAND_RUN_RESULT","Commands","Command run result",["command.*","agent.*","worktree.*"]),eC("COMMAND_OUTPUT_MATCH","Commands","Command output match",["command.*","output.*"]),eC("SKILL_SYNC_RESULT","Skills","Skill sync result",["skillSync.*","skill.*","repo.*"]),eC("SKILL_SYNC_CONFLICT","Skills","Skill sync conflict",["skillSync.*","skill.*","repo.*"]),eC("GITHUB_PIPELINE_STATUS_CHANGED","GitHub","Pipeline status changed",["pipeline.*","repo.*","pr.*","worktree.*","codebase.*","agent.*","ticket.*"]),eC("GITHUB_PR_SYNCHRONIZED","GitHub","Pull request synchronized",eE),eC("GITHUB_REVIEW_APPROVED","GitHub","Pull request review approved",eE),eC("JIRA_TICKET_UPDATED","Jira","Jira ticket updated",eS),eC("JIRA_COMMENT_ADDED","Jira","Jira comment added",eS),eC("JIRA_WORKLOG_ADDED","Jira","Jira worklog added",eS),eC("JIRA_SPRINT_ENDED","Jira","Jira sprint ended",eS),eC("CODEBASE_SYNC_STATE_CHANGED","Codebases","Codebase sync state changed",["codebase.*","agent.*","repo.*"]),eC("CODEBASE_OPERATION_FAILED","Codebases","Codebase operation failed",["codebase.*","agent.*","repo.*","operation.*"]),eC("WORKTREE_SYNC_STATE_CHANGED","Worktrees","Worktree sync state changed",ek),eC("WORKTREE_AUTOMATION_RESULT","Worktrees","Worktree automation result",[...ek,"automation.*"]),eC("WORKTREE_CLEAN","Worktrees","Worktree became clean",ek),eC("PUSH_NOTIFICATION_RESULT","Notifications","Push notification result",["pushBatch.*"]),eC("IOS_DEVICE_ENROLLED","Devices","iOS device enrolled",["device.*"]),eC("IOS_DEVICE_REGISTRATION_RESULT","Devices","iOS device registration result",["device.*"]),eC("SIGNING_OPERATION_RESULT","Signing","Signing operation result",["signing.*","signingProfile.*","agent.*"]),eC("SIGNING_ASSET_EXPIRING","Signing","Signing asset expiring",["signing.*","signingProfile.*","agent.*"]),eC("BUILD_DATA_THRESHOLD","Build Data","Build-data threshold",["buildData.*","agent.*","worktree.*"]),eC("BUILD_DATA_CLEANUP_RESULT","Build Data","Build-data cleanup result",["buildData.*","cleanup.*","agent.*"]),eC("POLLING_OPERATION_STATE","Operations","Polling operation state",["polling.*"]),eC("MODEL_COST_CATALOG_CHANGED","Operations","Model-cost catalog changed",["modelCosts.*"]),eC("CREDENTIAL_STORE_DEGRADED","Operations","Credential store degraded",["credentials.*"]),eC("AGENT_RESOURCE_THRESHOLD","Agents","Agent resource threshold",["agent.*"]),eC("AGENT_VERSION_CHANGED","Agents","Agent version changed",["agent.*"]),eC("TOOL_CALL_RESULT","Tools","Tool call result",["toolCall.*"])],eT=[e_("MANUAL","Manual","Manual run",[],{description:"Fires when someone presses Run on the workflow. The default entry point.",details:"Seeds nothing beyond `workflow.*`, so steps hanging off it can only bind to values that later steps produce. A caller may still pass session data explicitly when starting the run. A workflow that has only a choice trigger refuses a plain run."}),e_("MANUAL_CHOICE","Manual","Manual run with a choice",[],{description:"Fires when someone picks an option from the menu under the run button, and routes the run out of that option's own handle.",details:"Declare at least one option, each with a unique key — the key names the outgoing handle, so renaming a label leaves edges attached. One workflow can fan out into several entry paths without a step in front of them. Every edge must leave a handle that still exists, or publishing fails."}),e_("RESOURCE_MANUAL","Manual","Run from a resource",[],{description:"Fires when someone starts the workflow from a specific resource page — a worktree, pull request, build, codebase, ticket, or run.",details:"Must target exactly one resource kind; add a second trigger to accept another. The page seeds that resource's namespace into session data, so a worktree-launched run gets its worktree, codebase, owning agent, repository, and any linked ticket. Those seeds are an optimistic contract — an optional link that is absent resolves to nothing at run time. A worktree does not seed `pr.*`; use a pull-request trigger or Load pull request to bring one into session data. This is also what makes the workflow show up on that resource's page."}),e_("RESOURCE_MANUAL_CHOICE","Manual","Run from a resource with a choice",[],{description:"Fires from a resource page after the person picks an option, routing out of that option's handle.",details:"The resource and choice triggers combined: pick a resource kind and declare keyed options. Same rules as both — one resource kind per trigger, unique option keys, and every edge on a live handle."}),e_("SCHEDULE","Schedule","On a schedule",[],{description:"Fires repeatedly on a fixed cadence measured in seconds.",details:'A cadence, not a cron expression — there is no way to say "weekdays at 9am". The clock runs while the workflow is enabled, and pausing the workflow stops it. Seeds nothing, so scheduled workflows normally start by loading whatever they operate on. Mind the overlap policy: a cadence shorter than the run takes will queue or coalesce.'}),e_("WORKFLOW_FINISHED","Workflows","Another workflow finished",["workflow.*"],{description:"Fires when a different workflow run reaches a terminal state.",details:`Chains workflows without making one a sub-workflow of the other, so the two stay independently runnable. Filter on \`workflow.id\` to watch a specific one and on the finishing status to react only to failures. ${ex}`}),e_("GITHUB_PR_STATE","GitHub","Pull request opened or ready",eE,{description:"Fires when a pull request is opened, or when a draft is marked ready for review.",details:`Needs GitHub polling configured for the repository. Seeds \`pr.*\` and \`repo.*\`, so steps can act on the pull request straight away. ${ex} Filter on \`pr.isDraft\` or the base branch to avoid firing on every pull request in the repository.`}),e_("GITHUB_REVIEW_CHANGES_REQUESTED","GitHub","Changes requested",eE,{description:"Fires when a reviewer submits a review requesting changes.",details:`The entry point for an automated "address the review" loop: pair it with Collect review comments and an AI session. Approvals and plain comments do not fire it. ${ex}`}),e_("GITHUB_REVIEW_COMMENT","GitHub","Review comment created",eI,{description:"Fires when a new review comment is posted on a pull request.",details:`Fires per comment rather than per review, so a reviewer leaving five comments fires it five times — take care with steps that start AI runs. Use Changes requested when you want one event per review. ${ex}`}),e_("GITHUB_PR_CLOSED","GitHub","Pull request merged or closed",eE,{description:"Fires when a pull request is merged or closed without merging.",details:`Both outcomes fire it; branch on \`pr.state\` to tell them apart. The natural place to hang cleanup — deleting the worktree, moving the ticket on. ${ex}`}),e_("GITHUB_CHECK_FAILED","GitHub","Check suite or run failed",["repo.*","pipeline.*","worktree.*","codebase.*","agent.*","pr.*","ticket.*"],{description:"Fires when a check suite or check run reports a failure.",details:`Seeds \`pipeline.*\`, including the ids the retry and cancel steps need. Flaky suites fire this often, so gate an automatic retry on a count or a delay rather than retrying unconditionally. ${ex}`}),e_("GITHUB_PUSH_DEFAULT","GitHub","Push to default branch",["repo.*","push.*","ticket.*"],{description:"Fires when a commit lands on the repository's default branch.",details:`Seeds \`repo.*\` and \`push.*\`, plus a ticket key when the pushed branch contains one. There is no pull request or worktree in scope, so a workflow hanging off it usually starts by creating one. Fires on merges too, since a merge is a push. ${ex}`}),e_("GITHUB_WORKFLOW_SUCCEEDED","GitHub","Workflow run succeeded",["repo.*","pipeline.*","worktree.*","codebase.*","agent.*","pr.*","ticket.*"],{description:"Fires when a GitHub Actions workflow run completes successfully.",details:`The success counterpart to the failure triggers — useful for gating a deploy or a merge on a green pipeline. Filter on the workflow name so every unrelated Actions run does not start this workflow. ${ex}`}),e_("GITHUB_ISSUE_COMMAND","GitHub","Issue comment command",["repo.*","pr.*","ticket.*","comment.*"],{description:"Fires when a comment from an allow-listed GitHub user matches a command pattern, such as `/deploy`.",details:`The only trigger that lets outside text start a workflow, so it is deliberately strict: an explicit list of GitHub logins is required, and the pattern must be anchored with \`^\` and \`$\` — publishing fails otherwise. Both checks must pass. Keep the allow-list tight, since anyone on it can start whatever the workflow does. ${ex}`}),e_("GITHUB_ACTIONS_RESULT","GitHub Actions","Workflow result",["repo.*","pipeline.*","worktree.*","codebase.*","agent.*","pr.*","ticket.*"],{description:"Fires when a tracked GitHub Actions run finishes, whatever its conclusion.",details:`The richest of the Actions triggers: it correlates the run back to its worktree, owning agent, pull request, and ticket when those links exist. Branch on the conclusion rather than adding separate success and failure triggers. ${ex}`}),e_("GITHUB_PR_LABEL","GitHub","Pull request label set",eE,{description:"Fires when a label is applied to a pull request.",details:`Turns a label into a manual switch — label a pull request \`automerge\` and let a workflow take it from there. Filter on the label name, or every label change in the repository starts the workflow. ${ex}`}),e_("BUILD_RESULT","Builds","Build result",ev,{description:"Fires when a build finishes, succeeded or failed.",details:`Seeds \`build.*\` along with the worktree it ran in, so the read-results and coverage steps can follow directly. Branch on \`build.status\` to separate the outcomes. ${ex}`}),e_("BUILD_TEST_THRESHOLD","Builds","Test failure threshold",ev,{description:"Fires when a build's failing-test count crosses a threshold you set.",details:`Point the threshold path at \`build.testSummary.failed\` and pick an operator and value. ${eA} ${ex}`}),e_("BUILD_COVERAGE_THRESHOLD","Builds","Coverage threshold",ev,{description:"Fires when a build's code coverage crosses a threshold you set.",details:`Point the threshold path at the coverage summary — usually the changed-files percentage rather than the whole-project number — and compare with a less-than operator. ${eA} ${ex}`}),e_("BUILD_HOOK_FAILED","Builds","Build hook failed",ev,{description:"Fires when one of a build's pre- or post-build scripts fails.",details:`Distinguishes a broken build script from a genuine compile or test failure, which is what Build result reports. Seeds \`build.*\`. ${ex}`}),e_("AGENT_CONNECTION","Agents","Agent connection changed",["agent.*","codebase.agentId"],{description:"Fires when an agent comes online or goes offline.",details:`Seeds the agent id, name, connection state, and capacity metrics. A workflow hanging off it is usually about notifying a human rather than doing repository work — an offline agent cannot run agent steps anyway. Filter on the connection status to react to one direction only. ${ex}`}),e_("AGENT_JOB_FAILED","Agents","Agent job failed",["steps.trigger.*","agent.*","codebase.*","worktree.*","repo.*","ticket.*"],{description:"Fires when a job dispatched to an agent fails — a build, a Git operation, a terminal script.",details:`The failing job is seeded under \`steps.trigger.*\`, including its kind and error. When it targeted a worktree, the owning agent, codebase, repository, and ticket are included too. Catches infrastructure failures that a workflow's own failure handles never see, because the job belonged to a different run. ${ex}`}),e_("AGENT_DISK_REPORT","Agents","Agent disk report",["agent.*","codebase.agentId","disk.*"],{description:"Fires whenever the Derived Data monitor accepts a new agent disk report.",details:`Seeds the complete monitor snapshot under \`disk.*\`, while \`agent.diskFreeBytes\` remains the legacy root-disk inventory value. This can fire at the agent poll cadence; use filters when every report is not needed. ${ex}`}),e_("AGENT_DISK_THRESHOLD","Agents","Agent disk threshold",["agent.*","codebase.agentId","disk.*"],{description:"Fires when monitored Derived Data free space crosses a threshold you set.",details:`Use \`disk.freeGiB\`, \`disk.freeBytes\`, or \`disk.freePercent\` to evaluate the least-free monitored Derived Data volume. \`agent.diskFreeBytes\` remains available for older root-disk workflows. ${eA} ${ex}`}),e_("AGENT_DISK_STATE_CHANGED","Agents","Agent disk state changed",["agent.*","codebase.agentId","disk.*"],{description:"Fires when an agent's disk monitor changes status, pressure mode, health, or monitored volume.",details:`Filter on \`disk.status\`, \`disk.pressureMode\`, \`disk.enabled\`, or errors and warnings to react to a specific transition. Cleanup start appears as \`DELETING\`; recovery can be selected with \`IDLE\`. Repeated reports in the same state stay quiet. ${ex}`}),e_("AGENT_DISK_CLEANUP_RESULT","Agents","Automatic disk cleanup result",["agent.*","codebase.agentId","disk.*","cleanup.*"],{description:"Fires whenever a monitor-managed automatic Derived Data cleanup finishes.",details:`Seeds the terminal agent job under \`cleanup.*\`, including status, error, targets, and deleted entries. Every cleanup job is independent, so two successive successes both fire. Manual Build Data deletions remain outside this trigger. ${ex}`}),e_("CCUSAGE_THRESHOLD","Agents","Usage threshold",["run.usage.*","agent.*"],{description:"Fires when aggregate AI usage crosses a threshold you set.",details:`Watches usage across runs rather than one run's spend — Run usage threshold does that. The cost guardrail: notify, or pause workflows that start AI runs. ${eA} ${ex}`}),e_("WORKTREE_CREATED","Worktrees","Worktree created",ek,{description:"Fires after a new worktree is successfully created.",details:`Fires once after the created worktree is projected into the control plane. Seeds the worktree, repository, codebase, and owning agent, plus a linked pull request and Jira ticket when the branch resolves to them. ${ex}`}),e_("WORKTREE_BEHIND","Worktrees","Worktree behind base",ek,{description:"Fires when a worktree's branch falls behind the branch it was cut from.",details:`Pairs with a sync operation to keep long-lived branches current. Fires again as the base moves on, so a workflow that reacts should either sync or be filtered narrowly. ${ex}`}),e_("WORKTREE_CONFLICT","Worktrees","Worktree has conflicts",ek,{description:"Fires when a worktree is left with Git conflicts after a merge or rebase.",details:`Only fires when the worktree is genuinely marked conflicted. Conflicts need resolving before most other worktree steps will work, so this usually leads to a notification or an AI session pointed at the conflict. ${ex}`}),e_("WORKTREE_MISSING","Worktrees","Worktree missing",ek,{description:"Fires when a worktree the control plane knows about is no longer on disk.",details:`Only fires once the worktree is actually recorded as missing — usually someone deleted the directory by hand, or the agent's disk was cleaned. Steps that need the worktree will fail, so react by recreating it or clearing the record. ${ex}`}),e_("WORKTREE_DIVERGED","Worktrees","Worktree diverged",ek,{description:"Fires when a worktree's branch and its remote have both moved on independently.",details:`Only fires when the push status is genuinely diverged. Resolving it means a rebase, a merge, or a force push — all destructive enough that this usually routes to a human rather than to an automatic fix. ${ex}`}),e_("WORKTREE_DIRTY_DURATION","Worktrees","Worktree dirty too long",ek,{description:"Fires when a worktree has had uncommitted changes for longer than expected.",details:`Catches work that stalled — an AI session that edited files and was never followed up, or a human who wandered off. Usually a nudge rather than an automatic commit. ${ex}`}),e_("WORKTREE_NEW_COMMIT","Worktrees","New worktree commit",ek,{description:"Fires when a new commit lands in a worktree.",details:`Fires per commit, so a rebase or a batch of commits fires it repeatedly — keep the reaction cheap, or filter to one branch. Useful for kicking off a build or lint pass as work lands. ${ex}`}),e_("CODEBASE_REMOTE_BRANCH","Codebases","Matching remote branch",["codebase.*","agent.*","repo.*"],{description:"Fires when a remote branch matching the codebase's conventions appears.",details:`Lets a branch pushed from elsewhere pull work into this system — creating a worktree for it, or opening a pull request. Needs a fetch to have run for the branch to be visible. ${ex}`}),e_("JIRA_STATUS","Jira","Ticket status changed",eS,{description:"Fires when a Jira ticket moves to another status.",details:`Needs Jira polling configured. Seeds \`ticket.*\`. Filter on \`ticket.status\` to react to one column only — without a filter, every transition on every polled ticket starts the workflow. ${ex}`}),e_("JIRA_LABEL","Jira","Jira label set",eS,{description:"Fires when a label is applied to a Jira ticket.",details:`The Jira counterpart to the pull request label trigger: a label becomes a manual switch for automation. Filter on the label name. ${ex}`}),e_("JIRA_ASSIGNED_SELF","Jira","Ticket assigned to me",eS,{description:"Fires when a ticket is assigned to the account behind the configured Jira credential.",details:`"Me" is whoever the Jira credential authenticates as, not whoever is looking at the screen. The usual start of a "pick up my next ticket" workflow — create a worktree, start a plan. ${ex}`}),e_("JIRA_SOURCE_NEW_TICKET","Jira","New ticket in source",eS,{description:"Fires when a ticket appears in a configured Jira source — a saved JQL query or board.",details:`Fires on tickets newly matching the source, which includes existing tickets edited into range, not only freshly created ones. The source itself does the filtering, so keep its JQL tight. Seeds \`ticket.*\`. ${ex}`}),e_("JIRA_MENTION","Jira","Jira comment mention",eS,{description:"Fires when the configured Jira account is mentioned in a ticket comment.",details:`Lets someone pull automation into a conversation by mentioning the bot. The comment is seeded under \`comment.*\`, so an AI step can read what was actually asked — treat that text as untrusted input rather than instructions. ${ex}`}),e_("JIRA_SPRINT_STARTED","Jira","Sprint started",eS,{description:"Fires when a Jira sprint is started.",details:`Fires per ticket in the sprint, so a sprint of thirty tickets starts thirty runs — mind the workflow's concurrency settings. Good for sprint-opening bookkeeping. ${ex}`}),e_("JIRA_ISSUE_CREATED","Jira","Ticket created",eS,{description:"Fires when a Jira ticket is created.",details:`Needs the Jira webhook configured in Settings — the polled Jira triggers only observe tickets something already fetched, so they cannot see a brand-new one. Scope the webhook's JQL filter to the projects you care about, since every created ticket otherwise starts a run. ${ex}`}),e_("JIRA_ISSUE_DELETED","Jira","Ticket deleted",eS,{description:"Fires when a Jira ticket is deleted.",details:`Needs the Jira webhook. The ticket is gone by the time this runs, so only the payload's \`ticket.*\` snapshot is available — a step that loads the ticket will fail. Use it for cleanup: close the worktree, cancel the run, archive the branch. ${ex}`}),e_("JIRA_ISSUE_COMMAND","Jira","Ticket comment command",eS,{description:"Fires when a comment from an allow-listed Jira account matches a command pattern, such as `/deploy`.",details:`The Jira counterpart to the GitHub issue comment command, and just as strict: an explicit list of Jira account IDs is required, and the pattern must be anchored with \`^\` and \`$\` — publishing fails otherwise. Jira identifies people by opaque account ID, not display name, so copy the ID from the user's Jira profile URL. Treat the comment body as untrusted input rather than instructions. Needs the Jira webhook. ${ex}`}),e_("JIRA_ATTACHMENT_ADDED","Jira","Attachment added",[...eS,"attachment.*"],{description:"Fires when a file is attached to a Jira ticket.",details:`Needs the Jira webhook. Seeds \`attachment.*\` with the filename, MIME type, and author. Filter on \`attachment.mimeType\` to react to one kind of upload — a crash log, a design export. ${ex}`}),e_("JIRA_ISSUE_LINKED","Jira","Ticket linked",[...eS,"link.*"],{description:"Fires when a Jira issue link is created.",details:`Needs the Jira webhook. Seeds \`link.*\` with the link type and both issue IDs. Filter on \`link.type\` to react to one relationship — "blocks", "duplicates" — rather than every link. ${ex}`}),e_("RUN_STARTED","Plans and sessions","Run started",eb,{description:"Fires when an AI plan or session run begins.",details:`Every run trigger seeds the same shape — \`run.*\` plus the worktree, codebase, repository, and ticket it is attached to. Filter on \`run.kind\` to separate plans from sessions. ${ex}`}),e_("RUN_COMPLETED","Plans and sessions","Run completed",eb,{description:"Fires when an AI run finishes successfully.",details:`The place to hang everything that happens after the agent is done — committing, pushing, opening a pull request, moving the ticket. Filter on \`run.kind\` to react only to plans or only to sessions. ${ex}`}),e_("RUN_QUESTION_NEEDED","Plans and sessions","Run needs an answer",eb,{description:"Fires when an AI run pauses to ask a question, with the pending questions in session data.",details:`The questions arrive under \`run.questions\`, so the Answer run question step can respond without a human — the basis for unattended runs. Answer carefully: an automatic answer to a question the agent should have asked a person is how unwanted changes get made. ${ex}`}),e_("RUN_QUESTION_ANSWERED","Plans and sessions","Run question answered",eb,{description:"Fires when a pending question on an AI run is answered.",details:`Fires however the answer arrived — from a person or from another workflow. Use it to record decisions, or to resume work that was gated on the answer. ${ex}`}),e_("RUN_PAUSED","Plans and sessions","Run paused",eb,{description:"Fires when an AI run is paused.",details:`Covers pauses from any source, including a run that paused itself. A run needing an answer reports separately through Run needs an answer. ${ex}`}),e_("RUN_CONTINUED","Plans and sessions","Run continued",eb,{description:"Fires when a paused AI run resumes.",details:`The counterpart to Run paused. Fires on each resume, so a run that stops and starts repeatedly fires it repeatedly. ${ex}`}),e_("RUN_FAILED","Plans and sessions","Run failed",eb,{description:"Fires when an AI run ends in failure.",details:`The error is in the seeded run data, so a follow-up run can be pointed at what went wrong. Beware of loops — a workflow that reacts by starting another run that fails the same way will keep going. ${ex}`}),e_("RUN_CANCELLED","Plans and sessions","Run cancelled",eb,{description:"Fires when an AI run is cancelled.",details:`Cancellation leaves whatever the run already wrote in the worktree, so cleanup usually means inspecting or reverting rather than assuming nothing happened. ${ex}`}),e_("RUN_PLAN_PLAYED","Plans and sessions","Plan played",eb,{description:"Fires when a run is created by executing a previously completed plan.",details:`Distinguishes plan execution from an ordinary session, which Run started cannot. Lets a workflow treat planned work differently from ad-hoc work. ${ex}`}),e_("RUN_FOLLOW_UP","Plans and sessions","Run follow-up created",eb,{description:"Fires when a run is created as a follow-up to another run.",details:`Does not fire for plan execution, which reports through Plan played. The parent run is in the seeded data, so a workflow can count how deep a follow-up chain has gone and stop it. ${ex}`}),e_("RUN_IMPORTED","Plans and sessions","Provider run imported",eb,{description:"Fires when a run started outside this system is imported from a provider.",details:`Lets work begun in another tool pick up the same automation — labelling, ticket updates, pull requests. The run did not originate here, so its worktree and ticket links may be incomplete. ${ex}`}),e_("RUN_USAGE_THRESHOLD","Plans and sessions","Run usage threshold",eb,{description:"Fires when a single run's token or cost usage crosses a threshold you set.",details:`Scoped to one run, unlike the aggregate Usage threshold. Point the threshold path at the usage figure you care about — a runaway session can then be cancelled automatically. ${eA} ${ex}`}),e_("RUN_EVENT_MATCH","Plans and sessions","Run event or tool matched",eb,{description:"Fires on individual events inside an AI run, including each tool call it makes.",details:`The finest-grained run trigger, and by far the most talkative — a single run produces hundreds of events, and every one is a candidate. Always filter, on the event type or the tool name. Useful for reacting to a specific tool being used; a poor choice for anything expensive. ${ex}`}),...eR],eD=new Map(eT.map(e=>[e.kind,e])),eN=t.z.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/),eO=t.z.string().min(1).max(256).regex(/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_*\[\]-]+)*$/),eP=t.z.record(t.z.string(),t.z.unknown()).default({}),e$=t.z.object({id:eN,kind:t.z.enum(s),name:t.z.string().min(1).max(200).optional(),position:t.z.object({x:t.z.number().finite(),y:t.z.number().finite()}),config:eP}),eU=t.z.object({id:eN,kind:t.z.enum(n),name:t.z.string().min(1).max(200).optional(),position:t.z.object({x:t.z.number().finite(),y:t.z.number().finite()}),config:eP,requiredPaths:t.z.array(eO).max(100).default([]),providedPaths:t.z.array(eO).max(100).default([]),retry:t.z.object({maxAttempts:t.z.number().int().min(1).max(20).default(1),strategy:t.z.enum(["FIXED","EXPONENTIAL"]).default("EXPONENTIAL"),delaySeconds:t.z.number().int().min(1).max(86400).default(5)}).default({maxAttempts:1,strategy:"EXPONENTIAL",delaySeconds:5}),failurePolicy:t.z.enum(["FAIL","CONTINUE"]).default("FAIL")}),eB=t.z.object({id:eN,source:eN,target:eN,sourceHandle:t.z.string().min(1).max(100).default("success"),targetHandle:t.z.string().min(1).max(100).default("input")}),ej=t.z.object({format:t.z.literal(eo),schemaVersion:t.z.literal(1),name:t.z.string().min(1).max(200),description:t.z.string().max(2e3).default(""),triggers:t.z.array(e$).max(100).default([]),nodes:t.z.array(eU).max(1e3).default([]),edges:t.z.array(eB).max(5e3).default([]),editor:t.z.object({viewport:t.z.object({x:t.z.number(),y:t.z.number(),zoom:t.z.number().positive()}).optional(),handleLayout:t.z.enum(["SIDES","TOP_BOTTOM"]).default("SIDES"),displayLayout:t.z.enum(["REGULAR","BASIC"]).default("REGULAR")}).default({handleLayout:"SIDES",displayLayout:"REGULAR"})});function eL(e,t){return t.map(t=>t.replaceAll("<stepId>",e.id))}function eq(e,t){return e===t||"*"===e||e.endsWith(".*")&&t.startsWith(e.slice(0,-1))}function eM(e){return e.length?new Set([...e[0]].filter(t=>e.every(e=>e.has(t)))):new Set}function eF(e,t){return[...e].some(e=>eq(e,t))}let eK={stepPaths(e){let t=ew.get(e);return{requiredPaths:t?.requiredPaths??[],providedPaths:t?.providedPaths??[]}},triggerSeedPaths:e=>eD.get(e)?.seedPaths??[]};function eV(e,t=eK){let r=new Set(e.nodes.map(({id:e})=>e)),i=new Map(e.nodes.map(e=>[e.id,e])),a=new Map,n=new Map;for(let t of e.edges)a.set(t.source,[...a.get(t.source)??[],t.target]),n.set(t.target,[...n.get(t.target)??[],t.source]);let s=new Map(e.nodes.map(e=>[e.id,0]));for(let t of e.edges)r.has(t.source)&&r.has(t.target)&&s.set(t.target,(s.get(t.target)??0)+1);let o=[...s].filter(([,e])=>0===e).map(([e])=>e),l=[];for(;o.length;){let e=o.shift();for(let t of(l.push(e),a.get(e)??[])){if(!r.has(t))continue;let e=(s.get(t)??0)-1;s.set(t,e),0===e&&o.push(t)}}let u=e=>{let t=new Set,r=[...a.get(e)??[]];for(;r.length;){let e=r.shift();t.has(e)||(t.add(e),r.push(...a.get(e)??[]))}return t},c=new Map;for(let t of[...e.triggers,...e.nodes])c.set(t.id,u(t.id));let d=new Map;for(let r of e.nodes){let e=t.stepPaths(r.kind);d.set(r.id,[...eL(r,e.providedPaths),...r.providedPaths,`steps.${r.id}.*`])}let p=new Map,h=[];for(let r of e.triggers){let e=new Set(["workflow.*"]);for(let i of t.triggerSeedPaths(r.kind))e.add(i);for(let t of ed(r.kind,r.config))e.add(t);let a=new Map;for(let s of l){if(!c.get(r.id)?.has(s))continue;let o=i.get(s),l=(n.get(s)??[]).filter(e=>e===r.id||a.has(e));if(!l.length)continue;let u=eM(l.map(t=>t===r.id?e:a.get(t))),m=p.get(s);p.set(s,m?eM([m,u]):new Set(u));let f=new Set(d.get(s)??[]),g=[...ee(o.kind,"step",o.config)].filter(e=>!eF(f,e));for(let e of new Set([...eL(o,t.stepPaths(o.kind).requiredPaths),...o.requiredPaths,...g]))eF(u,e)||h.push({nodeId:o.id,triggerId:r.id,triggerName:r.name??r.kind,path:e});let y=new Set(u);for(let e of d.get(s)??[])y.add(e);a.set(s,y)}}return{availableBefore:new Map([...p].map(([e,t])=>[e,[...t]])),provides:d,requirementViolations:h}}function eG(e,t=""){return Array.isArray(e)?e.some(e=>eG(e,t)):e&&"object"==typeof e?Object.entries(e).some(([e,t])=>eG(t,e)):"string"==typeof e&&/(token|secret|password|passwd|private.?key|api.?key|authorization)/i.test(t)&&!/(credential.?id|credential.?ids)$/i.test(t)}function eH(e){return Array.isArray(e)?e.some(eH):!!e&&"object"==typeof e&&("UNRESOLVED"===e.referenceStatus||Object.values(e).some(eH))}e.s(["WORKFLOW_SCHEMA_VERSION",0,1,"WORKFLOW_STEP_BY_KIND",0,ew,"WORKFLOW_STEP_CATALOG",0,ey,"WORKFLOW_TRIGGER_CATALOG",0,eT,"computeWorkflowPathAvailability",0,eV,"emptyWorkflowDefinition",0,function(e="Untitled workflow"){return ej.parse({format:eo,schemaVersion:1,name:e,description:"",triggers:[{id:"manual",kind:"MANUAL",position:{x:0,y:100},config:{}}],nodes:[],edges:[],editor:{}})},"hasWorkflowErrors",0,function(e){return e.some(({severity:e})=>"ERROR"===e)},"parseWorkflowDefinition",0,function(e){return ej.parse(e)},"resourceManualSeedPaths",0,ed,"sanitizeWorkflowExportDefinition",0,function(e){let t=(e,r="")=>Array.isArray(e)?e.map(e=>t(e,r)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,r])=>[e,t(r,e)])):"string"==typeof e&&/(token|secret|password|passwd|private.?key|api.?key|authorization)/i.test(r)&&!/(credential.?id|credential.?ids)$/i.test(r)||"string"==typeof e&&/^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(e)&&/^(?:cwd|folder|path|directory)$/i.test(r)?null:e;return ej.parse(t(e))},"validateWorkflowDefinition",0,function(e){let t=ej.safeParse(e);if(!t.success)return{definition:null,diagnostics:t.error.issues.map(e=>({severity:"ERROR",code:"SCHEMA_INVALID",message:e.message,path:e.path.join(".")}))};let r=t.data,i=[],a=new Set;for(let e of[...r.triggers,...r.nodes])a.has(e.id)&&i.push({severity:"ERROR",code:"DUPLICATE_NODE_ID",message:`Duplicate graph id ${e.id}`,nodeId:e.id}),a.add(e.id);let n=new Set;for(let e of r.edges)n.has(e.id)&&i.push({severity:"ERROR",code:"DUPLICATE_EDGE_ID",message:`Duplicate edge id ${e.id}`}),n.add(e.id),a.has(e.source)&&a.has(e.target)||i.push({severity:"ERROR",code:"EDGE_ENDPOINT_MISSING",message:`Edge ${e.id} references a missing endpoint`}),r.triggers.some(({id:t})=>t===e.target)&&i.push({severity:"ERROR",code:"TRIGGER_HAS_INPUT",message:"Triggers cannot have incoming edges",triggerId:e.target});r.triggers.length||i.push({severity:"ERROR",code:"TRIGGER_REQUIRED",message:"At least one trigger is required"}),r.nodes.length||i.push({severity:"ERROR",code:"STEP_REQUIRED",message:"At least one step is required"});let s=new Set(r.nodes.map(({id:e})=>e)),o=new Map,l=new Map;for(let e of r.edges)o.set(e.source,[...o.get(e.source)??[],e.target]),l.set(e.target,[...l.get(e.target)??[],e.source]);for(let e of r.nodes)(l.get(e.id)??[]).filter(e=>s.has(e)).length>1&&"CONTROL_JOIN"!==e.kind&&i.push({severity:"ERROR",code:"EXPLICIT_JOIN_REQUIRED",message:"Nodes with multiple incoming branches must be explicit join nodes",nodeId:e.id});let u=new Map(r.nodes.map(e=>[e.id,0]));for(let e of r.edges)s.has(e.source)&&s.has(e.target)&&u.set(e.target,(u.get(e.target)??0)+1);let p=[...u].filter(([,e])=>0===e).map(([e])=>e),h=[];for(;p.length;){let e=p.shift();for(let t of(h.push(e),o.get(e)??[])){if(!s.has(t))continue;let e=(u.get(t)??0)-1;u.set(t,e),0===e&&p.push(t)}}h.length!==r.nodes.length&&i.push({severity:"ERROR",code:"DAG_CYCLE",message:"Workflow graphs cannot contain free-form cycles"});let m=new Map,f=e=>{let t=new Set,r=[...o.get(e)??[]];for(;r.length;){let e=r.shift();t.has(e)||(t.add(e),r.push(...o.get(e)??[]))}return t};for(let e of[...r.triggers,...r.nodes])m.set(e.id,f(e.id));for(let e of r.nodes){for(let t of(r.triggers.some(t=>m.get(t.id)?.has(e.id))||i.push({severity:"ERROR",code:"UNREACHABLE_STEP",message:"Step is not reachable from a trigger",nodeId:e.id}),eG(e.config)&&i.push({severity:"ERROR",code:"SECRET_LITERAL",message:"Store secrets as credential references, not workflow literals",nodeId:e.id}),eH(e.config)&&i.push({severity:"ERROR",code:"UNRESOLVED_REFERENCE",message:"Resolve imported references before publishing",nodeId:e.id}),new Set(E(e.config))))i.push({severity:"ERROR",code:"SESSION_BINDING_INVALID",message:t,nodeId:e.id});"CONTROL_SUBWORKFLOW"===e.kind&&"string"!=typeof e.config.versionId&&i.push({severity:"ERROR",code:"SUBWORKFLOW_VERSION_REQUIRED",message:"Sub-workflows must pin a published version",nodeId:e.id})}for(let e of r.triggers){for(let t of((o.get(e.id)??[]).length||i.push({severity:"ERROR",code:"TRIGGER_DISCONNECTED",message:"Trigger is not connected to a step",triggerId:e.id}),eG(e.config)&&i.push({severity:"ERROR",code:"SECRET_LITERAL",message:"Store secrets as credential references, not trigger literals",triggerId:e.id}),eH(e.config)&&i.push({severity:"ERROR",code:"UNRESOLVED_REFERENCE",message:"Resolve imported references before publishing",triggerId:e.id}),new Set(E(e.config))))i.push({severity:"ERROR",code:"SESSION_BINDING_INVALID",message:t,triggerId:e.id});if(d(e.kind)&&!ec(e.config)&&i.push({severity:"ERROR",code:"RESOURCE_KIND_REQUIRED",message:"Resource triggers must target a single resource kind; add one trigger per kind",triggerId:e.id}),c(e.kind)){let t=el(e.config),a=Array.isArray(e.config.choices)?e.config.choices.length:0;t.length&&t.length===a||i.push({severity:"ERROR",code:"TRIGGER_CHOICES_REQUIRED",message:"Choice triggers need at least one option, each with a unique key",triggerId:e.id});let n=new Set(t.map(({key:e})=>e));for(let t of r.edges)t.source===e.id&&(n.has(t.sourceHandle)||i.push({severity:"ERROR",code:"TRIGGER_CHOICE_HANDLE_UNKNOWN",message:`Connection ${t.id} leaves an option that no longer exists`,triggerId:e.id}))}if("GITHUB_ISSUE_COMMAND"===e.kind||"JIRA_ISSUE_COMMAND"===e.kind){let t="JIRA_ISSUE_COMMAND"===e.kind,r=t?e.config.allowedAccountIds:e.config.allowedLogins,a=e.config.commandPattern;(!Array.isArray(r)||!r.length||r.some(e=>"string"!=typeof e||!e.trim()))&&i.push({severity:"ERROR",code:"ISSUE_COMMAND_ALLOWLIST_REQUIRED",message:t?"Issue command triggers require an explicit Jira account ID allow-list":"Issue command triggers require an explicit GitHub login allow-list",triggerId:e.id}),"string"==typeof a&&a.startsWith("^")&&a.endsWith("$")||i.push({severity:"ERROR",code:"ISSUE_COMMAND_PATTERN_ANCHORED",message:"Issue command patterns must be anchored with ^ and $",triggerId:e.id})}}for(let e of eV(r).requirementViolations)i.push({severity:"ERROR",code:"REQUIREMENT_UNSATISFIED",message:`${e.path} is not guaranteed on the path from ${e.triggerName}`,nodeId:e.nodeId,triggerId:e.triggerId,path:e.path});for(let e=0;e<r.nodes.length;e+=1){let t=r.nodes[e],a=[...eL(t,ew.get(t.kind).providedPaths),...t.providedPaths].filter(e=>!e.startsWith(`steps.${t.id}.`));for(let n=e+1;n<r.nodes.length;n+=1){let e=r.nodes[n];if(m.get(t.id)?.has(e.id)||m.get(e.id)?.has(t.id))continue;let s=[...eL(e,ew.get(e.kind).providedPaths),...e.providedPaths].filter(t=>!t.startsWith(`steps.${e.id}.`));a.some(e=>s.some(t=>eq(e,t)||eq(t,e)))&&i.push({severity:"ERROR",code:"PARALLEL_WRITE_CONFLICT",message:`Parallel steps ${t.name??t.id} and ${e.name??e.id} can write the same session-data path`,nodeId:e.id})}}return{definition:r,diagnostics:i}},"workflowResourceKind",0,ec,"workflowTriggerChoices",0,el],497800)},107058,963910,112627,695248,e=>{"use strict";var t=e.i(666680),r=e.i(243783);e.i(582482);var i=e.i(318905),a=e.i(91022),n=e.i(397554),s=e.i(827957);function o(e){if(null===e||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function l(e){let t=o(e.get("x-ratelimit-limit")),r=o(e.get("x-ratelimit-remaining")),i=o(e.get("x-ratelimit-used")),a=o(e.get("x-ratelimit-reset")),n=e.get("x-ratelimit-resource")?.trim()??"";if(null===t||null===r||null===i||null===a||!n)return null;let s=new Date(1e3*a);return Number.isFinite(s.getTime())?{limit:t,remaining:r,used:i,resetAt:s,resource:n}:null}async function u(e,t){let i=l(t.headers);if(!i)return null;try{let t=await (0,r.getPrismaClient)(),a=`${e}:${i.resource}`,n=new Date;await t.gitHubRateLimitSnapshot.upsert({where:{authentication_resource:{authentication:e,resource:i.resource}},create:{id:a,authentication:e,observedAt:n,...i},update:{observedAt:n,...i}})}catch{}return i}async function c(){let e=await (0,r.getPrismaClient)();return(await e.gitHubRateLimitSnapshot.findMany({orderBy:[{resource:"asc"},{authentication:"asc"}]})).map(e=>({authentication:e.authentication,resource:e.resource,limit:e.limit,remaining:e.remaining,used:e.used,resetAt:e.resetAt.toISOString(),observedAt:e.observedAt.toISOString()}))}let d="actions.cancelWorkflowRun",p="actions.dispatchWorkflow",h="actions.forceCancelWorkflowRun",m="actions.getJobForWorkflowRun",f="actions.getWorkflowRun",g="actions.getWorkflowRunAttempt",y="actions.listJobsForWorkflowRun",w="actions.listJobsForWorkflowRunAttempt",b="actions.listRepoWorkflows",v="actions.listWorkflowRuns",k="actions.listWorkflowRunsForRepo",S="actions.reRunJobForWorkflowRun",E="actions.reRunWorkflow",I="actions.reRunWorkflowFailedJobs",x="apps.createInstallationAccessToken",A="apps.getAuthenticated",_="apps.getInstallation",C="apps.updateWebhookConfigForApp",R="repos.listPullRequestsAssociatedWithCommit",T="users.listEmailsForAuthenticatedUser";class D extends Error{code;githubRequestId;statusCode;rateLimit;constructor(e,t,r=null,i=null,a=null){super(t),this.code=e,this.githubRequestId=r,this.statusCode=i,this.rateLimit=a,this.name="GitHubAppError"}}let N=new Map,O=new Map;function P(e,t,r){let i=e.trim();if(!/^[1-9]\d*$/.test(i))throw new D(r,`${t} must be a positive integer`);return i}function $(e){let{privateKeyPkcs8:r,keyFingerprint:i}=function(e){try{let r=(0,t.createPrivateKey)({key:e.trim(),format:"pem"});if("rsa"!==r.asymmetricKeyType)throw Error("The key is not RSA");let i=r.export({format:"pem",type:"pkcs8"}).toString(),a=(0,t.createPublicKey)(r).export({format:"der",type:"spki"}),n=`SHA256:${(0,t.createHash)("sha256").update(a).digest("base64url")}`;return{key:r,privateKeyPkcs8:i,keyFingerprint:n}}catch{throw new D("INVALID_PRIVATE_KEY","The GitHub App private key is not a valid RSA PEM")}}(e.privateKey);return{...e,appId:P(e.appId,"GitHub App ID","INVALID_APP_ID"),installationId:P(e.installationId,"GitHub installation ID","INVALID_INSTALLATION_ID"),privateKeyPkcs8:r,keyFingerprint:i}}async function U(e){try{let t=await (0,n.importPKCS8)(e.privateKeyPkcs8,"RS256"),r=Math.floor(Date.now()/1e3);return await new s.SignJWT({}).setProtectedHeader({alg:"RS256",typ:"JWT"}).setIssuer(e.appId).setIssuedAt(r-60).setExpirationTime(r+540).sign(t)}catch{throw new D("INVALID_PRIVATE_KEY","The GitHub App private key could not sign an App JWT")}}function B(e){return`${e.appId}:${e.installationId}:${e.keyFingerprint}`}function j(e){return{accept:"application/vnd.github+json",authorization:e,"user-agent":"ai-development-environment","x-github-api-version":"2022-11-28"}}async function L(e,t,r,i,a){let n,s=Date.now(),o=(t.method??"GET").toUpperCase(),u=e===i?.graphqlUrl&&"string"==typeof t.body?t.body:null;try{n=await fetch(e,{...t,cache:"no-store"})}catch{throw i?.requestObserver&&await Promise.resolve(i.requestObserver({url:e,method:o,operation:r,requestSource:a,body:u,durationMs:Date.now()-s,statusCode:null,error:"GitHub could not be reached",rateLimit:null})).catch(()=>void 0),new D("GITHUB_APP_REQUEST_FAILED","GitHub could not be reached")}return i?.responseObserver&&await Promise.resolve(i.responseObserver(n)).catch(()=>void 0),i?.requestObserver&&await Promise.resolve(i.requestObserver({url:e,method:o,operation:r,requestSource:a,body:u,durationMs:Date.now()-s,statusCode:n.status,error:n.ok?null:`GitHub returned HTTP ${n.status}`,rateLimit:l(n.headers)})).catch(()=>void 0),n}async function q(e){try{return await e.json()}catch{return null}}function M(e){return e.headers.get("x-github-request-id")}function F(e,t,r=[]){let i=`GitHub returned HTTP ${t}`;for(let t of(e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message&&(i=e.message),r))t&&(i=i.split(t).join("[REDACTED]"));return i}async function K(e,t){let r=await L(`${e.apiBaseUrl}/app/installations/${e.installationId}`,{headers:j(`Bearer ${t}`)},_,e,"GITHUB_SETTINGS"),i=await q(r),a=M(r);if(401===r.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",a);if(404===r.status)throw new D("INSTALLATION_NOT_FOUND","The GitHub App installation was not found",a);if(!r.ok||!i||"object"!=typeof i)throw new D("GITHUB_APP_REQUEST_FAILED",F(i,r.status,[t,e.privateKey,e.privateKeyPkcs8]),a);if(String(i.app_id)!==e.appId)throw new D("APP_INSTALLATION_MISMATCH","The installation does not belong to the configured GitHub App",a);return i}async function V(e,t){let r=await L(`${e.apiBaseUrl}/app`,{headers:j(`Bearer ${t}`)},A,e,"GITHUB_SETTINGS"),i=await q(r),a=M(r);if(401===r.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",a);if(!r.ok||!i||"object"!=typeof i)throw new D("GITHUB_APP_REQUEST_FAILED",F(i,r.status,[t,e.privateKey,e.privateKeyPkcs8]),a);if(String(i.id)!==e.appId||!i.slug||!i.owner?.login||!i.owner.type)throw new D("GITHUB_APP_REQUEST_FAILED","GitHub returned incomplete GitHub App registration details",a);return{details:i,githubRequestId:a}}async function G(e){let t=$(e),r=await U(t),i=await V(t,r);return{appSlug:i.details.slug,appOwnerLogin:i.details.owner.login,appOwnerType:i.details.owner.type,githubRequestId:i.githubRequestId}}async function H(e,t,r){let i=r??await U(e),a=await L(`${e.apiBaseUrl}/app/installations/${e.installationId}/access_tokens`,{method:"POST",headers:j(`Bearer ${i}`)},x,e,t),n=await q(a),s=M(a);if(401===a.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the App ID or private key",s);if(404===a.status)throw new D("INSTALLATION_NOT_FOUND","The GitHub App installation was not found",s);if(!a.ok||!n||"object"!=typeof n)throw new D("GITHUB_APP_REQUEST_FAILED",F(n,a.status,[i,e.privateKey,e.privateKeyPkcs8]),s);if("string"!=typeof n.token||!n.token||"string"!=typeof n.expires_at||Number.isNaN(Date.parse(n.expires_at)))throw new D("GITHUB_APP_REQUEST_FAILED","GitHub returned an invalid installation token response",s);if("write"!==(n.permissions?.actions??"none"))throw new D("ACTIONS_PERMISSION_REQUIRED","The GitHub App installation must grant Actions: read and write",s);return{token:n.token,expiresAt:new Date(n.expires_at),permissions:n.permissions??{},repositorySelection:n.repository_selection??"selected"}}async function W(e,t){let r=B(e),i=N.get(r);if(i&&i.expiresAt.getTime()-3e5>Date.now())return i;let a=O.get(r);if(a)return a;let n=H(e,t).then(e=>(N.set(r,e),e)).finally(()=>O.delete(r));return O.set(r,n),n}function J(){N.clear(),O.clear()}async function z(e,t,r){let i=$(e),a=await W(i,r),n=await t(a.token);return 401===n.status&&(N.delete(B(i)),a=await W(i,r),n=await t(a.token)),{response:n,token:a.token}}async function Z(e,t,r,i){let{response:a,token:n}=await z(e,a=>L(e.graphqlUrl,{method:"POST",headers:{...j(`Bearer ${a}`),"content-type":"application/json"},body:JSON.stringify({query:t,variables:r})},null,e,i),i),s=await q(a),o=M(a),u=l(a.headers);if(401===a.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",o,a.status,u);if(!a.ok||s?.errors?.length||!s?.data){let t=s?.errors?.map(e=>e.message).filter(Boolean).join("; ")||F(s,a.status,[n]);throw new D("GITHUB_APP_REQUEST_FAILED",F({message:t},a.status,[n,e.privateKey]),o,a.status,u)}return{data:s.data,githubRequestId:o,statusCode:a.status,rateLimit:u}}async function Y(e){let t=$(e),r=await U(t),[i,a]=await Promise.all([K(t,r),V(t,r)]),n=await H(t,"GITHUB_SETTINGS",r);N.set(B(t),n);let s=await Z(t,"query VerifyGitHubApp { viewer { login } }",{},"GITHUB_SETTINGS");return{appId:t.appId,installationId:t.installationId,keyFingerprint:t.keyFingerprint,appSlug:a.details.slug,appOwnerLogin:a.details.owner.login,appOwnerType:a.details.owner.type,accountLogin:i.account.login,repositorySelection:n.repositorySelection,actionsPermission:n.permissions.actions??"none",checksPermission:n.permissions.checks??"none",commitStatusesPermission:n.permissions.statuses??"none",webhookEvents:Array.isArray(i.events)?i.events:[],viewerLogin:s.data.viewer.login,verifiedAt:new Date,githubRequestId:s.githubRequestId}}async function Q(e,t){let r=$(e),i=await U(r),a=await L(`${r.apiBaseUrl}/app/hook/config`,{method:"PATCH",headers:{...j(`Bearer ${i}`),"content-type":"application/json"},body:JSON.stringify({url:t.url,content_type:"json",secret:t.secret,insecure_ssl:"0"})},C,r,"GITHUB_SETTINGS"),n=M(a);if(404===a.status)return{configured:!1,githubRequestId:n};if(!a.ok)throw new D("GITHUB_APP_REQUEST_FAILED",F(await q(a),a.status,[i,t.secret,r.privateKey]),n);return{configured:!0,githubRequestId:n}}async function X(e,t){let r=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/rerun`,{response:i,token:a}=await z(e,i=>L(r,{method:"POST",headers:j(`Bearer ${i}`)},E,e,t.requestSource),t.requestSource),n=M(i);if(401===i.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",n);if(!i.ok){let t=await q(i);throw new D(404===i.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===i.status?"The repository or workflow run is not available to this installation":F(t,i.status,[a,e.privateKey]),n)}return{githubRequestId:n}}async function ee(e,t){let r=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/rerun-failed-jobs`,{response:i,token:a}=await z(e,i=>L(r,{method:"POST",headers:j(`Bearer ${i}`)},I,e,t.requestSource),t.requestSource),n=M(i);if(!i.ok){let t=await q(i);throw new D(404===i.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===i.status?"The repository or workflow run is not available to this installation":F(t,i.status,[a,e.privateKey]),n)}return{githubRequestId:n}}async function et(e,t){let r=t.force?"force-cancel":"cancel",i=t.force?h:d,a=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/${r}`,{response:n,token:s}=await z(e,r=>L(a,{method:"POST",headers:j(`Bearer ${r}`)},i,e,t.requestSource),t.requestSource),o=M(n);if(401===n.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",o);if(!n.ok){let t=await q(n);throw new D(404===n.status?"REPOSITORY_NOT_INSTALLED":"GITHUB_APP_REQUEST_FAILED",404===n.status?"The repository or workflow run is not available to this installation":F(t,n.status,[s,e.privateKey]),o)}return{githubRequestId:o}}async function er(e,t){let r=[],i=1,a=0;do{let n=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}/actions/runs/${encodeURIComponent(t.workflowRunId)}/jobs?filter=latest&per_page=100&page=${i}`,{response:s,token:o}=await z(e,r=>L(n,{headers:j(`Bearer ${r}`)},y,e,t.requestSource),t.requestSource),l=M(s);if(401===s.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",l);let u=await q(s);if(!s.ok||!u||"object"!=typeof u)throw new D("GITHUB_APP_REQUEST_FAILED",F(u,s.status,[o,e.privateKey]),l);if(!Number.isInteger(u.total_count)||!Array.isArray(u.jobs))throw new D("GITHUB_APP_REQUEST_FAILED","GitHub returned an invalid workflow jobs response",l);a=u.total_count??0,r.push(...u.jobs),i+=1}while(r.length<a)return r}async function ei(e,t){let r=`${e.apiBaseUrl}/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repository)}`,i=`${r}/actions/jobs/${encodeURIComponent(t.jobId)}`,a=await z(e,r=>L(i,{headers:j(`Bearer ${r}`)},m,e,t.requestSource),t.requestSource),n=M(a.response);if(401===a.response.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",n);let s=await q(a.response);if(!a.response.ok||!s||"object"!=typeof s)throw new D(404===a.response.status?"ACTIONS_JOB_NOT_FOUND":"GITHUB_APP_REQUEST_FAILED",404===a.response.status?"The GitHub Actions job is not available to this installation":F(s,a.response.status,[a.token,e.privateKey]),n);if(String(s.run_id??"")!==t.workflowRunId)throw new D("ACTIONS_JOB_RUN_MISMATCH","The GitHub Actions job does not belong to the selected workflow run",n);if(s.status?.toLowerCase()!=="completed")throw new D("ACTIONS_JOB_NOT_COMPLETED","The GitHub Actions job must be completed before it can be retried",n);let o=await z(e,r=>L(`${i}/rerun`,{method:"POST",headers:j(`Bearer ${r}`)},S,e,t.requestSource),t.requestSource),l=M(o.response);if(401===o.response.status)throw new D("GITHUB_APP_UNAUTHORIZED","GitHub rejected the installation access token",l);if(!o.response.ok){let t=await q(o.response);throw new D(404===o.response.status?"ACTIONS_JOB_NOT_FOUND":"GITHUB_APP_REQUEST_FAILED",404===o.response.status?"The GitHub Actions job is not available to this installation":F(t,o.response.status,[o.token,e.privateKey]),l)}return{githubRequestId:l}}let ea=new Set(["FAILURE","ERROR","STARTUP_FAILURE","TIMED_OUT"]),en=new Set(["ACTION_REQUIRED","EXPECTED","IN_PROGRESS","PENDING","QUEUED"]),es=["COMPLETED","EXHAUSTED","STOPPED"],eo={WORKFLOW_RUN:4,PULL_REQUEST:3,WORKTREE_BRANCH:2,REPOSITORY:1},el="server:github-auto-retry";function eu(e){return e.toISOString()}function ec(e){return{...e,scope:e.scope,mode:e.mode,failureStrategy:e.failureStrategy,status:e.status,executions:e.executions.map(e=>({...e,lastStatus:e.lastStatus,updatedAt:eu(e.updatedAt)})),createdAt:eu(e.createdAt),updatedAt:eu(e.updatedAt)}}class ed{github;polling;timer;pollingTickRunning;rerunRequested;reconciling;constructor(e,t,r=!0){this.github=e,this.polling=t,this.timer=null,this.pollingTickRunning=!1,this.rerunRequested=!1,this.reconciling=!1,this.polling?.register({id:el,kind:"GITHUB_AUTO_RETRY",runtime:"SERVER",enabled:!0,cadenceSeconds:60,details:{}}),r&&queueMicrotask(()=>void this.pollReconcile())}schedule(e){this.timer&&clearTimeout(this.timer);let t=1e3*Math.max(30,e);this.timer=setTimeout(()=>void this.pollReconcile(),t),this.timer.unref(),this.polling?.schedule(el,new Date(Date.now()+t))}configurationChanged(){if(this.pollingTickRunning){this.rerunRequested=!0;return}this.timer&&clearTimeout(this.timer),this.timer=null,queueMicrotask(()=>void this.pollReconcile())}async pollReconcile(){if(this.pollingTickRunning)return;this.pollingTickRunning=!0;let e=60;try{let t=async()=>(e=(await (await (0,r.getPrismaClient)()).gitHubSettings.upsert({where:{id:"default"},create:{id:"default"},update:{}})).actionsNotificationPollIntervalSeconds,this.polling?.configure(el,{cadenceSeconds:e}),this.reconcile());this.polling?await this.polling.run(el,t,e=>({activeRules:e})):await t()}catch{}finally{this.pollingTickRunning=!1,this.rerunRequested?(this.rerunRequested=!1,queueMicrotask(()=>void this.pollReconcile())):this.schedule(e)}}include(){return{targets:{orderBy:{createdAt:"asc"}},executions:{orderBy:{updatedAt:"desc"}}}}async list(e){let t=await (0,r.getPrismaClient)(),i=e.codebaseRepositoryId?await this.github.autoRetryRepositoryId(e.codebaseRepositoryId):null;return(await t.gitHubAutoRetryRule.findMany({where:{...i?{codebaseRepositoryId:i}:{},...e.workflowRunId?{targets:{some:{workflowRunId:e.workflowRunId}}}:{}},include:this.include(),orderBy:{updatedAt:"desc"}})).map(ec)}validate(e){if(!e.codebaseRepositoryId.trim())throw Error("Codebase repository is required");if("COUNT"===e.mode&&null==e.retryLimit)throw Error("Count mode requires a retry limit");if(null!=e.retryLimit&&(!Number.isInteger(e.retryLimit)||e.retryLimit<1||e.retryLimit>100))throw Error("Retry limit must be an integer from 1 to 100");if("FAILURE"===e.mode&&void 0===e.retryLimit)throw Error("Failure retry limit must be a number or null");if("WORKFLOW_RUN"===e.scope){if(!e.targets.length||e.targets.some(e=>!e.workflowRunId))throw Error("Current-run rules require workflow run targets")}else if(!e.allWorkflows&&!e.targets.length)throw Error("Select at least one workflow or choose all workflows");if("WORKTREE_BRANCH"===e.scope&&!e.worktreeId)throw Error("Worktree future rules require a worktree");if("PULL_REQUEST"===e.scope&&!e.pullRequestNumber)throw Error("Pull request future rules require a pull request number")}async save(e){if(!await this.github.autoRetryCredentialsReady())throw Error("A GitHub token and verified GitHub App with Actions write access are required");e={...e,codebaseRepositoryId:await this.github.autoRetryRepositoryId(e.codebaseRepositoryId)},this.validate(e);let i=await (0,r.getPrismaClient)(),a=e.branch?.trim()||null;if("WORKTREE_BRANCH"===e.scope&&e.worktreeId){let t=await i.worktree.findUnique({where:{id:e.worktreeId},select:{branch:!0}});if(!(a=t?.branch??null))throw Error("The worktree does not have a branch")}let n=await i.gitHubAutoRetryRule.findMany({where:{id:e.id?{not:e.id}:void 0,enabled:!0,scope:e.scope,codebaseRepositoryId:e.codebaseRepositoryId},include:{targets:!0}}),s=new Set(e.targets.map(e=>e.workflowRunId).filter(e=>!!e));if(n.find(t=>"WORKFLOW_RUN"===e.scope?t.targets.some(e=>e.workflowRunId&&s.has(e.workflowRunId)):"WORKTREE_BRANCH"===e.scope?t.branch===a:"PULL_REQUEST"!==e.scope||t.pullRequestNumber===e.pullRequestNumber))throw Error("An enabled Auto Retry rule already exists for this scope");let o=e.id??(0,t.randomUUID)(),l=await i.$transaction(async r=>(await r.gitHubAutoRetryRule.upsert({where:{id:o},create:{id:o,scope:e.scope,codebaseRepositoryId:e.codebaseRepositoryId,repositoryGithubId:e.repositoryGithubId??null,worktreeId:e.worktreeId??null,branch:a,pullRequestNumber:e.pullRequestNumber??null,allWorkflows:e.allWorkflows,mode:e.mode,retryLimit:e.retryLimit??null,failureStrategy:e.failureStrategy,status:"ACTIVE",enabled:!0},update:{scope:e.scope,codebaseRepositoryId:e.codebaseRepositoryId,repositoryGithubId:e.repositoryGithubId??null,worktreeId:e.worktreeId??null,branch:a,pullRequestNumber:e.pullRequestNumber??null,allWorkflows:e.allWorkflows,mode:e.mode,retryLimit:e.retryLimit??null,failureStrategy:e.failureStrategy,status:"ACTIVE",enabled:!0,lastError:null,activatedAt:new Date}}),await r.gitHubAutoRetryTarget.deleteMany({where:{ruleId:o}}),e.targets.length&&await r.gitHubAutoRetryTarget.createMany({data:e.targets.map(e=>({id:(0,t.randomUUID)(),ruleId:o,workflowId:e.workflowId?.trim()||null,workflowRunId:e.workflowRunId?.trim()||null,jobName:e.jobName?.trim()||null}))}),await r.gitHubAutoRetryExecution.deleteMany({where:{ruleId:o}}),r.gitHubAutoRetryRule.findUniqueOrThrow({where:{id:o},include:this.include()})));return queueMicrotask(()=>void this.reconcile().catch(()=>void 0)),ec(l)}async setEnabled(e,t){let i=await (0,r.getPrismaClient)(),a=await i.$transaction(async r=>(t&&await r.gitHubAutoRetryExecution.updateMany({where:{ruleId:e,pendingFromAttempt:{not:null}},data:{pendingFromAttempt:null,observedAttempt:0,status:"WATCHING",lastError:null,finishedAt:null}}),r.gitHubAutoRetryRule.update({where:{id:e},data:{enabled:t,status:t?"ACTIVE":"PAUSED",lastError:null,...t?{activatedAt:new Date}:{}},include:this.include()})));return t&&queueMicrotask(()=>void this.reconcile().catch(()=>void 0)),ec(a)}async delete(e){return(await (await (0,r.getPrismaClient)()).gitHubAutoRetryRule.deleteMany({where:{id:e}})).count>0}matches(e,t,r=!1){if("WORKFLOW_RUN"!==e.scope){let i=en.has(t.status);if(!r&&!i&&Date.parse(t.createdAt)<e.activatedAt.getTime())return!1}return"WORKTREE_BRANCH"===e.scope?t.headBranch===e.branch:"PULL_REQUEST"!==e.scope||t.pullRequests.some(t=>t.number===e.pullRequestNumber)}async execution(e,i,a){return(await (0,r.getPrismaClient)()).gitHubAutoRetryExecution.upsert({where:{ruleId_workflowRunId_targetKey:{ruleId:e,workflowRunId:i.id,targetKey:a}},create:{id:(0,t.randomUUID)(),ruleId:e,workflowRunId:i.id,workflowId:i.workflowId,targetKey:a},update:{}})}targetKeys(e,t){if(e.allWorkflows)return["workflow"];let r=e.targets.filter(e=>e.workflowRunId===t.id||e.workflowId===t.workflowId);return r.some(e=>!e.jobName)||"FAILURE"===e.mode&&"ALL_JOBS"===e.failureStrategy?["workflow"]:r.flatMap(e=>e.jobName?[`job:${e.jobName}`]:[])}async finishExecution(e,t,i){await (await (0,r.getPrismaClient)()).gitHubAutoRetryExecution.update({where:{id:e},data:{status:i,observedAttempt:t.runAttempt,lastStatus:t.status,pendingFromAttempt:null,finishedAt:new Date,lastError:null}})}async trigger(e,t,i,a,n){let s=await (0,r.getPrismaClient)();await s.gitHubAutoRetryExecution.update({where:{id:t.id},data:{status:"RETRYING",pendingFromAttempt:i.runAttempt,observedAttempt:i.runAttempt,lastStatus:i.status,lastError:null}});try{await this.github.autoRetryRerun(e.codebaseRepositoryId,i.id,a,n,{actor:"auto-retry",ipAddress:null,autoRetryRuleId:e.id,autoRetryExecutionId:t.id}),await s.gitHubAutoRetryExecution.update({where:{id:t.id},data:{automaticRetries:{increment:1},lastError:null}})}catch(i){let r=i instanceof Error?i.message:String(i);await s.gitHubAutoRetryExecution.update({where:{id:t.id},data:{lastError:r}}),await s.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r}})}}async reconcileExecution(e,t,i,a){var n;let s,o=await this.execution(e.id,t,i);if(null!=o.pendingFromAttempt)if(t.runAttempt>o.pendingFromAttempt)await (await (0,r.getPrismaClient)()).gitHubAutoRetryExecution.update({where:{id:o.id},data:{pendingFromAttempt:null,status:"WATCHING",lastError:null}});else{if(Date.now()-o.updatedAt.getTime()<12e4)return!1;let t=await (0,r.getPrismaClient)(),i="GitHub did not report a new attempt after the rerun request; automatic retries are paused to prevent a duplicate rerun";return await t.$transaction(async t=>{await t.gitHubAutoRetryExecution.update({where:{id:o.id},data:{status:"ERROR",lastError:i}}),await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{enabled:!1,status:"PAUSED",lastError:i}})}),!1}if(o.observedAttempt===t.runAttempt&&null==o.pendingFromAttempt)return!1;let l=a?.status??t.status,u=(s=null!=(n={mode:e.mode,retryLimit:e.retryLimit,automaticRetries:o.automaticRetries,state:l}).retryLimit&&n.automaticRetries>=n.retryLimit,"COUNT"===n.mode?"SUCCESS"!==n.state?"STOP":s?"COMPLETE":"RETRY":"SUCCESS"===n.state?"COMPLETE":ea.has(n.state)?s?"EXHAUSTED":"RETRY":"STOP");return"COMPLETE"===u?(await this.finishExecution(o.id,t,"COMPLETED"),!1):"EXHAUSTED"===u?(await this.finishExecution(o.id,t,"EXHAUSTED"),!1):"STOP"===u?(await this.finishExecution(o.id,t,"STOPPED"),!1):("COUNT"===e.mode?await this.trigger(e,o,t,a?"JOB":"ALL_JOBS",a?.id??null):await this.trigger(e,o,t,a?"ALL_JOBS"===e.failureStrategy?"ALL_JOBS":"JOB":"ALL_JOBS"===e.failureStrategy?"ALL_JOBS":"FAILED_JOBS",a?.id??null),!0)}async reconcile(){if(this.reconciling)return 0;this.reconciling=!0;let e=0;try{let t=await (0,r.getPrismaClient)(),i=await t.gitHubAutoRetryRule.findMany({where:{enabled:!0,status:"ACTIVE"},include:{targets:!0},orderBy:{createdAt:"asc"}});e=i.length;let a=new Map,n=i.length?await t.gitHubAutoRetryExecution.findMany({where:{ruleId:{in:i.map(e=>e.id)},status:{notIn:es}},select:{ruleId:!0,workflowRunId:!0}}):[],s=new Map;for(let e of n){let t=s.get(e.ruleId)??new Set;t.add(e.workflowRunId),s.set(e.ruleId,t)}let o=new Map;for(let e of i){let r=a.get(e.codebaseRepositoryId);if(!r)try{r=await this.github.autoRetryRuns(e.codebaseRepositoryId),a.set(e.codebaseRepositoryId,r)}catch(r){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r instanceof Error?r.message:String(r)}});continue}let i=new Set(e.targets.map(e=>e.workflowRunId).filter(e=>!!e)),n=s.get(e.id)??new Set;for(let a of new Set([...i,...n]))if(!r.some(e=>e.id===a))try{r.push(await this.github.autoRetryRun(e.codebaseRepositoryId,a,!1))}catch(r){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r instanceof Error?r.message:String(r)}})}for(let t of r){if("WORKFLOW_RUN"===e.scope&&!i.has(t.id)||!this.matches(e,t,n.has(t.id))||!e.allWorkflows&&!e.targets.some(e=>e.workflowRunId===t.id||e.workflowId===t.workflowId))continue;let r=o.get(t.id);(!r||eo[e.scope]>eo[r.rule.scope])&&o.set(t.id,{rule:e,run:t})}}for(let{rule:e,run:r}of o.values()){let i=this.targetKeys(e,r);if(en.has(r.status)){await Promise.all(i.map(t=>this.execution(e.id,r,t)));continue}let a=r,n=e.allWorkflows?[{jobName:null}]:e.targets.filter(e=>e.workflowRunId===a.id||e.workflowId===a.workflowId);if(n.some(e=>!e.jobName)){await this.reconcileExecution(e,a,"workflow",null);continue}let s=await Promise.all(i.map(t=>this.execution(e.id,a,t)));if(!s.some(e=>e.observedAttempt!==a.runAttempt||null!=e.pendingFromAttempt&&a.runAttempt>e.pendingFromAttempt)){for(let t=0;t<s.length;t+=1)s[t]?.pendingFromAttempt!=null&&await this.reconcileExecution(e,a,i[t],null);continue}try{a=await this.github.autoRetryRun(e.codebaseRepositoryId,a.id)}catch(r){await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{lastError:r instanceof Error?r.message:String(r)}});continue}if("FAILURE"===e.mode&&"ALL_JOBS"===e.failureStrategy){let t=a.jobs.filter(e=>n.some(t=>t.jobName===e.name)),r=t.find(e=>ea.has(e.status))??t.find(e=>"SUCCESS"!==e.status)??t[0];r?await this.reconcileExecution(e,a,"workflow",r):s[0]&&await this.finishExecution(s[0].id,a,"STOPPED");continue}let o=new Map(i.map((e,t)=>[e,s[t]]));for(let t of n){let r=a.jobs.find(e=>e.name===t.jobName);if(!r){let e=o.get(`job:${t.jobName}`);e&&await this.finishExecution(e.id,a,"STOPPED");continue}if(await this.reconcileExecution(e,a,`job:${r.name}`,r))break}}for(let e of i.filter(e=>"WORKFLOW_RUN"===e.scope)){let r=await t.gitHubAutoRetryExecution.findMany({where:{ruleId:e.id},select:{status:!0}});r.length>0&&r.every(e=>es.includes(e.status))&&await t.gitHubAutoRetryRule.update({where:{id:e.id},data:{enabled:!1,status:r.some(e=>"EXHAUSTED"===e.status)?"EXHAUSTED":"COMPLETED"}})}}finally{this.reconciling=!1}return e}}e.i(805422);var ep=e.i(661983);let eh={LEGACY:0,GRAPHQL:1,REST:2,WEBHOOK:3,MUTATION:4},em=new Set(["CANCELLED","FAILURE","STALE","STARTUP_FAILURE","TIMED_OUT"]),ef=new Set(["ACTION_REQUIRED","IN_PROGRESS","PENDING","QUEUED"]),eg=new Set(["SUCCESS","NEUTRAL","SKIPPED"]);function ey(e,t=null){return e.some(e=>"ERROR"===e)?"ERROR":e.some(e=>em.has(e))?"FAILURE":e.some(e=>ef.has(e))?"PENDING":e.some(e=>"EXPECTED"===e)||"EXPECTED"===t?"EXPECTED":e.length>0&&e.every(e=>eg.has(e))?"SUCCESS":0===e.length&&t?t:"NONE"}function ew(e,t){let r=(t||e||"NONE").toUpperCase();return ek(r)?r:"REQUESTED"===r||"WAITING"===r?"QUEUED":"NONE"}function eb(e){return ef.has(e)?1:2*("NONE"!==e&&"EXPECTED"!==e)}function ev(e,t,r){let i=e.runAttempt??0,a=t.runAttempt??0;if(a!==i)return a>i;let n=e.githubUpdatedAt?.getTime()??0,s=t.githubUpdatedAt?.getTime()??0;if(s!==n)return s>n;if("MUTATION"===e.source&&e.optimisticUntil&&e.optimisticUntil.getTime()>r.getTime())return"MUTATION"===t.source;let o="MUTATION"===e.source?eh.LEGACY:eh[e.source],l=eh[t.source];if("MUTATION"!==e.source&&"MUTATION"!==t.source&&e.status&&t.status){let r=eb(e.status),i=eb(t.status);if(i!==r)return i>r}return l===o||l>o}function ek(e){return"ACTION_REQUIRED"===e||"CANCELLED"===e||"ERROR"===e||"EXPECTED"===e||"FAILURE"===e||"IN_PROGRESS"===e||"NEUTRAL"===e||"PENDING"===e||"QUEUED"===e||"SKIPPED"===e||"STALE"===e||"STARTUP_FAILURE"===e||"SUCCESS"===e||"TIMED_OUT"===e||"NONE"===e}function eS(e){return"ERROR"===e||"EXPECTED"===e||"FAILURE"===e||"PENDING"===e||"SUCCESS"===e||"NONE"===e}function eE(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function eI(e){return"NONE"===e||"EXPECTED"===e?0:"ACTION_REQUIRED"===e||"PENDING"===e||"QUEUED"===e?1:"IN_PROGRESS"===e?2:3}function ex(e){return"GRAPHQL"===e||"REST"===e||"WEBHOOK"===e||"MUTATION"===e?e:"LEGACY"}function eA(e){return{id:e.githubPipelineId,name:e.name,status:ek(e.status)?e.status:"NONE",url:e.url,checkSuiteId:e.checkSuiteId,canRetry:e.canRetry,retryUnavailableReason:e.retryUnavailableReason,jobs:eE(e.jobsJson),workflowRunId:e.workflowRunId,workflowId:e.workflowId,runNumber:e.runNumber,runAttempt:e.runAttempt}}function e_(e,t){return{...eA(t),repositoryGithubId:e.repositoryGithubId,headSha:e.headSha,revision:e.revision,isCurrent:t.isCurrent}}function eC(e){return{repositoryGithubId:e.repositoryGithubId,repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,headSha:e.headSha,pipelineStatus:eS(e.pipelineStatus)?e.pipelineStatus:"NONE",pipelines:e.records.filter(e=>e.isCurrent).map(eA).sort((e,t)=>e.name.localeCompare(t.name)),revision:e.revision,updatedAt:e.updatedAt.toISOString()}}function eR(e){return JSON.stringify({identityKey:e.identityKey,githubPipelineId:e.githubPipelineId,name:e.name,status:e.status,url:e.url,checkSuiteId:e.checkSuiteId,workflowRunId:e.workflowRunId,workflowId:e.workflowId,runNumber:e.runNumber,runAttempt:e.runAttempt,canRetry:e.canRetry,retryUnavailableReason:e.retryUnavailableReason,jobsJson:e.jobsJson,isCurrent:e.isCurrent})}function eT(e){return JSON.stringify({repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,pipelineStatus:e.pipelineStatus,records:e.records.map(eR).sort((e,t)=>e.localeCompare(t))})}class eD{lastPrunedAt=0;async snapshot(e){let t=await (0,r.getPrismaClient)(),i=await t.gitHubPipelineSnapshot.findUnique({where:{repositoryGithubId_headSha:{repositoryGithubId:e.repositoryGithubId.trim(),headSha:e.headSha.trim()}},include:{records:!0}});return i?eC(i):null}async snapshots(e){let t=e.map(e=>({repositoryGithubId:e.repositoryGithubId.trim(),headSha:e.headSha.trim()})).filter(e=>e.repositoryGithubId&&e.headSha);if(0===t.length)return[];let i=await (0,r.getPrismaClient)();return(await i.gitHubPipelineSnapshot.findMany({where:{OR:t},include:{records:!0}})).map(eC)}async records(e){let t=e.map(e=>({repositoryGithubId:e.repositoryGithubId.trim(),workflowRunId:e.workflowRunId.trim()})).filter(e=>e.repositoryGithubId&&e.workflowRunId);if(0===t.length)return[];let i=await (0,r.getPrismaClient)();return(await i.gitHubPipelineRecord.findMany({where:{OR:t.map(e=>({workflowRunId:e.workflowRunId,snapshot:{repositoryGithubId:e.repositoryGithubId}}))},include:{snapshot:{include:{records:!0}}}})).map(e=>e_(e.snapshot,e))}async observeWorkflowRuns(e,t="REST",r=!0){let i=new Map;for(let t of e){if(!t.repositoryGithubId||!t.headSha)continue;let e=`${t.repositoryGithubId}\u0000${t.headSha}`,r=i.get(e)??[];r.push(t),i.set(e,r)}let a=new Map;for(let e of i.values()){let i=e[0];await this.observeSnapshot({repositoryGithubId:i.repositoryGithubId,repositoryNameWithOwner:i.repositoryNameWithOwner,repositoryUrl:i.repositoryUrl,headSha:i.headSha,pipelines:e.map(e=>(function(e,t,r=!0){return{id:e.id,name:e.name,status:e.status,url:e.url,checkSuiteId:e.checkSuiteId,workflowRunId:e.id,workflowId:e.workflowId,runNumber:e.runNumber,runAttempt:e.runAttempt,canRetry:e.canRetry,retryUnavailableReason:e.retryUnavailableReason,source:t,githubUpdatedAt:new Date(e.updatedAt),sourceFetchedAt:new Date,isCurrent:r}})(e,t,r))})}for(let t of(await this.records(e.map(e=>({repositoryGithubId:e.repositoryGithubId,workflowRunId:e.id})))))t.workflowRunId&&a.set(t.workflowRunId,t);return a}async observeJobs(e,t,i,a="REST",n=null){let s=await (0,r.getPrismaClient)(),o=await s.gitHubPipelineRecord.findFirst({where:{workflowRunId:t,...e?{snapshot:{repositoryGithubId:e}}:{}},include:{snapshot:!0},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!o)return null;let l=i.filter(e=>null==e.runAttempt||null==o.runAttempt||e.runAttempt===o.runAttempt);if(i.length>0&&0===l.length)return e_({...o.snapshot,records:[o]},o);let u=eE(o.jobsJson),c=new Map(u.map(e=>[e.id,e])),d=l.map(e=>(function(e,t){if(!e)return t;let r=e.runAttempt??0,i=t.runAttempt??0;if(i!==r)return i>r?t:e;let a=eI(e.status),n=eI(t.status);return n<a?e:n===a&&t.steps.length<e.steps.length?{...t,steps:e.steps}:t})(c.get(e.id),e)),p="WEBHOOK"===a?[...new Map([...u,...d].map(e=>[e.id,e])).values()]:d,h=ek(o.status)?o.status:"NONE",m="REST"===a&&l.length>0?ey(l.map(e=>e.status),null):"NONE",f=("ERROR"===m||"FAILURE"===m||"SUCCESS"===m)&&o.snapshot.graphqlRollupStatus===m?m:h;return(await this.observeSnapshot({repositoryGithubId:o.snapshot.repositoryGithubId,repositoryNameWithOwner:o.snapshot.repositoryNameWithOwner,repositoryUrl:o.snapshot.repositoryUrl,headSha:o.snapshot.headSha,pipelines:[{...eA(o),status:f,source:a,jobs:p,githubUpdatedAt:n??o.githubUpdatedAt,isCurrent:o.isCurrent}]})).changedPipeline}async optimisticByCheckSuite(e,t,r){return this.optimisticRecord({repositoryGithubId:e,checkSuiteId:t,workflowRunId:null},r)}async optimisticByWorkflowRun(e,t,r){return this.optimisticRecord({repositoryGithubId:e,checkSuiteId:null,workflowRunId:t},r)}async optimisticJobByCheckSuite(e,t,i){let a=await (0,r.getPrismaClient)(),n=await a.gitHubPipelineRecord.findFirst({where:{checkSuiteId:t,snapshot:{repositoryGithubId:e}},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!n)return null;let s=eE(n.jobsJson).map(e=>e.id===i?{...e,status:"QUEUED",canRetry:!1,retryUnavailableReason:"NOT_COMPLETED"}:e);return this.optimisticByCheckSuite(e,t,{status:"QUEUED",jobs:s})}async optimisticJobByWorkflowRun(e,t,i){let a=await (0,r.getPrismaClient)(),n=await a.gitHubPipelineRecord.findFirst({where:{workflowRunId:t,...e?{snapshot:{repositoryGithubId:e}}:{}},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!n)return null;let s=eE(n.jobsJson).map(e=>e.id===i?{...e,status:"QUEUED",canRetry:!1,retryUnavailableReason:"NOT_COMPLETED"}:e);return this.optimisticByWorkflowRun(e,t,{status:"QUEUED",jobs:s})}async optimisticRecord(e,t){let i=await (0,r.getPrismaClient)(),a=await i.gitHubPipelineRecord.findFirst({where:{...e.repositoryGithubId?{snapshot:{repositoryGithubId:e.repositoryGithubId}}:{},...e.checkSuiteId?{checkSuiteId:e.checkSuiteId}:{workflowRunId:e.workflowRunId}},include:{snapshot:!0},orderBy:[{runAttempt:"desc"},{sourceFetchedAt:"desc"}]});if(!a)return null;let n=new Date;return(await this.observeSnapshot({repositoryGithubId:a.snapshot.repositoryGithubId,repositoryNameWithOwner:a.snapshot.repositoryNameWithOwner,repositoryUrl:a.snapshot.repositoryUrl,headSha:a.snapshot.headSha,pipelines:[{...eA(a),status:t.status,jobs:t.jobs,canRetry:!1,retryUnavailableReason:"NOT_COMPLETED",source:"MUTATION",githubUpdatedAt:a.githubUpdatedAt,sourceFetchedAt:n,optimisticUntil:new Date(n.getTime()+12e4),isCurrent:a.isCurrent}]})).changedPipeline}async observeSnapshot(e){let i=e.repositoryGithubId.trim(),a=e.headSha.trim();if(!i||!a)throw Error("GitHub repository ID and head SHA are required");let n=new Date,s=e.sourceFetchedAt??n,o=await (0,r.getPrismaClient)(),l=await o.$transaction(async r=>{let o=await r.gitHubPipelineSnapshot.upsert({where:{repositoryGithubId_headSha:{repositoryGithubId:i,headSha:a}},create:{id:(0,t.randomUUID)(),repositoryGithubId:i,repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,headSha:a,pipelineStatus:"NONE",graphqlRollupStatus:null,revision:0,lastGraphqlSyncAt:null,lastObservedAt:n},update:{lastObservedAt:n},include:{records:!0}}),l=eT(o),u=!!(e.completeGraphqlRollup&&(!o.lastGraphqlSyncAt||s.getTime()>=o.lastGraphqlSyncAt.getTime())),c=new Set,d=null;for(let i of e.pipelines){let e=function(e){var t;return(t={id:e.id,checkSuiteId:e.checkSuiteId,workflowRunId:e.workflowRunId,statusContext:e.statusContext}).checkSuiteId?`CHECK_SUITE:${t.checkSuiteId}`:t.workflowRunId?`WORKFLOW_RUN:${t.workflowRunId}`:t.statusContext?`STATUS_CONTEXT:${t.statusContext}`:`PIPELINE:${t.id}`}(i),a=(await r.gitHubPipelineRecord.findMany({where:{snapshotId:o.id}})).filter(t=>t.identityKey===e||i.checkSuiteId&&t.checkSuiteId===i.checkSuiteId||i.workflowRunId&&t.workflowRunId===i.workflowRunId),l=a[0]??null;for(let e of a.slice(1))l&&ev({runAttempt:l.runAttempt,githubUpdatedAt:l.githubUpdatedAt,source:ex(l.source),optimisticUntil:l.optimisticUntil,status:ek(l.status)?l.status:"NONE"},{runAttempt:e.runAttempt,githubUpdatedAt:e.githubUpdatedAt,source:ex(e.source),status:ek(e.status)?e.status:"NONE"},n)&&(l=e);for(let e of a)l&&e.id!==l.id&&(0===eE(l.jobsJson).length&&eE(e.jobsJson).length>0&&(l=await r.gitHubPipelineRecord.update({where:{id:l.id},data:{jobsJson:e.jobsJson}})),await r.gitHubPipelineRecord.delete({where:{id:e.id}}),d=l.id);let p=i.sourceFetchedAt??s,h=i.githubUpdatedAt??null,m=void 0===i.runAttempt?l?.runAttempt??null:i.runAttempt,f=void 0!==i.jobs?JSON.stringify(i.jobs):l&&(m??0)<=(l.runAttempt??0)?l.jobsJson:"[]",g=!!u||(!1===i.isCurrent?l?.isCurrent??!1:i.isCurrent??l?.isCurrent??!0);if(l){c.add(l.id);let t=eR(l),a=ev({runAttempt:l.runAttempt,githubUpdatedAt:l.githubUpdatedAt,source:ex(l.source),optimisticUntil:l.optimisticUntil,status:ek(l.status)?l.status:"NONE"},{runAttempt:m,githubUpdatedAt:h,source:i.source,status:i.status},n),s=!!(!a&&"MUTATION"===l.source&&l.optimisticUntil&&l.optimisticUntil.getTime()>n.getTime()&&"MUTATION"!==i.source);t!==eR(l=await r.gitHubPipelineRecord.update({where:{id:l.id},data:a?{identityKey:e,githubPipelineId:i.id,name:i.name,status:i.status,url:void 0===i.url?l.url:i.url,checkSuiteId:void 0===i.checkSuiteId?l.checkSuiteId:i.checkSuiteId,workflowRunId:void 0===i.workflowRunId?l.workflowRunId:i.workflowRunId,workflowId:void 0===i.workflowId?l.workflowId:i.workflowId,runNumber:void 0===i.runNumber?l.runNumber:i.runNumber,runAttempt:m,canRetry:void 0===i.canRetry?l.canRetry:i.canRetry,retryUnavailableReason:void 0===i.retryUnavailableReason?l.retryUnavailableReason:i.retryUnavailableReason,jobsJson:f,source:i.source,githubUpdatedAt:h,sourceFetchedAt:p,lastObservedAt:n,optimisticUntil:void 0===i.optimisticUntil?l.optimisticUntil:i.optimisticUntil,isCurrent:g}:{lastObservedAt:n,...void 0!==i.jobs&&!s?{jobsJson:f}:{},...u?{isCurrent:!0}:{}}}))&&(d=l.id)}else d=(l=await r.gitHubPipelineRecord.create({data:{id:(0,t.randomUUID)(),snapshotId:o.id,identityKey:e,githubPipelineId:i.id,name:i.name,status:i.status,url:i.url??null,checkSuiteId:i.checkSuiteId??null,workflowRunId:i.workflowRunId??null,workflowId:i.workflowId??null,runNumber:i.runNumber??null,runAttempt:m,canRetry:i.canRetry??!1,retryUnavailableReason:i.retryUnavailableReason??null,jobsJson:f,source:i.source,githubUpdatedAt:h,sourceFetchedAt:p,lastObservedAt:n,optimisticUntil:i.optimisticUntil??null,isCurrent:g}})).id;c.add(l.id)}if(u)for(let e of(await r.gitHubPipelineRecord.findMany({where:{snapshotId:o.id,isCurrent:!0}})))!c.has(e.id)&&e.sourceFetchedAt.getTime()<=s.getTime()&&(!e.optimisticUntil||e.optimisticUntil.getTime()<=n.getTime())&&(await r.gitHubPipelineRecord.update({where:{id:e.id},data:{isCurrent:!1}}),d??=e.id);let p=await r.gitHubPipelineRecord.findMany({where:{snapshotId:o.id}}),h=u?e.graphqlRollupStatus??null:o.graphqlRollupStatus,m=ey(p.filter(e=>e.isCurrent).map(e=>ek(e.status)?e.status:"NONE"),h&&eS(h)?h:null),f=l!==eT(o=await r.gitHubPipelineSnapshot.update({where:{id:o.id},data:{repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,pipelineStatus:m,graphqlRollupStatus:h,lastGraphqlSyncAt:u?s:o.lastGraphqlSyncAt,lastObservedAt:n},include:{records:!0}}))||null!==d;f&&(o=await r.gitHubPipelineSnapshot.update({where:{id:o.id},data:{revision:{increment:1}},include:{records:!0}}));let g=o,y=d?g.records.find(e=>e.id===d)??null:null;return{changed:f,change:{snapshot:eC(g),changedPipeline:y?e_(g,y):null}}});return l.changed&&ep.agentEventBus.publish(ep.GITHUB_PIPELINE_STATUS_CHANGED_TOPIC,{githubPipelineStatusChanged:l.change}),this.pruneIfNeeded().catch(()=>void 0),l.change}subscribe(){return ep.agentEventBus.iterate(ep.GITHUB_PIPELINE_STATUS_CHANGED_TOPIC)}async pruneIfNeeded(){let e=Date.now();if(e-this.lastPrunedAt<864e5)return;this.lastPrunedAt=e;let t=await (0,r.getPrismaClient)();await t.gitHubPipelineSnapshot.deleteMany({where:{lastObservedAt:{lt:new Date(e-2592e6)}}})}}e.s(["GitHubPipelineStatusService",0,eD],963910);let eN=/^[_A-Za-z][_0-9A-Za-z]*$/,eO=new Map([["GitHubWorktreePullRequestStatuses",60]]),eP=[{window:"5m",milliseconds:3e5},{window:"10m",milliseconds:6e5},{window:"1h",milliseconds:36e5},{window:"24h",milliseconds:864e5}];function e$(e){return JSON.stringify(function e(t){return Array.isArray(t)?t.map(e):t&&"object"==typeof t?Object.fromEntries(Object.keys(t).sort().map(r=>[r,e(t[r])])):t}(e))}let eU=/(?:authorization|password|private.?key|secret|token)$/i;function eB(e,t=""){return eU.test(t)?"[REDACTED]":Array.isArray(e)?e.map(e=>eB(e)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,eB(t,e)])):e}function ej(e){try{return JSON.parse(e)}catch{return null}}function eL(e){return e&&"object"==typeof e?{statusCode:"number"==typeof e.statusCode?e.statusCode:null,rateLimit:e.rateLimit&&"object"==typeof e.rateLimit?e.rateLimit:null}:{statusCode:null,rateLimit:null}}class eq{recordCallLogs;inFlight;cacheWrites;cacheGeneration;lastPrunedAt;constructor(e="true"!==process.env.GITHUB_CACHE_LOGGING_DISABLED){this.recordCallLogs=e,this.inFlight=new Map,this.cacheWrites=new Set,this.cacheGeneration=0,this.lastPrunedAt=0}cacheKey(e){return(0,t.createHash)("sha256").update(e$({authentication:e.authentication,endpoint:e.endpoint,query:e.normalizedQuery,variables:e.variables})).digest("hex")}inFlightKey(e,t,r){return[r,e,!0===t.force?"force":"normal",!1===t.allowStaleOnError?"strict":"stale"].join(":")}async defaultTtlSeconds(){let e=await (0,r.getPrismaClient)();return(await e.gitHubSettings.upsert({where:{id:"default"},create:{id:"default",cacheTtlSeconds:300},update:{}})).cacheTtlSeconds}async effectiveTtlSeconds(e){let t=await (0,r.getPrismaClient)(),[i,a]=await Promise.all([t.gitHubGraphqlCacheTtlOverride.findUnique({where:{operation:e}}),this.defaultTtlSeconds()]);return i?.ttlSeconds??a}async query(e){let i=this.cacheGeneration,a=await (0,r.getPrismaClient)(),n=this.cacheKey(e),s=this.inFlightKey(n,e,i),o=Date.now(),[l,u,c]=await Promise.all([a.gitHubGraphqlCacheEntry.findUnique({where:{cacheKey:n}}),this.effectiveTtlSeconds(e.operation),a.gitHubRateLimitSnapshot.findUnique({where:{authentication_resource:{authentication:e.authentication,resource:"graphql"}}})]);if(i!==this.cacheGeneration)return this.query(e);let d=null!==l&&Date.now()-l.fetchedAt.getTime()<1e3*u;if(!e.force&&d)return(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"CACHE",durationMs:Date.now()-o,pointCost:0,pointsAvoided:l.pointCost??0}).catch(()=>void 0),i!==this.cacheGeneration)?this.query(e):{data:ej(l.responseJson),source:"CACHE",stale:!1,fetchedAt:l.fetchedAt,entryId:l.id,pointCost:l.pointCost};let p=this.inFlight.get(s);if(p){let t=await p;return i!==this.cacheGeneration||(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"CACHE",durationMs:Date.now()-o,pointCost:0,pointsAvoided:t.pointCost??0}).catch(()=>void 0),i!==this.cacheGeneration)?this.query(e):{...t,source:"CACHE"}}if(c?.remaining===0&&c.resetAt.getTime()>Date.now()){let t=`GitHub GraphQL rate limit is exhausted until ${c.resetAt.toISOString()}`,r=null!==l&&!1!==e.allowStaleOnError;if(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-o,error:t,servedStale:r,pointCost:0,pointsAvoided:r?l.pointCost??0:0,rateLimit:{limit:c.limit,remaining:c.remaining,used:c.used,resetAt:c.resetAt,resource:c.resource}}).catch(()=>void 0),i!==this.cacheGeneration)return this.query(e);if(r)return{data:ej(l.responseJson),source:"ERROR",stale:!0,fetchedAt:l.fetchedAt,entryId:l.id,pointCost:l.pointCost};throw Error(t)}let h=(async()=>{try{let r=await e.fetcher(),s=new Date,l=null;if(i===this.cacheGeneration){let i=a.gitHubGraphqlCacheEntry.upsert({where:{cacheKey:n},create:{id:(0,t.randomUUID)(),cacheKey:n,authentication:e.authentication,endpoint:e.endpoint,operation:e.operation,query:e.query,variablesJson:e$(e.variables),responseJson:JSON.stringify(r.data),fetchedAt:s,pointCost:r.pointCost},update:{operation:e.operation,query:e.query,variablesJson:e$(e.variables),responseJson:JSON.stringify(r.data),fetchedAt:s,pointCost:r.pointCost}});this.cacheWrites.add(i);try{l=await i}finally{this.cacheWrites.delete(i)}}return await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"LIVE",durationMs:Date.now()-o,statusCode:r.statusCode,pointCost:r.pointCost,rateLimit:r.rateLimit}).catch(()=>void 0),{data:r.data,source:"LIVE",stale:!1,fetchedAt:s,entryId:i===this.cacheGeneration?l?.id??null:null,pointCost:r.pointCost}}catch(a){let t=eL(a),r=i===this.cacheGeneration&&null!==l&&!1!==e.allowStaleOnError;if(await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-o,statusCode:t.statusCode,error:a instanceof Error?a.message:String(a),servedStale:r,pointsAvoided:r?l?.pointCost??0:0,rateLimit:t.rateLimit}).catch(()=>void 0),i!==this.cacheGeneration)throw a;if(r)return{data:ej(l.responseJson),source:"ERROR",stale:!0,fetchedAt:l.fetchedAt,entryId:l.id,pointCost:l.pointCost};throw a}})();this.inFlight.set(s,h);try{return await h}finally{this.inFlight.get(s)===h&&this.inFlight.delete(s)}}async mutation(e){let t,r=Date.now();try{t=await e.fetcher()}catch(i){let t=eL(i);throw await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"ERROR",durationMs:Date.now()-r,statusCode:t.statusCode,error:i instanceof Error?i.message:String(i),rateLimit:t.rateLimit}).catch(()=>void 0),i}return await this.clear(),await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,source:"LIVE",durationMs:Date.now()-r,statusCode:t.statusCode,pointCost:null,rateLimit:t.rateLimit}).catch(()=>void 0),t.data}async updateTtl(e,t){if(!Number.isInteger(e)||e<1||e>1440)throw Error("Cache TTL must be an integer from 1 to 1440 minutes");let i=await (0,r.getPrismaClient)();return await i.gitHubSettings.upsert({where:{id:"default"},create:{id:"default",cacheTtlSeconds:60*e},update:{cacheTtlSeconds:60*e}}),t()}async ttlOverrides(){let e=await (0,r.getPrismaClient)();return(await e.gitHubGraphqlCacheTtlOverride.findMany({orderBy:{operation:"asc"}})).map(e=>({operation:e.operation,ttlSeconds:e.ttlSeconds,builtIn:eO.has(e.operation),createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))}async cacheableOperations(){let e=await (0,r.getPrismaClient)(),[t,i]=await Promise.all([e.gitHubGraphqlCacheTtlOverride.findMany({select:{operation:!0}}),e.gitHubGraphqlCacheEntry.findMany({distinct:["operation"],select:{operation:!0}})]);return[...new Set([...eO.keys(),...t.map(({operation:e})=>e),...i.map(({operation:e})=>e)])].sort((e,t)=>e.localeCompare(t))}async saveTtlOverride(e,t){let i=e.trim();if(!eN.test(i))throw Error("Operation must be a valid GraphQL operation name");if(!Number.isInteger(t)||t<1||t>86400)throw Error("Cache TTL must be an integer from 1 to 86400 seconds");let a=await (0,r.getPrismaClient)(),n=await a.gitHubGraphqlCacheTtlOverride.upsert({where:{operation:i},create:{operation:i,ttlSeconds:t},update:{ttlSeconds:t}});return{operation:n.operation,ttlSeconds:n.ttlSeconds,builtIn:eO.has(n.operation),createdAt:n.createdAt.toISOString(),updatedAt:n.updatedAt.toISOString()}}async deleteTtlOverride(e){let t=e.trim();if(eO.has(t))throw Error("Built-in cache TTL overrides cannot be deleted");let i=await (0,r.getPrismaClient)();return(await i.gitHubGraphqlCacheTtlOverride.deleteMany({where:{operation:t}})).count>0}async recordRestCall(e){let t=e.endpoint,r={};try{let i=new URL(e.endpoint);t=i.pathname,r={path:i.pathname,query:Object.fromEntries(i.searchParams)}}catch{r={endpoint:e.endpoint}}await this.log({authentication:e.authentication,apiType:"REST",method:e.method.toUpperCase(),endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:`${e.method.toUpperCase()} ${t}`,variables:r,source:e.error?"ERROR":"LIVE",durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,pointCost:1,rateLimit:e.rateLimit})}async recordGraphqlTransportCall(e){await this.log({...this.graphqlContext(e),authentication:e.authentication,operation:e.operation,requestSource:e.requestSource,source:e.error?"ERROR":"LIVE",durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,rateLimit:e.rateLimit})}async clear(){let{cacheWrites:e}=this.beginInvalidation();await Promise.allSettled(e);let t=await (0,r.getPrismaClient)();return await t.gitHubGraphqlCacheEntry.deleteMany(),!0}async clearForCredentialChange(e){let{cacheWrites:t,inFlight:i}=this.beginInvalidation();await Promise.allSettled(t);let a=await (0,r.getPrismaClient)();return await a.gitHubGraphqlCacheEntry.deleteMany(),await Promise.allSettled(i),await a.gitHubRateLimitSnapshot.deleteMany({where:{authentication:e}}),!0}async clearCalls(){let e=await (0,r.getPrismaClient)();return await e.gitHubApiCallLog.deleteMany(),!0}async delete(e){let t=await (0,r.getPrismaClient)();return(await t.gitHubGraphqlCacheEntry.deleteMany({where:{id:e}})).count>0}async entries(e=50,t=0){let i=this.pagination(e,t),a=await (0,r.getPrismaClient)(),[n,s,o,l]=await Promise.all([a.gitHubGraphqlCacheEntry.findMany({take:i.limit,skip:i.offset,orderBy:{fetchedAt:"desc"}}),a.gitHubGraphqlCacheEntry.count(),this.defaultTtlSeconds(),a.gitHubGraphqlCacheTtlOverride.findMany({select:{operation:!0,ttlSeconds:!0}})]),u=new Map(l.map(({operation:e,ttlSeconds:t})=>[e,t]));return{...i,total:s,items:n.map(e=>this.entryView(e,u.get(e.operation)??o))}}async entry(e){let t=await (0,r.getPrismaClient)(),i=await t.gitHubGraphqlCacheEntry.findUnique({where:{id:e}});if(!i)return null;let a=await this.effectiveTtlSeconds(i.operation);return{...this.entryView(i,a),query:i.query,variables:ej(i.variablesJson),response:ej(i.responseJson)}}async calls(e=50,t=0,i={}){let a=this.pagination(e,t);await this.pruneLogs();let n=await (0,r.getPrismaClient)(),s={...i.apiType?{apiType:i.apiType}:{},...i.requestSource?{requestSource:i.requestSource}:{},...i.source?{source:i.source}:{}},[o,l]=await Promise.all([n.gitHubApiCallLog.findMany({where:s,take:a.limit,skip:a.offset,orderBy:{createdAt:"desc"}}),n.gitHubApiCallLog.count({where:s})]);return{...a,total:l,items:o.map(e=>({id:e.id,authentication:e.authentication,apiType:e.apiType,method:e.method,endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:e.requestSummary,variables:ej(e.variablesJson),source:e.source,durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,servedStale:e.servedStale,pointCost:e.pointCost,pointsAvoided:e.pointsAvoided,rateLimitLimit:e.rateLimitLimit,rateLimitRemaining:e.rateLimitRemaining,rateLimitUsed:e.rateLimitUsed,rateLimitResetAt:e.rateLimitResetAt?.toISOString()??null,rateLimitResource:e.rateLimitResource,createdAt:e.createdAt.toISOString()}))}}async metrics(){await this.pruneLogs();let e=await (0,r.getPrismaClient)(),t=Date.now(),i=await e.gitHubApiCallLog.findMany({where:{createdAt:{gte:new Date(t-eP.at(-1).milliseconds)}},orderBy:{createdAt:"asc"}}),a=eP.map(e=>this.metricWindow(e.window,i.filter(r=>r.createdAt.getTime()>=t-e.milliseconds)));return{windows:a,apiTypes:["GRAPHQL","REST"].map(e=>({apiType:e,windows:eP.map(r=>this.metricWindow(r.window,i.filter(i=>i.apiType===e&&i.createdAt.getTime()>=t-r.milliseconds)))})),operations:[...new Set(i.map(e=>e.operation))].sort().map(e=>({operation:e,windows:eP.map(r=>this.metricWindow(r.window,i.filter(i=>i.operation===e&&i.createdAt.getTime()>=t-r.milliseconds)))})),requestSources:[...new Set(i.map(e=>e.requestSource))].sort().map(e=>({requestSource:e,windows:eP.map(r=>this.metricWindow(r.window,i.filter(i=>i.requestSource===e&&i.createdAt.getTime()>=t-r.milliseconds)))}))}}entryView(e,t){return{id:e.id,authentication:e.authentication,operation:e.operation,endpoint:e.endpoint,fetchedAt:e.fetchedAt.toISOString(),pointCost:e.pointCost,stale:Date.now()-e.fetchedAt.getTime()>=1e3*t}}metricWindow(e,t){let r=t.length;return{window:e,total:r,live:t.filter(e=>"LIVE"===e.source).length,cache:t.filter(e=>"CACHE"===e.source).length,errors:t.filter(e=>"ERROR"===e.source).length,averageMs:0===r?0:Math.round(t.reduce((e,t)=>e+t.durationMs,0)/r),pointsUsed:t.reduce((e,t)=>e+Math.max(0,t.pointCost??0),0),pointsAvoided:t.reduce((e,t)=>e+Math.max(0,t.pointsAvoided),0)}}pagination(e,t){if(!Number.isInteger(e)||e<1||e>100)throw Error("limit must be an integer from 1 to 100");if(!Number.isInteger(t)||t<0)throw Error("offset must be a non-negative integer");return{limit:e,offset:t}}beginInvalidation(){let e=[...this.cacheWrites],t=[...new Set(this.inFlight.values())];return this.cacheGeneration+=1,this.inFlight.clear(),{cacheWrites:e,inFlight:t}}graphqlContext(e){let t=eB(e.variables);return{apiType:"GRAPHQL",method:"POST",endpoint:e.endpoint,requestSource:e.requestSource,requestSummary:function(e){if(!e||"object"!=typeof e||Array.isArray(e))return"No variables";let t=Object.entries(e);return t.length?t.map(([e,t])=>{let r=("string"==typeof t?t:JSON.stringify(t))??String(t);return`${e}=${r.length>120?`${r.slice(0,117)}…`:r}`}).join(" · "):"No variables"}(t),variables:t}}async log(e){if(!this.recordCallLogs)return;await this.pruneLogs();let i=await (0,r.getPrismaClient)();await i.gitHubApiCallLog.create({data:{id:(0,t.randomUUID)(),authentication:e.authentication,apiType:e.apiType,method:e.method,endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:e.requestSummary,variablesJson:e$(eB(e.variables)),source:e.source,durationMs:Math.max(0,Math.round(e.durationMs)),statusCode:e.statusCode??null,error:e.error?.slice(0,2e3)??null,servedStale:e.servedStale??!1,pointCost:e.pointCost??null,pointsAvoided:Math.max(0,e.pointsAvoided??0),rateLimitLimit:e.rateLimit?.limit??null,rateLimitRemaining:e.rateLimit?.remaining??null,rateLimitUsed:e.rateLimit?.used??null,rateLimitResetAt:e.rateLimit?.resetAt??null,rateLimitResource:e.rateLimit?.resource??null}})}async pruneLogs(){let e=Date.now();if(e-this.lastPrunedAt<36e5)return;this.lastPrunedAt=e;let t=await (0,r.getPrismaClient)();await t.gitHubApiCallLog.deleteMany({where:{createdAt:{lt:new Date(e-2592e6)}}})}}let eM=(process.env.GITHUB_API_BASE_URL||"https://api.github.com").replace(/\/+$/,""),eF=process.env.GITHUB_GRAPHQL_URL||`${eM}/graphql`;var eK=e.i(995702),eV=e.i(151112),eG=e.i(312851);let eH="_adeRateLimit";function eW(e){let t=(0,eV.parse)(e),r=t.definitions.filter(e=>e.kind===eK.Kind.OPERATION_DEFINITION);if(1!==r.length||!r[0])throw Error("GitHub GraphQL requests must contain one operation");let i=r[0],a=i.name?.value??("mutation"===i.operation?"AnonymousMutation":"AnonymousQuery"),n=(0,eG.print)(t);if("query"!==i.operation)return{kind:"mutation",operation:a,normalizedQuery:n,liveQuery:n};let s={...t,definitions:t.definitions.map(e=>e===i?{...i,selectionSet:{...i.selectionSet,selections:[...i.selectionSet.selections,{kind:eK.Kind.FIELD,alias:{kind:eK.Kind.NAME,value:eH},name:{kind:eK.Kind.NAME,value:"rateLimit"},arguments:[],directives:[],selectionSet:{kind:eK.Kind.SELECTION_SET,selections:[{kind:eK.Kind.FIELD,name:{kind:eK.Kind.NAME,value:"cost"},arguments:[],directives:[]}]}}]}}:e)};return{kind:"query",operation:a,normalizedQuery:n,liveQuery:(0,eG.print)(s)}}function eJ(e){if(!e||"object"!=typeof e||Array.isArray(e))return{data:e,pointCost:null};let t=e[eH],r=t&&"object"==typeof t&&!Array.isArray(t)&&Number.isSafeInteger(t.cost)?t.cost:null;if(!(eH in e))return{data:e,pointCost:r};let i={...e};return delete i[eH],{data:i,pointCost:r}}let ez="default",eZ="default",eY=String.raw`\b([A-Z][A-Z0-9_]*-\d+)\b`,eQ=["workflow_run","workflow_job","check_run","check_suite","status"];function eX(e){return"read"===e||"write"===e}function e0(e){let t=[];for(let r of(e.webhookConfigured||t.push("configure the signed webhook URL"),eX(e.actionsPermission)||t.push("grant Actions read permission"),eX(e.checksPermission)||t.push("grant Checks read permission"),eX(e.commitStatusesPermission)||t.push("grant Commit statuses read permission"),eQ))e.webhookEvents.includes(r)||t.push(`subscribe to the ${r} event`);return t}function e1(e){return"auto-retry"===e.actor?"AUTO_RETRY":"workflow"===e.actor?"WORKFLOW_AUTOMATION":"ACTIONS_PAGE"}class e2 extends Error{statusCode;rateLimit;constructor(e,t,r){super(e),this.statusCode=t,this.rateLimit=r,this.name="GitHubRequestError"}}let e3=`
26
26
  __typename
27
27
  ... on CheckRun {
28
28
  id
@@ -613,7 +613,7 @@ ${i}
613
613
  ${i}
614
614
  ~~~`}},sE=class{constructor(){(0,tG.__publicField)(this,"nodeType","blockquote")}toMarkdown(e,t){if(!e.content||0===e.content.length)return"> ";let r=e.content.map(r=>{let i=t.options.registry?.getNodeConverter(r.type);return i?i.toMarkdown(r,{...t,depth:t.depth+1,parent:e}):""}).join("\n").split("\n").map(e=>""===e.trim()?">":`> ${e}`);if(e.attrs&&Object.keys(e.attrs).length>0){let t=r.join("\n");return`${t}<!-- adf:blockquote attrs='${JSON.stringify(e.attrs)}' -->`}return r.join("\n")}},sI=class{constructor(){(0,tG.__publicField)(this,"nodeType","rule")}toMarkdown(e,t){return"---"}},sx=class{constructor(){(0,tG.__publicField)(this,"nodeType","hardBreak")}toMarkdown(e,t){return" \n"}},sA=class{constructor(){(0,tG.__publicField)(this,"nodeType","mention")}toMarkdown(e,t){let{id:r,text:i,userType:a}=e.attrs||{},n=`adf://mention/${r||"unknown"}`,s=i||`@${r||"unknown"}`;if(e.attrs&&Object.keys(e.attrs).length>0){let t=`<!-- adf:mention attrs='${JSON.stringify(e.attrs)}' -->`;return`[${s}](${n})${t}`}return`[${s}](${n})`}},s_=class{constructor(){(0,tG.__publicField)(this,"nodeType","date")}toMarkdown(e,t){let{timestamp:r}=e.attrs||{};if(!r)return"[Date]";let i=new Date(parseInt(r));if(isNaN(i.getTime())){if(e.attrs&&Object.keys(e.attrs).length>0){let t=`<!-- adf:date attrs='${JSON.stringify(e.attrs)}' -->`;return`[Invalid Date]${t}`}return"[Invalid Date]"}let a=i.toISOString().split("T")[0];if(e.attrs&&Object.keys(e.attrs).length>0){let t=`<!-- adf:date attrs='${JSON.stringify(e.attrs)}' -->`;return`${a}${t}`}return a}},sC=class{constructor(){(0,tG.__publicField)(this,"nodeType","emoji")}toMarkdown(e,t){let{shortName:r,text:i}=e.attrs||{};if(i){if(e.attrs&&Object.keys(e.attrs).length>0){let t=`<!-- adf:emoji attrs='${JSON.stringify(e.attrs)}' -->`;return`${i}${t}`}return i}if(r){let t=r.startsWith(":")&&r.endsWith(":")?r:`:${r}:`;if(e.attrs&&Object.keys(e.attrs).length>0){let r=`<!-- adf:emoji attrs='${JSON.stringify(e.attrs)}' -->`;return`${t}${r}`}return t}return":emoji:"}},sR=class{constructor(){(0,tG.__publicField)(this,"nodeType","status")}toMarkdown(e,t){let{text:r,color:i}=e.attrs||{},a=r||"Status";return i&&"neutral"!==i?`{status:${a}|color:${i}}`:`{status:${a}}`}},sT=class{constructor(){(0,tG.__publicField)(this,"nodeType","inlineCard")}toMarkdown(e,t){let{url:r,data:i}=e.attrs||{};if(!r)return"[Card]";let a=i?.title||i?.name||"Card",n=`adf://card/${encodeURIComponent(r)}`;if(e.attrs&&Object.keys(e.attrs).length>0){let t=`<!-- adf:inlineCard attrs='${JSON.stringify(e.attrs)}' -->`;return`[${a}](${n})${t}`}return`[${a}](${n})`}},sD=class{constructor(){(0,tG.__publicField)(this,"nodeType","mediaGroup")}toMarkdown(e,t){return(e.content||[]).map(e=>{let r=t.options.registry?.getNodeConverter(e.type);return r?r.toMarkdown(e,t):""}).filter(e=>e.length>0).join(" ")+"\n\n"}},sN=class{constructor(){(0,tG.__publicField)(this,"nodeType","doc")}toMarkdown(e,t){let r=e.content||[];return t.convertChildren(r).trim()+"\n"}},sO=class{constructor(){(0,tG.__publicField)(this,"markType","strong")}toMarkdown(e,t,r){return t.attrs&&Object.keys(t.attrs).length>0?`**${e}**<!-- adf:strong attrs='${JSON.stringify(t.attrs)}' -->`:`**${e}**`}},sP=class{constructor(){(0,tG.__publicField)(this,"markType","em")}toMarkdown(e,t,r){return t.attrs&&Object.keys(t.attrs).length>0?`*${e}*<!-- adf:em attrs='${JSON.stringify(t.attrs)}' -->`:`*${e}*`}},s$=class{constructor(){(0,tG.__publicField)(this,"markType","code")}toMarkdown(e,t,r){return t.attrs&&Object.keys(t.attrs).length>0?`\`${e}\`<!-- adf:code attrs='${JSON.stringify(t.attrs)}' -->`:`\`${e}\``}},sU=class{constructor(){(0,tG.__publicField)(this,"markType","link")}toMarkdown(e,t,r){let i;if(!t.attrs?.href)return e;let{href:a,title:n,...s}=t.attrs;return i=n?`[${e}](${a} "${n}")`:`[${e}](${a})`,Object.keys(s).length>0&&(i+=`<!-- adf:link attrs='${JSON.stringify(s)}' -->`),i}},sB=class{constructor(){(0,tG.__publicField)(this,"markType","strike")}toMarkdown(e,t,r){return t.attrs&&Object.keys(t.attrs).length>0?`~~${e}~~<!-- adf:strike attrs='${JSON.stringify(t.attrs)}' -->`:`~~${e}~~`}},sj=class{constructor(){(0,tG.__publicField)(this,"markType","underline")}toMarkdown(e,t,r){let i=`<u>${e}</u>`;return t.attrs&&Object.keys(t.attrs).length>0?`${i}<!-- adf:underline attrs='${JSON.stringify(t.attrs)}' -->`:i}},sL=class{constructor(){(0,tG.__publicField)(this,"markType","textColor")}toMarkdown(e,t,r){if(!t.attrs?.color)return e;let{color:i,...a}=t.attrs,n=`<span style="color: ${i}">${e}</span>`;return Object.keys(a).length>0&&(n+=`<!-- adf:textColor attrs='${JSON.stringify(a)}' -->`),n}},sq=class{constructor(){(0,tG.__publicField)(this,"markType","backgroundColor")}toMarkdown(e,t,r){let{color:i}=t.attrs||{},a=`<mark style="background-color: ${i||"yellow"}">${e}</mark>`;if(t.attrs&&Object.keys(t.attrs).length>0){let e=`<!-- adf:backgroundColor attrs='${JSON.stringify(t.attrs)}' -->`;return`${a}${e}`}return a}},sM=class{constructor(){(0,tG.__publicField)(this,"markType","subsup")}toMarkdown(e,t,r){let i,{type:a}=t.attrs||{};if(i="sub"===a?`<sub>${e}</sub>`:`<sup>${e}</sup>`,t.attrs&&Object.keys(t.attrs).length>0){let e=`<!-- adf:subsup attrs='${JSON.stringify(t.attrs)}' -->`;return`${i}${e}`}return i}},sF=class{constructor(e={}){(0,tG.__publicField)(this,"registry"),(0,tG.__publicField)(this,"validator"),(0,tG.__publicField)(this,"options"),this.options={strict:!1,gfm:!0,frontmatter:!0,enableAdfExtensions:!0,maxDepth:5,enableLogging:!1,preserveWhitespace:!1,validateInput:!1,preserveUnknownNodes:!0,maxRetries:3,retryDelay:100,fallbackStrategy:"best-effort",...e},this.registry=new nY,this.validator=new nH,this.registerConverters()}convert(e){if(!e||"object"!=typeof e){if(this.options.strict)throw Error("Invalid ADF document: must be a non-null object");return""}if("doc"!==e.type&&this.options.strict)throw Error('Invalid ADF document: root node must be of type "doc"');try{let t=this.validator.validate(e);if(!t.valid&&this.options.strict)throw Error(`Invalid ADF structure: ${t.errors.map(e=>e.message).join(", ")}`);return this.convertAdfToMarkdown(e)}catch(e){if(this.options.strict)throw e;return this.options.enableLogging&&console.warn("ADF to Markdown conversion failed, returning empty string:",e),""}}convertWithValidation(e){let t=[],r=this.validator.validate(e);if(!r.valid){if(this.options.strict)throw Error(`Invalid ADF structure: ${r.errors.map(e=>e.message).join(", ")}`);t.push(...r.errors.map(e=>e.message))}try{return{markdown:this.convertAdfToMarkdown(e),warnings:t}}catch(e){if(this.options.strict)throw e;return t.push(`Conversion failed: ${e instanceof Error?e.message:"Unknown error"}`),{markdown:"",warnings:t}}}getStats(e){let t={nodeCount:0,hasAdfExtensions:!1,hasGfmFeatures:!1,supportedTypes:new Set,unsupportedTypes:new Set},r=e=>{t.nodeCount++;try{this.registry.getNodeConverter(e.type),t.supportedTypes.add(e.type)}catch{t.unsupportedTypes.add(e.type)}["panel","expand","mediaSingle","mediaGroup","mention","emoji","date","status"].includes(e.type)&&(t.hasAdfExtensions=!0),["table","tableRow","tableHeader","tableCell"].includes(e.type)&&(t.hasGfmFeatures=!0),e.content&&Array.isArray(e.content)&&e.content.forEach(r)};e.content&&e.content.forEach(r);let i=t.nodeCount<10?"simple":t.nodeCount<50?"moderate":"complex";return{nodeCount:t.nodeCount,hasAdfExtensions:t.hasAdfExtensions,hasGfmFeatures:t.hasGfmFeatures,complexity:i,supportedTypes:Array.from(t.supportedTypes),unsupportedTypes:Array.from(t.unsupportedTypes)}}registerConverters(){this.registry.registerNodes([new so,new sl,new su,new sc,new sd,new sp,new sh,new sm,new sf,new sg,new sy,new sw,new sb,new sv,new sk,new sS,new sE,new sI,new sx,new sA,new s_,new sC,new sR,new sT,new sD,new sN]),this.registry.registerMarks([new sO,new sP,new s$,new sU,new sB,new sj,new sL,new sq,new sM])}convertAdfToMarkdown(e){let t={convertChildren:e=>Array.isArray(e)?e.map(e=>{try{return this.registry.getNodeConverter(e.type).toMarkdown(e,t)}catch(t){return this.options.enableLogging&&console.warn(`Failed to convert node type "${e.type}":`,t),this.options.preserveUnknownNodes?`<!-- Unknown node: ${e.type} -->`:""}}).join(""):"",depth:0,options:{...this.options,registry:this.registry}};return e.content&&Array.isArray(e.content)?e.content.map(e=>{try{return this.registry.getNodeConverter(e.type).toMarkdown(e,t)}catch(t){return this.options.enableLogging&&console.warn(`Failed to convert node type "${e.type}":`,t),this.options.preserveUnknownNodes?`<!-- Unknown node: ${e.type} -->`:""}}).filter(e=>e.length>0).join("\n\n"):""}},sK=class{constructor(e={}){(0,tG.__publicField)(this,"options"),this.options={maxRetries:3,retryDelay:100,fallbackStrategy:"best-effort",onError:()=>{},onRecovery:()=>{},enableLogging:!1,...e}}async executeWithRecovery(e,t){let r,i={operation:"unknown",input:"",attempt:0,previousErrors:[],...t},a=[];for(let t=0;t<=this.options.maxRetries;t++){i.attempt=t;try{let r=await e();return t>0&&this.options.onRecovery&&this.options.onRecovery("retry-success",i),{success:!0,data:r,warnings:a}}catch(e){if(r=e,i.previousErrors.push(r),this.options.onError&&this.options.onError(r,i),this.options.enableLogging&&console.warn(`Attempt ${t+1} failed:`,r.message),this.isNonRetryableError(r))break;t<this.options.maxRetries&&await this.delay(this.options.retryDelay)}}return this.applyFallbackStrategy(r,i,a)}async recoverAdfToMarkdown(e,t,r){let i=[];try{if(e.content&&Array.isArray(e.content)){let t=[];for(let r of e.content)try{let e=await this.recoverNodeConversion(r,"adf-to-markdown");e.success&&e.data?t.push(e.data):(i.push(`Failed to convert node type: ${r.type}`),t.push(this.createNodeFallback(r,"markdown")))}catch(e){i.push(`Node conversion error: ${e}`),t.push(this.createNodeFallback(r,"markdown"))}let a=t.join("\n\n");return this.options.onRecovery&&this.options.onRecovery("node-by-node-recovery",r),{success:!0,data:a,strategy:"node-by-node-recovery",fallback:!0,warnings:i}}let t=this.createMinimalMarkdown(e);return i.push("Used minimal fallback conversion"),{success:!0,data:t,strategy:"minimal-fallback",fallback:!0,warnings:i}}catch(e){return{success:!1,error:e,warnings:i}}}async recoverMarkdownToAdf(e,t,r){let i=[];try{let t=this.splitMarkdownIntoSections(e),a=[];for(let e of t)try{let t=await this.parseMarkdownSection(e);t.success&&t.data?a.push(...t.data.content):(i.push(`Failed to parse section: ${e.substring(0,50)}...`),a.push(this.createTextFallback(e)))}catch(t){i.push(`Section parsing error: ${t}`),a.push(this.createTextFallback(e))}return this.options.onRecovery&&this.options.onRecovery("section-by-section-recovery",r),{success:!0,data:{version:1,type:"doc",content:a},strategy:"section-by-section-recovery",fallback:!0,warnings:i}}catch(r){let t={version:1,type:"doc",content:[this.createTextFallback(e)]};return i.push("Used text-only fallback conversion"),{success:!0,data:t,strategy:"text-fallback",fallback:!0,warnings:i}}}async applyFallbackStrategy(e,t,r){switch(this.options.fallbackStrategy){case"skip":return r.push("Operation skipped due to errors"),{success:!1,error:e,warnings:r};case"placeholder":let i=this.createPlaceholder(t);return r.push("Used placeholder due to errors"),{success:!0,data:i,strategy:"placeholder",fallback:!0,warnings:r};case"best-effort":return await this.attemptBestEffortRecovery(e,t,r);default:return{success:!1,error:e,warnings:r}}}async attemptBestEffortRecovery(e,t,r){try{if(t.operation.includes("adfToMarkdown"))return await this.recoverAdfToMarkdown(t.input,e,t);if(t.operation.includes("markdownToAdf"))return await this.recoverMarkdownToAdf(t.input,e,t);return r.push("Applied generic fallback recovery"),{success:!1,error:e,strategy:"generic-fallback",warnings:r}}catch(e){return{success:!1,error:e,warnings:r}}}isNonRetryableError(e){return e instanceof nz||e.message.includes("Invalid JSON")||e.message.includes("Syntax error")}delay(e){return new Promise(t=>setTimeout(t,e))}async recoverNodeConversion(e,t){try{if("adf-to-markdown"===t)return{success:!0,data:this.createNodeFallback(e,"markdown"),warnings:[]};return{success:!0,data:JSON.stringify(e),warnings:[]}}catch(e){return{success:!1,error:e,warnings:[]}}}createNodeFallback(e,t){if("markdown"!==t)return JSON.stringify(e,null,2);switch(e.type){case"paragraph":return e.content?this.extractTextFromNodes(e.content):"[Paragraph]";case"heading":let r=e.attrs?.level||1,i=e.content?this.extractTextFromNodes(e.content):"[Heading]";return"#".repeat(r)+" "+i;case"codeBlock":return"```\n[Code Block]\n```";case"panel":return`> [${e.attrs?.panelType||"info"} panel]`;default:return`[${e.type}]`}}extractTextFromNodes(e){return e.map(e=>"text"===e.type&&e.text?e.text:e.content?this.extractTextFromNodes(e.content):"").join("")}createMinimalMarkdown(e){let t=e.content?e.content.map(e=>this.createNodeFallback(e,"markdown")).join("\n\n"):"[No content]";return`# Document
615
615
 
616
- ${t}`}splitMarkdownIntoSections(e){let t=e.split(/(?=^#{1,6}\s)|(?:\n\s*\n)/m).filter(e=>e.trim().length>0);return t.length>0?t:[e]}async parseMarkdownSection(e){try{let t=[this.createTextFallback(e)];return{success:!0,data:{version:1,type:"doc",content:t},warnings:[]}}catch(e){return{success:!1,error:e,warnings:[]}}}createTextFallback(e){return{type:"paragraph",content:[{type:"text",text:e.trim()}]}}createPlaceholder(e){return e.operation.includes("adfToMarkdown")?`[Error converting ADF to Markdown: ${e.operation}]`:e.operation.includes("markdownToAdf")?{version:1,type:"doc",content:[{type:"paragraph",content:[{type:"text",text:`[Error converting Markdown to ADF: ${e.operation}]`}]}]}:`[Error in operation: ${e.operation}]`}},sV=class{constructor(e){(0,tG.__publicField)(this,"mdToAdfEngine"),(0,tG.__publicField)(this,"adfToMdEngine"),(0,tG.__publicField)(this,"options"),(0,tG.__publicField)(this,"errorRecovery"),(0,tG.__publicField)(this,"remarkProcessor"),(0,tG.__publicField)(this,"registry");try{this.options=e||{},this.mdToAdfEngine=new ss(this.options),this.adfToMdEngine=new sF(this.options),this.errorRecovery=new sK({maxRetries:e?.maxRetries||3,retryDelay:e?.retryDelay||100,fallbackStrategy:e?.fallbackStrategy||"best-effort",enableLogging:e?.enableLogging||!1,onError:e?.onError,onRecovery:e?.onRecovery}),this.remarkProcessor=ri().use(iD).use(a_,["yaml"]).use(n$).use(nV,{strict:e?.strict||!1}).use(am),this.registry=new nY,this.registerConverters()}catch(e){throw new nJ("Failed to initialize Parser","INIT_ERROR")}}adfToMarkdown(e,t){return t&&Object.keys(t).length>0?new sF({...this.options,...t}).convert(e):this.adfToMdEngine.convert(e)}async adfToMarkdownWithRecovery(e,t){let r=await this.errorRecovery.executeWithRecovery(()=>this.adfToMarkdown(e,t),{operation:"adfToMarkdown",input:e,nodeType:e.type});if(!r.success)throw r.error||Error("ADF to Markdown conversion failed");return r.data}markdownToAdf(e,t){return t&&Object.keys(t).length>0?new ss({...this.options,...t}).convert(e):this.mdToAdfEngine.convert(e)}async markdownToAdfWithRecovery(e,t){let r=await this.errorRecovery.executeWithRecovery(()=>this.markdownToAdf(e,t),{operation:"markdownToAdf",input:e});if(!r.success)throw r.error||Error("Markdown to ADF conversion failed");return r.data}async markdownToAdfAsync(e,t){return await this.mdToAdfEngine.convertAsync(e)}async markdownToAdfAsyncWithRecovery(e,t){let r=await this.errorRecovery.executeWithRecovery(async()=>this.markdownToAdfAsync(e,t),{operation:"markdownToAdfAsync",input:e});if(!r.success)throw r.error||Error("Async Markdown to ADF conversion failed");return r.data}async validateMarkdownAsync(e){let t=await this.mdToAdfEngine.validate(e);return{valid:t.valid,errors:t.errors.map(e=>({message:e})),warnings:t.warnings}}async getStats(e){return await this.mdToAdfEngine.getStats(e)}stringify(e,t){return this.adfToMarkdown(e,t)}async stringifyAsync(e,t){return this.adfToMarkdownWithRecovery(e,t)}validateAdf(e){return new nH().validate(e)}validateMarkdown(e){return new nW().validate(e)}getErrorRecovery(){return this.errorRecovery}registerConverters(){this.registry.registerNodes([new so,new sl,new su,new sc,new sd,new sp,new sh,new sm,new sf,new sg,new sy,new sw,new sb,new sv,new sk,new sS,new sE,new sI,new sx,new sA,new s_,new sC,new sR,new sT,new sD,new sN]),this.registry.registerMarks([new sO,new sP,new s$,new sU,new sB,new sj,new sL,new sq,new sM])}convertAdfToMarkdown(e){return this.adfToMdEngine.convert(e)}convertMdastToAdf(e){return this.mdToAdfEngine.convert(e)}fallbackConversion(e){return this.mdToAdfEngine.convert(e)}countNodes(e){let t=0;for(let r of e)t++,r.content&&Array.isArray(r.content)&&(t+=this.countNodes(r.content));return t}postProcessAdfFenceBlocks(e){return e}parseAdfLanguageString(e,t){return{}}},sG=e.i(378731);let sH=[/^h[1-6]\.\s/m,/^bq\.\s/m,/\{code(?::[^}]+)?\}/i,/\{noformat\}/i,/\{\{[^}\n]+\}\}/,/^\|\|.+\|\|\s*$/m,/\[[^\]\n]+\|https?:\/\//i,/\[~[^\]\n]+\]/,/\[\^[^\]\n]+\]/,/![^!\n]+!/];function sW(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"doc"===e.type&&1===e.version&&Array.isArray(e.content)}function sJ(e,t){return sG.default.to_markdown(e.replace(/\[~([^\]\n]+)\]/g,"@$1").replace(/\[\^([^\]\n]+)\]/g,"[Attachment: $1]").replace(/\[([A-Z][A-Z0-9_]*-\d+)\]/g,(e,r)=>t?`[${r}](${t}/browse/${r})`:`**${r}**`))}let sz=new sV;function sZ(e,t){if(null==e)return null;let r=function(e){if(sW(e))return"ADF";let t="string"==typeof e?e:"";return sH.some(e=>e.test(t))?"JIRA_WIKI":"MARKDOWN"}(e),i="string"==typeof e?e:null==e?"":JSON.stringify(e,null,2),a="ADF"===r?function(e){try{return sz.adfToMarkdown(e)}catch{return function e(t){return t&&"object"==typeof t?["string"==typeof t.text?t.text:"",...Array.isArray(t.content)?t.content.map(e).filter(Boolean):[]].filter(Boolean).join("\n"):""}(e)}}(e):"JIRA_WIKI"===r?sJ(i,t):i;return{format:r,raw:e,rawText:i,markdown:a,wikiMarkup:"JIRA_WIKI"===r?i:sG.default.to_jira(a)}}function sY(e){let t=e.value.trim(),r="JIRA_WIKI"===e.format?sJ(t):t,i=sz.markdownToAdf(r);if(!sW(i))throw Error("The Jira text could not be converted to valid ADF");return i}let sQ="default",sX=["summary","status","issuetype","priority","assignee","project","updated"],s0=[{window:"5m",milliseconds:3e5},{window:"10m",milliseconds:6e5},{window:"1h",milliseconds:36e5},{window:"24h",milliseconds:864e5}];function s1(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function s2(e){return s1(e)?e:{}}function s3(e){return Array.isArray(e)?e:[]}function s4(e){return"string"==typeof e&&e.length>0?e:null}function s6(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function s8(e){let t=e.trim().toUpperCase();if(!/^[A-Z][A-Z0-9_]*-\d+$/.test(t))throw Error("Invalid Jira issue key");return t}function s5(e){if(null===e)return null;try{return JSON.parse(e)}catch{return null}}function s9(e){return s3(s5(e)).flatMap(e=>"string"==typeof e&&e.length>0?[e]:[])}function s7(e){return JSON.stringify(function e(t){return Array.isArray(t)?t.map(e):s1(t)?Object.fromEntries(Object.keys(t).sort().map(r=>[r,e(t[r])])):t}(e))}function oe(e){if(!s1(e))return null;let t=e.status??s2(e.response).status;return"number"==typeof t?t:null}function ot(e,t){let r=e instanceof Error?e.message:String(e);return(t?r.replaceAll(t,"[REDACTED]"):r).slice(0,1e3)}function or(e){return s4(s2(s2(e.fields).project).key)??(e.key?.split("-")[0]||"UNKNOWN")}function oi(e){let t=s2(e),r=s4(t.displayName);if(!r)return null;let i=s2(t.avatarUrls);return{accountId:s4(t.accountId),displayName:r,avatarUrl:s4(i["48x48"])??s4(i["32x32"])??s4(i["24x24"])}}function oa(e){return s3(e).map(s2).map(e=>({id:s4(e.id),name:s4(e.name)??"Unknown"}))}function on(e,t){let r=s2(e),i=s4(r.key);if(!i)return null;let a=s2(r.fields);return{relationship:t,key:i,summary:s4(a.summary)??i,status:s4(s2(a.status).name)}}function os(e){return{...e,kind:"BOARD"===e.kind?"BOARD":"JQL"}}function oo(e){return{source:e.source,stale:e.stale,fetchedAt:e.fetchedAt.toISOString()}}function ol(e){return 0===e.length?{source:"CACHE",stale:!1,fetchedAt:new Date(0).toISOString()}:{source:e.some(e=>"ERROR"===e.source)?"ERROR":e.some(e=>"LIVE"===e.source)?"LIVE":"CACHE",stale:e.some(e=>e.stale),fetchedAt:new Date(Math.max(...e.map(e=>e.fetchedAt.getTime()))).toISOString()}}function ou(e){let t=s2(e.fields),r=s2(t.status),i=s2(r.statusCategory),a=s2(t.assignee),n=s2(a.avatarUrls),s=s2(t.project),o=e.key??"UNKNOWN";return{id:e.id??o,key:o,summary:s4(t.summary)??o,statusId:s4(r.id)??s4(r.name)??"unknown",status:s4(r.name)??"Unknown",statusCategory:s4(i.key)??s4(i.name)??"unknown",issueType:s4(s2(t.issuetype).name),priority:s4(s2(t.priority).name),assignee:s4(a.displayName),assigneeAccountId:s4(a.accountId),assigneeAvatarUrl:s4(n["48x48"])??s4(n["32x32"]),projectKey:s4(s.key)??or(e),updatedAt:s4(t.updated)}}function oc(e){let t=e.toLowerCase();return"new"===t||t.includes("to do")?0:"indeterminate"===t||t.includes("progress")?1:"done"===t?2:3}let od=new Set(["ALL","UNASSIGNED_OR_SELF","SELF_IN_PROGRESS"]);function op(e){return od.has(e)?e:"ALL"}e.s(["JiraService",0,class{credentials;workflowEvents;inFlight;clients;lastPrunedAt;constructor(e=new tO.CredentialService,t){this.credentials=e,this.workflowEvents=t,this.inFlight=new Map,this.lastPrunedAt=0}async recordTicketWorkflowEvents(e,t){if(!this.workflowEvents)return;let r=e.comments.at(-1)??null,i={ticket:{key:e.key,title:e.summary,type:e.issueType,status:e.status,statusId:e.statusId,statusCategory:e.statusCategory,assignee:e.assignee,assigneeAccountId:e.assigneeAccountId,labels:e.labels,sprintNames:e.sprintNames,activeSprintNames:e.activeSprintNames,closedSprintNames:e.closedSprintNames,url:e.jiraUrl},comment:r?{id:r.id,body:r.content?.rawText??"",author:r.author}:null,...void 0!==t?{changelog:t}:{}},a=e.cache.fetchedAt,n=e.assigneeAccountId?await this.currentAccountId().catch(()=>null):null,s=[["JIRA_STATUS",e.statusId],["JIRA_LABEL",JSON.stringify([...e.labels].sort())],["JIRA_MENTION",r?.id??"none"],["JIRA_SPRINT_STARTED",[...e.activeSprintNames].sort()],["JIRA_TICKET_UPDATED",e.updatedAt??"unknown"],["JIRA_COMMENT_ADDED",r?.id??"none"],["JIRA_SPRINT_ENDED",[...e.closedSprintNames].sort()]];if(n&&n===e.assigneeAccountId&&s.push(["JIRA_ASSIGNED_SELF",n]),t?.items.length){let e=new Set(t.items.flatMap(e=>[e.fieldId,e.field].filter(e=>!!e).map(e=>e.trim().toLowerCase()))),r=new Set(["JIRA_TICKET_UPDATED"]);e.has("status")&&r.add("JIRA_STATUS"),(e.has("label")||e.has("labels"))&&r.add("JIRA_LABEL"),e.has("assignee")&&r.add("JIRA_ASSIGNED_SELF"),e.has("sprint")&&(r.add("JIRA_SPRINT_STARTED"),r.add("JIRA_SPRINT_ENDED")),s=s.filter(([e])=>r.has(e))}await Promise.allSettled(s.map(([t,r])=>this.workflowEvents.record({kind:t,subjectKey:e.key,dedupeKey:`jira-trigger:${t}:${e.key}:${a}`,payload:{...i,sessionData:i,cursorValue:r}})))}async getSettings(){let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.upsert({where:{id:sQ},create:{id:sQ,cacheTtlSeconds:300},update:{}});return{siteUrl:t.siteUrl,email:t.email,tokenConfigured:await this.credentials.isConfigured(tN.CREDENTIALS.jiraApiToken),cacheTtlSeconds:t.cacheTtlSeconds,updatedAt:t.updatedAt.toISOString()}}async saveSettings(e){let t=await (0,tD.getPrismaClient)(),r=function(e){let t=new URL(e.trim());if("https:"!==t.protocol)throw Error("Jira Cloud site URL must use HTTPS");if(!t.hostname.toLowerCase().endsWith(".atlassian.net"))throw Error("Only Jira Cloud *.atlassian.net sites are supported");if(t.username||t.password||t.search||t.hash)throw Error("Jira site URL must not include credentials, query, or fragment");return t.origin}(e.siteUrl),i=e.email.trim();if(!/^\S+@\S+\.\S+$/.test(i))throw Error("A valid Jira email is required");let a=await t.jiraSettings.findUnique({where:{id:sQ}}),n=e.apiToken?.trim()||null,s=!!(a?.siteUrl&&a.siteUrl!==r);if(s&&!e.resetSite)throw Error("Changing the Jira site requires resetSite=true");let o=a?.siteUrl!==r||a?.email!==i||!!n,l=async e=>{s&&(await e.jiraProject.deleteMany(),await e.jiraWebhookDelivery.deleteMany()),o&&(await e.jiraCacheEntry.deleteMany(),await e.jiraCachedTicket.deleteMany()),await e.jiraSettings.upsert({where:{id:sQ},create:{id:sQ,siteUrl:r,email:i,cacheTtlSeconds:300},update:s?{siteUrl:r,email:i,webhookEnabled:!1,webhookConfiguredAt:null,webhookId:null,webhookUrl:null,webhookJql:null}:{siteUrl:r,email:i}})};return n?await this.credentials.setText(tN.CREDENTIALS.jiraApiToken,n,l):await t.$transaction(l),s&&await this.credentials.delete(tN.CREDENTIALS.jiraWebhookSecret),this.clients=void 0,this.getSettings()}async clearCredentials(){let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:sQ},select:{siteUrl:!0,email:!0,webhookId:!0}}),r=await this.credentials.isConfigured(tN.CREDENTIALS.jiraApiToken);if(t?.siteUrl&&t.email&&t.webhookId&&r)try{await this.webhookApiRequest("DELETE",`/rest/webhooks/1.0/webhook/${encodeURIComponent(t.webhookId)}`)}catch(e){if(404!==oe(e))throw e}return await this.credentials.deleteMany([tN.CREDENTIALS.jiraApiToken,tN.CREDENTIALS.jiraWebhookSecret],async e=>{await e.jiraCacheEntry.deleteMany(),await e.jiraCachedTicket.deleteMany(),await e.jiraWebhookDelivery.deleteMany(),await e.jiraSettings.upsert({where:{id:sQ},create:{id:sQ,cacheTtlSeconds:300},update:{email:null,webhookEnabled:!1,webhookConfiguredAt:null,webhookId:null,webhookUrl:null,webhookJql:null}})}),this.clients=void 0,this.getSettings()}async updateCacheTtl(e){if(!Number.isInteger(e)||e<1||e>1440)throw Error("Cache TTL must be an integer from 1 to 1440 minutes");let t=await (0,tD.getPrismaClient)();return await t.jiraSettings.upsert({where:{id:sQ},create:{id:sQ,cacheTtlSeconds:60*e},update:{cacheTtlSeconds:60*e}}),this.getSettings()}async testConnection(){let e=await this.cachedCall({operation:"MYSELF",params:{},requestSummary:"Current Jira user",force:!0,allowStaleOnError:!1,fetcher:async()=>{let{version3:e}=await this.getClients();return e.myself.getCurrentUser()}});if(e.stale)throw Error("Jira connection test failed because the live request failed");let t=s2(e.value);return{accountId:s4(t.accountId),displayName:s4(t.displayName)??"Jira user",emailAddress:s4(t.emailAddress),cache:oo(e)}}async listProjects(){let e=await (0,tD.getPrismaClient)();return(await e.jiraProject.findMany({include:{sources:{orderBy:[{position:"asc"},{createdAt:"asc"}]}},orderBy:[{position:"asc"},{createdAt:"asc"}]})).map(e=>({id:e.id,jiraId:e.jiraId,key:e.key,name:e.name,avatarUrl:e.avatarUrl,position:e.position,ticketAssignmentFilter:op(e.ticketAssignmentFilter),hideCompletedTickets:e.hideCompletedTickets,completedStatusIds:s9(e.completedStatusIdsJson),doneStatusId:e.doneStatusId,branchNamingScript:e.branchNamingScript??tF,sources:e.sources.map(os)}))}async projectStatuses(e){let t=await (0,tD.getPrismaClient)(),r=await t.jiraProject.findUnique({where:{id:e},select:{jiraId:!0,key:!0}});if(!r)throw Error("Jira project not found");let i=await this.cachedCall({operation:"PROJECT_STATUSES",params:{jiraId:r.jiraId},requestSummary:`Statuses for project ${r.key}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.projects.getAllStatuses(r.jiraId)}}),a=new Map;for(let e of s3(i.value).map(s2))for(let t of s3(e.statuses).map(s2)){let e=s4(t.id),r=s4(t.name);if(!e||!r||a.has(e))continue;let i=s2(t.statusCategory);a.set(e,{id:e,name:r,category:s4(i.key)??s4(i.name)??"unknown"})}return[...a.values()].sort((e,t)=>oc(e.category)-oc(t.category)||e.name.localeCompare(t.name))}async updateProjectDisplaySettings(e){if(!od.has(e.ticketAssignmentFilter))throw Error("Invalid Jira ticket assignment filter");let t=[...new Set(e.completedStatusIds.map(e=>e.trim()).filter(Boolean))].slice(0,200),r=await (0,tD.getPrismaClient)(),i=void 0===e.doneStatusId?void 0:e.doneStatusId?.trim()||null;if(i&&!(await this.projectStatuses(e.projectId)).some(e=>e.id===i))throw Error("The selected Jira done status is not available");return await r.jiraProject.update({where:{id:e.projectId},data:{ticketAssignmentFilter:e.ticketAssignmentFilter,hideCompletedTickets:e.hideCompletedTickets,completedStatusIdsJson:JSON.stringify(t),...void 0===i?{}:{doneStatusId:i}}}),this.listProjects()}async updateProjectBranchNaming(e,t){let r=await (0,tD.getPrismaClient)(),i=await r.jiraProject.findUnique({where:{id:e},select:{key:!0}});if(!i)throw Error("Jira project not found");let a=await tV(t,i.key);return await r.jiraProject.update({where:{id:e},data:{branchNamingScript:a}}),this.listProjects()}async availableProjects(){let e=[],t=0;for(;;){let r=await this.cachedCall({operation:"PROJECTS",params:{startAt:t,maxResults:100},requestSummary:`Visible projects from ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.projects.searchProjects({startAt:t,maxResults:100,orderBy:"name"})},itemCount:e=>s3(s2(e).values).length}),i=s2(r.value),a=s3(i.values).map(s2);e.push(...a.flatMap(e=>{let t=s4(e.id),r=s4(e.key),i=s4(e.name);if(!t||!r||!i)return[];let a=s2(e.avatarUrls);return[{jiraId:t,key:r,name:i,avatarUrl:s4(a["48x48"])??s4(a["32x32"])}]}));let n=s6(i.total)??e.length;if(0===a.length||e.length>=n)break;t+=a.length}return e}async addProject(e){let t=e.trim();if(!t)throw Error("Jira project ID is required");let i=s2((await this.cachedCall({operation:"PROJECT",params:{jiraId:t},requestSummary:`Project ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.projects.getProject(t)}})).value),a=s4(i.key),n=s4(i.name),s=s4(i.id);if(!a||!n||!s)throw Error("Jira returned an incomplete project");let o=s2(i.avatarUrls),l=await (0,tD.getPrismaClient)(),u=await l.jiraProject.aggregate({_max:{position:!0}});return await l.jiraProject.create({data:{id:(0,r.randomUUID)(),jiraId:s,key:a,name:n,avatarUrl:s4(o["48x48"])??s4(o["32x32"]),position:(u._max.position??-1)+1,branchNamingScript:tF}}),this.listProjects()}async removeProject(e){let t=await (0,tD.getPrismaClient)(),r=(await t.jiraSource.findMany({where:{projectId:e},select:{id:!0}})).map(e=>e.id);return await t.$transaction(async t=>{r.length>0&&await t.jiraCacheEntry.deleteMany({where:{sourceId:{in:r}}}),await t.jiraProject.delete({where:{id:e}}),await t.jiraCachedTicket.deleteMany({where:{cacheEntries:{none:{}}}})}),this.listProjects()}async createSource(e){let t=await this.validateSource(e.kind,e.value),i=this.validateSourceName(e.name),a=await (0,tD.getPrismaClient)();if(!await a.jiraProject.findUnique({where:{id:e.projectId}}))throw Error("Jira project not found");let n=await a.jiraSource.aggregate({where:{projectId:e.projectId},_max:{position:!0}});return await a.jiraSource.create({data:{id:(0,r.randomUUID)(),projectId:e.projectId,name:i,kind:e.kind,value:t.value,boardId:t.boardId,position:(n._max.position??-1)+1}}),this.listProjects()}async updateSource(e){let t=await this.validateSource(e.kind,e.value),r=this.validateSourceName(e.name),i=await (0,tD.getPrismaClient)();return await i.$transaction([i.jiraCacheEntry.deleteMany({where:{sourceId:e.id}}),i.jiraSource.update({where:{id:e.id},data:{name:r,kind:e.kind,value:t.value,boardId:t.boardId}})]),this.listProjects()}async deleteSource(e){let t=await (0,tD.getPrismaClient)();return await t.$transaction(async t=>{await t.jiraCacheEntry.deleteMany({where:{sourceId:e}}),await t.jiraSource.delete({where:{id:e}}),await t.jiraCachedTicket.deleteMany({where:{cacheEntries:{none:{}}}})}),this.listProjects()}async ticketBoard(e,t=!1){var r;let i,a,n,s=await (0,tD.getPrismaClient)(),o=await s.jiraSource.findUnique({where:{id:e},include:{project:!0}});if(!o)throw Error("Jira source not found");let l=await s.jiraCacheEntry.findFirst({where:{sourceId:e,issues:{some:{}}},orderBy:{fetchedAt:"desc"},include:{issues:{select:{issueKey:!0}}}}),u=new Set(l?.issues.map(({issueKey:e})=>e)??[]),c="BOARD"===o.kind?await this.loadBoardSource(os(o),t):await this.loadJqlSource(os(o),t),d={ticketAssignmentFilter:op(o.project.ticketAssignmentFilter),hideCompletedTickets:o.project.hideCompletedTickets,completedStatusIds:s9(o.project.completedStatusIdsJson)},p="ALL"===d.ticketAssignmentFilter?null:await this.currentAccountId(),h=(r={source:os(o),...c},i=d.hideCompletedTickets?new Set(d.completedStatusIds):new Set,a=new Set(r.tickets.filter(e=>i.has(e.statusId)).map(e=>e.status)),n=r.tickets.filter(e=>{let t;return!i.has(e.statusId)&&("ALL"===d.ticketAssignmentFilter||("UNASSIGNED_OR_SELF"===d.ticketAssignmentFilter?null===e.assigneeAccountId||e.assigneeAccountId===p:null!==p&&e.assigneeAccountId===p&&("indeterminate"===(t=e.statusCategory.toLowerCase())||t.includes("progress"))))}),{...r,tickets:n,statusOrder:r.statusOrder.filter(e=>!a.has(e))});return this.workflowEvents&&l&&await Promise.allSettled(h.tickets.filter(({key:e})=>!u.has(e)).map(t=>{let r={ticket:{key:t.key,title:t.summary,type:t.issueType,status:t.status,statusId:t.statusId,statusCategory:t.statusCategory,assignee:t.assignee}};return this.workflowEvents.record({kind:"JIRA_SOURCE_NEW_TICKET",subjectKey:`${e}:${t.key}`,dedupeKey:`jira-source-new:${e}:${t.key}:${h.cache.fetchedAt}`,payload:{...r,sessionData:r,source:{id:e,name:o.name,kind:o.kind},cursorValue:t.key}})})),h}async ticket(e,t=!1,r){let i=s8(e),a=await this.cachedCall({operation:"ISSUE",params:{issueKey:i,fields:"*all",expand:"names,schema"},requestSummary:`Issue ${i} with all fields`,force:t,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getIssue({issueIdOrKey:i,fields:["*all"],expand:["names","schema"],updateHistory:!1})}});"LIVE"===a.source&&await this.storeDetail(a.entryId,a.value,a.fetchedAt);let n=[],s=[],o=0;for(;;){let e=await this.cachedCall({operation:"COMMENTS",params:{issueKey:i,startAt:o,maxResults:100},requestSummary:`Comments for ${i} from ${o}`,force:t,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueComments.getComments({issueIdOrKey:i,startAt:o,maxResults:100,orderBy:"created"})},itemCount:e=>s3(s2(e).comments).length});n.push(e);let r=s2(e.value),a=s3(r.comments);s.push(...a);let l=s6(r.total)??s.length;if(0===a.length||s.length>=l)break;o+=a.length}let l=new Date(Math.min(...n.map(e=>e.fetchedAt.getTime())));await this.storeComments(i,s,l,n.map(e=>e.entryId));let u=await this.requireCredentials(),c=this.normalizeTicketDetail(a.value,s,u.siteUrl,oo(a),ol(n));return await this.recordTicketWorkflowEvents(c,r),c}async assignableUsers(e,t=""){let r=s8(e),i=t.trim().slice(0,100),a=await this.cachedCall({operation:"ASSIGNABLE_USERS",params:{issueKey:r,query:i,maxResults:50},requestSummary:`Assignable users for ${r}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.userSearch.findAssignableUsers({issueKey:r,query:i,maxResults:50,recommend:!0})},itemCount:e=>s3(e).length});return await this.linkCacheEntryToIssue(r,a.entryId),s3(a.value).map(oi).filter(e=>null!==e)}async ticketTransitions(e){let t=s8(e),r=await this.cachedCall({operation:"ISSUE_TRANSITIONS",params:{issueKey:t,expand:"transitions.fields"},requestSummary:`Available transitions for ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getTransitions({issueIdOrKey:t,expand:"transitions.fields"})},itemCount:e=>s3(s2(e).transitions).length});return await this.linkCacheEntryToIssue(t,r.entryId),s3(s2(r.value).transitions).map(s2).filter(e=>!1!==e.isAvailable).flatMap(e=>{let t=s4(e.id),r=s4(e.name);if(!t||!r)return[];let i=s2(e.to),a=s2(i.statusCategory),n=Object.entries(s2(e.fields)).filter(([,e])=>!0===s2(e).required).map(([e,t])=>s4(s2(t).name)??e);return[{id:t,name:r,toStatusId:s4(i.id),toStatus:s4(i.name)??r,toStatusCategory:s4(a.key)??s4(a.name),hasScreen:!0===e.hasScreen,requiredFields:n}]})}async ticketEditFields(e){let t=s8(e),r=await this.cachedCall({operation:"ISSUE_EDIT_META",params:{issueKey:t},requestSummary:`Editable fields for ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getEditIssueMeta({issueIdOrKey:t})},itemCount:e=>Object.keys(s2(s2(e).fields)).length});return await this.linkCacheEntryToIssue(t,r.entryId),Object.entries(s2(s2(r.value).fields)).map(([e,t])=>{let r=s2(t);return{id:e,name:s4(r.name)??e,required:!0===r.required,schemaType:s4(s2(r.schema).type),allowedValues:s3(r.allowedValues).flatMap(e=>{if("string"==typeof e)return[{id:e,name:e}];let t=s2(e),r=s4(t.name)??s4(t.value)??s4(t.displayName)??s4(t.key);return r?[{id:s4(t.id)??s4(t.accountId)??s4(t.value)??r,name:r}]:[]})}}).sort((e,t)=>e.name.localeCompare(t.name))}async ticketChanges(e,t=50,i=0){let a=s8(e),n=this.validatePagination(t,i),s=await this.cachedCall({operation:"ISSUE_CHANGELOG",params:{issueKey:a,startAt:0,maxResults:1},requestSummary:`Changelog count for ${a}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getChangeLogs({issueIdOrKey:a,startAt:0,maxResults:1})},itemCount:e=>s3(s2(e).values).length});await this.linkCacheEntryToIssue(a,s.entryId);let o=s6(s2(s.value).total)??0,l=Math.min(n.limit,Math.max(0,o-n.offset)),u=Math.max(0,o-n.offset-l);if(0===l)return{...n,total:o,items:[],cache:oo(s)};let c=await this.cachedCall({operation:"ISSUE_CHANGELOG",params:{issueKey:a,startAt:u,maxResults:l},requestSummary:`Changelog for ${a} from ${u}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getChangeLogs({issueIdOrKey:a,startAt:u,maxResults:l})},itemCount:e=>s3(s2(e).values).length});await this.linkCacheEntryToIssue(a,c.entryId);let d=s3(s2(c.value).values).map(s2).reverse().map(e=>({id:s4(e.id)??(0,r.randomUUID)(),author:oi(e.author),createdAt:s4(e.created),items:s3(e.items).map(s2).map(e=>({field:s4(e.field)??"Field",fieldId:s4(e.fieldId),from:s4(e.fromString)??s4(e.from),to:s4(e.toString)??s4(e.to)}))}));return{...n,total:o,items:d,cache:ol([s,c])}}async ticketWorklogs(e,t=50,i=0){let a=s8(e),n=this.validatePagination(t,i),s=await this.cachedCall({operation:"ISSUE_WORKLOGS",params:{issueKey:a,startAt:0,maxResults:1},requestSummary:`Worklog count for ${a}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueWorklogs.getIssueWorklog({issueIdOrKey:a,startAt:0,maxResults:1})},itemCount:e=>s3(s2(e).worklogs).length});await this.linkCacheEntryToIssue(a,s.entryId);let o=s6(s2(s.value).total)??0,l=Math.min(n.limit,Math.max(0,o-n.offset)),u=Math.max(0,o-n.offset-l);if(0===l)return{...n,total:o,items:[],cache:oo(s)};let c=await this.cachedCall({operation:"ISSUE_WORKLOGS",params:{issueKey:a,startAt:u,maxResults:l},requestSummary:`Worklogs for ${a} from ${u}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueWorklogs.getIssueWorklog({issueIdOrKey:a,startAt:u,maxResults:l})},itemCount:e=>s3(s2(e).worklogs).length});await this.linkCacheEntryToIssue(a,c.entryId);let d=await this.requireCredentials(),p=s3(s2(c.value).worklogs).map(s2).reverse().map(e=>({id:s4(e.id)??(0,r.randomUUID)(),author:oi(e.author),comment:sZ(e.comment??null,d.siteUrl),timeSpent:s4(e.timeSpent),timeSpentSeconds:s6(e.timeSpentSeconds),startedAt:s4(e.started),createdAt:s4(e.created),updatedAt:s4(e.updated)})),h=p[0];if(this.workflowEvents&&h){let e={ticket:{key:a},worklog:{id:h.id,author:h.author,timeSpent:h.timeSpent,timeSpentSeconds:h.timeSpentSeconds,startedAt:h.startedAt,updatedAt:h.updatedAt}};await this.workflowEvents.record({kind:"JIRA_WORKLOG_ADDED",subjectKey:a,dedupeKey:`jira-worklog:${a}:${h.id}:${c.fetchedAt}`,payload:{...e,sessionData:e,cursorValue:h.id}})}return{...n,total:o,items:p,cache:ol([s,c])}}async addComment(e,t){let r=s8(e);if(!t.value.trim())throw Error("Comment text is required");let i=sY(t);return this.mutateTicket(r,"ADD_COMMENT",async()=>{let{version3:e}=await this.getClients();await e.issueComments.addComment({issueIdOrKey:r,comment:i})})}async assignTicket(e,t){let r=s8(e),i=t?.trim()||null;return this.mutateTicket(r,"ASSIGN_ISSUE",async()=>{let{version3:e}=await this.getClients();await e.issues.assignIssue({issueIdOrKey:r,accountId:i})})}async transitionTicket(e,t){let r=s8(e),i=(await this.ticketTransitions(r)).find(e=>e.id===t);if(!i)throw Error("The Jira transition is not available");if(i.requiredFields.length>0)throw Error(`This transition requires fields that must be completed in Jira: ${i.requiredFields.join(", ")}`);return this.mutateTicket(r,"TRANSITION_ISSUE",async()=>{let{version3:e}=await this.getClients();await e.issues.doTransition({issueIdOrKey:r,transition:{id:i.id}})})}async transitionTicketToConfiguredDone(e){let t=s8(e),r=t.split("-")[0]??"",i=await (0,tD.getPrismaClient)(),a=await i.jiraProject.findUnique({where:{key:r},select:{doneStatusId:!0}});if(!a?.doneStatusId)throw Error(`Configure a done status for Jira project ${r} before using this option`);let n=await this.ticket(t);if(n.statusId===a.doneStatusId)return n;let s=(await this.ticketTransitions(t)).filter(e=>e.toStatusId===a.doneStatusId).sort((e,t)=>e.requiredFields.length-t.requiredFields.length)[0];if(!s)throw Error("Jira does not currently offer a transition to the configured done status");return this.transitionTicket(t,s.id)}async updateTicket(e){let t=s8(e.issueKey),r=new Map((await this.ticketEditFields(t)).map(e=>[e.id,e])),i={},a=e=>{let t=r.get(e);if(!t)throw Error(`${e} is not editable on this ticket`);return t},n=t=>Object.prototype.hasOwnProperty.call(e,t);if(n("summary")){a("summary");let t=e.summary?.trim();if(!t)throw Error("Ticket summary is required");i.summary=t}if(n("description")){let t=a("description");if(null===e.description){if(t.required)throw Error("Description is required");i.description=null}else e.description&&(i.description=sY(e.description))}if(n("priorityId")){let t=a("priority"),r=e.priorityId?.trim()||null;if(!r&&t.required)throw Error("Priority is required");if(r&&t.allowedValues.length>0&&!t.allowedValues.some(e=>e.id===r))throw Error("The selected priority is not available");i.priority=r?{id:r}:null}n("labels")&&(a("labels"),i.labels=[...new Set((e.labels??[]).map(e=>e.trim()).filter(Boolean))]);let s=(t,r)=>{if(!n(t))return;let s=a(r),o=[...new Set(e[t]??[])];if(s.allowedValues.length>0&&o.some(e=>!s.allowedValues.some(t=>t.id===e)))throw Error(`A selected ${s.name} value is not available`);i[r]=o.map(e=>({id:e}))};if(s("componentIds","components"),s("fixVersionIds","fixVersions"),s("affectedVersionIds","versions"),n("dueDate")){let t=a("duedate"),r=e.dueDate?.trim()||null;if(r&&!/^\d{4}-\d{2}-\d{2}$/.test(r))throw Error("Due date must use YYYY-MM-DD");if(!r&&t.required)throw Error("Due date is required");i.duedate=r}if(0===Object.keys(i).length)throw Error("At least one editable Jira field is required");return this.mutateTicket(t,"EDIT_ISSUE",async()=>{let{version3:e}=await this.getClients();await e.issues.editIssue({issueIdOrKey:t,fields:i})})}async createTicket(e){let t=e.projectKey.trim().toUpperCase(),r=e.issueTypeId.trim(),i=e.summary.trim();if(!t||!r||!i)throw Error("Project, issue type, and summary are required");let{version3:a}=await this.getClients(),n=await a.issues.createIssue({fields:{...e.fields??{},project:{key:t},issuetype:{id:r},summary:i,...e.description?{description:sY(e.description)}:{}}});if(!n.key)throw Error("Jira did not return the created issue key");return this.ticket(n.key,!0)}async addWorklog(e){let t=s8(e.issueKey);if(!Number.isInteger(e.timeSpentSeconds)||e.timeSpentSeconds<1)throw Error("Time spent must be a positive number of seconds");let{version3:r}=await this.getClients();return await r.issueWorklogs.addWorklog({issueIdOrKey:t,timeSpentSeconds:e.timeSpentSeconds,started:e.startedAt??new Date().toISOString(),...e.comment?{comment:sY(e.comment)}:{}}),this.ticket(t,!0)}async linkTickets(e){let t=s8(e.inwardIssueKey),r=s8(e.outwardIssueKey),i=e.linkType.trim();if(!i)throw Error("Jira issue link type is required");let{version3:a}=await this.getClients();return await a.issueLinks.linkIssues({type:{name:i},inwardIssue:{key:t},outwardIssue:{key:r}}),this.ticket(t,!0)}async branchTicket(e){let t=s8(e),r=t.replace(/-\d+$/,""),i=await (0,tD.getPrismaClient)(),a=await i.jiraProject.findUnique({where:{key:r},select:{key:!0,branchNamingScript:!0}});if(!a)throw Error(`Jira project ${r} is not managed; add it in Manage Jira projects and sources`);let n=await this.cachedCall({operation:"ISSUE_BRANCH",params:{issueKey:t,fields:["summary","issuetype","project"]},requestSummary:`Branch details for ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getIssue({issueIdOrKey:t,fields:["summary","issuetype","project"],updateHistory:!1})}});await this.linkCacheEntryToIssue(t,n.entryId);let s=s2(n.value.fields);if((s4(s2(s.project).key)??or(n.value))!==a.key)throw Error(`Jira ticket ${t} does not belong to project ${a.key}`);return{ticketKey:n.value.key??t,ticketTitle:s4(s.summary)??t,ticketType:s4(s2(s.issuetype).name),projectKey:a.key,branchNamingScript:a.branchNamingScript??tF}}async clearCache(){let e=await (0,tD.getPrismaClient)();return await e.$transaction([e.jiraCacheEntry.deleteMany(),e.jiraCachedTicket.deleteMany()]),!0}async clearApiCalls(){let e=await (0,tD.getPrismaClient)();return await e.jiraApiCallLog.deleteMany(),!0}async deleteCachedTicket(e){return await this.invalidateIssueCaches(s8(e)),!0}async invalidateIssueCaches(e){let t=await (0,tD.getPrismaClient)(),r=await t.jiraCacheEntryIssue.findMany({where:{issueKey:e},select:{cacheEntryId:!0}});await t.$transaction(async t=>{r.length>0&&await t.jiraCacheEntry.deleteMany({where:{id:{in:r.map(e=>e.cacheEntryId)}}}),await t.jiraCachedTicket.deleteMany({where:{issueKey:e}})})}async refreshCachedTicket(e,t){let r=await (0,tD.getPrismaClient)(),i=await r.jiraCacheEntryIssue.findMany({where:{issueKey:e},select:{cacheEntryId:!0}});return i.length>0&&await r.jiraCacheEntry.deleteMany({where:{id:{in:i.map(e=>e.cacheEntryId)}}}),this.ticket(e,!0,t)}async resolveIssueKeys(e){let t=[...new Set(e.map(e=>e.trim()).filter(Boolean))];if(0===t.length)return[];let{version3:r}=await this.getClients();return[...new Set((await Promise.all(t.map(e=>r.issues.getIssue({issueIdOrKey:e,fields:["key"]})))).map(e=>{let t=s4(e.key);if(!t)throw Error(`Jira issue ${e.id??""} has no key`);return s8(t)}))]}async refreshSprintTickets(e){if(!Number.isSafeInteger(e)||e<=0)throw Error("Invalid Jira sprint ID");let{agile:t}=await this.getClients(),r=[],i=0;for(;r.length<1e3;){let a=Math.min(100,1e3-r.length),n=await t.sprint.getIssuesForSprint({sprintId:e,startAt:i,maxResults:a,fields:["key"]}),s=n.issues??[];r.push(...s.flatMap(e=>{let t=s4(e.key);return t?[s8(t)]:[]}));let o=void 0===n.total?s.length<a:i+s.length>=n.total;if(0===s.length||o)break;i+=s.length}let a=[],n=[...new Set(r)];for(let e=0;e<n.length;e+=5)a.push(...await Promise.all(n.slice(e,e+5).map(e=>this.refreshCachedTicket(e))));return a}async listCachedTickets(e=50,t=0){let r=this.validatePagination(e,t),i=await (0,tD.getPrismaClient)(),[a,n,s]=await Promise.all([i.jiraCachedTicket.findMany({take:r.limit,skip:r.offset,orderBy:{updatedAt:"desc"}}),i.jiraCachedTicket.count(),this.getSettings()]);return{...r,total:n,items:a.map(e=>this.cachedTicketView(e,s.cacheTtlSeconds))}}async cachedTicket(e){let t=await (0,tD.getPrismaClient)(),[r,i]=await Promise.all([t.jiraCachedTicket.findUnique({where:{issueKey:e},include:{cacheEntries:{include:{cacheEntry:!0}}}}),this.getSettings()]);return r?{...this.cachedTicketView(r,i.cacheTtlSeconds),summaryData:s5(r.summaryJson),detailData:s5(r.detailJson),commentsData:s5(r.commentsJson),cacheEntries:r.cacheEntries.map(e=>({id:e.cacheEntry.id,operation:e.cacheEntry.operation,fetchedAt:e.cacheEntry.fetchedAt.toISOString()})).sort((e,t)=>t.fetchedAt.localeCompare(e.fetchedAt))}:null}async listApiCalls(e=50,t=0){let r=this.validatePagination(e,t);await this.pruneLogs();let i=await (0,tD.getPrismaClient)(),[a,n]=await Promise.all([i.jiraApiCallLog.findMany({take:r.limit,skip:r.offset,orderBy:{createdAt:"desc"}}),i.jiraApiCallLog.count()]);return{...r,total:n,items:a.map(e=>({id:e.id,operation:e.operation,requestSummary:e.requestSummary,source:e.source,durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,itemCount:e.itemCount,servedStale:e.servedStale,createdAt:e.createdAt.toISOString()}))}}async cacheMetrics(){await this.pruneLogs();let e=await (0,tD.getPrismaClient)(),t=Date.now(),r=await e.jiraApiCallLog.findMany({where:{createdAt:{gte:new Date(t-s0.at(-1).milliseconds)}},orderBy:{createdAt:"asc"}});return{windows:s0.map(e=>this.metricWindow(e.window,r.filter(r=>r.createdAt.getTime()>=t-e.milliseconds))),operations:[...new Set(r.map(e=>e.operation))].sort().map(e=>({operation:e,windows:s0.map(i=>this.metricWindow(i.window,r.filter(r=>r.operation===e&&r.createdAt.getTime()>=t-i.milliseconds)))}))}}async requireCredentials(){let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:sQ}});if(!t?.siteUrl||!t.email)throw Error("Configure the Jira site, email, and API token in Settings first");let r=await this.credentials.getText(tN.CREDENTIALS.jiraApiToken);if(!r)throw Error("Configure the Jira site, email, and API token in Settings first");return{siteUrl:t.siteUrl,email:t.email,apiToken:r,cacheTtlSeconds:t.cacheTtlSeconds}}async getClients(){let e=await this.requireCredentials(),t=(0,r.createHash)("sha256").update(`${e.siteUrl}\0${e.email}\0${e.apiToken}`).digest("hex");if(this.clients?.key===t)return this.clients;let i={host:e.siteUrl,authentication:{basic:{email:e.email,apiToken:e.apiToken}},baseRequestConfig:{timeout:15e3}};return this.clients={key:t,version3:new tT(i),agile:new q(i)},this.clients}async webhookApiRequest(e,t,r){let i,a=await this.requireCredentials(),n=Buffer.from(`${a.email}:${a.apiToken}`).toString("base64");try{i=await fetch(`${a.siteUrl}${t}`,{method:e,headers:{Accept:"application/json",Authorization:`Basic ${n}`,"Content-Type":"application/json"},body:void 0===r?void 0:JSON.stringify(r),signal:AbortSignal.timeout(15e3)})}catch(e){throw Error(ot(e,a.apiToken))}let s=await i.text();if(!i.ok){let e=s.trim().slice(0,300)||i.statusText;throw Object.assign(Error(ot(`Jira rejected the webhook request with ${i.status}: ${e}`,a.apiToken)),{status:i.status})}if(!s.trim())return null;try{return JSON.parse(s)}catch{return null}}async currentAccountId(){let e=s4(s2((await this.cachedCall({operation:"MYSELF",params:{},requestSummary:"Current Jira user",fetcher:async()=>{let{version3:e}=await this.getClients();return e.myself.getCurrentUser()}})).value).accountId);if(!e)throw Error("Jira did not return the current user ID");return e}async linkCacheEntryToIssue(e,t){let r=await (0,tD.getPrismaClient)();await r.$transaction(async r=>{await r.jiraCachedTicket.upsert({where:{issueKey:e},create:{issueKey:e,projectKey:e.replace(/-\d+$/,"")},update:{}}),await r.jiraCacheEntryIssue.upsert({where:{cacheEntryId_issueKey:{cacheEntryId:t,issueKey:e}},create:{cacheEntryId:t,issueKey:e},update:{}})})}async mutateTicket(e,t,r){let i=await this.requireCredentials(),a=Date.now();try{await r(),await this.logCall({operation:t,requestSummary:`${t.replaceAll("_"," ")} for ${e}`,source:"LIVE",durationMs:Date.now()-a})}catch(n){let r=ot(n,i.apiToken);throw await this.logCall({operation:t,requestSummary:`${t.replaceAll("_"," ")} for ${e}`,source:"ERROR",durationMs:Date.now()-a,statusCode:oe(n),error:r}),Error(r)}await this.invalidateIssueCaches(e);try{return await this.ticket(e,!0)}catch(e){throw Error(`Jira accepted the update, but refreshed ticket details could not be loaded: ${ot(e,i.apiToken)}`)}}cacheKey(e,t,i){return(0,r.createHash)("sha256").update(s7({siteUrl:e,operation:t,params:i})).digest("hex")}async cachedCall(e){let t=await this.requireCredentials(),i=await (0,tD.getPrismaClient)(),a=this.cacheKey(t.siteUrl,e.operation,e.params),n=Date.now(),s=await i.jiraCacheEntry.findUnique({where:{cacheKey:a}}),o=null!==s&&Date.now()-s.fetchedAt.getTime()<1e3*t.cacheTtlSeconds;if(!e.force&&o)return await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"CACHE",durationMs:Date.now()-n,itemCount:e.itemCount?.(s5(s.responseJson))??null,sourceId:e.sourceId}),{value:s5(s.responseJson),source:"CACHE",stale:!1,fetchedAt:s.fetchedAt,entryId:s.id};let l=this.inFlight.get(a);if(l){let t=await l;return await this.logCall({operation:e.operation,requestSummary:`${e.requestSummary} (coalesced)`,source:"CACHE",durationMs:Date.now()-n,itemCount:e.itemCount?.(t.value)??null,sourceId:e.sourceId}),{...t,source:"CACHE"}}let u=(async()=>{try{let t=await e.fetcher(),s=new Date,o=await i.jiraCacheEntry.upsert({where:{cacheKey:a},create:{id:(0,r.randomUUID)(),cacheKey:a,operation:e.operation,paramsJson:s7(e.params),responseJson:JSON.stringify(t),fetchedAt:s,sourceId:e.sourceId??null},update:{operation:e.operation,paramsJson:s7(e.params),responseJson:JSON.stringify(t),fetchedAt:s,sourceId:e.sourceId??null}});return await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"LIVE",durationMs:Date.now()-n,itemCount:e.itemCount?.(t)??null,sourceId:e.sourceId}),{value:t,source:"LIVE",stale:!1,fetchedAt:s,entryId:o.id}}catch(i){let r=null!==s&&!1!==e.allowStaleOnError;if(await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"ERROR",durationMs:Date.now()-n,statusCode:oe(i),error:ot(i,t.apiToken),servedStale:r,sourceId:e.sourceId}),r)return{value:s5(s.responseJson),source:"ERROR",stale:!0,fetchedAt:s.fetchedAt,entryId:s.id};throw Error(ot(i,t.apiToken))}})();this.inFlight.set(a,u);try{return await u}finally{this.inFlight.delete(a)}}async logCall(e){let t=await (0,tD.getPrismaClient)();await t.jiraApiCallLog.create({data:{id:(0,r.randomUUID)(),operation:e.operation,requestSummary:e.requestSummary.slice(0,1e3),source:e.source,durationMs:Math.max(0,Math.round(e.durationMs)),statusCode:e.statusCode??null,error:e.error??null,itemCount:e.itemCount??null,servedStale:e.servedStale??!1,sourceId:e.sourceId??null}})}validateSourceName(e){let t=e.trim();if(!t||t.length>100)throw Error("Source name must be 1 to 100 characters");return t}async validateSource(e,t){let r=t.trim();if(!r)throw Error("BOARD"===e?"Board URL is required":"JQL is required");if("JQL"===e)return await this.cachedCall({operation:"JQL_VALIDATE",params:{jql:r},requestSummary:`Validate JQL: ${r}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueSearch.searchForIssuesUsingJqlEnhancedSearch({jql:r,maxResults:1,fields:["key"],failFast:!0})}}),{value:r,boardId:null};let i=function(e,t){let r=new URL(e.trim());if(r.origin!==new URL(t).origin)throw Error("Board URL must belong to the configured Jira site");let i=r.pathname.match(/\/boards\/(\d+)(?:\/|$)/i),a=r.searchParams.get("rapidView"),n=Number(i?.[1]??a);if(!Number.isSafeInteger(n)||n<=0)throw Error("Board URL must contain a Jira board ID");return{boardId:n,normalizedUrl:r.toString()}}(r,(await this.requireCredentials()).siteUrl);return await this.cachedCall({operation:"BOARD",params:{boardId:i.boardId},requestSummary:`Board ${i.boardId}`,fetcher:async()=>{let{agile:e}=await this.getClients();return e.board.getBoard({boardId:i.boardId})}}),{value:i.normalizedUrl,boardId:i.boardId}}async loadJqlSource(e,t){let r,i=[],a=[],n=[],s=!1;do{let o=Math.min(100,1e3-i.length),l=await this.cachedCall({operation:"JQL_SEARCH",params:{jql:e.value,nextPageToken:r??null,maxResults:o,fields:sX},requestSummary:`JQL ${e.name}${r?" next page":""}`,sourceId:e.id,force:t,fetcher:async()=>{let{version3:t}=await this.getClients();return t.issueSearch.searchForIssuesUsingJqlEnhancedSearch({jql:e.value,nextPageToken:r,maxResults:o,fields:sX})},itemCount:e=>e.issues?.length??0});a.push(l);let u=l.value.issues??[];i.push(...u),n.push(...l.value.warningMessages??[]),"LIVE"===l.source&&await this.storeSummaries(l.entryId,u,l.fetchedAt),r=l.value.nextPageToken,i.length>=1e3&&r&&(s=!0)}while(r&&i.length<1e3)return this.buildBoardResult(i,a,n,s)}async loadBoardSource(e,t){if(!e.boardId)throw Error("Saved board source has no board ID");let r=await this.cachedCall({operation:"BOARD",params:{boardId:e.boardId},requestSummary:`Board ${e.boardId}`,sourceId:e.id,force:t,fetcher:async()=>{let{agile:t}=await this.getClients();return t.board.getBoard({boardId:e.boardId})}}),i=await this.cachedCall({operation:"BOARD_CONFIGURATION",params:{boardId:e.boardId},requestSummary:`Board ${e.boardId} configuration`,sourceId:e.id,force:t,fetcher:async()=>{let{agile:t}=await this.getClients();return t.board.getConfiguration({boardId:e.boardId})}}),a=[r,i],n=[],s=[],o=!1;if("scrum"===(s4(r.value.type)??"").toLowerCase()){let r=await this.cachedCall({operation:"SPRINTS",params:{boardId:e.boardId,state:"active"},requestSummary:`Active sprints for board ${e.boardId}`,sourceId:e.id,force:t,fetcher:async()=>{let{agile:t}=await this.getClients();return t.board.getAllSprints({boardId:e.boardId,state:"active",startAt:0,maxResults:100})},itemCount:e=>s3(e.values).length});a.push(r);let i=s3(r.value.values).map(s2);for(let r of(0===i.length&&s.push("This Scrum board has no active sprint."),i)){let i=s6(r.id);if(!i||n.length>=1e3)continue;let l=await this.loadAgileIssues("SPRINT_ISSUES",e,t,(e,t)=>({sprintId:i,startAt:e,maxResults:t,fields:sX}),async e=>{let{agile:t}=await this.getClients();return t.sprint.getIssuesForSprint(e)},n.length);n.push(...l.issues),a.push(...l.results),s.push(...l.warnings),o||=l.truncated}}else{let r=await this.loadAgileIssues("BOARD_ISSUES",e,t,(t,r)=>({boardId:e.boardId,startAt:t,maxResults:r,fields:sX}),async e=>{let{agile:t}=await this.getClients();return t.board.getIssuesForBoard(e)},0);n.push(...r.issues),a.push(...r.results),s.push(...r.warnings),o=r.truncated}let l=[...new Map(n.map(e=>[e.key??e.id,e])).values()],u=new Map;return s3(s2(i.value.columnConfig).columns).map(s2).forEach((e,t)=>{s3(e.statuses).map(s2).forEach(e=>{let r=s4(e.id);r&&u.set(r,t)})}),this.buildBoardResult(l,a,s,o,u)}async loadAgileIssues(e,t,r,i,a,n){let s=[],o=[],l=[],u=0,c=1/0,d=!1;for(;u<c&&s.length+n<1e3;){let d=i(u,Math.min(100,1e3-n-s.length)),p=await this.cachedCall({operation:e,params:d,requestSummary:`${e.replaceAll("_"," ")} from ${u}`,sourceId:t.id,force:r,fetcher:()=>a(d),itemCount:e=>e.issues?.length??0});o.push(p);let h=p.value.issues??[];if(s.push(...h),l.push(...p.value.warningMessages??[]),"LIVE"===p.source&&await this.storeSummaries(p.entryId,h,p.fetchedAt),c=p.value.total??s.length,0===h.length)break;u+=h.length}return s.length+n>=1e3&&u<c&&(d=!0),{issues:s,results:o,warnings:l,truncated:d}}buildBoardResult(e,t,r,i,a){let n=e.slice(0,1e3).map(ou),s=[...new Map(n.map(e=>[e.status,e])).values()];return s.sort((e,t)=>{let r=a?.get(e.statusId),i=a?.get(t.statusId);return void 0!==r||void 0!==i?(r??Number.MAX_SAFE_INTEGER)-(i??Number.MAX_SAFE_INTEGER):oc(e.statusCategory)-oc(t.statusCategory)||e.status.localeCompare(t.status)}),{tickets:n,statusOrder:s.map(e=>e.status),cache:ol(t),truncated:i,warnings:[...new Set(r)]}}async storeSummaries(e,t,r){let i=await (0,tD.getPrismaClient)();await i.$transaction(async i=>{for(let e of t)e.key&&await i.jiraCachedTicket.upsert({where:{issueKey:e.key},create:{issueKey:e.key,projectKey:or(e),summaryJson:JSON.stringify(e),summaryFetchedAt:r},update:{projectKey:or(e),summaryJson:JSON.stringify(e),summaryFetchedAt:r}});await i.jiraCacheEntryIssue.deleteMany({where:{cacheEntryId:e}});let a=[...new Set(t.map(e=>e.key).filter(Boolean))];a.length>0&&await i.jiraCacheEntryIssue.createMany({data:a.map(t=>({cacheEntryId:e,issueKey:t}))})})}async storeDetail(e,t,r){if(!t.key)throw Error("Jira detail response did not include an issue key");let i=await (0,tD.getPrismaClient)();await i.$transaction(async i=>{await i.jiraCachedTicket.upsert({where:{issueKey:t.key},create:{issueKey:t.key,projectKey:or(t),detailJson:JSON.stringify(t),detailFetchedAt:r},update:{projectKey:or(t),detailJson:JSON.stringify(t),detailFetchedAt:r}}),await i.jiraCacheEntryIssue.upsert({where:{cacheEntryId_issueKey:{cacheEntryId:e,issueKey:t.key}},create:{cacheEntryId:e,issueKey:t.key},update:{}})})}async storeComments(e,t,r,i){let a=await (0,tD.getPrismaClient)();await a.$transaction(async a=>{for(let n of(await a.jiraCachedTicket.upsert({where:{issueKey:e},create:{issueKey:e,projectKey:e.split("-")[0]??"UNKNOWN",commentsJson:JSON.stringify(t),commentsFetchedAt:r},update:{commentsJson:JSON.stringify(t),commentsFetchedAt:r}}),i))await a.jiraCacheEntryIssue.upsert({where:{cacheEntryId_issueKey:{cacheEntryId:n,issueKey:e}},create:{cacheEntryId:n,issueKey:e},update:{}})})}normalizeTicketDetail(e,t,i,a,n){let s=ou(e),o=s2(e.fields),l=s2(e.names),u=s2(e.schema),c=[];for(let e of s3(o.issuelinks).map(s2)){let t=s2(e.type),r=on(e.outwardIssue,s4(t.outward)??"relates to"),i=on(e.inwardIssue,s4(t.inward)??"relates to");r&&c.push(r),i&&c.push(i)}let d=on(o.parent,"parent"),p=s3(o.subtasks).map(e=>on(e,"subtask")).filter(e=>null!==e),h=s3(o.sprint).map(s2),m=s3(o.closedSprints).map(s2),f=h.filter(e=>{let t=s4(e.state)?.toLowerCase();return!t||"active"===t}).map(e=>s4(e.name)).filter(e=>!!e),g=m.concat(h.filter(e=>s4(e.state)?.toLowerCase()==="closed")).map(e=>s4(e.name)).filter(e=>!!e),y=f.concat(g),w=t.map(s2).map(e=>({id:s4(e.id)??(0,r.randomUUID)(),author:oi(e.author),body:e.body??null,content:sZ(e.body??null,i),createdAt:s4(e.created),updatedAt:s4(e.updated)}));return{...s,jiraUrl:`${i}/browse/${s.key}`,description:o.description??null,descriptionContent:sZ(o.description??null,i),reporter:oi(o.reporter),creator:oi(o.creator),labels:s3(o.labels).filter(e=>"string"==typeof e),components:oa(o.components),fixVersions:oa(o.fixVersions),affectedVersions:oa(o.versions),sprintNames:[...new Set(y)],activeSprintNames:[...new Set(f)],closedSprintNames:[...new Set(g)],parent:d,subtasks:p,issueLinks:c,attachments:s3(o.attachment).map(s2).map(e=>({id:s4(e.id)??(0,r.randomUUID)(),filename:s4(e.filename)??"Attachment",contentUrl:s4(e.content),mimeType:s4(e.mimeType),size:s6(e.size),author:oi(e.author),createdAt:s4(e.created)})),comments:w,createdAt:s4(o.created),dueAt:s4(o.duedate),resolvedAt:s4(o.resolutiondate),timeTracking:o.timetracking??null,allFields:Object.entries(o).map(([e,t])=>{let r=s2(u[e]),a="string"==typeof t||s1(t)&&"doc"===t.type?sZ(t,i):null;return{id:e,name:s4(l[e])??e,schemaType:s4(r.type),custom:!0===r.custom||e.startsWith("customfield_"),value:t??null,content:a}}).sort((e,t)=>e.name.localeCompare(t.name)),cache:a,commentsCache:n}}cachedTicketView(e,t){let r=ou(s2(s5(e.detailJson)??s5(e.summaryJson))),i=e.detailJson&&e.commentsJson?"FULL":e.detailJson?"DETAIL":"SUMMARY",a=[e.summaryFetchedAt,e.detailFetchedAt,e.commentsFetchedAt].filter(e=>null!==e).some(e=>Date.now()-e.getTime()>=1e3*t);return{issueKey:e.issueKey,projectKey:e.projectKey,summary:r.summary,status:"Unknown"===r.status?null:r.status,coverage:i,stale:a,summaryFetchedAt:e.summaryFetchedAt?.toISOString()??null,detailFetchedAt:e.detailFetchedAt?.toISOString()??null,commentsFetchedAt:e.commentsFetchedAt?.toISOString()??null,updatedAt:e.updatedAt.toISOString()}}validatePagination(e,t){if(!Number.isInteger(e)||e<1||e>100)throw Error("Pagination limit must be from 1 to 100");if(!Number.isInteger(t)||t<0)throw Error("Pagination offset must be non-negative");return{limit:e,offset:t}}metricWindow(e,t){return{window:e,total:t.length,live:t.filter(e=>"LIVE"===e.source).length,cache:t.filter(e=>"CACHE"===e.source).length,errors:t.filter(e=>"ERROR"===e.source).length,averageMs:0===t.length?0:Math.round(t.reduce((e,t)=>e+t.durationMs,0)/t.length)}}async pruneLogs(){let e=Date.now();if(e-this.lastPrunedAt<36e5)return;this.lastPrunedAt=e;let t=await (0,tD.getPrismaClient)();await t.jiraApiCallLog.deleteMany({where:{createdAt:{lt:new Date(e-2592e6)}}})}}],126223);var oh=e.i(661983);let om="default",of=/^[A-Z][A-Z0-9_]*-\d+$/,og=new Set(["jira:issue_created","jira:issue_updated","comment_created","comment_updated","comment_deleted","worklog_created","worklog_updated","worklog_deleted","jira:worklog_updated","attachment_created","attachment_deleted","issuelink_created","issuelink_deleted","sprint_started","sprint_closed"]),oy={"jira:issue_created":"JIRA_ISSUE_CREATED","jira:issue_deleted":"JIRA_ISSUE_DELETED",comment_created:"JIRA_ISSUE_COMMAND",attachment_created:"JIRA_ATTACHMENT_ADDED",issuelink_created:"JIRA_ISSUE_LINKED"},ow="/api/public/jira/webhook",ob="/rest/webhooks/1.0/webhook",ov=new Set(["localhost","0.0.0.0","::1","[::1]",""]),ok=["jira:issue_created","jira:issue_updated","jira:issue_deleted","comment_created","worklog_created","attachment_created","issuelink_created","sprint_started","sprint_closed"];class oS extends Error{httpStatus;constructor(e,t){super(e),this.httpStatus=t,this.name="JiraWebhookRequestError"}}function oE(e){return"string"==typeof e&&e.trim()?e.trim():null}function oI(e){return"string"==typeof e?e.length?e:null:"number"==typeof e||"boolean"==typeof e?String(e):null}function ox(e){let t=oA(e);if(!t)return null;let r=Array.isArray(t.items)?t.items:[];return{id:oI(t.id),items:r.map(oA).filter(e=>null!==e).map(e=>({field:oE(e.field)??oE(e.fieldId)??"Field",fieldId:oE(e.fieldId),fieldType:oE(e.fieldtype)??oE(e.fieldType),from:oI(e.from),fromString:oI(e.fromString),to:oI(e.to),toString:oI(e.toString)}))}}function oA(e){return"object"!=typeof e||null===e||Array.isArray(e)?null:e}function o_(e){return"object"==typeof e&&null!==e&&"status"in e&&"number"==typeof e.status?e.status:null}function oC(e){let t=oA(e);return t?{accountId:oE(t.accountId),displayName:oE(t.displayName)}:null}function oR(e){return{deliveryId:e.deliveryId,event:e.event,issueKey:e.issueKey,projectKey:e.projectKey,changelog:function(e){if(!e)return null;try{return ox(JSON.parse(e))}catch{return null}}(e.changelogJson),retryCount:e.retryCount,outcome:e.outcome,error:e.error,receivedAt:e.receivedAt.toISOString(),processedAt:e.processedAt?.toISOString()??null}}e.s(["JiraWebhookRequestError",0,oS,"JiraWebhookService",0,class{jira;credentials;workflowEvents;constructor(e,t,r){this.jira=e,this.credentials=t,this.workflowEvents=r}async webhooksEnabled(){let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:om},select:{webhookEnabled:!0}});return!!t?.webhookEnabled&&this.credentials.isConfigured(tN.CREDENTIALS.jiraWebhookSecret)}async getWebhookSettings(){let e=await (0,tD.getPrismaClient)(),[t,r,i]=await Promise.all([e.jiraSettings.upsert({where:{id:om},create:{id:om},update:{}}),this.credentials.isConfigured(tN.CREDENTIALS.jiraWebhookSecret),e.jiraWebhookDelivery.findFirst({orderBy:[{receivedAt:"desc"},{deliveryId:"desc"}]})]);return{enabled:t.webhookEnabled&&r,secretConfigured:r,registered:!!t.webhookId,registrationId:t.webhookId??null,registeredUrl:t.webhookUrl??null,jql:t.webhookJql??null,configuredAt:t.webhookConfiguredAt?.toISOString()??null,lastReceivedAt:i?.receivedAt.toISOString()??null,lastOutcome:i?.outcome??null,lastError:i?.error??null}}async enableWebhook(){let e=(0,r.randomBytes)(32).toString("base64url");return await this.credentials.setText(tN.CREDENTIALS.jiraWebhookSecret,e,async e=>{await e.jiraSettings.upsert({where:{id:om},create:{id:om,webhookEnabled:!0,webhookConfiguredAt:new Date},update:{webhookEnabled:!0,webhookConfiguredAt:new Date}})}),{settings:await this.getWebhookSettings(),secret:e}}async registerWebhook(e){let t=function(e){let t;try{t=new URL(e.trim())}catch{throw Error("Enter the public URL of this server")}if("https:"!==t.protocol&&"http:"!==t.protocol)throw Error("The webhook URL must use HTTP or HTTPS");if(t.username||t.password||t.search||t.hash)throw Error("The webhook URL must not include credentials, query, or fragment");let r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(ov.has(r)||r.endsWith(".local")||r.endsWith(".localhost")||/^127\./.test(r)||/^10\./.test(r)||/^192\.168\./.test(r)||/^172\.(1[6-9]|2\d|3[01])\./.test(r))throw Error(`Jira cannot reach ${t.host}. Expose this server publicly, or set PUBLIC_BASE_URL to its public address.`);let i=t.pathname.replace(/\/+$/,"");if(!i)return`${t.origin}${ow}`;if(i.endsWith(ow))return`${t.origin}${i}`;throw Error(`The webhook URL must end with ${ow}`)}(e.url),i=e.jql?.trim()||null,a=(0,r.randomBytes)(32).toString("base64url"),n=await (0,tD.getPrismaClient)(),s=await n.jiraSettings.findUnique({where:{id:om},select:{webhookId:!0}}),o=await this.writeToJira({webhookId:s?.webhookId??null,url:t,jql:i,secret:a});return await this.credentials.setText(tN.CREDENTIALS.jiraWebhookSecret,a,async e=>{await e.jiraSettings.upsert({where:{id:om},create:{id:om,webhookEnabled:!0,webhookConfiguredAt:new Date,webhookId:o,webhookUrl:t,webhookJql:i},update:{webhookEnabled:!0,webhookConfiguredAt:new Date,webhookId:o,webhookUrl:t,webhookJql:i}})}),{settings:await this.getWebhookSettings(),secret:a}}async rotateSecret(){if(!await this.credentials.isConfigured(tN.CREDENTIALS.jiraWebhookSecret))throw Error("The Jira webhook is not configured");let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:om},select:{webhookId:!0,webhookUrl:!0,webhookJql:!0}});return t?.webhookId&&t.webhookUrl?this.registerWebhook({url:t.webhookUrl,jql:t.webhookJql}):this.enableWebhook()}async disableWebhook(){let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:om},select:{webhookId:!0}});return t?.webhookId&&await this.deleteFromJira(t.webhookId),await this.credentials.delete(tN.CREDENTIALS.jiraWebhookSecret,async e=>{await e.jiraSettings.upsert({where:{id:om},create:{id:om},update:{webhookEnabled:!1,webhookConfiguredAt:null,webhookId:null,webhookUrl:null,webhookJql:null}})}),this.getWebhookSettings()}async writeToJira(e){let t,r,i={name:"AI Development Environment",description:"Registered by AI Development Environment. Drives Jira workflow triggers and live ticket updates.",url:e.url,events:[...ok],excludeBody:!1,secret:e.secret,...e.jql?{filters:{"issue-related-events-section":e.jql}}:{}};if(e.webhookId){let t=`${ob}/${encodeURIComponent(e.webhookId)}`;try{return await this.jira.webhookApiRequest("PUT",t,i),e.webhookId}catch(e){if(404!==o_(e))throw e}}let a=await this.jira.webhookApiRequest("POST",ob,i),n=(t=oE(a?.self),(r=t?.match(/\/webhook\/([^/]+)\/?$/)?.[1])?decodeURIComponent(r):null);if(!n)throw Error("Jira did not return the ID of the new webhook");return n}async deleteFromJira(e){try{await this.jira.webhookApiRequest("DELETE",`${ob}/${encodeURIComponent(e)}`)}catch(e){if(404!==o_(e))throw e}}async deliveries(e=50,t=0){if(!Number.isInteger(e)||e<1||e>100)throw Error("Limit must be an integer from 1 to 100");if(!Number.isInteger(t)||t<0)throw Error("Offset must be a non-negative integer");let r=await this.webhooksEnabled();if(!r)return{enabled:r,items:[],total:0,limit:e,offset:t};let i=await (0,tD.getPrismaClient)(),[a,n]=await Promise.all([i.jiraWebhookDelivery.findMany({orderBy:[{receivedAt:"desc"},{deliveryId:"desc"}],take:e,skip:t}),i.jiraWebhookDelivery.count()]);return{enabled:r,items:a.map(oR),total:n,limit:e,offset:t}}async clearDeliveries(){let e=await (0,tD.getPrismaClient)();return await e.jiraWebhookDelivery.deleteMany(),!0}async prune(){let e=await (0,tD.getPrismaClient)();await e.jiraWebhookDelivery.deleteMany({where:{receivedAt:{lt:new Date(Date.now()-2592e6)}}})}async handleWebhook(e){var t,i,a,n,s,o;let l,u,c=await this.credentials.getText(tN.CREDENTIALS.jiraWebhookSecret);if(!c)throw new oS("Jira webhook is not configured",503);if(!e.signature?.startsWith("sha256="))throw new oS("Jira webhook signature is missing",401);if(t=`sha256=${(0,r.createHmac)("sha256",c).update(e.body).digest("hex")}`,i=e.signature,l=Buffer.from(t),u=Buffer.from(i),!(l.length===u.length&&(0,r.timingSafeEqual)(l,u)))throw new oS("Jira webhook signature is invalid",401);if(!e.deliveryId?.trim())throw new oS("Jira delivery ID is missing",400);let d=await (0,tD.getPrismaClient)(),p=e.deliveryId.trim(),h=Number.parseInt(e.retryCount??"",10),m=Number.isInteger(h)?h:null;try{await d.jiraWebhookDelivery.create({data:{deliveryId:p,event:"unknown",outcome:"RECEIVED",retryCount:m}})}catch(e){if(!("object"==typeof e&&null!==e&&"code"in e&&"P2002"===e.code))throw e;if(0===(await d.jiraWebhookDelivery.updateMany({where:{deliveryId:p,outcome:{notIn:["PROCESSED","IGNORED"]}},data:{event:"unknown",issueKey:null,projectKey:null,changelogJson:null,retryCount:m,outcome:"RECEIVED",error:null,receivedAt:new Date,processedAt:null}})).count)return await this.prune().catch(()=>void 0),{outcome:"DUPLICATE",event:null,issueKey:null,triggersRecorded:0}}let f=async(e,t=null)=>{let r=await d.jiraWebhookDelivery.update({where:{deliveryId:p},data:{outcome:e,error:t,processedAt:new Date}});oh.agentEventBus.publish(oh.JIRA_WEBHOOK_DELIVERY_TOPIC,{jiraWebhookDeliveryChanged:oR(r)})};try{let t,r,i,l,u,c;try{let r=JSON.parse(Buffer.from(e.body).toString("utf8")),i=oA(r);if(!i)throw Error("Payload is not an object");t=i}catch{throw new oS("Jira webhook payload is invalid JSON",400)}let h=oE(t.webhookEvent),g=(a=t,r=oA(a.issue),(i=oE(r?.key)?.toUpperCase()??null)&&of.test(i)?i:null),y=(n=t,l=oA(n.issue),u=oA(l?.fields),c=oA(u?.project)??oA(n.project),oE(c?.key)?.toUpperCase()??null),w=ox(t.changelog);if(await d.jiraWebhookDelivery.update({where:{deliveryId:p},data:{event:h??"unknown",issueKey:g,projectKey:y,changelogJson:w?JSON.stringify(w):null}}),!h)return await f("IGNORED","Payload has no webhookEvent"),{outcome:"IGNORED",event:h,issueKey:g,triggersRecorded:0};if(!(og.has(h)||"jira:issue_deleted"===h))return await f("IGNORED",`Unhandled Jira event ${h}`),{outcome:"IGNORED",event:h,issueKey:g,triggersRecorded:0};let b=g?[g]:[];if("issuelink_created"===h||"issuelink_deleted"===h){let e,r,i=(s=t,e=oA(s.issueLink),[oI(e?.sourceIssueId),oI(e?.destinationIssueId)].filter((e,t,r)=>!!(e&&r.indexOf(e)===t)));if(0===i.length)return await f("IGNORED","Payload has no issue-link issue IDs"),{outcome:"IGNORED",event:h,issueKey:g,triggersRecorded:0};y=(g=(b=await this.jira.resolveIssueKeys(i))[0]??null)?y??((r=(o=g).lastIndexOf("-"))>0?o.slice(0,r):null):y,await d.jiraWebhookDelivery.update({where:{deliveryId:p},data:{issueKey:g,projectKey:y}})}let v="sprint_started"===h||"sprint_closed"===h;if(!v&&!g)return await f("IGNORED","Payload has no issue key"),{outcome:"IGNORED",event:h,issueKey:g,triggersRecorded:0};let k=[];if("jira:issue_deleted"===h)await this.jira.deleteCachedTicket(g),k.push({key:g,projectKey:y});else if(v){let e=function(e){let t=oI(oA(e.sprint)?.id);if(!t)return null;let r=Number(t);return Number.isSafeInteger(r)&&r>0?r:null}(t);if(!e)return await f("IGNORED","Payload has no valid sprint ID"),{outcome:"IGNORED",event:h,issueKey:g,triggersRecorded:0};let r=await this.jira.refreshSprintTickets(e);k.push(...r.map(e=>({key:e.key,projectKey:e.projectKey})))}else if("jira:issue_updated"===h){let e=await this.jira.refreshCachedTicket(g,w);k.push({key:e.key,projectKey:e.projectKey})}else if(og.has(h)){let e=await Promise.all(b.map(e=>this.jira.refreshCachedTicket(e)));k.push(...e.map(e=>({key:e.key,projectKey:e.projectKey})))}let S=g?await this.recordWebhookTrigger({event:h,deliveryId:p,issueKey:g,projectKey:y,retries:m,payload:t}):0;for(let e of k)oh.agentEventBus.publish(oh.JIRA_TICKET_CHANGED_TOPIC,{jiraTicketChanged:{issueKey:e.key,projectKey:e.projectKey,event:h}});return await f("PROCESSED"),{outcome:"PROCESSED",event:h,issueKey:g,triggersRecorded:S}}catch(t){let e=t instanceof Error?t.message:String(t);throw await f("ERROR",e),t}finally{await this.prune().catch(()=>void 0)}}async recordWebhookTrigger(e){if(!this.workflowEvents)return 0;let t=oy[e.event];if(!t)return 0;let{payload:r}=e,i=oA(r.issue),a=oA(i?.fields),n=oA(r.comment),s=oA(r.attachment),o=oA(r.issueLink),l=oA(a?.status),u=ox(r.changelog),c={ticket:{key:e.issueKey,title:oE(a?.summary),type:oE(oA(a?.issuetype)?.name),status:oE(l?.name),statusId:oE(l?.id),statusCategory:oE(oA(l?.statusCategory)?.key),assignee:oE(oA(a?.assignee)?.displayName),assigneeAccountId:oE(oA(a?.assignee)?.accountId),labels:Array.isArray(a?.labels)?a.labels:[],projectKey:e.projectKey,url:null},comment:n?{id:oE(n.id),body:oE(n.body)??"",author:oC(n.author)}:null,attachment:s?{id:oE(s.id),filename:oE(s.filename),mimeType:oE(s.mimeType),author:oC(s.author)}:null,link:o?{id:oE(o.id),type:oE(oA(o.issueLinkType)?.name),sourceIssueId:oE(o.sourceIssueId),destinationIssueId:oE(o.destinationIssueId)}:null,user:oC(r.user),changelog:u};return+!!await this.workflowEvents.record({kind:t,subjectKey:e.issueKey,dedupeKey:`jira-webhook-trigger:${e.deliveryId}:${t}`,payload:{...c,sessionData:c,cursorValue:`${e.deliveryId}:${t}`,webhook:{event:e.event,deliveryId:e.deliveryId,retryCount:e.retries}}})}},"subscribeJiraTicketChanges",0,function(){return oh.agentEventBus.iterate(oh.JIRA_TICKET_CHANGED_TOPIC)},"subscribeJiraWebhookDeliveries",0,function(){return oh.agentEventBus.iterate(oh.JIRA_WEBHOOK_DELIVERY_TOPIC)}],642983),e.s([],151666)},984179,e=>{"use strict";let t=new Set(["QUEUED","PREPARING","RUNNING"]);e.s(["buildOutOfDate",0,function(e){let r;if(t.has(e.status)||!e.worktree||(e.worktree._count?.builds??0)>0||e.finishedAt&&(!e.worktree.lastCheckedAt||e.worktree.lastCheckedAt<e.finishedAt))return!1;try{r=JSON.parse(e.snapshotJson)}catch{return!1}if(!r||"object"!=typeof r||Array.isArray(r))return!1;let i=r.worktree;if(!i||"object"!=typeof i||Array.isArray(i))return!1;if("string"==typeof i.codeStateHash&&e.worktree.codeStateHash)return i.codeStateHash!==e.worktree.codeStateHash;if("string"==typeof i.headSha&&e.worktree.headSha!==i.headSha)return!0;if("boolean"==typeof i.hasStagedChanges){if(i.hasStagedChanges!==e.worktree.hasStagedChanges)return!0}else if(e.worktree.hasStagedChanges)return!0;return"boolean"==typeof i.hasUnstagedChanges?i.hasUnstagedChanges!==e.worktree.hasUnstagedChanges:e.worktree.hasUnstagedChanges}])},396763,504173,518733,925991,e=>{"use strict";var t=e.i(666680),r=e.i(885418),i=e.i(243783);e.i(805422);var a=e.i(694355),n=e.i(661983),s=e.i(750227),o=e.i(184015),l=e.i(119909),u=e.i(988349),c=e.i(497800),d=e.i(835544),p=e.i(499162);e.i(107058);var h=e.i(963910);e.i(151666);var m=e.i(468399),f=e.i(984179);let g="default",y=["QUEUED","RUNNING"],w=["PUSHING","CHECKING_OUT","AWAITING_STASH","CLEANING_UP"],b=["gray","stone","red","rose","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink"],v={codebase:{include:{agent:!0,repository:{include:{projects:{where:{type:"IOS_APP"},include:{configurations:{select:{id:!0}}}}}},jobs:{where:{status:{in:y}},orderBy:{createdAt:"desc"},take:1}}},tags:{include:{tag:!0}},builds:{orderBy:{createdAt:"desc"},take:1,select:{id:!0,status:!0,action:!0,destinationType:!0,destinationJson:!0,snapshotJson:!0,createdAt:!0,finishedAt:!0,artifacts:{select:{id:!0,kind:!0}}}},autoSync:!0,autoMerge:!0,pullRequest:!0,_count:{select:{builds:{where:{status:{in:["QUEUED","PREPARING","RUNNING"]}}}}}};function k(e){return null!==e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(e)&&null===e.disconnectedAt}function S(e){try{let t=JSON.parse(e.capabilitiesJson);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function E(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function I(e,t){if(!e||!t)return null;try{let r=RegExp(t,"i").exec(e),i=(r?.[1]??r?.[0])?.trim();return i?i.toUpperCase():null}catch{return null}}function x(e,t){return{id:e.githubId,number:e.number,title:e.title,url:e.url,repositoryGithubId:e.repositoryGithubId,repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,labels:function(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}(e.labelsJson),jiraKey:e.jiraKey,pipelineStatus:t?.pipelineStatus??"NONE",pipelines:t?.pipelines??[],pipelineRevision:t?.revision??0,reviewDecision:e.reviewDecision,unresolvedReviewThreadCount:e.unresolvedReviewThreadCount,state:e.state,isDraft:e.isDraft,mergeable:e.mergeable,mergeStateStatus:e.mergeStateStatus,autoMergeEnabled:e.autoMergeEnabled,viewerCanEnableAutoMerge:e.viewerCanEnableAutoMerge,viewerCanDisableAutoMerge:e.viewerCanDisableAutoMerge,headRefOid:e.headRefOid,headRefName:e.headRefName,worktreeId:e.worktreeId,worktreeHighlightColor:null,createdAt:e.githubCreatedAt.toISOString()}}function A(e){return{reviewDecision:e.reviewDecision,unresolvedReviewThreadCount:e.unresolvedReviewThreadCount,state:e.state,isDraft:e.isDraft,mergeable:e.mergeable,mergeStateStatus:e.mergeStateStatus,autoMergeEnabled:e.autoMergeEnabled,viewerCanEnableAutoMerge:e.viewerCanEnableAutoMerge,viewerCanDisableAutoMerge:e.viewerCanDisableAutoMerge,headRefOid:e.headRefOid}}function _(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")}function C(e,t){if(!t)return e;let r=_(t);if(r!==_(e))return e;let i=r?s.win32:s.posix,a=i.relative(t,e);return i.isAbsolute(a)||".."===a||a.startsWith(`..${i.sep}`)?e:a||"."}function R(e){if("SUCCEEDED"!==e.status||!e.resultJson)throw Error(e.error||"Worktree job failed");let t=JSON.parse(e.resultJson);if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Worktree job returned an invalid result");return t}function T(e,t,r){if(!t||!e.has(t))return;let i=e.get(t);i.some(e=>e.kind===r.kind&&e.id===r.id)||i.push(r)}async function D(e){let t=[...new Set(e.filter(Boolean))],r=new Map(t.map(e=>[e,[]]));if(!t.length)return r;let a=await (0,i.getPrismaClient)(),[n,s,o,l]=await Promise.all([a.build.findMany({where:{worktreeId:{in:t},OR:[{status:{in:["PREPARING","RUNNING"]}},{status:"QUEUED",job:{status:"RUNNING"}}]},select:{id:!0,worktreeId:!0}}),a.agentRun.findMany({where:{worktreeId:{in:t},attempts:{some:{status:{in:["STARTING","RUNNING"]},supersededAt:null}}},select:{id:!0,kind:!0,displayNumber:!0,worktreeId:!0}}),a.workflowStepAttempt.findMany({where:{status:"RUNNING",supersededAt:null},select:{id:!0,run:{select:{id:!0,displayNumber:!0,sessionDataJson:!0}}}}),a.agentJob.findMany({where:{worktreeId:{in:t},status:"RUNNING",kind:{startsWith:"workflow."}},select:{id:!0,worktreeId:!0}})]);for(let e of n)T(r,e.worktreeId,{kind:"BUILD",id:e.id,label:"Build",href:`/builds/${encodeURIComponent(e.id)}`});for(let e of s){let t="PLAN"===e.kind?"PLAN":"SESSION";T(r,e.worktreeId,{kind:t,id:e.id,label:`${"PLAN"===t?"Plan":"Session"} #${e.displayNumber}`,href:`/${"PLAN"===t?"plans":"sessions"}/${encodeURIComponent(e.id)}`})}for(let e of o)T(r,function(e){try{let t=JSON.parse(e);if(!t||"object"!=typeof t||Array.isArray(t))return null;let r=t.worktree;if(!r||"object"!=typeof r||Array.isArray(r))return null;let i=r.id;return"string"==typeof i&&i?i:null}catch{return null}}(e.run.sessionDataJson),{kind:"WORKFLOW",id:e.run.id,label:`Workflow run #${e.run.displayNumber}`,href:`/workflows/runs/${encodeURIComponent(e.run.id)}`});for(let e of l)T(r,e.worktreeId,{kind:"WORKFLOW_JOB",id:e.id,label:"Workflow terminal job",href:`/jobs/${encodeURIComponent(e.id)}`});return r}e.s(["WorktreesService",0,class{agentControl;jiraService;gitHubService;skillsService;workflowEvents;pipelineStatus;watchDemand;constructor(e,t,r,i,a,n=new h.GitHubPipelineStatusService){this.agentControl=e,this.jiraService=t,this.gitHubService=r,this.skillsService=i,this.workflowEvents=a,this.pipelineStatus=n,this.watchDemand=new Map,this.agentControl.registerCompletionHandler(l.WORKTREE_OPERATION_JOB_KIND,e=>this.projectOperation(e)),this.agentControl.registerCompletionHandler(l.WORKTREE_AUTO_SYNC_JOB_KIND,e=>this.projectOperation(e)),this.agentControl.registerCompletionHandler(l.WORKTREE_GIT_OPERATION_JOB_KIND,e=>this.projectOperation(e)),this.agentControl.registerCompletionHandler(l.WORKTREE_BRANCH_JOB_KIND,e=>this.projectBranchOperation(e)),this.agentControl.registerCompletionHandler(l.WORKTREE_MOVE_PUSH_JOB_KIND,e=>this.advanceMoveAfterPush(e)),this.agentControl.registerCompletionHandler(l.WORKTREE_MOVE_CHECKOUT_JOB_KIND,e=>this.advanceMoveAfterCheckout(e)),this.agentControl.registerCompletionHandler(l.WORKTREE_DELETE_JOB_KIND,e=>this.projectDeleteOperation(e))}async settings(){return(await (0,i.getPrismaClient)()).worktreeSettings.upsert({where:{id:g},create:{id:g,editorVariant:"CODE"},update:{}})}async saveSettings(e){if(!["CODE","CODE_INSIDERS","NONE"].includes(e))throw Error("Unknown editor setting");let t=await (0,i.getPrismaClient)(),r=await t.worktreeSettings.upsert({where:{id:g},create:{id:g,editorVariant:e},update:{editorVariant:e}});return this.publish(null,null),r}async requestRefresh(){let e=await (0,i.getPrismaClient)(),t=await e.codebase.findMany({select:{agentId:!0}});return this.agentControl.requestCodebaseReconcile(t.map(e=>e.agentId))}async cleanupExpired(){let e=await (0,i.getPrismaClient)();await e.worktree.deleteMany({where:{missingAt:{lt:new Date(Date.now()-6048e5)}}})}view(e,t=""){let r=e.codebase.repository.jiraBranchRegex??t;return{...e,relativePath:C(e.folder,e.codebase.agent.baseRepoDirectory),tags:e.tags.map(e=>e.tag),activeJob:e.codebase.jobs.find(t=>t.worktreeId===e.id)??e.codebase.jobs[0]??null,baseBranch:e.baseBranchOverride??e.codebase.defaultBranch??null,ticketKey:I(e.branch,String(r)),ticketTitle:null,ticketStatus:null,pullRequest:e.pullRequest?x(e.pullRequest):null,latestBuild:e.builds?.[0]?{...e.builds[0],outOfDate:(0,f.buildOutOfDate)({...e.builds[0],worktree:e})}:null}}async storePullRequest(e,t,r,a){let n=await (0,i.getPrismaClient)(),s=new Date;await n.$transaction(async i=>{if(await i.worktree.update({where:{id:e},data:{pullRequestLookupOrigin:t,pullRequestLookupBranch:r,pullRequestLookupAt:s}}),a){let t={githubId:a.id,number:a.number,title:a.title,url:a.url,repositoryGithubId:a.repositoryGithubId,repositoryNameWithOwner:a.repositoryNameWithOwner,repositoryUrl:a.repositoryUrl,labelsJson:JSON.stringify(a.labels),jiraKey:a.jiraKey,reviewDecision:a.reviewDecision,unresolvedReviewThreadCount:a.unresolvedReviewThreadCount,state:a.state,isDraft:a.isDraft,mergeable:a.mergeable,mergeStateStatus:a.mergeStateStatus,autoMergeEnabled:a.autoMergeEnabled,viewerCanEnableAutoMerge:a.viewerCanEnableAutoMerge,viewerCanDisableAutoMerge:a.viewerCanDisableAutoMerge,headRefOid:a.headRefOid,headRefName:a.headRefName,githubCreatedAt:new Date(a.createdAt)};await i.worktreePullRequest.upsert({where:{worktreeId:e},create:{worktreeId:e,...t},update:t})}else await i.worktreePullRequest.deleteMany({where:{worktreeId:e}})})}async clearPullRequest(e,t=!0){let r=await (0,i.getPrismaClient)();await r.$transaction([r.worktreePullRequest.deleteMany({where:{worktreeId:e}}),...t?[r.worktree.update({where:{id:e},data:{pullRequestLookupOrigin:null,pullRequestLookupBranch:null,pullRequestLookupAt:null}})]:[]])}async synchronizePullRequests(e){let t=await (0,i.getPrismaClient)(),r=await this.gitHubService.effectiveCacheTtlSeconds("GitHubWorktreePullRequests")*1e3,a=new Set,n=new Map;for(let t of e){let e=t.codebase.repository.canonicalOrigin;!(t.branch&&t.pullRequestLookupOrigin?.toLowerCase()===e.toLowerCase()&&t.pullRequestLookupBranch===t.branch)&&(t.pullRequest||t.pullRequestLookupOrigin||t.pullRequestLookupBranch||t.pullRequestLookupAt)&&(await this.clearPullRequest(t.id),t.pullRequest=null,t.pullRequestLookupOrigin=null,t.pullRequestLookupBranch=null,t.pullRequestLookupAt=null)}let s=e.filter(e=>e.pullRequest);if(s.length)try{let e=await this.gitHubService.pullRequestLiveStatuses(s.flatMap(e=>e.pullRequest?[e.pullRequest.id]:[]),{requestSource:"WORKTREES"});for(let r of s){let i=r.pullRequest;if(!i)continue;let s=e.get(i.id)??null;if(!s||"OPEN"!==s.state){n.set(r.id,i),r.pullRequest=null,a.add(r.id);continue}let o=A(s),l=A(i);JSON.stringify(o)!==JSON.stringify(l)&&(await t.worktreePullRequest.updateMany({where:{worktreeId:r.id},data:o}),r.pullRequest={...i,...s})}}catch{}let o=Date.now(),l=e.filter(e=>{if(e.pullRequest||!e.branch)return!1;let t=e.codebase.repository.canonicalOrigin;return!!/^github\.com\/[^/]+\/[^/]+$/i.test(t)&&(!!a.has(e.id)||e.pullRequestLookupOrigin?.toLowerCase()!==t.toLowerCase()||e.pullRequestLookupBranch!==e.branch||!e.pullRequestLookupAt||o-e.pullRequestLookupAt.getTime()>=r)}),u=new Map;for(let e of l){let t=e.codebase.repository.canonicalOrigin,r=`${a.has(e.id)?"force":"cached"}\0${t}`;u.set(r,[...u.get(r)??[],e])}await Promise.all([...u.entries()].map(async([e,t])=>{let r=e.startsWith("force\0"),i=t[0].codebase.repository.canonicalOrigin;try{let e=await this.gitHubService.pullRequestsForBranches(i,t.flatMap(e=>e.branch?[e.branch]:[]),{force:r,allowStaleOnError:!r,requestSource:"WORKTREES"});await Promise.all(t.map(async t=>{let r=t.branch,a=e.get(r)??null;await this.storePullRequest(t.id,i,r,a),t.pullRequest=a,t.pullRequestLookupOrigin=i,t.pullRequestLookupBranch=r,t.pullRequestLookupAt=new Date}))}catch{for(let e of t){let t=n.get(e.id);t&&(e.pullRequest=t)}}}))}async hydratePullRequestPipelines(e){let t=new Map((await this.pipelineStatus.snapshots(e.flatMap(e=>e.pullRequest?[{repositoryGithubId:e.pullRequest.repositoryGithubId,headSha:e.pullRequest.headRefOid}]:[]))).map(e=>[`${e.repositoryGithubId}\u0000${e.headSha}`,e]));for(let r of e){if(!r.pullRequest)continue;let e=t.get(`${r.pullRequest.repositoryGithubId}\u0000${r.pullRequest.headRefOid}`);r.pullRequest={...r.pullRequest,pipelineStatus:e?.pipelineStatus??r.pullRequest.pipelineStatus,pipelines:e?.pipelines??r.pullRequest.pipelines,pipelineRevision:e?.revision??r.pullRequest.pipelineRevision??0}}}async hydratedView(e,t=""){let r=this.view(e,t);return await this.hydratePullRequestPipelines([r]),r}async refreshPullRequest(e){let t=await (0,i.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e},include:v});if(!r||r.missingAt)throw Error("Worktree not found");let a=r.codebase.repository.canonicalOrigin;if(!r.branch)throw Error("A named worktree branch is required");if(!/^github\.com\/[^/]+\/[^/]+$/i.test(a))throw Error("The worktree repository is not hosted on GitHub");let n=await this.gitHubService.pullRequestsForBranches(a,[r.branch],{force:!0,allowStaleOnError:!1,requestSource:"WORKTREES"});await this.storePullRequest(e,a,r.branch,n.get(r.branch)??null);let s=await t.worktree.findUniqueOrThrow({where:{id:e},include:v});return this.publish(e,r.codebaseId),this.hydratedView(s)}async attachPullRequestForBranch(e,t,r){let a=await (0,i.getPrismaClient)(),n=(await a.worktree.findMany({where:{branch:t,missingAt:null},select:{id:!0,codebaseId:!0,codebase:{select:{repository:{select:{canonicalOrigin:!0}}}}}})).filter(t=>t.codebase.repository.canonicalOrigin.toLowerCase()===e.toLowerCase());return await Promise.all(n.map(async i=>{await this.storePullRequest(i.id,e,t,r),this.publish(i.id,i.codebaseId)})),n.length}async overview(){await this.cleanupExpired();let e=await (0,i.getPrismaClient)(),[t,r,a,n,s,o]=await Promise.all([e.worktree.findMany({where:{missingAt:null},include:v,orderBy:[{codebase:{agent:{name:"asc"}}},{codebase:{repository:{name:"asc"}}},{primary:"desc"},{branch:"asc"},{folder:"asc"}]}),e.worktreeTag.findMany({orderBy:{name:"asc"}}),this.settings(),e.codebaseSettings.findUnique({where:{id:"default"}}),e.worktree.count({where:{missingAt:{not:null}}}),e.worktreeMove.findMany({where:{status:{in:w}},orderBy:{createdAt:"asc"}})]),l=n?.defaultJiraBranchRegex??"",u=t.map(e=>this.view(e,l)),p=[...new Set(u.map(e=>e.codebase.repository.id))],h=(await e.workflow.findMany({where:{enabled:!0,archivedAt:null,activeVersionId:{not:null},quickActionKind:{in:["STANDARD","MERGE_CONFLICT"]},OR:[{quickActionRepositories:{none:{}}},{quickActionRepositories:{some:{repositoryId:{in:p}}}}]},include:{activeVersion:{include:{triggers:!0}},quickActionRepositories:{select:{repositoryId:!0}}},orderBy:[{name:"asc"},{id:"asc"}]})).filter(e=>e.activeVersion?.triggers.some(e=>{if(!(0,d.isResourceTriggerKind)(e.kind))return!1;try{return"WORKTREE"===(0,c.workflowResourceKind)(JSON.parse(e.configJson))}catch{return!1}}));await this.synchronizePullRequests(u),await this.hydratePullRequestPipelines(u);let m=[...new Set(u.map(e=>e.ticketKey).filter(Boolean))],f=new Map;for(let e of(await Promise.all(m.map(async e=>{try{let t=await this.jiraService.cachedTicket(e)??await this.jiraService.ticket(e);f.set(e,{title:t.summary,status:t.status})}catch{}})),u))e.ticketTitle=e.ticketKey?f.get(e.ticketKey)?.title??null:null,e.ticketStatus=e.ticketKey?f.get(e.ticketKey)?.status??null:null;let g=new Map;for(let e of u){let t=e.codebase.agent,r=g.get(t.id);r||(r={agent:t,codebases:[],codebaseMap:new Map},g.set(t.id,r));let i=r.codebaseMap.get(e.codebase.id);i||(i={codebase:e.codebase,repository:e.codebase.repository,worktrees:[],iosBuildConfigured:e.codebase.repository.projects?.some(e=>e.configurations.length>0)??!1,quickActions:h.filter(t=>"STANDARD"===t.quickActionKind&&(0===t.quickActionRepositories.length||t.quickActionRepositories.some(({repositoryId:t})=>t===e.codebase.repository.id))),mergeConflictQuickActions:h.filter(t=>"MERGE_CONFLICT"===t.quickActionKind&&(0===t.quickActionRepositories.length||t.quickActionRepositories.some(({repositoryId:t})=>t===e.codebase.repository.id)))},r.codebaseMap.set(e.codebase.id,i),r.codebases.push(i)),i.worktrees.push(e)}return{agents:[...g.values()].map(e=>({agent:e.agent,codebases:e.codebases})),tags:r,settings:a,hiddenCount:s,activeMoves:o}}async hidden(){await this.cleanupExpired();let e=await (0,i.getPrismaClient)(),t=await e.codebaseSettings.findUnique({where:{id:"default"}}),r=(await e.worktree.findMany({where:{missingAt:{not:null}},include:v,orderBy:{missingAt:"desc"}})).map(e=>this.view(e,t?.defaultJiraBranchRegex??""));return await this.hydratePullRequestPipelines(r),r}async report(e,r){let a=await (0,i.getPrismaClient)(),n=[],s=!1;for(let i of r.slice(0,100)){let r=(0,l.parseCodebaseWorktreeReport)(i),o=await a.codebase.findUnique({where:{id:r.codebaseId}});if(!o||o.agentId!==e)throw Error("Codebase not found for this agent");let u=r.worktrees.slice(0,1e3).map(e=>(0,l.parseWorktreeInventoryItem)(e)),c=await a.worktree.findMany({where:{codebaseId:o.id},select:{gitDirectory:!0,folder:!0,missingAt:!0}}),d=new Map(c.map(e=>[e.gitDirectory,e])),p=new Set(u.map(e=>e.gitDirectory));s||=u.some(e=>{let t=d.get(e.gitDirectory);return!t||t.folder!==e.folder||null!==t.missingAt})||r.complete&&c.some(e=>null===e.missingAt&&!p.has(e.gitDirectory)),await a.$transaction(async e=>{await e.codebase.update({where:{id:o.id},data:{defaultBranch:r.defaultBranch,localBranchesJson:JSON.stringify(r.localBranches),remoteBranchesJson:JSON.stringify(r.remoteBranches),...r.fetchedAt?{lastFetchedAt:new Date(r.fetchedAt)}:{},...r.fetchAttemptedAt?{lastFetchAttemptAt:new Date(r.fetchAttemptedAt),lastFetchError:r.fetchError}:r.fetchError?{lastFetchError:r.fetchError}:{}}});let i=[];for(let r of u){i.push(r.gitDirectory);let a=await e.worktree.upsert({where:{codebaseId_gitDirectory:{codebaseId:o.id,gitDirectory:r.gitDirectory}},create:{id:(0,t.randomUUID)(),codebaseId:o.id,gitDirectory:r.gitDirectory,...this.inventoryData(r)},update:{}}),s=a.branch!==r.branch,l=await e.worktree.updateMany({where:{id:a.id,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:new Date(r.checkedAt)}}]},data:{...this.inventoryData(r),missingAt:null,...s?{pullRequestLookupOrigin:null,pullRequestLookupBranch:null,pullRequestLookupAt:null}:{}}});s&&l.count>0&&await e.worktreePullRequest.deleteMany({where:{worktreeId:a.id}}),n.push(a.id)}r.complete&&await e.worktree.updateMany({where:{codebaseId:o.id,missingAt:null,...i.length?{gitDirectory:{notIn:i}}:{}},data:{missingAt:new Date}})}),this.publish(null,o.id)}return await this.cleanupExpired(),s&&await this.skillsService?.requestAutoReconcile(),a.worktree.findMany({where:{id:{in:n}},include:v})}async reportActivity(e,t){let r=(0,l.parseWorktreeActivityReport)(t),a=await (0,i.getPrismaClient)(),s=await a.worktree.findFirst({where:{codebaseId:r.codebaseId,gitDirectory:r.gitDirectory,missingAt:null,codebase:{agentId:e}},select:{id:!0,codebaseId:!0,branch:!0}});if(!s)throw Error("Worktree activity source was not found");let o=void 0!==r.branch||void 0!==r.headSha||void 0!==r.upstream||void 0!==r.ahead||void 0!==r.behind||void 0!==r.syncState||void 0!==r.baseAhead||void 0!==r.baseBehind,u=!0;if(o||void 0!==r.hasStagedChanges||void 0!==r.hasUnstagedChanges||void 0!==r.rebaseInProgress||void 0!==r.hasConflicts||void 0!==r.codeStateHash||void 0!==r.pushStatus){let e=void 0!==r.branch&&r.branch!==s.branch;(u=(await a.worktree.updateMany({where:{id:s.id,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:new Date(r.observedAt)}}]},data:{...void 0===r.branch?{}:{branch:r.branch},...e?{pullRequestLookupOrigin:null,pullRequestLookupBranch:null,pullRequestLookupAt:null}:{},...void 0===r.headSha?{}:{headSha:r.headSha},...void 0===r.upstream?{}:{upstream:r.upstream},...void 0===r.ahead?{}:{ahead:r.ahead},...void 0===r.behind?{}:{behind:r.behind},...void 0===r.syncState?{}:{syncState:r.syncState},...void 0===r.baseAhead?{}:{baseAhead:r.baseAhead},...void 0===r.baseBehind?{}:{baseBehind:r.baseBehind},lastCheckedAt:new Date(r.observedAt),...void 0===r.hasStagedChanges?{}:{hasStagedChanges:r.hasStagedChanges},...void 0===r.hasUnstagedChanges?{}:{hasUnstagedChanges:r.hasUnstagedChanges},...void 0===r.rebaseInProgress?{}:{rebaseInProgress:r.rebaseInProgress},...void 0===r.hasConflicts?{}:{hasConflicts:r.hasConflicts},...void 0===r.codeStateHash?{}:{codeStateHash:r.codeStateHash},...void 0===r.pushStatus?{}:{pushStatus:r.pushStatus}}})).count>0)&&(e&&await a.worktreePullRequest.deleteMany({where:{worktreeId:s.id}}),this.publish(s.id,s.codebaseId))}let c={worktreeId:s.id,...void 0===r.branch?{}:{branch:r.branch},...void 0===r.headSha?{}:{headSha:r.headSha},...void 0===r.upstream?{}:{upstream:r.upstream},...void 0===r.ahead?{}:{ahead:r.ahead},...void 0===r.behind?{}:{behind:r.behind},...void 0===r.syncState?{}:{syncState:r.syncState},...void 0===r.baseAhead?{}:{baseAhead:r.baseAhead},...void 0===r.baseBehind?{}:{baseBehind:r.baseBehind},...void 0===r.hasStagedChanges?{}:{hasStagedChanges:r.hasStagedChanges},...void 0===r.hasUnstagedChanges?{}:{hasUnstagedChanges:r.hasUnstagedChanges},...void 0===r.rebaseInProgress?{}:{rebaseInProgress:r.rebaseInProgress},...void 0===r.hasConflicts?{}:{hasConflicts:r.hasConflicts},...void 0===r.pushStatus?{}:{pushStatus:r.pushStatus},observedAt:r.observedAt};return this.watchDemand.has(s.id)&&u&&n.agentEventBus.publish((0,n.worktreeInspectionTopic)(s.id),{worktreeInspectionChanged:c}),c}inventoryData(e){return{folder:e.folder,relativePath:e.relativePath,primary:e.primary,branch:e.branch,headSha:e.headSha,codeStateHash:e.codeStateHash??null,upstream:e.upstream,ahead:e.ahead,behind:e.behind,syncState:e.syncState,baseAhead:e.baseAhead,baseBehind:e.baseBehind,hasStagedChanges:e.hasStagedChanges??!1,hasUnstagedChanges:e.hasUnstagedChanges??!1,rebaseInProgress:e.rebaseInProgress??!1,hasConflicts:e.hasConflicts??!1,pushStatus:e.pushStatus??"UNKNOWN",availability:e.availability,statusError:e.error,lastCheckedAt:new Date(e.checkedAt)}}async updateBaseBranch(e,t){let r=await (0,i.getPrismaClient)(),a=await r.worktree.findUnique({where:{id:e},include:{codebase:!0}});if(!a||a.missingAt)throw Error("Worktree not found");let n=t?.trim()||null;if(n&&!E(a.codebase.remoteBranchesJson).includes(n))throw Error("The selected origin branch is unavailable; fetch and try again");let s=await r.worktree.update({where:{id:e},data:{baseBranchOverride:n},include:v});return this.publish(e,a.codebaseId),await this.restartWatch(e),this.hydratedView(s)}requireColor(e){if(null===e||""===e)return null;if(!b.includes(e))throw Error("Unknown worktree color");return e}async updateHighlight(e,t){let r=await (0,i.getPrismaClient)(),a=await r.worktree.update({where:{id:e},data:{highlightColor:this.requireColor(t)},include:v});return this.publish(e,a.codebaseId),this.hydratedView(a)}async setTags(e,t){let r=await (0,i.getPrismaClient)(),a=[...new Set(t)].slice(0,100);if(await r.worktreeTag.count({where:{id:{in:a}}})!==a.length)throw Error("One or more tags were not found");await r.$transaction([r.worktreeTagAssignment.deleteMany({where:{worktreeId:e}}),...a.length?[r.worktreeTagAssignment.createMany({data:a.map(t=>({worktreeId:e,tagId:t}))})]:[]]);let n=await r.worktree.findUniqueOrThrow({where:{id:e},include:v});return this.publish(e,n.codebaseId),this.hydratedView(n)}async saveTag(e){let r=e.name.trim();if(!r||r.length>40)throw Error("Tag names must contain 1–40 characters");let a=this.requireColor(e.color),n=await (0,i.getPrismaClient)(),s=(await n.worktreeTag.findMany()).find(e=>e.name.toLocaleLowerCase()===r.toLocaleLowerCase());if(s&&s.id!==e.id)throw Error("Tag names must be unique");let o=e.id?await n.worktreeTag.update({where:{id:e.id},data:{name:r,color:a}}):await n.worktreeTag.create({data:{id:(0,t.randomUUID)(),name:r,color:a}});return this.publish(null,null),o}async deleteTag(e){let t=await (0,i.getPrismaClient)(),r=await t.worktreeTag.deleteMany({where:{id:e}});return r.count&&this.publish(null,null),r.count>0}async repositoryTakenBranches(e){let t=await (0,i.getPrismaClient)();return new Set((await t.codebase.findMany({where:{repositoryId:e},select:{localBranchesJson:!0,remoteBranchesJson:!0,worktrees:{where:{missingAt:null},select:{branch:!0}}}})).flatMap(e=>[...E(e.localBranchesJson),...E(e.remoteBranchesJson),...e.worktrees.flatMap(e=>e.branch?[e.branch]:[])]))}requireBaseBranch(e,t){let r=t.trim();if(!r||!E(e.remoteBranchesJson).includes(r))throw Error("The selected origin base branch is unavailable; fetch and try again");return r}async ticketBranch(e,t,r){let i=t?.trim()??"",a=await this.jiraService.branchTicket(i),n=await (0,m.jiraBranchCandidates)(a.branchNamingScript,{ticketKey:a.ticketKey,type:a.ticketType??"",title:a.ticketTitle}),s=await this.repositoryTakenBranches(e.repositoryId),o=n.filter(e=>e===r||!s.has(e));if(!o.length)throw Error("Every generated ticket branch name is already taken");return{ticket:a,candidates:o}}async previewTicketBranch(e){let t=await (0,i.getPrismaClient)(),r=await t.codebase.findUnique({where:{id:e.codebaseId},include:{agent:!0,repository:!0}});if(!r)throw Error("Codebase not found");let a=null;if(e.worktreeId){let r=await t.worktree.findFirst({where:{id:e.worktreeId,codebaseId:e.codebaseId,missingAt:null},select:{branch:!0}});if(!r)throw Error("Worktree not found for this codebase");a=r.branch}let{ticket:n,candidates:s}=await this.ticketBranch(r,e.ticketKey,a);return{ticketKey:n.ticketKey,ticketTitle:n.ticketTitle,ticketType:n.ticketType,projectKey:n.projectKey,branchName:s[0]}}async ticketKeyForWorktree(e){let t=await (0,i.getPrismaClient)(),[r,a]=await Promise.all([t.worktree.findFirst({where:{id:e,missingAt:null},select:{branch:!0,codebase:{select:{repository:{select:{jiraBranchRegex:!0}}}}}}),t.codebaseSettings.findUnique({where:{id:g}})]);if(!r)return null;let n=r.codebase.repository.jiraBranchRegex??a?.defaultJiraBranchRegex??"";return I(r.branch,n)}async workflowSessionDataForWorktree(e,t={}){var r;let a=await (0,i.getPrismaClient)(),[n,s]=await Promise.all([a.worktree.findFirst({where:{id:e,...t.includeMissing?{}:{missingAt:null}},select:{id:!0,folder:!0,branch:!0,baseBranchOverride:!0,headSha:!0,upstream:!0,ahead:!0,behind:!0,syncState:!0,baseAhead:!0,baseBehind:!0,rebaseInProgress:!0,hasConflicts:!0,pushStatus:!0,hasStagedChanges:!0,hasUnstagedChanges:!0,missingAt:!0,pullRequest:!0,codebase:{select:{id:!0,folder:!0,agentId:!0,branch:!0,headSha:!0,defaultBranch:!0,agent:{select:{id:!0,name:!0,hostname:!0}},repository:{select:{id:!0,name:!0,displayOrigin:!0,canonicalOrigin:!0,jiraBranchRegex:!0}}}}}}),a.codebaseSettings.findUnique({where:{id:g}})]);if(!n)return{};let o=n.codebase.repository,l=o.jiraBranchRegex??s?.defaultJiraBranchRegex??"",u=I(n.branch,l),c=null;if(u)try{c=await this.jiraService.cachedTicket(u)}catch{}let d=n.pullRequest?await this.pipelineStatus.snapshot({repositoryGithubId:n.pullRequest.repositoryGithubId,headSha:n.pullRequest.headRefOid}):null;return{worktree:{id:n.id,path:n.folder,branch:n.branch,baseBranch:n.baseBranchOverride??n.codebase.defaultBranch,headSha:n.headSha,upstream:n.upstream,ahead:n.ahead,behind:n.behind,syncState:n.syncState,baseAhead:n.baseAhead,baseBehind:n.baseBehind,rebaseInProgress:n.rebaseInProgress,hasConflicts:n.hasConflicts,pushStatus:n.pushStatus,dirty:n.hasStagedChanges||n.hasUnstagedChanges,missingAt:n.missingAt?.toISOString()??null},codebase:{id:n.codebase.id,folder:n.codebase.folder,agentId:n.codebase.agentId,branch:n.codebase.branch,headSha:n.codebase.headSha},agent:n.codebase.agent,repo:{id:o.id,name:o.name,url:o.displayOrigin,canonicalOrigin:o.canonicalOrigin,displayOrigin:o.displayOrigin,defaultBranch:n.codebase.defaultBranch},...n.pullRequest?{pr:{...r=x(n.pullRequest,d),headBranch:r.headRefName,headSha:r.headRefOid,merged:"MERGED"===r.state}}:{},...u?{ticket:{key:u,title:c?.summary??null,status:c?.status??null,projectKey:c?.projectKey??null}}:{}}}async workflowSessionDataForPullRequest(e,t,r){let a=e.trim().toLowerCase(),n=t.trim().toLowerCase();if(!a||!n||!Number.isInteger(r)||r<1)return{};let s=await (0,i.getPrismaClient)(),o=await s.worktreePullRequest.findMany({where:{number:r,worktree:{missingAt:null}},select:{worktreeId:!0,repositoryNameWithOwner:!0},orderBy:{updatedAt:"desc"}}),l=`${a}/${n}`,u=o.find(({repositoryNameWithOwner:e})=>e.toLowerCase()===l);return u?this.workflowSessionDataForWorktree(u.worktreeId):{}}async resolveBranchSelection(e,t,r){let a=this.requireBaseBranch(e,t.baseBranch);if("TICKET"===t.mode){let{candidates:i}=await this.ticketBranch(e,t.ticketKey,r?.branch??null);return{baseBranch:a,mode:"NEW",candidates:i}}let n=t.branchName?.trim()??"";if(!(0,l.validGitBranchName)(n))throw Error("Enter a valid Git branch name");if("NEW"===t.mode){if((await this.repositoryTakenBranches(e.repositoryId)).has(n))throw Error(`Branch ${n} is already taken`);return{baseBranch:a,mode:"NEW",candidates:[n]}}if("EXISTING"!==t.mode)throw Error("Unknown worktree branch mode");if(!new Set([...E(e.localBranchesJson),...E(e.remoteBranchesJson)]).has(n))throw Error(`Existing branch ${n} is unavailable; refresh and try again`);let s=await (0,i.getPrismaClient)();if(await s.worktree.findFirst({where:{codebaseId:e.id,branch:n,missingAt:null,...r?{id:{not:r.id}}:{}},select:{id:!0}}))throw Error(`Branch ${n} is checked out in another worktree`);return{baseBranch:a,mode:"EXISTING",candidates:[n]}}async createWorktree(e){let t=await this.requireRunnableCodebase(e.codebaseId),r=await this.resolveBranchSelection(t,e.selection,null);return this.agentControl.createJob({agentId:t.agentId,codebaseId:t.id,kind:l.WORKTREE_BRANCH_JOB_KIND,payload:{codebaseId:t.id,rootFolder:t.folder,folder:null,gitDirectory:null,expectedOrigin:t.repository.canonicalOrigin,baseBranch:r.baseBranch,action:"CREATE",mode:r.mode,candidates:r.candidates,stashOnFailure:!1},idempotencyKey:`worktree:branch:create:${e.requestId}:${t.id}`,timeoutSeconds:600})}async changeWorktreeBranch(e){let t=await this.requireRunnable(e.worktreeId,l.WORKTREE_BRANCH_JOB_KIND),r=await this.resolveBranchSelection(t.codebase,e.selection,{id:t.id,branch:t.branch});return this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:l.WORKTREE_BRANCH_JOB_KIND,payload:{codebaseId:t.codebaseId,rootFolder:t.codebase.folder,folder:t.folder,gitDirectory:t.gitDirectory,expectedOrigin:t.codebase.repository.canonicalOrigin,baseBranch:r.baseBranch,action:"CHANGE",mode:r.mode,candidates:r.candidates,stashOnFailure:!!e.stashOnFailure},idempotencyKey:`worktree:branch:change:${e.requestId}:${t.id}`,timeoutSeconds:600})}async getMove(e){return(await (0,i.getPrismaClient)()).worktreeMove.findUnique({where:{id:e}})}async moveWorktree(e){let r,a=await (0,i.getPrismaClient)(),n=await a.worktreeMove.findUnique({where:{sourceWorktreeId_requestId:{sourceWorktreeId:e.sourceWorktreeId,requestId:e.requestId}}});if(n)return n;let s=await this.requireRunnable(e.sourceWorktreeId,l.WORKTREE_MOVE_PUSH_JOB_KIND);if(!s.branch||!s.headSha)throw Error("A named source branch is required");if(s.hasStagedChanges||s.hasUnstagedChanges||"READY"!==s.pushStatus)throw Error("The source branch must be clean and safely pushable before moving");if(e.deleteSource&&s.primary)throw Error("The primary worktree cannot be deleted after moving");if(e.deleteSource&&!S(s.codebase.agent).includes(l.WORKTREE_DELETE_JOB_KIND))throw Error("Source agent must be updated to remove the old worktree");let o=await this.requireRunnableCodebase(e.targetCodebaseId,l.WORKTREE_MOVE_CHECKOUT_JOB_KIND);if(s.codebase.repositoryId!==o.repositoryId||s.codebase.agentId===o.agentId)throw Error("The destination must be the same repository on another agent");let u=e.targetWorktreeId?await a.worktree.findFirst({where:{id:e.targetWorktreeId,codebaseId:o.id,missingAt:null,availability:"AVAILABLE"}}):null;if(e.targetWorktreeId&&!u)throw Error("Destination worktree not found");if(await a.worktree.findFirst({where:{codebaseId:o.id,branch:s.branch,missingAt:null,...u?{id:{not:u.id}}:{}},select:{id:!0}}))throw Error("The source branch is already checked out in another destination worktree");let c=o.defaultBranch??s.codebase.defaultBranch;if(!c)throw Error("The destination default branch is unavailable");let d=(0,t.randomUUID)();try{r=await a.worktreeMove.create({data:{id:d,requestId:e.requestId,sourceWorktreeId:s.id,sourceCodebaseId:s.codebaseId,targetCodebaseId:o.id,targetWorktreeId:u?.id??null,destinationMode:u?"EXISTING":"NEW",branch:s.branch,headSha:s.headSha,baseBranch:c,deleteSource:e.deleteSource,status:"PUSHING"}})}catch(r){let t=await a.worktreeMove.findUnique({where:{sourceWorktreeId_requestId:{sourceWorktreeId:e.sourceWorktreeId,requestId:e.requestId}}});if(t)return t;throw r}try{let e=await this.agentControl.createJob({agentId:s.codebase.agentId,codebaseId:s.codebaseId,worktreeId:s.id,kind:l.WORKTREE_MOVE_PUSH_JOB_KIND,payload:{moveId:r.id,codebaseId:s.codebaseId,folder:s.folder,gitDirectory:s.gitDirectory,expectedOrigin:s.codebase.repository.canonicalOrigin,branch:s.branch,expectedHeadSha:s.headSha},idempotencyKey:`worktree:move:push:${r.id}`,timeoutSeconds:600});return r=await a.worktreeMove.update({where:{id:r.id},data:{sourceJobId:e.id}}),this.publish(s.id,s.codebaseId),r}catch(e){throw await a.worktreeMove.update({where:{id:r.id},data:{status:"FAILED",error:e instanceof Error?e.message:String(e),finishedAt:new Date}}),e}}async retryWorktreeMoveWithStash(e){let t=await (0,i.getPrismaClient)(),r=await t.worktreeMove.findUnique({where:{id:e}});if(!r||"AWAITING_STASH"!==r.status)throw Error("This move is not waiting for a stash decision");let a=await this.createMoveCheckoutJob(r,!0);if(1!==(await t.worktreeMove.updateMany({where:{id:e,status:"AWAITING_STASH"},data:{status:"CHECKING_OUT",targetJobId:a.id,error:null}})).count){let r=await t.worktreeMove.findUniqueOrThrow({where:{id:e}});if("AWAITING_STASH"!==r.status)return r;throw Error("The move state changed; refresh and try again")}return this.publish(r.sourceWorktreeId,r.sourceCodebaseId),t.worktreeMove.findUniqueOrThrow({where:{id:e}})}async cancelWorktreeMove(e){let t=await (0,i.getPrismaClient)(),r=await t.worktreeMove.findUnique({where:{id:e}});if(!r||"AWAITING_STASH"!==r.status)throw Error("Only a move waiting for a stash decision can be cancelled");let a=await t.worktreeMove.update({where:{id:e},data:{status:"CANCELLED",finishedAt:new Date}});return this.publish(r.sourceWorktreeId,r.sourceCodebaseId),a}async deleteWorktree(e){let t=await this.requireRunnable(e.worktreeId,l.WORKTREE_DELETE_JOB_KIND);if(t.primary)throw Error("The primary worktree cannot be deleted");if(void 0!==e.expectedBranch&&t.branch!==e.expectedBranch)throw Error("The worktree branch changed before deletion");if(!0===e.requireClean&&void 0!==e.expectedHeadSha&&t.headSha!==e.expectedHeadSha)throw Error("The worktree HEAD changed before deletion");if(e.deleteRemoteBranch&&(!t.branch||t.branch===t.codebase.defaultBranch))throw Error("The default remote branch cannot be deleted");return this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:l.WORKTREE_DELETE_JOB_KIND,payload:{moveId:null,codebaseId:t.codebaseId,rootFolder:t.codebase.folder,folder:t.folder,gitDirectory:t.gitDirectory,expectedOrigin:t.codebase.repository.canonicalOrigin,branch:void 0===e.expectedBranch?t.branch:e.expectedBranch,defaultBranch:t.codebase.defaultBranch,deleteRemoteBranch:e.deleteRemoteBranch,requireClean:e.requireClean??!1,expectedHeadSha:!0===e.requireClean?e.expectedHeadSha??t.headSha:null},idempotencyKey:`worktree:delete:${e.requestId}:${t.id}`,timeoutSeconds:600})}async inspect(e,t){let r=await this.requireRunnable(e,l.WORKTREE_INSPECT_JOB_KIND,!0),a=await this.createSerializedCodebaseJob({agentId:r.codebase.agentId,codebaseId:r.codebaseId,worktreeId:r.id,kind:l.WORKTREE_INSPECT_JOB_KIND,payload:this.payload(r),idempotencyKey:`worktree:inspect:${t}:${e}`,timeoutSeconds:30,visibility:"SYSTEM"});try{let e=await this.waitForJob(a.id),i=R(e).detail;if(!i||"object"!=typeof i)throw Error("Invalid worktree detail");let n=Array.isArray(i.changes)?i.changes.map(e=>e&&"object"==typeof e&&!Array.isArray(e)?{...e,changeType:"string"==typeof e.changeType?e.changeType:"MODIFIED"}:e):[],s={...i,changes:n,branchChanges:Array.isArray(i.branchChanges)?i.branchChanges:[],branchChangesTruncated:!0===i.branchChangesTruncated};if(this.workflowEvents){let e=n.filter(e=>e&&"object"==typeof e&&!Array.isArray(e)&&!0===e.conflicted),i=(0,p.mergeSessionData)(await this.workflowSessionDataForWorktree(r.id),{repo:{id:r.codebase.repository.id,name:r.codebase.repository.name,url:r.codebase.repository.displayOrigin,canonicalOrigin:r.codebase.repository.canonicalOrigin,displayOrigin:r.codebase.repository.displayOrigin,defaultBranch:r.codebase.defaultBranch},codebase:{id:r.codebase.id,folder:r.codebase.folder,agentId:r.codebase.agentId},worktree:{id:r.id,path:r.folder,branch:r.branch,headSha:r.headSha,conflicted:e.length>0,conflicts:e}});await this.workflowEvents.record({kind:"WORKTREE_CONFLICT",subjectKey:r.id,dedupeKey:`worktree-conflict:${r.id}:${t}`,payload:{...i,sessionData:i,cursorValue:e.length?e.map(e=>String(e.path??"")):[]}})}return s}finally{let e=await (0,i.getPrismaClient)();await e.agentJob.deleteMany({where:{id:a.id,visibility:"SYSTEM"}})}}async inspectDiff(e,t,r){let a=await this.requireRunnable(e,l.WORKTREE_DIFF_JOB_KIND,!0),n=this.payload(a);if(!n.baseBranch)throw Error("A base branch is required");let s=await this.createSerializedCodebaseJob({agentId:a.codebase.agentId,codebaseId:a.codebaseId,worktreeId:a.id,kind:l.WORKTREE_DIFF_JOB_KIND,payload:{...n,baseBranch:n.baseBranch,scope:t.scope,path:t.path??null,previousPath:t.previousPath??null,commitSha:t.commitSha??null,uploadId:null,side:null},idempotencyKey:`worktree:diff:${r}:${e}`,timeoutSeconds:30,visibility:"SYSTEM"});try{let e=await this.waitForJob(s.id),t=R(e).diff;if(!t||"object"!=typeof t)throw Error("Invalid worktree diff result");return t}finally{let e=await (0,i.getPrismaClient)();await e.agentJob.deleteMany({where:{id:s.id,visibility:"SYSTEM"}})}}async prepareDiffAsset(e,t,r){let a=await this.requireRunnable(e,l.WORKTREE_DIFF_ASSET_JOB_KIND,!0),n=this.payload(a);if(!n.baseBranch)throw Error("A base branch is required");let s=await this.createSerializedCodebaseJob({agentId:a.codebase.agentId,codebaseId:a.codebaseId,worktreeId:a.id,kind:l.WORKTREE_DIFF_ASSET_JOB_KIND,payload:{...n,baseBranch:n.baseBranch,scope:t.scope,path:t.path,previousPath:t.previousPath??null,commitSha:t.commitSha??null,uploadId:r,side:t.side},idempotencyKey:`worktree:diff-asset:${r}:${e}`,timeoutSeconds:60,visibility:"SYSTEM"});try{R(await this.waitForJob(s.id))}finally{let e=await (0,i.getPrismaClient)();await e.agentJob.deleteMany({where:{id:s.id,visibility:"SYSTEM"}})}}async diffAssetAgentId(e){let t=await (0,i.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e},select:{codebase:{select:{agentId:!0}}}});return r?.codebase.agentId??null}async runOperation(e,t,r){if(!l.WORKTREE_OPERATIONS.includes(t))throw Error("Unknown worktree operation");let i=await this.requireRunnable(e,l.WORKTREE_OPERATION_JOB_KIND),a=await this.settings();return this.agentControl.createJob({agentId:i.codebase.agentId,codebaseId:i.codebaseId,worktreeId:i.id,kind:l.WORKTREE_OPERATION_JOB_KIND,payload:{...this.payload(i),operation:t,..."OPEN_EDITOR"===t?{editorVariant:a.editorVariant}:{}},idempotencyKey:`worktree:operation:${r}:${e}`,timeoutSeconds:"OPEN_EDITOR"===t?30:600})}async createAutoSyncJob(e,t,r,i){let a=await this.requireRunnable(e,l.WORKTREE_AUTO_SYNC_JOB_KIND),n=this.payload(a);if(!n.baseBranch)throw Error("Auto Sync requires a base branch");return this.agentControl.createJob({agentId:a.codebase.agentId,codebaseId:a.codebaseId,worktreeId:a.id,kind:l.WORKTREE_AUTO_SYNC_JOB_KIND,payload:{...n,expectedBranch:r,baseBranch:n.baseBranch,phase:t},idempotencyKey:`worktree:auto-sync:${t.toLowerCase()}:${i}:${e}`,timeoutSeconds:600})}publishAutomationChange(e,t=null){this.publish(e,t)}async inspectGitState(e,t){if(!t.trim())throw Error("requestId is required");let r=await this.requireRunnable(e,l.WORKTREE_GIT_INSPECT_JOB_KIND,!0),a=await this.createSerializedCodebaseJob({agentId:r.codebase.agentId,codebaseId:r.codebaseId,worktreeId:r.id,kind:l.WORKTREE_GIT_INSPECT_JOB_KIND,payload:{action:"STATE",codebaseId:r.codebaseId,folder:r.folder,gitDirectory:r.gitDirectory,expectedOrigin:r.codebase.repository.canonicalOrigin},idempotencyKey:`worktree:git:state:${t}:${e}`,timeoutSeconds:30,visibility:"SYSTEM"});try{let e=await this.waitForJob(a.id);return(0,o.parseCodebaseGitState)(R(e).state)}finally{let e=await (0,i.getPrismaClient)();await e.agentJob.deleteMany({where:{id:a.id,visibility:"SYSTEM"}})}}async runGitOperation(e){if(!e.requestId.trim())throw Error("requestId is required");if(!l.WORKTREE_GIT_OPERATIONS.includes(e.operation))throw Error("Unknown worktree Git operation");let t=await this.requireRunnable(e.worktreeId,l.WORKTREE_GIT_OPERATION_JOB_KIND);return this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:l.WORKTREE_GIT_OPERATION_JOB_KIND,payload:{codebaseId:t.codebaseId,folder:t.folder,gitDirectory:t.gitDirectory,expectedOrigin:t.codebase.repository.canonicalOrigin,baseBranch:t.baseBranchOverride??t.codebase.defaultBranch??null,defaultBranch:t.codebase.defaultBranch,operation:e.operation,...e.branch?{branch:e.branch}:{},...e.stashOid?{stashOid:e.stashOid}:{},..."SWITCH_BRANCH"===e.operation?{stashChanges:!!e.stashChanges}:{}},idempotencyKey:`worktree:git:${e.operation}:${e.requestId}:${e.worktreeId}`,timeoutSeconds:"PULL_BRANCH"===e.operation?300:60})}payload(e){return{codebaseId:e.codebaseId,folder:e.folder,gitDirectory:e.gitDirectory,expectedOrigin:e.codebase.repository.canonicalOrigin,baseBranch:e.baseBranchOverride??e.codebase.defaultBranch??null}}async createSerializedCodebaseJob(e){let t=await (0,i.getPrismaClient)(),r=Date.now()+3e4;for(;Date.now()<r;){let i=await t.agentJob.findFirst({where:{codebaseId:e.codebaseId,status:{in:y}},select:{id:!0,idempotencyKey:!0,kind:!0}});if(i){if(i.idempotencyKey===e.idempotencyKey)return this.agentControl.createJob(e);await this.waitForCodebaseJob(i.id,r);continue}try{return await this.agentControl.createJob(e)}catch(e){if(!function(e){if(!e||"object"!=typeof e||"P2002"!==e.code)return!1;let t=e.meta?.target;return Array.isArray(t)?t.includes("codebaseId"):"string"==typeof t&&t.includes("codebaseId")}(e))throw e}}throw new u.CodebaseBusyError}async waitForCodebaseJob(e,t){let r=n.agentEventBus.iterate((0,n.agentJobChangedTopic)(e));try{for(;Date.now()<t;){let i=await this.agentControl.getJob(e);if(!i||!y.includes(i.status))return;await Promise.race([r.next(),new Promise(e=>setTimeout(e,Math.max(0,t-Date.now())))])}throw new u.CodebaseBusyError}finally{await r.return?.()}}async requireRunnable(e,t,r=!1){let a=await (0,i.getPrismaClient)(),n=await a.worktree.findUnique({where:{id:e},include:{codebase:{include:{agent:!0,repository:!0}}}});if(!n||n.missingAt||"AVAILABLE"!==n.availability)throw Error("Worktree is unavailable");if(!k(n.codebase.agent))throw Error("Agent is offline");if(!S(n.codebase.agent).includes(t))throw Error("Agent must be updated to use worktrees");if(!r){let[e,t]=await Promise.all([a.agentJob.findFirst({where:{codebaseId:n.codebaseId,status:{in:y}}}),a.worktreeMove.findFirst({where:{status:{in:w},OR:[{sourceCodebaseId:n.codebaseId},{targetCodebaseId:n.codebaseId}]}})]);if(e||t)throw new u.CodebaseBusyError}return n}async requireRunnableCodebase(e,t=l.WORKTREE_BRANCH_JOB_KIND){let r=await (0,i.getPrismaClient)(),a=await r.codebase.findUnique({where:{id:e},include:{agent:!0,repository:!0}});if(!a||"AVAILABLE"!==a.availability)throw Error("Codebase is unavailable");if(!k(a.agent))throw Error("Agent is offline");if(!S(a.agent).includes(t))throw Error("Agent must be updated to create or change worktrees");let[n,s]=await Promise.all([r.agentJob.findFirst({where:{codebaseId:e,status:{in:y}}}),r.worktreeMove.findFirst({where:{status:{in:w},OR:[{sourceCodebaseId:e},{targetCodebaseId:e}]}})]);if(n||s)throw new u.CodebaseBusyError;return a}async purge(e){let t=await (0,i.getPrismaClient)(),r=await t.worktree.deleteMany({where:{id:e,missingAt:{not:null}}});return r.count&&this.publish(e,null),r.count>0}async purgeAll(){let e=await (0,i.getPrismaClient)(),t=await e.worktree.deleteMany({where:{missingAt:{not:null}}});return t.count&&this.publish(null,null),t.count}subscribe(){return n.agentEventBus.iterate(n.WORKTREE_CHANGED_TOPIC)}async *subscribeInspection(e){let t=n.agentEventBus.iterate((0,n.worktreeInspectionTopic)(e)),r=!1;try{for await(let i of(await this.acquireWatch(e),r=!0,t))yield i}finally{await t.return?.(),r&&await this.releaseWatch(e)}}async acquireWatch(e){let r=this.watchDemand.get(e);if(r){r.subscribers+=1,await r.started;return}let i=await this.requireRunnable(e,l.WORKTREE_WATCH_JOB_KIND,!0),a=(0,t.randomUUID)(),n=this.payload(i),s={subscribers:1,watchId:a,agentId:i.codebase.agentId,worktreeId:i.id,codebaseId:i.codebaseId,payload:n,started:Promise.resolve()};s.started=this.runWatchAction(s,"START"),this.watchDemand.set(e,s);try{await s.started}catch(t){throw this.watchDemand.get(e)===s&&this.watchDemand.delete(e),t}}async releaseWatch(e){let t=this.watchDemand.get(e);if(t&&(t.subscribers-=1,!(t.subscribers>0))){this.watchDemand.delete(e);try{await t.started,await this.runWatchAction(t,"STOP")}catch(e){console.error("Could not stop worktree watcher:",e instanceof Error?e.message:e)}}}async runWatchAction(e,t){let r=await this.agentControl.createJob({agentId:e.agentId,worktreeId:e.worktreeId,kind:l.WORKTREE_WATCH_JOB_KIND,payload:{...e.payload,action:t,watchId:e.watchId},idempotencyKey:`worktree:watch:${t}:${e.watchId}`,timeoutSeconds:30,visibility:"SYSTEM"});try{R(await this.waitForJob(r.id))}finally{let e=await (0,i.getPrismaClient)();await e.agentJob.deleteMany({where:{id:r.id,visibility:"SYSTEM"}})}}async restartWatch(e){let r=this.watchDemand.get(e);if(r)try{if(await r.started,this.watchDemand.get(e)!==r||(await this.runWatchAction(r,"STOP"),this.watchDemand.get(e)!==r))return;let i=await this.requireRunnable(e,l.WORKTREE_WATCH_JOB_KIND,!0),a={subscribers:r.subscribers,watchId:(0,t.randomUUID)(),agentId:i.codebase.agentId,worktreeId:i.id,codebaseId:i.codebaseId,payload:this.payload(i),started:Promise.resolve()};a.started=this.runWatchAction(a,"START"),this.watchDemand.set(e,a),await a.started}catch(e){console.error("Could not restart worktree watcher:",e instanceof Error?e.message:e)}}publish(e,t){n.agentEventBus.publish(n.WORKTREE_CHANGED_TOPIC,{worktreeOverviewChanged:{worktreeId:e,codebaseId:t}})}moveIdFromJob(e){let t=JSON.parse(e.payloadJson);if(!t||"object"!=typeof t||Array.isArray(t)||"string"!=typeof t.moveId)throw Error("Move job is missing its workflow identifier");return String(t.moveId)}async failMove(e,t,r){let a=await (0,i.getPrismaClient)();(await a.worktreeMove.updateMany({where:{id:e,status:t},data:{status:"FAILED",error:r,finishedAt:new Date}})).count&&this.publish(null,null)}async createMoveCheckoutJob(e,t){let r=await (0,i.getPrismaClient)(),a=await r.codebase.findUnique({where:{id:e.targetCodebaseId},include:{agent:!0,repository:!0}});if(!a)throw Error("Destination codebase no longer exists");if(!k(a.agent))throw Error("Destination agent is offline");if(!S(a.agent).includes(l.WORKTREE_MOVE_CHECKOUT_JOB_KIND))throw Error("Destination agent must be updated to move worktrees");let n=e.targetWorktreeId?await r.worktree.findFirst({where:{id:e.targetWorktreeId,codebaseId:a.id,missingAt:null,availability:"AVAILABLE"}}):null;if("EXISTING"===e.destinationMode&&!n)throw Error("Destination worktree is no longer available");return this.agentControl.createJob({agentId:a.agentId,codebaseId:a.id,worktreeId:n?.id??null,kind:l.WORKTREE_MOVE_CHECKOUT_JOB_KIND,payload:{moveId:e.id,codebaseId:a.id,rootFolder:a.folder,folder:n?.folder??null,gitDirectory:n?.gitDirectory??null,expectedOrigin:a.repository.canonicalOrigin,branch:e.branch,expectedHeadSha:e.headSha,baseBranch:e.baseBranch,mode:e.destinationMode,stashOnFailure:t},idempotencyKey:`worktree:move:checkout:${e.id}:${t?"stash":"initial"}`,timeoutSeconds:600})}async advanceMoveAfterPush(e){let t=this.moveIdFromJob(e),r=await (0,i.getPrismaClient)(),a=await r.worktreeMove.findUnique({where:{id:t}});if(!a||"PUSHING"!==a.status||a.sourceJobId&&a.sourceJobId!==e.id)return;if("SUCCEEDED"!==e.status)return void await this.failMove(a.id,"PUSHING",e.error||"Could not push the source branch");let n=R(e);if(n.headSha!==a.headSha||n.branch!==a.branch)return void await this.failMove(a.id,"PUSHING","The source push returned an unexpected branch");try{let e=await this.createMoveCheckoutJob(a,!1);await r.worktreeMove.updateMany({where:{id:a.id,status:"PUSHING"},data:{status:"CHECKING_OUT",targetJobId:e.id}}),this.publish(a.sourceWorktreeId,a.sourceCodebaseId)}catch(e){await this.failMove(a.id,"PUSHING",e instanceof Error?e.message:String(e))}}async projectMoveDestination(e,r){let a=(0,l.parseWorktreeInventoryItem)(r),n=await (0,i.getPrismaClient)(),s=await n.codebase.findUnique({where:{id:e.targetCodebaseId},select:{localBranchesJson:!0}});if(!s)throw Error("Destination codebase no longer exists");let o=new Set(E(s.localBranchesJson));a.branch&&o.add(a.branch);let u=e.targetWorktreeId;return await n.$transaction(async r=>{if(await r.codebase.update({where:{id:e.targetCodebaseId},data:{localBranchesJson:JSON.stringify([...o].sort((e,t)=>e.localeCompare(t)))}}),u){if(1!==(await r.worktree.updateMany({where:{id:u,codebaseId:e.targetCodebaseId},data:{...this.inventoryData(a),gitDirectory:a.gitDirectory,baseBranchOverride:e.baseBranch,missingAt:null}})).count)throw Error("Destination worktree no longer exists")}else u=(await r.worktree.upsert({where:{codebaseId_gitDirectory:{codebaseId:e.targetCodebaseId,gitDirectory:a.gitDirectory}},create:{id:(0,t.randomUUID)(),codebaseId:e.targetCodebaseId,gitDirectory:a.gitDirectory,...this.inventoryData(a),baseBranchOverride:e.baseBranch},update:{...this.inventoryData(a),baseBranchOverride:e.baseBranch,missingAt:null}})).id;await r.worktreeMove.update({where:{id:e.id},data:{targetWorktreeId:u}})}),this.publish(u??null,e.targetCodebaseId),await this.skillsService?.requestAutoReconcile(),u}async scheduleMoveCleanup(e){let t=await (0,i.getPrismaClient)(),r=await t.worktreeMove.findUniqueOrThrow({where:{id:e}}),a=await t.worktree.findUnique({where:{id:r.sourceWorktreeId},include:{codebase:{include:{agent:!0,repository:!0}}}});if(!a||a.missingAt||a.primary){await t.worktreeMove.update({where:{id:r.id},data:{status:"SUCCEEDED_WITH_WARNING",warning:"Destination is ready, but the source worktree could not be removed",finishedAt:new Date}}),this.publish(r.sourceWorktreeId,r.sourceCodebaseId);return}try{let e=await this.agentControl.createJob({agentId:a.codebase.agentId,codebaseId:a.codebaseId,worktreeId:a.id,kind:l.WORKTREE_DELETE_JOB_KIND,payload:{moveId:r.id,codebaseId:a.codebaseId,rootFolder:a.codebase.folder,folder:a.folder,gitDirectory:a.gitDirectory,expectedOrigin:a.codebase.repository.canonicalOrigin,branch:a.branch,defaultBranch:a.codebase.defaultBranch,deleteRemoteBranch:!1,requireClean:!0,expectedHeadSha:r.headSha},idempotencyKey:`worktree:move:cleanup:${r.id}`,timeoutSeconds:600});await t.worktreeMove.updateMany({where:{id:r.id,status:{in:["PUSHING","CHECKING_OUT","AWAITING_STASH"]}},data:{status:"CLEANING_UP",cleanupJobId:e.id}}),this.publish(a.id,a.codebaseId)}catch(e){await t.worktreeMove.update({where:{id:r.id},data:{status:"SUCCEEDED_WITH_WARNING",warning:e instanceof Error?e.message:String(e),finishedAt:new Date}}),this.publish(a.id,a.codebaseId)}}async advanceMoveAfterCheckout(e){let t=this.moveIdFromJob(e),r=await (0,i.getPrismaClient)(),a=await r.worktreeMove.findUnique({where:{id:t}});if(!a||!["PUSHING","CHECKING_OUT","AWAITING_STASH"].includes(a.status)||a.targetJobId&&a.targetJobId!==e.id)return;if("SUCCEEDED"!==e.status)return void await this.failMove(a.id,a.status,e.error||"Could not check out the destination branch");let n=R(e);if("NEEDS_STASH"===n.outcome){await r.worktreeMove.updateMany({where:{id:a.id,status:{in:["PUSHING","CHECKING_OUT","AWAITING_STASH"]}},data:{status:"AWAITING_STASH",error:"string"==typeof n.message?n.message:"Destination changes block the branch switch"}}),this.publish(a.sourceWorktreeId,a.sourceCodebaseId);return}"CHECKED_OUT"===n.outcome&&n.worktree?(await this.projectMoveDestination(a,n.worktree),a.deleteSource?await this.scheduleMoveCleanup(a.id):(await r.worktreeMove.update({where:{id:a.id},data:{status:"SUCCEEDED",error:null,finishedAt:new Date}}),this.publish(a.sourceWorktreeId,a.sourceCodebaseId))):await this.failMove(a.id,a.status,"Destination checkout returned an invalid result")}async projectDeleteOperation(e){let t=JSON.parse(e.payloadJson),r=t&&"object"==typeof t&&!Array.isArray(t)&&"string"==typeof t.moveId?String(t.moveId):null,a=await (0,i.getPrismaClient)();if(r){let t=await a.worktreeMove.findUnique({where:{id:r}});if(!t||!["PUSHING","CHECKING_OUT","AWAITING_STASH","CLEANING_UP"].includes(t.status)||t.cleanupJobId&&t.cleanupJobId!==e.id)return;if("SUCCEEDED"!==e.status){await a.worktreeMove.update({where:{id:t.id},data:{status:"SUCCEEDED_WITH_WARNING",warning:e.error||"Destination is ready, but the source worktree was retained",finishedAt:new Date}}),this.publish(t.sourceWorktreeId,t.sourceCodebaseId);return}await a.$transaction([a.worktree.deleteMany({where:{id:t.sourceWorktreeId}}),a.worktreeMove.update({where:{id:t.id},data:{status:"SUCCEEDED",finishedAt:new Date}})]),this.publish(t.sourceWorktreeId,t.sourceCodebaseId);return}if("SUCCEEDED"!==e.status||!e.worktreeId)return;let n=await a.worktree.findUnique({where:{id:e.worktreeId},select:{codebaseId:!0}});await a.worktree.deleteMany({where:{id:e.worktreeId}}),this.publish(e.worktreeId,n?.codebaseId??null)}async projectOperation(e){if(!e.worktreeId||"SUCCEEDED"!==e.status||!e.resultJson)return;let t=R({...e,error:null});if(!t.worktree)return;let r=(0,l.parseWorktreeInventoryItem)(t.worktree),a=await (0,i.getPrismaClient)(),n=await a.worktree.findUnique({where:{id:e.worktreeId}});if(!n)return;let s=new Date(r.checkedAt);(await a.worktree.updateMany({where:{id:n.id,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:s}}]},data:{branch:r.branch,headSha:r.headSha,upstream:r.upstream,ahead:r.ahead,behind:r.behind,syncState:r.syncState,baseAhead:r.baseAhead,baseBehind:r.baseBehind,hasStagedChanges:r.hasStagedChanges??!1,hasUnstagedChanges:r.hasUnstagedChanges??!1,rebaseInProgress:r.rebaseInProgress??!1,hasConflicts:r.hasConflicts??!1,pushStatus:r.pushStatus??"UNKNOWN",availability:r.availability,statusError:r.error,lastCheckedAt:s}})).count>0&&this.publish(n.id,n.codebaseId)}async projectBranchOperation(e){if(!e.codebaseId||"SUCCEEDED"!==e.status||!e.resultJson)return;let r=R({...e,error:null});if(!r.worktree||"string"!=typeof r.baseBranch)return;let a=(0,l.parseWorktreeInventoryItem)(r.worktree),n=await (0,i.getPrismaClient)(),s=await n.codebase.findUnique({where:{id:e.codebaseId},select:{localBranchesJson:!0}});if(!s)return;let o=new Set(E(s.localBranchesJson));a.branch&&o.add(a.branch);let u=e.worktreeId;await n.$transaction(async i=>{if(await i.codebase.update({where:{id:e.codebaseId},data:{localBranchesJson:JSON.stringify([...o].sort((e,t)=>e.localeCompare(t)))}}),e.worktreeId){if(1!==(await i.worktree.updateMany({where:{id:e.worktreeId,codebaseId:e.codebaseId},data:{...this.inventoryData(a),gitDirectory:a.gitDirectory,baseBranchOverride:r.baseBranch,missingAt:null}})).count)throw Error("Worktree no longer exists");return}u=(await i.worktree.upsert({where:{codebaseId_gitDirectory:{codebaseId:e.codebaseId,gitDirectory:a.gitDirectory}},create:{id:(0,t.randomUUID)(),codebaseId:e.codebaseId,gitDirectory:a.gitDirectory,...this.inventoryData(a),baseBranchOverride:r.baseBranch},update:{...this.inventoryData(a),baseBranchOverride:r.baseBranch,missingAt:null}})).id}),this.publish(u??null,e.codebaseId),!e.worktreeId&&u&&await this.recordWorktreeCreated(u),await this.skillsService?.requestAutoReconcile(),e.worktreeId&&await this.restartWatch(e.worktreeId)}async recordWorktreeCreated(e){if(!this.workflowEvents)return;let t=await this.workflowSessionDataForWorktree(e);Object.keys(t).length&&await this.workflowEvents.record({kind:"WORKTREE_CREATED",subjectKey:e,dedupeKey:`worktree-created:${e}`,payload:{...t,sessionData:t}})}async waitForJob(e){let t=n.agentEventBus.iterate((0,n.agentJobChangedTopic)(e)),r=Date.now()+3e4;try{for(;Date.now()<r;){let i=await this.agentControl.getJob(e);if(!i)throw Error("Worktree job disappeared");if(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"].includes(i.status))return i;await Promise.race([t.next(),new Promise(e=>setTimeout(e,r-Date.now()))])}throw await this.agentControl.cancelJob(e),Error("Agent did not respond in time")}finally{await t.return?.()}}},"worktreeDisplayPath",0,C],504173),e.s(["executingResourcesByWorktree",0,D],518733);let N=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT","INVALID"]),O={agents:{include:{agent:!0}},jobs:{orderBy:{createdAt:"asc"}}};function P(e){return null!==e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(e)&&null===e.disconnectedAt}function $(e){try{let t=JSON.parse(e.capabilitiesJson);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function U(e){return null===e?null:JSON.parse(e)}function B(e){let t=U(e.payloadJson);return(e.kind===r.BUILD_DATA_DELETE_JOB_KIND?(0,r.buildDataDeletePayload)(t).targets:(0,r.buildDataTargetsPayload)(t).targets).map(e=>e.path)}function j(e,t){let i=e===r.BUILD_DATA_DELETE_JOB_KIND?"delete":"size";return`Invalid Build Data ${i} result: ${t instanceof Error?t.message:String(t)}`}function L(e,t,r){try{for(let i of B(t)){let a=e.get(q(t.agentId,i));a&&(a.error=r)}}catch{}}function q(e,r){return(0,t.createHash)("sha256").update(e).update("\0").update(r).digest("base64url")}e.s(["BuildDataService",0,class{agentControlService;initialized;constructor(e){this.agentControlService=e,this.initialized=!1,this.agentControlService.registerCompletionHandler(r.BUILD_DATA_DELETE_JOB_KIND,e=>this.projectDeletion(e))}async initialize(){this.initialized||(await this.pruneHistory(),this.initialized=!0)}async refresh(e){await this.initialize();let r=e?.trim()||(0,t.randomUUID)();return await this.ensureCollection(r),await this.getCollection(r)}async getCollection(e){await this.initialize();let t=await this.loadCollection(e);if(!t)return null;!t.finishedAt&&t.deadlineAt.getTime()<=Date.now()&&(await this.expireCollection(t),t=await this.loadCollection(e)??t);let r=await this.snapshot(t);if("COMPLETED"===r.status&&!t.finishedAt){let t=new Date,a=await (0,i.getPrismaClient)();await a.buildDataCollection.updateMany({where:{id:e,finishedAt:null},data:{finishedAt:t}}),r.finishedAt=t.toISOString()}return r}async *subscribe(e){await this.initialize();let t=n.agentEventBus.iterate((0,n.buildDataCollectionChangedTopic)(e));try{let r=await this.getCollection(e);for(r&&(yield r);;){if((await t.next()).done)return;let r=await this.getCollection(e);r&&(yield r)}}finally{await t.return?.()}}async calculateSizes(e,t,i){let a=await this.requireCollection(e);return await this.createTargetJobs(a,t,i,r.BUILD_DATA_SIZE_JOB_KIND),await this.getCollection(e)}async deleteEntries(e,t,i,a=!1){let n=await this.requireCollection(e);return await this.createTargetJobs(n,t,i,r.BUILD_DATA_DELETE_JOB_KIND,a),await this.getCollection(e)}async history(e=100,t){await this.initialize(),await this.pruneHistory();let r=Math.max(1,Math.min(e,200)),a=await (0,i.getPrismaClient)(),n=t?await a.buildDataDeletionHistory.findUnique({where:{id:t},select:{id:!0,deletedAt:!0}}):null,s=await a.buildDataDeletionHistory.findMany({where:n?{OR:[{deletedAt:{lt:n.deletedAt}},{deletedAt:n.deletedAt,id:{lt:n.id}}]}:void 0,orderBy:[{deletedAt:"desc"},{id:"desc"}],take:r+1}),o=s.length>r,l=s.slice(0,r);return{items:l,nextCursor:o?l.at(-1)?.id??null:null}}async clearHistory(){await this.initialize();let e=await (0,i.getPrismaClient)();return(await e.buildDataDeletionHistory.deleteMany()).count}async ensureCollection(e){let t=await (0,i.getPrismaClient)(),a=await t.buildDataCollection.findUnique({where:{id:e},select:{id:!0}});if(!a){let i=await this.agentControlService.listAgents();try{a=await t.buildDataCollection.create({data:{id:e,deadlineAt:new Date(Date.now()+6e4),agents:{create:i.map(e=>({agentId:e.id,initialStatus:P(e)?$(e).includes(r.BUILD_DATA_SCAN_JOB_KIND)?"QUEUING":"UNSUPPORTED":"OFFLINE"}))}},select:{id:!0}}),this.publish(e)}catch(r){if(!(a=await t.buildDataCollection.findUnique({where:{id:e},select:{id:!0}})))throw r}}await this.ensureScanJobs(e)}async ensureScanJobs(e){let t=await (0,i.getPrismaClient)(),a=await t.buildDataCollection.findUnique({where:{id:e},select:{deadlineAt:!0,finishedAt:!0}});if(!a||a.finishedAt||a.deadlineAt<=new Date)return;let n=await t.buildDataCollectionAgent.findMany({where:{collectionId:e,initialStatus:"QUEUING"},include:{agent:!0}}),s=new Set((await t.agentJob.findMany({where:{buildDataCollectionId:e,kind:r.BUILD_DATA_SCAN_JOB_KIND},select:{agentId:!0}})).map(e=>e.agentId));for(let i of n)if(!s.has(i.agentId))try{let a=await t.worktree.findMany({where:{missingAt:null,codebase:{agentId:i.agentId}},select:{id:!0,folder:!0}});await this.agentControlService.createJob({agentId:i.agentId,kind:r.BUILD_DATA_SCAN_JOB_KIND,payload:{mode:i.agent.derivedDataLocationMode,path:i.agent.derivedDataPath,worktrees:a},idempotencyKey:`build-data:scan:${e}`,timeoutSeconds:45,buildDataCollectionId:e,visibility:"SYSTEM"})}catch(r){await t.buildDataCollectionAgent.update({where:{collectionId_agentId:{collectionId:e,agentId:i.agentId}},data:{initialStatus:"FAILED",error:r instanceof Error?r.message:String(r)}}),this.publish(e)}}async createTargetJobs(e,t,a,n,s=!1){let o=[...new Set(t)];if(!o.length)throw Error("Select at least one Derived Data entry");let l=new Map(e.entries.map(e=>[e.id,e])),u=o.map(e=>{let t=l.get(e);if(!t)throw Error("A selected Derived Data entry is no longer available");return t});if(n===r.BUILD_DATA_DELETE_JOB_KIND&&!s){let e=u.filter(e=>e.locked||e.activeResources.length>0);if(e.length)throw Error(`Explicit override confirmation is required to delete protected Derived Data: ${e.map(e=>e.name).join(", ")}`)}let c=new Map;for(let e of u){let t=c.get(e.agent.id)??[];t.push(e),c.set(e.agent.id,t)}let d=await (0,i.getPrismaClient)(),p=[];for(let[e,t]of c){let r=t[0].agent,i=await d.agent.findUnique({where:{id:e}});if(!i||!P(i))throw Error(`${r.name} is offline; reconnect it before running this operation`);if(!$(i).includes(n))throw Error(`${r.name} must be updated before this operation can run`);p.push({agentId:e,entries:t})}for(let{agentId:t,entries:i}of p){let s=n===r.BUILD_DATA_DELETE_JOB_KIND?[...new Map(i.filter(e=>!!e.worktreeId).map(e=>[e.worktreeId,e])).values()]:[],o=[];try{for(let e of s)await d.derivedDataCleanupLease.create({data:{worktreeId:e.worktreeId,agentId:t,path:e.path,source:"USER",expiresAt:new Date(Date.now()+6048e5)}}),o.push(e.worktreeId);let r=await this.agentControlService.createJob({agentId:t,kind:n,payload:{targets:i.map(({path:e,rootPath:t})=>({path:e,rootPath:t}))},idempotencyKey:`${n}:${e.id}:${a}:${t}`,timeoutSeconds:604800,buildDataCollectionId:e.id,visibility:"SYSTEM"});s.length&&await d.derivedDataCleanupLease.updateMany({where:{worktreeId:{in:s.map(e=>e.worktreeId)},jobId:null},data:{jobId:r.id}})}catch(e){throw o.length&&await d.derivedDataCleanupLease.deleteMany({where:{worktreeId:{in:o},source:"USER",jobId:null}}),e}}}async requireCollection(e){let t=await this.getCollection(e);if(!t)throw Error("Derived Data collection not found");if("COMPLETED"!==t.status)throw Error("Wait for the Derived Data scan to finish");return t}async loadCollection(e){return(await (0,i.getPrismaClient)()).buildDataCollection.findUnique({where:{id:e},include:O})}progress(e){let t=new Map(e.jobs.filter(e=>e.kind===r.BUILD_DATA_SCAN_JOB_KIND).map(e=>[e.agentId,e])),i=e.agents.map(e=>{let i=t.get(e.agentId),a=e.initialStatus,n=e.error,s=[];if("QUEUING"===e.initialStatus&&i&&(a=i.status,n=i.error,"SUCCEEDED"===i.status))try{s=(0,r.parseBuildDataScanResult)(U(i.resultJson)).warnings}catch(e){a="INVALID",n=e instanceof Error?e.message:String(e)}return{agent:e.agent,status:a,jobId:i?.id??null,error:n,warnings:s}}),a=i.filter(({status:e})=>"OFFLINE"!==e&&"UNSUPPORTED"!==e),n=a.filter(({status:e})=>N.has(e));return{agents:i,eligibleCount:a.length,finishedCount:n.length,successfulCount:a.filter(({status:e})=>"SUCCEEDED"===e).length}}async snapshot(e){let t=this.progress(e),r=await this.entries(e,!1);return{id:e.id,status:t.finishedCount===t.eligibleCount?"COMPLETED":"COLLECTING",createdAt:e.createdAt.toISOString(),deadlineAt:e.deadlineAt.toISOString(),finishedAt:e.finishedAt?.toISOString()??null,progress:t,entries:r}}async entries(e,t){let a=await (0,i.getPrismaClient)(),n=new Map(e.agents.map(e=>[e.agentId,e.agent])),s=await a.worktree.findMany({where:{missingAt:null,codebase:{agentId:{in:[...n.keys()]}}},include:{codebase:{select:{agentId:!0}}}}),o=new Map;for(let e of s){let t=o.get(e.codebase.agentId)??[];t.push(e),o.set(e.codebase.agentId,t)}let l=new Map;for(let t of e.jobs){let e;if(t.kind!==r.BUILD_DATA_SCAN_JOB_KIND||"SUCCEEDED"!==t.status)continue;let i=n.get(t.agentId);if(i){try{e=(0,r.parseBuildDataScanResult)(U(t.resultJson))}catch{continue}for(let r of e.entries){let e=(r.workspacePath?(o.get(t.agentId)??[]).filter(e=>(function(e,t){let r="/"===e?e:e.replace(/\/+$/,"");return t===r||t.startsWith(`${r}/`)})(e.folder,r.workspacePath)).sort((e,t)=>t.folder.length-e.folder.length):[])[0]??null,a=q(t.agentId,r.path);l.set(a,{id:a,name:r.name,kind:r.kind,status:"DEVICE_SUPPORT"===r.kind?"READY":"PENDING"===r.kind?"PENDING":"SHARED_CACHE"===r.kind?"SHARED_CACHE":e?"READY":"UNLINKED",workspacePath:r.workspacePath,worktreeId:e?.id??null,worktreePath:e?C(e.folder,i.baseRepoDirectory):null,sizeBytes:null,operation:"IDLE",error:null,agent:i,path:r.path,rootPath:r.rootPath,modifiedAt:r.modifiedAt,volumeId:r.volumeId,locked:!1,activeResources:[]})}}}for(let i of e.jobs){if(i.kind===r.BUILD_DATA_SIZE_JOB_KIND&&"SUCCEEDED"===i.status)try{for(let e of(0,r.parseBuildDataSizeResult)(U(i.resultJson)).sizes){let t=l.get(q(i.agentId,e.path));t&&(t.sizeBytes=e.sizeBytes,t.error=e.error)}}catch(e){L(l,i,j(r.BUILD_DATA_SIZE_JOB_KIND,e))}if(i.kind===r.BUILD_DATA_DELETE_JOB_KIND&&"SUCCEEDED"===i.status)try{for(let e of(0,r.parseBuildDataDeleteResult)(U(i.resultJson)).deleted){let r=q(i.agentId,e.path),a=l.get(r);a&&(e.deleted&&!t?l.delete(r):a.error=e.error)}}catch(e){L(l,i,j(r.BUILD_DATA_DELETE_JOB_KIND,e))}if("QUEUED"===i.status||"RUNNING"===i.status){if(i.kind!==r.BUILD_DATA_SIZE_JOB_KIND&&i.kind!==r.BUILD_DATA_DELETE_JOB_KIND)continue;try{for(let e of B(i)){let t=l.get(q(i.agentId,e));t&&(t.operation=i.kind===r.BUILD_DATA_DELETE_JOB_KIND?"DELETING":"SIZING")}}catch{}}if("SUCCEEDED"!==i.status&&N.has(i.status)&&(i.kind===r.BUILD_DATA_SIZE_JOB_KIND||i.kind===r.BUILD_DATA_DELETE_JOB_KIND))try{for(let e of B(i)){let t=l.get(q(i.agentId,e));t&&(t.error=i.error||"Build Data operation failed")}}catch{}}let u=[...l.values()],c=u.map(e=>e.worktreeId).filter(e=>!!e),[d,p]=await Promise.all([a.derivedDataLock.findMany({where:{OR:u.map(e=>({agentId:e.agent.id,path:e.path}))},select:{agentId:!0,path:!0}}),D(c)]),h=new Set(d.map(e=>`${e.agentId}\0${e.path}`));for(let e of u)e.locked=h.has(`${e.agent.id}\0${e.path}`),e.activeResources=e.worktreeId?p.get(e.worktreeId)??[]:[];return u.sort((e,t)=>e.agent.name.localeCompare(t.agent.name)||(null===e.modifiedAt?1:null===t.modifiedAt?-1:new Date(e.modifiedAt).getTime()-new Date(t.modifiedAt).getTime())||e.name.localeCompare(t.name))}async setEntryLocked(e,r,a){let n=(await this.requireCollection(e)).entries.find(e=>e.id===r);if(!n)throw Error("Derived Data entry not found");let s=await (0,i.getPrismaClient)();return a?await s.derivedDataLock.upsert({where:{agentId_path:{agentId:n.agent.id,path:n.path}},create:{id:(0,t.randomUUID)(),agentId:n.agent.id,path:n.path},update:{}}):await s.derivedDataLock.deleteMany({where:{agentId:n.agent.id,path:n.path}}),this.publish(e),await this.getCollection(e)}async expireCollection(e){let t=await (0,i.getPrismaClient)(),a=new Set(e.jobs.filter(e=>e.kind===r.BUILD_DATA_SCAN_JOB_KIND).map(e=>e.agentId));await t.buildDataCollectionAgent.updateMany({where:{collectionId:e.id,initialStatus:"QUEUING",agentId:{notIn:[...a]}},data:{initialStatus:"TIMED_OUT"}}),await this.agentControlService.timeoutBuildDataCollectionJobs(e.id),this.publish(e.id)}async projectDeletion(e){let a;if("SUCCEEDED"!==e.status||!e.resultJson)return;await this.pruneHistory();let n=await (0,i.getPrismaClient)();if(await n.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))return;try{a=(0,r.parseBuildDataDeleteResult)(U(e.resultJson)).deleted.filter(e=>e.deleted)}catch(i){let t=j(r.BUILD_DATA_DELETE_JOB_KIND,i);try{await n.buildDataDeleteProjection.create({data:{jobId:e.id,error:t}})}catch(t){if(!await n.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))throw t}return}if(!a.length)return void await n.buildDataDeleteProjection.create({data:{jobId:e.id}});let s=(0,r.buildDataDeletePayload)(U(e.payloadJson)),o=e.buildDataCollectionId?await this.loadCollection(e.buildDataCollectionId):null,l=new Map((o?await this.entries(o,!0):[]).filter(t=>t.agent.id===e.agentId).map(e=>[e.path,e])),u=new Map(s.targets.map(e=>[e.path,e])),c=await n.agent.findUnique({where:{id:e.agentId}});if(c)try{await n.$transaction(async r=>{if(!await r.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))for(let i of(await r.buildDataDeleteProjection.create({data:{jobId:e.id}}),a)){let a=l.get(i.path),n=u.get(i.path),o=n?.worktreeId??a?.worktreeId??null,d=o?(await r.worktree.findUnique({where:{id:o},select:{id:!0}}))?.id??null:null;await r.buildDataDeletionHistory.create({data:{id:(0,t.randomUUID)(),agentId:e.agentId,agentName:c.name,folderName:n?.name??a?.name??i.path,worktreeId:d,worktreePath:n?.worktreePath??a?.worktreePath??null,source:s.source,entryKind:n?.kind??a?.kind??"PROJECT",jobId:e.id,targetKey:a?.id??q(e.agentId,i.path)}})}})}catch(t){if(!await n.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))throw t}}async pruneHistory(){let e=await (0,i.getPrismaClient)();await e.buildDataDeletionHistory.deleteMany({where:{deletedAt:{lt:new Date(Date.now()-7776e6)}}})}publish(e){n.agentEventBus.publish(n.BUILD_DATA_CHANGED_TOPIC,{buildDataCollectionChanged:{id:e}}),n.agentEventBus.publish((0,n.buildDataCollectionChangedTopic)(e),{buildDataCollectionChanged:{id:e}})}}],925991),e.s([],396763)},971619,e=>{"use strict";var t=e.i(750227);e.s(["effectiveBuildsDirectory",0,function(e){var r;return e.buildsDirectory??((r=e.baseRepoDirectory)?/^[a-z]:[\\/]/i.test(r)||r.startsWith("\\\\")?t.win32.join(r,"Builds"):t.posix.join(r,"Builds"):null)}])},224174,669602,190714,646462,890564,e=>{"use strict";var t=e.i(666680),r=e.i(750227),i=e.i(807055),a=e.i(503083),n=e.i(243783);e.i(805422);var s=e.i(694355),o=e.i(661983),l=e.i(971619);let u=new Set(i.BUILD_CONFIGURATION_ICON_KEYS),c=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]),d=["QUEUED","PREPARING","RUNNING"];function p(e,t=null){if(null===e)return t;try{return JSON.parse(e)}catch{return t}}function h(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${t} must be an object`);return e}function m(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function f(e){return null!==e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=(0,s.agentOnlineWindowMs)(e)&&null===e.disconnectedAt}function g(e){return m(p(e.capabilitiesJson,[]))}function y(e,t,r=80){let i=e.trim();if(!i)throw Error(`${t} is required`);if(i.length>r)throw Error(`${t} is too long`);return i}function w(e){return`${e.type}:${e.id}`}function b(e){if(e.codebaseId)return e.codebaseId;let t=p(e.snapshotJson,{});if(t&&"object"==typeof t&&!Array.isArray(t)){let e=t.codebase;if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.id;if("string"==typeof t&&t.trim())return t}}throw Error("Build coordination metadata is unavailable")}function v(e){return"SUCCEEDED"===e?"SUCCEEDED":"CANCELLED"===e?"CANCELLED":"FAILED"}let k={agent:!0,codebase:{include:{repository:!0}},worktree:{include:{_count:{select:{builds:{where:{status:{in:d}}}}}}},configuration:{include:{source:!0,project:!0}},artifacts:{orderBy:{createdAt:"asc"}},scriptExecutions:{orderBy:[{phase:"asc"},{position:"asc"}]},deployments:{orderBy:{createdAt:"desc"}},exports:{orderBy:{createdAt:"desc"}}};e.s(["BuildsService",0,class{agentControl;telemetry;notifications;diskSpace;constructor(e,t,r,n){this.agentControl=e,this.telemetry=t,this.notifications=r,this.diskSpace=n,this.agentControl.registerCompletionHandler(i.IOS_BUILD_JOB_KIND,e=>this.projectBuildCompletion(e)),this.agentControl.registerCompletionHandler(i.IOS_DEPLOY_JOB_KIND,e=>this.projectDeploymentCompletion(e)),this.agentControl.registerCompletionHandler(i.IOS_EXPORT_JOB_KIND,e=>this.projectExportCompletion(e)),this.agentControl.registerCompletionHandler(i.IOS_TEST_RESULTS_JOB_KIND,e=>this.projectGeneratedReportCompletion(e)),this.agentControl.registerCompletionHandler(i.IOS_COVERAGE_REPORT_JOB_KIND,e=>this.projectGeneratedReportCompletion(e)),this.agentControl.registerCompletionHandler(a.COVERAGE_IMPORT_JOB_KIND,e=>this.importedCoverageCompletion(e))}publish(e){o.agentEventBus.publish((0,o.buildTopic)(e),{buildChanged:{id:e}}),o.agentEventBus.publish(o.BUILDS_CHANGED_TOPIC,{buildsChanged:{id:e}}),o.agentEventBus.publish(o.SIDEBAR_STATUS_CHANGED_TOPIC,{sidebarStatusChanged:!0})}async requireWorktree(e,t,r="Agent must be updated to use iOS builds"){let i=await (0,n.getPrismaClient)(),a=await i.worktree.findUnique({where:{id:e},include:{codebase:{include:{agent:!0,repository:!0}}}});if(!a||a.missingAt||"AVAILABLE"!==a.availability)throw Error("Worktree is unavailable");if(!f(a.codebase.agent))throw Error("Agent is offline");if(!g(a.codebase.agent).includes(t))throw Error(r);return a}identity(e){return{codebaseId:e.codebaseId,worktreeId:e.id,branch:e.branch,folder:e.folder,gitDirectory:e.gitDirectory,expectedOrigin:e.codebase.repository.canonicalOrigin,headSha:e.headSha,baseBranch:e.baseBranchOverride??e.codebase.defaultBranch??null}}async ensureProject(e){let r=await (0,n.getPrismaClient)(),i=await r.codebase.findUnique({where:{id:e},select:{repositoryId:!0}});if(!i)throw Error("Codebase not found");return r.codebaseProject.upsert({where:{repositoryId_type:{repositoryId:i.repositoryId,type:"IOS_APP"}},create:{id:(0,t.randomUUID)(),repositoryId:i.repositoryId,type:"IOS_APP"},update:{}})}async project(e){let t=await (0,n.getPrismaClient)(),r=await t.codebase.findUnique({where:{id:e},include:{repository:!0}});if(!r)return null;let i=await t.codebaseProject.findUnique({where:{repositoryId_type:{repositoryId:r.repositoryId,type:"IOS_APP"}},include:{configurations:{orderBy:{name:"asc"},include:{source:{include:{observations:{where:{codebaseId:e},orderBy:{lastParseAttemptAt:"desc"},take:1}}}}}}}),a=await t.codebaseRepositoryBuildScript.findMany({where:{repositoryId:r.repositoryId,script:{deletedAt:null}},orderBy:[{position:"asc"},{script:{name:"asc"}}],include:{script:!0}});return i?{...i,repository:r.repository,allowedScripts:a}:null}async createProject(e){return await this.ensureProject(e),this.project(e)}async projectForWorktree(e){let t=await (0,n.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e},select:{codebaseId:!0}});return r?this.project(r.codebaseId):null}async saveConfiguration(e){let r=await this.ensureProject(e.codebaseId),a=(0,i.parseBuildSource)({kind:e.sourceKind,relativePath:e.sourcePath}),s=y(e.name,"Configuration name"),o=y(e.scheme,"Scheme",256),l=y(e.buildConfiguration,"Xcode configuration",256);if(!i.BUILD_ACTIONS.includes(e.defaultAction))throw Error("Build action is invalid");let c=e.iconKey?.trim()||null;if(c&&!u.has(c))throw Error("Icon is invalid");let d=(0,i.parseBuildAdvancedSettings)(e.advancedSettings??i.DEFAULT_BUILD_ADVANCED_SETTINGS),p=!0===e.autoExport;if(p&&"ARCHIVE"!==e.defaultAction)throw Error("Auto Export is available only for Archive configurations");let h=e.exportSettings?(0,i.parseBuildExportSettings)(e.exportSettings):null;if(p&&!h)throw Error("Auto Export settings are required");let m=await (0,n.getPrismaClient)(),f=e.id?await m.buildConfiguration.findUnique({where:{id:e.id}}):null;if(e.id&&(!f||f.projectId!==r.id))throw Error("Build configuration not found");let g=await m.buildSource.upsert({where:{projectId_relativePath:{projectId:r.id,relativePath:a.relativePath}},create:{id:(0,t.randomUUID)(),projectId:r.id,kind:a.kind,relativePath:a.relativePath},update:{kind:a.kind}}),w=f?.id??(0,t.randomUUID)();return m.buildConfiguration.upsert({where:{id:w},create:{id:w,projectId:r.id,sourceId:g.id,name:s,iconKey:c,scheme:o,buildConfiguration:l,defaultAction:e.defaultAction,advancedSettingsJson:JSON.stringify(d),autoExport:p,exportSettingsJson:h?JSON.stringify(h):null},update:{sourceId:g.id,name:s,iconKey:c,scheme:o,buildConfiguration:l,defaultAction:e.defaultAction,advancedSettingsJson:JSON.stringify(d),autoExport:p,exportSettingsJson:h?JSON.stringify(h):null},include:{source:!0}})}async deleteConfiguration(e){let t=await (0,n.getPrismaClient)();if(await t.build.findFirst({where:{configurationId:e,status:{in:d}}}))throw Error("Configuration has an active build");return 1===(await t.buildConfiguration.deleteMany({where:{id:e}})).count}async scripts(){return(await (0,n.getPrismaClient)()).buildScript.findMany({where:{deletedAt:null},orderBy:{name:"asc"}})}async saveScript(e){let r=y(e.name,"Script name"),a=e.preBuildScript?.trim()||null,s=e.postBuildScript?.trim()||null;if(!a&&!s)throw Error("A pre-build or post-build script is required");let o=e.timeoutSeconds??300;if(!Number.isInteger(o)||o<1||o>3600)throw Error("Script timeout must be between 1 and 3600 seconds");if(!i.BUILD_SCRIPT_FAILURE_BEHAVIORS.includes(e.failureBehavior))throw Error("Script failure behavior is invalid");let l=await (0,n.getPrismaClient)(),u=e.id??(0,t.randomUUID)();return l.buildScript.upsert({where:{id:u},create:{id:u,name:r,preBuildScript:a,postBuildScript:s,enabledByDefault:e.enabledByDefault,timeoutSeconds:o,failureBehavior:e.failureBehavior},update:{name:r,preBuildScript:a,postBuildScript:s,enabledByDefault:e.enabledByDefault,timeoutSeconds:o,failureBehavior:e.failureBehavior,deletedAt:null}})}async deleteScript(e){let t=await (0,n.getPrismaClient)(),r=await t.buildScript.updateMany({where:{id:e,deletedAt:null},data:{deletedAt:new Date}});return await t.codebaseRepositoryBuildScript.deleteMany({where:{scriptId:e}}),1===r.count}async setAllowedScripts(e,t){let r=await (0,n.getPrismaClient)(),i=await r.codebase.findUnique({where:{id:e}});if(!i)throw Error("Codebase not found");let a=[...new Set(t)];if((await r.buildScript.findMany({where:{id:{in:a},deletedAt:null}})).length!==a.length)throw Error("Build script not found");return await r.$transaction(async e=>{await e.codebaseRepositoryBuildScript.deleteMany({where:{repositoryId:i.repositoryId}}),a.length&&await e.codebaseRepositoryBuildScript.createMany({data:a.map((e,t)=>({repositoryId:i.repositoryId,scriptId:e,position:t}))})}),this.project(e)}async waitForJob(e,t=12e4){let r=o.agentEventBus.iterate((0,o.agentJobChangedTopic)(e)),i=Date.now()+t;try{for(;Date.now()<i;){let t=await this.agentControl.getJob(e);if(!t)throw Error("Agent job disappeared");if(c.has(t.status))return t;await Promise.race([r.next(),new Promise(e=>setTimeout(e,Math.max(1,i-Date.now())))])}throw await this.agentControl.cancelJob(e),Error("Agent did not respond in time")}finally{await r.return?.()}}result(e){if("SUCCEEDED"!==e.status)throw Error(e.error||"Agent operation failed");return h(p(e.resultJson,{}),"agent result")}async discoverSources(e,t){let r=await this.requireWorktree(e,i.IOS_SOURCE_DISCOVER_JOB_KIND),a=await this.agentControl.createJob({agentId:r.codebase.agentId,codebaseId:r.codebaseId,worktreeId:r.id,kind:i.IOS_SOURCE_DISCOVER_JOB_KIND,payload:this.identity(r),idempotencyKey:`ios:source:discover:${t}:${r.id}`,timeoutSeconds:60,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(a.id));return Array.isArray(e.sources)?e.sources:[]}finally{let e=await (0,n.getPrismaClient)();await e.agentJob.deleteMany({where:{id:a.id,visibility:"SYSTEM"}})}}async reparse(e,r,a){let s=await this.requireWorktree(r,i.IOS_SOURCE_PARSE_JOB_KIND),o=await (0,n.getPrismaClient)(),l=await o.buildConfiguration.findUnique({where:{id:e},include:{source:{include:{project:!0}}}});if(!l||l.source.project.repositoryId!==s.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let u=`worktree:${s.id}`,c=await o.buildSourceObservation.findUnique({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:u}}}),d=new Date;await o.buildSourceObservation.upsert({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:u}},create:{id:(0,t.randomUUID)(),sourceId:l.sourceId,scopeKey:u,codebaseId:s.codebaseId,worktreeId:s.id,status:"PARSING",lastParseAttemptAt:d},update:{status:"PARSING",error:null,lastParseAttemptAt:d}});let p=await this.agentControl.createJob({agentId:s.codebase.agentId,codebaseId:s.codebaseId,worktreeId:s.id,kind:i.IOS_SOURCE_PARSE_JOB_KIND,payload:{...this.identity(s),source:{kind:l.source.kind,relativePath:l.source.relativePath},scheme:l.scheme},idempotencyKey:`ios:source:parse:${a}:${l.id}:${s.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(p.id)),t=m(e.schemes),r=m(e.configurations),i=t.includes(l.scheme)&&r.includes(l.buildConfiguration);return o.buildSourceObservation.update({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:u}},data:{status:i?"VALID":"INVALID",schemesJson:JSON.stringify(t),configurationsJson:JSON.stringify(r),testPlansJson:JSON.stringify(m(e.testPlans)),error:i?null:"The saved scheme or configuration is no longer available",stale:!1,headSha:"string"==typeof e.headSha?e.headSha:s.headSha,xcodeVersion:"string"==typeof e.xcodeVersion?e.xcodeVersion:null,lastParsedAt:new Date}})}catch(t){let e=t instanceof Error?t.message:String(t);return o.buildSourceObservation.update({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:u}},data:{status:"ERROR",error:e,stale:!!c?.lastParsedAt}})}finally{await o.agentJob.deleteMany({where:{id:p.id,visibility:"SYSTEM"}})}}async inspectSource(e){let t=await this.requireWorktree(e.worktreeId,i.IOS_SOURCE_PARSE_JOB_KIND),r=(0,i.parseBuildSource)({kind:e.sourceKind,relativePath:e.sourcePath}),a=await this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:i.IOS_SOURCE_PARSE_JOB_KIND,payload:{...this.identity(t),source:r,scheme:e.scheme?.trim()||null,configuration:e.configuration?.trim()||null},idempotencyKey:`ios:source:inspect:${e.requestId}:${t.id}:${r.relativePath}:${e.scheme??""}:${e.configuration??""}`,timeoutSeconds:120,visibility:"SYSTEM"});try{var s;let e=this.result(await this.waitForJob(a.id));return{source:r,schemes:m(e.schemes),configurations:m(e.configurations),testPlans:m(e.testPlans),signingRequirements:(s=e.signingRequirements,Array.isArray(s)?s.flatMap(e=>!e||"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.bundleId||"string"!=typeof e.name||"string"!=typeof e.target?[]:[{bundleId:e.bundleId,name:e.name,target:e.target,platform:"string"==typeof e.platform?e.platform:null,teamId:"string"==typeof e.teamId?e.teamId:null,provisioningProfileSpecifier:"string"==typeof e.provisioningProfileSpecifier?e.provisioningProfileSpecifier:null}]):[]),headSha:"string"==typeof e.headSha?e.headSha:t.headSha,xcodeVersion:"string"==typeof e.xcodeVersion?e.xcodeVersion:null}}finally{let e=await (0,n.getPrismaClient)();await e.agentJob.deleteMany({where:{id:a.id,visibility:"SYSTEM"}})}}async destinations(e){let t=await this.requireWorktree(e.worktreeId,i.IOS_DESTINATIONS_JOB_KIND),r=await (0,n.getPrismaClient)(),a=await r.buildConfiguration.findUnique({where:{id:e.configurationId},include:{source:{include:{project:!0}}}});if(!a||a.source.project.repositoryId!==t.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let s=e.action??a.defaultAction;if(!i.BUILD_ACTIONS.includes(s))throw Error("Build action is invalid");let o=function(e){if(!i.GENERIC_BUILD_DESTINATION_ACTIONS.includes(e))return[];let t={type:"PHYSICAL_DEVICE",id:"generic-ios",name:"Any Physical iOS Device",platform:"iOS",osVersion:null,state:null,generic:!0};return"ARCHIVE"===e?[t]:[{type:"SIMULATOR",id:"generic-ios-simulator",name:"Any iOS Simulator",platform:"iOS Simulator",osVersion:null,state:null,generic:!0},t]}(s);if("ARCHIVE"===s)return o;let l=await this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:i.IOS_DESTINATIONS_JOB_KIND,payload:{...this.identity(t),source:{kind:a.source.kind,relativePath:a.source.relativePath},scheme:a.scheme,configuration:a.buildConfiguration,action:s},idempotencyKey:`ios:destinations:${e.requestId}:${a.id}:${t.id}:${s}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(l.id));return Array.isArray(e.destinations)?e.destinations:[]}finally{await r.agentJob.deleteMany({where:{id:l.id,visibility:"SYSTEM"}})}}async signingOptionsForBuild(e){let t=await (0,n.getPrismaClient)(),r=await t.build.findUnique({where:{id:e},include:{artifacts:!0}}),a=r?.artifacts.find(e=>"ARCHIVE"===e.kind);if(!r||"SUCCEEDED"!==r.status||!r.worktreeId)throw Error("A successful archive build is required");if(!a)throw Error("Build does not contain an archive");let s=await this.requireWorktree(r.worktreeId,i.IOS_SIGNING_INSPECT_JOB_KIND),o=await this.agentControl.createJob({agentId:s.codebase.agentId,codebaseId:s.codebaseId,worktreeId:s.id,kind:i.IOS_SIGNING_INSPECT_JOB_KIND,payload:{buildId:r.id,codebaseId:s.codebaseId,artifactDirectory:r.artifactDirectory,archiveRelativePath:a.relativePath},idempotencyKey:`ios:signing:${r.id}:${a.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(o.id));return{teams:Array.isArray(e.teams)?e.teams:[],identities:Array.isArray(e.identities)?e.identities:[],profiles:Array.isArray(e.profiles)?e.profiles:[],bundles:Array.isArray(e.bundles)?e.bundles:[]}}finally{await t.agentJob.deleteMany({where:{id:o.id,visibility:"SYSTEM"}})}}async destinationsForBuild(e,t){let r=await (0,n.getPrismaClient)(),a=await r.build.findUnique({where:{id:e},include:{artifacts:!0}});if(!a||"SUCCEEDED"!==a.status||!a.worktreeId||!a.artifacts.some(e=>"RUNNABLE_APP"===e.kind))throw Error("A successful runnable build is required");let s=await this.requireWorktree(a.worktreeId,i.IOS_RUN_DESTINATIONS_JOB_KIND);if(a.agentId!==s.codebase.agentId||a.codebaseId!==s.codebaseId)throw Error("The build no longer belongs to this worktree checkout");let o=await this.agentControl.createJob({agentId:s.codebase.agentId,codebaseId:s.codebaseId,worktreeId:s.id,kind:i.IOS_RUN_DESTINATIONS_JOB_KIND,payload:{...this.identity(s),destinationType:a.destinationType},idempotencyKey:`ios:build-destinations:${y(t,"Request ID",200)}:${a.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(o.id));return(Array.isArray(e.destinations)?e.destinations:[]).map(e=>(0,i.parseBuildDestination)(e)).filter(e=>e.type===a.destinationType&&!e.generic)}finally{await r.agentJob.deleteMany({where:{id:o.id,visibility:"SYSTEM"}})}}async startBuild(e){let a=y(e.requestId,"Request ID",200),s=`${e.worktreeId}:${a}`,o=await (0,n.getPrismaClient)(),u=await o.build.findUnique({where:{requestKey:s},include:k});if(u){if(this.telemetry){let e=p(u.snapshotJson,{}),t=h(e.configuration??{},"build configuration snapshot"),r=h(e.destination??{},"build destination snapshot");await this.telemetry.addBuildSeparator({buildId:u.id,name:`Build \xb7 ${String(t.name??"iOS")} \xb7 ${String(r.name??"Destination")}`,clientTime:u.createdAt})}return u}let c=await this.requireWorktree(e.worktreeId,i.IOS_BUILD_JOB_KIND);if(await this.diskSpace?.assertWorktreeCanStart(c.id),e.worktreeCoverage&&!g(c.codebase.agent).includes(i.IOS_COVERAGE_REPORT_JOB_KIND))throw Error("Build agent must be updated for worktree coverage");let d=await o.buildConfiguration.findUnique({where:{id:e.configurationId},include:{source:{include:{project:!0}}}});if(!d||d.source.project.repositoryId!==c.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let m=await o.buildSourceObservation.findUnique({where:{sourceId_scopeKey:{sourceId:d.sourceId,scopeKey:`worktree:${c.id}`}}}),f=e.action??d.defaultAction;if(!i.BUILD_ACTIONS.includes(f))throw Error("Build action is invalid");if(e.exportWhenComplete&&"ARCHIVE"!==f)throw Error("Export when complete is available only for Archive builds");let w="ARCHIVE"===f&&(e.exportWhenComplete??d.autoExport),b=e.exportSettings??p(d.exportSettingsJson,null),v=w||b?(0,i.parseBuildExportSettings)(b):null;if(w&&!v)throw Error("Export settings are required when automatic export is enabled");let S=(0,i.parseBuildDestination)(e.destination);if(!i.BUILD_DESTINATION_TYPES.includes(S.type))throw Error("Destination is invalid");if("ARCHIVE"===f&&("PHYSICAL_DEVICE"!==S.type||!S.generic))throw Error("Archive builds require the generic physical iOS destination");if(S.generic&&!i.GENERIC_BUILD_DESTINATION_ACTIONS.includes(f))throw Error("This build action requires a concrete destination");let E=h(p(d.advancedSettingsJson,{}),"saved advanced settings"),I=e.advancedSettings?h(e.advancedSettings,"advanced settings override"):{},x=(0,i.parseBuildAdvancedSettings)({...E,...I,buildSettingOverrides:{...h(E.buildSettingOverrides??{},"saved overrides"),...h(I.buildSettingOverrides??{},"run overrides")}});if("TEST_WITHOUT_BUILDING"===f){if(!x.priorBuildForTestingId)throw Error("Test Without Building requires a prior Build for Testing result");let e=await o.build.findUnique({where:{id:x.priorBuildForTestingId},include:{artifacts:{where:{kind:{in:["TEST_PRODUCTS","XCTESTRUN"]}},orderBy:{createdAt:"asc"}}}});if(!e||"SUCCEEDED"!==e.status||"BUILD_FOR_TESTING"!==e.action)throw Error("Test Without Building requires a successful Build for Testing result");if(e.agentId!==c.codebase.agentId||e.worktreeId!==c.id||e.configurationId!==d.id)throw Error("The prior Build for Testing result is not compatible with this agent, worktree, and configuration");if(e.destinationType!==S.type)throw Error("The prior Build for Testing result uses a different destination type");let t=h(p(e.snapshotJson,{}),"prior Build for Testing snapshot"),a=h(t.configuration??{},"prior Build for Testing configuration snapshot"),n=(0,i.parseBuildAdvancedSettings)(a.advancedSettings??{});if(x.testPlan&&n.testPlan&&x.testPlan!==n.testPlan)throw Error("The selected test plan does not match the prior Build for Testing result");let s=x.testPlan??n.testPlan??null,l=e.artifacts.filter(e=>"TEST_PRODUCTS"===e.kind&&e.relativePath.endsWith(".xctestproducts")),u=e.artifacts.filter(e=>"XCTESTRUN"===e.kind&&e.relativePath.endsWith(".xctestrun"));if(l.length>1)throw Error("The prior Build for Testing result contains multiple test-products artifacts");let m=l[0];if(m||1!==u.length||(m=u[0]),!m&&u.length>1&&s&&(m=u.find(e=>h(p(e.metadataJson,{}),"test-run artifact metadata").testPlan===s||e.relativePath.endsWith(`/${s}.xctestrun`)||e.relativePath===`${s}.xctestrun`)),!m&&u.length>1)throw Error("Select a test plan to choose among the captured .xctestrun artifacts");let f=m?.relativePath??"test-products.xctestproducts",g=(0,r.resolve)(e.artifactDirectory),y=(0,r.resolve)(g,f),w=(0,r.relative)(g,y);if(!w||w.startsWith("..")||(0,r.isAbsolute)(w))throw Error("The prior Build for Testing artifact path is invalid");x={...x,testPlan:s,priorTestProductsPath:f.endsWith(".xctestproducts")?y:null,priorXctestrunPath:f.endsWith(".xctestrun")?y:null}}let A=await o.codebaseRepositoryBuildScript.findMany({where:{repositoryId:c.codebase.repositoryId,script:{deletedAt:null}},orderBy:[{position:"asc"},{script:{name:"asc"}}],include:{script:!0}}),_=new Set(e.scriptIds??[]);if([..._].some(e=>!A.some(t=>t.scriptId===e)))throw Error("A selected build script is not allowed for this codebase");let C=A.filter(e=>_.has(e.scriptId)),R=(0,t.randomUUID)(),T=(0,l.effectiveBuildsDirectory)(c.codebase.agent);if(!T)throw Error("The agent builds directory is unavailable");let D=(0,r.join)(T,R),N={kind:d.source.kind,relativePath:d.source.relativePath},O=function(e){var t;let i=e.advancedSettings,a="TEST_WITHOUT_BUILDING"===e.action,n=["xcodebuild",...a?[]:[..."PACKAGE"===e.source.kind?[]:"PROJECT"===e.source.kind?["-project",e.source.relativePath]:["-workspace",e.source.relativePath],"-scheme",e.scheme,"-configuration",e.configuration],"-destination",(t=e.destination).generic?"SIMULATOR"===t.type?"generic/platform=iOS Simulator":"generic/platform=iOS":"SIMULATOR"===t.type?`platform=iOS Simulator,id=${t.id}`:`platform=iOS,id=${t.id}`,"-hideShellScriptEnvironment","-resultBundlePath",(0,r.join)(e.artifactDirectory,"result.xcresult")];for(let e of(!a&&("RESOLVED_ONLY"===i.packageResolution?n.push("-onlyUsePackageVersionsFromResolvedFile"):"SKIP_UPDATES"===i.packageResolution?n.push("-skipPackageUpdates"):"DISABLE_AUTOMATIC"===i.packageResolution&&n.push("-disableAutomaticPackageResolution"),i.disablePackageRepositoryCache&&n.push("-disablePackageRepositoryCache"),"PROJECT_DEFAULT"!==i.signingStyle&&n.push(`CODE_SIGN_STYLE=${"AUTOMATIC"===i.signingStyle?"Automatic":"Manual"}`),i.developmentTeam&&n.push(`DEVELOPMENT_TEAM=${i.developmentTeam}`),i.codeSignIdentity&&n.push(`CODE_SIGN_IDENTITY=${i.codeSignIdentity}`),i.provisioningProfileSpecifier&&n.push(`PROVISIONING_PROFILE_SPECIFIER=${i.provisioningProfileSpecifier}`),i.productBundleIdentifier&&n.push(`PRODUCT_BUNDLE_IDENTIFIER=${i.productBundleIdentifier}`),i.allowProvisioningUpdates&&n.push("-allowProvisioningUpdates"),i.allowProvisioningDeviceRegistration&&n.push("-allowProvisioningDeviceRegistration")),i.testPlan&&n.push("-testPlan",i.testPlan),i.codeCoverage&&n.push("-enableCodeCoverage","YES"),null!==i.parallelTesting&&n.push("-parallel-testing-enabled",i.parallelTesting?"YES":"NO"),null!==i.parallelTestingWorkers&&n.push("-parallel-testing-worker-count",String(i.parallelTestingWorkers)),i.onlyTesting))n.push(`-only-testing:${e}`);for(let e of i.skipTesting)n.push(`-skip-testing:${e}`);if(!a)for(let[e,t]of Object.entries(i.buildSettingOverrides))n.push(`${e}=${t}`);"ARCHIVE"===e.action&&n.push("-archivePath",(0,r.join)(e.artifactDirectory,"archive.xcarchive")),"BUILD_FOR_TESTING"===e.action&&n.push("-testProductsPath",(0,r.join)(e.artifactDirectory,"test-products.xctestproducts")),"TEST_WITHOUT_BUILDING"===e.action&&i.priorTestProductsPath&&n.push("-testProductsPath",i.priorTestProductsPath),"TEST_WITHOUT_BUILDING"===e.action&&!i.priorTestProductsPath&&i.priorXctestrunPath&&n.push("-xctestrun",i.priorXctestrunPath),n.push({BUILD:"build",TEST:"test",ANALYZE:"analyze",ARCHIVE:"archive",BUILD_FOR_TESTING:"build-for-testing",TEST_WITHOUT_BUILDING:"test-without-building"}[e.action]);let s=n.map(e=>/^[A-Za-z0-9_./:=,-]+$/.test(e)?e:JSON.stringify(e)).join(" ");return`cd ${JSON.stringify(e.folder)} && xcrun ${s}`}({folder:c.folder,source:N,scheme:d.scheme,configuration:d.buildConfiguration,destination:S,action:f,advancedSettings:x,artifactDirectory:D}),P=C.map(({script:e,position:t})=>({id:e.id,name:e.name,preBuildScript:e.preBuildScript,postBuildScript:e.postBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior,position:t})),$=await this.telemetry?.buildSettings(S.type,{requestOrigin:e.telemetryRequestOrigin}),U={repository:{id:c.codebase.repository.id,name:c.codebase.repository.name,canonicalOrigin:c.codebase.repository.canonicalOrigin},codebase:{id:c.codebase.id,folder:c.codebase.folder},worktree:{id:c.id,folder:c.folder,branch:c.branch,headSha:c.headSha,codeStateHash:c.codeStateHash,hasStagedChanges:c.hasStagedChanges,hasUnstagedChanges:c.hasUnstagedChanges},agent:{id:c.codebase.agent.id,name:c.codebase.agent.name,hostname:c.codebase.agent.hostname},configuration:{id:d.id,name:d.name,iconKey:d.iconKey,source:N,scheme:d.scheme,buildConfiguration:d.buildConfiguration,action:f,advancedSettings:x,autoExport:w,exportSettings:v,parse:m?{status:m.status,schemes:p(m.schemesJson,[]),configurations:p(m.configurationsJson,[]),testPlans:p(m.testPlansJson,[]),headSha:m.headSha,xcodeVersion:m.xcodeVersion,parsedAt:m.lastParsedAt?.toISOString()??null}:{status:"UNPARSED",schemes:[],configurations:[],testPlans:[],headSha:null,xcodeVersion:null,parsedAt:null}},destination:S,scripts:P,...$?{telemetry:$}:{},worktreeCoverage:!0===e.worktreeCoverage},B=new Date,j=o.build.create({data:{id:R,requestKey:s,requestId:a,agentId:c.codebase.agentId,codebaseId:c.codebaseId,worktreeId:c.id,configurationId:d.id,status:"QUEUED",action:f,destinationType:S.type,destinationJson:JSON.stringify(S),snapshotJson:JSON.stringify(U),commandSummary:O,artifactDirectory:D,createdAt:B,scriptExecutions:{create:P.flatMap(e=>[...e.preBuildScript?[{id:(0,t.randomUUID)(),scriptId:e.id,phase:"PRE_BUILD",position:e.position,nameSnapshot:e.name,sourceSnapshot:e.preBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior}]:[],...e.postBuildScript?[{id:(0,t.randomUUID)(),scriptId:e.id,phase:"POST_BUILD",position:e.position,nameSnapshot:e.name,sourceSnapshot:e.postBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior}]:[]])}}});if(this.telemetry){let e=(0,t.randomUUID)();await o.$transaction([j,o.telemetryEntry.create({data:{id:e,entryType:"SEPARATOR",clientTime:B,receivedAt:B,separatorKind:"BUILD",separatorName:`Build \xb7 ${d.name} \xb7 ${S.name}`.slice(0,100),buildId:R}})]),this.telemetry.notifyChange([e],"BUILD_SEPARATOR_ADDED")}else await j;try{let t=await this.agentControl.createJob({agentId:c.codebase.agentId,codebaseId:c.codebaseId,worktreeId:c.id,kind:i.IOS_BUILD_JOB_KIND,payload:{...this.identity(c),buildId:R,artifactDirectory:D,source:N,scheme:d.scheme,configuration:d.buildConfiguration,action:f,destination:S,advancedSettings:x,scripts:P,...$?{telemetry:$}:{},worktreeCoverage:!0===e.worktreeCoverage},idempotencyKey:`ios:build:${a}:${c.id}`,timeoutSeconds:604800});await o.build.update({where:{id:R},data:{jobId:t.id}})}catch(e){throw await o.build.update({where:{id:R},data:{status:"FAILED",errorCode:"QUEUE_FAILED",error:e instanceof Error?e.message:String(e),finishedAt:new Date}}),e}return this.publish(R),o.build.findUniqueOrThrow({where:{id:R},include:k})}async rebuildBuild(e,t,r){let i=await (0,n.getPrismaClient)(),a=await i.build.findUnique({where:{id:e},select:{worktreeId:!0,configurationId:!0,destinationJson:!0,action:!0,snapshotJson:!0}});if(!a)throw Error("Build not found");let s=h(p(a.snapshotJson,{}),"build snapshot"),o=h(s.worktree??{},"build worktree snapshot"),l=h(s.configuration??{},"build configuration snapshot"),u=Array.isArray(s.scripts)?s.scripts:[],c=a.worktreeId??("string"==typeof o.id?o.id:null),d=a.configurationId??("string"==typeof l.id?l.id:null);if(!c||!d)throw Error("The original build settings are unavailable");return this.startBuild({worktreeId:c,configurationId:d,destination:p(a.destinationJson,{}),scriptIds:u.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];let t=e.id;return"string"==typeof t?[t]:[]}),action:a.action,advancedSettings:l.advancedSettings,exportWhenComplete:!0===l.autoExport,...Object.hasOwn(l,"exportSettings")?{exportSettings:l.exportSettings}:{},requestId:t,...r?{telemetryRequestOrigin:r}:{}})}async startWorktreeCoverage(e){let t=await (0,n.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e.worktreeId},select:{baseBranchOverride:!0,codebase:{select:{defaultBranch:!0}}}});if(!r||!(r.baseBranchOverride??r.codebase.defaultBranch))throw Error("A base branch is required for worktree coverage");let i=h(e.advancedSettings??{},"coverage advanced settings");return this.startBuild({...e,action:"TEST",advancedSettings:{...i,codeCoverage:!0,parseTestResults:!0},worktreeCoverage:!0})}async importCoverageReport(e){let i=await (0,n.getPrismaClient)(),s=await this.requireWorktree(e.worktreeId,a.COVERAGE_IMPORT_JOB_KIND,"Agent must be updated to import coverage reports"),o=s.baseBranchOverride??s.codebase.defaultBranch??null,u=(e.format||"AUTO").toUpperCase();if(!a.COVERAGE_REPORT_FORMATS.includes(u))throw Error("Coverage format must be AUTO, LCOV, or ISTANBUL");let c=y(e.buildName??"Coverage report","Build name",200),d=y(e.reportPath,"Coverage file",4e3),p=y(e.requestId,"Request ID",200),h=`coverage:${e.worktreeId}:${p}`,m=await i.build.findUnique({where:{requestKey:h}});if(m)return m;let f=(0,t.randomUUID)(),g=(0,l.effectiveBuildsDirectory)(s.codebase.agent);if(!g)throw Error("The agent builds directory is unavailable");let w={repository:{id:s.codebase.repository.id,name:s.codebase.repository.name,canonicalOrigin:s.codebase.repository.canonicalOrigin},codebase:{id:s.codebase.id,folder:s.codebase.folder},worktree:{id:s.id,folder:s.folder,branch:s.branch,headSha:s.headSha,codeStateHash:s.codeStateHash,hasStagedChanges:s.hasStagedChanges,hasUnstagedChanges:s.hasUnstagedChanges},agent:{id:s.codebase.agent.id,name:s.codebase.agent.name,hostname:s.codebase.agent.hostname},configuration:{name:c},coverageImport:{reportPath:d,format:u,baseBranch:o},worktreeCoverage:!0},b={type:"HOST",id:s.codebase.agent.id,name:s.codebase.agent.name,platform:s.codebase.agent.architecture,osVersion:s.codebase.agent.osVersion||null,state:"Connected"},v=await i.build.create({data:{id:f,requestKey:h,requestId:p,agentId:s.codebase.agentId,codebaseId:s.codebaseId,worktreeId:s.id,status:"RUNNING",action:"TEST",destinationType:"HOST",destinationJson:JSON.stringify(b),snapshotJson:JSON.stringify(w),commandSummary:`Import coverage from ${d}`,artifactDirectory:(0,r.join)(g,f),startedAt:new Date}}),k=null;try{await i.buildReport.create({data:{id:(0,t.randomUUID)(),buildId:f,kind:"CODE_COVERAGE",source:"WORKTREE",status:"PENDING"}}),this.publish(f);let e=await this.agentControl.createJob({agentId:s.codebase.agentId,codebaseId:s.codebaseId,worktreeId:s.id,kind:a.COVERAGE_IMPORT_JOB_KIND,payload:{buildId:f,codebaseId:s.codebaseId,worktreeId:s.id,folder:s.folder,reportPath:d,format:u,baseBranch:o},idempotencyKey:`coverage:import:${p}:${f}`,timeoutSeconds:300,visibility:"SYSTEM"});return k=e.id,await i.build.update({where:{id:f},data:{jobId:e.id}}),{...v,jobId:e.id}}catch(a){k&&await this.agentControl.cancelJob(k).catch(()=>void 0);let e=a instanceof Error?a.message:String(a),r=new Date;throw await i.$transaction(async i=>{await i.buildReport.upsert({where:{buildId_kind:{buildId:f,kind:"CODE_COVERAGE"}},create:{id:(0,t.randomUUID)(),buildId:f,kind:"CODE_COVERAGE",source:"WORKTREE",status:"FAILED",error:e,finishedAt:r},update:{status:"FAILED",error:e,finishedAt:r}}),await i.build.update({where:{id:f},data:{status:"FAILED",errorCode:"QUEUE_FAILED",error:e,finishedAt:r}})}),this.publish(f),a}}async importedCoverageCompletion(e){let r=h(p(e.payloadJson,{}),"coverage import payload");if("string"!=typeof r.buildId)return;let i=r.buildId,a=h(p(e.resultJson,{}),"coverage import result"),s="SUCCEEDED"===e.status&&!!a.report&&"object"==typeof a.report,o=await (0,n.getPrismaClient)();await o.$transaction(async r=>{s?await this.upsertReportProjection(r,i,a.report,"WORKTREE"):await r.buildReport.upsert({where:{buildId_kind:{buildId:i,kind:"CODE_COVERAGE"}},create:{id:(0,t.randomUUID)(),buildId:i,kind:"CODE_COVERAGE",source:"WORKTREE",status:"FAILED",error:e.error||"Coverage import failed",finishedAt:new Date},update:{status:"FAILED",error:e.error||"Coverage import failed",finishedAt:new Date}}),await r.build.update({where:{id:i},data:{status:s?"SUCCEEDED":"FAILED",error:s?null:e.error||"Coverage import failed",finishedAt:new Date}})}),this.publish(i)}async generateReport(e,r,a){let s=await (0,n.getPrismaClient)(),o=await s.buildReport.findUnique({where:{buildId_kind:{buildId:e,kind:r}},include:{artifact:!0}});if(o?.status==="READY")return o;let l=await s.build.findUnique({where:{id:e},include:{agent:!0,artifacts:!0}});if(!l)throw Error("Build not found");if(d.includes(l.status))throw Error("Wait for the build to finish before generating reports");if(!l.agentId||!l.agent||!f(l.agent))throw Error("Build agent is offline");let u="TEST_RESULTS"===r?i.IOS_TEST_RESULTS_JOB_KIND:i.IOS_COVERAGE_REPORT_JOB_KIND;if(!g(l.agent).includes(u))throw Error("Build agent must be updated to generate reports");if(!l.artifacts.some(e=>"RESULT_BUNDLE"===e.kind))throw Error("The build result bundle is unavailable");if("TEST_RESULTS"===r&&!["TEST","TEST_WITHOUT_BUILDING"].includes(l.action))throw Error("This build did not run tests");let c=await s.buildReport.upsert({where:{buildId_kind:{buildId:e,kind:r}},create:{id:(0,t.randomUUID)(),buildId:e,kind:r,source:"MANUAL",status:"PENDING"},update:{source:"MANUAL",status:"PENDING",error:null,finishedAt:null}});this.publish(e);let p=b(l),h=await this.agentControl.createJob({agentId:l.agentId,codebaseId:p,worktreeId:l.worktreeId,kind:u,payload:{buildId:e,artifactDirectory:l.artifactDirectory,codebaseId:p,reportKind:r,source:"MANUAL"},idempotencyKey:`ios:report:${r}:${y(a,"Request ID",200)}:${e}`,timeoutSeconds:180,visibility:"SYSTEM"});try{return await this.waitForJob(h.id,17e4),s.buildReport.findUniqueOrThrow({where:{id:c.id},include:{artifact:!0}})}finally{await s.agentJob.deleteMany({where:{id:h.id,visibility:"SYSTEM"}})}}async coverageHistory(e){return(await (0,n.getPrismaClient)()).buildReport.findMany({where:{kind:"CODE_COVERAGE",source:"WORKTREE",build:{worktreeId:e}},orderBy:{createdAt:"desc"},take:50,select:{id:!0,buildId:!0,artifactId:!0,kind:!0,source:!0,status:!0,summaryJson:!0,error:!0,createdAt:!0,updatedAt:!0,finishedAt:!0,artifact:!0,build:{select:{id:!0,status:!0,action:!0,destinationType:!0,destinationJson:!0,snapshotJson:!0,createdAt:!0,startedAt:!0,finishedAt:!0,updatedAt:!0,worktree:{select:{headSha:!0,codeStateHash:!0,hasStagedChanges:!0,hasUnstagedChanges:!0,lastCheckedAt:!0,_count:{select:{builds:{where:{status:{in:d}}}}}}},artifacts:{orderBy:{createdAt:"asc"}}}}}})}async reportsForBuild(e){return(await (0,n.getPrismaClient)()).buildReport.findMany({where:{buildId:e},orderBy:{createdAt:"asc"},include:{artifact:!0}})}async reportData(e){let t=await (0,n.getPrismaClient)(),r=await t.buildReport.findUnique({where:{id:e},select:{dataJson:!0}});return r?.dataJson??"{}"}async builds(e={}){let t=await (0,n.getPrismaClient)(),r=Math.max(1,Math.min(e.first??50,200)),i=await t.build.findMany({where:{...e.status?{status:e.status}:{},...e.codebaseId?{codebaseId:e.codebaseId}:{},...e.worktreeId?{worktreeId:e.worktreeId}:{}},orderBy:[{createdAt:"desc"},{id:"desc"}],...e.after?{cursor:{id:e.after},skip:1}:{},take:r+1,include:k});return{items:i.slice(0,r),nextCursor:i.length>r?i[r-1].id:null}}async getBuild(e){return(await (0,n.getPrismaClient)()).build.findUnique({where:{id:e},include:k})}async deleteBuilds(e){let t=[...new Set(e)];if(!t.length)return 0;if(t.length>200)throw Error("At most 200 builds can be deleted at once");let a=await (0,n.getPrismaClient)(),s=await a.build.findMany({where:{id:{in:t}},select:{id:!0,status:!0,artifactDirectory:!0,snapshotJson:!0,agentId:!0,agent:{select:{capabilitiesJson:!0}},codebaseId:!0,worktreeId:!0,deployments:{where:{status:{in:d}},select:{id:!0}},exports:{where:{status:{in:d}},select:{id:!0}}}});if(s.some(e=>d.includes(e.status)))throw Error("Running builds cannot be deleted");if(s.some(e=>e.deployments.length>0||e.exports.length>0))throw Error("Builds with running deployments or exports cannot be deleted");for(let e of s){if(!(0,r.isAbsolute)(e.artifactDirectory)||(0,r.basename)(e.artifactDirectory)!==e.id)throw Error(`Build folder is invalid for ${e.id}`);if(e.agentId){let t=b(e);if(!e.agent||!g(e.agent).includes(i.IOS_BUILD_DELETE_JOB_KIND))throw Error("Build agent must be updated to delete builds");await this.agentControl.createJob({agentId:e.agentId,codebaseId:t,worktreeId:e.worktreeId,kind:i.IOS_BUILD_DELETE_JOB_KIND,payload:{buildId:e.id,artifactDirectory:e.artifactDirectory,codebaseId:t},idempotencyKey:`ios:build:delete:${e.id}`,timeoutSeconds:300,visibility:"SYSTEM"})}}let o=await a.build.deleteMany({where:{id:{in:s.map(e=>e.id)}}});for(let e of s)this.publish(e.id);return o.count}async artifactForInstall(e,t){let r=await (0,n.getPrismaClient)(),i=await r.buildArtifact.findFirst({where:{id:t,buildId:e}});return i?{id:i.id,kind:i.kind,relativePath:i.relativePath,sizeBytes:i.sizeBytes,checksum:i.checksum,createdAt:i.createdAt.toISOString(),metadata:h(p(i.metadataJson,{}),"build artifact metadata")}:null}async prepareArtifactDownload(e,t,r,a=17e4){let s=await (0,n.getPrismaClient)(),o=await s.buildArtifact.findFirst({where:{id:t,buildId:e},include:{build:{include:{agent:!0}}}});if(!o)throw Error("Build artifact not found");let{build:l}=o;if(!l.agentId||!l.agent)throw Error("The build agent is no longer available");if(!f(l.agent))throw Error("Build agent is offline");if(!g(l.agent).includes(i.IOS_ARTIFACT_DOWNLOAD_JOB_KIND))throw Error("Build agent must be updated to download artifacts");let u=b(l),c=await this.agentControl.createJob({agentId:l.agentId,codebaseId:u,worktreeId:l.worktreeId,kind:i.IOS_ARTIFACT_DOWNLOAD_JOB_KIND,payload:{buildId:l.id,artifactDirectory:l.artifactDirectory,artifactRelativePath:o.relativePath,uploadId:r,codebaseId:u},idempotencyKey:`ios:artifact:download:${r}`,timeoutSeconds:Math.ceil(a/1e3)+10,visibility:"SYSTEM"});try{this.result(await this.waitForJob(c.id,a))}finally{await s.agentJob.deleteMany({where:{id:c.id,visibility:"SYSTEM"}})}}async logChunks(e,t=null,r=1e3){let i=await (0,n.getPrismaClient)(),a=t?await i.buildLogChunk.findFirst({where:{id:t,buildId:e},select:{id:!0,createdAt:!0,sequence:!0}}):null;if(t&&!a)throw Error("Build log cursor not found");return i.buildLogChunk.findMany({where:{buildId:e,...a?{OR:[{createdAt:{gt:a.createdAt}},{createdAt:a.createdAt,sequence:{gt:a.sequence}},{createdAt:a.createdAt,sequence:a.sequence,id:{gt:a.id}}]}:{}},orderBy:[{createdAt:"asc"},{sequence:"asc"},{id:"asc"}],take:Math.max(1,Math.min(r,5e3))})}async cancelBuild(e){let t=await (0,n.getPrismaClient)(),r=await t.build.findUnique({where:{id:e}});if(!r)throw Error("Build not found");return d.includes(r.status)&&(r.jobId&&await this.agentControl.cancelJob(r.jobId),await t.build.update({where:{id:e},data:{status:"CANCELLED",finishedAt:new Date,errorCode:"CANCELLED"}}),this.publish(e)),this.getBuild(e)}async reportProgress(e,t){if(!["PREPARING","RUNNING"].includes(t.status))throw Error("Build progress status is invalid");let r=await (0,n.getPrismaClient)(),i=await r.build.findUnique({where:{id:t.buildId}});if(!i||i.agentId!==e)throw Error("Build not found for agent");if(!d.includes(i.status))return i;let a=await r.build.update({where:{id:t.buildId},data:{status:t.status,startedAt:i.startedAt??(t.startedAt?new Date(t.startedAt):new Date),errorCode:t.errorCode??void 0,error:t.error??void 0}});return this.publish(t.buildId),a}async appendLogChunks(e,r,i){if(!i.length||i.length>200)throw Error("Build log batches must contain 1 to 200 chunks");let a=await (0,n.getPrismaClient)(),s=await a.build.findUnique({where:{id:r}});if(!s||s.agentId!==e)throw Error("Build not found for agent");let l=i.map(e=>{if(!Number.isInteger(e.sequence)||e.sequence<0)throw Error("Log sequence must be a non-negative integer");if(!["STDOUT","STDERR","SYSTEM"].includes(e.stream))throw Error("Log stream is invalid");let i=Buffer.from(e.dataBase64,"base64");if(i.length!==e.byteLength||i.length>262144)throw Error("Log byte length is invalid");let a=Buffer.from(i.toString("utf8").replace(/(Bearer\s+)[A-Za-z0-9._~+\/-]+=*/gi,"$1[REDACTED]").replace(/([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^\s/@]+@/g,"$1[REDACTED]@").replace(/\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY)[A-Z0-9_]*)\s*=\s*[^\s]+/gi,"$1=[REDACTED]").replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g,"[REDACTED PRIVATE KEY]"),"utf8"),n=new Date(e.createdAt);if(Number.isNaN(n.valueOf()))throw Error("Log date is invalid");return{id:(0,t.randomUUID)(),buildId:r,scope:y(e.scope,"Log scope",40),scopeId:y(e.scopeId,"Log scope ID",200),sequence:e.sequence,phase:y(e.phase,"Log phase",80),stream:e.stream,dataBase64:a.toString("base64"),byteLength:a.byteLength,createdAt:n}}),u=[];for(let e of l){let t=await a.buildLogChunk.upsert({where:{scope_scopeId_sequence:{scope:e.scope,scopeId:e.scopeId,sequence:e.sequence}},create:e,update:{}});u.push(t),o.agentEventBus.publish((0,o.buildLogChunkTopic)(r),{buildLogChunkAdded:t})}return u}async runBuild(e){let r=await (0,n.getPrismaClient)(),a=await r.build.findUnique({where:{id:e.buildId},include:{artifacts:!0,worktree:{include:{codebase:{include:{agent:!0,repository:!0}}}}}});if(!a||"SUCCEEDED"!==a.status||!a.worktree)throw Error("A successful build is required");let s=a.artifacts.find(e=>"RUNNABLE_APP"===e.kind);if(!s)throw Error("Build does not contain a runnable app");let o=y(String(h(p(s.metadataJson,{}),"runnable metadata").bundleIdentifier??""),"Runnable bundle identifier",512),l=e.destinations.map(i.parseBuildDestination);if(!l.length)throw Error("Select at least one destination");if(new Set(l.map(e=>`${e.type}:${e.id}`)).size!==l.length)throw Error("Run destinations must be unique");if(l.some(e=>e.type!==a.destinationType))throw Error("Run destinations must match the build destination type");let u=await this.destinationsForBuild(a.id,`${y(e.requestId,"Request ID",200)}:preflight`),c=l.map(e=>u.find(t=>t.type===e.type&&t.id===e.id));if(c.some(e=>!e))throw Error("A selected run destination is no longer available");l=c;let d=await this.requireWorktree(a.worktree.id,i.IOS_DEPLOY_JOB_KIND),m=(0,t.randomUUID)(),f=[];for(let i of l){let n=await r.buildDeployment.findUnique({where:{buildId_requestId_destinationKey:{buildId:a.id,requestId:e.requestId,destinationKey:w(i)}}});f.push(n??await r.buildDeployment.create({data:{id:(0,t.randomUUID)(),buildId:a.id,batchId:m,requestId:e.requestId,destinationJson:JSON.stringify(i),destinationKey:w(i),commandSummary:"SIMULATOR"===i.type?`open -a Simulator --args -CurrentDeviceUDID ${i.id}; xcrun simctl install/launch ${i.id}`:`xcrun devicectl device install/process launch --device ${i.id}`}}))}let g=await this.agentControl.createJob({agentId:d.codebase.agentId,codebaseId:d.codebaseId,worktreeId:d.id,kind:i.IOS_DEPLOY_JOB_KIND,payload:{...this.identity(d),buildId:a.id,artifactDirectory:a.artifactDirectory,artifactRelativePath:s.relativePath,bundleIdentifier:o,deployments:f.map((e,t)=>({id:e.id,destination:l[t]}))},idempotencyKey:`ios:deploy:${a.id}:${e.requestId}`,timeoutSeconds:3600});return await r.buildDeployment.updateMany({where:{id:{in:f.map(e=>e.id)}},data:{jobId:g.id}}),this.publish(a.id),r.buildDeployment.findMany({where:{id:{in:f.map(e=>e.id)}},orderBy:{createdAt:"asc"}})}async exportArchive(e){let r=await (0,n.getPrismaClient)(),a=await r.buildExport.findUnique({where:{buildId_requestId:{buildId:e.buildId,requestId:e.requestId}}});if(a)return a;let s=await r.build.findUnique({where:{id:e.buildId},include:{artifacts:!0,worktree:!0}});if(!s||"SUCCEEDED"!==s.status||!s.worktree)throw Error("A successful archive build is required");let o=s.artifacts.find(e=>"ARCHIVE"===e.kind);if(!o)throw Error("Build does not contain an archive");let l=(0,i.parseBuildExportSettings)(e.settings),u=await this.requireWorktree(s.worktree.id,i.IOS_EXPORT_JOB_KIND),c=(0,t.randomUUID)(),d=await r.buildExport.create({data:{id:c,buildId:s.id,requestId:e.requestId,settingsSnapshotJson:JSON.stringify(l),commandSummary:`xcrun xcodebuild -exportArchive -archivePath ${JSON.stringify(o.relativePath)} -exportPath exports/${c}`}});try{let t=await this.agentControl.createJob({agentId:u.codebase.agentId,codebaseId:u.codebaseId,worktreeId:u.id,kind:i.IOS_EXPORT_JOB_KIND,payload:{...this.identity(u),buildId:s.id,exportId:c,artifactDirectory:s.artifactDirectory,archiveRelativePath:o.relativePath,settings:l},idempotencyKey:`ios:export:${s.id}:${e.requestId}`,timeoutSeconds:3600}),a=await r.buildExport.update({where:{id:d.id},data:{jobId:t.id}});return this.publish(s.id),a}catch(t){let e=await r.buildExport.update({where:{id:d.id},data:{status:"FAILED",error:t instanceof Error?t.message:String(t),finishedAt:new Date}});return this.publish(s.id),e}}async upsertArtifacts(e,r,a){for(let n of(0,i.parseBuildArtifactSnapshots)(a)){let i={kind:n.kind,sizeBytes:n.sizeBytes,checksum:n.checksum,metadataJson:JSON.stringify(n.metadata)};await e.buildArtifact.upsert({where:{buildId_relativePath:{buildId:r,relativePath:n.relativePath}},create:{id:(0,t.randomUUID)(),buildId:r,relativePath:n.relativePath,...i},update:i})}}async upsertReportProjection(e,r,i,a){let n=h(i,"build report");if("TEST_RESULTS"!==n.kind&&"CODE_COVERAGE"!==n.kind)return;let s=n.kind,o=n.artifact&&"object"==typeof n.artifact?h(n.artifact,"build report artifact"):null,l=o&&"string"==typeof o.relativePath?await e.buildArtifact.findUnique({where:{buildId_relativePath:{buildId:r,relativePath:o.relativePath}}}):null,u="READY"===n.status?"READY":"FAILED";await e.buildReport.upsert({where:{buildId_kind:{buildId:r,kind:s}},create:{id:(0,t.randomUUID)(),buildId:r,artifactId:l?.id??null,kind:s,source:a,status:u,summaryJson:JSON.stringify(n.summary&&"object"==typeof n.summary?n.summary:{}),dataJson:JSON.stringify(n.data&&"object"==typeof n.data?n.data:{}),error:"string"==typeof n.error?n.error:null,finishedAt:new Date},update:{artifactId:l?.id??null,source:a,status:u,summaryJson:JSON.stringify(n.summary&&"object"==typeof n.summary?n.summary:{}),dataJson:JSON.stringify(n.data&&"object"==typeof n.data?n.data:{}),error:"string"==typeof n.error?n.error:null,finishedAt:new Date}})}async projectBuildCompletion(e){let r=await (0,n.getPrismaClient)(),i=await r.build.findFirst({where:{jobId:e.id},include:{worktree:{select:{highlightColor:!0}}}});if(!i)return;let a=h(p(e.resultJson,{}),"build result"),s="CANCELLED"===i.status?"CANCELLED":v(e.status),o="string"==typeof a.sourceStateHash?a.sourceStateHash:null,l="string"==typeof a.finalStateHash?a.finalStateHash:null,u="string"==typeof a.codeStateObservedAt&&Number.isFinite(Date.parse(a.codeStateObservedAt))?new Date(a.codeStateObservedAt):new Date,c=l?u:new Date,d=i.snapshotJson;if(o){let e=h(p(i.snapshotJson,{}),"build snapshot"),t=h(e.worktree??{},"build worktree snapshot");d=JSON.stringify({...e,worktree:{...t,codeStateHash:o}})}let m=null;await r.$transaction(async r=>{if(await r.build.update({where:{id:i.id},data:{status:s,errorCode:"string"==typeof a.errorCode?a.errorCode:"TIMED_OUT"===e.status?"TIMEOUT":"FAILED"===s?"XCODEBUILD_FAILED":i.errorCode,error:e.error??("string"==typeof a.error?a.error:i.error),startedAt:i.startedAt??new Date,finishedAt:c,snapshotJson:d}}),i.worktreeId&&l&&await r.worktree.updateMany({where:{id:i.worktreeId,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:u}}]},data:{codeStateHash:l,lastCheckedAt:u}}),Array.isArray(a.artifacts))for(let e of a.artifacts){let a=h(e,"build artifact");"string"==typeof a.relativePath&&"string"==typeof a.kind&&await r.buildArtifact.upsert({where:{buildId_relativePath:{buildId:i.id,relativePath:a.relativePath}},create:{id:(0,t.randomUUID)(),buildId:i.id,kind:a.kind,relativePath:a.relativePath,sizeBytes:"number"==typeof a.sizeBytes?a.sizeBytes:null,checksum:"string"==typeof a.checksum?a.checksum:null,metadataJson:JSON.stringify(a.metadata&&"object"==typeof a.metadata?a.metadata:{})},update:{}})}if(Array.isArray(a.scriptExecutions))for(let e of a.scriptExecutions){let t=h(e,"script execution");"string"==typeof t.phase&&"number"==typeof t.position&&await r.buildScriptExecution.updateMany({where:{buildId:i.id,phase:t.phase,position:t.position},data:{status:"string"==typeof t.status?t.status:"FAILED",exitCode:"number"==typeof t.exitCode?t.exitCode:null,durationMs:"number"==typeof t.durationMs?t.durationMs:null,causedBuildFailure:!0===t.causedBuildFailure,outputRelativePath:"string"==typeof t.outputRelativePath?t.outputRelativePath:null,error:"string"==typeof t.error?t.error:null}})}if(Array.isArray(a.reports))for(let e of a.reports){let t=e&&"object"==typeof e&&!Array.isArray(e)?e:{};await this.upsertReportProjection(r,i.id,e,"CODE_COVERAGE"===t.kind?"WORKTREE":"AUTOMATIC")}if(this.notifications&&("SUCCEEDED"===s||"FAILED"===s)){let e=h(p(d,{}),"build notification snapshot"),t=h(e.repository??{},"build repository snapshot"),a=h(e.configuration??{},"build configuration snapshot"),n=h(e.worktree??{},"build worktree snapshot"),o=["string"==typeof t.name?t.name:null,"string"==typeof a.name?a.name:null,"string"==typeof n.branch?n.branch:"string"==typeof n.folder?n.folder:null].filter(e=>!!e);m=await this.notifications.recordInTransaction(r,{dedupeKey:`ios-build:${i.id}:${s}`,typeKey:"SUCCEEDED"===s?"IOS_BUILD_SUCCEEDED":"IOS_BUILD_FAILED",title:"SUCCEEDED"===s?"iOS build succeeded":"iOS build failed",body:o.join(" · ")||`Build ${i.id}`,href:`/builds/${i.id}`,resourceKind:"BUILD",resourceId:i.id,worktreeId:i.worktreeId,highlightColor:i.worktree?.highlightColor??null})}}),this.publish(i.id),this.notifications?.created(m),"SUCCEEDED"===s&&await this.queueAutomaticExport(i.id,d)}async queueAutomaticExport(e,r){let i=h(p(r,{}),"build snapshot"),a=h(i.configuration??{},"build configuration snapshot");if(!0!==a.autoExport)return;let s=a.exportSettings;try{await this.exportArchive({buildId:e,requestId:"automatic",settings:s})}catch(a){let r=await (0,n.getPrismaClient)(),i=a instanceof Error?a.message:String(a);await r.buildExport.upsert({where:{buildId_requestId:{buildId:e,requestId:"automatic"}},create:{id:(0,t.randomUUID)(),buildId:e,requestId:"automatic",status:"FAILED",settingsSnapshotJson:JSON.stringify(s??{}),commandSummary:"Automatic archive export",error:i,finishedAt:new Date},update:{status:"FAILED",error:i,finishedAt:new Date}}),this.publish(e)}}async projectGeneratedReportCompletion(e){let r=h(p(e.payloadJson,{}),"build report payload");if("string"!=typeof r.buildId)return;let i=r.buildId,a=h(p(e.resultJson,{}),"build report result"),s=await (0,n.getPrismaClient)();await s.$transaction(async n=>{if(await this.upsertArtifacts(n,i,a.artifacts),a.report&&"object"==typeof a.report)await this.upsertReportProjection(n,i,a.report,"WORKTREE"===r.source?"WORKTREE":"MANUAL");else{let a="CODE_COVERAGE"===r.reportKind?"CODE_COVERAGE":"TEST_RESULTS";await n.buildReport.upsert({where:{buildId_kind:{buildId:i,kind:a}},create:{id:(0,t.randomUUID)(),buildId:i,kind:a,source:"WORKTREE"===r.source?"WORKTREE":"MANUAL",status:"FAILED",error:e.error||"Report generation failed",finishedAt:new Date},update:{status:"FAILED",error:e.error||"Report generation failed",finishedAt:new Date}})}}),this.publish(i)}async projectDeploymentCompletion(e){let t=await (0,n.getPrismaClient)(),r=await t.buildDeployment.findMany({where:{jobId:e.id}});if(!r.length)return;let i=h(p(e.resultJson,{}),"deployment result"),a=Array.isArray(i.deployments)?i.deployments:[];for(let i of r){let r=a.map(e=>h(e,"deployment outcome")).find(e=>e.id===i.id);await t.buildDeployment.update({where:{id:i.id},data:{status:"string"==typeof r?.status?r.status:v(e.status),error:"string"==typeof r?.error?r.error:e.error,outputRelativePath:"string"==typeof r?.outputRelativePath?r.outputRelativePath:null,startedAt:i.startedAt??new Date,finishedAt:new Date}})}this.publish(r[0].buildId)}async projectExportCompletion(e){let r=await (0,n.getPrismaClient)(),i=await r.buildExport.findFirst({where:{jobId:e.id}});if(!i)return;let a=h(p(e.resultJson,{}),"export result");if(await r.buildExport.update({where:{id:i.id},data:{status:v(e.status),error:e.error??("string"==typeof a.error?a.error:null),outputRelativePath:"string"==typeof a.outputRelativePath?a.outputRelativePath:null,startedAt:i.startedAt??new Date,finishedAt:new Date}}),"SUCCEEDED"===e.status&&"string"==typeof a.outputRelativePath){let e=a.outputRelativePath;await r.$transaction(async r=>{await r.buildArtifact.upsert({where:{buildId_relativePath:{buildId:i.buildId,relativePath:e}},create:{id:(0,t.randomUUID)(),buildId:i.buildId,kind:"EXPORT",relativePath:e,sizeBytes:"number"==typeof a.sizeBytes?a.sizeBytes:null,metadataJson:JSON.stringify({exportId:i.id})},update:{}}),await this.upsertArtifacts(r,i.buildId,a.artifacts)})}this.publish(i.buildId)}}],669602);var S=e.i(907855);let E=S.object({status:S.string().optional(),codebaseId:S.string().optional(),worktreeId:S.string().optional(),first:S.number().int().min(1).max(200).default(50),after:S.string().optional()}),I=S.object({builds:S.array(S.unknown()),nextCursor:S.string().nullable()}),x=S.object({buildId:S.string().min(1),afterLogId:S.string().min(1).nullable().default(null),logLimit:S.number().int().min(1).max(5e3).default(1e3)}),A=S.object({build:S.unknown(),logs:S.array(S.unknown())}),_=S.object({worktreeId:S.string().min(1)}),C=S.object({project:S.unknown().nullable()}),R=S.union([S.object({buildId:S.string().min(1),requestId:S.string().min(1)}),S.object({worktreeId:S.string().min(1),configurationId:S.string().min(1),action:S.string().optional(),requestId:S.string().min(1)})]),T=S.object({destinations:S.array(S.unknown())}),D=S.object({worktreeId:S.string().min(1),configurationId:S.string().min(1),destination:S.record(S.string(),S.unknown()),scriptIds:S.array(S.string()).default([]),action:S.string().optional(),advancedSettings:S.record(S.string(),S.unknown()).optional(),requestId:S.string().min(1)}),N=S.object({build:S.unknown()}),O=S.object({worktreeId:S.string().min(1),reportPath:S.string().min(1).max(4e3),format:S.enum(["AUTO","LCOV","ISTANBUL"]).default("AUTO"),requestId:S.string().min(1)}),P=S.object({build:S.unknown()}),$=S.object({buildId:S.string().min(1),requestId:S.string().min(1)}),U=S.object({build:S.unknown()}),B=S.object({buildId:S.string().min(1),destinations:S.array(S.record(S.string(),S.unknown())).min(1),requestId:S.string().min(1)}),j=S.object({deployments:S.array(S.unknown())}),L=S.object({buildId:S.string().min(1),settings:S.record(S.string(),S.unknown()),requestId:S.string().min(1)}),q=S.object({export:S.unknown()});e.s(["CancelBuildToolInputSchema",0,$,"CancelBuildToolOutputSchema",0,U,"ExportBuildToolInputSchema",0,L,"ExportBuildToolOutputSchema",0,q,"GetBuildConfigurationsInputSchema",0,_,"GetBuildConfigurationsOutputSchema",0,C,"GetBuildDestinationsInputSchema",0,R,"GetBuildDestinationsOutputSchema",0,T,"GetBuildInputSchema",0,x,"GetBuildOutputSchema",0,A,"GetBuildsInputSchema",0,E,"GetBuildsOutputSchema",0,I,"ImportCoverageReportToolInputSchema",0,O,"ImportCoverageReportToolOutputSchema",0,P,"RunBuildToolInputSchema",0,B,"RunBuildToolOutputSchema",0,j,"StartBuildToolInputSchema",0,D,"StartBuildToolOutputSchema",0,N],190714),e.s([],224174),e.i(582482);var M=e.i(318905),F=e.i(91022);let K="default",V={"exact-primary":"EXACT_PRIMARY","prefixed-primary":"PREFIXED_PRIMARY","exact-restore":"EXACT_RESTORE","prefixed-restore":"PREFIXED_RESTORE"};function G(e,t){return t?e.split(t).join("[REDACTED]"):e}function H(e){return{id:e.id,key:e.key,version:e.version,scope:e.scope,repoId:e.repoId,updatedAt:e.updatedAt,locationId:e.locationId}}e.s(["CacheServerService",0,class{credentials;constructor(e=new F.CredentialService){this.credentials=e}async getSettings(){let e=await (0,n.getPrismaClient)(),t=await e.cacheServerSettings.upsert({where:{id:K},create:{id:K},update:{}}),[r,i]=await Promise.all([this.credentials.isConfigured(M.CREDENTIALS.cacheServerApiKey),this.credentials.isConfigured(M.CREDENTIALS.cacheServerHeaders)]);return this.settingsView(t,r,i)}settingsView(e,t,r){return{configured:!!(e.baseUrl&&t),baseUrl:e.baseUrl,apiKeyConfigured:t,headers:(function(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}})(e.headerNamesJson).map(e=>({name:e,valueConfigured:r})),updatedAt:e.updatedAt.toISOString()}}async saveSettings(e){let t=function(e){let t,r=e.trim().replace(/\/+$/,"");if(!r)throw Error("A cache server base URL is required");try{t=new URL(r)}catch{throw Error("The cache server base URL is not a valid URL")}if("http:"!==t.protocol&&"https:"!==t.protocol)throw Error("The cache server base URL must use http or https");return r}(e.baseUrl),r=await this.credentials.isConfigured(M.CREDENTIALS.cacheServerApiKey),i=e.apiKey?.trim()||(r?await this.credentials.getText(M.CREDENTIALS.cacheServerApiKey):null);if(!i)throw Error("A cache server API key is required");let a=await this.credentials.isConfigured(M.CREDENTIALS.cacheServerHeaders)?await this.credentials.getJson(M.CREDENTIALS.cacheServerHeaders)??[]:[],n=function(e,t){if(!e)return[];let r=new Map(t.map(e=>[e.name.toLowerCase(),e.value])),i=new Set,a=[];for(let t of e){let e=t.name.trim();if(!e)continue;let n=e.toLowerCase();if(i.has(n))continue;i.add(n);let s=t.value||r.get(n);if(!s)throw Error(`A value is required for the ${e} header`);a.push({name:e,value:s})}return a}(e.headers,a),s=JSON.stringify(n.map(e=>e.name));return await this.credentials.setMany([{descriptor:M.CREDENTIALS.cacheServerApiKey,value:Buffer.from(i,"utf8")},{descriptor:M.CREDENTIALS.cacheServerHeaders,value:(0,M.encodeJsonCredential)(n)}],async e=>{await e.cacheServerSettings.upsert({where:{id:K},create:{id:K,baseUrl:t,headerNamesJson:s},update:{baseUrl:t,headerNamesJson:s}})}),this.getSettings()}async clearSettings(){return await this.credentials.deleteMany([M.CREDENTIALS.cacheServerApiKey,M.CREDENTIALS.cacheServerHeaders],async e=>{await e.cacheServerSettings.upsert({where:{id:K},create:{id:K},update:{baseUrl:null,headerNamesJson:"[]"}})}),this.getSettings()}async testConnection(){var e;if(!("object"==typeof(e=await this.request("GET","/cache-entries",{query:{itemsPerPage:1,page:1}}))&&null!==e&&"number"==typeof e.total&&Number.isInteger(e.total)&&e.total>=0&&Array.isArray(e.items)))throw Error("Cache server returned an invalid cache entry response");return this.getSettings()}async listCacheEntries(e){let t=await this.request("GET","/cache-entries",{query:{key:e.key?.trim()||void 0,version:e.version?.trim()||void 0,scope:e.scope?.trim()||void 0,repoId:e.repoId?.trim()||void 0,itemsPerPage:e.itemsPerPage??20,page:e.page??1}});return{total:t?.total??0,items:(t?.items??[]).map(H)}}async getCacheEntry(e){let t=await this.request("GET",`/cache-entries/${encodeURIComponent(e)}`,{allowNotFound:!0});return t?H(t):null}async getCacheEntryDetail(e){let t=await this.getCacheEntry(e);if(!t)return null;let r=t.locationId?await this.getStorageLocation(t.locationId):null;return{entry:t,location:r}}async getStorageLocation(e){let t=await this.request("GET",`/storage-locations/${encodeURIComponent(e)}`,{allowNotFound:!0});return t?{id:t.id,folderName:t.folderName,partCount:t.partCount,mergeStartedAt:t.mergeStartedAt??null,mergedAt:t.mergedAt??null,partsDeletedAt:t.partsDeletedAt??null,lastDownloadedAt:t.lastDownloadedAt??null,sizeBytes:t.sizeBytes??null}:null}async matchCacheEntry(e){let t=(e.restoreKeys??[]).map(e=>e.trim()).filter(Boolean),r=e.scopes.map(e=>e.trim()).filter(Boolean),i=await this.request("GET","/cache-entries/match",{query:{primaryKey:e.primaryKey,restoreKeys:t.length>0?t:void 0,scopes:r,repoId:e.repoId,version:e.version}});if(!i)return null;let a=V[i.type];if(!a)throw Error("Cache server returned an unknown match type");return{match:H(i.match),type:a}}async deleteCacheEntry(e){return await this.request("DELETE",`/cache-entries/${encodeURIComponent(e)}`,{allowNotFound:!0}),!0}async deleteCacheEntriesByIds(e){for(let t of e)await this.deleteCacheEntry(t);return!0}async deleteCacheEntries(e){let t=e.repoId?.trim();if(t){let r=new Set,i=1,a=0;do{let n=await this.listCacheEntries({...e,repoId:t,itemsPerPage:100,page:i});for(let e of(a=n.total,n.items))e.repoId===t&&r.add(e.id);i+=1}while((i-1)*100<a)return this.deleteCacheEntriesByIds([...r])}let r={};return e.key?.trim()&&(r.key=e.key.trim()),e.version?.trim()&&(r.version=e.version.trim()),e.scope?.trim()&&(r.scope=e.scope.trim()),await this.request("DELETE","/cache-entries",{body:r}),!0}async deleteStorageLocation(e){return await this.request("DELETE",`/storage-locations/${encodeURIComponent(e)}`,{allowNotFound:!0}),!0}async requireConfig(){let e=await (0,n.getPrismaClient)(),t=await e.cacheServerSettings.findUnique({where:{id:K}});if(!t?.baseUrl)throw Error("The cache server is not configured");let r=await this.credentials.getText(M.CREDENTIALS.cacheServerApiKey);if(!r)throw Error("The cache server is not configured");let i=await this.credentials.getJson(M.CREDENTIALS.cacheServerHeaders)??[];return{baseUrl:t.baseUrl,apiKey:r,headers:i}}buildUrl(e,t,r){let i=new URL(`${e}${t}`);if(r){for(let[e,t]of Object.entries(r))if(null!=t)if(Array.isArray(t))for(let r of t)i.searchParams.append(e,r);else i.searchParams.append(e,String(t))}return i.toString()}async request(e,t,r={}){let i,a,n=await this.requireConfig(),s=this.buildUrl(n.baseUrl,t,r.query),o={accept:"application/json"};for(let e of n.headers)o[e.name]=e.value;o["x-api-key"]=n.apiKey,void 0!==r.body&&(o["content-type"]="application/json");try{i=await fetch(s,{method:e,headers:o,body:void 0!==r.body?JSON.stringify(r.body):void 0,cache:"no-store"})}catch(e){throw Error(G(e instanceof Error?e.message:String(e),n.apiKey))}if(r.allowNotFound&&404===i.status)return null;let l=await i.text();if(l)try{a=JSON.parse(l)}catch{if(!i.ok)throw Error(`Cache server returned HTTP ${i.status}`);a=void 0}if(!i.ok)throw Error(G(a&&"object"==typeof a&&"message"in a&&"string"==typeof a.message?a.message:`Cache server returned HTTP ${i.status}`,n.apiKey));return a??null}}],646462),e.s([],890564)},952128,187963,117958,514849,e=>{"use strict";let t;var r,i,a,n,s,o,l,u=e.i(243783);e.s(["PrismaService",0,class{async healthCheck(){try{let e=await (0,u.getPrismaClient)();return await e.$queryRawUnsafe("SELECT 1"),!0}catch(e){return console.error("Database health check failed:",e),!1}}}],187963),e.s([],952128),(r=n||(n={})).assertEqual=e=>{},r.assertIs=function(e){},r.assertNever=function(e){throw Error()},r.arrayToEnum=e=>{let t={};for(let r of e)t[r]=r;return t},r.getValidEnumValues=e=>{let t=r.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),i={};for(let r of t)i[r]=e[r];return r.objectValues(i)},r.objectValues=e=>r.objectKeys(e).map(function(t){return e[t]}),r.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{let t=[];for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},r.find=(e,t)=>{for(let r of e)if(t(r))return r},r.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,r.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},r.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(s||(s={})).mergeShapes=(e,t)=>({...e,...t});let c=n.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),d=e=>{switch(typeof e){case"undefined":return c.undefined;case"string":return c.string;case"number":return Number.isNaN(e)?c.nan:c.number;case"boolean":return c.boolean;case"function":return c.function;case"bigint":return c.bigint;case"symbol":return c.symbol;case"object":if(Array.isArray(e))return c.array;if(null===e)return c.null;if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return c.promise;if("u">typeof Map&&e instanceof Map)return c.map;if("u">typeof Set&&e instanceof Set)return c.set;if("u">typeof Date&&e instanceof Date)return c.date;return c.object;default:return c.unknown}},p=n.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class h extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(e){return e.message},r={_errors:[]},i=e=>{for(let a of e.issues)if("invalid_union"===a.code)a.unionErrors.map(i);else if("invalid_return_type"===a.code)i(a.returnTypeError);else if("invalid_arguments"===a.code)i(a.argumentsError);else if(0===a.path.length)r._errors.push(t(a));else{let e=r,i=0;for(;i<a.path.length;){let r=a.path[i];i===a.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(a))):e[r]=e[r]||{_errors:[]},e=e[r],i++}}};return i(this),r}static assert(e){if(!(e instanceof h))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,n.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){let t=Object.create(null),r=[];for(let i of this.issues)if(i.path.length>0){let r=i.path[0];t[r]=t[r]||[],t[r].push(e(i))}else r.push(e(i));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}h.create=e=>new h(e);let m=(e,t)=>{let r;switch(e.code){case p.invalid_type:r=e.received===c.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case p.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,n.jsonStringifyReplacer)}`;break;case p.unrecognized_keys:r=`Unrecognized key(s) in object: ${n.joinValues(e.keys,", ")}`;break;case p.invalid_union:r="Invalid input";break;case p.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${n.joinValues(e.options)}`;break;case p.invalid_enum_value:r=`Invalid enum value. Expected ${n.joinValues(e.options)}, received '${e.received}'`;break;case p.invalid_arguments:r="Invalid function arguments";break;case p.invalid_return_type:r="Invalid function return type";break;case p.invalid_date:r="Invalid date";break;case p.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:n.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case p.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case p.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case p.custom:r="Invalid input";break;case p.invalid_intersection_types:r="Intersection results could not be merged";break;case p.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case p.not_finite:r="Number must be finite";break;default:r=t.defaultError,n.assertNever(e)}return{message:r}};(i=o||(o={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},i.toString=e=>"string"==typeof e?e:e?.message;let f=e=>{let{data:t,path:r,errorMaps:i,issueData:a}=e,n=[...r,...a.path||[]],s={...a,path:n};if(void 0!==a.message)return{...a,path:n,message:a.message};let o="";for(let e of i.filter(e=>!!e).slice().reverse())o=e(s,{data:t,defaultError:o}).message;return{...a,path:n,message:o}};function g(e,t){let r=f({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,m,void 0].filter(e=>!!e)});e.common.issues.push(r)}class y{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let i of t){if("aborted"===i.status)return w;"dirty"===i.status&&e.dirty(),r.push(i.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let e of t){let t=await e.key,i=await e.value;r.push({key:t,value:i})}return y.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let i of t){let{key:t,value:a}=i;if("aborted"===t.status||"aborted"===a.status)return w;"dirty"===t.status&&e.dirty(),"dirty"===a.status&&e.dirty(),"__proto__"!==t.value&&(void 0!==a.value||i.alwaysSet)&&(r[t.value]=a.value)}return{status:e.value,value:r}}}let w=Object.freeze({status:"aborted"}),b=e=>({status:"dirty",value:e}),v=e=>({status:"valid",value:e}),k=e=>"u">typeof Promise&&e instanceof Promise;class S{constructor(e,t,r,i){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}let E=(e,t)=>{if("valid"===t.status)return{success:!0,data:t.value};if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new h(e.common.issues);return this._error=t,this._error}}};function I(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:i,description:a}=e;if(t&&(r||i))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:a}:{errorMap:(t,a)=>{let{message:n}=e;return"invalid_enum_value"===t.code?{message:n??a.defaultError}:void 0===a.data?{message:n??i??a.defaultError}:"invalid_type"!==t.code?{message:a.defaultError}:{message:n??r??a.defaultError}},description:a}}class x{get description(){return this._def.description}_getType(e){return d(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:d(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new y,ctx:{common:e.parent.common,data:e.data,parsedType:d(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(k(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){return Promise.resolve(this._parse(e))}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:d(e)},i=this._parseSync({data:e,path:r.path,parent:r});return E(r,i)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:d(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return"valid"===r.status?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>"valid"===e.status?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:d(e)},i=this._parse({data:e,path:r.path,parent:r});return E(r,await (k(i)?i:Promise.resolve(i)))}refine(e,t){return this._refinement((r,i)=>{let a=e(r),n=()=>i.addIssue({code:p.custom,..."string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(r):t});return"u">typeof Promise&&a instanceof Promise?a.then(e=>!!e||(n(),!1)):!!a||(n(),!1)})}refinement(e,t){return this._refinement((r,i)=>!!e(r)||(i.addIssue("function"==typeof t?t(r,i):t),!1))}_refinement(e){return new ew({schema:this,typeName:l.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return eb.create(this,this._def)}nullable(){return ev.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return et.create(this)}promise(){return ey.create(this,this._def)}or(e){return ei.create([this,e],this._def)}and(e){return es.create(this,e,this._def)}transform(e){return new ew({...I(this._def),schema:this,typeName:l.ZodEffects,effect:{type:"transform",transform:e}})}default(e){return new ek({...I(this._def),innerType:this,defaultValue:"function"==typeof e?e:()=>e,typeName:l.ZodDefault})}brand(){return new eI({typeName:l.ZodBranded,type:this,...I(this._def)})}catch(e){return new eS({...I(this._def),innerType:this,catchValue:"function"==typeof e?e:()=>e,typeName:l.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return ex.create(this,e)}readonly(){return eA.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let A=/^c[^\s-]{8,}$/i,_=/^[0-9a-z]+$/,C=/^[0-9A-HJKMNP-TV-Z]{26}$/i,R=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,T=/^[a-z0-9_-]{21}$/i,D=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,N=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,O=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,P=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,$=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,U=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,B=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,j=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,L=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,q="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",M=RegExp(`^${q}$`);function F(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}class K extends x{_parse(e){var r,i,a,s;let o;if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==c.string){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.string,received:t.parsedType}),w}let l=new y;for(let u of this._def.checks)if("min"===u.kind)e.data.length<u.value&&(g(o=this._getOrReturnCtx(e,o),{code:p.too_small,minimum:u.value,type:"string",inclusive:!0,exact:!1,message:u.message}),l.dirty());else if("max"===u.kind)e.data.length>u.value&&(g(o=this._getOrReturnCtx(e,o),{code:p.too_big,maximum:u.value,type:"string",inclusive:!0,exact:!1,message:u.message}),l.dirty());else if("length"===u.kind){let t=e.data.length>u.value,r=e.data.length<u.value;(t||r)&&(o=this._getOrReturnCtx(e,o),t?g(o,{code:p.too_big,maximum:u.value,type:"string",inclusive:!0,exact:!0,message:u.message}):r&&g(o,{code:p.too_small,minimum:u.value,type:"string",inclusive:!0,exact:!0,message:u.message}),l.dirty())}else if("email"===u.kind)O.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"email",code:p.invalid_string,message:u.message}),l.dirty());else if("emoji"===u.kind)t||(t=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),t.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"emoji",code:p.invalid_string,message:u.message}),l.dirty());else if("uuid"===u.kind)R.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"uuid",code:p.invalid_string,message:u.message}),l.dirty());else if("nanoid"===u.kind)T.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"nanoid",code:p.invalid_string,message:u.message}),l.dirty());else if("cuid"===u.kind)A.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"cuid",code:p.invalid_string,message:u.message}),l.dirty());else if("cuid2"===u.kind)_.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"cuid2",code:p.invalid_string,message:u.message}),l.dirty());else if("ulid"===u.kind)C.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"ulid",code:p.invalid_string,message:u.message}),l.dirty());else if("url"===u.kind)try{new URL(e.data)}catch{g(o=this._getOrReturnCtx(e,o),{validation:"url",code:p.invalid_string,message:u.message}),l.dirty()}else"regex"===u.kind?(u.regex.lastIndex=0,u.regex.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"regex",code:p.invalid_string,message:u.message}),l.dirty())):"trim"===u.kind?e.data=e.data.trim():"includes"===u.kind?e.data.includes(u.value,u.position)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:{includes:u.value,position:u.position},message:u.message}),l.dirty()):"toLowerCase"===u.kind?e.data=e.data.toLowerCase():"toUpperCase"===u.kind?e.data=e.data.toUpperCase():"startsWith"===u.kind?e.data.startsWith(u.value)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:{startsWith:u.value},message:u.message}),l.dirty()):"endsWith"===u.kind?e.data.endsWith(u.value)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:{endsWith:u.value},message:u.message}),l.dirty()):"datetime"===u.kind?(function(e){let t=`${q}T${F(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,RegExp(`^${t}$`)})(u).test(e.data)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:"datetime",message:u.message}),l.dirty()):"date"===u.kind?M.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:"date",message:u.message}),l.dirty()):"time"===u.kind?RegExp(`^${F(u)}$`).test(e.data)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:"time",message:u.message}),l.dirty()):"duration"===u.kind?N.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"duration",code:p.invalid_string,message:u.message}),l.dirty()):"ip"===u.kind?(r=e.data,!(("v4"===(i=u.version)||!i)&&P.test(r)||("v6"===i||!i)&&U.test(r))&&1&&(g(o=this._getOrReturnCtx(e,o),{validation:"ip",code:p.invalid_string,message:u.message}),l.dirty())):"jwt"===u.kind?!function(e,t){if(!D.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let i=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),a=JSON.parse(atob(i));if("object"!=typeof a||null===a||"typ"in a&&a?.typ!=="JWT"||!a.alg||t&&a.alg!==t)return!1;return!0}catch{return!1}}(e.data,u.alg)&&(g(o=this._getOrReturnCtx(e,o),{validation:"jwt",code:p.invalid_string,message:u.message}),l.dirty()):"cidr"===u.kind?(a=e.data,!(("v4"===(s=u.version)||!s)&&$.test(a)||("v6"===s||!s)&&B.test(a))&&1&&(g(o=this._getOrReturnCtx(e,o),{validation:"cidr",code:p.invalid_string,message:u.message}),l.dirty())):"base64"===u.kind?j.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"base64",code:p.invalid_string,message:u.message}),l.dirty()):"base64url"===u.kind?L.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"base64url",code:p.invalid_string,message:u.message}),l.dirty()):n.assertNever(u);return{status:l.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:p.invalid_string,...o.errToObj(r)})}_addCheck(e){return new K({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...o.errToObj(e)})}url(e){return this._addCheck({kind:"url",...o.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...o.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...o.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...o.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...o.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...o.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...o.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...o.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...o.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...o.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...o.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...o.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...o.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...o.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...o.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...o.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...o.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...o.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...o.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...o.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...o.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...o.errToObj(t)})}nonempty(e){return this.min(1,o.errToObj(e))}trim(){return new K({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new K({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new K({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}K.create=e=>new K({checks:[],typeName:l.ZodString,coerce:e?.coerce??!1,...I(e)});class V extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){let t;if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==c.number){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.number,received:t.parsedType}),w}let r=new y;for(let i of this._def.checks)"int"===i.kind?n.isInteger(e.data)||(g(t=this._getOrReturnCtx(e,t),{code:p.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()):"min"===i.kind?(i.inclusive?e.data<i.value:e.data<=i.value)&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):"max"===i.kind?(i.inclusive?e.data>i.value:e.data>=i.value)&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):"multipleOf"===i.kind?0!==function(e,t){let r=(e.toString().split(".")[1]||"").length,i=(t.toString().split(".")[1]||"").length,a=r>i?r:i;return Number.parseInt(e.toFixed(a).replace(".",""))%Number.parseInt(t.toFixed(a).replace(".",""))/10**a}(e.data,i.value)&&(g(t=this._getOrReturnCtx(e,t),{code:p.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):"finite"===i.kind?Number.isFinite(e.data)||(g(t=this._getOrReturnCtx(e,t),{code:p.not_finite,message:i.message}),r.dirty()):n.assertNever(i);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,o.toString(t))}gt(e,t){return this.setLimit("min",e,!1,o.toString(t))}lte(e,t){return this.setLimit("max",e,!0,o.toString(t))}lt(e,t){return this.setLimit("max",e,!1,o.toString(t))}setLimit(e,t,r,i){return new V({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:o.toString(i)}]})}_addCheck(e){return new V({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:o.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:o.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:o.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:o.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:o.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:o.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:o.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:o.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:o.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&n.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;else"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value);return Number.isFinite(t)&&Number.isFinite(e)}}V.create=e=>new V({checks:[],typeName:l.ZodNumber,coerce:e?.coerce||!1,...I(e)});class G extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){let t;if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==c.bigint)return this._getInvalidInput(e);let r=new y;for(let i of this._def.checks)"min"===i.kind?(i.inclusive?e.data<i.value:e.data<=i.value)&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):"max"===i.kind?(i.inclusive?e.data>i.value:e.data>=i.value)&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):"multipleOf"===i.kind?e.data%i.value!==BigInt(0)&&(g(t=this._getOrReturnCtx(e,t),{code:p.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):n.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.bigint,received:t.parsedType}),w}gte(e,t){return this.setLimit("min",e,!0,o.toString(t))}gt(e,t){return this.setLimit("min",e,!1,o.toString(t))}lte(e,t){return this.setLimit("max",e,!0,o.toString(t))}lt(e,t){return this.setLimit("max",e,!1,o.toString(t))}setLimit(e,t,r,i){return new G({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:o.toString(i)}]})}_addCheck(e){return new G({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:o.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:o.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:o.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:o.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:o.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}G.create=e=>new G({checks:[],typeName:l.ZodBigInt,coerce:e?.coerce??!1,...I(e)});class H extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==c.boolean){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.boolean,received:t.parsedType}),w}return v(e.data)}}H.create=e=>new H({typeName:l.ZodBoolean,coerce:e?.coerce||!1,...I(e)});class W extends x{_parse(e){let t;if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==c.date){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.date,received:t.parsedType}),w}if(Number.isNaN(e.data.getTime()))return g(this._getOrReturnCtx(e),{code:p.invalid_date}),w;let r=new y;for(let i of this._def.checks)"min"===i.kind?e.data.getTime()<i.value&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):"max"===i.kind?e.data.getTime()>i.value&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):n.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new W({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:o.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:o.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}W.create=e=>new W({checks:[],coerce:e?.coerce||!1,typeName:l.ZodDate,...I(e)});class J extends x{_parse(e){if(this._getType(e)!==c.symbol){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.symbol,received:t.parsedType}),w}return v(e.data)}}J.create=e=>new J({typeName:l.ZodSymbol,...I(e)});class z extends x{_parse(e){if(this._getType(e)!==c.undefined){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.undefined,received:t.parsedType}),w}return v(e.data)}}z.create=e=>new z({typeName:l.ZodUndefined,...I(e)});class Z extends x{_parse(e){if(this._getType(e)!==c.null){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.null,received:t.parsedType}),w}return v(e.data)}}Z.create=e=>new Z({typeName:l.ZodNull,...I(e)});class Y extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return v(e.data)}}Y.create=e=>new Y({typeName:l.ZodAny,...I(e)});class Q extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return v(e.data)}}Q.create=e=>new Q({typeName:l.ZodUnknown,...I(e)});class X extends x{_parse(e){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.never,received:t.parsedType}),w}}X.create=e=>new X({typeName:l.ZodNever,...I(e)});class ee extends x{_parse(e){if(this._getType(e)!==c.undefined){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.void,received:t.parsedType}),w}return v(e.data)}}ee.create=e=>new ee({typeName:l.ZodVoid,...I(e)});class et extends x{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),i=this._def;if(t.parsedType!==c.array)return g(t,{code:p.invalid_type,expected:c.array,received:t.parsedType}),w;if(null!==i.exactLength){let e=t.data.length>i.exactLength.value,a=t.data.length<i.exactLength.value;(e||a)&&(g(t,{code:e?p.too_big:p.too_small,minimum:a?i.exactLength.value:void 0,maximum:e?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(null!==i.minLength&&t.data.length<i.minLength.value&&(g(t,{code:p.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),null!==i.maxLength&&t.data.length>i.maxLength.value&&(g(t,{code:p.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>i.type._parseAsync(new S(t,e,t.path,r)))).then(e=>y.mergeArray(r,e));let a=[...t.data].map((e,r)=>i.type._parseSync(new S(t,e,t.path,r)));return y.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new et({...this._def,minLength:{value:e,message:o.toString(t)}})}max(e,t){return new et({...this._def,maxLength:{value:e,message:o.toString(t)}})}length(e,t){return new et({...this._def,exactLength:{value:e,message:o.toString(t)}})}nonempty(e){return this.min(1,e)}}et.create=(e,t)=>new et({type:e,minLength:null,maxLength:null,exactLength:null,typeName:l.ZodArray,...I(t)});class er extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let e=this._def.shape(),t=n.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==c.object){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.object,received:t.parsedType}),w}let{status:t,ctx:r}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),n=[];if(!(this._def.catchall instanceof X&&"strip"===this._def.unknownKeys))for(let e in r.data)a.includes(e)||n.push(e);let s=[];for(let e of a){let t=i[e],a=r.data[e];s.push({key:{status:"valid",value:e},value:t._parse(new S(r,a,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof X){let e=this._def.unknownKeys;if("passthrough"===e)for(let e of n)s.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)n.length>0&&(g(r,{code:p.unrecognized_keys,keys:n}),t.dirty());else if("strip"===e);else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let e=this._def.catchall;for(let t of n){let i=r.data[t];s.push({key:{status:"valid",value:t},value:e._parse(new S(r,i,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of s){let r=await t.key,i=await t.value;e.push({key:r,value:i,alwaysSet:t.alwaysSet})}return e}).then(e=>y.mergeObjectSync(t,e)):y.mergeObjectSync(t,s)}get shape(){return this._def.shape()}strict(e){return o.errToObj,new er({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{let i=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:o.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new er({...this._def,unknownKeys:"strip"})}passthrough(){return new er({...this._def,unknownKeys:"passthrough"})}extend(e){return new er({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new er({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:l.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new er({...this._def,catchall:e})}pick(e){let t={};for(let r of n.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new er({...this._def,shape:()=>t})}omit(e){let t={};for(let r of n.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new er({...this._def,shape:()=>t})}deepPartial(){return function e(t){if(t instanceof er){let r={};for(let i in t.shape){let a=t.shape[i];r[i]=eb.create(e(a))}return new er({...t._def,shape:()=>r})}if(t instanceof et)return new et({...t._def,type:e(t.element)});if(t instanceof eb)return eb.create(e(t.unwrap()));if(t instanceof ev)return ev.create(e(t.unwrap()));if(t instanceof eo)return eo.create(t.items.map(t=>e(t)));else return t}(this)}partial(e){let t={};for(let r of n.objectKeys(this.shape)){let i=this.shape[r];e&&!e[r]?t[r]=i:t[r]=i.optional()}return new er({...this._def,shape:()=>t})}required(e){let t={};for(let r of n.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof eb;)e=e._def.innerType;t[r]=e}return new er({...this._def,shape:()=>t})}keyof(){return em(n.objectKeys(this.shape))}}er.create=(e,t)=>new er({shape:()=>e,unknownKeys:"strip",catchall:X.create(),typeName:l.ZodObject,...I(t)}),er.strictCreate=(e,t)=>new er({shape:()=>e,unknownKeys:"strict",catchall:X.create(),typeName:l.ZodObject,...I(t)}),er.lazycreate=(e,t)=>new er({shape:e,unknownKeys:"strip",catchall:X.create(),typeName:l.ZodObject,...I(t)});class ei extends x{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{let r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(let t of e)if("valid"===t.result.status)return t.result;for(let r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;let r=e.map(e=>new h(e.ctx.common.issues));return g(t,{code:p.invalid_union,unionErrors:r}),w});{let e,i=[];for(let a of r){let r={...t,common:{...t.common,issues:[]},parent:null},n=a._parseSync({data:t.data,path:t.path,parent:r});if("valid"===n.status)return n;"dirty"!==n.status||e||(e={result:n,ctx:r}),r.common.issues.length&&i.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let a=i.map(e=>new h(e));return g(t,{code:p.invalid_union,unionErrors:a}),w}}get options(){return this._def.options}}ei.create=(e,t)=>new ei({options:e,typeName:l.ZodUnion,...I(t)});let ea=e=>{if(e instanceof ep)return ea(e.schema);if(e instanceof ew)return ea(e.innerType());if(e instanceof eh)return[e.value];if(e instanceof ef)return e.options;if(e instanceof eg)return n.objectValues(e.enum);else if(e instanceof ek)return ea(e._def.innerType);else if(e instanceof z)return[void 0];else if(e instanceof Z)return[null];else if(e instanceof eb)return[void 0,...ea(e.unwrap())];else if(e instanceof ev)return[null,...ea(e.unwrap())];else if(e instanceof eI)return ea(e.unwrap());else if(e instanceof eA)return ea(e.unwrap());else if(e instanceof eS)return ea(e._def.innerType);else return[]};class en extends x{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==c.object)return g(t,{code:p.invalid_type,expected:c.object,received:t.parsedType}),w;let r=this.discriminator,i=t.data[r],a=this.optionsMap.get(i);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(g(t,{code:p.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),w)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let i=new Map;for(let r of t){let t=ea(r.shape[e]);if(!t.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of t){if(i.has(a))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,r)}}return new en({typeName:l.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:i,...I(r)})}}class es extends x{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),i=(e,i)=>{if("aborted"===e.status||"aborted"===i.status)return w;let a=function e(t,r){let i=d(t),a=d(r);if(t===r)return{valid:!0,data:t};if(i===c.object&&a===c.object){let i=n.objectKeys(r),a=n.objectKeys(t).filter(e=>-1!==i.indexOf(e)),s={...t,...r};for(let i of a){let a=e(t[i],r[i]);if(!a.valid)return{valid:!1};s[i]=a.data}return{valid:!0,data:s}}if(i===c.array&&a===c.array){if(t.length!==r.length)return{valid:!1};let i=[];for(let a=0;a<t.length;a++){let n=e(t[a],r[a]);if(!n.valid)return{valid:!1};i.push(n.data)}return{valid:!0,data:i}}if(i===c.date&&a===c.date&&+t==+r)return{valid:!0,data:t};return{valid:!1}}(e.value,i.value);return a.valid?(("dirty"===e.status||"dirty"===i.status)&&t.dirty(),{status:t.value,value:a.data}):(g(r,{code:p.invalid_intersection_types}),w)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>i(e,t)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}es.create=(e,t,r)=>new es({left:e,right:t,typeName:l.ZodIntersection,...I(r)});class eo extends x{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==c.array)return g(r,{code:p.invalid_type,expected:c.array,received:r.parsedType}),w;if(r.data.length<this._def.items.length)return g(r,{code:p.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w;!this._def.rest&&r.data.length>this._def.items.length&&(g(r,{code:p.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...r.data].map((e,t)=>{let i=this._def.items[t]||this._def.rest;return i?i._parse(new S(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(i).then(e=>y.mergeArray(t,e)):y.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new eo({...this._def,rest:e})}}eo.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new eo({items:e,typeName:l.ZodTuple,rest:null,...I(t)})};class el extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==c.object)return g(r,{code:p.invalid_type,expected:c.object,received:r.parsedType}),w;let i=[],a=this._def.keyType,n=this._def.valueType;for(let e in r.data)i.push({key:a._parse(new S(r,e,r.path,e)),value:n._parse(new S(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?y.mergeObjectAsync(t,i):y.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,r){return new el(t instanceof x?{keyType:e,valueType:t,typeName:l.ZodRecord,...I(r)}:{keyType:K.create(),valueType:e,typeName:l.ZodRecord,...I(t)})}}class eu extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==c.map)return g(r,{code:p.invalid_type,expected:c.map,received:r.parsedType}),w;let i=this._def.keyType,a=this._def.valueType,n=[...r.data.entries()].map(([e,t],n)=>({key:i._parse(new S(r,e,r.path,[n,"key"])),value:a._parse(new S(r,t,r.path,[n,"value"]))}));if(r.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let r of n){let i=await r.key,a=await r.value;if("aborted"===i.status||"aborted"===a.status)return w;("dirty"===i.status||"dirty"===a.status)&&t.dirty(),e.set(i.value,a.value)}return{status:t.value,value:e}})}{let e=new Map;for(let r of n){let i=r.key,a=r.value;if("aborted"===i.status||"aborted"===a.status)return w;("dirty"===i.status||"dirty"===a.status)&&t.dirty(),e.set(i.value,a.value)}return{status:t.value,value:e}}}}eu.create=(e,t,r)=>new eu({valueType:t,keyType:e,typeName:l.ZodMap,...I(r)});class ec extends x{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==c.set)return g(r,{code:p.invalid_type,expected:c.set,received:r.parsedType}),w;let i=this._def;null!==i.minSize&&r.data.size<i.minSize.value&&(g(r,{code:p.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),t.dirty()),null!==i.maxSize&&r.data.size>i.maxSize.value&&(g(r,{code:p.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());let a=this._def.valueType;function n(e){let r=new Set;for(let i of e){if("aborted"===i.status)return w;"dirty"===i.status&&t.dirty(),r.add(i.value)}return{status:t.value,value:r}}let s=[...r.data.values()].map((e,t)=>a._parse(new S(r,e,r.path,t)));return r.common.async?Promise.all(s).then(e=>n(e)):n(s)}min(e,t){return new ec({...this._def,minSize:{value:e,message:o.toString(t)}})}max(e,t){return new ec({...this._def,maxSize:{value:e,message:o.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ec.create=(e,t)=>new ec({valueType:e,minSize:null,maxSize:null,typeName:l.ZodSet,...I(t)});class ed extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==c.function)return g(t,{code:p.invalid_type,expected:c.function,received:t.parsedType}),w;function r(e,r){return f({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,m,m].filter(e=>!!e),issueData:{code:p.invalid_arguments,argumentsError:r}})}function i(e,r){return f({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,m,m].filter(e=>!!e),issueData:{code:p.invalid_return_type,returnTypeError:r}})}let a={errorMap:t.common.contextualErrorMap},n=t.data;if(this._def.returns instanceof ey){let e=this;return v(async function(...t){let s=new h([]),o=await e._def.args.parseAsync(t,a).catch(e=>{throw s.addIssue(r(t,e)),s}),l=await Reflect.apply(n,this,o);return await e._def.returns._def.type.parseAsync(l,a).catch(e=>{throw s.addIssue(i(l,e)),s})})}{let e=this;return v(function(...t){let s=e._def.args.safeParse(t,a);if(!s.success)throw new h([r(t,s.error)]);let o=Reflect.apply(n,this,s.data),l=e._def.returns.safeParse(o,a);if(!l.success)throw new h([i(o,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ed({...this._def,args:eo.create(e).rest(Q.create())})}returns(e){return new ed({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new ed({args:e||eo.create([]).rest(Q.create()),returns:t||Q.create(),typeName:l.ZodFunction,...I(r)})}}class ep extends x{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ep.create=(e,t)=>new ep({getter:e,typeName:l.ZodLazy,...I(t)});class eh extends x{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return g(t,{received:t.data,code:p.invalid_literal,expected:this._def.value}),w}return{status:"valid",value:e.data}}get value(){return this._def.value}}function em(e,t){return new ef({values:e,typeName:l.ZodEnum,...I(t)})}eh.create=(e,t)=>new eh({value:e,typeName:l.ZodLiteral,...I(t)});class ef extends x{_parse(e){if("string"!=typeof e.data){let t=this._getOrReturnCtx(e),r=this._def.values;return g(t,{expected:n.joinValues(r),received:t.parsedType,code:p.invalid_type}),w}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return g(t,{received:t.data,code:p.invalid_enum_value,options:r}),w}return v(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ef.create(e,{...this._def,...t})}exclude(e,t=this._def){return ef.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}ef.create=em;class eg extends x{_parse(e){let t=n.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==c.string&&r.parsedType!==c.number){let e=n.objectValues(t);return g(r,{expected:n.joinValues(e),received:r.parsedType,code:p.invalid_type}),w}if(this._cache||(this._cache=new Set(n.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let e=n.objectValues(t);return g(r,{received:r.data,code:p.invalid_enum_value,options:e}),w}return v(e.data)}get enum(){return this._def.values}}eg.create=(e,t)=>new eg({values:e,typeName:l.ZodNativeEnum,...I(t)});class ey extends x{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==c.promise&&!1===t.common.async?(g(t,{code:p.invalid_type,expected:c.promise,received:t.parsedType}),w):v((t.parsedType===c.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ey.create=(e,t)=>new ey({type:e,typeName:l.ZodPromise,...I(t)});class ew extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===l.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),i=this._def.effect||null,a={addIssue:e=>{g(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),"preprocess"===i.type){let e=i.transform(r.data,a);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return w;let i=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===i.status?w:"dirty"===i.status||"dirty"===t.value?b(i.value):i});{if("aborted"===t.value)return w;let i=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===i.status?w:"dirty"===i.status||"dirty"===t.value?b(i.value):i}}if("refinement"===i.type){let e=e=>{let t=i.refinement(e,a);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?w:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))));{let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===i.status?w:("dirty"===i.status&&t.dirty(),e(i.value),{status:t.value,value:i.value})}}if("transform"===i.type)if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>"valid"!==e.status?w:Promise.resolve(i.transform(e.value,a)).then(e=>({status:t.value,value:e})));else{let e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if("valid"!==e.status)return w;let n=i.transform(e.value,a);if(n instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:n}}n.assertNever(i)}}ew.create=(e,t,r)=>new ew({schema:e,typeName:l.ZodEffects,effect:t,...I(r)}),ew.createWithPreprocess=(e,t,r)=>new ew({schema:t,effect:{type:"preprocess",transform:e},typeName:l.ZodEffects,...I(r)});class eb extends x{_parse(e){return this._getType(e)===c.undefined?v(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}eb.create=(e,t)=>new eb({innerType:e,typeName:l.ZodOptional,...I(t)});class ev extends x{_parse(e){return this._getType(e)===c.null?v(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ev.create=(e,t)=>new ev({innerType:e,typeName:l.ZodNullable,...I(t)});class ek extends x{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===c.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ek.create=(e,t)=>new ek({innerType:e,typeName:l.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...I(t)});class eS extends x{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return k(i)?i.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new h(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===i.status?i.value:this._def.catchValue({get error(){return new h(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}eS.create=(e,t)=>new eS({innerType:e,typeName:l.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...I(t)});class eE extends x{_parse(e){if(this._getType(e)!==c.nan){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.nan,received:t.parsedType}),w}return{status:"valid",value:e.data}}}eE.create=e=>new eE({typeName:l.ZodNaN,...I(e)}),Symbol("zod_brand");class eI extends x{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class ex extends x{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?w:"dirty"===e.status?(t.dirty(),b(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{let e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?w:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new ex({in:e,out:t,typeName:l.ZodPipeline})}}class eA extends x{_parse(e){let t=this._def.innerType._parse(e),r=e=>("valid"===e.status&&(e.value=Object.freeze(e.value)),e);return k(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}eA.create=(e,t)=>new eA({innerType:e,typeName:l.ZodReadonly,...I(t)}),er.lazycreate,(a=l||(l={})).ZodString="ZodString",a.ZodNumber="ZodNumber",a.ZodNaN="ZodNaN",a.ZodBigInt="ZodBigInt",a.ZodBoolean="ZodBoolean",a.ZodDate="ZodDate",a.ZodSymbol="ZodSymbol",a.ZodUndefined="ZodUndefined",a.ZodNull="ZodNull",a.ZodAny="ZodAny",a.ZodUnknown="ZodUnknown",a.ZodNever="ZodNever",a.ZodVoid="ZodVoid",a.ZodArray="ZodArray",a.ZodObject="ZodObject",a.ZodUnion="ZodUnion",a.ZodDiscriminatedUnion="ZodDiscriminatedUnion",a.ZodIntersection="ZodIntersection",a.ZodTuple="ZodTuple",a.ZodRecord="ZodRecord",a.ZodMap="ZodMap",a.ZodSet="ZodSet",a.ZodFunction="ZodFunction",a.ZodLazy="ZodLazy",a.ZodLiteral="ZodLiteral",a.ZodEnum="ZodEnum",a.ZodEffects="ZodEffects",a.ZodNativeEnum="ZodNativeEnum",a.ZodOptional="ZodOptional",a.ZodNullable="ZodNullable",a.ZodDefault="ZodDefault",a.ZodCatch="ZodCatch",a.ZodPromise="ZodPromise",a.ZodBranded="ZodBranded",a.ZodPipeline="ZodPipeline",a.ZodReadonly="ZodReadonly",K.create,V.create,eE.create,G.create,H.create,W.create,J.create,z.create,Z.create,Y.create,Q.create,X.create,ee.create,et.create;let e_=er.create;er.strictCreate,ei.create,en.create,es.create,eo.create,el.create,eu.create,ec.create,ed.create,ep.create,eh.create,ef.create,eg.create,ey.create,ew.create,eb.create,ev.create,ew.createWithPreprocess,ex.create,e.s(["ZodFirstPartyTypeKind",0,l,"object",0,e_],117958);var eC=e.i(127438),eR=e.i(639510),eT=e.i(486618),eD=e.i(862061);e.i(467662),e.i(236608);var eN=e.i(715143);let eO=eC.$constructor("ZodMiniType",(e,t)=>{if(!e._zod)throw Error("Uninitialized schema in ZodMiniType.");eR.$ZodType.init(e,t),e.def=t,e.type=t.type,e.parse=(t,r)=>eN.parse(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>eN.safeParse(e,t,r),e.parseAsync=async(t,r)=>eN.parseAsync(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>eN.safeParseAsync(e,t,r),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,r)=>eT.clone(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.apply=t=>t(e)}),eP=eC.$constructor("ZodMiniString",(e,t)=>{eR.$ZodString.init(e,t),eO.init(e,t)}),e$=((e,t)=>{eR.$ZodStringFormat.init(e,t),eP.init(e,t)},eC.$constructor("ZodMiniObject",(e,t)=>{eR.$ZodObject.init(e,t),eO.init(e,t),eT.defineLazy(e,"shape",()=>t.shape)}));function eU(e,t){return new e$({type:"object",shape:e??{},...eT.normalizeParams(t)})}function eB(e){return!!e._zod}function ej(e){let t=Object.values(e);if(0===t.length)return eU({});let r=t.every(eB),i=t.every(e=>!eB(e));if(r)return eU(e);if(i)return e_(e);throw Error("Mixed Zod versions detected in object shape.")}async function eL(e,t){return eB(e)?await eN.safeParseAsync(e,t):await e.safeParseAsync(t)}eD.describe,eD.meta,e.s(["getLiteralValue",0,function(e){if(eB(e)){let t=e._zod?.def;if(t){if(void 0!==t.value)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(void 0!==t.value)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let r=e.value;if(void 0!==r)return r},"getObjectShape",0,function(e){let t;if(e&&(t=eB(e)?e._zod?.def?.shape:e.shape)){if("function"==typeof t)try{return t()}catch{return}return t}},"getParseErrorMessage",0,function(e){if(e&&"object"==typeof e){if("message"in e&&"string"==typeof e.message)return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&"object"==typeof t&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch{}}return String(e)},"getSchemaDescription",0,function(e){return e.description},"isSchemaOptional",0,function(e){return eB(e)?e._zod?.def?.type==="optional":"function"==typeof e.isOptional?e.isOptional():e._def?.typeName==="ZodOptional"},"isZ4Schema",0,eB,"normalizeObjectSchema",0,function(e){if(e){if("object"==typeof e&&!e._def&&!e._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>"object"==typeof e&&null!==e&&(void 0!==e._def||void 0!==e._zod||"function"==typeof e.parse)))return ej(e)}if(eB(e)){let t=e._zod?.def;if(t&&("object"===t.type||void 0!==t.shape))return e}else if(void 0!==e.shape)return e}},"objectFromShape",0,ej,"safeParse",0,function(e,t){return eB(e)?eN.safeParse(e,t):e.safeParse(t)},"safeParseAsync",0,eL],514849)},556690,807237,e=>{"use strict";var t,r,i=e.i(907855),a=e.i(551047);e.s(["iso",0,a],807237);var a=a;let n="2025-11-25",s=[n,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],o="io.modelcontextprotocol/related-task",l=i.custom(e=>null!==e&&("object"==typeof e||"function"==typeof e)),u=i.union([i.string(),i.number().int()]),c=i.string();i.looseObject({ttl:i.number().optional(),pollInterval:i.number().optional()});let d=i.object({ttl:i.number().optional()}),p=i.object({taskId:i.string()}),h=i.looseObject({progressToken:u.optional(),[o]:p.optional()}),m=i.object({_meta:h.optional()}),f=m.extend({task:d.optional()}),g=i.object({method:i.string(),params:m.loose().optional()}),y=i.object({_meta:h.optional()}),w=i.object({method:i.string(),params:y.loose().optional()}),b=i.looseObject({_meta:h.optional()}),v=i.union([i.string(),i.number().int()]),k=i.object({jsonrpc:i.literal("2.0"),id:v,...g.shape}).strict(),S=i.object({jsonrpc:i.literal("2.0"),...w.shape}).strict(),E=i.object({jsonrpc:i.literal("2.0"),id:v,result:b}).strict();(t=r||(r={}))[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired";let I=i.object({jsonrpc:i.literal("2.0"),id:v.optional(),error:i.object({code:i.number().int(),message:i.string(),data:i.unknown().optional()})}).strict(),x=i.union([k,S,E,I]);i.union([E,I]);let A=b.strict(),_=y.extend({requestId:v.optional(),reason:i.string().optional()}),C=w.extend({method:i.literal("notifications/cancelled"),params:_}),R=i.object({src:i.string(),mimeType:i.string().optional(),sizes:i.array(i.string()).optional(),theme:i.enum(["light","dark"]).optional()}),T=i.object({icons:i.array(R).optional()}),D=i.object({name:i.string(),title:i.string().optional()}),N=D.extend({...D.shape,...T.shape,version:i.string(),websiteUrl:i.string().optional(),description:i.string().optional()}),O=i.intersection(i.object({applyDefaults:i.boolean().optional()}),i.record(i.string(),i.unknown())),P=i.preprocess(e=>e&&"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length?{form:{}}:e,i.intersection(i.object({form:O.optional(),url:l.optional()}),i.record(i.string(),i.unknown()).optional())),$=i.looseObject({list:l.optional(),cancel:l.optional(),requests:i.looseObject({sampling:i.looseObject({createMessage:l.optional()}).optional(),elicitation:i.looseObject({create:l.optional()}).optional()}).optional()}),U=i.looseObject({list:l.optional(),cancel:l.optional(),requests:i.looseObject({tools:i.looseObject({call:l.optional()}).optional()}).optional()}),B=i.object({experimental:i.record(i.string(),l).optional(),sampling:i.object({context:l.optional(),tools:l.optional()}).optional(),elicitation:P.optional(),roots:i.object({listChanged:i.boolean().optional()}).optional(),tasks:$.optional(),extensions:i.record(i.string(),l).optional()}),j=m.extend({protocolVersion:i.string(),capabilities:B,clientInfo:N}),L=g.extend({method:i.literal("initialize"),params:j}),q=i.object({experimental:i.record(i.string(),l).optional(),logging:l.optional(),completions:l.optional(),prompts:i.object({listChanged:i.boolean().optional()}).optional(),resources:i.object({subscribe:i.boolean().optional(),listChanged:i.boolean().optional()}).optional(),tools:i.object({listChanged:i.boolean().optional()}).optional(),tasks:U.optional(),extensions:i.record(i.string(),l).optional()}),M=b.extend({protocolVersion:i.string(),capabilities:q,serverInfo:N,instructions:i.string().optional()}),F=w.extend({method:i.literal("notifications/initialized"),params:y.optional()}),K=g.extend({method:i.literal("ping"),params:m.optional()}),V=i.object({progress:i.number(),total:i.optional(i.number()),message:i.optional(i.string())}),G=i.object({...y.shape,...V.shape,progressToken:u}),H=w.extend({method:i.literal("notifications/progress"),params:G}),W=m.extend({cursor:c.optional()}),J=g.extend({params:W.optional()}),z=b.extend({nextCursor:c.optional()}),Z=i.enum(["working","input_required","completed","failed","cancelled"]),Y=i.object({taskId:i.string(),status:Z,ttl:i.union([i.number(),i.null()]),createdAt:i.string(),lastUpdatedAt:i.string(),pollInterval:i.optional(i.number()),statusMessage:i.optional(i.string())}),Q=b.extend({task:Y}),X=y.merge(Y),ee=w.extend({method:i.literal("notifications/tasks/status"),params:X}),et=g.extend({method:i.literal("tasks/get"),params:m.extend({taskId:i.string()})}),er=b.merge(Y),ei=g.extend({method:i.literal("tasks/result"),params:m.extend({taskId:i.string()})});b.loose();let ea=J.extend({method:i.literal("tasks/list")}),en=z.extend({tasks:i.array(Y)}),es=g.extend({method:i.literal("tasks/cancel"),params:m.extend({taskId:i.string()})}),eo=b.merge(Y),el=i.object({uri:i.string(),mimeType:i.optional(i.string()),_meta:i.record(i.string(),i.unknown()).optional()}),eu=el.extend({text:i.string()}),ec=i.string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),ed=el.extend({blob:ec}),ep=i.enum(["user","assistant"]),eh=i.object({audience:i.array(ep).optional(),priority:i.number().min(0).max(1).optional(),lastModified:a.datetime({offset:!0}).optional()}),em=i.object({...D.shape,...T.shape,uri:i.string(),description:i.optional(i.string()),mimeType:i.optional(i.string()),size:i.optional(i.number()),annotations:eh.optional(),_meta:i.optional(i.looseObject({}))}),ef=i.object({...D.shape,...T.shape,uriTemplate:i.string(),description:i.optional(i.string()),mimeType:i.optional(i.string()),annotations:eh.optional(),_meta:i.optional(i.looseObject({}))}),eg=J.extend({method:i.literal("resources/list")}),ey=z.extend({resources:i.array(em)}),ew=J.extend({method:i.literal("resources/templates/list")}),eb=z.extend({resourceTemplates:i.array(ef)}),ev=m.extend({uri:i.string()}),ek=g.extend({method:i.literal("resources/read"),params:ev}),eS=b.extend({contents:i.array(i.union([eu,ed]))}),eE=w.extend({method:i.literal("notifications/resources/list_changed"),params:y.optional()}),eI=g.extend({method:i.literal("resources/subscribe"),params:ev}),ex=g.extend({method:i.literal("resources/unsubscribe"),params:ev}),eA=y.extend({uri:i.string()}),e_=w.extend({method:i.literal("notifications/resources/updated"),params:eA}),eC=i.object({name:i.string(),description:i.optional(i.string()),required:i.optional(i.boolean())}),eR=i.object({...D.shape,...T.shape,description:i.optional(i.string()),arguments:i.optional(i.array(eC)),_meta:i.optional(i.looseObject({}))}),eT=J.extend({method:i.literal("prompts/list")}),eD=z.extend({prompts:i.array(eR)}),eN=m.extend({name:i.string(),arguments:i.record(i.string(),i.string()).optional()}),eO=g.extend({method:i.literal("prompts/get"),params:eN}),eP=i.object({type:i.literal("text"),text:i.string(),annotations:eh.optional(),_meta:i.record(i.string(),i.unknown()).optional()}),e$=i.object({type:i.literal("image"),data:ec,mimeType:i.string(),annotations:eh.optional(),_meta:i.record(i.string(),i.unknown()).optional()}),eU=i.object({type:i.literal("audio"),data:ec,mimeType:i.string(),annotations:eh.optional(),_meta:i.record(i.string(),i.unknown()).optional()}),eB=i.object({type:i.literal("tool_use"),name:i.string(),id:i.string(),input:i.record(i.string(),i.unknown()),_meta:i.record(i.string(),i.unknown()).optional()}),ej=i.object({type:i.literal("resource"),resource:i.union([eu,ed]),annotations:eh.optional(),_meta:i.record(i.string(),i.unknown()).optional()}),eL=em.extend({type:i.literal("resource_link")}),eq=i.union([eP,e$,eU,eL,ej]),eM=i.object({role:ep,content:eq}),eF=b.extend({description:i.string().optional(),messages:i.array(eM)}),eK=w.extend({method:i.literal("notifications/prompts/list_changed"),params:y.optional()}),eV=i.object({title:i.string().optional(),readOnlyHint:i.boolean().optional(),destructiveHint:i.boolean().optional(),idempotentHint:i.boolean().optional(),openWorldHint:i.boolean().optional()}),eG=i.object({taskSupport:i.enum(["required","optional","forbidden"]).optional()}),eH=i.object({...D.shape,...T.shape,description:i.string().optional(),inputSchema:i.object({type:i.literal("object"),properties:i.record(i.string(),l).optional(),required:i.array(i.string()).optional()}).catchall(i.unknown()),outputSchema:i.object({type:i.literal("object"),properties:i.record(i.string(),l).optional(),required:i.array(i.string()).optional()}).catchall(i.unknown()).optional(),annotations:eV.optional(),execution:eG.optional(),_meta:i.record(i.string(),i.unknown()).optional()}),eW=J.extend({method:i.literal("tools/list")}),eJ=z.extend({tools:i.array(eH)}),ez=b.extend({content:i.array(eq).default([]),structuredContent:i.record(i.string(),i.unknown()).optional(),isError:i.boolean().optional()});ez.or(b.extend({toolResult:i.unknown()}));let eZ=f.extend({name:i.string(),arguments:i.record(i.string(),i.unknown()).optional()}),eY=g.extend({method:i.literal("tools/call"),params:eZ}),eQ=w.extend({method:i.literal("notifications/tools/list_changed"),params:y.optional()}),eX=i.object({autoRefresh:i.boolean().default(!0),debounceMs:i.number().int().nonnegative().default(300)}),e0=i.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),e1=m.extend({level:e0}),e2=g.extend({method:i.literal("logging/setLevel"),params:e1}),e3=y.extend({level:e0,logger:i.string().optional(),data:i.unknown()}),e4=w.extend({method:i.literal("notifications/message"),params:e3}),e6=i.object({name:i.string().optional()}),e8=i.object({hints:i.array(e6).optional(),costPriority:i.number().min(0).max(1).optional(),speedPriority:i.number().min(0).max(1).optional(),intelligencePriority:i.number().min(0).max(1).optional()}),e5=i.object({mode:i.enum(["auto","required","none"]).optional()}),e9=i.object({type:i.literal("tool_result"),toolUseId:i.string().describe("The unique identifier for the corresponding tool call."),content:i.array(eq).default([]),structuredContent:i.object({}).loose().optional(),isError:i.boolean().optional(),_meta:i.record(i.string(),i.unknown()).optional()}),e7=i.discriminatedUnion("type",[eP,e$,eU]),te=i.discriminatedUnion("type",[eP,e$,eU,eB,e9]),tt=i.object({role:ep,content:i.union([te,i.array(te)]),_meta:i.record(i.string(),i.unknown()).optional()}),tr=f.extend({messages:i.array(tt),modelPreferences:e8.optional(),systemPrompt:i.string().optional(),includeContext:i.enum(["none","thisServer","allServers"]).optional(),temperature:i.number().optional(),maxTokens:i.number().int(),stopSequences:i.array(i.string()).optional(),metadata:l.optional(),tools:i.array(eH).optional(),toolChoice:e5.optional()}),ti=g.extend({method:i.literal("sampling/createMessage"),params:tr}),ta=b.extend({model:i.string(),stopReason:i.optional(i.enum(["endTurn","stopSequence","maxTokens"]).or(i.string())),role:ep,content:e7}),tn=b.extend({model:i.string(),stopReason:i.optional(i.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(i.string())),role:ep,content:i.union([te,i.array(te)])}),ts=i.object({type:i.literal("boolean"),title:i.string().optional(),description:i.string().optional(),default:i.boolean().optional()}),to=i.object({type:i.literal("string"),title:i.string().optional(),description:i.string().optional(),minLength:i.number().optional(),maxLength:i.number().optional(),format:i.enum(["email","uri","date","date-time"]).optional(),default:i.string().optional()}),tl=i.object({type:i.enum(["number","integer"]),title:i.string().optional(),description:i.string().optional(),minimum:i.number().optional(),maximum:i.number().optional(),default:i.number().optional()}),tu=i.object({type:i.literal("string"),title:i.string().optional(),description:i.string().optional(),enum:i.array(i.string()),default:i.string().optional()}),tc=i.object({type:i.literal("string"),title:i.string().optional(),description:i.string().optional(),oneOf:i.array(i.object({const:i.string(),title:i.string()})),default:i.string().optional()}),td=i.object({type:i.literal("string"),title:i.string().optional(),description:i.string().optional(),enum:i.array(i.string()),enumNames:i.array(i.string()).optional(),default:i.string().optional()}),tp=i.union([tu,tc]),th=i.object({type:i.literal("array"),title:i.string().optional(),description:i.string().optional(),minItems:i.number().optional(),maxItems:i.number().optional(),items:i.object({type:i.literal("string"),enum:i.array(i.string())}),default:i.array(i.string()).optional()}),tm=i.object({type:i.literal("array"),title:i.string().optional(),description:i.string().optional(),minItems:i.number().optional(),maxItems:i.number().optional(),items:i.object({anyOf:i.array(i.object({const:i.string(),title:i.string()}))}),default:i.array(i.string()).optional()}),tf=i.union([th,tm]),tg=i.union([td,tp,tf]),ty=i.union([tg,ts,to,tl]),tw=f.extend({mode:i.literal("form").optional(),message:i.string(),requestedSchema:i.object({type:i.literal("object"),properties:i.record(i.string(),ty),required:i.array(i.string()).optional()})}),tb=f.extend({mode:i.literal("url"),message:i.string(),elicitationId:i.string(),url:i.string().url()}),tv=i.union([tw,tb]),tk=g.extend({method:i.literal("elicitation/create"),params:tv}),tS=y.extend({elicitationId:i.string()}),tE=w.extend({method:i.literal("notifications/elicitation/complete"),params:tS}),tI=b.extend({action:i.enum(["accept","decline","cancel"]),content:i.preprocess(e=>null===e?void 0:e,i.record(i.string(),i.union([i.string(),i.number(),i.boolean(),i.array(i.string())])).optional())}),tx=i.object({type:i.literal("ref/resource"),uri:i.string()}),tA=i.object({type:i.literal("ref/prompt"),name:i.string()}),t_=m.extend({ref:i.union([tA,tx]),argument:i.object({name:i.string(),value:i.string()}),context:i.object({arguments:i.record(i.string(),i.string()).optional()}).optional()}),tC=g.extend({method:i.literal("completion/complete"),params:t_}),tR=b.extend({completion:i.looseObject({values:i.array(i.string()).max(100),total:i.optional(i.number().int()),hasMore:i.optional(i.boolean())})}),tT=i.object({uri:i.string().startsWith("file://"),name:i.string().optional(),_meta:i.record(i.string(),i.unknown()).optional()}),tD=g.extend({method:i.literal("roots/list"),params:m.optional()}),tN=b.extend({roots:i.array(tT)}),tO=w.extend({method:i.literal("notifications/roots/list_changed"),params:y.optional()});i.union([K,L,tC,e2,eO,eT,eg,ew,ek,eI,ex,eY,eW,et,ei,ea,es]),i.union([C,H,F,tO,ee]),i.union([A,ta,tn,tI,tN,er,en,Q]),i.union([K,ti,tk,tD,et,ei,ea,es]),i.union([C,H,e4,e_,eE,eQ,eK,ee,tE]),i.union([A,M,tR,eF,eD,ey,eb,eS,ez,eJ,er,en,Q]);class tP extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,t,i){return e===r.UrlElicitationRequired&&i&&i.elicitations?new t$(i.elicitations,t):new tP(e,t,i)}}class t$ extends tP{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(r.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}e.s(["CallToolRequestSchema",0,eY,"CallToolResultSchema",0,ez,"CancelTaskRequestSchema",0,es,"CancelTaskResultSchema",0,eo,"CancelledNotificationSchema",0,C,"CompleteRequestSchema",0,tC,"CompleteResultSchema",0,tR,"CreateMessageRequestSchema",0,ti,"CreateMessageResultSchema",0,ta,"CreateMessageResultWithToolsSchema",0,tn,"CreateTaskResultSchema",0,Q,"DEFAULT_NEGOTIATED_PROTOCOL_VERSION",0,"2025-03-26","ElicitRequestSchema",0,tk,"ElicitResultSchema",0,tI,"EmptyResultSchema",0,A,"ErrorCode",0,r,"GetPromptRequestSchema",0,eO,"GetPromptResultSchema",0,eF,"GetTaskPayloadRequestSchema",0,ei,"GetTaskRequestSchema",0,et,"GetTaskResultSchema",0,er,"InitializeRequestSchema",0,L,"InitializeResultSchema",0,M,"InitializedNotificationSchema",0,F,"JSONRPCMessageSchema",0,x,"LATEST_PROTOCOL_VERSION",0,n,"ListChangedOptionsBaseSchema",0,eX,"ListPromptsRequestSchema",0,eT,"ListPromptsResultSchema",0,eD,"ListResourceTemplatesRequestSchema",0,ew,"ListResourceTemplatesResultSchema",0,eb,"ListResourcesRequestSchema",0,eg,"ListResourcesResultSchema",0,ey,"ListRootsResultSchema",0,tN,"ListTasksRequestSchema",0,ea,"ListTasksResultSchema",0,en,"ListToolsRequestSchema",0,eW,"ListToolsResultSchema",0,eJ,"LoggingLevelSchema",0,e0,"McpError",0,tP,"PingRequestSchema",0,K,"ProgressNotificationSchema",0,H,"PromptListChangedNotificationSchema",0,eK,"RELATED_TASK_META_KEY",0,o,"ReadResourceRequestSchema",0,ek,"ReadResourceResultSchema",0,eS,"ResourceListChangedNotificationSchema",0,eE,"SUPPORTED_PROTOCOL_VERSIONS",0,s,"SetLevelRequestSchema",0,e2,"TaskStatusNotificationSchema",0,ee,"ToolListChangedNotificationSchema",0,eQ,"assertCompleteRequestPrompt",0,function(e){if("ref/prompt"!==e.params.ref.type)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)},"assertCompleteRequestResourceTemplate",0,function(e){if("ref/resource"!==e.params.ref.type)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)},"isInitializeRequest",0,e=>L.safeParse(e).success,"isInitializedNotification",0,e=>F.safeParse(e).success,"isJSONRPCErrorResponse",0,e=>I.safeParse(e).success,"isJSONRPCNotification",0,e=>S.safeParse(e).success,"isJSONRPCRequest",0,e=>k.safeParse(e).success,"isJSONRPCResultResponse",0,e=>E.safeParse(e).success,"isTaskAugmentedRequestParams",0,e=>f.safeParse(e).success],556690)},917397,(e,t,r)=>{!function(t,r){"use strict";function i(e,t){if(!e)throw Error(t||"Assertion failed")}function a(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}function n(e,t,r){if(n.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&(("le"===t||"be"===t)&&(r=t,t=10),this._init(e||0,t||10,r||"be"))}t.exports=n,n.BN=n,n.wordSize=26;try{u=e.r(500874).Buffer}catch(e){}function s(e,t){var r=e.charCodeAt(t);return r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:r-48&15}function o(e,t,r){var i=s(e,r);return r-1>=t&&(i|=s(e,r-1)<<4),i}function l(e,t,r,i){for(var a=0,n=Math.min(e.length,r),s=t;s<n;s++){var o=e.charCodeAt(s)-48;a*=i,o>=49?a+=o-49+10:o>=17?a+=o-17+10:a+=o}return a}n.isBN=function(e){return e instanceof n||null!==e&&"object"==typeof e&&e.constructor.wordSize===n.wordSize&&Array.isArray(e.words)},n.max=function(e,t){return e.cmp(t)>0?e:t},n.min=function(e,t){return 0>e.cmp(t)?e:t},n.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),i(t===(0|t)&&t>=2&&t<=36);var a=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(a++,this.negative=1),a<e.length&&(16===t?this._parseHex(e,a,r):(this._parseBase(e,t,a),"le"===r&&this._initArray(this.toArray(),t,r)))},n.prototype._initNumber=function(e,t,r){e<0&&(this.negative=1,e=-e),e<0x4000000?(this.words=[0x3ffffff&e],this.length=1):e<0x10000000000000?(this.words=[0x3ffffff&e,e/0x4000000&0x3ffffff],this.length=2):(i(e<0x20000000000000),this.words=[0x3ffffff&e,e/0x4000000&0x3ffffff,1],this.length=3),"le"===r&&this._initArray(this.toArray(),t,r)},n.prototype._initArray=function(e,t,r){if(i("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=Array(this.length);for(var a,n,s=0;s<this.length;s++)this.words[s]=0;var o=0;if("be"===r)for(s=e.length-1,a=0;s>=0;s-=3)n=e[s]|e[s-1]<<8|e[s-2]<<16,this.words[a]|=n<<o&0x3ffffff,this.words[a+1]=n>>>26-o&0x3ffffff,(o+=24)>=26&&(o-=26,a++);else if("le"===r)for(s=0,a=0;s<e.length;s+=3)n=e[s]|e[s+1]<<8|e[s+2]<<16,this.words[a]|=n<<o&0x3ffffff,this.words[a+1]=n>>>26-o&0x3ffffff,(o+=24)>=26&&(o-=26,a++);return this.strip()},n.prototype._parseHex=function(e,t,r){this.length=Math.ceil((e.length-t)/6),this.words=Array(this.length);for(var i,a=0;a<this.length;a++)this.words[a]=0;var n=0,s=0;if("be"===r)for(a=e.length-1;a>=t;a-=2)i=o(e,t,a)<<n,this.words[s]|=0x3ffffff&i,n>=18?(n-=18,s+=1,this.words[s]|=i>>>26):n+=8;else for(a=(e.length-t)%2==0?t+1:t;a<e.length;a+=2)i=o(e,t,a)<<n,this.words[s]|=0x3ffffff&i,n>=18?(n-=18,s+=1,this.words[s]|=i>>>26):n+=8;this.strip()},n.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var i=0,a=1;a<=0x3ffffff;a*=t)i++;i--,a=a/t|0;for(var n=e.length-r,s=n%i,o=Math.min(n,n-s)+r,u=0,c=r;c<o;c+=i)u=l(e,c,c+i,t),this.imuln(a),this.words[0]+u<0x4000000?this.words[0]+=u:this._iaddn(u);if(0!==s){var d=1;for(u=l(e,c,e.length,t),c=0;c<s;c++)d*=t;this.imuln(d),this.words[0]+u<0x4000000?this.words[0]+=u:this._iaddn(u)}this.strip()},n.prototype.copy=function(e){e.words=Array(this.length);for(var t=0;t<this.length;t++)e.words[t]=this.words[t];e.length=this.length,e.negative=this.negative,e.red=this.red},n.prototype.clone=function(){var e=new n(null);return this.copy(e),e},n.prototype._expand=function(e){for(;this.length<e;)this.words[this.length++]=0;return this},n.prototype.strip=function(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this._normSign()},n.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},n.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var u,c=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],d=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],p=[0,0,0x2000000,0x290d741,0x1000000,0x2e90edd,0x39aa400,0x267bf47,0x1000000,0x290d741,1e7,0x12959c3,0x222c000,0x3bd7765,7529536,0xadcea1,0x1000000,0x1704f61,0x206fc40,0x2cddcf9,64e6,4084101,5153632,6436343,7962624,9765625,0xb54ba0,0xdaf26b,0x1069c00,0x138f9ad,243e5,0x1b4d89f,0x2000000,0x25528a1,0x2b54a20,0x3216b93,0x39aa400];function h(e,t,r){r.negative=t.negative^e.negative;var i=e.length+t.length|0;r.length=i,i=i-1|0;var a=0|e.words[0],n=0|t.words[0],s=a*n,o=0x3ffffff&s,l=s/0x4000000|0;r.words[0]=o;for(var u=1;u<i;u++){for(var c=l>>>26,d=0x3ffffff&l,p=Math.min(u,t.length-1),h=Math.max(0,u-e.length+1);h<=p;h++){var m=u-h|0;c+=(s=(a=0|e.words[m])*(n=0|t.words[h])+d)/0x4000000|0,d=0x3ffffff&s}r.words[u]=0|d,l=0|c}return 0!==l?r.words[u]=0|l:r.length--,r.strip()}n.prototype.toString=function(e,t){if(t=0|t||1,16===(e=e||10)||"hex"===e){for(var r="",a=0,n=0,s=0;s<this.length;s++){var o=this.words[s],l=((o<<a|n)&0xffffff).toString(16);n=o>>>24-a&0xffffff,(a+=2)>=26&&(a-=26,s--),r=0!==n||s!==this.length-1?c[6-l.length]+l+r:l+r}for(0!==n&&(r=n.toString(16)+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var u=d[e],h=p[e];r="";var m=this.clone();for(m.negative=0;!m.isZero();){var f=m.modn(h).toString(e);r=(m=m.idivn(h)).isZero()?f+r:c[u-f.length]+f+r}for(this.isZero()&&(r="0"+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}i(!1,"Base should be between 2 and 36")},n.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=0x4000000*this.words[1]:3===this.length&&1===this.words[2]?e+=0x10000000000000+0x4000000*this.words[1]:this.length>2&&i(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},n.prototype.toJSON=function(){return this.toString(16)},n.prototype.toBuffer=function(e,t){return i(void 0!==u),this.toArrayLike(u,e,t)},n.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},n.prototype.toArrayLike=function(e,t,r){var a,n,s=this.byteLength(),o=r||Math.max(1,s);i(s<=o,"byte array longer than desired length"),i(o>0,"Requested array length <= 0"),this.strip();var l=new e(o),u=this.clone();if("le"===t){for(n=0;!u.isZero();n++)a=u.andln(255),u.iushrn(8),l[n]=a;for(;n<o;n++)l[n]=0}else{for(n=0;n<o-s;n++)l[n]=0;for(n=0;!u.isZero();n++)a=u.andln(255),u.iushrn(8),l[o-n-1]=a}return l},Math.clz32?n.prototype._countBits=function(e){return 32-Math.clz32(e)}:n.prototype._countBits=function(e){var t=e,r=0;return t>=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},n.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return(8191&t)==0&&(r+=13,t>>>=13),(127&t)==0&&(r+=7,t>>>=7),(15&t)==0&&(r+=4,t>>>=4),(3&t)==0&&(r+=2,t>>>=2),(1&t)==0&&r++,r},n.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return(this.length-1)*26+t},n.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;t<this.length;t++){var r=this._zeroBits(this.words[t]);if(e+=r,26!==r)break}return e},n.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},n.prototype.toTwos=function(e){return 0!==this.negative?this.abs().inotn(e).iaddn(1):this.clone()},n.prototype.fromTwos=function(e){return this.testn(e-1)?this.notn(e).iaddn(1).ineg():this.clone()},n.prototype.isNeg=function(){return 0!==this.negative},n.prototype.neg=function(){return this.clone().ineg()},n.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},n.prototype.iuor=function(e){for(;this.length<e.length;)this.words[this.length++]=0;for(var t=0;t<e.length;t++)this.words[t]=this.words[t]|e.words[t];return this.strip()},n.prototype.ior=function(e){return i((this.negative|e.negative)==0),this.iuor(e)},n.prototype.or=function(e){return this.length>e.length?this.clone().ior(e):e.clone().ior(this)},n.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},n.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;r<t.length;r++)this.words[r]=this.words[r]&e.words[r];return this.length=t.length,this.strip()},n.prototype.iand=function(e){return i((this.negative|e.negative)==0),this.iuand(e)},n.prototype.and=function(e){return this.length>e.length?this.clone().iand(e):e.clone().iand(this)},n.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},n.prototype.iuxor=function(e){this.length>e.length?(t=this,r=e):(t=e,r=this);for(var t,r,i=0;i<r.length;i++)this.words[i]=t.words[i]^r.words[i];if(this!==t)for(;i<t.length;i++)this.words[i]=t.words[i];return this.length=t.length,this.strip()},n.prototype.ixor=function(e){return i((this.negative|e.negative)==0),this.iuxor(e)},n.prototype.xor=function(e){return this.length>e.length?this.clone().ixor(e):e.clone().ixor(this)},n.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},n.prototype.inotn=function(e){i("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var a=0;a<t;a++)this.words[a]=0x3ffffff&~this.words[a];for(r>0&&(this.words[a]=~this.words[a]&0x3ffffff>>26-r,a++);a<this.length;a++)this.words[a]=0;return this.strip()},n.prototype.notn=function(e){return this.clone().inotn(e)},n.prototype.setn=function(e,t){i("number"==typeof e&&e>=0);var r=e/26|0,a=e%26;return this._expand(r+1),t?this.words[r]=this.words[r]|1<<a:this.words[r]=this.words[r]&~(1<<a),this.strip()},n.prototype.iadd=function(e){if(0!==this.negative&&0===e.negative)return this.negative=0,t=this.isub(e),this.negative^=1,this._normSign();if(0===this.negative&&0!==e.negative)return e.negative=0,t=this.isub(e),e.negative=1,t._normSign();this.length>e.length?(r=this,i=e):(r=e,i=this);for(var t,r,i,a=0,n=0;n<i.length;n++)t=(0|r.words[n])+(0|i.words[n])+a,this.words[n]=0x3ffffff&t,a=t>>>26;for(;0!==a&&n<r.length;n++)t=(0|r.words[n])+a,this.words[n]=0x3ffffff&t,a=t>>>26;if(this.length=r.length,0!==a)this.words[this.length]=a,this.length++;else if(r!==this)for(;n<r.length;n++)this.words[n]=r.words[n];return this},n.prototype.add=function(e){var t;return 0!==e.negative&&0===this.negative?(e.negative=0,t=this.sub(e),e.negative^=1,t):0===e.negative&&0!==this.negative?(this.negative=0,t=e.sub(this),this.negative=1,t):this.length>e.length?this.clone().iadd(e):e.clone().iadd(this)},n.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t,r,i=this.iadd(e);return e.negative=1,i._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var a=this.cmp(e);if(0===a)return this.negative=0,this.length=1,this.words[0]=0,this;a>0?(t=this,r=e):(t=e,r=this);for(var n=0,s=0;s<r.length;s++)n=(i=(0|t.words[s])-(0|r.words[s])+n)>>26,this.words[s]=0x3ffffff&i;for(;0!==n&&s<t.length;s++)n=(i=(0|t.words[s])+n)>>26,this.words[s]=0x3ffffff&i;if(0===n&&s<t.length&&t!==this)for(;s<t.length;s++)this.words[s]=t.words[s];return this.length=Math.max(this.length,s),t!==this&&(this.negative=1),this.strip()},n.prototype.sub=function(e){return this.clone().isub(e)};var m=function(e,t,r){var i,a,n,s=e.words,o=t.words,l=r.words,u=0,c=0|s[0],d=8191&c,p=c>>>13,h=0|s[1],m=8191&h,f=h>>>13,g=0|s[2],y=8191&g,w=g>>>13,b=0|s[3],v=8191&b,k=b>>>13,S=0|s[4],E=8191&S,I=S>>>13,x=0|s[5],A=8191&x,_=x>>>13,C=0|s[6],R=8191&C,T=C>>>13,D=0|s[7],N=8191&D,O=D>>>13,P=0|s[8],$=8191&P,U=P>>>13,B=0|s[9],j=8191&B,L=B>>>13,q=0|o[0],M=8191&q,F=q>>>13,K=0|o[1],V=8191&K,G=K>>>13,H=0|o[2],W=8191&H,J=H>>>13,z=0|o[3],Z=8191&z,Y=z>>>13,Q=0|o[4],X=8191&Q,ee=Q>>>13,et=0|o[5],er=8191&et,ei=et>>>13,ea=0|o[6],en=8191&ea,es=ea>>>13,eo=0|o[7],el=8191&eo,eu=eo>>>13,ec=0|o[8],ed=8191&ec,ep=ec>>>13,eh=0|o[9],em=8191&eh,ef=eh>>>13;r.negative=e.negative^t.negative,r.length=19,i=Math.imul(d,M);var eg=(u+i|0)+((8191&(a=(a=Math.imul(d,F))+Math.imul(p,M)|0))<<13)|0;u=((n=Math.imul(p,F))+(a>>>13)|0)+(eg>>>26)|0,eg&=0x3ffffff,i=Math.imul(m,M),a=(a=Math.imul(m,F))+Math.imul(f,M)|0,n=Math.imul(f,F),i=i+Math.imul(d,V)|0;var ey=(u+i|0)+((8191&(a=(a=a+Math.imul(d,G)|0)+Math.imul(p,V)|0))<<13)|0;u=((n=n+Math.imul(p,G)|0)+(a>>>13)|0)+(ey>>>26)|0,ey&=0x3ffffff,i=Math.imul(y,M),a=(a=Math.imul(y,F))+Math.imul(w,M)|0,n=Math.imul(w,F),i=i+Math.imul(m,V)|0,a=(a=a+Math.imul(m,G)|0)+Math.imul(f,V)|0,n=n+Math.imul(f,G)|0,i=i+Math.imul(d,W)|0;var ew=(u+i|0)+((8191&(a=(a=a+Math.imul(d,J)|0)+Math.imul(p,W)|0))<<13)|0;u=((n=n+Math.imul(p,J)|0)+(a>>>13)|0)+(ew>>>26)|0,ew&=0x3ffffff,i=Math.imul(v,M),a=(a=Math.imul(v,F))+Math.imul(k,M)|0,n=Math.imul(k,F),i=i+Math.imul(y,V)|0,a=(a=a+Math.imul(y,G)|0)+Math.imul(w,V)|0,n=n+Math.imul(w,G)|0,i=i+Math.imul(m,W)|0,a=(a=a+Math.imul(m,J)|0)+Math.imul(f,W)|0,n=n+Math.imul(f,J)|0,i=i+Math.imul(d,Z)|0;var eb=(u+i|0)+((8191&(a=(a=a+Math.imul(d,Y)|0)+Math.imul(p,Z)|0))<<13)|0;u=((n=n+Math.imul(p,Y)|0)+(a>>>13)|0)+(eb>>>26)|0,eb&=0x3ffffff,i=Math.imul(E,M),a=(a=Math.imul(E,F))+Math.imul(I,M)|0,n=Math.imul(I,F),i=i+Math.imul(v,V)|0,a=(a=a+Math.imul(v,G)|0)+Math.imul(k,V)|0,n=n+Math.imul(k,G)|0,i=i+Math.imul(y,W)|0,a=(a=a+Math.imul(y,J)|0)+Math.imul(w,W)|0,n=n+Math.imul(w,J)|0,i=i+Math.imul(m,Z)|0,a=(a=a+Math.imul(m,Y)|0)+Math.imul(f,Z)|0,n=n+Math.imul(f,Y)|0,i=i+Math.imul(d,X)|0;var ev=(u+i|0)+((8191&(a=(a=a+Math.imul(d,ee)|0)+Math.imul(p,X)|0))<<13)|0;u=((n=n+Math.imul(p,ee)|0)+(a>>>13)|0)+(ev>>>26)|0,ev&=0x3ffffff,i=Math.imul(A,M),a=(a=Math.imul(A,F))+Math.imul(_,M)|0,n=Math.imul(_,F),i=i+Math.imul(E,V)|0,a=(a=a+Math.imul(E,G)|0)+Math.imul(I,V)|0,n=n+Math.imul(I,G)|0,i=i+Math.imul(v,W)|0,a=(a=a+Math.imul(v,J)|0)+Math.imul(k,W)|0,n=n+Math.imul(k,J)|0,i=i+Math.imul(y,Z)|0,a=(a=a+Math.imul(y,Y)|0)+Math.imul(w,Z)|0,n=n+Math.imul(w,Y)|0,i=i+Math.imul(m,X)|0,a=(a=a+Math.imul(m,ee)|0)+Math.imul(f,X)|0,n=n+Math.imul(f,ee)|0,i=i+Math.imul(d,er)|0;var ek=(u+i|0)+((8191&(a=(a=a+Math.imul(d,ei)|0)+Math.imul(p,er)|0))<<13)|0;u=((n=n+Math.imul(p,ei)|0)+(a>>>13)|0)+(ek>>>26)|0,ek&=0x3ffffff,i=Math.imul(R,M),a=(a=Math.imul(R,F))+Math.imul(T,M)|0,n=Math.imul(T,F),i=i+Math.imul(A,V)|0,a=(a=a+Math.imul(A,G)|0)+Math.imul(_,V)|0,n=n+Math.imul(_,G)|0,i=i+Math.imul(E,W)|0,a=(a=a+Math.imul(E,J)|0)+Math.imul(I,W)|0,n=n+Math.imul(I,J)|0,i=i+Math.imul(v,Z)|0,a=(a=a+Math.imul(v,Y)|0)+Math.imul(k,Z)|0,n=n+Math.imul(k,Y)|0,i=i+Math.imul(y,X)|0,a=(a=a+Math.imul(y,ee)|0)+Math.imul(w,X)|0,n=n+Math.imul(w,ee)|0,i=i+Math.imul(m,er)|0,a=(a=a+Math.imul(m,ei)|0)+Math.imul(f,er)|0,n=n+Math.imul(f,ei)|0,i=i+Math.imul(d,en)|0;var eS=(u+i|0)+((8191&(a=(a=a+Math.imul(d,es)|0)+Math.imul(p,en)|0))<<13)|0;u=((n=n+Math.imul(p,es)|0)+(a>>>13)|0)+(eS>>>26)|0,eS&=0x3ffffff,i=Math.imul(N,M),a=(a=Math.imul(N,F))+Math.imul(O,M)|0,n=Math.imul(O,F),i=i+Math.imul(R,V)|0,a=(a=a+Math.imul(R,G)|0)+Math.imul(T,V)|0,n=n+Math.imul(T,G)|0,i=i+Math.imul(A,W)|0,a=(a=a+Math.imul(A,J)|0)+Math.imul(_,W)|0,n=n+Math.imul(_,J)|0,i=i+Math.imul(E,Z)|0,a=(a=a+Math.imul(E,Y)|0)+Math.imul(I,Z)|0,n=n+Math.imul(I,Y)|0,i=i+Math.imul(v,X)|0,a=(a=a+Math.imul(v,ee)|0)+Math.imul(k,X)|0,n=n+Math.imul(k,ee)|0,i=i+Math.imul(y,er)|0,a=(a=a+Math.imul(y,ei)|0)+Math.imul(w,er)|0,n=n+Math.imul(w,ei)|0,i=i+Math.imul(m,en)|0,a=(a=a+Math.imul(m,es)|0)+Math.imul(f,en)|0,n=n+Math.imul(f,es)|0,i=i+Math.imul(d,el)|0;var eE=(u+i|0)+((8191&(a=(a=a+Math.imul(d,eu)|0)+Math.imul(p,el)|0))<<13)|0;u=((n=n+Math.imul(p,eu)|0)+(a>>>13)|0)+(eE>>>26)|0,eE&=0x3ffffff,i=Math.imul($,M),a=(a=Math.imul($,F))+Math.imul(U,M)|0,n=Math.imul(U,F),i=i+Math.imul(N,V)|0,a=(a=a+Math.imul(N,G)|0)+Math.imul(O,V)|0,n=n+Math.imul(O,G)|0,i=i+Math.imul(R,W)|0,a=(a=a+Math.imul(R,J)|0)+Math.imul(T,W)|0,n=n+Math.imul(T,J)|0,i=i+Math.imul(A,Z)|0,a=(a=a+Math.imul(A,Y)|0)+Math.imul(_,Z)|0,n=n+Math.imul(_,Y)|0,i=i+Math.imul(E,X)|0,a=(a=a+Math.imul(E,ee)|0)+Math.imul(I,X)|0,n=n+Math.imul(I,ee)|0,i=i+Math.imul(v,er)|0,a=(a=a+Math.imul(v,ei)|0)+Math.imul(k,er)|0,n=n+Math.imul(k,ei)|0,i=i+Math.imul(y,en)|0,a=(a=a+Math.imul(y,es)|0)+Math.imul(w,en)|0,n=n+Math.imul(w,es)|0,i=i+Math.imul(m,el)|0,a=(a=a+Math.imul(m,eu)|0)+Math.imul(f,el)|0,n=n+Math.imul(f,eu)|0,i=i+Math.imul(d,ed)|0;var eI=(u+i|0)+((8191&(a=(a=a+Math.imul(d,ep)|0)+Math.imul(p,ed)|0))<<13)|0;u=((n=n+Math.imul(p,ep)|0)+(a>>>13)|0)+(eI>>>26)|0,eI&=0x3ffffff,i=Math.imul(j,M),a=(a=Math.imul(j,F))+Math.imul(L,M)|0,n=Math.imul(L,F),i=i+Math.imul($,V)|0,a=(a=a+Math.imul($,G)|0)+Math.imul(U,V)|0,n=n+Math.imul(U,G)|0,i=i+Math.imul(N,W)|0,a=(a=a+Math.imul(N,J)|0)+Math.imul(O,W)|0,n=n+Math.imul(O,J)|0,i=i+Math.imul(R,Z)|0,a=(a=a+Math.imul(R,Y)|0)+Math.imul(T,Z)|0,n=n+Math.imul(T,Y)|0,i=i+Math.imul(A,X)|0,a=(a=a+Math.imul(A,ee)|0)+Math.imul(_,X)|0,n=n+Math.imul(_,ee)|0,i=i+Math.imul(E,er)|0,a=(a=a+Math.imul(E,ei)|0)+Math.imul(I,er)|0,n=n+Math.imul(I,ei)|0,i=i+Math.imul(v,en)|0,a=(a=a+Math.imul(v,es)|0)+Math.imul(k,en)|0,n=n+Math.imul(k,es)|0,i=i+Math.imul(y,el)|0,a=(a=a+Math.imul(y,eu)|0)+Math.imul(w,el)|0,n=n+Math.imul(w,eu)|0,i=i+Math.imul(m,ed)|0,a=(a=a+Math.imul(m,ep)|0)+Math.imul(f,ed)|0,n=n+Math.imul(f,ep)|0,i=i+Math.imul(d,em)|0;var ex=(u+i|0)+((8191&(a=(a=a+Math.imul(d,ef)|0)+Math.imul(p,em)|0))<<13)|0;u=((n=n+Math.imul(p,ef)|0)+(a>>>13)|0)+(ex>>>26)|0,ex&=0x3ffffff,i=Math.imul(j,V),a=(a=Math.imul(j,G))+Math.imul(L,V)|0,n=Math.imul(L,G),i=i+Math.imul($,W)|0,a=(a=a+Math.imul($,J)|0)+Math.imul(U,W)|0,n=n+Math.imul(U,J)|0,i=i+Math.imul(N,Z)|0,a=(a=a+Math.imul(N,Y)|0)+Math.imul(O,Z)|0,n=n+Math.imul(O,Y)|0,i=i+Math.imul(R,X)|0,a=(a=a+Math.imul(R,ee)|0)+Math.imul(T,X)|0,n=n+Math.imul(T,ee)|0,i=i+Math.imul(A,er)|0,a=(a=a+Math.imul(A,ei)|0)+Math.imul(_,er)|0,n=n+Math.imul(_,ei)|0,i=i+Math.imul(E,en)|0,a=(a=a+Math.imul(E,es)|0)+Math.imul(I,en)|0,n=n+Math.imul(I,es)|0,i=i+Math.imul(v,el)|0,a=(a=a+Math.imul(v,eu)|0)+Math.imul(k,el)|0,n=n+Math.imul(k,eu)|0,i=i+Math.imul(y,ed)|0,a=(a=a+Math.imul(y,ep)|0)+Math.imul(w,ed)|0,n=n+Math.imul(w,ep)|0,i=i+Math.imul(m,em)|0;var eA=(u+i|0)+((8191&(a=(a=a+Math.imul(m,ef)|0)+Math.imul(f,em)|0))<<13)|0;u=((n=n+Math.imul(f,ef)|0)+(a>>>13)|0)+(eA>>>26)|0,eA&=0x3ffffff,i=Math.imul(j,W),a=(a=Math.imul(j,J))+Math.imul(L,W)|0,n=Math.imul(L,J),i=i+Math.imul($,Z)|0,a=(a=a+Math.imul($,Y)|0)+Math.imul(U,Z)|0,n=n+Math.imul(U,Y)|0,i=i+Math.imul(N,X)|0,a=(a=a+Math.imul(N,ee)|0)+Math.imul(O,X)|0,n=n+Math.imul(O,ee)|0,i=i+Math.imul(R,er)|0,a=(a=a+Math.imul(R,ei)|0)+Math.imul(T,er)|0,n=n+Math.imul(T,ei)|0,i=i+Math.imul(A,en)|0,a=(a=a+Math.imul(A,es)|0)+Math.imul(_,en)|0,n=n+Math.imul(_,es)|0,i=i+Math.imul(E,el)|0,a=(a=a+Math.imul(E,eu)|0)+Math.imul(I,el)|0,n=n+Math.imul(I,eu)|0,i=i+Math.imul(v,ed)|0,a=(a=a+Math.imul(v,ep)|0)+Math.imul(k,ed)|0,n=n+Math.imul(k,ep)|0,i=i+Math.imul(y,em)|0;var e_=(u+i|0)+((8191&(a=(a=a+Math.imul(y,ef)|0)+Math.imul(w,em)|0))<<13)|0;u=((n=n+Math.imul(w,ef)|0)+(a>>>13)|0)+(e_>>>26)|0,e_&=0x3ffffff,i=Math.imul(j,Z),a=(a=Math.imul(j,Y))+Math.imul(L,Z)|0,n=Math.imul(L,Y),i=i+Math.imul($,X)|0,a=(a=a+Math.imul($,ee)|0)+Math.imul(U,X)|0,n=n+Math.imul(U,ee)|0,i=i+Math.imul(N,er)|0,a=(a=a+Math.imul(N,ei)|0)+Math.imul(O,er)|0,n=n+Math.imul(O,ei)|0,i=i+Math.imul(R,en)|0,a=(a=a+Math.imul(R,es)|0)+Math.imul(T,en)|0,n=n+Math.imul(T,es)|0,i=i+Math.imul(A,el)|0,a=(a=a+Math.imul(A,eu)|0)+Math.imul(_,el)|0,n=n+Math.imul(_,eu)|0,i=i+Math.imul(E,ed)|0,a=(a=a+Math.imul(E,ep)|0)+Math.imul(I,ed)|0,n=n+Math.imul(I,ep)|0,i=i+Math.imul(v,em)|0;var eC=(u+i|0)+((8191&(a=(a=a+Math.imul(v,ef)|0)+Math.imul(k,em)|0))<<13)|0;u=((n=n+Math.imul(k,ef)|0)+(a>>>13)|0)+(eC>>>26)|0,eC&=0x3ffffff,i=Math.imul(j,X),a=(a=Math.imul(j,ee))+Math.imul(L,X)|0,n=Math.imul(L,ee),i=i+Math.imul($,er)|0,a=(a=a+Math.imul($,ei)|0)+Math.imul(U,er)|0,n=n+Math.imul(U,ei)|0,i=i+Math.imul(N,en)|0,a=(a=a+Math.imul(N,es)|0)+Math.imul(O,en)|0,n=n+Math.imul(O,es)|0,i=i+Math.imul(R,el)|0,a=(a=a+Math.imul(R,eu)|0)+Math.imul(T,el)|0,n=n+Math.imul(T,eu)|0,i=i+Math.imul(A,ed)|0,a=(a=a+Math.imul(A,ep)|0)+Math.imul(_,ed)|0,n=n+Math.imul(_,ep)|0,i=i+Math.imul(E,em)|0;var eR=(u+i|0)+((8191&(a=(a=a+Math.imul(E,ef)|0)+Math.imul(I,em)|0))<<13)|0;u=((n=n+Math.imul(I,ef)|0)+(a>>>13)|0)+(eR>>>26)|0,eR&=0x3ffffff,i=Math.imul(j,er),a=(a=Math.imul(j,ei))+Math.imul(L,er)|0,n=Math.imul(L,ei),i=i+Math.imul($,en)|0,a=(a=a+Math.imul($,es)|0)+Math.imul(U,en)|0,n=n+Math.imul(U,es)|0,i=i+Math.imul(N,el)|0,a=(a=a+Math.imul(N,eu)|0)+Math.imul(O,el)|0,n=n+Math.imul(O,eu)|0,i=i+Math.imul(R,ed)|0,a=(a=a+Math.imul(R,ep)|0)+Math.imul(T,ed)|0,n=n+Math.imul(T,ep)|0,i=i+Math.imul(A,em)|0;var eT=(u+i|0)+((8191&(a=(a=a+Math.imul(A,ef)|0)+Math.imul(_,em)|0))<<13)|0;u=((n=n+Math.imul(_,ef)|0)+(a>>>13)|0)+(eT>>>26)|0,eT&=0x3ffffff,i=Math.imul(j,en),a=(a=Math.imul(j,es))+Math.imul(L,en)|0,n=Math.imul(L,es),i=i+Math.imul($,el)|0,a=(a=a+Math.imul($,eu)|0)+Math.imul(U,el)|0,n=n+Math.imul(U,eu)|0,i=i+Math.imul(N,ed)|0,a=(a=a+Math.imul(N,ep)|0)+Math.imul(O,ed)|0,n=n+Math.imul(O,ep)|0,i=i+Math.imul(R,em)|0;var eD=(u+i|0)+((8191&(a=(a=a+Math.imul(R,ef)|0)+Math.imul(T,em)|0))<<13)|0;u=((n=n+Math.imul(T,ef)|0)+(a>>>13)|0)+(eD>>>26)|0,eD&=0x3ffffff,i=Math.imul(j,el),a=(a=Math.imul(j,eu))+Math.imul(L,el)|0,n=Math.imul(L,eu),i=i+Math.imul($,ed)|0,a=(a=a+Math.imul($,ep)|0)+Math.imul(U,ed)|0,n=n+Math.imul(U,ep)|0,i=i+Math.imul(N,em)|0;var eN=(u+i|0)+((8191&(a=(a=a+Math.imul(N,ef)|0)+Math.imul(O,em)|0))<<13)|0;u=((n=n+Math.imul(O,ef)|0)+(a>>>13)|0)+(eN>>>26)|0,eN&=0x3ffffff,i=Math.imul(j,ed),a=(a=Math.imul(j,ep))+Math.imul(L,ed)|0,n=Math.imul(L,ep),i=i+Math.imul($,em)|0;var eO=(u+i|0)+((8191&(a=(a=a+Math.imul($,ef)|0)+Math.imul(U,em)|0))<<13)|0;u=((n=n+Math.imul(U,ef)|0)+(a>>>13)|0)+(eO>>>26)|0,eO&=0x3ffffff,i=Math.imul(j,em);var eP=(u+i|0)+((8191&(a=(a=Math.imul(j,ef))+Math.imul(L,em)|0))<<13)|0;return u=((n=Math.imul(L,ef))+(a>>>13)|0)+(eP>>>26)|0,eP&=0x3ffffff,l[0]=eg,l[1]=ey,l[2]=ew,l[3]=eb,l[4]=ev,l[5]=ek,l[6]=eS,l[7]=eE,l[8]=eI,l[9]=ex,l[10]=eA,l[11]=e_,l[12]=eC,l[13]=eR,l[14]=eT,l[15]=eD,l[16]=eN,l[17]=eO,l[18]=eP,0!==u&&(l[19]=u,r.length++),r};function f(e,t,r){return new g().mulp(e,t,r)}function g(e,t){this.x=e,this.y=t}Math.imul||(m=h),n.prototype.mulTo=function(e,t){var r=this.length+e.length;return 10===this.length&&10===e.length?m(this,e,t):r<63?h(this,e,t):r<1024?function(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var i=0,a=0,n=0;n<r.length-1;n++){var s=a;a=0;for(var o=0x3ffffff&i,l=Math.min(n,t.length-1),u=Math.max(0,n-e.length+1);u<=l;u++){var c=n-u,d=(0|e.words[c])*(0|t.words[u]),p=0x3ffffff&d;s=s+(d/0x4000000|0)|0,o=0x3ffffff&(p=p+o|0),a+=(s=s+(p>>>26)|0)>>>26,s&=0x3ffffff}r.words[n]=o,i=s,s=a}return 0!==i?r.words[n]=i:r.length--,r.strip()}(this,e,t):f(this,e,t)},g.prototype.makeRBT=function(e){for(var t=Array(e),r=n.prototype._countBits(e)-1,i=0;i<e;i++)t[i]=this.revBin(i,r,e);return t},g.prototype.revBin=function(e,t,r){if(0===e||e===r-1)return e;for(var i=0,a=0;a<t;a++)i|=(1&e)<<t-a-1,e>>=1;return i},g.prototype.permute=function(e,t,r,i,a,n){for(var s=0;s<n;s++)i[s]=t[e[s]],a[s]=r[e[s]]},g.prototype.transform=function(e,t,r,i,a,n){this.permute(n,e,t,r,i,a);for(var s=1;s<a;s<<=1)for(var o=s<<1,l=Math.cos(2*Math.PI/o),u=Math.sin(2*Math.PI/o),c=0;c<a;c+=o)for(var d=l,p=u,h=0;h<s;h++){var m=r[c+h],f=i[c+h],g=r[c+h+s],y=i[c+h+s],w=d*g-p*y;y=d*y+p*g,g=w,r[c+h]=m+g,i[c+h]=f+y,r[c+h+s]=m-g,i[c+h+s]=f-y,h!==o&&(w=l*d-u*p,p=l*p+u*d,d=w)}},g.prototype.guessLen13b=function(e,t){var r=1|Math.max(t,e),i=1&r,a=0;for(r=r/2|0;r;r>>>=1)a++;return 1<<a+1+i},g.prototype.conjugate=function(e,t,r){if(!(r<=1))for(var i=0;i<r/2;i++){var a=e[i];e[i]=e[r-i-1],e[r-i-1]=a,a=t[i],t[i]=-t[r-i-1],t[r-i-1]=-a}},g.prototype.normalize13b=function(e,t){for(var r=0,i=0;i<t/2;i++){var a=8192*Math.round(e[2*i+1]/t)+Math.round(e[2*i]/t)+r;e[i]=0x3ffffff&a,r=a<0x4000000?0:a/0x4000000|0}return e},g.prototype.convert13b=function(e,t,r,a){for(var n=0,s=0;s<t;s++)n+=0|e[s],r[2*s]=8191&n,n>>>=13,r[2*s+1]=8191&n,n>>>=13;for(s=2*t;s<a;++s)r[s]=0;i(0===n),i((-8192&n)==0)},g.prototype.stub=function(e){for(var t=Array(e),r=0;r<e;r++)t[r]=0;return t},g.prototype.mulp=function(e,t,r){var i=2*this.guessLen13b(e.length,t.length),a=this.makeRBT(i),n=this.stub(i),s=Array(i),o=Array(i),l=Array(i),u=Array(i),c=Array(i),d=Array(i),p=r.words;p.length=i,this.convert13b(e.words,e.length,s,i),this.convert13b(t.words,t.length,u,i),this.transform(s,n,o,l,i,a),this.transform(u,n,c,d,i,a);for(var h=0;h<i;h++){var m=o[h]*c[h]-l[h]*d[h];l[h]=o[h]*d[h]+l[h]*c[h],o[h]=m}return this.conjugate(o,l,i),this.transform(o,l,p,n,i,a),this.conjugate(p,n,i),this.normalize13b(p,i),r.negative=e.negative^t.negative,r.length=e.length+t.length,r.strip()},n.prototype.mul=function(e){var t=new n(null);return t.words=Array(this.length+e.length),this.mulTo(e,t)},n.prototype.mulf=function(e){var t=new n(null);return t.words=Array(this.length+e.length),f(this,e,t)},n.prototype.imul=function(e){return this.clone().mulTo(e,this)},n.prototype.imuln=function(e){i("number"==typeof e),i(e<0x4000000);for(var t=0,r=0;r<this.length;r++){var a=(0|this.words[r])*e,n=(0x3ffffff&a)+(0x3ffffff&t);t>>=26,t+=(a/0x4000000|0)+(n>>>26),this.words[r]=0x3ffffff&n}return 0!==t&&(this.words[r]=t,this.length++),0===e&&(this.length=1,this._normSign()),this},n.prototype.muln=function(e){return this.clone().imuln(e)},n.prototype.sqr=function(){return this.mul(this)},n.prototype.isqr=function(){return this.imul(this.clone())},n.prototype.pow=function(e){var t=function(e){for(var t=Array(e.bitLength()),r=0;r<t.length;r++){var i=r/26|0,a=r%26;t[r]=(e.words[i]&1<<a)>>>a}return t}(e);if(0===t.length)return new n(1);for(var r=this,i=0;i<t.length&&0===t[i];i++,r=r.sqr());if(++i<t.length)for(var a=r.sqr();i<t.length;i++,a=a.sqr())0!==t[i]&&(r=r.mul(a));return r},n.prototype.iushln=function(e){i("number"==typeof e&&e>=0);var t,r=e%26,a=(e-r)/26,n=0x3ffffff>>>26-r<<26-r;if(0!==r){var s=0;for(t=0;t<this.length;t++){var o=this.words[t]&n,l=(0|this.words[t])-o<<r;this.words[t]=l|s,s=o>>>26-r}s&&(this.words[t]=s,this.length++)}if(0!==a){for(t=this.length-1;t>=0;t--)this.words[t+a]=this.words[t];for(t=0;t<a;t++)this.words[t]=0;this.length+=a}return this.strip()},n.prototype.ishln=function(e){return i(0===this.negative),this.iushln(e)},n.prototype.iushrn=function(e,t,r){i("number"==typeof e&&e>=0);var a=t?(t-t%26)/26:0,n=e%26,s=Math.min((e-n)/26,this.length),o=0x3ffffff^0x3ffffff>>>n<<n;if(a-=s,a=Math.max(0,a),r){for(var l=0;l<s;l++)r.words[l]=this.words[l];r.length=s}if(0===s);else if(this.length>s)for(this.length-=s,l=0;l<this.length;l++)this.words[l]=this.words[l+s];else this.words[0]=0,this.length=1;var u=0;for(l=this.length-1;l>=0&&(0!==u||l>=a);l--){var c=0|this.words[l];this.words[l]=u<<26-n|c>>>n,u=c&o}return r&&0!==u&&(r.words[r.length++]=u),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},n.prototype.ishrn=function(e,t,r){return i(0===this.negative),this.iushrn(e,t,r)},n.prototype.shln=function(e){return this.clone().ishln(e)},n.prototype.ushln=function(e){return this.clone().iushln(e)},n.prototype.shrn=function(e){return this.clone().ishrn(e)},n.prototype.ushrn=function(e){return this.clone().iushrn(e)},n.prototype.testn=function(e){i("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26;return!(this.length<=r)&&!!(this.words[r]&1<<t)},n.prototype.imaskn=function(e){i("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26;return(i(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)?this:(0!==t&&r++,this.length=Math.min(r,this.length),0!==t&&(this.words[this.length-1]&=0x3ffffff^0x3ffffff>>>t<<t),0===this.length&&(this.words[0]=0,this.length=1),this.strip())},n.prototype.maskn=function(e){return this.clone().imaskn(e)},n.prototype.iaddn=function(e){return(i("number"==typeof e),i(e<0x4000000),e<0)?this.isubn(-e):0!==this.negative?(1===this.length&&(0|this.words[0])<e?(this.words[0]=e-(0|this.words[0]),this.negative=0):(this.negative=0,this.isubn(e),this.negative=1),this):this._iaddn(e)},n.prototype._iaddn=function(e){this.words[0]+=e;for(var t=0;t<this.length&&this.words[t]>=0x4000000;t++)this.words[t]-=0x4000000,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},n.prototype.isubn=function(e){if(i("number"==typeof e),i(e<0x4000000),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t<this.length&&this.words[t]<0;t++)this.words[t]+=0x4000000,this.words[t+1]-=1;return this.strip()},n.prototype.addn=function(e){return this.clone().iaddn(e)},n.prototype.subn=function(e){return this.clone().isubn(e)},n.prototype.iabs=function(){return this.negative=0,this},n.prototype.abs=function(){return this.clone().iabs()},n.prototype._ishlnsubmul=function(e,t,r){var a,n,s=e.length+r;this._expand(s);var o=0;for(a=0;a<e.length;a++){n=(0|this.words[a+r])+o;var l=(0|e.words[a])*t;n-=0x3ffffff&l,o=(n>>26)-(l/0x4000000|0),this.words[a+r]=0x3ffffff&n}for(;a<this.length-r;a++)o=(n=(0|this.words[a+r])+o)>>26,this.words[a+r]=0x3ffffff&n;if(0===o)return this.strip();for(i(-1===o),o=0,a=0;a<this.length;a++)o=(n=-(0|this.words[a])+o)>>26,this.words[a]=0x3ffffff&n;return this.negative=1,this.strip()},n.prototype._wordDiv=function(e,t){var r,i=this.length-e.length,a=this.clone(),s=e,o=0|s.words[s.length-1];0!=(i=26-this._countBits(o))&&(s=s.ushln(i),a.iushln(i),o=0|s.words[s.length-1]);var l=a.length-s.length;if("mod"!==t){(r=new n(null)).length=l+1,r.words=Array(r.length);for(var u=0;u<r.length;u++)r.words[u]=0}var c=a.clone()._ishlnsubmul(s,1,l);0===c.negative&&(a=c,r&&(r.words[l]=1));for(var d=l-1;d>=0;d--){var p=(0|a.words[s.length+d])*0x4000000+(0|a.words[s.length+d-1]);for(p=Math.min(p/o|0,0x3ffffff),a._ishlnsubmul(s,p,d);0!==a.negative;)p--,a.negative=0,a._ishlnsubmul(s,1,d),a.isZero()||(a.negative^=1);r&&(r.words[d]=p)}return r&&r.strip(),a.strip(),"div"!==t&&0!==i&&a.iushrn(i),{div:r||null,mod:a}},n.prototype.divmod=function(e,t,r){var a,s,o;return(i(!e.isZero()),this.isZero())?{div:new n(0),mod:new n(0)}:0!==this.negative&&0===e.negative?(o=this.neg().divmod(e,t),"mod"!==t&&(a=o.div.neg()),"div"!==t&&(s=o.mod.neg(),r&&0!==s.negative&&s.iadd(e)),{div:a,mod:s}):0===this.negative&&0!==e.negative?(o=this.divmod(e.neg(),t),"mod"!==t&&(a=o.div.neg()),{div:a,mod:o.mod}):(this.negative&e.negative)!=0?(o=this.neg().divmod(e.neg(),t),"div"!==t&&(s=o.mod.neg(),r&&0!==s.negative&&s.isub(e)),{div:o.div,mod:s}):e.length>this.length||0>this.cmp(e)?{div:new n(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new n(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new n(this.modn(e.words[0]))}:this._wordDiv(e,t)},n.prototype.div=function(e){return this.divmod(e,"div",!1).div},n.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},n.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},n.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=t.mod.abs(),i=e.abs().iushrn(1),a=1&e.words[0],s=r.cmp(i);if(s<0||1===a&&0===s)return t.div;var o=new n(1);return o.negative=this.negative^e.negative,t.div.iadd(o)},n.prototype.modn=function(e){i(e<=0x3ffffff);for(var t=0x4000000%e,r=0,a=this.length-1;a>=0;a--)r=(t*r+(0|this.words[a]))%e;return r},n.prototype.idivn=function(e){i(e<=0x3ffffff);for(var t=0,r=this.length-1;r>=0;r--){var a=(0|this.words[r])+0x4000000*t;this.words[r]=a/e|0,t=a%e}return this.strip()},n.prototype.divn=function(e){return this.clone().idivn(e)},n.prototype.egcd=function(e){i(0===e.negative),i(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var a=new n(1),s=new n(0),o=new n(0),l=new n(1),u=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++u;for(var c=r.clone(),d=t.clone();!t.isZero();){for(var p=0,h=1;(t.words[0]&h)==0&&p<26;++p,h<<=1);if(p>0)for(t.iushrn(p);p-- >0;)(a.isOdd()||s.isOdd())&&(a.iadd(c),s.isub(d)),a.iushrn(1),s.iushrn(1);for(var m=0,f=1;(r.words[0]&f)==0&&m<26;++m,f<<=1);if(m>0)for(r.iushrn(m);m-- >0;)(o.isOdd()||l.isOdd())&&(o.iadd(c),l.isub(d)),o.iushrn(1),l.iushrn(1);t.cmp(r)>=0?(t.isub(r),a.isub(o),s.isub(l)):(r.isub(t),o.isub(a),l.isub(s))}return{a:o,b:l,gcd:r.iushln(u)}},n.prototype._invmp=function(e){i(0===e.negative),i(!e.isZero());var t,r=this,a=e.clone();r=0!==r.negative?r.umod(e):r.clone();for(var s=new n(1),o=new n(0),l=a.clone();r.cmpn(1)>0&&a.cmpn(1)>0;){for(var u=0,c=1;(r.words[0]&c)==0&&u<26;++u,c<<=1);if(u>0)for(r.iushrn(u);u-- >0;)s.isOdd()&&s.iadd(l),s.iushrn(1);for(var d=0,p=1;(a.words[0]&p)==0&&d<26;++d,p<<=1);if(d>0)for(a.iushrn(d);d-- >0;)o.isOdd()&&o.iadd(l),o.iushrn(1);r.cmp(a)>=0?(r.isub(a),s.isub(o)):(a.isub(r),o.isub(s))}return 0>(t=0===r.cmpn(1)?s:o).cmpn(0)&&t.iadd(e),t},n.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var i=0;t.isEven()&&r.isEven();i++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var a=t.cmp(r);if(a<0){var n=t;t=r,r=n}else if(0===a||0===r.cmpn(1))break;t.isub(r)}return r.iushln(i)},n.prototype.invm=function(e){return this.egcd(e).a.umod(e)},n.prototype.isEven=function(){return(1&this.words[0])==0},n.prototype.isOdd=function(){return(1&this.words[0])==1},n.prototype.andln=function(e){return this.words[0]&e},n.prototype.bincn=function(e){i("number"==typeof e);var t=e%26,r=(e-t)/26,a=1<<t;if(this.length<=r)return this._expand(r+1),this.words[r]|=a,this;for(var n=a,s=r;0!==n&&s<this.length;s++){var o=0|this.words[s];o+=n,n=o>>>26,o&=0x3ffffff,this.words[s]=o}return 0!==n&&(this.words[s]=n,this.length++),this},n.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},n.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return -1;if(0===this.negative&&r)return 1;if(this.strip(),this.length>1)t=1;else{r&&(e=-e),i(e<=0x3ffffff,"Number is too big");var a=0|this.words[0];t=a===e?0:a<e?-1:1}return 0!==this.negative?0|-t:t},n.prototype.cmp=function(e){if(0!==this.negative&&0===e.negative)return -1;if(0===this.negative&&0!==e.negative)return 1;var t=this.ucmp(e);return 0!==this.negative?0|-t:t},n.prototype.ucmp=function(e){if(this.length>e.length)return 1;if(this.length<e.length)return -1;for(var t=0,r=this.length-1;r>=0;r--){var i=0|this.words[r],a=0|e.words[r];if(i!==a){i<a?t=-1:i>a&&(t=1);break}}return t},n.prototype.gtn=function(e){return 1===this.cmpn(e)},n.prototype.gt=function(e){return 1===this.cmp(e)},n.prototype.gten=function(e){return this.cmpn(e)>=0},n.prototype.gte=function(e){return this.cmp(e)>=0},n.prototype.ltn=function(e){return -1===this.cmpn(e)},n.prototype.lt=function(e){return -1===this.cmp(e)},n.prototype.lten=function(e){return 0>=this.cmpn(e)},n.prototype.lte=function(e){return 0>=this.cmp(e)},n.prototype.eqn=function(e){return 0===this.cmpn(e)},n.prototype.eq=function(e){return 0===this.cmp(e)},n.red=function(e){return new E(e)},n.prototype.toRed=function(e){return i(!this.red,"Already a number in reduction context"),i(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},n.prototype.fromRed=function(){return i(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},n.prototype._forceRed=function(e){return this.red=e,this},n.prototype.forceRed=function(e){return i(!this.red,"Already a number in reduction context"),this._forceRed(e)},n.prototype.redAdd=function(e){return i(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},n.prototype.redIAdd=function(e){return i(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},n.prototype.redSub=function(e){return i(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},n.prototype.redISub=function(e){return i(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},n.prototype.redShl=function(e){return i(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},n.prototype.redMul=function(e){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},n.prototype.redIMul=function(e){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},n.prototype.redSqr=function(){return i(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},n.prototype.redISqr=function(){return i(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},n.prototype.redSqrt=function(){return i(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},n.prototype.redInvm=function(){return i(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},n.prototype.redNeg=function(){return i(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},n.prototype.redPow=function(e){return i(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var y={k256:null,p224:null,p192:null,p25519:null};function w(e,t){this.name=e,this.p=new n(t,16),this.n=this.p.bitLength(),this.k=new n(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function b(){w.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function v(){w.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function k(){w.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function S(){w.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function E(e){if("string"==typeof e){var t=n._prime(e);this.m=t.p,this.prime=t}else i(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function I(e){E.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new n(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}w.prototype._tmp=function(){var e=new n(null);return e.words=Array(Math.ceil(this.n/13)),e},w.prototype.ireduce=function(e){var t,r=e;do this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength();while(t>this.n)var i=t<this.n?-1:r.ucmp(this.p);return 0===i?(r.words[0]=0,r.length=1):i>0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},w.prototype.split=function(e,t){e.iushrn(this.n,0,t)},w.prototype.imulK=function(e){return e.imul(this.k)},a(b,w),b.prototype.split=function(e,t){for(var r=Math.min(e.length,9),i=0;i<r;i++)t.words[i]=e.words[i];if(t.length=r,e.length<=9){e.words[0]=0,e.length=1;return}var a=e.words[9];for(i=10,t.words[t.length++]=4194303&a;i<e.length;i++){var n=0|e.words[i];e.words[i-10]=(4194303&n)<<4|a>>>22,a=n}a>>>=22,e.words[i-10]=a,0===a&&e.length>10?e.length-=10:e.length-=9},b.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r<e.length;r++){var i=0|e.words[r];t+=977*i,e.words[r]=0x3ffffff&t,t=64*i+(t/0x4000000|0)}return 0===e.words[e.length-1]&&(e.length--,0===e.words[e.length-1]&&e.length--),e},a(v,w),a(k,w),a(S,w),S.prototype.imulK=function(e){for(var t=0,r=0;r<e.length;r++){var i=(0|e.words[r])*19+t,a=0x3ffffff&i;i>>>=26,e.words[r]=a,t=i}return 0!==t&&(e.words[e.length++]=t),e},n._prime=function(e){var t;if(y[e])return y[e];if("k256"===e)t=new b;else if("p224"===e)t=new v;else if("p192"===e)t=new k;else if("p25519"===e)t=new S;else throw Error("Unknown prime "+e);return y[e]=t,t},E.prototype._verify1=function(e){i(0===e.negative,"red works only with positives"),i(e.red,"red works only with red numbers")},E.prototype._verify2=function(e,t){i((e.negative|t.negative)==0,"red works only with positives"),i(e.red&&e.red===t.red,"red works only with red numbers")},E.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},E.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},E.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},E.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},E.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return 0>r.cmpn(0)&&r.iadd(this.m),r._forceRed(this)},E.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return 0>r.cmpn(0)&&r.iadd(this.m),r},E.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},E.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},E.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},E.prototype.isqr=function(e){return this.imul(e,e.clone())},E.prototype.sqr=function(e){return this.mul(e,e)},E.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(i(t%2==1),3===t){var r=this.m.add(new n(1)).iushrn(2);return this.pow(e,r)}for(var a=this.m.subn(1),s=0;!a.isZero()&&0===a.andln(1);)s++,a.iushrn(1);i(!a.isZero());var o=new n(1).toRed(this),l=o.redNeg(),u=this.m.subn(1).iushrn(1),c=this.m.bitLength();for(c=new n(2*c*c).toRed(this);0!==this.pow(c,u).cmp(l);)c.redIAdd(l);for(var d=this.pow(c,a),p=this.pow(e,a.addn(1).iushrn(1)),h=this.pow(e,a),m=s;0!==h.cmp(o);){for(var f=h,g=0;0!==f.cmp(o);g++)f=f.redSqr();i(g<m);var y=this.pow(d,new n(1).iushln(m-g-1));p=p.redMul(y),d=y.redSqr(),h=h.redMul(d),m=g}return p},E.prototype.invm=function(e){var t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)},E.prototype.pow=function(e,t){if(t.isZero())return new n(1).toRed(this);if(0===t.cmpn(1))return e.clone();var r=Array(16);r[0]=new n(1).toRed(this),r[1]=e;for(var i=2;i<r.length;i++)r[i]=this.mul(r[i-1],e);var a=r[0],s=0,o=0,l=t.bitLength()%26;for(0===l&&(l=26),i=t.length-1;i>=0;i--){for(var u=t.words[i],c=l-1;c>=0;c--){var d=u>>c&1;if(a!==r[0]&&(a=this.sqr(a)),0===d&&0===s){o=0;continue}s<<=1,s|=d,(4==++o||0===i&&0===c)&&(a=this.mul(a,r[s]),o=0,s=0)}l=26}return a},E.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},E.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},n.mont=function(e){return new I(e)},a(I,E),I.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},I.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},I.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=r.isub(i).iushrn(this.shift),n=a;return a.cmp(this.m)>=0?n=a.isub(this.m):0>a.cmpn(0)&&(n=a.iadd(this.m)),n._forceRed(this)},I.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new n(0)._forceRed(this);var r=e.mul(t),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=r.isub(i).iushrn(this.shift),s=a;return a.cmp(this.m)>=0?s=a.isub(this.m):0>a.cmpn(0)&&(s=a.iadd(this.m)),s._forceRed(this)},I.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(t,e.e)},832623,(e,t,r)=>{"use strict";var i,a=e.r(500874),n=a.Buffer,s={};for(i in a)a.hasOwnProperty(i)&&"SlowBuffer"!==i&&"Buffer"!==i&&(s[i]=a[i]);var o=s.Buffer={};for(i in n)n.hasOwnProperty(i)&&"allocUnsafe"!==i&&"allocUnsafeSlow"!==i&&(o[i]=n[i]);if(s.Buffer.prototype=n.prototype,o.from&&o.from!==Uint8Array.from||(o.from=function(e,t,r){if("number"==typeof e)throw TypeError('The "value" argument must not be of type number. Received type '+typeof e);if(e&&void 0===e.length)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);return n(e,t,r)}),o.alloc||(o.alloc=function(e,t,r){if("number"!=typeof e)throw TypeError('The "size" argument must be of type number. Received type '+typeof e);if(e<0||e>=2*0x40000000)throw RangeError('The value "'+e+'" is invalid for option "size"');var i=n(e);return t&&0!==t.length?"string"==typeof r?i.fill(t,r):i.fill(t):i.fill(0),i}),!s.kStringMaxLength)try{s.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch(e){}!s.constants&&(s.constants={MAX_LENGTH:s.kMaxLength},s.kStringMaxLength&&(s.constants.MAX_STRING_LENGTH=s.kStringMaxLength)),t.exports=s},857406,(e,t,r)=>{"use strict";let i=e.r(966397);function a(e){this._reporterState={obj:null,path:[],options:e||{},errors:[]}}function n(e,t){this.path=e,this.rethrow(t)}r.Reporter=a,a.prototype.isError=function(e){return e instanceof n},a.prototype.save=function(){let e=this._reporterState;return{obj:e.obj,pathLen:e.path.length}},a.prototype.restore=function(e){let t=this._reporterState;t.obj=e.obj,t.path=t.path.slice(0,e.pathLen)},a.prototype.enterKey=function(e){return this._reporterState.path.push(e)},a.prototype.exitKey=function(e){let t=this._reporterState;t.path=t.path.slice(0,e-1)},a.prototype.leaveKey=function(e,t,r){let i=this._reporterState;this.exitKey(e),null!==i.obj&&(i.obj[t]=r)},a.prototype.path=function(){return this._reporterState.path.join("/")},a.prototype.enterObject=function(){let e=this._reporterState,t=e.obj;return e.obj={},t},a.prototype.leaveObject=function(e){let t=this._reporterState,r=t.obj;return t.obj=e,r},a.prototype.error=function(e){let t,r=this._reporterState,i=e instanceof n;if(t=i?e:new n(r.path.map(function(e){return"["+JSON.stringify(e)+"]"}).join(""),e.message||e,e.stack),!r.options.partial)throw t;return i||r.errors.push(t),t},a.prototype.wrapResult=function(e){let t=this._reporterState;return t.options.partial?{result:this.isError(e)?null:e,errors:t.errors}:e},i(n,Error),n.prototype.rethrow=function(e){if(this.message=e+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,n),!this.stack)try{throw Error(this.message)}catch(e){this.stack=e.stack}return this}},644833,(e,t,r)=>{"use strict";let i=e.r(966397),a=e.r(857406).Reporter,n=e.r(832623).Buffer;function s(e,t){(a.call(this,t),n.isBuffer(e))?(this.base=e,this.offset=0,this.length=e.length):this.error("Input not Buffer")}function o(e,t){if(Array.isArray(e))this.length=0,this.value=e.map(function(e){return o.isEncoderBuffer(e)||(e=new o(e,t)),this.length+=e.length,e},this);else if("number"==typeof e){if(!(0<=e&&e<=255))return t.error("non-byte EncoderBuffer value");this.value=e,this.length=1}else if("string"==typeof e)this.value=e,this.length=n.byteLength(e);else{if(!n.isBuffer(e))return t.error("Unsupported type: "+typeof e);this.value=e,this.length=e.length}}i(s,a),r.DecoderBuffer=s,s.isDecoderBuffer=function(e){return e instanceof s||"object"==typeof e&&n.isBuffer(e.base)&&"DecoderBuffer"===e.constructor.name&&"number"==typeof e.offset&&"number"==typeof e.length&&"function"==typeof e.save&&"function"==typeof e.restore&&"function"==typeof e.isEmpty&&"function"==typeof e.readUInt8&&"function"==typeof e.skip&&"function"==typeof e.raw},s.prototype.save=function(){return{offset:this.offset,reporter:a.prototype.save.call(this)}},s.prototype.restore=function(e){let t=new s(this.base);return t.offset=e.offset,t.length=this.offset,this.offset=e.offset,a.prototype.restore.call(this,e.reporter),t},s.prototype.isEmpty=function(){return this.offset===this.length},s.prototype.readUInt8=function(e){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(e||"DecoderBuffer overrun")},s.prototype.skip=function(e,t){if(!(this.offset+e<=this.length))return this.error(t||"DecoderBuffer overrun");let r=new s(this.base);return r._reporterState=this._reporterState,r.offset=this.offset,r.length=this.offset+e,this.offset+=e,r},s.prototype.raw=function(e){return this.base.slice(e?e.offset:this.offset,this.length)},r.EncoderBuffer=o,o.isEncoderBuffer=function(e){return e instanceof o||"object"==typeof e&&"EncoderBuffer"===e.constructor.name&&"number"==typeof e.length&&"function"==typeof e.join},o.prototype.join=function(e,t){return e||(e=n.alloc(this.length)),t||(t=0),0===this.length||(Array.isArray(this.value)?this.value.forEach(function(r){r.join(e,t),t+=r.length}):("number"==typeof this.value?e[t]=this.value:"string"==typeof this.value?e.write(this.value,t):n.isBuffer(this.value)&&this.value.copy(e,t),t+=this.length)),e}},81221,(e,t,r)=>{function i(e,t){if(!e)throw Error(t||"Assertion failed")}t.exports=i,i.equal=function(e,t,r){if(e!=t)throw Error(r||"Assertion failed: "+e+" != "+t)}},524283,(e,t,r)=>{"use strict";let i=e.r(857406).Reporter,a=e.r(644833).EncoderBuffer,n=e.r(644833).DecoderBuffer,s=e.r(81221),o=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],l=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(o);function u(e,t,r){let i={};this._baseState=i,i.name=r,i.enc=e,i.parent=t||null,i.children=null,i.tag=null,i.args=null,i.reverseArgs=null,i.choice=null,i.optional=!1,i.any=!1,i.obj=!1,i.use=null,i.useDecoder=null,i.key=null,i.default=null,i.explicit=null,i.implicit=null,i.contains=null,i.parent||(i.children=[],this._wrap())}t.exports=u;let c=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];u.prototype.clone=function(){let e=this._baseState,t={};c.forEach(function(r){t[r]=e[r]});let r=new this.constructor(t.parent);return r._baseState=t,r},u.prototype._wrap=function(){let e=this._baseState;l.forEach(function(t){this[t]=function(){let r=new this.constructor(this);return e.children.push(r),r[t].apply(r,arguments)}},this)},u.prototype._init=function(e){let t=this._baseState;s(null===t.parent),e.call(this),t.children=t.children.filter(function(e){return e._baseState.parent===this},this),s.equal(t.children.length,1,"Root node can have only one child")},u.prototype._useArgs=function(e){let t=this._baseState,r=e.filter(function(e){return e instanceof this.constructor},this);e=e.filter(function(e){return!(e instanceof this.constructor)},this),0!==r.length&&(s(null===t.children),t.children=r,r.forEach(function(e){e._baseState.parent=this},this)),0!==e.length&&(s(null===t.args),t.args=e,t.reverseArgs=e.map(function(e){if("object"!=typeof e||e.constructor!==Object)return e;let t={};return Object.keys(e).forEach(function(r){r==(0|r)&&(r|=0),t[e[r]]=r}),t}))},["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"].forEach(function(e){u.prototype[e]=function(){throw Error(e+" not implemented for encoding: "+this._baseState.enc)}}),o.forEach(function(e){u.prototype[e]=function(){let t=this._baseState,r=Array.prototype.slice.call(arguments);return s(null===t.tag),t.tag=e,this._useArgs(r),this}}),u.prototype.use=function(e){s(e);let t=this._baseState;return s(null===t.use),t.use=e,this},u.prototype.optional=function(){return this._baseState.optional=!0,this},u.prototype.def=function(e){let t=this._baseState;return s(null===t.default),t.default=e,t.optional=!0,this},u.prototype.explicit=function(e){let t=this._baseState;return s(null===t.explicit&&null===t.implicit),t.explicit=e,this},u.prototype.implicit=function(e){let t=this._baseState;return s(null===t.explicit&&null===t.implicit),t.implicit=e,this},u.prototype.obj=function(){let e=this._baseState,t=Array.prototype.slice.call(arguments);return e.obj=!0,0!==t.length&&this._useArgs(t),this},u.prototype.key=function(e){let t=this._baseState;return s(null===t.key),t.key=e,this},u.prototype.any=function(){return this._baseState.any=!0,this},u.prototype.choice=function(e){let t=this._baseState;return s(null===t.choice),t.choice=e,this._useArgs(Object.keys(e).map(function(t){return e[t]})),this},u.prototype.contains=function(e){let t=this._baseState;return s(null===t.use),t.contains=e,this},u.prototype._decode=function(e,t){let r,i=this._baseState;if(null===i.parent)return e.wrapResult(i.children[0]._decode(e,t));let a=i.default,s=!0,o=null;if(null!==i.key&&(o=e.enterKey(i.key)),i.optional){let r=null;if(null!==i.explicit?r=i.explicit:null!==i.implicit?r=i.implicit:null!==i.tag&&(r=i.tag),null!==r||i.any){if(s=this._peekTag(e,r,i.any),e.isError(s))return s}else{let r=e.save();try{null===i.choice?this._decodeGeneric(i.tag,e,t):this._decodeChoice(e,t),s=!0}catch(e){s=!1}e.restore(r)}}if(i.obj&&s&&(r=e.enterObject()),s){if(null!==i.explicit){let t=this._decodeTag(e,i.explicit);if(e.isError(t))return t;e=t}let r=e.offset;if(null===i.use&&null===i.choice){let t;i.any&&(t=e.save());let r=this._decodeTag(e,null!==i.implicit?i.implicit:i.tag,i.any);if(e.isError(r))return r;i.any?a=e.raw(t):e=r}if(t&&t.track&&null!==i.tag&&t.track(e.path(),r,e.length,"tagged"),t&&t.track&&null!==i.tag&&t.track(e.path(),e.offset,e.length,"content"),i.any||(a=null===i.choice?this._decodeGeneric(i.tag,e,t):this._decodeChoice(e,t)),e.isError(a))return a;if(i.any||null!==i.choice||null===i.children||i.children.forEach(function(r){r._decode(e,t)}),i.contains&&("octstr"===i.tag||"bitstr"===i.tag)){let r=new n(a);a=this._getUse(i.contains,e._reporterState.obj)._decode(r,t)}}return i.obj&&s&&(a=e.leaveObject(r)),null!==i.key&&(null!==a||!0===s)?e.leaveKey(o,i.key,a):null!==o&&e.exitKey(o),a},u.prototype._decodeGeneric=function(e,t,r){let i=this._baseState;if("seq"===e||"set"===e)return null;if("seqof"===e||"setof"===e)return this._decodeList(t,e,i.args[0],r);if(/str$/.test(e))return this._decodeStr(t,e,r);if("objid"===e&&i.args)return this._decodeObjid(t,i.args[0],i.args[1],r);if("objid"===e)return this._decodeObjid(t,null,null,r);if("gentime"===e||"utctime"===e)return this._decodeTime(t,e,r);else if("null_"===e)return this._decodeNull(t,r);else if("bool"===e)return this._decodeBool(t,r);else if("objDesc"===e)return this._decodeStr(t,e,r);else if("int"===e||"enum"===e)return this._decodeInt(t,i.args&&i.args[0],r);return null!==i.use?this._getUse(i.use,t._reporterState.obj)._decode(t,r):t.error("unknown tag: "+e)},u.prototype._getUse=function(e,t){let r=this._baseState;return r.useDecoder=this._use(e,t),s(null===r.useDecoder._baseState.parent),r.useDecoder=r.useDecoder._baseState.children[0],r.implicit!==r.useDecoder._baseState.implicit&&(r.useDecoder=r.useDecoder.clone(),r.useDecoder._baseState.implicit=r.implicit),r.useDecoder},u.prototype._decodeChoice=function(e,t){let r=this._baseState,i=null,a=!1;return(Object.keys(r.choice).some(function(n){let s=e.save(),o=r.choice[n];try{let r=o._decode(e,t);if(e.isError(r))return!1;i={type:n,value:r},a=!0}catch(t){return e.restore(s),!1}return!0},this),a)?i:e.error("Choice not matched")},u.prototype._createEncoderBuffer=function(e){return new a(e,this.reporter)},u.prototype._encode=function(e,t,r){let i=this._baseState;if(null!==i.default&&i.default===e)return;let a=this._encodeValue(e,t,r);if(void 0!==a&&!this._skipDefault(a,t,r))return a},u.prototype._encodeValue=function(e,t,r){let a=this._baseState;if(null===a.parent)return a.children[0]._encode(e,t||new i);let n=null;if(this.reporter=t,a.optional&&void 0===e)if(null===a.default)return;else e=a.default;let s=null,o=!1;if(a.any)n=this._createEncoderBuffer(e);else if(a.choice)n=this._encodeChoice(e,t);else if(a.contains)s=this._getUse(a.contains,r)._encode(e,t),o=!0;else if(a.children)s=a.children.map(function(r){if("null_"===r._baseState.tag)return r._encode(null,t,e);if(null===r._baseState.key)return t.error("Child should have a key");let i=t.enterKey(r._baseState.key);if("object"!=typeof e)return t.error("Child expected, but input is not object");let a=r._encode(e[r._baseState.key],t,e);return t.leaveKey(i),a},this).filter(function(e){return e}),s=this._createEncoderBuffer(s);else if("seqof"===a.tag||"setof"===a.tag){if(!(a.args&&1===a.args.length))return t.error("Too many args for : "+a.tag);if(!Array.isArray(e))return t.error("seqof/setof, but data is not Array");let r=this.clone();r._baseState.implicit=null,s=this._createEncoderBuffer(e.map(function(r){let i=this._baseState;return this._getUse(i.args[0],e)._encode(r,t)},r))}else null!==a.use?n=this._getUse(a.use,r)._encode(e,t):(s=this._encodePrimitive(a.tag,e),o=!0);if(!a.any&&null===a.choice){let e=null!==a.implicit?a.implicit:a.tag,r=null===a.implicit?"universal":"context";null===e?null===a.use&&t.error("Tag could be omitted only for .use()"):null===a.use&&(n=this._encodeComposite(e,o,r,s))}return null!==a.explicit&&(n=this._encodeComposite(a.explicit,!1,"context",n)),n},u.prototype._encodeChoice=function(e,t){let r=this._baseState,i=r.choice[e.type];return i||s(!1,e.type+" not found in "+JSON.stringify(Object.keys(r.choice))),i._encode(e.value,t)},u.prototype._encodePrimitive=function(e,t){let r=this._baseState;if(/str$/.test(e))return this._encodeStr(t,e);if("objid"===e&&r.args)return this._encodeObjid(t,r.reverseArgs[0],r.args[1]);if("objid"===e)return this._encodeObjid(t,null,null);if("gentime"===e||"utctime"===e)return this._encodeTime(t,e);if("null_"===e)return this._encodeNull();else if("int"===e||"enum"===e)return this._encodeInt(t,r.args&&r.reverseArgs[0]);else if("bool"===e)return this._encodeBool(t);else if("objDesc"===e)return this._encodeStr(t,e);else throw Error("Unsupported tag: "+e)},u.prototype._isNumstr=function(e){return/^[0-9 ]*$/.test(e)},u.prototype._isPrintstr=function(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/.test(e)}},433689,(e,t,r)=>{"use strict";function i(e){let t={};return Object.keys(e).forEach(function(r){(0|r)==r&&(r|=0),t[e[r]]=r}),t}r.tagClass={0:"universal",1:"application",2:"context",3:"private"},r.tagClassByName=i(r.tagClass),r.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},r.tagByName=i(r.tag)},970738,(e,t,r)=>{"use strict";let i=e.r(966397),a=e.r(832623).Buffer,n=e.r(524283),s=e.r(433689);function o(e){this.enc="der",this.name=e.name,this.entity=e,this.tree=new l,this.tree._init(e.body)}function l(e){n.call(this,"der",e)}function u(e){return e<10?"0"+e:e}t.exports=o,o.prototype.encode=function(e,t){return this.tree._encode(e,t).join()},i(l,n),l.prototype._encodeComposite=function(e,t,r,i){let n=function(e,t,r,i){let a;if("seqof"===e?e="seq":"setof"===e&&(e="set"),s.tagByName.hasOwnProperty(e))a=s.tagByName[e];else{if("number"!=typeof e||(0|e)!==e)return i.error("Unknown tag: "+e);a=e}return a>=31?i.error("Multi-octet tag encoding unsupported"):(t||(a|=32),a|=s.tagClassByName[r||"universal"]<<6)}(e,t,r,this.reporter);if(i.length<128){let e=a.alloc(2);return e[0]=n,e[1]=i.length,this._createEncoderBuffer([e,i])}let o=1;for(let e=i.length;e>=256;e>>=8)o++;let l=a.alloc(2+o);l[0]=n,l[1]=128|o;for(let e=1+o,t=i.length;t>0;e--,t>>=8)l[e]=255&t;return this._createEncoderBuffer([l,i])},l.prototype._encodeStr=function(e,t){if("bitstr"===t)return this._createEncoderBuffer([0|e.unused,e.data]);if("bmpstr"===t){let t=a.alloc(2*e.length);for(let r=0;r<e.length;r++)t.writeUInt16BE(e.charCodeAt(r),2*r);return this._createEncoderBuffer(t)}if("numstr"===t)return this._isNumstr(e)?this._createEncoderBuffer(e):this.reporter.error("Encoding of string type: numstr supports only digits and space");if("printstr"===t)return this._isPrintstr(e)?this._createEncoderBuffer(e):this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark");if(/str$/.test(t))return this._createEncoderBuffer(e);else if("objDesc"===t)return this._createEncoderBuffer(e);else return this.reporter.error("Encoding of string type: "+t+" unsupported")},l.prototype._encodeObjid=function(e,t,r){if("string"==typeof e){if(!t)return this.reporter.error("string objid given, but no values map found");if(!t.hasOwnProperty(e))return this.reporter.error("objid not found in values map");e=t[e].split(/[\s.]+/g);for(let t=0;t<e.length;t++)e[t]|=0}else if(Array.isArray(e)){e=e.slice();for(let t=0;t<e.length;t++)e[t]|=0}if(!Array.isArray(e))return this.reporter.error("objid() should be either array or string, got: "+JSON.stringify(e));if(!r){if(e[1]>=40)return this.reporter.error("Second objid identifier OOB");e.splice(0,2,40*e[0]+e[1])}let i=0;for(let t=0;t<e.length;t++){let r=e[t];for(i++;r>=128;r>>=7)i++}let n=a.alloc(i),s=n.length-1;for(let t=e.length-1;t>=0;t--){let r=e[t];for(n[s--]=127&r;(r>>=7)>0;)n[s--]=128|127&r}return this._createEncoderBuffer(n)},l.prototype._encodeTime=function(e,t){let r,i=new Date(e);return"gentime"===t?r=""+u(i.getUTCFullYear())+u(i.getUTCMonth()+1)+u(i.getUTCDate())+u(i.getUTCHours())+u(i.getUTCMinutes())+u(i.getUTCSeconds())+"Z":"utctime"===t?r=""+u(i.getUTCFullYear()%100)+u(i.getUTCMonth()+1)+u(i.getUTCDate())+u(i.getUTCHours())+u(i.getUTCMinutes())+u(i.getUTCSeconds())+"Z":this.reporter.error("Encoding "+t+" time is not supported yet"),this._encodeStr(r,"octstr")},l.prototype._encodeNull=function(){return this._createEncoderBuffer("")},l.prototype._encodeInt=function(e,t){if("string"==typeof e){if(!t)return this.reporter.error("String int or enum given, but no values map");if(!t.hasOwnProperty(e))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(e));e=t[e]}if("number"!=typeof e&&!a.isBuffer(e)){let t=e.toArray();!e.sign&&128&t[0]&&t.unshift(0),e=a.from(t)}if(a.isBuffer(e)){let t=e.length;0===e.length&&t++;let r=a.alloc(t);return e.copy(r),0===e.length&&(r[0]=0),this._createEncoderBuffer(r)}if(e<128)return this._createEncoderBuffer(e);if(e<256)return this._createEncoderBuffer([0,e]);let r=1;for(let t=e;t>=256;t>>=8)r++;let i=Array(r);for(let t=i.length-1;t>=0;t--)i[t]=255&e,e>>=8;return 128&i[0]&&i.unshift(0),this._createEncoderBuffer(a.from(i))},l.prototype._encodeBool=function(e){return this._createEncoderBuffer(255*!!e)},l.prototype._use=function(e,t){return"function"==typeof e&&(e=e(t)),e._getEncoder("der").tree},l.prototype._skipDefault=function(e,t,r){let i,a=this._baseState;if(null===a.default)return!1;let n=e.join();if(void 0===a.defaultBuffer&&(a.defaultBuffer=this._encodeValue(a.default,t,r).join()),n.length!==a.defaultBuffer.length)return!1;for(i=0;i<n.length;i++)if(n[i]!==a.defaultBuffer[i])return!1;return!0}},671153,(e,t,r)=>{"use strict";let i=e.r(966397),a=e.r(970738);function n(e){a.call(this,e),this.enc="pem"}i(n,a),t.exports=n,n.prototype.encode=function(e,t){let r=a.prototype.encode.call(this,e).toString("base64"),i=["-----BEGIN "+t.label+"-----"];for(let e=0;e<r.length;e+=64)i.push(r.slice(e,e+64));return i.push("-----END "+t.label+"-----"),i.join("\n")}},642134,(e,t,r)=>{"use strict";r.der=e.r(970738),r.pem=e.r(671153)},229677,(e,t,r)=>{"use strict";let i=e.r(966397),a=e.r(917397),n=e.r(644833).DecoderBuffer,s=e.r(524283),o=e.r(433689);function l(e){this.enc="der",this.name=e.name,this.entity=e,this.tree=new u,this.tree._init(e.body)}function u(e){s.call(this,"der",e)}function c(e,t){let r=e.readUInt8(t);if(e.isError(r))return r;let i=o.tagClass[r>>6],a=(32&r)==0;if((31&r)==31){let i=r;for(r=0;(128&i)==128;){if(i=e.readUInt8(t),e.isError(i))return i;r<<=7,r|=127&i}}else r&=31;let n=o.tag[r];return{cls:i,primitive:a,tag:r,tagStr:n}}function d(e,t,r){let i=e.readUInt8(r);if(e.isError(i))return i;if(!t&&128===i)return null;if((128&i)==0)return i;let a=127&i;if(a>4)return e.error("length octect is too long");i=0;for(let t=0;t<a;t++){i<<=8;let t=e.readUInt8(r);if(e.isError(t))return t;i|=t}return i}t.exports=l,l.prototype.decode=function(e,t){return n.isDecoderBuffer(e)||(e=new n(e,t)),this.tree._decode(e,t)},i(u,s),u.prototype._peekTag=function(e,t,r){if(e.isEmpty())return!1;let i=e.save(),a=c(e,'Failed to peek tag: "'+t+'"');return e.isError(a)?a:(e.restore(i),a.tag===t||a.tagStr===t||a.tagStr+"of"===t||r)},u.prototype._decodeTag=function(e,t,r){let i=c(e,'Failed to decode tag of "'+t+'"');if(e.isError(i))return i;let a=d(e,i.primitive,'Failed to get length of "'+t+'"');if(e.isError(a))return a;if(!r&&i.tag!==t&&i.tagStr!==t&&i.tagStr+"of"!==t)return e.error('Failed to match tag: "'+t+'"');if(i.primitive||null!==a)return e.skip(a,'Failed to match body of: "'+t+'"');let n=e.save(),s=this._skipUntilEnd(e,'Failed to skip indefinite length body: "'+this.tag+'"');return e.isError(s)?s:(a=e.offset-n.offset,e.restore(n),e.skip(a,'Failed to match body of: "'+t+'"'))},u.prototype._skipUntilEnd=function(e,t){for(;;){let r,i=c(e,t);if(e.isError(i))return i;let a=d(e,i.primitive,t);if(e.isError(a))return a;if(r=i.primitive||null!==a?e.skip(a):this._skipUntilEnd(e,t),e.isError(r))return r;if("end"===i.tagStr)break}},u.prototype._decodeList=function(e,t,r,i){let a=[];for(;!e.isEmpty();){let t=this._peekTag(e,"end");if(e.isError(t))return t;let n=r.decode(e,"der",i);if(e.isError(n)&&t)break;a.push(n)}return a},u.prototype._decodeStr=function(e,t){if("bitstr"===t){let t=e.readUInt8();return e.isError(t)?t:{unused:t,data:e.raw()}}if("bmpstr"===t){let t=e.raw();if(t.length%2==1)return e.error("Decoding of string type: bmpstr length mismatch");let r="";for(let e=0;e<t.length/2;e++)r+=String.fromCharCode(t.readUInt16BE(2*e));return r}if("numstr"===t){let t=e.raw().toString("ascii");return this._isNumstr(t)?t:e.error("Decoding of string type: numstr unsupported characters")}if("octstr"===t)return e.raw();if("objDesc"===t)return e.raw();else if("printstr"===t){let t=e.raw().toString("ascii");return this._isPrintstr(t)?t:e.error("Decoding of string type: printstr unsupported characters")}else if(/str$/.test(t))return e.raw().toString();else return e.error("Decoding of string type: "+t+" unsupported")},u.prototype._decodeObjid=function(e,t,r){let i,a=[],n=0,s=0;for(;!e.isEmpty();)s=e.readUInt8(),n<<=7,n|=127&s,(128&s)==0&&(a.push(n),n=0);128&s&&a.push(n);let o=a[0]/40|0,l=a[0]%40;if(i=r?a:[o,l].concat(a.slice(1)),t){let e=t[i.join(" ")];void 0===e&&(e=t[i.join(".")]),void 0!==e&&(i=e)}return i},u.prototype._decodeTime=function(e,t){let r,i,a,n,s,o,l=e.raw().toString();if("gentime"===t)r=0|l.slice(0,4),i=0|l.slice(4,6),a=0|l.slice(6,8),n=0|l.slice(8,10),s=0|l.slice(10,12),o=0|l.slice(12,14);else{if("utctime"!==t)return e.error("Decoding "+t+" time is not supported yet");r=0|l.slice(0,2),i=0|l.slice(2,4),a=0|l.slice(4,6),n=0|l.slice(6,8),s=0|l.slice(8,10),o=0|l.slice(10,12),r=r<70?2e3+r:1900+r}return Date.UTC(r,i-1,a,n,s,o,0)},u.prototype._decodeNull=function(){return null},u.prototype._decodeBool=function(e){let t=e.readUInt8();return e.isError(t)?t:0!==t},u.prototype._decodeInt=function(e,t){let r=new a(e.raw());return t&&(r=t[r.toString(10)]||r),r},u.prototype._use=function(e,t){return"function"==typeof e&&(e=e(t)),e._getDecoder("der").tree}},594334,(e,t,r)=>{"use strict";let i=e.r(966397),a=e.r(832623).Buffer,n=e.r(229677);function s(e){n.call(this,e),this.enc="pem"}i(s,n),t.exports=s,s.prototype.decode=function(e,t){let r=e.toString().split(/[\r\n]+/g),i=t.label.toUpperCase(),s=/^-----(BEGIN|END) ([^-]+)-----$/,o=-1,l=-1;for(let e=0;e<r.length;e++){let t=r[e].match(s);if(null!==t&&t[2]===i)if(-1===o){if("BEGIN"!==t[1])break;o=e}else{if("END"!==t[1])break;l=e;break}}if(-1===o||-1===l)throw Error("PEM section not found for: "+i);let u=r.slice(o+1,l).join("");u.replace(/[^a-z0-9+/=]+/gi,"");let c=a.from(u,"base64");return n.prototype.decode.call(this,c,t)}},88855,(e,t,r)=>{"use strict";r.der=e.r(229677),r.pem=e.r(594334)},181713,(e,t,r)=>{"use strict";let i=e.r(642134),a=e.r(88855),n=e.r(966397);function s(e,t){this.name=e,this.body=t,this.decoders={},this.encoders={}}r.define=function(e,t){return new s(e,t)},s.prototype._createNamed=function(e){let t=this.name;function r(e){this._initNamed(e,t)}return n(r,e),r.prototype._initNamed=function(t,r){e.call(this,t,r)},new r(this)},s.prototype._getDecoder=function(e){return e=e||"der",this.decoders.hasOwnProperty(e)||(this.decoders[e]=this._createNamed(a[e])),this.decoders[e]},s.prototype.decode=function(e,t,r){return this._getDecoder(t).decode(e,r)},s.prototype._getEncoder=function(e){return e=e||"der",this.encoders.hasOwnProperty(e)||(this.encoders[e]=this._createNamed(i[e])),this.encoders[e]},s.prototype.encode=function(e,t,r){return this._getEncoder(t).encode(e,r)}},356767,(e,t,r)=>{"use strict";r.Reporter=e.r(857406).Reporter,r.DecoderBuffer=e.r(644833).DecoderBuffer,r.EncoderBuffer=e.r(644833).EncoderBuffer,r.Node=e.r(524283)},434299,(e,t,r)=>{"use strict";r._reverse=function(e){let t={};return Object.keys(e).forEach(function(r){(0|r)==r&&(r|=0),t[e[r]]=r}),t},r.der=e.r(433689)},572257,(e,t,r)=>{"use strict";r.bignum=e.r(917397),r.define=e.r(181713).define,r.base=e.r(356767),r.constants=e.r(434299),r.decoders=e.r(88855),r.encoders=e.r(642134)},41949,(e,t,r)=>{var i=e.r(223469).Buffer,a=e.r(688947);function n(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=i.alloc(0),this;if("function"==typeof e.pipe)return this.buffer=i.alloc(0),e.pipe(this),this;if(e.length||"object"==typeof e)return this.buffer=e,this.writable=!1,process.nextTick((function(){this.emit("end",e),this.readable=!1,this.emit("close")}).bind(this)),this;throw TypeError("Unexpected data type ("+typeof e+")")}e.r(224361).inherits(n,a),n.prototype.write=function(e){this.buffer=i.concat([this.buffer,i.from(e)]),this.emit("data",e)},n.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1},t.exports=n},465880,(e,t,r)=>{"use strict";function i(e){return(e/8|0)+ +(e%8!=0)}var a={ES256:i(256),ES384:i(384),ES512:i(521)};t.exports=function(e){var t=a[e];if(t)return t;throw Error('Unknown algorithm "'+e+'"')}},732955,(e,t,r)=>{"use strict";var i=e.r(223469).Buffer,a=e.r(465880);function n(e){if(i.isBuffer(e))return e;if("string"==typeof e)return i.from(e,"base64");throw TypeError("ECDSA signature must be a Base64 string or a Buffer")}function s(e,t,r){for(var i=0;t+i<r&&0===e[t+i];)++i;return e[t+i]>=128&&--i,i}t.exports={derToJose:function(e,t){e=n(e);var r=a(t),s=r+1,o=e.length,l=0;if(48!==e[l++])throw Error('Could not find expected "seq"');var u=e[l++];if(129===u&&(u=e[l++]),o-l<u)throw Error('"seq" specified length of "'+u+'", only "'+(o-l)+'" remaining');if(2!==e[l++])throw Error('Could not find expected "int" for "r"');var c=e[l++];if(o-l-2<c)throw Error('"r" specified length of "'+c+'", only "'+(o-l-2)+'" available');if(s<c)throw Error('"r" specified length of "'+c+'", max of "'+s+'" is acceptable');var d=l;if(l+=c,2!==e[l++])throw Error('Could not find expected "int" for "s"');var p=e[l++];if(o-l!==p)throw Error('"s" specified length of "'+p+'", expected "'+(o-l)+'"');if(s<p)throw Error('"s" specified length of "'+p+'", max of "'+s+'" is acceptable');var h=l;if((l+=p)!==o)throw Error('Expected to consume entire buffer, but "'+(o-l)+'" bytes remain');var m=r-c,f=r-p,g=i.allocUnsafe(m+c+f+p);for(l=0;l<m;++l)g[l]=0;e.copy(g,l,d+Math.max(-m,0),d+c),l=r;for(var y=l;l<y+f;++l)g[l]=0;return e.copy(g,l,h+Math.max(-f,0),h+p),g=(g=g.toString("base64")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")},joseToDer:function(e,t){e=n(e);var r=a(t),o=e.length;if(o!==2*r)throw TypeError('"'+t+'" signatures must be "'+2*r+'" bytes, saw "'+o+'"');var l=s(e,0,r),u=s(e,r,e.length),c=r-l,d=r-u,p=2+c+1+1+d,h=p<128,m=i.allocUnsafe((h?2:3)+p),f=0;return m[f++]=48,h?m[f++]=p:(m[f++]=129,m[f++]=255&p),m[f++]=2,m[f++]=c,l<0?(m[f++]=0,f+=e.copy(m,f,0,r)):f+=e.copy(m,f,l,r),m[f++]=2,m[f++]=d,u<0?(m[f++]=0,e.copy(m,f,r)):e.copy(m,f,r+u),m}}},922691,(e,t,r)=>{"use strict";var i=e.r(500874).Buffer,a=e.r(500874).SlowBuffer;function n(e,t){if(!i.isBuffer(e)||!i.isBuffer(t)||e.length!==t.length)return!1;for(var r=0,a=0;a<e.length;a++)r|=e[a]^t[a];return 0===r}t.exports=n,n.install=function(){i.prototype.equal=a.prototype.equal=function(e){return n(this,e)}};var s=i.prototype.equal,o=a.prototype.equal;n.restore=function(){i.prototype.equal=s,a.prototype.equal=o}},757067,(e,t,r)=>{var i,a=e.r(223469).Buffer,n=e.r(254799),s=e.r(732955),o=e.r(224361),l="secret must be a string or buffer",u="key must be a string or a buffer",c="function"==typeof n.createPublicKey;function d(e){if(!a.isBuffer(e)&&"string"!=typeof e&&(!c||"object"!=typeof e||"string"!=typeof e.type||"string"!=typeof e.asymmetricKeyType||"function"!=typeof e.export))throw f(u)}function p(e){if(!a.isBuffer(e)&&"string"!=typeof e&&"object"!=typeof e)throw f("key must be a string, a buffer or an object")}function h(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function m(e){var t=4-(e=e.toString()).length%4;if(4!==t)for(var r=0;r<t;++r)e+="=";return e.replace(/\-/g,"+").replace(/_/g,"/")}function f(e){var t=[].slice.call(arguments,1);return TypeError(o.format.bind(o,e).apply(null,t))}function g(e){var t;return t=e,a.isBuffer(t)||"string"==typeof t||(e=JSON.stringify(e)),e}function y(e){return function(t,r){!function(e){if(!a.isBuffer(e)){if("string"!=typeof e){if(!c||"object"!=typeof e||"secret"!==e.type||"function"!=typeof e.export)throw f(l)}}}(r),t=g(t);var i=n.createHmac("sha"+e,r);return h((i.update(t),i.digest("base64")))}}c&&(u+=" or a KeyObject",l+="or a KeyObject");var w="timingSafeEqual"in n?function(e,t){return e.byteLength===t.byteLength&&n.timingSafeEqual(e,t)}:function(t,r){return i||(i=e.r(922691)),i(t,r)};function b(e){return function(t,r,i){var n=y(e)(t,i);return w(a.from(r),a.from(n))}}function v(e){return function(t,r){p(r),t=g(t);var i=n.createSign("RSA-SHA"+e);return h((i.update(t),i.sign(r,"base64")))}}function k(e){return function(t,r,i){d(i),t=g(t),r=m(r);var a=n.createVerify("RSA-SHA"+e);return a.update(t),a.verify(i,r,"base64")}}function S(e){return function(t,r){p(r),t=g(t);var i=n.createSign("RSA-SHA"+e);return h((i.update(t),i.sign({key:r,padding:n.constants.RSA_PKCS1_PSS_PADDING,saltLength:n.constants.RSA_PSS_SALTLEN_DIGEST},"base64")))}}function E(e){return function(t,r,i){d(i),t=g(t),r=m(r);var a=n.createVerify("RSA-SHA"+e);return a.update(t),a.verify({key:i,padding:n.constants.RSA_PKCS1_PSS_PADDING,saltLength:n.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function I(e){var t=v(e);return function(){var r=t.apply(null,arguments);return s.derToJose(r,"ES"+e)}}function x(e){var t=k(e);return function(r,i,a){return t(r,i=s.joseToDer(i,"ES"+e).toString("base64"),a)}}function A(){return function(){return""}}function _(){return function(e,t){return""===t}}t.exports=function(e){var t=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!t)throw f('"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".',e);var r=(t[1]||t[3]).toLowerCase(),i=t[2];return{sign:({hs:y,rs:v,ps:S,es:I,none:A})[r](i),verify:({hs:b,rs:k,ps:E,es:x,none:_})[r](i)}}},576872,(e,t,r)=>{var i=e.r(500874).Buffer;t.exports=function(e){return"string"==typeof e?e:"number"==typeof e||i.isBuffer(e)?e.toString():JSON.stringify(e)}},614743,(e,t,r)=>{var i=e.r(223469).Buffer,a=e.r(41949),n=e.r(757067),s=e.r(688947),o=e.r(576872),l=e.r(224361);function u(e,t){return i.from(e,t).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function c(e){var t,r,i,a=e.header,s=e.payload,c=e.secret||e.privateKey,d=e.encoding,p=n(a.alg),h=(t=(t=d)||"utf8",r=u(o(a),"binary"),i=u(o(s),t),l.format("%s.%s",r,i)),m=p.sign(h,c);return l.format("%s.%s",h,m)}function d(e){var t=e.secret;if(t=null==(t=null==t?e.privateKey:t)?e.key:t,!0===/^hs/i.test(e.header.alg)&&null==t)throw TypeError("secret must be a string or buffer or a KeyObject");var r=new a(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=r,this.payload=new a(e.payload),this.secret.once("close",(function(){!this.payload.writable&&this.readable&&this.sign()}).bind(this)),this.payload.once("close",(function(){!this.secret.writable&&this.readable&&this.sign()}).bind(this))}l.inherits(d,s),d.prototype.sign=function(){try{var e=c({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}},d.sign=c,t.exports=d},148233,(e,t,r)=>{var i=e.r(223469).Buffer,a=e.r(41949),n=e.r(757067),s=e.r(688947),o=e.r(576872),l=e.r(224361),u=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function c(e){var t=e.split(".",1)[0],r=i.from(t,"base64").toString("binary");if("[object Object]"===Object.prototype.toString.call(r))return r;try{return JSON.parse(r)}catch(e){return}}function d(e){return e.split(".")[2]}function p(e){return u.test(e)&&!!c(e)}function h(e,t,r){if(!t){var i=Error("Missing algorithm parameter for jws.verify");throw i.code="MISSING_ALGORITHM",i}var a=d(e=o(e)),s=e.split(".",2).join(".");return n(t).verify(s,a,r)}function m(e,t){if(t=t||{},!p(e=o(e)))return null;var r,a,n=c(e);if(!n)return null;var s=(r=r||"utf8",a=e.split(".")[1],i.from(a,"base64").toString(r));return("JWT"===n.typ||t.json)&&(s=JSON.parse(s,t.encoding)),{header:n,payload:s,signature:d(e)}}function f(e){var t=(e=e||{}).secret;if(t=null==(t=null==t?e.publicKey:t)?e.key:t,!0===/^hs/i.test(e.algorithm)&&null==t)throw TypeError("secret must be a string or buffer or a KeyObject");var r=new a(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=r,this.signature=new a(e.signature),this.secret.once("close",(function(){!this.signature.writable&&this.readable&&this.verify()}).bind(this)),this.signature.once("close",(function(){!this.secret.writable&&this.readable&&this.verify()}).bind(this))}l.inherits(f,s),f.prototype.verify=function(){try{var e=h(this.signature.buffer,this.algorithm,this.key.buffer),t=m(this.signature.buffer,this.encoding);return this.emit("done",e,t),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}},f.decode=m,f.isValid=p,f.verify=h,t.exports=f},258184,(e,t,r)=>{var i=e.r(614743),a=e.r(148233);r.ALGORITHMS=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"],r.sign=i.sign,r.verify=a.verify,r.decode=a.decode,r.isValid=a.isValid,r.createSign=function(e){return new i(e)},r.createVerify=function(e){return new a(e)}},162232,(e,t,r)=>{"use strict";let i={};i.supportedContentEncodings={AES_GCM:"aesgcm",AES_128_GCM:"aes128gcm"},i.supportedUrgency={VERY_LOW:"very-low",LOW:"low",NORMAL:"normal",HIGH:"high"},t.exports=i},341220,(e,t,r)=>{"use strict";t.exports={validate:function(e){return/^[A-Za-z0-9\-_]+$/.test(e)}}},114916,(e,t,r)=>{"use strict";let i=e.r(254799),a=e.r(572257),n=e.r(258184),{URL:s}=e.r(792509),o=e.r(162232),l=e.r(341220),u=a.define("ECPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").explicit(0).objid().optional(),this.key("publicKey").explicit(1).bitstr().optional())});function c(e){if(!e)throw Error("No subject set in vapidDetails.subject.");if("string"!=typeof e||0===e.length)throw Error("The subject value must be a string containing an https: URL or mailto: address. "+e);let t=null;try{t=new s(e)}catch(t){throw Error("Vapid subject is not a valid URL. "+e)}if(!["https:","mailto:"].includes(t.protocol))throw Error("Vapid subject is not an https: or mailto: URL. "+e);"localhost"===t.hostname&&console.warn("Vapid subject points to a localhost web URI, which is unsupported by Apple's push notification server and will result in a BadJwtToken error when sending notifications.")}function d(e){if(!e)throw Error("No key set vapidDetails.publicKey");if("string"!=typeof e)throw Error("Vapid public key is must be a URL safe Base 64 encoded string.");if(!l.validate(e))throw Error('Vapid public key must be a URL safe Base 64 (without "=")');if(65!==(e=Buffer.from(e,"base64url")).length)throw Error("Vapid public key should be 65 bytes long when decoded.")}function p(e){if(!e)throw Error("No key set in vapidDetails.privateKey");if("string"!=typeof e)throw Error("Vapid private key must be a URL safe Base 64 encoded string.");if(!l.validate(e))throw Error('Vapid private key must be a URL safe Base 64 (without "=")');if(32!==(e=Buffer.from(e,"base64url")).length)throw Error("Vapid private key should be 32 bytes long when decoded.")}function h(e){let t=new Date;return t.setSeconds(t.getSeconds()+e),Math.floor(t.getTime()/1e3)}function m(e){if(!Number.isInteger(e))throw Error("`expiration` value must be a number");if(e<0)throw Error("`expiration` must be a positive integer");if(e>=h(86400))throw Error("`expiration` value is greater than maximum of 24 hours")}t.exports={generateVAPIDKeys:function(){let e=i.createECDH("prime256v1");e.generateKeys();let t=e.getPublicKey(),r=e.getPrivateKey();if(r.length<32){let e=Buffer.alloc(32-r.length);e.fill(0),r=Buffer.concat([e,r])}if(t.length<65){let e=Buffer.alloc(65-t.length);e.fill(0),t=Buffer.concat([e,t])}return{publicKey:t.toString("base64url"),privateKey:r.toString("base64url")}},getFutureExpirationTimestamp:h,getVapidHeaders:function(e,t,r,i,a,l){var f;if(!e)throw Error("No audience could be generated for VAPID.");if("string"!=typeof e||0===e.length)throw Error("The audience value must be a string containing the origin of a push service. "+e);try{new s(e)}catch(t){throw Error("VAPID audience is not a url. "+e)}c(t),d(r),p(i),i=Buffer.from(i,"base64url"),l?m(l):l=h(43200);let g={aud:e,exp:l,sub:t},y=n.sign({header:{typ:"JWT",alg:"ES256"},payload:g,privateKey:(f=i,u.encode({version:1,privateKey:f,parameters:[1,2,840,10045,3,1,7]},"pem",{label:"EC PRIVATE KEY"}))});if(a===o.supportedContentEncodings.AES_128_GCM)return{Authorization:"vapid t="+y+", k="+r};if(a===o.supportedContentEncodings.AES_GCM)return{Authorization:"WebPush "+y,"Crypto-Key":"p256ecdsa="+r};throw Error("Unsupported encoding type specified.")},validateSubject:c,validatePublicKey:d,validatePrivateKey:p,validateExpiration:m}},792320,(e,t,r)=>{"use strict";var i,a=e.r(254799),n="aes-128-gcm",s={aes128gcm:1,aesgcm:2},o="encrypt",l="decrypt";function u(e){return"string"==typeof e?Buffer.from(e,"base64url"):e}function c(e,t){var r=a.createHmac("sha256",e);return r.update(t),r.digest()}function d(e,t){return i("salt",e),i("ikm",t),i("extract",c(e,t))}function p(e,t,r){i("prk",e),i("info",t);var a=Buffer.alloc(0),n=Buffer.alloc(0);t=Buffer.from(t,"ascii");for(var s=0,o=Buffer.alloc(1);a.length<r;)o.writeUIntBE(++s,0,1),n=c(e,Buffer.concat([n,t,o])),a=Buffer.concat([a,n]);return i("expand",a.slice(0,r))}function h(e,t){var r=Buffer.concat([Buffer.from("Content-Encoding: "+e+"\0","ascii"),t]);return i("info "+e,r),r}function m(e){var t=Buffer.concat([Buffer.alloc(2),e]);return t.writeUIntBE(e.length,0,2),t}function f(e,t,r){if(!e.salt)throw Error("must include a salt parameter for "+e.version);if("aesgcm"===e.version){var a,n,s,u=function(e,t){var r,a,n,s={secret:null,context:Buffer.alloc(0)};if(e.key){if(s.secret=e.key,16!==s.secret.length)throw Error("An explicit key must be 16 bytes")}else e.dh?s=function(e,t){var r,i,a=e.privateKey;if(t===o)r=a.getPublicKey(),i=e.dh;else if(t===l)r=e.dh,i=a.getPublicKey();else throw Error("Unknown mode only "+o+" and "+l+" supported");return{secret:a.computeSecret(e.dh),context:Buffer.concat([Buffer.from(e.keylabel,"ascii"),Buffer.from([0]),m(i),m(r)])}}(e,t):(e.keyid,s.secret=e.keymap[e.keyid]);if(!s.secret)throw Error("Unable to determine key");return i("secret",s.secret),i("context",s.context),e.authSecret&&(s.secret=(r=e.authSecret,a=s.secret,n=h("auth",Buffer.alloc(0)),p(d(r,a),n,32)),i("authsecret",s.secret)),s}(e,t);a=h("aesgcm",u.context),n=h("nonce",u.context),s=u.secret}else if("aes128gcm"===e.version)a=Buffer.from("Content-Encoding: aes128gcm\0"),n=Buffer.from("Content-Encoding: nonce\0"),s=function(e,t,r){if(r&&"function"!=typeof r)throw Error("Callback is not a function");if(e.key){if(16!==e.key.length)throw Error("An explicit key must be 16 bytes");return i("secret key",e.key)}if(!e.privateKey){if(r)var a=r(e.keyid);else var a=e.keymap&&e.keymap[e.keyid];if(!a)throw Error('No saved key (keyid: "'+e.keyid+'")');return a}return function(e,t){var r,a,n,s,u,c;if(!e.authSecret)throw Error("No authentication secret for webpush");if(i("authsecret",e.authSecret),t===o)a=e.privateKey.getPublicKey(),r=n=e.dh;else if(t===l)r=a=e.keyid,n=e.privateKey.getPublicKey();else throw Error("Unknown mode only "+o+" and "+l+" supported");return i("remote pubkey",r),i("sender pubkey",a),i("receiver pubkey",n),i("secret dh",(s=e.authSecret,u=e.privateKey.computeSecret(r),c=Buffer.concat([Buffer.from("WebPush: info\0"),n,a]),p(d(s,u),c,32)))}(e,t)}(e,t,r);else throw Error("Unable to set context for mode "+e.version);var c=d(e.salt,s),f={key:p(c,a,16),nonce:p(c,n,12)};return i("key",f.key),i("nonce base",f.nonce),f}function g(e){var t={};t.version=e.version||"aes128gcm",t.rs=parseInt(e.rs,10),isNaN(t.rs)&&(t.rs=4096);var r=s[t.version];if("aes128gcm"===t.version&&(r+=16),t.rs<=r)throw Error("The rs parameter has to be greater than "+r);if(e.salt&&(t.salt=u(e.salt),16!==t.salt.length))throw Error("The salt parameter must be 16 bytes");return t.keyid=e.keyid,e.key?t.key=u(e.key):(t.privateKey=e.privateKey,t.privateKey||(t.keymap=e.keymap),"aes128gcm"!==t.version&&(t.keylabel=e.keylabel||"P-256"),e.dh&&(t.dh=u(e.dh))),e.authSecret&&(t.authSecret=u(e.authSecret)),t}function y(e,t){var r=Buffer.from(e),a=r.readUIntBE(r.length-6,6);return r.writeUIntBE(((a^t)&0xffffff)+((a/0x1000000^t/0x1000000)&0xffffff)*0x1000000,r.length-6,6),i("nonce"+t,r),r}i="1"===process.env.ECE_KEYLOG?function(e,t){return console.warn(e+" ["+t.length+"]: "+t.toString("base64url")),t}:function(e,t){return t},t.exports={decrypt:function(e,t,r){var o=g(t);if("aes128gcm"===o.version){var u,c,d=(c=(u=e).readUIntBE(20,1),o.salt=u.slice(0,16),o.rs=u.readUIntBE(16,4),o.keyid=u.slice(21,21+c),21+c);e=e.slice(d)}var p=f(o,l,r),h=0,m=Buffer.alloc(0),w=o.rs;"aes128gcm"!==o.version&&(w+=16);for(var b=0;h<e.length;++b){var v=h+w;if("aes128gcm"!==o.version&&v===e.length)throw Error("Truncated payload");if((v=Math.min(v,e.length))-h<=16)throw Error("Invalid block: too small at "+b);var k=function(e,t,r,o,l){i("decrypt",r);var u=y(e.nonce,t),c=a.createDecipheriv(n,e.key,u);c.setAuthTag(r.slice(r.length-16));var d=c.update(r.slice(0,r.length-16));if(d=Buffer.concat([d,c.final()]),i("decrypted",d),"aes128gcm"!==o.version)return function(e,t){var r=s[t],a=e.readUIntBE(0,r);if(a+r>e.length)throw Error("padding exceeds block size");i("padding",e.slice(0,r+a));var n=Buffer.alloc(a);if(n.fill(0),0!==n.compare(e.slice(r,r+a)))throw Error("invalid padding");return e.slice(r+a)}(d,o.version);for(var p=d,h=p.length-1;h>=0;){if(p[h]){if(l){if(2!==p[h])throw Error("last record needs to start padding with a 2")}else if(1!==p[h])throw Error("last record needs to start padding with a 2");return p.slice(0,h)}--h}throw Error("all zero plaintext")}(p,b,e.slice(h,v),o,v>=e.length);m=Buffer.concat([m,k]),h=v}return m},encrypt:function(e,t,r){if(!Buffer.isBuffer(e))throw Error("buffer argument must be a Buffer");var l,u=g(t);u.salt||(u.salt=a.randomBytes(16)),"aes128gcm"===u.version?(u.privateKey&&!u.keyid&&(u.keyid=u.privateKey.getPublicKey()),l=function(e){var t=Buffer.alloc(5),r=Buffer.from(e.keyid||[]);if(r.length>255)throw Error("keyid is too large");return t.writeUIntBE(e.rs,0,4),t.writeUIntBE(r.length,4,1),Buffer.concat([e.salt,t,r])}(u)):l=Buffer.alloc(0);var c=f(u,o,r),d=0,p=s[u.version],h=p;"aes128gcm"===u.version&&(h+=16);for(var m=isNaN(parseInt(t.pad,10))?0:parseInt(t.pad,10),w=0,b=!1;!b;){var v=Math.min(u.rs-h-1,m);"aes128gcm"!==u.version&&(v=Math.min((1<<8*p)-1,v)),m>0&&0===v&&++v,m-=v;var k=d+u.rs-h-v;b=(b="aes128gcm"!==u.version?k>e.length:k>=e.length)&&m<=0;var S=function(e,t,r,o,l,u){i("encrypt",r),o=o||0;var c=y(e.nonce,t),d=a.createCipheriv(n,e.key,c),p=[],h=s[l.version],m=Buffer.alloc(o+h);if(m.fill(0),"aes128gcm"!==l.version){if(m.writeUIntBE(o,0,h),i("padding",m),p.push(d.update(m)),p.push(d.update(r)),!u&&m.length+r.length<l.rs)throw Error("Unable to pad to record size")}else p.push(d.update(r)),m.writeUIntBE(u?2:1,0,1),i("padding",m),p.push(d.update(m));d.final();var f=d.getAuthTag();if(16!==f.length)throw Error("invalid tag generated");return p.push(f),i("encrypted",Buffer.concat(p))}(c,w,e.slice(d,k),v,u,b);l=Buffer.concat([l,S]),d=k,++w}return l}}},44703,(e,t,r)=>{"use strict";let i=e.r(254799),a=e.r(792320);t.exports={encrypt:function(e,t,r,n){if(!e)throw Error("No user public key provided for encryption.");if("string"!=typeof e)throw Error("The subscription p256dh value must be a string.");if(65!==Buffer.from(e,"base64url").length)throw Error("The subscription p256dh value should be 65 bytes long.");if(!t)throw Error("No user auth provided for encryption.");if("string"!=typeof t)throw Error("The subscription auth key must be a string.");if(Buffer.from(t,"base64url").length<16)throw Error("The subscription auth key should be at least 16 bytes long");if("string"!=typeof r&&!Buffer.isBuffer(r))throw Error("Payload must be either a string or a Node Buffer.");("string"==typeof r||r instanceof String)&&(r=Buffer.from(r));let s=i.createECDH("prime256v1"),o=s.generateKeys(),l=i.randomBytes(16).toString("base64url"),u=a.encrypt(r,{version:n,dh:e,privateKey:s,salt:l,authSecret:t});return{localPublicKey:o,salt:l,cipherText:u}}}},894635,(e,t,r)=>{"use strict";var i=e.e&&e.e.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var a=Object.getOwnPropertyDescriptor(t,r);(!a||("get"in a?!t.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,a)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),a=e.e&&e.e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=e.e&&e.e.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return a(t,e),t};Object.defineProperty(r,"__esModule",{value:!0}),r.req=r.json=r.toBuffer=void 0;let s=n(e.r(921517)),o=n(e.r(524836));async function l(e){let t=0,r=[];for await(let i of e)t+=i.length,r.push(i);return Buffer.concat(r,t)}r.toBuffer=l,r.json=async function(e){let t=(await l(e)).toString("utf8");try{return JSON.parse(t)}catch(e){throw e.message+=` (input: ${t})`,e}},r.req=function(e,t={}){let r=(("string"==typeof e?e:e.href).startsWith("https:")?o:s).request(e,t),i=new Promise((e,t)=>{r.once("response",e).once("error",t).end()});return r.then=i.then.bind(i),r}},326504,(e,t,r)=>{"use strict";var i=e.e&&e.e.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var a=Object.getOwnPropertyDescriptor(t,r);(!a||("get"in a?!t.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,a)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),a=e.e&&e.e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=e.e&&e.e.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return a(t,e),t},s=e.e&&e.e.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||i(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),r.Agent=void 0;let o=n(e.r(504446)),l=n(e.r(921517)),u=e.r(524836);s(e.r(894635),r);let c=Symbol("AgentBaseInternalState");class d extends l.Agent{constructor(e){super(e),this[c]={}}isSecureEndpoint(e){if(e){if("boolean"==typeof e.secureEndpoint)return e.secureEndpoint;if("string"==typeof e.protocol)return"https:"===e.protocol}let{stack:t}=Error();return"string"==typeof t&&t.split("\n").some(e=>-1!==e.indexOf("(https.js:")||-1!==e.indexOf("node:https:"))}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let t=new o.Socket({writable:!1});return this.sockets[e].push(t),this.totalSocketCount++,t}decrementSockets(e,t){if(!this.sockets[e]||null===t)return;let r=this.sockets[e],i=r.indexOf(t);-1!==i&&(r.splice(i,1),this.totalSocketCount--,0===r.length&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?u.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,t,r){let i={...t,secureEndpoint:this.isSecureEndpoint(t)},a=this.getName(i),n=this.incrementSockets(a);Promise.resolve().then(()=>this.connect(e,i)).then(s=>{if(this.decrementSockets(a,n),s instanceof l.Agent)try{return s.addRequest(e,i)}catch(e){return r(e)}this[c].currentSocket=s,super.createSocket(e,t,r)},e=>{this.decrementSockets(a,n),r(e)})}createConnection(){let e=this[c].currentSocket;if(this[c].currentSocket=void 0,!e)throw Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[c].defaultPort??("https:"===this.protocol?443:80)}set defaultPort(e){this[c]&&(this[c].defaultPort=e)}get protocol(){return this[c].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[c]&&(this[c].protocol=e)}}r.Agent=d},377557,(e,t,r)=>{"use strict";var i=e.e&&e.e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.parseProxyResponse=void 0;let a=(0,i(e.r(817293)).default)("https-proxy-agent:parse-proxy-response");r.parseProxyResponse=function(e){return new Promise((t,r)=>{let i=0,n=[];function s(){let l=e.read();l?function(l){n.push(l),i+=l.length;let u=Buffer.concat(n,i),c=u.indexOf("\r\n\r\n");if(-1===c){a("have not received end of HTTP headers yet..."),s();return}let d=u.slice(0,c).toString("ascii").split("\r\n"),p=d.shift();if(!p)return e.destroy(),r(Error("No header received from proxy CONNECT response"));let h=p.split(" "),m=+h[1],f=h.slice(2).join(" "),g={};for(let t of d){if(!t)continue;let i=t.indexOf(":");if(-1===i)return e.destroy(),r(Error(`Invalid header from proxy CONNECT response: "${t}"`));let a=t.slice(0,i).toLowerCase(),n=t.slice(i+1).trimStart(),s=g[a];"string"==typeof s?g[a]=[s,n]:Array.isArray(s)?s.push(n):g[a]=n}a("got proxy server response: %o %o",p,g),o(),t({connect:{statusCode:m,statusText:f,headers:g},buffered:u})}(l):e.once("readable",s)}function o(){e.removeListener("end",l),e.removeListener("error",u),e.removeListener("readable",s)}function l(){o(),a("onend"),r(Error("Proxy connection ended before receiving CONNECT response"))}function u(e){o(),a("onerror %o",e),r(e)}e.on("error",u),e.on("end",l),s()})}},648630,(e,t,r)=>{"use strict";var i=e.e&&e.e.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var a=Object.getOwnPropertyDescriptor(t,r);(!a||("get"in a?!t.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,a)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),a=e.e&&e.e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=e.e&&e.e.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return a(t,e),t},s=e.e&&e.e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.HttpsProxyAgent=void 0;let o=n(e.r(504446)),l=n(e.r(755004)),u=s(e.r(449719)),c=s(e.r(817293)),d=e.r(326504),p=e.r(792509),h=e.r(377557),m=(0,c.default)("https-proxy-agent"),f=e=>void 0===e.servername&&e.host&&!o.isIP(e.host)?{...e,servername:e.host}:e;class g extends d.Agent{constructor(e,t){super(t),this.options={path:void 0},this.proxy="string"==typeof e?new p.URL(e):e,this.proxyHeaders=t?.headers??{},m("Creating new HttpsProxyAgent instance: %o",this.proxy.href);const r=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),i=this.proxy.port?parseInt(this.proxy.port,10):"https:"===this.proxy.protocol?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...t?w(t,"headers"):null,host:r,port:i}}async connect(e,t){let r,{proxy:i}=this;if(!t.host)throw TypeError('No "host" provided');"https:"===i.protocol?(m("Creating `tls.Socket`: %o",this.connectOpts),r=l.connect(f(this.connectOpts))):(m("Creating `net.Socket`: %o",this.connectOpts),r=o.connect(this.connectOpts));let a="function"==typeof this.proxyHeaders?this.proxyHeaders():{...this.proxyHeaders},n=o.isIPv6(t.host)?`[${t.host}]`:t.host,s=`CONNECT ${n}:${t.port} HTTP/1.1\r
616
+ ${t}`}splitMarkdownIntoSections(e){let t=e.split(/(?=^#{1,6}\s)|(?:\n\s*\n)/m).filter(e=>e.trim().length>0);return t.length>0?t:[e]}async parseMarkdownSection(e){try{let t=[this.createTextFallback(e)];return{success:!0,data:{version:1,type:"doc",content:t},warnings:[]}}catch(e){return{success:!1,error:e,warnings:[]}}}createTextFallback(e){return{type:"paragraph",content:[{type:"text",text:e.trim()}]}}createPlaceholder(e){return e.operation.includes("adfToMarkdown")?`[Error converting ADF to Markdown: ${e.operation}]`:e.operation.includes("markdownToAdf")?{version:1,type:"doc",content:[{type:"paragraph",content:[{type:"text",text:`[Error converting Markdown to ADF: ${e.operation}]`}]}]}:`[Error in operation: ${e.operation}]`}},sV=class{constructor(e){(0,tG.__publicField)(this,"mdToAdfEngine"),(0,tG.__publicField)(this,"adfToMdEngine"),(0,tG.__publicField)(this,"options"),(0,tG.__publicField)(this,"errorRecovery"),(0,tG.__publicField)(this,"remarkProcessor"),(0,tG.__publicField)(this,"registry");try{this.options=e||{},this.mdToAdfEngine=new ss(this.options),this.adfToMdEngine=new sF(this.options),this.errorRecovery=new sK({maxRetries:e?.maxRetries||3,retryDelay:e?.retryDelay||100,fallbackStrategy:e?.fallbackStrategy||"best-effort",enableLogging:e?.enableLogging||!1,onError:e?.onError,onRecovery:e?.onRecovery}),this.remarkProcessor=ri().use(iD).use(a_,["yaml"]).use(n$).use(nV,{strict:e?.strict||!1}).use(am),this.registry=new nY,this.registerConverters()}catch(e){throw new nJ("Failed to initialize Parser","INIT_ERROR")}}adfToMarkdown(e,t){return t&&Object.keys(t).length>0?new sF({...this.options,...t}).convert(e):this.adfToMdEngine.convert(e)}async adfToMarkdownWithRecovery(e,t){let r=await this.errorRecovery.executeWithRecovery(()=>this.adfToMarkdown(e,t),{operation:"adfToMarkdown",input:e,nodeType:e.type});if(!r.success)throw r.error||Error("ADF to Markdown conversion failed");return r.data}markdownToAdf(e,t){return t&&Object.keys(t).length>0?new ss({...this.options,...t}).convert(e):this.mdToAdfEngine.convert(e)}async markdownToAdfWithRecovery(e,t){let r=await this.errorRecovery.executeWithRecovery(()=>this.markdownToAdf(e,t),{operation:"markdownToAdf",input:e});if(!r.success)throw r.error||Error("Markdown to ADF conversion failed");return r.data}async markdownToAdfAsync(e,t){return await this.mdToAdfEngine.convertAsync(e)}async markdownToAdfAsyncWithRecovery(e,t){let r=await this.errorRecovery.executeWithRecovery(async()=>this.markdownToAdfAsync(e,t),{operation:"markdownToAdfAsync",input:e});if(!r.success)throw r.error||Error("Async Markdown to ADF conversion failed");return r.data}async validateMarkdownAsync(e){let t=await this.mdToAdfEngine.validate(e);return{valid:t.valid,errors:t.errors.map(e=>({message:e})),warnings:t.warnings}}async getStats(e){return await this.mdToAdfEngine.getStats(e)}stringify(e,t){return this.adfToMarkdown(e,t)}async stringifyAsync(e,t){return this.adfToMarkdownWithRecovery(e,t)}validateAdf(e){return new nH().validate(e)}validateMarkdown(e){return new nW().validate(e)}getErrorRecovery(){return this.errorRecovery}registerConverters(){this.registry.registerNodes([new so,new sl,new su,new sc,new sd,new sp,new sh,new sm,new sf,new sg,new sy,new sw,new sb,new sv,new sk,new sS,new sE,new sI,new sx,new sA,new s_,new sC,new sR,new sT,new sD,new sN]),this.registry.registerMarks([new sO,new sP,new s$,new sU,new sB,new sj,new sL,new sq,new sM])}convertAdfToMarkdown(e){return this.adfToMdEngine.convert(e)}convertMdastToAdf(e){return this.mdToAdfEngine.convert(e)}fallbackConversion(e){return this.mdToAdfEngine.convert(e)}countNodes(e){let t=0;for(let r of e)t++,r.content&&Array.isArray(r.content)&&(t+=this.countNodes(r.content));return t}postProcessAdfFenceBlocks(e){return e}parseAdfLanguageString(e,t){return{}}},sG=e.i(378731);let sH=[/^h[1-6]\.\s/m,/^bq\.\s/m,/\{code(?::[^}]+)?\}/i,/\{noformat\}/i,/\{\{[^}\n]+\}\}/,/^\|\|.+\|\|\s*$/m,/\[[^\]\n]+\|https?:\/\//i,/\[~[^\]\n]+\]/,/\[\^[^\]\n]+\]/,/![^!\n]+!/];function sW(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"doc"===e.type&&1===e.version&&Array.isArray(e.content)}function sJ(e,t){return sG.default.to_markdown(e.replace(/\[~([^\]\n]+)\]/g,"@$1").replace(/\[\^([^\]\n]+)\]/g,"[Attachment: $1]").replace(/\[([A-Z][A-Z0-9_]*-\d+)\]/g,(e,r)=>t?`[${r}](${t}/browse/${r})`:`**${r}**`))}let sz=new sV;function sZ(e,t){if(null==e)return null;let r=function(e){if(sW(e))return"ADF";let t="string"==typeof e?e:"";return sH.some(e=>e.test(t))?"JIRA_WIKI":"MARKDOWN"}(e),i="string"==typeof e?e:null==e?"":JSON.stringify(e,null,2),a="ADF"===r?function(e){try{return sz.adfToMarkdown(e)}catch{return function e(t){return t&&"object"==typeof t?["string"==typeof t.text?t.text:"",...Array.isArray(t.content)?t.content.map(e).filter(Boolean):[]].filter(Boolean).join("\n"):""}(e)}}(e):"JIRA_WIKI"===r?sJ(i,t):i;return{format:r,raw:e,rawText:i,markdown:a,wikiMarkup:"JIRA_WIKI"===r?i:sG.default.to_jira(a)}}function sY(e){let t=e.value.trim(),r="JIRA_WIKI"===e.format?sJ(t):t,i=sz.markdownToAdf(r);if(!sW(i))throw Error("The Jira text could not be converted to valid ADF");return i}let sQ="default",sX=["summary","status","issuetype","priority","assignee","project","updated"],s0=[{window:"5m",milliseconds:3e5},{window:"10m",milliseconds:6e5},{window:"1h",milliseconds:36e5},{window:"24h",milliseconds:864e5}];function s1(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function s2(e){return s1(e)?e:{}}function s3(e){return Array.isArray(e)?e:[]}function s4(e){return"string"==typeof e&&e.length>0?e:null}function s6(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function s8(e){let t=e.trim().toUpperCase();if(!/^[A-Z][A-Z0-9_]*-\d+$/.test(t))throw Error("Invalid Jira issue key");return t}function s5(e){if(null===e)return null;try{return JSON.parse(e)}catch{return null}}function s9(e){return s3(s5(e)).flatMap(e=>"string"==typeof e&&e.length>0?[e]:[])}function s7(e){return JSON.stringify(function e(t){return Array.isArray(t)?t.map(e):s1(t)?Object.fromEntries(Object.keys(t).sort().map(r=>[r,e(t[r])])):t}(e))}function oe(e){if(!s1(e))return null;let t=e.status??s2(e.response).status;return"number"==typeof t?t:null}function ot(e,t){let r=e instanceof Error?e.message:String(e);return(t?r.replaceAll(t,"[REDACTED]"):r).slice(0,1e3)}function or(e){return s4(s2(s2(e.fields).project).key)??(e.key?.split("-")[0]||"UNKNOWN")}function oi(e){let t=s2(e),r=s4(t.displayName);if(!r)return null;let i=s2(t.avatarUrls);return{accountId:s4(t.accountId),displayName:r,avatarUrl:s4(i["48x48"])??s4(i["32x32"])??s4(i["24x24"])}}function oa(e){return s3(e).map(s2).map(e=>({id:s4(e.id),name:s4(e.name)??"Unknown"}))}function on(e,t){let r=s2(e),i=s4(r.key);if(!i)return null;let a=s2(r.fields);return{relationship:t,key:i,summary:s4(a.summary)??i,status:s4(s2(a.status).name)}}function os(e){return{...e,kind:"BOARD"===e.kind?"BOARD":"JQL"}}function oo(e){return{source:e.source,stale:e.stale,fetchedAt:e.fetchedAt.toISOString()}}function ol(e){return 0===e.length?{source:"CACHE",stale:!1,fetchedAt:new Date(0).toISOString()}:{source:e.some(e=>"ERROR"===e.source)?"ERROR":e.some(e=>"LIVE"===e.source)?"LIVE":"CACHE",stale:e.some(e=>e.stale),fetchedAt:new Date(Math.max(...e.map(e=>e.fetchedAt.getTime()))).toISOString()}}function ou(e){let t=s2(e.fields),r=s2(t.status),i=s2(r.statusCategory),a=s2(t.assignee),n=s2(a.avatarUrls),s=s2(t.project),o=e.key??"UNKNOWN";return{id:e.id??o,key:o,summary:s4(t.summary)??o,statusId:s4(r.id)??s4(r.name)??"unknown",status:s4(r.name)??"Unknown",statusCategory:s4(i.key)??s4(i.name)??"unknown",issueType:s4(s2(t.issuetype).name),priority:s4(s2(t.priority).name),assignee:s4(a.displayName),assigneeAccountId:s4(a.accountId),assigneeAvatarUrl:s4(n["48x48"])??s4(n["32x32"]),projectKey:s4(s.key)??or(e),updatedAt:s4(t.updated)}}function oc(e){let t=e.toLowerCase();return"new"===t||t.includes("to do")?0:"indeterminate"===t||t.includes("progress")?1:"done"===t?2:3}let od=new Set(["ALL","UNASSIGNED_OR_SELF","SELF_IN_PROGRESS"]);function op(e){return od.has(e)?e:"ALL"}e.s(["JiraService",0,class{credentials;workflowEvents;recordCallLogs;inFlight;clients;lastPrunedAt;constructor(e=new tO.CredentialService,t,r="true"!==process.env.JIRA_CACHE_LOGGING_DISABLED){this.credentials=e,this.workflowEvents=t,this.recordCallLogs=r,this.inFlight=new Map,this.lastPrunedAt=0}async recordTicketWorkflowEvents(e,t){if(!this.workflowEvents)return;let r=e.comments.at(-1)??null,i={ticket:{key:e.key,title:e.summary,type:e.issueType,status:e.status,statusId:e.statusId,statusCategory:e.statusCategory,assignee:e.assignee,assigneeAccountId:e.assigneeAccountId,labels:e.labels,sprintNames:e.sprintNames,activeSprintNames:e.activeSprintNames,closedSprintNames:e.closedSprintNames,url:e.jiraUrl},comment:r?{id:r.id,body:r.content?.rawText??"",author:r.author}:null,...void 0!==t?{changelog:t}:{}},a=e.cache.fetchedAt,n=e.assigneeAccountId?await this.currentAccountId().catch(()=>null):null,s=[["JIRA_STATUS",e.statusId],["JIRA_LABEL",JSON.stringify([...e.labels].sort())],["JIRA_MENTION",r?.id??"none"],["JIRA_SPRINT_STARTED",[...e.activeSprintNames].sort()],["JIRA_TICKET_UPDATED",e.updatedAt??"unknown"],["JIRA_COMMENT_ADDED",r?.id??"none"],["JIRA_SPRINT_ENDED",[...e.closedSprintNames].sort()]];if(n&&n===e.assigneeAccountId&&s.push(["JIRA_ASSIGNED_SELF",n]),t?.items.length){let e=new Set(t.items.flatMap(e=>[e.fieldId,e.field].filter(e=>!!e).map(e=>e.trim().toLowerCase()))),r=new Set(["JIRA_TICKET_UPDATED"]);e.has("status")&&r.add("JIRA_STATUS"),(e.has("label")||e.has("labels"))&&r.add("JIRA_LABEL"),e.has("assignee")&&r.add("JIRA_ASSIGNED_SELF"),e.has("sprint")&&(r.add("JIRA_SPRINT_STARTED"),r.add("JIRA_SPRINT_ENDED")),s=s.filter(([e])=>r.has(e))}await Promise.allSettled(s.map(([t,r])=>this.workflowEvents.record({kind:t,subjectKey:e.key,dedupeKey:`jira-trigger:${t}:${e.key}:${a}`,payload:{...i,sessionData:i,cursorValue:r}})))}async getSettings(){let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.upsert({where:{id:sQ},create:{id:sQ,cacheTtlSeconds:300},update:{}});return{siteUrl:t.siteUrl,email:t.email,tokenConfigured:await this.credentials.isConfigured(tN.CREDENTIALS.jiraApiToken),cacheTtlSeconds:t.cacheTtlSeconds,updatedAt:t.updatedAt.toISOString()}}async saveSettings(e){let t=await (0,tD.getPrismaClient)(),r=function(e){let t=new URL(e.trim());if("https:"!==t.protocol)throw Error("Jira Cloud site URL must use HTTPS");if(!t.hostname.toLowerCase().endsWith(".atlassian.net"))throw Error("Only Jira Cloud *.atlassian.net sites are supported");if(t.username||t.password||t.search||t.hash)throw Error("Jira site URL must not include credentials, query, or fragment");return t.origin}(e.siteUrl),i=e.email.trim();if(!/^\S+@\S+\.\S+$/.test(i))throw Error("A valid Jira email is required");let a=await t.jiraSettings.findUnique({where:{id:sQ}}),n=e.apiToken?.trim()||null,s=!!(a?.siteUrl&&a.siteUrl!==r);if(s&&!e.resetSite)throw Error("Changing the Jira site requires resetSite=true");let o=a?.siteUrl!==r||a?.email!==i||!!n,l=async e=>{s&&(await e.jiraProject.deleteMany(),await e.jiraWebhookDelivery.deleteMany()),o&&(await e.jiraCacheEntry.deleteMany(),await e.jiraCachedTicket.deleteMany()),await e.jiraSettings.upsert({where:{id:sQ},create:{id:sQ,siteUrl:r,email:i,cacheTtlSeconds:300},update:s?{siteUrl:r,email:i,webhookEnabled:!1,webhookConfiguredAt:null,webhookId:null,webhookUrl:null,webhookJql:null}:{siteUrl:r,email:i}})};return n?await this.credentials.setText(tN.CREDENTIALS.jiraApiToken,n,l):await t.$transaction(l),s&&await this.credentials.delete(tN.CREDENTIALS.jiraWebhookSecret),this.clients=void 0,this.getSettings()}async clearCredentials(){let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:sQ},select:{siteUrl:!0,email:!0,webhookId:!0}}),r=await this.credentials.isConfigured(tN.CREDENTIALS.jiraApiToken);if(t?.siteUrl&&t.email&&t.webhookId&&r)try{await this.webhookApiRequest("DELETE",`/rest/webhooks/1.0/webhook/${encodeURIComponent(t.webhookId)}`)}catch(e){if(404!==oe(e))throw e}return await this.credentials.deleteMany([tN.CREDENTIALS.jiraApiToken,tN.CREDENTIALS.jiraWebhookSecret],async e=>{await e.jiraCacheEntry.deleteMany(),await e.jiraCachedTicket.deleteMany(),await e.jiraWebhookDelivery.deleteMany(),await e.jiraSettings.upsert({where:{id:sQ},create:{id:sQ,cacheTtlSeconds:300},update:{email:null,webhookEnabled:!1,webhookConfiguredAt:null,webhookId:null,webhookUrl:null,webhookJql:null}})}),this.clients=void 0,this.getSettings()}async updateCacheTtl(e){if(!Number.isInteger(e)||e<1||e>1440)throw Error("Cache TTL must be an integer from 1 to 1440 minutes");let t=await (0,tD.getPrismaClient)();return await t.jiraSettings.upsert({where:{id:sQ},create:{id:sQ,cacheTtlSeconds:60*e},update:{cacheTtlSeconds:60*e}}),this.getSettings()}async testConnection(){let e=await this.cachedCall({operation:"MYSELF",params:{},requestSummary:"Current Jira user",force:!0,allowStaleOnError:!1,fetcher:async()=>{let{version3:e}=await this.getClients();return e.myself.getCurrentUser()}});if(e.stale)throw Error("Jira connection test failed because the live request failed");let t=s2(e.value);return{accountId:s4(t.accountId),displayName:s4(t.displayName)??"Jira user",emailAddress:s4(t.emailAddress),cache:oo(e)}}async listProjects(){let e=await (0,tD.getPrismaClient)();return(await e.jiraProject.findMany({include:{sources:{orderBy:[{position:"asc"},{createdAt:"asc"}]}},orderBy:[{position:"asc"},{createdAt:"asc"}]})).map(e=>({id:e.id,jiraId:e.jiraId,key:e.key,name:e.name,avatarUrl:e.avatarUrl,position:e.position,ticketAssignmentFilter:op(e.ticketAssignmentFilter),hideCompletedTickets:e.hideCompletedTickets,completedStatusIds:s9(e.completedStatusIdsJson),doneStatusId:e.doneStatusId,branchNamingScript:e.branchNamingScript??tF,sources:e.sources.map(os)}))}async projectStatuses(e){let t=await (0,tD.getPrismaClient)(),r=await t.jiraProject.findUnique({where:{id:e},select:{jiraId:!0,key:!0}});if(!r)throw Error("Jira project not found");let i=await this.cachedCall({operation:"PROJECT_STATUSES",params:{jiraId:r.jiraId},requestSummary:`Statuses for project ${r.key}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.projects.getAllStatuses(r.jiraId)}}),a=new Map;for(let e of s3(i.value).map(s2))for(let t of s3(e.statuses).map(s2)){let e=s4(t.id),r=s4(t.name);if(!e||!r||a.has(e))continue;let i=s2(t.statusCategory);a.set(e,{id:e,name:r,category:s4(i.key)??s4(i.name)??"unknown"})}return[...a.values()].sort((e,t)=>oc(e.category)-oc(t.category)||e.name.localeCompare(t.name))}async updateProjectDisplaySettings(e){if(!od.has(e.ticketAssignmentFilter))throw Error("Invalid Jira ticket assignment filter");let t=[...new Set(e.completedStatusIds.map(e=>e.trim()).filter(Boolean))].slice(0,200),r=await (0,tD.getPrismaClient)(),i=void 0===e.doneStatusId?void 0:e.doneStatusId?.trim()||null;if(i&&!(await this.projectStatuses(e.projectId)).some(e=>e.id===i))throw Error("The selected Jira done status is not available");return await r.jiraProject.update({where:{id:e.projectId},data:{ticketAssignmentFilter:e.ticketAssignmentFilter,hideCompletedTickets:e.hideCompletedTickets,completedStatusIdsJson:JSON.stringify(t),...void 0===i?{}:{doneStatusId:i}}}),this.listProjects()}async updateProjectBranchNaming(e,t){let r=await (0,tD.getPrismaClient)(),i=await r.jiraProject.findUnique({where:{id:e},select:{key:!0}});if(!i)throw Error("Jira project not found");let a=await tV(t,i.key);return await r.jiraProject.update({where:{id:e},data:{branchNamingScript:a}}),this.listProjects()}async availableProjects(){let e=[],t=0;for(;;){let r=await this.cachedCall({operation:"PROJECTS",params:{startAt:t,maxResults:100},requestSummary:`Visible projects from ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.projects.searchProjects({startAt:t,maxResults:100,orderBy:"name"})},itemCount:e=>s3(s2(e).values).length}),i=s2(r.value),a=s3(i.values).map(s2);e.push(...a.flatMap(e=>{let t=s4(e.id),r=s4(e.key),i=s4(e.name);if(!t||!r||!i)return[];let a=s2(e.avatarUrls);return[{jiraId:t,key:r,name:i,avatarUrl:s4(a["48x48"])??s4(a["32x32"])}]}));let n=s6(i.total)??e.length;if(0===a.length||e.length>=n)break;t+=a.length}return e}async addProject(e){let t=e.trim();if(!t)throw Error("Jira project ID is required");let i=s2((await this.cachedCall({operation:"PROJECT",params:{jiraId:t},requestSummary:`Project ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.projects.getProject(t)}})).value),a=s4(i.key),n=s4(i.name),s=s4(i.id);if(!a||!n||!s)throw Error("Jira returned an incomplete project");let o=s2(i.avatarUrls),l=await (0,tD.getPrismaClient)(),u=await l.jiraProject.aggregate({_max:{position:!0}});return await l.jiraProject.create({data:{id:(0,r.randomUUID)(),jiraId:s,key:a,name:n,avatarUrl:s4(o["48x48"])??s4(o["32x32"]),position:(u._max.position??-1)+1,branchNamingScript:tF}}),this.listProjects()}async removeProject(e){let t=await (0,tD.getPrismaClient)(),r=(await t.jiraSource.findMany({where:{projectId:e},select:{id:!0}})).map(e=>e.id);return await t.$transaction(async t=>{r.length>0&&await t.jiraCacheEntry.deleteMany({where:{sourceId:{in:r}}}),await t.jiraProject.delete({where:{id:e}}),await t.jiraCachedTicket.deleteMany({where:{cacheEntries:{none:{}}}})}),this.listProjects()}async createSource(e){let t=await this.validateSource(e.kind,e.value),i=this.validateSourceName(e.name),a=await (0,tD.getPrismaClient)();if(!await a.jiraProject.findUnique({where:{id:e.projectId}}))throw Error("Jira project not found");let n=await a.jiraSource.aggregate({where:{projectId:e.projectId},_max:{position:!0}});return await a.jiraSource.create({data:{id:(0,r.randomUUID)(),projectId:e.projectId,name:i,kind:e.kind,value:t.value,boardId:t.boardId,position:(n._max.position??-1)+1}}),this.listProjects()}async updateSource(e){let t=await this.validateSource(e.kind,e.value),r=this.validateSourceName(e.name),i=await (0,tD.getPrismaClient)();return await i.$transaction([i.jiraCacheEntry.deleteMany({where:{sourceId:e.id}}),i.jiraSource.update({where:{id:e.id},data:{name:r,kind:e.kind,value:t.value,boardId:t.boardId}})]),this.listProjects()}async deleteSource(e){let t=await (0,tD.getPrismaClient)();return await t.$transaction(async t=>{await t.jiraCacheEntry.deleteMany({where:{sourceId:e}}),await t.jiraSource.delete({where:{id:e}}),await t.jiraCachedTicket.deleteMany({where:{cacheEntries:{none:{}}}})}),this.listProjects()}async ticketBoard(e,t=!1){var r;let i,a,n,s=await (0,tD.getPrismaClient)(),o=await s.jiraSource.findUnique({where:{id:e},include:{project:!0}});if(!o)throw Error("Jira source not found");let l=await s.jiraCacheEntry.findFirst({where:{sourceId:e,issues:{some:{}}},orderBy:{fetchedAt:"desc"},include:{issues:{select:{issueKey:!0}}}}),u=new Set(l?.issues.map(({issueKey:e})=>e)??[]),c="BOARD"===o.kind?await this.loadBoardSource(os(o),t):await this.loadJqlSource(os(o),t),d={ticketAssignmentFilter:op(o.project.ticketAssignmentFilter),hideCompletedTickets:o.project.hideCompletedTickets,completedStatusIds:s9(o.project.completedStatusIdsJson)},p="ALL"===d.ticketAssignmentFilter?null:await this.currentAccountId(),h=(r={source:os(o),...c},i=d.hideCompletedTickets?new Set(d.completedStatusIds):new Set,a=new Set(r.tickets.filter(e=>i.has(e.statusId)).map(e=>e.status)),n=r.tickets.filter(e=>{let t;return!i.has(e.statusId)&&("ALL"===d.ticketAssignmentFilter||("UNASSIGNED_OR_SELF"===d.ticketAssignmentFilter?null===e.assigneeAccountId||e.assigneeAccountId===p:null!==p&&e.assigneeAccountId===p&&("indeterminate"===(t=e.statusCategory.toLowerCase())||t.includes("progress"))))}),{...r,tickets:n,statusOrder:r.statusOrder.filter(e=>!a.has(e))});return this.workflowEvents&&l&&await Promise.allSettled(h.tickets.filter(({key:e})=>!u.has(e)).map(t=>{let r={ticket:{key:t.key,title:t.summary,type:t.issueType,status:t.status,statusId:t.statusId,statusCategory:t.statusCategory,assignee:t.assignee}};return this.workflowEvents.record({kind:"JIRA_SOURCE_NEW_TICKET",subjectKey:`${e}:${t.key}`,dedupeKey:`jira-source-new:${e}:${t.key}:${h.cache.fetchedAt}`,payload:{...r,sessionData:r,source:{id:e,name:o.name,kind:o.kind},cursorValue:t.key}})})),h}async ticket(e,t=!1,r){let i=s8(e),a=await this.cachedCall({operation:"ISSUE",params:{issueKey:i,fields:"*all",expand:"names,schema"},requestSummary:`Issue ${i} with all fields`,force:t,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getIssue({issueIdOrKey:i,fields:["*all"],expand:["names","schema"],updateHistory:!1})}});"LIVE"===a.source&&await this.storeDetail(a.entryId,a.value,a.fetchedAt);let n=[],s=[],o=0;for(;;){let e=await this.cachedCall({operation:"COMMENTS",params:{issueKey:i,startAt:o,maxResults:100},requestSummary:`Comments for ${i} from ${o}`,force:t,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueComments.getComments({issueIdOrKey:i,startAt:o,maxResults:100,orderBy:"created"})},itemCount:e=>s3(s2(e).comments).length});n.push(e);let r=s2(e.value),a=s3(r.comments);s.push(...a);let l=s6(r.total)??s.length;if(0===a.length||s.length>=l)break;o+=a.length}let l=new Date(Math.min(...n.map(e=>e.fetchedAt.getTime())));await this.storeComments(i,s,l,n.map(e=>e.entryId));let u=await this.requireCredentials(),c=this.normalizeTicketDetail(a.value,s,u.siteUrl,oo(a),ol(n));return await this.recordTicketWorkflowEvents(c,r),c}async assignableUsers(e,t=""){let r=s8(e),i=t.trim().slice(0,100),a=await this.cachedCall({operation:"ASSIGNABLE_USERS",params:{issueKey:r,query:i,maxResults:50},requestSummary:`Assignable users for ${r}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.userSearch.findAssignableUsers({issueKey:r,query:i,maxResults:50,recommend:!0})},itemCount:e=>s3(e).length});return await this.linkCacheEntryToIssue(r,a.entryId),s3(a.value).map(oi).filter(e=>null!==e)}async ticketTransitions(e){let t=s8(e),r=await this.cachedCall({operation:"ISSUE_TRANSITIONS",params:{issueKey:t,expand:"transitions.fields"},requestSummary:`Available transitions for ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getTransitions({issueIdOrKey:t,expand:"transitions.fields"})},itemCount:e=>s3(s2(e).transitions).length});return await this.linkCacheEntryToIssue(t,r.entryId),s3(s2(r.value).transitions).map(s2).filter(e=>!1!==e.isAvailable).flatMap(e=>{let t=s4(e.id),r=s4(e.name);if(!t||!r)return[];let i=s2(e.to),a=s2(i.statusCategory),n=Object.entries(s2(e.fields)).filter(([,e])=>!0===s2(e).required).map(([e,t])=>s4(s2(t).name)??e);return[{id:t,name:r,toStatusId:s4(i.id),toStatus:s4(i.name)??r,toStatusCategory:s4(a.key)??s4(a.name),hasScreen:!0===e.hasScreen,requiredFields:n}]})}async ticketEditFields(e){let t=s8(e),r=await this.cachedCall({operation:"ISSUE_EDIT_META",params:{issueKey:t},requestSummary:`Editable fields for ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getEditIssueMeta({issueIdOrKey:t})},itemCount:e=>Object.keys(s2(s2(e).fields)).length});return await this.linkCacheEntryToIssue(t,r.entryId),Object.entries(s2(s2(r.value).fields)).map(([e,t])=>{let r=s2(t);return{id:e,name:s4(r.name)??e,required:!0===r.required,schemaType:s4(s2(r.schema).type),allowedValues:s3(r.allowedValues).flatMap(e=>{if("string"==typeof e)return[{id:e,name:e}];let t=s2(e),r=s4(t.name)??s4(t.value)??s4(t.displayName)??s4(t.key);return r?[{id:s4(t.id)??s4(t.accountId)??s4(t.value)??r,name:r}]:[]})}}).sort((e,t)=>e.name.localeCompare(t.name))}async ticketChanges(e,t=50,i=0){let a=s8(e),n=this.validatePagination(t,i),s=await this.cachedCall({operation:"ISSUE_CHANGELOG",params:{issueKey:a,startAt:0,maxResults:1},requestSummary:`Changelog count for ${a}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getChangeLogs({issueIdOrKey:a,startAt:0,maxResults:1})},itemCount:e=>s3(s2(e).values).length});await this.linkCacheEntryToIssue(a,s.entryId);let o=s6(s2(s.value).total)??0,l=Math.min(n.limit,Math.max(0,o-n.offset)),u=Math.max(0,o-n.offset-l);if(0===l)return{...n,total:o,items:[],cache:oo(s)};let c=await this.cachedCall({operation:"ISSUE_CHANGELOG",params:{issueKey:a,startAt:u,maxResults:l},requestSummary:`Changelog for ${a} from ${u}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getChangeLogs({issueIdOrKey:a,startAt:u,maxResults:l})},itemCount:e=>s3(s2(e).values).length});await this.linkCacheEntryToIssue(a,c.entryId);let d=s3(s2(c.value).values).map(s2).reverse().map(e=>({id:s4(e.id)??(0,r.randomUUID)(),author:oi(e.author),createdAt:s4(e.created),items:s3(e.items).map(s2).map(e=>({field:s4(e.field)??"Field",fieldId:s4(e.fieldId),from:s4(e.fromString)??s4(e.from),to:s4(e.toString)??s4(e.to)}))}));return{...n,total:o,items:d,cache:ol([s,c])}}async ticketWorklogs(e,t=50,i=0){let a=s8(e),n=this.validatePagination(t,i),s=await this.cachedCall({operation:"ISSUE_WORKLOGS",params:{issueKey:a,startAt:0,maxResults:1},requestSummary:`Worklog count for ${a}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueWorklogs.getIssueWorklog({issueIdOrKey:a,startAt:0,maxResults:1})},itemCount:e=>s3(s2(e).worklogs).length});await this.linkCacheEntryToIssue(a,s.entryId);let o=s6(s2(s.value).total)??0,l=Math.min(n.limit,Math.max(0,o-n.offset)),u=Math.max(0,o-n.offset-l);if(0===l)return{...n,total:o,items:[],cache:oo(s)};let c=await this.cachedCall({operation:"ISSUE_WORKLOGS",params:{issueKey:a,startAt:u,maxResults:l},requestSummary:`Worklogs for ${a} from ${u}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueWorklogs.getIssueWorklog({issueIdOrKey:a,startAt:u,maxResults:l})},itemCount:e=>s3(s2(e).worklogs).length});await this.linkCacheEntryToIssue(a,c.entryId);let d=await this.requireCredentials(),p=s3(s2(c.value).worklogs).map(s2).reverse().map(e=>({id:s4(e.id)??(0,r.randomUUID)(),author:oi(e.author),comment:sZ(e.comment??null,d.siteUrl),timeSpent:s4(e.timeSpent),timeSpentSeconds:s6(e.timeSpentSeconds),startedAt:s4(e.started),createdAt:s4(e.created),updatedAt:s4(e.updated)})),h=p[0];if(this.workflowEvents&&h){let e={ticket:{key:a},worklog:{id:h.id,author:h.author,timeSpent:h.timeSpent,timeSpentSeconds:h.timeSpentSeconds,startedAt:h.startedAt,updatedAt:h.updatedAt}};await this.workflowEvents.record({kind:"JIRA_WORKLOG_ADDED",subjectKey:a,dedupeKey:`jira-worklog:${a}:${h.id}:${c.fetchedAt}`,payload:{...e,sessionData:e,cursorValue:h.id}})}return{...n,total:o,items:p,cache:ol([s,c])}}async addComment(e,t){let r=s8(e);if(!t.value.trim())throw Error("Comment text is required");let i=sY(t);return this.mutateTicket(r,"ADD_COMMENT",async()=>{let{version3:e}=await this.getClients();await e.issueComments.addComment({issueIdOrKey:r,comment:i})})}async assignTicket(e,t){let r=s8(e),i=t?.trim()||null;return this.mutateTicket(r,"ASSIGN_ISSUE",async()=>{let{version3:e}=await this.getClients();await e.issues.assignIssue({issueIdOrKey:r,accountId:i})})}async transitionTicket(e,t){let r=s8(e),i=(await this.ticketTransitions(r)).find(e=>e.id===t);if(!i)throw Error("The Jira transition is not available");if(i.requiredFields.length>0)throw Error(`This transition requires fields that must be completed in Jira: ${i.requiredFields.join(", ")}`);return this.mutateTicket(r,"TRANSITION_ISSUE",async()=>{let{version3:e}=await this.getClients();await e.issues.doTransition({issueIdOrKey:r,transition:{id:i.id}})})}async transitionTicketToConfiguredDone(e){let t=s8(e),r=t.split("-")[0]??"",i=await (0,tD.getPrismaClient)(),a=await i.jiraProject.findUnique({where:{key:r},select:{doneStatusId:!0}});if(!a?.doneStatusId)throw Error(`Configure a done status for Jira project ${r} before using this option`);let n=await this.ticket(t);if(n.statusId===a.doneStatusId)return n;let s=(await this.ticketTransitions(t)).filter(e=>e.toStatusId===a.doneStatusId).sort((e,t)=>e.requiredFields.length-t.requiredFields.length)[0];if(!s)throw Error("Jira does not currently offer a transition to the configured done status");return this.transitionTicket(t,s.id)}async updateTicket(e){let t=s8(e.issueKey),r=new Map((await this.ticketEditFields(t)).map(e=>[e.id,e])),i={},a=e=>{let t=r.get(e);if(!t)throw Error(`${e} is not editable on this ticket`);return t},n=t=>Object.prototype.hasOwnProperty.call(e,t);if(n("summary")){a("summary");let t=e.summary?.trim();if(!t)throw Error("Ticket summary is required");i.summary=t}if(n("description")){let t=a("description");if(null===e.description){if(t.required)throw Error("Description is required");i.description=null}else e.description&&(i.description=sY(e.description))}if(n("priorityId")){let t=a("priority"),r=e.priorityId?.trim()||null;if(!r&&t.required)throw Error("Priority is required");if(r&&t.allowedValues.length>0&&!t.allowedValues.some(e=>e.id===r))throw Error("The selected priority is not available");i.priority=r?{id:r}:null}n("labels")&&(a("labels"),i.labels=[...new Set((e.labels??[]).map(e=>e.trim()).filter(Boolean))]);let s=(t,r)=>{if(!n(t))return;let s=a(r),o=[...new Set(e[t]??[])];if(s.allowedValues.length>0&&o.some(e=>!s.allowedValues.some(t=>t.id===e)))throw Error(`A selected ${s.name} value is not available`);i[r]=o.map(e=>({id:e}))};if(s("componentIds","components"),s("fixVersionIds","fixVersions"),s("affectedVersionIds","versions"),n("dueDate")){let t=a("duedate"),r=e.dueDate?.trim()||null;if(r&&!/^\d{4}-\d{2}-\d{2}$/.test(r))throw Error("Due date must use YYYY-MM-DD");if(!r&&t.required)throw Error("Due date is required");i.duedate=r}if(0===Object.keys(i).length)throw Error("At least one editable Jira field is required");return this.mutateTicket(t,"EDIT_ISSUE",async()=>{let{version3:e}=await this.getClients();await e.issues.editIssue({issueIdOrKey:t,fields:i})})}async createTicket(e){let t=e.projectKey.trim().toUpperCase(),r=e.issueTypeId.trim(),i=e.summary.trim();if(!t||!r||!i)throw Error("Project, issue type, and summary are required");let{version3:a}=await this.getClients(),n=await a.issues.createIssue({fields:{...e.fields??{},project:{key:t},issuetype:{id:r},summary:i,...e.description?{description:sY(e.description)}:{}}});if(!n.key)throw Error("Jira did not return the created issue key");return this.ticket(n.key,!0)}async addWorklog(e){let t=s8(e.issueKey);if(!Number.isInteger(e.timeSpentSeconds)||e.timeSpentSeconds<1)throw Error("Time spent must be a positive number of seconds");let{version3:r}=await this.getClients();return await r.issueWorklogs.addWorklog({issueIdOrKey:t,timeSpentSeconds:e.timeSpentSeconds,started:e.startedAt??new Date().toISOString(),...e.comment?{comment:sY(e.comment)}:{}}),this.ticket(t,!0)}async linkTickets(e){let t=s8(e.inwardIssueKey),r=s8(e.outwardIssueKey),i=e.linkType.trim();if(!i)throw Error("Jira issue link type is required");let{version3:a}=await this.getClients();return await a.issueLinks.linkIssues({type:{name:i},inwardIssue:{key:t},outwardIssue:{key:r}}),this.ticket(t,!0)}async branchTicket(e){let t=s8(e),r=t.replace(/-\d+$/,""),i=await (0,tD.getPrismaClient)(),a=await i.jiraProject.findUnique({where:{key:r},select:{key:!0,branchNamingScript:!0}});if(!a)throw Error(`Jira project ${r} is not managed; add it in Manage Jira projects and sources`);let n=await this.cachedCall({operation:"ISSUE_BRANCH",params:{issueKey:t,fields:["summary","issuetype","project"]},requestSummary:`Branch details for ${t}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issues.getIssue({issueIdOrKey:t,fields:["summary","issuetype","project"],updateHistory:!1})}});await this.linkCacheEntryToIssue(t,n.entryId);let s=s2(n.value.fields);if((s4(s2(s.project).key)??or(n.value))!==a.key)throw Error(`Jira ticket ${t} does not belong to project ${a.key}`);return{ticketKey:n.value.key??t,ticketTitle:s4(s.summary)??t,ticketType:s4(s2(s.issuetype).name),projectKey:a.key,branchNamingScript:a.branchNamingScript??tF}}async clearCache(){let e=await (0,tD.getPrismaClient)();return await e.$transaction([e.jiraCacheEntry.deleteMany(),e.jiraCachedTicket.deleteMany()]),!0}async clearApiCalls(){let e=await (0,tD.getPrismaClient)();return await e.jiraApiCallLog.deleteMany(),!0}async deleteCachedTicket(e){return await this.invalidateIssueCaches(s8(e)),!0}async invalidateIssueCaches(e){let t=await (0,tD.getPrismaClient)(),r=await t.jiraCacheEntryIssue.findMany({where:{issueKey:e},select:{cacheEntryId:!0}});await t.$transaction(async t=>{r.length>0&&await t.jiraCacheEntry.deleteMany({where:{id:{in:r.map(e=>e.cacheEntryId)}}}),await t.jiraCachedTicket.deleteMany({where:{issueKey:e}})})}async refreshCachedTicket(e,t){let r=await (0,tD.getPrismaClient)(),i=await r.jiraCacheEntryIssue.findMany({where:{issueKey:e},select:{cacheEntryId:!0}});return i.length>0&&await r.jiraCacheEntry.deleteMany({where:{id:{in:i.map(e=>e.cacheEntryId)}}}),this.ticket(e,!0,t)}async resolveIssueKeys(e){let t=[...new Set(e.map(e=>e.trim()).filter(Boolean))];if(0===t.length)return[];let{version3:r}=await this.getClients();return[...new Set((await Promise.all(t.map(e=>r.issues.getIssue({issueIdOrKey:e,fields:["key"]})))).map(e=>{let t=s4(e.key);if(!t)throw Error(`Jira issue ${e.id??""} has no key`);return s8(t)}))]}async refreshSprintTickets(e){if(!Number.isSafeInteger(e)||e<=0)throw Error("Invalid Jira sprint ID");let{agile:t}=await this.getClients(),r=[],i=0;for(;r.length<1e3;){let a=Math.min(100,1e3-r.length),n=await t.sprint.getIssuesForSprint({sprintId:e,startAt:i,maxResults:a,fields:["key"]}),s=n.issues??[];r.push(...s.flatMap(e=>{let t=s4(e.key);return t?[s8(t)]:[]}));let o=void 0===n.total?s.length<a:i+s.length>=n.total;if(0===s.length||o)break;i+=s.length}let a=[],n=[...new Set(r)];for(let e=0;e<n.length;e+=5)a.push(...await Promise.all(n.slice(e,e+5).map(e=>this.refreshCachedTicket(e))));return a}async listCachedTickets(e=50,t=0){let r=this.validatePagination(e,t),i=await (0,tD.getPrismaClient)(),[a,n,s]=await Promise.all([i.jiraCachedTicket.findMany({take:r.limit,skip:r.offset,orderBy:{updatedAt:"desc"}}),i.jiraCachedTicket.count(),this.getSettings()]);return{...r,total:n,items:a.map(e=>this.cachedTicketView(e,s.cacheTtlSeconds))}}async cachedTicket(e){let t=await (0,tD.getPrismaClient)(),[r,i]=await Promise.all([t.jiraCachedTicket.findUnique({where:{issueKey:e},include:{cacheEntries:{include:{cacheEntry:!0}}}}),this.getSettings()]);return r?{...this.cachedTicketView(r,i.cacheTtlSeconds),summaryData:s5(r.summaryJson),detailData:s5(r.detailJson),commentsData:s5(r.commentsJson),cacheEntries:r.cacheEntries.map(e=>({id:e.cacheEntry.id,operation:e.cacheEntry.operation,fetchedAt:e.cacheEntry.fetchedAt.toISOString()})).sort((e,t)=>t.fetchedAt.localeCompare(e.fetchedAt))}:null}async listApiCalls(e=50,t=0){let r=this.validatePagination(e,t);await this.pruneLogs();let i=await (0,tD.getPrismaClient)(),[a,n]=await Promise.all([i.jiraApiCallLog.findMany({take:r.limit,skip:r.offset,orderBy:{createdAt:"desc"}}),i.jiraApiCallLog.count()]);return{...r,total:n,items:a.map(e=>({id:e.id,operation:e.operation,requestSummary:e.requestSummary,source:e.source,durationMs:e.durationMs,statusCode:e.statusCode,error:e.error,itemCount:e.itemCount,servedStale:e.servedStale,createdAt:e.createdAt.toISOString()}))}}async cacheMetrics(){await this.pruneLogs();let e=await (0,tD.getPrismaClient)(),t=Date.now(),r=await e.jiraApiCallLog.findMany({where:{createdAt:{gte:new Date(t-s0.at(-1).milliseconds)}},orderBy:{createdAt:"asc"}});return{windows:s0.map(e=>this.metricWindow(e.window,r.filter(r=>r.createdAt.getTime()>=t-e.milliseconds))),operations:[...new Set(r.map(e=>e.operation))].sort().map(e=>({operation:e,windows:s0.map(i=>this.metricWindow(i.window,r.filter(r=>r.operation===e&&r.createdAt.getTime()>=t-i.milliseconds)))}))}}async requireCredentials(){let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:sQ}});if(!t?.siteUrl||!t.email)throw Error("Configure the Jira site, email, and API token in Settings first");let r=await this.credentials.getText(tN.CREDENTIALS.jiraApiToken);if(!r)throw Error("Configure the Jira site, email, and API token in Settings first");return{siteUrl:t.siteUrl,email:t.email,apiToken:r,cacheTtlSeconds:t.cacheTtlSeconds}}async getClients(){let e=await this.requireCredentials(),t=(0,r.createHash)("sha256").update(`${e.siteUrl}\0${e.email}\0${e.apiToken}`).digest("hex");if(this.clients?.key===t)return this.clients;let i={host:e.siteUrl,authentication:{basic:{email:e.email,apiToken:e.apiToken}},baseRequestConfig:{timeout:15e3}};return this.clients={key:t,version3:new tT(i),agile:new q(i)},this.clients}async webhookApiRequest(e,t,r){let i,a=await this.requireCredentials(),n=Buffer.from(`${a.email}:${a.apiToken}`).toString("base64");try{i=await fetch(`${a.siteUrl}${t}`,{method:e,headers:{Accept:"application/json",Authorization:`Basic ${n}`,"Content-Type":"application/json"},body:void 0===r?void 0:JSON.stringify(r),signal:AbortSignal.timeout(15e3)})}catch(e){throw Error(ot(e,a.apiToken))}let s=await i.text();if(!i.ok){let e=s.trim().slice(0,300)||i.statusText;throw Object.assign(Error(ot(`Jira rejected the webhook request with ${i.status}: ${e}`,a.apiToken)),{status:i.status})}if(!s.trim())return null;try{return JSON.parse(s)}catch{return null}}async currentAccountId(){let e=s4(s2((await this.cachedCall({operation:"MYSELF",params:{},requestSummary:"Current Jira user",fetcher:async()=>{let{version3:e}=await this.getClients();return e.myself.getCurrentUser()}})).value).accountId);if(!e)throw Error("Jira did not return the current user ID");return e}async linkCacheEntryToIssue(e,t){let r=await (0,tD.getPrismaClient)();await r.$transaction(async r=>{await r.jiraCachedTicket.upsert({where:{issueKey:e},create:{issueKey:e,projectKey:e.replace(/-\d+$/,"")},update:{}}),await r.jiraCacheEntryIssue.upsert({where:{cacheEntryId_issueKey:{cacheEntryId:t,issueKey:e}},create:{cacheEntryId:t,issueKey:e},update:{}})})}async mutateTicket(e,t,r){let i=await this.requireCredentials(),a=Date.now();try{await r(),await this.logCall({operation:t,requestSummary:`${t.replaceAll("_"," ")} for ${e}`,source:"LIVE",durationMs:Date.now()-a})}catch(n){let r=ot(n,i.apiToken);throw await this.logCall({operation:t,requestSummary:`${t.replaceAll("_"," ")} for ${e}`,source:"ERROR",durationMs:Date.now()-a,statusCode:oe(n),error:r}),Error(r)}await this.invalidateIssueCaches(e);try{return await this.ticket(e,!0)}catch(e){throw Error(`Jira accepted the update, but refreshed ticket details could not be loaded: ${ot(e,i.apiToken)}`)}}cacheKey(e,t,i){return(0,r.createHash)("sha256").update(s7({siteUrl:e,operation:t,params:i})).digest("hex")}async cachedCall(e){let t=await this.requireCredentials(),i=await (0,tD.getPrismaClient)(),a=this.cacheKey(t.siteUrl,e.operation,e.params),n=Date.now(),s=await i.jiraCacheEntry.findUnique({where:{cacheKey:a}}),o=null!==s&&Date.now()-s.fetchedAt.getTime()<1e3*t.cacheTtlSeconds;if(!e.force&&o)return await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"CACHE",durationMs:Date.now()-n,itemCount:e.itemCount?.(s5(s.responseJson))??null,sourceId:e.sourceId}),{value:s5(s.responseJson),source:"CACHE",stale:!1,fetchedAt:s.fetchedAt,entryId:s.id};let l=this.inFlight.get(a);if(l){let t=await l;return await this.logCall({operation:e.operation,requestSummary:`${e.requestSummary} (coalesced)`,source:"CACHE",durationMs:Date.now()-n,itemCount:e.itemCount?.(t.value)??null,sourceId:e.sourceId}),{...t,source:"CACHE"}}let u=(async()=>{try{let t=await e.fetcher(),s=new Date,o=await i.jiraCacheEntry.upsert({where:{cacheKey:a},create:{id:(0,r.randomUUID)(),cacheKey:a,operation:e.operation,paramsJson:s7(e.params),responseJson:JSON.stringify(t),fetchedAt:s,sourceId:e.sourceId??null},update:{operation:e.operation,paramsJson:s7(e.params),responseJson:JSON.stringify(t),fetchedAt:s,sourceId:e.sourceId??null}});return await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"LIVE",durationMs:Date.now()-n,itemCount:e.itemCount?.(t)??null,sourceId:e.sourceId}),{value:t,source:"LIVE",stale:!1,fetchedAt:s,entryId:o.id}}catch(i){let r=null!==s&&!1!==e.allowStaleOnError;if(await this.logCall({operation:e.operation,requestSummary:e.requestSummary,source:"ERROR",durationMs:Date.now()-n,statusCode:oe(i),error:ot(i,t.apiToken),servedStale:r,sourceId:e.sourceId}),r)return{value:s5(s.responseJson),source:"ERROR",stale:!0,fetchedAt:s.fetchedAt,entryId:s.id};throw Error(ot(i,t.apiToken))}})();this.inFlight.set(a,u);try{return await u}finally{this.inFlight.delete(a)}}async logCall(e){if(!this.recordCallLogs)return;let t=await (0,tD.getPrismaClient)();await t.jiraApiCallLog.create({data:{id:(0,r.randomUUID)(),operation:e.operation,requestSummary:e.requestSummary.slice(0,1e3),source:e.source,durationMs:Math.max(0,Math.round(e.durationMs)),statusCode:e.statusCode??null,error:e.error??null,itemCount:e.itemCount??null,servedStale:e.servedStale??!1,sourceId:e.sourceId??null}})}validateSourceName(e){let t=e.trim();if(!t||t.length>100)throw Error("Source name must be 1 to 100 characters");return t}async validateSource(e,t){let r=t.trim();if(!r)throw Error("BOARD"===e?"Board URL is required":"JQL is required");if("JQL"===e)return await this.cachedCall({operation:"JQL_VALIDATE",params:{jql:r},requestSummary:`Validate JQL: ${r}`,fetcher:async()=>{let{version3:e}=await this.getClients();return e.issueSearch.searchForIssuesUsingJqlEnhancedSearch({jql:r,maxResults:1,fields:["key"],failFast:!0})}}),{value:r,boardId:null};let i=function(e,t){let r=new URL(e.trim());if(r.origin!==new URL(t).origin)throw Error("Board URL must belong to the configured Jira site");let i=r.pathname.match(/\/boards\/(\d+)(?:\/|$)/i),a=r.searchParams.get("rapidView"),n=Number(i?.[1]??a);if(!Number.isSafeInteger(n)||n<=0)throw Error("Board URL must contain a Jira board ID");return{boardId:n,normalizedUrl:r.toString()}}(r,(await this.requireCredentials()).siteUrl);return await this.cachedCall({operation:"BOARD",params:{boardId:i.boardId},requestSummary:`Board ${i.boardId}`,fetcher:async()=>{let{agile:e}=await this.getClients();return e.board.getBoard({boardId:i.boardId})}}),{value:i.normalizedUrl,boardId:i.boardId}}async loadJqlSource(e,t){let r,i=[],a=[],n=[],s=!1;do{let o=Math.min(100,1e3-i.length),l=await this.cachedCall({operation:"JQL_SEARCH",params:{jql:e.value,nextPageToken:r??null,maxResults:o,fields:sX},requestSummary:`JQL ${e.name}${r?" next page":""}`,sourceId:e.id,force:t,fetcher:async()=>{let{version3:t}=await this.getClients();return t.issueSearch.searchForIssuesUsingJqlEnhancedSearch({jql:e.value,nextPageToken:r,maxResults:o,fields:sX})},itemCount:e=>e.issues?.length??0});a.push(l);let u=l.value.issues??[];i.push(...u),n.push(...l.value.warningMessages??[]),"LIVE"===l.source&&await this.storeSummaries(l.entryId,u,l.fetchedAt),r=l.value.nextPageToken,i.length>=1e3&&r&&(s=!0)}while(r&&i.length<1e3)return this.buildBoardResult(i,a,n,s)}async loadBoardSource(e,t){if(!e.boardId)throw Error("Saved board source has no board ID");let r=await this.cachedCall({operation:"BOARD",params:{boardId:e.boardId},requestSummary:`Board ${e.boardId}`,sourceId:e.id,force:t,fetcher:async()=>{let{agile:t}=await this.getClients();return t.board.getBoard({boardId:e.boardId})}}),i=await this.cachedCall({operation:"BOARD_CONFIGURATION",params:{boardId:e.boardId},requestSummary:`Board ${e.boardId} configuration`,sourceId:e.id,force:t,fetcher:async()=>{let{agile:t}=await this.getClients();return t.board.getConfiguration({boardId:e.boardId})}}),a=[r,i],n=[],s=[],o=!1;if("scrum"===(s4(r.value.type)??"").toLowerCase()){let r=await this.cachedCall({operation:"SPRINTS",params:{boardId:e.boardId,state:"active"},requestSummary:`Active sprints for board ${e.boardId}`,sourceId:e.id,force:t,fetcher:async()=>{let{agile:t}=await this.getClients();return t.board.getAllSprints({boardId:e.boardId,state:"active",startAt:0,maxResults:100})},itemCount:e=>s3(e.values).length});a.push(r);let i=s3(r.value.values).map(s2);for(let r of(0===i.length&&s.push("This Scrum board has no active sprint."),i)){let i=s6(r.id);if(!i||n.length>=1e3)continue;let l=await this.loadAgileIssues("SPRINT_ISSUES",e,t,(e,t)=>({sprintId:i,startAt:e,maxResults:t,fields:sX}),async e=>{let{agile:t}=await this.getClients();return t.sprint.getIssuesForSprint(e)},n.length);n.push(...l.issues),a.push(...l.results),s.push(...l.warnings),o||=l.truncated}}else{let r=await this.loadAgileIssues("BOARD_ISSUES",e,t,(t,r)=>({boardId:e.boardId,startAt:t,maxResults:r,fields:sX}),async e=>{let{agile:t}=await this.getClients();return t.board.getIssuesForBoard(e)},0);n.push(...r.issues),a.push(...r.results),s.push(...r.warnings),o=r.truncated}let l=[...new Map(n.map(e=>[e.key??e.id,e])).values()],u=new Map;return s3(s2(i.value.columnConfig).columns).map(s2).forEach((e,t)=>{s3(e.statuses).map(s2).forEach(e=>{let r=s4(e.id);r&&u.set(r,t)})}),this.buildBoardResult(l,a,s,o,u)}async loadAgileIssues(e,t,r,i,a,n){let s=[],o=[],l=[],u=0,c=1/0,d=!1;for(;u<c&&s.length+n<1e3;){let d=i(u,Math.min(100,1e3-n-s.length)),p=await this.cachedCall({operation:e,params:d,requestSummary:`${e.replaceAll("_"," ")} from ${u}`,sourceId:t.id,force:r,fetcher:()=>a(d),itemCount:e=>e.issues?.length??0});o.push(p);let h=p.value.issues??[];if(s.push(...h),l.push(...p.value.warningMessages??[]),"LIVE"===p.source&&await this.storeSummaries(p.entryId,h,p.fetchedAt),c=p.value.total??s.length,0===h.length)break;u+=h.length}return s.length+n>=1e3&&u<c&&(d=!0),{issues:s,results:o,warnings:l,truncated:d}}buildBoardResult(e,t,r,i,a){let n=e.slice(0,1e3).map(ou),s=[...new Map(n.map(e=>[e.status,e])).values()];return s.sort((e,t)=>{let r=a?.get(e.statusId),i=a?.get(t.statusId);return void 0!==r||void 0!==i?(r??Number.MAX_SAFE_INTEGER)-(i??Number.MAX_SAFE_INTEGER):oc(e.statusCategory)-oc(t.statusCategory)||e.status.localeCompare(t.status)}),{tickets:n,statusOrder:s.map(e=>e.status),cache:ol(t),truncated:i,warnings:[...new Set(r)]}}async storeSummaries(e,t,r){let i=await (0,tD.getPrismaClient)();await i.$transaction(async i=>{for(let e of t)e.key&&await i.jiraCachedTicket.upsert({where:{issueKey:e.key},create:{issueKey:e.key,projectKey:or(e),summaryJson:JSON.stringify(e),summaryFetchedAt:r},update:{projectKey:or(e),summaryJson:JSON.stringify(e),summaryFetchedAt:r}});await i.jiraCacheEntryIssue.deleteMany({where:{cacheEntryId:e}});let a=[...new Set(t.map(e=>e.key).filter(Boolean))];a.length>0&&await i.jiraCacheEntryIssue.createMany({data:a.map(t=>({cacheEntryId:e,issueKey:t}))})})}async storeDetail(e,t,r){if(!t.key)throw Error("Jira detail response did not include an issue key");let i=await (0,tD.getPrismaClient)();await i.$transaction(async i=>{await i.jiraCachedTicket.upsert({where:{issueKey:t.key},create:{issueKey:t.key,projectKey:or(t),detailJson:JSON.stringify(t),detailFetchedAt:r},update:{projectKey:or(t),detailJson:JSON.stringify(t),detailFetchedAt:r}}),await i.jiraCacheEntryIssue.upsert({where:{cacheEntryId_issueKey:{cacheEntryId:e,issueKey:t.key}},create:{cacheEntryId:e,issueKey:t.key},update:{}})})}async storeComments(e,t,r,i){let a=await (0,tD.getPrismaClient)();await a.$transaction(async a=>{for(let n of(await a.jiraCachedTicket.upsert({where:{issueKey:e},create:{issueKey:e,projectKey:e.split("-")[0]??"UNKNOWN",commentsJson:JSON.stringify(t),commentsFetchedAt:r},update:{commentsJson:JSON.stringify(t),commentsFetchedAt:r}}),i))await a.jiraCacheEntryIssue.upsert({where:{cacheEntryId_issueKey:{cacheEntryId:n,issueKey:e}},create:{cacheEntryId:n,issueKey:e},update:{}})})}normalizeTicketDetail(e,t,i,a,n){let s=ou(e),o=s2(e.fields),l=s2(e.names),u=s2(e.schema),c=[];for(let e of s3(o.issuelinks).map(s2)){let t=s2(e.type),r=on(e.outwardIssue,s4(t.outward)??"relates to"),i=on(e.inwardIssue,s4(t.inward)??"relates to");r&&c.push(r),i&&c.push(i)}let d=on(o.parent,"parent"),p=s3(o.subtasks).map(e=>on(e,"subtask")).filter(e=>null!==e),h=s3(o.sprint).map(s2),m=s3(o.closedSprints).map(s2),f=h.filter(e=>{let t=s4(e.state)?.toLowerCase();return!t||"active"===t}).map(e=>s4(e.name)).filter(e=>!!e),g=m.concat(h.filter(e=>s4(e.state)?.toLowerCase()==="closed")).map(e=>s4(e.name)).filter(e=>!!e),y=f.concat(g),w=t.map(s2).map(e=>({id:s4(e.id)??(0,r.randomUUID)(),author:oi(e.author),body:e.body??null,content:sZ(e.body??null,i),createdAt:s4(e.created),updatedAt:s4(e.updated)}));return{...s,jiraUrl:`${i}/browse/${s.key}`,description:o.description??null,descriptionContent:sZ(o.description??null,i),reporter:oi(o.reporter),creator:oi(o.creator),labels:s3(o.labels).filter(e=>"string"==typeof e),components:oa(o.components),fixVersions:oa(o.fixVersions),affectedVersions:oa(o.versions),sprintNames:[...new Set(y)],activeSprintNames:[...new Set(f)],closedSprintNames:[...new Set(g)],parent:d,subtasks:p,issueLinks:c,attachments:s3(o.attachment).map(s2).map(e=>({id:s4(e.id)??(0,r.randomUUID)(),filename:s4(e.filename)??"Attachment",contentUrl:s4(e.content),mimeType:s4(e.mimeType),size:s6(e.size),author:oi(e.author),createdAt:s4(e.created)})),comments:w,createdAt:s4(o.created),dueAt:s4(o.duedate),resolvedAt:s4(o.resolutiondate),timeTracking:o.timetracking??null,allFields:Object.entries(o).map(([e,t])=>{let r=s2(u[e]),a="string"==typeof t||s1(t)&&"doc"===t.type?sZ(t,i):null;return{id:e,name:s4(l[e])??e,schemaType:s4(r.type),custom:!0===r.custom||e.startsWith("customfield_"),value:t??null,content:a}}).sort((e,t)=>e.name.localeCompare(t.name)),cache:a,commentsCache:n}}cachedTicketView(e,t){let r=ou(s2(s5(e.detailJson)??s5(e.summaryJson))),i=e.detailJson&&e.commentsJson?"FULL":e.detailJson?"DETAIL":"SUMMARY",a=[e.summaryFetchedAt,e.detailFetchedAt,e.commentsFetchedAt].filter(e=>null!==e).some(e=>Date.now()-e.getTime()>=1e3*t);return{issueKey:e.issueKey,projectKey:e.projectKey,summary:r.summary,status:"Unknown"===r.status?null:r.status,coverage:i,stale:a,summaryFetchedAt:e.summaryFetchedAt?.toISOString()??null,detailFetchedAt:e.detailFetchedAt?.toISOString()??null,commentsFetchedAt:e.commentsFetchedAt?.toISOString()??null,updatedAt:e.updatedAt.toISOString()}}validatePagination(e,t){if(!Number.isInteger(e)||e<1||e>100)throw Error("Pagination limit must be from 1 to 100");if(!Number.isInteger(t)||t<0)throw Error("Pagination offset must be non-negative");return{limit:e,offset:t}}metricWindow(e,t){return{window:e,total:t.length,live:t.filter(e=>"LIVE"===e.source).length,cache:t.filter(e=>"CACHE"===e.source).length,errors:t.filter(e=>"ERROR"===e.source).length,averageMs:0===t.length?0:Math.round(t.reduce((e,t)=>e+t.durationMs,0)/t.length)}}async pruneLogs(){let e=Date.now();if(e-this.lastPrunedAt<36e5)return;this.lastPrunedAt=e;let t=await (0,tD.getPrismaClient)();await t.jiraApiCallLog.deleteMany({where:{createdAt:{lt:new Date(e-2592e6)}}})}}],126223);var oh=e.i(661983);let om="default",of=/^[A-Z][A-Z0-9_]*-\d+$/,og=new Set(["jira:issue_created","jira:issue_updated","comment_created","comment_updated","comment_deleted","worklog_created","worklog_updated","worklog_deleted","jira:worklog_updated","attachment_created","attachment_deleted","issuelink_created","issuelink_deleted","sprint_started","sprint_closed"]),oy={"jira:issue_created":"JIRA_ISSUE_CREATED","jira:issue_deleted":"JIRA_ISSUE_DELETED",comment_created:"JIRA_ISSUE_COMMAND",attachment_created:"JIRA_ATTACHMENT_ADDED",issuelink_created:"JIRA_ISSUE_LINKED"},ow="/api/public/jira/webhook",ob="/rest/webhooks/1.0/webhook",ov=new Set(["localhost","0.0.0.0","::1","[::1]",""]),ok=["jira:issue_created","jira:issue_updated","jira:issue_deleted","comment_created","worklog_created","attachment_created","issuelink_created","sprint_started","sprint_closed"];class oS extends Error{httpStatus;constructor(e,t){super(e),this.httpStatus=t,this.name="JiraWebhookRequestError"}}function oE(e){return"string"==typeof e&&e.trim()?e.trim():null}function oI(e){return"string"==typeof e?e.length?e:null:"number"==typeof e||"boolean"==typeof e?String(e):null}function ox(e){let t=oA(e);if(!t)return null;let r=Array.isArray(t.items)?t.items:[];return{id:oI(t.id),items:r.map(oA).filter(e=>null!==e).map(e=>({field:oE(e.field)??oE(e.fieldId)??"Field",fieldId:oE(e.fieldId),fieldType:oE(e.fieldtype)??oE(e.fieldType),from:oI(e.from),fromString:oI(e.fromString),to:oI(e.to),toString:oI(e.toString)}))}}function oA(e){return"object"!=typeof e||null===e||Array.isArray(e)?null:e}function o_(e){return"object"==typeof e&&null!==e&&"status"in e&&"number"==typeof e.status?e.status:null}function oC(e){let t=oA(e);return t?{accountId:oE(t.accountId),displayName:oE(t.displayName)}:null}function oR(e){return{deliveryId:e.deliveryId,event:e.event,issueKey:e.issueKey,projectKey:e.projectKey,changelog:function(e){if(!e)return null;try{return ox(JSON.parse(e))}catch{return null}}(e.changelogJson),retryCount:e.retryCount,outcome:e.outcome,error:e.error,receivedAt:e.receivedAt.toISOString(),processedAt:e.processedAt?.toISOString()??null}}e.s(["JiraWebhookRequestError",0,oS,"JiraWebhookService",0,class{jira;credentials;workflowEvents;constructor(e,t,r){this.jira=e,this.credentials=t,this.workflowEvents=r}async webhooksEnabled(){let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:om},select:{webhookEnabled:!0}});return!!t?.webhookEnabled&&this.credentials.isConfigured(tN.CREDENTIALS.jiraWebhookSecret)}async getWebhookSettings(){let e=await (0,tD.getPrismaClient)(),[t,r,i]=await Promise.all([e.jiraSettings.upsert({where:{id:om},create:{id:om},update:{}}),this.credentials.isConfigured(tN.CREDENTIALS.jiraWebhookSecret),e.jiraWebhookDelivery.findFirst({orderBy:[{receivedAt:"desc"},{deliveryId:"desc"}]})]);return{enabled:t.webhookEnabled&&r,secretConfigured:r,registered:!!t.webhookId,registrationId:t.webhookId??null,registeredUrl:t.webhookUrl??null,jql:t.webhookJql??null,configuredAt:t.webhookConfiguredAt?.toISOString()??null,lastReceivedAt:i?.receivedAt.toISOString()??null,lastOutcome:i?.outcome??null,lastError:i?.error??null}}async enableWebhook(){let e=(0,r.randomBytes)(32).toString("base64url");return await this.credentials.setText(tN.CREDENTIALS.jiraWebhookSecret,e,async e=>{await e.jiraSettings.upsert({where:{id:om},create:{id:om,webhookEnabled:!0,webhookConfiguredAt:new Date},update:{webhookEnabled:!0,webhookConfiguredAt:new Date}})}),{settings:await this.getWebhookSettings(),secret:e}}async registerWebhook(e){let t=function(e){let t;try{t=new URL(e.trim())}catch{throw Error("Enter the public URL of this server")}if("https:"!==t.protocol&&"http:"!==t.protocol)throw Error("The webhook URL must use HTTP or HTTPS");if(t.username||t.password||t.search||t.hash)throw Error("The webhook URL must not include credentials, query, or fragment");let r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(ov.has(r)||r.endsWith(".local")||r.endsWith(".localhost")||/^127\./.test(r)||/^10\./.test(r)||/^192\.168\./.test(r)||/^172\.(1[6-9]|2\d|3[01])\./.test(r))throw Error(`Jira cannot reach ${t.host}. Expose this server publicly, or set PUBLIC_BASE_URL to its public address.`);let i=t.pathname.replace(/\/+$/,"");if(!i)return`${t.origin}${ow}`;if(i.endsWith(ow))return`${t.origin}${i}`;throw Error(`The webhook URL must end with ${ow}`)}(e.url),i=e.jql?.trim()||null,a=(0,r.randomBytes)(32).toString("base64url"),n=await (0,tD.getPrismaClient)(),s=await n.jiraSettings.findUnique({where:{id:om},select:{webhookId:!0}}),o=await this.writeToJira({webhookId:s?.webhookId??null,url:t,jql:i,secret:a});return await this.credentials.setText(tN.CREDENTIALS.jiraWebhookSecret,a,async e=>{await e.jiraSettings.upsert({where:{id:om},create:{id:om,webhookEnabled:!0,webhookConfiguredAt:new Date,webhookId:o,webhookUrl:t,webhookJql:i},update:{webhookEnabled:!0,webhookConfiguredAt:new Date,webhookId:o,webhookUrl:t,webhookJql:i}})}),{settings:await this.getWebhookSettings(),secret:a}}async rotateSecret(){if(!await this.credentials.isConfigured(tN.CREDENTIALS.jiraWebhookSecret))throw Error("The Jira webhook is not configured");let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:om},select:{webhookId:!0,webhookUrl:!0,webhookJql:!0}});return t?.webhookId&&t.webhookUrl?this.registerWebhook({url:t.webhookUrl,jql:t.webhookJql}):this.enableWebhook()}async disableWebhook(){let e=await (0,tD.getPrismaClient)(),t=await e.jiraSettings.findUnique({where:{id:om},select:{webhookId:!0}});return t?.webhookId&&await this.deleteFromJira(t.webhookId),await this.credentials.delete(tN.CREDENTIALS.jiraWebhookSecret,async e=>{await e.jiraSettings.upsert({where:{id:om},create:{id:om},update:{webhookEnabled:!1,webhookConfiguredAt:null,webhookId:null,webhookUrl:null,webhookJql:null}})}),this.getWebhookSettings()}async writeToJira(e){let t,r,i={name:"AI Development Environment",description:"Registered by AI Development Environment. Drives Jira workflow triggers and live ticket updates.",url:e.url,events:[...ok],excludeBody:!1,secret:e.secret,...e.jql?{filters:{"issue-related-events-section":e.jql}}:{}};if(e.webhookId){let t=`${ob}/${encodeURIComponent(e.webhookId)}`;try{return await this.jira.webhookApiRequest("PUT",t,i),e.webhookId}catch(e){if(404!==o_(e))throw e}}let a=await this.jira.webhookApiRequest("POST",ob,i),n=(t=oE(a?.self),(r=t?.match(/\/webhook\/([^/]+)\/?$/)?.[1])?decodeURIComponent(r):null);if(!n)throw Error("Jira did not return the ID of the new webhook");return n}async deleteFromJira(e){try{await this.jira.webhookApiRequest("DELETE",`${ob}/${encodeURIComponent(e)}`)}catch(e){if(404!==o_(e))throw e}}async deliveries(e=50,t=0){if(!Number.isInteger(e)||e<1||e>100)throw Error("Limit must be an integer from 1 to 100");if(!Number.isInteger(t)||t<0)throw Error("Offset must be a non-negative integer");let r=await this.webhooksEnabled();if(!r)return{enabled:r,items:[],total:0,limit:e,offset:t};let i=await (0,tD.getPrismaClient)(),[a,n]=await Promise.all([i.jiraWebhookDelivery.findMany({orderBy:[{receivedAt:"desc"},{deliveryId:"desc"}],take:e,skip:t}),i.jiraWebhookDelivery.count()]);return{enabled:r,items:a.map(oR),total:n,limit:e,offset:t}}async clearDeliveries(){let e=await (0,tD.getPrismaClient)();return await e.jiraWebhookDelivery.deleteMany(),!0}async prune(){let e=await (0,tD.getPrismaClient)();await e.jiraWebhookDelivery.deleteMany({where:{receivedAt:{lt:new Date(Date.now()-2592e6)}}})}async handleWebhook(e){var t,i,a,n,s,o;let l,u,c=await this.credentials.getText(tN.CREDENTIALS.jiraWebhookSecret);if(!c)throw new oS("Jira webhook is not configured",503);if(!e.signature?.startsWith("sha256="))throw new oS("Jira webhook signature is missing",401);if(t=`sha256=${(0,r.createHmac)("sha256",c).update(e.body).digest("hex")}`,i=e.signature,l=Buffer.from(t),u=Buffer.from(i),!(l.length===u.length&&(0,r.timingSafeEqual)(l,u)))throw new oS("Jira webhook signature is invalid",401);if(!e.deliveryId?.trim())throw new oS("Jira delivery ID is missing",400);let d=await (0,tD.getPrismaClient)(),p=e.deliveryId.trim(),h=Number.parseInt(e.retryCount??"",10),m=Number.isInteger(h)?h:null;try{await d.jiraWebhookDelivery.create({data:{deliveryId:p,event:"unknown",outcome:"RECEIVED",retryCount:m}})}catch(e){if(!("object"==typeof e&&null!==e&&"code"in e&&"P2002"===e.code))throw e;if(0===(await d.jiraWebhookDelivery.updateMany({where:{deliveryId:p,outcome:{notIn:["PROCESSED","IGNORED"]}},data:{event:"unknown",issueKey:null,projectKey:null,changelogJson:null,retryCount:m,outcome:"RECEIVED",error:null,receivedAt:new Date,processedAt:null}})).count)return await this.prune().catch(()=>void 0),{outcome:"DUPLICATE",event:null,issueKey:null,triggersRecorded:0}}let f=async(e,t=null)=>{let r=await d.jiraWebhookDelivery.update({where:{deliveryId:p},data:{outcome:e,error:t,processedAt:new Date}});oh.agentEventBus.publish(oh.JIRA_WEBHOOK_DELIVERY_TOPIC,{jiraWebhookDeliveryChanged:oR(r)})};try{let t,r,i,l,u,c;try{let r=JSON.parse(Buffer.from(e.body).toString("utf8")),i=oA(r);if(!i)throw Error("Payload is not an object");t=i}catch{throw new oS("Jira webhook payload is invalid JSON",400)}let h=oE(t.webhookEvent),g=(a=t,r=oA(a.issue),(i=oE(r?.key)?.toUpperCase()??null)&&of.test(i)?i:null),y=(n=t,l=oA(n.issue),u=oA(l?.fields),c=oA(u?.project)??oA(n.project),oE(c?.key)?.toUpperCase()??null),w=ox(t.changelog);if(await d.jiraWebhookDelivery.update({where:{deliveryId:p},data:{event:h??"unknown",issueKey:g,projectKey:y,changelogJson:w?JSON.stringify(w):null}}),!h)return await f("IGNORED","Payload has no webhookEvent"),{outcome:"IGNORED",event:h,issueKey:g,triggersRecorded:0};if(!(og.has(h)||"jira:issue_deleted"===h))return await f("IGNORED",`Unhandled Jira event ${h}`),{outcome:"IGNORED",event:h,issueKey:g,triggersRecorded:0};let b=g?[g]:[];if("issuelink_created"===h||"issuelink_deleted"===h){let e,r,i=(s=t,e=oA(s.issueLink),[oI(e?.sourceIssueId),oI(e?.destinationIssueId)].filter((e,t,r)=>!!(e&&r.indexOf(e)===t)));if(0===i.length)return await f("IGNORED","Payload has no issue-link issue IDs"),{outcome:"IGNORED",event:h,issueKey:g,triggersRecorded:0};y=(g=(b=await this.jira.resolveIssueKeys(i))[0]??null)?y??((r=(o=g).lastIndexOf("-"))>0?o.slice(0,r):null):y,await d.jiraWebhookDelivery.update({where:{deliveryId:p},data:{issueKey:g,projectKey:y}})}let v="sprint_started"===h||"sprint_closed"===h;if(!v&&!g)return await f("IGNORED","Payload has no issue key"),{outcome:"IGNORED",event:h,issueKey:g,triggersRecorded:0};let k=[];if("jira:issue_deleted"===h)await this.jira.deleteCachedTicket(g),k.push({key:g,projectKey:y});else if(v){let e=function(e){let t=oI(oA(e.sprint)?.id);if(!t)return null;let r=Number(t);return Number.isSafeInteger(r)&&r>0?r:null}(t);if(!e)return await f("IGNORED","Payload has no valid sprint ID"),{outcome:"IGNORED",event:h,issueKey:g,triggersRecorded:0};let r=await this.jira.refreshSprintTickets(e);k.push(...r.map(e=>({key:e.key,projectKey:e.projectKey})))}else if("jira:issue_updated"===h){let e=await this.jira.refreshCachedTicket(g,w);k.push({key:e.key,projectKey:e.projectKey})}else if(og.has(h)){let e=await Promise.all(b.map(e=>this.jira.refreshCachedTicket(e)));k.push(...e.map(e=>({key:e.key,projectKey:e.projectKey})))}let S=g?await this.recordWebhookTrigger({event:h,deliveryId:p,issueKey:g,projectKey:y,retries:m,payload:t}):0;for(let e of k)oh.agentEventBus.publish(oh.JIRA_TICKET_CHANGED_TOPIC,{jiraTicketChanged:{issueKey:e.key,projectKey:e.projectKey,event:h}});return await f("PROCESSED"),{outcome:"PROCESSED",event:h,issueKey:g,triggersRecorded:S}}catch(t){let e=t instanceof Error?t.message:String(t);throw await f("ERROR",e),t}finally{await this.prune().catch(()=>void 0)}}async recordWebhookTrigger(e){if(!this.workflowEvents)return 0;let t=oy[e.event];if(!t)return 0;let{payload:r}=e,i=oA(r.issue),a=oA(i?.fields),n=oA(r.comment),s=oA(r.attachment),o=oA(r.issueLink),l=oA(a?.status),u=ox(r.changelog),c={ticket:{key:e.issueKey,title:oE(a?.summary),type:oE(oA(a?.issuetype)?.name),status:oE(l?.name),statusId:oE(l?.id),statusCategory:oE(oA(l?.statusCategory)?.key),assignee:oE(oA(a?.assignee)?.displayName),assigneeAccountId:oE(oA(a?.assignee)?.accountId),labels:Array.isArray(a?.labels)?a.labels:[],projectKey:e.projectKey,url:null},comment:n?{id:oE(n.id),body:oE(n.body)??"",author:oC(n.author)}:null,attachment:s?{id:oE(s.id),filename:oE(s.filename),mimeType:oE(s.mimeType),author:oC(s.author)}:null,link:o?{id:oE(o.id),type:oE(oA(o.issueLinkType)?.name),sourceIssueId:oE(o.sourceIssueId),destinationIssueId:oE(o.destinationIssueId)}:null,user:oC(r.user),changelog:u};return+!!await this.workflowEvents.record({kind:t,subjectKey:e.issueKey,dedupeKey:`jira-webhook-trigger:${e.deliveryId}:${t}`,payload:{...c,sessionData:c,cursorValue:`${e.deliveryId}:${t}`,webhook:{event:e.event,deliveryId:e.deliveryId,retryCount:e.retries}}})}},"subscribeJiraTicketChanges",0,function(){return oh.agentEventBus.iterate(oh.JIRA_TICKET_CHANGED_TOPIC)},"subscribeJiraWebhookDeliveries",0,function(){return oh.agentEventBus.iterate(oh.JIRA_WEBHOOK_DELIVERY_TOPIC)}],642983),e.s([],151666)},984179,e=>{"use strict";let t=new Set(["QUEUED","PREPARING","RUNNING"]);e.s(["buildOutOfDate",0,function(e){let r;if(t.has(e.status)||!e.worktree||(e.worktree._count?.builds??0)>0||e.finishedAt&&(!e.worktree.lastCheckedAt||e.worktree.lastCheckedAt<e.finishedAt))return!1;try{r=JSON.parse(e.snapshotJson)}catch{return!1}if(!r||"object"!=typeof r||Array.isArray(r))return!1;let i=r.worktree;if(!i||"object"!=typeof i||Array.isArray(i))return!1;if("string"==typeof i.codeStateHash&&e.worktree.codeStateHash)return i.codeStateHash!==e.worktree.codeStateHash;if("string"==typeof i.headSha&&e.worktree.headSha!==i.headSha)return!0;if("boolean"==typeof i.hasStagedChanges){if(i.hasStagedChanges!==e.worktree.hasStagedChanges)return!0}else if(e.worktree.hasStagedChanges)return!0;return"boolean"==typeof i.hasUnstagedChanges?i.hasUnstagedChanges!==e.worktree.hasUnstagedChanges:e.worktree.hasUnstagedChanges}])},396763,504173,518733,925991,e=>{"use strict";var t=e.i(666680),r=e.i(885418),i=e.i(243783);e.i(805422);var a=e.i(694355),n=e.i(661983),s=e.i(750227),o=e.i(184015),l=e.i(119909),u=e.i(988349),c=e.i(497800),d=e.i(835544),p=e.i(499162);e.i(107058);var h=e.i(963910);e.i(151666);var m=e.i(468399),f=e.i(984179);let g="default",y=["QUEUED","RUNNING"],w=["PUSHING","CHECKING_OUT","AWAITING_STASH","CLEANING_UP"],b=["gray","stone","red","rose","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink"],v={codebase:{include:{agent:!0,repository:{include:{projects:{where:{type:"IOS_APP"},include:{configurations:{select:{id:!0}}}}}},jobs:{where:{status:{in:y}},orderBy:{createdAt:"desc"},take:1}}},tags:{include:{tag:!0}},builds:{orderBy:{createdAt:"desc"},take:1,select:{id:!0,status:!0,action:!0,destinationType:!0,destinationJson:!0,snapshotJson:!0,createdAt:!0,finishedAt:!0,artifacts:{select:{id:!0,kind:!0}}}},autoSync:!0,autoMerge:!0,pullRequest:!0,_count:{select:{builds:{where:{status:{in:["QUEUED","PREPARING","RUNNING"]}}}}}};function k(e){return null!==e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(e)&&null===e.disconnectedAt}function S(e){try{let t=JSON.parse(e.capabilitiesJson);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function E(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function I(e,t){if(!e||!t)return null;try{let r=RegExp(t,"i").exec(e),i=(r?.[1]??r?.[0])?.trim();return i?i.toUpperCase():null}catch{return null}}function x(e,t){return{id:e.githubId,number:e.number,title:e.title,url:e.url,repositoryGithubId:e.repositoryGithubId,repositoryNameWithOwner:e.repositoryNameWithOwner,repositoryUrl:e.repositoryUrl,labels:function(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}(e.labelsJson),jiraKey:e.jiraKey,pipelineStatus:t?.pipelineStatus??"NONE",pipelines:t?.pipelines??[],pipelineRevision:t?.revision??0,reviewDecision:e.reviewDecision,unresolvedReviewThreadCount:e.unresolvedReviewThreadCount,state:e.state,isDraft:e.isDraft,mergeable:e.mergeable,mergeStateStatus:e.mergeStateStatus,autoMergeEnabled:e.autoMergeEnabled,viewerCanEnableAutoMerge:e.viewerCanEnableAutoMerge,viewerCanDisableAutoMerge:e.viewerCanDisableAutoMerge,headRefOid:e.headRefOid,headRefName:e.headRefName,worktreeId:e.worktreeId,worktreeHighlightColor:null,createdAt:e.githubCreatedAt.toISOString()}}function A(e){return{reviewDecision:e.reviewDecision,unresolvedReviewThreadCount:e.unresolvedReviewThreadCount,state:e.state,isDraft:e.isDraft,mergeable:e.mergeable,mergeStateStatus:e.mergeStateStatus,autoMergeEnabled:e.autoMergeEnabled,viewerCanEnableAutoMerge:e.viewerCanEnableAutoMerge,viewerCanDisableAutoMerge:e.viewerCanDisableAutoMerge,headRefOid:e.headRefOid}}function _(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")}function C(e,t){if(!t)return e;let r=_(t);if(r!==_(e))return e;let i=r?s.win32:s.posix,a=i.relative(t,e);return i.isAbsolute(a)||".."===a||a.startsWith(`..${i.sep}`)?e:a||"."}function R(e){if("SUCCEEDED"!==e.status||!e.resultJson)throw Error(e.error||"Worktree job failed");let t=JSON.parse(e.resultJson);if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Worktree job returned an invalid result");return t}function T(e,t,r){if(!t||!e.has(t))return;let i=e.get(t);i.some(e=>e.kind===r.kind&&e.id===r.id)||i.push(r)}async function D(e){let t=[...new Set(e.filter(Boolean))],r=new Map(t.map(e=>[e,[]]));if(!t.length)return r;let a=await (0,i.getPrismaClient)(),[n,s,o,l]=await Promise.all([a.build.findMany({where:{worktreeId:{in:t},OR:[{status:{in:["PREPARING","RUNNING"]}},{status:"QUEUED",job:{status:"RUNNING"}}]},select:{id:!0,worktreeId:!0}}),a.agentRun.findMany({where:{worktreeId:{in:t},attempts:{some:{status:{in:["STARTING","RUNNING"]},supersededAt:null}}},select:{id:!0,kind:!0,displayNumber:!0,worktreeId:!0}}),a.workflowStepAttempt.findMany({where:{status:"RUNNING",supersededAt:null},select:{id:!0,run:{select:{id:!0,displayNumber:!0,sessionDataJson:!0}}}}),a.agentJob.findMany({where:{worktreeId:{in:t},status:"RUNNING",kind:{startsWith:"workflow."}},select:{id:!0,worktreeId:!0}})]);for(let e of n)T(r,e.worktreeId,{kind:"BUILD",id:e.id,label:"Build",href:`/builds/${encodeURIComponent(e.id)}`});for(let e of s){let t="PLAN"===e.kind?"PLAN":"SESSION";T(r,e.worktreeId,{kind:t,id:e.id,label:`${"PLAN"===t?"Plan":"Session"} #${e.displayNumber}`,href:`/${"PLAN"===t?"plans":"sessions"}/${encodeURIComponent(e.id)}`})}for(let e of o)T(r,function(e){try{let t=JSON.parse(e);if(!t||"object"!=typeof t||Array.isArray(t))return null;let r=t.worktree;if(!r||"object"!=typeof r||Array.isArray(r))return null;let i=r.id;return"string"==typeof i&&i?i:null}catch{return null}}(e.run.sessionDataJson),{kind:"WORKFLOW",id:e.run.id,label:`Workflow run #${e.run.displayNumber}`,href:`/workflows/runs/${encodeURIComponent(e.run.id)}`});for(let e of l)T(r,e.worktreeId,{kind:"WORKFLOW_JOB",id:e.id,label:"Workflow terminal job",href:`/jobs/${encodeURIComponent(e.id)}`});return r}e.s(["WorktreesService",0,class{agentControl;jiraService;gitHubService;skillsService;workflowEvents;pipelineStatus;watchDemand;constructor(e,t,r,i,a,n=new h.GitHubPipelineStatusService){this.agentControl=e,this.jiraService=t,this.gitHubService=r,this.skillsService=i,this.workflowEvents=a,this.pipelineStatus=n,this.watchDemand=new Map,this.agentControl.registerCompletionHandler(l.WORKTREE_OPERATION_JOB_KIND,e=>this.projectOperation(e)),this.agentControl.registerCompletionHandler(l.WORKTREE_AUTO_SYNC_JOB_KIND,e=>this.projectOperation(e)),this.agentControl.registerCompletionHandler(l.WORKTREE_GIT_OPERATION_JOB_KIND,e=>this.projectOperation(e)),this.agentControl.registerCompletionHandler(l.WORKTREE_BRANCH_JOB_KIND,e=>this.projectBranchOperation(e)),this.agentControl.registerCompletionHandler(l.WORKTREE_MOVE_PUSH_JOB_KIND,e=>this.advanceMoveAfterPush(e)),this.agentControl.registerCompletionHandler(l.WORKTREE_MOVE_CHECKOUT_JOB_KIND,e=>this.advanceMoveAfterCheckout(e)),this.agentControl.registerCompletionHandler(l.WORKTREE_DELETE_JOB_KIND,e=>this.projectDeleteOperation(e))}async settings(){return(await (0,i.getPrismaClient)()).worktreeSettings.upsert({where:{id:g},create:{id:g,editorVariant:"CODE"},update:{}})}async saveSettings(e){if(!["CODE","CODE_INSIDERS","NONE"].includes(e))throw Error("Unknown editor setting");let t=await (0,i.getPrismaClient)(),r=await t.worktreeSettings.upsert({where:{id:g},create:{id:g,editorVariant:e},update:{editorVariant:e}});return this.publish(null,null),r}async requestRefresh(){let e=await (0,i.getPrismaClient)(),t=await e.codebase.findMany({select:{agentId:!0}});return this.agentControl.requestCodebaseReconcile(t.map(e=>e.agentId))}async cleanupExpired(){let e=await (0,i.getPrismaClient)();await e.worktree.deleteMany({where:{missingAt:{lt:new Date(Date.now()-6048e5)}}})}view(e,t=""){let r=e.codebase.repository.jiraBranchRegex??t;return{...e,relativePath:C(e.folder,e.codebase.agent.baseRepoDirectory),tags:e.tags.map(e=>e.tag),activeJob:e.codebase.jobs.find(t=>t.worktreeId===e.id)??e.codebase.jobs[0]??null,baseBranch:e.baseBranchOverride??e.codebase.defaultBranch??null,ticketKey:I(e.branch,String(r)),ticketTitle:null,ticketStatus:null,pullRequest:e.pullRequest?x(e.pullRequest):null,latestBuild:e.builds?.[0]?{...e.builds[0],outOfDate:(0,f.buildOutOfDate)({...e.builds[0],worktree:e})}:null}}async storePullRequest(e,t,r,a){let n=await (0,i.getPrismaClient)(),s=new Date;await n.$transaction(async i=>{if(await i.worktree.update({where:{id:e},data:{pullRequestLookupOrigin:t,pullRequestLookupBranch:r,pullRequestLookupAt:s}}),a){let t={githubId:a.id,number:a.number,title:a.title,url:a.url,repositoryGithubId:a.repositoryGithubId,repositoryNameWithOwner:a.repositoryNameWithOwner,repositoryUrl:a.repositoryUrl,labelsJson:JSON.stringify(a.labels),jiraKey:a.jiraKey,reviewDecision:a.reviewDecision,unresolvedReviewThreadCount:a.unresolvedReviewThreadCount,state:a.state,isDraft:a.isDraft,mergeable:a.mergeable,mergeStateStatus:a.mergeStateStatus,autoMergeEnabled:a.autoMergeEnabled,viewerCanEnableAutoMerge:a.viewerCanEnableAutoMerge,viewerCanDisableAutoMerge:a.viewerCanDisableAutoMerge,headRefOid:a.headRefOid,headRefName:a.headRefName,githubCreatedAt:new Date(a.createdAt)};await i.worktreePullRequest.upsert({where:{worktreeId:e},create:{worktreeId:e,...t},update:t})}else await i.worktreePullRequest.deleteMany({where:{worktreeId:e}})})}async clearPullRequest(e,t=!0){let r=await (0,i.getPrismaClient)();await r.$transaction([r.worktreePullRequest.deleteMany({where:{worktreeId:e}}),...t?[r.worktree.update({where:{id:e},data:{pullRequestLookupOrigin:null,pullRequestLookupBranch:null,pullRequestLookupAt:null}})]:[]])}async synchronizePullRequests(e){let t=await (0,i.getPrismaClient)(),r=await this.gitHubService.effectiveCacheTtlSeconds("GitHubWorktreePullRequests")*1e3,a=new Set,n=new Map;for(let t of e){let e=t.codebase.repository.canonicalOrigin;!(t.branch&&t.pullRequestLookupOrigin?.toLowerCase()===e.toLowerCase()&&t.pullRequestLookupBranch===t.branch)&&(t.pullRequest||t.pullRequestLookupOrigin||t.pullRequestLookupBranch||t.pullRequestLookupAt)&&(await this.clearPullRequest(t.id),t.pullRequest=null,t.pullRequestLookupOrigin=null,t.pullRequestLookupBranch=null,t.pullRequestLookupAt=null)}let s=e.filter(e=>e.pullRequest);if(s.length)try{let e=await this.gitHubService.pullRequestLiveStatuses(s.flatMap(e=>e.pullRequest?[e.pullRequest.id]:[]),{requestSource:"WORKTREES"});for(let r of s){let i=r.pullRequest;if(!i)continue;let s=e.get(i.id)??null;if(!s||"OPEN"!==s.state){n.set(r.id,i),r.pullRequest=null,a.add(r.id);continue}let o=A(s),l=A(i);JSON.stringify(o)!==JSON.stringify(l)&&(await t.worktreePullRequest.updateMany({where:{worktreeId:r.id},data:o}),r.pullRequest={...i,...s})}}catch{}let o=Date.now(),l=e.filter(e=>{if(e.pullRequest||!e.branch)return!1;let t=e.codebase.repository.canonicalOrigin;return!!/^github\.com\/[^/]+\/[^/]+$/i.test(t)&&(!!a.has(e.id)||e.pullRequestLookupOrigin?.toLowerCase()!==t.toLowerCase()||e.pullRequestLookupBranch!==e.branch||!e.pullRequestLookupAt||o-e.pullRequestLookupAt.getTime()>=r)}),u=new Map;for(let e of l){let t=e.codebase.repository.canonicalOrigin,r=`${a.has(e.id)?"force":"cached"}\0${t}`;u.set(r,[...u.get(r)??[],e])}await Promise.all([...u.entries()].map(async([e,t])=>{let r=e.startsWith("force\0"),i=t[0].codebase.repository.canonicalOrigin;try{let e=await this.gitHubService.pullRequestsForBranches(i,t.flatMap(e=>e.branch?[e.branch]:[]),{force:r,allowStaleOnError:!r,requestSource:"WORKTREES"});await Promise.all(t.map(async t=>{let r=t.branch,a=e.get(r)??null;await this.storePullRequest(t.id,i,r,a),t.pullRequest=a,t.pullRequestLookupOrigin=i,t.pullRequestLookupBranch=r,t.pullRequestLookupAt=new Date}))}catch{for(let e of t){let t=n.get(e.id);t&&(e.pullRequest=t)}}}))}async hydratePullRequestPipelines(e){let t=new Map((await this.pipelineStatus.snapshots(e.flatMap(e=>e.pullRequest?[{repositoryGithubId:e.pullRequest.repositoryGithubId,headSha:e.pullRequest.headRefOid}]:[]))).map(e=>[`${e.repositoryGithubId}\u0000${e.headSha}`,e]));for(let r of e){if(!r.pullRequest)continue;let e=t.get(`${r.pullRequest.repositoryGithubId}\u0000${r.pullRequest.headRefOid}`);r.pullRequest={...r.pullRequest,pipelineStatus:e?.pipelineStatus??r.pullRequest.pipelineStatus,pipelines:e?.pipelines??r.pullRequest.pipelines,pipelineRevision:e?.revision??r.pullRequest.pipelineRevision??0}}}async hydratedView(e,t=""){let r=this.view(e,t);return await this.hydratePullRequestPipelines([r]),r}async refreshPullRequest(e){let t=await (0,i.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e},include:v});if(!r||r.missingAt)throw Error("Worktree not found");let a=r.codebase.repository.canonicalOrigin;if(!r.branch)throw Error("A named worktree branch is required");if(!/^github\.com\/[^/]+\/[^/]+$/i.test(a))throw Error("The worktree repository is not hosted on GitHub");let n=await this.gitHubService.pullRequestsForBranches(a,[r.branch],{force:!0,allowStaleOnError:!1,requestSource:"WORKTREES"});await this.storePullRequest(e,a,r.branch,n.get(r.branch)??null);let s=await t.worktree.findUniqueOrThrow({where:{id:e},include:v});return this.publish(e,r.codebaseId),this.hydratedView(s)}async attachPullRequestForBranch(e,t,r){let a=await (0,i.getPrismaClient)(),n=(await a.worktree.findMany({where:{branch:t,missingAt:null},select:{id:!0,codebaseId:!0,codebase:{select:{repository:{select:{canonicalOrigin:!0}}}}}})).filter(t=>t.codebase.repository.canonicalOrigin.toLowerCase()===e.toLowerCase());return await Promise.all(n.map(async i=>{await this.storePullRequest(i.id,e,t,r),this.publish(i.id,i.codebaseId)})),n.length}async overview(){await this.cleanupExpired();let e=await (0,i.getPrismaClient)(),[t,r,a,n,s,o]=await Promise.all([e.worktree.findMany({where:{missingAt:null},include:v,orderBy:[{codebase:{agent:{name:"asc"}}},{codebase:{repository:{name:"asc"}}},{primary:"desc"},{branch:"asc"},{folder:"asc"}]}),e.worktreeTag.findMany({orderBy:{name:"asc"}}),this.settings(),e.codebaseSettings.findUnique({where:{id:"default"}}),e.worktree.count({where:{missingAt:{not:null}}}),e.worktreeMove.findMany({where:{status:{in:w}},orderBy:{createdAt:"asc"}})]),l=n?.defaultJiraBranchRegex??"",u=t.map(e=>this.view(e,l)),p=[...new Set(u.map(e=>e.codebase.repository.id))],h=(await e.workflow.findMany({where:{enabled:!0,archivedAt:null,activeVersionId:{not:null},quickActionKind:{in:["STANDARD","MERGE_CONFLICT"]},OR:[{quickActionRepositories:{none:{}}},{quickActionRepositories:{some:{repositoryId:{in:p}}}}]},include:{activeVersion:{include:{triggers:!0}},quickActionRepositories:{select:{repositoryId:!0}}},orderBy:[{name:"asc"},{id:"asc"}]})).filter(e=>e.activeVersion?.triggers.some(e=>{if(!(0,d.isResourceTriggerKind)(e.kind))return!1;try{return"WORKTREE"===(0,c.workflowResourceKind)(JSON.parse(e.configJson))}catch{return!1}}));await this.synchronizePullRequests(u),await this.hydratePullRequestPipelines(u);let m=[...new Set(u.map(e=>e.ticketKey).filter(Boolean))],f=new Map;for(let e of(await Promise.all(m.map(async e=>{try{let t=await this.jiraService.cachedTicket(e)??await this.jiraService.ticket(e);f.set(e,{title:t.summary,status:t.status})}catch{}})),u))e.ticketTitle=e.ticketKey?f.get(e.ticketKey)?.title??null:null,e.ticketStatus=e.ticketKey?f.get(e.ticketKey)?.status??null:null;let g=new Map;for(let e of u){let t=e.codebase.agent,r=g.get(t.id);r||(r={agent:t,codebases:[],codebaseMap:new Map},g.set(t.id,r));let i=r.codebaseMap.get(e.codebase.id);i||(i={codebase:e.codebase,repository:e.codebase.repository,worktrees:[],iosBuildConfigured:e.codebase.repository.projects?.some(e=>e.configurations.length>0)??!1,quickActions:h.filter(t=>"STANDARD"===t.quickActionKind&&(0===t.quickActionRepositories.length||t.quickActionRepositories.some(({repositoryId:t})=>t===e.codebase.repository.id))),mergeConflictQuickActions:h.filter(t=>"MERGE_CONFLICT"===t.quickActionKind&&(0===t.quickActionRepositories.length||t.quickActionRepositories.some(({repositoryId:t})=>t===e.codebase.repository.id)))},r.codebaseMap.set(e.codebase.id,i),r.codebases.push(i)),i.worktrees.push(e)}return{agents:[...g.values()].map(e=>({agent:e.agent,codebases:e.codebases})),tags:r,settings:a,hiddenCount:s,activeMoves:o}}async hidden(){await this.cleanupExpired();let e=await (0,i.getPrismaClient)(),t=await e.codebaseSettings.findUnique({where:{id:"default"}}),r=(await e.worktree.findMany({where:{missingAt:{not:null}},include:v,orderBy:{missingAt:"desc"}})).map(e=>this.view(e,t?.defaultJiraBranchRegex??""));return await this.hydratePullRequestPipelines(r),r}async report(e,r){let a=await (0,i.getPrismaClient)(),n=[],s=!1;for(let i of r.slice(0,100)){let r=(0,l.parseCodebaseWorktreeReport)(i),o=await a.codebase.findUnique({where:{id:r.codebaseId}});if(!o||o.agentId!==e)throw Error("Codebase not found for this agent");let u=r.worktrees.slice(0,1e3).map(e=>(0,l.parseWorktreeInventoryItem)(e)),c=await a.worktree.findMany({where:{codebaseId:o.id},select:{gitDirectory:!0,folder:!0,missingAt:!0}}),d=new Map(c.map(e=>[e.gitDirectory,e])),p=new Set(u.map(e=>e.gitDirectory));s||=u.some(e=>{let t=d.get(e.gitDirectory);return!t||t.folder!==e.folder||null!==t.missingAt})||r.complete&&c.some(e=>null===e.missingAt&&!p.has(e.gitDirectory)),await a.$transaction(async e=>{await e.codebase.update({where:{id:o.id},data:{defaultBranch:r.defaultBranch,localBranchesJson:JSON.stringify(r.localBranches),remoteBranchesJson:JSON.stringify(r.remoteBranches),...r.fetchedAt?{lastFetchedAt:new Date(r.fetchedAt)}:{},...r.fetchAttemptedAt?{lastFetchAttemptAt:new Date(r.fetchAttemptedAt),lastFetchError:r.fetchError}:r.fetchError?{lastFetchError:r.fetchError}:{}}});let i=[];for(let r of u){i.push(r.gitDirectory);let a=await e.worktree.upsert({where:{codebaseId_gitDirectory:{codebaseId:o.id,gitDirectory:r.gitDirectory}},create:{id:(0,t.randomUUID)(),codebaseId:o.id,gitDirectory:r.gitDirectory,...this.inventoryData(r)},update:{}}),s=a.branch!==r.branch,l=await e.worktree.updateMany({where:{id:a.id,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:new Date(r.checkedAt)}}]},data:{...this.inventoryData(r),missingAt:null,...s?{pullRequestLookupOrigin:null,pullRequestLookupBranch:null,pullRequestLookupAt:null}:{}}});s&&l.count>0&&await e.worktreePullRequest.deleteMany({where:{worktreeId:a.id}}),n.push(a.id)}r.complete&&await e.worktree.updateMany({where:{codebaseId:o.id,missingAt:null,...i.length?{gitDirectory:{notIn:i}}:{}},data:{missingAt:new Date}})}),this.publish(null,o.id)}return await this.cleanupExpired(),s&&await this.skillsService?.requestAutoReconcile(),a.worktree.findMany({where:{id:{in:n}},include:v})}async reportActivity(e,t){let r=(0,l.parseWorktreeActivityReport)(t),a=await (0,i.getPrismaClient)(),s=await a.worktree.findFirst({where:{codebaseId:r.codebaseId,gitDirectory:r.gitDirectory,missingAt:null,codebase:{agentId:e}},select:{id:!0,codebaseId:!0,branch:!0}});if(!s)throw Error("Worktree activity source was not found");let o=void 0!==r.branch||void 0!==r.headSha||void 0!==r.upstream||void 0!==r.ahead||void 0!==r.behind||void 0!==r.syncState||void 0!==r.baseAhead||void 0!==r.baseBehind,u=!0;if(o||void 0!==r.hasStagedChanges||void 0!==r.hasUnstagedChanges||void 0!==r.rebaseInProgress||void 0!==r.hasConflicts||void 0!==r.codeStateHash||void 0!==r.pushStatus){let e=void 0!==r.branch&&r.branch!==s.branch;(u=(await a.worktree.updateMany({where:{id:s.id,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:new Date(r.observedAt)}}]},data:{...void 0===r.branch?{}:{branch:r.branch},...e?{pullRequestLookupOrigin:null,pullRequestLookupBranch:null,pullRequestLookupAt:null}:{},...void 0===r.headSha?{}:{headSha:r.headSha},...void 0===r.upstream?{}:{upstream:r.upstream},...void 0===r.ahead?{}:{ahead:r.ahead},...void 0===r.behind?{}:{behind:r.behind},...void 0===r.syncState?{}:{syncState:r.syncState},...void 0===r.baseAhead?{}:{baseAhead:r.baseAhead},...void 0===r.baseBehind?{}:{baseBehind:r.baseBehind},lastCheckedAt:new Date(r.observedAt),...void 0===r.hasStagedChanges?{}:{hasStagedChanges:r.hasStagedChanges},...void 0===r.hasUnstagedChanges?{}:{hasUnstagedChanges:r.hasUnstagedChanges},...void 0===r.rebaseInProgress?{}:{rebaseInProgress:r.rebaseInProgress},...void 0===r.hasConflicts?{}:{hasConflicts:r.hasConflicts},...void 0===r.codeStateHash?{}:{codeStateHash:r.codeStateHash},...void 0===r.pushStatus?{}:{pushStatus:r.pushStatus}}})).count>0)&&(e&&await a.worktreePullRequest.deleteMany({where:{worktreeId:s.id}}),this.publish(s.id,s.codebaseId))}let c={worktreeId:s.id,...void 0===r.branch?{}:{branch:r.branch},...void 0===r.headSha?{}:{headSha:r.headSha},...void 0===r.upstream?{}:{upstream:r.upstream},...void 0===r.ahead?{}:{ahead:r.ahead},...void 0===r.behind?{}:{behind:r.behind},...void 0===r.syncState?{}:{syncState:r.syncState},...void 0===r.baseAhead?{}:{baseAhead:r.baseAhead},...void 0===r.baseBehind?{}:{baseBehind:r.baseBehind},...void 0===r.hasStagedChanges?{}:{hasStagedChanges:r.hasStagedChanges},...void 0===r.hasUnstagedChanges?{}:{hasUnstagedChanges:r.hasUnstagedChanges},...void 0===r.rebaseInProgress?{}:{rebaseInProgress:r.rebaseInProgress},...void 0===r.hasConflicts?{}:{hasConflicts:r.hasConflicts},...void 0===r.pushStatus?{}:{pushStatus:r.pushStatus},observedAt:r.observedAt};return this.watchDemand.has(s.id)&&u&&n.agentEventBus.publish((0,n.worktreeInspectionTopic)(s.id),{worktreeInspectionChanged:c}),c}inventoryData(e){return{folder:e.folder,relativePath:e.relativePath,primary:e.primary,branch:e.branch,headSha:e.headSha,codeStateHash:e.codeStateHash??null,upstream:e.upstream,ahead:e.ahead,behind:e.behind,syncState:e.syncState,baseAhead:e.baseAhead,baseBehind:e.baseBehind,hasStagedChanges:e.hasStagedChanges??!1,hasUnstagedChanges:e.hasUnstagedChanges??!1,rebaseInProgress:e.rebaseInProgress??!1,hasConflicts:e.hasConflicts??!1,pushStatus:e.pushStatus??"UNKNOWN",availability:e.availability,statusError:e.error,lastCheckedAt:new Date(e.checkedAt)}}async updateBaseBranch(e,t){let r=await (0,i.getPrismaClient)(),a=await r.worktree.findUnique({where:{id:e},include:{codebase:!0}});if(!a||a.missingAt)throw Error("Worktree not found");let n=t?.trim()||null;if(n&&!E(a.codebase.remoteBranchesJson).includes(n))throw Error("The selected origin branch is unavailable; fetch and try again");let s=await r.worktree.update({where:{id:e},data:{baseBranchOverride:n},include:v});return this.publish(e,a.codebaseId),await this.restartWatch(e),this.hydratedView(s)}requireColor(e){if(null===e||""===e)return null;if(!b.includes(e))throw Error("Unknown worktree color");return e}async updateHighlight(e,t){let r=await (0,i.getPrismaClient)(),a=await r.worktree.update({where:{id:e},data:{highlightColor:this.requireColor(t)},include:v});return this.publish(e,a.codebaseId),this.hydratedView(a)}async setTags(e,t){let r=await (0,i.getPrismaClient)(),a=[...new Set(t)].slice(0,100);if(await r.worktreeTag.count({where:{id:{in:a}}})!==a.length)throw Error("One or more tags were not found");await r.$transaction([r.worktreeTagAssignment.deleteMany({where:{worktreeId:e}}),...a.length?[r.worktreeTagAssignment.createMany({data:a.map(t=>({worktreeId:e,tagId:t}))})]:[]]);let n=await r.worktree.findUniqueOrThrow({where:{id:e},include:v});return this.publish(e,n.codebaseId),this.hydratedView(n)}async saveTag(e){let r=e.name.trim();if(!r||r.length>40)throw Error("Tag names must contain 1–40 characters");let a=this.requireColor(e.color),n=await (0,i.getPrismaClient)(),s=(await n.worktreeTag.findMany()).find(e=>e.name.toLocaleLowerCase()===r.toLocaleLowerCase());if(s&&s.id!==e.id)throw Error("Tag names must be unique");let o=e.id?await n.worktreeTag.update({where:{id:e.id},data:{name:r,color:a}}):await n.worktreeTag.create({data:{id:(0,t.randomUUID)(),name:r,color:a}});return this.publish(null,null),o}async deleteTag(e){let t=await (0,i.getPrismaClient)(),r=await t.worktreeTag.deleteMany({where:{id:e}});return r.count&&this.publish(null,null),r.count>0}async repositoryTakenBranches(e){let t=await (0,i.getPrismaClient)();return new Set((await t.codebase.findMany({where:{repositoryId:e},select:{localBranchesJson:!0,remoteBranchesJson:!0,worktrees:{where:{missingAt:null},select:{branch:!0}}}})).flatMap(e=>[...E(e.localBranchesJson),...E(e.remoteBranchesJson),...e.worktrees.flatMap(e=>e.branch?[e.branch]:[])]))}requireBaseBranch(e,t){let r=t.trim();if(!r||!E(e.remoteBranchesJson).includes(r))throw Error("The selected origin base branch is unavailable; fetch and try again");return r}async ticketBranch(e,t,r){let i=t?.trim()??"",a=await this.jiraService.branchTicket(i),n=await (0,m.jiraBranchCandidates)(a.branchNamingScript,{ticketKey:a.ticketKey,type:a.ticketType??"",title:a.ticketTitle}),s=await this.repositoryTakenBranches(e.repositoryId),o=n.filter(e=>e===r||!s.has(e));if(!o.length)throw Error("Every generated ticket branch name is already taken");return{ticket:a,candidates:o}}async previewTicketBranch(e){let t=await (0,i.getPrismaClient)(),r=await t.codebase.findUnique({where:{id:e.codebaseId},include:{agent:!0,repository:!0}});if(!r)throw Error("Codebase not found");let a=null;if(e.worktreeId){let r=await t.worktree.findFirst({where:{id:e.worktreeId,codebaseId:e.codebaseId,missingAt:null},select:{branch:!0}});if(!r)throw Error("Worktree not found for this codebase");a=r.branch}let{ticket:n,candidates:s}=await this.ticketBranch(r,e.ticketKey,a);return{ticketKey:n.ticketKey,ticketTitle:n.ticketTitle,ticketType:n.ticketType,projectKey:n.projectKey,branchName:s[0]}}async ticketKeyForWorktree(e){let t=await (0,i.getPrismaClient)(),[r,a]=await Promise.all([t.worktree.findFirst({where:{id:e,missingAt:null},select:{branch:!0,codebase:{select:{repository:{select:{jiraBranchRegex:!0}}}}}}),t.codebaseSettings.findUnique({where:{id:g}})]);if(!r)return null;let n=r.codebase.repository.jiraBranchRegex??a?.defaultJiraBranchRegex??"";return I(r.branch,n)}async workflowSessionDataForWorktree(e,t={}){var r;let a=await (0,i.getPrismaClient)(),[n,s]=await Promise.all([a.worktree.findFirst({where:{id:e,...t.includeMissing?{}:{missingAt:null}},select:{id:!0,folder:!0,branch:!0,baseBranchOverride:!0,headSha:!0,upstream:!0,ahead:!0,behind:!0,syncState:!0,baseAhead:!0,baseBehind:!0,rebaseInProgress:!0,hasConflicts:!0,pushStatus:!0,hasStagedChanges:!0,hasUnstagedChanges:!0,missingAt:!0,pullRequest:!0,codebase:{select:{id:!0,folder:!0,agentId:!0,branch:!0,headSha:!0,defaultBranch:!0,agent:{select:{id:!0,name:!0,hostname:!0}},repository:{select:{id:!0,name:!0,displayOrigin:!0,canonicalOrigin:!0,jiraBranchRegex:!0}}}}}}),a.codebaseSettings.findUnique({where:{id:g}})]);if(!n)return{};let o=n.codebase.repository,l=o.jiraBranchRegex??s?.defaultJiraBranchRegex??"",u=I(n.branch,l),c=null;if(u)try{c=await this.jiraService.cachedTicket(u)}catch{}let d=n.pullRequest?await this.pipelineStatus.snapshot({repositoryGithubId:n.pullRequest.repositoryGithubId,headSha:n.pullRequest.headRefOid}):null;return{worktree:{id:n.id,path:n.folder,branch:n.branch,baseBranch:n.baseBranchOverride??n.codebase.defaultBranch,headSha:n.headSha,upstream:n.upstream,ahead:n.ahead,behind:n.behind,syncState:n.syncState,baseAhead:n.baseAhead,baseBehind:n.baseBehind,rebaseInProgress:n.rebaseInProgress,hasConflicts:n.hasConflicts,pushStatus:n.pushStatus,dirty:n.hasStagedChanges||n.hasUnstagedChanges,missingAt:n.missingAt?.toISOString()??null},codebase:{id:n.codebase.id,folder:n.codebase.folder,agentId:n.codebase.agentId,branch:n.codebase.branch,headSha:n.codebase.headSha},agent:n.codebase.agent,repo:{id:o.id,name:o.name,url:o.displayOrigin,canonicalOrigin:o.canonicalOrigin,displayOrigin:o.displayOrigin,defaultBranch:n.codebase.defaultBranch},...n.pullRequest?{pr:{...r=x(n.pullRequest,d),headBranch:r.headRefName,headSha:r.headRefOid,merged:"MERGED"===r.state}}:{},...u?{ticket:{key:u,title:c?.summary??null,status:c?.status??null,projectKey:c?.projectKey??null}}:{}}}async workflowSessionDataForPullRequest(e,t,r){let a=e.trim().toLowerCase(),n=t.trim().toLowerCase();if(!a||!n||!Number.isInteger(r)||r<1)return{};let s=await (0,i.getPrismaClient)(),o=await s.worktreePullRequest.findMany({where:{number:r,worktree:{missingAt:null}},select:{worktreeId:!0,repositoryNameWithOwner:!0},orderBy:{updatedAt:"desc"}}),l=`${a}/${n}`,u=o.find(({repositoryNameWithOwner:e})=>e.toLowerCase()===l);return u?this.workflowSessionDataForWorktree(u.worktreeId):{}}async resolveBranchSelection(e,t,r){let a=this.requireBaseBranch(e,t.baseBranch);if("TICKET"===t.mode){let{candidates:i}=await this.ticketBranch(e,t.ticketKey,r?.branch??null);return{baseBranch:a,mode:"NEW",candidates:i}}let n=t.branchName?.trim()??"";if(!(0,l.validGitBranchName)(n))throw Error("Enter a valid Git branch name");if("NEW"===t.mode){if((await this.repositoryTakenBranches(e.repositoryId)).has(n))throw Error(`Branch ${n} is already taken`);return{baseBranch:a,mode:"NEW",candidates:[n]}}if("EXISTING"!==t.mode)throw Error("Unknown worktree branch mode");if(!new Set([...E(e.localBranchesJson),...E(e.remoteBranchesJson)]).has(n))throw Error(`Existing branch ${n} is unavailable; refresh and try again`);let s=await (0,i.getPrismaClient)();if(await s.worktree.findFirst({where:{codebaseId:e.id,branch:n,missingAt:null,...r?{id:{not:r.id}}:{}},select:{id:!0}}))throw Error(`Branch ${n} is checked out in another worktree`);return{baseBranch:a,mode:"EXISTING",candidates:[n]}}async createWorktree(e){let t=await this.requireRunnableCodebase(e.codebaseId),r=await this.resolveBranchSelection(t,e.selection,null);return this.agentControl.createJob({agentId:t.agentId,codebaseId:t.id,kind:l.WORKTREE_BRANCH_JOB_KIND,payload:{codebaseId:t.id,rootFolder:t.folder,folder:null,gitDirectory:null,expectedOrigin:t.repository.canonicalOrigin,baseBranch:r.baseBranch,action:"CREATE",mode:r.mode,candidates:r.candidates,stashOnFailure:!1},idempotencyKey:`worktree:branch:create:${e.requestId}:${t.id}`,timeoutSeconds:600})}async changeWorktreeBranch(e){let t=await this.requireRunnable(e.worktreeId,l.WORKTREE_BRANCH_JOB_KIND),r=await this.resolveBranchSelection(t.codebase,e.selection,{id:t.id,branch:t.branch});return this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:l.WORKTREE_BRANCH_JOB_KIND,payload:{codebaseId:t.codebaseId,rootFolder:t.codebase.folder,folder:t.folder,gitDirectory:t.gitDirectory,expectedOrigin:t.codebase.repository.canonicalOrigin,baseBranch:r.baseBranch,action:"CHANGE",mode:r.mode,candidates:r.candidates,stashOnFailure:!!e.stashOnFailure},idempotencyKey:`worktree:branch:change:${e.requestId}:${t.id}`,timeoutSeconds:600})}async getMove(e){return(await (0,i.getPrismaClient)()).worktreeMove.findUnique({where:{id:e}})}async moveWorktree(e){let r,a=await (0,i.getPrismaClient)(),n=await a.worktreeMove.findUnique({where:{sourceWorktreeId_requestId:{sourceWorktreeId:e.sourceWorktreeId,requestId:e.requestId}}});if(n)return n;let s=await this.requireRunnable(e.sourceWorktreeId,l.WORKTREE_MOVE_PUSH_JOB_KIND);if(!s.branch||!s.headSha)throw Error("A named source branch is required");if(s.hasStagedChanges||s.hasUnstagedChanges||"READY"!==s.pushStatus)throw Error("The source branch must be clean and safely pushable before moving");if(e.deleteSource&&s.primary)throw Error("The primary worktree cannot be deleted after moving");if(e.deleteSource&&!S(s.codebase.agent).includes(l.WORKTREE_DELETE_JOB_KIND))throw Error("Source agent must be updated to remove the old worktree");let o=await this.requireRunnableCodebase(e.targetCodebaseId,l.WORKTREE_MOVE_CHECKOUT_JOB_KIND);if(s.codebase.repositoryId!==o.repositoryId||s.codebase.agentId===o.agentId)throw Error("The destination must be the same repository on another agent");let u=e.targetWorktreeId?await a.worktree.findFirst({where:{id:e.targetWorktreeId,codebaseId:o.id,missingAt:null,availability:"AVAILABLE"}}):null;if(e.targetWorktreeId&&!u)throw Error("Destination worktree not found");if(await a.worktree.findFirst({where:{codebaseId:o.id,branch:s.branch,missingAt:null,...u?{id:{not:u.id}}:{}},select:{id:!0}}))throw Error("The source branch is already checked out in another destination worktree");let c=o.defaultBranch??s.codebase.defaultBranch;if(!c)throw Error("The destination default branch is unavailable");let d=(0,t.randomUUID)();try{r=await a.worktreeMove.create({data:{id:d,requestId:e.requestId,sourceWorktreeId:s.id,sourceCodebaseId:s.codebaseId,targetCodebaseId:o.id,targetWorktreeId:u?.id??null,destinationMode:u?"EXISTING":"NEW",branch:s.branch,headSha:s.headSha,baseBranch:c,deleteSource:e.deleteSource,status:"PUSHING"}})}catch(r){let t=await a.worktreeMove.findUnique({where:{sourceWorktreeId_requestId:{sourceWorktreeId:e.sourceWorktreeId,requestId:e.requestId}}});if(t)return t;throw r}try{let e=await this.agentControl.createJob({agentId:s.codebase.agentId,codebaseId:s.codebaseId,worktreeId:s.id,kind:l.WORKTREE_MOVE_PUSH_JOB_KIND,payload:{moveId:r.id,codebaseId:s.codebaseId,folder:s.folder,gitDirectory:s.gitDirectory,expectedOrigin:s.codebase.repository.canonicalOrigin,branch:s.branch,expectedHeadSha:s.headSha},idempotencyKey:`worktree:move:push:${r.id}`,timeoutSeconds:600});return r=await a.worktreeMove.update({where:{id:r.id},data:{sourceJobId:e.id}}),this.publish(s.id,s.codebaseId),r}catch(e){throw await a.worktreeMove.update({where:{id:r.id},data:{status:"FAILED",error:e instanceof Error?e.message:String(e),finishedAt:new Date}}),e}}async retryWorktreeMoveWithStash(e){let t=await (0,i.getPrismaClient)(),r=await t.worktreeMove.findUnique({where:{id:e}});if(!r||"AWAITING_STASH"!==r.status)throw Error("This move is not waiting for a stash decision");let a=await this.createMoveCheckoutJob(r,!0);if(1!==(await t.worktreeMove.updateMany({where:{id:e,status:"AWAITING_STASH"},data:{status:"CHECKING_OUT",targetJobId:a.id,error:null}})).count){let r=await t.worktreeMove.findUniqueOrThrow({where:{id:e}});if("AWAITING_STASH"!==r.status)return r;throw Error("The move state changed; refresh and try again")}return this.publish(r.sourceWorktreeId,r.sourceCodebaseId),t.worktreeMove.findUniqueOrThrow({where:{id:e}})}async cancelWorktreeMove(e){let t=await (0,i.getPrismaClient)(),r=await t.worktreeMove.findUnique({where:{id:e}});if(!r||"AWAITING_STASH"!==r.status)throw Error("Only a move waiting for a stash decision can be cancelled");let a=await t.worktreeMove.update({where:{id:e},data:{status:"CANCELLED",finishedAt:new Date}});return this.publish(r.sourceWorktreeId,r.sourceCodebaseId),a}async deleteWorktree(e){let t=await this.requireRunnable(e.worktreeId,l.WORKTREE_DELETE_JOB_KIND);if(t.primary)throw Error("The primary worktree cannot be deleted");if(void 0!==e.expectedBranch&&t.branch!==e.expectedBranch)throw Error("The worktree branch changed before deletion");if(!0===e.requireClean&&void 0!==e.expectedHeadSha&&t.headSha!==e.expectedHeadSha)throw Error("The worktree HEAD changed before deletion");if(e.deleteRemoteBranch&&(!t.branch||t.branch===t.codebase.defaultBranch))throw Error("The default remote branch cannot be deleted");return this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:l.WORKTREE_DELETE_JOB_KIND,payload:{moveId:null,codebaseId:t.codebaseId,rootFolder:t.codebase.folder,folder:t.folder,gitDirectory:t.gitDirectory,expectedOrigin:t.codebase.repository.canonicalOrigin,branch:void 0===e.expectedBranch?t.branch:e.expectedBranch,defaultBranch:t.codebase.defaultBranch,deleteRemoteBranch:e.deleteRemoteBranch,requireClean:e.requireClean??!1,expectedHeadSha:!0===e.requireClean?e.expectedHeadSha??t.headSha:null},idempotencyKey:`worktree:delete:${e.requestId}:${t.id}`,timeoutSeconds:600})}async inspect(e,t){let r=await this.requireRunnable(e,l.WORKTREE_INSPECT_JOB_KIND,!0),a=await this.createSerializedCodebaseJob({agentId:r.codebase.agentId,codebaseId:r.codebaseId,worktreeId:r.id,kind:l.WORKTREE_INSPECT_JOB_KIND,payload:this.payload(r),idempotencyKey:`worktree:inspect:${t}:${e}`,timeoutSeconds:30,visibility:"SYSTEM"});try{let e=await this.waitForJob(a.id),i=R(e).detail;if(!i||"object"!=typeof i)throw Error("Invalid worktree detail");let n=Array.isArray(i.changes)?i.changes.map(e=>e&&"object"==typeof e&&!Array.isArray(e)?{...e,changeType:"string"==typeof e.changeType?e.changeType:"MODIFIED"}:e):[],s={...i,changes:n,branchChanges:Array.isArray(i.branchChanges)?i.branchChanges:[],branchChangesTruncated:!0===i.branchChangesTruncated};if(this.workflowEvents){let e=n.filter(e=>e&&"object"==typeof e&&!Array.isArray(e)&&!0===e.conflicted),i=(0,p.mergeSessionData)(await this.workflowSessionDataForWorktree(r.id),{repo:{id:r.codebase.repository.id,name:r.codebase.repository.name,url:r.codebase.repository.displayOrigin,canonicalOrigin:r.codebase.repository.canonicalOrigin,displayOrigin:r.codebase.repository.displayOrigin,defaultBranch:r.codebase.defaultBranch},codebase:{id:r.codebase.id,folder:r.codebase.folder,agentId:r.codebase.agentId},worktree:{id:r.id,path:r.folder,branch:r.branch,headSha:r.headSha,conflicted:e.length>0,conflicts:e}});await this.workflowEvents.record({kind:"WORKTREE_CONFLICT",subjectKey:r.id,dedupeKey:`worktree-conflict:${r.id}:${t}`,payload:{...i,sessionData:i,cursorValue:e.length?e.map(e=>String(e.path??"")):[]}})}return s}finally{let e=await (0,i.getPrismaClient)();await e.agentJob.deleteMany({where:{id:a.id,visibility:"SYSTEM"}})}}async inspectDiff(e,t,r){let a=await this.requireRunnable(e,l.WORKTREE_DIFF_JOB_KIND,!0),n=this.payload(a);if(!n.baseBranch)throw Error("A base branch is required");let s=await this.createSerializedCodebaseJob({agentId:a.codebase.agentId,codebaseId:a.codebaseId,worktreeId:a.id,kind:l.WORKTREE_DIFF_JOB_KIND,payload:{...n,baseBranch:n.baseBranch,scope:t.scope,path:t.path??null,previousPath:t.previousPath??null,commitSha:t.commitSha??null,uploadId:null,side:null},idempotencyKey:`worktree:diff:${r}:${e}`,timeoutSeconds:30,visibility:"SYSTEM"});try{let e=await this.waitForJob(s.id),t=R(e).diff;if(!t||"object"!=typeof t)throw Error("Invalid worktree diff result");return t}finally{let e=await (0,i.getPrismaClient)();await e.agentJob.deleteMany({where:{id:s.id,visibility:"SYSTEM"}})}}async prepareDiffAsset(e,t,r){let a=await this.requireRunnable(e,l.WORKTREE_DIFF_ASSET_JOB_KIND,!0),n=this.payload(a);if(!n.baseBranch)throw Error("A base branch is required");let s=await this.createSerializedCodebaseJob({agentId:a.codebase.agentId,codebaseId:a.codebaseId,worktreeId:a.id,kind:l.WORKTREE_DIFF_ASSET_JOB_KIND,payload:{...n,baseBranch:n.baseBranch,scope:t.scope,path:t.path,previousPath:t.previousPath??null,commitSha:t.commitSha??null,uploadId:r,side:t.side},idempotencyKey:`worktree:diff-asset:${r}:${e}`,timeoutSeconds:60,visibility:"SYSTEM"});try{R(await this.waitForJob(s.id))}finally{let e=await (0,i.getPrismaClient)();await e.agentJob.deleteMany({where:{id:s.id,visibility:"SYSTEM"}})}}async diffAssetAgentId(e){let t=await (0,i.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e},select:{codebase:{select:{agentId:!0}}}});return r?.codebase.agentId??null}async runOperation(e,t,r){if(!l.WORKTREE_OPERATIONS.includes(t))throw Error("Unknown worktree operation");let i=await this.requireRunnable(e,l.WORKTREE_OPERATION_JOB_KIND),a=await this.settings();return this.agentControl.createJob({agentId:i.codebase.agentId,codebaseId:i.codebaseId,worktreeId:i.id,kind:l.WORKTREE_OPERATION_JOB_KIND,payload:{...this.payload(i),operation:t,..."OPEN_EDITOR"===t?{editorVariant:a.editorVariant}:{}},idempotencyKey:`worktree:operation:${r}:${e}`,timeoutSeconds:"OPEN_EDITOR"===t?30:600})}async createAutoSyncJob(e,t,r,i){let a=await this.requireRunnable(e,l.WORKTREE_AUTO_SYNC_JOB_KIND),n=this.payload(a);if(!n.baseBranch)throw Error("Auto Sync requires a base branch");return this.agentControl.createJob({agentId:a.codebase.agentId,codebaseId:a.codebaseId,worktreeId:a.id,kind:l.WORKTREE_AUTO_SYNC_JOB_KIND,payload:{...n,expectedBranch:r,baseBranch:n.baseBranch,phase:t},idempotencyKey:`worktree:auto-sync:${t.toLowerCase()}:${i}:${e}`,timeoutSeconds:600})}publishAutomationChange(e,t=null){this.publish(e,t)}async inspectGitState(e,t){if(!t.trim())throw Error("requestId is required");let r=await this.requireRunnable(e,l.WORKTREE_GIT_INSPECT_JOB_KIND,!0),a=await this.createSerializedCodebaseJob({agentId:r.codebase.agentId,codebaseId:r.codebaseId,worktreeId:r.id,kind:l.WORKTREE_GIT_INSPECT_JOB_KIND,payload:{action:"STATE",codebaseId:r.codebaseId,folder:r.folder,gitDirectory:r.gitDirectory,expectedOrigin:r.codebase.repository.canonicalOrigin},idempotencyKey:`worktree:git:state:${t}:${e}`,timeoutSeconds:30,visibility:"SYSTEM"});try{let e=await this.waitForJob(a.id);return(0,o.parseCodebaseGitState)(R(e).state)}finally{let e=await (0,i.getPrismaClient)();await e.agentJob.deleteMany({where:{id:a.id,visibility:"SYSTEM"}})}}async runGitOperation(e){if(!e.requestId.trim())throw Error("requestId is required");if(!l.WORKTREE_GIT_OPERATIONS.includes(e.operation))throw Error("Unknown worktree Git operation");let t=await this.requireRunnable(e.worktreeId,l.WORKTREE_GIT_OPERATION_JOB_KIND);return this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:l.WORKTREE_GIT_OPERATION_JOB_KIND,payload:{codebaseId:t.codebaseId,folder:t.folder,gitDirectory:t.gitDirectory,expectedOrigin:t.codebase.repository.canonicalOrigin,baseBranch:t.baseBranchOverride??t.codebase.defaultBranch??null,defaultBranch:t.codebase.defaultBranch,operation:e.operation,...e.branch?{branch:e.branch}:{},...e.stashOid?{stashOid:e.stashOid}:{},..."SWITCH_BRANCH"===e.operation?{stashChanges:!!e.stashChanges}:{}},idempotencyKey:`worktree:git:${e.operation}:${e.requestId}:${e.worktreeId}`,timeoutSeconds:"PULL_BRANCH"===e.operation?300:60})}payload(e){return{codebaseId:e.codebaseId,folder:e.folder,gitDirectory:e.gitDirectory,expectedOrigin:e.codebase.repository.canonicalOrigin,baseBranch:e.baseBranchOverride??e.codebase.defaultBranch??null}}async createSerializedCodebaseJob(e){let t=await (0,i.getPrismaClient)(),r=Date.now()+3e4;for(;Date.now()<r;){let i=await t.agentJob.findFirst({where:{codebaseId:e.codebaseId,status:{in:y}},select:{id:!0,idempotencyKey:!0,kind:!0}});if(i){if(i.idempotencyKey===e.idempotencyKey)return this.agentControl.createJob(e);await this.waitForCodebaseJob(i.id,r);continue}try{return await this.agentControl.createJob(e)}catch(e){if(!function(e){if(!e||"object"!=typeof e||"P2002"!==e.code)return!1;let t=e.meta?.target;return Array.isArray(t)?t.includes("codebaseId"):"string"==typeof t&&t.includes("codebaseId")}(e))throw e}}throw new u.CodebaseBusyError}async waitForCodebaseJob(e,t){let r=n.agentEventBus.iterate((0,n.agentJobChangedTopic)(e));try{for(;Date.now()<t;){let i=await this.agentControl.getJob(e);if(!i||!y.includes(i.status))return;await Promise.race([r.next(),new Promise(e=>setTimeout(e,Math.max(0,t-Date.now())))])}throw new u.CodebaseBusyError}finally{await r.return?.()}}async requireRunnable(e,t,r=!1){let a=await (0,i.getPrismaClient)(),n=await a.worktree.findUnique({where:{id:e},include:{codebase:{include:{agent:!0,repository:!0}}}});if(!n||n.missingAt||"AVAILABLE"!==n.availability)throw Error("Worktree is unavailable");if(!k(n.codebase.agent))throw Error("Agent is offline");if(!S(n.codebase.agent).includes(t))throw Error("Agent must be updated to use worktrees");if(!r){let[e,t]=await Promise.all([a.agentJob.findFirst({where:{codebaseId:n.codebaseId,status:{in:y}}}),a.worktreeMove.findFirst({where:{status:{in:w},OR:[{sourceCodebaseId:n.codebaseId},{targetCodebaseId:n.codebaseId}]}})]);if(e||t)throw new u.CodebaseBusyError}return n}async requireRunnableCodebase(e,t=l.WORKTREE_BRANCH_JOB_KIND){let r=await (0,i.getPrismaClient)(),a=await r.codebase.findUnique({where:{id:e},include:{agent:!0,repository:!0}});if(!a||"AVAILABLE"!==a.availability)throw Error("Codebase is unavailable");if(!k(a.agent))throw Error("Agent is offline");if(!S(a.agent).includes(t))throw Error("Agent must be updated to create or change worktrees");let[n,s]=await Promise.all([r.agentJob.findFirst({where:{codebaseId:e,status:{in:y}}}),r.worktreeMove.findFirst({where:{status:{in:w},OR:[{sourceCodebaseId:e},{targetCodebaseId:e}]}})]);if(n||s)throw new u.CodebaseBusyError;return a}async purge(e){let t=await (0,i.getPrismaClient)(),r=await t.worktree.deleteMany({where:{id:e,missingAt:{not:null}}});return r.count&&this.publish(e,null),r.count>0}async purgeAll(){let e=await (0,i.getPrismaClient)(),t=await e.worktree.deleteMany({where:{missingAt:{not:null}}});return t.count&&this.publish(null,null),t.count}subscribe(){return n.agentEventBus.iterate(n.WORKTREE_CHANGED_TOPIC)}async *subscribeInspection(e){let t=n.agentEventBus.iterate((0,n.worktreeInspectionTopic)(e)),r=!1;try{for await(let i of(await this.acquireWatch(e),r=!0,t))yield i}finally{await t.return?.(),r&&await this.releaseWatch(e)}}async acquireWatch(e){let r=this.watchDemand.get(e);if(r){r.subscribers+=1,await r.started;return}let i=await this.requireRunnable(e,l.WORKTREE_WATCH_JOB_KIND,!0),a=(0,t.randomUUID)(),n=this.payload(i),s={subscribers:1,watchId:a,agentId:i.codebase.agentId,worktreeId:i.id,codebaseId:i.codebaseId,payload:n,started:Promise.resolve()};s.started=this.runWatchAction(s,"START"),this.watchDemand.set(e,s);try{await s.started}catch(t){throw this.watchDemand.get(e)===s&&this.watchDemand.delete(e),t}}async releaseWatch(e){let t=this.watchDemand.get(e);if(t&&(t.subscribers-=1,!(t.subscribers>0))){this.watchDemand.delete(e);try{await t.started,await this.runWatchAction(t,"STOP")}catch(e){console.error("Could not stop worktree watcher:",e instanceof Error?e.message:e)}}}async runWatchAction(e,t){let r=await this.agentControl.createJob({agentId:e.agentId,worktreeId:e.worktreeId,kind:l.WORKTREE_WATCH_JOB_KIND,payload:{...e.payload,action:t,watchId:e.watchId},idempotencyKey:`worktree:watch:${t}:${e.watchId}`,timeoutSeconds:30,visibility:"SYSTEM"});try{R(await this.waitForJob(r.id))}finally{let e=await (0,i.getPrismaClient)();await e.agentJob.deleteMany({where:{id:r.id,visibility:"SYSTEM"}})}}async restartWatch(e){let r=this.watchDemand.get(e);if(r)try{if(await r.started,this.watchDemand.get(e)!==r||(await this.runWatchAction(r,"STOP"),this.watchDemand.get(e)!==r))return;let i=await this.requireRunnable(e,l.WORKTREE_WATCH_JOB_KIND,!0),a={subscribers:r.subscribers,watchId:(0,t.randomUUID)(),agentId:i.codebase.agentId,worktreeId:i.id,codebaseId:i.codebaseId,payload:this.payload(i),started:Promise.resolve()};a.started=this.runWatchAction(a,"START"),this.watchDemand.set(e,a),await a.started}catch(e){console.error("Could not restart worktree watcher:",e instanceof Error?e.message:e)}}publish(e,t){n.agentEventBus.publish(n.WORKTREE_CHANGED_TOPIC,{worktreeOverviewChanged:{worktreeId:e,codebaseId:t}})}moveIdFromJob(e){let t=JSON.parse(e.payloadJson);if(!t||"object"!=typeof t||Array.isArray(t)||"string"!=typeof t.moveId)throw Error("Move job is missing its workflow identifier");return String(t.moveId)}async failMove(e,t,r){let a=await (0,i.getPrismaClient)();(await a.worktreeMove.updateMany({where:{id:e,status:t},data:{status:"FAILED",error:r,finishedAt:new Date}})).count&&this.publish(null,null)}async createMoveCheckoutJob(e,t){let r=await (0,i.getPrismaClient)(),a=await r.codebase.findUnique({where:{id:e.targetCodebaseId},include:{agent:!0,repository:!0}});if(!a)throw Error("Destination codebase no longer exists");if(!k(a.agent))throw Error("Destination agent is offline");if(!S(a.agent).includes(l.WORKTREE_MOVE_CHECKOUT_JOB_KIND))throw Error("Destination agent must be updated to move worktrees");let n=e.targetWorktreeId?await r.worktree.findFirst({where:{id:e.targetWorktreeId,codebaseId:a.id,missingAt:null,availability:"AVAILABLE"}}):null;if("EXISTING"===e.destinationMode&&!n)throw Error("Destination worktree is no longer available");return this.agentControl.createJob({agentId:a.agentId,codebaseId:a.id,worktreeId:n?.id??null,kind:l.WORKTREE_MOVE_CHECKOUT_JOB_KIND,payload:{moveId:e.id,codebaseId:a.id,rootFolder:a.folder,folder:n?.folder??null,gitDirectory:n?.gitDirectory??null,expectedOrigin:a.repository.canonicalOrigin,branch:e.branch,expectedHeadSha:e.headSha,baseBranch:e.baseBranch,mode:e.destinationMode,stashOnFailure:t},idempotencyKey:`worktree:move:checkout:${e.id}:${t?"stash":"initial"}`,timeoutSeconds:600})}async advanceMoveAfterPush(e){let t=this.moveIdFromJob(e),r=await (0,i.getPrismaClient)(),a=await r.worktreeMove.findUnique({where:{id:t}});if(!a||"PUSHING"!==a.status||a.sourceJobId&&a.sourceJobId!==e.id)return;if("SUCCEEDED"!==e.status)return void await this.failMove(a.id,"PUSHING",e.error||"Could not push the source branch");let n=R(e);if(n.headSha!==a.headSha||n.branch!==a.branch)return void await this.failMove(a.id,"PUSHING","The source push returned an unexpected branch");try{let e=await this.createMoveCheckoutJob(a,!1);await r.worktreeMove.updateMany({where:{id:a.id,status:"PUSHING"},data:{status:"CHECKING_OUT",targetJobId:e.id}}),this.publish(a.sourceWorktreeId,a.sourceCodebaseId)}catch(e){await this.failMove(a.id,"PUSHING",e instanceof Error?e.message:String(e))}}async projectMoveDestination(e,r){let a=(0,l.parseWorktreeInventoryItem)(r),n=await (0,i.getPrismaClient)(),s=await n.codebase.findUnique({where:{id:e.targetCodebaseId},select:{localBranchesJson:!0}});if(!s)throw Error("Destination codebase no longer exists");let o=new Set(E(s.localBranchesJson));a.branch&&o.add(a.branch);let u=e.targetWorktreeId;return await n.$transaction(async r=>{if(await r.codebase.update({where:{id:e.targetCodebaseId},data:{localBranchesJson:JSON.stringify([...o].sort((e,t)=>e.localeCompare(t)))}}),u){if(1!==(await r.worktree.updateMany({where:{id:u,codebaseId:e.targetCodebaseId},data:{...this.inventoryData(a),gitDirectory:a.gitDirectory,baseBranchOverride:e.baseBranch,missingAt:null}})).count)throw Error("Destination worktree no longer exists")}else u=(await r.worktree.upsert({where:{codebaseId_gitDirectory:{codebaseId:e.targetCodebaseId,gitDirectory:a.gitDirectory}},create:{id:(0,t.randomUUID)(),codebaseId:e.targetCodebaseId,gitDirectory:a.gitDirectory,...this.inventoryData(a),baseBranchOverride:e.baseBranch},update:{...this.inventoryData(a),baseBranchOverride:e.baseBranch,missingAt:null}})).id;await r.worktreeMove.update({where:{id:e.id},data:{targetWorktreeId:u}})}),this.publish(u??null,e.targetCodebaseId),await this.skillsService?.requestAutoReconcile(),u}async scheduleMoveCleanup(e){let t=await (0,i.getPrismaClient)(),r=await t.worktreeMove.findUniqueOrThrow({where:{id:e}}),a=await t.worktree.findUnique({where:{id:r.sourceWorktreeId},include:{codebase:{include:{agent:!0,repository:!0}}}});if(!a||a.missingAt||a.primary){await t.worktreeMove.update({where:{id:r.id},data:{status:"SUCCEEDED_WITH_WARNING",warning:"Destination is ready, but the source worktree could not be removed",finishedAt:new Date}}),this.publish(r.sourceWorktreeId,r.sourceCodebaseId);return}try{let e=await this.agentControl.createJob({agentId:a.codebase.agentId,codebaseId:a.codebaseId,worktreeId:a.id,kind:l.WORKTREE_DELETE_JOB_KIND,payload:{moveId:r.id,codebaseId:a.codebaseId,rootFolder:a.codebase.folder,folder:a.folder,gitDirectory:a.gitDirectory,expectedOrigin:a.codebase.repository.canonicalOrigin,branch:a.branch,defaultBranch:a.codebase.defaultBranch,deleteRemoteBranch:!1,requireClean:!0,expectedHeadSha:r.headSha},idempotencyKey:`worktree:move:cleanup:${r.id}`,timeoutSeconds:600});await t.worktreeMove.updateMany({where:{id:r.id,status:{in:["PUSHING","CHECKING_OUT","AWAITING_STASH"]}},data:{status:"CLEANING_UP",cleanupJobId:e.id}}),this.publish(a.id,a.codebaseId)}catch(e){await t.worktreeMove.update({where:{id:r.id},data:{status:"SUCCEEDED_WITH_WARNING",warning:e instanceof Error?e.message:String(e),finishedAt:new Date}}),this.publish(a.id,a.codebaseId)}}async advanceMoveAfterCheckout(e){let t=this.moveIdFromJob(e),r=await (0,i.getPrismaClient)(),a=await r.worktreeMove.findUnique({where:{id:t}});if(!a||!["PUSHING","CHECKING_OUT","AWAITING_STASH"].includes(a.status)||a.targetJobId&&a.targetJobId!==e.id)return;if("SUCCEEDED"!==e.status)return void await this.failMove(a.id,a.status,e.error||"Could not check out the destination branch");let n=R(e);if("NEEDS_STASH"===n.outcome){await r.worktreeMove.updateMany({where:{id:a.id,status:{in:["PUSHING","CHECKING_OUT","AWAITING_STASH"]}},data:{status:"AWAITING_STASH",error:"string"==typeof n.message?n.message:"Destination changes block the branch switch"}}),this.publish(a.sourceWorktreeId,a.sourceCodebaseId);return}"CHECKED_OUT"===n.outcome&&n.worktree?(await this.projectMoveDestination(a,n.worktree),a.deleteSource?await this.scheduleMoveCleanup(a.id):(await r.worktreeMove.update({where:{id:a.id},data:{status:"SUCCEEDED",error:null,finishedAt:new Date}}),this.publish(a.sourceWorktreeId,a.sourceCodebaseId))):await this.failMove(a.id,a.status,"Destination checkout returned an invalid result")}async projectDeleteOperation(e){let t=JSON.parse(e.payloadJson),r=t&&"object"==typeof t&&!Array.isArray(t)&&"string"==typeof t.moveId?String(t.moveId):null,a=await (0,i.getPrismaClient)();if(r){let t=await a.worktreeMove.findUnique({where:{id:r}});if(!t||!["PUSHING","CHECKING_OUT","AWAITING_STASH","CLEANING_UP"].includes(t.status)||t.cleanupJobId&&t.cleanupJobId!==e.id)return;if("SUCCEEDED"!==e.status){await a.worktreeMove.update({where:{id:t.id},data:{status:"SUCCEEDED_WITH_WARNING",warning:e.error||"Destination is ready, but the source worktree was retained",finishedAt:new Date}}),this.publish(t.sourceWorktreeId,t.sourceCodebaseId);return}await a.$transaction([a.worktree.deleteMany({where:{id:t.sourceWorktreeId}}),a.worktreeMove.update({where:{id:t.id},data:{status:"SUCCEEDED",finishedAt:new Date}})]),this.publish(t.sourceWorktreeId,t.sourceCodebaseId);return}if("SUCCEEDED"!==e.status||!e.worktreeId)return;let n=await a.worktree.findUnique({where:{id:e.worktreeId},select:{codebaseId:!0}});await a.worktree.deleteMany({where:{id:e.worktreeId}}),this.publish(e.worktreeId,n?.codebaseId??null)}async projectOperation(e){if(!e.worktreeId||"SUCCEEDED"!==e.status||!e.resultJson)return;let t=R({...e,error:null});if(!t.worktree)return;let r=(0,l.parseWorktreeInventoryItem)(t.worktree),a=await (0,i.getPrismaClient)(),n=await a.worktree.findUnique({where:{id:e.worktreeId}});if(!n)return;let s=new Date(r.checkedAt);(await a.worktree.updateMany({where:{id:n.id,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:s}}]},data:{branch:r.branch,headSha:r.headSha,upstream:r.upstream,ahead:r.ahead,behind:r.behind,syncState:r.syncState,baseAhead:r.baseAhead,baseBehind:r.baseBehind,hasStagedChanges:r.hasStagedChanges??!1,hasUnstagedChanges:r.hasUnstagedChanges??!1,rebaseInProgress:r.rebaseInProgress??!1,hasConflicts:r.hasConflicts??!1,pushStatus:r.pushStatus??"UNKNOWN",availability:r.availability,statusError:r.error,lastCheckedAt:s}})).count>0&&this.publish(n.id,n.codebaseId)}async projectBranchOperation(e){if(!e.codebaseId||"SUCCEEDED"!==e.status||!e.resultJson)return;let r=R({...e,error:null});if(!r.worktree||"string"!=typeof r.baseBranch)return;let a=(0,l.parseWorktreeInventoryItem)(r.worktree),n=await (0,i.getPrismaClient)(),s=await n.codebase.findUnique({where:{id:e.codebaseId},select:{localBranchesJson:!0}});if(!s)return;let o=new Set(E(s.localBranchesJson));a.branch&&o.add(a.branch);let u=e.worktreeId;await n.$transaction(async i=>{if(await i.codebase.update({where:{id:e.codebaseId},data:{localBranchesJson:JSON.stringify([...o].sort((e,t)=>e.localeCompare(t)))}}),e.worktreeId){if(1!==(await i.worktree.updateMany({where:{id:e.worktreeId,codebaseId:e.codebaseId},data:{...this.inventoryData(a),gitDirectory:a.gitDirectory,baseBranchOverride:r.baseBranch,missingAt:null}})).count)throw Error("Worktree no longer exists");return}u=(await i.worktree.upsert({where:{codebaseId_gitDirectory:{codebaseId:e.codebaseId,gitDirectory:a.gitDirectory}},create:{id:(0,t.randomUUID)(),codebaseId:e.codebaseId,gitDirectory:a.gitDirectory,...this.inventoryData(a),baseBranchOverride:r.baseBranch},update:{...this.inventoryData(a),baseBranchOverride:r.baseBranch,missingAt:null}})).id}),this.publish(u??null,e.codebaseId),!e.worktreeId&&u&&await this.recordWorktreeCreated(u),await this.skillsService?.requestAutoReconcile(),e.worktreeId&&await this.restartWatch(e.worktreeId)}async recordWorktreeCreated(e){if(!this.workflowEvents)return;let t=await this.workflowSessionDataForWorktree(e);Object.keys(t).length&&await this.workflowEvents.record({kind:"WORKTREE_CREATED",subjectKey:e,dedupeKey:`worktree-created:${e}`,payload:{...t,sessionData:t}})}async waitForJob(e){let t=n.agentEventBus.iterate((0,n.agentJobChangedTopic)(e)),r=Date.now()+3e4;try{for(;Date.now()<r;){let i=await this.agentControl.getJob(e);if(!i)throw Error("Worktree job disappeared");if(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"].includes(i.status))return i;await Promise.race([t.next(),new Promise(e=>setTimeout(e,r-Date.now()))])}throw await this.agentControl.cancelJob(e),Error("Agent did not respond in time")}finally{await t.return?.()}}},"worktreeDisplayPath",0,C],504173),e.s(["executingResourcesByWorktree",0,D],518733);let N=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT","INVALID"]),O={agents:{include:{agent:!0}},jobs:{orderBy:{createdAt:"asc"}}};function P(e){return null!==e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(e)&&null===e.disconnectedAt}function $(e){try{let t=JSON.parse(e.capabilitiesJson);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function U(e){return null===e?null:JSON.parse(e)}function B(e){let t=U(e.payloadJson);return(e.kind===r.BUILD_DATA_DELETE_JOB_KIND?(0,r.buildDataDeletePayload)(t).targets:(0,r.buildDataTargetsPayload)(t).targets).map(e=>e.path)}function j(e,t){let i=e===r.BUILD_DATA_DELETE_JOB_KIND?"delete":"size";return`Invalid Build Data ${i} result: ${t instanceof Error?t.message:String(t)}`}function L(e,t,r){try{for(let i of B(t)){let a=e.get(q(t.agentId,i));a&&(a.error=r)}}catch{}}function q(e,r){return(0,t.createHash)("sha256").update(e).update("\0").update(r).digest("base64url")}e.s(["BuildDataService",0,class{agentControlService;initialized;constructor(e){this.agentControlService=e,this.initialized=!1,this.agentControlService.registerCompletionHandler(r.BUILD_DATA_DELETE_JOB_KIND,e=>this.projectDeletion(e))}async initialize(){this.initialized||(await this.pruneHistory(),this.initialized=!0)}async refresh(e){await this.initialize();let r=e?.trim()||(0,t.randomUUID)();return await this.ensureCollection(r),await this.getCollection(r)}async getCollection(e){await this.initialize();let t=await this.loadCollection(e);if(!t)return null;!t.finishedAt&&t.deadlineAt.getTime()<=Date.now()&&(await this.expireCollection(t),t=await this.loadCollection(e)??t);let r=await this.snapshot(t);if("COMPLETED"===r.status&&!t.finishedAt){let t=new Date,a=await (0,i.getPrismaClient)();await a.buildDataCollection.updateMany({where:{id:e,finishedAt:null},data:{finishedAt:t}}),r.finishedAt=t.toISOString()}return r}async *subscribe(e){await this.initialize();let t=n.agentEventBus.iterate((0,n.buildDataCollectionChangedTopic)(e));try{let r=await this.getCollection(e);for(r&&(yield r);;){if((await t.next()).done)return;let r=await this.getCollection(e);r&&(yield r)}}finally{await t.return?.()}}async calculateSizes(e,t,i){let a=await this.requireCollection(e);return await this.createTargetJobs(a,t,i,r.BUILD_DATA_SIZE_JOB_KIND),await this.getCollection(e)}async deleteEntries(e,t,i,a=!1){let n=await this.requireCollection(e);return await this.createTargetJobs(n,t,i,r.BUILD_DATA_DELETE_JOB_KIND,a),await this.getCollection(e)}async history(e=100,t){await this.initialize(),await this.pruneHistory();let r=Math.max(1,Math.min(e,200)),a=await (0,i.getPrismaClient)(),n=t?await a.buildDataDeletionHistory.findUnique({where:{id:t},select:{id:!0,deletedAt:!0}}):null,s=await a.buildDataDeletionHistory.findMany({where:n?{OR:[{deletedAt:{lt:n.deletedAt}},{deletedAt:n.deletedAt,id:{lt:n.id}}]}:void 0,orderBy:[{deletedAt:"desc"},{id:"desc"}],take:r+1}),o=s.length>r,l=s.slice(0,r);return{items:l,nextCursor:o?l.at(-1)?.id??null:null}}async clearHistory(){await this.initialize();let e=await (0,i.getPrismaClient)();return(await e.buildDataDeletionHistory.deleteMany()).count}async ensureCollection(e){let t=await (0,i.getPrismaClient)(),a=await t.buildDataCollection.findUnique({where:{id:e},select:{id:!0}});if(!a){let i=await this.agentControlService.listAgents();try{a=await t.buildDataCollection.create({data:{id:e,deadlineAt:new Date(Date.now()+6e4),agents:{create:i.map(e=>({agentId:e.id,initialStatus:P(e)?$(e).includes(r.BUILD_DATA_SCAN_JOB_KIND)?"QUEUING":"UNSUPPORTED":"OFFLINE"}))}},select:{id:!0}}),this.publish(e)}catch(r){if(!(a=await t.buildDataCollection.findUnique({where:{id:e},select:{id:!0}})))throw r}}await this.ensureScanJobs(e)}async ensureScanJobs(e){let t=await (0,i.getPrismaClient)(),a=await t.buildDataCollection.findUnique({where:{id:e},select:{deadlineAt:!0,finishedAt:!0}});if(!a||a.finishedAt||a.deadlineAt<=new Date)return;let n=await t.buildDataCollectionAgent.findMany({where:{collectionId:e,initialStatus:"QUEUING"},include:{agent:!0}}),s=new Set((await t.agentJob.findMany({where:{buildDataCollectionId:e,kind:r.BUILD_DATA_SCAN_JOB_KIND},select:{agentId:!0}})).map(e=>e.agentId));for(let i of n)if(!s.has(i.agentId))try{let a=await t.worktree.findMany({where:{missingAt:null,codebase:{agentId:i.agentId}},select:{id:!0,folder:!0}});await this.agentControlService.createJob({agentId:i.agentId,kind:r.BUILD_DATA_SCAN_JOB_KIND,payload:{mode:i.agent.derivedDataLocationMode,path:i.agent.derivedDataPath,worktrees:a},idempotencyKey:`build-data:scan:${e}`,timeoutSeconds:45,buildDataCollectionId:e,visibility:"SYSTEM"})}catch(r){await t.buildDataCollectionAgent.update({where:{collectionId_agentId:{collectionId:e,agentId:i.agentId}},data:{initialStatus:"FAILED",error:r instanceof Error?r.message:String(r)}}),this.publish(e)}}async createTargetJobs(e,t,a,n,s=!1){let o=[...new Set(t)];if(!o.length)throw Error("Select at least one Derived Data entry");let l=new Map(e.entries.map(e=>[e.id,e])),u=o.map(e=>{let t=l.get(e);if(!t)throw Error("A selected Derived Data entry is no longer available");return t});if(n===r.BUILD_DATA_DELETE_JOB_KIND&&!s){let e=u.filter(e=>e.locked||e.activeResources.length>0);if(e.length)throw Error(`Explicit override confirmation is required to delete protected Derived Data: ${e.map(e=>e.name).join(", ")}`)}let c=new Map;for(let e of u){let t=c.get(e.agent.id)??[];t.push(e),c.set(e.agent.id,t)}let d=await (0,i.getPrismaClient)(),p=[];for(let[e,t]of c){let r=t[0].agent,i=await d.agent.findUnique({where:{id:e}});if(!i||!P(i))throw Error(`${r.name} is offline; reconnect it before running this operation`);if(!$(i).includes(n))throw Error(`${r.name} must be updated before this operation can run`);p.push({agentId:e,entries:t})}for(let{agentId:t,entries:i}of p){let s=n===r.BUILD_DATA_DELETE_JOB_KIND?[...new Map(i.filter(e=>!!e.worktreeId).map(e=>[e.worktreeId,e])).values()]:[],o=[];try{for(let e of s)await d.derivedDataCleanupLease.create({data:{worktreeId:e.worktreeId,agentId:t,path:e.path,source:"USER",expiresAt:new Date(Date.now()+6048e5)}}),o.push(e.worktreeId);let r=await this.agentControlService.createJob({agentId:t,kind:n,payload:{targets:i.map(({path:e,rootPath:t})=>({path:e,rootPath:t}))},idempotencyKey:`${n}:${e.id}:${a}:${t}`,timeoutSeconds:604800,buildDataCollectionId:e.id,visibility:"SYSTEM"});s.length&&await d.derivedDataCleanupLease.updateMany({where:{worktreeId:{in:s.map(e=>e.worktreeId)},jobId:null},data:{jobId:r.id}})}catch(e){throw o.length&&await d.derivedDataCleanupLease.deleteMany({where:{worktreeId:{in:o},source:"USER",jobId:null}}),e}}}async requireCollection(e){let t=await this.getCollection(e);if(!t)throw Error("Derived Data collection not found");if("COMPLETED"!==t.status)throw Error("Wait for the Derived Data scan to finish");return t}async loadCollection(e){return(await (0,i.getPrismaClient)()).buildDataCollection.findUnique({where:{id:e},include:O})}progress(e){let t=new Map(e.jobs.filter(e=>e.kind===r.BUILD_DATA_SCAN_JOB_KIND).map(e=>[e.agentId,e])),i=e.agents.map(e=>{let i=t.get(e.agentId),a=e.initialStatus,n=e.error,s=[];if("QUEUING"===e.initialStatus&&i&&(a=i.status,n=i.error,"SUCCEEDED"===i.status))try{s=(0,r.parseBuildDataScanResult)(U(i.resultJson)).warnings}catch(e){a="INVALID",n=e instanceof Error?e.message:String(e)}return{agent:e.agent,status:a,jobId:i?.id??null,error:n,warnings:s}}),a=i.filter(({status:e})=>"OFFLINE"!==e&&"UNSUPPORTED"!==e),n=a.filter(({status:e})=>N.has(e));return{agents:i,eligibleCount:a.length,finishedCount:n.length,successfulCount:a.filter(({status:e})=>"SUCCEEDED"===e).length}}async snapshot(e){let t=this.progress(e),r=await this.entries(e,!1);return{id:e.id,status:t.finishedCount===t.eligibleCount?"COMPLETED":"COLLECTING",createdAt:e.createdAt.toISOString(),deadlineAt:e.deadlineAt.toISOString(),finishedAt:e.finishedAt?.toISOString()??null,progress:t,entries:r}}async entries(e,t){let a=await (0,i.getPrismaClient)(),n=new Map(e.agents.map(e=>[e.agentId,e.agent])),s=await a.worktree.findMany({where:{missingAt:null,codebase:{agentId:{in:[...n.keys()]}}},include:{codebase:{select:{agentId:!0}}}}),o=new Map;for(let e of s){let t=o.get(e.codebase.agentId)??[];t.push(e),o.set(e.codebase.agentId,t)}let l=new Map;for(let t of e.jobs){let e;if(t.kind!==r.BUILD_DATA_SCAN_JOB_KIND||"SUCCEEDED"!==t.status)continue;let i=n.get(t.agentId);if(i){try{e=(0,r.parseBuildDataScanResult)(U(t.resultJson))}catch{continue}for(let r of e.entries){let e=(r.workspacePath?(o.get(t.agentId)??[]).filter(e=>(function(e,t){let r="/"===e?e:e.replace(/\/+$/,"");return t===r||t.startsWith(`${r}/`)})(e.folder,r.workspacePath)).sort((e,t)=>t.folder.length-e.folder.length):[])[0]??null,a=q(t.agentId,r.path);l.set(a,{id:a,name:r.name,kind:r.kind,status:"DEVICE_SUPPORT"===r.kind?"READY":"PENDING"===r.kind?"PENDING":"SHARED_CACHE"===r.kind?"SHARED_CACHE":e?"READY":"UNLINKED",workspacePath:r.workspacePath,worktreeId:e?.id??null,worktreePath:e?C(e.folder,i.baseRepoDirectory):null,sizeBytes:null,operation:"IDLE",error:null,agent:i,path:r.path,rootPath:r.rootPath,modifiedAt:r.modifiedAt,volumeId:r.volumeId,locked:!1,activeResources:[]})}}}for(let i of e.jobs){if(i.kind===r.BUILD_DATA_SIZE_JOB_KIND&&"SUCCEEDED"===i.status)try{for(let e of(0,r.parseBuildDataSizeResult)(U(i.resultJson)).sizes){let t=l.get(q(i.agentId,e.path));t&&(t.sizeBytes=e.sizeBytes,t.error=e.error)}}catch(e){L(l,i,j(r.BUILD_DATA_SIZE_JOB_KIND,e))}if(i.kind===r.BUILD_DATA_DELETE_JOB_KIND&&"SUCCEEDED"===i.status)try{for(let e of(0,r.parseBuildDataDeleteResult)(U(i.resultJson)).deleted){let r=q(i.agentId,e.path),a=l.get(r);a&&(e.deleted&&!t?l.delete(r):a.error=e.error)}}catch(e){L(l,i,j(r.BUILD_DATA_DELETE_JOB_KIND,e))}if("QUEUED"===i.status||"RUNNING"===i.status){if(i.kind!==r.BUILD_DATA_SIZE_JOB_KIND&&i.kind!==r.BUILD_DATA_DELETE_JOB_KIND)continue;try{for(let e of B(i)){let t=l.get(q(i.agentId,e));t&&(t.operation=i.kind===r.BUILD_DATA_DELETE_JOB_KIND?"DELETING":"SIZING")}}catch{}}if("SUCCEEDED"!==i.status&&N.has(i.status)&&(i.kind===r.BUILD_DATA_SIZE_JOB_KIND||i.kind===r.BUILD_DATA_DELETE_JOB_KIND))try{for(let e of B(i)){let t=l.get(q(i.agentId,e));t&&(t.error=i.error||"Build Data operation failed")}}catch{}}let u=[...l.values()],c=u.map(e=>e.worktreeId).filter(e=>!!e),[d,p]=await Promise.all([a.derivedDataLock.findMany({where:{OR:u.map(e=>({agentId:e.agent.id,path:e.path}))},select:{agentId:!0,path:!0}}),D(c)]),h=new Set(d.map(e=>`${e.agentId}\0${e.path}`));for(let e of u)e.locked=h.has(`${e.agent.id}\0${e.path}`),e.activeResources=e.worktreeId?p.get(e.worktreeId)??[]:[];return u.sort((e,t)=>e.agent.name.localeCompare(t.agent.name)||(null===e.modifiedAt?1:null===t.modifiedAt?-1:new Date(e.modifiedAt).getTime()-new Date(t.modifiedAt).getTime())||e.name.localeCompare(t.name))}async setEntryLocked(e,r,a){let n=(await this.requireCollection(e)).entries.find(e=>e.id===r);if(!n)throw Error("Derived Data entry not found");let s=await (0,i.getPrismaClient)();return a?await s.derivedDataLock.upsert({where:{agentId_path:{agentId:n.agent.id,path:n.path}},create:{id:(0,t.randomUUID)(),agentId:n.agent.id,path:n.path},update:{}}):await s.derivedDataLock.deleteMany({where:{agentId:n.agent.id,path:n.path}}),this.publish(e),await this.getCollection(e)}async expireCollection(e){let t=await (0,i.getPrismaClient)(),a=new Set(e.jobs.filter(e=>e.kind===r.BUILD_DATA_SCAN_JOB_KIND).map(e=>e.agentId));await t.buildDataCollectionAgent.updateMany({where:{collectionId:e.id,initialStatus:"QUEUING",agentId:{notIn:[...a]}},data:{initialStatus:"TIMED_OUT"}}),await this.agentControlService.timeoutBuildDataCollectionJobs(e.id),this.publish(e.id)}async projectDeletion(e){let a;if("SUCCEEDED"!==e.status||!e.resultJson)return;await this.pruneHistory();let n=await (0,i.getPrismaClient)();if(await n.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))return;try{a=(0,r.parseBuildDataDeleteResult)(U(e.resultJson)).deleted.filter(e=>e.deleted)}catch(i){let t=j(r.BUILD_DATA_DELETE_JOB_KIND,i);try{await n.buildDataDeleteProjection.create({data:{jobId:e.id,error:t}})}catch(t){if(!await n.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))throw t}return}if(!a.length)return void await n.buildDataDeleteProjection.create({data:{jobId:e.id}});let s=(0,r.buildDataDeletePayload)(U(e.payloadJson)),o=e.buildDataCollectionId?await this.loadCollection(e.buildDataCollectionId):null,l=new Map((o?await this.entries(o,!0):[]).filter(t=>t.agent.id===e.agentId).map(e=>[e.path,e])),u=new Map(s.targets.map(e=>[e.path,e])),c=await n.agent.findUnique({where:{id:e.agentId}});if(c)try{await n.$transaction(async r=>{if(!await r.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))for(let i of(await r.buildDataDeleteProjection.create({data:{jobId:e.id}}),a)){let a=l.get(i.path),n=u.get(i.path),o=n?.worktreeId??a?.worktreeId??null,d=o?(await r.worktree.findUnique({where:{id:o},select:{id:!0}}))?.id??null:null;await r.buildDataDeletionHistory.create({data:{id:(0,t.randomUUID)(),agentId:e.agentId,agentName:c.name,folderName:n?.name??a?.name??i.path,worktreeId:d,worktreePath:n?.worktreePath??a?.worktreePath??null,source:s.source,entryKind:n?.kind??a?.kind??"PROJECT",jobId:e.id,targetKey:a?.id??q(e.agentId,i.path)}})}})}catch(t){if(!await n.buildDataDeleteProjection.findUnique({where:{jobId:e.id}}))throw t}}async pruneHistory(){let e=await (0,i.getPrismaClient)();await e.buildDataDeletionHistory.deleteMany({where:{deletedAt:{lt:new Date(Date.now()-7776e6)}}})}publish(e){n.agentEventBus.publish(n.BUILD_DATA_CHANGED_TOPIC,{buildDataCollectionChanged:{id:e}}),n.agentEventBus.publish((0,n.buildDataCollectionChangedTopic)(e),{buildDataCollectionChanged:{id:e}})}}],925991),e.s([],396763)},971619,e=>{"use strict";var t=e.i(750227);e.s(["effectiveBuildsDirectory",0,function(e){var r;return e.buildsDirectory??((r=e.baseRepoDirectory)?/^[a-z]:[\\/]/i.test(r)||r.startsWith("\\\\")?t.win32.join(r,"Builds"):t.posix.join(r,"Builds"):null)}])},224174,669602,190714,646462,890564,e=>{"use strict";var t=e.i(666680),r=e.i(750227),i=e.i(807055),a=e.i(503083),n=e.i(243783);e.i(805422);var s=e.i(694355),o=e.i(661983),l=e.i(971619);let u=new Set(i.BUILD_CONFIGURATION_ICON_KEYS),c=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]),d=["QUEUED","PREPARING","RUNNING"];function p(e,t=null){if(null===e)return t;try{return JSON.parse(e)}catch{return t}}function h(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${t} must be an object`);return e}function m(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function f(e){return null!==e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=(0,s.agentOnlineWindowMs)(e)&&null===e.disconnectedAt}function g(e){return m(p(e.capabilitiesJson,[]))}function y(e,t,r=80){let i=e.trim();if(!i)throw Error(`${t} is required`);if(i.length>r)throw Error(`${t} is too long`);return i}function w(e){return`${e.type}:${e.id}`}function b(e){if(e.codebaseId)return e.codebaseId;let t=p(e.snapshotJson,{});if(t&&"object"==typeof t&&!Array.isArray(t)){let e=t.codebase;if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.id;if("string"==typeof t&&t.trim())return t}}throw Error("Build coordination metadata is unavailable")}function v(e){return"SUCCEEDED"===e?"SUCCEEDED":"CANCELLED"===e?"CANCELLED":"FAILED"}let k={agent:!0,codebase:{include:{repository:!0}},worktree:{include:{_count:{select:{builds:{where:{status:{in:d}}}}}}},configuration:{include:{source:!0,project:!0}},artifacts:{orderBy:{createdAt:"asc"}},scriptExecutions:{orderBy:[{phase:"asc"},{position:"asc"}]},deployments:{orderBy:{createdAt:"desc"}},exports:{orderBy:{createdAt:"desc"}}};e.s(["BuildsService",0,class{agentControl;telemetry;notifications;diskSpace;constructor(e,t,r,n){this.agentControl=e,this.telemetry=t,this.notifications=r,this.diskSpace=n,this.agentControl.registerCompletionHandler(i.IOS_BUILD_JOB_KIND,e=>this.projectBuildCompletion(e)),this.agentControl.registerCompletionHandler(i.IOS_DEPLOY_JOB_KIND,e=>this.projectDeploymentCompletion(e)),this.agentControl.registerCompletionHandler(i.IOS_EXPORT_JOB_KIND,e=>this.projectExportCompletion(e)),this.agentControl.registerCompletionHandler(i.IOS_TEST_RESULTS_JOB_KIND,e=>this.projectGeneratedReportCompletion(e)),this.agentControl.registerCompletionHandler(i.IOS_COVERAGE_REPORT_JOB_KIND,e=>this.projectGeneratedReportCompletion(e)),this.agentControl.registerCompletionHandler(a.COVERAGE_IMPORT_JOB_KIND,e=>this.importedCoverageCompletion(e))}publish(e){o.agentEventBus.publish((0,o.buildTopic)(e),{buildChanged:{id:e}}),o.agentEventBus.publish(o.BUILDS_CHANGED_TOPIC,{buildsChanged:{id:e}}),o.agentEventBus.publish(o.SIDEBAR_STATUS_CHANGED_TOPIC,{sidebarStatusChanged:!0})}async requireWorktree(e,t,r="Agent must be updated to use iOS builds"){let i=await (0,n.getPrismaClient)(),a=await i.worktree.findUnique({where:{id:e},include:{codebase:{include:{agent:!0,repository:!0}}}});if(!a||a.missingAt||"AVAILABLE"!==a.availability)throw Error("Worktree is unavailable");if(!f(a.codebase.agent))throw Error("Agent is offline");if(!g(a.codebase.agent).includes(t))throw Error(r);return a}identity(e){return{codebaseId:e.codebaseId,worktreeId:e.id,branch:e.branch,folder:e.folder,gitDirectory:e.gitDirectory,expectedOrigin:e.codebase.repository.canonicalOrigin,headSha:e.headSha,baseBranch:e.baseBranchOverride??e.codebase.defaultBranch??null}}async ensureProject(e){let r=await (0,n.getPrismaClient)(),i=await r.codebase.findUnique({where:{id:e},select:{repositoryId:!0}});if(!i)throw Error("Codebase not found");return r.codebaseProject.upsert({where:{repositoryId_type:{repositoryId:i.repositoryId,type:"IOS_APP"}},create:{id:(0,t.randomUUID)(),repositoryId:i.repositoryId,type:"IOS_APP"},update:{}})}async project(e){let t=await (0,n.getPrismaClient)(),r=await t.codebase.findUnique({where:{id:e},include:{repository:!0}});if(!r)return null;let i=await t.codebaseProject.findUnique({where:{repositoryId_type:{repositoryId:r.repositoryId,type:"IOS_APP"}},include:{configurations:{orderBy:{name:"asc"},include:{source:{include:{observations:{where:{codebaseId:e},orderBy:{lastParseAttemptAt:"desc"},take:1}}}}}}}),a=await t.codebaseRepositoryBuildScript.findMany({where:{repositoryId:r.repositoryId,script:{deletedAt:null}},orderBy:[{position:"asc"},{script:{name:"asc"}}],include:{script:!0}});return i?{...i,repository:r.repository,allowedScripts:a}:null}async createProject(e){return await this.ensureProject(e),this.project(e)}async projectForWorktree(e){let t=await (0,n.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e},select:{codebaseId:!0}});return r?this.project(r.codebaseId):null}async saveConfiguration(e){let r=await this.ensureProject(e.codebaseId),a=(0,i.parseBuildSource)({kind:e.sourceKind,relativePath:e.sourcePath}),s=y(e.name,"Configuration name"),o=y(e.scheme,"Scheme",256),l=y(e.buildConfiguration,"Xcode configuration",256);if(!i.BUILD_ACTIONS.includes(e.defaultAction))throw Error("Build action is invalid");let c=e.iconKey?.trim()||null;if(c&&!u.has(c))throw Error("Icon is invalid");let d=(0,i.parseBuildAdvancedSettings)(e.advancedSettings??i.DEFAULT_BUILD_ADVANCED_SETTINGS),p=!0===e.autoExport;if(p&&"ARCHIVE"!==e.defaultAction)throw Error("Auto Export is available only for Archive configurations");let h=e.exportSettings?(0,i.parseBuildExportSettings)(e.exportSettings):null;if(p&&!h)throw Error("Auto Export settings are required");let m=await (0,n.getPrismaClient)(),f=e.id?await m.buildConfiguration.findUnique({where:{id:e.id}}):null;if(e.id&&(!f||f.projectId!==r.id))throw Error("Build configuration not found");let g=await m.buildSource.upsert({where:{projectId_relativePath:{projectId:r.id,relativePath:a.relativePath}},create:{id:(0,t.randomUUID)(),projectId:r.id,kind:a.kind,relativePath:a.relativePath},update:{kind:a.kind}}),w=f?.id??(0,t.randomUUID)();return m.buildConfiguration.upsert({where:{id:w},create:{id:w,projectId:r.id,sourceId:g.id,name:s,iconKey:c,scheme:o,buildConfiguration:l,defaultAction:e.defaultAction,advancedSettingsJson:JSON.stringify(d),autoExport:p,exportSettingsJson:h?JSON.stringify(h):null},update:{sourceId:g.id,name:s,iconKey:c,scheme:o,buildConfiguration:l,defaultAction:e.defaultAction,advancedSettingsJson:JSON.stringify(d),autoExport:p,exportSettingsJson:h?JSON.stringify(h):null},include:{source:!0}})}async deleteConfiguration(e){let t=await (0,n.getPrismaClient)();if(await t.build.findFirst({where:{configurationId:e,status:{in:d}}}))throw Error("Configuration has an active build");return 1===(await t.buildConfiguration.deleteMany({where:{id:e}})).count}async scripts(){return(await (0,n.getPrismaClient)()).buildScript.findMany({where:{deletedAt:null},orderBy:{name:"asc"}})}async saveScript(e){let r=y(e.name,"Script name"),a=e.preBuildScript?.trim()||null,s=e.postBuildScript?.trim()||null;if(!a&&!s)throw Error("A pre-build or post-build script is required");let o=e.timeoutSeconds??300;if(!Number.isInteger(o)||o<1||o>3600)throw Error("Script timeout must be between 1 and 3600 seconds");if(!i.BUILD_SCRIPT_FAILURE_BEHAVIORS.includes(e.failureBehavior))throw Error("Script failure behavior is invalid");let l=await (0,n.getPrismaClient)(),u=e.id??(0,t.randomUUID)();return l.buildScript.upsert({where:{id:u},create:{id:u,name:r,preBuildScript:a,postBuildScript:s,enabledByDefault:e.enabledByDefault,timeoutSeconds:o,failureBehavior:e.failureBehavior},update:{name:r,preBuildScript:a,postBuildScript:s,enabledByDefault:e.enabledByDefault,timeoutSeconds:o,failureBehavior:e.failureBehavior,deletedAt:null}})}async deleteScript(e){let t=await (0,n.getPrismaClient)(),r=await t.buildScript.updateMany({where:{id:e,deletedAt:null},data:{deletedAt:new Date}});return await t.codebaseRepositoryBuildScript.deleteMany({where:{scriptId:e}}),1===r.count}async setAllowedScripts(e,t){let r=await (0,n.getPrismaClient)(),i=await r.codebase.findUnique({where:{id:e}});if(!i)throw Error("Codebase not found");let a=[...new Set(t)];if((await r.buildScript.findMany({where:{id:{in:a},deletedAt:null}})).length!==a.length)throw Error("Build script not found");return await r.$transaction(async e=>{await e.codebaseRepositoryBuildScript.deleteMany({where:{repositoryId:i.repositoryId}}),a.length&&await e.codebaseRepositoryBuildScript.createMany({data:a.map((e,t)=>({repositoryId:i.repositoryId,scriptId:e,position:t}))})}),this.project(e)}async waitForJob(e,t=12e4){let r=o.agentEventBus.iterate((0,o.agentJobChangedTopic)(e)),i=Date.now()+t;try{for(;Date.now()<i;){let t=await this.agentControl.getJob(e);if(!t)throw Error("Agent job disappeared");if(c.has(t.status))return t;await Promise.race([r.next(),new Promise(e=>setTimeout(e,Math.max(1,i-Date.now())))])}throw await this.agentControl.cancelJob(e),Error("Agent did not respond in time")}finally{await r.return?.()}}result(e){if("SUCCEEDED"!==e.status)throw Error(e.error||"Agent operation failed");return h(p(e.resultJson,{}),"agent result")}async discoverSources(e,t){let r=await this.requireWorktree(e,i.IOS_SOURCE_DISCOVER_JOB_KIND),a=await this.agentControl.createJob({agentId:r.codebase.agentId,codebaseId:r.codebaseId,worktreeId:r.id,kind:i.IOS_SOURCE_DISCOVER_JOB_KIND,payload:this.identity(r),idempotencyKey:`ios:source:discover:${t}:${r.id}`,timeoutSeconds:60,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(a.id));return Array.isArray(e.sources)?e.sources:[]}finally{let e=await (0,n.getPrismaClient)();await e.agentJob.deleteMany({where:{id:a.id,visibility:"SYSTEM"}})}}async reparse(e,r,a){let s=await this.requireWorktree(r,i.IOS_SOURCE_PARSE_JOB_KIND),o=await (0,n.getPrismaClient)(),l=await o.buildConfiguration.findUnique({where:{id:e},include:{source:{include:{project:!0}}}});if(!l||l.source.project.repositoryId!==s.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let u=`worktree:${s.id}`,c=await o.buildSourceObservation.findUnique({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:u}}}),d=new Date;await o.buildSourceObservation.upsert({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:u}},create:{id:(0,t.randomUUID)(),sourceId:l.sourceId,scopeKey:u,codebaseId:s.codebaseId,worktreeId:s.id,status:"PARSING",lastParseAttemptAt:d},update:{status:"PARSING",error:null,lastParseAttemptAt:d}});let p=await this.agentControl.createJob({agentId:s.codebase.agentId,codebaseId:s.codebaseId,worktreeId:s.id,kind:i.IOS_SOURCE_PARSE_JOB_KIND,payload:{...this.identity(s),source:{kind:l.source.kind,relativePath:l.source.relativePath},scheme:l.scheme},idempotencyKey:`ios:source:parse:${a}:${l.id}:${s.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(p.id)),t=m(e.schemes),r=m(e.configurations),i=t.includes(l.scheme)&&r.includes(l.buildConfiguration);return o.buildSourceObservation.update({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:u}},data:{status:i?"VALID":"INVALID",schemesJson:JSON.stringify(t),configurationsJson:JSON.stringify(r),testPlansJson:JSON.stringify(m(e.testPlans)),error:i?null:"The saved scheme or configuration is no longer available",stale:!1,headSha:"string"==typeof e.headSha?e.headSha:s.headSha,xcodeVersion:"string"==typeof e.xcodeVersion?e.xcodeVersion:null,lastParsedAt:new Date}})}catch(t){let e=t instanceof Error?t.message:String(t);return o.buildSourceObservation.update({where:{sourceId_scopeKey:{sourceId:l.sourceId,scopeKey:u}},data:{status:"ERROR",error:e,stale:!!c?.lastParsedAt}})}finally{await o.agentJob.deleteMany({where:{id:p.id,visibility:"SYSTEM"}})}}async inspectSource(e){let t=await this.requireWorktree(e.worktreeId,i.IOS_SOURCE_PARSE_JOB_KIND),r=(0,i.parseBuildSource)({kind:e.sourceKind,relativePath:e.sourcePath}),a=await this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:i.IOS_SOURCE_PARSE_JOB_KIND,payload:{...this.identity(t),source:r,scheme:e.scheme?.trim()||null,configuration:e.configuration?.trim()||null},idempotencyKey:`ios:source:inspect:${e.requestId}:${t.id}:${r.relativePath}:${e.scheme??""}:${e.configuration??""}`,timeoutSeconds:120,visibility:"SYSTEM"});try{var s;let e=this.result(await this.waitForJob(a.id));return{source:r,schemes:m(e.schemes),configurations:m(e.configurations),testPlans:m(e.testPlans),signingRequirements:(s=e.signingRequirements,Array.isArray(s)?s.flatMap(e=>!e||"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.bundleId||"string"!=typeof e.name||"string"!=typeof e.target?[]:[{bundleId:e.bundleId,name:e.name,target:e.target,platform:"string"==typeof e.platform?e.platform:null,teamId:"string"==typeof e.teamId?e.teamId:null,provisioningProfileSpecifier:"string"==typeof e.provisioningProfileSpecifier?e.provisioningProfileSpecifier:null}]):[]),headSha:"string"==typeof e.headSha?e.headSha:t.headSha,xcodeVersion:"string"==typeof e.xcodeVersion?e.xcodeVersion:null}}finally{let e=await (0,n.getPrismaClient)();await e.agentJob.deleteMany({where:{id:a.id,visibility:"SYSTEM"}})}}async destinations(e){let t=await this.requireWorktree(e.worktreeId,i.IOS_DESTINATIONS_JOB_KIND),r=await (0,n.getPrismaClient)(),a=await r.buildConfiguration.findUnique({where:{id:e.configurationId},include:{source:{include:{project:!0}}}});if(!a||a.source.project.repositoryId!==t.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let s=e.action??a.defaultAction;if(!i.BUILD_ACTIONS.includes(s))throw Error("Build action is invalid");let o=function(e){if(!i.GENERIC_BUILD_DESTINATION_ACTIONS.includes(e))return[];let t={type:"PHYSICAL_DEVICE",id:"generic-ios",name:"Any Physical iOS Device",platform:"iOS",osVersion:null,state:null,generic:!0};return"ARCHIVE"===e?[t]:[{type:"SIMULATOR",id:"generic-ios-simulator",name:"Any iOS Simulator",platform:"iOS Simulator",osVersion:null,state:null,generic:!0},t]}(s);if("ARCHIVE"===s)return o;let l=await this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:i.IOS_DESTINATIONS_JOB_KIND,payload:{...this.identity(t),source:{kind:a.source.kind,relativePath:a.source.relativePath},scheme:a.scheme,configuration:a.buildConfiguration,action:s},idempotencyKey:`ios:destinations:${e.requestId}:${a.id}:${t.id}:${s}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(l.id));return Array.isArray(e.destinations)?e.destinations:[]}finally{await r.agentJob.deleteMany({where:{id:l.id,visibility:"SYSTEM"}})}}async signingOptionsForBuild(e){let t=await (0,n.getPrismaClient)(),r=await t.build.findUnique({where:{id:e},include:{artifacts:!0}}),a=r?.artifacts.find(e=>"ARCHIVE"===e.kind);if(!r||"SUCCEEDED"!==r.status||!r.worktreeId)throw Error("A successful archive build is required");if(!a)throw Error("Build does not contain an archive");let s=await this.requireWorktree(r.worktreeId,i.IOS_SIGNING_INSPECT_JOB_KIND),o=await this.agentControl.createJob({agentId:s.codebase.agentId,codebaseId:s.codebaseId,worktreeId:s.id,kind:i.IOS_SIGNING_INSPECT_JOB_KIND,payload:{buildId:r.id,codebaseId:s.codebaseId,artifactDirectory:r.artifactDirectory,archiveRelativePath:a.relativePath},idempotencyKey:`ios:signing:${r.id}:${a.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(o.id));return{teams:Array.isArray(e.teams)?e.teams:[],identities:Array.isArray(e.identities)?e.identities:[],profiles:Array.isArray(e.profiles)?e.profiles:[],bundles:Array.isArray(e.bundles)?e.bundles:[]}}finally{await t.agentJob.deleteMany({where:{id:o.id,visibility:"SYSTEM"}})}}async destinationsForBuild(e,t){let r=await (0,n.getPrismaClient)(),a=await r.build.findUnique({where:{id:e},include:{artifacts:!0}});if(!a||"SUCCEEDED"!==a.status||!a.worktreeId||!a.artifacts.some(e=>"RUNNABLE_APP"===e.kind))throw Error("A successful runnable build is required");let s=await this.requireWorktree(a.worktreeId,i.IOS_RUN_DESTINATIONS_JOB_KIND);if(a.agentId!==s.codebase.agentId||a.codebaseId!==s.codebaseId)throw Error("The build no longer belongs to this worktree checkout");let o=await this.agentControl.createJob({agentId:s.codebase.agentId,codebaseId:s.codebaseId,worktreeId:s.id,kind:i.IOS_RUN_DESTINATIONS_JOB_KIND,payload:{...this.identity(s),destinationType:a.destinationType},idempotencyKey:`ios:build-destinations:${y(t,"Request ID",200)}:${a.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(o.id));return(Array.isArray(e.destinations)?e.destinations:[]).map(e=>(0,i.parseBuildDestination)(e)).filter(e=>e.type===a.destinationType&&!e.generic)}finally{await r.agentJob.deleteMany({where:{id:o.id,visibility:"SYSTEM"}})}}async startBuild(e){let a=y(e.requestId,"Request ID",200),s=`${e.worktreeId}:${a}`,o=await (0,n.getPrismaClient)(),u=await o.build.findUnique({where:{requestKey:s},include:k});if(u){if(this.telemetry){let e=p(u.snapshotJson,{}),t=h(e.configuration??{},"build configuration snapshot"),r=h(e.destination??{},"build destination snapshot");await this.telemetry.addBuildSeparator({buildId:u.id,name:`Build \xb7 ${String(t.name??"iOS")} \xb7 ${String(r.name??"Destination")}`,clientTime:u.createdAt})}return u}let c=await this.requireWorktree(e.worktreeId,i.IOS_BUILD_JOB_KIND);if(await this.diskSpace?.assertWorktreeCanStart(c.id),e.worktreeCoverage&&!g(c.codebase.agent).includes(i.IOS_COVERAGE_REPORT_JOB_KIND))throw Error("Build agent must be updated for worktree coverage");let d=await o.buildConfiguration.findUnique({where:{id:e.configurationId},include:{source:{include:{project:!0}}}});if(!d||d.source.project.repositoryId!==c.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let m=await o.buildSourceObservation.findUnique({where:{sourceId_scopeKey:{sourceId:d.sourceId,scopeKey:`worktree:${c.id}`}}}),f=e.action??d.defaultAction;if(!i.BUILD_ACTIONS.includes(f))throw Error("Build action is invalid");if(e.exportWhenComplete&&"ARCHIVE"!==f)throw Error("Export when complete is available only for Archive builds");let w="ARCHIVE"===f&&(e.exportWhenComplete??d.autoExport),b=e.exportSettings??p(d.exportSettingsJson,null),v=w||b?(0,i.parseBuildExportSettings)(b):null;if(w&&!v)throw Error("Export settings are required when automatic export is enabled");let S=(0,i.parseBuildDestination)(e.destination);if(!i.BUILD_DESTINATION_TYPES.includes(S.type))throw Error("Destination is invalid");if("ARCHIVE"===f&&("PHYSICAL_DEVICE"!==S.type||!S.generic))throw Error("Archive builds require the generic physical iOS destination");if(S.generic&&!i.GENERIC_BUILD_DESTINATION_ACTIONS.includes(f))throw Error("This build action requires a concrete destination");let E=h(p(d.advancedSettingsJson,{}),"saved advanced settings"),I=e.advancedSettings?h(e.advancedSettings,"advanced settings override"):{},x=(0,i.parseBuildAdvancedSettings)({...E,...I,buildSettingOverrides:{...h(E.buildSettingOverrides??{},"saved overrides"),...h(I.buildSettingOverrides??{},"run overrides")}});if("TEST_WITHOUT_BUILDING"===f){if(!x.priorBuildForTestingId)throw Error("Test Without Building requires a prior Build for Testing result");let e=await o.build.findUnique({where:{id:x.priorBuildForTestingId},include:{artifacts:{where:{kind:{in:["TEST_PRODUCTS","XCTESTRUN"]}},orderBy:{createdAt:"asc"}}}});if(!e||"SUCCEEDED"!==e.status||"BUILD_FOR_TESTING"!==e.action)throw Error("Test Without Building requires a successful Build for Testing result");if(e.agentId!==c.codebase.agentId||e.worktreeId!==c.id||e.configurationId!==d.id)throw Error("The prior Build for Testing result is not compatible with this agent, worktree, and configuration");if(e.destinationType!==S.type)throw Error("The prior Build for Testing result uses a different destination type");let t=h(p(e.snapshotJson,{}),"prior Build for Testing snapshot"),a=h(t.configuration??{},"prior Build for Testing configuration snapshot"),n=(0,i.parseBuildAdvancedSettings)(a.advancedSettings??{});if(x.testPlan&&n.testPlan&&x.testPlan!==n.testPlan)throw Error("The selected test plan does not match the prior Build for Testing result");let s=x.testPlan??n.testPlan??null,l=e.artifacts.filter(e=>"TEST_PRODUCTS"===e.kind&&e.relativePath.endsWith(".xctestproducts")),u=e.artifacts.filter(e=>"XCTESTRUN"===e.kind&&e.relativePath.endsWith(".xctestrun"));if(l.length>1)throw Error("The prior Build for Testing result contains multiple test-products artifacts");let m=l[0];if(m||1!==u.length||(m=u[0]),!m&&u.length>1&&s&&(m=u.find(e=>h(p(e.metadataJson,{}),"test-run artifact metadata").testPlan===s||e.relativePath.endsWith(`/${s}.xctestrun`)||e.relativePath===`${s}.xctestrun`)),!m&&u.length>1)throw Error("Select a test plan to choose among the captured .xctestrun artifacts");let f=m?.relativePath??"test-products.xctestproducts",g=(0,r.resolve)(e.artifactDirectory),y=(0,r.resolve)(g,f),w=(0,r.relative)(g,y);if(!w||w.startsWith("..")||(0,r.isAbsolute)(w))throw Error("The prior Build for Testing artifact path is invalid");x={...x,testPlan:s,priorTestProductsPath:f.endsWith(".xctestproducts")?y:null,priorXctestrunPath:f.endsWith(".xctestrun")?y:null}}let A=await o.codebaseRepositoryBuildScript.findMany({where:{repositoryId:c.codebase.repositoryId,script:{deletedAt:null}},orderBy:[{position:"asc"},{script:{name:"asc"}}],include:{script:!0}}),_=new Set(e.scriptIds??[]);if([..._].some(e=>!A.some(t=>t.scriptId===e)))throw Error("A selected build script is not allowed for this codebase");let C=A.filter(e=>_.has(e.scriptId)),R=(0,t.randomUUID)(),T=(0,l.effectiveBuildsDirectory)(c.codebase.agent);if(!T)throw Error("The agent builds directory is unavailable");let D=(0,r.join)(T,R),N={kind:d.source.kind,relativePath:d.source.relativePath},O=function(e){var t;let i=e.advancedSettings,a="TEST_WITHOUT_BUILDING"===e.action,n=["xcodebuild",...a?[]:[..."PACKAGE"===e.source.kind?[]:"PROJECT"===e.source.kind?["-project",e.source.relativePath]:["-workspace",e.source.relativePath],"-scheme",e.scheme,"-configuration",e.configuration],"-destination",(t=e.destination).generic?"SIMULATOR"===t.type?"generic/platform=iOS Simulator":"generic/platform=iOS":"SIMULATOR"===t.type?`platform=iOS Simulator,id=${t.id}`:`platform=iOS,id=${t.id}`,"-hideShellScriptEnvironment","-resultBundlePath",(0,r.join)(e.artifactDirectory,"result.xcresult")];for(let e of(!a&&("RESOLVED_ONLY"===i.packageResolution?n.push("-onlyUsePackageVersionsFromResolvedFile"):"SKIP_UPDATES"===i.packageResolution?n.push("-skipPackageUpdates"):"DISABLE_AUTOMATIC"===i.packageResolution&&n.push("-disableAutomaticPackageResolution"),i.disablePackageRepositoryCache&&n.push("-disablePackageRepositoryCache"),"PROJECT_DEFAULT"!==i.signingStyle&&n.push(`CODE_SIGN_STYLE=${"AUTOMATIC"===i.signingStyle?"Automatic":"Manual"}`),i.developmentTeam&&n.push(`DEVELOPMENT_TEAM=${i.developmentTeam}`),i.codeSignIdentity&&n.push(`CODE_SIGN_IDENTITY=${i.codeSignIdentity}`),i.provisioningProfileSpecifier&&n.push(`PROVISIONING_PROFILE_SPECIFIER=${i.provisioningProfileSpecifier}`),i.productBundleIdentifier&&n.push(`PRODUCT_BUNDLE_IDENTIFIER=${i.productBundleIdentifier}`),i.allowProvisioningUpdates&&n.push("-allowProvisioningUpdates"),i.allowProvisioningDeviceRegistration&&n.push("-allowProvisioningDeviceRegistration")),i.testPlan&&n.push("-testPlan",i.testPlan),i.codeCoverage&&n.push("-enableCodeCoverage","YES"),null!==i.parallelTesting&&n.push("-parallel-testing-enabled",i.parallelTesting?"YES":"NO"),null!==i.parallelTestingWorkers&&n.push("-parallel-testing-worker-count",String(i.parallelTestingWorkers)),i.onlyTesting))n.push(`-only-testing:${e}`);for(let e of i.skipTesting)n.push(`-skip-testing:${e}`);if(!a)for(let[e,t]of Object.entries(i.buildSettingOverrides))n.push(`${e}=${t}`);"ARCHIVE"===e.action&&n.push("-archivePath",(0,r.join)(e.artifactDirectory,"archive.xcarchive")),"BUILD_FOR_TESTING"===e.action&&n.push("-testProductsPath",(0,r.join)(e.artifactDirectory,"test-products.xctestproducts")),"TEST_WITHOUT_BUILDING"===e.action&&i.priorTestProductsPath&&n.push("-testProductsPath",i.priorTestProductsPath),"TEST_WITHOUT_BUILDING"===e.action&&!i.priorTestProductsPath&&i.priorXctestrunPath&&n.push("-xctestrun",i.priorXctestrunPath),n.push({BUILD:"build",TEST:"test",ANALYZE:"analyze",ARCHIVE:"archive",BUILD_FOR_TESTING:"build-for-testing",TEST_WITHOUT_BUILDING:"test-without-building"}[e.action]);let s=n.map(e=>/^[A-Za-z0-9_./:=,-]+$/.test(e)?e:JSON.stringify(e)).join(" ");return`cd ${JSON.stringify(e.folder)} && xcrun ${s}`}({folder:c.folder,source:N,scheme:d.scheme,configuration:d.buildConfiguration,destination:S,action:f,advancedSettings:x,artifactDirectory:D}),P=C.map(({script:e,position:t})=>({id:e.id,name:e.name,preBuildScript:e.preBuildScript,postBuildScript:e.postBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior,position:t})),$=await this.telemetry?.buildSettings(S.type,{requestOrigin:e.telemetryRequestOrigin}),U={repository:{id:c.codebase.repository.id,name:c.codebase.repository.name,canonicalOrigin:c.codebase.repository.canonicalOrigin},codebase:{id:c.codebase.id,folder:c.codebase.folder},worktree:{id:c.id,folder:c.folder,branch:c.branch,headSha:c.headSha,codeStateHash:c.codeStateHash,hasStagedChanges:c.hasStagedChanges,hasUnstagedChanges:c.hasUnstagedChanges},agent:{id:c.codebase.agent.id,name:c.codebase.agent.name,hostname:c.codebase.agent.hostname},configuration:{id:d.id,name:d.name,iconKey:d.iconKey,source:N,scheme:d.scheme,buildConfiguration:d.buildConfiguration,action:f,advancedSettings:x,autoExport:w,exportSettings:v,parse:m?{status:m.status,schemes:p(m.schemesJson,[]),configurations:p(m.configurationsJson,[]),testPlans:p(m.testPlansJson,[]),headSha:m.headSha,xcodeVersion:m.xcodeVersion,parsedAt:m.lastParsedAt?.toISOString()??null}:{status:"UNPARSED",schemes:[],configurations:[],testPlans:[],headSha:null,xcodeVersion:null,parsedAt:null}},destination:S,scripts:P,...$?{telemetry:$}:{},worktreeCoverage:!0===e.worktreeCoverage},B=new Date,j=o.build.create({data:{id:R,requestKey:s,requestId:a,agentId:c.codebase.agentId,codebaseId:c.codebaseId,worktreeId:c.id,configurationId:d.id,status:"QUEUED",action:f,destinationType:S.type,destinationJson:JSON.stringify(S),snapshotJson:JSON.stringify(U),commandSummary:O,artifactDirectory:D,createdAt:B,scriptExecutions:{create:P.flatMap(e=>[...e.preBuildScript?[{id:(0,t.randomUUID)(),scriptId:e.id,phase:"PRE_BUILD",position:e.position,nameSnapshot:e.name,sourceSnapshot:e.preBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior}]:[],...e.postBuildScript?[{id:(0,t.randomUUID)(),scriptId:e.id,phase:"POST_BUILD",position:e.position,nameSnapshot:e.name,sourceSnapshot:e.postBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior}]:[]])}}});if(this.telemetry){let e=(0,t.randomUUID)();await o.$transaction([j,o.telemetryEntry.create({data:{id:e,entryType:"SEPARATOR",clientTime:B,receivedAt:B,separatorKind:"BUILD",separatorName:`Build \xb7 ${d.name} \xb7 ${S.name}`.slice(0,100),buildId:R}})]),this.telemetry.notifyChange([e],"BUILD_SEPARATOR_ADDED")}else await j;try{let t=await this.agentControl.createJob({agentId:c.codebase.agentId,codebaseId:c.codebaseId,worktreeId:c.id,kind:i.IOS_BUILD_JOB_KIND,payload:{...this.identity(c),buildId:R,artifactDirectory:D,source:N,scheme:d.scheme,configuration:d.buildConfiguration,action:f,destination:S,advancedSettings:x,scripts:P,...$?{telemetry:$}:{},worktreeCoverage:!0===e.worktreeCoverage},idempotencyKey:`ios:build:${a}:${c.id}`,timeoutSeconds:604800});await o.build.update({where:{id:R},data:{jobId:t.id}})}catch(e){throw await o.build.update({where:{id:R},data:{status:"FAILED",errorCode:"QUEUE_FAILED",error:e instanceof Error?e.message:String(e),finishedAt:new Date}}),e}return this.publish(R),o.build.findUniqueOrThrow({where:{id:R},include:k})}async rebuildBuild(e,t,r){let i=await (0,n.getPrismaClient)(),a=await i.build.findUnique({where:{id:e},select:{worktreeId:!0,configurationId:!0,destinationJson:!0,action:!0,snapshotJson:!0}});if(!a)throw Error("Build not found");let s=h(p(a.snapshotJson,{}),"build snapshot"),o=h(s.worktree??{},"build worktree snapshot"),l=h(s.configuration??{},"build configuration snapshot"),u=Array.isArray(s.scripts)?s.scripts:[],c=a.worktreeId??("string"==typeof o.id?o.id:null),d=a.configurationId??("string"==typeof l.id?l.id:null);if(!c||!d)throw Error("The original build settings are unavailable");return this.startBuild({worktreeId:c,configurationId:d,destination:p(a.destinationJson,{}),scriptIds:u.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];let t=e.id;return"string"==typeof t?[t]:[]}),action:a.action,advancedSettings:l.advancedSettings,exportWhenComplete:!0===l.autoExport,...Object.hasOwn(l,"exportSettings")?{exportSettings:l.exportSettings}:{},requestId:t,...r?{telemetryRequestOrigin:r}:{}})}async startWorktreeCoverage(e){let t=await (0,n.getPrismaClient)(),r=await t.worktree.findUnique({where:{id:e.worktreeId},select:{baseBranchOverride:!0,codebase:{select:{defaultBranch:!0}}}});if(!r||!(r.baseBranchOverride??r.codebase.defaultBranch))throw Error("A base branch is required for worktree coverage");let i=h(e.advancedSettings??{},"coverage advanced settings");return this.startBuild({...e,action:"TEST",advancedSettings:{...i,codeCoverage:!0,parseTestResults:!0},worktreeCoverage:!0})}async importCoverageReport(e){let i=await (0,n.getPrismaClient)(),s=await this.requireWorktree(e.worktreeId,a.COVERAGE_IMPORT_JOB_KIND,"Agent must be updated to import coverage reports"),o=s.baseBranchOverride??s.codebase.defaultBranch??null,u=(e.format||"AUTO").toUpperCase();if(!a.COVERAGE_REPORT_FORMATS.includes(u))throw Error("Coverage format must be AUTO, LCOV, or ISTANBUL");let c=y(e.buildName??"Coverage report","Build name",200),d=y(e.reportPath,"Coverage file",4e3),p=y(e.requestId,"Request ID",200),h=`coverage:${e.worktreeId}:${p}`,m=await i.build.findUnique({where:{requestKey:h}});if(m)return m;let f=(0,t.randomUUID)(),g=(0,l.effectiveBuildsDirectory)(s.codebase.agent);if(!g)throw Error("The agent builds directory is unavailable");let w={repository:{id:s.codebase.repository.id,name:s.codebase.repository.name,canonicalOrigin:s.codebase.repository.canonicalOrigin},codebase:{id:s.codebase.id,folder:s.codebase.folder},worktree:{id:s.id,folder:s.folder,branch:s.branch,headSha:s.headSha,codeStateHash:s.codeStateHash,hasStagedChanges:s.hasStagedChanges,hasUnstagedChanges:s.hasUnstagedChanges},agent:{id:s.codebase.agent.id,name:s.codebase.agent.name,hostname:s.codebase.agent.hostname},configuration:{name:c},coverageImport:{reportPath:d,format:u,baseBranch:o},worktreeCoverage:!0},b={type:"HOST",id:s.codebase.agent.id,name:s.codebase.agent.name,platform:s.codebase.agent.architecture,osVersion:s.codebase.agent.osVersion||null,state:"Connected"},v=await i.build.create({data:{id:f,requestKey:h,requestId:p,agentId:s.codebase.agentId,codebaseId:s.codebaseId,worktreeId:s.id,status:"RUNNING",action:"TEST",destinationType:"HOST",destinationJson:JSON.stringify(b),snapshotJson:JSON.stringify(w),commandSummary:`Import coverage from ${d}`,artifactDirectory:(0,r.join)(g,f),startedAt:new Date}}),k=null;try{await i.buildReport.create({data:{id:(0,t.randomUUID)(),buildId:f,kind:"CODE_COVERAGE",source:"WORKTREE",status:"PENDING"}}),this.publish(f);let e=await this.agentControl.createJob({agentId:s.codebase.agentId,codebaseId:s.codebaseId,worktreeId:s.id,kind:a.COVERAGE_IMPORT_JOB_KIND,payload:{buildId:f,codebaseId:s.codebaseId,worktreeId:s.id,folder:s.folder,reportPath:d,format:u,baseBranch:o},idempotencyKey:`coverage:import:${p}:${f}`,timeoutSeconds:300,visibility:"SYSTEM"});return k=e.id,await i.build.update({where:{id:f},data:{jobId:e.id}}),{...v,jobId:e.id}}catch(a){k&&await this.agentControl.cancelJob(k).catch(()=>void 0);let e=a instanceof Error?a.message:String(a),r=new Date;throw await i.$transaction(async i=>{await i.buildReport.upsert({where:{buildId_kind:{buildId:f,kind:"CODE_COVERAGE"}},create:{id:(0,t.randomUUID)(),buildId:f,kind:"CODE_COVERAGE",source:"WORKTREE",status:"FAILED",error:e,finishedAt:r},update:{status:"FAILED",error:e,finishedAt:r}}),await i.build.update({where:{id:f},data:{status:"FAILED",errorCode:"QUEUE_FAILED",error:e,finishedAt:r}})}),this.publish(f),a}}async importedCoverageCompletion(e){let r=h(p(e.payloadJson,{}),"coverage import payload");if("string"!=typeof r.buildId)return;let i=r.buildId,a=h(p(e.resultJson,{}),"coverage import result"),s="SUCCEEDED"===e.status&&!!a.report&&"object"==typeof a.report,o=await (0,n.getPrismaClient)();await o.$transaction(async r=>{s?await this.upsertReportProjection(r,i,a.report,"WORKTREE"):await r.buildReport.upsert({where:{buildId_kind:{buildId:i,kind:"CODE_COVERAGE"}},create:{id:(0,t.randomUUID)(),buildId:i,kind:"CODE_COVERAGE",source:"WORKTREE",status:"FAILED",error:e.error||"Coverage import failed",finishedAt:new Date},update:{status:"FAILED",error:e.error||"Coverage import failed",finishedAt:new Date}}),await r.build.update({where:{id:i},data:{status:s?"SUCCEEDED":"FAILED",error:s?null:e.error||"Coverage import failed",finishedAt:new Date}})}),this.publish(i)}async generateReport(e,r,a){let s=await (0,n.getPrismaClient)(),o=await s.buildReport.findUnique({where:{buildId_kind:{buildId:e,kind:r}},include:{artifact:!0}});if(o?.status==="READY")return o;let l=await s.build.findUnique({where:{id:e},include:{agent:!0,artifacts:!0}});if(!l)throw Error("Build not found");if(d.includes(l.status))throw Error("Wait for the build to finish before generating reports");if(!l.agentId||!l.agent||!f(l.agent))throw Error("Build agent is offline");let u="TEST_RESULTS"===r?i.IOS_TEST_RESULTS_JOB_KIND:i.IOS_COVERAGE_REPORT_JOB_KIND;if(!g(l.agent).includes(u))throw Error("Build agent must be updated to generate reports");if(!l.artifacts.some(e=>"RESULT_BUNDLE"===e.kind))throw Error("The build result bundle is unavailable");if("TEST_RESULTS"===r&&!["TEST","TEST_WITHOUT_BUILDING"].includes(l.action))throw Error("This build did not run tests");let c=await s.buildReport.upsert({where:{buildId_kind:{buildId:e,kind:r}},create:{id:(0,t.randomUUID)(),buildId:e,kind:r,source:"MANUAL",status:"PENDING"},update:{source:"MANUAL",status:"PENDING",error:null,finishedAt:null}});this.publish(e);let p=b(l),h=await this.agentControl.createJob({agentId:l.agentId,codebaseId:p,worktreeId:l.worktreeId,kind:u,payload:{buildId:e,artifactDirectory:l.artifactDirectory,codebaseId:p,reportKind:r,source:"MANUAL"},idempotencyKey:`ios:report:${r}:${y(a,"Request ID",200)}:${e}`,timeoutSeconds:180,visibility:"SYSTEM"});try{return await this.waitForJob(h.id,17e4),s.buildReport.findUniqueOrThrow({where:{id:c.id},include:{artifact:!0}})}finally{await s.agentJob.deleteMany({where:{id:h.id,visibility:"SYSTEM"}})}}async coverageHistory(e){return(await (0,n.getPrismaClient)()).buildReport.findMany({where:{kind:"CODE_COVERAGE",source:"WORKTREE",build:{worktreeId:e}},orderBy:{createdAt:"desc"},take:50,select:{id:!0,buildId:!0,artifactId:!0,kind:!0,source:!0,status:!0,summaryJson:!0,error:!0,createdAt:!0,updatedAt:!0,finishedAt:!0,artifact:!0,build:{select:{id:!0,status:!0,action:!0,destinationType:!0,destinationJson:!0,snapshotJson:!0,createdAt:!0,startedAt:!0,finishedAt:!0,updatedAt:!0,worktree:{select:{headSha:!0,codeStateHash:!0,hasStagedChanges:!0,hasUnstagedChanges:!0,lastCheckedAt:!0,_count:{select:{builds:{where:{status:{in:d}}}}}}},artifacts:{orderBy:{createdAt:"asc"}}}}}})}async reportsForBuild(e){return(await (0,n.getPrismaClient)()).buildReport.findMany({where:{buildId:e},orderBy:{createdAt:"asc"},include:{artifact:!0}})}async reportData(e){let t=await (0,n.getPrismaClient)(),r=await t.buildReport.findUnique({where:{id:e},select:{dataJson:!0}});return r?.dataJson??"{}"}async builds(e={}){let t=await (0,n.getPrismaClient)(),r=Math.max(1,Math.min(e.first??50,200)),i=await t.build.findMany({where:{...e.status?{status:e.status}:{},...e.codebaseId?{codebaseId:e.codebaseId}:{},...e.worktreeId?{worktreeId:e.worktreeId}:{}},orderBy:[{createdAt:"desc"},{id:"desc"}],...e.after?{cursor:{id:e.after},skip:1}:{},take:r+1,include:k});return{items:i.slice(0,r),nextCursor:i.length>r?i[r-1].id:null}}async getBuild(e){return(await (0,n.getPrismaClient)()).build.findUnique({where:{id:e},include:k})}async deleteBuilds(e){let t=[...new Set(e)];if(!t.length)return 0;if(t.length>200)throw Error("At most 200 builds can be deleted at once");let a=await (0,n.getPrismaClient)(),s=await a.build.findMany({where:{id:{in:t}},select:{id:!0,status:!0,artifactDirectory:!0,snapshotJson:!0,agentId:!0,agent:{select:{capabilitiesJson:!0}},codebaseId:!0,worktreeId:!0,deployments:{where:{status:{in:d}},select:{id:!0}},exports:{where:{status:{in:d}},select:{id:!0}}}});if(s.some(e=>d.includes(e.status)))throw Error("Running builds cannot be deleted");if(s.some(e=>e.deployments.length>0||e.exports.length>0))throw Error("Builds with running deployments or exports cannot be deleted");for(let e of s){if(!(0,r.isAbsolute)(e.artifactDirectory)||(0,r.basename)(e.artifactDirectory)!==e.id)throw Error(`Build folder is invalid for ${e.id}`);if(e.agentId){let t=b(e);if(!e.agent||!g(e.agent).includes(i.IOS_BUILD_DELETE_JOB_KIND))throw Error("Build agent must be updated to delete builds");await this.agentControl.createJob({agentId:e.agentId,codebaseId:t,worktreeId:e.worktreeId,kind:i.IOS_BUILD_DELETE_JOB_KIND,payload:{buildId:e.id,artifactDirectory:e.artifactDirectory,codebaseId:t},idempotencyKey:`ios:build:delete:${e.id}`,timeoutSeconds:300,visibility:"SYSTEM"})}}let o=await a.build.deleteMany({where:{id:{in:s.map(e=>e.id)}}});for(let e of s)this.publish(e.id);return o.count}async artifactForInstall(e,t){let r=await (0,n.getPrismaClient)(),i=await r.buildArtifact.findFirst({where:{id:t,buildId:e}});return i?{id:i.id,kind:i.kind,relativePath:i.relativePath,sizeBytes:i.sizeBytes,checksum:i.checksum,createdAt:i.createdAt.toISOString(),metadata:h(p(i.metadataJson,{}),"build artifact metadata")}:null}async prepareArtifactDownload(e,t,r,a=17e4){let s=await (0,n.getPrismaClient)(),o=await s.buildArtifact.findFirst({where:{id:t,buildId:e},include:{build:{include:{agent:!0}}}});if(!o)throw Error("Build artifact not found");let{build:l}=o;if(!l.agentId||!l.agent)throw Error("The build agent is no longer available");if(!f(l.agent))throw Error("Build agent is offline");if(!g(l.agent).includes(i.IOS_ARTIFACT_DOWNLOAD_JOB_KIND))throw Error("Build agent must be updated to download artifacts");let u=b(l),c=await this.agentControl.createJob({agentId:l.agentId,codebaseId:u,worktreeId:l.worktreeId,kind:i.IOS_ARTIFACT_DOWNLOAD_JOB_KIND,payload:{buildId:l.id,artifactDirectory:l.artifactDirectory,artifactRelativePath:o.relativePath,uploadId:r,codebaseId:u},idempotencyKey:`ios:artifact:download:${r}`,timeoutSeconds:Math.ceil(a/1e3)+10,visibility:"SYSTEM"});try{this.result(await this.waitForJob(c.id,a))}finally{await s.agentJob.deleteMany({where:{id:c.id,visibility:"SYSTEM"}})}}async logChunks(e,t=null,r=1e3){let i=await (0,n.getPrismaClient)(),a=t?await i.buildLogChunk.findFirst({where:{id:t,buildId:e},select:{id:!0,createdAt:!0,sequence:!0}}):null;if(t&&!a)throw Error("Build log cursor not found");return i.buildLogChunk.findMany({where:{buildId:e,...a?{OR:[{createdAt:{gt:a.createdAt}},{createdAt:a.createdAt,sequence:{gt:a.sequence}},{createdAt:a.createdAt,sequence:a.sequence,id:{gt:a.id}}]}:{}},orderBy:[{createdAt:"asc"},{sequence:"asc"},{id:"asc"}],take:Math.max(1,Math.min(r,5e3))})}async cancelBuild(e){let t=await (0,n.getPrismaClient)(),r=await t.build.findUnique({where:{id:e}});if(!r)throw Error("Build not found");return d.includes(r.status)&&(r.jobId&&await this.agentControl.cancelJob(r.jobId),await t.build.update({where:{id:e},data:{status:"CANCELLED",finishedAt:new Date,errorCode:"CANCELLED"}}),this.publish(e)),this.getBuild(e)}async reportProgress(e,t){if(!["PREPARING","RUNNING"].includes(t.status))throw Error("Build progress status is invalid");let r=await (0,n.getPrismaClient)(),i=await r.build.findUnique({where:{id:t.buildId}});if(!i||i.agentId!==e)throw Error("Build not found for agent");if(!d.includes(i.status))return i;let a=await r.build.update({where:{id:t.buildId},data:{status:t.status,startedAt:i.startedAt??(t.startedAt?new Date(t.startedAt):new Date),errorCode:t.errorCode??void 0,error:t.error??void 0}});return this.publish(t.buildId),a}async appendLogChunks(e,r,i){if(!i.length||i.length>200)throw Error("Build log batches must contain 1 to 200 chunks");let a=await (0,n.getPrismaClient)(),s=await a.build.findUnique({where:{id:r}});if(!s||s.agentId!==e)throw Error("Build not found for agent");let l=i.map(e=>{if(!Number.isInteger(e.sequence)||e.sequence<0)throw Error("Log sequence must be a non-negative integer");if(!["STDOUT","STDERR","SYSTEM"].includes(e.stream))throw Error("Log stream is invalid");let i=Buffer.from(e.dataBase64,"base64");if(i.length!==e.byteLength||i.length>262144)throw Error("Log byte length is invalid");let a=Buffer.from(i.toString("utf8").replace(/(Bearer\s+)[A-Za-z0-9._~+\/-]+=*/gi,"$1[REDACTED]").replace(/([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^\s/@]+@/g,"$1[REDACTED]@").replace(/\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY)[A-Z0-9_]*)\s*=\s*[^\s]+/gi,"$1=[REDACTED]").replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g,"[REDACTED PRIVATE KEY]"),"utf8"),n=new Date(e.createdAt);if(Number.isNaN(n.valueOf()))throw Error("Log date is invalid");return{id:(0,t.randomUUID)(),buildId:r,scope:y(e.scope,"Log scope",40),scopeId:y(e.scopeId,"Log scope ID",200),sequence:e.sequence,phase:y(e.phase,"Log phase",80),stream:e.stream,dataBase64:a.toString("base64"),byteLength:a.byteLength,createdAt:n}}),u=[];for(let e of l){let t=await a.buildLogChunk.upsert({where:{scope_scopeId_sequence:{scope:e.scope,scopeId:e.scopeId,sequence:e.sequence}},create:e,update:{}});u.push(t),o.agentEventBus.publish((0,o.buildLogChunkTopic)(r),{buildLogChunkAdded:t})}return u}async runBuild(e){let r=await (0,n.getPrismaClient)(),a=await r.build.findUnique({where:{id:e.buildId},include:{artifacts:!0,worktree:{include:{codebase:{include:{agent:!0,repository:!0}}}}}});if(!a||"SUCCEEDED"!==a.status||!a.worktree)throw Error("A successful build is required");let s=a.artifacts.find(e=>"RUNNABLE_APP"===e.kind);if(!s)throw Error("Build does not contain a runnable app");let o=y(String(h(p(s.metadataJson,{}),"runnable metadata").bundleIdentifier??""),"Runnable bundle identifier",512),l=e.destinations.map(i.parseBuildDestination);if(!l.length)throw Error("Select at least one destination");if(new Set(l.map(e=>`${e.type}:${e.id}`)).size!==l.length)throw Error("Run destinations must be unique");if(l.some(e=>e.type!==a.destinationType))throw Error("Run destinations must match the build destination type");let u=await this.destinationsForBuild(a.id,`${y(e.requestId,"Request ID",200)}:preflight`),c=l.map(e=>u.find(t=>t.type===e.type&&t.id===e.id));if(c.some(e=>!e))throw Error("A selected run destination is no longer available");l=c;let d=await this.requireWorktree(a.worktree.id,i.IOS_DEPLOY_JOB_KIND),m=(0,t.randomUUID)(),f=[];for(let i of l){let n=await r.buildDeployment.findUnique({where:{buildId_requestId_destinationKey:{buildId:a.id,requestId:e.requestId,destinationKey:w(i)}}});f.push(n??await r.buildDeployment.create({data:{id:(0,t.randomUUID)(),buildId:a.id,batchId:m,requestId:e.requestId,destinationJson:JSON.stringify(i),destinationKey:w(i),commandSummary:"SIMULATOR"===i.type?`open -a Simulator --args -CurrentDeviceUDID ${i.id}; xcrun simctl install/launch ${i.id}`:`xcrun devicectl device install/process launch --device ${i.id}`}}))}let g=await this.agentControl.createJob({agentId:d.codebase.agentId,codebaseId:d.codebaseId,worktreeId:d.id,kind:i.IOS_DEPLOY_JOB_KIND,payload:{...this.identity(d),buildId:a.id,artifactDirectory:a.artifactDirectory,artifactRelativePath:s.relativePath,bundleIdentifier:o,deployments:f.map((e,t)=>({id:e.id,destination:l[t]}))},idempotencyKey:`ios:deploy:${a.id}:${e.requestId}`,timeoutSeconds:3600});return await r.buildDeployment.updateMany({where:{id:{in:f.map(e=>e.id)}},data:{jobId:g.id}}),this.publish(a.id),r.buildDeployment.findMany({where:{id:{in:f.map(e=>e.id)}},orderBy:{createdAt:"asc"}})}async exportArchive(e){let r=await (0,n.getPrismaClient)(),a=await r.buildExport.findUnique({where:{buildId_requestId:{buildId:e.buildId,requestId:e.requestId}}});if(a)return a;let s=await r.build.findUnique({where:{id:e.buildId},include:{artifacts:!0,worktree:!0}});if(!s||"SUCCEEDED"!==s.status||!s.worktree)throw Error("A successful archive build is required");let o=s.artifacts.find(e=>"ARCHIVE"===e.kind);if(!o)throw Error("Build does not contain an archive");let l=(0,i.parseBuildExportSettings)(e.settings),u=await this.requireWorktree(s.worktree.id,i.IOS_EXPORT_JOB_KIND),c=(0,t.randomUUID)(),d=await r.buildExport.create({data:{id:c,buildId:s.id,requestId:e.requestId,settingsSnapshotJson:JSON.stringify(l),commandSummary:`xcrun xcodebuild -exportArchive -archivePath ${JSON.stringify(o.relativePath)} -exportPath exports/${c}`}});try{let t=await this.agentControl.createJob({agentId:u.codebase.agentId,codebaseId:u.codebaseId,worktreeId:u.id,kind:i.IOS_EXPORT_JOB_KIND,payload:{...this.identity(u),buildId:s.id,exportId:c,artifactDirectory:s.artifactDirectory,archiveRelativePath:o.relativePath,settings:l},idempotencyKey:`ios:export:${s.id}:${e.requestId}`,timeoutSeconds:3600}),a=await r.buildExport.update({where:{id:d.id},data:{jobId:t.id}});return this.publish(s.id),a}catch(t){let e=await r.buildExport.update({where:{id:d.id},data:{status:"FAILED",error:t instanceof Error?t.message:String(t),finishedAt:new Date}});return this.publish(s.id),e}}async upsertArtifacts(e,r,a){for(let n of(0,i.parseBuildArtifactSnapshots)(a)){let i={kind:n.kind,sizeBytes:n.sizeBytes,checksum:n.checksum,metadataJson:JSON.stringify(n.metadata)};await e.buildArtifact.upsert({where:{buildId_relativePath:{buildId:r,relativePath:n.relativePath}},create:{id:(0,t.randomUUID)(),buildId:r,relativePath:n.relativePath,...i},update:i})}}async upsertReportProjection(e,r,i,a){let n=h(i,"build report");if("TEST_RESULTS"!==n.kind&&"CODE_COVERAGE"!==n.kind)return;let s=n.kind,o=n.artifact&&"object"==typeof n.artifact?h(n.artifact,"build report artifact"):null,l=o&&"string"==typeof o.relativePath?await e.buildArtifact.findUnique({where:{buildId_relativePath:{buildId:r,relativePath:o.relativePath}}}):null,u="READY"===n.status?"READY":"FAILED";await e.buildReport.upsert({where:{buildId_kind:{buildId:r,kind:s}},create:{id:(0,t.randomUUID)(),buildId:r,artifactId:l?.id??null,kind:s,source:a,status:u,summaryJson:JSON.stringify(n.summary&&"object"==typeof n.summary?n.summary:{}),dataJson:JSON.stringify(n.data&&"object"==typeof n.data?n.data:{}),error:"string"==typeof n.error?n.error:null,finishedAt:new Date},update:{artifactId:l?.id??null,source:a,status:u,summaryJson:JSON.stringify(n.summary&&"object"==typeof n.summary?n.summary:{}),dataJson:JSON.stringify(n.data&&"object"==typeof n.data?n.data:{}),error:"string"==typeof n.error?n.error:null,finishedAt:new Date}})}async projectBuildCompletion(e){let r=await (0,n.getPrismaClient)(),i=await r.build.findFirst({where:{jobId:e.id},include:{worktree:{select:{highlightColor:!0}}}});if(!i)return;let a=h(p(e.resultJson,{}),"build result"),s="CANCELLED"===i.status?"CANCELLED":v(e.status),o="string"==typeof a.sourceStateHash?a.sourceStateHash:null,l="string"==typeof a.finalStateHash?a.finalStateHash:null,u="string"==typeof a.codeStateObservedAt&&Number.isFinite(Date.parse(a.codeStateObservedAt))?new Date(a.codeStateObservedAt):new Date,c=l?u:new Date,d=i.snapshotJson;if(o){let e=h(p(i.snapshotJson,{}),"build snapshot"),t=h(e.worktree??{},"build worktree snapshot");d=JSON.stringify({...e,worktree:{...t,codeStateHash:o}})}let m=null;await r.$transaction(async r=>{if(await r.build.update({where:{id:i.id},data:{status:s,errorCode:"string"==typeof a.errorCode?a.errorCode:"TIMED_OUT"===e.status?"TIMEOUT":"FAILED"===s?"XCODEBUILD_FAILED":i.errorCode,error:e.error??("string"==typeof a.error?a.error:i.error),startedAt:i.startedAt??new Date,finishedAt:c,snapshotJson:d}}),i.worktreeId&&l&&await r.worktree.updateMany({where:{id:i.worktreeId,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:u}}]},data:{codeStateHash:l,lastCheckedAt:u}}),Array.isArray(a.artifacts))for(let e of a.artifacts){let a=h(e,"build artifact");"string"==typeof a.relativePath&&"string"==typeof a.kind&&await r.buildArtifact.upsert({where:{buildId_relativePath:{buildId:i.id,relativePath:a.relativePath}},create:{id:(0,t.randomUUID)(),buildId:i.id,kind:a.kind,relativePath:a.relativePath,sizeBytes:"number"==typeof a.sizeBytes?a.sizeBytes:null,checksum:"string"==typeof a.checksum?a.checksum:null,metadataJson:JSON.stringify(a.metadata&&"object"==typeof a.metadata?a.metadata:{})},update:{}})}if(Array.isArray(a.scriptExecutions))for(let e of a.scriptExecutions){let t=h(e,"script execution");"string"==typeof t.phase&&"number"==typeof t.position&&await r.buildScriptExecution.updateMany({where:{buildId:i.id,phase:t.phase,position:t.position},data:{status:"string"==typeof t.status?t.status:"FAILED",exitCode:"number"==typeof t.exitCode?t.exitCode:null,durationMs:"number"==typeof t.durationMs?t.durationMs:null,causedBuildFailure:!0===t.causedBuildFailure,outputRelativePath:"string"==typeof t.outputRelativePath?t.outputRelativePath:null,error:"string"==typeof t.error?t.error:null}})}if(Array.isArray(a.reports))for(let e of a.reports){let t=e&&"object"==typeof e&&!Array.isArray(e)?e:{};await this.upsertReportProjection(r,i.id,e,"CODE_COVERAGE"===t.kind?"WORKTREE":"AUTOMATIC")}if(this.notifications&&("SUCCEEDED"===s||"FAILED"===s)){let e=h(p(d,{}),"build notification snapshot"),t=h(e.repository??{},"build repository snapshot"),a=h(e.configuration??{},"build configuration snapshot"),n=h(e.worktree??{},"build worktree snapshot"),o=["string"==typeof t.name?t.name:null,"string"==typeof a.name?a.name:null,"string"==typeof n.branch?n.branch:"string"==typeof n.folder?n.folder:null].filter(e=>!!e);m=await this.notifications.recordInTransaction(r,{dedupeKey:`ios-build:${i.id}:${s}`,typeKey:"SUCCEEDED"===s?"IOS_BUILD_SUCCEEDED":"IOS_BUILD_FAILED",title:"SUCCEEDED"===s?"iOS build succeeded":"iOS build failed",body:o.join(" · ")||`Build ${i.id}`,href:`/builds/${i.id}`,resourceKind:"BUILD",resourceId:i.id,worktreeId:i.worktreeId,highlightColor:i.worktree?.highlightColor??null})}}),this.publish(i.id),this.notifications?.created(m),"SUCCEEDED"===s&&await this.queueAutomaticExport(i.id,d)}async queueAutomaticExport(e,r){let i=h(p(r,{}),"build snapshot"),a=h(i.configuration??{},"build configuration snapshot");if(!0!==a.autoExport)return;let s=a.exportSettings;try{await this.exportArchive({buildId:e,requestId:"automatic",settings:s})}catch(a){let r=await (0,n.getPrismaClient)(),i=a instanceof Error?a.message:String(a);await r.buildExport.upsert({where:{buildId_requestId:{buildId:e,requestId:"automatic"}},create:{id:(0,t.randomUUID)(),buildId:e,requestId:"automatic",status:"FAILED",settingsSnapshotJson:JSON.stringify(s??{}),commandSummary:"Automatic archive export",error:i,finishedAt:new Date},update:{status:"FAILED",error:i,finishedAt:new Date}}),this.publish(e)}}async projectGeneratedReportCompletion(e){let r=h(p(e.payloadJson,{}),"build report payload");if("string"!=typeof r.buildId)return;let i=r.buildId,a=h(p(e.resultJson,{}),"build report result"),s=await (0,n.getPrismaClient)();await s.$transaction(async n=>{if(await this.upsertArtifacts(n,i,a.artifacts),a.report&&"object"==typeof a.report)await this.upsertReportProjection(n,i,a.report,"WORKTREE"===r.source?"WORKTREE":"MANUAL");else{let a="CODE_COVERAGE"===r.reportKind?"CODE_COVERAGE":"TEST_RESULTS";await n.buildReport.upsert({where:{buildId_kind:{buildId:i,kind:a}},create:{id:(0,t.randomUUID)(),buildId:i,kind:a,source:"WORKTREE"===r.source?"WORKTREE":"MANUAL",status:"FAILED",error:e.error||"Report generation failed",finishedAt:new Date},update:{status:"FAILED",error:e.error||"Report generation failed",finishedAt:new Date}})}}),this.publish(i)}async projectDeploymentCompletion(e){let t=await (0,n.getPrismaClient)(),r=await t.buildDeployment.findMany({where:{jobId:e.id}});if(!r.length)return;let i=h(p(e.resultJson,{}),"deployment result"),a=Array.isArray(i.deployments)?i.deployments:[];for(let i of r){let r=a.map(e=>h(e,"deployment outcome")).find(e=>e.id===i.id);await t.buildDeployment.update({where:{id:i.id},data:{status:"string"==typeof r?.status?r.status:v(e.status),error:"string"==typeof r?.error?r.error:e.error,outputRelativePath:"string"==typeof r?.outputRelativePath?r.outputRelativePath:null,startedAt:i.startedAt??new Date,finishedAt:new Date}})}this.publish(r[0].buildId)}async projectExportCompletion(e){let r=await (0,n.getPrismaClient)(),i=await r.buildExport.findFirst({where:{jobId:e.id}});if(!i)return;let a=h(p(e.resultJson,{}),"export result");if(await r.buildExport.update({where:{id:i.id},data:{status:v(e.status),error:e.error??("string"==typeof a.error?a.error:null),outputRelativePath:"string"==typeof a.outputRelativePath?a.outputRelativePath:null,startedAt:i.startedAt??new Date,finishedAt:new Date}}),"SUCCEEDED"===e.status&&"string"==typeof a.outputRelativePath){let e=a.outputRelativePath;await r.$transaction(async r=>{await r.buildArtifact.upsert({where:{buildId_relativePath:{buildId:i.buildId,relativePath:e}},create:{id:(0,t.randomUUID)(),buildId:i.buildId,kind:"EXPORT",relativePath:e,sizeBytes:"number"==typeof a.sizeBytes?a.sizeBytes:null,metadataJson:JSON.stringify({exportId:i.id})},update:{}}),await this.upsertArtifacts(r,i.buildId,a.artifacts)})}this.publish(i.buildId)}}],669602);var S=e.i(907855);let E=S.object({status:S.string().optional(),codebaseId:S.string().optional(),worktreeId:S.string().optional(),first:S.number().int().min(1).max(200).default(50),after:S.string().optional()}),I=S.object({builds:S.array(S.unknown()),nextCursor:S.string().nullable()}),x=S.object({buildId:S.string().min(1),afterLogId:S.string().min(1).nullable().default(null),logLimit:S.number().int().min(1).max(5e3).default(1e3)}),A=S.object({build:S.unknown(),logs:S.array(S.unknown())}),_=S.object({worktreeId:S.string().min(1)}),C=S.object({project:S.unknown().nullable()}),R=S.union([S.object({buildId:S.string().min(1),requestId:S.string().min(1)}),S.object({worktreeId:S.string().min(1),configurationId:S.string().min(1),action:S.string().optional(),requestId:S.string().min(1)})]),T=S.object({destinations:S.array(S.unknown())}),D=S.object({worktreeId:S.string().min(1),configurationId:S.string().min(1),destination:S.record(S.string(),S.unknown()),scriptIds:S.array(S.string()).default([]),action:S.string().optional(),advancedSettings:S.record(S.string(),S.unknown()).optional(),requestId:S.string().min(1)}),N=S.object({build:S.unknown()}),O=S.object({worktreeId:S.string().min(1),reportPath:S.string().min(1).max(4e3),format:S.enum(["AUTO","LCOV","ISTANBUL"]).default("AUTO"),requestId:S.string().min(1)}),P=S.object({build:S.unknown()}),$=S.object({buildId:S.string().min(1),requestId:S.string().min(1)}),U=S.object({build:S.unknown()}),B=S.object({buildId:S.string().min(1),destinations:S.array(S.record(S.string(),S.unknown())).min(1),requestId:S.string().min(1)}),j=S.object({deployments:S.array(S.unknown())}),L=S.object({buildId:S.string().min(1),settings:S.record(S.string(),S.unknown()),requestId:S.string().min(1)}),q=S.object({export:S.unknown()});e.s(["CancelBuildToolInputSchema",0,$,"CancelBuildToolOutputSchema",0,U,"ExportBuildToolInputSchema",0,L,"ExportBuildToolOutputSchema",0,q,"GetBuildConfigurationsInputSchema",0,_,"GetBuildConfigurationsOutputSchema",0,C,"GetBuildDestinationsInputSchema",0,R,"GetBuildDestinationsOutputSchema",0,T,"GetBuildInputSchema",0,x,"GetBuildOutputSchema",0,A,"GetBuildsInputSchema",0,E,"GetBuildsOutputSchema",0,I,"ImportCoverageReportToolInputSchema",0,O,"ImportCoverageReportToolOutputSchema",0,P,"RunBuildToolInputSchema",0,B,"RunBuildToolOutputSchema",0,j,"StartBuildToolInputSchema",0,D,"StartBuildToolOutputSchema",0,N],190714),e.s([],224174),e.i(582482);var M=e.i(318905),F=e.i(91022);let K="default",V={"exact-primary":"EXACT_PRIMARY","prefixed-primary":"PREFIXED_PRIMARY","exact-restore":"EXACT_RESTORE","prefixed-restore":"PREFIXED_RESTORE"};function G(e,t){return t?e.split(t).join("[REDACTED]"):e}function H(e){return{id:e.id,key:e.key,version:e.version,scope:e.scope,repoId:e.repoId,updatedAt:e.updatedAt,locationId:e.locationId}}e.s(["CacheServerService",0,class{credentials;constructor(e=new F.CredentialService){this.credentials=e}async getSettings(){let e=await (0,n.getPrismaClient)(),t=await e.cacheServerSettings.upsert({where:{id:K},create:{id:K},update:{}}),[r,i]=await Promise.all([this.credentials.isConfigured(M.CREDENTIALS.cacheServerApiKey),this.credentials.isConfigured(M.CREDENTIALS.cacheServerHeaders)]);return this.settingsView(t,r,i)}settingsView(e,t,r){return{configured:!!(e.baseUrl&&t),baseUrl:e.baseUrl,apiKeyConfigured:t,headers:(function(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}})(e.headerNamesJson).map(e=>({name:e,valueConfigured:r})),updatedAt:e.updatedAt.toISOString()}}async saveSettings(e){let t=function(e){let t,r=e.trim().replace(/\/+$/,"");if(!r)throw Error("A cache server base URL is required");try{t=new URL(r)}catch{throw Error("The cache server base URL is not a valid URL")}if("http:"!==t.protocol&&"https:"!==t.protocol)throw Error("The cache server base URL must use http or https");return r}(e.baseUrl),r=await this.credentials.isConfigured(M.CREDENTIALS.cacheServerApiKey),i=e.apiKey?.trim()||(r?await this.credentials.getText(M.CREDENTIALS.cacheServerApiKey):null);if(!i)throw Error("A cache server API key is required");let a=await this.credentials.isConfigured(M.CREDENTIALS.cacheServerHeaders)?await this.credentials.getJson(M.CREDENTIALS.cacheServerHeaders)??[]:[],n=function(e,t){if(!e)return[];let r=new Map(t.map(e=>[e.name.toLowerCase(),e.value])),i=new Set,a=[];for(let t of e){let e=t.name.trim();if(!e)continue;let n=e.toLowerCase();if(i.has(n))continue;i.add(n);let s=t.value||r.get(n);if(!s)throw Error(`A value is required for the ${e} header`);a.push({name:e,value:s})}return a}(e.headers,a),s=JSON.stringify(n.map(e=>e.name));return await this.credentials.setMany([{descriptor:M.CREDENTIALS.cacheServerApiKey,value:Buffer.from(i,"utf8")},{descriptor:M.CREDENTIALS.cacheServerHeaders,value:(0,M.encodeJsonCredential)(n)}],async e=>{await e.cacheServerSettings.upsert({where:{id:K},create:{id:K,baseUrl:t,headerNamesJson:s},update:{baseUrl:t,headerNamesJson:s}})}),this.getSettings()}async clearSettings(){return await this.credentials.deleteMany([M.CREDENTIALS.cacheServerApiKey,M.CREDENTIALS.cacheServerHeaders],async e=>{await e.cacheServerSettings.upsert({where:{id:K},create:{id:K},update:{baseUrl:null,headerNamesJson:"[]"}})}),this.getSettings()}async testConnection(){var e;if(!("object"==typeof(e=await this.request("GET","/cache-entries",{query:{itemsPerPage:1,page:1}}))&&null!==e&&"number"==typeof e.total&&Number.isInteger(e.total)&&e.total>=0&&Array.isArray(e.items)))throw Error("Cache server returned an invalid cache entry response");return this.getSettings()}async listCacheEntries(e){let t=await this.request("GET","/cache-entries",{query:{key:e.key?.trim()||void 0,version:e.version?.trim()||void 0,scope:e.scope?.trim()||void 0,repoId:e.repoId?.trim()||void 0,itemsPerPage:e.itemsPerPage??20,page:e.page??1}});return{total:t?.total??0,items:(t?.items??[]).map(H)}}async getCacheEntry(e){let t=await this.request("GET",`/cache-entries/${encodeURIComponent(e)}`,{allowNotFound:!0});return t?H(t):null}async getCacheEntryDetail(e){let t=await this.getCacheEntry(e);if(!t)return null;let r=t.locationId?await this.getStorageLocation(t.locationId):null;return{entry:t,location:r}}async getStorageLocation(e){let t=await this.request("GET",`/storage-locations/${encodeURIComponent(e)}`,{allowNotFound:!0});return t?{id:t.id,folderName:t.folderName,partCount:t.partCount,mergeStartedAt:t.mergeStartedAt??null,mergedAt:t.mergedAt??null,partsDeletedAt:t.partsDeletedAt??null,lastDownloadedAt:t.lastDownloadedAt??null,sizeBytes:t.sizeBytes??null}:null}async matchCacheEntry(e){let t=(e.restoreKeys??[]).map(e=>e.trim()).filter(Boolean),r=e.scopes.map(e=>e.trim()).filter(Boolean),i=await this.request("GET","/cache-entries/match",{query:{primaryKey:e.primaryKey,restoreKeys:t.length>0?t:void 0,scopes:r,repoId:e.repoId,version:e.version}});if(!i)return null;let a=V[i.type];if(!a)throw Error("Cache server returned an unknown match type");return{match:H(i.match),type:a}}async deleteCacheEntry(e){return await this.request("DELETE",`/cache-entries/${encodeURIComponent(e)}`,{allowNotFound:!0}),!0}async deleteCacheEntriesByIds(e){for(let t of e)await this.deleteCacheEntry(t);return!0}async deleteCacheEntries(e){let t=e.repoId?.trim();if(t){let r=new Set,i=1,a=0;do{let n=await this.listCacheEntries({...e,repoId:t,itemsPerPage:100,page:i});for(let e of(a=n.total,n.items))e.repoId===t&&r.add(e.id);i+=1}while((i-1)*100<a)return this.deleteCacheEntriesByIds([...r])}let r={};return e.key?.trim()&&(r.key=e.key.trim()),e.version?.trim()&&(r.version=e.version.trim()),e.scope?.trim()&&(r.scope=e.scope.trim()),await this.request("DELETE","/cache-entries",{body:r}),!0}async deleteStorageLocation(e){return await this.request("DELETE",`/storage-locations/${encodeURIComponent(e)}`,{allowNotFound:!0}),!0}async requireConfig(){let e=await (0,n.getPrismaClient)(),t=await e.cacheServerSettings.findUnique({where:{id:K}});if(!t?.baseUrl)throw Error("The cache server is not configured");let r=await this.credentials.getText(M.CREDENTIALS.cacheServerApiKey);if(!r)throw Error("The cache server is not configured");let i=await this.credentials.getJson(M.CREDENTIALS.cacheServerHeaders)??[];return{baseUrl:t.baseUrl,apiKey:r,headers:i}}buildUrl(e,t,r){let i=new URL(`${e}${t}`);if(r){for(let[e,t]of Object.entries(r))if(null!=t)if(Array.isArray(t))for(let r of t)i.searchParams.append(e,r);else i.searchParams.append(e,String(t))}return i.toString()}async request(e,t,r={}){let i,a,n=await this.requireConfig(),s=this.buildUrl(n.baseUrl,t,r.query),o={accept:"application/json"};for(let e of n.headers)o[e.name]=e.value;o["x-api-key"]=n.apiKey,void 0!==r.body&&(o["content-type"]="application/json");try{i=await fetch(s,{method:e,headers:o,body:void 0!==r.body?JSON.stringify(r.body):void 0,cache:"no-store"})}catch(e){throw Error(G(e instanceof Error?e.message:String(e),n.apiKey))}if(r.allowNotFound&&404===i.status)return null;let l=await i.text();if(l)try{a=JSON.parse(l)}catch{if(!i.ok)throw Error(`Cache server returned HTTP ${i.status}`);a=void 0}if(!i.ok)throw Error(G(a&&"object"==typeof a&&"message"in a&&"string"==typeof a.message?a.message:`Cache server returned HTTP ${i.status}`,n.apiKey));return a??null}}],646462),e.s([],890564)},952128,187963,117958,514849,e=>{"use strict";let t;var r,i,a,n,s,o,l,u=e.i(243783);e.s(["PrismaService",0,class{async healthCheck(){try{let e=await (0,u.getPrismaClient)();return await e.$queryRawUnsafe("SELECT 1"),!0}catch(e){return console.error("Database health check failed:",e),!1}}}],187963),e.s([],952128),(r=n||(n={})).assertEqual=e=>{},r.assertIs=function(e){},r.assertNever=function(e){throw Error()},r.arrayToEnum=e=>{let t={};for(let r of e)t[r]=r;return t},r.getValidEnumValues=e=>{let t=r.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),i={};for(let r of t)i[r]=e[r];return r.objectValues(i)},r.objectValues=e=>r.objectKeys(e).map(function(t){return e[t]}),r.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{let t=[];for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},r.find=(e,t)=>{for(let r of e)if(t(r))return r},r.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,r.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},r.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(s||(s={})).mergeShapes=(e,t)=>({...e,...t});let c=n.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),d=e=>{switch(typeof e){case"undefined":return c.undefined;case"string":return c.string;case"number":return Number.isNaN(e)?c.nan:c.number;case"boolean":return c.boolean;case"function":return c.function;case"bigint":return c.bigint;case"symbol":return c.symbol;case"object":if(Array.isArray(e))return c.array;if(null===e)return c.null;if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return c.promise;if("u">typeof Map&&e instanceof Map)return c.map;if("u">typeof Set&&e instanceof Set)return c.set;if("u">typeof Date&&e instanceof Date)return c.date;return c.object;default:return c.unknown}},p=n.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class h extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(e){return e.message},r={_errors:[]},i=e=>{for(let a of e.issues)if("invalid_union"===a.code)a.unionErrors.map(i);else if("invalid_return_type"===a.code)i(a.returnTypeError);else if("invalid_arguments"===a.code)i(a.argumentsError);else if(0===a.path.length)r._errors.push(t(a));else{let e=r,i=0;for(;i<a.path.length;){let r=a.path[i];i===a.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(a))):e[r]=e[r]||{_errors:[]},e=e[r],i++}}};return i(this),r}static assert(e){if(!(e instanceof h))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,n.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){let t=Object.create(null),r=[];for(let i of this.issues)if(i.path.length>0){let r=i.path[0];t[r]=t[r]||[],t[r].push(e(i))}else r.push(e(i));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}h.create=e=>new h(e);let m=(e,t)=>{let r;switch(e.code){case p.invalid_type:r=e.received===c.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case p.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,n.jsonStringifyReplacer)}`;break;case p.unrecognized_keys:r=`Unrecognized key(s) in object: ${n.joinValues(e.keys,", ")}`;break;case p.invalid_union:r="Invalid input";break;case p.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${n.joinValues(e.options)}`;break;case p.invalid_enum_value:r=`Invalid enum value. Expected ${n.joinValues(e.options)}, received '${e.received}'`;break;case p.invalid_arguments:r="Invalid function arguments";break;case p.invalid_return_type:r="Invalid function return type";break;case p.invalid_date:r="Invalid date";break;case p.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:n.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case p.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case p.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case p.custom:r="Invalid input";break;case p.invalid_intersection_types:r="Intersection results could not be merged";break;case p.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case p.not_finite:r="Number must be finite";break;default:r=t.defaultError,n.assertNever(e)}return{message:r}};(i=o||(o={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},i.toString=e=>"string"==typeof e?e:e?.message;let f=e=>{let{data:t,path:r,errorMaps:i,issueData:a}=e,n=[...r,...a.path||[]],s={...a,path:n};if(void 0!==a.message)return{...a,path:n,message:a.message};let o="";for(let e of i.filter(e=>!!e).slice().reverse())o=e(s,{data:t,defaultError:o}).message;return{...a,path:n,message:o}};function g(e,t){let r=f({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,m,void 0].filter(e=>!!e)});e.common.issues.push(r)}class y{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let i of t){if("aborted"===i.status)return w;"dirty"===i.status&&e.dirty(),r.push(i.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let e of t){let t=await e.key,i=await e.value;r.push({key:t,value:i})}return y.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let i of t){let{key:t,value:a}=i;if("aborted"===t.status||"aborted"===a.status)return w;"dirty"===t.status&&e.dirty(),"dirty"===a.status&&e.dirty(),"__proto__"!==t.value&&(void 0!==a.value||i.alwaysSet)&&(r[t.value]=a.value)}return{status:e.value,value:r}}}let w=Object.freeze({status:"aborted"}),b=e=>({status:"dirty",value:e}),v=e=>({status:"valid",value:e}),k=e=>"u">typeof Promise&&e instanceof Promise;class S{constructor(e,t,r,i){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}let E=(e,t)=>{if("valid"===t.status)return{success:!0,data:t.value};if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new h(e.common.issues);return this._error=t,this._error}}};function I(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:i,description:a}=e;if(t&&(r||i))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:a}:{errorMap:(t,a)=>{let{message:n}=e;return"invalid_enum_value"===t.code?{message:n??a.defaultError}:void 0===a.data?{message:n??i??a.defaultError}:"invalid_type"!==t.code?{message:a.defaultError}:{message:n??r??a.defaultError}},description:a}}class x{get description(){return this._def.description}_getType(e){return d(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:d(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new y,ctx:{common:e.parent.common,data:e.data,parsedType:d(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(k(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){return Promise.resolve(this._parse(e))}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:d(e)},i=this._parseSync({data:e,path:r.path,parent:r});return E(r,i)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:d(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return"valid"===r.status?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>"valid"===e.status?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:d(e)},i=this._parse({data:e,path:r.path,parent:r});return E(r,await (k(i)?i:Promise.resolve(i)))}refine(e,t){return this._refinement((r,i)=>{let a=e(r),n=()=>i.addIssue({code:p.custom,..."string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(r):t});return"u">typeof Promise&&a instanceof Promise?a.then(e=>!!e||(n(),!1)):!!a||(n(),!1)})}refinement(e,t){return this._refinement((r,i)=>!!e(r)||(i.addIssue("function"==typeof t?t(r,i):t),!1))}_refinement(e){return new ew({schema:this,typeName:l.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return eb.create(this,this._def)}nullable(){return ev.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return et.create(this)}promise(){return ey.create(this,this._def)}or(e){return ei.create([this,e],this._def)}and(e){return es.create(this,e,this._def)}transform(e){return new ew({...I(this._def),schema:this,typeName:l.ZodEffects,effect:{type:"transform",transform:e}})}default(e){return new ek({...I(this._def),innerType:this,defaultValue:"function"==typeof e?e:()=>e,typeName:l.ZodDefault})}brand(){return new eI({typeName:l.ZodBranded,type:this,...I(this._def)})}catch(e){return new eS({...I(this._def),innerType:this,catchValue:"function"==typeof e?e:()=>e,typeName:l.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return ex.create(this,e)}readonly(){return eA.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let A=/^c[^\s-]{8,}$/i,_=/^[0-9a-z]+$/,C=/^[0-9A-HJKMNP-TV-Z]{26}$/i,R=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,T=/^[a-z0-9_-]{21}$/i,D=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,N=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,O=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,P=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,$=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,U=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,B=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,j=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,L=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,q="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",M=RegExp(`^${q}$`);function F(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}class K extends x{_parse(e){var r,i,a,s;let o;if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==c.string){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.string,received:t.parsedType}),w}let l=new y;for(let u of this._def.checks)if("min"===u.kind)e.data.length<u.value&&(g(o=this._getOrReturnCtx(e,o),{code:p.too_small,minimum:u.value,type:"string",inclusive:!0,exact:!1,message:u.message}),l.dirty());else if("max"===u.kind)e.data.length>u.value&&(g(o=this._getOrReturnCtx(e,o),{code:p.too_big,maximum:u.value,type:"string",inclusive:!0,exact:!1,message:u.message}),l.dirty());else if("length"===u.kind){let t=e.data.length>u.value,r=e.data.length<u.value;(t||r)&&(o=this._getOrReturnCtx(e,o),t?g(o,{code:p.too_big,maximum:u.value,type:"string",inclusive:!0,exact:!0,message:u.message}):r&&g(o,{code:p.too_small,minimum:u.value,type:"string",inclusive:!0,exact:!0,message:u.message}),l.dirty())}else if("email"===u.kind)O.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"email",code:p.invalid_string,message:u.message}),l.dirty());else if("emoji"===u.kind)t||(t=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),t.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"emoji",code:p.invalid_string,message:u.message}),l.dirty());else if("uuid"===u.kind)R.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"uuid",code:p.invalid_string,message:u.message}),l.dirty());else if("nanoid"===u.kind)T.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"nanoid",code:p.invalid_string,message:u.message}),l.dirty());else if("cuid"===u.kind)A.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"cuid",code:p.invalid_string,message:u.message}),l.dirty());else if("cuid2"===u.kind)_.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"cuid2",code:p.invalid_string,message:u.message}),l.dirty());else if("ulid"===u.kind)C.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"ulid",code:p.invalid_string,message:u.message}),l.dirty());else if("url"===u.kind)try{new URL(e.data)}catch{g(o=this._getOrReturnCtx(e,o),{validation:"url",code:p.invalid_string,message:u.message}),l.dirty()}else"regex"===u.kind?(u.regex.lastIndex=0,u.regex.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"regex",code:p.invalid_string,message:u.message}),l.dirty())):"trim"===u.kind?e.data=e.data.trim():"includes"===u.kind?e.data.includes(u.value,u.position)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:{includes:u.value,position:u.position},message:u.message}),l.dirty()):"toLowerCase"===u.kind?e.data=e.data.toLowerCase():"toUpperCase"===u.kind?e.data=e.data.toUpperCase():"startsWith"===u.kind?e.data.startsWith(u.value)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:{startsWith:u.value},message:u.message}),l.dirty()):"endsWith"===u.kind?e.data.endsWith(u.value)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:{endsWith:u.value},message:u.message}),l.dirty()):"datetime"===u.kind?(function(e){let t=`${q}T${F(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,RegExp(`^${t}$`)})(u).test(e.data)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:"datetime",message:u.message}),l.dirty()):"date"===u.kind?M.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:"date",message:u.message}),l.dirty()):"time"===u.kind?RegExp(`^${F(u)}$`).test(e.data)||(g(o=this._getOrReturnCtx(e,o),{code:p.invalid_string,validation:"time",message:u.message}),l.dirty()):"duration"===u.kind?N.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"duration",code:p.invalid_string,message:u.message}),l.dirty()):"ip"===u.kind?(r=e.data,!(("v4"===(i=u.version)||!i)&&P.test(r)||("v6"===i||!i)&&U.test(r))&&1&&(g(o=this._getOrReturnCtx(e,o),{validation:"ip",code:p.invalid_string,message:u.message}),l.dirty())):"jwt"===u.kind?!function(e,t){if(!D.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let i=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),a=JSON.parse(atob(i));if("object"!=typeof a||null===a||"typ"in a&&a?.typ!=="JWT"||!a.alg||t&&a.alg!==t)return!1;return!0}catch{return!1}}(e.data,u.alg)&&(g(o=this._getOrReturnCtx(e,o),{validation:"jwt",code:p.invalid_string,message:u.message}),l.dirty()):"cidr"===u.kind?(a=e.data,!(("v4"===(s=u.version)||!s)&&$.test(a)||("v6"===s||!s)&&B.test(a))&&1&&(g(o=this._getOrReturnCtx(e,o),{validation:"cidr",code:p.invalid_string,message:u.message}),l.dirty())):"base64"===u.kind?j.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"base64",code:p.invalid_string,message:u.message}),l.dirty()):"base64url"===u.kind?L.test(e.data)||(g(o=this._getOrReturnCtx(e,o),{validation:"base64url",code:p.invalid_string,message:u.message}),l.dirty()):n.assertNever(u);return{status:l.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:p.invalid_string,...o.errToObj(r)})}_addCheck(e){return new K({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...o.errToObj(e)})}url(e){return this._addCheck({kind:"url",...o.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...o.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...o.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...o.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...o.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...o.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...o.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...o.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...o.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...o.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...o.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...o.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...o.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...o.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...o.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...o.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...o.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...o.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...o.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...o.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...o.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...o.errToObj(t)})}nonempty(e){return this.min(1,o.errToObj(e))}trim(){return new K({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new K({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new K({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}K.create=e=>new K({checks:[],typeName:l.ZodString,coerce:e?.coerce??!1,...I(e)});class V extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){let t;if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==c.number){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.number,received:t.parsedType}),w}let r=new y;for(let i of this._def.checks)"int"===i.kind?n.isInteger(e.data)||(g(t=this._getOrReturnCtx(e,t),{code:p.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()):"min"===i.kind?(i.inclusive?e.data<i.value:e.data<=i.value)&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):"max"===i.kind?(i.inclusive?e.data>i.value:e.data>=i.value)&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):"multipleOf"===i.kind?0!==function(e,t){let r=(e.toString().split(".")[1]||"").length,i=(t.toString().split(".")[1]||"").length,a=r>i?r:i;return Number.parseInt(e.toFixed(a).replace(".",""))%Number.parseInt(t.toFixed(a).replace(".",""))/10**a}(e.data,i.value)&&(g(t=this._getOrReturnCtx(e,t),{code:p.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):"finite"===i.kind?Number.isFinite(e.data)||(g(t=this._getOrReturnCtx(e,t),{code:p.not_finite,message:i.message}),r.dirty()):n.assertNever(i);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,o.toString(t))}gt(e,t){return this.setLimit("min",e,!1,o.toString(t))}lte(e,t){return this.setLimit("max",e,!0,o.toString(t))}lt(e,t){return this.setLimit("max",e,!1,o.toString(t))}setLimit(e,t,r,i){return new V({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:o.toString(i)}]})}_addCheck(e){return new V({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:o.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:o.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:o.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:o.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:o.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:o.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:o.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:o.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:o.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&n.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;else"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value);return Number.isFinite(t)&&Number.isFinite(e)}}V.create=e=>new V({checks:[],typeName:l.ZodNumber,coerce:e?.coerce||!1,...I(e)});class G extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){let t;if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==c.bigint)return this._getInvalidInput(e);let r=new y;for(let i of this._def.checks)"min"===i.kind?(i.inclusive?e.data<i.value:e.data<=i.value)&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):"max"===i.kind?(i.inclusive?e.data>i.value:e.data>=i.value)&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):"multipleOf"===i.kind?e.data%i.value!==BigInt(0)&&(g(t=this._getOrReturnCtx(e,t),{code:p.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):n.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.bigint,received:t.parsedType}),w}gte(e,t){return this.setLimit("min",e,!0,o.toString(t))}gt(e,t){return this.setLimit("min",e,!1,o.toString(t))}lte(e,t){return this.setLimit("max",e,!0,o.toString(t))}lt(e,t){return this.setLimit("max",e,!1,o.toString(t))}setLimit(e,t,r,i){return new G({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:o.toString(i)}]})}_addCheck(e){return new G({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:o.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:o.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:o.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:o.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:o.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}G.create=e=>new G({checks:[],typeName:l.ZodBigInt,coerce:e?.coerce??!1,...I(e)});class H extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==c.boolean){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.boolean,received:t.parsedType}),w}return v(e.data)}}H.create=e=>new H({typeName:l.ZodBoolean,coerce:e?.coerce||!1,...I(e)});class W extends x{_parse(e){let t;if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==c.date){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.date,received:t.parsedType}),w}if(Number.isNaN(e.data.getTime()))return g(this._getOrReturnCtx(e),{code:p.invalid_date}),w;let r=new y;for(let i of this._def.checks)"min"===i.kind?e.data.getTime()<i.value&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):"max"===i.kind?e.data.getTime()>i.value&&(g(t=this._getOrReturnCtx(e,t),{code:p.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):n.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new W({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:o.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:o.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}W.create=e=>new W({checks:[],coerce:e?.coerce||!1,typeName:l.ZodDate,...I(e)});class J extends x{_parse(e){if(this._getType(e)!==c.symbol){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.symbol,received:t.parsedType}),w}return v(e.data)}}J.create=e=>new J({typeName:l.ZodSymbol,...I(e)});class z extends x{_parse(e){if(this._getType(e)!==c.undefined){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.undefined,received:t.parsedType}),w}return v(e.data)}}z.create=e=>new z({typeName:l.ZodUndefined,...I(e)});class Z extends x{_parse(e){if(this._getType(e)!==c.null){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.null,received:t.parsedType}),w}return v(e.data)}}Z.create=e=>new Z({typeName:l.ZodNull,...I(e)});class Y extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return v(e.data)}}Y.create=e=>new Y({typeName:l.ZodAny,...I(e)});class Q extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return v(e.data)}}Q.create=e=>new Q({typeName:l.ZodUnknown,...I(e)});class X extends x{_parse(e){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.never,received:t.parsedType}),w}}X.create=e=>new X({typeName:l.ZodNever,...I(e)});class ee extends x{_parse(e){if(this._getType(e)!==c.undefined){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.void,received:t.parsedType}),w}return v(e.data)}}ee.create=e=>new ee({typeName:l.ZodVoid,...I(e)});class et extends x{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),i=this._def;if(t.parsedType!==c.array)return g(t,{code:p.invalid_type,expected:c.array,received:t.parsedType}),w;if(null!==i.exactLength){let e=t.data.length>i.exactLength.value,a=t.data.length<i.exactLength.value;(e||a)&&(g(t,{code:e?p.too_big:p.too_small,minimum:a?i.exactLength.value:void 0,maximum:e?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(null!==i.minLength&&t.data.length<i.minLength.value&&(g(t,{code:p.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),null!==i.maxLength&&t.data.length>i.maxLength.value&&(g(t,{code:p.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>i.type._parseAsync(new S(t,e,t.path,r)))).then(e=>y.mergeArray(r,e));let a=[...t.data].map((e,r)=>i.type._parseSync(new S(t,e,t.path,r)));return y.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new et({...this._def,minLength:{value:e,message:o.toString(t)}})}max(e,t){return new et({...this._def,maxLength:{value:e,message:o.toString(t)}})}length(e,t){return new et({...this._def,exactLength:{value:e,message:o.toString(t)}})}nonempty(e){return this.min(1,e)}}et.create=(e,t)=>new et({type:e,minLength:null,maxLength:null,exactLength:null,typeName:l.ZodArray,...I(t)});class er extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let e=this._def.shape(),t=n.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==c.object){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.object,received:t.parsedType}),w}let{status:t,ctx:r}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),n=[];if(!(this._def.catchall instanceof X&&"strip"===this._def.unknownKeys))for(let e in r.data)a.includes(e)||n.push(e);let s=[];for(let e of a){let t=i[e],a=r.data[e];s.push({key:{status:"valid",value:e},value:t._parse(new S(r,a,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof X){let e=this._def.unknownKeys;if("passthrough"===e)for(let e of n)s.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)n.length>0&&(g(r,{code:p.unrecognized_keys,keys:n}),t.dirty());else if("strip"===e);else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let e=this._def.catchall;for(let t of n){let i=r.data[t];s.push({key:{status:"valid",value:t},value:e._parse(new S(r,i,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of s){let r=await t.key,i=await t.value;e.push({key:r,value:i,alwaysSet:t.alwaysSet})}return e}).then(e=>y.mergeObjectSync(t,e)):y.mergeObjectSync(t,s)}get shape(){return this._def.shape()}strict(e){return o.errToObj,new er({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{let i=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:o.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new er({...this._def,unknownKeys:"strip"})}passthrough(){return new er({...this._def,unknownKeys:"passthrough"})}extend(e){return new er({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new er({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:l.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new er({...this._def,catchall:e})}pick(e){let t={};for(let r of n.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new er({...this._def,shape:()=>t})}omit(e){let t={};for(let r of n.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new er({...this._def,shape:()=>t})}deepPartial(){return function e(t){if(t instanceof er){let r={};for(let i in t.shape){let a=t.shape[i];r[i]=eb.create(e(a))}return new er({...t._def,shape:()=>r})}if(t instanceof et)return new et({...t._def,type:e(t.element)});if(t instanceof eb)return eb.create(e(t.unwrap()));if(t instanceof ev)return ev.create(e(t.unwrap()));if(t instanceof eo)return eo.create(t.items.map(t=>e(t)));else return t}(this)}partial(e){let t={};for(let r of n.objectKeys(this.shape)){let i=this.shape[r];e&&!e[r]?t[r]=i:t[r]=i.optional()}return new er({...this._def,shape:()=>t})}required(e){let t={};for(let r of n.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof eb;)e=e._def.innerType;t[r]=e}return new er({...this._def,shape:()=>t})}keyof(){return em(n.objectKeys(this.shape))}}er.create=(e,t)=>new er({shape:()=>e,unknownKeys:"strip",catchall:X.create(),typeName:l.ZodObject,...I(t)}),er.strictCreate=(e,t)=>new er({shape:()=>e,unknownKeys:"strict",catchall:X.create(),typeName:l.ZodObject,...I(t)}),er.lazycreate=(e,t)=>new er({shape:e,unknownKeys:"strip",catchall:X.create(),typeName:l.ZodObject,...I(t)});class ei extends x{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{let r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(let t of e)if("valid"===t.result.status)return t.result;for(let r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;let r=e.map(e=>new h(e.ctx.common.issues));return g(t,{code:p.invalid_union,unionErrors:r}),w});{let e,i=[];for(let a of r){let r={...t,common:{...t.common,issues:[]},parent:null},n=a._parseSync({data:t.data,path:t.path,parent:r});if("valid"===n.status)return n;"dirty"!==n.status||e||(e={result:n,ctx:r}),r.common.issues.length&&i.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let a=i.map(e=>new h(e));return g(t,{code:p.invalid_union,unionErrors:a}),w}}get options(){return this._def.options}}ei.create=(e,t)=>new ei({options:e,typeName:l.ZodUnion,...I(t)});let ea=e=>{if(e instanceof ep)return ea(e.schema);if(e instanceof ew)return ea(e.innerType());if(e instanceof eh)return[e.value];if(e instanceof ef)return e.options;if(e instanceof eg)return n.objectValues(e.enum);else if(e instanceof ek)return ea(e._def.innerType);else if(e instanceof z)return[void 0];else if(e instanceof Z)return[null];else if(e instanceof eb)return[void 0,...ea(e.unwrap())];else if(e instanceof ev)return[null,...ea(e.unwrap())];else if(e instanceof eI)return ea(e.unwrap());else if(e instanceof eA)return ea(e.unwrap());else if(e instanceof eS)return ea(e._def.innerType);else return[]};class en extends x{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==c.object)return g(t,{code:p.invalid_type,expected:c.object,received:t.parsedType}),w;let r=this.discriminator,i=t.data[r],a=this.optionsMap.get(i);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(g(t,{code:p.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),w)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let i=new Map;for(let r of t){let t=ea(r.shape[e]);if(!t.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of t){if(i.has(a))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,r)}}return new en({typeName:l.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:i,...I(r)})}}class es extends x{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),i=(e,i)=>{if("aborted"===e.status||"aborted"===i.status)return w;let a=function e(t,r){let i=d(t),a=d(r);if(t===r)return{valid:!0,data:t};if(i===c.object&&a===c.object){let i=n.objectKeys(r),a=n.objectKeys(t).filter(e=>-1!==i.indexOf(e)),s={...t,...r};for(let i of a){let a=e(t[i],r[i]);if(!a.valid)return{valid:!1};s[i]=a.data}return{valid:!0,data:s}}if(i===c.array&&a===c.array){if(t.length!==r.length)return{valid:!1};let i=[];for(let a=0;a<t.length;a++){let n=e(t[a],r[a]);if(!n.valid)return{valid:!1};i.push(n.data)}return{valid:!0,data:i}}if(i===c.date&&a===c.date&&+t==+r)return{valid:!0,data:t};return{valid:!1}}(e.value,i.value);return a.valid?(("dirty"===e.status||"dirty"===i.status)&&t.dirty(),{status:t.value,value:a.data}):(g(r,{code:p.invalid_intersection_types}),w)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>i(e,t)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}es.create=(e,t,r)=>new es({left:e,right:t,typeName:l.ZodIntersection,...I(r)});class eo extends x{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==c.array)return g(r,{code:p.invalid_type,expected:c.array,received:r.parsedType}),w;if(r.data.length<this._def.items.length)return g(r,{code:p.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w;!this._def.rest&&r.data.length>this._def.items.length&&(g(r,{code:p.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...r.data].map((e,t)=>{let i=this._def.items[t]||this._def.rest;return i?i._parse(new S(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(i).then(e=>y.mergeArray(t,e)):y.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new eo({...this._def,rest:e})}}eo.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new eo({items:e,typeName:l.ZodTuple,rest:null,...I(t)})};class el extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==c.object)return g(r,{code:p.invalid_type,expected:c.object,received:r.parsedType}),w;let i=[],a=this._def.keyType,n=this._def.valueType;for(let e in r.data)i.push({key:a._parse(new S(r,e,r.path,e)),value:n._parse(new S(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?y.mergeObjectAsync(t,i):y.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,r){return new el(t instanceof x?{keyType:e,valueType:t,typeName:l.ZodRecord,...I(r)}:{keyType:K.create(),valueType:e,typeName:l.ZodRecord,...I(t)})}}class eu extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==c.map)return g(r,{code:p.invalid_type,expected:c.map,received:r.parsedType}),w;let i=this._def.keyType,a=this._def.valueType,n=[...r.data.entries()].map(([e,t],n)=>({key:i._parse(new S(r,e,r.path,[n,"key"])),value:a._parse(new S(r,t,r.path,[n,"value"]))}));if(r.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let r of n){let i=await r.key,a=await r.value;if("aborted"===i.status||"aborted"===a.status)return w;("dirty"===i.status||"dirty"===a.status)&&t.dirty(),e.set(i.value,a.value)}return{status:t.value,value:e}})}{let e=new Map;for(let r of n){let i=r.key,a=r.value;if("aborted"===i.status||"aborted"===a.status)return w;("dirty"===i.status||"dirty"===a.status)&&t.dirty(),e.set(i.value,a.value)}return{status:t.value,value:e}}}}eu.create=(e,t,r)=>new eu({valueType:t,keyType:e,typeName:l.ZodMap,...I(r)});class ec extends x{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==c.set)return g(r,{code:p.invalid_type,expected:c.set,received:r.parsedType}),w;let i=this._def;null!==i.minSize&&r.data.size<i.minSize.value&&(g(r,{code:p.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),t.dirty()),null!==i.maxSize&&r.data.size>i.maxSize.value&&(g(r,{code:p.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());let a=this._def.valueType;function n(e){let r=new Set;for(let i of e){if("aborted"===i.status)return w;"dirty"===i.status&&t.dirty(),r.add(i.value)}return{status:t.value,value:r}}let s=[...r.data.values()].map((e,t)=>a._parse(new S(r,e,r.path,t)));return r.common.async?Promise.all(s).then(e=>n(e)):n(s)}min(e,t){return new ec({...this._def,minSize:{value:e,message:o.toString(t)}})}max(e,t){return new ec({...this._def,maxSize:{value:e,message:o.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ec.create=(e,t)=>new ec({valueType:e,minSize:null,maxSize:null,typeName:l.ZodSet,...I(t)});class ed extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==c.function)return g(t,{code:p.invalid_type,expected:c.function,received:t.parsedType}),w;function r(e,r){return f({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,m,m].filter(e=>!!e),issueData:{code:p.invalid_arguments,argumentsError:r}})}function i(e,r){return f({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,m,m].filter(e=>!!e),issueData:{code:p.invalid_return_type,returnTypeError:r}})}let a={errorMap:t.common.contextualErrorMap},n=t.data;if(this._def.returns instanceof ey){let e=this;return v(async function(...t){let s=new h([]),o=await e._def.args.parseAsync(t,a).catch(e=>{throw s.addIssue(r(t,e)),s}),l=await Reflect.apply(n,this,o);return await e._def.returns._def.type.parseAsync(l,a).catch(e=>{throw s.addIssue(i(l,e)),s})})}{let e=this;return v(function(...t){let s=e._def.args.safeParse(t,a);if(!s.success)throw new h([r(t,s.error)]);let o=Reflect.apply(n,this,s.data),l=e._def.returns.safeParse(o,a);if(!l.success)throw new h([i(o,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ed({...this._def,args:eo.create(e).rest(Q.create())})}returns(e){return new ed({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new ed({args:e||eo.create([]).rest(Q.create()),returns:t||Q.create(),typeName:l.ZodFunction,...I(r)})}}class ep extends x{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ep.create=(e,t)=>new ep({getter:e,typeName:l.ZodLazy,...I(t)});class eh extends x{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return g(t,{received:t.data,code:p.invalid_literal,expected:this._def.value}),w}return{status:"valid",value:e.data}}get value(){return this._def.value}}function em(e,t){return new ef({values:e,typeName:l.ZodEnum,...I(t)})}eh.create=(e,t)=>new eh({value:e,typeName:l.ZodLiteral,...I(t)});class ef extends x{_parse(e){if("string"!=typeof e.data){let t=this._getOrReturnCtx(e),r=this._def.values;return g(t,{expected:n.joinValues(r),received:t.parsedType,code:p.invalid_type}),w}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return g(t,{received:t.data,code:p.invalid_enum_value,options:r}),w}return v(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ef.create(e,{...this._def,...t})}exclude(e,t=this._def){return ef.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}ef.create=em;class eg extends x{_parse(e){let t=n.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==c.string&&r.parsedType!==c.number){let e=n.objectValues(t);return g(r,{expected:n.joinValues(e),received:r.parsedType,code:p.invalid_type}),w}if(this._cache||(this._cache=new Set(n.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let e=n.objectValues(t);return g(r,{received:r.data,code:p.invalid_enum_value,options:e}),w}return v(e.data)}get enum(){return this._def.values}}eg.create=(e,t)=>new eg({values:e,typeName:l.ZodNativeEnum,...I(t)});class ey extends x{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==c.promise&&!1===t.common.async?(g(t,{code:p.invalid_type,expected:c.promise,received:t.parsedType}),w):v((t.parsedType===c.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ey.create=(e,t)=>new ey({type:e,typeName:l.ZodPromise,...I(t)});class ew extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===l.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),i=this._def.effect||null,a={addIssue:e=>{g(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),"preprocess"===i.type){let e=i.transform(r.data,a);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return w;let i=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===i.status?w:"dirty"===i.status||"dirty"===t.value?b(i.value):i});{if("aborted"===t.value)return w;let i=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===i.status?w:"dirty"===i.status||"dirty"===t.value?b(i.value):i}}if("refinement"===i.type){let e=e=>{let t=i.refinement(e,a);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?w:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))));{let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===i.status?w:("dirty"===i.status&&t.dirty(),e(i.value),{status:t.value,value:i.value})}}if("transform"===i.type)if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>"valid"!==e.status?w:Promise.resolve(i.transform(e.value,a)).then(e=>({status:t.value,value:e})));else{let e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if("valid"!==e.status)return w;let n=i.transform(e.value,a);if(n instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:n}}n.assertNever(i)}}ew.create=(e,t,r)=>new ew({schema:e,typeName:l.ZodEffects,effect:t,...I(r)}),ew.createWithPreprocess=(e,t,r)=>new ew({schema:t,effect:{type:"preprocess",transform:e},typeName:l.ZodEffects,...I(r)});class eb extends x{_parse(e){return this._getType(e)===c.undefined?v(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}eb.create=(e,t)=>new eb({innerType:e,typeName:l.ZodOptional,...I(t)});class ev extends x{_parse(e){return this._getType(e)===c.null?v(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ev.create=(e,t)=>new ev({innerType:e,typeName:l.ZodNullable,...I(t)});class ek extends x{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===c.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ek.create=(e,t)=>new ek({innerType:e,typeName:l.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...I(t)});class eS extends x{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return k(i)?i.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new h(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===i.status?i.value:this._def.catchValue({get error(){return new h(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}eS.create=(e,t)=>new eS({innerType:e,typeName:l.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...I(t)});class eE extends x{_parse(e){if(this._getType(e)!==c.nan){let t=this._getOrReturnCtx(e);return g(t,{code:p.invalid_type,expected:c.nan,received:t.parsedType}),w}return{status:"valid",value:e.data}}}eE.create=e=>new eE({typeName:l.ZodNaN,...I(e)}),Symbol("zod_brand");class eI extends x{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class ex extends x{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?w:"dirty"===e.status?(t.dirty(),b(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{let e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?w:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new ex({in:e,out:t,typeName:l.ZodPipeline})}}class eA extends x{_parse(e){let t=this._def.innerType._parse(e),r=e=>("valid"===e.status&&(e.value=Object.freeze(e.value)),e);return k(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}eA.create=(e,t)=>new eA({innerType:e,typeName:l.ZodReadonly,...I(t)}),er.lazycreate,(a=l||(l={})).ZodString="ZodString",a.ZodNumber="ZodNumber",a.ZodNaN="ZodNaN",a.ZodBigInt="ZodBigInt",a.ZodBoolean="ZodBoolean",a.ZodDate="ZodDate",a.ZodSymbol="ZodSymbol",a.ZodUndefined="ZodUndefined",a.ZodNull="ZodNull",a.ZodAny="ZodAny",a.ZodUnknown="ZodUnknown",a.ZodNever="ZodNever",a.ZodVoid="ZodVoid",a.ZodArray="ZodArray",a.ZodObject="ZodObject",a.ZodUnion="ZodUnion",a.ZodDiscriminatedUnion="ZodDiscriminatedUnion",a.ZodIntersection="ZodIntersection",a.ZodTuple="ZodTuple",a.ZodRecord="ZodRecord",a.ZodMap="ZodMap",a.ZodSet="ZodSet",a.ZodFunction="ZodFunction",a.ZodLazy="ZodLazy",a.ZodLiteral="ZodLiteral",a.ZodEnum="ZodEnum",a.ZodEffects="ZodEffects",a.ZodNativeEnum="ZodNativeEnum",a.ZodOptional="ZodOptional",a.ZodNullable="ZodNullable",a.ZodDefault="ZodDefault",a.ZodCatch="ZodCatch",a.ZodPromise="ZodPromise",a.ZodBranded="ZodBranded",a.ZodPipeline="ZodPipeline",a.ZodReadonly="ZodReadonly",K.create,V.create,eE.create,G.create,H.create,W.create,J.create,z.create,Z.create,Y.create,Q.create,X.create,ee.create,et.create;let e_=er.create;er.strictCreate,ei.create,en.create,es.create,eo.create,el.create,eu.create,ec.create,ed.create,ep.create,eh.create,ef.create,eg.create,ey.create,ew.create,eb.create,ev.create,ew.createWithPreprocess,ex.create,e.s(["ZodFirstPartyTypeKind",0,l,"object",0,e_],117958);var eC=e.i(127438),eR=e.i(639510),eT=e.i(486618),eD=e.i(862061);e.i(467662),e.i(236608);var eN=e.i(715143);let eO=eC.$constructor("ZodMiniType",(e,t)=>{if(!e._zod)throw Error("Uninitialized schema in ZodMiniType.");eR.$ZodType.init(e,t),e.def=t,e.type=t.type,e.parse=(t,r)=>eN.parse(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>eN.safeParse(e,t,r),e.parseAsync=async(t,r)=>eN.parseAsync(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>eN.safeParseAsync(e,t,r),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,r)=>eT.clone(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.apply=t=>t(e)}),eP=eC.$constructor("ZodMiniString",(e,t)=>{eR.$ZodString.init(e,t),eO.init(e,t)}),e$=((e,t)=>{eR.$ZodStringFormat.init(e,t),eP.init(e,t)},eC.$constructor("ZodMiniObject",(e,t)=>{eR.$ZodObject.init(e,t),eO.init(e,t),eT.defineLazy(e,"shape",()=>t.shape)}));function eU(e,t){return new e$({type:"object",shape:e??{},...eT.normalizeParams(t)})}function eB(e){return!!e._zod}function ej(e){let t=Object.values(e);if(0===t.length)return eU({});let r=t.every(eB),i=t.every(e=>!eB(e));if(r)return eU(e);if(i)return e_(e);throw Error("Mixed Zod versions detected in object shape.")}async function eL(e,t){return eB(e)?await eN.safeParseAsync(e,t):await e.safeParseAsync(t)}eD.describe,eD.meta,e.s(["getLiteralValue",0,function(e){if(eB(e)){let t=e._zod?.def;if(t){if(void 0!==t.value)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(void 0!==t.value)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let r=e.value;if(void 0!==r)return r},"getObjectShape",0,function(e){let t;if(e&&(t=eB(e)?e._zod?.def?.shape:e.shape)){if("function"==typeof t)try{return t()}catch{return}return t}},"getParseErrorMessage",0,function(e){if(e&&"object"==typeof e){if("message"in e&&"string"==typeof e.message)return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&"object"==typeof t&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch{}}return String(e)},"getSchemaDescription",0,function(e){return e.description},"isSchemaOptional",0,function(e){return eB(e)?e._zod?.def?.type==="optional":"function"==typeof e.isOptional?e.isOptional():e._def?.typeName==="ZodOptional"},"isZ4Schema",0,eB,"normalizeObjectSchema",0,function(e){if(e){if("object"==typeof e&&!e._def&&!e._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>"object"==typeof e&&null!==e&&(void 0!==e._def||void 0!==e._zod||"function"==typeof e.parse)))return ej(e)}if(eB(e)){let t=e._zod?.def;if(t&&("object"===t.type||void 0!==t.shape))return e}else if(void 0!==e.shape)return e}},"objectFromShape",0,ej,"safeParse",0,function(e,t){return eB(e)?eN.safeParse(e,t):e.safeParse(t)},"safeParseAsync",0,eL],514849)},556690,807237,e=>{"use strict";var t,r,i=e.i(907855),a=e.i(551047);e.s(["iso",0,a],807237);var a=a;let n="2025-11-25",s=[n,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],o="io.modelcontextprotocol/related-task",l=i.custom(e=>null!==e&&("object"==typeof e||"function"==typeof e)),u=i.union([i.string(),i.number().int()]),c=i.string();i.looseObject({ttl:i.number().optional(),pollInterval:i.number().optional()});let d=i.object({ttl:i.number().optional()}),p=i.object({taskId:i.string()}),h=i.looseObject({progressToken:u.optional(),[o]:p.optional()}),m=i.object({_meta:h.optional()}),f=m.extend({task:d.optional()}),g=i.object({method:i.string(),params:m.loose().optional()}),y=i.object({_meta:h.optional()}),w=i.object({method:i.string(),params:y.loose().optional()}),b=i.looseObject({_meta:h.optional()}),v=i.union([i.string(),i.number().int()]),k=i.object({jsonrpc:i.literal("2.0"),id:v,...g.shape}).strict(),S=i.object({jsonrpc:i.literal("2.0"),...w.shape}).strict(),E=i.object({jsonrpc:i.literal("2.0"),id:v,result:b}).strict();(t=r||(r={}))[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired";let I=i.object({jsonrpc:i.literal("2.0"),id:v.optional(),error:i.object({code:i.number().int(),message:i.string(),data:i.unknown().optional()})}).strict(),x=i.union([k,S,E,I]);i.union([E,I]);let A=b.strict(),_=y.extend({requestId:v.optional(),reason:i.string().optional()}),C=w.extend({method:i.literal("notifications/cancelled"),params:_}),R=i.object({src:i.string(),mimeType:i.string().optional(),sizes:i.array(i.string()).optional(),theme:i.enum(["light","dark"]).optional()}),T=i.object({icons:i.array(R).optional()}),D=i.object({name:i.string(),title:i.string().optional()}),N=D.extend({...D.shape,...T.shape,version:i.string(),websiteUrl:i.string().optional(),description:i.string().optional()}),O=i.intersection(i.object({applyDefaults:i.boolean().optional()}),i.record(i.string(),i.unknown())),P=i.preprocess(e=>e&&"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length?{form:{}}:e,i.intersection(i.object({form:O.optional(),url:l.optional()}),i.record(i.string(),i.unknown()).optional())),$=i.looseObject({list:l.optional(),cancel:l.optional(),requests:i.looseObject({sampling:i.looseObject({createMessage:l.optional()}).optional(),elicitation:i.looseObject({create:l.optional()}).optional()}).optional()}),U=i.looseObject({list:l.optional(),cancel:l.optional(),requests:i.looseObject({tools:i.looseObject({call:l.optional()}).optional()}).optional()}),B=i.object({experimental:i.record(i.string(),l).optional(),sampling:i.object({context:l.optional(),tools:l.optional()}).optional(),elicitation:P.optional(),roots:i.object({listChanged:i.boolean().optional()}).optional(),tasks:$.optional(),extensions:i.record(i.string(),l).optional()}),j=m.extend({protocolVersion:i.string(),capabilities:B,clientInfo:N}),L=g.extend({method:i.literal("initialize"),params:j}),q=i.object({experimental:i.record(i.string(),l).optional(),logging:l.optional(),completions:l.optional(),prompts:i.object({listChanged:i.boolean().optional()}).optional(),resources:i.object({subscribe:i.boolean().optional(),listChanged:i.boolean().optional()}).optional(),tools:i.object({listChanged:i.boolean().optional()}).optional(),tasks:U.optional(),extensions:i.record(i.string(),l).optional()}),M=b.extend({protocolVersion:i.string(),capabilities:q,serverInfo:N,instructions:i.string().optional()}),F=w.extend({method:i.literal("notifications/initialized"),params:y.optional()}),K=g.extend({method:i.literal("ping"),params:m.optional()}),V=i.object({progress:i.number(),total:i.optional(i.number()),message:i.optional(i.string())}),G=i.object({...y.shape,...V.shape,progressToken:u}),H=w.extend({method:i.literal("notifications/progress"),params:G}),W=m.extend({cursor:c.optional()}),J=g.extend({params:W.optional()}),z=b.extend({nextCursor:c.optional()}),Z=i.enum(["working","input_required","completed","failed","cancelled"]),Y=i.object({taskId:i.string(),status:Z,ttl:i.union([i.number(),i.null()]),createdAt:i.string(),lastUpdatedAt:i.string(),pollInterval:i.optional(i.number()),statusMessage:i.optional(i.string())}),Q=b.extend({task:Y}),X=y.merge(Y),ee=w.extend({method:i.literal("notifications/tasks/status"),params:X}),et=g.extend({method:i.literal("tasks/get"),params:m.extend({taskId:i.string()})}),er=b.merge(Y),ei=g.extend({method:i.literal("tasks/result"),params:m.extend({taskId:i.string()})});b.loose();let ea=J.extend({method:i.literal("tasks/list")}),en=z.extend({tasks:i.array(Y)}),es=g.extend({method:i.literal("tasks/cancel"),params:m.extend({taskId:i.string()})}),eo=b.merge(Y),el=i.object({uri:i.string(),mimeType:i.optional(i.string()),_meta:i.record(i.string(),i.unknown()).optional()}),eu=el.extend({text:i.string()}),ec=i.string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),ed=el.extend({blob:ec}),ep=i.enum(["user","assistant"]),eh=i.object({audience:i.array(ep).optional(),priority:i.number().min(0).max(1).optional(),lastModified:a.datetime({offset:!0}).optional()}),em=i.object({...D.shape,...T.shape,uri:i.string(),description:i.optional(i.string()),mimeType:i.optional(i.string()),size:i.optional(i.number()),annotations:eh.optional(),_meta:i.optional(i.looseObject({}))}),ef=i.object({...D.shape,...T.shape,uriTemplate:i.string(),description:i.optional(i.string()),mimeType:i.optional(i.string()),annotations:eh.optional(),_meta:i.optional(i.looseObject({}))}),eg=J.extend({method:i.literal("resources/list")}),ey=z.extend({resources:i.array(em)}),ew=J.extend({method:i.literal("resources/templates/list")}),eb=z.extend({resourceTemplates:i.array(ef)}),ev=m.extend({uri:i.string()}),ek=g.extend({method:i.literal("resources/read"),params:ev}),eS=b.extend({contents:i.array(i.union([eu,ed]))}),eE=w.extend({method:i.literal("notifications/resources/list_changed"),params:y.optional()}),eI=g.extend({method:i.literal("resources/subscribe"),params:ev}),ex=g.extend({method:i.literal("resources/unsubscribe"),params:ev}),eA=y.extend({uri:i.string()}),e_=w.extend({method:i.literal("notifications/resources/updated"),params:eA}),eC=i.object({name:i.string(),description:i.optional(i.string()),required:i.optional(i.boolean())}),eR=i.object({...D.shape,...T.shape,description:i.optional(i.string()),arguments:i.optional(i.array(eC)),_meta:i.optional(i.looseObject({}))}),eT=J.extend({method:i.literal("prompts/list")}),eD=z.extend({prompts:i.array(eR)}),eN=m.extend({name:i.string(),arguments:i.record(i.string(),i.string()).optional()}),eO=g.extend({method:i.literal("prompts/get"),params:eN}),eP=i.object({type:i.literal("text"),text:i.string(),annotations:eh.optional(),_meta:i.record(i.string(),i.unknown()).optional()}),e$=i.object({type:i.literal("image"),data:ec,mimeType:i.string(),annotations:eh.optional(),_meta:i.record(i.string(),i.unknown()).optional()}),eU=i.object({type:i.literal("audio"),data:ec,mimeType:i.string(),annotations:eh.optional(),_meta:i.record(i.string(),i.unknown()).optional()}),eB=i.object({type:i.literal("tool_use"),name:i.string(),id:i.string(),input:i.record(i.string(),i.unknown()),_meta:i.record(i.string(),i.unknown()).optional()}),ej=i.object({type:i.literal("resource"),resource:i.union([eu,ed]),annotations:eh.optional(),_meta:i.record(i.string(),i.unknown()).optional()}),eL=em.extend({type:i.literal("resource_link")}),eq=i.union([eP,e$,eU,eL,ej]),eM=i.object({role:ep,content:eq}),eF=b.extend({description:i.string().optional(),messages:i.array(eM)}),eK=w.extend({method:i.literal("notifications/prompts/list_changed"),params:y.optional()}),eV=i.object({title:i.string().optional(),readOnlyHint:i.boolean().optional(),destructiveHint:i.boolean().optional(),idempotentHint:i.boolean().optional(),openWorldHint:i.boolean().optional()}),eG=i.object({taskSupport:i.enum(["required","optional","forbidden"]).optional()}),eH=i.object({...D.shape,...T.shape,description:i.string().optional(),inputSchema:i.object({type:i.literal("object"),properties:i.record(i.string(),l).optional(),required:i.array(i.string()).optional()}).catchall(i.unknown()),outputSchema:i.object({type:i.literal("object"),properties:i.record(i.string(),l).optional(),required:i.array(i.string()).optional()}).catchall(i.unknown()).optional(),annotations:eV.optional(),execution:eG.optional(),_meta:i.record(i.string(),i.unknown()).optional()}),eW=J.extend({method:i.literal("tools/list")}),eJ=z.extend({tools:i.array(eH)}),ez=b.extend({content:i.array(eq).default([]),structuredContent:i.record(i.string(),i.unknown()).optional(),isError:i.boolean().optional()});ez.or(b.extend({toolResult:i.unknown()}));let eZ=f.extend({name:i.string(),arguments:i.record(i.string(),i.unknown()).optional()}),eY=g.extend({method:i.literal("tools/call"),params:eZ}),eQ=w.extend({method:i.literal("notifications/tools/list_changed"),params:y.optional()}),eX=i.object({autoRefresh:i.boolean().default(!0),debounceMs:i.number().int().nonnegative().default(300)}),e0=i.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),e1=m.extend({level:e0}),e2=g.extend({method:i.literal("logging/setLevel"),params:e1}),e3=y.extend({level:e0,logger:i.string().optional(),data:i.unknown()}),e4=w.extend({method:i.literal("notifications/message"),params:e3}),e6=i.object({name:i.string().optional()}),e8=i.object({hints:i.array(e6).optional(),costPriority:i.number().min(0).max(1).optional(),speedPriority:i.number().min(0).max(1).optional(),intelligencePriority:i.number().min(0).max(1).optional()}),e5=i.object({mode:i.enum(["auto","required","none"]).optional()}),e9=i.object({type:i.literal("tool_result"),toolUseId:i.string().describe("The unique identifier for the corresponding tool call."),content:i.array(eq).default([]),structuredContent:i.object({}).loose().optional(),isError:i.boolean().optional(),_meta:i.record(i.string(),i.unknown()).optional()}),e7=i.discriminatedUnion("type",[eP,e$,eU]),te=i.discriminatedUnion("type",[eP,e$,eU,eB,e9]),tt=i.object({role:ep,content:i.union([te,i.array(te)]),_meta:i.record(i.string(),i.unknown()).optional()}),tr=f.extend({messages:i.array(tt),modelPreferences:e8.optional(),systemPrompt:i.string().optional(),includeContext:i.enum(["none","thisServer","allServers"]).optional(),temperature:i.number().optional(),maxTokens:i.number().int(),stopSequences:i.array(i.string()).optional(),metadata:l.optional(),tools:i.array(eH).optional(),toolChoice:e5.optional()}),ti=g.extend({method:i.literal("sampling/createMessage"),params:tr}),ta=b.extend({model:i.string(),stopReason:i.optional(i.enum(["endTurn","stopSequence","maxTokens"]).or(i.string())),role:ep,content:e7}),tn=b.extend({model:i.string(),stopReason:i.optional(i.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(i.string())),role:ep,content:i.union([te,i.array(te)])}),ts=i.object({type:i.literal("boolean"),title:i.string().optional(),description:i.string().optional(),default:i.boolean().optional()}),to=i.object({type:i.literal("string"),title:i.string().optional(),description:i.string().optional(),minLength:i.number().optional(),maxLength:i.number().optional(),format:i.enum(["email","uri","date","date-time"]).optional(),default:i.string().optional()}),tl=i.object({type:i.enum(["number","integer"]),title:i.string().optional(),description:i.string().optional(),minimum:i.number().optional(),maximum:i.number().optional(),default:i.number().optional()}),tu=i.object({type:i.literal("string"),title:i.string().optional(),description:i.string().optional(),enum:i.array(i.string()),default:i.string().optional()}),tc=i.object({type:i.literal("string"),title:i.string().optional(),description:i.string().optional(),oneOf:i.array(i.object({const:i.string(),title:i.string()})),default:i.string().optional()}),td=i.object({type:i.literal("string"),title:i.string().optional(),description:i.string().optional(),enum:i.array(i.string()),enumNames:i.array(i.string()).optional(),default:i.string().optional()}),tp=i.union([tu,tc]),th=i.object({type:i.literal("array"),title:i.string().optional(),description:i.string().optional(),minItems:i.number().optional(),maxItems:i.number().optional(),items:i.object({type:i.literal("string"),enum:i.array(i.string())}),default:i.array(i.string()).optional()}),tm=i.object({type:i.literal("array"),title:i.string().optional(),description:i.string().optional(),minItems:i.number().optional(),maxItems:i.number().optional(),items:i.object({anyOf:i.array(i.object({const:i.string(),title:i.string()}))}),default:i.array(i.string()).optional()}),tf=i.union([th,tm]),tg=i.union([td,tp,tf]),ty=i.union([tg,ts,to,tl]),tw=f.extend({mode:i.literal("form").optional(),message:i.string(),requestedSchema:i.object({type:i.literal("object"),properties:i.record(i.string(),ty),required:i.array(i.string()).optional()})}),tb=f.extend({mode:i.literal("url"),message:i.string(),elicitationId:i.string(),url:i.string().url()}),tv=i.union([tw,tb]),tk=g.extend({method:i.literal("elicitation/create"),params:tv}),tS=y.extend({elicitationId:i.string()}),tE=w.extend({method:i.literal("notifications/elicitation/complete"),params:tS}),tI=b.extend({action:i.enum(["accept","decline","cancel"]),content:i.preprocess(e=>null===e?void 0:e,i.record(i.string(),i.union([i.string(),i.number(),i.boolean(),i.array(i.string())])).optional())}),tx=i.object({type:i.literal("ref/resource"),uri:i.string()}),tA=i.object({type:i.literal("ref/prompt"),name:i.string()}),t_=m.extend({ref:i.union([tA,tx]),argument:i.object({name:i.string(),value:i.string()}),context:i.object({arguments:i.record(i.string(),i.string()).optional()}).optional()}),tC=g.extend({method:i.literal("completion/complete"),params:t_}),tR=b.extend({completion:i.looseObject({values:i.array(i.string()).max(100),total:i.optional(i.number().int()),hasMore:i.optional(i.boolean())})}),tT=i.object({uri:i.string().startsWith("file://"),name:i.string().optional(),_meta:i.record(i.string(),i.unknown()).optional()}),tD=g.extend({method:i.literal("roots/list"),params:m.optional()}),tN=b.extend({roots:i.array(tT)}),tO=w.extend({method:i.literal("notifications/roots/list_changed"),params:y.optional()});i.union([K,L,tC,e2,eO,eT,eg,ew,ek,eI,ex,eY,eW,et,ei,ea,es]),i.union([C,H,F,tO,ee]),i.union([A,ta,tn,tI,tN,er,en,Q]),i.union([K,ti,tk,tD,et,ei,ea,es]),i.union([C,H,e4,e_,eE,eQ,eK,ee,tE]),i.union([A,M,tR,eF,eD,ey,eb,eS,ez,eJ,er,en,Q]);class tP extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,t,i){return e===r.UrlElicitationRequired&&i&&i.elicitations?new t$(i.elicitations,t):new tP(e,t,i)}}class t$ extends tP{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(r.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}e.s(["CallToolRequestSchema",0,eY,"CallToolResultSchema",0,ez,"CancelTaskRequestSchema",0,es,"CancelTaskResultSchema",0,eo,"CancelledNotificationSchema",0,C,"CompleteRequestSchema",0,tC,"CompleteResultSchema",0,tR,"CreateMessageRequestSchema",0,ti,"CreateMessageResultSchema",0,ta,"CreateMessageResultWithToolsSchema",0,tn,"CreateTaskResultSchema",0,Q,"DEFAULT_NEGOTIATED_PROTOCOL_VERSION",0,"2025-03-26","ElicitRequestSchema",0,tk,"ElicitResultSchema",0,tI,"EmptyResultSchema",0,A,"ErrorCode",0,r,"GetPromptRequestSchema",0,eO,"GetPromptResultSchema",0,eF,"GetTaskPayloadRequestSchema",0,ei,"GetTaskRequestSchema",0,et,"GetTaskResultSchema",0,er,"InitializeRequestSchema",0,L,"InitializeResultSchema",0,M,"InitializedNotificationSchema",0,F,"JSONRPCMessageSchema",0,x,"LATEST_PROTOCOL_VERSION",0,n,"ListChangedOptionsBaseSchema",0,eX,"ListPromptsRequestSchema",0,eT,"ListPromptsResultSchema",0,eD,"ListResourceTemplatesRequestSchema",0,ew,"ListResourceTemplatesResultSchema",0,eb,"ListResourcesRequestSchema",0,eg,"ListResourcesResultSchema",0,ey,"ListRootsResultSchema",0,tN,"ListTasksRequestSchema",0,ea,"ListTasksResultSchema",0,en,"ListToolsRequestSchema",0,eW,"ListToolsResultSchema",0,eJ,"LoggingLevelSchema",0,e0,"McpError",0,tP,"PingRequestSchema",0,K,"ProgressNotificationSchema",0,H,"PromptListChangedNotificationSchema",0,eK,"RELATED_TASK_META_KEY",0,o,"ReadResourceRequestSchema",0,ek,"ReadResourceResultSchema",0,eS,"ResourceListChangedNotificationSchema",0,eE,"SUPPORTED_PROTOCOL_VERSIONS",0,s,"SetLevelRequestSchema",0,e2,"TaskStatusNotificationSchema",0,ee,"ToolListChangedNotificationSchema",0,eQ,"assertCompleteRequestPrompt",0,function(e){if("ref/prompt"!==e.params.ref.type)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)},"assertCompleteRequestResourceTemplate",0,function(e){if("ref/resource"!==e.params.ref.type)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)},"isInitializeRequest",0,e=>L.safeParse(e).success,"isInitializedNotification",0,e=>F.safeParse(e).success,"isJSONRPCErrorResponse",0,e=>I.safeParse(e).success,"isJSONRPCNotification",0,e=>S.safeParse(e).success,"isJSONRPCRequest",0,e=>k.safeParse(e).success,"isJSONRPCResultResponse",0,e=>E.safeParse(e).success,"isTaskAugmentedRequestParams",0,e=>f.safeParse(e).success],556690)},917397,(e,t,r)=>{!function(t,r){"use strict";function i(e,t){if(!e)throw Error(t||"Assertion failed")}function a(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}function n(e,t,r){if(n.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&(("le"===t||"be"===t)&&(r=t,t=10),this._init(e||0,t||10,r||"be"))}t.exports=n,n.BN=n,n.wordSize=26;try{u=e.r(500874).Buffer}catch(e){}function s(e,t){var r=e.charCodeAt(t);return r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:r-48&15}function o(e,t,r){var i=s(e,r);return r-1>=t&&(i|=s(e,r-1)<<4),i}function l(e,t,r,i){for(var a=0,n=Math.min(e.length,r),s=t;s<n;s++){var o=e.charCodeAt(s)-48;a*=i,o>=49?a+=o-49+10:o>=17?a+=o-17+10:a+=o}return a}n.isBN=function(e){return e instanceof n||null!==e&&"object"==typeof e&&e.constructor.wordSize===n.wordSize&&Array.isArray(e.words)},n.max=function(e,t){return e.cmp(t)>0?e:t},n.min=function(e,t){return 0>e.cmp(t)?e:t},n.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),i(t===(0|t)&&t>=2&&t<=36);var a=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(a++,this.negative=1),a<e.length&&(16===t?this._parseHex(e,a,r):(this._parseBase(e,t,a),"le"===r&&this._initArray(this.toArray(),t,r)))},n.prototype._initNumber=function(e,t,r){e<0&&(this.negative=1,e=-e),e<0x4000000?(this.words=[0x3ffffff&e],this.length=1):e<0x10000000000000?(this.words=[0x3ffffff&e,e/0x4000000&0x3ffffff],this.length=2):(i(e<0x20000000000000),this.words=[0x3ffffff&e,e/0x4000000&0x3ffffff,1],this.length=3),"le"===r&&this._initArray(this.toArray(),t,r)},n.prototype._initArray=function(e,t,r){if(i("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=Array(this.length);for(var a,n,s=0;s<this.length;s++)this.words[s]=0;var o=0;if("be"===r)for(s=e.length-1,a=0;s>=0;s-=3)n=e[s]|e[s-1]<<8|e[s-2]<<16,this.words[a]|=n<<o&0x3ffffff,this.words[a+1]=n>>>26-o&0x3ffffff,(o+=24)>=26&&(o-=26,a++);else if("le"===r)for(s=0,a=0;s<e.length;s+=3)n=e[s]|e[s+1]<<8|e[s+2]<<16,this.words[a]|=n<<o&0x3ffffff,this.words[a+1]=n>>>26-o&0x3ffffff,(o+=24)>=26&&(o-=26,a++);return this.strip()},n.prototype._parseHex=function(e,t,r){this.length=Math.ceil((e.length-t)/6),this.words=Array(this.length);for(var i,a=0;a<this.length;a++)this.words[a]=0;var n=0,s=0;if("be"===r)for(a=e.length-1;a>=t;a-=2)i=o(e,t,a)<<n,this.words[s]|=0x3ffffff&i,n>=18?(n-=18,s+=1,this.words[s]|=i>>>26):n+=8;else for(a=(e.length-t)%2==0?t+1:t;a<e.length;a+=2)i=o(e,t,a)<<n,this.words[s]|=0x3ffffff&i,n>=18?(n-=18,s+=1,this.words[s]|=i>>>26):n+=8;this.strip()},n.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var i=0,a=1;a<=0x3ffffff;a*=t)i++;i--,a=a/t|0;for(var n=e.length-r,s=n%i,o=Math.min(n,n-s)+r,u=0,c=r;c<o;c+=i)u=l(e,c,c+i,t),this.imuln(a),this.words[0]+u<0x4000000?this.words[0]+=u:this._iaddn(u);if(0!==s){var d=1;for(u=l(e,c,e.length,t),c=0;c<s;c++)d*=t;this.imuln(d),this.words[0]+u<0x4000000?this.words[0]+=u:this._iaddn(u)}this.strip()},n.prototype.copy=function(e){e.words=Array(this.length);for(var t=0;t<this.length;t++)e.words[t]=this.words[t];e.length=this.length,e.negative=this.negative,e.red=this.red},n.prototype.clone=function(){var e=new n(null);return this.copy(e),e},n.prototype._expand=function(e){for(;this.length<e;)this.words[this.length++]=0;return this},n.prototype.strip=function(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this._normSign()},n.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},n.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var u,c=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],d=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],p=[0,0,0x2000000,0x290d741,0x1000000,0x2e90edd,0x39aa400,0x267bf47,0x1000000,0x290d741,1e7,0x12959c3,0x222c000,0x3bd7765,7529536,0xadcea1,0x1000000,0x1704f61,0x206fc40,0x2cddcf9,64e6,4084101,5153632,6436343,7962624,9765625,0xb54ba0,0xdaf26b,0x1069c00,0x138f9ad,243e5,0x1b4d89f,0x2000000,0x25528a1,0x2b54a20,0x3216b93,0x39aa400];function h(e,t,r){r.negative=t.negative^e.negative;var i=e.length+t.length|0;r.length=i,i=i-1|0;var a=0|e.words[0],n=0|t.words[0],s=a*n,o=0x3ffffff&s,l=s/0x4000000|0;r.words[0]=o;for(var u=1;u<i;u++){for(var c=l>>>26,d=0x3ffffff&l,p=Math.min(u,t.length-1),h=Math.max(0,u-e.length+1);h<=p;h++){var m=u-h|0;c+=(s=(a=0|e.words[m])*(n=0|t.words[h])+d)/0x4000000|0,d=0x3ffffff&s}r.words[u]=0|d,l=0|c}return 0!==l?r.words[u]=0|l:r.length--,r.strip()}n.prototype.toString=function(e,t){if(t=0|t||1,16===(e=e||10)||"hex"===e){for(var r="",a=0,n=0,s=0;s<this.length;s++){var o=this.words[s],l=((o<<a|n)&0xffffff).toString(16);n=o>>>24-a&0xffffff,(a+=2)>=26&&(a-=26,s--),r=0!==n||s!==this.length-1?c[6-l.length]+l+r:l+r}for(0!==n&&(r=n.toString(16)+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var u=d[e],h=p[e];r="";var m=this.clone();for(m.negative=0;!m.isZero();){var f=m.modn(h).toString(e);r=(m=m.idivn(h)).isZero()?f+r:c[u-f.length]+f+r}for(this.isZero()&&(r="0"+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}i(!1,"Base should be between 2 and 36")},n.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=0x4000000*this.words[1]:3===this.length&&1===this.words[2]?e+=0x10000000000000+0x4000000*this.words[1]:this.length>2&&i(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},n.prototype.toJSON=function(){return this.toString(16)},n.prototype.toBuffer=function(e,t){return i(void 0!==u),this.toArrayLike(u,e,t)},n.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},n.prototype.toArrayLike=function(e,t,r){var a,n,s=this.byteLength(),o=r||Math.max(1,s);i(s<=o,"byte array longer than desired length"),i(o>0,"Requested array length <= 0"),this.strip();var l=new e(o),u=this.clone();if("le"===t){for(n=0;!u.isZero();n++)a=u.andln(255),u.iushrn(8),l[n]=a;for(;n<o;n++)l[n]=0}else{for(n=0;n<o-s;n++)l[n]=0;for(n=0;!u.isZero();n++)a=u.andln(255),u.iushrn(8),l[o-n-1]=a}return l},Math.clz32?n.prototype._countBits=function(e){return 32-Math.clz32(e)}:n.prototype._countBits=function(e){var t=e,r=0;return t>=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},n.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return(8191&t)==0&&(r+=13,t>>>=13),(127&t)==0&&(r+=7,t>>>=7),(15&t)==0&&(r+=4,t>>>=4),(3&t)==0&&(r+=2,t>>>=2),(1&t)==0&&r++,r},n.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return(this.length-1)*26+t},n.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;t<this.length;t++){var r=this._zeroBits(this.words[t]);if(e+=r,26!==r)break}return e},n.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},n.prototype.toTwos=function(e){return 0!==this.negative?this.abs().inotn(e).iaddn(1):this.clone()},n.prototype.fromTwos=function(e){return this.testn(e-1)?this.notn(e).iaddn(1).ineg():this.clone()},n.prototype.isNeg=function(){return 0!==this.negative},n.prototype.neg=function(){return this.clone().ineg()},n.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},n.prototype.iuor=function(e){for(;this.length<e.length;)this.words[this.length++]=0;for(var t=0;t<e.length;t++)this.words[t]=this.words[t]|e.words[t];return this.strip()},n.prototype.ior=function(e){return i((this.negative|e.negative)==0),this.iuor(e)},n.prototype.or=function(e){return this.length>e.length?this.clone().ior(e):e.clone().ior(this)},n.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},n.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;r<t.length;r++)this.words[r]=this.words[r]&e.words[r];return this.length=t.length,this.strip()},n.prototype.iand=function(e){return i((this.negative|e.negative)==0),this.iuand(e)},n.prototype.and=function(e){return this.length>e.length?this.clone().iand(e):e.clone().iand(this)},n.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},n.prototype.iuxor=function(e){this.length>e.length?(t=this,r=e):(t=e,r=this);for(var t,r,i=0;i<r.length;i++)this.words[i]=t.words[i]^r.words[i];if(this!==t)for(;i<t.length;i++)this.words[i]=t.words[i];return this.length=t.length,this.strip()},n.prototype.ixor=function(e){return i((this.negative|e.negative)==0),this.iuxor(e)},n.prototype.xor=function(e){return this.length>e.length?this.clone().ixor(e):e.clone().ixor(this)},n.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},n.prototype.inotn=function(e){i("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var a=0;a<t;a++)this.words[a]=0x3ffffff&~this.words[a];for(r>0&&(this.words[a]=~this.words[a]&0x3ffffff>>26-r,a++);a<this.length;a++)this.words[a]=0;return this.strip()},n.prototype.notn=function(e){return this.clone().inotn(e)},n.prototype.setn=function(e,t){i("number"==typeof e&&e>=0);var r=e/26|0,a=e%26;return this._expand(r+1),t?this.words[r]=this.words[r]|1<<a:this.words[r]=this.words[r]&~(1<<a),this.strip()},n.prototype.iadd=function(e){if(0!==this.negative&&0===e.negative)return this.negative=0,t=this.isub(e),this.negative^=1,this._normSign();if(0===this.negative&&0!==e.negative)return e.negative=0,t=this.isub(e),e.negative=1,t._normSign();this.length>e.length?(r=this,i=e):(r=e,i=this);for(var t,r,i,a=0,n=0;n<i.length;n++)t=(0|r.words[n])+(0|i.words[n])+a,this.words[n]=0x3ffffff&t,a=t>>>26;for(;0!==a&&n<r.length;n++)t=(0|r.words[n])+a,this.words[n]=0x3ffffff&t,a=t>>>26;if(this.length=r.length,0!==a)this.words[this.length]=a,this.length++;else if(r!==this)for(;n<r.length;n++)this.words[n]=r.words[n];return this},n.prototype.add=function(e){var t;return 0!==e.negative&&0===this.negative?(e.negative=0,t=this.sub(e),e.negative^=1,t):0===e.negative&&0!==this.negative?(this.negative=0,t=e.sub(this),this.negative=1,t):this.length>e.length?this.clone().iadd(e):e.clone().iadd(this)},n.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t,r,i=this.iadd(e);return e.negative=1,i._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var a=this.cmp(e);if(0===a)return this.negative=0,this.length=1,this.words[0]=0,this;a>0?(t=this,r=e):(t=e,r=this);for(var n=0,s=0;s<r.length;s++)n=(i=(0|t.words[s])-(0|r.words[s])+n)>>26,this.words[s]=0x3ffffff&i;for(;0!==n&&s<t.length;s++)n=(i=(0|t.words[s])+n)>>26,this.words[s]=0x3ffffff&i;if(0===n&&s<t.length&&t!==this)for(;s<t.length;s++)this.words[s]=t.words[s];return this.length=Math.max(this.length,s),t!==this&&(this.negative=1),this.strip()},n.prototype.sub=function(e){return this.clone().isub(e)};var m=function(e,t,r){var i,a,n,s=e.words,o=t.words,l=r.words,u=0,c=0|s[0],d=8191&c,p=c>>>13,h=0|s[1],m=8191&h,f=h>>>13,g=0|s[2],y=8191&g,w=g>>>13,b=0|s[3],v=8191&b,k=b>>>13,S=0|s[4],E=8191&S,I=S>>>13,x=0|s[5],A=8191&x,_=x>>>13,C=0|s[6],R=8191&C,T=C>>>13,D=0|s[7],N=8191&D,O=D>>>13,P=0|s[8],$=8191&P,U=P>>>13,B=0|s[9],j=8191&B,L=B>>>13,q=0|o[0],M=8191&q,F=q>>>13,K=0|o[1],V=8191&K,G=K>>>13,H=0|o[2],W=8191&H,J=H>>>13,z=0|o[3],Z=8191&z,Y=z>>>13,Q=0|o[4],X=8191&Q,ee=Q>>>13,et=0|o[5],er=8191&et,ei=et>>>13,ea=0|o[6],en=8191&ea,es=ea>>>13,eo=0|o[7],el=8191&eo,eu=eo>>>13,ec=0|o[8],ed=8191&ec,ep=ec>>>13,eh=0|o[9],em=8191&eh,ef=eh>>>13;r.negative=e.negative^t.negative,r.length=19,i=Math.imul(d,M);var eg=(u+i|0)+((8191&(a=(a=Math.imul(d,F))+Math.imul(p,M)|0))<<13)|0;u=((n=Math.imul(p,F))+(a>>>13)|0)+(eg>>>26)|0,eg&=0x3ffffff,i=Math.imul(m,M),a=(a=Math.imul(m,F))+Math.imul(f,M)|0,n=Math.imul(f,F),i=i+Math.imul(d,V)|0;var ey=(u+i|0)+((8191&(a=(a=a+Math.imul(d,G)|0)+Math.imul(p,V)|0))<<13)|0;u=((n=n+Math.imul(p,G)|0)+(a>>>13)|0)+(ey>>>26)|0,ey&=0x3ffffff,i=Math.imul(y,M),a=(a=Math.imul(y,F))+Math.imul(w,M)|0,n=Math.imul(w,F),i=i+Math.imul(m,V)|0,a=(a=a+Math.imul(m,G)|0)+Math.imul(f,V)|0,n=n+Math.imul(f,G)|0,i=i+Math.imul(d,W)|0;var ew=(u+i|0)+((8191&(a=(a=a+Math.imul(d,J)|0)+Math.imul(p,W)|0))<<13)|0;u=((n=n+Math.imul(p,J)|0)+(a>>>13)|0)+(ew>>>26)|0,ew&=0x3ffffff,i=Math.imul(v,M),a=(a=Math.imul(v,F))+Math.imul(k,M)|0,n=Math.imul(k,F),i=i+Math.imul(y,V)|0,a=(a=a+Math.imul(y,G)|0)+Math.imul(w,V)|0,n=n+Math.imul(w,G)|0,i=i+Math.imul(m,W)|0,a=(a=a+Math.imul(m,J)|0)+Math.imul(f,W)|0,n=n+Math.imul(f,J)|0,i=i+Math.imul(d,Z)|0;var eb=(u+i|0)+((8191&(a=(a=a+Math.imul(d,Y)|0)+Math.imul(p,Z)|0))<<13)|0;u=((n=n+Math.imul(p,Y)|0)+(a>>>13)|0)+(eb>>>26)|0,eb&=0x3ffffff,i=Math.imul(E,M),a=(a=Math.imul(E,F))+Math.imul(I,M)|0,n=Math.imul(I,F),i=i+Math.imul(v,V)|0,a=(a=a+Math.imul(v,G)|0)+Math.imul(k,V)|0,n=n+Math.imul(k,G)|0,i=i+Math.imul(y,W)|0,a=(a=a+Math.imul(y,J)|0)+Math.imul(w,W)|0,n=n+Math.imul(w,J)|0,i=i+Math.imul(m,Z)|0,a=(a=a+Math.imul(m,Y)|0)+Math.imul(f,Z)|0,n=n+Math.imul(f,Y)|0,i=i+Math.imul(d,X)|0;var ev=(u+i|0)+((8191&(a=(a=a+Math.imul(d,ee)|0)+Math.imul(p,X)|0))<<13)|0;u=((n=n+Math.imul(p,ee)|0)+(a>>>13)|0)+(ev>>>26)|0,ev&=0x3ffffff,i=Math.imul(A,M),a=(a=Math.imul(A,F))+Math.imul(_,M)|0,n=Math.imul(_,F),i=i+Math.imul(E,V)|0,a=(a=a+Math.imul(E,G)|0)+Math.imul(I,V)|0,n=n+Math.imul(I,G)|0,i=i+Math.imul(v,W)|0,a=(a=a+Math.imul(v,J)|0)+Math.imul(k,W)|0,n=n+Math.imul(k,J)|0,i=i+Math.imul(y,Z)|0,a=(a=a+Math.imul(y,Y)|0)+Math.imul(w,Z)|0,n=n+Math.imul(w,Y)|0,i=i+Math.imul(m,X)|0,a=(a=a+Math.imul(m,ee)|0)+Math.imul(f,X)|0,n=n+Math.imul(f,ee)|0,i=i+Math.imul(d,er)|0;var ek=(u+i|0)+((8191&(a=(a=a+Math.imul(d,ei)|0)+Math.imul(p,er)|0))<<13)|0;u=((n=n+Math.imul(p,ei)|0)+(a>>>13)|0)+(ek>>>26)|0,ek&=0x3ffffff,i=Math.imul(R,M),a=(a=Math.imul(R,F))+Math.imul(T,M)|0,n=Math.imul(T,F),i=i+Math.imul(A,V)|0,a=(a=a+Math.imul(A,G)|0)+Math.imul(_,V)|0,n=n+Math.imul(_,G)|0,i=i+Math.imul(E,W)|0,a=(a=a+Math.imul(E,J)|0)+Math.imul(I,W)|0,n=n+Math.imul(I,J)|0,i=i+Math.imul(v,Z)|0,a=(a=a+Math.imul(v,Y)|0)+Math.imul(k,Z)|0,n=n+Math.imul(k,Y)|0,i=i+Math.imul(y,X)|0,a=(a=a+Math.imul(y,ee)|0)+Math.imul(w,X)|0,n=n+Math.imul(w,ee)|0,i=i+Math.imul(m,er)|0,a=(a=a+Math.imul(m,ei)|0)+Math.imul(f,er)|0,n=n+Math.imul(f,ei)|0,i=i+Math.imul(d,en)|0;var eS=(u+i|0)+((8191&(a=(a=a+Math.imul(d,es)|0)+Math.imul(p,en)|0))<<13)|0;u=((n=n+Math.imul(p,es)|0)+(a>>>13)|0)+(eS>>>26)|0,eS&=0x3ffffff,i=Math.imul(N,M),a=(a=Math.imul(N,F))+Math.imul(O,M)|0,n=Math.imul(O,F),i=i+Math.imul(R,V)|0,a=(a=a+Math.imul(R,G)|0)+Math.imul(T,V)|0,n=n+Math.imul(T,G)|0,i=i+Math.imul(A,W)|0,a=(a=a+Math.imul(A,J)|0)+Math.imul(_,W)|0,n=n+Math.imul(_,J)|0,i=i+Math.imul(E,Z)|0,a=(a=a+Math.imul(E,Y)|0)+Math.imul(I,Z)|0,n=n+Math.imul(I,Y)|0,i=i+Math.imul(v,X)|0,a=(a=a+Math.imul(v,ee)|0)+Math.imul(k,X)|0,n=n+Math.imul(k,ee)|0,i=i+Math.imul(y,er)|0,a=(a=a+Math.imul(y,ei)|0)+Math.imul(w,er)|0,n=n+Math.imul(w,ei)|0,i=i+Math.imul(m,en)|0,a=(a=a+Math.imul(m,es)|0)+Math.imul(f,en)|0,n=n+Math.imul(f,es)|0,i=i+Math.imul(d,el)|0;var eE=(u+i|0)+((8191&(a=(a=a+Math.imul(d,eu)|0)+Math.imul(p,el)|0))<<13)|0;u=((n=n+Math.imul(p,eu)|0)+(a>>>13)|0)+(eE>>>26)|0,eE&=0x3ffffff,i=Math.imul($,M),a=(a=Math.imul($,F))+Math.imul(U,M)|0,n=Math.imul(U,F),i=i+Math.imul(N,V)|0,a=(a=a+Math.imul(N,G)|0)+Math.imul(O,V)|0,n=n+Math.imul(O,G)|0,i=i+Math.imul(R,W)|0,a=(a=a+Math.imul(R,J)|0)+Math.imul(T,W)|0,n=n+Math.imul(T,J)|0,i=i+Math.imul(A,Z)|0,a=(a=a+Math.imul(A,Y)|0)+Math.imul(_,Z)|0,n=n+Math.imul(_,Y)|0,i=i+Math.imul(E,X)|0,a=(a=a+Math.imul(E,ee)|0)+Math.imul(I,X)|0,n=n+Math.imul(I,ee)|0,i=i+Math.imul(v,er)|0,a=(a=a+Math.imul(v,ei)|0)+Math.imul(k,er)|0,n=n+Math.imul(k,ei)|0,i=i+Math.imul(y,en)|0,a=(a=a+Math.imul(y,es)|0)+Math.imul(w,en)|0,n=n+Math.imul(w,es)|0,i=i+Math.imul(m,el)|0,a=(a=a+Math.imul(m,eu)|0)+Math.imul(f,el)|0,n=n+Math.imul(f,eu)|0,i=i+Math.imul(d,ed)|0;var eI=(u+i|0)+((8191&(a=(a=a+Math.imul(d,ep)|0)+Math.imul(p,ed)|0))<<13)|0;u=((n=n+Math.imul(p,ep)|0)+(a>>>13)|0)+(eI>>>26)|0,eI&=0x3ffffff,i=Math.imul(j,M),a=(a=Math.imul(j,F))+Math.imul(L,M)|0,n=Math.imul(L,F),i=i+Math.imul($,V)|0,a=(a=a+Math.imul($,G)|0)+Math.imul(U,V)|0,n=n+Math.imul(U,G)|0,i=i+Math.imul(N,W)|0,a=(a=a+Math.imul(N,J)|0)+Math.imul(O,W)|0,n=n+Math.imul(O,J)|0,i=i+Math.imul(R,Z)|0,a=(a=a+Math.imul(R,Y)|0)+Math.imul(T,Z)|0,n=n+Math.imul(T,Y)|0,i=i+Math.imul(A,X)|0,a=(a=a+Math.imul(A,ee)|0)+Math.imul(_,X)|0,n=n+Math.imul(_,ee)|0,i=i+Math.imul(E,er)|0,a=(a=a+Math.imul(E,ei)|0)+Math.imul(I,er)|0,n=n+Math.imul(I,ei)|0,i=i+Math.imul(v,en)|0,a=(a=a+Math.imul(v,es)|0)+Math.imul(k,en)|0,n=n+Math.imul(k,es)|0,i=i+Math.imul(y,el)|0,a=(a=a+Math.imul(y,eu)|0)+Math.imul(w,el)|0,n=n+Math.imul(w,eu)|0,i=i+Math.imul(m,ed)|0,a=(a=a+Math.imul(m,ep)|0)+Math.imul(f,ed)|0,n=n+Math.imul(f,ep)|0,i=i+Math.imul(d,em)|0;var ex=(u+i|0)+((8191&(a=(a=a+Math.imul(d,ef)|0)+Math.imul(p,em)|0))<<13)|0;u=((n=n+Math.imul(p,ef)|0)+(a>>>13)|0)+(ex>>>26)|0,ex&=0x3ffffff,i=Math.imul(j,V),a=(a=Math.imul(j,G))+Math.imul(L,V)|0,n=Math.imul(L,G),i=i+Math.imul($,W)|0,a=(a=a+Math.imul($,J)|0)+Math.imul(U,W)|0,n=n+Math.imul(U,J)|0,i=i+Math.imul(N,Z)|0,a=(a=a+Math.imul(N,Y)|0)+Math.imul(O,Z)|0,n=n+Math.imul(O,Y)|0,i=i+Math.imul(R,X)|0,a=(a=a+Math.imul(R,ee)|0)+Math.imul(T,X)|0,n=n+Math.imul(T,ee)|0,i=i+Math.imul(A,er)|0,a=(a=a+Math.imul(A,ei)|0)+Math.imul(_,er)|0,n=n+Math.imul(_,ei)|0,i=i+Math.imul(E,en)|0,a=(a=a+Math.imul(E,es)|0)+Math.imul(I,en)|0,n=n+Math.imul(I,es)|0,i=i+Math.imul(v,el)|0,a=(a=a+Math.imul(v,eu)|0)+Math.imul(k,el)|0,n=n+Math.imul(k,eu)|0,i=i+Math.imul(y,ed)|0,a=(a=a+Math.imul(y,ep)|0)+Math.imul(w,ed)|0,n=n+Math.imul(w,ep)|0,i=i+Math.imul(m,em)|0;var eA=(u+i|0)+((8191&(a=(a=a+Math.imul(m,ef)|0)+Math.imul(f,em)|0))<<13)|0;u=((n=n+Math.imul(f,ef)|0)+(a>>>13)|0)+(eA>>>26)|0,eA&=0x3ffffff,i=Math.imul(j,W),a=(a=Math.imul(j,J))+Math.imul(L,W)|0,n=Math.imul(L,J),i=i+Math.imul($,Z)|0,a=(a=a+Math.imul($,Y)|0)+Math.imul(U,Z)|0,n=n+Math.imul(U,Y)|0,i=i+Math.imul(N,X)|0,a=(a=a+Math.imul(N,ee)|0)+Math.imul(O,X)|0,n=n+Math.imul(O,ee)|0,i=i+Math.imul(R,er)|0,a=(a=a+Math.imul(R,ei)|0)+Math.imul(T,er)|0,n=n+Math.imul(T,ei)|0,i=i+Math.imul(A,en)|0,a=(a=a+Math.imul(A,es)|0)+Math.imul(_,en)|0,n=n+Math.imul(_,es)|0,i=i+Math.imul(E,el)|0,a=(a=a+Math.imul(E,eu)|0)+Math.imul(I,el)|0,n=n+Math.imul(I,eu)|0,i=i+Math.imul(v,ed)|0,a=(a=a+Math.imul(v,ep)|0)+Math.imul(k,ed)|0,n=n+Math.imul(k,ep)|0,i=i+Math.imul(y,em)|0;var e_=(u+i|0)+((8191&(a=(a=a+Math.imul(y,ef)|0)+Math.imul(w,em)|0))<<13)|0;u=((n=n+Math.imul(w,ef)|0)+(a>>>13)|0)+(e_>>>26)|0,e_&=0x3ffffff,i=Math.imul(j,Z),a=(a=Math.imul(j,Y))+Math.imul(L,Z)|0,n=Math.imul(L,Y),i=i+Math.imul($,X)|0,a=(a=a+Math.imul($,ee)|0)+Math.imul(U,X)|0,n=n+Math.imul(U,ee)|0,i=i+Math.imul(N,er)|0,a=(a=a+Math.imul(N,ei)|0)+Math.imul(O,er)|0,n=n+Math.imul(O,ei)|0,i=i+Math.imul(R,en)|0,a=(a=a+Math.imul(R,es)|0)+Math.imul(T,en)|0,n=n+Math.imul(T,es)|0,i=i+Math.imul(A,el)|0,a=(a=a+Math.imul(A,eu)|0)+Math.imul(_,el)|0,n=n+Math.imul(_,eu)|0,i=i+Math.imul(E,ed)|0,a=(a=a+Math.imul(E,ep)|0)+Math.imul(I,ed)|0,n=n+Math.imul(I,ep)|0,i=i+Math.imul(v,em)|0;var eC=(u+i|0)+((8191&(a=(a=a+Math.imul(v,ef)|0)+Math.imul(k,em)|0))<<13)|0;u=((n=n+Math.imul(k,ef)|0)+(a>>>13)|0)+(eC>>>26)|0,eC&=0x3ffffff,i=Math.imul(j,X),a=(a=Math.imul(j,ee))+Math.imul(L,X)|0,n=Math.imul(L,ee),i=i+Math.imul($,er)|0,a=(a=a+Math.imul($,ei)|0)+Math.imul(U,er)|0,n=n+Math.imul(U,ei)|0,i=i+Math.imul(N,en)|0,a=(a=a+Math.imul(N,es)|0)+Math.imul(O,en)|0,n=n+Math.imul(O,es)|0,i=i+Math.imul(R,el)|0,a=(a=a+Math.imul(R,eu)|0)+Math.imul(T,el)|0,n=n+Math.imul(T,eu)|0,i=i+Math.imul(A,ed)|0,a=(a=a+Math.imul(A,ep)|0)+Math.imul(_,ed)|0,n=n+Math.imul(_,ep)|0,i=i+Math.imul(E,em)|0;var eR=(u+i|0)+((8191&(a=(a=a+Math.imul(E,ef)|0)+Math.imul(I,em)|0))<<13)|0;u=((n=n+Math.imul(I,ef)|0)+(a>>>13)|0)+(eR>>>26)|0,eR&=0x3ffffff,i=Math.imul(j,er),a=(a=Math.imul(j,ei))+Math.imul(L,er)|0,n=Math.imul(L,ei),i=i+Math.imul($,en)|0,a=(a=a+Math.imul($,es)|0)+Math.imul(U,en)|0,n=n+Math.imul(U,es)|0,i=i+Math.imul(N,el)|0,a=(a=a+Math.imul(N,eu)|0)+Math.imul(O,el)|0,n=n+Math.imul(O,eu)|0,i=i+Math.imul(R,ed)|0,a=(a=a+Math.imul(R,ep)|0)+Math.imul(T,ed)|0,n=n+Math.imul(T,ep)|0,i=i+Math.imul(A,em)|0;var eT=(u+i|0)+((8191&(a=(a=a+Math.imul(A,ef)|0)+Math.imul(_,em)|0))<<13)|0;u=((n=n+Math.imul(_,ef)|0)+(a>>>13)|0)+(eT>>>26)|0,eT&=0x3ffffff,i=Math.imul(j,en),a=(a=Math.imul(j,es))+Math.imul(L,en)|0,n=Math.imul(L,es),i=i+Math.imul($,el)|0,a=(a=a+Math.imul($,eu)|0)+Math.imul(U,el)|0,n=n+Math.imul(U,eu)|0,i=i+Math.imul(N,ed)|0,a=(a=a+Math.imul(N,ep)|0)+Math.imul(O,ed)|0,n=n+Math.imul(O,ep)|0,i=i+Math.imul(R,em)|0;var eD=(u+i|0)+((8191&(a=(a=a+Math.imul(R,ef)|0)+Math.imul(T,em)|0))<<13)|0;u=((n=n+Math.imul(T,ef)|0)+(a>>>13)|0)+(eD>>>26)|0,eD&=0x3ffffff,i=Math.imul(j,el),a=(a=Math.imul(j,eu))+Math.imul(L,el)|0,n=Math.imul(L,eu),i=i+Math.imul($,ed)|0,a=(a=a+Math.imul($,ep)|0)+Math.imul(U,ed)|0,n=n+Math.imul(U,ep)|0,i=i+Math.imul(N,em)|0;var eN=(u+i|0)+((8191&(a=(a=a+Math.imul(N,ef)|0)+Math.imul(O,em)|0))<<13)|0;u=((n=n+Math.imul(O,ef)|0)+(a>>>13)|0)+(eN>>>26)|0,eN&=0x3ffffff,i=Math.imul(j,ed),a=(a=Math.imul(j,ep))+Math.imul(L,ed)|0,n=Math.imul(L,ep),i=i+Math.imul($,em)|0;var eO=(u+i|0)+((8191&(a=(a=a+Math.imul($,ef)|0)+Math.imul(U,em)|0))<<13)|0;u=((n=n+Math.imul(U,ef)|0)+(a>>>13)|0)+(eO>>>26)|0,eO&=0x3ffffff,i=Math.imul(j,em);var eP=(u+i|0)+((8191&(a=(a=Math.imul(j,ef))+Math.imul(L,em)|0))<<13)|0;return u=((n=Math.imul(L,ef))+(a>>>13)|0)+(eP>>>26)|0,eP&=0x3ffffff,l[0]=eg,l[1]=ey,l[2]=ew,l[3]=eb,l[4]=ev,l[5]=ek,l[6]=eS,l[7]=eE,l[8]=eI,l[9]=ex,l[10]=eA,l[11]=e_,l[12]=eC,l[13]=eR,l[14]=eT,l[15]=eD,l[16]=eN,l[17]=eO,l[18]=eP,0!==u&&(l[19]=u,r.length++),r};function f(e,t,r){return new g().mulp(e,t,r)}function g(e,t){this.x=e,this.y=t}Math.imul||(m=h),n.prototype.mulTo=function(e,t){var r=this.length+e.length;return 10===this.length&&10===e.length?m(this,e,t):r<63?h(this,e,t):r<1024?function(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var i=0,a=0,n=0;n<r.length-1;n++){var s=a;a=0;for(var o=0x3ffffff&i,l=Math.min(n,t.length-1),u=Math.max(0,n-e.length+1);u<=l;u++){var c=n-u,d=(0|e.words[c])*(0|t.words[u]),p=0x3ffffff&d;s=s+(d/0x4000000|0)|0,o=0x3ffffff&(p=p+o|0),a+=(s=s+(p>>>26)|0)>>>26,s&=0x3ffffff}r.words[n]=o,i=s,s=a}return 0!==i?r.words[n]=i:r.length--,r.strip()}(this,e,t):f(this,e,t)},g.prototype.makeRBT=function(e){for(var t=Array(e),r=n.prototype._countBits(e)-1,i=0;i<e;i++)t[i]=this.revBin(i,r,e);return t},g.prototype.revBin=function(e,t,r){if(0===e||e===r-1)return e;for(var i=0,a=0;a<t;a++)i|=(1&e)<<t-a-1,e>>=1;return i},g.prototype.permute=function(e,t,r,i,a,n){for(var s=0;s<n;s++)i[s]=t[e[s]],a[s]=r[e[s]]},g.prototype.transform=function(e,t,r,i,a,n){this.permute(n,e,t,r,i,a);for(var s=1;s<a;s<<=1)for(var o=s<<1,l=Math.cos(2*Math.PI/o),u=Math.sin(2*Math.PI/o),c=0;c<a;c+=o)for(var d=l,p=u,h=0;h<s;h++){var m=r[c+h],f=i[c+h],g=r[c+h+s],y=i[c+h+s],w=d*g-p*y;y=d*y+p*g,g=w,r[c+h]=m+g,i[c+h]=f+y,r[c+h+s]=m-g,i[c+h+s]=f-y,h!==o&&(w=l*d-u*p,p=l*p+u*d,d=w)}},g.prototype.guessLen13b=function(e,t){var r=1|Math.max(t,e),i=1&r,a=0;for(r=r/2|0;r;r>>>=1)a++;return 1<<a+1+i},g.prototype.conjugate=function(e,t,r){if(!(r<=1))for(var i=0;i<r/2;i++){var a=e[i];e[i]=e[r-i-1],e[r-i-1]=a,a=t[i],t[i]=-t[r-i-1],t[r-i-1]=-a}},g.prototype.normalize13b=function(e,t){for(var r=0,i=0;i<t/2;i++){var a=8192*Math.round(e[2*i+1]/t)+Math.round(e[2*i]/t)+r;e[i]=0x3ffffff&a,r=a<0x4000000?0:a/0x4000000|0}return e},g.prototype.convert13b=function(e,t,r,a){for(var n=0,s=0;s<t;s++)n+=0|e[s],r[2*s]=8191&n,n>>>=13,r[2*s+1]=8191&n,n>>>=13;for(s=2*t;s<a;++s)r[s]=0;i(0===n),i((-8192&n)==0)},g.prototype.stub=function(e){for(var t=Array(e),r=0;r<e;r++)t[r]=0;return t},g.prototype.mulp=function(e,t,r){var i=2*this.guessLen13b(e.length,t.length),a=this.makeRBT(i),n=this.stub(i),s=Array(i),o=Array(i),l=Array(i),u=Array(i),c=Array(i),d=Array(i),p=r.words;p.length=i,this.convert13b(e.words,e.length,s,i),this.convert13b(t.words,t.length,u,i),this.transform(s,n,o,l,i,a),this.transform(u,n,c,d,i,a);for(var h=0;h<i;h++){var m=o[h]*c[h]-l[h]*d[h];l[h]=o[h]*d[h]+l[h]*c[h],o[h]=m}return this.conjugate(o,l,i),this.transform(o,l,p,n,i,a),this.conjugate(p,n,i),this.normalize13b(p,i),r.negative=e.negative^t.negative,r.length=e.length+t.length,r.strip()},n.prototype.mul=function(e){var t=new n(null);return t.words=Array(this.length+e.length),this.mulTo(e,t)},n.prototype.mulf=function(e){var t=new n(null);return t.words=Array(this.length+e.length),f(this,e,t)},n.prototype.imul=function(e){return this.clone().mulTo(e,this)},n.prototype.imuln=function(e){i("number"==typeof e),i(e<0x4000000);for(var t=0,r=0;r<this.length;r++){var a=(0|this.words[r])*e,n=(0x3ffffff&a)+(0x3ffffff&t);t>>=26,t+=(a/0x4000000|0)+(n>>>26),this.words[r]=0x3ffffff&n}return 0!==t&&(this.words[r]=t,this.length++),0===e&&(this.length=1,this._normSign()),this},n.prototype.muln=function(e){return this.clone().imuln(e)},n.prototype.sqr=function(){return this.mul(this)},n.prototype.isqr=function(){return this.imul(this.clone())},n.prototype.pow=function(e){var t=function(e){for(var t=Array(e.bitLength()),r=0;r<t.length;r++){var i=r/26|0,a=r%26;t[r]=(e.words[i]&1<<a)>>>a}return t}(e);if(0===t.length)return new n(1);for(var r=this,i=0;i<t.length&&0===t[i];i++,r=r.sqr());if(++i<t.length)for(var a=r.sqr();i<t.length;i++,a=a.sqr())0!==t[i]&&(r=r.mul(a));return r},n.prototype.iushln=function(e){i("number"==typeof e&&e>=0);var t,r=e%26,a=(e-r)/26,n=0x3ffffff>>>26-r<<26-r;if(0!==r){var s=0;for(t=0;t<this.length;t++){var o=this.words[t]&n,l=(0|this.words[t])-o<<r;this.words[t]=l|s,s=o>>>26-r}s&&(this.words[t]=s,this.length++)}if(0!==a){for(t=this.length-1;t>=0;t--)this.words[t+a]=this.words[t];for(t=0;t<a;t++)this.words[t]=0;this.length+=a}return this.strip()},n.prototype.ishln=function(e){return i(0===this.negative),this.iushln(e)},n.prototype.iushrn=function(e,t,r){i("number"==typeof e&&e>=0);var a=t?(t-t%26)/26:0,n=e%26,s=Math.min((e-n)/26,this.length),o=0x3ffffff^0x3ffffff>>>n<<n;if(a-=s,a=Math.max(0,a),r){for(var l=0;l<s;l++)r.words[l]=this.words[l];r.length=s}if(0===s);else if(this.length>s)for(this.length-=s,l=0;l<this.length;l++)this.words[l]=this.words[l+s];else this.words[0]=0,this.length=1;var u=0;for(l=this.length-1;l>=0&&(0!==u||l>=a);l--){var c=0|this.words[l];this.words[l]=u<<26-n|c>>>n,u=c&o}return r&&0!==u&&(r.words[r.length++]=u),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},n.prototype.ishrn=function(e,t,r){return i(0===this.negative),this.iushrn(e,t,r)},n.prototype.shln=function(e){return this.clone().ishln(e)},n.prototype.ushln=function(e){return this.clone().iushln(e)},n.prototype.shrn=function(e){return this.clone().ishrn(e)},n.prototype.ushrn=function(e){return this.clone().iushrn(e)},n.prototype.testn=function(e){i("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26;return!(this.length<=r)&&!!(this.words[r]&1<<t)},n.prototype.imaskn=function(e){i("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26;return(i(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)?this:(0!==t&&r++,this.length=Math.min(r,this.length),0!==t&&(this.words[this.length-1]&=0x3ffffff^0x3ffffff>>>t<<t),0===this.length&&(this.words[0]=0,this.length=1),this.strip())},n.prototype.maskn=function(e){return this.clone().imaskn(e)},n.prototype.iaddn=function(e){return(i("number"==typeof e),i(e<0x4000000),e<0)?this.isubn(-e):0!==this.negative?(1===this.length&&(0|this.words[0])<e?(this.words[0]=e-(0|this.words[0]),this.negative=0):(this.negative=0,this.isubn(e),this.negative=1),this):this._iaddn(e)},n.prototype._iaddn=function(e){this.words[0]+=e;for(var t=0;t<this.length&&this.words[t]>=0x4000000;t++)this.words[t]-=0x4000000,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},n.prototype.isubn=function(e){if(i("number"==typeof e),i(e<0x4000000),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t<this.length&&this.words[t]<0;t++)this.words[t]+=0x4000000,this.words[t+1]-=1;return this.strip()},n.prototype.addn=function(e){return this.clone().iaddn(e)},n.prototype.subn=function(e){return this.clone().isubn(e)},n.prototype.iabs=function(){return this.negative=0,this},n.prototype.abs=function(){return this.clone().iabs()},n.prototype._ishlnsubmul=function(e,t,r){var a,n,s=e.length+r;this._expand(s);var o=0;for(a=0;a<e.length;a++){n=(0|this.words[a+r])+o;var l=(0|e.words[a])*t;n-=0x3ffffff&l,o=(n>>26)-(l/0x4000000|0),this.words[a+r]=0x3ffffff&n}for(;a<this.length-r;a++)o=(n=(0|this.words[a+r])+o)>>26,this.words[a+r]=0x3ffffff&n;if(0===o)return this.strip();for(i(-1===o),o=0,a=0;a<this.length;a++)o=(n=-(0|this.words[a])+o)>>26,this.words[a]=0x3ffffff&n;return this.negative=1,this.strip()},n.prototype._wordDiv=function(e,t){var r,i=this.length-e.length,a=this.clone(),s=e,o=0|s.words[s.length-1];0!=(i=26-this._countBits(o))&&(s=s.ushln(i),a.iushln(i),o=0|s.words[s.length-1]);var l=a.length-s.length;if("mod"!==t){(r=new n(null)).length=l+1,r.words=Array(r.length);for(var u=0;u<r.length;u++)r.words[u]=0}var c=a.clone()._ishlnsubmul(s,1,l);0===c.negative&&(a=c,r&&(r.words[l]=1));for(var d=l-1;d>=0;d--){var p=(0|a.words[s.length+d])*0x4000000+(0|a.words[s.length+d-1]);for(p=Math.min(p/o|0,0x3ffffff),a._ishlnsubmul(s,p,d);0!==a.negative;)p--,a.negative=0,a._ishlnsubmul(s,1,d),a.isZero()||(a.negative^=1);r&&(r.words[d]=p)}return r&&r.strip(),a.strip(),"div"!==t&&0!==i&&a.iushrn(i),{div:r||null,mod:a}},n.prototype.divmod=function(e,t,r){var a,s,o;return(i(!e.isZero()),this.isZero())?{div:new n(0),mod:new n(0)}:0!==this.negative&&0===e.negative?(o=this.neg().divmod(e,t),"mod"!==t&&(a=o.div.neg()),"div"!==t&&(s=o.mod.neg(),r&&0!==s.negative&&s.iadd(e)),{div:a,mod:s}):0===this.negative&&0!==e.negative?(o=this.divmod(e.neg(),t),"mod"!==t&&(a=o.div.neg()),{div:a,mod:o.mod}):(this.negative&e.negative)!=0?(o=this.neg().divmod(e.neg(),t),"div"!==t&&(s=o.mod.neg(),r&&0!==s.negative&&s.isub(e)),{div:o.div,mod:s}):e.length>this.length||0>this.cmp(e)?{div:new n(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new n(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new n(this.modn(e.words[0]))}:this._wordDiv(e,t)},n.prototype.div=function(e){return this.divmod(e,"div",!1).div},n.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},n.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},n.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=t.mod.abs(),i=e.abs().iushrn(1),a=1&e.words[0],s=r.cmp(i);if(s<0||1===a&&0===s)return t.div;var o=new n(1);return o.negative=this.negative^e.negative,t.div.iadd(o)},n.prototype.modn=function(e){i(e<=0x3ffffff);for(var t=0x4000000%e,r=0,a=this.length-1;a>=0;a--)r=(t*r+(0|this.words[a]))%e;return r},n.prototype.idivn=function(e){i(e<=0x3ffffff);for(var t=0,r=this.length-1;r>=0;r--){var a=(0|this.words[r])+0x4000000*t;this.words[r]=a/e|0,t=a%e}return this.strip()},n.prototype.divn=function(e){return this.clone().idivn(e)},n.prototype.egcd=function(e){i(0===e.negative),i(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var a=new n(1),s=new n(0),o=new n(0),l=new n(1),u=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++u;for(var c=r.clone(),d=t.clone();!t.isZero();){for(var p=0,h=1;(t.words[0]&h)==0&&p<26;++p,h<<=1);if(p>0)for(t.iushrn(p);p-- >0;)(a.isOdd()||s.isOdd())&&(a.iadd(c),s.isub(d)),a.iushrn(1),s.iushrn(1);for(var m=0,f=1;(r.words[0]&f)==0&&m<26;++m,f<<=1);if(m>0)for(r.iushrn(m);m-- >0;)(o.isOdd()||l.isOdd())&&(o.iadd(c),l.isub(d)),o.iushrn(1),l.iushrn(1);t.cmp(r)>=0?(t.isub(r),a.isub(o),s.isub(l)):(r.isub(t),o.isub(a),l.isub(s))}return{a:o,b:l,gcd:r.iushln(u)}},n.prototype._invmp=function(e){i(0===e.negative),i(!e.isZero());var t,r=this,a=e.clone();r=0!==r.negative?r.umod(e):r.clone();for(var s=new n(1),o=new n(0),l=a.clone();r.cmpn(1)>0&&a.cmpn(1)>0;){for(var u=0,c=1;(r.words[0]&c)==0&&u<26;++u,c<<=1);if(u>0)for(r.iushrn(u);u-- >0;)s.isOdd()&&s.iadd(l),s.iushrn(1);for(var d=0,p=1;(a.words[0]&p)==0&&d<26;++d,p<<=1);if(d>0)for(a.iushrn(d);d-- >0;)o.isOdd()&&o.iadd(l),o.iushrn(1);r.cmp(a)>=0?(r.isub(a),s.isub(o)):(a.isub(r),o.isub(s))}return 0>(t=0===r.cmpn(1)?s:o).cmpn(0)&&t.iadd(e),t},n.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var i=0;t.isEven()&&r.isEven();i++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var a=t.cmp(r);if(a<0){var n=t;t=r,r=n}else if(0===a||0===r.cmpn(1))break;t.isub(r)}return r.iushln(i)},n.prototype.invm=function(e){return this.egcd(e).a.umod(e)},n.prototype.isEven=function(){return(1&this.words[0])==0},n.prototype.isOdd=function(){return(1&this.words[0])==1},n.prototype.andln=function(e){return this.words[0]&e},n.prototype.bincn=function(e){i("number"==typeof e);var t=e%26,r=(e-t)/26,a=1<<t;if(this.length<=r)return this._expand(r+1),this.words[r]|=a,this;for(var n=a,s=r;0!==n&&s<this.length;s++){var o=0|this.words[s];o+=n,n=o>>>26,o&=0x3ffffff,this.words[s]=o}return 0!==n&&(this.words[s]=n,this.length++),this},n.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},n.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return -1;if(0===this.negative&&r)return 1;if(this.strip(),this.length>1)t=1;else{r&&(e=-e),i(e<=0x3ffffff,"Number is too big");var a=0|this.words[0];t=a===e?0:a<e?-1:1}return 0!==this.negative?0|-t:t},n.prototype.cmp=function(e){if(0!==this.negative&&0===e.negative)return -1;if(0===this.negative&&0!==e.negative)return 1;var t=this.ucmp(e);return 0!==this.negative?0|-t:t},n.prototype.ucmp=function(e){if(this.length>e.length)return 1;if(this.length<e.length)return -1;for(var t=0,r=this.length-1;r>=0;r--){var i=0|this.words[r],a=0|e.words[r];if(i!==a){i<a?t=-1:i>a&&(t=1);break}}return t},n.prototype.gtn=function(e){return 1===this.cmpn(e)},n.prototype.gt=function(e){return 1===this.cmp(e)},n.prototype.gten=function(e){return this.cmpn(e)>=0},n.prototype.gte=function(e){return this.cmp(e)>=0},n.prototype.ltn=function(e){return -1===this.cmpn(e)},n.prototype.lt=function(e){return -1===this.cmp(e)},n.prototype.lten=function(e){return 0>=this.cmpn(e)},n.prototype.lte=function(e){return 0>=this.cmp(e)},n.prototype.eqn=function(e){return 0===this.cmpn(e)},n.prototype.eq=function(e){return 0===this.cmp(e)},n.red=function(e){return new E(e)},n.prototype.toRed=function(e){return i(!this.red,"Already a number in reduction context"),i(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},n.prototype.fromRed=function(){return i(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},n.prototype._forceRed=function(e){return this.red=e,this},n.prototype.forceRed=function(e){return i(!this.red,"Already a number in reduction context"),this._forceRed(e)},n.prototype.redAdd=function(e){return i(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},n.prototype.redIAdd=function(e){return i(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},n.prototype.redSub=function(e){return i(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},n.prototype.redISub=function(e){return i(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},n.prototype.redShl=function(e){return i(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},n.prototype.redMul=function(e){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},n.prototype.redIMul=function(e){return i(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},n.prototype.redSqr=function(){return i(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},n.prototype.redISqr=function(){return i(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},n.prototype.redSqrt=function(){return i(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},n.prototype.redInvm=function(){return i(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},n.prototype.redNeg=function(){return i(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},n.prototype.redPow=function(e){return i(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var y={k256:null,p224:null,p192:null,p25519:null};function w(e,t){this.name=e,this.p=new n(t,16),this.n=this.p.bitLength(),this.k=new n(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function b(){w.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function v(){w.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function k(){w.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function S(){w.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function E(e){if("string"==typeof e){var t=n._prime(e);this.m=t.p,this.prime=t}else i(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function I(e){E.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new n(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}w.prototype._tmp=function(){var e=new n(null);return e.words=Array(Math.ceil(this.n/13)),e},w.prototype.ireduce=function(e){var t,r=e;do this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength();while(t>this.n)var i=t<this.n?-1:r.ucmp(this.p);return 0===i?(r.words[0]=0,r.length=1):i>0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},w.prototype.split=function(e,t){e.iushrn(this.n,0,t)},w.prototype.imulK=function(e){return e.imul(this.k)},a(b,w),b.prototype.split=function(e,t){for(var r=Math.min(e.length,9),i=0;i<r;i++)t.words[i]=e.words[i];if(t.length=r,e.length<=9){e.words[0]=0,e.length=1;return}var a=e.words[9];for(i=10,t.words[t.length++]=4194303&a;i<e.length;i++){var n=0|e.words[i];e.words[i-10]=(4194303&n)<<4|a>>>22,a=n}a>>>=22,e.words[i-10]=a,0===a&&e.length>10?e.length-=10:e.length-=9},b.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r<e.length;r++){var i=0|e.words[r];t+=977*i,e.words[r]=0x3ffffff&t,t=64*i+(t/0x4000000|0)}return 0===e.words[e.length-1]&&(e.length--,0===e.words[e.length-1]&&e.length--),e},a(v,w),a(k,w),a(S,w),S.prototype.imulK=function(e){for(var t=0,r=0;r<e.length;r++){var i=(0|e.words[r])*19+t,a=0x3ffffff&i;i>>>=26,e.words[r]=a,t=i}return 0!==t&&(e.words[e.length++]=t),e},n._prime=function(e){var t;if(y[e])return y[e];if("k256"===e)t=new b;else if("p224"===e)t=new v;else if("p192"===e)t=new k;else if("p25519"===e)t=new S;else throw Error("Unknown prime "+e);return y[e]=t,t},E.prototype._verify1=function(e){i(0===e.negative,"red works only with positives"),i(e.red,"red works only with red numbers")},E.prototype._verify2=function(e,t){i((e.negative|t.negative)==0,"red works only with positives"),i(e.red&&e.red===t.red,"red works only with red numbers")},E.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},E.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},E.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},E.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},E.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return 0>r.cmpn(0)&&r.iadd(this.m),r._forceRed(this)},E.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return 0>r.cmpn(0)&&r.iadd(this.m),r},E.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},E.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},E.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},E.prototype.isqr=function(e){return this.imul(e,e.clone())},E.prototype.sqr=function(e){return this.mul(e,e)},E.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(i(t%2==1),3===t){var r=this.m.add(new n(1)).iushrn(2);return this.pow(e,r)}for(var a=this.m.subn(1),s=0;!a.isZero()&&0===a.andln(1);)s++,a.iushrn(1);i(!a.isZero());var o=new n(1).toRed(this),l=o.redNeg(),u=this.m.subn(1).iushrn(1),c=this.m.bitLength();for(c=new n(2*c*c).toRed(this);0!==this.pow(c,u).cmp(l);)c.redIAdd(l);for(var d=this.pow(c,a),p=this.pow(e,a.addn(1).iushrn(1)),h=this.pow(e,a),m=s;0!==h.cmp(o);){for(var f=h,g=0;0!==f.cmp(o);g++)f=f.redSqr();i(g<m);var y=this.pow(d,new n(1).iushln(m-g-1));p=p.redMul(y),d=y.redSqr(),h=h.redMul(d),m=g}return p},E.prototype.invm=function(e){var t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)},E.prototype.pow=function(e,t){if(t.isZero())return new n(1).toRed(this);if(0===t.cmpn(1))return e.clone();var r=Array(16);r[0]=new n(1).toRed(this),r[1]=e;for(var i=2;i<r.length;i++)r[i]=this.mul(r[i-1],e);var a=r[0],s=0,o=0,l=t.bitLength()%26;for(0===l&&(l=26),i=t.length-1;i>=0;i--){for(var u=t.words[i],c=l-1;c>=0;c--){var d=u>>c&1;if(a!==r[0]&&(a=this.sqr(a)),0===d&&0===s){o=0;continue}s<<=1,s|=d,(4==++o||0===i&&0===c)&&(a=this.mul(a,r[s]),o=0,s=0)}l=26}return a},E.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},E.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},n.mont=function(e){return new I(e)},a(I,E),I.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},I.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},I.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=r.isub(i).iushrn(this.shift),n=a;return a.cmp(this.m)>=0?n=a.isub(this.m):0>a.cmpn(0)&&(n=a.iadd(this.m)),n._forceRed(this)},I.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new n(0)._forceRed(this);var r=e.mul(t),i=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=r.isub(i).iushrn(this.shift),s=a;return a.cmp(this.m)>=0?s=a.isub(this.m):0>a.cmpn(0)&&(s=a.iadd(this.m)),s._forceRed(this)},I.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(t,e.e)},832623,(e,t,r)=>{"use strict";var i,a=e.r(500874),n=a.Buffer,s={};for(i in a)a.hasOwnProperty(i)&&"SlowBuffer"!==i&&"Buffer"!==i&&(s[i]=a[i]);var o=s.Buffer={};for(i in n)n.hasOwnProperty(i)&&"allocUnsafe"!==i&&"allocUnsafeSlow"!==i&&(o[i]=n[i]);if(s.Buffer.prototype=n.prototype,o.from&&o.from!==Uint8Array.from||(o.from=function(e,t,r){if("number"==typeof e)throw TypeError('The "value" argument must not be of type number. Received type '+typeof e);if(e&&void 0===e.length)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);return n(e,t,r)}),o.alloc||(o.alloc=function(e,t,r){if("number"!=typeof e)throw TypeError('The "size" argument must be of type number. Received type '+typeof e);if(e<0||e>=2*0x40000000)throw RangeError('The value "'+e+'" is invalid for option "size"');var i=n(e);return t&&0!==t.length?"string"==typeof r?i.fill(t,r):i.fill(t):i.fill(0),i}),!s.kStringMaxLength)try{s.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch(e){}!s.constants&&(s.constants={MAX_LENGTH:s.kMaxLength},s.kStringMaxLength&&(s.constants.MAX_STRING_LENGTH=s.kStringMaxLength)),t.exports=s},857406,(e,t,r)=>{"use strict";let i=e.r(966397);function a(e){this._reporterState={obj:null,path:[],options:e||{},errors:[]}}function n(e,t){this.path=e,this.rethrow(t)}r.Reporter=a,a.prototype.isError=function(e){return e instanceof n},a.prototype.save=function(){let e=this._reporterState;return{obj:e.obj,pathLen:e.path.length}},a.prototype.restore=function(e){let t=this._reporterState;t.obj=e.obj,t.path=t.path.slice(0,e.pathLen)},a.prototype.enterKey=function(e){return this._reporterState.path.push(e)},a.prototype.exitKey=function(e){let t=this._reporterState;t.path=t.path.slice(0,e-1)},a.prototype.leaveKey=function(e,t,r){let i=this._reporterState;this.exitKey(e),null!==i.obj&&(i.obj[t]=r)},a.prototype.path=function(){return this._reporterState.path.join("/")},a.prototype.enterObject=function(){let e=this._reporterState,t=e.obj;return e.obj={},t},a.prototype.leaveObject=function(e){let t=this._reporterState,r=t.obj;return t.obj=e,r},a.prototype.error=function(e){let t,r=this._reporterState,i=e instanceof n;if(t=i?e:new n(r.path.map(function(e){return"["+JSON.stringify(e)+"]"}).join(""),e.message||e,e.stack),!r.options.partial)throw t;return i||r.errors.push(t),t},a.prototype.wrapResult=function(e){let t=this._reporterState;return t.options.partial?{result:this.isError(e)?null:e,errors:t.errors}:e},i(n,Error),n.prototype.rethrow=function(e){if(this.message=e+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,n),!this.stack)try{throw Error(this.message)}catch(e){this.stack=e.stack}return this}},644833,(e,t,r)=>{"use strict";let i=e.r(966397),a=e.r(857406).Reporter,n=e.r(832623).Buffer;function s(e,t){(a.call(this,t),n.isBuffer(e))?(this.base=e,this.offset=0,this.length=e.length):this.error("Input not Buffer")}function o(e,t){if(Array.isArray(e))this.length=0,this.value=e.map(function(e){return o.isEncoderBuffer(e)||(e=new o(e,t)),this.length+=e.length,e},this);else if("number"==typeof e){if(!(0<=e&&e<=255))return t.error("non-byte EncoderBuffer value");this.value=e,this.length=1}else if("string"==typeof e)this.value=e,this.length=n.byteLength(e);else{if(!n.isBuffer(e))return t.error("Unsupported type: "+typeof e);this.value=e,this.length=e.length}}i(s,a),r.DecoderBuffer=s,s.isDecoderBuffer=function(e){return e instanceof s||"object"==typeof e&&n.isBuffer(e.base)&&"DecoderBuffer"===e.constructor.name&&"number"==typeof e.offset&&"number"==typeof e.length&&"function"==typeof e.save&&"function"==typeof e.restore&&"function"==typeof e.isEmpty&&"function"==typeof e.readUInt8&&"function"==typeof e.skip&&"function"==typeof e.raw},s.prototype.save=function(){return{offset:this.offset,reporter:a.prototype.save.call(this)}},s.prototype.restore=function(e){let t=new s(this.base);return t.offset=e.offset,t.length=this.offset,this.offset=e.offset,a.prototype.restore.call(this,e.reporter),t},s.prototype.isEmpty=function(){return this.offset===this.length},s.prototype.readUInt8=function(e){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(e||"DecoderBuffer overrun")},s.prototype.skip=function(e,t){if(!(this.offset+e<=this.length))return this.error(t||"DecoderBuffer overrun");let r=new s(this.base);return r._reporterState=this._reporterState,r.offset=this.offset,r.length=this.offset+e,this.offset+=e,r},s.prototype.raw=function(e){return this.base.slice(e?e.offset:this.offset,this.length)},r.EncoderBuffer=o,o.isEncoderBuffer=function(e){return e instanceof o||"object"==typeof e&&"EncoderBuffer"===e.constructor.name&&"number"==typeof e.length&&"function"==typeof e.join},o.prototype.join=function(e,t){return e||(e=n.alloc(this.length)),t||(t=0),0===this.length||(Array.isArray(this.value)?this.value.forEach(function(r){r.join(e,t),t+=r.length}):("number"==typeof this.value?e[t]=this.value:"string"==typeof this.value?e.write(this.value,t):n.isBuffer(this.value)&&this.value.copy(e,t),t+=this.length)),e}},81221,(e,t,r)=>{function i(e,t){if(!e)throw Error(t||"Assertion failed")}t.exports=i,i.equal=function(e,t,r){if(e!=t)throw Error(r||"Assertion failed: "+e+" != "+t)}},524283,(e,t,r)=>{"use strict";let i=e.r(857406).Reporter,a=e.r(644833).EncoderBuffer,n=e.r(644833).DecoderBuffer,s=e.r(81221),o=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],l=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(o);function u(e,t,r){let i={};this._baseState=i,i.name=r,i.enc=e,i.parent=t||null,i.children=null,i.tag=null,i.args=null,i.reverseArgs=null,i.choice=null,i.optional=!1,i.any=!1,i.obj=!1,i.use=null,i.useDecoder=null,i.key=null,i.default=null,i.explicit=null,i.implicit=null,i.contains=null,i.parent||(i.children=[],this._wrap())}t.exports=u;let c=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];u.prototype.clone=function(){let e=this._baseState,t={};c.forEach(function(r){t[r]=e[r]});let r=new this.constructor(t.parent);return r._baseState=t,r},u.prototype._wrap=function(){let e=this._baseState;l.forEach(function(t){this[t]=function(){let r=new this.constructor(this);return e.children.push(r),r[t].apply(r,arguments)}},this)},u.prototype._init=function(e){let t=this._baseState;s(null===t.parent),e.call(this),t.children=t.children.filter(function(e){return e._baseState.parent===this},this),s.equal(t.children.length,1,"Root node can have only one child")},u.prototype._useArgs=function(e){let t=this._baseState,r=e.filter(function(e){return e instanceof this.constructor},this);e=e.filter(function(e){return!(e instanceof this.constructor)},this),0!==r.length&&(s(null===t.children),t.children=r,r.forEach(function(e){e._baseState.parent=this},this)),0!==e.length&&(s(null===t.args),t.args=e,t.reverseArgs=e.map(function(e){if("object"!=typeof e||e.constructor!==Object)return e;let t={};return Object.keys(e).forEach(function(r){r==(0|r)&&(r|=0),t[e[r]]=r}),t}))},["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"].forEach(function(e){u.prototype[e]=function(){throw Error(e+" not implemented for encoding: "+this._baseState.enc)}}),o.forEach(function(e){u.prototype[e]=function(){let t=this._baseState,r=Array.prototype.slice.call(arguments);return s(null===t.tag),t.tag=e,this._useArgs(r),this}}),u.prototype.use=function(e){s(e);let t=this._baseState;return s(null===t.use),t.use=e,this},u.prototype.optional=function(){return this._baseState.optional=!0,this},u.prototype.def=function(e){let t=this._baseState;return s(null===t.default),t.default=e,t.optional=!0,this},u.prototype.explicit=function(e){let t=this._baseState;return s(null===t.explicit&&null===t.implicit),t.explicit=e,this},u.prototype.implicit=function(e){let t=this._baseState;return s(null===t.explicit&&null===t.implicit),t.implicit=e,this},u.prototype.obj=function(){let e=this._baseState,t=Array.prototype.slice.call(arguments);return e.obj=!0,0!==t.length&&this._useArgs(t),this},u.prototype.key=function(e){let t=this._baseState;return s(null===t.key),t.key=e,this},u.prototype.any=function(){return this._baseState.any=!0,this},u.prototype.choice=function(e){let t=this._baseState;return s(null===t.choice),t.choice=e,this._useArgs(Object.keys(e).map(function(t){return e[t]})),this},u.prototype.contains=function(e){let t=this._baseState;return s(null===t.use),t.contains=e,this},u.prototype._decode=function(e,t){let r,i=this._baseState;if(null===i.parent)return e.wrapResult(i.children[0]._decode(e,t));let a=i.default,s=!0,o=null;if(null!==i.key&&(o=e.enterKey(i.key)),i.optional){let r=null;if(null!==i.explicit?r=i.explicit:null!==i.implicit?r=i.implicit:null!==i.tag&&(r=i.tag),null!==r||i.any){if(s=this._peekTag(e,r,i.any),e.isError(s))return s}else{let r=e.save();try{null===i.choice?this._decodeGeneric(i.tag,e,t):this._decodeChoice(e,t),s=!0}catch(e){s=!1}e.restore(r)}}if(i.obj&&s&&(r=e.enterObject()),s){if(null!==i.explicit){let t=this._decodeTag(e,i.explicit);if(e.isError(t))return t;e=t}let r=e.offset;if(null===i.use&&null===i.choice){let t;i.any&&(t=e.save());let r=this._decodeTag(e,null!==i.implicit?i.implicit:i.tag,i.any);if(e.isError(r))return r;i.any?a=e.raw(t):e=r}if(t&&t.track&&null!==i.tag&&t.track(e.path(),r,e.length,"tagged"),t&&t.track&&null!==i.tag&&t.track(e.path(),e.offset,e.length,"content"),i.any||(a=null===i.choice?this._decodeGeneric(i.tag,e,t):this._decodeChoice(e,t)),e.isError(a))return a;if(i.any||null!==i.choice||null===i.children||i.children.forEach(function(r){r._decode(e,t)}),i.contains&&("octstr"===i.tag||"bitstr"===i.tag)){let r=new n(a);a=this._getUse(i.contains,e._reporterState.obj)._decode(r,t)}}return i.obj&&s&&(a=e.leaveObject(r)),null!==i.key&&(null!==a||!0===s)?e.leaveKey(o,i.key,a):null!==o&&e.exitKey(o),a},u.prototype._decodeGeneric=function(e,t,r){let i=this._baseState;if("seq"===e||"set"===e)return null;if("seqof"===e||"setof"===e)return this._decodeList(t,e,i.args[0],r);if(/str$/.test(e))return this._decodeStr(t,e,r);if("objid"===e&&i.args)return this._decodeObjid(t,i.args[0],i.args[1],r);if("objid"===e)return this._decodeObjid(t,null,null,r);if("gentime"===e||"utctime"===e)return this._decodeTime(t,e,r);else if("null_"===e)return this._decodeNull(t,r);else if("bool"===e)return this._decodeBool(t,r);else if("objDesc"===e)return this._decodeStr(t,e,r);else if("int"===e||"enum"===e)return this._decodeInt(t,i.args&&i.args[0],r);return null!==i.use?this._getUse(i.use,t._reporterState.obj)._decode(t,r):t.error("unknown tag: "+e)},u.prototype._getUse=function(e,t){let r=this._baseState;return r.useDecoder=this._use(e,t),s(null===r.useDecoder._baseState.parent),r.useDecoder=r.useDecoder._baseState.children[0],r.implicit!==r.useDecoder._baseState.implicit&&(r.useDecoder=r.useDecoder.clone(),r.useDecoder._baseState.implicit=r.implicit),r.useDecoder},u.prototype._decodeChoice=function(e,t){let r=this._baseState,i=null,a=!1;return(Object.keys(r.choice).some(function(n){let s=e.save(),o=r.choice[n];try{let r=o._decode(e,t);if(e.isError(r))return!1;i={type:n,value:r},a=!0}catch(t){return e.restore(s),!1}return!0},this),a)?i:e.error("Choice not matched")},u.prototype._createEncoderBuffer=function(e){return new a(e,this.reporter)},u.prototype._encode=function(e,t,r){let i=this._baseState;if(null!==i.default&&i.default===e)return;let a=this._encodeValue(e,t,r);if(void 0!==a&&!this._skipDefault(a,t,r))return a},u.prototype._encodeValue=function(e,t,r){let a=this._baseState;if(null===a.parent)return a.children[0]._encode(e,t||new i);let n=null;if(this.reporter=t,a.optional&&void 0===e)if(null===a.default)return;else e=a.default;let s=null,o=!1;if(a.any)n=this._createEncoderBuffer(e);else if(a.choice)n=this._encodeChoice(e,t);else if(a.contains)s=this._getUse(a.contains,r)._encode(e,t),o=!0;else if(a.children)s=a.children.map(function(r){if("null_"===r._baseState.tag)return r._encode(null,t,e);if(null===r._baseState.key)return t.error("Child should have a key");let i=t.enterKey(r._baseState.key);if("object"!=typeof e)return t.error("Child expected, but input is not object");let a=r._encode(e[r._baseState.key],t,e);return t.leaveKey(i),a},this).filter(function(e){return e}),s=this._createEncoderBuffer(s);else if("seqof"===a.tag||"setof"===a.tag){if(!(a.args&&1===a.args.length))return t.error("Too many args for : "+a.tag);if(!Array.isArray(e))return t.error("seqof/setof, but data is not Array");let r=this.clone();r._baseState.implicit=null,s=this._createEncoderBuffer(e.map(function(r){let i=this._baseState;return this._getUse(i.args[0],e)._encode(r,t)},r))}else null!==a.use?n=this._getUse(a.use,r)._encode(e,t):(s=this._encodePrimitive(a.tag,e),o=!0);if(!a.any&&null===a.choice){let e=null!==a.implicit?a.implicit:a.tag,r=null===a.implicit?"universal":"context";null===e?null===a.use&&t.error("Tag could be omitted only for .use()"):null===a.use&&(n=this._encodeComposite(e,o,r,s))}return null!==a.explicit&&(n=this._encodeComposite(a.explicit,!1,"context",n)),n},u.prototype._encodeChoice=function(e,t){let r=this._baseState,i=r.choice[e.type];return i||s(!1,e.type+" not found in "+JSON.stringify(Object.keys(r.choice))),i._encode(e.value,t)},u.prototype._encodePrimitive=function(e,t){let r=this._baseState;if(/str$/.test(e))return this._encodeStr(t,e);if("objid"===e&&r.args)return this._encodeObjid(t,r.reverseArgs[0],r.args[1]);if("objid"===e)return this._encodeObjid(t,null,null);if("gentime"===e||"utctime"===e)return this._encodeTime(t,e);if("null_"===e)return this._encodeNull();else if("int"===e||"enum"===e)return this._encodeInt(t,r.args&&r.reverseArgs[0]);else if("bool"===e)return this._encodeBool(t);else if("objDesc"===e)return this._encodeStr(t,e);else throw Error("Unsupported tag: "+e)},u.prototype._isNumstr=function(e){return/^[0-9 ]*$/.test(e)},u.prototype._isPrintstr=function(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/.test(e)}},433689,(e,t,r)=>{"use strict";function i(e){let t={};return Object.keys(e).forEach(function(r){(0|r)==r&&(r|=0),t[e[r]]=r}),t}r.tagClass={0:"universal",1:"application",2:"context",3:"private"},r.tagClassByName=i(r.tagClass),r.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},r.tagByName=i(r.tag)},970738,(e,t,r)=>{"use strict";let i=e.r(966397),a=e.r(832623).Buffer,n=e.r(524283),s=e.r(433689);function o(e){this.enc="der",this.name=e.name,this.entity=e,this.tree=new l,this.tree._init(e.body)}function l(e){n.call(this,"der",e)}function u(e){return e<10?"0"+e:e}t.exports=o,o.prototype.encode=function(e,t){return this.tree._encode(e,t).join()},i(l,n),l.prototype._encodeComposite=function(e,t,r,i){let n=function(e,t,r,i){let a;if("seqof"===e?e="seq":"setof"===e&&(e="set"),s.tagByName.hasOwnProperty(e))a=s.tagByName[e];else{if("number"!=typeof e||(0|e)!==e)return i.error("Unknown tag: "+e);a=e}return a>=31?i.error("Multi-octet tag encoding unsupported"):(t||(a|=32),a|=s.tagClassByName[r||"universal"]<<6)}(e,t,r,this.reporter);if(i.length<128){let e=a.alloc(2);return e[0]=n,e[1]=i.length,this._createEncoderBuffer([e,i])}let o=1;for(let e=i.length;e>=256;e>>=8)o++;let l=a.alloc(2+o);l[0]=n,l[1]=128|o;for(let e=1+o,t=i.length;t>0;e--,t>>=8)l[e]=255&t;return this._createEncoderBuffer([l,i])},l.prototype._encodeStr=function(e,t){if("bitstr"===t)return this._createEncoderBuffer([0|e.unused,e.data]);if("bmpstr"===t){let t=a.alloc(2*e.length);for(let r=0;r<e.length;r++)t.writeUInt16BE(e.charCodeAt(r),2*r);return this._createEncoderBuffer(t)}if("numstr"===t)return this._isNumstr(e)?this._createEncoderBuffer(e):this.reporter.error("Encoding of string type: numstr supports only digits and space");if("printstr"===t)return this._isPrintstr(e)?this._createEncoderBuffer(e):this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark");if(/str$/.test(t))return this._createEncoderBuffer(e);else if("objDesc"===t)return this._createEncoderBuffer(e);else return this.reporter.error("Encoding of string type: "+t+" unsupported")},l.prototype._encodeObjid=function(e,t,r){if("string"==typeof e){if(!t)return this.reporter.error("string objid given, but no values map found");if(!t.hasOwnProperty(e))return this.reporter.error("objid not found in values map");e=t[e].split(/[\s.]+/g);for(let t=0;t<e.length;t++)e[t]|=0}else if(Array.isArray(e)){e=e.slice();for(let t=0;t<e.length;t++)e[t]|=0}if(!Array.isArray(e))return this.reporter.error("objid() should be either array or string, got: "+JSON.stringify(e));if(!r){if(e[1]>=40)return this.reporter.error("Second objid identifier OOB");e.splice(0,2,40*e[0]+e[1])}let i=0;for(let t=0;t<e.length;t++){let r=e[t];for(i++;r>=128;r>>=7)i++}let n=a.alloc(i),s=n.length-1;for(let t=e.length-1;t>=0;t--){let r=e[t];for(n[s--]=127&r;(r>>=7)>0;)n[s--]=128|127&r}return this._createEncoderBuffer(n)},l.prototype._encodeTime=function(e,t){let r,i=new Date(e);return"gentime"===t?r=""+u(i.getUTCFullYear())+u(i.getUTCMonth()+1)+u(i.getUTCDate())+u(i.getUTCHours())+u(i.getUTCMinutes())+u(i.getUTCSeconds())+"Z":"utctime"===t?r=""+u(i.getUTCFullYear()%100)+u(i.getUTCMonth()+1)+u(i.getUTCDate())+u(i.getUTCHours())+u(i.getUTCMinutes())+u(i.getUTCSeconds())+"Z":this.reporter.error("Encoding "+t+" time is not supported yet"),this._encodeStr(r,"octstr")},l.prototype._encodeNull=function(){return this._createEncoderBuffer("")},l.prototype._encodeInt=function(e,t){if("string"==typeof e){if(!t)return this.reporter.error("String int or enum given, but no values map");if(!t.hasOwnProperty(e))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(e));e=t[e]}if("number"!=typeof e&&!a.isBuffer(e)){let t=e.toArray();!e.sign&&128&t[0]&&t.unshift(0),e=a.from(t)}if(a.isBuffer(e)){let t=e.length;0===e.length&&t++;let r=a.alloc(t);return e.copy(r),0===e.length&&(r[0]=0),this._createEncoderBuffer(r)}if(e<128)return this._createEncoderBuffer(e);if(e<256)return this._createEncoderBuffer([0,e]);let r=1;for(let t=e;t>=256;t>>=8)r++;let i=Array(r);for(let t=i.length-1;t>=0;t--)i[t]=255&e,e>>=8;return 128&i[0]&&i.unshift(0),this._createEncoderBuffer(a.from(i))},l.prototype._encodeBool=function(e){return this._createEncoderBuffer(255*!!e)},l.prototype._use=function(e,t){return"function"==typeof e&&(e=e(t)),e._getEncoder("der").tree},l.prototype._skipDefault=function(e,t,r){let i,a=this._baseState;if(null===a.default)return!1;let n=e.join();if(void 0===a.defaultBuffer&&(a.defaultBuffer=this._encodeValue(a.default,t,r).join()),n.length!==a.defaultBuffer.length)return!1;for(i=0;i<n.length;i++)if(n[i]!==a.defaultBuffer[i])return!1;return!0}},671153,(e,t,r)=>{"use strict";let i=e.r(966397),a=e.r(970738);function n(e){a.call(this,e),this.enc="pem"}i(n,a),t.exports=n,n.prototype.encode=function(e,t){let r=a.prototype.encode.call(this,e).toString("base64"),i=["-----BEGIN "+t.label+"-----"];for(let e=0;e<r.length;e+=64)i.push(r.slice(e,e+64));return i.push("-----END "+t.label+"-----"),i.join("\n")}},642134,(e,t,r)=>{"use strict";r.der=e.r(970738),r.pem=e.r(671153)},229677,(e,t,r)=>{"use strict";let i=e.r(966397),a=e.r(917397),n=e.r(644833).DecoderBuffer,s=e.r(524283),o=e.r(433689);function l(e){this.enc="der",this.name=e.name,this.entity=e,this.tree=new u,this.tree._init(e.body)}function u(e){s.call(this,"der",e)}function c(e,t){let r=e.readUInt8(t);if(e.isError(r))return r;let i=o.tagClass[r>>6],a=(32&r)==0;if((31&r)==31){let i=r;for(r=0;(128&i)==128;){if(i=e.readUInt8(t),e.isError(i))return i;r<<=7,r|=127&i}}else r&=31;let n=o.tag[r];return{cls:i,primitive:a,tag:r,tagStr:n}}function d(e,t,r){let i=e.readUInt8(r);if(e.isError(i))return i;if(!t&&128===i)return null;if((128&i)==0)return i;let a=127&i;if(a>4)return e.error("length octect is too long");i=0;for(let t=0;t<a;t++){i<<=8;let t=e.readUInt8(r);if(e.isError(t))return t;i|=t}return i}t.exports=l,l.prototype.decode=function(e,t){return n.isDecoderBuffer(e)||(e=new n(e,t)),this.tree._decode(e,t)},i(u,s),u.prototype._peekTag=function(e,t,r){if(e.isEmpty())return!1;let i=e.save(),a=c(e,'Failed to peek tag: "'+t+'"');return e.isError(a)?a:(e.restore(i),a.tag===t||a.tagStr===t||a.tagStr+"of"===t||r)},u.prototype._decodeTag=function(e,t,r){let i=c(e,'Failed to decode tag of "'+t+'"');if(e.isError(i))return i;let a=d(e,i.primitive,'Failed to get length of "'+t+'"');if(e.isError(a))return a;if(!r&&i.tag!==t&&i.tagStr!==t&&i.tagStr+"of"!==t)return e.error('Failed to match tag: "'+t+'"');if(i.primitive||null!==a)return e.skip(a,'Failed to match body of: "'+t+'"');let n=e.save(),s=this._skipUntilEnd(e,'Failed to skip indefinite length body: "'+this.tag+'"');return e.isError(s)?s:(a=e.offset-n.offset,e.restore(n),e.skip(a,'Failed to match body of: "'+t+'"'))},u.prototype._skipUntilEnd=function(e,t){for(;;){let r,i=c(e,t);if(e.isError(i))return i;let a=d(e,i.primitive,t);if(e.isError(a))return a;if(r=i.primitive||null!==a?e.skip(a):this._skipUntilEnd(e,t),e.isError(r))return r;if("end"===i.tagStr)break}},u.prototype._decodeList=function(e,t,r,i){let a=[];for(;!e.isEmpty();){let t=this._peekTag(e,"end");if(e.isError(t))return t;let n=r.decode(e,"der",i);if(e.isError(n)&&t)break;a.push(n)}return a},u.prototype._decodeStr=function(e,t){if("bitstr"===t){let t=e.readUInt8();return e.isError(t)?t:{unused:t,data:e.raw()}}if("bmpstr"===t){let t=e.raw();if(t.length%2==1)return e.error("Decoding of string type: bmpstr length mismatch");let r="";for(let e=0;e<t.length/2;e++)r+=String.fromCharCode(t.readUInt16BE(2*e));return r}if("numstr"===t){let t=e.raw().toString("ascii");return this._isNumstr(t)?t:e.error("Decoding of string type: numstr unsupported characters")}if("octstr"===t)return e.raw();if("objDesc"===t)return e.raw();else if("printstr"===t){let t=e.raw().toString("ascii");return this._isPrintstr(t)?t:e.error("Decoding of string type: printstr unsupported characters")}else if(/str$/.test(t))return e.raw().toString();else return e.error("Decoding of string type: "+t+" unsupported")},u.prototype._decodeObjid=function(e,t,r){let i,a=[],n=0,s=0;for(;!e.isEmpty();)s=e.readUInt8(),n<<=7,n|=127&s,(128&s)==0&&(a.push(n),n=0);128&s&&a.push(n);let o=a[0]/40|0,l=a[0]%40;if(i=r?a:[o,l].concat(a.slice(1)),t){let e=t[i.join(" ")];void 0===e&&(e=t[i.join(".")]),void 0!==e&&(i=e)}return i},u.prototype._decodeTime=function(e,t){let r,i,a,n,s,o,l=e.raw().toString();if("gentime"===t)r=0|l.slice(0,4),i=0|l.slice(4,6),a=0|l.slice(6,8),n=0|l.slice(8,10),s=0|l.slice(10,12),o=0|l.slice(12,14);else{if("utctime"!==t)return e.error("Decoding "+t+" time is not supported yet");r=0|l.slice(0,2),i=0|l.slice(2,4),a=0|l.slice(4,6),n=0|l.slice(6,8),s=0|l.slice(8,10),o=0|l.slice(10,12),r=r<70?2e3+r:1900+r}return Date.UTC(r,i-1,a,n,s,o,0)},u.prototype._decodeNull=function(){return null},u.prototype._decodeBool=function(e){let t=e.readUInt8();return e.isError(t)?t:0!==t},u.prototype._decodeInt=function(e,t){let r=new a(e.raw());return t&&(r=t[r.toString(10)]||r),r},u.prototype._use=function(e,t){return"function"==typeof e&&(e=e(t)),e._getDecoder("der").tree}},594334,(e,t,r)=>{"use strict";let i=e.r(966397),a=e.r(832623).Buffer,n=e.r(229677);function s(e){n.call(this,e),this.enc="pem"}i(s,n),t.exports=s,s.prototype.decode=function(e,t){let r=e.toString().split(/[\r\n]+/g),i=t.label.toUpperCase(),s=/^-----(BEGIN|END) ([^-]+)-----$/,o=-1,l=-1;for(let e=0;e<r.length;e++){let t=r[e].match(s);if(null!==t&&t[2]===i)if(-1===o){if("BEGIN"!==t[1])break;o=e}else{if("END"!==t[1])break;l=e;break}}if(-1===o||-1===l)throw Error("PEM section not found for: "+i);let u=r.slice(o+1,l).join("");u.replace(/[^a-z0-9+/=]+/gi,"");let c=a.from(u,"base64");return n.prototype.decode.call(this,c,t)}},88855,(e,t,r)=>{"use strict";r.der=e.r(229677),r.pem=e.r(594334)},181713,(e,t,r)=>{"use strict";let i=e.r(642134),a=e.r(88855),n=e.r(966397);function s(e,t){this.name=e,this.body=t,this.decoders={},this.encoders={}}r.define=function(e,t){return new s(e,t)},s.prototype._createNamed=function(e){let t=this.name;function r(e){this._initNamed(e,t)}return n(r,e),r.prototype._initNamed=function(t,r){e.call(this,t,r)},new r(this)},s.prototype._getDecoder=function(e){return e=e||"der",this.decoders.hasOwnProperty(e)||(this.decoders[e]=this._createNamed(a[e])),this.decoders[e]},s.prototype.decode=function(e,t,r){return this._getDecoder(t).decode(e,r)},s.prototype._getEncoder=function(e){return e=e||"der",this.encoders.hasOwnProperty(e)||(this.encoders[e]=this._createNamed(i[e])),this.encoders[e]},s.prototype.encode=function(e,t,r){return this._getEncoder(t).encode(e,r)}},356767,(e,t,r)=>{"use strict";r.Reporter=e.r(857406).Reporter,r.DecoderBuffer=e.r(644833).DecoderBuffer,r.EncoderBuffer=e.r(644833).EncoderBuffer,r.Node=e.r(524283)},434299,(e,t,r)=>{"use strict";r._reverse=function(e){let t={};return Object.keys(e).forEach(function(r){(0|r)==r&&(r|=0),t[e[r]]=r}),t},r.der=e.r(433689)},572257,(e,t,r)=>{"use strict";r.bignum=e.r(917397),r.define=e.r(181713).define,r.base=e.r(356767),r.constants=e.r(434299),r.decoders=e.r(88855),r.encoders=e.r(642134)},41949,(e,t,r)=>{var i=e.r(223469).Buffer,a=e.r(688947);function n(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=i.alloc(0),this;if("function"==typeof e.pipe)return this.buffer=i.alloc(0),e.pipe(this),this;if(e.length||"object"==typeof e)return this.buffer=e,this.writable=!1,process.nextTick((function(){this.emit("end",e),this.readable=!1,this.emit("close")}).bind(this)),this;throw TypeError("Unexpected data type ("+typeof e+")")}e.r(224361).inherits(n,a),n.prototype.write=function(e){this.buffer=i.concat([this.buffer,i.from(e)]),this.emit("data",e)},n.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1},t.exports=n},465880,(e,t,r)=>{"use strict";function i(e){return(e/8|0)+ +(e%8!=0)}var a={ES256:i(256),ES384:i(384),ES512:i(521)};t.exports=function(e){var t=a[e];if(t)return t;throw Error('Unknown algorithm "'+e+'"')}},732955,(e,t,r)=>{"use strict";var i=e.r(223469).Buffer,a=e.r(465880);function n(e){if(i.isBuffer(e))return e;if("string"==typeof e)return i.from(e,"base64");throw TypeError("ECDSA signature must be a Base64 string or a Buffer")}function s(e,t,r){for(var i=0;t+i<r&&0===e[t+i];)++i;return e[t+i]>=128&&--i,i}t.exports={derToJose:function(e,t){e=n(e);var r=a(t),s=r+1,o=e.length,l=0;if(48!==e[l++])throw Error('Could not find expected "seq"');var u=e[l++];if(129===u&&(u=e[l++]),o-l<u)throw Error('"seq" specified length of "'+u+'", only "'+(o-l)+'" remaining');if(2!==e[l++])throw Error('Could not find expected "int" for "r"');var c=e[l++];if(o-l-2<c)throw Error('"r" specified length of "'+c+'", only "'+(o-l-2)+'" available');if(s<c)throw Error('"r" specified length of "'+c+'", max of "'+s+'" is acceptable');var d=l;if(l+=c,2!==e[l++])throw Error('Could not find expected "int" for "s"');var p=e[l++];if(o-l!==p)throw Error('"s" specified length of "'+p+'", expected "'+(o-l)+'"');if(s<p)throw Error('"s" specified length of "'+p+'", max of "'+s+'" is acceptable');var h=l;if((l+=p)!==o)throw Error('Expected to consume entire buffer, but "'+(o-l)+'" bytes remain');var m=r-c,f=r-p,g=i.allocUnsafe(m+c+f+p);for(l=0;l<m;++l)g[l]=0;e.copy(g,l,d+Math.max(-m,0),d+c),l=r;for(var y=l;l<y+f;++l)g[l]=0;return e.copy(g,l,h+Math.max(-f,0),h+p),g=(g=g.toString("base64")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")},joseToDer:function(e,t){e=n(e);var r=a(t),o=e.length;if(o!==2*r)throw TypeError('"'+t+'" signatures must be "'+2*r+'" bytes, saw "'+o+'"');var l=s(e,0,r),u=s(e,r,e.length),c=r-l,d=r-u,p=2+c+1+1+d,h=p<128,m=i.allocUnsafe((h?2:3)+p),f=0;return m[f++]=48,h?m[f++]=p:(m[f++]=129,m[f++]=255&p),m[f++]=2,m[f++]=c,l<0?(m[f++]=0,f+=e.copy(m,f,0,r)):f+=e.copy(m,f,l,r),m[f++]=2,m[f++]=d,u<0?(m[f++]=0,e.copy(m,f,r)):e.copy(m,f,r+u),m}}},922691,(e,t,r)=>{"use strict";var i=e.r(500874).Buffer,a=e.r(500874).SlowBuffer;function n(e,t){if(!i.isBuffer(e)||!i.isBuffer(t)||e.length!==t.length)return!1;for(var r=0,a=0;a<e.length;a++)r|=e[a]^t[a];return 0===r}t.exports=n,n.install=function(){i.prototype.equal=a.prototype.equal=function(e){return n(this,e)}};var s=i.prototype.equal,o=a.prototype.equal;n.restore=function(){i.prototype.equal=s,a.prototype.equal=o}},757067,(e,t,r)=>{var i,a=e.r(223469).Buffer,n=e.r(254799),s=e.r(732955),o=e.r(224361),l="secret must be a string or buffer",u="key must be a string or a buffer",c="function"==typeof n.createPublicKey;function d(e){if(!a.isBuffer(e)&&"string"!=typeof e&&(!c||"object"!=typeof e||"string"!=typeof e.type||"string"!=typeof e.asymmetricKeyType||"function"!=typeof e.export))throw f(u)}function p(e){if(!a.isBuffer(e)&&"string"!=typeof e&&"object"!=typeof e)throw f("key must be a string, a buffer or an object")}function h(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function m(e){var t=4-(e=e.toString()).length%4;if(4!==t)for(var r=0;r<t;++r)e+="=";return e.replace(/\-/g,"+").replace(/_/g,"/")}function f(e){var t=[].slice.call(arguments,1);return TypeError(o.format.bind(o,e).apply(null,t))}function g(e){var t;return t=e,a.isBuffer(t)||"string"==typeof t||(e=JSON.stringify(e)),e}function y(e){return function(t,r){!function(e){if(!a.isBuffer(e)){if("string"!=typeof e){if(!c||"object"!=typeof e||"secret"!==e.type||"function"!=typeof e.export)throw f(l)}}}(r),t=g(t);var i=n.createHmac("sha"+e,r);return h((i.update(t),i.digest("base64")))}}c&&(u+=" or a KeyObject",l+="or a KeyObject");var w="timingSafeEqual"in n?function(e,t){return e.byteLength===t.byteLength&&n.timingSafeEqual(e,t)}:function(t,r){return i||(i=e.r(922691)),i(t,r)};function b(e){return function(t,r,i){var n=y(e)(t,i);return w(a.from(r),a.from(n))}}function v(e){return function(t,r){p(r),t=g(t);var i=n.createSign("RSA-SHA"+e);return h((i.update(t),i.sign(r,"base64")))}}function k(e){return function(t,r,i){d(i),t=g(t),r=m(r);var a=n.createVerify("RSA-SHA"+e);return a.update(t),a.verify(i,r,"base64")}}function S(e){return function(t,r){p(r),t=g(t);var i=n.createSign("RSA-SHA"+e);return h((i.update(t),i.sign({key:r,padding:n.constants.RSA_PKCS1_PSS_PADDING,saltLength:n.constants.RSA_PSS_SALTLEN_DIGEST},"base64")))}}function E(e){return function(t,r,i){d(i),t=g(t),r=m(r);var a=n.createVerify("RSA-SHA"+e);return a.update(t),a.verify({key:i,padding:n.constants.RSA_PKCS1_PSS_PADDING,saltLength:n.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function I(e){var t=v(e);return function(){var r=t.apply(null,arguments);return s.derToJose(r,"ES"+e)}}function x(e){var t=k(e);return function(r,i,a){return t(r,i=s.joseToDer(i,"ES"+e).toString("base64"),a)}}function A(){return function(){return""}}function _(){return function(e,t){return""===t}}t.exports=function(e){var t=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!t)throw f('"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".',e);var r=(t[1]||t[3]).toLowerCase(),i=t[2];return{sign:({hs:y,rs:v,ps:S,es:I,none:A})[r](i),verify:({hs:b,rs:k,ps:E,es:x,none:_})[r](i)}}},576872,(e,t,r)=>{var i=e.r(500874).Buffer;t.exports=function(e){return"string"==typeof e?e:"number"==typeof e||i.isBuffer(e)?e.toString():JSON.stringify(e)}},614743,(e,t,r)=>{var i=e.r(223469).Buffer,a=e.r(41949),n=e.r(757067),s=e.r(688947),o=e.r(576872),l=e.r(224361);function u(e,t){return i.from(e,t).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function c(e){var t,r,i,a=e.header,s=e.payload,c=e.secret||e.privateKey,d=e.encoding,p=n(a.alg),h=(t=(t=d)||"utf8",r=u(o(a),"binary"),i=u(o(s),t),l.format("%s.%s",r,i)),m=p.sign(h,c);return l.format("%s.%s",h,m)}function d(e){var t=e.secret;if(t=null==(t=null==t?e.privateKey:t)?e.key:t,!0===/^hs/i.test(e.header.alg)&&null==t)throw TypeError("secret must be a string or buffer or a KeyObject");var r=new a(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=r,this.payload=new a(e.payload),this.secret.once("close",(function(){!this.payload.writable&&this.readable&&this.sign()}).bind(this)),this.payload.once("close",(function(){!this.secret.writable&&this.readable&&this.sign()}).bind(this))}l.inherits(d,s),d.prototype.sign=function(){try{var e=c({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}},d.sign=c,t.exports=d},148233,(e,t,r)=>{var i=e.r(223469).Buffer,a=e.r(41949),n=e.r(757067),s=e.r(688947),o=e.r(576872),l=e.r(224361),u=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function c(e){var t=e.split(".",1)[0],r=i.from(t,"base64").toString("binary");if("[object Object]"===Object.prototype.toString.call(r))return r;try{return JSON.parse(r)}catch(e){return}}function d(e){return e.split(".")[2]}function p(e){return u.test(e)&&!!c(e)}function h(e,t,r){if(!t){var i=Error("Missing algorithm parameter for jws.verify");throw i.code="MISSING_ALGORITHM",i}var a=d(e=o(e)),s=e.split(".",2).join(".");return n(t).verify(s,a,r)}function m(e,t){if(t=t||{},!p(e=o(e)))return null;var r,a,n=c(e);if(!n)return null;var s=(r=r||"utf8",a=e.split(".")[1],i.from(a,"base64").toString(r));return("JWT"===n.typ||t.json)&&(s=JSON.parse(s,t.encoding)),{header:n,payload:s,signature:d(e)}}function f(e){var t=(e=e||{}).secret;if(t=null==(t=null==t?e.publicKey:t)?e.key:t,!0===/^hs/i.test(e.algorithm)&&null==t)throw TypeError("secret must be a string or buffer or a KeyObject");var r=new a(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=r,this.signature=new a(e.signature),this.secret.once("close",(function(){!this.signature.writable&&this.readable&&this.verify()}).bind(this)),this.signature.once("close",(function(){!this.secret.writable&&this.readable&&this.verify()}).bind(this))}l.inherits(f,s),f.prototype.verify=function(){try{var e=h(this.signature.buffer,this.algorithm,this.key.buffer),t=m(this.signature.buffer,this.encoding);return this.emit("done",e,t),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}},f.decode=m,f.isValid=p,f.verify=h,t.exports=f},258184,(e,t,r)=>{var i=e.r(614743),a=e.r(148233);r.ALGORITHMS=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"],r.sign=i.sign,r.verify=a.verify,r.decode=a.decode,r.isValid=a.isValid,r.createSign=function(e){return new i(e)},r.createVerify=function(e){return new a(e)}},162232,(e,t,r)=>{"use strict";let i={};i.supportedContentEncodings={AES_GCM:"aesgcm",AES_128_GCM:"aes128gcm"},i.supportedUrgency={VERY_LOW:"very-low",LOW:"low",NORMAL:"normal",HIGH:"high"},t.exports=i},341220,(e,t,r)=>{"use strict";t.exports={validate:function(e){return/^[A-Za-z0-9\-_]+$/.test(e)}}},114916,(e,t,r)=>{"use strict";let i=e.r(254799),a=e.r(572257),n=e.r(258184),{URL:s}=e.r(792509),o=e.r(162232),l=e.r(341220),u=a.define("ECPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").explicit(0).objid().optional(),this.key("publicKey").explicit(1).bitstr().optional())});function c(e){if(!e)throw Error("No subject set in vapidDetails.subject.");if("string"!=typeof e||0===e.length)throw Error("The subject value must be a string containing an https: URL or mailto: address. "+e);let t=null;try{t=new s(e)}catch(t){throw Error("Vapid subject is not a valid URL. "+e)}if(!["https:","mailto:"].includes(t.protocol))throw Error("Vapid subject is not an https: or mailto: URL. "+e);"localhost"===t.hostname&&console.warn("Vapid subject points to a localhost web URI, which is unsupported by Apple's push notification server and will result in a BadJwtToken error when sending notifications.")}function d(e){if(!e)throw Error("No key set vapidDetails.publicKey");if("string"!=typeof e)throw Error("Vapid public key is must be a URL safe Base 64 encoded string.");if(!l.validate(e))throw Error('Vapid public key must be a URL safe Base 64 (without "=")');if(65!==(e=Buffer.from(e,"base64url")).length)throw Error("Vapid public key should be 65 bytes long when decoded.")}function p(e){if(!e)throw Error("No key set in vapidDetails.privateKey");if("string"!=typeof e)throw Error("Vapid private key must be a URL safe Base 64 encoded string.");if(!l.validate(e))throw Error('Vapid private key must be a URL safe Base 64 (without "=")');if(32!==(e=Buffer.from(e,"base64url")).length)throw Error("Vapid private key should be 32 bytes long when decoded.")}function h(e){let t=new Date;return t.setSeconds(t.getSeconds()+e),Math.floor(t.getTime()/1e3)}function m(e){if(!Number.isInteger(e))throw Error("`expiration` value must be a number");if(e<0)throw Error("`expiration` must be a positive integer");if(e>=h(86400))throw Error("`expiration` value is greater than maximum of 24 hours")}t.exports={generateVAPIDKeys:function(){let e=i.createECDH("prime256v1");e.generateKeys();let t=e.getPublicKey(),r=e.getPrivateKey();if(r.length<32){let e=Buffer.alloc(32-r.length);e.fill(0),r=Buffer.concat([e,r])}if(t.length<65){let e=Buffer.alloc(65-t.length);e.fill(0),t=Buffer.concat([e,t])}return{publicKey:t.toString("base64url"),privateKey:r.toString("base64url")}},getFutureExpirationTimestamp:h,getVapidHeaders:function(e,t,r,i,a,l){var f;if(!e)throw Error("No audience could be generated for VAPID.");if("string"!=typeof e||0===e.length)throw Error("The audience value must be a string containing the origin of a push service. "+e);try{new s(e)}catch(t){throw Error("VAPID audience is not a url. "+e)}c(t),d(r),p(i),i=Buffer.from(i,"base64url"),l?m(l):l=h(43200);let g={aud:e,exp:l,sub:t},y=n.sign({header:{typ:"JWT",alg:"ES256"},payload:g,privateKey:(f=i,u.encode({version:1,privateKey:f,parameters:[1,2,840,10045,3,1,7]},"pem",{label:"EC PRIVATE KEY"}))});if(a===o.supportedContentEncodings.AES_128_GCM)return{Authorization:"vapid t="+y+", k="+r};if(a===o.supportedContentEncodings.AES_GCM)return{Authorization:"WebPush "+y,"Crypto-Key":"p256ecdsa="+r};throw Error("Unsupported encoding type specified.")},validateSubject:c,validatePublicKey:d,validatePrivateKey:p,validateExpiration:m}},792320,(e,t,r)=>{"use strict";var i,a=e.r(254799),n="aes-128-gcm",s={aes128gcm:1,aesgcm:2},o="encrypt",l="decrypt";function u(e){return"string"==typeof e?Buffer.from(e,"base64url"):e}function c(e,t){var r=a.createHmac("sha256",e);return r.update(t),r.digest()}function d(e,t){return i("salt",e),i("ikm",t),i("extract",c(e,t))}function p(e,t,r){i("prk",e),i("info",t);var a=Buffer.alloc(0),n=Buffer.alloc(0);t=Buffer.from(t,"ascii");for(var s=0,o=Buffer.alloc(1);a.length<r;)o.writeUIntBE(++s,0,1),n=c(e,Buffer.concat([n,t,o])),a=Buffer.concat([a,n]);return i("expand",a.slice(0,r))}function h(e,t){var r=Buffer.concat([Buffer.from("Content-Encoding: "+e+"\0","ascii"),t]);return i("info "+e,r),r}function m(e){var t=Buffer.concat([Buffer.alloc(2),e]);return t.writeUIntBE(e.length,0,2),t}function f(e,t,r){if(!e.salt)throw Error("must include a salt parameter for "+e.version);if("aesgcm"===e.version){var a,n,s,u=function(e,t){var r,a,n,s={secret:null,context:Buffer.alloc(0)};if(e.key){if(s.secret=e.key,16!==s.secret.length)throw Error("An explicit key must be 16 bytes")}else e.dh?s=function(e,t){var r,i,a=e.privateKey;if(t===o)r=a.getPublicKey(),i=e.dh;else if(t===l)r=e.dh,i=a.getPublicKey();else throw Error("Unknown mode only "+o+" and "+l+" supported");return{secret:a.computeSecret(e.dh),context:Buffer.concat([Buffer.from(e.keylabel,"ascii"),Buffer.from([0]),m(i),m(r)])}}(e,t):(e.keyid,s.secret=e.keymap[e.keyid]);if(!s.secret)throw Error("Unable to determine key");return i("secret",s.secret),i("context",s.context),e.authSecret&&(s.secret=(r=e.authSecret,a=s.secret,n=h("auth",Buffer.alloc(0)),p(d(r,a),n,32)),i("authsecret",s.secret)),s}(e,t);a=h("aesgcm",u.context),n=h("nonce",u.context),s=u.secret}else if("aes128gcm"===e.version)a=Buffer.from("Content-Encoding: aes128gcm\0"),n=Buffer.from("Content-Encoding: nonce\0"),s=function(e,t,r){if(r&&"function"!=typeof r)throw Error("Callback is not a function");if(e.key){if(16!==e.key.length)throw Error("An explicit key must be 16 bytes");return i("secret key",e.key)}if(!e.privateKey){if(r)var a=r(e.keyid);else var a=e.keymap&&e.keymap[e.keyid];if(!a)throw Error('No saved key (keyid: "'+e.keyid+'")');return a}return function(e,t){var r,a,n,s,u,c;if(!e.authSecret)throw Error("No authentication secret for webpush");if(i("authsecret",e.authSecret),t===o)a=e.privateKey.getPublicKey(),r=n=e.dh;else if(t===l)r=a=e.keyid,n=e.privateKey.getPublicKey();else throw Error("Unknown mode only "+o+" and "+l+" supported");return i("remote pubkey",r),i("sender pubkey",a),i("receiver pubkey",n),i("secret dh",(s=e.authSecret,u=e.privateKey.computeSecret(r),c=Buffer.concat([Buffer.from("WebPush: info\0"),n,a]),p(d(s,u),c,32)))}(e,t)}(e,t,r);else throw Error("Unable to set context for mode "+e.version);var c=d(e.salt,s),f={key:p(c,a,16),nonce:p(c,n,12)};return i("key",f.key),i("nonce base",f.nonce),f}function g(e){var t={};t.version=e.version||"aes128gcm",t.rs=parseInt(e.rs,10),isNaN(t.rs)&&(t.rs=4096);var r=s[t.version];if("aes128gcm"===t.version&&(r+=16),t.rs<=r)throw Error("The rs parameter has to be greater than "+r);if(e.salt&&(t.salt=u(e.salt),16!==t.salt.length))throw Error("The salt parameter must be 16 bytes");return t.keyid=e.keyid,e.key?t.key=u(e.key):(t.privateKey=e.privateKey,t.privateKey||(t.keymap=e.keymap),"aes128gcm"!==t.version&&(t.keylabel=e.keylabel||"P-256"),e.dh&&(t.dh=u(e.dh))),e.authSecret&&(t.authSecret=u(e.authSecret)),t}function y(e,t){var r=Buffer.from(e),a=r.readUIntBE(r.length-6,6);return r.writeUIntBE(((a^t)&0xffffff)+((a/0x1000000^t/0x1000000)&0xffffff)*0x1000000,r.length-6,6),i("nonce"+t,r),r}i="1"===process.env.ECE_KEYLOG?function(e,t){return console.warn(e+" ["+t.length+"]: "+t.toString("base64url")),t}:function(e,t){return t},t.exports={decrypt:function(e,t,r){var o=g(t);if("aes128gcm"===o.version){var u,c,d=(c=(u=e).readUIntBE(20,1),o.salt=u.slice(0,16),o.rs=u.readUIntBE(16,4),o.keyid=u.slice(21,21+c),21+c);e=e.slice(d)}var p=f(o,l,r),h=0,m=Buffer.alloc(0),w=o.rs;"aes128gcm"!==o.version&&(w+=16);for(var b=0;h<e.length;++b){var v=h+w;if("aes128gcm"!==o.version&&v===e.length)throw Error("Truncated payload");if((v=Math.min(v,e.length))-h<=16)throw Error("Invalid block: too small at "+b);var k=function(e,t,r,o,l){i("decrypt",r);var u=y(e.nonce,t),c=a.createDecipheriv(n,e.key,u);c.setAuthTag(r.slice(r.length-16));var d=c.update(r.slice(0,r.length-16));if(d=Buffer.concat([d,c.final()]),i("decrypted",d),"aes128gcm"!==o.version)return function(e,t){var r=s[t],a=e.readUIntBE(0,r);if(a+r>e.length)throw Error("padding exceeds block size");i("padding",e.slice(0,r+a));var n=Buffer.alloc(a);if(n.fill(0),0!==n.compare(e.slice(r,r+a)))throw Error("invalid padding");return e.slice(r+a)}(d,o.version);for(var p=d,h=p.length-1;h>=0;){if(p[h]){if(l){if(2!==p[h])throw Error("last record needs to start padding with a 2")}else if(1!==p[h])throw Error("last record needs to start padding with a 2");return p.slice(0,h)}--h}throw Error("all zero plaintext")}(p,b,e.slice(h,v),o,v>=e.length);m=Buffer.concat([m,k]),h=v}return m},encrypt:function(e,t,r){if(!Buffer.isBuffer(e))throw Error("buffer argument must be a Buffer");var l,u=g(t);u.salt||(u.salt=a.randomBytes(16)),"aes128gcm"===u.version?(u.privateKey&&!u.keyid&&(u.keyid=u.privateKey.getPublicKey()),l=function(e){var t=Buffer.alloc(5),r=Buffer.from(e.keyid||[]);if(r.length>255)throw Error("keyid is too large");return t.writeUIntBE(e.rs,0,4),t.writeUIntBE(r.length,4,1),Buffer.concat([e.salt,t,r])}(u)):l=Buffer.alloc(0);var c=f(u,o,r),d=0,p=s[u.version],h=p;"aes128gcm"===u.version&&(h+=16);for(var m=isNaN(parseInt(t.pad,10))?0:parseInt(t.pad,10),w=0,b=!1;!b;){var v=Math.min(u.rs-h-1,m);"aes128gcm"!==u.version&&(v=Math.min((1<<8*p)-1,v)),m>0&&0===v&&++v,m-=v;var k=d+u.rs-h-v;b=(b="aes128gcm"!==u.version?k>e.length:k>=e.length)&&m<=0;var S=function(e,t,r,o,l,u){i("encrypt",r),o=o||0;var c=y(e.nonce,t),d=a.createCipheriv(n,e.key,c),p=[],h=s[l.version],m=Buffer.alloc(o+h);if(m.fill(0),"aes128gcm"!==l.version){if(m.writeUIntBE(o,0,h),i("padding",m),p.push(d.update(m)),p.push(d.update(r)),!u&&m.length+r.length<l.rs)throw Error("Unable to pad to record size")}else p.push(d.update(r)),m.writeUIntBE(u?2:1,0,1),i("padding",m),p.push(d.update(m));d.final();var f=d.getAuthTag();if(16!==f.length)throw Error("invalid tag generated");return p.push(f),i("encrypted",Buffer.concat(p))}(c,w,e.slice(d,k),v,u,b);l=Buffer.concat([l,S]),d=k,++w}return l}}},44703,(e,t,r)=>{"use strict";let i=e.r(254799),a=e.r(792320);t.exports={encrypt:function(e,t,r,n){if(!e)throw Error("No user public key provided for encryption.");if("string"!=typeof e)throw Error("The subscription p256dh value must be a string.");if(65!==Buffer.from(e,"base64url").length)throw Error("The subscription p256dh value should be 65 bytes long.");if(!t)throw Error("No user auth provided for encryption.");if("string"!=typeof t)throw Error("The subscription auth key must be a string.");if(Buffer.from(t,"base64url").length<16)throw Error("The subscription auth key should be at least 16 bytes long");if("string"!=typeof r&&!Buffer.isBuffer(r))throw Error("Payload must be either a string or a Node Buffer.");("string"==typeof r||r instanceof String)&&(r=Buffer.from(r));let s=i.createECDH("prime256v1"),o=s.generateKeys(),l=i.randomBytes(16).toString("base64url"),u=a.encrypt(r,{version:n,dh:e,privateKey:s,salt:l,authSecret:t});return{localPublicKey:o,salt:l,cipherText:u}}}},894635,(e,t,r)=>{"use strict";var i=e.e&&e.e.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var a=Object.getOwnPropertyDescriptor(t,r);(!a||("get"in a?!t.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,a)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),a=e.e&&e.e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=e.e&&e.e.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return a(t,e),t};Object.defineProperty(r,"__esModule",{value:!0}),r.req=r.json=r.toBuffer=void 0;let s=n(e.r(921517)),o=n(e.r(524836));async function l(e){let t=0,r=[];for await(let i of e)t+=i.length,r.push(i);return Buffer.concat(r,t)}r.toBuffer=l,r.json=async function(e){let t=(await l(e)).toString("utf8");try{return JSON.parse(t)}catch(e){throw e.message+=` (input: ${t})`,e}},r.req=function(e,t={}){let r=(("string"==typeof e?e:e.href).startsWith("https:")?o:s).request(e,t),i=new Promise((e,t)=>{r.once("response",e).once("error",t).end()});return r.then=i.then.bind(i),r}},326504,(e,t,r)=>{"use strict";var i=e.e&&e.e.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var a=Object.getOwnPropertyDescriptor(t,r);(!a||("get"in a?!t.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,a)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),a=e.e&&e.e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=e.e&&e.e.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return a(t,e),t},s=e.e&&e.e.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||i(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),r.Agent=void 0;let o=n(e.r(504446)),l=n(e.r(921517)),u=e.r(524836);s(e.r(894635),r);let c=Symbol("AgentBaseInternalState");class d extends l.Agent{constructor(e){super(e),this[c]={}}isSecureEndpoint(e){if(e){if("boolean"==typeof e.secureEndpoint)return e.secureEndpoint;if("string"==typeof e.protocol)return"https:"===e.protocol}let{stack:t}=Error();return"string"==typeof t&&t.split("\n").some(e=>-1!==e.indexOf("(https.js:")||-1!==e.indexOf("node:https:"))}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let t=new o.Socket({writable:!1});return this.sockets[e].push(t),this.totalSocketCount++,t}decrementSockets(e,t){if(!this.sockets[e]||null===t)return;let r=this.sockets[e],i=r.indexOf(t);-1!==i&&(r.splice(i,1),this.totalSocketCount--,0===r.length&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?u.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,t,r){let i={...t,secureEndpoint:this.isSecureEndpoint(t)},a=this.getName(i),n=this.incrementSockets(a);Promise.resolve().then(()=>this.connect(e,i)).then(s=>{if(this.decrementSockets(a,n),s instanceof l.Agent)try{return s.addRequest(e,i)}catch(e){return r(e)}this[c].currentSocket=s,super.createSocket(e,t,r)},e=>{this.decrementSockets(a,n),r(e)})}createConnection(){let e=this[c].currentSocket;if(this[c].currentSocket=void 0,!e)throw Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[c].defaultPort??("https:"===this.protocol?443:80)}set defaultPort(e){this[c]&&(this[c].defaultPort=e)}get protocol(){return this[c].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[c]&&(this[c].protocol=e)}}r.Agent=d},377557,(e,t,r)=>{"use strict";var i=e.e&&e.e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.parseProxyResponse=void 0;let a=(0,i(e.r(817293)).default)("https-proxy-agent:parse-proxy-response");r.parseProxyResponse=function(e){return new Promise((t,r)=>{let i=0,n=[];function s(){let l=e.read();l?function(l){n.push(l),i+=l.length;let u=Buffer.concat(n,i),c=u.indexOf("\r\n\r\n");if(-1===c){a("have not received end of HTTP headers yet..."),s();return}let d=u.slice(0,c).toString("ascii").split("\r\n"),p=d.shift();if(!p)return e.destroy(),r(Error("No header received from proxy CONNECT response"));let h=p.split(" "),m=+h[1],f=h.slice(2).join(" "),g={};for(let t of d){if(!t)continue;let i=t.indexOf(":");if(-1===i)return e.destroy(),r(Error(`Invalid header from proxy CONNECT response: "${t}"`));let a=t.slice(0,i).toLowerCase(),n=t.slice(i+1).trimStart(),s=g[a];"string"==typeof s?g[a]=[s,n]:Array.isArray(s)?s.push(n):g[a]=n}a("got proxy server response: %o %o",p,g),o(),t({connect:{statusCode:m,statusText:f,headers:g},buffered:u})}(l):e.once("readable",s)}function o(){e.removeListener("end",l),e.removeListener("error",u),e.removeListener("readable",s)}function l(){o(),a("onend"),r(Error("Proxy connection ended before receiving CONNECT response"))}function u(e){o(),a("onerror %o",e),r(e)}e.on("error",u),e.on("end",l),s()})}},648630,(e,t,r)=>{"use strict";var i=e.e&&e.e.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var a=Object.getOwnPropertyDescriptor(t,r);(!a||("get"in a?!t.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,a)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),a=e.e&&e.e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=e.e&&e.e.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return a(t,e),t},s=e.e&&e.e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.HttpsProxyAgent=void 0;let o=n(e.r(504446)),l=n(e.r(755004)),u=s(e.r(449719)),c=s(e.r(817293)),d=e.r(326504),p=e.r(792509),h=e.r(377557),m=(0,c.default)("https-proxy-agent"),f=e=>void 0===e.servername&&e.host&&!o.isIP(e.host)?{...e,servername:e.host}:e;class g extends d.Agent{constructor(e,t){super(t),this.options={path:void 0},this.proxy="string"==typeof e?new p.URL(e):e,this.proxyHeaders=t?.headers??{},m("Creating new HttpsProxyAgent instance: %o",this.proxy.href);const r=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),i=this.proxy.port?parseInt(this.proxy.port,10):"https:"===this.proxy.protocol?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...t?w(t,"headers"):null,host:r,port:i}}async connect(e,t){let r,{proxy:i}=this;if(!t.host)throw TypeError('No "host" provided');"https:"===i.protocol?(m("Creating `tls.Socket`: %o",this.connectOpts),r=l.connect(f(this.connectOpts))):(m("Creating `net.Socket`: %o",this.connectOpts),r=o.connect(this.connectOpts));let a="function"==typeof this.proxyHeaders?this.proxyHeaders():{...this.proxyHeaders},n=o.isIPv6(t.host)?`[${t.host}]`:t.host,s=`CONNECT ${n}:${t.port} HTTP/1.1\r
617
617
  `;if(i.username||i.password){let e=`${decodeURIComponent(i.username)}:${decodeURIComponent(i.password)}`;a["Proxy-Authorization"]=`Basic ${Buffer.from(e).toString("base64")}`}for(let e of(a.Host=`${n}:${t.port}`,a["Proxy-Connection"]||(a["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close"),Object.keys(a)))s+=`${e}: ${a[e]}\r
618
618
  `;let c=(0,h.parseProxyResponse)(r);r.write(`${s}\r
619
619
  `);let{connect:d,buffered:p}=await c;if(e.emit("proxyConnect",d),this.emit("proxyConnect",d,e),200===d.statusCode)return(e.once("socket",y),t.secureEndpoint)?(m("Upgrading socket connection to TLS"),l.connect({...w(f(t),"host","path","port"),socket:r})):r;r.destroy();let g=new o.Socket({writable:!1});return g.readable=!0,e.once("socket",e=>{m("Replaying proxy buffer for failed request"),(0,u.default)(e.listenerCount("data")>0),e.push(p),e.push(null)}),g}}function y(e){e.resume()}function w(e,...t){let r,i={};for(r in e)t.includes(r)||(i[r]=e[r]);return i}g.protocols=["http","https"],r.HttpsProxyAgent=g},361751,(e,t,r)=>{"use strict";function i(e,t,r,i,a){Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.message=e,this.statusCode=t,this.headers=r,this.body=i,this.endpoint=a}e.r(224361).inherits(i,Error),t.exports=i},9578,(e,t,r)=>{"use strict";let i,a=e.r(792509),n=e.r(524836),s=e.r(361751),o=e.r(114916),l=e.r(44703),u=e.r(162232),c=e.r(341220),d="";function p(){}p.prototype.setGCMAPIKey=function(e){if(null===e){d=null;return}if(void 0===e||"string"!=typeof e||0===e.length)throw Error("The GCM API Key should be a non-empty string or null.");d=e},p.prototype.setVapidDetails=function(e,t,r){if(1==arguments.length&&null===arguments[0]){i=null;return}o.validateSubject(e),o.validatePublicKey(t),o.validatePrivateKey(r),i={subject:e,publicKey:t,privateKey:r}},p.prototype.generateRequestDetails=function(e,t,r){let s,p,h,m;if(!e||!e.endpoint)throw Error("You must pass in a subscription with at least an endpoint.");if("string"!=typeof e.endpoint||0===e.endpoint.length)throw Error("The subscription endpoint must be a string with a valid URL.");if(t&&("object"!=typeof e||!e.keys||!e.keys.p256dh||!e.keys.auth))throw Error("To send a message with a payload, the subscription must have 'auth' and 'p256dh' keys.");let f=d,g=i,y=2419200,w={},b=u.supportedContentEncodings.AES_128_GCM,v=u.supportedUrgency.NORMAL;if(r){let e=["headers","gcmAPIKey","vapidDetails","TTL","contentEncoding","urgency","topic","proxy","agent","timeout"],t=Object.keys(r);for(let r=0;r<t.length;r+=1){let i=t[r];if(!e.includes(i))throw Error("'"+i+"' is an invalid option. The valid options are ['"+e.join("', '")+"'].")}if(r.headers){let e=Object.keys(w=r.headers).filter(function(e){return void 0!==r[e]});if(e.length>0)throw Error("Duplicated headers defined ["+e.join(",")+"]. Please either define the header in thetop level options OR in the 'headers' key.")}if(r.gcmAPIKey&&(f=r.gcmAPIKey),void 0!==r.vapidDetails&&(g=r.vapidDetails),void 0!==r.TTL&&(y=Number(r.TTL))<0)throw Error("TTL should be a number and should be at least 0");if(r.contentEncoding)if(r.contentEncoding===u.supportedContentEncodings.AES_128_GCM||r.contentEncoding===u.supportedContentEncodings.AES_GCM)b=r.contentEncoding;else throw Error("Unsupported content encoding specified.");if(r.urgency)if(r.urgency===u.supportedUrgency.VERY_LOW||r.urgency===u.supportedUrgency.LOW||r.urgency===u.supportedUrgency.NORMAL||r.urgency===u.supportedUrgency.HIGH)v=r.urgency;else throw Error("Unsupported urgency specified.");if(r.topic){if(!c.validate(r.topic))throw Error("Unsupported characters set use the URL or filename-safe Base64 characters set");if(r.topic.length>32)throw Error("use maximum of 32 characters from the URL or filename-safe Base64 characters set");s=r.topic}r.proxy&&("string"==typeof r.proxy||"string"==typeof r.proxy.host?p=r.proxy:console.warn("Attempt to use proxy option, but invalid type it should be a string or proxy options object.")),r.agent&&(r.agent instanceof n.Agent?(p&&console.warn("Agent option will be ignored because proxy option is defined."),h=r.agent):console.warn("Wrong type for the agent option, it should be an instance of https.Agent.")),"number"==typeof r.timeout&&(m=r.timeout)}void 0===y&&(y=2419200);let k={method:"POST",headers:{TTL:y}};Object.keys(w).forEach(function(e){k.headers[e]=w[e]});let S=null;if(t){let r=l.encrypt(e.keys.p256dh,e.keys.auth,t,b);k.headers["Content-Length"]=r.cipherText.length,k.headers["Content-Type"]="application/octet-stream",b===u.supportedContentEncodings.AES_128_GCM?k.headers["Content-Encoding"]=u.supportedContentEncodings.AES_128_GCM:b===u.supportedContentEncodings.AES_GCM&&(k.headers["Content-Encoding"]=u.supportedContentEncodings.AES_GCM,k.headers.Encryption="salt="+r.salt,k.headers["Crypto-Key"]="dh="+r.localPublicKey.toString("base64url")),S=r.cipherText}else k.headers["Content-Length"]=0;let E=e.endpoint.startsWith("https://android.googleapis.com/gcm/send"),I=e.endpoint.startsWith("https://fcm.googleapis.com/fcm/send");if(E)f?k.headers.Authorization="key="+f:console.warn("Attempt to send push notification to GCM endpoint, but no GCM key is defined. Please use setGCMApiKey() or add 'gcmAPIKey' as an option.");else if(g){let t=a.parse(e.endpoint),r=t.protocol+"//"+t.host,i=o.getVapidHeaders(r,g.subject,g.publicKey,g.privateKey,b);k.headers.Authorization=i.Authorization,b===u.supportedContentEncodings.AES_GCM&&(k.headers["Crypto-Key"]?k.headers["Crypto-Key"]+=";"+i["Crypto-Key"]:k.headers["Crypto-Key"]=i["Crypto-Key"])}else I&&f&&(k.headers.Authorization="key="+f);return k.headers.Urgency=v,s&&(k.headers.Topic=s),k.body=S,k.endpoint=e.endpoint,p&&(k.proxy=p),h&&(k.agent=h),m&&(k.timeout=m),k},p.prototype.sendNotification=function(t,r,i){let o;try{o=this.generateRequestDetails(t,r,i)}catch(e){return Promise.reject(e)}return new Promise(function(t,r){let i={},l=a.parse(o.endpoint);if(i.hostname=l.hostname,i.port=l.port,i.path=l.path,i.headers=o.headers,i.method=o.method,o.timeout&&(i.timeout=o.timeout),o.agent&&(i.agent=o.agent),o.proxy){let{HttpsProxyAgent:t}=e.r(648630);i.agent=new t(o.proxy)}let u=n.request(i,function(e){let i="";e.on("data",function(e){i+=e}),e.on("end",function(){e.statusCode<200||e.statusCode>299?r(new s("Received unexpected response code",e.statusCode,e.headers,i,o.endpoint)):t({statusCode:e.statusCode,body:i,headers:e.headers})})});o.timeout&&u.on("timeout",function(){u.destroy(Error("Socket timeout"))}),u.on("error",function(e){r(e)}),o.body&&u.write(o.body),u.end()})},t.exports=p},726355,(e,t,r)=>{"use strict";let i=e.r(114916),a=e.r(44703),n=e.r(9578),s=e.r(361751),o=e.r(162232),l=new n;t.exports={WebPushError:s,supportedContentEncodings:o.supportedContentEncodings,encrypt:a.encrypt,getVapidHeaders:i.getVapidHeaders,generateVAPIDKeys:i.generateVAPIDKeys,setGCMAPIKey:l.setGCMAPIKey,setVapidDetails:l.setVapidDetails,generateRequestDetails:l.generateRequestDetails,sendNotification:l.sendNotification.bind(l)}},887394,583801,700909,719961,e=>{"use strict";let t,r;e.i(805422);var i,a=e.i(694355);e.i(121717);var n=e.i(483024);e.i(396763);var s=e.i(925991);e.i(224174);var o=e.i(669602);e.i(250246);var l=e.i(104503),u=e.i(516785);e.i(107058);var c=e.i(695248),d=e.i(963910),p=e.i(112627);e.i(890564);var h=e.i(646462);e.i(151666);var m=e.i(126223),f=e.i(642983);e.i(115354);var g=e.i(149721);e.i(952128);var y=e.i(187963),w=e.i(666680),b=e.i(807055),v=e.i(514849),k=e.i(556690);function S(e){return"completed"===e||"failed"===e||"cancelled"===e}var E=e.i(865889);let I=Symbol("Let zodToJsonSchema decide on which parser to use"),x={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"};var A=e.i(117958);let _=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function C(e){if("openAi"!==e.target)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?_(t,e.currentPath):t.join("/")}}function R(e,t,r,i){i?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function T(e,t,r,i,a){e[t]=r,R(e,t,i,a)}function D(e,t){return Q(e.type._def,t)}let N=/^[cC][^\s-]{8,}$/,O=/^[0-9a-z]+$/,P=/^[0-9A-HJKMNP-TV-Z]{26}$/,$=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,U=()=>(void 0===r&&(r=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),r),B=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,j=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,L=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,q=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,M=/^[a-zA-Z0-9_-]{21}$/,F=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function K(e,t){let r={type:"string"};if(e.checks)for(let i of e.checks)switch(i.kind){case"min":T(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,i.value):i.value,i.message,t);break;case"max":T(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,i.value):i.value,i.message,t);break;case"email":switch(t.emailStrategy){case"format:email":H(r,"email",i.message,t);break;case"format:idn-email":H(r,"idn-email",i.message,t);break;case"pattern:zod":W(r,$,i.message,t)}break;case"url":H(r,"uri",i.message,t);break;case"uuid":H(r,"uuid",i.message,t);break;case"regex":W(r,i.regex,i.message,t);break;case"cuid":W(r,N,i.message,t);break;case"cuid2":W(r,O,i.message,t);break;case"startsWith":W(r,RegExp(`^${V(i.value,t)}`),i.message,t);break;case"endsWith":W(r,RegExp(`${V(i.value,t)}$`),i.message,t);break;case"datetime":H(r,"date-time",i.message,t);break;case"date":H(r,"date",i.message,t);break;case"time":H(r,"time",i.message,t);break;case"duration":H(r,"duration",i.message,t);break;case"length":T(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,i.value):i.value,i.message,t),T(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,i.value):i.value,i.message,t);break;case"includes":W(r,RegExp(V(i.value,t)),i.message,t);break;case"ip":"v6"!==i.version&&H(r,"ipv4",i.message,t),"v4"!==i.version&&H(r,"ipv6",i.message,t);break;case"base64url":W(r,q,i.message,t);break;case"jwt":W(r,F,i.message,t);break;case"cidr":"v6"!==i.version&&W(r,B,i.message,t),"v4"!==i.version&&W(r,j,i.message,t);break;case"emoji":W(r,U(),i.message,t);break;case"ulid":W(r,P,i.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":H(r,"binary",i.message,t);break;case"contentEncoding:base64":T(r,"contentEncoding","base64",i.message,t);break;case"pattern:zod":W(r,L,i.message,t)}break;case"nanoid":W(r,M,i.message,t)}return r}function V(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let r=0;r<e.length;r++)G.has(e[r])||(t+="\\"),t+=e[r];return t}(e):e}let G=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function H(e,t,r,i){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&i.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&i.errorMessages&&{errorMessage:{format:r}}})):T(e,"format",t,r,i)}function W(e,t,r,i){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&i.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:J(t,i),...r&&i.errorMessages&&{errorMessage:{pattern:r}}})):T(e,"pattern",J(t,i),r,i)}function J(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},i=r.i?e.source.toLowerCase():e.source,a="",n=!1,s=!1,o=!1;for(let e=0;e<i.length;e++){if(n){a+=i[e],n=!1;continue}if(r.i){if(s){if(i[e].match(/[a-z]/)){o?(a+=i[e],a+=`${i[e-2]}-${i[e]}`.toUpperCase(),o=!1):"-"===i[e+1]&&i[e+2]?.match(/[a-z]/)?(a+=i[e],o=!0):a+=`${i[e]}${i[e].toUpperCase()}`;continue}}else if(i[e].match(/[a-z]/)){a+=`[${i[e]}${i[e].toUpperCase()}]`;continue}}if(r.m){if("^"===i[e]){a+=`(^|(?<=[\r