@chief-clancy/terminal 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundle/clancy-autopilot.js +255 -0
- package/dist/bundle/clancy-implement.js +254 -0
- package/dist/hooks/clancy-branch-guard.js +1 -1
- package/dist/hooks/clancy-context-monitor.js +2 -2
- package/dist/hooks/clancy-credential-guard.js +2 -2
- package/dist/hooks/clancy-drift-detector.js +1 -1
- package/dist/hooks/clancy-post-compact.js +2 -2
- package/dist/runner/autopilot/entrypoint.d.ts +82 -0
- package/dist/runner/autopilot/entrypoint.d.ts.map +1 -0
- package/dist/runner/autopilot/entrypoint.js +149 -0
- package/dist/runner/autopilot/entrypoint.js.map +1 -0
- package/dist/runner/esbuild.runtime.d.ts +2 -0
- package/dist/runner/esbuild.runtime.d.ts.map +1 -0
- package/dist/runner/esbuild.runtime.js +55 -0
- package/dist/runner/esbuild.runtime.js.map +1 -0
- package/dist/runner/implement/entrypoint.d.ts +37 -0
- package/dist/runner/implement/entrypoint.d.ts.map +1 -0
- package/dist/runner/implement/entrypoint.js +98 -0
- package/dist/runner/implement/entrypoint.js.map +1 -0
- package/package.json +2 -2
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
var $m=Object.defineProperty;var ze=(e,t)=>{for(var r in t)$m(e,r,{get:t[r],enumerable:!0})};import{spawnSync as _m}from"node:child_process";import{appendFileSync as wm,mkdirSync as Ro,readFileSync as Co,renameSync as oS,unlinkSync as sS,writeFileSync as xm}from"node:fs";import{resolve as iS}from"node:path";import{fileURLToPath as aS}from"node:url";import{join as Pm}from"node:path";var Im=e=>{if(e.length<2)return e;let t=e[0],r=e[e.length-1];return t==='"'&&r==='"'||t==="'"&&r==="'"?e.slice(1,-1):e},Rm=e=>{let t=e.trim();if(!t||t.startsWith("#"))return;let r=t.indexOf("=");if(r===-1)return;let n=t.slice(0,r).trim();if(!n)return;let o=Im(t.slice(r+1).trim());return[n,o]},Cm=e=>e!==void 0,To=e=>{let r=e.split(`
|
|
2
|
+
`).map(Rm).filter(Cm);return Object.fromEntries(r)},$r=(e,t)=>{let r=Pm(e,".clancy",".env");try{return To(t.readFile(r))}catch{return}};var ue=class{#e;get(){return this.#e}store(t){this.#e=t}},Ue=class{#e=new Map;get(t){return this.#e.get(t)}has(t){return this.#e.has(t)}store(t,r){this.#e.set(t,r)}};async function Tm(e){try{let t=await e.text();return t?` \u2014 ${t.slice(0,200)}`:""}catch{return""}}function Em(e){return e instanceof Error?e.message:String(e)}async function S(e,t,r){let{schema:n,label:o,fetcher:s=fetch}=r,i=await s(e,t).catch(l=>{console.warn(`\u26A0 ${o} request failed: ${Em(l)}`)});if(!i)return;if(!i.ok){let l=await Tm(i);console.warn(`\u26A0 ${o} returned HTTP ${i.status}${l}`);return}let c=await i.json().catch(()=>{console.warn(`\u26A0 ${o} returned invalid JSON`)});if(c===void 0)return;let u=n.safeParse(c);if(!u.success){console.warn(`\u26A0 ${o} unexpected response shape: ${u.error.message}`);return}return u.data}async function V(e){let{url:t,headers:r,statusErrors:n,networkError:o,fetcher:s}=e,i=s??fetch;try{let c=await i(t,{headers:r,signal:AbortSignal.timeout(1e4)});if(await c.arrayBuffer().catch(()=>{}),c.ok)return{ok:!0};let u=n[c.status];return u?{ok:!1,error:u}:{ok:!1,error:`\u2717 HTTP ${c.status}`}}catch{return{ok:!1,error:o}}}function zm(e){if(!e)return;let t=parseInt(e,10);if(!Number.isNaN(t)&&t>=0)return t*1e3;let r=new Date(e);if(!Number.isNaN(r.getTime())){let n=r.getTime()-Date.now();return n>0?n:0}}function Eo(e,t,r){return Math.min(t*2**e,r)}function Am(e){return e===429||e>=500&&e<=599}function Lm(e,t,r){if(e.status===429){let n=zm(e.headers.get("Retry-After")),o=Eo(r,t.baseDelayMs,t.maxDelayMs);return Math.min(n??o,t.maxDelayMs)}return Eo(r,t.baseDelayMs,t.maxDelayMs)}function Jl(e){return new Promise(t=>setTimeout(t,e))}async function zo(e,t){try{let r=await fetch(e.url,e.init);if(!Am(r.status)||t>=e.maxRetries)return r;let n=Lm(r,e,t);return await r.arrayBuffer().catch(()=>{}),await Jl(n),zo(e,t+1)}catch(r){if(t>=e.maxRetries)throw r;let n=Eo(t,e.baseDelayMs,e.maxDelayMs);return await Jl(n),zo(e,t+1)}}async function Ae(e,t,r){let n={url:e,init:t,maxRetries:Math.max(0,r?.maxRetries??3),baseDelayMs:r?.baseDelayMs??1e3,maxDelayMs:r?.maxDelayMs??1e4};return zo(n,0)}async function R(e,t){try{await e()}catch(r){console.warn(`\u26A0 ${t} failed: ${r instanceof Error?r.message:String(r)}`)}}async function O(e){let{fetchCurrent:t,writeUpdated:r,target:n,mode:o}=e,s=await t();if(!s)return;let i=s.includes(n);if(o==="add"&&i||o==="remove"&&!i)return;let c=o==="add"?[...s,n]:s.filter(u=>u!==n);await r(c)}var Le=new Set(["PR_CREATED","PUSHED","REWORK","RESUMED"]);var a={};ze(a,{$brand:()=>Lo,$input:()=>fa,$output:()=>pa,NEVER:()=>Ao,TimePrecision:()=>Ba,ZodMiniAny:()=>nf,ZodMiniArray:()=>uf,ZodMiniBase64:()=>Wp,ZodMiniBase64URL:()=>Jp,ZodMiniBigInt:()=>Ht,ZodMiniBigIntFormat:()=>qc,ZodMiniBoolean:()=>Kt,ZodMiniCIDRv4:()=>qp,ZodMiniCIDRv6:()=>Kp,ZodMiniCUID:()=>Bp,ZodMiniCUID2:()=>Op,ZodMiniCatch:()=>Tf,ZodMiniCodec:()=>Vc,ZodMiniCustom:()=>Qc,ZodMiniCustomStringFormat:()=>Ut,ZodMiniDate:()=>rn,ZodMiniDefault:()=>If,ZodMiniDiscriminatedUnion:()=>ff,ZodMiniE164:()=>Yp,ZodMiniEmail:()=>Ap,ZodMiniEmoji:()=>Np,ZodMiniEnum:()=>Wc,ZodMiniExactOptional:()=>vf,ZodMiniFile:()=>wf,ZodMiniFunction:()=>Of,ZodMiniGUID:()=>Lp,ZodMiniIPv4:()=>Mp,ZodMiniIPv6:()=>Up,ZodMiniISODate:()=>an,ZodMiniISODateTime:()=>sn,ZodMiniISODuration:()=>un,ZodMiniISOTime:()=>cn,ZodMiniIntersection:()=>df,ZodMiniJWT:()=>Gp,ZodMiniKSUID:()=>Fp,ZodMiniLazy:()=>Lf,ZodMiniLiteral:()=>_f,ZodMiniMAC:()=>Hp,ZodMiniMap:()=>gf,ZodMiniNaN:()=>Ef,ZodMiniNanoID:()=>jp,ZodMiniNever:()=>sf,ZodMiniNonOptional:()=>Yc,ZodMiniNull:()=>tf,ZodMiniNullable:()=>$f,ZodMiniNumber:()=>qt,ZodMiniNumberFormat:()=>Xe,ZodMiniObject:()=>nn,ZodMiniOptional:()=>Jc,ZodMiniPipe:()=>Gc,ZodMiniPrefault:()=>Rf,ZodMiniPromise:()=>jf,ZodMiniReadonly:()=>zf,ZodMiniRecord:()=>on,ZodMiniSet:()=>yf,ZodMiniString:()=>Qe,ZodMiniStringFormat:()=>P,ZodMiniSuccess:()=>Cf,ZodMiniSymbol:()=>Xp,ZodMiniTemplateLiteral:()=>Af,ZodMiniTransform:()=>xf,ZodMiniTuple:()=>mf,ZodMiniType:()=>k,ZodMiniULID:()=>Zp,ZodMiniURL:()=>Uc,ZodMiniUUID:()=>Mt,ZodMiniUndefined:()=>ef,ZodMiniUnion:()=>Hc,ZodMiniUnknown:()=>of,ZodMiniVoid:()=>cf,ZodMiniXID:()=>Dp,ZodMiniXor:()=>pf,_default:()=>ay,_function:()=>Py,any:()=>Ag,array:()=>Kc,base64:()=>hg,base64url:()=>bg,bigint:()=>Rg,boolean:()=>Qp,catch:()=>py,catchall:()=>Wg,check:()=>yy,cidrv4:()=>fg,cidrv6:()=>dg,clone:()=>A,codec:()=>my,coerce:()=>eu,config:()=>E,core:()=>Ve,cuid:()=>sg,cuid2:()=>ig,custom:()=>Bf,date:()=>Ng,decode:()=>rs,decodeAsync:()=>os,describe:()=>wy,discriminatedUnion:()=>Yg,e164:()=>gg,email:()=>Yb,emoji:()=>ng,encode:()=>ts,encodeAsync:()=>ns,endsWith:()=>Ic,enum:()=>kf,exactOptional:()=>sy,extend:()=>Dg,file:()=>ny,flattenError:()=>Vo,float32:()=>vg,float64:()=>$g,formatError:()=>Qo,function:()=>Py,globalRegistry:()=>ne,gt:()=>Vr,gte:()=>Ft,guid:()=>Gb,hash:()=>xg,hex:()=>wg,hostname:()=>_g,httpUrl:()=>rg,includes:()=>$c,instanceof:()=>Sy,int:()=>Sg,int32:()=>Pg,int64:()=>Cg,intersection:()=>Gg,ipv4:()=>lg,ipv6:()=>pg,iso:()=>Xc,json:()=>$y,jwt:()=>yg,keyof:()=>jg,ksuid:()=>ug,lazy:()=>Nf,length:()=>wc,literal:()=>ry,locales:()=>Zt,looseObject:()=>Zg,looseRecord:()=>Qg,lowercase:()=>Sc,lt:()=>Gr,lte:()=>Dt,mac:()=>mg,map:()=>Xg,maxLength:()=>kc,maxSize:()=>bc,maximum:()=>Dt,merge:()=>Mg,meta:()=>xy,mime:()=>Cc,minLength:()=>_c,minSize:()=>gc,minimum:()=>Ft,multipleOf:()=>hc,nan:()=>fy,nanoid:()=>og,nativeEnum:()=>ty,negative:()=>fc,never:()=>af,nonnegative:()=>mc,nonoptional:()=>uy,nonpositive:()=>dc,normalize:()=>Tc,null:()=>rf,nullable:()=>Pf,nullish:()=>iy,number:()=>Vp,object:()=>Bg,omit:()=>qg,optional:()=>Sf,overwrite:()=>ye,parse:()=>be,parseAsync:()=>ge,partial:()=>Kg,partialRecord:()=>Vg,pick:()=>Ug,pipe:()=>dy,positive:()=>pc,prefault:()=>cy,prettifyError:()=>es,promise:()=>gy,property:()=>Rc,readonly:()=>hy,record:()=>bf,refine:()=>ky,regex:()=>xc,regexes:()=>J,registry:()=>Jr,required:()=>Hg,safeDecode:()=>is,safeDecodeAsync:()=>cs,safeEncode:()=>ss,safeEncodeAsync:()=>as,safeExtend:()=>Fg,safeParse:()=>je,safeParseAsync:()=>Be,set:()=>ey,size:()=>yc,startsWith:()=>Pc,strictObject:()=>Og,string:()=>Mc,stringFormat:()=>kg,stringbool:()=>vy,success:()=>ly,superRefine:()=>_y,symbol:()=>Eg,templateLiteral:()=>by,toJSONSchema:()=>Xr,toLowerCase:()=>zc,toUpperCase:()=>Ac,transform:()=>oy,treeifyError:()=>Xo,trim:()=>Ec,tuple:()=>hf,uint32:()=>Ig,uint64:()=>Tg,ulid:()=>ag,undefined:()=>zg,union:()=>lf,unknown:()=>tn,uppercase:()=>vc,url:()=>tg,util:()=>W,uuid:()=>Vb,uuidv4:()=>Qb,uuidv6:()=>Xb,uuidv7:()=>eg,void:()=>Lg,xid:()=>cg,xor:()=>Jg});var Ve={};ze(Ve,{$ZodAny:()=>Li,$ZodArray:()=>Zi,$ZodAsyncError:()=>Q,$ZodBase64:()=>vi,$ZodBase64URL:()=>$i,$ZodBigInt:()=>Ur,$ZodBigIntFormat:()=>Ti,$ZodBoolean:()=>jt,$ZodCIDRv4:()=>wi,$ZodCIDRv6:()=>xi,$ZodCUID:()=>ui,$ZodCUID2:()=>li,$ZodCatch:()=>ra,$ZodCheck:()=>$,$ZodCheckBigIntFormat:()=>Zs,$ZodCheckEndsWith:()=>Vs,$ZodCheckGreaterThan:()=>jr,$ZodCheckIncludes:()=>Ys,$ZodCheckLengthEquals:()=>Ks,$ZodCheckLessThan:()=>Nr,$ZodCheckLowerCase:()=>Ws,$ZodCheckMaxLength:()=>Us,$ZodCheckMaxSize:()=>Ds,$ZodCheckMimeType:()=>Xs,$ZodCheckMinLength:()=>qs,$ZodCheckMinSize:()=>Fs,$ZodCheckMultipleOf:()=>Bs,$ZodCheckNumberFormat:()=>Os,$ZodCheckOverwrite:()=>ei,$ZodCheckProperty:()=>Qs,$ZodCheckRegex:()=>Hs,$ZodCheckSizeEquals:()=>Ms,$ZodCheckStartsWith:()=>Gs,$ZodCheckStringFormat:()=>Je,$ZodCheckUpperCase:()=>Js,$ZodCodec:()=>Ot,$ZodCustom:()=>la,$ZodCustomStringFormat:()=>Ri,$ZodDate:()=>Oi,$ZodDefault:()=>Qi,$ZodDiscriminatedUnion:()=>Fi,$ZodE164:()=>Pi,$ZodEmail:()=>si,$ZodEmoji:()=>ai,$ZodEncodeError:()=>qe,$ZodEnum:()=>Hi,$ZodError:()=>Go,$ZodExactOptional:()=>Gi,$ZodFile:()=>Ji,$ZodFunction:()=>aa,$ZodGUID:()=>ni,$ZodIPv4:()=>yi,$ZodIPv6:()=>ki,$ZodISODate:()=>hi,$ZodISODateTime:()=>mi,$ZodISODuration:()=>gi,$ZodISOTime:()=>bi,$ZodIntersection:()=>Mi,$ZodJWT:()=>Ii,$ZodKSUID:()=>di,$ZodLazy:()=>ua,$ZodLiteral:()=>Wi,$ZodMAC:()=>_i,$ZodMap:()=>qi,$ZodNaN:()=>na,$ZodNanoID:()=>ci,$ZodNever:()=>ji,$ZodNonOptional:()=>ea,$ZodNull:()=>Ai,$ZodNullable:()=>Vi,$ZodNumber:()=>Mr,$ZodNumberFormat:()=>Ci,$ZodObject:()=>qr,$ZodObjectJIT:()=>zh,$ZodOptional:()=>Hr,$ZodPipe:()=>oa,$ZodPrefault:()=>Xi,$ZodPromise:()=>ca,$ZodReadonly:()=>sa,$ZodRealError:()=>D,$ZodRecord:()=>Ui,$ZodRegistry:()=>Wr,$ZodSet:()=>Ki,$ZodString:()=>Ye,$ZodStringFormat:()=>v,$ZodSuccess:()=>ta,$ZodSymbol:()=>Ei,$ZodTemplateLiteral:()=>ia,$ZodTransform:()=>Yi,$ZodTuple:()=>Kr,$ZodType:()=>g,$ZodULID:()=>pi,$ZodURL:()=>ii,$ZodUUID:()=>oi,$ZodUndefined:()=>zi,$ZodUnion:()=>Bt,$ZodUnknown:()=>Ni,$ZodVoid:()=>Bi,$ZodXID:()=>fi,$ZodXor:()=>Di,$brand:()=>Lo,$constructor:()=>f,$input:()=>fa,$output:()=>pa,Doc:()=>Nt,JSONSchema:()=>zp,JSONSchemaGenerator:()=>en,NEVER:()=>Ao,TimePrecision:()=>Ba,_any:()=>oc,_array:()=>Bh,_base64:()=>Aa,_base64url:()=>La,_bigint:()=>Va,_boolean:()=>Ya,_catch:()=>tb,_check:()=>Ep,_cidrv4:()=>Ea,_cidrv6:()=>za,_coercedBigint:()=>Qa,_coercedBoolean:()=>Ga,_coercedDate:()=>uc,_coercedNumber:()=>Ua,_coercedString:()=>ma,_cuid:()=>Sa,_cuid2:()=>va,_custom:()=>Nc,_date:()=>cc,_decode:()=>rp,_decodeAsync:()=>op,_default:()=>Qh,_discriminatedUnion:()=>Dh,_e164:()=>Na,_email:()=>ha,_emoji:()=>wa,_encode:()=>tp,_encodeAsync:()=>np,_endsWith:()=>Ic,_enum:()=>Hh,_file:()=>Lc,_float32:()=>Ka,_float64:()=>Ha,_gt:()=>Vr,_gte:()=>Ft,_guid:()=>ba,_includes:()=>$c,_int:()=>qa,_int32:()=>Wa,_int64:()=>Xa,_intersection:()=>Fh,_ipv4:()=>Ra,_ipv6:()=>Ca,_isoDate:()=>Za,_isoDateTime:()=>Oa,_isoDuration:()=>Fa,_isoTime:()=>Da,_jwt:()=>ja,_ksuid:()=>Ia,_lazy:()=>sb,_length:()=>wc,_literal:()=>Jh,_lowercase:()=>Sc,_lt:()=>Gr,_lte:()=>Dt,_mac:()=>Ta,_map:()=>qh,_max:()=>Dt,_maxLength:()=>kc,_maxSize:()=>bc,_mime:()=>Cc,_min:()=>Ft,_minLength:()=>_c,_minSize:()=>gc,_multipleOf:()=>hc,_nan:()=>lc,_nanoid:()=>xa,_nativeEnum:()=>Wh,_negative:()=>fc,_never:()=>ic,_nonnegative:()=>mc,_nonoptional:()=>Xh,_nonpositive:()=>dc,_normalize:()=>Tc,_null:()=>nc,_nullable:()=>Vh,_number:()=>Ma,_optional:()=>Gh,_overwrite:()=>ye,_parse:()=>Cr,_parseAsync:()=>Tr,_pipe:()=>rb,_positive:()=>pc,_promise:()=>ib,_property:()=>Rc,_readonly:()=>nb,_record:()=>Uh,_refine:()=>jc,_regex:()=>xc,_safeDecode:()=>ip,_safeDecodeAsync:()=>cp,_safeEncode:()=>sp,_safeEncodeAsync:()=>ap,_safeParse:()=>Er,_safeParseAsync:()=>zr,_set:()=>Kh,_size:()=>yc,_slugify:()=>jh,_startsWith:()=>Pc,_string:()=>da,_stringFormat:()=>Ge,_stringbool:()=>Dc,_success:()=>eb,_superRefine:()=>Bc,_symbol:()=>tc,_templateLiteral:()=>ob,_toLowerCase:()=>zc,_toUpperCase:()=>Ac,_transform:()=>Yh,_trim:()=>Ec,_tuple:()=>Mh,_uint32:()=>Ja,_uint64:()=>ec,_ulid:()=>$a,_undefined:()=>rc,_union:()=>Oh,_unknown:()=>sc,_uppercase:()=>vc,_url:()=>Yr,_uuid:()=>ga,_uuidv4:()=>ya,_uuidv6:()=>ka,_uuidv7:()=>_a,_void:()=>ac,_xid:()=>Pa,_xor:()=>Zh,clone:()=>A,config:()=>E,createStandardJSONSchemaMethod:()=>Fc,createToJSONSchemaMethod:()=>ab,decode:()=>rs,decodeAsync:()=>os,describe:()=>Oc,encode:()=>ts,encodeAsync:()=>ns,extractDefs:()=>_e,finalize:()=>we,flattenError:()=>Vo,formatError:()=>Qo,globalConfig:()=>Pt,globalRegistry:()=>ne,initializeContext:()=>ke,isValidBase64:()=>Si,isValidBase64URL:()=>Pp,isValidJWT:()=>Ip,locales:()=>Zt,meta:()=>Zc,parse:()=>be,parseAsync:()=>ge,prettifyError:()=>es,process:()=>x,regexes:()=>J,registry:()=>Jr,safeDecode:()=>is,safeDecodeAsync:()=>cs,safeEncode:()=>ss,safeEncodeAsync:()=>as,safeParse:()=>je,safeParseAsync:()=>Be,toDotPath:()=>ep,toJSONSchema:()=>Xr,treeifyError:()=>Xo,util:()=>W,version:()=>ti});var Ao=Object.freeze({status:"aborted"});function f(e,t,r){function n(c,u){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:u,constr:i,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,u);let l=i.prototype,p=Object.keys(l);for(let d=0;d<p.length;d++){let h=p[d];h in c||(c[h]=l[h].bind(c))}}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function i(c){var u;let l=r?.Parent?new s:this;n(l,c),(u=l._zod).deferred??(u.deferred=[]);for(let p of l._zod.deferred)p();return l}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}var Lo=Symbol("zod_brand"),Q=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},qe=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}},Pt={};function E(e){return e&&Object.assign(Pt,e),Pt}var W={};ze(W,{BIGINT_FORMAT_RANGES:()=>qo,Class:()=>jo,NUMBER_FORMAT_RANGES:()=>Uo,aborted:()=>he,allowsEval:()=>Do,assert:()=>Fm,assertEqual:()=>Bm,assertIs:()=>Zm,assertNever:()=>Dm,assertNotEqual:()=>Om,assignProp:()=>de,base64ToUint8Array:()=>Vl,base64urlToUint8Array:()=>eh,cached:()=>Ke,captureStackTrace:()=>Ir,cleanEnum:()=>Xm,cleanRegex:()=>Ct,clone:()=>A,cloneDef:()=>qm,createTransparentProxy:()=>Gm,defineLazy:()=>y,esc:()=>Pr,escapeRegex:()=>H,extend:()=>Rr,finalizeIssue:()=>Z,floatSafeRemainder:()=>Oo,getElementAtPath:()=>Km,getEnumValues:()=>Rt,getLengthableOrigin:()=>zt,getParsedType:()=>Ym,getSizableOrigin:()=>Et,hexToUint8Array:()=>rh,isObject:()=>Ne,isPlainObject:()=>me,issue:()=>We,joinValues:()=>Mm,jsonStringifyReplacer:()=>Bo,merge:()=>Vm,mergeDefs:()=>le,normalizeParams:()=>m,nullish:()=>fe,numKeys:()=>Jm,objectClone:()=>Um,omit:()=>Ho,optionalKeys:()=>Mo,parsedType:()=>Qm,partial:()=>Jo,pick:()=>Ko,prefixIssues:()=>U,primitiveTypes:()=>Fo,promiseAllObject:()=>Hm,propertyKeyTypes:()=>Tt,randomString:()=>Wm,required:()=>Yo,safeExtend:()=>Wo,shallowClone:()=>He,slugify:()=>Zo,stringifyPrimitive:()=>Gl,uint8ArrayToBase64:()=>Ql,uint8ArrayToBase64url:()=>th,uint8ArrayToHex:()=>nh,unwrapMessage:()=>It});function Bm(e){return e}function Om(e){return e}function Zm(e){}function Dm(e){throw new Error("Unexpected value in exhaustive check")}function Fm(e){}function Rt(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function Mm(e,t="|"){return e.map(r=>Gl(r)).join(t)}function Bo(e,t){return typeof t=="bigint"?t.toString():t}function Ke(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function fe(e){return e==null}function Ct(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Oo(e,t){let r=(e.toString().split(".")[1]||"").length,n=t.toString(),o=(n.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(n)){let u=n.match(/\d?e-(\d?)/);u?.[1]&&(o=Number.parseInt(u[1]))}let s=r>o?r:o,i=Number.parseInt(e.toFixed(s).replace(".","")),c=Number.parseInt(t.toFixed(s).replace(".",""));return i%c/10**s}var Yl=Symbol("evaluating");function y(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==Yl)return n===void 0&&(n=Yl,n=r()),n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Um(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function de(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function le(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function qm(e){return le(e._zod.def)}function Km(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function Hm(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<t.length;s++)o[t[s]]=n[s];return o})}function Wm(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function Pr(e){return JSON.stringify(e)}function Zo(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Ir="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ne(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Do=Ke(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function me(e){if(Ne(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(Ne(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function He(e){return me(e)?{...e}:Array.isArray(e)?[...e]:e}function Jm(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var Ym=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Tt=new Set(["string","number","symbol"]),Fo=new Set(["string","number","bigint","boolean","symbol","undefined"]);function H(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function A(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function m(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Gm(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,s){return t??(t=e()),Reflect.set(t,n,o,s)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function Gl(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Mo(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Uo={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},qo={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Ko(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=le(e._zod.def,{get shape(){let i={};for(let c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(i[c]=r.shape[c])}return de(this,"shape",i),i},checks:[]});return A(e,s)}function Ho(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=le(e._zod.def,{get shape(){let i={...e._zod.def.shape};for(let c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete i[c]}return de(this,"shape",i),i},checks:[]});return A(e,s)}function Rr(e,t){if(!me(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let s=e._zod.def.shape;for(let i in t)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=le(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return de(this,"shape",s),s}});return A(e,o)}function Wo(e,t){if(!me(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=le(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return de(this,"shape",n),n}});return A(e,r)}function Vm(e,t){let r=le(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return de(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return A(e,r)}function Jo(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let i=le(t._zod.def,{get shape(){let c=t._zod.def.shape,u={...c};if(r)for(let l in r){if(!(l in c))throw new Error(`Unrecognized key: "${l}"`);r[l]&&(u[l]=e?new e({type:"optional",innerType:c[l]}):c[l])}else for(let l in c)u[l]=e?new e({type:"optional",innerType:c[l]}):c[l];return de(this,"shape",u),u},checks:[]});return A(t,i)}function Yo(e,t,r){let n=le(t._zod.def,{get shape(){let o=t._zod.def.shape,s={...o};if(r)for(let i in r){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(s[i]=new e({type:"nonoptional",innerType:o[i]}))}else for(let i in o)s[i]=new e({type:"nonoptional",innerType:o[i]});return de(this,"shape",s),s}});return A(t,n)}function he(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function U(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function It(e){return typeof e=="string"?e:e?.message}function Z(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=It(e.inst?._zod.def?.error?.(e))??It(t?.error?.(e))??It(r.customError?.(e))??It(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Et(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function zt(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Qm(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function We(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function Xm(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function Vl(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function Ql(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function eh(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return Vl(t+r)}function th(e){return Ql(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function rh(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=Number.parseInt(t.slice(n,n+2),16);return r}function nh(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var jo=class{constructor(...t){}};var Xl=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Bo,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Go=f("$ZodError",Xl),D=f("$ZodError",Xl,{Parent:Error});function Vo(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function Qo(e,t=r=>r.message){let r={_errors:[]},n=o=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(i=>n({issues:i}));else if(s.code==="invalid_key")n({issues:s.issues});else if(s.code==="invalid_element")n({issues:s.issues});else if(s.path.length===0)r._errors.push(t(s));else{let i=r,c=0;for(;c<s.path.length;){let u=s.path[c];c===s.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(t(s))):i[u]=i[u]||{_errors:[]},i=i[u],c++}}};return n(e),r}function Xo(e,t=r=>r.message){let r={errors:[]},n=(o,s=[])=>{var i,c;for(let u of o.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(l=>n({issues:l},u.path));else if(u.code==="invalid_key")n({issues:u.issues},u.path);else if(u.code==="invalid_element")n({issues:u.issues},u.path);else{let l=[...s,...u.path];if(l.length===0){r.errors.push(t(u));continue}let p=r,d=0;for(;d<l.length;){let h=l[d],b=d===l.length-1;typeof h=="string"?(p.properties??(p.properties={}),(i=p.properties)[h]??(i[h]={errors:[]}),p=p.properties[h]):(p.items??(p.items=[]),(c=p.items)[h]??(c[h]={errors:[]}),p=p.items[h]),b&&p.errors.push(t(u)),d++}}};return n(e),r}function ep(e){let t=[],r=e.map(n=>typeof n=="object"?n.key:n);for(let n of r)typeof n=="number"?t.push(`[${n}]`):typeof n=="symbol"?t.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?t.push(`[${JSON.stringify(n)}]`):(t.length&&t.push("."),t.push(n));return t.join("")}function es(e){let t=[],r=[...e.issues].sort((n,o)=>(n.path??[]).length-(o.path??[]).length);for(let n of r)t.push(`\u2716 ${n.message}`),n.path?.length&&t.push(` \u2192 at ${ep(n.path)}`);return t.join(`
|
|
3
|
+
`)}var Cr=e=>(t,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Q;if(i.issues.length){let c=new(o?.Err??e)(i.issues.map(u=>Z(u,s,E())));throw Ir(c,o?.callee),c}return i.value},be=Cr(D),Tr=e=>async(t,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let c=new(o?.Err??e)(i.issues.map(u=>Z(u,s,E())));throw Ir(c,o?.callee),c}return i.value},ge=Tr(D),Er=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Q;return s.issues.length?{success:!1,error:new(e??Go)(s.issues.map(i=>Z(i,o,E())))}:{success:!0,data:s.value}},je=Er(D),zr=e=>async(t,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(i=>Z(i,o,E())))}:{success:!0,data:s.value}},Be=zr(D),tp=e=>(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Cr(e)(t,r,o)},ts=tp(D),rp=e=>(t,r,n)=>Cr(e)(t,r,n),rs=rp(D),np=e=>async(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Tr(e)(t,r,o)},ns=np(D),op=e=>async(t,r,n)=>Tr(e)(t,r,n),os=op(D),sp=e=>(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Er(e)(t,r,o)},ss=sp(D),ip=e=>(t,r,n)=>Er(e)(t,r,n),is=ip(D),ap=e=>async(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return zr(e)(t,r,o)},as=ap(D),cp=e=>async(t,r,n)=>zr(e)(t,r,n),cs=cp(D);var J={};ze(J,{base64:()=>vs,base64url:()=>Ar,bigint:()=>Ts,boolean:()=>zs,browserEmail:()=>fh,cidrv4:()=>xs,cidrv6:()=>Ss,cuid:()=>us,cuid2:()=>ls,date:()=>Ps,datetime:()=>Rs,domain:()=>hh,duration:()=>hs,e164:()=>$s,email:()=>gs,emoji:()=>ys,extendedDuration:()=>sh,guid:()=>bs,hex:()=>bh,hostname:()=>mh,html5Email:()=>uh,idnEmail:()=>ph,integer:()=>Es,ipv4:()=>ks,ipv6:()=>_s,ksuid:()=>ds,lowercase:()=>Ns,mac:()=>ws,md5_base64:()=>yh,md5_base64url:()=>kh,md5_hex:()=>gh,nanoid:()=>ms,null:()=>As,number:()=>Lr,rfc5322Email:()=>lh,sha1_base64:()=>wh,sha1_base64url:()=>xh,sha1_hex:()=>_h,sha256_base64:()=>vh,sha256_base64url:()=>$h,sha256_hex:()=>Sh,sha384_base64:()=>Ih,sha384_base64url:()=>Rh,sha384_hex:()=>Ph,sha512_base64:()=>Th,sha512_base64url:()=>Eh,sha512_hex:()=>Ch,string:()=>Cs,time:()=>Is,ulid:()=>ps,undefined:()=>Ls,unicodeEmail:()=>up,uppercase:()=>js,uuid:()=>Oe,uuid4:()=>ih,uuid6:()=>ah,uuid7:()=>ch,xid:()=>fs});var us=/^[cC][^\s-]{8,}$/,ls=/^[0-9a-z]+$/,ps=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,fs=/^[0-9a-vA-V]{20}$/,ds=/^[A-Za-z0-9]{27}$/,ms=/^[a-zA-Z0-9_-]{21}$/,hs=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,sh=/^[-+]?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)?)??$/,bs=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Oe=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,ih=Oe(4),ah=Oe(6),ch=Oe(7),gs=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,uh=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,lh=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,up=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,ph=up,fh=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,dh="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ys(){return new RegExp(dh,"u")}var ks=/^(?:(?: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])$/,_s=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,ws=e=>{let t=H(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},xs=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,Ss=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,vs=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ar=/^[A-Za-z0-9_-]*$/,mh=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,hh=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,$s=/^\+[1-9]\d{6,14}$/,lp="(?:(?:\\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])))",Ps=new RegExp(`^${lp}$`);function pp(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Is(e){return new RegExp(`^${pp(e)}$`)}function Rs(e){let t=pp({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${lp}T(?:${n})$`)}var Cs=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Ts=/^-?\d+n?$/,Es=/^-?\d+$/,Lr=/^-?\d+(?:\.\d+)?$/,zs=/^(?:true|false)$/i,As=/^null$/i;var Ls=/^undefined$/i;var Ns=/^[^A-Z]*$/,js=/^[^a-z]*$/,bh=/^[0-9a-fA-F]*$/;function At(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function Lt(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var gh=/^[0-9a-fA-F]{32}$/,yh=At(22,"=="),kh=Lt(22),_h=/^[0-9a-fA-F]{40}$/,wh=At(27,"="),xh=Lt(27),Sh=/^[0-9a-fA-F]{64}$/,vh=At(43,"="),$h=Lt(43),Ph=/^[0-9a-fA-F]{96}$/,Ih=At(64,""),Rh=Lt(64),Ch=/^[0-9a-fA-F]{128}$/,Th=At(86,"=="),Eh=Lt(86);var $=f("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),dp={number:"number",bigint:"bigint",object:"date"},Nr=f("$ZodCheckLessThan",(e,t)=>{$.init(e,t);let r=dp[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),jr=f("$ZodCheckGreaterThan",(e,t)=>{$.init(e,t);let r=dp[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Bs=f("$ZodCheckMultipleOf",(e,t)=>{$.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):Oo(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Os=f("$ZodCheckNumberFormat",(e,t)=>{$.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,s]=Uo[t.format];e._zod.onattach.push(i=>{let c=i._zod.bag;c.format=t.format,c.minimum=o,c.maximum=s,r&&(c.pattern=Es)}),e._zod.check=i=>{let c=i.value;if(r){if(!Number.isInteger(c)){i.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?i.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):i.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}c<o&&i.issues.push({origin:"number",input:c,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),c>s&&i.issues.push({origin:"number",input:c,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),Zs=f("$ZodCheckBigIntFormat",(e,t)=>{$.init(e,t);let[r,n]=qo[t.format];e._zod.onattach.push(o=>{let s=o._zod.bag;s.format=t.format,s.minimum=r,s.maximum=n}),e._zod.check=o=>{let s=o.value;s<r&&o.issues.push({origin:"bigint",input:s,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),s>n&&o.issues.push({origin:"bigint",input:s,code:"too_big",maximum:n,inclusive:!0,inst:e,continue:!t.abort})}}),Ds=f("$ZodCheckMaxSize",(e,t)=>{var r;$.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!fe(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;o.size<=t.maximum||n.issues.push({origin:Et(o),code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Fs=f("$ZodCheckMinSize",(e,t)=>{var r;$.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!fe(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;o.size>=t.minimum||n.issues.push({origin:Et(o),code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Ms=f("$ZodCheckSizeEquals",(e,t)=>{var r;$.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!fe(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.size,o.maximum=t.size,o.size=t.size}),e._zod.check=n=>{let o=n.value,s=o.size;if(s===t.size)return;let i=s>t.size;n.issues.push({origin:Et(o),...i?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Us=f("$ZodCheckMaxLength",(e,t)=>{var r;$.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!fe(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;if(o.length<=t.maximum)return;let i=zt(o);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),qs=f("$ZodCheckMinLength",(e,t)=>{var r;$.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!fe(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;if(o.length>=t.minimum)return;let i=zt(o);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Ks=f("$ZodCheckLengthEquals",(e,t)=>{var r;$.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!fe(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{let o=n.value,s=o.length;if(s===t.length)return;let i=zt(o),c=s>t.length;n.issues.push({origin:i,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Je=f("$ZodCheckStringFormat",(e,t)=>{var r,n;$.init(e,t),e._zod.onattach.push(o=>{let s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Hs=f("$ZodCheckRegex",(e,t)=>{Je.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ws=f("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ns),Je.init(e,t)}),Js=f("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=js),Je.init(e,t)}),Ys=f("$ZodCheckIncludes",(e,t)=>{$.init(e,t);let r=H(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Gs=f("$ZodCheckStartsWith",(e,t)=>{$.init(e,t);let r=new RegExp(`^${H(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Vs=f("$ZodCheckEndsWith",(e,t)=>{$.init(e,t);let r=new RegExp(`.*${H(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});function fp(e,t,r){e.issues.length&&t.issues.push(...U(r,e.issues))}var Qs=f("$ZodCheckProperty",(e,t)=>{$.init(e,t),e._zod.check=r=>{let n=t.schema._zod.run({value:r.value[t.property],issues:[]},{});if(n instanceof Promise)return n.then(o=>fp(o,r,t.property));fp(n,r,t.property)}}),Xs=f("$ZodCheckMimeType",(e,t)=>{$.init(e,t);let r=new Set(t.mime);e._zod.onattach.push(n=>{n._zod.bag.mime=t.mime}),e._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:t.mime,input:n.value.type,inst:e,continue:!t.abort})}}),ei=f("$ZodCheckOverwrite",(e,t)=>{$.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Nt=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
|
|
4
|
+
`).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let t=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...r,o.join(`
|
|
5
|
+
`))}};var ti={major:4,minor:3,patch:6};var g=f("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ti;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(i,c,u)=>{let l=he(i),p;for(let d of c){if(d._zod.def.when){if(!d._zod.def.when(i))continue}else if(l)continue;let h=i.issues.length,b=d._zod.check(i);if(b instanceof Promise&&u?.async===!1)throw new Q;if(p||b instanceof Promise)p=(p??Promise.resolve()).then(async()=>{await b,i.issues.length!==h&&(l||(l=he(i,h)))});else{if(i.issues.length===h)continue;l||(l=he(i,h))}}return p?p.then(()=>i):i},s=(i,c,u)=>{if(he(i))return i.aborted=!0,i;let l=o(c,n,u);if(l instanceof Promise){if(u.async===!1)throw new Q;return l.then(p=>e._zod.parse(p,u))}return e._zod.parse(l,u)};e._zod.run=(i,c)=>{if(c.skipChecks)return e._zod.parse(i,c);if(c.direction==="backward"){let l=e._zod.parse({value:i.value,issues:[]},{...c,skipChecks:!0});return l instanceof Promise?l.then(p=>s(p,i,c)):s(l,i,c)}let u=e._zod.parse(i,c);if(u instanceof Promise){if(c.async===!1)throw new Q;return u.then(l=>o(l,n,c))}return o(u,n,c)}}y(e,"~standard",()=>({validate:o=>{try{let s=je(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Be(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),Ye=f("$ZodString",(e,t)=>{g.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Cs(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),v=f("$ZodStringFormat",(e,t)=>{Je.init(e,t),Ye.init(e,t)}),ni=f("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=bs),v.init(e,t)}),oi=f("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Oe(n))}else t.pattern??(t.pattern=Oe());v.init(e,t)}),si=f("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=gs),v.init(e,t)}),ii=f("$ZodURL",(e,t)=>{v.init(e,t),e._zod.check=r=>{try{let n=r.value.trim(),o=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=o.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),ai=f("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=ys()),v.init(e,t)}),ci=f("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=ms),v.init(e,t)}),ui=f("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=us),v.init(e,t)}),li=f("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=ls),v.init(e,t)}),pi=f("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ps),v.init(e,t)}),fi=f("$ZodXID",(e,t)=>{t.pattern??(t.pattern=fs),v.init(e,t)}),di=f("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ds),v.init(e,t)}),mi=f("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Rs(t)),v.init(e,t)}),hi=f("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Ps),v.init(e,t)}),bi=f("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Is(t)),v.init(e,t)}),gi=f("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=hs),v.init(e,t)}),yi=f("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ks),v.init(e,t),e._zod.bag.format="ipv4"}),ki=f("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=_s),v.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),_i=f("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=ws(t.delimiter)),v.init(e,t),e._zod.bag.format="mac"}),wi=f("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=xs),v.init(e,t)}),xi=f("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Ss),v.init(e,t),e._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,s]=n;if(!s)throw new Error;let i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Si(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var vi=f("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=vs),v.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{Si(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function Pp(e){if(!Ar.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Si(r)}var $i=f("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Ar),v.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{Pp(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Pi=f("$ZodE164",(e,t)=>{t.pattern??(t.pattern=$s),v.init(e,t)});function Ip(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}var Ii=f("$ZodJWT",(e,t)=>{v.init(e,t),e._zod.check=r=>{Ip(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Ri=f("$ZodCustomStringFormat",(e,t)=>{v.init(e,t),e._zod.check=r=>{t.fn(r.value)||r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}}),Mr=f("$ZodNumber",(e,t)=>{g.init(e,t),e._zod.pattern=e._zod.bag.pattern??Lr,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),Ci=f("$ZodNumberFormat",(e,t)=>{Os.init(e,t),Mr.init(e,t)}),jt=f("$ZodBoolean",(e,t)=>{g.init(e,t),e._zod.pattern=zs,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),Ur=f("$ZodBigInt",(e,t)=>{g.init(e,t),e._zod.pattern=Ts,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),Ti=f("$ZodBigIntFormat",(e,t)=>{Zs.init(e,t),Ur.init(e,t)}),Ei=f("$ZodSymbol",(e,t)=>{g.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;return typeof o=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:o,inst:e}),r}}),zi=f("$ZodUndefined",(e,t)=>{g.init(e,t),e._zod.pattern=Ls,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(r,n)=>{let o=r.value;return typeof o>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:o,inst:e}),r}}),Ai=f("$ZodNull",(e,t)=>{g.init(e,t),e._zod.pattern=As,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}}),Li=f("$ZodAny",(e,t)=>{g.init(e,t),e._zod.parse=r=>r}),Ni=f("$ZodUnknown",(e,t)=>{g.init(e,t),e._zod.parse=r=>r}),ji=f("$ZodNever",(e,t)=>{g.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)}),Bi=f("$ZodVoid",(e,t)=>{g.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;return typeof o>"u"||r.issues.push({expected:"void",code:"invalid_type",input:o,inst:e}),r}}),Oi=f("$ZodDate",(e,t)=>{g.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,s=o instanceof Date;return s&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...s?{received:"Invalid Date"}:{},inst:e}),r}});function hp(e,t,r){e.issues.length&&t.issues.push(...U(r,e.issues)),t.value[r]=e.value}var Zi=f("$ZodArray",(e,t)=>{g.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let c=o[i],u=t.element._zod.run({value:c,issues:[]},n);u instanceof Promise?s.push(u.then(l=>hp(l,r,i))):hp(u,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function Fr(e,t,r,n,o){if(e.issues.length){if(o&&!(r in n))return;t.issues.push(...U(r,e.issues))}e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}function Rp(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=Mo(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function Cp(e,t,r,n,o,s){let i=[],c=o.keySet,u=o.catchall._zod,l=u.def.type,p=u.optout==="optional";for(let d in t){if(c.has(d))continue;if(l==="never"){i.push(d);continue}let h=u.run({value:t[d],issues:[]},n);h instanceof Promise?e.push(h.then(b=>Fr(b,r,d,t,p))):Fr(h,r,d,t,p)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:s}),e.length?Promise.all(e).then(()=>r):r}var qr=f("$ZodObject",(e,t)=>{if(g.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let c=t.shape;Object.defineProperty(t,"shape",{get:()=>{let u={...c};return Object.defineProperty(t,"shape",{value:u}),u}})}let n=Ke(()=>Rp(t));y(e._zod,"propValues",()=>{let c=t.shape,u={};for(let l in c){let p=c[l]._zod;if(p.values){u[l]??(u[l]=new Set);for(let d of p.values)u[l].add(d)}}return u});let o=Ne,s=t.catchall,i;e._zod.parse=(c,u)=>{i??(i=n.value);let l=c.value;if(!o(l))return c.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),c;c.value={};let p=[],d=i.shape;for(let h of i.keys){let b=d[h],_=b._zod.optout==="optional",w=b._zod.run({value:l[h],issues:[]},u);w instanceof Promise?p.push(w.then(I=>Fr(I,c,h,l,_))):Fr(w,c,h,l,_)}return s?Cp(p,l,c,u,n.value,e):p.length?Promise.all(p).then(()=>c):c}}),zh=f("$ZodObjectJIT",(e,t)=>{qr.init(e,t);let r=e._zod.parse,n=Ke(()=>Rp(t)),o=h=>{let b=new Nt(["shape","payload","ctx"]),_=n.value,w=re=>{let B=Pr(re);return`shape[${B}]._zod.run({ value: input[${B}], issues: [] }, ctx)`};b.write("const input = payload.value;");let I=Object.create(null),Ee=0;for(let re of _.keys)I[re]=`key_${Ee++}`;b.write("const newResult = {};");for(let re of _.keys){let B=I[re],G=Pr(re),vm=h[re]?._zod?.optout==="optional";b.write(`const ${B} = ${w(re)};`),vm?b.write(`
|
|
6
|
+
if (${B}.issues.length) {
|
|
7
|
+
if (${G} in input) {
|
|
8
|
+
payload.issues = payload.issues.concat(${B}.issues.map(iss => ({
|
|
9
|
+
...iss,
|
|
10
|
+
path: iss.path ? [${G}, ...iss.path] : [${G}]
|
|
11
|
+
})));
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
if (${B}.value === undefined) {
|
|
16
|
+
if (${G} in input) {
|
|
17
|
+
newResult[${G}] = undefined;
|
|
18
|
+
}
|
|
19
|
+
} else {
|
|
20
|
+
newResult[${G}] = ${B}.value;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
`):b.write(`
|
|
24
|
+
if (${B}.issues.length) {
|
|
25
|
+
payload.issues = payload.issues.concat(${B}.issues.map(iss => ({
|
|
26
|
+
...iss,
|
|
27
|
+
path: iss.path ? [${G}, ...iss.path] : [${G}]
|
|
28
|
+
})));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (${B}.value === undefined) {
|
|
32
|
+
if (${G} in input) {
|
|
33
|
+
newResult[${G}] = undefined;
|
|
34
|
+
}
|
|
35
|
+
} else {
|
|
36
|
+
newResult[${G}] = ${B}.value;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
`)}b.write("payload.value = newResult;"),b.write("return payload;");let Sm=b.compile();return(re,B)=>Sm(h,re,B)},s,i=Ne,c=!Pt.jitless,l=c&&Do.value,p=t.catchall,d;e._zod.parse=(h,b)=>{d??(d=n.value);let _=h.value;return i(_)?c&&l&&b?.async===!1&&b.jitless!==!0?(s||(s=o(t.shape)),h=s(h,b),p?Cp([],_,h,b,d,e):h):r(h,b):(h.issues.push({expected:"object",code:"invalid_type",input:_,inst:e}),h)}});function bp(e,t,r,n){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let o=e.filter(s=>!he(s));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(s=>s.issues.map(i=>Z(i,n,E())))}),t)}var Bt=f("$ZodUnion",(e,t)=>{g.init(e,t),y(e._zod,"optin",()=>t.options.some(o=>o._zod.optin==="optional")?"optional":void 0),y(e._zod,"optout",()=>t.options.some(o=>o._zod.optout==="optional")?"optional":void 0),y(e._zod,"values",()=>{if(t.options.every(o=>o._zod.values))return new Set(t.options.flatMap(o=>Array.from(o._zod.values)))}),y(e._zod,"pattern",()=>{if(t.options.every(o=>o._zod.pattern)){let o=t.options.map(s=>s._zod.pattern);return new RegExp(`^(${o.map(s=>Ct(s.source)).join("|")})$`)}});let r=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(o,s)=>{if(r)return n(o,s);let i=!1,c=[];for(let u of t.options){let l=u._zod.run({value:o.value,issues:[]},s);if(l instanceof Promise)c.push(l),i=!0;else{if(l.issues.length===0)return l;c.push(l)}}return i?Promise.all(c).then(u=>bp(u,o,e,s)):bp(c,o,e,s)}});function gp(e,t,r,n){let o=e.filter(s=>s.issues.length===0);return o.length===1?(t.value=o[0].value,t):(o.length===0?t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(s=>s.issues.map(i=>Z(i,n,E())))}):t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:[],inclusive:!1}),t)}var Di=f("$ZodXor",(e,t)=>{Bt.init(e,t),t.inclusive=!1;let r=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(o,s)=>{if(r)return n(o,s);let i=!1,c=[];for(let u of t.options){let l=u._zod.run({value:o.value,issues:[]},s);l instanceof Promise?(c.push(l),i=!0):c.push(l)}return i?Promise.all(c).then(u=>gp(u,o,e,s)):gp(c,o,e,s)}}),Fi=f("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Bt.init(e,t);let r=e._zod.parse;y(e._zod,"propValues",()=>{let o={};for(let s of t.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let[c,u]of Object.entries(i)){o[c]||(o[c]=new Set);for(let l of u)o[c].add(l)}}return o});let n=Ke(()=>{let o=t.options,s=new Map;for(let i of o){let c=i._zod.propValues?.[t.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let u of c){if(s.has(u))throw new Error(`Duplicate discriminator value "${String(u)}"`);s.set(u,i)}}return s});e._zod.parse=(o,s)=>{let i=o.value;if(!Ne(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;let c=n.value.get(i?.[t.discriminator]);return c?c._zod.run(o,s):t.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:i,path:[t.discriminator],inst:e}),o)}}),Mi=f("$ZodIntersection",(e,t)=>{g.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,s=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([u,l])=>yp(r,u,l)):yp(r,s,i)}});function ri(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(me(e)&&me(t)){let r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),o={...e,...t};for(let s of n){let i=ri(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],s=t[n],i=ri(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function yp(e,t,r){let n=new Map,o;for(let c of t.issues)if(c.code==="unrecognized_keys"){o??(o=c);for(let u of c.keys)n.has(u)||n.set(u,{}),n.get(u).l=!0}else e.issues.push(c);for(let c of r.issues)if(c.code==="unrecognized_keys")for(let u of c.keys)n.has(u)||n.set(u,{}),n.get(u).r=!0;else e.issues.push(c);let s=[...n].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(s.length&&o&&e.issues.push({...o,keys:s}),he(e))return e;let i=ri(t.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}var Kr=f("$ZodTuple",(e,t)=>{g.init(e,t);let r=t.items;e._zod.parse=(n,o)=>{let s=n.value;if(!Array.isArray(s))return n.issues.push({input:s,inst:e,expected:"tuple",code:"invalid_type"}),n;n.value=[];let i=[],c=[...r].reverse().findIndex(p=>p._zod.optin!=="optional"),u=c===-1?0:r.length-c;if(!t.rest){let p=s.length>r.length,d=s.length<u-1;if(p||d)return n.issues.push({...p?{code:"too_big",maximum:r.length,inclusive:!0}:{code:"too_small",minimum:r.length},input:s,inst:e,origin:"array"}),n}let l=-1;for(let p of r){if(l++,l>=s.length&&l>=u)continue;let d=p._zod.run({value:s[l],issues:[]},o);d instanceof Promise?i.push(d.then(h=>Br(h,n,l))):Br(d,n,l)}if(t.rest){let p=s.slice(r.length);for(let d of p){l++;let h=t.rest._zod.run({value:d,issues:[]},o);h instanceof Promise?i.push(h.then(b=>Br(b,n,l))):Br(h,n,l)}}return i.length?Promise.all(i).then(()=>n):n}});function Br(e,t,r){e.issues.length&&t.issues.push(...U(r,e.issues)),t.value[r]=e.value}var Ui=f("$ZodRecord",(e,t)=>{g.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!me(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let s=[],i=t.keyType._zod.values;if(i){r.value={};let c=new Set;for(let l of i)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){c.add(typeof l=="number"?l.toString():l);let p=t.valueType._zod.run({value:o[l],issues:[]},n);p instanceof Promise?s.push(p.then(d=>{d.issues.length&&r.issues.push(...U(l,d.issues)),r.value[l]=d.value})):(p.issues.length&&r.issues.push(...U(l,p.issues)),r.value[l]=p.value)}let u;for(let l in o)c.has(l)||(u=u??[],u.push(l));u&&u.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:u})}else{r.value={};for(let c of Reflect.ownKeys(o)){if(c==="__proto__")continue;let u=t.keyType._zod.run({value:c,issues:[]},n);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof c=="string"&&Lr.test(c)&&u.issues.length){let d=t.keyType._zod.run({value:Number(c),issues:[]},n);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(u=d)}if(u.issues.length){t.mode==="loose"?r.value[c]=o[c]:r.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(d=>Z(d,n,E())),input:c,path:[c],inst:e});continue}let p=t.valueType._zod.run({value:o[c],issues:[]},n);p instanceof Promise?s.push(p.then(d=>{d.issues.length&&r.issues.push(...U(c,d.issues)),r.value[u.value]=d.value})):(p.issues.length&&r.issues.push(...U(c,p.issues)),r.value[u.value]=p.value)}}return s.length?Promise.all(s).then(()=>r):r}}),qi=f("$ZodMap",(e,t)=>{g.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!(o instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:o,inst:e}),r;let s=[];r.value=new Map;for(let[i,c]of o){let u=t.keyType._zod.run({value:i,issues:[]},n),l=t.valueType._zod.run({value:c,issues:[]},n);u instanceof Promise||l instanceof Promise?s.push(Promise.all([u,l]).then(([p,d])=>{kp(p,d,r,i,o,e,n)})):kp(u,l,r,i,o,e,n)}return s.length?Promise.all(s).then(()=>r):r}});function kp(e,t,r,n,o,s,i){e.issues.length&&(Tt.has(typeof n)?r.issues.push(...U(n,e.issues)):r.issues.push({code:"invalid_key",origin:"map",input:o,inst:s,issues:e.issues.map(c=>Z(c,i,E()))})),t.issues.length&&(Tt.has(typeof n)?r.issues.push(...U(n,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:o,inst:s,key:n,issues:t.issues.map(c=>Z(c,i,E()))})),r.value.set(e.value,t.value)}var Ki=f("$ZodSet",(e,t)=>{g.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!(o instanceof Set))return r.issues.push({input:o,inst:e,expected:"set",code:"invalid_type"}),r;let s=[];r.value=new Set;for(let i of o){let c=t.valueType._zod.run({value:i,issues:[]},n);c instanceof Promise?s.push(c.then(u=>_p(u,r))):_p(c,r)}return s.length?Promise.all(s).then(()=>r):r}});function _p(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}var Hi=f("$ZodEnum",(e,t)=>{g.init(e,t);let r=Rt(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(o=>Tt.has(typeof o)).map(o=>typeof o=="string"?H(o):o.toString()).join("|")})$`),e._zod.parse=(o,s)=>{let i=o.value;return n.has(i)||o.issues.push({code:"invalid_value",values:r,input:i,inst:e}),o}}),Wi=f("$ZodLiteral",(e,t)=>{if(g.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?H(n):n?H(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,o)=>{let s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),n}}),Ji=f("$ZodFile",(e,t)=>{g.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;return o instanceof File||r.issues.push({expected:"file",code:"invalid_type",input:o,inst:e}),r}}),Yi=f("$ZodTransform",(e,t)=>{g.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new qe(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Q;return r.value=o,r}});function wp(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var Hr=f("$ZodOptional",(e,t)=>{g.init(e,t),e._zod.optin="optional",e._zod.optout="optional",y(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),y(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Ct(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>wp(s,r.value)):wp(o,r.value)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),Gi=f("$ZodExactOptional",(e,t)=>{Hr.init(e,t),y(e._zod,"values",()=>t.innerType._zod.values),y(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),Vi=f("$ZodNullable",(e,t)=>{g.init(e,t),y(e._zod,"optin",()=>t.innerType._zod.optin),y(e._zod,"optout",()=>t.innerType._zod.optout),y(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Ct(r.source)}|null)$`):void 0}),y(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),Qi=f("$ZodDefault",(e,t)=>{g.init(e,t),e._zod.optin="optional",y(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>xp(s,t)):xp(o,t)}});function xp(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Xi=f("$ZodPrefault",(e,t)=>{g.init(e,t),e._zod.optin="optional",y(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),ea=f("$ZodNonOptional",(e,t)=>{g.init(e,t),y(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Sp(s,e)):Sp(o,e)}});function Sp(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var ta=f("$ZodSuccess",(e,t)=>{g.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new qe("ZodSuccess");let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.issues.length===0,r)):(r.value=o.issues.length===0,r)}}),ra=f("$ZodCatch",(e,t)=>{g.init(e,t),y(e._zod,"optin",()=>t.innerType._zod.optin),y(e._zod,"optout",()=>t.innerType._zod.optout),y(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(i=>Z(i,n,E()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>Z(s,n,E()))},input:r.value}),r.issues=[]),r)}}),na=f("$ZodNaN",(e,t)=>{g.init(e,t),e._zod.parse=(r,n)=>((typeof r.value!="number"||!Number.isNaN(r.value))&&r.issues.push({input:r.value,inst:e,expected:"nan",code:"invalid_type"}),r)}),oa=f("$ZodPipe",(e,t)=>{g.init(e,t),y(e._zod,"values",()=>t.in._zod.values),y(e._zod,"optin",()=>t.in._zod.optin),y(e._zod,"optout",()=>t.out._zod.optout),y(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=t.out._zod.run(r,n);return s instanceof Promise?s.then(i=>Or(i,t.in,n)):Or(s,t.in,n)}let o=t.in._zod.run(r,n);return o instanceof Promise?o.then(s=>Or(s,t.out,n)):Or(o,t.out,n)}});function Or(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}var Ot=f("$ZodCodec",(e,t)=>{g.init(e,t),y(e._zod,"values",()=>t.in._zod.values),y(e._zod,"optin",()=>t.in._zod.optin),y(e._zod,"optout",()=>t.out._zod.optout),y(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if((n.direction||"forward")==="forward"){let s=t.in._zod.run(r,n);return s instanceof Promise?s.then(i=>Zr(i,t,n)):Zr(s,t,n)}else{let s=t.out._zod.run(r,n);return s instanceof Promise?s.then(i=>Zr(i,t,n)):Zr(s,t,n)}}});function Zr(e,t,r){if(e.issues.length)return e.aborted=!0,e;if((r.direction||"forward")==="forward"){let o=t.transform(e.value,e);return o instanceof Promise?o.then(s=>Dr(e,s,t.out,r)):Dr(e,o,t.out,r)}else{let o=t.reverseTransform(e.value,e);return o instanceof Promise?o.then(s=>Dr(e,s,t.in,r)):Dr(e,o,t.in,r)}}function Dr(e,t,r,n){return e.issues.length?(e.aborted=!0,e):r._zod.run({value:t,issues:e.issues},n)}var sa=f("$ZodReadonly",(e,t)=>{g.init(e,t),y(e._zod,"propValues",()=>t.innerType._zod.propValues),y(e._zod,"values",()=>t.innerType._zod.values),y(e._zod,"optin",()=>t.innerType?._zod?.optin),y(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(vp):vp(o)}});function vp(e){return e.value=Object.freeze(e.value),e}var ia=f("$ZodTemplateLiteral",(e,t)=>{g.init(e,t);let r=[];for(let n of t.parts)if(typeof n=="object"&&n!==null){if(!n._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...n._zod.traits].shift()}`);let o=n._zod.pattern instanceof RegExp?n._zod.pattern.source:n._zod.pattern;if(!o)throw new Error(`Invalid template literal part: ${n._zod.traits}`);let s=o.startsWith("^")?1:0,i=o.endsWith("$")?o.length-1:o.length;r.push(o.slice(s,i))}else if(n===null||Fo.has(typeof n))r.push(H(`${n}`));else throw new Error(`Invalid template literal part: ${n}`);e._zod.pattern=new RegExp(`^${r.join("")}$`),e._zod.parse=(n,o)=>typeof n.value!="string"?(n.issues.push({input:n.value,inst:e,expected:"string",code:"invalid_type"}),n):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),n)}),aa=f("$ZodFunction",(e,t)=>(g.init(e,t),e._def=t,e._zod.def=t,e.implement=r=>{if(typeof r!="function")throw new Error("implement() must be called with a function");return function(...n){let o=e._def.input?be(e._def.input,n):n,s=Reflect.apply(r,this,o);return e._def.output?be(e._def.output,s):s}},e.implementAsync=r=>{if(typeof r!="function")throw new Error("implementAsync() must be called with a function");return async function(...n){let o=e._def.input?await ge(e._def.input,n):n,s=await Reflect.apply(r,this,o);return e._def.output?await ge(e._def.output,s):s}},e._zod.parse=(r,n)=>typeof r.value!="function"?(r.issues.push({code:"invalid_type",expected:"function",input:r.value,inst:e}),r):(e._def.output&&e._def.output._zod.def.type==="promise"?r.value=e.implementAsync(r.value):r.value=e.implement(r.value),r),e.input=(...r)=>{let n=e.constructor;return Array.isArray(r[0])?new n({type:"function",input:new Kr({type:"tuple",items:r[0],rest:r[1]}),output:e._def.output}):new n({type:"function",input:r[0],output:e._def.output})},e.output=r=>{let n=e.constructor;return new n({type:"function",input:e._def.input,output:r})},e)),ca=f("$ZodPromise",(e,t)=>{g.init(e,t),e._zod.parse=(r,n)=>Promise.resolve(r.value).then(o=>t.innerType._zod.run({value:o,issues:[]},n))}),ua=f("$ZodLazy",(e,t)=>{g.init(e,t),y(e._zod,"innerType",()=>t.getter()),y(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),y(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),y(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),y(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),la=f("$ZodCustom",(e,t)=>{$.init(e,t),g.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(s=>$p(s,r,n,e));$p(o,r,n,e)}});function $p(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(We(o))}}var Zt={};ze(Zt,{default:()=>Lh});var Lh={};var Tp,pa=Symbol("ZodOutput"),fa=Symbol("ZodInput"),Wr=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){let n=r[0];return this._map.set(t,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let o={...n,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};function Jr(){return new Wr}(Tp=globalThis).__zod_globalRegistry??(Tp.__zod_globalRegistry=Jr());var ne=globalThis.__zod_globalRegistry;function da(e,t){return new e({type:"string",...m(t)})}function ma(e,t){return new e({type:"string",coerce:!0,...m(t)})}function ha(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...m(t)})}function ba(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...m(t)})}function ga(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...m(t)})}function ya(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...m(t)})}function ka(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...m(t)})}function _a(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...m(t)})}function Yr(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...m(t)})}function wa(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...m(t)})}function xa(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...m(t)})}function Sa(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...m(t)})}function va(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...m(t)})}function $a(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...m(t)})}function Pa(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...m(t)})}function Ia(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...m(t)})}function Ra(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...m(t)})}function Ca(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...m(t)})}function Ta(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...m(t)})}function Ea(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...m(t)})}function za(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...m(t)})}function Aa(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...m(t)})}function La(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...m(t)})}function Na(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...m(t)})}function ja(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...m(t)})}var Ba={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function Oa(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...m(t)})}function Za(e,t){return new e({type:"string",format:"date",check:"string_format",...m(t)})}function Da(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...m(t)})}function Fa(e,t){return new e({type:"string",format:"duration",check:"string_format",...m(t)})}function Ma(e,t){return new e({type:"number",checks:[],...m(t)})}function Ua(e,t){return new e({type:"number",coerce:!0,checks:[],...m(t)})}function qa(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...m(t)})}function Ka(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...m(t)})}function Ha(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...m(t)})}function Wa(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...m(t)})}function Ja(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...m(t)})}function Ya(e,t){return new e({type:"boolean",...m(t)})}function Ga(e,t){return new e({type:"boolean",coerce:!0,...m(t)})}function Va(e,t){return new e({type:"bigint",...m(t)})}function Qa(e,t){return new e({type:"bigint",coerce:!0,...m(t)})}function Xa(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...m(t)})}function ec(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...m(t)})}function tc(e,t){return new e({type:"symbol",...m(t)})}function rc(e,t){return new e({type:"undefined",...m(t)})}function nc(e,t){return new e({type:"null",...m(t)})}function oc(e){return new e({type:"any"})}function sc(e){return new e({type:"unknown"})}function ic(e,t){return new e({type:"never",...m(t)})}function ac(e,t){return new e({type:"void",...m(t)})}function cc(e,t){return new e({type:"date",...m(t)})}function uc(e,t){return new e({type:"date",coerce:!0,...m(t)})}function lc(e,t){return new e({type:"nan",...m(t)})}function Gr(e,t){return new Nr({check:"less_than",...m(t),value:e,inclusive:!1})}function Dt(e,t){return new Nr({check:"less_than",...m(t),value:e,inclusive:!0})}function Vr(e,t){return new jr({check:"greater_than",...m(t),value:e,inclusive:!1})}function Ft(e,t){return new jr({check:"greater_than",...m(t),value:e,inclusive:!0})}function pc(e){return Vr(0,e)}function fc(e){return Gr(0,e)}function dc(e){return Dt(0,e)}function mc(e){return Ft(0,e)}function hc(e,t){return new Bs({check:"multiple_of",...m(t),value:e})}function bc(e,t){return new Ds({check:"max_size",...m(t),maximum:e})}function gc(e,t){return new Fs({check:"min_size",...m(t),minimum:e})}function yc(e,t){return new Ms({check:"size_equals",...m(t),size:e})}function kc(e,t){return new Us({check:"max_length",...m(t),maximum:e})}function _c(e,t){return new qs({check:"min_length",...m(t),minimum:e})}function wc(e,t){return new Ks({check:"length_equals",...m(t),length:e})}function xc(e,t){return new Hs({check:"string_format",format:"regex",...m(t),pattern:e})}function Sc(e){return new Ws({check:"string_format",format:"lowercase",...m(e)})}function vc(e){return new Js({check:"string_format",format:"uppercase",...m(e)})}function $c(e,t){return new Ys({check:"string_format",format:"includes",...m(t),includes:e})}function Pc(e,t){return new Gs({check:"string_format",format:"starts_with",...m(t),prefix:e})}function Ic(e,t){return new Vs({check:"string_format",format:"ends_with",...m(t),suffix:e})}function Rc(e,t,r){return new Qs({check:"property",property:e,schema:t,...m(r)})}function Cc(e,t){return new Xs({check:"mime_type",mime:e,...m(t)})}function ye(e){return new ei({check:"overwrite",tx:e})}function Tc(e){return ye(t=>t.normalize(e))}function Ec(){return ye(e=>e.trim())}function zc(){return ye(e=>e.toLowerCase())}function Ac(){return ye(e=>e.toUpperCase())}function jh(){return ye(e=>Zo(e))}function Bh(e,t,r){return new e({type:"array",element:t,...m(r)})}function Oh(e,t,r){return new e({type:"union",options:t,...m(r)})}function Zh(e,t,r){return new e({type:"union",options:t,inclusive:!1,...m(r)})}function Dh(e,t,r,n){return new e({type:"union",options:r,discriminator:t,...m(n)})}function Fh(e,t,r){return new e({type:"intersection",left:t,right:r})}function Mh(e,t,r,n){let o=r instanceof g,s=o?n:r,i=o?r:null;return new e({type:"tuple",items:t,rest:i,...m(s)})}function Uh(e,t,r,n){return new e({type:"record",keyType:t,valueType:r,...m(n)})}function qh(e,t,r,n){return new e({type:"map",keyType:t,valueType:r,...m(n)})}function Kh(e,t,r){return new e({type:"set",valueType:t,...m(r)})}function Hh(e,t,r){let n=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new e({type:"enum",entries:n,...m(r)})}function Wh(e,t,r){return new e({type:"enum",entries:t,...m(r)})}function Jh(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...m(r)})}function Lc(e,t){return new e({type:"file",...m(t)})}function Yh(e,t){return new e({type:"transform",transform:t})}function Gh(e,t){return new e({type:"optional",innerType:t})}function Vh(e,t){return new e({type:"nullable",innerType:t})}function Qh(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():He(r)}})}function Xh(e,t,r){return new e({type:"nonoptional",innerType:t,...m(r)})}function eb(e,t){return new e({type:"success",innerType:t})}function tb(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:()=>r})}function rb(e,t,r){return new e({type:"pipe",in:t,out:r})}function nb(e,t){return new e({type:"readonly",innerType:t})}function ob(e,t,r){return new e({type:"template_literal",parts:t,...m(r)})}function sb(e,t){return new e({type:"lazy",getter:t})}function ib(e,t){return new e({type:"promise",innerType:t})}function Nc(e,t,r){let n=m(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function jc(e,t,r){return new e({type:"custom",check:"custom",fn:t,...m(r)})}function Bc(e){let t=Ep(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(We(n,r.value,t._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(We(o))}},e(r.value,r)));return t}function Ep(e,t){let r=new $({check:"custom",...m(t)});return r._zod.check=e,r}function Oc(e){let t=new $({check:"describe"});return t._zod.onattach=[r=>{let n=ne.get(r)??{};ne.add(r,{...n,description:e})}],t._zod.check=()=>{},t}function Zc(e){let t=new $({check:"meta"});return t._zod.onattach=[r=>{let n=ne.get(r)??{};ne.add(r,{...n,...e})}],t._zod.check=()=>{},t}function Dc(e,t){let r=m(t),n=r.truthy??["true","1","yes","on","y","enabled"],o=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(n=n.map(b=>typeof b=="string"?b.toLowerCase():b),o=o.map(b=>typeof b=="string"?b.toLowerCase():b));let s=new Set(n),i=new Set(o),c=e.Codec??Ot,u=e.Boolean??jt,l=e.String??Ye,p=new l({type:"string",error:r.error}),d=new u({type:"boolean",error:r.error}),h=new c({type:"pipe",in:p,out:d,transform:((b,_)=>{let w=b;return r.case!=="sensitive"&&(w=w.toLowerCase()),s.has(w)?!0:i.has(w)?!1:(_.issues.push({code:"invalid_value",expected:"stringbool",values:[...s,...i],input:_.value,inst:h,continue:!1}),{})}),reverseTransform:((b,_)=>b===!0?n[0]||"true":o[0]||"false"),error:r.error});return h}function Ge(e,t,r,n={}){let o=m(n),s={...m(n),check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:c=>r.test(c),...o};return r instanceof RegExp&&(s.pattern=r),new e(s)}function ke(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??ne,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function x(e,t,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s=t.seen.get(e);if(s)return s.count++,r.schemaPath.includes(e)&&(s.cycle=r.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i);let c=e._zod.toJSONSchema?.();if(c)i.schema=c;else{let p={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,p);else{let h=i.schema,b=t.processors[o.type];if(!b)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);b(e,t,h,p)}let d=e._zod.parent;d&&(i.ref||(i.ref=d),x(d,t,p),t.seen.get(d).isParent=!0)}let u=t.metadataRegistry.get(e);return u&&Object.assign(i.schema,u),t.io==="input"&&L(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&i.schema._prefault&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function _e(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let i of e.seen.entries()){let c=e.metadataRegistry.get(i[0])?.id;if(c){let u=n.get(c);if(u&&u!==i[0])throw new Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(c,i[0])}}let o=i=>{let c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let d=e.external.registry.get(i[0])?.id,h=e.external.uri??(_=>_);if(d)return{ref:h(d)};let b=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=b,{defId:b,ref:`${h("__shared")}#/${c}/${b}`}}if(i[1]===r)return{ref:"#"};let l=`#/${c}/`,p=i[1].schema.id??`__schema${e.counter++}`;return{defId:p,ref:l+p}},s=i=>{if(i[1].schema.$ref)return;let c=i[1],{ref:u,defId:l}=o(i);c.def={...c.schema},l&&(c.defId=l);let p=c.schema;for(let d in p)delete p[d];p.$ref=u};if(e.cycles==="throw")for(let i of e.seen.entries()){let c=i[1];if(c.cycle)throw new Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
|
|
40
|
+
|
|
41
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let c=i[1];if(t===i[0]){s(i);continue}if(e.external){let l=e.external.registry.get(i[0])?.id;if(t!==i[0]&&l){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(c.cycle){s(i);continue}if(c.count>1&&e.reused==="ref"){s(i);continue}}}function we(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=i=>{let c=e.seen.get(i);if(c.ref===null)return;let u=c.def??c.schema,l={...u},p=c.ref;if(c.ref=null,p){n(p);let h=e.seen.get(p),b=h.schema;if(b.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(b)):Object.assign(u,b),Object.assign(u,l),i._zod.parent===p)for(let w in u)w==="$ref"||w==="allOf"||w in l||delete u[w];if(b.$ref&&h.def)for(let w in u)w==="$ref"||w==="allOf"||w in h.def&&JSON.stringify(u[w])===JSON.stringify(h.def[w])&&delete u[w]}let d=i._zod.parent;if(d&&d!==p){n(d);let h=e.seen.get(d);if(h?.schema.$ref&&(u.$ref=h.schema.$ref,h.def))for(let b in u)b==="$ref"||b==="allOf"||b in h.def&&JSON.stringify(u[b])===JSON.stringify(h.def[b])&&delete u[b]}e.override({zodSchema:i,jsonSchema:u,path:c.path??[]})};for(let i of[...e.seen.entries()].reverse())n(i[0]);let o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let i=e.external.registry.get(t)?.id;if(!i)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(i)}Object.assign(o,r.def??r.schema);let s=e.external?.defs??{};for(let i of e.seen.entries()){let c=i[1];c.def&&c.defId&&(s[c.defId]=c.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?o.$defs=s:o.definitions=s);try{let i=JSON.parse(JSON.stringify(o));return Object.defineProperty(i,"~standard",{value:{...t["~standard"],jsonSchema:{input:Fc(t,"input",e.processors),output:Fc(t,"output",e.processors)}},enumerable:!1,writable:!1}),i}catch{throw new Error("Error converting schema to JSON.")}}function L(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return L(n.element,r);if(n.type==="set")return L(n.valueType,r);if(n.type==="lazy")return L(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return L(n.innerType,r);if(n.type==="intersection")return L(n.left,r)||L(n.right,r);if(n.type==="record"||n.type==="map")return L(n.keyType,r)||L(n.valueType,r);if(n.type==="pipe")return L(n.in,r)||L(n.out,r);if(n.type==="object"){for(let o in n.shape)if(L(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(L(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(L(o,r))return!0;return!!(n.rest&&L(n.rest,r))}return!1}var ab=(e,t={})=>r=>{let n=ke({...r,processors:t});return x(e,n),_e(n,e),we(n,e)},Fc=(e,t,r={})=>n=>{let{libraryOptions:o,target:s}=n??{},i=ke({...o??{},target:s,io:t,processors:r});return x(e,i),_e(i,e),we(i,e)};var cb={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ub=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:i,format:c,patterns:u,contentEncoding:l}=e._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),c&&(o.format=cb[c]??c,o.format===""&&delete o.format,c==="time"&&delete o.format),l&&(o.contentEncoding=l),u&&u.size>0){let p=[...u];p.length===1?o.pattern=p[0].source:p.length>1&&(o.allOf=[...p.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},lb=(e,t,r,n)=>{let o=r,{minimum:s,maximum:i,format:c,multipleOf:u,exclusiveMaximum:l,exclusiveMinimum:p}=e._zod.bag;typeof c=="string"&&c.includes("int")?o.type="integer":o.type="number",typeof p=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.minimum=p,o.exclusiveMinimum=!0):o.exclusiveMinimum=p),typeof s=="number"&&(o.minimum=s,typeof p=="number"&&t.target!=="draft-04"&&(p>=s?delete o.minimum:delete o.exclusiveMinimum)),typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.maximum=l,o.exclusiveMaximum=!0):o.exclusiveMaximum=l),typeof i=="number"&&(o.maximum=i,typeof l=="number"&&t.target!=="draft-04"&&(l<=i?delete o.maximum:delete o.exclusiveMaximum)),typeof u=="number"&&(o.multipleOf=u)},pb=(e,t,r,n)=>{r.type="boolean"},fb=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},db=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},mb=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},hb=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},bb=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},gb=(e,t,r,n)=>{r.not={}},yb=(e,t,r,n)=>{},kb=(e,t,r,n)=>{},_b=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},wb=(e,t,r,n)=>{let o=e._zod.def,s=Rt(o.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},xb=(e,t,r,n)=>{let o=e._zod.def,s=[];for(let i of o.values)if(i===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){let i=s[0];r.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[i]:r.const=i}else s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),s.every(i=>typeof i=="boolean")&&(r.type="boolean"),s.every(i=>i===null)&&(r.type="null"),r.enum=s},Sb=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},vb=(e,t,r,n)=>{let o=r,s=e._zod.pattern;if(!s)throw new Error("Pattern not found in template literal");o.type="string",o.pattern=s.source},$b=(e,t,r,n)=>{let o=r,s={type:"string",format:"binary",contentEncoding:"binary"},{minimum:i,maximum:c,mime:u}=e._zod.bag;i!==void 0&&(s.minLength=i),c!==void 0&&(s.maxLength=c),u?u.length===1?(s.contentMediaType=u[0],Object.assign(o,s)):(Object.assign(o,s),o.anyOf=u.map(l=>({contentMediaType:l}))):Object.assign(o,s)},Pb=(e,t,r,n)=>{r.type="boolean"},Ib=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Rb=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},Cb=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Tb=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},Eb=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},zb=(e,t,r,n)=>{let o=r,s=e._zod.def,{minimum:i,maximum:c}=e._zod.bag;typeof i=="number"&&(o.minItems=i),typeof c=="number"&&(o.maxItems=c),o.type="array",o.items=x(s.element,t,{...n,path:[...n.path,"items"]})},Ab=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="object",o.properties={};let i=s.shape;for(let l in i)o.properties[l]=x(i[l],t,{...n,path:[...n.path,"properties",l]});let c=new Set(Object.keys(i)),u=new Set([...c].filter(l=>{let p=s.shape[l]._zod;return t.io==="input"?p.optin===void 0:p.optout===void 0}));u.size>0&&(o.required=Array.from(u)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=x(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},Lb=(e,t,r,n)=>{let o=e._zod.def,s=o.inclusive===!1,i=o.options.map((c,u)=>x(c,t,{...n,path:[...n.path,s?"oneOf":"anyOf",u]}));s?r.oneOf=i:r.anyOf=i},Nb=(e,t,r,n)=>{let o=e._zod.def,s=x(o.left,t,{...n,path:[...n.path,"allOf",0]}),i=x(o.right,t,{...n,path:[...n.path,"allOf",1]}),c=l=>"allOf"in l&&Object.keys(l).length===1,u=[...c(s)?s.allOf:[s],...c(i)?i.allOf:[i]];r.allOf=u},jb=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="array";let i=t.target==="draft-2020-12"?"prefixItems":"items",c=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",u=s.items.map((h,b)=>x(h,t,{...n,path:[...n.path,i,b]})),l=s.rest?x(s.rest,t,{...n,path:[...n.path,c,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null;t.target==="draft-2020-12"?(o.prefixItems=u,l&&(o.items=l)):t.target==="openapi-3.0"?(o.items={anyOf:u},l&&o.items.anyOf.push(l),o.minItems=u.length,l||(o.maxItems=u.length)):(o.items=u,l&&(o.additionalItems=l));let{minimum:p,maximum:d}=e._zod.bag;typeof p=="number"&&(o.minItems=p),typeof d=="number"&&(o.maxItems=d)},Bb=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="object";let i=s.keyType,u=i._zod.bag?.patterns;if(s.mode==="loose"&&u&&u.size>0){let p=x(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let d of u)o.patternProperties[d.source]=p}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=x(s.keyType,t,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=x(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]});let l=i._zod.values;if(l){let p=[...l].filter(d=>typeof d=="string"||typeof d=="number");p.length>0&&(o.required=p)}},Ob=(e,t,r,n)=>{let o=e._zod.def,s=x(o.innerType,t,n),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=o.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},Zb=(e,t,r,n)=>{let o=e._zod.def;x(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},Db=(e,t,r,n)=>{let o=e._zod.def;x(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},Fb=(e,t,r,n)=>{let o=e._zod.def;x(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},Mb=(e,t,r,n)=>{let o=e._zod.def;x(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},Ub=(e,t,r,n)=>{let o=e._zod.def,s=t.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;x(s,t,n);let i=t.seen.get(e);i.ref=s},qb=(e,t,r,n)=>{let o=e._zod.def;x(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.readOnly=!0},Kb=(e,t,r,n)=>{let o=e._zod.def;x(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},Hb=(e,t,r,n)=>{let o=e._zod.def;x(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},Wb=(e,t,r,n)=>{let o=e._zod.innerType;x(o,t,n);let s=t.seen.get(e);s.ref=o},Qr={string:ub,number:lb,boolean:pb,bigint:fb,symbol:db,null:mb,undefined:hb,void:bb,never:gb,any:yb,unknown:kb,date:_b,enum:wb,literal:xb,nan:Sb,template_literal:vb,file:$b,success:Pb,custom:Ib,function:Rb,transform:Cb,map:Tb,set:Eb,array:zb,object:Ab,union:Lb,intersection:Nb,tuple:jb,record:Bb,nullable:Ob,nonoptional:Zb,default:Db,prefault:Fb,catch:Mb,pipe:Ub,readonly:qb,promise:Kb,optional:Hb,lazy:Wb};function Xr(e,t){if("_idmap"in e){let n=e,o=ke({...t,processors:Qr}),s={};for(let u of n._idmap.entries()){let[l,p]=u;x(p,o)}let i={},c={registry:n,uri:t?.uri,defs:s};o.external=c;for(let u of n._idmap.entries()){let[l,p]=u;_e(o,p),i[l]=we(o,p)}if(Object.keys(s).length>0){let u=o.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[u]:s}}return{schemas:i}}let r=ke({...t,processors:Qr});return x(e,r),_e(r,e),we(r,e)}var en=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(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let r=t?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=ke({processors:Qr,target:r,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,r={path:[],schemaPath:[]}){return x(t,this.ctx,r)}emit(t,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),_e(this.ctx,t);let n=we(this.ctx,t),{"~standard":o,...s}=n;return s}};var zp={};var k=f("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");g.init(e,t),e.def=t,e.type=t.type,e.parse=(r,n)=>be(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>je(e,r,n),e.parseAsync=async(r,n)=>ge(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Be(e,r,n),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]},{parent:!0}),e.with=e.check,e.clone=(r,n)=>A(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.apply=r=>r(e)}),Qe=f("ZodMiniString",(e,t)=>{Ye.init(e,t),k.init(e,t)});function Mc(e){return da(Qe,e)}var P=f("ZodMiniStringFormat",(e,t)=>{v.init(e,t),Qe.init(e,t)}),Ap=f("ZodMiniEmail",(e,t)=>{si.init(e,t),P.init(e,t)});function Yb(e){return ha(Ap,e)}var Lp=f("ZodMiniGUID",(e,t)=>{ni.init(e,t),P.init(e,t)});function Gb(e){return ba(Lp,e)}var Mt=f("ZodMiniUUID",(e,t)=>{oi.init(e,t),P.init(e,t)});function Vb(e){return ga(Mt,e)}function Qb(e){return ya(Mt,e)}function Xb(e){return ka(Mt,e)}function eg(e){return _a(Mt,e)}var Uc=f("ZodMiniURL",(e,t)=>{ii.init(e,t),P.init(e,t)});function tg(e){return Yr(Uc,e)}function rg(e){return Yr(Uc,{protocol:/^https?$/,hostname:J.domain,...m(e)})}var Np=f("ZodMiniEmoji",(e,t)=>{ai.init(e,t),P.init(e,t)});function ng(e){return wa(Np,e)}var jp=f("ZodMiniNanoID",(e,t)=>{ci.init(e,t),P.init(e,t)});function og(e){return xa(jp,e)}var Bp=f("ZodMiniCUID",(e,t)=>{ui.init(e,t),P.init(e,t)});function sg(e){return Sa(Bp,e)}var Op=f("ZodMiniCUID2",(e,t)=>{li.init(e,t),P.init(e,t)});function ig(e){return va(Op,e)}var Zp=f("ZodMiniULID",(e,t)=>{pi.init(e,t),P.init(e,t)});function ag(e){return $a(Zp,e)}var Dp=f("ZodMiniXID",(e,t)=>{fi.init(e,t),P.init(e,t)});function cg(e){return Pa(Dp,e)}var Fp=f("ZodMiniKSUID",(e,t)=>{di.init(e,t),P.init(e,t)});function ug(e){return Ia(Fp,e)}var Mp=f("ZodMiniIPv4",(e,t)=>{yi.init(e,t),P.init(e,t)});function lg(e){return Ra(Mp,e)}var Up=f("ZodMiniIPv6",(e,t)=>{ki.init(e,t),P.init(e,t)});function pg(e){return Ca(Up,e)}var qp=f("ZodMiniCIDRv4",(e,t)=>{wi.init(e,t),P.init(e,t)});function fg(e){return Ea(qp,e)}var Kp=f("ZodMiniCIDRv6",(e,t)=>{xi.init(e,t),P.init(e,t)});function dg(e){return za(Kp,e)}var Hp=f("ZodMiniMAC",(e,t)=>{_i.init(e,t),P.init(e,t)});function mg(e){return Ta(Hp,e)}var Wp=f("ZodMiniBase64",(e,t)=>{vi.init(e,t),P.init(e,t)});function hg(e){return Aa(Wp,e)}var Jp=f("ZodMiniBase64URL",(e,t)=>{$i.init(e,t),P.init(e,t)});function bg(e){return La(Jp,e)}var Yp=f("ZodMiniE164",(e,t)=>{Pi.init(e,t),P.init(e,t)});function gg(e){return Na(Yp,e)}var Gp=f("ZodMiniJWT",(e,t)=>{Ii.init(e,t),P.init(e,t)});function yg(e){return ja(Gp,e)}var Ut=f("ZodMiniCustomStringFormat",(e,t)=>{Ri.init(e,t),P.init(e,t)});function kg(e,t,r={}){return Ge(Ut,e,t,r)}function _g(e){return Ge(Ut,"hostname",J.hostname,e)}function wg(e){return Ge(Ut,"hex",J.hex,e)}function xg(e,t){let r=t?.enc??"hex",n=`${e}_${r}`,o=J[n];if(!o)throw new Error(`Unrecognized hash format: ${n}`);return Ge(Ut,n,o,t)}var qt=f("ZodMiniNumber",(e,t)=>{Mr.init(e,t),k.init(e,t)});function Vp(e){return Ma(qt,e)}var Xe=f("ZodMiniNumberFormat",(e,t)=>{Ci.init(e,t),qt.init(e,t)});function Sg(e){return qa(Xe,e)}function vg(e){return Ka(Xe,e)}function $g(e){return Ha(Xe,e)}function Pg(e){return Wa(Xe,e)}function Ig(e){return Ja(Xe,e)}var Kt=f("ZodMiniBoolean",(e,t)=>{jt.init(e,t),k.init(e,t)});function Qp(e){return Ya(Kt,e)}var Ht=f("ZodMiniBigInt",(e,t)=>{Ur.init(e,t),k.init(e,t)});function Rg(e){return Va(Ht,e)}var qc=f("ZodMiniBigIntFormat",(e,t)=>{Ti.init(e,t),Ht.init(e,t)});function Cg(e){return Xa(qc,e)}function Tg(e){return ec(qc,e)}var Xp=f("ZodMiniSymbol",(e,t)=>{Ei.init(e,t),k.init(e,t)});function Eg(e){return tc(Xp,e)}var ef=f("ZodMiniUndefined",(e,t)=>{zi.init(e,t),k.init(e,t)});function zg(e){return rc(ef,e)}var tf=f("ZodMiniNull",(e,t)=>{Ai.init(e,t),k.init(e,t)});function rf(e){return nc(tf,e)}var nf=f("ZodMiniAny",(e,t)=>{Li.init(e,t),k.init(e,t)});function Ag(){return oc(nf)}var of=f("ZodMiniUnknown",(e,t)=>{Ni.init(e,t),k.init(e,t)});function tn(){return sc(of)}var sf=f("ZodMiniNever",(e,t)=>{ji.init(e,t),k.init(e,t)});function af(e){return ic(sf,e)}var cf=f("ZodMiniVoid",(e,t)=>{Bi.init(e,t),k.init(e,t)});function Lg(e){return ac(cf,e)}var rn=f("ZodMiniDate",(e,t)=>{Oi.init(e,t),k.init(e,t)});function Ng(e){return cc(rn,e)}var uf=f("ZodMiniArray",(e,t)=>{Zi.init(e,t),k.init(e,t)});function Kc(e,t){return new uf({type:"array",element:e,...m(t)})}function jg(e){let t=e._zod.def.shape;return kf(Object.keys(t))}var nn=f("ZodMiniObject",(e,t)=>{qr.init(e,t),k.init(e,t),y(e,"shape",()=>t.shape)});function Bg(e,t){let r={type:"object",shape:e??{},...m(t)};return new nn(r)}function Og(e,t){return new nn({type:"object",shape:e,catchall:af(),...m(t)})}function Zg(e,t){return new nn({type:"object",shape:e,catchall:tn(),...m(t)})}function Dg(e,t){return Rr(e,t)}function Fg(e,t){return Wo(e,t)}function Mg(e,t){return Rr(e,t)}function Ug(e,t){return Ko(e,t)}function qg(e,t){return Ho(e,t)}function Kg(e,t){return Jo(Jc,e,t)}function Hg(e,t){return Yo(Yc,e,t)}function Wg(e,t){return e.clone({...e._zod.def,catchall:t})}var Hc=f("ZodMiniUnion",(e,t)=>{Bt.init(e,t),k.init(e,t)});function lf(e,t){return new Hc({type:"union",options:e,...m(t)})}var pf=f("ZodMiniXor",(e,t)=>{Hc.init(e,t),Di.init(e,t)});function Jg(e,t){return new pf({type:"union",options:e,inclusive:!1,...m(t)})}var ff=f("ZodMiniDiscriminatedUnion",(e,t)=>{Fi.init(e,t),k.init(e,t)});function Yg(e,t,r){return new ff({type:"union",options:t,discriminator:e,...m(r)})}var df=f("ZodMiniIntersection",(e,t)=>{Mi.init(e,t),k.init(e,t)});function Gg(e,t){return new df({type:"intersection",left:e,right:t})}var mf=f("ZodMiniTuple",(e,t)=>{Kr.init(e,t),k.init(e,t)});function hf(e,t,r){let n=t instanceof g,o=n?r:t,s=n?t:null;return new mf({type:"tuple",items:e,rest:s,...m(o)})}var on=f("ZodMiniRecord",(e,t)=>{Ui.init(e,t),k.init(e,t)});function bf(e,t,r){return new on({type:"record",keyType:e,valueType:t,...m(r)})}function Vg(e,t,r){let n=A(e);return n._zod.values=void 0,new on({type:"record",keyType:n,valueType:t,...m(r)})}function Qg(e,t,r){return new on({type:"record",keyType:e,valueType:t,mode:"loose",...m(r)})}var gf=f("ZodMiniMap",(e,t)=>{qi.init(e,t),k.init(e,t)});function Xg(e,t,r){return new gf({type:"map",keyType:e,valueType:t,...m(r)})}var yf=f("ZodMiniSet",(e,t)=>{Ki.init(e,t),k.init(e,t)});function ey(e,t){return new yf({type:"set",valueType:e,...m(t)})}var Wc=f("ZodMiniEnum",(e,t)=>{Hi.init(e,t),k.init(e,t),e.options=Object.values(t.entries)});function kf(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Wc({type:"enum",entries:r,...m(t)})}function ty(e,t){return new Wc({type:"enum",entries:e,...m(t)})}var _f=f("ZodMiniLiteral",(e,t)=>{Wi.init(e,t),k.init(e,t)});function ry(e,t){return new _f({type:"literal",values:Array.isArray(e)?e:[e],...m(t)})}var wf=f("ZodMiniFile",(e,t)=>{Ji.init(e,t),k.init(e,t)});function ny(e){return Lc(wf,e)}var xf=f("ZodMiniTransform",(e,t)=>{Yi.init(e,t),k.init(e,t)});function oy(e){return new xf({type:"transform",transform:e})}var Jc=f("ZodMiniOptional",(e,t)=>{Hr.init(e,t),k.init(e,t)});function Sf(e){return new Jc({type:"optional",innerType:e})}var vf=f("ZodMiniExactOptional",(e,t)=>{Gi.init(e,t),k.init(e,t)});function sy(e){return new vf({type:"optional",innerType:e})}var $f=f("ZodMiniNullable",(e,t)=>{Vi.init(e,t),k.init(e,t)});function Pf(e){return new $f({type:"nullable",innerType:e})}function iy(e){return Sf(Pf(e))}var If=f("ZodMiniDefault",(e,t)=>{Qi.init(e,t),k.init(e,t)});function ay(e,t){return new If({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():He(t)}})}var Rf=f("ZodMiniPrefault",(e,t)=>{Xi.init(e,t),k.init(e,t)});function cy(e,t){return new Rf({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():He(t)}})}var Yc=f("ZodMiniNonOptional",(e,t)=>{ea.init(e,t),k.init(e,t)});function uy(e,t){return new Yc({type:"nonoptional",innerType:e,...m(t)})}var Cf=f("ZodMiniSuccess",(e,t)=>{ta.init(e,t),k.init(e,t)});function ly(e){return new Cf({type:"success",innerType:e})}var Tf=f("ZodMiniCatch",(e,t)=>{ra.init(e,t),k.init(e,t)});function py(e,t){return new Tf({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Ef=f("ZodMiniNaN",(e,t)=>{na.init(e,t),k.init(e,t)});function fy(e){return lc(Ef,e)}var Gc=f("ZodMiniPipe",(e,t)=>{oa.init(e,t),k.init(e,t)});function dy(e,t){return new Gc({type:"pipe",in:e,out:t})}var Vc=f("ZodMiniCodec",(e,t)=>{Gc.init(e,t),Ot.init(e,t)});function my(e,t,r){return new Vc({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}var zf=f("ZodMiniReadonly",(e,t)=>{sa.init(e,t),k.init(e,t)});function hy(e){return new zf({type:"readonly",innerType:e})}var Af=f("ZodMiniTemplateLiteral",(e,t)=>{ia.init(e,t),k.init(e,t)});function by(e,t){return new Af({type:"template_literal",parts:e,...m(t)})}var Lf=f("ZodMiniLazy",(e,t)=>{ua.init(e,t),k.init(e,t)});function Nf(e){return new Lf({type:"lazy",getter:e})}var jf=f("ZodMiniPromise",(e,t)=>{ca.init(e,t),k.init(e,t)});function gy(e){return new jf({type:"promise",innerType:e})}var Qc=f("ZodMiniCustom",(e,t)=>{la.init(e,t),k.init(e,t)});function yy(e,t){let r=new $({check:"custom",...m(t)});return r._zod.check=e,r}function Bf(e,t){return Nc(Qc,e??(()=>!0),t)}function ky(e,t={}){return jc(Qc,e,t)}function _y(e){return Bc(e)}var wy=Oc,xy=Zc;function Sy(e,t={}){let r=Bf(n=>n instanceof e,t);return r._zod.bag.Class=e,r._zod.check=n=>{n.value instanceof e||n.issues.push({code:"invalid_type",expected:e.name,input:n.value,inst:r,path:[...r._zod.def.path??[]]})},r}var vy=(...e)=>Dc({Codec:Vc,Boolean:Kt,String:Qe},...e);function $y(){let e=Nf(()=>lf([Mc(),Vp(),Qp(),rf(),Kc(e),bf(Mc(),e)]));return e}var Of=f("ZodMiniFunction",(e,t)=>{aa.init(e,t),k.init(e,t)});function Py(e){return new Of({type:"function",input:Array.isArray(e?.input)?hf(e?.input):e?.input??Kc(tn()),output:e?.output??tn()})}var Xc={};ze(Xc,{ZodMiniISODate:()=>an,ZodMiniISODateTime:()=>sn,ZodMiniISODuration:()=>un,ZodMiniISOTime:()=>cn,date:()=>Ry,datetime:()=>Iy,duration:()=>Ty,time:()=>Cy});var sn=f("ZodMiniISODateTime",(e,t)=>{mi.init(e,t),P.init(e,t)});function Iy(e){return Oa(sn,e)}var an=f("ZodMiniISODate",(e,t)=>{hi.init(e,t),P.init(e,t)});function Ry(e){return Za(an,e)}var cn=f("ZodMiniISOTime",(e,t)=>{bi.init(e,t),P.init(e,t)});function Cy(e){return Da(cn,e)}var un=f("ZodMiniISODuration",(e,t)=>{gi.init(e,t),P.init(e,t)});function Ty(e){return Fa(un,e)}var eu={};ze(eu,{bigint:()=>Ly,boolean:()=>Ay,date:()=>Ny,number:()=>zy,string:()=>Ey});function Ey(e){return ma(Qe,e)}function zy(e){return Ua(qt,e)}function Ay(e){return Ga(Kt,e)}function Ly(e){return Qa(Ht,e)}function Ny(e){return uc(rn,e)}var q=a.string().check(a.minLength(1)),jy=a.string().check(a.regex(/^https?:\/\/.+/)),xe=a.object({CLANCY_BASE_BRANCH:a.optional(a.string()),CLANCY_LABEL:a.optional(a.string()),CLANCY_MODEL:a.optional(a.string()),CLANCY_NOTIFY_WEBHOOK:a.optional(a.string()),CLANCY_STATUS_IN_PROGRESS:a.optional(a.string()),CLANCY_STATUS_DONE:a.optional(a.string()),CLANCY_STATUS_REVIEW:a.optional(a.string()),MAX_ITERATIONS:a.optional(a.string()),PLAYWRIGHT_ENABLED:a.optional(a.string()),PLAYWRIGHT_DEV_PORT:a.optional(a.string()),CLANCY_ROLES:a.optional(a.string()),CLANCY_PLAN_STATUS:a.optional(a.string()),CLANCY_PLAN_LABEL:a.optional(a.string()),CLANCY_PLAN_STATE_TYPE:a.optional(a.string()),CLANCY_STATUS_PLANNED:a.optional(a.string()),CLANCY_SKIP_COMMENTS:a.optional(a.string()),GITHUB_TOKEN:a.optional(a.string()),GITLAB_TOKEN:a.optional(a.string()),BITBUCKET_USER:a.optional(a.string()),BITBUCKET_TOKEN:a.optional(a.string()),AZDO_PAT:a.optional(a.string()),CLANCY_GIT_PLATFORM:a.optional(a.string()),CLANCY_GIT_API_URL:a.optional(a.string()),CLANCY_MAX_REWORK:a.optional(a.string()),CLANCY_TDD:a.optional(a.string()),CLANCY_MODE:a.optional(a.string()),CLANCY_BRIEF_ISSUE_TYPE:a.optional(a.string()),CLANCY_BRIEF_EPIC:a.optional(a.string()),CLANCY_COMPONENT:a.optional(a.string()),CLANCY_FIX_RETRIES:a.optional(a.string()),CLANCY_VERIFY_COMMANDS:a.optional(a.string()),CLANCY_TOKEN_RATE:a.optional(a.string()),CLANCY_TIME_LIMIT:a.optional(a.string()),CLANCY_BRANCH_GUARD:a.optional(a.string()),CLANCY_LABEL_BRIEF:a.optional(a.string()),CLANCY_LABEL_PLAN:a.optional(a.string()),CLANCY_LABEL_BUILD:a.optional(a.string())}),ln=a.extend(xe,{JIRA_BASE_URL:jy,JIRA_USER:q,JIRA_API_TOKEN:q,JIRA_PROJECT_KEY:q,CLANCY_JQL_STATUS:a.optional(a.string()),CLANCY_JQL_SPRINT:a.optional(a.string())}),pn=a.extend(xe,{GITHUB_TOKEN:q,GITHUB_REPO:q}),fn=a.extend(xe,{LINEAR_API_KEY:q,LINEAR_TEAM_ID:q}),dn=a.extend(xe,{SHORTCUT_API_TOKEN:q,SHORTCUT_WORKFLOW:a.optional(a.string())}),mn=a.extend(xe,{NOTION_TOKEN:q,NOTION_DATABASE_ID:q,CLANCY_NOTION_STATUS:a.optional(a.string()),CLANCY_NOTION_TODO:a.optional(a.string()),CLANCY_NOTION_ASSIGNEE:a.optional(a.string()),CLANCY_NOTION_LABELS:a.optional(a.string()),CLANCY_NOTION_PARENT:a.optional(a.string())}),hn=a.extend(xe,{AZDO_ORG:q,AZDO_PROJECT:q,AZDO_PAT:q,CLANCY_AZDO_STATUS:a.optional(a.string()),CLANCY_AZDO_WIT:a.optional(a.string())});var tu=a.object({id:a.number(),url:a.optional(a.string())}),bn=a.object({workItems:a.array(tu)}),By=a.object({rel:a.string(),url:a.string(),attributes:a.optional(a.object({name:a.optional(a.string())}))}),Oy=a.object({"System.Title":a.optional(a.string()),"System.Description":a.optional(a.nullable(a.string())),"System.State":a.optional(a.string()),"System.Tags":a.optional(a.nullable(a.string())),"System.AssignedTo":a.optional(a.nullable(a.object({displayName:a.optional(a.string()),uniqueName:a.optional(a.string())}))),"System.WorkItemType":a.optional(a.string())}),Wt=a.object({id:a.number(),fields:Oy,relations:a.optional(a.nullable(a.array(By)))}),gn=a.object({value:a.array(Wt),count:a.optional(a.number())}),Df=a.object({id:a.string(),name:a.string(),state:a.optional(a.string())}),Zy=a.object({source:a.optional(a.nullable(tu)),target:a.optional(a.nullable(tu))}),yn=a.object({workItemRelations:a.optional(a.array(Zy))});var ru=a.object({number:a.number(),title:a.string(),body:a.optional(a.nullable(a.string())),pull_request:a.optional(a.unknown()),milestone:a.optional(a.nullable(a.object({title:a.string()}))),labels:a.optional(a.array(a.object({name:a.optional(a.string())})))}),kn=a.array(ru),nu=a.object({id:a.number(),body:a.optional(a.nullable(a.string())),created_at:a.string(),user:a.optional(a.object({login:a.string()}))}),_n=a.array(nu),ou=a.object({number:a.number(),html_url:a.string(),state:a.string()}),wn=a.array(ou),Ff=a.object({html_url:a.optional(a.string()),number:a.optional(a.number())}),su=a.object({state:a.string(),user:a.object({login:a.string()}),submitted_at:a.string()}),xn=a.array(su),iu=a.object({body:a.optional(a.nullable(a.string())),path:a.optional(a.string()),created_at:a.optional(a.string()),user:a.optional(a.object({login:a.string()}))}),Sn=a.array(iu),Mf=a.object({id:a.number(),name:a.string(),full_name:a.string()});var Dy=a.object({type:a.optional(a.object({name:a.optional(a.string())})),inwardIssue:a.optional(a.object({key:a.optional(a.string())}))}),Fy=a.object({summary:a.string(),description:a.optional(a.unknown()),issuelinks:a.optional(a.array(Dy)),parent:a.optional(a.object({key:a.optional(a.string())})),customfield_10014:a.optional(a.nullable(a.string())),labels:a.optional(a.array(a.string()))}),My=a.object({key:a.string(),fields:Fy}),vn=a.object({total:a.optional(a.number()),isLast:a.optional(a.boolean()),issues:a.array(My)}),Uy=a.object({id:a.string(),name:a.string()}),$n=a.object({transitions:a.array(Uy)}),qy=a.object({type:a.optional(a.object({name:a.optional(a.string())})),inwardIssue:a.optional(a.object({key:a.optional(a.string()),fields:a.optional(a.object({status:a.optional(a.object({statusCategory:a.optional(a.object({key:a.optional(a.string())}))}))}))}))}),Pn=a.object({fields:a.optional(a.object({issuelinks:a.optional(a.array(qy))}))}),In=a.object({fields:a.optional(a.object({labels:a.optional(a.array(a.string()))}))}),Uf=a.object({id:a.string(),key:a.string(),name:a.string()});var Ky=a.object({id:a.string(),identifier:a.string(),title:a.string(),description:a.optional(a.nullable(a.string())),parent:a.optional(a.nullable(a.object({identifier:a.string(),title:a.optional(a.string())}))),labels:a.optional(a.object({nodes:a.array(a.object({name:a.string()}))}))}),Rn=a.object({data:a.optional(a.object({viewer:a.optional(a.object({assignedIssues:a.optional(a.object({nodes:a.array(Ky)}))}))}))}),Cn=a.object({data:a.optional(a.object({viewer:a.optional(a.object({id:a.optional(a.string())}))}))}),Tn=a.object({data:a.optional(a.object({workflowStates:a.optional(a.object({nodes:a.array(a.object({id:a.string()}))}))}))}),En=a.object({data:a.optional(a.object({issueUpdate:a.optional(a.object({success:a.optional(a.boolean())}))}))}),Hy=a.object({type:a.string(),relatedIssue:a.optional(a.object({state:a.optional(a.object({type:a.optional(a.string())}))}))}),zn=a.object({data:a.optional(a.object({issue:a.optional(a.object({relations:a.optional(a.object({nodes:a.array(Hy)}))}))}))}),qf=a.object({state:a.optional(a.object({type:a.optional(a.string())}))}),An=a.object({data:a.optional(a.object({issueSearch:a.optional(a.object({nodes:a.array(qf)}))}))}),Ln=a.object({data:a.optional(a.object({issue:a.optional(a.object({children:a.optional(a.object({nodes:a.array(qf)}))}))}))}),Nn=a.object({data:a.optional(a.object({team:a.optional(a.object({labels:a.optional(a.object({nodes:a.array(a.object({id:a.string(),name:a.string()}))}))}))}))}),jn=a.object({data:a.optional(a.object({issueLabels:a.optional(a.object({nodes:a.array(a.object({id:a.string(),name:a.string()}))}))}))}),Bn=a.object({data:a.optional(a.object({issueLabelCreate:a.optional(a.object({issueLabel:a.optional(a.object({id:a.string()})),success:a.optional(a.boolean())}))}))}),Wy=a.object({id:a.string(),labels:a.optional(a.object({nodes:a.array(a.object({id:a.string(),name:a.optional(a.string())}))}))}),On=a.object({data:a.optional(a.object({issueSearch:a.optional(a.object({nodes:a.array(Wy)}))}))});var Kf=a.object({plain_text:a.string()}),Jy=a.object({type:a.literal("status"),status:a.nullable(a.object({id:a.optional(a.string()),name:a.string(),color:a.optional(a.string())}))}),Yy=a.object({type:a.literal("select"),select:a.nullable(a.object({id:a.optional(a.string()),name:a.string(),color:a.optional(a.string())}))}),Gy=a.object({id:a.optional(a.string()),name:a.string(),color:a.optional(a.string())}),Vy=a.object({type:a.literal("multi_select"),multi_select:a.array(Gy)}),Qy=a.object({type:a.literal("people"),people:a.array(a.object({id:a.string(),name:a.optional(a.nullable(a.string()))}))}),Xy=a.object({type:a.literal("relation"),relation:a.array(a.object({id:a.string()}))}),ek=a.object({type:a.literal("title"),title:a.array(Kf)}),tk=a.object({type:a.literal("rich_text"),rich_text:a.array(Kf)}),rk=a.union([Jy,Yy,Vy,Qy,Xy,ek,tk,a.object({type:a.string()})]),Jt=a.object({id:a.string(),url:a.optional(a.string()),properties:a.record(a.string(),rk)}),Zn=a.object({results:a.array(Jt),has_more:a.boolean(),next_cursor:a.optional(a.nullable(a.string()))}),Hf=a.object({id:a.string(),type:a.optional(a.string()),name:a.optional(a.nullable(a.string())),avatar_url:a.optional(a.nullable(a.string()))});var nk=a.object({verb:a.string(),subject_id:a.number(),object_id:a.number()}),au=a.object({id:a.number(),name:a.string(),description:a.optional(a.nullable(a.string())),story_type:a.optional(a.string()),blocked:a.optional(a.boolean()),story_links:a.optional(a.array(nk)),label_ids:a.optional(a.array(a.number())),labels:a.optional(a.array(a.object({id:a.number(),name:a.string()}))),epic_id:a.optional(a.nullable(a.number())),workflow_state_id:a.optional(a.number()),owner_ids:a.optional(a.array(a.string()))}),Ze=a.object({data:a.array(au),next:a.optional(a.nullable(a.string())),total:a.optional(a.number())}),De=au,ok=a.object({id:a.number(),name:a.string(),type:a.string()}),sk=a.object({id:a.number(),name:a.string(),states:a.array(ok)}),Dn=a.array(sk),Wf=a.object({id:a.number(),name:a.string()}),Fn=a.array(Wf),Mn=Wf,Un=a.array(au),qn=a.object({id:a.string(),mention_name:a.optional(a.string())});var Yt=class{projectRoot;argv;dryRun;skipFeasibility;startTime;isAfk;config;board;ticket;isRework;prFeedback;reworkPrNumber;reworkDiscussionIds;reworkReviewers;ticketBranch;targetBranch;effectiveTarget;baseBranch;originalBranch;skipEpicBranch;hasParent;lockOwner;setPreflight(t,r){this.config=t,this.board=r}setRework(t){this.isRework=t.isRework,this.prFeedback=t.prFeedback,this.reworkPrNumber=t.reworkPrNumber,this.reworkDiscussionIds=t.reworkDiscussionIds,this.reworkReviewers=t.reworkReviewers}setTicket(t){this.ticket=t}setTicketBranches(t){this.ticketBranch=t.ticketBranch,this.targetBranch=t.targetBranch,this.baseBranch=t.baseBranch,this.hasParent=t.hasParent}setBranchSetup(t){this.ticketBranch=t.ticketBranch,this.targetBranch=t.targetBranch,this.effectiveTarget=t.effectiveTarget,this.baseBranch=t.baseBranch,this.originalBranch=t.originalBranch,this.skipEpicBranch=t.skipEpicBranch,this.hasParent=t.hasParent}setLockOwner(t){this.lockOwner=t}constructor(t){this.projectRoot=t.projectRoot,this.argv=t.argv,this.dryRun=t.argv.includes("--dry-run"),this.skipFeasibility=t.argv.includes("--skip-feasibility"),this.startTime=t.now??Date.now(),this.isAfk=t.isAfk??!1}};function Kn(e){return new Yt(e)}async function Hn(e,t){let r=await t.lockCheck(e);if(r.action==="abort")return{status:"aborted",phase:"lock-check"};if(r.action==="resumed")return{status:"resumed"};try{return await ak(e,t)}catch(n){return ck(e,t),{status:"error",error:n instanceof Error?n.message:String(n)}}finally{uk(e,t)}}async function ak(e,t){return(await t.preflight(e)).ok?(await t.epicCompletion(e),await t.prRetry(e),await t.reworkDetection(e),(await t.ticketFetch(e)).ok?e.dryRun?{status:"dry-run"}:(await t.feasibility(e)).ok?(await t.branchSetup(e)).ok?(await t.transition(e),(await t.invoke(e)).ok?(await t.deliver(e)).ok?(t.cost(e),await t.cleanup(e),{status:"completed"}):{status:"aborted",phase:"deliver"}:{status:"aborted",phase:"invoke"}):{status:"aborted",phase:"branch-setup"}:{status:"aborted",phase:"feasibility"}:{status:"aborted",phase:"ticket-fetch"}):{status:"aborted",phase:"preflight"}}function ck(e,t){if(e.originalBranch)try{t.checkout(e.originalBranch)}catch{}}function uk(e,t){if(e.lockOwner===!0){try{t.deleteLock()}catch{}try{t.deleteVerifyAttempt()}catch{}}}async function et(e,t){let r=e.ticketBranch,n=e.targetBranch,o=e.baseBranch,s=e.hasParent===!0,i=e.isRework===!0,c=t.currentBranch(),u=await lk(e,t),l=s&&!u?n:o;e.setBranchSetup({ticketBranch:r,targetBranch:n,effectiveTarget:l,baseBranch:o,originalBranch:c,skipEpicBranch:u,hasParent:s});let p=i?pk(e,t):fk(e,t);return p.ok?(bk(e,t),{ok:!0}):(t.checkout(c),p)}async function lk(e,t){return e.hasParent!==!0||e.isRework===!0?!1:(await t.fetchChildrenStatus(e.ticket))?.total===1}function pk(e,t){let r=e.ticketBranch,n=e.effectiveTarget,o=e.baseBranch;if(e.hasParent===!0&&e.skipEpicBranch!==!0){let i=t.ensureEpicBranch(e.targetBranch,o);if(!i.ok)return{ok:!1,error:i.error}}else t.ensureBranch(n,o);return t.fetchRemoteBranch(r)?t.checkout(r):(t.checkout(n),t.checkout(r,!0)),{ok:!0}}function fk(e,t){return e.hasParent===!0&&e.skipEpicBranch!==!0?dk(e,t):mk(e,t)}function dk(e,t){let r=t.ensureEpicBranch(e.targetBranch,e.baseBranch);return r.ok?(t.checkout(e.targetBranch),t.checkout(e.ticketBranch,!0),{ok:!0}):{ok:!1,error:r.error}}function mk(e,t){let r=e.baseBranch;return t.ensureBranch(r,r),t.checkout(r),t.checkout(e.ticketBranch,!0),{ok:!0}}function hk(e){return(e.now??(()=>new Date().toISOString()))()}function bk(e,t){try{let r=e.ticket;t.writeLock({ticketKey:r.key,ticketTitle:r.title,ticketBranch:e.ticketBranch,targetBranch:e.effectiveTarget,parentKey:r.parentInfo,description:(r.description??"").slice(0,2e3)||void 0,startedAt:hk(t)}),e.setLockOwner(!0)}catch{}}async function tt(e,t){let r=e.config,n=e.ticket,o=Date.now()-e.startTime,s=r.env.CLANCY_NOTIFY_WEBHOOK;if(s)try{await t.notify(s,`\u2713 Clancy completed [${n.key}] ${n.title}`)}catch{}return{ok:!0,ticketKey:n.key,ticketTitle:n.title,elapsedMs:o}}function rt(e,t){try{let r=e.config,n=e.ticket,o=t.readLock();if(!o)return{ok:!0};let s=gk(r.env.CLANCY_TOKEN_RATE);t.appendCostEntry({ticketKey:n.key,startedAt:o.startedAt,tokenRate:s})}catch{}return{ok:!0}}function gk(e){if(e==null)return 6600;let t=Number(e);return Number.isFinite(t)&&t>0?t:6600}async function nt(e,t){return e.isRework===!0?yk(e,t):kk(e,t)}async function yk(e,t){let r=e.ticket,n=e.ticketBranch,o=e.effectiveTarget,{parentKey:s}=Yf(e);if(!(await t.deliverViaPullRequest({ticketBranch:n,targetBranch:o,skipLog:!0,parent:s})).pushed)return t.appendProgress({key:r.key,summary:r.title,status:"PUSH_FAILED",parent:s}),{ok:!1};if(t.appendProgress({key:r.key,summary:r.title,status:"REWORK",prNumber:e.reworkPrNumber,parent:s}),t.recordRework(),await Jf(r.key,t),e.reworkPrNumber!=null)try{await t.postReworkActions({prNumber:e.reworkPrNumber,feedback:e.prFeedback??[],discussionIds:e.reworkDiscussionIds,reviewers:e.reworkReviewers})}catch{}return{ok:!0}}async function kk(e,t){let r=e.ticket,n=e.ticketBranch,o=e.effectiveTarget,{parentKey:s,singleChildParent:i}=Yf(e);return(await t.deliverViaPullRequest({ticketBranch:n,targetBranch:o,parent:s,singleChildParent:i})).pushed?(t.recordDelivery(),await Jf(r.key,t),{ok:!0}):(t.appendProgress({key:r.key,summary:r.title,status:"PUSH_FAILED",parent:s}),{ok:!1})}async function Jf(e,t){try{await t.removeBuildLabel(e)}catch{}}function Yf(e){let t=e.ticket,r=e.hasParent===!0,n=e.skipEpicBranch===!0,o=e.config.provider,s=r&&!n?t.parentInfo:void 0,i=r&&n?t.parentInfo:void 0,c=_k(i,o);return{parentKey:s,singleChildParent:c}}function _k(e,t){if(e!=null)return t!=="github"||/^#\d+$/.test(e)?e:void 0}async function ot(e,t){try{return await wk(e,t)}catch{return{results:[]}}}async function wk(e,t){let r=e.config,n=r.env.CLANCY_BASE_BRANCH??"main",o=t.findCompletedEpics(e),s=async(u,l)=>{let p=await t.deliverEpicToBase({projectRoot:e.projectRoot,config:r,epicKey:u,epicTitle:u,epicBranch:l,baseBranch:n});return{epicKey:u,ok:p.ok}},i=[...o.entries()];return{results:await Promise.all(i.map(([u,l])=>s(u,l)))}}async function st(e,t){if(e.isRework===!0||e.skipFeasibility)return{ok:!0,skipped:!0};let r=e.ticket,n=e.config,o=await t.checkFeasibility({key:r.key,title:r.title,description:r.description},n.env.CLANCY_MODEL);return o.feasible?{ok:!0,skipped:!1}:(t.appendProgress({key:r.key,summary:r.title,status:"SKIPPED"}),{ok:!1,skipped:!1,reason:o.reason??"not implementable as code changes"})}import{join as Gt}from"node:path";var xk=a.object({pid:a.number(),ticketKey:a.string(),ticketTitle:a.string(),ticketBranch:a.string(),targetBranch:a.string(),parentKey:a.string(),description:a.optional(a.string()),startedAt:a.string().check(a.minLength(1))}),uu=".clancy",Sk="lock.json",lu=`${uu}/${Sk}`,vk=`${uu}/verify-attempt.txt`,$k=1440*60*1e3;function Wn(e,t,r){e.mkdir(Gt(t,uu)),e.writeFile(Gt(t,lu),JSON.stringify(r,null,2))}function it(e,t){try{let r=JSON.parse(e.readFile(Gt(t,lu))),n=xk.safeParse(r);return n.success?n.data:void 0}catch{return}}function at(e,t){try{e.deleteFile(Gt(t,lu))}catch(r){if(!(r instanceof Error&&"code"in r&&r.code==="ENOENT"))throw r}}function Pk(e){try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t&&t.code==="EPERM"}}function ct(e,t){try{e.deleteFile(Gt(t,vk))}catch(r){if(!(r instanceof Error&&"code"in r&&r.code==="ENOENT"))throw r}}function Gf(e){if(!Pk(e.pid))return!0;let t=Date.now()-new Date(e.startedAt).getTime();return Number.isNaN(t)?!0:t>$k}async function Ik(e,t,r){let n={exec:r.exec,progressFs:r.progressFs,projectRoot:e.projectRoot,lock:t},o=r.detectResume(n);return o?o.alreadyDelivered?{action:"continue",reason:`${t.ticketKey} already delivered \u2014 skipping`}:e.isAfk?(await r.executeResume({...n,resumeInfo:o})).ok?{action:"resumed",reason:`Resumed ${t.ticketKey}`}:{action:"continue"}:{action:"continue",reason:`Found in-progress work on ${o.branch}`}:{action:"continue"}}async function ut(e,t){let r=it(t.lockFs,e.projectRoot);if(!r)return{action:"continue"};if(!Gf(r))return{action:"abort",reason:`Another Clancy session is running (PID ${r.pid}, ticket ${r.ticketKey})`};at(t.lockFs,e.projectRoot),ct(t.lockFs,e.projectRoot);try{return await Ik(e,r,t)}catch{return{action:"continue"}}}async function lt(e,t){try{return await Ck(e,t)}catch{return{results:[]}}}function Vf(e){return e&&e!=="none"?e:void 0}function Rk(e){return e?.ok?"created":e&&!e.ok&&e.alreadyExists?"exists":e&&!e.ok?"failed":"skipped"}async function Ck(e,t){let r=t.findRetryable(e);if(r.length===0)return{results:[]};let n=t.detectRemote(e);if(n.host==="none"||n.host==="unknown")return Tk(r,t);let o=async i=>{let c=await t.retryEntry(i,n,e),u=Rk(c),l=Vf(i.parent);return(u==="created"||u==="exists")&&t.appendProgress({key:i.key,summary:i.summary,status:"PR_CREATED",prNumber:c?.ok?c.number:void 0,parent:l}),{key:i.key,status:u,...c?.ok&&{prNumber:c.number}}};return{results:await Promise.all(r.map(o))}}function Tk(e,t){return{results:e.map(n=>(t.appendProgress({key:n.key,summary:n.summary,status:"PR_CREATED",parent:Vf(n.parent)}),{key:n.key,status:"unsupported"}))}}async function pt(e,t){let r=t.runPreflight(e.projectRoot);if(!r.ok)return{ok:!1,error:r.error};if(!r.env)return{ok:!1,error:"Preflight passed but env is missing"};let n=t.detectBoard(r.env);if(typeof n=="string")return{ok:!1,error:n};let o=t.createBoard(n),s=o.validateInputs();if(s)return{ok:!1,error:s};let i=await o.ping();return i.ok?(e.setPreflight(n,o),{ok:!0,warning:r.warning}):{ok:!1,error:i.error}}async function ft(e,t){try{return await Ek(e,t)}catch{return{detected:!1}}}async function Ek(e,t){let r=e.config,n=await t.fetchRework(r);return n?(e.setRework({isRework:!0,prFeedback:n.feedback,reworkPrNumber:n.prNumber,reworkDiscussionIds:n.discussionIds,reworkReviewers:n.reviewers}),e.setTicket(n.ticket),{detected:!0,ticketKey:n.ticket.key}):{detected:!1}}async function dt(e,t){let r=e.config;if(!e.ticket){let s=await t.fetchTicket(e.board);if(!s)return{ok:!1,reason:"no-tickets"};e.setTicket(s)}let n=e.ticket;if(e.isRework===!0){let s=zk(r,n,t);if(s)return s}let o=Lk(e,t);return e.setTicketBranches(o),{ok:!0,ticketKey:n.key}}function zk(e,t,r){let n=Ak(e.env.CLANCY_MAX_REWORK);if(r.countReworkCycles(t.key)>=n)return r.appendProgress({key:t.key,summary:t.title,status:"SKIPPED"}),{ok:!1,reason:"max-rework",ticketKey:t.key}}function Ak(e){let t=parseInt(e??"3",10);return Number.isFinite(t)&&t>=0?t:3}function Lk(e,t){let r=e.config,n=e.ticket,o=r.env.CLANCY_BASE_BRANCH??"main",s=n.parentInfo!=="none",i=s?n.parentInfo:void 0,c=t.computeTicketBranch(r.provider,n.key),u=t.computeTargetBranch(r.provider,o,i);return{ticketBranch:c,targetBranch:u,baseBranch:o,hasParent:s}}async function mt(e,t){try{let r=e.config,n=e.ticket,o=r.env.CLANCY_STATUS_IN_PROGRESS;o&&await t.transitionTicket(n,o)}catch{}return{ok:!0}}function Nk(e){let t=e.trim().replace(/\.git$/,""),r=t.match(/^git@([^:]+):(.+)$/),n=t.match(/^(?:https?|ssh):\/\/(?:[^@]+@)?([^/:]+)(?::\d+)?\/(.+)$/),o=r?.[1]??n?.[1],s=r?.[2]??n?.[2];if(!(!o||!s))return{hostname:o,path:s}}function jk(e,t){let r=e.match(/^scm\/([^/]+)\/(.+)$/);if(r)return{host:"bitbucket-server",projectKey:r[1],repoSlug:r[2],hostname:t}}function Bk(e){let t=e.match(/^([^/]+)\/([^/]+)\/_git\/(.+)$/);if(t)return{org:t[1],project:t[2],repo:t[3]};let r=e.match(/^v3\/([^/]+)\/([^/]+)\/(.+)$/);if(r)return{org:r[1],project:r[2],repo:r[3]}}function Qf(e,t){let r=jk(e.path,e.hostname);if(r)return r;let n=e.path.split("/");if(n.length<2)return{host:"unknown",url:e.rawUrl};let[o,s]=n,{hostname:i}=e;return t==="bitbucket"?{host:"bitbucket",workspace:o,repoSlug:s,hostname:i}:{host:"bitbucket-server",projectKey:o,repoSlug:s,hostname:i}}function Ok(e){let{platform:t,hostname:r,path:n,rawUrl:o}=e;switch(t){case"github":{let s=n.split("/");return s.length>=2?{host:"github",owner:s[0],repo:s[1],hostname:r}:{host:"unknown",url:o}}case"gitlab":return{host:"gitlab",projectPath:n,hostname:r};case"bitbucket":return Qf(e,"bitbucket");case"bitbucket-server":return Qf(e,"bitbucket-server");case"azure":{let s=Bk(n);return s?{host:"azure",org:s.org,project:s.project,repo:s.repo,hostname:r}:{host:"unknown",url:o}}default:return{host:"unknown",url:o}}}function pu(e,t){let r=Nk(e);if(!r)return{host:"unknown",url:e};let{hostname:n,path:o}=r,s=t??Zk(n);return Ok({platform:s,hostname:n,path:o,rawUrl:e})}function Zk(e){let t=e.toLowerCase(),r=t==="github.com"||t.includes("github"),n=t==="gitlab.com"||t.includes("gitlab"),o=t==="bitbucket.org"||t.includes("bitbucket"),s=t.includes("dev.azure")||t.includes("visualstudio");return r?"github":n?"gitlab":o?"bitbucket":s?"azure":"unknown"}function Vt(e,t){if(t)return t.replace(/\/$/,"");switch(e.host){case"github":return e.hostname==="github.com"?"https://api.github.com":`https://${e.hostname}/api/v3`;case"gitlab":return`https://${e.hostname}/api/v4`;case"bitbucket":return"https://api.bitbucket.org/2.0";case"bitbucket-server":return`https://${e.hostname}/rest/api/1.0`;case"azure":return"https://dev.azure.com";case"none":case"unknown":return}}function Dk(e){return e.length>0&&!e.includes("..")&&!e.startsWith("/")}var Fk=new Set(["github","gitlab","bitbucket","bitbucket-server","azure"]);function ht(e){return e(["rev-parse","--abbrev-ref","HEAD"]).trim()}function Qt(e){try{return e(["diff","--quiet"]),e(["diff","--cached","--quiet"]),!1}catch{return!0}}function bt(e,t){if(!Dk(t))return!1;try{return e(["show-ref","--verify","--quiet",`refs/heads/${t}`]),!0}catch{return!1}}function Jn(e,t,r){bt(e,t)||e(["checkout","-b",t,r])}function oe(e,t,r=!1){e(["checkout",...r?["-B"]:[],t])}function fu(e,t){try{return e(["ls-remote","--heads","origin",t]).trim().length>0}catch{return!1}}function gt(e,t){try{return e(["fetch","origin",`${t}:${t}`]),!0}catch{return!1}}function Fe(e,t){try{return e(["push","-u","origin",t]),!0}catch{return!1}}function X(e,t){let r=Mk(e,["remote","get-url","origin"]);if(!r)return{host:"none"};let n=Uk(t)?t:void 0;return pu(r,n)}function Mk(e,t){try{return e(t).trim()||void 0}catch{return}}function Uk(e){return e!==void 0&&Fk.has(e)}import{join as du}from"node:path";function mu(e){let t=e.getUTCFullYear(),r=String(e.getUTCMonth()+1).padStart(2,"0"),n=String(e.getUTCDate()).padStart(2,"0"),o=String(e.getUTCHours()).padStart(2,"0"),s=String(e.getUTCMinutes()).padStart(2,"0");return`${t}-${r}-${n} ${o}:${s}`}var Xf=".clancy/progress.txt",ed=new Set(["BRIEF","APPROVE_BRIEF"]),qk=new Set(["DONE","SKIPPED","PR_CREATED","PUSHED","PUSH_FAILED","LOCAL","PLAN","APPROVE_PLAN","APPROVE","REWORK","EPIC_PR_CREATED","BRIEF","APPROVE_BRIEF","TIME_LIMIT","RESUMED"]);function ee(e,t,r){let n=du(t,Xf);e.mkdir(du(t,".clancy"));let o=mu(new Date),s=ed.has(r.status)?Kk(o,r):Hk(o,r);e.appendFile(n,s)}function Kk(e,t){return`${e} | ${t.status} | ${t.key} | ${t.summary}
|
|
42
|
+
`}function Hk(e,t){let r=t.prNumber!=null?` | pr:${t.prNumber}`:"",n=t.parent?` | parent:${t.parent}`:"",o=t.ticketType?` | type:${t.ticketType}`:"";return`${e} | ${t.key} | ${t.summary} | ${t.status}${r}${n}${o}
|
|
43
|
+
`}function Xt(e,t){let r=Wk(e,du(t,Xf));return r?r.split(/\r?\n/).filter(n=>n.trim().length>0).map(n=>Jk(n.trim())).filter(n=>n!==void 0):[]}function Wk(e,t){try{return e.readFile(t)}catch{return}}function Jk(e){let t=e.split(" | ");if(t.length<4)return;let r=t[0];return ed.has(t[1])?Yk(r,t):Gk(r,t)}function Yk(e,t){return{timestamp:e,key:t[2],summary:t.slice(3).join(" | "),status:t[1]}}function Gk(e,t){let r=t[1],n=t.slice(2),{status:o,summary:s,prNumber:i,parent:c,ticketType:u}=Vk(n);return o?{timestamp:e,key:r,summary:s,status:o==="APPROVE"?"APPROVE_PLAN":o,...i!=null&&{prNumber:i},...c!=null&&{parent:c},...u!=null&&{ticketType:u}}:void 0}function Vk(e){let t=e.find(l=>/^pr:\d+$/.test(l)),r=e.find(l=>l.startsWith("parent:")),n=e.find(l=>l.startsWith("type:")),o=e.find((l,p)=>p>=1&&Qk(l)&&l!==t&&l!==r&&l!==n),s=t?parseInt(t.slice(3),10):void 0,i=r?r.slice(7):void 0,c=n?n.slice(5):void 0,u=e.filter(l=>l!==t&&l!==r&&l!==n&&l!==o);return{status:o,summary:u.join(" | "),prNumber:s,parent:i,ticketType:c}}function Qk(e){return qk.has(e)}function hu(e,t,r){let n=Xt(e,t),o=r.toLowerCase();return[...n].reverse().find(s=>s.key.toLowerCase()===o)}function Yn(e,t,r){let n=Xt(e,t),o=r.toLowerCase();return n.filter(s=>s.key.toLowerCase()===o&&s.status==="REWORK").length}function K(e,t,r){let n=Xt(e,t);return[...new Map(n.map(s=>[s.key,s])).values()].filter(s=>s.status===r)}function Me(e,t){return e==="github"?`feature/issue-${t.replace("#","")}`:`feature/${t.toLowerCase()}`}function er(e,t,r){if(!r)return t;if(e==="github"){let n=r.match(/^#(\d+)$/);return n?`epic/${n[1]}`:`milestone/${r.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}`}return`epic/${r.toLowerCase()}`}function Xk(e,t){try{return e(t,["--version"]),!0}catch{return!1}}function e_(e){try{return e("git",["rev-parse","--git-dir"]),!0}catch{return!1}}function t_(e){try{return e("git",["ls-remote","origin","HEAD"]),!0}catch{return!1}}function r_(e){let t=o=>e("git",o),n=[[!t_(e),"Could not reach origin. PR creation and rework detection may not work."],[Qt(t),"Working directory has uncommitted changes \u2014 they will be included in the branch."]].filter(([o])=>o).map(([,o])=>o);return n.length>0?n.join(`
|
|
44
|
+
`):void 0}function bu(e,t){let r=c=>({ok:!1,error:c,warning:void 0,env:void 0}),o=["claude","git"].find(c=>!Xk(t.exec,c));if(o)return r(`${o} is required but not found`);let s=$r(e,t.envFs);if(!s)return r(".clancy/.env not found \u2014 run /clancy:init first");if(!e_(t.exec))return r("Not inside a git repository");let i=r_(t.exec);return{ok:!0,env:s,error:void 0,warning:i}}function gu(e){let{exec:t,progressFs:r,projectRoot:n,lock:o}=e,s=o.ticketBranch;if(!bt(t,s))return;let i=n_(t);if(!i)return;if(!Gn(t,s)){Gn(t,i);return}let c=o_(t,s,o.targetBranch);return Gn(t,i),!c.hasUncommitted&&!c.hasUnpushed?a_({progressFs:r,projectRoot:n,lock:o},s):{branch:s,...c,alreadyDelivered:!1}}async function yu(e){let{exec:t,progressFs:r,projectRoot:n,lock:o,resumeInfo:s,createPr:i}=e;try{if(oe(t,s.branch),s.hasUncommitted&&!c_(t,o))return{ok:!1,error:"Could not commit in-progress work"};if(!Fe(t,s.branch))return{ok:!1,error:"Could not push branch"};let c=i?await i(o,s.branch):void 0;return l_({progressFs:r,projectRoot:n,lock:o},c),Gn(t,o.targetBranch),{ok:!0,prResult:c}}catch(c){return{ok:!1,error:c instanceof Error?c.message:String(c)}}}function n_(e){try{return ht(e)}catch{return}}function Gn(e,t){try{return oe(e,t),!0}catch{return!1}}function o_(e,t,r){let n=s_(e),o=i_(e,t,r);return{hasUncommitted:n,hasUnpushed:o}}function s_(e){try{return Qt(e)}catch{return!1}}function i_(e,t,r){try{return e(["log",`origin/${t}..${t}`,"--oneline"]).trim().length>0}catch{try{return e(["log",`origin/${r}..${t}`,"--oneline"]).trim().length>0}catch{return!1}}}function a_(e,t){let r=hu(e.progressFs,e.projectRoot,e.lock.ticketKey);if(r&&Le.has(r.status))return{branch:t,hasUncommitted:!1,hasUnpushed:!1,alreadyDelivered:!0}}function c_(e,t){try{return e(["add","-A"]),e(["commit","-m",`fix(${t.ticketKey}): resume after crash`]),!0}catch{return!1}}function u_(e){return e.parentKey&&e.parentKey!=="none"?e.parentKey:void 0}function l_(e,t){ee(e.progressFs,e.projectRoot,{key:e.lock.ticketKey,summary:e.lock.ticketTitle,status:"RESUMED",prNumber:t?.ok?t.number:void 0,parent:u_(e.lock)})}var p_=5,td=3,f_=80;function d_(e){if(e.length===0)return"[clancy] Rework pushed addressing reviewer feedback.";let t=e.length,r=e.slice(0,td).map(o=>`- ${o.slice(0,f_)}`).join(`
|
|
45
|
+
`),n=t>td?`
|
|
46
|
+
- ...`:"";return`[clancy] Rework pushed addressing ${t} feedback item${t!==1?"s":""}.
|
|
47
|
+
|
|
48
|
+
${r}${n}`}async function ku(e){let{progressFs:t,projectRoot:r,provider:n,handlers:o}=e,s=[...K(t,r,"PR_CREATED"),...K(t,r,"REWORK"),...K(t,r,"PUSHED"),...K(t,r,"PUSH_FAILED")];if(s.length===0)return;let i=s.slice(0,p_);return rd(i,n,o)}async function _u(e){let{handlers:t,prNumber:r,feedback:n,discussionIds:o,reviewers:s}=e;await m_(t,r,n),await h_(t,r,o),await b_(t,r,s)}async function m_(e,t,r){try{let n=d_(r);await e.postComment(t,n)&&console.log(" \u2713 Posted rework comment")}catch{}}async function h_(e,t,r){if(!(!r||r.length===0))try{let n=await e.resolveThreads(t,r);n>0&&console.log(` \u2713 Resolved ${n} discussion thread${n!==1?"s":""}`)}catch{}}async function b_(e,t,r){if(!(!r||r.length===0))try{await e.reRequestReview(t,r)&&console.log(` \u2713 Re-requested review from ${r.join(", ")}`)}catch{}}function g_(e){let t=new Date(e.replace(" ","T")+"Z");return Number.isNaN(t.getTime())?void 0:t.toISOString()}async function rd(e,t,r){if(e.length===0)return;let[n,...o]=e,s=Me(t,n.key),i=n.timestamp?g_(n.timestamp):void 0,c=await r.checkReviewState(s,i);if(c?.changesRequested){let{comments:u,discussionIds:l}=await r.fetchComments(c.prNumber,i);return{ticket:{key:n.key,title:n.summary,description:n.summary,parentInfo:n.parent??"none",blockers:"None"},feedback:u,prNumber:c.prNumber,discussionIds:l,reviewers:c.reviewers??[]}}return rd(o,t,r)}function y_(e,t){return{github:e.GITHUB_TOKEN,gitlab:e.GITLAB_TOKEN,"bitbucket-server":e.BITBUCKET_TOKEN,azure:e.AZDO_PAT}[t]}function tr(e,t){if(t.host==="bitbucket")return e.BITBUCKET_USER&&e.BITBUCKET_TOKEN?{token:e.BITBUCKET_TOKEN,username:e.BITBUCKET_USER}:void 0;let r=y_(e,t.host);return r?{token:r}:void 0}var k_=a.object({pullRequestId:a.number(),status:a.optional(a.string()),reviewers:a.optional(a.array(a.object({vote:a.optional(a.number()),displayName:a.optional(a.string()),uniqueName:a.optional(a.string())})))}),nd=a.object({pullRequestId:a.optional(a.number())}),od=a.object({value:a.array(k_),count:a.optional(a.number())}),__=a.object({filePath:a.optional(a.string())}),w_=a.object({content:a.optional(a.string()),commentType:a.optional(a.string()),publishedDate:a.optional(a.string())}),x_=a.object({id:a.number(),status:a.optional(a.string()),comments:a.array(w_),threadContext:a.optional(a.nullable(__)),isDeleted:a.optional(a.boolean()),publishedDate:a.optional(a.string())}),sd=a.object({value:a.array(x_),count:a.optional(a.number())});async function se(e){let{fetchFn:t,url:r,headers:n,body:o,parseSuccess:s,isAlreadyExists:i}=e,c=new AbortController,u=setTimeout(()=>c.abort(),3e4);try{let l=await t(r,{method:"POST",headers:{...n,"Content-Type":"application/json"},body:JSON.stringify(o),signal:c.signal});if(!l.ok){let h=await l.text().catch(()=>""),b=i?.(l.status,h)??!1;return{ok:!1,error:`HTTP ${l.status}${h?`: ${h.slice(0,200)}`:""}`,alreadyExists:b}}let p=await l.json(),d=s(p);return!d.url&&!d.number?{ok:!1,error:"PR created but response missing URL and number"}:{ok:!0,url:d.url,number:d.number}}catch(l){return{ok:!1,error:l instanceof Error?l.message:String(l)}}finally{clearTimeout(u)}}function ie(e,t){return`Basic ${Buffer.from(`${e}:${t}`).toString("base64")}`}function N(e){return e.trim().toLowerCase().startsWith("rework:")}function F(e){return e.trimStart().startsWith("[clancy]")}function ae(e){return e.trim().replace(/^rework:\s*/i,"").trim()}var Qn="api-version=7.1",Vn="https://dev.azure.com";async function wu(e){let{fetchFn:t,org:r,project:n,repo:o,pat:s}=e,{sourceBranch:i,targetBranch:c,title:u,description:l}=e,p=encodeURIComponent(r),d=encodeURIComponent(n),h=encodeURIComponent(o);return se({fetchFn:t,url:`${Vn}/${p}/${d}/_apis/git/repositories/${h}/pullrequests?${Qn}`,headers:{Authorization:ie("",s)},body:{sourceRefName:`refs/heads/${i}`,targetRefName:`refs/heads/${c}`,title:u,description:l},parseSuccess:b=>{let w=nd.parse(b).pullRequestId??0;return{url:`${Vn}/${p}/${d}/_git/${h}/pullrequest/${w}`,number:w}},isAlreadyExists:(b,_)=>b===409||b===400&&_.includes("already has an active pull request")})}async function xu(e){let{fetchFn:t,org:r,project:n,repo:o,pat:s,prId:i,body:c}=e;try{let u=$u(r,n,o);return(await t(`${u}/${i}/threads?${Qn}`,{method:"POST",headers:{Authorization:ie("",s),"Content-Type":"application/json"},body:JSON.stringify({comments:[{parentCommentId:0,content:c,commentType:1}],status:1})})).ok}catch{return!1}}async function Su(e){let{fetchFn:t,org:r,project:n,repo:o,pat:s,branch:i,since:c}=e,u=ie("",s);try{let l=$u(r,n,o),p=await t(`${l}?searchCriteria.sourceRefName=${encodeURIComponent(`refs/heads/${i}`)}&searchCriteria.status=active&${Qn}`,{headers:{Authorization:u}});if(!p.ok)return;let d=od.parse(await p.json());if(d.value.length===0)return;let h=d.value[0],b=await id({fetchFn:t,auth:u,org:r,project:n,repo:o,prId:h.pullRequestId});if(!b)return;let _=cd(ad(b),c),w=_.some(Ee=>Ee.threadContext!=null),I=_.some(Ee=>Ee.threadContext==null&&Ee.comments.length>0&&N(Ee.comments[0].content??""));return{changesRequested:w||I,prNumber:h.pullRequestId,prUrl:`${Vn}/${encodeURIComponent(r)}/${encodeURIComponent(n)}/_git/${encodeURIComponent(o)}/pullrequest/${h.pullRequestId}`}}catch{return}}async function vu(e){let{fetchFn:t,org:r,project:n,repo:o,pat:s,prId:i,since:c}=e,u=ie("",s);try{let l=await id({fetchFn:t,auth:u,org:r,project:n,repo:o,prId:i});return l?cd(ad(l),c).flatMap(p=>S_(p)):[]}catch{return[]}}function $u(e,t,r){let n=encodeURIComponent(e),o=encodeURIComponent(t),s=encodeURIComponent(r);return`${Vn}/${n}/${o}/_apis/git/repositories/${s}/pullrequests`}async function id(e){let{fetchFn:t,auth:r,org:n,project:o,repo:s,prId:i}=e,c=$u(n,o,s),u=await t(`${c}/${i}/threads?${Qn}`,{headers:{Authorization:r}});return u.ok?sd.parse(await u.json()).value:void 0}function ad(e){return e.filter(t=>t.isDeleted!==!0&&t.comments.length>0&&t.comments[0].commentType!=="system"&&!F(t.comments[0].content??""))}function cd(e,t){return t?e.filter(r=>(r.publishedDate??"")>t):e}function S_(e){let t=e.comments[0]?.content??"";return t?e.threadContext!=null?[`${e.threadContext.filePath?`[${e.threadContext.filePath}] `:""}${t}`]:N(t)?[ae(t)]:[]:[]}var v_=a.object({id:a.number(),links:a.object({html:a.optional(a.object({href:a.optional(a.string())}))}),participants:a.array(a.object({state:a.optional(a.string()),role:a.string()}))}),ud=a.object({values:a.array(v_)}),ld=a.object({id:a.optional(a.number()),links:a.optional(a.object({html:a.optional(a.object({href:a.optional(a.string())}))}))}),$_=a.object({content:a.object({raw:a.string()}),inline:a.optional(a.object({path:a.optional(a.string())})),created_on:a.string(),user:a.optional(a.object({nickname:a.optional(a.string())}))}),pd=a.object({values:a.array($_)}),P_=a.object({id:a.number(),links:a.object({self:a.optional(a.array(a.object({href:a.optional(a.string())})))}),reviewers:a.array(a.object({status:a.string()}))}),fd=a.object({values:a.array(P_)}),dd=a.object({id:a.optional(a.number()),links:a.optional(a.object({self:a.optional(a.array(a.object({href:a.optional(a.string())})))}))}),I_=a.object({text:a.string(),anchor:a.optional(a.object({path:a.optional(a.string())})),createdDate:a.number(),author:a.optional(a.object({slug:a.optional(a.string())}))}),R_=a.object({action:a.string(),comment:a.optional(I_)}),md=a.object({values:a.array(R_)});var Xn="https://api.bitbucket.org/2.0";async function Pu(e){let{fetchFn:t,username:r,token:n,workspace:o,repoSlug:s}=e,{sourceBranch:i,targetBranch:c,title:u,description:l}=e;return se({fetchFn:t,url:`${Xn}/repositories/${encodeURIComponent(o)}/${encodeURIComponent(s)}/pullrequests`,headers:{Authorization:ie(r,n)},body:{title:u,description:l,source:{branch:{name:i}},destination:{branch:{name:c}},close_source_branch:!0},parseSuccess:p=>{let d=ld.parse(p);return{url:d.links?.html?.href??"",number:d.id??0}},isAlreadyExists:(p,d)=>p===409&&d.includes("already exists")})}async function Iu(e){let{fetchFn:t,username:r,token:n,workspace:o,repoSlug:s,prId:i,body:c}=e;try{return(await t(`${Xn}/repositories/${encodeURIComponent(o)}/${encodeURIComponent(s)}/pullrequests/${i}/comments`,{method:"POST",headers:{Authorization:ie(r,n),"Content-Type":"application/json"},body:JSON.stringify({content:{raw:c}})})).ok}catch{return!1}}async function Ru(e){let{fetchFn:t,username:r,token:n,workspace:o,repoSlug:s,branch:i,since:c}=e,u=ie(r,n);try{let l=await t(`${Xn}/repositories/${encodeURIComponent(o)}/${encodeURIComponent(s)}/pullrequests?q=source.branch.name="${encodeURIComponent(i)}"&state=OPEN`,{headers:{Authorization:u}});if(!l.ok)return;let p=ud.parse(await l.json());if(p.values.length===0)return;let d=p.values[0],h=await hd({fetchFn:t,auth:u,workspace:o,repoSlug:s,prId:d.id});if(!h)return;let b=bd(h,c).filter(I=>!F(I.content.raw)),_=b.some(I=>I.inline!=null),w=b.some(I=>I.inline==null&&N(I.content.raw));return{changesRequested:_||w,prNumber:d.id,prUrl:d.links.html?.href??""}}catch{return}}async function Cu(e){let{fetchFn:t,username:r,token:n,workspace:o,repoSlug:s,prId:i,since:c}=e,u=ie(r,n);try{let l=await hd({fetchFn:t,auth:u,workspace:o,repoSlug:s,prId:i});return l?bd(l,c).filter(p=>!F(p.content.raw)).flatMap(p=>C_(p)):[]}catch{return[]}}async function hd(e){let{fetchFn:t,auth:r,workspace:n,repoSlug:o,prId:s}=e,i=await t(`${Xn}/repositories/${encodeURIComponent(n)}/${encodeURIComponent(o)}/pullrequests/${s}/comments?pagelen=100`,{headers:{Authorization:r}});return i.ok?pd.parse(await i.json()).values:void 0}function bd(e,t){return t?e.filter(r=>r.created_on>t):e}function C_(e){return e.inline!=null?[`${e.inline.path?`[${e.inline.path}] `:""}${e.content.raw}`]:N(e.content.raw)?[ae(e.content.raw)]:[]}async function Tu(e){let{fetchFn:t,token:r,apiBase:n,projectKey:o,repoSlug:s}=e,{sourceBranch:i,targetBranch:c,title:u,description:l}=e;return se({fetchFn:t,url:`${n}/projects/${encodeURIComponent(o)}/repos/${encodeURIComponent(s)}/pull-requests`,headers:{Authorization:`Bearer ${r}`},body:{title:u,description:l,fromRef:{id:`refs/heads/${i}`,repository:{slug:s,project:{key:o}}},toRef:{id:`refs/heads/${c}`,repository:{slug:s,project:{key:o}}}},parseSuccess:p=>{let d=dd.parse(p);return{url:d.links?.self?.[0]?.href??"",number:d.id??0}},isAlreadyExists:(p,d)=>p===409&&(d.includes("already exists")||d.includes("Only one pull request"))})}async function Eu(e){let{fetchFn:t,token:r,apiBase:n,projectKey:o,repoSlug:s,prId:i,body:c}=e;try{return(await t(`${n}/projects/${encodeURIComponent(o)}/repos/${encodeURIComponent(s)}/pull-requests/${i}/comments`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify({text:c})})).ok}catch{return!1}}async function zu(e){let{fetchFn:t,token:r,apiBase:n,projectKey:o,repoSlug:s,branch:i,since:c}=e,u=`Bearer ${r}`;try{let l=await t(`${n}/projects/${encodeURIComponent(o)}/repos/${encodeURIComponent(s)}/pull-requests?state=OPEN&at=${encodeURIComponent(`refs/heads/${i}`)}`,{headers:{Authorization:u}});if(!l.ok)return;let p=fd.parse(await l.json());if(p.values.length===0)return;let d=p.values[0],h=await gd({fetchFn:t,auth:u,apiBase:n,projectKey:o,repoSlug:s,prId:d.id});if(!h)return;let b=yd(h,c).filter(I=>!F(I.text)),_=b.some(I=>I.anchor!=null),w=b.some(I=>I.anchor==null&&N(I.text));return{changesRequested:_||w,prNumber:d.id,prUrl:d.links.self?.[0]?.href??""}}catch{return}}async function Au(e){let{fetchFn:t,token:r,apiBase:n,projectKey:o,repoSlug:s,prId:i,since:c}=e,u=`Bearer ${r}`;try{let l=await gd({fetchFn:t,auth:u,apiBase:n,projectKey:o,repoSlug:s,prId:i});return l?yd(l,c).filter(p=>!F(p.text)).flatMap(p=>T_(p)):[]}catch{return[]}}async function gd(e){let{fetchFn:t,auth:r,apiBase:n,projectKey:o,repoSlug:s,prId:i}=e,c=await t(`${n}/projects/${encodeURIComponent(o)}/repos/${encodeURIComponent(s)}/pull-requests/${i}/activities?limit=100`,{headers:{Authorization:r}});return c.ok?md.parse(await c.json()).values.filter(l=>l.action==="COMMENTED"&&l.comment!=null).map(l=>l.comment):void 0}function yd(e,t){if(!t)return e;let r=Date.parse(t);return e.filter(n=>n.createdDate>r)}function T_(e){return e.anchor!=null?[`${e.anchor.path?`[${e.anchor.path}] `:""}${e.text}`]:N(e.text)?[ae(e.text)]:[]}var C="https://api.github.com",E_=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,z_=a.object({login:a.string()});function T(e){return{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}}function Se(e){return E_.test(e)}async function Lu(e,t,r){return Se(t)?V({url:`${C}/repos/${t}`,headers:T(e),statusErrors:{401:"\u2717 GitHub auth failed \u2014 check GITHUB_TOKEN",403:"\u2717 GitHub permission denied",404:`\u2717 GitHub repo "${t}" not found`},networkError:"\u2717 Could not reach GitHub \u2014 check network",fetcher:r}):{ok:!1,error:"\u2717 GITHUB_REPO format is invalid"}}async function Nu(e,t,r){let n=t.get();if(n)return n;let o=r??fetch;try{let s=await o(`${C}/user`,{headers:T(e)});if(s.ok){let i=await s.json(),c=z_.safeParse(i);if(c.success)return t.store(c.data.login),c.data.login;console.warn("\u26A0 Unexpected GitHub /user response \u2014 falling back to @me")}else console.warn(`\u26A0 GitHub /user returned HTTP ${s.status} \u2014 falling back to @me`)}catch(s){console.warn(`\u26A0 GitHub /user request failed: ${s instanceof Error?s.message:String(s)} \u2014 falling back to @me`)}return t.store("@me"),"@me"}function A_(e){return{key:`#${e.number}`,title:e.title,description:e.body??"",provider:"github",milestone:e.milestone?.title,labels:e.labels?.map(t=>t.name).filter(t=>!!t)}}async function ju(e){let{token:t,repo:r,label:n,username:o,excludeHitl:s,limit:i=5,fetcher:c}=e;if(!Se(r))return[];let u=new URLSearchParams({state:"open",assignee:o??"@me",per_page:"10",...n?{labels:n}:{}}),l=await S(`${C}/repos/${r}/issues?${u}`,{headers:T(t)},{schema:kn,label:"GitHub Issues API",fetcher:c});if(!l)return[];let p=l.filter(h=>!h.pull_request);return(s?p.filter(h=>!h.labels?.some(b=>b.name==="clancy:hitl")):p).slice(0,i).map(A_)}async function Bu(e){let{fetchFn:t,token:r,repo:n,branch:o,owner:s}=e,i=e.apiBase??C;try{let c=await L_({fetchFn:t,apiBase:i,repo:n,owner:s,branch:o,token:r});if(!c)return;let{inline:u,convo:l}=await kd({fetchFn:t,apiBase:i,repo:n,prNumber:c.number,token:r,since:e.since}),p=u.length>0,d=l.some(_=>_.body!=null&&N(_.body));if(p||d)return{changesRequested:!0,prNumber:c.number,prUrl:c.url};let b=await N_({fetchFn:t,apiBase:i,repo:n,prNumber:c.number,token:r});return{changesRequested:b.changesRequested,prNumber:c.number,prUrl:c.url,...b.reviewers&&{reviewers:b.reviewers}}}catch{return}}async function Ou(e){let{fetchFn:t,token:r,repo:n,prNumber:o}=e,s=e.apiBase??C;try{let{inline:i,convo:c}=await kd({fetchFn:t,apiBase:s,repo:n,prNumber:o,token:r,since:e.since}),u=i.filter(p=>p.body!=null).map(p=>`${p.path?`[${p.path}] `:""}${p.body}`),l=c.filter(p=>p.body!=null&&N(p.body)).map(p=>ae(p.body));return[...u,...l]}catch{return[]}}async function Zu(e){let{fetchFn:t,token:r,repo:n,prNumber:o,body:s}=e,i=e.apiBase??C;try{return(await t(`${i}/repos/${n}/issues/${o}/comments`,{method:"POST",headers:{...T(r),"Content-Type":"application/json"},body:JSON.stringify({body:s})})).ok}catch{return!1}}async function Du(e){let{fetchFn:t,token:r,repo:n,prNumber:o,reviewers:s}=e,i=e.apiBase??C;try{return(await t(`${i}/repos/${n}/pulls/${o}/requested_reviewers`,{method:"POST",headers:{...T(r),"Content-Type":"application/json"},body:JSON.stringify({reviewers:s})})).ok}catch{return!1}}async function Fu(e){let{fetchFn:t,token:r,repo:n,head:o,base:s,title:i,body:c}=e,u=e.apiBase??C;return se({fetchFn:t,url:`${u}/repos/${n}/pulls`,headers:T(r),body:{title:i,head:o,base:s,body:c},parseSuccess:l=>{let p=Ff.parse(l);return{url:p.html_url??"",number:p.number??0}},isAlreadyExists:(l,p)=>l===422&&p.includes("already exists")})}async function L_(e){let{fetchFn:t,apiBase:r,repo:n,owner:o,branch:s,token:i}=e,c=await t(`${r}/repos/${n}/pulls?head=${encodeURIComponent(`${o}:${s}`)}&state=open`,{headers:T(i)});if(!c.ok)return;let u=wn.parse(await c.json());if(u.length===0)return;let l=u[0];return{number:l.number,url:l.html_url}}async function kd(e){let{fetchFn:t,apiBase:r,repo:n,prNumber:o,token:s,since:i}=e,c=T(s),u=i?`&since=${encodeURIComponent(i)}`:"",[l,p]=await Promise.all([t(`${r}/repos/${n}/pulls/${o}/comments?per_page=100${u}`,{headers:c}),t(`${r}/repos/${n}/issues/${o}/comments?per_page=100${u}`,{headers:c})]);if(!l.ok||!p.ok)return{inline:[],convo:[]};let d=Sn.parse(await l.json()),h=_n.parse(await p.json());return{inline:d.filter(b=>!b.body||!F(b.body)),convo:h.filter(b=>!b.body||!F(b.body))}}async function N_(e){let{fetchFn:t,apiBase:r,repo:n,prNumber:o,token:s}=e;try{let i=await t(`${r}/repos/${n}/pulls/${o}/reviews?per_page=100`,{headers:T(s)});if(!i.ok)return{changesRequested:!1};let c=xn.parse(await i.json()),l=[...new Map(c.filter(p=>p.state!=="PENDING"&&p.state!=="DISMISSED").map(p=>[p.user.login,p.state])).entries()].filter(([,p])=>p==="CHANGES_REQUESTED").map(([p])=>p);return l.length===0?{changesRequested:!1}:{changesRequested:!0,reviewers:l}}catch{return{changesRequested:!1}}}var j_=a.object({iid:a.number(),web_url:a.string(),detailed_merge_status:a.optional(a.string())}),_d=a.array(j_),wd=a.object({iid:a.optional(a.number()),web_url:a.optional(a.string())}),B_=a.object({body:a.string(),resolvable:a.boolean(),resolved:a.optional(a.boolean()),system:a.boolean(),type:a.optional(a.nullable(a.string())),created_at:a.optional(a.string()),position:a.optional(a.object({new_path:a.optional(a.string())})),author:a.optional(a.object({username:a.string()}))}),O_=a.object({id:a.optional(a.string()),notes:a.array(B_)}),xd=a.array(O_);async function Mu(e){let{fetchFn:t,token:r,apiBase:n,projectPath:o}=e,{sourceBranch:s,targetBranch:i,title:c,description:u}=e,l=encodeURIComponent(o);return se({fetchFn:t,url:`${n}/projects/${l}/merge_requests`,headers:{"PRIVATE-TOKEN":r},body:{source_branch:s,target_branch:i,title:c,description:u,remove_source_branch:!0},parseSuccess:p=>{let d=wd.parse(p);return{url:d.web_url??"",number:d.iid??0}},isAlreadyExists:(p,d)=>p===409&&d.includes("already exists")})}async function Uu(e){let{fetchFn:t,token:r,apiBase:n,projectPath:o,mrIid:s,body:i}=e;try{let c=encodeURIComponent(o);return(await t(`${n}/projects/${c}/merge_requests/${s}/notes`,{method:"POST",headers:{"PRIVATE-TOKEN":r,"Content-Type":"application/json"},body:JSON.stringify({body:i})})).ok}catch{return!1}}async function qu(e){let{fetchFn:t,token:r,apiBase:n,projectPath:o,mrIid:s,discussionIds:i}=e,c=encodeURIComponent(o);return(await Promise.allSettled(i.map(l=>t(`${n}/projects/${c}/merge_requests/${s}/discussions/${l}`,{method:"PUT",headers:{"PRIVATE-TOKEN":r,"Content-Type":"application/json"},body:JSON.stringify({resolved:!0})}).then(p=>p.ok)))).filter(l=>l.status==="fulfilled"&&l.value===!0).length}async function Ku(e){let{fetchFn:t,token:r,apiBase:n,projectPath:o,branch:s,since:i}=e;try{let c=await Z_({fetchFn:t,token:r,apiBase:n,projectPath:o,branch:s});if(!c)return;let u=await Sd({fetchFn:t,token:r,apiBase:n,projectPath:o,mrIid:c.iid});return u?{changesRequested:u.some(p=>p.notes.some(d=>D_(d,i))),prNumber:c.iid,prUrl:c.url}:void 0}catch{return}}async function Hu(e){let{fetchFn:t,token:r,apiBase:n,projectPath:o,mrIid:s,since:i}=e;try{let c=await Sd({fetchFn:t,token:r,apiBase:n,projectPath:o,mrIid:s});return c?F_(c,i):{comments:[],discussionIds:[]}}catch{return{comments:[],discussionIds:[]}}}async function Z_(e){let{fetchFn:t,token:r,apiBase:n,projectPath:o,branch:s}=e,i=encodeURIComponent(o),c=await t(`${n}/projects/${i}/merge_requests?source_branch=${encodeURIComponent(s)}&state=opened`,{headers:{"PRIVATE-TOKEN":r}});if(!c.ok)return;let u=_d.parse(await c.json());if(u.length===0)return;let l=u[0];return{iid:l.iid,url:l.web_url}}async function Sd(e){let{fetchFn:t,token:r,apiBase:n,projectPath:o,mrIid:s}=e,i=encodeURIComponent(o),c=await t(`${n}/projects/${i}/merge_requests/${s}/discussions?per_page=100`,{headers:{"PRIVATE-TOKEN":r}});if(c.ok)return xd.parse(await c.json())}function D_(e,t){return e.system||F(e.body)||t&&e.created_at&&e.created_at<=t?!1:e.type==="DiffNote"&&e.resolvable!==!1&&e.resolved!==!0||N(e.body)}function F_(e,t){let r=e.map(n=>{let s=n.notes.filter(c=>!c.system&&!F(c.body)).filter(c=>!t||!c.created_at||c.created_at>t).flatMap(c=>M_(c)).filter(c=>c!==void 0),i=s.length>0&&n.id!=null?n.id:void 0;return{feedback:s,discussionId:i}});return{comments:r.flatMap(n=>n.feedback),discussionIds:r.map(n=>n.discussionId).filter(n=>n!=null)}}function M_(e){return e.type==="DiffNote"&&e.resolvable!==!1&&e.resolved!==!0?[`${e.position?.new_path?`[${e.position.new_path}] `:""}${e.body}`]:N(e.body)?[ae(e.body)]:[]}var eo=async()=>0,to=async()=>!1;function vd(e,t){let{fetchFn:r,token:n,apiBase:o}=e,s=`${t.owner}/${t.repo}`;return{checkReviewState:(i,c)=>Bu({fetchFn:r,token:n,repo:s,branch:i,owner:t.owner,apiBase:o,since:c}),fetchComments:async(i,c)=>({comments:await Ou({fetchFn:r,token:n,repo:s,prNumber:i,apiBase:o,since:c})}),postComment:(i,c)=>Zu({fetchFn:r,token:n,repo:s,prNumber:i,body:c,apiBase:o}),resolveThreads:eo,reRequestReview:(i,c)=>Du({fetchFn:r,token:n,repo:s,prNumber:i,reviewers:c,apiBase:o})}}function $d(e,t){let{fetchFn:r,token:n,apiBase:o}=e;return{checkReviewState:(s,i)=>Ku({fetchFn:r,token:n,apiBase:o,projectPath:t.projectPath,branch:s,since:i}),fetchComments:(s,i)=>Hu({fetchFn:r,token:n,apiBase:o,projectPath:t.projectPath,mrIid:s,since:i}),postComment:(s,i)=>Uu({fetchFn:r,token:n,apiBase:o,projectPath:t.projectPath,mrIid:s,body:i}),resolveThreads:(s,i)=>qu({fetchFn:r,token:n,apiBase:o,projectPath:t.projectPath,mrIid:s,discussionIds:i}),reRequestReview:to}}function Pd(e,t){let{fetchFn:r,token:n,username:o}=e;if(!o)throw new Error("Bitbucket Cloud requires a username");return{checkReviewState:(s,i)=>Ru({fetchFn:r,username:o,token:n,workspace:t.workspace,repoSlug:t.repoSlug,branch:s,since:i}),fetchComments:async(s,i)=>({comments:await Cu({fetchFn:r,username:o,token:n,workspace:t.workspace,repoSlug:t.repoSlug,prId:s,since:i})}),postComment:(s,i)=>Iu({fetchFn:r,username:o,token:n,workspace:t.workspace,repoSlug:t.repoSlug,prId:s,body:i}),resolveThreads:eo,reRequestReview:to}}function Id(e,t){let{fetchFn:r,token:n,apiBase:o}=e;return{checkReviewState:(s,i)=>zu({fetchFn:r,token:n,apiBase:o,projectKey:t.projectKey,repoSlug:t.repoSlug,branch:s,since:i}),fetchComments:async(s,i)=>({comments:await Au({fetchFn:r,token:n,apiBase:o,projectKey:t.projectKey,repoSlug:t.repoSlug,prId:s,since:i})}),postComment:(s,i)=>Eu({fetchFn:r,token:n,apiBase:o,projectKey:t.projectKey,repoSlug:t.repoSlug,prId:s,body:i}),resolveThreads:eo,reRequestReview:to}}function Rd(e,t){let{fetchFn:r,token:n}=e,{org:o,project:s,repo:i}=t;return{checkReviewState:(c,u)=>Su({fetchFn:r,org:o,project:s,repo:i,pat:n,branch:c,since:u}),fetchComments:async(c,u)=>({comments:await vu({fetchFn:r,org:o,project:s,repo:i,pat:n,prId:c,since:u})}),postComment:(c,u)=>xu({fetchFn:r,org:o,project:s,repo:i,pat:n,prId:c,body:u}),resolveThreads:eo,reRequestReview:to}}function rr(e){let{fetchFn:t,env:r,remote:n}=e,o=tr(r,n);if(!o)return;let s=Vt(n,r.CLANCY_GIT_API_URL);if(!s)return;let i={fetchFn:t,token:o.token,apiBase:s,username:o.username};switch(n.host){case"github":return vd(i,n);case"gitlab":return $d(i,n);case"bitbucket":return Pd(i,n);case"bitbucket-server":return Id(i,n);case"azure":return Rd(i,n);default:return}}function U_(e){return`You are evaluating whether a ticket can be implemented as pure code changes in a repository.
|
|
49
|
+
|
|
50
|
+
Ticket: [${e.key}] ${e.title}
|
|
51
|
+
Description:
|
|
52
|
+
${e.description}
|
|
53
|
+
|
|
54
|
+
Can this ticket be completed entirely through code changes committed to a git repository?
|
|
55
|
+
|
|
56
|
+
Answer INFEASIBLE if the ticket requires ANY of:
|
|
57
|
+
- Manual testing or configuration in external tools or admin panels
|
|
58
|
+
- Access to external services, APIs, or platforms not available in the codebase
|
|
59
|
+
- Physical, hardware, or infrastructure changes
|
|
60
|
+
- Design assets that do not yet exist
|
|
61
|
+
- Deployment or infrastructure changes outside the repository
|
|
62
|
+
- Human judgment calls that require stakeholder input
|
|
63
|
+
|
|
64
|
+
Answer with exactly one line in this format:
|
|
65
|
+
FEASIBLE
|
|
66
|
+
or
|
|
67
|
+
INFEASIBLE: one-line reason
|
|
68
|
+
|
|
69
|
+
Do not include any other text.`}function q_(e){let r=(e.trim().split(`
|
|
70
|
+
`).at(-1)??"").trim();return/^INFEASIBLE/i.test(r)?{feasible:!1,reason:r.replace(/^INFEASIBLE:?\s*/i,"").trim()||void 0}:{feasible:!0}}function Wu(e,t,r){let n=U_(t),{stdout:o,ok:s}=e(n,r);return s?q_(o):{feasible:!0}}var K_=["bug","bugfix","defect","hotfix","incident"],H_=["chore","task","maintenance","spike","tech debt","infrastructure"];function Cd(e,t){return new RegExp(`\\b${t}\\b`).test(e)}function ve(e){if(!e)return"feat";let t=e.toLowerCase().trim();return t?K_.some(r=>Cd(t,r))?"fix":H_.some(r=>Cd(t,r))?"chore":"feat":"feat"}function ro(e){return e.startsWith("epic/")||e.startsWith("milestone/")}function yt(e){let{config:t,ticket:r,targetBranch:n,verificationWarning:o}=e,{singleChildParent:s,epicContext:i}=e,c=n?ro(n):!1;return[...W_(i,c),...J_({config:t,ticket:r,isEpic:c,singleChildParent:s}),"",...Y_(r.description),...G_(o),...Q_()].join(`
|
|
71
|
+
`)}function Ju(e){let{epicKey:t,epicTitle:r,childEntries:n,provider:o}=e,s=n.map(u=>{let l=u.prNumber?` (#${u.prNumber})`:"";return`- ${u.key} \u2014 ${u.summary}${l}`}),i=o==="github"?X_(t,n):[];return[`## ${t} \u2014 ${r}`,"","### Children","",...s,...i,"","---","*Created by [Clancy](https://github.com/Pushedskydiver/chief-clancy)*"].join(`
|
|
72
|
+
`)}function W_(e,t){if(!e||!t)return[];let r=e.siblingsDelivered,n=r===0?"No siblings delivered yet":`${r} sibling${r===1?"":"s"} previously delivered to \`${e.epicBranch}\``;return[`## Part of epic ${e.parentKey}`,n,"",`> This PR targets \`${e.epicBranch}\`. A final epic PR will be created when all children are complete.`,""]}function J_(e){let{config:t,ticket:r,isEpic:n,singleChildParent:o}=e;switch(t.provider){case"github":{let s=n?`Part of ${r.key}`:`Closes ${r.key}`,i=o&&!n?[`Closes ${o}`]:[];return[s,...i]}case"jira":return[`**Jira:** [${r.key}](${t.env.JIRA_BASE_URL}/browse/${r.key})`];case"linear":return[`**Linear:** ${r.key}`];case"shortcut":case"notion":case"azdo":return[`**Ticket:** ${r.key}`]}}function Y_(e){return e?["## Description","",e,""]:[]}function G_(e){return e?["## \u26A0 Verification Warning","",e,"","This PR may need manual fixes before merging.",""]:[]}var V_=`---
|
|
73
|
+
*Created by [Clancy](https://github.com/Pushedskydiver/chief-clancy)*
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
<details>
|
|
77
|
+
<summary><strong>Rework instructions</strong> (click to expand)</summary>
|
|
78
|
+
|
|
79
|
+
To request changes:
|
|
80
|
+
- **Code comments** \u2014 leave inline comments on specific lines. These are always picked up automatically.
|
|
81
|
+
- **General feedback** \u2014 reply with a comment starting with \`Rework:\` followed by what needs fixing. Comments without the \`Rework:\` prefix are treated as discussion.
|
|
82
|
+
|
|
83
|
+
Example: \`Rework: The form validation doesn't handle empty passwords\`
|
|
84
|
+
|
|
85
|
+
</details>`;function Q_(){return V_.split(`
|
|
86
|
+
`)}function X_(e,t){let r=t.map(s=>s.key).filter(s=>s.startsWith("#")),o=[...e.startsWith("#")?[e]:[],...r];return o.length===0?[]:["","### Closes","",o.map(s=>`Closes ${s}`).join(", ")]}function Yu(e){let{exec:t,epicBranch:r,baseBranch:n}=e,o=fu(t,r),s=bt(t,r);return o?gt(t,r)?{ok:!0}:{ok:!1,error:`Could not fetch ${r} from remote`}:s?{ok:!1,error:`${r} exists locally but not on remote \u2014 push manually: git push -u origin ${r}`}:ew(t,r,n)}function Gu(e){let{progressFs:t,projectRoot:r,parent:n,targetBranch:o,ticketKey:s}=e;if(!n||!ro(o))return;let i=[...Le].flatMap(c=>K(t,r,c)).filter(c=>c.parent===n&&c.key!==s);return{parentKey:n,siblingsDelivered:i.length,epicBranch:o}}function Vu(e){let{progressFs:t,projectRoot:r,epicKey:n}=e;return[...Le].flatMap(o=>K(t,r,o)).filter(o=>o.parent===n)}function ew(e,t,r){try{return e(["fetch","origin",r]),e(["checkout","-b",t,`origin/${r}`]),Fe(e,t)?{ok:!0}:{ok:!1,error:`Created ${t} locally but could not push`}}catch(n){return{ok:!1,error:`Could not create epic branch: ${n instanceof Error?n.message:String(n)}`}}}async function $e(e){let{env:t,remote:r}=e,n=tr(t,r);if(!n)return;let o=Vt(r,t.CLANCY_GIT_API_URL);if(!o)return;let s={fetchFn:e.fetchFn,creds:n,apiBase:o,branch:e};switch(r.host){case"github":return tw(s,r);case"gitlab":return rw(s,r);case"bitbucket":return nw(s,r);case"bitbucket-server":return ow(s,r);case"azure":return sw(s,r);default:return}}function no(e,t,r){let n=encodeURIComponent(t),o=encodeURIComponent(r);switch(e.host){case"github":return`https://${e.hostname}/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}/compare/${o}...${n}`;case"gitlab":return`https://${e.hostname}/${e.projectPath}/-/merge_requests/new?merge_request[source_branch]=${n}&merge_request[target_branch]=${o}`;case"bitbucket":return`https://${e.hostname}/${encodeURIComponent(e.workspace)}/${encodeURIComponent(e.repoSlug)}/pull-requests/new?source=${n}&dest=${o}`;case"bitbucket-server":return`https://${e.hostname}/projects/${encodeURIComponent(e.projectKey)}/repos/${encodeURIComponent(e.repoSlug)}/pull-requests?create&sourceBranch=refs/heads/${n}&targetBranch=refs/heads/${o}`;case"azure":return`https://${e.hostname}/${encodeURIComponent(e.org)}/${encodeURIComponent(e.project)}/_git/${encodeURIComponent(e.repo)}/pullrequestcreate?sourceRef=${n}&targetRef=${o}`;default:return}}function tw(e,t){return Fu({fetchFn:e.fetchFn,token:e.creds.token,repo:`${t.owner}/${t.repo}`,head:e.branch.sourceBranch,base:e.branch.targetBranch,title:e.branch.title,body:e.branch.body,apiBase:e.apiBase})}function rw(e,t){return Mu({fetchFn:e.fetchFn,token:e.creds.token,apiBase:e.apiBase,projectPath:t.projectPath,sourceBranch:e.branch.sourceBranch,targetBranch:e.branch.targetBranch,title:e.branch.title,description:e.branch.body})}function nw(e,t){let{username:r}=e.creds;if(!r)throw new Error("Bitbucket Cloud requires a username");return Pu({fetchFn:e.fetchFn,username:r,token:e.creds.token,workspace:t.workspace,repoSlug:t.repoSlug,sourceBranch:e.branch.sourceBranch,targetBranch:e.branch.targetBranch,title:e.branch.title,description:e.branch.body})}function ow(e,t){return Tu({fetchFn:e.fetchFn,token:e.creds.token,apiBase:e.apiBase,projectKey:t.projectKey,repoSlug:t.repoSlug,sourceBranch:e.branch.sourceBranch,targetBranch:e.branch.targetBranch,title:e.branch.title,description:e.branch.body})}function sw(e,t){return wu({fetchFn:e.fetchFn,org:t.org,project:t.project,repo:t.repo,pat:e.creds.token,sourceBranch:e.branch.sourceBranch,targetBranch:e.branch.targetBranch,title:e.branch.title,description:e.branch.body})}function nr(e){let{pr:t,remote:r,sourceBranch:n,targetBranch:o}=e;return r.host==="none"?{type:"local"}:r.host==="unknown"?{type:"unsupported"}:t?.ok?{type:"created",url:t.url,number:t.number}:t&&!t.ok&&t.alreadyExists?{type:"exists"}:t&&!t.ok?{type:"failed",error:t.error,manualUrl:no(r,n,o)}:{type:"not_attempted",manualUrl:no(r,n,o)}}function or(e){switch(e.type){case"created":return{status:"PR_CREATED",prNumber:e.number};case"local":return{status:"LOCAL"};case"exists":case"failed":case"not_attempted":case"unsupported":return{status:"PUSHED"};default:return e}}async function Qu(e){let{exec:t,ticketBranch:r,targetBranch:n}=e;if(!Fe(t,r))return iw(e);let s=X(t,e.config.env.CLANCY_GIT_PLATFORM),i=await aw(e,s),c=nr({pr:i,remote:s,sourceBranch:r,targetBranch:n});return lw(e,c),Td(t,n),{pushed:!0,outcome:c,prResult:i}}function iw(e){let{exec:t,progressFs:r,projectRoot:n,ticket:o,targetBranch:s}=e,{skipLog:i=!1,parent:c}=e;return i||ee(r,n,{key:o.key,summary:o.title,status:"PUSH_FAILED",parent:c}),Td(t,s),{pushed:!1,outcome:{type:"local"}}}async function aw(e,t){let{fetchFn:r,config:n,ticket:o,ticketBranch:s,targetBranch:i}=e,u=`${ve(o.ticketType)}(${o.key}): ${o.title}`,l=cw(e),p=yt({config:n,ticket:{key:o.key,title:o.title,description:o.description,provider:n.provider},targetBranch:i,verificationWarning:uw(e),singleChildParent:e.singleChildParent,epicContext:l});return $e({fetchFn:r,env:n.env,remote:t,sourceBranch:s,targetBranch:i,title:u,body:p})}function cw(e){return Gu({progressFs:e.progressFs,projectRoot:e.projectRoot,parent:e.parent,targetBranch:e.targetBranch,ticketKey:e.ticket.key})}function uw(e){try{let t=e.deliverFs.readFile(`${e.projectRoot}/.clancy/verify-attempt.txt`).trim(),r=parseInt(t,10);if(r>0)return`Verification checks did not fully pass (${r} attempt(s)). Review carefully.`}catch{}}function lw(e,t){if(e.skipLog)return;let{status:r,prNumber:n}=or(t);ee(e.progressFs,e.projectRoot,{key:e.ticket.key,summary:e.ticket.title,status:r,prNumber:n,parent:e.parent})}function Td(e,t){try{oe(e,t)}catch{}}async function Xu(e){let{exec:t,config:r,epicKey:n,epicBranch:o,baseBranch:s}=e,i=Vu({progressFs:e.progressFs,projectRoot:e.projectRoot,epicKey:n}),c=X(t,r.env.CLANCY_GIT_PLATFORM),u=await pw(e,c,i),l=nr({pr:u,remote:c,sourceBranch:o,targetBranch:s});return fw(e,l),dw(l)}async function pw(e,t,r){let{fetchFn:n,config:o,epicKey:s,epicTitle:i,epicBranch:c,baseBranch:u}=e,p=`${ve(e.ticketType)}(${s}): ${i}`,d=Ju({epicKey:s,epicTitle:i,childEntries:r,provider:o.provider});return $e({fetchFn:n,env:o.env,remote:t,sourceBranch:c,targetBranch:u,title:p,body:d})}function fw(e,t){let{status:r,prNumber:n}=or(t),o=r==="PR_CREATED"?"EPIC_PR_CREATED":r;ee(e.progressFs,e.projectRoot,{key:e.epicKey,summary:e.epicTitle,status:o,prNumber:n})}function dw(e){return{ok:e.type==="created"||e.type==="exists",outcome:e}}import{join as tl}from"node:path";var Ed=".clancy",mw="quality.json",zd=`${Ed}/${mw}`,Ad={totalTickets:0,avgReworkCycles:0,avgVerificationRetries:0,avgDuration:0};function hw(){return{tickets:{},summary:Ad}}function el(e){return Math.round(e*100)/100}function oo(e,t,r=0){return r>=e.length?0:t(e[r])+oo(e,t,r+1)}function bw(e){return e!==null&&typeof e=="object"&&"reworkCycles"in e&&"verificationRetries"in e&&Number.isFinite(e.reworkCycles)&&Number.isFinite(e.verificationRetries)}function gw(e){return e!==null&&typeof e=="object"&&"tickets"in e&&typeof e.tickets=="object"&&e.tickets!==null&&!Array.isArray(e.tickets)}function rl(e){let t=Object.values(e),r=t.length;if(r===0)return Ad;let n=t.filter(o=>o.duration!=null);return{totalTickets:r,avgReworkCycles:el(oo(t,o=>o.reworkCycles)/r),avgVerificationRetries:el(oo(t,o=>o.verificationRetries)/r),avgDuration:n.length>0?el(oo(n,o=>o.duration)/n.length):0}}function Ld(e,t,r){let n=tl(t,zd),o=`${n}.tmp`;e.mkdir(tl(t,Ed)),e.writeFile(o,JSON.stringify(r,null,2)+`
|
|
87
|
+
`),e.rename(o,n)}function Nd(e,t){let r=e[t];if(r)return[r,e];let n={reworkCycles:0,verificationRetries:0};return[n,{...e,[t]:n}]}function jd(e,t){try{let r=JSON.parse(e.readFile(tl(t,zd)));if(gw(r)){let n=r.tickets,o=Object.fromEntries(Object.entries(n).filter(([,s])=>bw(s)));return{tickets:o,summary:rl(o)}}}catch{}return hw()}function nl(e,t,r){try{let n=jd(e,t),[o,s]=Nd(n.tickets,r),i={...s,[r]:{...o,reworkCycles:o.reworkCycles+1}};Ld(e,t,{tickets:i,summary:rl(i)})}catch{}}function ol(e,t,r){try{let n=jd(e,t),[o,s]=Nd(n.tickets,r.ticketKey),i={...s,[r.ticketKey]:{...o,deliveredAt:new Date(r.now).toISOString(),duration:Math.max(0,r.duration)}};Ld(e,t,{tickets:i,summary:rl(i)})}catch{}}import{join as Bd}from"node:path";var Od=".clancy",yw="costs.log",kw=6600,_w=6e4;function sl(e,t,r){let{ticketKey:n,startedAt:o,now:s,tokenRate:i=kw}=r,c=new Date(o).getTime(),u=Number.isNaN(c)?0:Math.max(0,s-c),l=Math.round(u/_w),p=Math.round(l*i),h=`${new Date(s).toISOString()} | ${n} | ${l}min | ~${p} tokens (estimated)
|
|
88
|
+
`;e.mkdir(Bd(t,Od)),e.appendFile(Bd(t,Od,yw),h)}function il(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;let r=Math.floor(t/60),n=t%60;if(r<60)return n>0?`${r}m ${n}s`:`${r}m`;let o=Math.floor(r/60),s=r%60;return s>0?`${o}h ${s}m`:`${o}h`}var ww=[{provider:"jira",label:"Jira",detect:e=>!!e.JIRA_BASE_URL,schema:ln},{provider:"github",label:"GitHub",detect:e=>!!(e.GITHUB_TOKEN&&e.GITHUB_REPO),schema:pn},{provider:"linear",label:"Linear",detect:e=>!!e.LINEAR_API_KEY,schema:fn},{provider:"shortcut",label:"Shortcut",detect:e=>!!e.SHORTCUT_API_TOKEN,schema:dn},{provider:"notion",label:"Notion",detect:e=>!!e.NOTION_DATABASE_ID,schema:mn},{provider:"azdo",label:"Azure DevOps",detect:e=>!!e.AZDO_ORG,schema:hn}];function so(e){let t=ww.find(n=>n.detect(e));if(!t)return"\u2717 No board detected \u2014 set Jira, GitHub, Linear, Shortcut, Notion, or Azure DevOps credentials in .clancy/.env";let r=t.schema.safeParse(e);return r.success?{provider:t.provider,env:r.data}:`\u2717 ${t.label} env validation failed: ${r.error.message}`}function Zd(e){return`Basic ${btoa(`:${e}`)}`}function Pe(e){return{Authorization:Zd(e),"Content-Type":"application/json"}}function Dd(e){return{Authorization:Zd(e),"Content-Type":"application/json-patch+json"}}function Y(e){return!(e.includes("'")||e.includes("\\")||e.includes("--")||e.includes(";")||e.includes("/*")||/[^\x20-\x7E\t]/.test(e))}function Ie(e,t){return`https://dev.azure.com/${encodeURIComponent(e)}/${encodeURIComponent(t)}/_apis`}function sr(e){return e?e.split(";").map(t=>t.trim()).filter(Boolean):[]}function al(e){return e.join("; ")}function ir(e){let t=e.match(/workItems\/(\d+)/i);if(!t)return;let r=parseInt(t[1],10);return Number.isNaN(r)?void 0:r}function Re(e){let t=parseInt(e.replace("azdo-",""),10);return Number.isNaN(t)?void 0:t}async function cl(e){let t=`https://dev.azure.com/${encodeURIComponent(e.org)}/_apis/projects/${encodeURIComponent(e.project)}?api-version=${"7.1"}`;return V({url:t,headers:Pe(e.pat),statusErrors:{401:"\u2717 Azure DevOps auth failed \u2014 check AZDO_PAT",403:"\u2717 Azure DevOps auth failed \u2014 check AZDO_PAT"},networkError:"\u2717 Could not reach Azure DevOps \u2014 check network",fetcher:e.fetcher})}async function io(e,t){let r=await S(`${Ie(e.org,e.project)}/wit/wiql?api-version=${"7.1"}`,{method:"POST",headers:Pe(e.pat),body:JSON.stringify({query:t})},{schema:bn,label:"Azure DevOps WIQL",fetcher:e.fetcher});return r?r.workItems.map(n=>n.id):[]}async function ar(e,t){return S(`${Ie(e.org,e.project)}/wit/workitems/${String(t)}?$expand=relations&api-version=${"7.1"}`,{headers:Pe(e.pat)},{schema:Wt,label:"Azure DevOps work item",fetcher:e.fetcher})}async function cr(e){let{ctx:t,id:r,patchOps:n}=e,o=t.fetcher??fetch;try{return(await o(`${Ie(t.org,t.project)}/wit/workitems/${String(r)}?api-version=${"7.1"}`,{method:"PATCH",headers:Dd(t.pat),body:JSON.stringify(n)})).ok}catch{return!1}}var Sw=200;function vw(e,t){return Array.from({length:Math.ceil(e.length/t)},(r,n)=>e.slice(n*t,n*t+t))}async function $w(e,t){let r=t.join(","),n=await S(`${Ie(e.org,e.project)}/wit/workitems?ids=${r}&$expand=relations&api-version=${"7.1"}`,{headers:Pe(e.pat)},{schema:gn,label:"Azure DevOps work items batch",fetcher:e.fetcher});return n?n.value:[]}async function kt(e,t){if(!t.length)return[];let r=vw(t,Sw);return(await Promise.all(r.map(o=>$w(e,o)))).flat()}function Pw(e){let t=sr(e.fields["System.Tags"]),r=(e.relations??[]).find(o=>o.rel==="System.LinkTypes.Hierarchy-Reverse"),n=r?ir(r.url):void 0;return{key:`azdo-${String(e.id)}`,title:e.fields["System.Title"]??"",description:e.fields["System.Description"]??"",workItemId:e.id,parentId:n,labels:t}}function Iw(e){let{ctx:t,status:r,wit:n}=e;return!Y(t.project)||!Y(r)||n&&!Y(n)?void 0:`SELECT [System.Id] FROM WorkItems WHERE ${[`[System.TeamProject] = '${t.project}'`,`[System.State] = '${r}'`,"[System.AssignedTo] = @Me",...n?[`[System.WorkItemType] = '${n}'`]:[]].join(" AND ")} ORDER BY [System.CreatedDate] ASC`}async function ul(e){let{ctx:t,excludeHitl:r,label:n,limit:o=5}=e,s=Iw(e);if(!s)return[];let i=await io(t,s);if(!i.length)return[];let c=i.slice(0,o*2),l=(await kt(t,c)).map(Pw),p=r?l.filter(h=>!h.labels?.includes("clancy:hitl")):l;return(n?p.filter(h=>h.labels?.includes(n)):p).slice(0,o)}async function Fd(e,t){let r=await ar(e,t);return r?sr(r.fields["System.Tags"]):void 0}async function Md(e,t,r){await cr({ctx:e,id:t,patchOps:[{op:"replace",path:"/fields/System.Tags",value:al(r)}]})}async function ll(e,t,r){await R(async()=>{let n=Re(t);n!==void 0&&await O({fetchCurrent:()=>Fd(e,n),writeUpdated:o=>Md(e,n,o),target:r,mode:"add"})},"addLabel")}async function pl(e,t,r){await R(async()=>{let n=Re(t);n!==void 0&&await O({fetchCurrent:()=>Fd(e,n),writeUpdated:o=>Md(e,n,o),target:r,mode:"remove"})},"removeLabel")}var Rw=new Set(["Done","Closed","Completed","Resolved"]);function Ud(e){let t=e.fields["System.State"];return!t||!Rw.has(t)}function qd(e){return{total:e.length,incomplete:e.filter(Ud).length}}async function ur(e,t){try{let r=await ar(e,t);if(!r)return!1;let n=(r.relations??[]).filter(i=>i.rel==="System.LinkTypes.Dependency-Reverse");if(!n.length)return!1;let o=n.map(i=>ir(i.url)).filter(i=>i!==void 0);return o.length?(await kt(e,o)).some(Ud):!1}catch{return!1}}async function lr(e){let{ctx:t,parentId:r,parentKey:n}=e;try{if(n){let o=`Epic: ${n}`,s=await Cw(t,o);if(s&&s.total>0)return s}return await Tw(t,r)}catch{return}}async function Cw(e,t){if(!Y(e.project)||!Y(t))return;let r=`SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = '${e.project}' AND [System.Description] CONTAINS '${t}'`,n=await io(e,r);if(!n.length)return{total:0,incomplete:0};let o=await kt(e,n);return qd(o)}async function Tw(e,t){if(Number.isNaN(t))return;let r=`SELECT [System.Id] FROM WorkItemLinks WHERE [Source].[System.Id] = ${String(t)} AND [System.Links.LinkType] = 'System.LinkTypes.Hierarchy-Forward' MODE (MustContain)`,n=await S(`${Ie(e.org,e.project)}/wit/wiql?api-version=${"7.1"}`,{method:"POST",headers:Pe(e.pat),body:JSON.stringify({query:r})},{schema:yn,label:"Azure DevOps WIQL links",fetcher:e.fetcher});if(!n)return;let s=(n.workItemRelations??[]).map(c=>c.target?.id).filter(c=>c!==void 0&&c!==t);if(!s.length)return{total:0,incomplete:0};let i=await kt(e,s);return qd(i)}function Ew(e,t){return{key:e.key,title:e.title,description:e.description,parentInfo:e.parentId?`azdo-${String(e.parentId)}`:"none",blockers:"None",issueId:String(e.workItemId),labels:e.labels??[],status:t}}function zw(e){if(!e.AZDO_ORG.trim())return"\u2717 AZDO_ORG must not be empty";if(!e.AZDO_PROJECT.trim())return"\u2717 AZDO_PROJECT must not be empty";if(!e.AZDO_PAT.trim())return"\u2717 AZDO_PAT must not be empty";if(!Y(e.AZDO_PROJECT))return"\u2717 AZDO_PROJECT contains unsafe characters for WIQL queries";let t=e.CLANCY_AZDO_STATUS??"New";if(!Y(t))return"\u2717 CLANCY_AZDO_STATUS contains unsafe characters for WIQL queries";if(e.CLANCY_AZDO_WIT&&!Y(e.CLANCY_AZDO_WIT))return"\u2717 CLANCY_AZDO_WIT contains unsafe characters for WIQL queries"}async function Aw(e,t,r){let n=r.CLANCY_AZDO_STATUS??"New";return(await ul({ctx:e,status:n,wit:r.CLANCY_AZDO_WIT,excludeHitl:t.excludeHitl,label:t.buildLabel??r.CLANCY_LABEL})).map(s=>Ew(s,n))}async function Lw(e,t,r){let n=Re(t.key);if(n===void 0)return!1;let o=await cr({ctx:e,id:n,patchOps:[{op:"replace",path:"/fields/System.State",value:r}]});return o&&console.log(` \u2192 Transitioned to ${r}`),o}function ao(e,t){let r={org:e.AZDO_ORG,project:e.AZDO_PROJECT,pat:e.AZDO_PAT,fetcher:t},n=o=>Aw(r,o,e);return{ping:()=>cl(r),validateInputs:()=>zw(e),fetchTicket:async o=>(await n(o))[0],fetchTickets:n,fetchBlockerStatus(o){let s=Re(o.key);return s!==void 0?ur(r,s):Promise.resolve(!1)},fetchChildrenStatus(o,s){let i=Re(s??o);return i===void 0?Promise.resolve(void 0):lr({ctx:r,parentId:i,parentKey:o})},transitionTicket:(o,s)=>Lw(r,o,s),ensureLabel:async()=>{},addLabel:(o,s)=>ll(r,o,s),removeLabel:(o,s)=>pl(r,o,s),sharedEnv:()=>e}}function fl(e){return e instanceof Error?e.message:String(e)}async function co(e,t){try{let r=T(e.token),n=e.fetcher??fetch,o=`${C}/repos/${e.repo}/labels/${encodeURIComponent(t)}`,s=await n(o,{headers:r});if(s.ok)return;s.status===404?await Nw(e,t,r):console.warn(`\u26A0 ensureLabel GET returned HTTP ${s.status}`)}catch(r){console.warn(`\u26A0 ensureLabel failed: ${fl(r)}`)}}async function Nw(e,t,r){let o=await(e.fetcher??fetch)(`${C}/repos/${e.repo}/labels`,{method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify({name:t,color:"0075ca"})});!o.ok&&o.status!==422&&console.warn(`\u26A0 ensureLabel create returned HTTP ${o.status}`)}async function dl(e,t,r){try{let n=T(e.token),s=await(e.fetcher??fetch)(`${C}/repos/${e.repo}/issues/${t}/labels`,{method:"POST",headers:{...n,"Content-Type":"application/json"},body:JSON.stringify({labels:[r]})});s.ok||console.warn(`\u26A0 addLabel returned HTTP ${s.status}`)}catch(n){console.warn(`\u26A0 addLabel failed: ${fl(n)}`)}}async function ml(e,t,r){try{let n=T(e.token),o=e.fetcher??fetch,s=`${C}/repos/${e.repo}/issues/${t}/labels/${encodeURIComponent(r)}`,i=await o(s,{method:"DELETE",headers:n});!i.ok&&i.status!==404&&console.warn(`\u26A0 removeLabel returned HTTP ${i.status}`)}catch(n){console.warn(`\u26A0 removeLabel failed: ${fl(n)}`)}}var jw=a.object({state:a.optional(a.string())}),Kd=a.object({total_count:a.optional(a.number())});async function Bw(e){let{headers:t,repo:r,blockerNumbers:n,fetcher:o}=e,s=o??fetch;return(await Promise.all(n.map(async c=>{let u=await s(`${C}/repos/${r}/issues/${c}`,{headers:t});if(!u.ok)return!1;let l=jw.safeParse(await u.json());return l.success&&l.data.state!=="closed"}))).some(Boolean)}async function pr(e){let{token:t,repo:r,issueNumber:n,body:o,fetcher:s}=e;if(!Se(r))return!1;let i=Ow(o,n);if(i.length===0)return!1;try{let c=T(t);return await Bw({headers:c,repo:r,blockerNumbers:i,fetcher:s})}catch(c){return console.warn(`\u26A0 fetchBlockerStatus failed: ${c instanceof Error?c.message:String(c)}`),!1}}function Ow(e,t){return[...e.matchAll(/Blocked by #(\d+)/gi)].map(r=>parseInt(r[1],10)).filter(r=>!Number.isNaN(r)&&r!==t)}async function Zw(e){let{token:t,repo:r,parentNumber:n,fetcher:o}=e,s={token:t,repo:r,fetcher:o},i=await Hd({...s,bodyRef:`Epic: #${n}`});if(i&&i.total>0)return{epic:i,parent:void 0};let c=await Hd({...s,bodyRef:`Parent: #${n}`});return{epic:i,parent:c}}async function fr(e){let{token:t,repo:r,parentNumber:n,currentTicketKey:o,fetcher:s}=e;if(Se(r))try{let{epic:i,parent:c}=await Zw({token:t,repo:r,parentNumber:n,fetcher:s}),u=[i,c].find(l=>l&&l.total>0);return u||(!i&&!c?void 0:o?{total:1,incomplete:1}:i??c??{total:0,incomplete:0})}catch(i){console.warn(`\u26A0 fetchChildrenStatus failed: ${i instanceof Error?i.message:String(i)}`);return}}async function Hd(e){let{token:t,repo:r,bodyRef:n,fetcher:o}=e,s=T(t),i=o??fetch,c=`"${n}" repo:${r} is:issue`,u=new URLSearchParams({q:c,per_page:"1"}),l=await i(`${C}/search/issues?${u}`,{headers:s});if(!l.ok)return;let p=Kd.safeParse(await l.json());if(!p.success)return;let d=p.data.total_count??0;if(d===0)return{total:0,incomplete:0};let h=`"${n}" repo:${r} is:issue is:open`,b=new URLSearchParams({q:h,per_page:"1"}),_=await i(`${C}/search/issues?${b}`,{headers:s});if(!_.ok)return;let w=Kd.safeParse(await _.json());return{total:d,incomplete:w.success?w.data.total_count??0:d}}var Dw=/^(?:Epic|Parent): (#\d+)/m;function Fw(e){return e.match(Dw)?.[1]}function uo(e){let t=parseInt(e.replace("#",""),10);return Number.isNaN(t)?void 0:t}function Mw(e){return{key:e.key,title:e.title,description:e.description,parentInfo:e.milestone??Fw(e.description)??"none",blockers:"None",issueId:e.key,labels:e.labels??[],status:"open"}}async function Uw(e,t){let r=await Nu(e.token,e.usernameCache,e.fetcher);return(await ju({token:e.token,repo:e.repo,label:t.buildLabel??e.defaultLabel,username:r,excludeHitl:t.excludeHitl,fetcher:e.fetcher})).map(Mw)}function lo(e,t){let r={token:e.GITHUB_TOKEN,repo:e.GITHUB_REPO,defaultLabel:e.CLANCY_LABEL,usernameCache:new ue,fetcher:t},n=o=>Uw(r,o);return{ping:()=>Lu(r.token,r.repo,r.fetcher),validateInputs:()=>Se(r.repo)?void 0:"\u2717 GITHUB_REPO format is invalid \u2014 expected owner/repo",fetchTicket:async o=>(await n(o))[0],fetchTickets:n,async fetchBlockerStatus(o){let s=uo(o.key),i={token:r.token,repo:r.repo,fetcher:r.fetcher};return s?pr({...i,issueNumber:s,body:o.description}):!1},async fetchChildrenStatus(o,s,i){let c=uo(o),u={token:r.token,repo:r.repo,fetcher:r.fetcher};return c?fr({...u,parentNumber:c,currentTicketKey:i}):void 0},transitionTicket:async()=>!1,ensureLabel:o=>co(r,o),async addLabel(o,s){await co(r,s);let i=uo(o);i&&await dl(r,i,s)},async removeLabel(o,s){let i=uo(o);i&&await ml(r,i,s)},sharedEnv:()=>e}}var qw=/^[a-zA-Z0-9 _\-'.:]+$/,Kw=/^[A-Z][A-Z0-9]+-\d+$/;function bl(e,t){return Buffer.from(`${e}:${t}`).toString("base64")}function te(e){return{Authorization:`Basic ${e}`,Accept:"application/json"}}function _t(e){return qw.test(e)}function Te(e){return Kw.test(e)}async function gl(e){let{baseUrl:t,projectKey:r,auth:n,fetcher:o}=e;return V({url:`${t}/rest/api/3/project/${r}`,headers:te(n),statusErrors:{401:"\u2717 Jira auth failed \u2014 check credentials",403:"\u2717 Jira permission denied for this project",404:`\u2717 Jira project "${r}" not found`},networkError:"\u2717 Could not reach Jira \u2014 check network",fetcher:o})}function Hw(e){let{projectKey:t,status:r,sprint:n,label:o,excludeHitl:s}=e,c=[t,r,...o?[o]:[]].find(l=>!_t(l));if(c)throw new Error(`Unsafe JQL value: "${c}"`);return`${[`project="${t}"`,...n?["sprint in openSprints()"]:[],...o?[`labels = "${o}"`]:[],...s?['labels != "clancy:hitl"']:[],"assignee=currentUser()",`status="${r}"`].join(" AND ")} ORDER BY priority ASC`}function Ww(e){return!e||typeof e!="object"?"":hl(e).join(" ")}function hl(e){return typeof e=="string"?[e]:Array.isArray(e)?e.flatMap(hl):e&&typeof e=="object"?Object.values(e).flatMap(hl):[]}async function yl(e){let{baseUrl:t,auth:r,projectKey:n,status:o}=e,{sprint:s,label:i,excludeHitl:c,limit:u=5,fetcher:l}=e,p=Hw({projectKey:n,status:o,sprint:s,label:i,excludeHitl:c}),d=await S(`${t}/rest/api/3/search/jql`,{method:"POST",headers:{...te(r),"Content-Type":"application/json"},body:JSON.stringify({jql:p,maxResults:u,fields:["summary","description","issuelinks","parent","customfield_10014","labels"]})},{schema:vn,label:"Jira API",fetcher:l});return d?d.issues.map(Yw):[]}function Jw(e){return(e??[]).filter(t=>t.type?.name==="Blocks"&&t.inwardIssue?.key).map(t=>t.inwardIssue?.key).filter(t=>!!t)}function Yw(e){let{fields:t}=e;return{key:e.key,title:t.summary,description:Ww(t.description),provider:"jira",epicKey:t.parent?.key??t.customfield_10014??void 0,blockers:Jw(t.issuelinks),labels:t.labels}}async function Gw(e){let{baseUrl:t,auth:r,issueKey:n,statusName:o}=e;return Te(n)?(await S(`${t}/rest/api/3/issue/${n}/transitions`,{headers:te(r)},{schema:$n,label:"Jira transitions",fetcher:e.fetcher}))?.transitions.find(i=>i.name===o)?.id:void 0}async function kl(e){let{baseUrl:t,auth:r,issueKey:n,statusName:o,fetcher:s}=e;try{let i=await Gw(e);return i?(await(s??fetch)(`${t}/rest/api/3/issue/${n}/transitions`,{method:"POST",headers:{...te(r),"Content-Type":"application/json"},body:JSON.stringify({transition:{id:i}})})).ok:(console.warn(`\u26A0 Jira transition "${o}" not found for ${n}`),!1)}catch{return!1}}async function Wd(e,t){let n=await(e.fetcher??fetch)(`${e.baseUrl}/rest/api/3/issue/${encodeURIComponent(t)}?fields=labels`,{headers:te(e.auth)});if(!n.ok){console.warn(`\u26A0 label GET ${t} failed: HTTP ${n.status}`);return}let o=In.safeParse(await n.json());if(o.success)return o.data.fields?.labels??[]}async function Jd(e,t,r){let o=await(e.fetcher??fetch)(`${e.baseUrl}/rest/api/3/issue/${encodeURIComponent(t)}`,{method:"PUT",headers:{...te(e.auth),"Content-Type":"application/json"},body:JSON.stringify({fields:{labels:r}})});o.ok||console.warn(`\u26A0 label PUT ${t} returned HTTP ${o.status}`)}async function _l(e,t,r){await R(async()=>{Te(t)&&await O({fetchCurrent:()=>Wd(e,t),writeUpdated:n=>Jd(e,t,n),target:r,mode:"add"})},"addLabel")}async function wl(e,t,r){await R(async()=>{Te(t)&&await O({fetchCurrent:()=>Wd(e,t),writeUpdated:n=>Jd(e,t,n),target:r,mode:"remove"})},"removeLabel")}var Yd=a.object({total:a.optional(a.number())});async function dr(e){let{baseUrl:t,auth:r,key:n,fetcher:o}=e;if(!Te(n))return!1;let s=o??fetch;try{let i=await s(`${t}/rest/api/3/issue/${n}?fields=issuelinks`,{headers:te(r)});if(!i.ok)return!1;let c=await i.json(),u=Pn.safeParse(c);return u.success?(u.data.fields?.issuelinks??[]).some(p=>{if(p.type?.name!=="Blocks"||!p.inwardIssue?.key)return!1;let d=p.inwardIssue.fields?.status?.statusCategory?.key;return d?d!=="done":!1}):!1}catch(i){return console.warn(`\u26A0 fetchBlockerStatus failed: ${i instanceof Error?i.message:String(i)}`),!1}}async function mr(e){let{baseUrl:t,auth:r,parentKey:n,fetcher:o}=e;if(Te(n))try{let s=n.split("-")[0],i={baseUrl:t,auth:r,fetcher:o},c=await Gd({...i,jql:`project = "${s}" AND description ~ "Epic: ${n}"`});return c&&c.total>0?c:await Gd({...i,jql:`parent = ${n}`})}catch(s){console.warn(`\u26A0 fetchChildrenStatus failed: ${s instanceof Error?s.message:String(s)}`);return}}async function Gd(e){let{baseUrl:t,auth:r,jql:n,fetcher:o}=e,s={...te(r),"Content-Type":"application/json"},i=o??fetch,c=await i(`${t}/rest/api/3/search/jql`,{method:"POST",headers:s,body:JSON.stringify({jql:n,maxResults:0})});if(!c.ok)return;let u=Yd.safeParse(await c.json());if(!u.success)return;let l=u.data.total??0;if(l===0)return{total:0,incomplete:0};let p=await i(`${t}/rest/api/3/search/jql`,{method:"POST",headers:s,body:JSON.stringify({jql:`${n} AND statusCategory != "done"`,maxResults:0})});if(!p.ok)return;let d=Yd.safeParse(await p.json());return{total:l,incomplete:d.success?d.data.total??0:l}}function Vw(e,t){let r=e.blockers.length?`Blocked by: ${e.blockers.join(", ")}`:"None";return{key:e.key,title:e.title,description:e.description,parentInfo:e.epicKey??"none",blockers:r,issueId:e.key,labels:e.labels??[],status:t}}function Qw(e){if(!_t(e.JIRA_PROJECT_KEY))return"\u2717 JIRA_PROJECT_KEY contains invalid characters";if(e.CLANCY_LABEL&&!_t(e.CLANCY_LABEL))return"\u2717 CLANCY_LABEL contains invalid characters";if(e.CLANCY_JQL_STATUS&&!_t(e.CLANCY_JQL_STATUS))return"\u2717 CLANCY_JQL_STATUS contains invalid characters"}async function Xw(e,t,r){return(await yl({baseUrl:e.baseUrl,auth:e.auth,projectKey:e.projectKey,status:e.statusName,sprint:r.CLANCY_JQL_SPRINT,label:t.buildLabel??r.CLANCY_LABEL,excludeHitl:t.excludeHitl,fetcher:e.fetcher})).map(o=>Vw(o,e.statusName))}async function ex(e,t,r){let n=await kl({baseUrl:e.baseUrl,auth:e.auth,issueKey:t.key,statusName:r,fetcher:e.fetcher});return n&&console.log(` \u2192 Transitioned to ${r}`),n}function po(e,t){let r={baseUrl:e.JIRA_BASE_URL,auth:bl(e.JIRA_USER,e.JIRA_API_TOKEN),projectKey:e.JIRA_PROJECT_KEY,statusName:e.CLANCY_JQL_STATUS??"To Do",fetcher:t},n={baseUrl:r.baseUrl,auth:r.auth,fetcher:r.fetcher},o=s=>Xw(r,s,e);return{ping:()=>gl({baseUrl:r.baseUrl,projectKey:r.projectKey,auth:r.auth,fetcher:r.fetcher}),validateInputs:()=>Qw(e),fetchTicket:async s=>(await o(s))[0],fetchTickets:o,fetchBlockerStatus:s=>dr({baseUrl:r.baseUrl,auth:r.auth,key:s.key,fetcher:r.fetcher}),fetchChildrenStatus:s=>mr({baseUrl:r.baseUrl,auth:r.auth,parentKey:s,fetcher:r.fetcher}),transitionTicket:(s,i)=>ex(r,s,i),ensureLabel:async()=>{},addLabel:(s,i)=>_l(n,s,i),removeLabel:(s,i)=>wl(n,s,i),sharedEnv:()=>e}}var Vd="https://api.linear.app/graphql",tx=/^[a-zA-Z0-9_-]+$/;function rx(e){return{Authorization:e,"Content-Type":"application/json"}}function fo(e){return tx.test(e)}function Qd(e,t,r){return{method:"POST",headers:rx(e),body:JSON.stringify({query:t,variables:r})}}async function M(e){let{apiKey:t,query:r,variables:n,fetcher:o}=e,i=await(o??fetch)(Vd,Qd(t,r,n)).catch(c=>{console.warn(`\u26A0 Linear API request failed: ${c instanceof Error?c.message:String(c)}`)});if(i){if(!i.ok){console.warn(`\u26A0 Linear API returned HTTP ${i.status}`);return}try{return await i.json()}catch{console.warn("\u26A0 Linear API returned invalid JSON");return}}}function nx(e){return e===401||e===403?{ok:!1,error:"\u2717 Linear auth failed \u2014 check LINEAR_API_KEY"}:{ok:!1,error:`\u2717 Linear API returned HTTP ${e}`}}async function xl(e,t){let r=await(t??fetch)(Vd,Qd(e,"{ viewer { id } }")).catch(()=>{});if(!r)return{ok:!1,error:"\u2717 Could not reach Linear \u2014 check network"};if(!r.ok)return nx(r.status);try{let n=await r.json(),o=Cn.safeParse(n);if(o.success&&o.data.data?.viewer?.id)return{ok:!0}}catch{}return{ok:!1,error:"\u2717 Linear auth failed \u2014 check LINEAR_API_KEY"}}function ox(e){return{key:e.identifier,title:e.title,description:e.description??"",provider:"linear",issueId:e.id,parentIdentifier:e.parent?.identifier,labels:e.labels?.nodes?.map(t=>t.name).filter(t=>!!t)}}function sx(e){let{teamId:t,label:r,excludeHitl:n,limit:o=5}=e,s=!!r?.trim(),i=["$teamId: ID!",...s?["$label: String!"]:[]],u=['state: { type: { eq: "unstarted" } }',"team: { id: { eq: $teamId } }",s?"labels: { name: { eq: $label } }":""].filter(Boolean),l=Math.min(Math.max(o,1),50),p=n?l*3:l;return{query:`
|
|
89
|
+
query(${i.join(", ")}) {
|
|
90
|
+
viewer {
|
|
91
|
+
assignedIssues(
|
|
92
|
+
filter: {
|
|
93
|
+
${u.join(`
|
|
94
|
+
`)}
|
|
95
|
+
}
|
|
96
|
+
first: ${String(p)}
|
|
97
|
+
orderBy: createdAt
|
|
98
|
+
) {
|
|
99
|
+
nodes {
|
|
100
|
+
id
|
|
101
|
+
identifier
|
|
102
|
+
title
|
|
103
|
+
description
|
|
104
|
+
parent { identifier title }
|
|
105
|
+
labels { nodes { name } }
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
`,variables:s?{teamId:t,label:r}:{teamId:t}}}function ix(e){return e.labels?.nodes?.some(t=>t.name==="clancy:hitl")===!0}async function Sl(e){if(!fo(e.teamId))return[];let{apiKey:t,excludeHitl:r,limit:n=5}=e,{query:o,variables:s}=sx(e),i=await M({apiKey:t,query:o,variables:s,fetcher:e.fetcher}),c=Rn.safeParse(i);if(!c.success)return[];let u=c.data.data?.viewer?.assignedIssues?.nodes??[];return(r?u.filter(p=>!ix(p)):u).slice(0,n).map(ox)}async function ax(e){let{apiKey:t,teamId:r,label:n,fetcher:o}=e,i=await M({apiKey:t,query:`
|
|
111
|
+
query($teamId: String!, $name: String!) {
|
|
112
|
+
team(id: $teamId) {
|
|
113
|
+
labels(filter: { name: { eq: $name } }) { nodes { id name } }
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
`,variables:{teamId:r,name:n},fetcher:o}),c=Nn.safeParse(i);return c.success?c.data.data?.team?.labels?.nodes?.[0]?.id:void 0}async function cx(e){let{apiKey:t,label:r,fetcher:n}=e,s=await M({apiKey:t,query:`
|
|
117
|
+
query($name: String!) {
|
|
118
|
+
issueLabels(filter: { name: { eq: $name } }) {
|
|
119
|
+
nodes { id name }
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
`,variables:{name:r},fetcher:n}),i=jn.safeParse(s);return i.success?i.data.data?.issueLabels?.nodes?.[0]?.id:void 0}async function ux(e){let{apiKey:t,teamId:r,label:n,fetcher:o}=e,i=await M({apiKey:t,query:`
|
|
123
|
+
mutation($teamId: String!, $name: String!) {
|
|
124
|
+
issueLabelCreate(input: { teamId: $teamId, name: $name, color: "#0075ca" }) {
|
|
125
|
+
issueLabel { id }
|
|
126
|
+
success
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
`,variables:{teamId:r,name:n},fetcher:o}),c=Bn.safeParse(i);return c.success?c.data.data?.issueLabelCreate?.issueLabel?.id:void 0}async function mo(e){let{apiKey:t,teamId:r,labelCache:n,label:o,fetcher:s}=e,i={apiKey:t,teamId:r,label:o,fetcher:s};await R(async()=>{if(n.has(o))return;let c=await ax(i);if(c){n.store(o,c);return}let u=await cx(i);if(u){n.store(o,u);return}let l=await ux(i);l&&n.store(o,l)},"ensureLabel")}async function vl(e){let{apiKey:t,labelCache:r,issueKey:n,label:o,fetcher:s}=e;await R(async()=>{let i=r.get(o);if(!i)return;let c=await Xd(t,n,s);if(!c)return;let u=c.labelIds;u.includes(i)||await em({apiKey:t,issueId:c.id,labelIds:[...u,i],fetcher:s})},"addLabel")}async function $l(e){let{apiKey:t,labelCache:r,issueKey:n,label:o,fetcher:s}=e;await R(async()=>{let i=await Xd(t,n,s);if(!i)return;let c=r.get(o),u=i.labels,l=c??u.find(d=>d.name===o)?.id;if(!l)return;let p=u.map(d=>d.id).filter(d=>d!==l);p.length!==u.length&&await em({apiKey:t,issueId:i.id,labelIds:p,fetcher:s})},"removeLabel")}async function Xd(e,t,r){let o=await M({apiKey:e,query:`
|
|
130
|
+
query($identifier: String!) {
|
|
131
|
+
issueSearch: issues(filter: { identifier: { eq: $identifier } }, first: 1) {
|
|
132
|
+
nodes {
|
|
133
|
+
id
|
|
134
|
+
labels { nodes { id name } }
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
`,variables:{identifier:t},fetcher:r}),s=On.safeParse(o);if(!s.success)return;let i=s.data.data?.issueSearch?.nodes?.[0];if(!i)return;let c=i.labels?.nodes??[];return{id:i.id,labelIds:c.map(u=>u.id),labels:c}}async function em(e){let{apiKey:t,issueId:r,labelIds:n,fetcher:o}=e;await M({apiKey:t,query:`
|
|
139
|
+
mutation($issueId: String!, $labelIds: [String!]!) {
|
|
140
|
+
issueUpdate(id: $issueId, input: { labelIds: $labelIds }) {
|
|
141
|
+
success
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
`,variables:{issueId:r,labelIds:n},fetcher:o})}var tm=new Set(["completed","canceled"]);async function hr(e,t,r){let o=await M({apiKey:e,query:`
|
|
145
|
+
query($issueId: String!) {
|
|
146
|
+
issue(id: $issueId) {
|
|
147
|
+
relations {
|
|
148
|
+
nodes {
|
|
149
|
+
type
|
|
150
|
+
relatedIssue {
|
|
151
|
+
state { type }
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
`,variables:{issueId:t},fetcher:r}),s=zn.safeParse(o);return s.success?(s.data.data?.issue?.relations?.nodes??[]).some(c=>{if(c.type!=="blockedBy")return!1;let u=c.relatedIssue?.state?.type;return u?!tm.has(u):!1}):!1}async function br(e){let{apiKey:t,parentId:r,parentIdentifier:n,fetcher:o}=e;try{if(n){let s=await lx(t,`Epic: ${n}`,o);if(s&&s.total>0)return s}return await px(t,r,o)}catch{return}}function rm(e){let t=e.length,r=e.filter(n=>!n.state?.type||!tm.has(n.state.type)).length;return{total:t,incomplete:r}}async function lx(e,t,r){let o=await M({apiKey:e,query:`
|
|
158
|
+
query($filter: String!) {
|
|
159
|
+
issueSearch(query: $filter) {
|
|
160
|
+
nodes {
|
|
161
|
+
state { type }
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
`,variables:{filter:t},fetcher:r}),s=An.safeParse(o);if(!s.success)return;let i=s.data.data?.issueSearch?.nodes??[];return rm(i)}async function px(e,t,r){let o=await M({apiKey:e,query:`
|
|
166
|
+
query($issueId: String!) {
|
|
167
|
+
issue(id: $issueId) {
|
|
168
|
+
children {
|
|
169
|
+
nodes {
|
|
170
|
+
state { type }
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
`,variables:{issueId:t},fetcher:r}),s=Ln.safeParse(o);if(!s.success)return;let i=s.data.data?.issue?.children?.nodes??[];return rm(i)}async function fx(e){let{apiKey:t,teamId:r,stateName:n,fetcher:o}=e,i=await M({apiKey:t,query:`
|
|
176
|
+
query($teamId: String!, $name: String!) {
|
|
177
|
+
workflowStates(filter: {
|
|
178
|
+
team: { id: { eq: $teamId } }
|
|
179
|
+
name: { eq: $name }
|
|
180
|
+
}) {
|
|
181
|
+
nodes { id }
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
`,variables:{teamId:r,name:n},fetcher:o}),c=Tn.safeParse(i);if(c.success)return c.data.data?.workflowStates?.nodes?.[0]?.id}async function Pl(e){let{apiKey:t,teamId:r,issueId:n,stateName:o,fetcher:s}=e;try{let i=await fx({apiKey:t,teamId:r,stateName:o,fetcher:s});if(!i)return console.warn(`\u26A0 Linear workflow state "${o}" not found \u2014 check team configuration`),!1;let u=await M({apiKey:t,query:`
|
|
185
|
+
mutation($issueId: String!, $stateId: String!) {
|
|
186
|
+
issueUpdate(id: $issueId, input: { stateId: $stateId }) {
|
|
187
|
+
success
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
`,variables:{issueId:n,stateId:i},fetcher:s}),l=En.safeParse(u);return l.success?l.data.data?.issueUpdate?.success===!0:!1}catch{return!1}}function dx(e){return{key:e.key,title:e.title,description:e.description,parentInfo:e.parentIdentifier??"none",blockers:"None",linearIssueId:e.issueId,issueId:e.issueId,labels:e.labels??[],status:"unstarted"}}async function mx(e,t){return(await Sl({apiKey:e.apiKey,teamId:e.teamId,label:t.buildLabel??e.defaultLabel,excludeHitl:t.excludeHitl,fetcher:e.fetcher})).map(dx)}async function hx(e,t,r){if(!t.linearIssueId)return!1;let n=await Pl({apiKey:e.apiKey,teamId:e.teamId,issueId:t.linearIssueId,stateName:r,fetcher:e.fetcher});return n&&console.log(` \u2192 Transitioned to ${r}`),n}async function bx(e,t,r){await mo({apiKey:e.apiKey,teamId:e.teamId,labelCache:e.labelCache,label:r,fetcher:e.fetcher}),await vl({apiKey:e.apiKey,labelCache:e.labelCache,issueKey:t,label:r,fetcher:e.fetcher})}function ho(e,t){let r={apiKey:e.LINEAR_API_KEY,teamId:e.LINEAR_TEAM_ID,defaultLabel:e.CLANCY_LABEL,labelCache:new Ue,fetcher:t},n=o=>mx(r,o);return{ping:()=>xl(r.apiKey,r.fetcher),validateInputs:()=>fo(r.teamId)?void 0:"\u2717 LINEAR_TEAM_ID contains invalid characters",fetchTicket:async o=>(await n(o))[0],fetchTickets:n,async fetchBlockerStatus(o){return o.issueId?hr(r.apiKey,o.issueId,r.fetcher):!1},fetchChildrenStatus:(o,s)=>br({apiKey:r.apiKey,parentId:s??o,parentIdentifier:o,fetcher:r.fetcher}),transitionTicket:(o,s)=>hx(r,o,s),ensureLabel:o=>mo({apiKey:r.apiKey,teamId:r.teamId,labelCache:r.labelCache,label:o,fetcher:r.fetcher}),addLabel:(o,s)=>bx(r,o,s),removeLabel:(o,s)=>$l({apiKey:r.apiKey,labelCache:r.labelCache,issueKey:o,label:s,fetcher:r.fetcher}),sharedEnv:()=>e}}var gr="https://api.notion.com/v1",gx="2022-06-28";function yr(e){return{Authorization:`Bearer ${e}`,"Notion-Version":gx,"Content-Type":"application/json"}}function bo(e,t,r){let n=e.properties[t];if(!(!n||n.type!==r))switch(r){case"status":return n.status?.name;case"select":return n.select?.name;case"title":return n.title.map(s=>s.plain_text).join("");case"rich_text":return n.rich_text.map(s=>s.plain_text).join("")}}function pe(e,t,r){let n=e.properties[t];if(!(!n||n.type!==r))switch(r){case"multi_select":return n.multi_select.map(s=>s.name);case"relation":return n.relation.map(s=>s.id);case"people":return n.people.map(s=>s.id)}}function go(e){return`notion-${e.replace(/-/g,"").slice(0,8)}`}var yx=new Set(["done","complete","completed","closed"]);function yo(e){return yx.has(e.toLowerCase())}function wt(e){return["Description","description","Body","body"].map(r=>bo(e,r,"rich_text")).find(Boolean)}function Il(e){let t=Object.entries(e.properties).find(([,r])=>r.type==="title");return t?bo(e,t[0],"title")??"":""}function ko(e,t){return bo(e,t,"status")??bo(e,t,"select")}function Rl(e,t){let r=ko(e,t);return!r||!yo(r)}function Cl(e,t){if(e.properties[t])return e.properties[t];let r=t.toLowerCase();return Object.entries(e.properties).find(([o])=>o.toLowerCase()===r)?.[1]}async function Tl(e,t){return V({url:`${gr}/users/me`,headers:yr(e),statusErrors:{401:"\u2717 Notion auth failed \u2014 check NOTION_TOKEN",403:"\u2717 Notion auth failed \u2014 check NOTION_TOKEN"},networkError:"\u2717 Could not reach Notion \u2014 check network",fetcher:t})}async function xt(e){let{ctx:t,filter:r,sorts:n,startCursor:o}=e,s={...r?{filter:r}:{},...n?{sorts:n}:{},...o?{start_cursor:o}:{}};return S(`${gr}/databases/${t.databaseId}/query`,{method:"POST",headers:yr(t.token),body:JSON.stringify(s)},{schema:Zn,label:"Notion API",fetcher:t.fetcher??Ae})}var kx=10;async function kr(e){return nm(e,void 0,[])}async function nm(e,t,r){let n=await xt({...e,startCursor:t});if(!n)return r;let o=[...r,...n.results],s=n.has_more?n.next_cursor:void 0,i=Math.ceil(o.length/100)<kx;return s&&i?nm(e,s,o):o}async function _o(e,t,r){return S(`${gr}/pages/${t}`,{headers:yr(e)},{schema:Jt,label:"Notion page",fetcher:r??Ae})}async function St(e){let{token:t,pageId:r,properties:n,fetcher:o}=e,s=o??Ae;try{return(await s(`${gr}/pages/${r}`,{method:"PATCH",headers:yr(t),body:JSON.stringify({properties:n})})).ok}catch{return!1}}async function vt(e,t){let r=t.replace("notion-","");return r?(await kr({ctx:e})).find(o=>o.id.replace(/-/g,"").slice(0,8)===r):void 0}async function om(e,t){await St({token:e.ctx.token,pageId:e.pageId,properties:{[e.labelsProp]:{multi_select:t.map(r=>({name:r}))}},fetcher:e.ctx.fetcher})}async function El(e){let{ctx:t,issueKey:r,label:n,labelsProp:o}=e;await R(async()=>{let s=await vt(t,r);s&&await O({fetchCurrent:()=>Promise.resolve(pe(s,o,"multi_select")??[]),writeUpdated:i=>om({ctx:t,pageId:s.id,labelsProp:o},i),target:n,mode:"add"})},"addLabel")}async function zl(e){let{ctx:t,issueKey:r,label:n,labelsProp:o}=e;await R(async()=>{let s=await vt(t,r);s&&await O({fetchCurrent:()=>Promise.resolve(pe(s,o,"multi_select")??[]),writeUpdated:i=>om({ctx:t,pageId:s.id,labelsProp:o},i),target:n,mode:"remove"})},"removeLabel")}function sm(e,t){let r=ko(e,t);return r!==void 0&&!yo(r)}async function _r(e){let{ctx:t,pageId:r,statusProp:n}=e;try{let o=await _o(t.token,r,t.fetcher);if(!o)return!1;let s=await _x(t,o,n);return s!==void 0?s:wx({ctx:t,page:o,pageId:r,statusProp:n})}catch{return!1}}async function _x(e,t,r){let n=Cl(t,"Blocked by");if(n?.type!=="relation")return;let o=n.relation;return o.length?(await Promise.all(o.map(i=>_o(e.token,i.id,e.fetcher)))).some(i=>!!i&&sm(i,r)):!1}async function wx(e){let{ctx:t,page:r,pageId:n,statusProp:o}=e,s=wt(r);if(!s)return!1;let i=s.match(/Blocked by (notion-[a-f0-9]{8})/gi);if(!i)return!1;let c=n.replace(/-/g,"").slice(0,8),u=await kr({ctx:t});if(!u.length)return!1;let l=p=>{let d=p.replace(/blocked by notion-/i,"").toLowerCase();if(d===c)return!1;let h=u.find(b=>b.id.replace(/-/g,"").slice(0,8)===d);return h!=null&&sm(h,o)};return i.some(l)}async function wr(e){let{ctx:t,parentKey:r,parentProp:n,statusProp:o}=e;try{let s=`Epic: ${r}`,i=await xx(t,s,o);if(i&&i.total>0)return i;let c=await vt(t,r);return c?await Sx({ctx:t,parentPageId:c.id,parentProp:n,statusProp:o}):void 0}catch{return}}async function xx(e,t,r){let n=await kr({ctx:e});if(!n.length)return;let o=n.filter(s=>wt(s)?.includes(t));return im(o,r)}async function Sx(e){let{ctx:t,parentPageId:r,parentProp:n,statusProp:o}=e,s=await xt({ctx:t,filter:{property:n,relation:{contains:r}}});if(s)return im([...s.results],o)}function im(e,t){return{total:e.length,incomplete:e.filter(r=>Rl(r,t)).length}}var wo={status:"Status",labels:"Labels",parent:"Epic",todo:"To-do"},vx=/^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;function $x(e,t){let r=pe(e,t.parentProp,"relation"),o=r&&r.length>0?go(r[0]):"none";return{key:go(e.id),title:Il(e),description:wt(e)??"",parentInfo:o,blockers:"None",issueId:e.id,labels:pe(e,t.labelsProp,"multi_select")??[],status:t.todoName}}async function Px(e){let{ctx:t,fetchOpts:r,props:n,defaultLabel:o}=e,s={property:n.statusProp,status:{equals:n.todoName}},i=await xt({ctx:t,filter:s});if(!i)return[];let c=r.excludeHitl?i.results.filter(p=>!pe(p,n.labelsProp,"multi_select")?.includes("clancy:hitl")):[...i.results],u=r.buildLabel??o;return(u?c.filter(p=>pe(p,n.labelsProp,"multi_select")?.includes(u)):c).slice(0,5).map(p=>$x(p,n))}async function Ix(e){let{token:t,ticket:r,status:n,statusProp:o,fetcher:s}=e,i=r.issueId;if(!i)return!1;if(await St({token:t,pageId:i,properties:{[o]:{status:{name:n}}},fetcher:s}))return console.log(` \u2192 Transitioned to ${n}`),!0;let u=await St({token:t,pageId:i,properties:{[o]:{select:{name:n}}},fetcher:s});return u&&console.log(` \u2192 Transitioned to ${n}`),u}function Rx(e,t){return{token:e.token,statusProp:t.statusProp,fetcher:e.fetcher}}function Cx(e,t){return{token:e.NOTION_TOKEN,databaseId:e.NOTION_DATABASE_ID,fetcher:t}}function Tx(e){return{statusProp:e.CLANCY_NOTION_STATUS??wo.status,labelsProp:e.CLANCY_NOTION_LABELS??wo.labels,parentProp:e.CLANCY_NOTION_PARENT??wo.parent,todoName:e.CLANCY_NOTION_TODO??wo.todo}}function xo(e,t){let r=Cx(e,t),n=Tx(e),o=Rx(r,n),s=i=>Px({ctx:r,fetchOpts:i,props:n,defaultLabel:e.CLANCY_LABEL});return{ping:()=>Tl(r.token,r.fetcher),validateInputs(){if(!vx.test(e.NOTION_DATABASE_ID))return"\u2717 NOTION_DATABASE_ID does not look like a valid UUID"},fetchTicket:async i=>(await s(i))[0],fetchTickets:s,fetchBlockerStatus:i=>i.issueId?_r({ctx:r,pageId:i.issueId,statusProp:n.statusProp}):Promise.resolve(!1),fetchChildrenStatus:i=>wr({ctx:r,parentKey:i,parentProp:n.parentProp,statusProp:n.statusProp}),transitionTicket:(i,c)=>Ix({...o,ticket:i,status:c}),ensureLabel:async()=>{},addLabel:(i,c)=>El({ctx:r,issueKey:i,label:c,labelsProp:n.labelsProp}),removeLabel:(i,c)=>zl({ctx:r,issueKey:i,label:c,labelsProp:n.labelsProp}),sharedEnv:()=>e}}var z="https://api.app.shortcut.com/api/v3";function j(e){return{"Shortcut-Token":e,"Content-Type":"application/json"}}async function Al(e,t){let r=j(e),n=t??fetch,o=await n(`${z}/member-info`,{headers:r}).then(async s=>s.ok?s:n(`${z}/workflows`,{headers:r})).catch(()=>{});if(!o)return{ok:!1,error:"\u2717 Could not reach Shortcut \u2014 check network"};if(!o.ok)return o.status===401||o.status===403?{ok:!1,error:"\u2717 Shortcut auth failed \u2014 check SHORTCUT_API_TOKEN"}:{ok:!1,error:`\u2717 Shortcut API returned HTTP ${o.status}`};try{let s=await o.json(),i=qn.safeParse(s);if(i.success&&i.data.id)return{ok:!0};if(Array.isArray(s))return{ok:!0}}catch{}return{ok:!1,error:"\u2717 Shortcut auth failed \u2014 check SHORTCUT_API_TOKEN"}}async function am(e,t,r){let n=t.get();if(n)return n;let o=await S(`${z}/workflows`,{headers:j(e)},{schema:Dn,label:"Shortcut workflows",fetcher:r});return o&&t.store(o),o??[]}async function Ll(e,t){let{token:r,cache:n,workflowName:o,fetcher:s}=t,i=await am(r,n,s),c=e.toLowerCase();return i.filter(l=>!o||l.name===o).flatMap(l=>l.states).find(l=>l.name.toLowerCase()===c)?.id}async function So(e,t){let{token:r,cache:n,workflowName:o,fetcher:s}=t;return(await am(r,n,s)).flatMap(c=>o&&c.name!==o?[]:c.states.filter(u=>u.type===e).map(u=>u.id))}async function xr(e,t){let r=await So("done",{token:e,cache:t});return new Set(r)}function Ex(e){let t=Ze.safeParse(e);if(t.success)return t.data.data;if(Array.isArray(e)){let r=Ze.safeParse({data:e});if(r.success)return r.data.data}return[]}function zx(e){return{key:`sc-${String(e.id)}`,title:e.name,description:e.description??"",provider:"shortcut",storyId:e.id,epicId:e.epic_id??void 0,labels:e.labels?.map(t=>t.name).filter(t=>!!t)}}async function Ax(e,t,r){let o=await(r??fetch)(`${z}/stories/search`,{method:"POST",headers:j(e),body:JSON.stringify(t)}).catch(i=>{console.warn(`\u26A0 Shortcut API request failed: ${i instanceof Error?i.message:String(i)}`)});if(!o)return[];if(!o.ok){let i=await o.text().catch(()=>"");return console.warn(`\u26A0 Shortcut story search returned HTTP ${o.status} \u2014 ${i}`),[]}let s=await o.json().catch(()=>{console.warn("\u26A0 Shortcut API returned invalid JSON")});return s===void 0?[]:Ex(s)}async function Nl(e){let{token:t,workflowStateIds:r,label:n,excludeHitl:o,limit:s=5}=e;if(!r.length)return[];let i=new Set(r),c={archived:!1,...n?{label_name:n}:{}},l=(await Ax(t,c,e.fetcher)).filter(d=>d.workflow_state_id!==void 0&&i.has(d.workflow_state_id));return(o?l.filter(d=>!d.labels?.some(h=>h.name==="clancy:hitl")):l).slice(0,s).map(zx)}async function jl(e){let{token:t,storyId:r,workflowStateId:n,fetcher:o}=e,s=o??fetch;try{return(await s(`${z}/stories/${String(r)}`,{method:"PUT",headers:j(t),body:JSON.stringify({workflow_state_id:n})})).ok}catch{return!1}}async function Bl(e){let{token:t,cache:r,refresh:n,fetcher:o}=e,s=r.get();if(s&&!n)return s;let i=await S(`${z}/labels`,{headers:j(t)},{schema:Fn,label:"Shortcut labels",fetcher:o});return i&&r.store(i),i??[]}async function Lx(e,t,r){return(await S(`${z}/labels`,{method:"POST",headers:j(e),body:JSON.stringify({name:t,color:"#0075ca"})},{schema:Mn,label:"Shortcut label create",fetcher:r}))?.id}async function cm(e,t,r){let n=await S(`${z}/stories/${String(t)}`,{headers:j(e)},{schema:De,label:"Shortcut story",fetcher:r});return n?n.label_ids??[]:void 0}async function um(e){let{token:t,storyId:r,labelIds:n,fetcher:o}=e,s=o??fetch;try{let i=await s(`${z}/stories/${String(r)}`,{method:"PUT",headers:j(t),body:JSON.stringify({label_ids:n})});i.ok||console.warn(`\u26A0 Shortcut story label update returned HTTP ${i.status}`)}catch(i){console.warn(`\u26A0 Shortcut story label update failed: ${i instanceof Error?i.message:String(i)}`)}}async function vo(e){let{token:t,labelCache:r,label:n,fetcher:o}=e;await R(async()=>{(await Bl({token:t,cache:r,fetcher:o})).find(c=>c.name===n)||(await Lx(t,n,o),await Bl({token:t,cache:r,refresh:!0,fetcher:o}))},"ensureLabel")}async function lm(e){let{token:t,labelCache:r,label:n,fetcher:o}=e;return(await Bl({token:t,cache:r,fetcher:o})).find(i=>i.name===n)?.id}function $t(e){let t=parseInt(e.replace("sc-",""),10);return Number.isNaN(t)?void 0:t}async function Ol(e){let{token:t,labelCache:r,issueKey:n,label:o,fetcher:s}=e;await R(async()=>{let i=$t(n);if(i===void 0)return;let c=await lm({token:t,labelCache:r,label:o,fetcher:s});c!==void 0&&await O({fetchCurrent:()=>cm(t,i,s),writeUpdated:u=>um({token:t,storyId:i,labelIds:u,fetcher:s}),target:c,mode:"add"})},"addLabel")}async function Zl(e){let{token:t,labelCache:r,issueKey:n,label:o,fetcher:s}=e;await R(async()=>{let i=$t(n);if(i===void 0)return;let c=await lm({token:t,labelCache:r,label:o,fetcher:s});c!==void 0&&await O({fetchCurrent:()=>cm(t,i,s),writeUpdated:u=>um({token:t,storyId:i,labelIds:u,fetcher:s}),target:c,mode:"remove"})},"removeLabel")}async function Nx(e){let{token:t,blockerId:r,doneStateIds:n,fetcher:o}=e,s=await S(`${z}/stories/${String(r)}`,{headers:j(t)},{schema:De,label:"Shortcut blocker",fetcher:o});return s?s.workflow_state_id!==void 0&&!n.has(s.workflow_state_id):!1}async function Sr(e){let{token:t,storyId:r,workflowCache:n,fetcher:o}=e;try{let s=await S(`${z}/stories/${String(r)}`,{headers:j(t)},{schema:De,label:"Shortcut story",fetcher:o});if(!s?.blocked)return!1;let i=(s.story_links??[]).filter(l=>l.verb==="is blocked by");if(!i.length)return!1;let c=await xr(t,n);return(await Promise.all(i.map(l=>Nx({token:t,blockerId:l.object_id,doneStateIds:c,fetcher:o})))).some(Boolean)}catch{return!1}}async function vr(e){let{token:t,epicId:r,workflowCache:n,parentKey:o,fetcher:s}=e;try{let i={token:t,workflowCache:n,fetcher:s};if(o){let c=await jx({...i,descriptionRef:`Epic: ${o}`});if(c&&c.total>0)return c}return await Bx({...i,epicId:r})}catch{return}}function pm(e,t){let r=e.length,n=e.filter(o=>o.workflow_state_id===void 0||!t.has(o.workflow_state_id)).length;return{total:r,incomplete:n}}async function jx(e){let{token:t,workflowCache:r,fetcher:n,descriptionRef:o}=e,s=await S(`${z}/stories/search`,{method:"POST",headers:j(t),body:JSON.stringify({query:o})},{schema:Ze,label:"Shortcut story search",fetcher:n});if(!s)return;let i=s.data;if(!i.length)return{total:0,incomplete:0};let c=await xr(t,r);return pm(i,c)}async function Bx(e){let{token:t,workflowCache:r,fetcher:n,epicId:o}=e,s=await S(`${z}/epics/${String(o)}/stories`,{headers:j(t)},{schema:Un,label:"Shortcut epic stories",fetcher:n});if(!s)return;if(!s.length)return{total:0,incomplete:0};let i=await xr(t,r);return pm(s,i)}function Ox(e){return{key:e.key,title:e.title,description:e.description,parentInfo:e.epicId?`epic-${String(e.epicId)}`:"none",blockers:"None",issueId:String(e.storyId),labels:e.labels??[],status:"unstarted"}}function fm(e){return{token:e.token,cache:e.workflowCache,workflowName:e.workflowName,fetcher:e.fetcher}}async function Zx(e,t){let r=await So("unstarted",fm(e));return(await Nl({token:e.token,workflowStateIds:r,label:t.buildLabel??e.defaultLabel,excludeHitl:t.excludeHitl,fetcher:e.fetcher})).map(Ox)}async function Dx(e,t,r){let n=$t(t.key);if(n===void 0)return!1;let o=await Ll(r,fm(e));if(o===void 0)return console.warn(`\u26A0 Shortcut workflow state "${r}" not found \u2014 check workflow configuration`),!1;let s=await jl({token:e.token,storyId:n,workflowStateId:o,fetcher:e.fetcher});return s&&console.log(` \u2192 Transitioned to ${r}`),s}async function Fx(e,t){let r=$t(t);return r!==void 0?Sr({token:e.token,storyId:r,workflowCache:e.workflowCache,fetcher:e.fetcher}):!1}async function Mx(e,t,r){let n=r??t.replace(/^(?:sc-|epic-)/,""),o=parseInt(n,10);return Number.isNaN(o)?void 0:vr({token:e.token,epicId:o,workflowCache:e.workflowCache,parentKey:t,fetcher:e.fetcher})}async function Ux(e,t,r){await vo({token:e.token,labelCache:e.labelCache,label:r,fetcher:e.fetcher}),await Ol({token:e.token,labelCache:e.labelCache,issueKey:t,label:r,fetcher:e.fetcher})}function $o(e,t){let r={token:e.SHORTCUT_API_TOKEN,workflowName:e.SHORTCUT_WORKFLOW,defaultLabel:e.CLANCY_LABEL,workflowCache:new ue,labelCache:new ue,fetcher:t},n=o=>Zx(r,o);return{ping:()=>Al(r.token,r.fetcher),validateInputs:()=>{},fetchTicket:async o=>(await n(o))[0],fetchTickets:n,fetchBlockerStatus:o=>Fx(r,o.key),fetchChildrenStatus:(o,s)=>Mx(r,o,s),transitionTicket:(o,s)=>Dx(r,o,s),ensureLabel:o=>vo({token:r.token,labelCache:r.labelCache,label:o,fetcher:r.fetcher}),addLabel:(o,s)=>Ux(r,o,s),removeLabel:(o,s)=>Zl({token:r.token,labelCache:r.labelCache,issueKey:o,label:s,fetcher:r.fetcher}),sharedEnv:()=>e}}function Po(e,t){switch(e.provider){case"jira":return po(e.env,t);case"github":return lo(e.env,t);case"linear":return ho(e.env,t);case"shortcut":return $o(e.env,t);case"notion":return xo(e.env,t);case"azdo":return ao(e.env,t);default:return e}}var ce=e=>`\x1B[2m${e}\x1B[0m`;var Dl=e=>`\x1B[32m${e}\x1B[0m`,Io=e=>`\x1B[31m${e}\x1B[0m`;function dm(e,t){return t?[...e,"--model",t]:e}function mm(e){return e.status===0&&!e.error}function Fl(e){let{prompt:t,model:r,spawn:n}=e,s=dm(["-p","--dangerously-skip-permissions"],r),i=n("claude",s,{input:t,stdio:["pipe","pipe","pipe"],encoding:"utf8"});return{stdout:i.stdout??"",ok:mm(i)}}function Ml(e){let{prompt:t,model:r,spawn:n}=e,s=dm(["--dangerously-skip-permissions"],r),i=n("claude",s,{input:t,stdio:["pipe","inherit","inherit"],encoding:"utf8"});return mm(i)}function qx(e){try{let{hostname:t}=new URL(e);return t==="hooks.slack.com"||t.endsWith(".hooks.slack.com")}catch{return!1}}function Kx(e){return JSON.stringify({text:e})}function Hx(e){return JSON.stringify({type:"message",attachments:[{contentType:"application/vnd.microsoft.card.adaptive",content:{$schema:"http://adaptivecards.io/schemas/adaptive-card.json",type:"AdaptiveCard",version:"1.4",body:[{type:"TextBlock",text:e,wrap:!0}]}}]})}async function Ul(e){let{webhookUrl:t,message:r,fetch:n,warn:o=console.warn}=e,s=qx(t)?Kx(r):Hx(r);try{let i=await n(t,{method:"POST",headers:{"Content-Type":"application/json"},body:s});i.ok||o(`\u26A0 Notification failed: HTTP ${i.status}`)}catch{o("\u26A0 Notification failed: could not reach webhook")}}function hm(e,t){let{projectRoot:r,exec:n,fetch:o,qualityFs:s}=e;return{deliver:i=>nt(i,{deliverViaPullRequest:c=>Qu({...c,exec:n,fetchFn:o,progressFs:e.progressFs,deliverFs:{readFile:u=>s.readFile(u)},projectRoot:r,config:i.config,ticket:i.ticket}),appendProgress:t,recordDelivery:()=>{let c=Date.now();ol(s,r,{ticketKey:i.ticket.key,duration:c-i.startTime,now:c})},recordRework:()=>nl(s,r,i.ticket.key),removeBuildLabel:async c=>{await i.board.removeLabel(c,ql(i))},postReworkActions:async c=>{let u=X(n),l=rr({fetchFn:o,env:i.config.env,remote:u});l&&await _u({...c,handlers:l})}})}}function Wx(e){switch(e){case"jira":return"Jira ticket";case"github":return"GitHub Issue";case"linear":return"Linear issue";case"shortcut":return"Shortcut story";case"notion":return"Notion page";case"azdo":return"Azure DevOps work item"}}var bm=`
|
|
191
|
+
## Test-Driven Development
|
|
192
|
+
|
|
193
|
+
You MUST follow the red-green-refactor cycle for every behaviour change:
|
|
194
|
+
|
|
195
|
+
1. **Red** \u2014 Write a failing test that describes the desired behaviour.
|
|
196
|
+
Run the test suite and confirm the new test fails.
|
|
197
|
+
2. **Green** \u2014 Write the minimum code to make the failing test pass.
|
|
198
|
+
Do not add behaviour beyond what the test requires.
|
|
199
|
+
3. **Refactor** \u2014 Clean up the implementation while keeping all tests green.
|
|
200
|
+
Look for duplication, unclear names, or unnecessary complexity.
|
|
201
|
+
|
|
202
|
+
Repeat for each behaviour. Do not write implementation code without a failing test first.
|
|
203
|
+
Design interfaces for testability \u2014 prefer pure functions and thin boundaries
|
|
204
|
+
so modules are easy to test in isolation.`;function Jx(e){switch(e){case"github":return"Milestone";case"notion":return"Parent page";case"jira":case"linear":case"shortcut":case"azdo":return"Epic"}}function Kl(e){let t=Wx(e.provider),r=Jx(e.provider),n=e.provider==="github",o=n?"issue":"ticket",s=e.blockers&&!n?`
|
|
205
|
+
Blockers: ${e.blockers}`:"";return`You are implementing ${t} ${e.key}.
|
|
206
|
+
|
|
207
|
+
${n?"Title":"Summary"}: ${e.title}
|
|
208
|
+
${r}: ${e.parentInfo}${s}
|
|
209
|
+
|
|
210
|
+
Description:
|
|
211
|
+
${e.description}
|
|
212
|
+
|
|
213
|
+
Step 0 \u2014 Executability check (do this before any git or file operation):
|
|
214
|
+
Read the ${n?"issue title and description":"ticket summary and description"} above. Can this ${o} be implemented entirely
|
|
215
|
+
as a code change committed to this repo? Consult the 'Executability check' section of
|
|
216
|
+
CLAUDE.md for the full list of skip conditions.
|
|
217
|
+
|
|
218
|
+
If you must SKIP this ${o}:
|
|
219
|
+
1. Output: \u26A0 Skipping [${e.key}]: {one-line reason}
|
|
220
|
+
2. Output: Ticket skipped \u2014 update it to be codebase-only work, then re-run.
|
|
221
|
+
3. Append to .clancy/progress.txt: YYYY-MM-DD HH:MM | ${e.key} | {reason} | SKIPPED
|
|
222
|
+
4. Stop \u2014 no branches, no file changes, no git operations.
|
|
223
|
+
|
|
224
|
+
If the ${o} IS implementable, continue:${e.tdd?bm:""}
|
|
225
|
+
1. Read core docs in .clancy/docs/: STACK.md, ARCHITECTURE.md, CONVENTIONS.md, GIT.md, DEFINITION-OF-DONE.md, CONCERNS.md
|
|
226
|
+
Also read if relevant to this ticket: INTEGRATIONS.md (external APIs/services/auth), TESTING.md (tests/specs/coverage), DESIGN-SYSTEM.md (UI/components/styles), ACCESSIBILITY.md (accessibility/ARIA/WCAG)
|
|
227
|
+
2. Follow the conventions in GIT.md exactly
|
|
228
|
+
3. Implement the ${o} fully
|
|
229
|
+
4. Commit your work following the conventions in GIT.md
|
|
230
|
+
5. When done, confirm you are finished.`}function Hl(e){let t=e.feedbackComments.length>0?e.feedbackComments.map((n,o)=>`${o+1}. ${n}`).join(`
|
|
231
|
+
`):"No reviewer comments found. Review the existing implementation and fix any issues.",r=e.previousContext?`
|
|
232
|
+
|
|
233
|
+
## Previous Implementation
|
|
234
|
+
|
|
235
|
+
\`\`\`
|
|
236
|
+
${e.previousContext}
|
|
237
|
+
\`\`\``:"";return`You are fixing review feedback on [${e.key}] ${e.title}.
|
|
238
|
+
|
|
239
|
+
Description:
|
|
240
|
+
${e.description}
|
|
241
|
+
|
|
242
|
+
## Reviewer Feedback
|
|
243
|
+
|
|
244
|
+
${t}${r}
|
|
245
|
+
|
|
246
|
+
Address the specific feedback above. Don't re-implement unrelated areas. Focus only on what was flagged.${e.tdd?bm:""}
|
|
247
|
+
|
|
248
|
+
Steps:
|
|
249
|
+
1. Read core docs in .clancy/docs/: STACK.md, ARCHITECTURE.md, CONVENTIONS.md, GIT.md, DEFINITION-OF-DONE.md, CONCERNS.md
|
|
250
|
+
Also read if relevant to this ticket: INTEGRATIONS.md (external APIs/services/auth), TESTING.md (tests/specs/coverage), DESIGN-SYSTEM.md (UI/components/styles), ACCESSIBILITY.md (accessibility/ARIA/WCAG)
|
|
251
|
+
2. Follow the conventions in GIT.md exactly
|
|
252
|
+
3. Fix the issues identified in the reviewer feedback
|
|
253
|
+
4. Commit your work following the conventions in GIT.md
|
|
254
|
+
5. When done, confirm you are finished.`}function gm(e){return async t=>{let r=t.config,n=t.ticket,o=r.env.CLANCY_TDD==="true",s=t.isRework?Hl({provider:r.provider,key:n.key,title:n.title,description:n.description,feedbackComments:t.prFeedback??[],tdd:o}):Kl({provider:r.provider,key:n.key,title:n.title,description:n.description,parentInfo:n.parentInfo,blockers:n.blockers,tdd:o});return{ok:Ml({prompt:s,model:r.env.CLANCY_MODEL,spawn:e})}}}function Yx(e,t){return r=>ee(e,t,r)}var Gx="clancy:build";function ql(e){let t=e.config?.env;return t?.CLANCY_LABEL_BUILD??t?.CLANCY_LABEL??Gx}function ym(e){return e.parent!==void 0}function Vx(e,t){return()=>{let n=K(e,t,"DONE").filter(ym).map(o=>[o.parent,o.key]);return new Map(n)}}function Qx(e){return async(t,r,n)=>{let o=n.config,s=o.env.CLANCY_BASE_BRANCH??"main",i=ym(t)?t.parent:void 0,c=Me(o.provider,t.key),u=er(o.provider,s,i),p=`${ve(t.ticketType)}(${t.key}): ${t.summary}`,d=yt({config:o,ticket:{key:t.key,title:t.summary,description:t.summary,provider:o.provider},targetBranch:u});return $e({fetchFn:e,env:o.env,remote:r,sourceBranch:c,targetBranch:u,title:p,body:d})}}function Xx(e,t){let{projectRoot:r,exec:n,lockFs:o,progressFs:s}=e;return{lockCheck:i=>ut(i,{lockFs:o,exec:n,progressFs:s,detectResume:c=>gu(c),executeResume:c=>yu(c)}),preflight:i=>pt(i,{runPreflight:c=>bu(c,{exec:(u,l)=>n([u,...l]),envFs:e.envFs}),detectBoard:c=>so(c),createBoard:c=>Po(c,(u,l)=>e.fetch(u,l??{}))}),epicCompletion:i=>ot(i,{findCompletedEpics:Vx(s,r),deliverEpicToBase:c=>Xu({...c,exec:n,fetchFn:e.fetch,progressFs:s,projectRoot:r,config:c.config})}),prRetry:i=>lt(i,{findRetryable:()=>K(s,r,"PUSHED"),detectRemote:()=>X(n),retryEntry:Qx(e.fetch),appendProgress:t})}}function eS(e,t){let{projectRoot:r,exec:n,progressFs:o,spawn:s,fetch:i}=e;return{reworkDetection:c=>ft(c,{fetchRework:async u=>{let l=X(n),p=rr({fetchFn:i,env:u.env,remote:l});if(p)return ku({progressFs:o,projectRoot:r,provider:u.provider,handlers:p})}}),ticketFetch:c=>dt(c,{fetchTicket:u=>u.fetchTicket({buildLabel:ql(c)}),countReworkCycles:u=>Yn(o,r,u),appendProgress:t,computeTicketBranch:(u,l)=>Me(u,l),computeTargetBranch:(u,l,p)=>er(u,l,p)}),feasibility:c=>st(c,{checkFeasibility:(u,l)=>{let p=Wu(d=>Fl({prompt:d,model:l,spawn:s}),u,l);return Promise.resolve(p)},appendProgress:t})}}function tS(e){let{projectRoot:t,exec:r,lockFs:n,spawn:o}=e;return{branchSetup:s=>et(s,{currentBranch:()=>ht(r),checkout:(i,c)=>oe(r,i,c),fetchRemoteBranch:i=>gt(r,i),ensureBranch:(i,c)=>Jn(r,i,c),ensureEpicBranch:(i,c)=>Yu({exec:r,epicBranch:i,baseBranch:c}),fetchChildrenStatus:i=>s.board.fetchChildrenStatus(i.key,i.issueId),writeLock:i=>Wn(n,t,{...i,pid:process.pid})}),transition:s=>mt(s,{transitionTicket:(i,c)=>s.board.transitionTicket(i,c)}),invoke:gm(o)}}function rS(e){let{projectRoot:t,exec:r,lockFs:n,costFs:o,fetch:s}=e;return{cost:i=>rt(i,{readLock:()=>it(n,t),appendCostEntry:c=>sl(o,t,{...c,now:Date.now()})}),cleanup:i=>tt(i,{notify:(c,u)=>Ul({webhookUrl:c,message:u,fetch:s})}),checkout:i=>oe(r,i),deleteLock:()=>at(n,t),deleteVerifyAttempt:()=>ct(n,t)}}function Wl(e){let t=Yx(e.progressFs,e.projectRoot);return{...Xx(e,t),...eS(e,t),...tS(e),...hm(e,t),...rS(e)}}function nS(e,t,r){let n=il(r.clock()-t),{out:o}=r;switch(e.status){case"completed":o.log(Dl("\u2705 Ticket completed")+ce(` (${n})`));break;case"aborted":o.log(ce(`\u23F9 Pipeline aborted at ${e.phase??"unknown"}`)+ce(` (${n})`));break;case"resumed":o.log(ce("\u21A9 Resumed previous session")+ce(` (${n})`));break;case"dry-run":o.log(ce("\u{1F3C1} Dry run complete")+ce(` (${n})`));break;case"error":o.error(Io("\u274C Clancy stopped")+ce(` (${n})`)),o.error(Io(` ${e.error??"Unknown error"}`));break;default:return e.status}}async function km(e){let t=Kn({projectRoot:e.projectRoot,argv:e.argv,isAfk:e.isAfk,now:e.now}),r=Wl({projectRoot:e.projectRoot,exec:e.exec,lockFs:e.lockFs,progressFs:e.progressFs,costFs:e.costFs,envFs:e.envFs,qualityFs:e.qualityFs,spawn:e.spawn,fetch:e.fetch}),n=await e.runPipeline(t,r),o=e.clock??Date.now;nS(n,t.startTime,{out:e.console,clock:o})}function cS(e,t=_m){return r=>{let n=t("git",[...r],{cwd:e,encoding:"utf8"});if(n.status!==0){let o=r[0]??"unknown",s=n.status??"null",i=n.stderr?.trim(),c=i?`git ${o} failed (exit ${s}): ${i}`:`git ${o} failed (exit ${s})`;throw new Error(c)}return n.stdout.trim()}}function uS(){return{readFile:e=>Co(e,"utf8"),writeFile:(e,t)=>xm(e,t,"utf8"),deleteFile:e=>sS(e),mkdir:e=>Ro(e,{recursive:!0})}}function lS(){return{readFile:e=>Co(e,"utf8"),appendFile:(e,t)=>wm(e,t,"utf8"),mkdir:e=>Ro(e,{recursive:!0})}}function pS(){return{appendFile:(e,t)=>wm(e,t,"utf8"),mkdir:e=>Ro(e,{recursive:!0})}}function fS(){return{readFile:e=>Co(e,"utf8"),writeFile:(e,t)=>xm(e,t,"utf8"),rename:(e,t)=>oS(e,t),mkdir:e=>Ro(e,{recursive:!0})}}function dS(){return{readFile:e=>Co(e,"utf8")}}async function mS(){let e=process.cwd();await km({argv:process.argv,projectRoot:e,isAfk:!1,exec:cS(e),lockFs:uS(),progressFs:lS(),costFs:pS(),envFs:dS(),qualityFs:fS(),spawn:(t,r,n)=>_m(t,[...r],{...n,stdio:[...n.stdio]}),fetch:globalThis.fetch.bind(globalThis),runPipeline:Hn,console})}process.argv[1]&&aS(import.meta.url)===iS(process.argv[1])&&mS().catch(e=>{let t=e instanceof Error?e.message:String(e);console.error(t)});export{pS as makeCostFs,dS as makeEnvFs,cS as makeExecGit,uS as makeLockFs,lS as makeProgressFs,fS as makeQualityFs};
|