@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,255 @@
|
|
|
1
|
+
var qm=Object.defineProperty;var Ae=(e,t)=>{for(var r in t)qm(e,r,{get:t[r],enumerable:!0})};import{spawnSync as QS}from"node:child_process";import{mkdirSync as XS,readFileSync as ev,writeFileSync as tv}from"node:fs";import{resolve as rv}from"node:path";import{setTimeout as nv}from"node:timers/promises";import{fileURLToPath as ov}from"node:url";import{join as Km}from"node:path";var Hm=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},Wm=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=Hm(t.slice(r+1).trim());return[n,o]},Jm=e=>e!==void 0,Bo=e=>{let r=e.split(`
|
|
2
|
+
`).map(Wm).filter(Jm);return Object.fromEntries(r)},zr=(e,t)=>{let r=Km(e,".clancy",".env");try{return Bo(t.readFile(r))}catch{return}};var le=class{#e;get(){return this.#e}store(t){this.#e=t}},Ke=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 Vm(e){try{let t=await e.text();return t?` \u2014 ${t.slice(0,200)}`:""}catch{return""}}function Ym(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: ${Ym(l)}`)});if(!i)return;if(!i.ok){let l=await Vm(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 Q(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 Gm(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 Oo(e,t,r){return Math.min(t*2**e,r)}function Qm(e){return e===429||e>=500&&e<=599}function Xm(e,t,r){if(e.status===429){let n=Gm(e.headers.get("Retry-After")),o=Oo(r,t.baseDelayMs,t.maxDelayMs);return Math.min(n??o,t.maxDelayMs)}return Oo(r,t.baseDelayMs,t.maxDelayMs)}function up(e){return new Promise(t=>setTimeout(t,e))}async function Zo(e,t){try{let r=await fetch(e.url,e.init);if(!Qm(r.status)||t>=e.maxRetries)return r;let n=Xm(r,e,t);return await r.arrayBuffer().catch(()=>{}),await up(n),Zo(e,t+1)}catch(r){if(t>=e.maxRetries)throw r;let n=Oo(t,e.baseDelayMs,e.maxDelayMs);return await up(n),Zo(e,t+1)}}async function Ne(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 C(e,t){try{await e()}catch(r){console.warn(`\u26A0 ${t} failed: ${r instanceof Error?r.message:String(r)}`)}}async function Z(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"]),Tt=new Set(["DONE","PR_CREATED","PUSHED","EPIC_PR_CREATED","RESUMED"]),Ar=new Set(["SKIPPED","PUSH_FAILED","TIME_LIMIT"]);var a={};Ae(a,{$brand:()=>Fo,$input:()=>ka,$output:()=>ya,NEVER:()=>Do,TimePrecision:()=>qa,ZodMiniAny:()=>kf,ZodMiniArray:()=>vf,ZodMiniBase64:()=>uf,ZodMiniBase64URL:()=>lf,ZodMiniBigInt:()=>Gt,ZodMiniBigIntFormat:()=>Gc,ZodMiniBoolean:()=>Yt,ZodMiniCIDRv4:()=>sf,ZodMiniCIDRv6:()=>af,ZodMiniCUID:()=>Qp,ZodMiniCUID2:()=>Xp,ZodMiniCatch:()=>Kf,ZodMiniCodec:()=>ou,ZodMiniCustom:()=>su,ZodMiniCustomStringFormat:()=>Jt,ZodMiniDate:()=>pn,ZodMiniDefault:()=>Mf,ZodMiniDiscriminatedUnion:()=>Pf,ZodMiniE164:()=>pf,ZodMiniEmail:()=>Jp,ZodMiniEmoji:()=>Yp,ZodMiniEnum:()=>eu,ZodMiniExactOptional:()=>Zf,ZodMiniFile:()=>jf,ZodMiniFunction:()=>Xf,ZodMiniGUID:()=>Vp,ZodMiniIPv4:()=>nf,ZodMiniIPv6:()=>of,ZodMiniISODate:()=>hn,ZodMiniISODateTime:()=>mn,ZodMiniISODuration:()=>bn,ZodMiniISOTime:()=>gn,ZodMiniIntersection:()=>Rf,ZodMiniJWT:()=>ff,ZodMiniKSUID:()=>rf,ZodMiniLazy:()=>Vf,ZodMiniLiteral:()=>Lf,ZodMiniMAC:()=>cf,ZodMiniMap:()=>zf,ZodMiniNaN:()=>Hf,ZodMiniNanoID:()=>Gp,ZodMiniNever:()=>wf,ZodMiniNonOptional:()=>ru,ZodMiniNull:()=>bf,ZodMiniNullable:()=>Df,ZodMiniNumber:()=>Vt,ZodMiniNumberFormat:()=>tt,ZodMiniObject:()=>fn,ZodMiniOptional:()=>tu,ZodMiniPipe:()=>nu,ZodMiniPrefault:()=>Uf,ZodMiniPromise:()=>Gf,ZodMiniReadonly:()=>Wf,ZodMiniRecord:()=>dn,ZodMiniSet:()=>Af,ZodMiniString:()=>et,ZodMiniStringFormat:()=>I,ZodMiniSuccess:()=>qf,ZodMiniSymbol:()=>hf,ZodMiniTemplateLiteral:()=>Jf,ZodMiniTransform:()=>Bf,ZodMiniTuple:()=>Cf,ZodMiniType:()=>k,ZodMiniULID:()=>ef,ZodMiniURL:()=>Yc,ZodMiniUUID:()=>Wt,ZodMiniUndefined:()=>gf,ZodMiniUnion:()=>Xc,ZodMiniUnknown:()=>_f,ZodMiniVoid:()=>Sf,ZodMiniXID:()=>tf,ZodMiniXor:()=>If,_default:()=>vy,_function:()=>Uy,any:()=>Yb,array:()=>Qc,base64:()=>zb,base64url:()=>Ab,bigint:()=>Kb,boolean:()=>mf,catch:()=>Ry,catchall:()=>ly,check:()=>Ly,cidrv4:()=>Cb,cidrv6:()=>Tb,clone:()=>N,codec:()=>Ey,coerce:()=>au,config:()=>z,core:()=>Xe,cuid:()=>xb,cuid2:()=>Sb,custom:()=>Qf,date:()=>Qb,decode:()=>us,decodeAsync:()=>ps,describe:()=>Oy,discriminatedUnion:()=>fy,e164:()=>Nb,email:()=>fb,emoji:()=>_b,encode:()=>cs,encodeAsync:()=>ls,endsWith:()=>Nc,enum:()=>Nf,exactOptional:()=>xy,extend:()=>ny,file:()=>_y,flattenError:()=>os,float32:()=>Fb,float64:()=>Mb,formatError:()=>ss,function:()=>Uy,globalRegistry:()=>oe,gt:()=>sn,gte:()=>Ht,guid:()=>db,hash:()=>Zb,hex:()=>Ob,hostname:()=>Bb,httpUrl:()=>kb,includes:()=>zc,instanceof:()=>Dy,int:()=>Db,int32:()=>Ub,int64:()=>Hb,intersection:()=>dy,ipv4:()=>Pb,ipv6:()=>Rb,iso:()=>iu,json:()=>My,jwt:()=>Lb,keyof:()=>Xb,ksuid:()=>Ib,lazy:()=>Yf,length:()=>Rc,literal:()=>ky,locales:()=>qt,looseObject:()=>ry,looseRecord:()=>hy,lowercase:()=>Tc,lt:()=>on,lte:()=>Kt,mac:()=>Eb,map:()=>gy,maxLength:()=>Ic,maxSize:()=>Sc,maximum:()=>Kt,merge:()=>sy,meta:()=>Zy,mime:()=>jc,minLength:()=>Pc,minSize:()=>vc,minimum:()=>Ht,multipleOf:()=>xc,nan:()=>Cy,nanoid:()=>wb,nativeEnum:()=>yy,negative:()=>kc,never:()=>xf,nonnegative:()=>wc,nonoptional:()=>Iy,nonpositive:()=>_c,normalize:()=>Bc,null:()=>yf,nullable:()=>Ff,nullish:()=>Sy,number:()=>df,object:()=>ey,omit:()=>ay,optional:()=>Of,overwrite:()=>ke,parse:()=>be,parseAsync:()=>ye,partial:()=>cy,partialRecord:()=>my,pick:()=>iy,pipe:()=>Ty,positive:()=>yc,prefault:()=>$y,prettifyError:()=>as,promise:()=>Ny,property:()=>Lc,readonly:()=>zy,record:()=>Ef,refine:()=>jy,regex:()=>Cc,regexes:()=>V,registry:()=>rn,required:()=>uy,safeDecode:()=>ds,safeDecodeAsync:()=>hs,safeEncode:()=>fs,safeEncodeAsync:()=>ms,safeExtend:()=>oy,safeParse:()=>Be,safeParseAsync:()=>Oe,set:()=>by,size:()=>$c,startsWith:()=>Ac,strictObject:()=>ty,string:()=>Vc,stringFormat:()=>jb,stringbool:()=>Fy,success:()=>Py,superRefine:()=>By,symbol:()=>Jb,templateLiteral:()=>Ay,toJSONSchema:()=>cn,toLowerCase:()=>Zc,toUpperCase:()=>Dc,transform:()=>wy,treeifyError:()=>is,trim:()=>Oc,tuple:()=>Tf,uint32:()=>qb,uint64:()=>Wb,ulid:()=>vb,undefined:()=>Vb,union:()=>$f,unknown:()=>ln,uppercase:()=>Ec,url:()=>yb,util:()=>J,uuid:()=>mb,uuidv4:()=>hb,uuidv6:()=>gb,uuidv7:()=>bb,void:()=>Gb,xid:()=>$b,xor:()=>py});var Xe={};Ae(Xe,{$ZodAny:()=>Fi,$ZodArray:()=>Hi,$ZodAsyncError:()=>X,$ZodBase64:()=>Ei,$ZodBase64URL:()=>zi,$ZodBigInt:()=>Gr,$ZodBigIntFormat:()=>Bi,$ZodBoolean:()=>Ft,$ZodCIDRv4:()=>Ri,$ZodCIDRv6:()=>Ci,$ZodCUID:()=>gi,$ZodCUID2:()=>bi,$ZodCatch:()=>ua,$ZodCheck:()=>$,$ZodCheckBigIntFormat:()=>Hs,$ZodCheckEndsWith:()=>oi,$ZodCheckGreaterThan:()=>qr,$ZodCheckIncludes:()=>ri,$ZodCheckLengthEquals:()=>Qs,$ZodCheckLessThan:()=>Ur,$ZodCheckLowerCase:()=>ei,$ZodCheckMaxLength:()=>Ys,$ZodCheckMaxSize:()=>Ws,$ZodCheckMimeType:()=>ii,$ZodCheckMinLength:()=>Gs,$ZodCheckMinSize:()=>Js,$ZodCheckMultipleOf:()=>qs,$ZodCheckNumberFormat:()=>Ks,$ZodCheckOverwrite:()=>ai,$ZodCheckProperty:()=>si,$ZodCheckRegex:()=>Xs,$ZodCheckSizeEquals:()=>Vs,$ZodCheckStartsWith:()=>ni,$ZodCheckStringFormat:()=>Ye,$ZodCheckUpperCase:()=>ti,$ZodCodec:()=>Ut,$ZodCustom:()=>ba,$ZodCustomStringFormat:()=>Li,$ZodDate:()=>Ki,$ZodDefault:()=>sa,$ZodDiscriminatedUnion:()=>Ji,$ZodE164:()=>Ai,$ZodEmail:()=>fi,$ZodEmoji:()=>mi,$ZodEncodeError:()=>He,$ZodEnum:()=>Xi,$ZodError:()=>ns,$ZodExactOptional:()=>na,$ZodFile:()=>ta,$ZodFunction:()=>ma,$ZodGUID:()=>li,$ZodIPv4:()=>$i,$ZodIPv6:()=>Ii,$ZodISODate:()=>xi,$ZodISODateTime:()=>wi,$ZodISODuration:()=>vi,$ZodISOTime:()=>Si,$ZodIntersection:()=>Vi,$ZodJWT:()=>Ni,$ZodKSUID:()=>_i,$ZodLazy:()=>ga,$ZodLiteral:()=>ea,$ZodMAC:()=>Pi,$ZodMap:()=>Gi,$ZodNaN:()=>la,$ZodNanoID:()=>hi,$ZodNever:()=>Ui,$ZodNonOptional:()=>aa,$ZodNull:()=>Di,$ZodNullable:()=>oa,$ZodNumber:()=>Yr,$ZodNumberFormat:()=>ji,$ZodObject:()=>Qr,$ZodObjectJIT:()=>Vh,$ZodOptional:()=>en,$ZodPipe:()=>pa,$ZodPrefault:()=>ia,$ZodPromise:()=>ha,$ZodReadonly:()=>fa,$ZodRealError:()=>F,$ZodRecord:()=>Yi,$ZodRegistry:()=>tn,$ZodSet:()=>Qi,$ZodString:()=>Ge,$ZodStringFormat:()=>v,$ZodSuccess:()=>ca,$ZodSymbol:()=>Oi,$ZodTemplateLiteral:()=>da,$ZodTransform:()=>ra,$ZodTuple:()=>Xr,$ZodType:()=>b,$ZodULID:()=>yi,$ZodURL:()=>di,$ZodUUID:()=>pi,$ZodUndefined:()=>Zi,$ZodUnion:()=>Mt,$ZodUnknown:()=>Mi,$ZodVoid:()=>qi,$ZodXID:()=>ki,$ZodXor:()=>Wi,$brand:()=>Fo,$constructor:()=>f,$input:()=>ka,$output:()=>ya,Doc:()=>Dt,JSONSchema:()=>Wp,JSONSchemaGenerator:()=>un,NEVER:()=>Do,TimePrecision:()=>qa,_any:()=>pc,_array:()=>eg,_base64:()=>Da,_base64url:()=>Fa,_bigint:()=>oc,_boolean:()=>rc,_catch:()=>yg,_check:()=>Hp,_cidrv4:()=>Oa,_cidrv6:()=>Za,_coercedBigint:()=>sc,_coercedBoolean:()=>nc,_coercedDate:()=>gc,_coercedNumber:()=>Ya,_coercedString:()=>wa,_cuid:()=>Ta,_cuid2:()=>Ea,_custom:()=>Mc,_date:()=>hc,_decode:()=>bp,_decodeAsync:()=>kp,_default:()=>hg,_discriminatedUnion:()=>ng,_e164:()=>Ma,_email:()=>xa,_emoji:()=>Ra,_encode:()=>gp,_encodeAsync:()=>yp,_endsWith:()=>Nc,_enum:()=>ug,_file:()=>Fc,_float32:()=>Qa,_float64:()=>Xa,_gt:()=>sn,_gte:()=>Ht,_guid:()=>Sa,_includes:()=>zc,_int:()=>Ga,_int32:()=>ec,_int64:()=>ic,_intersection:()=>og,_ipv4:()=>La,_ipv6:()=>ja,_isoDate:()=>Ha,_isoDateTime:()=>Ka,_isoDuration:()=>Ja,_isoTime:()=>Wa,_jwt:()=>Ua,_ksuid:()=>Na,_lazy:()=>xg,_length:()=>Rc,_literal:()=>pg,_lowercase:()=>Tc,_lt:()=>on,_lte:()=>Kt,_mac:()=>Ba,_map:()=>ag,_max:()=>Kt,_maxLength:()=>Ic,_maxSize:()=>Sc,_mime:()=>jc,_min:()=>Ht,_minLength:()=>Pc,_minSize:()=>vc,_multipleOf:()=>xc,_nan:()=>bc,_nanoid:()=>Ca,_nativeEnum:()=>lg,_negative:()=>kc,_never:()=>dc,_nonnegative:()=>wc,_nonoptional:()=>gg,_nonpositive:()=>_c,_normalize:()=>Bc,_null:()=>lc,_nullable:()=>mg,_number:()=>Va,_optional:()=>dg,_overwrite:()=>ke,_parse:()=>Br,_parseAsync:()=>Or,_pipe:()=>kg,_positive:()=>yc,_promise:()=>Sg,_property:()=>Lc,_readonly:()=>_g,_record:()=>ig,_refine:()=>Uc,_regex:()=>Cc,_safeDecode:()=>wp,_safeDecodeAsync:()=>Sp,_safeEncode:()=>_p,_safeEncodeAsync:()=>xp,_safeParse:()=>Zr,_safeParseAsync:()=>Dr,_set:()=>cg,_size:()=>$c,_slugify:()=>Xh,_startsWith:()=>Ac,_string:()=>_a,_stringFormat:()=>Qe,_stringbool:()=>Wc,_success:()=>bg,_superRefine:()=>qc,_symbol:()=>cc,_templateLiteral:()=>wg,_toLowerCase:()=>Zc,_toUpperCase:()=>Dc,_transform:()=>fg,_trim:()=>Oc,_tuple:()=>sg,_uint32:()=>tc,_uint64:()=>ac,_ulid:()=>za,_undefined:()=>uc,_union:()=>tg,_unknown:()=>fc,_uppercase:()=>Ec,_url:()=>nn,_uuid:()=>va,_uuidv4:()=>$a,_uuidv6:()=>Ia,_uuidv7:()=>Pa,_void:()=>mc,_xid:()=>Aa,_xor:()=>rg,clone:()=>N,config:()=>z,createStandardJSONSchemaMethod:()=>Jc,createToJSONSchemaMethod:()=>vg,decode:()=>us,decodeAsync:()=>ps,describe:()=>Kc,encode:()=>cs,encodeAsync:()=>ls,extractDefs:()=>we,finalize:()=>xe,flattenError:()=>os,formatError:()=>ss,globalConfig:()=>Et,globalRegistry:()=>oe,initializeContext:()=>_e,isValidBase64:()=>Ti,isValidBase64URL:()=>Fp,isValidJWT:()=>Mp,locales:()=>qt,meta:()=>Hc,parse:()=>be,parseAsync:()=>ye,prettifyError:()=>as,process:()=>x,regexes:()=>V,registry:()=>rn,safeDecode:()=>ds,safeDecodeAsync:()=>hs,safeEncode:()=>fs,safeEncodeAsync:()=>ms,safeParse:()=>Be,safeParseAsync:()=>Oe,toDotPath:()=>hp,toJSONSchema:()=>cn,treeifyError:()=>is,util:()=>J,version:()=>ci});var Do=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 Fo=Symbol("zod_brand"),X=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},He=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}},Et={};function z(e){return e&&Object.assign(Et,e),Et}var J={};Ae(J,{BIGINT_FORMAT_RANGES:()=>Go,Class:()=>Uo,NUMBER_FORMAT_RANGES:()=>Yo,aborted:()=>ge,allowsEval:()=>Wo,assert:()=>oh,assertEqual:()=>eh,assertIs:()=>rh,assertNever:()=>nh,assertNotEqual:()=>th,assignProp:()=>me,base64ToUint8Array:()=>fp,base64urlToUint8Array:()=>bh,cached:()=>We,captureStackTrace:()=>Lr,cleanEnum:()=>gh,cleanRegex:()=>Nt,clone:()=>N,cloneDef:()=>ah,createTransparentProxy:()=>dh,defineLazy:()=>y,esc:()=>Nr,escapeRegex:()=>W,extend:()=>jr,finalizeIssue:()=>D,floatSafeRemainder:()=>Ko,getElementAtPath:()=>ch,getEnumValues:()=>At,getLengthableOrigin:()=>Bt,getParsedType:()=>fh,getSizableOrigin:()=>jt,hexToUint8Array:()=>kh,isObject:()=>je,isPlainObject:()=>he,issue:()=>Ve,joinValues:()=>sh,jsonStringifyReplacer:()=>qo,merge:()=>mh,mergeDefs:()=>pe,normalizeParams:()=>m,nullish:()=>de,numKeys:()=>ph,objectClone:()=>ih,omit:()=>Xo,optionalKeys:()=>Vo,parsedType:()=>hh,partial:()=>ts,pick:()=>Qo,prefixIssues:()=>q,primitiveTypes:()=>Jo,promiseAllObject:()=>uh,propertyKeyTypes:()=>Lt,randomString:()=>lh,required:()=>rs,safeExtend:()=>es,shallowClone:()=>Je,slugify:()=>Ho,stringifyPrimitive:()=>pp,uint8ArrayToBase64:()=>dp,uint8ArrayToBase64url:()=>yh,uint8ArrayToHex:()=>_h,unwrapMessage:()=>zt});function eh(e){return e}function th(e){return e}function rh(e){}function nh(e){throw new Error("Unexpected value in exhaustive check")}function oh(e){}function At(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 sh(e,t="|"){return e.map(r=>pp(r)).join(t)}function qo(e,t){return typeof t=="bigint"?t.toString():t}function We(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function de(e){return e==null}function Nt(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Ko(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 lp=Symbol("evaluating");function y(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==lp)return n===void 0&&(n=lp,n=r()),n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function ih(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function me(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function pe(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function ah(e){return pe(e._zod.def)}function ch(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function uh(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 lh(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function Nr(e){return JSON.stringify(e)}function Ho(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Lr="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function je(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Wo=We(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function he(e){if(je(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(je(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Je(e){return he(e)?{...e}:Array.isArray(e)?[...e]:e}function ph(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var fh=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}`)}},Lt=new Set(["string","number","symbol"]),Jo=new Set(["string","number","bigint","boolean","symbol","undefined"]);function W(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function N(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 dh(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 pp(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Vo(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Yo={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]},Go={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Qo(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=pe(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 me(this,"shape",i),i},checks:[]});return N(e,s)}function Xo(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=pe(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 me(this,"shape",i),i},checks:[]});return N(e,s)}function jr(e,t){if(!he(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=pe(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return me(this,"shape",s),s}});return N(e,o)}function es(e,t){if(!he(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=pe(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return me(this,"shape",n),n}});return N(e,r)}function mh(e,t){let r=pe(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return me(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return N(e,r)}function ts(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=pe(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 me(this,"shape",u),u},checks:[]});return N(t,i)}function rs(e,t,r){let n=pe(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 me(this,"shape",s),s}});return N(t,n)}function ge(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 q(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function zt(e){return typeof e=="string"?e:e?.message}function D(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=zt(e.inst?._zod.def?.error?.(e))??zt(t?.error?.(e))??zt(r.customError?.(e))??zt(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function jt(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Bt(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function hh(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 Ve(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function gh(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function fp(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 dp(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function bh(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return fp(t+r)}function yh(e){return dp(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function kh(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 _h(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var Uo=class{constructor(...t){}};var mp=(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,qo,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ns=f("$ZodError",mp),F=f("$ZodError",mp,{Parent:Error});function os(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 ss(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 is(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],g=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]),g&&p.errors.push(t(u)),d++}}};return n(e),r}function hp(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 as(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 ${hp(n.path)}`);return t.join(`
|
|
3
|
+
`)}var Br=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 X;if(i.issues.length){let c=new(o?.Err??e)(i.issues.map(u=>D(u,s,z())));throw Lr(c,o?.callee),c}return i.value},be=Br(F),Or=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=>D(u,s,z())));throw Lr(c,o?.callee),c}return i.value},ye=Or(F),Zr=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 X;return s.issues.length?{success:!1,error:new(e??ns)(s.issues.map(i=>D(i,o,z())))}:{success:!0,data:s.value}},Be=Zr(F),Dr=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=>D(i,o,z())))}:{success:!0,data:s.value}},Oe=Dr(F),gp=e=>(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Br(e)(t,r,o)},cs=gp(F),bp=e=>(t,r,n)=>Br(e)(t,r,n),us=bp(F),yp=e=>async(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Or(e)(t,r,o)},ls=yp(F),kp=e=>async(t,r,n)=>Or(e)(t,r,n),ps=kp(F),_p=e=>(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Zr(e)(t,r,o)},fs=_p(F),wp=e=>(t,r,n)=>Zr(e)(t,r,n),ds=wp(F),xp=e=>async(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Dr(e)(t,r,o)},ms=xp(F),Sp=e=>async(t,r,n)=>Dr(e)(t,r,n),hs=Sp(F);var V={};Ae(V,{base64:()=>Es,base64url:()=>Fr,bigint:()=>Bs,boolean:()=>Zs,browserEmail:()=>Ch,cidrv4:()=>Cs,cidrv6:()=>Ts,cuid:()=>gs,cuid2:()=>bs,date:()=>As,datetime:()=>Ls,domain:()=>zh,duration:()=>xs,e164:()=>zs,email:()=>vs,emoji:()=>$s,extendedDuration:()=>xh,guid:()=>Ss,hex:()=>Ah,hostname:()=>Eh,html5Email:()=>Ih,idnEmail:()=>Rh,integer:()=>Os,ipv4:()=>Is,ipv6:()=>Ps,ksuid:()=>_s,lowercase:()=>Ms,mac:()=>Rs,md5_base64:()=>Lh,md5_base64url:()=>jh,md5_hex:()=>Nh,nanoid:()=>ws,null:()=>Ds,number:()=>Mr,rfc5322Email:()=>Ph,sha1_base64:()=>Oh,sha1_base64url:()=>Zh,sha1_hex:()=>Bh,sha256_base64:()=>Fh,sha256_base64url:()=>Mh,sha256_hex:()=>Dh,sha384_base64:()=>qh,sha384_base64url:()=>Kh,sha384_hex:()=>Uh,sha512_base64:()=>Wh,sha512_base64url:()=>Jh,sha512_hex:()=>Hh,string:()=>js,time:()=>Ns,ulid:()=>ys,undefined:()=>Fs,unicodeEmail:()=>vp,uppercase:()=>Us,uuid:()=>Ze,uuid4:()=>Sh,uuid6:()=>vh,uuid7:()=>$h,xid:()=>ks});var gs=/^[cC][^\s-]{8,}$/,bs=/^[0-9a-z]+$/,ys=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ks=/^[0-9a-vA-V]{20}$/,_s=/^[A-Za-z0-9]{27}$/,ws=/^[a-zA-Z0-9_-]{21}$/,xs=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,xh=/^[-+]?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)?)??$/,Ss=/^([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})$/,Ze=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)$/,Sh=Ze(4),vh=Ze(6),$h=Ze(7),vs=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Ih=/^[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])?)*$/,Ph=/^(([^<>()\[\]\\.,;:\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,}))$/,vp=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Rh=vp,Ch=/^[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])?)*$/,Th="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function $s(){return new RegExp(Th,"u")}var Is=/^(?:(?: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])$/,Ps=/^(([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}|:))$/,Rs=e=>{let t=W(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},Cs=/^((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])$/,Ts=/^(([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])$/,Es=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Fr=/^[A-Za-z0-9_-]*$/,Eh=/^(?=.{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])?)*\.?$/,zh=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,zs=/^\+[1-9]\d{6,14}$/,$p="(?:(?:\\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])))",As=new RegExp(`^${$p}$`);function Ip(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 Ns(e){return new RegExp(`^${Ip(e)}$`)}function Ls(e){let t=Ip({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(`^${$p}T(?:${n})$`)}var js=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Bs=/^-?\d+n?$/,Os=/^-?\d+$/,Mr=/^-?\d+(?:\.\d+)?$/,Zs=/^(?:true|false)$/i,Ds=/^null$/i;var Fs=/^undefined$/i;var Ms=/^[^A-Z]*$/,Us=/^[^a-z]*$/,Ah=/^[0-9a-fA-F]*$/;function Ot(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function Zt(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var Nh=/^[0-9a-fA-F]{32}$/,Lh=Ot(22,"=="),jh=Zt(22),Bh=/^[0-9a-fA-F]{40}$/,Oh=Ot(27,"="),Zh=Zt(27),Dh=/^[0-9a-fA-F]{64}$/,Fh=Ot(43,"="),Mh=Zt(43),Uh=/^[0-9a-fA-F]{96}$/,qh=Ot(64,""),Kh=Zt(64),Hh=/^[0-9a-fA-F]{128}$/,Wh=Ot(86,"=="),Jh=Zt(86);var $=f("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Rp={number:"number",bigint:"bigint",object:"date"},Ur=f("$ZodCheckLessThan",(e,t)=>{$.init(e,t);let r=Rp[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})}}),qr=f("$ZodCheckGreaterThan",(e,t)=>{$.init(e,t);let r=Rp[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})}}),qs=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):Ko(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})}}),Ks=f("$ZodCheckNumberFormat",(e,t)=>{$.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,s]=Yo[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=Os)}),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})}}),Hs=f("$ZodCheckBigIntFormat",(e,t)=>{$.init(e,t);let[r,n]=Go[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})}}),Ws=f("$ZodCheckMaxSize",(e,t)=>{var r;$.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!de(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:jt(o),code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Js=f("$ZodCheckMinSize",(e,t)=>{var r;$.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!de(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:jt(o),code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Vs=f("$ZodCheckSizeEquals",(e,t)=>{var r;$.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!de(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:jt(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})}}),Ys=f("$ZodCheckMaxLength",(e,t)=>{var r;$.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!de(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=Bt(o);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Gs=f("$ZodCheckMinLength",(e,t)=>{var r;$.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!de(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=Bt(o);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Qs=f("$ZodCheckLengthEquals",(e,t)=>{var r;$.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!de(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=Bt(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})}}),Ye=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=()=>{})}),Xs=f("$ZodCheckRegex",(e,t)=>{Ye.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})}}),ei=f("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ms),Ye.init(e,t)}),ti=f("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Us),Ye.init(e,t)}),ri=f("$ZodCheckIncludes",(e,t)=>{$.init(e,t);let r=W(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})}}),ni=f("$ZodCheckStartsWith",(e,t)=>{$.init(e,t);let r=new RegExp(`^${W(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})}}),oi=f("$ZodCheckEndsWith",(e,t)=>{$.init(e,t);let r=new RegExp(`.*${W(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 Pp(e,t,r){e.issues.length&&t.issues.push(...q(r,e.issues))}var si=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=>Pp(o,r,t.property));Pp(n,r,t.property)}}),ii=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})}}),ai=f("$ZodCheckOverwrite",(e,t)=>{$.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Dt=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 ci={major:4,minor:3,patch:6};var b=f("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ci;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=ge(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,g=d._zod.check(i);if(g instanceof Promise&&u?.async===!1)throw new X;if(p||g instanceof Promise)p=(p??Promise.resolve()).then(async()=>{await g,i.issues.length!==h&&(l||(l=ge(i,h)))});else{if(i.issues.length===h)continue;l||(l=ge(i,h))}}return p?p.then(()=>i):i},s=(i,c,u)=>{if(ge(i))return i.aborted=!0,i;let l=o(c,n,u);if(l instanceof Promise){if(u.async===!1)throw new X;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 X;return u.then(l=>o(l,n,c))}return o(u,n,c)}}y(e,"~standard",()=>({validate:o=>{try{let s=Be(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Oe(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),Ge=f("$ZodString",(e,t)=>{b.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??js(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)=>{Ye.init(e,t),Ge.init(e,t)}),li=f("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Ss),v.init(e,t)}),pi=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=Ze(n))}else t.pattern??(t.pattern=Ze());v.init(e,t)}),fi=f("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=vs),v.init(e,t)}),di=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})}}}),mi=f("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=$s()),v.init(e,t)}),hi=f("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=ws),v.init(e,t)}),gi=f("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=gs),v.init(e,t)}),bi=f("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=bs),v.init(e,t)}),yi=f("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ys),v.init(e,t)}),ki=f("$ZodXID",(e,t)=>{t.pattern??(t.pattern=ks),v.init(e,t)}),_i=f("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=_s),v.init(e,t)}),wi=f("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Ls(t)),v.init(e,t)}),xi=f("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=As),v.init(e,t)}),Si=f("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Ns(t)),v.init(e,t)}),vi=f("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=xs),v.init(e,t)}),$i=f("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Is),v.init(e,t),e._zod.bag.format="ipv4"}),Ii=f("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Ps),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})}}}),Pi=f("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=Rs(t.delimiter)),v.init(e,t),e._zod.bag.format="mac"}),Ri=f("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Cs),v.init(e,t)}),Ci=f("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Ts),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 Ti(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Ei=f("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Es),v.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{Ti(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function Fp(e){if(!Fr.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Ti(r)}var zi=f("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Fr),v.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{Fp(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Ai=f("$ZodE164",(e,t)=>{t.pattern??(t.pattern=zs),v.init(e,t)});function Mp(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 Ni=f("$ZodJWT",(e,t)=>{v.init(e,t),e._zod.check=r=>{Mp(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Li=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})}}),Yr=f("$ZodNumber",(e,t)=>{b.init(e,t),e._zod.pattern=e._zod.bag.pattern??Mr,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}}),ji=f("$ZodNumberFormat",(e,t)=>{Ks.init(e,t),Yr.init(e,t)}),Ft=f("$ZodBoolean",(e,t)=>{b.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}}),Gr=f("$ZodBigInt",(e,t)=>{b.init(e,t),e._zod.pattern=Bs,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}}),Bi=f("$ZodBigIntFormat",(e,t)=>{Hs.init(e,t),Gr.init(e,t)}),Oi=f("$ZodSymbol",(e,t)=>{b.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)=>{b.init(e,t),e._zod.pattern=Fs,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}}),Di=f("$ZodNull",(e,t)=>{b.init(e,t),e._zod.pattern=Ds,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}}),Fi=f("$ZodAny",(e,t)=>{b.init(e,t),e._zod.parse=r=>r}),Mi=f("$ZodUnknown",(e,t)=>{b.init(e,t),e._zod.parse=r=>r}),Ui=f("$ZodNever",(e,t)=>{b.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)}),qi=f("$ZodVoid",(e,t)=>{b.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}}),Ki=f("$ZodDate",(e,t)=>{b.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 Tp(e,t,r){e.issues.length&&t.issues.push(...q(r,e.issues)),t.value[r]=e.value}var Hi=f("$ZodArray",(e,t)=>{b.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=>Tp(l,r,i))):Tp(u,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function Vr(e,t,r,n,o){if(e.issues.length){if(o&&!(r in n))return;t.issues.push(...q(r,e.issues))}e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}function Up(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=Vo(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function qp(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(g=>Vr(g,r,d,t,p))):Vr(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(b.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=We(()=>Up(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=je,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 g=d[h],_=g._zod.optout==="optional",w=g._zod.run({value:l[h],issues:[]},u);w instanceof Promise?p.push(w.then(R=>Vr(R,c,h,l,_))):Vr(w,c,h,l,_)}return s?qp(p,l,c,u,n.value,e):p.length?Promise.all(p).then(()=>c):c}}),Vh=f("$ZodObjectJIT",(e,t)=>{Qr.init(e,t);let r=e._zod.parse,n=We(()=>Up(t)),o=h=>{let g=new Dt(["shape","payload","ctx"]),_=n.value,w=ne=>{let O=Nr(ne);return`shape[${O}]._zod.run({ value: input[${O}], issues: [] }, ctx)`};g.write("const input = payload.value;");let R=Object.create(null),ze=0;for(let ne of _.keys)R[ne]=`key_${ze++}`;g.write("const newResult = {};");for(let ne of _.keys){let O=R[ne],G=Nr(ne),Um=h[ne]?._zod?.optout==="optional";g.write(`const ${O} = ${w(ne)};`),Um?g.write(`
|
|
6
|
+
if (${O}.issues.length) {
|
|
7
|
+
if (${G} in input) {
|
|
8
|
+
payload.issues = payload.issues.concat(${O}.issues.map(iss => ({
|
|
9
|
+
...iss,
|
|
10
|
+
path: iss.path ? [${G}, ...iss.path] : [${G}]
|
|
11
|
+
})));
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
if (${O}.value === undefined) {
|
|
16
|
+
if (${G} in input) {
|
|
17
|
+
newResult[${G}] = undefined;
|
|
18
|
+
}
|
|
19
|
+
} else {
|
|
20
|
+
newResult[${G}] = ${O}.value;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
`):g.write(`
|
|
24
|
+
if (${O}.issues.length) {
|
|
25
|
+
payload.issues = payload.issues.concat(${O}.issues.map(iss => ({
|
|
26
|
+
...iss,
|
|
27
|
+
path: iss.path ? [${G}, ...iss.path] : [${G}]
|
|
28
|
+
})));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (${O}.value === undefined) {
|
|
32
|
+
if (${G} in input) {
|
|
33
|
+
newResult[${G}] = undefined;
|
|
34
|
+
}
|
|
35
|
+
} else {
|
|
36
|
+
newResult[${G}] = ${O}.value;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
`)}g.write("payload.value = newResult;"),g.write("return payload;");let Mm=g.compile();return(ne,O)=>Mm(h,ne,O)},s,i=je,c=!Et.jitless,l=c&&Wo.value,p=t.catchall,d;e._zod.parse=(h,g)=>{d??(d=n.value);let _=h.value;return i(_)?c&&l&&g?.async===!1&&g.jitless!==!0?(s||(s=o(t.shape)),h=s(h,g),p?qp([],_,h,g,d,e):h):r(h,g):(h.issues.push({expected:"object",code:"invalid_type",input:_,inst:e}),h)}});function Ep(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=>!ge(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=>D(i,n,z())))}),t)}var Mt=f("$ZodUnion",(e,t)=>{b.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=>Nt(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=>Ep(u,o,e,s)):Ep(c,o,e,s)}});function zp(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=>D(i,n,z())))}):t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:[],inclusive:!1}),t)}var Wi=f("$ZodXor",(e,t)=>{Mt.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=>zp(u,o,e,s)):zp(c,o,e,s)}}),Ji=f("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Mt.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=We(()=>{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(!je(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)}}),Vi=f("$ZodIntersection",(e,t)=>{b.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])=>Ap(r,u,l)):Ap(r,s,i)}});function ui(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(he(e)&&he(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=ui(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=ui(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 Ap(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}),ge(e))return e;let i=ui(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 Xr=f("$ZodTuple",(e,t)=>{b.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=>Kr(h,n,l))):Kr(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(g=>Kr(g,n,l))):Kr(h,n,l)}}return i.length?Promise.all(i).then(()=>n):n}});function Kr(e,t,r){e.issues.length&&t.issues.push(...q(r,e.issues)),t.value[r]=e.value}var Yi=f("$ZodRecord",(e,t)=>{b.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!he(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(...q(l,d.issues)),r.value[l]=d.value})):(p.issues.length&&r.issues.push(...q(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"&&Mr.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=>D(d,n,z())),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(...q(c,d.issues)),r.value[u.value]=d.value})):(p.issues.length&&r.issues.push(...q(c,p.issues)),r.value[u.value]=p.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Gi=f("$ZodMap",(e,t)=>{b.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])=>{Np(p,d,r,i,o,e,n)})):Np(u,l,r,i,o,e,n)}return s.length?Promise.all(s).then(()=>r):r}});function Np(e,t,r,n,o,s,i){e.issues.length&&(Lt.has(typeof n)?r.issues.push(...q(n,e.issues)):r.issues.push({code:"invalid_key",origin:"map",input:o,inst:s,issues:e.issues.map(c=>D(c,i,z()))})),t.issues.length&&(Lt.has(typeof n)?r.issues.push(...q(n,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:o,inst:s,key:n,issues:t.issues.map(c=>D(c,i,z()))})),r.value.set(e.value,t.value)}var Qi=f("$ZodSet",(e,t)=>{b.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=>Lp(u,r))):Lp(c,r)}return s.length?Promise.all(s).then(()=>r):r}});function Lp(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}var Xi=f("$ZodEnum",(e,t)=>{b.init(e,t);let r=At(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(o=>Lt.has(typeof o)).map(o=>typeof o=="string"?W(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}}),ea=f("$ZodLiteral",(e,t)=>{if(b.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"?W(n):n?W(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}}),ta=f("$ZodFile",(e,t)=>{b.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}}),ra=f("$ZodTransform",(e,t)=>{b.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new He(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 X;return r.value=o,r}});function jp(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var en=f("$ZodOptional",(e,t)=>{b.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(`^(${Nt(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=>jp(s,r.value)):jp(o,r.value)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),na=f("$ZodExactOptional",(e,t)=>{en.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)}),oa=f("$ZodNullable",(e,t)=>{b.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(`^(${Nt(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)}),sa=f("$ZodDefault",(e,t)=>{b.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=>Bp(s,t)):Bp(o,t)}});function Bp(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var ia=f("$ZodPrefault",(e,t)=>{b.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))}),aa=f("$ZodNonOptional",(e,t)=>{b.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=>Op(s,e)):Op(o,e)}});function Op(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 ca=f("$ZodSuccess",(e,t)=>{b.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new He("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)}}),ua=f("$ZodCatch",(e,t)=>{b.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=>D(i,n,z()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>D(s,n,z()))},input:r.value}),r.issues=[]),r)}}),la=f("$ZodNaN",(e,t)=>{b.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)}),pa=f("$ZodPipe",(e,t)=>{b.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=>Hr(i,t.in,n)):Hr(s,t.in,n)}let o=t.in._zod.run(r,n);return o instanceof Promise?o.then(s=>Hr(s,t.out,n)):Hr(o,t.out,n)}});function Hr(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}var Ut=f("$ZodCodec",(e,t)=>{b.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=>Wr(i,t,n)):Wr(s,t,n)}else{let s=t.out._zod.run(r,n);return s instanceof Promise?s.then(i=>Wr(i,t,n)):Wr(s,t,n)}}});function Wr(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=>Jr(e,s,t.out,r)):Jr(e,o,t.out,r)}else{let o=t.reverseTransform(e.value,e);return o instanceof Promise?o.then(s=>Jr(e,s,t.in,r)):Jr(e,o,t.in,r)}}function Jr(e,t,r,n){return e.issues.length?(e.aborted=!0,e):r._zod.run({value:t,issues:e.issues},n)}var fa=f("$ZodReadonly",(e,t)=>{b.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(Zp):Zp(o)}});function Zp(e){return e.value=Object.freeze(e.value),e}var da=f("$ZodTemplateLiteral",(e,t)=>{b.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||Jo.has(typeof n))r.push(W(`${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)}),ma=f("$ZodFunction",(e,t)=>(b.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 ye(e._def.input,n):n,s=await Reflect.apply(r,this,o);return e._def.output?await ye(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 Xr({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)),ha=f("$ZodPromise",(e,t)=>{b.init(e,t),e._zod.parse=(r,n)=>Promise.resolve(r.value).then(o=>t.innerType._zod.run({value:o,issues:[]},n))}),ga=f("$ZodLazy",(e,t)=>{b.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)}),ba=f("$ZodCustom",(e,t)=>{$.init(e,t),b.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=>Dp(s,r,n,e));Dp(o,r,n,e)}});function Dp(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(Ve(o))}}var qt={};Ae(qt,{default:()=>Gh});var Gh={};var Kp,ya=Symbol("ZodOutput"),ka=Symbol("ZodInput"),tn=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 rn(){return new tn}(Kp=globalThis).__zod_globalRegistry??(Kp.__zod_globalRegistry=rn());var oe=globalThis.__zod_globalRegistry;function _a(e,t){return new e({type:"string",...m(t)})}function wa(e,t){return new e({type:"string",coerce:!0,...m(t)})}function xa(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...m(t)})}function Sa(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...m(t)})}function va(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...m(t)})}function $a(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...m(t)})}function Ia(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...m(t)})}function Pa(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...m(t)})}function nn(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...m(t)})}function Ra(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...m(t)})}function Ca(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...m(t)})}function Ta(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...m(t)})}function Ea(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...m(t)})}function za(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...m(t)})}function Aa(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...m(t)})}function Na(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...m(t)})}function La(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...m(t)})}function ja(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...m(t)})}function Ba(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...m(t)})}function Oa(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 Da(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...m(t)})}function Fa(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...m(t)})}function Ma(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...m(t)})}function Ua(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...m(t)})}var qa={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function Ka(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...m(t)})}function Ha(e,t){return new e({type:"string",format:"date",check:"string_format",...m(t)})}function Wa(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...m(t)})}function Ja(e,t){return new e({type:"string",format:"duration",check:"string_format",...m(t)})}function Va(e,t){return new e({type:"number",checks:[],...m(t)})}function Ya(e,t){return new e({type:"number",coerce:!0,checks:[],...m(t)})}function Ga(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...m(t)})}function Qa(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...m(t)})}function Xa(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...m(t)})}function ec(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...m(t)})}function tc(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...m(t)})}function rc(e,t){return new e({type:"boolean",...m(t)})}function nc(e,t){return new e({type:"boolean",coerce:!0,...m(t)})}function oc(e,t){return new e({type:"bigint",...m(t)})}function sc(e,t){return new e({type:"bigint",coerce:!0,...m(t)})}function ic(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...m(t)})}function ac(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...m(t)})}function cc(e,t){return new e({type:"symbol",...m(t)})}function uc(e,t){return new e({type:"undefined",...m(t)})}function lc(e,t){return new e({type:"null",...m(t)})}function pc(e){return new e({type:"any"})}function fc(e){return new e({type:"unknown"})}function dc(e,t){return new e({type:"never",...m(t)})}function mc(e,t){return new e({type:"void",...m(t)})}function hc(e,t){return new e({type:"date",...m(t)})}function gc(e,t){return new e({type:"date",coerce:!0,...m(t)})}function bc(e,t){return new e({type:"nan",...m(t)})}function on(e,t){return new Ur({check:"less_than",...m(t),value:e,inclusive:!1})}function Kt(e,t){return new Ur({check:"less_than",...m(t),value:e,inclusive:!0})}function sn(e,t){return new qr({check:"greater_than",...m(t),value:e,inclusive:!1})}function Ht(e,t){return new qr({check:"greater_than",...m(t),value:e,inclusive:!0})}function yc(e){return sn(0,e)}function kc(e){return on(0,e)}function _c(e){return Kt(0,e)}function wc(e){return Ht(0,e)}function xc(e,t){return new qs({check:"multiple_of",...m(t),value:e})}function Sc(e,t){return new Ws({check:"max_size",...m(t),maximum:e})}function vc(e,t){return new Js({check:"min_size",...m(t),minimum:e})}function $c(e,t){return new Vs({check:"size_equals",...m(t),size:e})}function Ic(e,t){return new Ys({check:"max_length",...m(t),maximum:e})}function Pc(e,t){return new Gs({check:"min_length",...m(t),minimum:e})}function Rc(e,t){return new Qs({check:"length_equals",...m(t),length:e})}function Cc(e,t){return new Xs({check:"string_format",format:"regex",...m(t),pattern:e})}function Tc(e){return new ei({check:"string_format",format:"lowercase",...m(e)})}function Ec(e){return new ti({check:"string_format",format:"uppercase",...m(e)})}function zc(e,t){return new ri({check:"string_format",format:"includes",...m(t),includes:e})}function Ac(e,t){return new ni({check:"string_format",format:"starts_with",...m(t),prefix:e})}function Nc(e,t){return new oi({check:"string_format",format:"ends_with",...m(t),suffix:e})}function Lc(e,t,r){return new si({check:"property",property:e,schema:t,...m(r)})}function jc(e,t){return new ii({check:"mime_type",mime:e,...m(t)})}function ke(e){return new ai({check:"overwrite",tx:e})}function Bc(e){return ke(t=>t.normalize(e))}function Oc(){return ke(e=>e.trim())}function Zc(){return ke(e=>e.toLowerCase())}function Dc(){return ke(e=>e.toUpperCase())}function Xh(){return ke(e=>Ho(e))}function eg(e,t,r){return new e({type:"array",element:t,...m(r)})}function tg(e,t,r){return new e({type:"union",options:t,...m(r)})}function rg(e,t,r){return new e({type:"union",options:t,inclusive:!1,...m(r)})}function ng(e,t,r,n){return new e({type:"union",options:r,discriminator:t,...m(n)})}function og(e,t,r){return new e({type:"intersection",left:t,right:r})}function sg(e,t,r,n){let o=r instanceof b,s=o?n:r,i=o?r:null;return new e({type:"tuple",items:t,rest:i,...m(s)})}function ig(e,t,r,n){return new e({type:"record",keyType:t,valueType:r,...m(n)})}function ag(e,t,r,n){return new e({type:"map",keyType:t,valueType:r,...m(n)})}function cg(e,t,r){return new e({type:"set",valueType:t,...m(r)})}function ug(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 lg(e,t,r){return new e({type:"enum",entries:t,...m(r)})}function pg(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...m(r)})}function Fc(e,t){return new e({type:"file",...m(t)})}function fg(e,t){return new e({type:"transform",transform:t})}function dg(e,t){return new e({type:"optional",innerType:t})}function mg(e,t){return new e({type:"nullable",innerType:t})}function hg(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():Je(r)}})}function gg(e,t,r){return new e({type:"nonoptional",innerType:t,...m(r)})}function bg(e,t){return new e({type:"success",innerType:t})}function yg(e,t,r){return new e({type:"catch",innerType:t,catchValue:typeof r=="function"?r:()=>r})}function kg(e,t,r){return new e({type:"pipe",in:t,out:r})}function _g(e,t){return new e({type:"readonly",innerType:t})}function wg(e,t,r){return new e({type:"template_literal",parts:t,...m(r)})}function xg(e,t){return new e({type:"lazy",getter:t})}function Sg(e,t){return new e({type:"promise",innerType:t})}function Mc(e,t,r){let n=m(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Uc(e,t,r){return new e({type:"custom",check:"custom",fn:t,...m(r)})}function qc(e){let t=Hp(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Ve(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(Ve(o))}},e(r.value,r)));return t}function Hp(e,t){let r=new $({check:"custom",...m(t)});return r._zod.check=e,r}function Kc(e){let t=new $({check:"describe"});return t._zod.onattach=[r=>{let n=oe.get(r)??{};oe.add(r,{...n,description:e})}],t._zod.check=()=>{},t}function Hc(e){let t=new $({check:"meta"});return t._zod.onattach=[r=>{let n=oe.get(r)??{};oe.add(r,{...n,...e})}],t._zod.check=()=>{},t}function Wc(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(g=>typeof g=="string"?g.toLowerCase():g),o=o.map(g=>typeof g=="string"?g.toLowerCase():g));let s=new Set(n),i=new Set(o),c=e.Codec??Ut,u=e.Boolean??Ft,l=e.String??Ge,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:((g,_)=>{let w=g;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:((g,_)=>g===!0?n[0]||"true":o[0]||"false"),error:r.error});return h}function Qe(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 _e(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??oe,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,g=t.processors[o.type];if(!g)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);g(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 we(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 g=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=g,{defId:g,ref:`${h("__shared")}#/${c}/${g}`}}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 xe(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),g=h.schema;if(g.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(g)):Object.assign(u,g),Object.assign(u,l),i._zod.parent===p)for(let w in u)w==="$ref"||w==="allOf"||w in l||delete u[w];if(g.$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 g in u)g==="$ref"||g==="allOf"||g in h.def&&JSON.stringify(u[g])===JSON.stringify(h.def[g])&&delete u[g]}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:Jc(t,"input",e.processors),output:Jc(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 vg=(e,t={})=>r=>{let n=_e({...r,processors:t});return x(e,n),we(n,e),xe(n,e)},Jc=(e,t,r={})=>n=>{let{libraryOptions:o,target:s}=n??{},i=_e({...o??{},target:s,io:t,processors:r});return x(e,i),we(i,e),xe(i,e)};var $g={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Ig=(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=$g[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}))])}},Pg=(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)},Rg=(e,t,r,n)=>{r.type="boolean"},Cg=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},Tg=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},Eg=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},zg=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},Ag=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},Ng=(e,t,r,n)=>{r.not={}},Lg=(e,t,r,n)=>{},jg=(e,t,r,n)=>{},Bg=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Og=(e,t,r,n)=>{let o=e._zod.def,s=At(o.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},Zg=(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},Dg=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},Fg=(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},Mg=(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)},Ug=(e,t,r,n)=>{r.type="boolean"},qg=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Kg=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},Hg=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Wg=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},Jg=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},Vg=(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"]})},Yg=(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)},Gg=(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},Qg=(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},Xg=(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,g)=>x(h,t,{...n,path:[...n.path,i,g]})),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)},eb=(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)}},tb=(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"}]},rb=(e,t,r,n)=>{let o=e._zod.def;x(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},nb=(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))},ob=(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)))},sb=(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},ib=(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},ab=(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},cb=(e,t,r,n)=>{let o=e._zod.def;x(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},ub=(e,t,r,n)=>{let o=e._zod.def;x(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},lb=(e,t,r,n)=>{let o=e._zod.innerType;x(o,t,n);let s=t.seen.get(e);s.ref=o},an={string:Ig,number:Pg,boolean:Rg,bigint:Cg,symbol:Tg,null:Eg,undefined:zg,void:Ag,never:Ng,any:Lg,unknown:jg,date:Bg,enum:Og,literal:Zg,nan:Dg,template_literal:Fg,file:Mg,success:Ug,custom:qg,function:Kg,transform:Hg,map:Wg,set:Jg,array:Vg,object:Yg,union:Gg,intersection:Qg,tuple:Xg,record:eb,nullable:tb,nonoptional:rb,default:nb,prefault:ob,catch:sb,pipe:ib,readonly:ab,promise:cb,optional:ub,lazy:lb};function cn(e,t){if("_idmap"in e){let n=e,o=_e({...t,processors:an}),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;we(o,p),i[l]=xe(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=_e({...t,processors:an});return x(e,r),we(r,e),xe(r,e)}var un=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=_e({processors:an,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)),we(this.ctx,t);let n=xe(this.ctx,t),{"~standard":o,...s}=n;return s}};var Wp={};var k=f("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");b.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)=>Be(e,r,n),e.parseAsync=async(r,n)=>ye(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Oe(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)=>N(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.apply=r=>r(e)}),et=f("ZodMiniString",(e,t)=>{Ge.init(e,t),k.init(e,t)});function Vc(e){return _a(et,e)}var I=f("ZodMiniStringFormat",(e,t)=>{v.init(e,t),et.init(e,t)}),Jp=f("ZodMiniEmail",(e,t)=>{fi.init(e,t),I.init(e,t)});function fb(e){return xa(Jp,e)}var Vp=f("ZodMiniGUID",(e,t)=>{li.init(e,t),I.init(e,t)});function db(e){return Sa(Vp,e)}var Wt=f("ZodMiniUUID",(e,t)=>{pi.init(e,t),I.init(e,t)});function mb(e){return va(Wt,e)}function hb(e){return $a(Wt,e)}function gb(e){return Ia(Wt,e)}function bb(e){return Pa(Wt,e)}var Yc=f("ZodMiniURL",(e,t)=>{di.init(e,t),I.init(e,t)});function yb(e){return nn(Yc,e)}function kb(e){return nn(Yc,{protocol:/^https?$/,hostname:V.domain,...m(e)})}var Yp=f("ZodMiniEmoji",(e,t)=>{mi.init(e,t),I.init(e,t)});function _b(e){return Ra(Yp,e)}var Gp=f("ZodMiniNanoID",(e,t)=>{hi.init(e,t),I.init(e,t)});function wb(e){return Ca(Gp,e)}var Qp=f("ZodMiniCUID",(e,t)=>{gi.init(e,t),I.init(e,t)});function xb(e){return Ta(Qp,e)}var Xp=f("ZodMiniCUID2",(e,t)=>{bi.init(e,t),I.init(e,t)});function Sb(e){return Ea(Xp,e)}var ef=f("ZodMiniULID",(e,t)=>{yi.init(e,t),I.init(e,t)});function vb(e){return za(ef,e)}var tf=f("ZodMiniXID",(e,t)=>{ki.init(e,t),I.init(e,t)});function $b(e){return Aa(tf,e)}var rf=f("ZodMiniKSUID",(e,t)=>{_i.init(e,t),I.init(e,t)});function Ib(e){return Na(rf,e)}var nf=f("ZodMiniIPv4",(e,t)=>{$i.init(e,t),I.init(e,t)});function Pb(e){return La(nf,e)}var of=f("ZodMiniIPv6",(e,t)=>{Ii.init(e,t),I.init(e,t)});function Rb(e){return ja(of,e)}var sf=f("ZodMiniCIDRv4",(e,t)=>{Ri.init(e,t),I.init(e,t)});function Cb(e){return Oa(sf,e)}var af=f("ZodMiniCIDRv6",(e,t)=>{Ci.init(e,t),I.init(e,t)});function Tb(e){return Za(af,e)}var cf=f("ZodMiniMAC",(e,t)=>{Pi.init(e,t),I.init(e,t)});function Eb(e){return Ba(cf,e)}var uf=f("ZodMiniBase64",(e,t)=>{Ei.init(e,t),I.init(e,t)});function zb(e){return Da(uf,e)}var lf=f("ZodMiniBase64URL",(e,t)=>{zi.init(e,t),I.init(e,t)});function Ab(e){return Fa(lf,e)}var pf=f("ZodMiniE164",(e,t)=>{Ai.init(e,t),I.init(e,t)});function Nb(e){return Ma(pf,e)}var ff=f("ZodMiniJWT",(e,t)=>{Ni.init(e,t),I.init(e,t)});function Lb(e){return Ua(ff,e)}var Jt=f("ZodMiniCustomStringFormat",(e,t)=>{Li.init(e,t),I.init(e,t)});function jb(e,t,r={}){return Qe(Jt,e,t,r)}function Bb(e){return Qe(Jt,"hostname",V.hostname,e)}function Ob(e){return Qe(Jt,"hex",V.hex,e)}function Zb(e,t){let r=t?.enc??"hex",n=`${e}_${r}`,o=V[n];if(!o)throw new Error(`Unrecognized hash format: ${n}`);return Qe(Jt,n,o,t)}var Vt=f("ZodMiniNumber",(e,t)=>{Yr.init(e,t),k.init(e,t)});function df(e){return Va(Vt,e)}var tt=f("ZodMiniNumberFormat",(e,t)=>{ji.init(e,t),Vt.init(e,t)});function Db(e){return Ga(tt,e)}function Fb(e){return Qa(tt,e)}function Mb(e){return Xa(tt,e)}function Ub(e){return ec(tt,e)}function qb(e){return tc(tt,e)}var Yt=f("ZodMiniBoolean",(e,t)=>{Ft.init(e,t),k.init(e,t)});function mf(e){return rc(Yt,e)}var Gt=f("ZodMiniBigInt",(e,t)=>{Gr.init(e,t),k.init(e,t)});function Kb(e){return oc(Gt,e)}var Gc=f("ZodMiniBigIntFormat",(e,t)=>{Bi.init(e,t),Gt.init(e,t)});function Hb(e){return ic(Gc,e)}function Wb(e){return ac(Gc,e)}var hf=f("ZodMiniSymbol",(e,t)=>{Oi.init(e,t),k.init(e,t)});function Jb(e){return cc(hf,e)}var gf=f("ZodMiniUndefined",(e,t)=>{Zi.init(e,t),k.init(e,t)});function Vb(e){return uc(gf,e)}var bf=f("ZodMiniNull",(e,t)=>{Di.init(e,t),k.init(e,t)});function yf(e){return lc(bf,e)}var kf=f("ZodMiniAny",(e,t)=>{Fi.init(e,t),k.init(e,t)});function Yb(){return pc(kf)}var _f=f("ZodMiniUnknown",(e,t)=>{Mi.init(e,t),k.init(e,t)});function ln(){return fc(_f)}var wf=f("ZodMiniNever",(e,t)=>{Ui.init(e,t),k.init(e,t)});function xf(e){return dc(wf,e)}var Sf=f("ZodMiniVoid",(e,t)=>{qi.init(e,t),k.init(e,t)});function Gb(e){return mc(Sf,e)}var pn=f("ZodMiniDate",(e,t)=>{Ki.init(e,t),k.init(e,t)});function Qb(e){return hc(pn,e)}var vf=f("ZodMiniArray",(e,t)=>{Hi.init(e,t),k.init(e,t)});function Qc(e,t){return new vf({type:"array",element:e,...m(t)})}function Xb(e){let t=e._zod.def.shape;return Nf(Object.keys(t))}var fn=f("ZodMiniObject",(e,t)=>{Qr.init(e,t),k.init(e,t),y(e,"shape",()=>t.shape)});function ey(e,t){let r={type:"object",shape:e??{},...m(t)};return new fn(r)}function ty(e,t){return new fn({type:"object",shape:e,catchall:xf(),...m(t)})}function ry(e,t){return new fn({type:"object",shape:e,catchall:ln(),...m(t)})}function ny(e,t){return jr(e,t)}function oy(e,t){return es(e,t)}function sy(e,t){return jr(e,t)}function iy(e,t){return Qo(e,t)}function ay(e,t){return Xo(e,t)}function cy(e,t){return ts(tu,e,t)}function uy(e,t){return rs(ru,e,t)}function ly(e,t){return e.clone({...e._zod.def,catchall:t})}var Xc=f("ZodMiniUnion",(e,t)=>{Mt.init(e,t),k.init(e,t)});function $f(e,t){return new Xc({type:"union",options:e,...m(t)})}var If=f("ZodMiniXor",(e,t)=>{Xc.init(e,t),Wi.init(e,t)});function py(e,t){return new If({type:"union",options:e,inclusive:!1,...m(t)})}var Pf=f("ZodMiniDiscriminatedUnion",(e,t)=>{Ji.init(e,t),k.init(e,t)});function fy(e,t,r){return new Pf({type:"union",options:t,discriminator:e,...m(r)})}var Rf=f("ZodMiniIntersection",(e,t)=>{Vi.init(e,t),k.init(e,t)});function dy(e,t){return new Rf({type:"intersection",left:e,right:t})}var Cf=f("ZodMiniTuple",(e,t)=>{Xr.init(e,t),k.init(e,t)});function Tf(e,t,r){let n=t instanceof b,o=n?r:t,s=n?t:null;return new Cf({type:"tuple",items:e,rest:s,...m(o)})}var dn=f("ZodMiniRecord",(e,t)=>{Yi.init(e,t),k.init(e,t)});function Ef(e,t,r){return new dn({type:"record",keyType:e,valueType:t,...m(r)})}function my(e,t,r){let n=N(e);return n._zod.values=void 0,new dn({type:"record",keyType:n,valueType:t,...m(r)})}function hy(e,t,r){return new dn({type:"record",keyType:e,valueType:t,mode:"loose",...m(r)})}var zf=f("ZodMiniMap",(e,t)=>{Gi.init(e,t),k.init(e,t)});function gy(e,t,r){return new zf({type:"map",keyType:e,valueType:t,...m(r)})}var Af=f("ZodMiniSet",(e,t)=>{Qi.init(e,t),k.init(e,t)});function by(e,t){return new Af({type:"set",valueType:e,...m(t)})}var eu=f("ZodMiniEnum",(e,t)=>{Xi.init(e,t),k.init(e,t),e.options=Object.values(t.entries)});function Nf(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new eu({type:"enum",entries:r,...m(t)})}function yy(e,t){return new eu({type:"enum",entries:e,...m(t)})}var Lf=f("ZodMiniLiteral",(e,t)=>{ea.init(e,t),k.init(e,t)});function ky(e,t){return new Lf({type:"literal",values:Array.isArray(e)?e:[e],...m(t)})}var jf=f("ZodMiniFile",(e,t)=>{ta.init(e,t),k.init(e,t)});function _y(e){return Fc(jf,e)}var Bf=f("ZodMiniTransform",(e,t)=>{ra.init(e,t),k.init(e,t)});function wy(e){return new Bf({type:"transform",transform:e})}var tu=f("ZodMiniOptional",(e,t)=>{en.init(e,t),k.init(e,t)});function Of(e){return new tu({type:"optional",innerType:e})}var Zf=f("ZodMiniExactOptional",(e,t)=>{na.init(e,t),k.init(e,t)});function xy(e){return new Zf({type:"optional",innerType:e})}var Df=f("ZodMiniNullable",(e,t)=>{oa.init(e,t),k.init(e,t)});function Ff(e){return new Df({type:"nullable",innerType:e})}function Sy(e){return Of(Ff(e))}var Mf=f("ZodMiniDefault",(e,t)=>{sa.init(e,t),k.init(e,t)});function vy(e,t){return new Mf({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Je(t)}})}var Uf=f("ZodMiniPrefault",(e,t)=>{ia.init(e,t),k.init(e,t)});function $y(e,t){return new Uf({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Je(t)}})}var ru=f("ZodMiniNonOptional",(e,t)=>{aa.init(e,t),k.init(e,t)});function Iy(e,t){return new ru({type:"nonoptional",innerType:e,...m(t)})}var qf=f("ZodMiniSuccess",(e,t)=>{ca.init(e,t),k.init(e,t)});function Py(e){return new qf({type:"success",innerType:e})}var Kf=f("ZodMiniCatch",(e,t)=>{ua.init(e,t),k.init(e,t)});function Ry(e,t){return new Kf({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Hf=f("ZodMiniNaN",(e,t)=>{la.init(e,t),k.init(e,t)});function Cy(e){return bc(Hf,e)}var nu=f("ZodMiniPipe",(e,t)=>{pa.init(e,t),k.init(e,t)});function Ty(e,t){return new nu({type:"pipe",in:e,out:t})}var ou=f("ZodMiniCodec",(e,t)=>{nu.init(e,t),Ut.init(e,t)});function Ey(e,t,r){return new ou({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}var Wf=f("ZodMiniReadonly",(e,t)=>{fa.init(e,t),k.init(e,t)});function zy(e){return new Wf({type:"readonly",innerType:e})}var Jf=f("ZodMiniTemplateLiteral",(e,t)=>{da.init(e,t),k.init(e,t)});function Ay(e,t){return new Jf({type:"template_literal",parts:e,...m(t)})}var Vf=f("ZodMiniLazy",(e,t)=>{ga.init(e,t),k.init(e,t)});function Yf(e){return new Vf({type:"lazy",getter:e})}var Gf=f("ZodMiniPromise",(e,t)=>{ha.init(e,t),k.init(e,t)});function Ny(e){return new Gf({type:"promise",innerType:e})}var su=f("ZodMiniCustom",(e,t)=>{ba.init(e,t),k.init(e,t)});function Ly(e,t){let r=new $({check:"custom",...m(t)});return r._zod.check=e,r}function Qf(e,t){return Mc(su,e??(()=>!0),t)}function jy(e,t={}){return Uc(su,e,t)}function By(e){return qc(e)}var Oy=Kc,Zy=Hc;function Dy(e,t={}){let r=Qf(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 Fy=(...e)=>Wc({Codec:ou,Boolean:Yt,String:et},...e);function My(){let e=Yf(()=>$f([Vc(),df(),mf(),yf(),Qc(e),Ef(Vc(),e)]));return e}var Xf=f("ZodMiniFunction",(e,t)=>{ma.init(e,t),k.init(e,t)});function Uy(e){return new Xf({type:"function",input:Array.isArray(e?.input)?Tf(e?.input):e?.input??Qc(ln()),output:e?.output??ln()})}var iu={};Ae(iu,{ZodMiniISODate:()=>hn,ZodMiniISODateTime:()=>mn,ZodMiniISODuration:()=>bn,ZodMiniISOTime:()=>gn,date:()=>Ky,datetime:()=>qy,duration:()=>Wy,time:()=>Hy});var mn=f("ZodMiniISODateTime",(e,t)=>{wi.init(e,t),I.init(e,t)});function qy(e){return Ka(mn,e)}var hn=f("ZodMiniISODate",(e,t)=>{xi.init(e,t),I.init(e,t)});function Ky(e){return Ha(hn,e)}var gn=f("ZodMiniISOTime",(e,t)=>{Si.init(e,t),I.init(e,t)});function Hy(e){return Wa(gn,e)}var bn=f("ZodMiniISODuration",(e,t)=>{vi.init(e,t),I.init(e,t)});function Wy(e){return Ja(bn,e)}var au={};Ae(au,{bigint:()=>Gy,boolean:()=>Yy,date:()=>Qy,number:()=>Vy,string:()=>Jy});function Jy(e){return wa(et,e)}function Vy(e){return Ya(Vt,e)}function Yy(e){return nc(Yt,e)}function Gy(e){return sc(Gt,e)}function Qy(e){return gc(pn,e)}var K=a.string().check(a.minLength(1)),Xy=a.string().check(a.regex(/^https?:\/\/.+/)),Se=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())}),yn=a.extend(Se,{JIRA_BASE_URL:Xy,JIRA_USER:K,JIRA_API_TOKEN:K,JIRA_PROJECT_KEY:K,CLANCY_JQL_STATUS:a.optional(a.string()),CLANCY_JQL_SPRINT:a.optional(a.string())}),kn=a.extend(Se,{GITHUB_TOKEN:K,GITHUB_REPO:K}),_n=a.extend(Se,{LINEAR_API_KEY:K,LINEAR_TEAM_ID:K}),wn=a.extend(Se,{SHORTCUT_API_TOKEN:K,SHORTCUT_WORKFLOW:a.optional(a.string())}),xn=a.extend(Se,{NOTION_TOKEN:K,NOTION_DATABASE_ID:K,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())}),Sn=a.extend(Se,{AZDO_ORG:K,AZDO_PROJECT:K,AZDO_PAT:K,CLANCY_AZDO_STATUS:a.optional(a.string()),CLANCY_AZDO_WIT:a.optional(a.string())});var cu=a.object({id:a.number(),url:a.optional(a.string())}),vn=a.object({workItems:a.array(cu)}),ek=a.object({rel:a.string(),url:a.string(),attributes:a.optional(a.object({name:a.optional(a.string())}))}),tk=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())}),Qt=a.object({id:a.number(),fields:tk,relations:a.optional(a.nullable(a.array(ek)))}),$n=a.object({value:a.array(Qt),count:a.optional(a.number())}),td=a.object({id:a.string(),name:a.string(),state:a.optional(a.string())}),rk=a.object({source:a.optional(a.nullable(cu)),target:a.optional(a.nullable(cu))}),In=a.object({workItemRelations:a.optional(a.array(rk))});var uu=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())})))}),Pn=a.array(uu),lu=a.object({id:a.number(),body:a.optional(a.nullable(a.string())),created_at:a.string(),user:a.optional(a.object({login:a.string()}))}),Rn=a.array(lu),pu=a.object({number:a.number(),html_url:a.string(),state:a.string()}),Cn=a.array(pu),rd=a.object({html_url:a.optional(a.string()),number:a.optional(a.number())}),fu=a.object({state:a.string(),user:a.object({login:a.string()}),submitted_at:a.string()}),Tn=a.array(fu),du=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()}))}),En=a.array(du),nd=a.object({id:a.number(),name:a.string(),full_name:a.string()});var nk=a.object({type:a.optional(a.object({name:a.optional(a.string())})),inwardIssue:a.optional(a.object({key:a.optional(a.string())}))}),ok=a.object({summary:a.string(),description:a.optional(a.unknown()),issuelinks:a.optional(a.array(nk)),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()))}),sk=a.object({key:a.string(),fields:ok}),zn=a.object({total:a.optional(a.number()),isLast:a.optional(a.boolean()),issues:a.array(sk)}),ik=a.object({id:a.string(),name:a.string()}),An=a.object({transitions:a.array(ik)}),ak=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())}))}))}))}))}),Nn=a.object({fields:a.optional(a.object({issuelinks:a.optional(a.array(ak))}))}),Ln=a.object({fields:a.optional(a.object({labels:a.optional(a.array(a.string()))}))}),od=a.object({id:a.string(),key:a.string(),name:a.string()});var ck=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()}))}))}),jn=a.object({data:a.optional(a.object({viewer:a.optional(a.object({assignedIssues:a.optional(a.object({nodes:a.array(ck)}))}))}))}),Bn=a.object({data:a.optional(a.object({viewer:a.optional(a.object({id:a.optional(a.string())}))}))}),On=a.object({data:a.optional(a.object({workflowStates:a.optional(a.object({nodes:a.array(a.object({id:a.string()}))}))}))}),Zn=a.object({data:a.optional(a.object({issueUpdate:a.optional(a.object({success:a.optional(a.boolean())}))}))}),uk=a.object({type:a.string(),relatedIssue:a.optional(a.object({state:a.optional(a.object({type:a.optional(a.string())}))}))}),Dn=a.object({data:a.optional(a.object({issue:a.optional(a.object({relations:a.optional(a.object({nodes:a.array(uk)}))}))}))}),sd=a.object({state:a.optional(a.object({type:a.optional(a.string())}))}),Fn=a.object({data:a.optional(a.object({issueSearch:a.optional(a.object({nodes:a.array(sd)}))}))}),Mn=a.object({data:a.optional(a.object({issue:a.optional(a.object({children:a.optional(a.object({nodes:a.array(sd)}))}))}))}),Un=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()}))}))}))}))}),qn=a.object({data:a.optional(a.object({issueLabels:a.optional(a.object({nodes:a.array(a.object({id:a.string(),name:a.string()}))}))}))}),Kn=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())}))}))}),lk=a.object({id:a.string(),labels:a.optional(a.object({nodes:a.array(a.object({id:a.string(),name:a.optional(a.string())}))}))}),Hn=a.object({data:a.optional(a.object({issueSearch:a.optional(a.object({nodes:a.array(lk)}))}))});var id=a.object({plain_text:a.string()}),pk=a.object({type:a.literal("status"),status:a.nullable(a.object({id:a.optional(a.string()),name:a.string(),color:a.optional(a.string())}))}),fk=a.object({type:a.literal("select"),select:a.nullable(a.object({id:a.optional(a.string()),name:a.string(),color:a.optional(a.string())}))}),dk=a.object({id:a.optional(a.string()),name:a.string(),color:a.optional(a.string())}),mk=a.object({type:a.literal("multi_select"),multi_select:a.array(dk)}),hk=a.object({type:a.literal("people"),people:a.array(a.object({id:a.string(),name:a.optional(a.nullable(a.string()))}))}),gk=a.object({type:a.literal("relation"),relation:a.array(a.object({id:a.string()}))}),bk=a.object({type:a.literal("title"),title:a.array(id)}),yk=a.object({type:a.literal("rich_text"),rich_text:a.array(id)}),kk=a.union([pk,fk,mk,hk,gk,bk,yk,a.object({type:a.string()})]),Xt=a.object({id:a.string(),url:a.optional(a.string()),properties:a.record(a.string(),kk)}),Wn=a.object({results:a.array(Xt),has_more:a.boolean(),next_cursor:a.optional(a.nullable(a.string()))}),ad=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 _k=a.object({verb:a.string(),subject_id:a.number(),object_id:a.number()}),mu=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(_k)),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()))}),De=a.object({data:a.array(mu),next:a.optional(a.nullable(a.string())),total:a.optional(a.number())}),Fe=mu,wk=a.object({id:a.number(),name:a.string(),type:a.string()}),xk=a.object({id:a.number(),name:a.string(),states:a.array(wk)}),Jn=a.array(xk),cd=a.object({id:a.number(),name:a.string()}),Vn=a.array(cd),Yn=cd,Gn=a.array(mu),Qn=a.object({id:a.string(),mention_name:a.optional(a.string())});var er=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 rt(e){return new er(e)}async function nt(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 vk(e,t)}catch(n){return $k(e,t),{status:"error",error:n instanceof Error?n.message:String(n)}}finally{Ik(e,t)}}async function vk(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 $k(e,t){if(e.originalBranch)try{t.checkout(e.originalBranch)}catch{}}function Ik(e,t){if(e.lockOwner===!0){try{t.deleteLock()}catch{}try{t.deleteVerifyAttempt()}catch{}}}async function ot(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 Pk(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?Rk(e,t):Ck(e,t);return p.ok?(Ak(e,t),{ok:!0}):(t.checkout(c),p)}async function Pk(e,t){return e.hasParent!==!0||e.isRework===!0?!1:(await t.fetchChildrenStatus(e.ticket))?.total===1}function Rk(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 Ck(e,t){return e.hasParent===!0&&e.skipEpicBranch!==!0?Tk(e,t):Ek(e,t)}function Tk(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 Ek(e,t){let r=e.baseBranch;return t.ensureBranch(r,r),t.checkout(r),t.checkout(e.ticketBranch,!0),{ok:!0}}function zk(e){return(e.now??(()=>new Date().toISOString()))()}function Ak(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:zk(t)}),e.setLockOwner(!0)}catch{}}async function st(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 it(e,t){try{let r=e.config,n=e.ticket,o=t.readLock();if(!o)return{ok:!0};let s=Nk(r.env.CLANCY_TOKEN_RATE);t.appendCostEntry({ticketKey:n.key,startedAt:o.startedAt,tokenRate:s})}catch{}return{ok:!0}}function Nk(e){if(e==null)return 6600;let t=Number(e);return Number.isFinite(t)&&t>0?t:6600}async function at(e,t){return e.isRework===!0?Lk(e,t):jk(e,t)}async function Lk(e,t){let r=e.ticket,n=e.ticketBranch,o=e.effectiveTarget,{parentKey:s}=ld(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 ud(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 jk(e,t){let r=e.ticket,n=e.ticketBranch,o=e.effectiveTarget,{parentKey:s,singleChildParent:i}=ld(e);return(await t.deliverViaPullRequest({ticketBranch:n,targetBranch:o,parent:s,singleChildParent:i})).pushed?(t.recordDelivery(),await ud(r.key,t),{ok:!0}):(t.appendProgress({key:r.key,summary:r.title,status:"PUSH_FAILED",parent:s}),{ok:!1})}async function ud(e,t){try{await t.removeBuildLabel(e)}catch{}}function ld(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=Bk(i,o);return{parentKey:s,singleChildParent:c}}function Bk(e,t){if(e!=null)return t!=="github"||/^#\d+$/.test(e)?e:void 0}async function ct(e,t){try{return await Ok(e,t)}catch{return{results:[]}}}async function Ok(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 ut(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 tr}from"node:path";var Zk=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))}),gu=".clancy",Dk="lock.json",bu=`${gu}/${Dk}`,Fk=`${gu}/verify-attempt.txt`,Mk=1440*60*1e3;function Xn(e,t,r){e.mkdir(tr(t,gu)),e.writeFile(tr(t,bu),JSON.stringify(r,null,2))}function lt(e,t){try{let r=JSON.parse(e.readFile(tr(t,bu))),n=Zk.safeParse(r);return n.success?n.data:void 0}catch{return}}function pt(e,t){try{e.deleteFile(tr(t,bu))}catch(r){if(!(r instanceof Error&&"code"in r&&r.code==="ENOENT"))throw r}}function Uk(e){try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t&&t.code==="EPERM"}}function ft(e,t){try{e.deleteFile(tr(t,Fk))}catch(r){if(!(r instanceof Error&&"code"in r&&r.code==="ENOENT"))throw r}}function pd(e){if(!Uk(e.pid))return!0;let t=Date.now()-new Date(e.startedAt).getTime();return Number.isNaN(t)?!0:t>Mk}async function qk(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 dt(e,t){let r=lt(t.lockFs,e.projectRoot);if(!r)return{action:"continue"};if(!pd(r))return{action:"abort",reason:`Another Clancy session is running (PID ${r.pid}, ticket ${r.ticketKey})`};pt(t.lockFs,e.projectRoot),ft(t.lockFs,e.projectRoot);try{return await qk(e,r,t)}catch{return{action:"continue"}}}async function mt(e,t){try{return await Hk(e,t)}catch{return{results:[]}}}function fd(e){return e&&e!=="none"?e:void 0}function Kk(e){return e?.ok?"created":e&&!e.ok&&e.alreadyExists?"exists":e&&!e.ok?"failed":"skipped"}async function Hk(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 Wk(r,t);let o=async i=>{let c=await t.retryEntry(i,n,e),u=Kk(c),l=fd(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 Wk(e,t){return{results:e.map(n=>(t.appendProgress({key:n.key,summary:n.summary,status:"PR_CREATED",parent:fd(n.parent)}),{key:n.key,status:"unsupported"}))}}async function ht(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 gt(e,t){try{return await Jk(e,t)}catch{return{detected:!1}}}async function Jk(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 bt(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=Vk(r,n,t);if(s)return s}let o=Gk(e,t);return e.setTicketBranches(o),{ok:!0,ticketKey:n.key}}function Vk(e,t,r){let n=Yk(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 Yk(e){let t=parseInt(e??"3",10);return Number.isFinite(t)&&t>=0?t:3}function Gk(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 yt(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 Qk(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 Xk(e,t){let r=e.match(/^scm\/([^/]+)\/(.+)$/);if(r)return{host:"bitbucket-server",projectKey:r[1],repoSlug:r[2],hostname:t}}function e_(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 dd(e,t){let r=Xk(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 t_(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 dd(e,"bitbucket");case"bitbucket-server":return dd(e,"bitbucket-server");case"azure":{let s=e_(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 yu(e,t){let r=Qk(e);if(!r)return{host:"unknown",url:e};let{hostname:n,path:o}=r,s=t??r_(n);return t_({platform:s,hostname:n,path:o,rawUrl:e})}function r_(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 rr(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 n_(e){return e.length>0&&!e.includes("..")&&!e.startsWith("/")}var o_=new Set(["github","gitlab","bitbucket","bitbucket-server","azure"]);function kt(e){return e(["rev-parse","--abbrev-ref","HEAD"]).trim()}function nr(e){try{return e(["diff","--quiet"]),e(["diff","--cached","--quiet"]),!1}catch{return!0}}function _t(e,t){if(!n_(t))return!1;try{return e(["show-ref","--verify","--quiet",`refs/heads/${t}`]),!0}catch{return!1}}function eo(e,t,r){_t(e,t)||e(["checkout","-b",t,r])}function se(e,t,r=!1){e(["checkout",...r?["-B"]:[],t])}function ku(e,t){try{return e(["ls-remote","--heads","origin",t]).trim().length>0}catch{return!1}}function wt(e,t){try{return e(["fetch","origin",`${t}:${t}`]),!0}catch{return!1}}function Me(e,t){try{return e(["push","-u","origin",t]),!0}catch{return!1}}function ee(e,t){let r=s_(e,["remote","get-url","origin"]);if(!r)return{host:"none"};let n=i_(t)?t:void 0;return yu(r,n)}function s_(e,t){try{return e(t).trim()||void 0}catch{return}}function i_(e){return e!==void 0&&o_.has(e)}import{join as _u}from"node:path";function wu(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 md=".clancy/progress.txt",hd=new Set(["BRIEF","APPROVE_BRIEF"]),a_=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 te(e,t,r){let n=_u(t,md);e.mkdir(_u(t,".clancy"));let o=wu(new Date),s=hd.has(r.status)?c_(o,r):u_(o,r);e.appendFile(n,s)}function c_(e,t){return`${e} | ${t.status} | ${t.key} | ${t.summary}
|
|
42
|
+
`}function u_(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 Ue(e,t){let r=l_(e,_u(t,md));return r?r.split(/\r?\n/).filter(n=>n.trim().length>0).map(n=>p_(n.trim())).filter(n=>n!==void 0):[]}function l_(e,t){try{return e.readFile(t)}catch{return}}function p_(e){let t=e.split(" | ");if(t.length<4)return;let r=t[0];return hd.has(t[1])?f_(r,t):d_(r,t)}function f_(e,t){return{timestamp:e,key:t[2],summary:t.slice(3).join(" | "),status:t[1]}}function d_(e,t){let r=t[1],n=t.slice(2),{status:o,summary:s,prNumber:i,parent:c,ticketType:u}=m_(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 m_(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&&h_(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 h_(e){return a_.has(e)}function xu(e,t,r){let n=Ue(e,t),o=r.toLowerCase();return[...n].reverse().find(s=>s.key.toLowerCase()===o)}function to(e,t,r){let n=Ue(e,t),o=r.toLowerCase();return n.filter(s=>s.key.toLowerCase()===o&&s.status==="REWORK").length}function H(e,t,r){let n=Ue(e,t);return[...new Map(n.map(s=>[s.key,s])).values()].filter(s=>s.status===r)}function qe(e,t){return e==="github"?`feature/issue-${t.replace("#","")}`:`feature/${t.toLowerCase()}`}function or(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 g_(e,t){try{return e(t,["--version"]),!0}catch{return!1}}function b_(e){try{return e("git",["rev-parse","--git-dir"]),!0}catch{return!1}}function y_(e){try{return e("git",["ls-remote","origin","HEAD"]),!0}catch{return!1}}function k_(e){let t=o=>e("git",o),n=[[!y_(e),"Could not reach origin. PR creation and rework detection may not work."],[nr(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 Su(e,t){let r=c=>({ok:!1,error:c,warning:void 0,env:void 0}),o=["claude","git"].find(c=>!g_(t.exec,c));if(o)return r(`${o} is required but not found`);let s=zr(e,t.envFs);if(!s)return r(".clancy/.env not found \u2014 run /clancy:init first");if(!b_(t.exec))return r("Not inside a git repository");let i=k_(t.exec);return{ok:!0,env:s,error:void 0,warning:i}}function vu(e){let{exec:t,progressFs:r,projectRoot:n,lock:o}=e,s=o.ticketBranch;if(!_t(t,s))return;let i=__(t);if(!i)return;if(!ro(t,s)){ro(t,i);return}let c=w_(t,s,o.targetBranch);return ro(t,i),!c.hasUncommitted&&!c.hasUnpushed?v_({progressFs:r,projectRoot:n,lock:o},s):{branch:s,...c,alreadyDelivered:!1}}async function $u(e){let{exec:t,progressFs:r,projectRoot:n,lock:o,resumeInfo:s,createPr:i}=e;try{if(se(t,s.branch),s.hasUncommitted&&!$_(t,o))return{ok:!1,error:"Could not commit in-progress work"};if(!Me(t,s.branch))return{ok:!1,error:"Could not push branch"};let c=i?await i(o,s.branch):void 0;return P_({progressFs:r,projectRoot:n,lock:o},c),ro(t,o.targetBranch),{ok:!0,prResult:c}}catch(c){return{ok:!1,error:c instanceof Error?c.message:String(c)}}}function __(e){try{return kt(e)}catch{return}}function ro(e,t){try{return se(e,t),!0}catch{return!1}}function w_(e,t,r){let n=x_(e),o=S_(e,t,r);return{hasUncommitted:n,hasUnpushed:o}}function x_(e){try{return nr(e)}catch{return!1}}function S_(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 v_(e,t){let r=xu(e.progressFs,e.projectRoot,e.lock.ticketKey);if(r&&Le.has(r.status))return{branch:t,hasUncommitted:!1,hasUnpushed:!1,alreadyDelivered:!0}}function $_(e,t){try{return e(["add","-A"]),e(["commit","-m",`fix(${t.ticketKey}): resume after crash`]),!0}catch{return!1}}function I_(e){return e.parentKey&&e.parentKey!=="none"?e.parentKey:void 0}function P_(e,t){te(e.progressFs,e.projectRoot,{key:e.lock.ticketKey,summary:e.lock.ticketTitle,status:"RESUMED",prNumber:t?.ok?t.number:void 0,parent:I_(e.lock)})}var R_=5,gd=3,C_=80;function T_(e){if(e.length===0)return"[clancy] Rework pushed addressing reviewer feedback.";let t=e.length,r=e.slice(0,gd).map(o=>`- ${o.slice(0,C_)}`).join(`
|
|
45
|
+
`),n=t>gd?`
|
|
46
|
+
- ...`:"";return`[clancy] Rework pushed addressing ${t} feedback item${t!==1?"s":""}.
|
|
47
|
+
|
|
48
|
+
${r}${n}`}async function Iu(e){let{progressFs:t,projectRoot:r,provider:n,handlers:o}=e,s=[...H(t,r,"PR_CREATED"),...H(t,r,"REWORK"),...H(t,r,"PUSHED"),...H(t,r,"PUSH_FAILED")];if(s.length===0)return;let i=s.slice(0,R_);return bd(i,n,o)}async function Pu(e){let{handlers:t,prNumber:r,feedback:n,discussionIds:o,reviewers:s}=e;await E_(t,r,n),await z_(t,r,o),await A_(t,r,s)}async function E_(e,t,r){try{let n=T_(r);await e.postComment(t,n)&&console.log(" \u2713 Posted rework comment")}catch{}}async function z_(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 A_(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 N_(e){let t=new Date(e.replace(" ","T")+"Z");return Number.isNaN(t.getTime())?void 0:t.toISOString()}async function bd(e,t,r){if(e.length===0)return;let[n,...o]=e,s=qe(t,n.key),i=n.timestamp?N_(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 bd(o,t,r)}function L_(e,t){return{github:e.GITHUB_TOKEN,gitlab:e.GITLAB_TOKEN,"bitbucket-server":e.BITBUCKET_TOKEN,azure:e.AZDO_PAT}[t]}function sr(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=L_(e,t.host);return r?{token:r}:void 0}var j_=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())})))}),yd=a.object({pullRequestId:a.optional(a.number())}),kd=a.object({value:a.array(j_),count:a.optional(a.number())}),B_=a.object({filePath:a.optional(a.string())}),O_=a.object({content:a.optional(a.string()),commentType:a.optional(a.string()),publishedDate:a.optional(a.string())}),Z_=a.object({id:a.number(),status:a.optional(a.string()),comments:a.array(O_),threadContext:a.optional(a.nullable(B_)),isDeleted:a.optional(a.boolean()),publishedDate:a.optional(a.string())}),_d=a.object({value:a.array(Z_),count:a.optional(a.number())});async function ie(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(()=>""),g=i?.(l.status,h)??!1;return{ok:!1,error:`HTTP ${l.status}${h?`: ${h.slice(0,200)}`:""}`,alreadyExists:g}}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 ae(e,t){return`Basic ${Buffer.from(`${e}:${t}`).toString("base64")}`}function j(e){return e.trim().toLowerCase().startsWith("rework:")}function M(e){return e.trimStart().startsWith("[clancy]")}function ce(e){return e.trim().replace(/^rework:\s*/i,"").trim()}var oo="api-version=7.1",no="https://dev.azure.com";async function Ru(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 ie({fetchFn:t,url:`${no}/${p}/${d}/_apis/git/repositories/${h}/pullrequests?${oo}`,headers:{Authorization:ae("",s)},body:{sourceRefName:`refs/heads/${i}`,targetRefName:`refs/heads/${c}`,title:u,description:l},parseSuccess:g=>{let w=yd.parse(g).pullRequestId??0;return{url:`${no}/${p}/${d}/_git/${h}/pullrequest/${w}`,number:w}},isAlreadyExists:(g,_)=>g===409||g===400&&_.includes("already has an active pull request")})}async function Cu(e){let{fetchFn:t,org:r,project:n,repo:o,pat:s,prId:i,body:c}=e;try{let u=zu(r,n,o);return(await t(`${u}/${i}/threads?${oo}`,{method:"POST",headers:{Authorization:ae("",s),"Content-Type":"application/json"},body:JSON.stringify({comments:[{parentCommentId:0,content:c,commentType:1}],status:1})})).ok}catch{return!1}}async function Tu(e){let{fetchFn:t,org:r,project:n,repo:o,pat:s,branch:i,since:c}=e,u=ae("",s);try{let l=zu(r,n,o),p=await t(`${l}?searchCriteria.sourceRefName=${encodeURIComponent(`refs/heads/${i}`)}&searchCriteria.status=active&${oo}`,{headers:{Authorization:u}});if(!p.ok)return;let d=kd.parse(await p.json());if(d.value.length===0)return;let h=d.value[0],g=await wd({fetchFn:t,auth:u,org:r,project:n,repo:o,prId:h.pullRequestId});if(!g)return;let _=Sd(xd(g),c),w=_.some(ze=>ze.threadContext!=null),R=_.some(ze=>ze.threadContext==null&&ze.comments.length>0&&j(ze.comments[0].content??""));return{changesRequested:w||R,prNumber:h.pullRequestId,prUrl:`${no}/${encodeURIComponent(r)}/${encodeURIComponent(n)}/_git/${encodeURIComponent(o)}/pullrequest/${h.pullRequestId}`}}catch{return}}async function Eu(e){let{fetchFn:t,org:r,project:n,repo:o,pat:s,prId:i,since:c}=e,u=ae("",s);try{let l=await wd({fetchFn:t,auth:u,org:r,project:n,repo:o,prId:i});return l?Sd(xd(l),c).flatMap(p=>D_(p)):[]}catch{return[]}}function zu(e,t,r){let n=encodeURIComponent(e),o=encodeURIComponent(t),s=encodeURIComponent(r);return`${no}/${n}/${o}/_apis/git/repositories/${s}/pullrequests`}async function wd(e){let{fetchFn:t,auth:r,org:n,project:o,repo:s,prId:i}=e,c=zu(n,o,s),u=await t(`${c}/${i}/threads?${oo}`,{headers:{Authorization:r}});return u.ok?_d.parse(await u.json()).value:void 0}function xd(e){return e.filter(t=>t.isDeleted!==!0&&t.comments.length>0&&t.comments[0].commentType!=="system"&&!M(t.comments[0].content??""))}function Sd(e,t){return t?e.filter(r=>(r.publishedDate??"")>t):e}function D_(e){let t=e.comments[0]?.content??"";return t?e.threadContext!=null?[`${e.threadContext.filePath?`[${e.threadContext.filePath}] `:""}${t}`]:j(t)?[ce(t)]:[]:[]}var F_=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()}))}),vd=a.object({values:a.array(F_)}),$d=a.object({id:a.optional(a.number()),links:a.optional(a.object({html:a.optional(a.object({href:a.optional(a.string())}))}))}),M_=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())}))}),Id=a.object({values:a.array(M_)}),U_=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()}))}),Pd=a.object({values:a.array(U_)}),Rd=a.object({id:a.optional(a.number()),links:a.optional(a.object({self:a.optional(a.array(a.object({href:a.optional(a.string())})))}))}),q_=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())}))}),K_=a.object({action:a.string(),comment:a.optional(q_)}),Cd=a.object({values:a.array(K_)});var so="https://api.bitbucket.org/2.0";async function Au(e){let{fetchFn:t,username:r,token:n,workspace:o,repoSlug:s}=e,{sourceBranch:i,targetBranch:c,title:u,description:l}=e;return ie({fetchFn:t,url:`${so}/repositories/${encodeURIComponent(o)}/${encodeURIComponent(s)}/pullrequests`,headers:{Authorization:ae(r,n)},body:{title:u,description:l,source:{branch:{name:i}},destination:{branch:{name:c}},close_source_branch:!0},parseSuccess:p=>{let d=$d.parse(p);return{url:d.links?.html?.href??"",number:d.id??0}},isAlreadyExists:(p,d)=>p===409&&d.includes("already exists")})}async function Nu(e){let{fetchFn:t,username:r,token:n,workspace:o,repoSlug:s,prId:i,body:c}=e;try{return(await t(`${so}/repositories/${encodeURIComponent(o)}/${encodeURIComponent(s)}/pullrequests/${i}/comments`,{method:"POST",headers:{Authorization:ae(r,n),"Content-Type":"application/json"},body:JSON.stringify({content:{raw:c}})})).ok}catch{return!1}}async function Lu(e){let{fetchFn:t,username:r,token:n,workspace:o,repoSlug:s,branch:i,since:c}=e,u=ae(r,n);try{let l=await t(`${so}/repositories/${encodeURIComponent(o)}/${encodeURIComponent(s)}/pullrequests?q=source.branch.name="${encodeURIComponent(i)}"&state=OPEN`,{headers:{Authorization:u}});if(!l.ok)return;let p=vd.parse(await l.json());if(p.values.length===0)return;let d=p.values[0],h=await Td({fetchFn:t,auth:u,workspace:o,repoSlug:s,prId:d.id});if(!h)return;let g=Ed(h,c).filter(R=>!M(R.content.raw)),_=g.some(R=>R.inline!=null),w=g.some(R=>R.inline==null&&j(R.content.raw));return{changesRequested:_||w,prNumber:d.id,prUrl:d.links.html?.href??""}}catch{return}}async function ju(e){let{fetchFn:t,username:r,token:n,workspace:o,repoSlug:s,prId:i,since:c}=e,u=ae(r,n);try{let l=await Td({fetchFn:t,auth:u,workspace:o,repoSlug:s,prId:i});return l?Ed(l,c).filter(p=>!M(p.content.raw)).flatMap(p=>H_(p)):[]}catch{return[]}}async function Td(e){let{fetchFn:t,auth:r,workspace:n,repoSlug:o,prId:s}=e,i=await t(`${so}/repositories/${encodeURIComponent(n)}/${encodeURIComponent(o)}/pullrequests/${s}/comments?pagelen=100`,{headers:{Authorization:r}});return i.ok?Id.parse(await i.json()).values:void 0}function Ed(e,t){return t?e.filter(r=>r.created_on>t):e}function H_(e){return e.inline!=null?[`${e.inline.path?`[${e.inline.path}] `:""}${e.content.raw}`]:j(e.content.raw)?[ce(e.content.raw)]:[]}async function Bu(e){let{fetchFn:t,token:r,apiBase:n,projectKey:o,repoSlug:s}=e,{sourceBranch:i,targetBranch:c,title:u,description:l}=e;return ie({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=Rd.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 Ou(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=Pd.parse(await l.json());if(p.values.length===0)return;let d=p.values[0],h=await zd({fetchFn:t,auth:u,apiBase:n,projectKey:o,repoSlug:s,prId:d.id});if(!h)return;let g=Ad(h,c).filter(R=>!M(R.text)),_=g.some(R=>R.anchor!=null),w=g.some(R=>R.anchor==null&&j(R.text));return{changesRequested:_||w,prNumber:d.id,prUrl:d.links.self?.[0]?.href??""}}catch{return}}async function Du(e){let{fetchFn:t,token:r,apiBase:n,projectKey:o,repoSlug:s,prId:i,since:c}=e,u=`Bearer ${r}`;try{let l=await zd({fetchFn:t,auth:u,apiBase:n,projectKey:o,repoSlug:s,prId:i});return l?Ad(l,c).filter(p=>!M(p.text)).flatMap(p=>W_(p)):[]}catch{return[]}}async function zd(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?Cd.parse(await c.json()).values.filter(l=>l.action==="COMMENTED"&&l.comment!=null).map(l=>l.comment):void 0}function Ad(e,t){if(!t)return e;let r=Date.parse(t);return e.filter(n=>n.createdDate>r)}function W_(e){return e.anchor!=null?[`${e.anchor.path?`[${e.anchor.path}] `:""}${e.text}`]:j(e.text)?[ce(e.text)]:[]}var T="https://api.github.com",J_=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,V_=a.object({login:a.string()});function E(e){return{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}}function ve(e){return J_.test(e)}async function Fu(e,t,r){return ve(t)?Q({url:`${T}/repos/${t}`,headers:E(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 Mu(e,t,r){let n=t.get();if(n)return n;let o=r??fetch;try{let s=await o(`${T}/user`,{headers:E(e)});if(s.ok){let i=await s.json(),c=V_.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 Y_(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 Uu(e){let{token:t,repo:r,label:n,username:o,excludeHitl:s,limit:i=5,fetcher:c}=e;if(!ve(r))return[];let u=new URLSearchParams({state:"open",assignee:o??"@me",per_page:"10",...n?{labels:n}:{}}),l=await S(`${T}/repos/${r}/issues?${u}`,{headers:E(t)},{schema:Pn,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(g=>g.name==="clancy:hitl")):p).slice(0,i).map(Y_)}async function qu(e){let{fetchFn:t,token:r,repo:n,branch:o,owner:s}=e,i=e.apiBase??T;try{let c=await G_({fetchFn:t,apiBase:i,repo:n,owner:s,branch:o,token:r});if(!c)return;let{inline:u,convo:l}=await Nd({fetchFn:t,apiBase:i,repo:n,prNumber:c.number,token:r,since:e.since}),p=u.length>0,d=l.some(_=>_.body!=null&&j(_.body));if(p||d)return{changesRequested:!0,prNumber:c.number,prUrl:c.url};let g=await Q_({fetchFn:t,apiBase:i,repo:n,prNumber:c.number,token:r});return{changesRequested:g.changesRequested,prNumber:c.number,prUrl:c.url,...g.reviewers&&{reviewers:g.reviewers}}}catch{return}}async function Ku(e){let{fetchFn:t,token:r,repo:n,prNumber:o}=e,s=e.apiBase??T;try{let{inline:i,convo:c}=await Nd({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&&j(p.body)).map(p=>ce(p.body));return[...u,...l]}catch{return[]}}async function Hu(e){let{fetchFn:t,token:r,repo:n,prNumber:o,body:s}=e,i=e.apiBase??T;try{return(await t(`${i}/repos/${n}/issues/${o}/comments`,{method:"POST",headers:{...E(r),"Content-Type":"application/json"},body:JSON.stringify({body:s})})).ok}catch{return!1}}async function Wu(e){let{fetchFn:t,token:r,repo:n,prNumber:o,reviewers:s}=e,i=e.apiBase??T;try{return(await t(`${i}/repos/${n}/pulls/${o}/requested_reviewers`,{method:"POST",headers:{...E(r),"Content-Type":"application/json"},body:JSON.stringify({reviewers:s})})).ok}catch{return!1}}async function Ju(e){let{fetchFn:t,token:r,repo:n,head:o,base:s,title:i,body:c}=e,u=e.apiBase??T;return ie({fetchFn:t,url:`${u}/repos/${n}/pulls`,headers:E(r),body:{title:i,head:o,base:s,body:c},parseSuccess:l=>{let p=rd.parse(l);return{url:p.html_url??"",number:p.number??0}},isAlreadyExists:(l,p)=>l===422&&p.includes("already exists")})}async function G_(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:E(i)});if(!c.ok)return;let u=Cn.parse(await c.json());if(u.length===0)return;let l=u[0];return{number:l.number,url:l.html_url}}async function Nd(e){let{fetchFn:t,apiBase:r,repo:n,prNumber:o,token:s,since:i}=e,c=E(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=En.parse(await l.json()),h=Rn.parse(await p.json());return{inline:d.filter(g=>!g.body||!M(g.body)),convo:h.filter(g=>!g.body||!M(g.body))}}async function Q_(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:E(s)});if(!i.ok)return{changesRequested:!1};let c=Tn.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 X_=a.object({iid:a.number(),web_url:a.string(),detailed_merge_status:a.optional(a.string())}),Ld=a.array(X_),jd=a.object({iid:a.optional(a.number()),web_url:a.optional(a.string())}),ew=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()}))}),tw=a.object({id:a.optional(a.string()),notes:a.array(ew)}),Bd=a.array(tw);async function Vu(e){let{fetchFn:t,token:r,apiBase:n,projectPath:o}=e,{sourceBranch:s,targetBranch:i,title:c,description:u}=e,l=encodeURIComponent(o);return ie({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=jd.parse(p);return{url:d.web_url??"",number:d.iid??0}},isAlreadyExists:(p,d)=>p===409&&d.includes("already exists")})}async function Yu(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 Gu(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 Qu(e){let{fetchFn:t,token:r,apiBase:n,projectPath:o,branch:s,since:i}=e;try{let c=await rw({fetchFn:t,token:r,apiBase:n,projectPath:o,branch:s});if(!c)return;let u=await Od({fetchFn:t,token:r,apiBase:n,projectPath:o,mrIid:c.iid});return u?{changesRequested:u.some(p=>p.notes.some(d=>nw(d,i))),prNumber:c.iid,prUrl:c.url}:void 0}catch{return}}async function Xu(e){let{fetchFn:t,token:r,apiBase:n,projectPath:o,mrIid:s,since:i}=e;try{let c=await Od({fetchFn:t,token:r,apiBase:n,projectPath:o,mrIid:s});return c?ow(c,i):{comments:[],discussionIds:[]}}catch{return{comments:[],discussionIds:[]}}}async function rw(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=Ld.parse(await c.json());if(u.length===0)return;let l=u[0];return{iid:l.iid,url:l.web_url}}async function Od(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 Bd.parse(await c.json())}function nw(e,t){return e.system||M(e.body)||t&&e.created_at&&e.created_at<=t?!1:e.type==="DiffNote"&&e.resolvable!==!1&&e.resolved!==!0||j(e.body)}function ow(e,t){let r=e.map(n=>{let s=n.notes.filter(c=>!c.system&&!M(c.body)).filter(c=>!t||!c.created_at||c.created_at>t).flatMap(c=>sw(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 sw(e){return e.type==="DiffNote"&&e.resolvable!==!1&&e.resolved!==!0?[`${e.position?.new_path?`[${e.position.new_path}] `:""}${e.body}`]:j(e.body)?[ce(e.body)]:[]}var io=async()=>0,ao=async()=>!1;function Zd(e,t){let{fetchFn:r,token:n,apiBase:o}=e,s=`${t.owner}/${t.repo}`;return{checkReviewState:(i,c)=>qu({fetchFn:r,token:n,repo:s,branch:i,owner:t.owner,apiBase:o,since:c}),fetchComments:async(i,c)=>({comments:await Ku({fetchFn:r,token:n,repo:s,prNumber:i,apiBase:o,since:c})}),postComment:(i,c)=>Hu({fetchFn:r,token:n,repo:s,prNumber:i,body:c,apiBase:o}),resolveThreads:io,reRequestReview:(i,c)=>Wu({fetchFn:r,token:n,repo:s,prNumber:i,reviewers:c,apiBase:o})}}function Dd(e,t){let{fetchFn:r,token:n,apiBase:o}=e;return{checkReviewState:(s,i)=>Qu({fetchFn:r,token:n,apiBase:o,projectPath:t.projectPath,branch:s,since:i}),fetchComments:(s,i)=>Xu({fetchFn:r,token:n,apiBase:o,projectPath:t.projectPath,mrIid:s,since:i}),postComment:(s,i)=>Yu({fetchFn:r,token:n,apiBase:o,projectPath:t.projectPath,mrIid:s,body:i}),resolveThreads:(s,i)=>Gu({fetchFn:r,token:n,apiBase:o,projectPath:t.projectPath,mrIid:s,discussionIds:i}),reRequestReview:ao}}function Fd(e,t){let{fetchFn:r,token:n,username:o}=e;if(!o)throw new Error("Bitbucket Cloud requires a username");return{checkReviewState:(s,i)=>Lu({fetchFn:r,username:o,token:n,workspace:t.workspace,repoSlug:t.repoSlug,branch:s,since:i}),fetchComments:async(s,i)=>({comments:await ju({fetchFn:r,username:o,token:n,workspace:t.workspace,repoSlug:t.repoSlug,prId:s,since:i})}),postComment:(s,i)=>Nu({fetchFn:r,username:o,token:n,workspace:t.workspace,repoSlug:t.repoSlug,prId:s,body:i}),resolveThreads:io,reRequestReview:ao}}function Md(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 Du({fetchFn:r,token:n,apiBase:o,projectKey:t.projectKey,repoSlug:t.repoSlug,prId:s,since:i})}),postComment:(s,i)=>Ou({fetchFn:r,token:n,apiBase:o,projectKey:t.projectKey,repoSlug:t.repoSlug,prId:s,body:i}),resolveThreads:io,reRequestReview:ao}}function Ud(e,t){let{fetchFn:r,token:n}=e,{org:o,project:s,repo:i}=t;return{checkReviewState:(c,u)=>Tu({fetchFn:r,org:o,project:s,repo:i,pat:n,branch:c,since:u}),fetchComments:async(c,u)=>({comments:await Eu({fetchFn:r,org:o,project:s,repo:i,pat:n,prId:c,since:u})}),postComment:(c,u)=>Cu({fetchFn:r,org:o,project:s,repo:i,pat:n,prId:c,body:u}),resolveThreads:io,reRequestReview:ao}}function ir(e){let{fetchFn:t,env:r,remote:n}=e,o=sr(r,n);if(!o)return;let s=rr(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 Zd(i,n);case"gitlab":return Dd(i,n);case"bitbucket":return Fd(i,n);case"bitbucket-server":return Md(i,n);case"azure":return Ud(i,n);default:return}}function iw(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 aw(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 el(e,t,r){let n=iw(t),{stdout:o,ok:s}=e(n,r);return s?aw(o):{feasible:!0}}var cw=["bug","bugfix","defect","hotfix","incident"],uw=["chore","task","maintenance","spike","tech debt","infrastructure"];function qd(e,t){return new RegExp(`\\b${t}\\b`).test(e)}function $e(e){if(!e)return"feat";let t=e.toLowerCase().trim();return t?cw.some(r=>qd(t,r))?"fix":uw.some(r=>qd(t,r))?"chore":"feat":"feat"}function co(e){return e.startsWith("epic/")||e.startsWith("milestone/")}function xt(e){let{config:t,ticket:r,targetBranch:n,verificationWarning:o}=e,{singleChildParent:s,epicContext:i}=e,c=n?co(n):!1;return[...lw(i,c),...pw({config:t,ticket:r,isEpic:c,singleChildParent:s}),"",...fw(r.description),...dw(o),...hw()].join(`
|
|
71
|
+
`)}function tl(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"?gw(t,n):[];return[`## ${t} \u2014 ${r}`,"","### Children","",...s,...i,"","---","*Created by [Clancy](https://github.com/Pushedskydiver/chief-clancy)*"].join(`
|
|
72
|
+
`)}function lw(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 pw(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 fw(e){return e?["## Description","",e,""]:[]}function dw(e){return e?["## \u26A0 Verification Warning","",e,"","This PR may need manual fixes before merging.",""]:[]}var mw=`---
|
|
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 hw(){return mw.split(`
|
|
86
|
+
`)}function gw(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 rl(e){let{exec:t,epicBranch:r,baseBranch:n}=e,o=ku(t,r),s=_t(t,r);return o?wt(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}`}:bw(t,r,n)}function nl(e){let{progressFs:t,projectRoot:r,parent:n,targetBranch:o,ticketKey:s}=e;if(!n||!co(o))return;let i=[...Le].flatMap(c=>H(t,r,c)).filter(c=>c.parent===n&&c.key!==s);return{parentKey:n,siblingsDelivered:i.length,epicBranch:o}}function ol(e){let{progressFs:t,projectRoot:r,epicKey:n}=e;return[...Le].flatMap(o=>H(t,r,o)).filter(o=>o.parent===n)}function bw(e,t,r){try{return e(["fetch","origin",r]),e(["checkout","-b",t,`origin/${r}`]),Me(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 Ie(e){let{env:t,remote:r}=e,n=sr(t,r);if(!n)return;let o=rr(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 yw(s,r);case"gitlab":return kw(s,r);case"bitbucket":return _w(s,r);case"bitbucket-server":return ww(s,r);case"azure":return xw(s,r);default:return}}function uo(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 yw(e,t){return Ju({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 kw(e,t){return Vu({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 _w(e,t){let{username:r}=e.creds;if(!r)throw new Error("Bitbucket Cloud requires a username");return Au({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 ww(e,t){return Bu({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 xw(e,t){return Ru({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 ar(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:uo(r,n,o)}:{type:"not_attempted",manualUrl:uo(r,n,o)}}function cr(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 sl(e){let{exec:t,ticketBranch:r,targetBranch:n}=e;if(!Me(t,r))return Sw(e);let s=ee(t,e.config.env.CLANCY_GIT_PLATFORM),i=await vw(e,s),c=ar({pr:i,remote:s,sourceBranch:r,targetBranch:n});return Pw(e,c),Kd(t,n),{pushed:!0,outcome:c,prResult:i}}function Sw(e){let{exec:t,progressFs:r,projectRoot:n,ticket:o,targetBranch:s}=e,{skipLog:i=!1,parent:c}=e;return i||te(r,n,{key:o.key,summary:o.title,status:"PUSH_FAILED",parent:c}),Kd(t,s),{pushed:!1,outcome:{type:"local"}}}async function vw(e,t){let{fetchFn:r,config:n,ticket:o,ticketBranch:s,targetBranch:i}=e,u=`${$e(o.ticketType)}(${o.key}): ${o.title}`,l=$w(e),p=xt({config:n,ticket:{key:o.key,title:o.title,description:o.description,provider:n.provider},targetBranch:i,verificationWarning:Iw(e),singleChildParent:e.singleChildParent,epicContext:l});return Ie({fetchFn:r,env:n.env,remote:t,sourceBranch:s,targetBranch:i,title:u,body:p})}function $w(e){return nl({progressFs:e.progressFs,projectRoot:e.projectRoot,parent:e.parent,targetBranch:e.targetBranch,ticketKey:e.ticket.key})}function Iw(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 Pw(e,t){if(e.skipLog)return;let{status:r,prNumber:n}=cr(t);te(e.progressFs,e.projectRoot,{key:e.ticket.key,summary:e.ticket.title,status:r,prNumber:n,parent:e.parent})}function Kd(e,t){try{se(e,t)}catch{}}async function il(e){let{exec:t,config:r,epicKey:n,epicBranch:o,baseBranch:s}=e,i=ol({progressFs:e.progressFs,projectRoot:e.projectRoot,epicKey:n}),c=ee(t,r.env.CLANCY_GIT_PLATFORM),u=await Rw(e,c,i),l=ar({pr:u,remote:c,sourceBranch:o,targetBranch:s});return Cw(e,l),Tw(l)}async function Rw(e,t,r){let{fetchFn:n,config:o,epicKey:s,epicTitle:i,epicBranch:c,baseBranch:u}=e,p=`${$e(e.ticketType)}(${s}): ${i}`,d=tl({epicKey:s,epicTitle:i,childEntries:r,provider:o.provider});return Ie({fetchFn:n,env:o.env,remote:t,sourceBranch:c,targetBranch:u,title:p,body:d})}function Cw(e,t){let{status:r,prNumber:n}=cr(t),o=r==="PR_CREATED"?"EPIC_PR_CREATED":r;te(e.progressFs,e.projectRoot,{key:e.epicKey,summary:e.epicTitle,status:o,prNumber:n})}function Tw(e){return{ok:e.type==="created"||e.type==="exists",outcome:e}}import{join as cl}from"node:path";var Hd=".clancy",Ew="quality.json",Wd=`${Hd}/${Ew}`,Jd={totalTickets:0,avgReworkCycles:0,avgVerificationRetries:0,avgDuration:0};function zw(){return{tickets:{},summary:Jd}}function al(e){return Math.round(e*100)/100}function lo(e,t,r=0){return r>=e.length?0:t(e[r])+lo(e,t,r+1)}function Aw(e){return e!==null&&typeof e=="object"&&"reworkCycles"in e&&"verificationRetries"in e&&Number.isFinite(e.reworkCycles)&&Number.isFinite(e.verificationRetries)}function Nw(e){return e!==null&&typeof e=="object"&&"tickets"in e&&typeof e.tickets=="object"&&e.tickets!==null&&!Array.isArray(e.tickets)}function ul(e){let t=Object.values(e),r=t.length;if(r===0)return Jd;let n=t.filter(o=>o.duration!=null);return{totalTickets:r,avgReworkCycles:al(lo(t,o=>o.reworkCycles)/r),avgVerificationRetries:al(lo(t,o=>o.verificationRetries)/r),avgDuration:n.length>0?al(lo(n,o=>o.duration)/n.length):0}}function Vd(e,t,r){let n=cl(t,Wd),o=`${n}.tmp`;e.mkdir(cl(t,Hd)),e.writeFile(o,JSON.stringify(r,null,2)+`
|
|
87
|
+
`),e.rename(o,n)}function Yd(e,t){let r=e[t];if(r)return[r,e];let n={reworkCycles:0,verificationRetries:0};return[n,{...e,[t]:n}]}function ll(e,t){try{let r=JSON.parse(e.readFile(cl(t,Wd)));if(Nw(r)){let n=r.tickets,o=Object.fromEntries(Object.entries(n).filter(([,s])=>Aw(s)));return{tickets:o,summary:ul(o)}}}catch{}return zw()}function pl(e,t,r){try{let n=ll(e,t),[o,s]=Yd(n.tickets,r),i={...s,[r]:{...o,reworkCycles:o.reworkCycles+1}};Vd(e,t,{tickets:i,summary:ul(i)})}catch{}}function fl(e,t,r){try{let n=ll(e,t),[o,s]=Yd(n.tickets,r.ticketKey),i={...s,[r.ticketKey]:{...o,deliveredAt:new Date(r.now).toISOString(),duration:Math.max(0,r.duration)}};Vd(e,t,{tickets:i,summary:ul(i)})}catch{}}function dl(e,t){let r=ll(e,t);return Object.keys(r.tickets).length===0?void 0:r}import{join as Gd}from"node:path";var Qd=".clancy",Lw="costs.log",jw=6600,Bw=6e4;function ml(e,t,r){let{ticketKey:n,startedAt:o,now:s,tokenRate:i=jw}=r,c=new Date(o).getTime(),u=Number.isNaN(c)?0:Math.max(0,s-c),l=Math.round(u/Bw),p=Math.round(l*i),h=`${new Date(s).toISOString()} | ${n} | ${l}min | ~${p} tokens (estimated)
|
|
88
|
+
`;e.mkdir(Gd(t,Qd)),e.appendFile(Gd(t,Qd,Lw),h)}function ue(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 Ow=[{provider:"jira",label:"Jira",detect:e=>!!e.JIRA_BASE_URL,schema:yn},{provider:"github",label:"GitHub",detect:e=>!!(e.GITHUB_TOKEN&&e.GITHUB_REPO),schema:kn},{provider:"linear",label:"Linear",detect:e=>!!e.LINEAR_API_KEY,schema:_n},{provider:"shortcut",label:"Shortcut",detect:e=>!!e.SHORTCUT_API_TOKEN,schema:wn},{provider:"notion",label:"Notion",detect:e=>!!e.NOTION_DATABASE_ID,schema:xn},{provider:"azdo",label:"Azure DevOps",detect:e=>!!e.AZDO_ORG,schema:Sn}];function po(e){let t=Ow.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 Xd(e){return`Basic ${btoa(`:${e}`)}`}function Pe(e){return{Authorization:Xd(e),"Content-Type":"application/json"}}function em(e){return{Authorization:Xd(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 Re(e,t){return`https://dev.azure.com/${encodeURIComponent(e)}/${encodeURIComponent(t)}/_apis`}function ur(e){return e?e.split(";").map(t=>t.trim()).filter(Boolean):[]}function hl(e){return e.join("; ")}function lr(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 Ce(e){let t=parseInt(e.replace("azdo-",""),10);return Number.isNaN(t)?void 0:t}async function gl(e){let t=`https://dev.azure.com/${encodeURIComponent(e.org)}/_apis/projects/${encodeURIComponent(e.project)}?api-version=${"7.1"}`;return Q({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 fo(e,t){let r=await S(`${Re(e.org,e.project)}/wit/wiql?api-version=${"7.1"}`,{method:"POST",headers:Pe(e.pat),body:JSON.stringify({query:t})},{schema:vn,label:"Azure DevOps WIQL",fetcher:e.fetcher});return r?r.workItems.map(n=>n.id):[]}async function pr(e,t){return S(`${Re(e.org,e.project)}/wit/workitems/${String(t)}?$expand=relations&api-version=${"7.1"}`,{headers:Pe(e.pat)},{schema:Qt,label:"Azure DevOps work item",fetcher:e.fetcher})}async function fr(e){let{ctx:t,id:r,patchOps:n}=e,o=t.fetcher??fetch;try{return(await o(`${Re(t.org,t.project)}/wit/workitems/${String(r)}?api-version=${"7.1"}`,{method:"PATCH",headers:em(t.pat),body:JSON.stringify(n)})).ok}catch{return!1}}var Dw=200;function Fw(e,t){return Array.from({length:Math.ceil(e.length/t)},(r,n)=>e.slice(n*t,n*t+t))}async function Mw(e,t){let r=t.join(","),n=await S(`${Re(e.org,e.project)}/wit/workitems?ids=${r}&$expand=relations&api-version=${"7.1"}`,{headers:Pe(e.pat)},{schema:$n,label:"Azure DevOps work items batch",fetcher:e.fetcher});return n?n.value:[]}async function St(e,t){if(!t.length)return[];let r=Fw(t,Dw);return(await Promise.all(r.map(o=>Mw(e,o)))).flat()}function Uw(e){let t=ur(e.fields["System.Tags"]),r=(e.relations??[]).find(o=>o.rel==="System.LinkTypes.Hierarchy-Reverse"),n=r?lr(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 qw(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 bl(e){let{ctx:t,excludeHitl:r,label:n,limit:o=5}=e,s=qw(e);if(!s)return[];let i=await fo(t,s);if(!i.length)return[];let c=i.slice(0,o*2),l=(await St(t,c)).map(Uw),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 tm(e,t){let r=await pr(e,t);return r?ur(r.fields["System.Tags"]):void 0}async function rm(e,t,r){await fr({ctx:e,id:t,patchOps:[{op:"replace",path:"/fields/System.Tags",value:hl(r)}]})}async function yl(e,t,r){await C(async()=>{let n=Ce(t);n!==void 0&&await Z({fetchCurrent:()=>tm(e,n),writeUpdated:o=>rm(e,n,o),target:r,mode:"add"})},"addLabel")}async function kl(e,t,r){await C(async()=>{let n=Ce(t);n!==void 0&&await Z({fetchCurrent:()=>tm(e,n),writeUpdated:o=>rm(e,n,o),target:r,mode:"remove"})},"removeLabel")}var Kw=new Set(["Done","Closed","Completed","Resolved"]);function nm(e){let t=e.fields["System.State"];return!t||!Kw.has(t)}function om(e){return{total:e.length,incomplete:e.filter(nm).length}}async function dr(e,t){try{let r=await pr(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=>lr(i.url)).filter(i=>i!==void 0);return o.length?(await St(e,o)).some(nm):!1}catch{return!1}}async function mr(e){let{ctx:t,parentId:r,parentKey:n}=e;try{if(n){let o=`Epic: ${n}`,s=await Hw(t,o);if(s&&s.total>0)return s}return await Ww(t,r)}catch{return}}async function Hw(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 fo(e,r);if(!n.length)return{total:0,incomplete:0};let o=await St(e,n);return om(o)}async function Ww(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(`${Re(e.org,e.project)}/wit/wiql?api-version=${"7.1"}`,{method:"POST",headers:Pe(e.pat),body:JSON.stringify({query:r})},{schema:In,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 St(e,s);return om(i)}function Jw(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 Vw(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 Yw(e,t,r){let n=r.CLANCY_AZDO_STATUS??"New";return(await bl({ctx:e,status:n,wit:r.CLANCY_AZDO_WIT,excludeHitl:t.excludeHitl,label:t.buildLabel??r.CLANCY_LABEL})).map(s=>Jw(s,n))}async function Gw(e,t,r){let n=Ce(t.key);if(n===void 0)return!1;let o=await fr({ctx:e,id:n,patchOps:[{op:"replace",path:"/fields/System.State",value:r}]});return o&&console.log(` \u2192 Transitioned to ${r}`),o}function mo(e,t){let r={org:e.AZDO_ORG,project:e.AZDO_PROJECT,pat:e.AZDO_PAT,fetcher:t},n=o=>Yw(r,o,e);return{ping:()=>gl(r),validateInputs:()=>Vw(e),fetchTicket:async o=>(await n(o))[0],fetchTickets:n,fetchBlockerStatus(o){let s=Ce(o.key);return s!==void 0?dr(r,s):Promise.resolve(!1)},fetchChildrenStatus(o,s){let i=Ce(s??o);return i===void 0?Promise.resolve(void 0):mr({ctx:r,parentId:i,parentKey:o})},transitionTicket:(o,s)=>Gw(r,o,s),ensureLabel:async()=>{},addLabel:(o,s)=>yl(r,o,s),removeLabel:(o,s)=>kl(r,o,s),sharedEnv:()=>e}}function _l(e){return e instanceof Error?e.message:String(e)}async function ho(e,t){try{let r=E(e.token),n=e.fetcher??fetch,o=`${T}/repos/${e.repo}/labels/${encodeURIComponent(t)}`,s=await n(o,{headers:r});if(s.ok)return;s.status===404?await Qw(e,t,r):console.warn(`\u26A0 ensureLabel GET returned HTTP ${s.status}`)}catch(r){console.warn(`\u26A0 ensureLabel failed: ${_l(r)}`)}}async function Qw(e,t,r){let o=await(e.fetcher??fetch)(`${T}/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 wl(e,t,r){try{let n=E(e.token),s=await(e.fetcher??fetch)(`${T}/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: ${_l(n)}`)}}async function xl(e,t,r){try{let n=E(e.token),o=e.fetcher??fetch,s=`${T}/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: ${_l(n)}`)}}var Xw=a.object({state:a.optional(a.string())}),sm=a.object({total_count:a.optional(a.number())});async function ex(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(`${T}/repos/${r}/issues/${c}`,{headers:t});if(!u.ok)return!1;let l=Xw.safeParse(await u.json());return l.success&&l.data.state!=="closed"}))).some(Boolean)}async function hr(e){let{token:t,repo:r,issueNumber:n,body:o,fetcher:s}=e;if(!ve(r))return!1;let i=tx(o,n);if(i.length===0)return!1;try{let c=E(t);return await ex({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 tx(e,t){return[...e.matchAll(/Blocked by #(\d+)/gi)].map(r=>parseInt(r[1],10)).filter(r=>!Number.isNaN(r)&&r!==t)}async function rx(e){let{token:t,repo:r,parentNumber:n,fetcher:o}=e,s={token:t,repo:r,fetcher:o},i=await im({...s,bodyRef:`Epic: #${n}`});if(i&&i.total>0)return{epic:i,parent:void 0};let c=await im({...s,bodyRef:`Parent: #${n}`});return{epic:i,parent:c}}async function gr(e){let{token:t,repo:r,parentNumber:n,currentTicketKey:o,fetcher:s}=e;if(ve(r))try{let{epic:i,parent:c}=await rx({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 im(e){let{token:t,repo:r,bodyRef:n,fetcher:o}=e,s=E(t),i=o??fetch,c=`"${n}" repo:${r} is:issue`,u=new URLSearchParams({q:c,per_page:"1"}),l=await i(`${T}/search/issues?${u}`,{headers:s});if(!l.ok)return;let p=sm.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`,g=new URLSearchParams({q:h,per_page:"1"}),_=await i(`${T}/search/issues?${g}`,{headers:s});if(!_.ok)return;let w=sm.safeParse(await _.json());return{total:d,incomplete:w.success?w.data.total_count??0:d}}var nx=/^(?:Epic|Parent): (#\d+)/m;function ox(e){return e.match(nx)?.[1]}function go(e){let t=parseInt(e.replace("#",""),10);return Number.isNaN(t)?void 0:t}function sx(e){return{key:e.key,title:e.title,description:e.description,parentInfo:e.milestone??ox(e.description)??"none",blockers:"None",issueId:e.key,labels:e.labels??[],status:"open"}}async function ix(e,t){let r=await Mu(e.token,e.usernameCache,e.fetcher);return(await Uu({token:e.token,repo:e.repo,label:t.buildLabel??e.defaultLabel,username:r,excludeHitl:t.excludeHitl,fetcher:e.fetcher})).map(sx)}function bo(e,t){let r={token:e.GITHUB_TOKEN,repo:e.GITHUB_REPO,defaultLabel:e.CLANCY_LABEL,usernameCache:new le,fetcher:t},n=o=>ix(r,o);return{ping:()=>Fu(r.token,r.repo,r.fetcher),validateInputs:()=>ve(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=go(o.key),i={token:r.token,repo:r.repo,fetcher:r.fetcher};return s?hr({...i,issueNumber:s,body:o.description}):!1},async fetchChildrenStatus(o,s,i){let c=go(o),u={token:r.token,repo:r.repo,fetcher:r.fetcher};return c?gr({...u,parentNumber:c,currentTicketKey:i}):void 0},transitionTicket:async()=>!1,ensureLabel:o=>ho(r,o),async addLabel(o,s){await ho(r,s);let i=go(o);i&&await wl(r,i,s)},async removeLabel(o,s){let i=go(o);i&&await xl(r,i,s)},sharedEnv:()=>e}}var ax=/^[a-zA-Z0-9 _\-'.:]+$/,cx=/^[A-Z][A-Z0-9]+-\d+$/;function vl(e,t){return Buffer.from(`${e}:${t}`).toString("base64")}function re(e){return{Authorization:`Basic ${e}`,Accept:"application/json"}}function vt(e){return ax.test(e)}function Ee(e){return cx.test(e)}async function $l(e){let{baseUrl:t,projectKey:r,auth:n,fetcher:o}=e;return Q({url:`${t}/rest/api/3/project/${r}`,headers:re(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 ux(e){let{projectKey:t,status:r,sprint:n,label:o,excludeHitl:s}=e,c=[t,r,...o?[o]:[]].find(l=>!vt(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 lx(e){return!e||typeof e!="object"?"":Sl(e).join(" ")}function Sl(e){return typeof e=="string"?[e]:Array.isArray(e)?e.flatMap(Sl):e&&typeof e=="object"?Object.values(e).flatMap(Sl):[]}async function Il(e){let{baseUrl:t,auth:r,projectKey:n,status:o}=e,{sprint:s,label:i,excludeHitl:c,limit:u=5,fetcher:l}=e,p=ux({projectKey:n,status:o,sprint:s,label:i,excludeHitl:c}),d=await S(`${t}/rest/api/3/search/jql`,{method:"POST",headers:{...re(r),"Content-Type":"application/json"},body:JSON.stringify({jql:p,maxResults:u,fields:["summary","description","issuelinks","parent","customfield_10014","labels"]})},{schema:zn,label:"Jira API",fetcher:l});return d?d.issues.map(fx):[]}function px(e){return(e??[]).filter(t=>t.type?.name==="Blocks"&&t.inwardIssue?.key).map(t=>t.inwardIssue?.key).filter(t=>!!t)}function fx(e){let{fields:t}=e;return{key:e.key,title:t.summary,description:lx(t.description),provider:"jira",epicKey:t.parent?.key??t.customfield_10014??void 0,blockers:px(t.issuelinks),labels:t.labels}}async function dx(e){let{baseUrl:t,auth:r,issueKey:n,statusName:o}=e;return Ee(n)?(await S(`${t}/rest/api/3/issue/${n}/transitions`,{headers:re(r)},{schema:An,label:"Jira transitions",fetcher:e.fetcher}))?.transitions.find(i=>i.name===o)?.id:void 0}async function Pl(e){let{baseUrl:t,auth:r,issueKey:n,statusName:o,fetcher:s}=e;try{let i=await dx(e);return i?(await(s??fetch)(`${t}/rest/api/3/issue/${n}/transitions`,{method:"POST",headers:{...re(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 am(e,t){let n=await(e.fetcher??fetch)(`${e.baseUrl}/rest/api/3/issue/${encodeURIComponent(t)}?fields=labels`,{headers:re(e.auth)});if(!n.ok){console.warn(`\u26A0 label GET ${t} failed: HTTP ${n.status}`);return}let o=Ln.safeParse(await n.json());if(o.success)return o.data.fields?.labels??[]}async function cm(e,t,r){let o=await(e.fetcher??fetch)(`${e.baseUrl}/rest/api/3/issue/${encodeURIComponent(t)}`,{method:"PUT",headers:{...re(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 Rl(e,t,r){await C(async()=>{Ee(t)&&await Z({fetchCurrent:()=>am(e,t),writeUpdated:n=>cm(e,t,n),target:r,mode:"add"})},"addLabel")}async function Cl(e,t,r){await C(async()=>{Ee(t)&&await Z({fetchCurrent:()=>am(e,t),writeUpdated:n=>cm(e,t,n),target:r,mode:"remove"})},"removeLabel")}var um=a.object({total:a.optional(a.number())});async function br(e){let{baseUrl:t,auth:r,key:n,fetcher:o}=e;if(!Ee(n))return!1;let s=o??fetch;try{let i=await s(`${t}/rest/api/3/issue/${n}?fields=issuelinks`,{headers:re(r)});if(!i.ok)return!1;let c=await i.json(),u=Nn.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 yr(e){let{baseUrl:t,auth:r,parentKey:n,fetcher:o}=e;if(Ee(n))try{let s=n.split("-")[0],i={baseUrl:t,auth:r,fetcher:o},c=await lm({...i,jql:`project = "${s}" AND description ~ "Epic: ${n}"`});return c&&c.total>0?c:await lm({...i,jql:`parent = ${n}`})}catch(s){console.warn(`\u26A0 fetchChildrenStatus failed: ${s instanceof Error?s.message:String(s)}`);return}}async function lm(e){let{baseUrl:t,auth:r,jql:n,fetcher:o}=e,s={...re(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=um.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=um.safeParse(await p.json());return{total:l,incomplete:d.success?d.data.total??0:l}}function mx(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 hx(e){if(!vt(e.JIRA_PROJECT_KEY))return"\u2717 JIRA_PROJECT_KEY contains invalid characters";if(e.CLANCY_LABEL&&!vt(e.CLANCY_LABEL))return"\u2717 CLANCY_LABEL contains invalid characters";if(e.CLANCY_JQL_STATUS&&!vt(e.CLANCY_JQL_STATUS))return"\u2717 CLANCY_JQL_STATUS contains invalid characters"}async function gx(e,t,r){return(await Il({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=>mx(o,e.statusName))}async function bx(e,t,r){let n=await Pl({baseUrl:e.baseUrl,auth:e.auth,issueKey:t.key,statusName:r,fetcher:e.fetcher});return n&&console.log(` \u2192 Transitioned to ${r}`),n}function yo(e,t){let r={baseUrl:e.JIRA_BASE_URL,auth:vl(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=>gx(r,s,e);return{ping:()=>$l({baseUrl:r.baseUrl,projectKey:r.projectKey,auth:r.auth,fetcher:r.fetcher}),validateInputs:()=>hx(e),fetchTicket:async s=>(await o(s))[0],fetchTickets:o,fetchBlockerStatus:s=>br({baseUrl:r.baseUrl,auth:r.auth,key:s.key,fetcher:r.fetcher}),fetchChildrenStatus:s=>yr({baseUrl:r.baseUrl,auth:r.auth,parentKey:s,fetcher:r.fetcher}),transitionTicket:(s,i)=>bx(r,s,i),ensureLabel:async()=>{},addLabel:(s,i)=>Rl(n,s,i),removeLabel:(s,i)=>Cl(n,s,i),sharedEnv:()=>e}}var pm="https://api.linear.app/graphql",yx=/^[a-zA-Z0-9_-]+$/;function kx(e){return{Authorization:e,"Content-Type":"application/json"}}function ko(e){return yx.test(e)}function fm(e,t,r){return{method:"POST",headers:kx(e),body:JSON.stringify({query:t,variables:r})}}async function U(e){let{apiKey:t,query:r,variables:n,fetcher:o}=e,i=await(o??fetch)(pm,fm(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 _x(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 Tl(e,t){let r=await(t??fetch)(pm,fm(e,"{ viewer { id } }")).catch(()=>{});if(!r)return{ok:!1,error:"\u2717 Could not reach Linear \u2014 check network"};if(!r.ok)return _x(r.status);try{let n=await r.json(),o=Bn.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 wx(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 xx(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 Sx(e){return e.labels?.nodes?.some(t=>t.name==="clancy:hitl")===!0}async function El(e){if(!ko(e.teamId))return[];let{apiKey:t,excludeHitl:r,limit:n=5}=e,{query:o,variables:s}=xx(e),i=await U({apiKey:t,query:o,variables:s,fetcher:e.fetcher}),c=jn.safeParse(i);if(!c.success)return[];let u=c.data.data?.viewer?.assignedIssues?.nodes??[];return(r?u.filter(p=>!Sx(p)):u).slice(0,n).map(wx)}async function vx(e){let{apiKey:t,teamId:r,label:n,fetcher:o}=e,i=await U({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=Un.safeParse(i);return c.success?c.data.data?.team?.labels?.nodes?.[0]?.id:void 0}async function $x(e){let{apiKey:t,label:r,fetcher:n}=e,s=await U({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=qn.safeParse(s);return i.success?i.data.data?.issueLabels?.nodes?.[0]?.id:void 0}async function Ix(e){let{apiKey:t,teamId:r,label:n,fetcher:o}=e,i=await U({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=Kn.safeParse(i);return c.success?c.data.data?.issueLabelCreate?.issueLabel?.id:void 0}async function _o(e){let{apiKey:t,teamId:r,labelCache:n,label:o,fetcher:s}=e,i={apiKey:t,teamId:r,label:o,fetcher:s};await C(async()=>{if(n.has(o))return;let c=await vx(i);if(c){n.store(o,c);return}let u=await $x(i);if(u){n.store(o,u);return}let l=await Ix(i);l&&n.store(o,l)},"ensureLabel")}async function zl(e){let{apiKey:t,labelCache:r,issueKey:n,label:o,fetcher:s}=e;await C(async()=>{let i=r.get(o);if(!i)return;let c=await dm(t,n,s);if(!c)return;let u=c.labelIds;u.includes(i)||await mm({apiKey:t,issueId:c.id,labelIds:[...u,i],fetcher:s})},"addLabel")}async function Al(e){let{apiKey:t,labelCache:r,issueKey:n,label:o,fetcher:s}=e;await C(async()=>{let i=await dm(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 mm({apiKey:t,issueId:i.id,labelIds:p,fetcher:s})},"removeLabel")}async function dm(e,t,r){let o=await U({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=Hn.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 mm(e){let{apiKey:t,issueId:r,labelIds:n,fetcher:o}=e;await U({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 hm=new Set(["completed","canceled"]);async function kr(e,t,r){let o=await U({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=Dn.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?!hm.has(u):!1}):!1}async function _r(e){let{apiKey:t,parentId:r,parentIdentifier:n,fetcher:o}=e;try{if(n){let s=await Px(t,`Epic: ${n}`,o);if(s&&s.total>0)return s}return await Rx(t,r,o)}catch{return}}function gm(e){let t=e.length,r=e.filter(n=>!n.state?.type||!hm.has(n.state.type)).length;return{total:t,incomplete:r}}async function Px(e,t,r){let o=await U({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=Fn.safeParse(o);if(!s.success)return;let i=s.data.data?.issueSearch?.nodes??[];return gm(i)}async function Rx(e,t,r){let o=await U({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=Mn.safeParse(o);if(!s.success)return;let i=s.data.data?.issue?.children?.nodes??[];return gm(i)}async function Cx(e){let{apiKey:t,teamId:r,stateName:n,fetcher:o}=e,i=await U({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=On.safeParse(i);if(c.success)return c.data.data?.workflowStates?.nodes?.[0]?.id}async function Nl(e){let{apiKey:t,teamId:r,issueId:n,stateName:o,fetcher:s}=e;try{let i=await Cx({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 U({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=Zn.safeParse(u);return l.success?l.data.data?.issueUpdate?.success===!0:!1}catch{return!1}}function Tx(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 Ex(e,t){return(await El({apiKey:e.apiKey,teamId:e.teamId,label:t.buildLabel??e.defaultLabel,excludeHitl:t.excludeHitl,fetcher:e.fetcher})).map(Tx)}async function zx(e,t,r){if(!t.linearIssueId)return!1;let n=await Nl({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 Ax(e,t,r){await _o({apiKey:e.apiKey,teamId:e.teamId,labelCache:e.labelCache,label:r,fetcher:e.fetcher}),await zl({apiKey:e.apiKey,labelCache:e.labelCache,issueKey:t,label:r,fetcher:e.fetcher})}function wo(e,t){let r={apiKey:e.LINEAR_API_KEY,teamId:e.LINEAR_TEAM_ID,defaultLabel:e.CLANCY_LABEL,labelCache:new Ke,fetcher:t},n=o=>Ex(r,o);return{ping:()=>Tl(r.apiKey,r.fetcher),validateInputs:()=>ko(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?kr(r.apiKey,o.issueId,r.fetcher):!1},fetchChildrenStatus:(o,s)=>_r({apiKey:r.apiKey,parentId:s??o,parentIdentifier:o,fetcher:r.fetcher}),transitionTicket:(o,s)=>zx(r,o,s),ensureLabel:o=>_o({apiKey:r.apiKey,teamId:r.teamId,labelCache:r.labelCache,label:o,fetcher:r.fetcher}),addLabel:(o,s)=>Ax(r,o,s),removeLabel:(o,s)=>Al({apiKey:r.apiKey,labelCache:r.labelCache,issueKey:o,label:s,fetcher:r.fetcher}),sharedEnv:()=>e}}var wr="https://api.notion.com/v1",Nx="2022-06-28";function xr(e){return{Authorization:`Bearer ${e}`,"Notion-Version":Nx,"Content-Type":"application/json"}}function xo(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 fe(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 So(e){return`notion-${e.replace(/-/g,"").slice(0,8)}`}var Lx=new Set(["done","complete","completed","closed"]);function vo(e){return Lx.has(e.toLowerCase())}function $t(e){return["Description","description","Body","body"].map(r=>xo(e,r,"rich_text")).find(Boolean)}function Ll(e){let t=Object.entries(e.properties).find(([,r])=>r.type==="title");return t?xo(e,t[0],"title")??"":""}function $o(e,t){return xo(e,t,"status")??xo(e,t,"select")}function jl(e,t){let r=$o(e,t);return!r||!vo(r)}function Bl(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 Ol(e,t){return Q({url:`${wr}/users/me`,headers:xr(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 It(e){let{ctx:t,filter:r,sorts:n,startCursor:o}=e,s={...r?{filter:r}:{},...n?{sorts:n}:{},...o?{start_cursor:o}:{}};return S(`${wr}/databases/${t.databaseId}/query`,{method:"POST",headers:xr(t.token),body:JSON.stringify(s)},{schema:Wn,label:"Notion API",fetcher:t.fetcher??Ne})}var jx=10;async function Sr(e){return bm(e,void 0,[])}async function bm(e,t,r){let n=await It({...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)<jx;return s&&i?bm(e,s,o):o}async function Io(e,t,r){return S(`${wr}/pages/${t}`,{headers:xr(e)},{schema:Xt,label:"Notion page",fetcher:r??Ne})}async function Pt(e){let{token:t,pageId:r,properties:n,fetcher:o}=e,s=o??Ne;try{return(await s(`${wr}/pages/${r}`,{method:"PATCH",headers:xr(t),body:JSON.stringify({properties:n})})).ok}catch{return!1}}async function Rt(e,t){let r=t.replace("notion-","");return r?(await Sr({ctx:e})).find(o=>o.id.replace(/-/g,"").slice(0,8)===r):void 0}async function ym(e,t){await Pt({token:e.ctx.token,pageId:e.pageId,properties:{[e.labelsProp]:{multi_select:t.map(r=>({name:r}))}},fetcher:e.ctx.fetcher})}async function Zl(e){let{ctx:t,issueKey:r,label:n,labelsProp:o}=e;await C(async()=>{let s=await Rt(t,r);s&&await Z({fetchCurrent:()=>Promise.resolve(fe(s,o,"multi_select")??[]),writeUpdated:i=>ym({ctx:t,pageId:s.id,labelsProp:o},i),target:n,mode:"add"})},"addLabel")}async function Dl(e){let{ctx:t,issueKey:r,label:n,labelsProp:o}=e;await C(async()=>{let s=await Rt(t,r);s&&await Z({fetchCurrent:()=>Promise.resolve(fe(s,o,"multi_select")??[]),writeUpdated:i=>ym({ctx:t,pageId:s.id,labelsProp:o},i),target:n,mode:"remove"})},"removeLabel")}function km(e,t){let r=$o(e,t);return r!==void 0&&!vo(r)}async function vr(e){let{ctx:t,pageId:r,statusProp:n}=e;try{let o=await Io(t.token,r,t.fetcher);if(!o)return!1;let s=await Bx(t,o,n);return s!==void 0?s:Ox({ctx:t,page:o,pageId:r,statusProp:n})}catch{return!1}}async function Bx(e,t,r){let n=Bl(t,"Blocked by");if(n?.type!=="relation")return;let o=n.relation;return o.length?(await Promise.all(o.map(i=>Io(e.token,i.id,e.fetcher)))).some(i=>!!i&&km(i,r)):!1}async function Ox(e){let{ctx:t,page:r,pageId:n,statusProp:o}=e,s=$t(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 Sr({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(g=>g.id.replace(/-/g,"").slice(0,8)===d);return h!=null&&km(h,o)};return i.some(l)}async function $r(e){let{ctx:t,parentKey:r,parentProp:n,statusProp:o}=e;try{let s=`Epic: ${r}`,i=await Zx(t,s,o);if(i&&i.total>0)return i;let c=await Rt(t,r);return c?await Dx({ctx:t,parentPageId:c.id,parentProp:n,statusProp:o}):void 0}catch{return}}async function Zx(e,t,r){let n=await Sr({ctx:e});if(!n.length)return;let o=n.filter(s=>$t(s)?.includes(t));return _m(o,r)}async function Dx(e){let{ctx:t,parentPageId:r,parentProp:n,statusProp:o}=e,s=await It({ctx:t,filter:{property:n,relation:{contains:r}}});if(s)return _m([...s.results],o)}function _m(e,t){return{total:e.length,incomplete:e.filter(r=>jl(r,t)).length}}var Po={status:"Status",labels:"Labels",parent:"Epic",todo:"To-do"},Fx=/^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;function Mx(e,t){let r=fe(e,t.parentProp,"relation"),o=r&&r.length>0?So(r[0]):"none";return{key:So(e.id),title:Ll(e),description:$t(e)??"",parentInfo:o,blockers:"None",issueId:e.id,labels:fe(e,t.labelsProp,"multi_select")??[],status:t.todoName}}async function Ux(e){let{ctx:t,fetchOpts:r,props:n,defaultLabel:o}=e,s={property:n.statusProp,status:{equals:n.todoName}},i=await It({ctx:t,filter:s});if(!i)return[];let c=r.excludeHitl?i.results.filter(p=>!fe(p,n.labelsProp,"multi_select")?.includes("clancy:hitl")):[...i.results],u=r.buildLabel??o;return(u?c.filter(p=>fe(p,n.labelsProp,"multi_select")?.includes(u)):c).slice(0,5).map(p=>Mx(p,n))}async function qx(e){let{token:t,ticket:r,status:n,statusProp:o,fetcher:s}=e,i=r.issueId;if(!i)return!1;if(await Pt({token:t,pageId:i,properties:{[o]:{status:{name:n}}},fetcher:s}))return console.log(` \u2192 Transitioned to ${n}`),!0;let u=await Pt({token:t,pageId:i,properties:{[o]:{select:{name:n}}},fetcher:s});return u&&console.log(` \u2192 Transitioned to ${n}`),u}function Kx(e,t){return{token:e.token,statusProp:t.statusProp,fetcher:e.fetcher}}function Hx(e,t){return{token:e.NOTION_TOKEN,databaseId:e.NOTION_DATABASE_ID,fetcher:t}}function Wx(e){return{statusProp:e.CLANCY_NOTION_STATUS??Po.status,labelsProp:e.CLANCY_NOTION_LABELS??Po.labels,parentProp:e.CLANCY_NOTION_PARENT??Po.parent,todoName:e.CLANCY_NOTION_TODO??Po.todo}}function Ro(e,t){let r=Hx(e,t),n=Wx(e),o=Kx(r,n),s=i=>Ux({ctx:r,fetchOpts:i,props:n,defaultLabel:e.CLANCY_LABEL});return{ping:()=>Ol(r.token,r.fetcher),validateInputs(){if(!Fx.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?vr({ctx:r,pageId:i.issueId,statusProp:n.statusProp}):Promise.resolve(!1),fetchChildrenStatus:i=>$r({ctx:r,parentKey:i,parentProp:n.parentProp,statusProp:n.statusProp}),transitionTicket:(i,c)=>qx({...o,ticket:i,status:c}),ensureLabel:async()=>{},addLabel:(i,c)=>Zl({ctx:r,issueKey:i,label:c,labelsProp:n.labelsProp}),removeLabel:(i,c)=>Dl({ctx:r,issueKey:i,label:c,labelsProp:n.labelsProp}),sharedEnv:()=>e}}var A="https://api.app.shortcut.com/api/v3";function B(e){return{"Shortcut-Token":e,"Content-Type":"application/json"}}async function Fl(e,t){let r=B(e),n=t??fetch,o=await n(`${A}/member-info`,{headers:r}).then(async s=>s.ok?s:n(`${A}/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 wm(e,t,r){let n=t.get();if(n)return n;let o=await S(`${A}/workflows`,{headers:B(e)},{schema:Jn,label:"Shortcut workflows",fetcher:r});return o&&t.store(o),o??[]}async function Ml(e,t){let{token:r,cache:n,workflowName:o,fetcher:s}=t,i=await wm(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 Co(e,t){let{token:r,cache:n,workflowName:o,fetcher:s}=t;return(await wm(r,n,s)).flatMap(c=>o&&c.name!==o?[]:c.states.filter(u=>u.type===e).map(u=>u.id))}async function Ir(e,t){let r=await Co("done",{token:e,cache:t});return new Set(r)}function Jx(e){let t=De.safeParse(e);if(t.success)return t.data.data;if(Array.isArray(e)){let r=De.safeParse({data:e});if(r.success)return r.data.data}return[]}function Vx(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 Yx(e,t,r){let o=await(r??fetch)(`${A}/stories/search`,{method:"POST",headers:B(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?[]:Jx(s)}async function Ul(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 Yx(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(Vx)}async function ql(e){let{token:t,storyId:r,workflowStateId:n,fetcher:o}=e,s=o??fetch;try{return(await s(`${A}/stories/${String(r)}`,{method:"PUT",headers:B(t),body:JSON.stringify({workflow_state_id:n})})).ok}catch{return!1}}async function Kl(e){let{token:t,cache:r,refresh:n,fetcher:o}=e,s=r.get();if(s&&!n)return s;let i=await S(`${A}/labels`,{headers:B(t)},{schema:Vn,label:"Shortcut labels",fetcher:o});return i&&r.store(i),i??[]}async function Gx(e,t,r){return(await S(`${A}/labels`,{method:"POST",headers:B(e),body:JSON.stringify({name:t,color:"#0075ca"})},{schema:Yn,label:"Shortcut label create",fetcher:r}))?.id}async function xm(e,t,r){let n=await S(`${A}/stories/${String(t)}`,{headers:B(e)},{schema:Fe,label:"Shortcut story",fetcher:r});return n?n.label_ids??[]:void 0}async function Sm(e){let{token:t,storyId:r,labelIds:n,fetcher:o}=e,s=o??fetch;try{let i=await s(`${A}/stories/${String(r)}`,{method:"PUT",headers:B(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 To(e){let{token:t,labelCache:r,label:n,fetcher:o}=e;await C(async()=>{(await Kl({token:t,cache:r,fetcher:o})).find(c=>c.name===n)||(await Gx(t,n,o),await Kl({token:t,cache:r,refresh:!0,fetcher:o}))},"ensureLabel")}async function vm(e){let{token:t,labelCache:r,label:n,fetcher:o}=e;return(await Kl({token:t,cache:r,fetcher:o})).find(i=>i.name===n)?.id}function Ct(e){let t=parseInt(e.replace("sc-",""),10);return Number.isNaN(t)?void 0:t}async function Hl(e){let{token:t,labelCache:r,issueKey:n,label:o,fetcher:s}=e;await C(async()=>{let i=Ct(n);if(i===void 0)return;let c=await vm({token:t,labelCache:r,label:o,fetcher:s});c!==void 0&&await Z({fetchCurrent:()=>xm(t,i,s),writeUpdated:u=>Sm({token:t,storyId:i,labelIds:u,fetcher:s}),target:c,mode:"add"})},"addLabel")}async function Wl(e){let{token:t,labelCache:r,issueKey:n,label:o,fetcher:s}=e;await C(async()=>{let i=Ct(n);if(i===void 0)return;let c=await vm({token:t,labelCache:r,label:o,fetcher:s});c!==void 0&&await Z({fetchCurrent:()=>xm(t,i,s),writeUpdated:u=>Sm({token:t,storyId:i,labelIds:u,fetcher:s}),target:c,mode:"remove"})},"removeLabel")}async function Qx(e){let{token:t,blockerId:r,doneStateIds:n,fetcher:o}=e,s=await S(`${A}/stories/${String(r)}`,{headers:B(t)},{schema:Fe,label:"Shortcut blocker",fetcher:o});return s?s.workflow_state_id!==void 0&&!n.has(s.workflow_state_id):!1}async function Pr(e){let{token:t,storyId:r,workflowCache:n,fetcher:o}=e;try{let s=await S(`${A}/stories/${String(r)}`,{headers:B(t)},{schema:Fe,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 Ir(t,n);return(await Promise.all(i.map(l=>Qx({token:t,blockerId:l.object_id,doneStateIds:c,fetcher:o})))).some(Boolean)}catch{return!1}}async function Rr(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 Xx({...i,descriptionRef:`Epic: ${o}`});if(c&&c.total>0)return c}return await eS({...i,epicId:r})}catch{return}}function $m(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 Xx(e){let{token:t,workflowCache:r,fetcher:n,descriptionRef:o}=e,s=await S(`${A}/stories/search`,{method:"POST",headers:B(t),body:JSON.stringify({query:o})},{schema:De,label:"Shortcut story search",fetcher:n});if(!s)return;let i=s.data;if(!i.length)return{total:0,incomplete:0};let c=await Ir(t,r);return $m(i,c)}async function eS(e){let{token:t,workflowCache:r,fetcher:n,epicId:o}=e,s=await S(`${A}/epics/${String(o)}/stories`,{headers:B(t)},{schema:Gn,label:"Shortcut epic stories",fetcher:n});if(!s)return;if(!s.length)return{total:0,incomplete:0};let i=await Ir(t,r);return $m(s,i)}function tS(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 Im(e){return{token:e.token,cache:e.workflowCache,workflowName:e.workflowName,fetcher:e.fetcher}}async function rS(e,t){let r=await Co("unstarted",Im(e));return(await Ul({token:e.token,workflowStateIds:r,label:t.buildLabel??e.defaultLabel,excludeHitl:t.excludeHitl,fetcher:e.fetcher})).map(tS)}async function nS(e,t,r){let n=Ct(t.key);if(n===void 0)return!1;let o=await Ml(r,Im(e));if(o===void 0)return console.warn(`\u26A0 Shortcut workflow state "${r}" not found \u2014 check workflow configuration`),!1;let s=await ql({token:e.token,storyId:n,workflowStateId:o,fetcher:e.fetcher});return s&&console.log(` \u2192 Transitioned to ${r}`),s}async function oS(e,t){let r=Ct(t);return r!==void 0?Pr({token:e.token,storyId:r,workflowCache:e.workflowCache,fetcher:e.fetcher}):!1}async function sS(e,t,r){let n=r??t.replace(/^(?:sc-|epic-)/,""),o=parseInt(n,10);return Number.isNaN(o)?void 0:Rr({token:e.token,epicId:o,workflowCache:e.workflowCache,parentKey:t,fetcher:e.fetcher})}async function iS(e,t,r){await To({token:e.token,labelCache:e.labelCache,label:r,fetcher:e.fetcher}),await Hl({token:e.token,labelCache:e.labelCache,issueKey:t,label:r,fetcher:e.fetcher})}function Eo(e,t){let r={token:e.SHORTCUT_API_TOKEN,workflowName:e.SHORTCUT_WORKFLOW,defaultLabel:e.CLANCY_LABEL,workflowCache:new le,labelCache:new le,fetcher:t},n=o=>rS(r,o);return{ping:()=>Fl(r.token,r.fetcher),validateInputs:()=>{},fetchTicket:async o=>(await n(o))[0],fetchTickets:n,fetchBlockerStatus:o=>oS(r,o.key),fetchChildrenStatus:(o,s)=>sS(r,o,s),transitionTicket:(o,s)=>nS(r,o,s),ensureLabel:o=>To({token:r.token,labelCache:r.labelCache,label:o,fetcher:r.fetcher}),addLabel:(o,s)=>iS(r,o,s),removeLabel:(o,s)=>Wl({token:r.token,labelCache:r.labelCache,issueKey:o,label:s,fetcher:r.fetcher}),sharedEnv:()=>e}}function zo(e,t){switch(e.provider){case"jira":return yo(e.env,t);case"github":return bo(e.env,t);case"linear":return wo(e.env,t);case"shortcut":return Eo(e.env,t);case"notion":return Ro(e.env,t);case"azdo":return mo(e.env,t);default:return e}}function Pm(e,t){return t?[...e,"--model",t]:e}function Rm(e){return e.status===0&&!e.error}function Jl(e){let{prompt:t,model:r,spawn:n}=e,s=Pm(["-p","--dangerously-skip-permissions"],r),i=n("claude",s,{input:t,stdio:["pipe","pipe","pipe"],encoding:"utf8"});return{stdout:i.stdout??"",ok:Rm(i)}}function Vl(e){let{prompt:t,model:r,spawn:n}=e,s=Pm(["--dangerously-skip-permissions"],r),i=n("claude",s,{input:t,stdio:["pipe","inherit","inherit"],encoding:"utf8"});return Rm(i)}function aS(e){try{let{hostname:t}=new URL(e);return t==="hooks.slack.com"||t.endsWith(".hooks.slack.com")}catch{return!1}}function cS(e){return JSON.stringify({text:e})}function uS(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 Cr(e){let{webhookUrl:t,message:r,fetch:n,warn:o=console.warn}=e,s=aS(t)?cS(r):uS(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 Cm(e,t){let{projectRoot:r,exec:n,fetch:o,qualityFs:s}=e;return{deliver:i=>at(i,{deliverViaPullRequest:c=>sl({...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();fl(s,r,{ticketKey:i.ticket.key,duration:c-i.startTime,now:c})},recordRework:()=>pl(s,r,i.ticket.key),removeBuildLabel:async c=>{await i.board.removeLabel(c,Yl(i))},postReworkActions:async c=>{let u=ee(n),l=ir({fetchFn:o,env:i.config.env,remote:u});l&&await Pu({...c,handlers:l})}})}}function lS(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 Tm=`
|
|
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 pS(e){switch(e){case"github":return"Milestone";case"notion":return"Parent page";case"jira":case"linear":case"shortcut":case"azdo":return"Epic"}}function Gl(e){let t=lS(e.provider),r=pS(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?Tm:""}
|
|
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 Ql(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?Tm:""}
|
|
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 Em(e){return async t=>{let r=t.config,n=t.ticket,o=r.env.CLANCY_TDD==="true",s=t.isRework?Ql({provider:r.provider,key:n.key,title:n.title,description:n.description,feedbackComments:t.prFeedback??[],tdd:o}):Gl({provider:r.provider,key:n.key,title:n.title,description:n.description,parentInfo:n.parentInfo,blockers:n.blockers,tdd:o});return{ok:Vl({prompt:s,model:r.env.CLANCY_MODEL,spawn:e})}}}function fS(e,t){return r=>te(e,t,r)}var dS="clancy:build";function Yl(e){let t=e.config?.env;return t?.CLANCY_LABEL_BUILD??t?.CLANCY_LABEL??dS}function zm(e){return e.parent!==void 0}function mS(e,t){return()=>{let n=H(e,t,"DONE").filter(zm).map(o=>[o.parent,o.key]);return new Map(n)}}function hS(e){return async(t,r,n)=>{let o=n.config,s=o.env.CLANCY_BASE_BRANCH??"main",i=zm(t)?t.parent:void 0,c=qe(o.provider,t.key),u=or(o.provider,s,i),p=`${$e(t.ticketType)}(${t.key}): ${t.summary}`,d=xt({config:o,ticket:{key:t.key,title:t.summary,description:t.summary,provider:o.provider},targetBranch:u});return Ie({fetchFn:e,env:o.env,remote:r,sourceBranch:c,targetBranch:u,title:p,body:d})}}function gS(e,t){let{projectRoot:r,exec:n,lockFs:o,progressFs:s}=e;return{lockCheck:i=>dt(i,{lockFs:o,exec:n,progressFs:s,detectResume:c=>vu(c),executeResume:c=>$u(c)}),preflight:i=>ht(i,{runPreflight:c=>Su(c,{exec:(u,l)=>n([u,...l]),envFs:e.envFs}),detectBoard:c=>po(c),createBoard:c=>zo(c,(u,l)=>e.fetch(u,l??{}))}),epicCompletion:i=>ct(i,{findCompletedEpics:mS(s,r),deliverEpicToBase:c=>il({...c,exec:n,fetchFn:e.fetch,progressFs:s,projectRoot:r,config:c.config})}),prRetry:i=>mt(i,{findRetryable:()=>H(s,r,"PUSHED"),detectRemote:()=>ee(n),retryEntry:hS(e.fetch),appendProgress:t})}}function bS(e,t){let{projectRoot:r,exec:n,progressFs:o,spawn:s,fetch:i}=e;return{reworkDetection:c=>gt(c,{fetchRework:async u=>{let l=ee(n),p=ir({fetchFn:i,env:u.env,remote:l});if(p)return Iu({progressFs:o,projectRoot:r,provider:u.provider,handlers:p})}}),ticketFetch:c=>bt(c,{fetchTicket:u=>u.fetchTicket({buildLabel:Yl(c)}),countReworkCycles:u=>to(o,r,u),appendProgress:t,computeTicketBranch:(u,l)=>qe(u,l),computeTargetBranch:(u,l,p)=>or(u,l,p)}),feasibility:c=>ut(c,{checkFeasibility:(u,l)=>{let p=el(d=>Jl({prompt:d,model:l,spawn:s}),u,l);return Promise.resolve(p)},appendProgress:t})}}function yS(e){let{projectRoot:t,exec:r,lockFs:n,spawn:o}=e;return{branchSetup:s=>ot(s,{currentBranch:()=>kt(r),checkout:(i,c)=>se(r,i,c),fetchRemoteBranch:i=>wt(r,i),ensureBranch:(i,c)=>eo(r,i,c),ensureEpicBranch:(i,c)=>rl({exec:r,epicBranch:i,baseBranch:c}),fetchChildrenStatus:i=>s.board.fetchChildrenStatus(i.key,i.issueId),writeLock:i=>Xn(n,t,{...i,pid:process.pid})}),transition:s=>yt(s,{transitionTicket:(i,c)=>s.board.transitionTicket(i,c)}),invoke:Em(o)}}function kS(e){let{projectRoot:t,exec:r,lockFs:n,costFs:o,fetch:s}=e;return{cost:i=>it(i,{readLock:()=>lt(n,t),appendCostEntry:c=>ml(o,t,{...c,now:Date.now()})}),cleanup:i=>st(i,{notify:(c,u)=>Cr({webhookUrl:c,message:u,fetch:s})}),checkout:i=>se(r,i),deleteLock:()=>pt(n,t),deleteVerifyAttempt:()=>ft(n,t)}}function Tr(e){let t=fS(e.progressFs,e.projectRoot);return{...gS(e,t),...bS(e,t),...yS(e),...Cm(e,t),...kS(e)}}import{spawnSync as Nm}from"node:child_process";import{appendFileSync as Lm,mkdirSync as Lo,readFileSync as jo,renameSync as wS,unlinkSync as xS,writeFileSync as jm}from"node:fs";import{resolve as SS}from"node:path";import{fileURLToPath as vS}from"node:url";var P=e=>`\x1B[2m${e}\x1B[0m`,Ao=e=>`\x1B[1m${e}\x1B[0m`;var Er=e=>`\x1B[32m${e}\x1B[0m`,No=e=>`\x1B[31m${e}\x1B[0m`,Xl=e=>`\x1B[33m${e}\x1B[0m`;function _S(e,t,r){let n=ue(r.clock()-t),{out:o}=r;switch(e.status){case"completed":o.log(Er("\u2705 Ticket completed")+P(` (${n})`));break;case"aborted":o.log(P(`\u23F9 Pipeline aborted at ${e.phase??"unknown"}`)+P(` (${n})`));break;case"resumed":o.log(P("\u21A9 Resumed previous session")+P(` (${n})`));break;case"dry-run":o.log(P("\u{1F3C1} Dry run complete")+P(` (${n})`));break;case"error":o.error(No("\u274C Clancy stopped")+P(` (${n})`)),o.error(No(` ${e.error??"Unknown error"}`));break;default:return e.status}}async function Am(e){let t=rt({projectRoot:e.projectRoot,argv:e.argv,isAfk:e.isAfk,now:e.now}),r=Tr({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;_S(n,t.startTime,{out:e.console,clock:o})}function ep(e,t=Nm){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 tp(){return{readFile:e=>jo(e,"utf8"),writeFile:(e,t)=>jm(e,t,"utf8"),deleteFile:e=>xS(e),mkdir:e=>Lo(e,{recursive:!0})}}function rp(){return{readFile:e=>jo(e,"utf8"),appendFile:(e,t)=>Lm(e,t,"utf8"),mkdir:e=>Lo(e,{recursive:!0})}}function np(){return{appendFile:(e,t)=>Lm(e,t,"utf8"),mkdir:e=>Lo(e,{recursive:!0})}}function op(){return{readFile:e=>jo(e,"utf8"),writeFile:(e,t)=>jm(e,t,"utf8"),rename:(e,t)=>wS(e,t),mkdir:e=>Lo(e,{recursive:!0})}}function sp(){return{readFile:e=>jo(e,"utf8")}}async function $S(){let e=process.cwd();await Am({argv:process.argv,projectRoot:e,isAfk:!1,exec:ep(e),lockFs:tp(),progressFs:rp(),costFs:np(),envFs:sp(),qualityFs:op(),spawn:(t,r,n)=>Nm(t,[...r],{...n,stdio:[...n.stdio]}),fetch:globalThis.fetch.bind(globalThis),runPipeline:nt,console})}process.argv[1]&&vS(import.meta.url)===SS(process.argv[1])&&$S().catch(e=>{let t=e instanceof Error?e.message:String(e);console.error(t)});import{join as ip}from"node:path";function IS(e){return/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/.test(e)?new Date(e.replace(" ","T")+":00Z").getTime():NaN}function PS(e,t){return e.split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0).map(o=>RS(o,t)).filter(o=>o!==void 0)}function RS(e,t){let r=e.split(" | ");if(r.length<4)return;let n=r[0],o=new Date(n).getTime();if(!Number.isNaN(o)&&o>=t)return{timestamp:n,key:r[1],duration:r[2],tokens:r[3]}}function CS(e){let t=e.match(/~(\d[\d,]*)/);if(!t)return 0;let r=parseInt(t[1].replace(/,/g,""),10);return Number.isNaN(r)?0:r}function Bm(e,t=0){return t>=e.length?0:CS(e[t].tokens)+Bm(e,t+1)}function TS(e){let t=new Date(e),r=t.getUTCFullYear(),n=String(t.getUTCMonth()+1).padStart(2,"0"),o=String(t.getUTCDate()).padStart(2,"0");return`${r}-${n}-${o}`}function ap(e,t){return e!=null?[t(e)]:[]}function ES(e,t){let r=e.get(t.key);return{...t,duration:r?.duration,tokens:r?.tokens}}function zS(e,t){let r=new Map(t.map(o=>[o.key,o]));return[...new Map(e.map(o=>[o.key,o])).values()].map(o=>ES(r,o))}function Om(e){let{entries:t,costs:r,quality:n,loopStartTime:o,loopEndTime:s}=e,i=zS(t,r),c=i.filter(l=>Tt.has(l.status)),u=i.filter(l=>Ar.has(l.status));return[...AS({completed:c.length,failed:u.length},{start:o,end:s},r),...NS(i),...jS(i,u),...BS(n),""].join(`
|
|
255
|
+
`)}function AS(e,t,r){let n=ue(t.end-t.start),o=Bm(r),s=o>0?[`- Estimated token usage: ${o.toLocaleString("en-US")}`]:[];return[`# Autopilot Session Report \u2014 ${TS(t.start)}`,"","## Summary",`- Tickets completed: ${e.completed}`,`- Tickets failed: ${e.failed}`,`- Total duration: ${n}`,...s]}function NS(e){return e.length===0?["","## Tickets","","No tickets were processed in this session."]:["","## Tickets",...e.flatMap(LS)]}function LS(e){return["",`### ${Tt.has(e.status)?"\u2713":"\u2717"} ${e.key} \u2014 ${e.summary}`,...ap(e.duration,n=>`- Duration: ${n}`),...ap(e.tokens,n=>`- Tokens: ${n}`),...ap(e.prNumber,n=>`- PR: #${n}`),`- Status: ${e.status}`]}function jS(e,t){let r=e.filter(s=>s.prNumber!=null).map(s=>`#${s.prNumber}`),n=t.map(s=>s.key);return r.length>0||n.length>0?["","## Next Steps",...r.length>0?[`- Review PRs ${r.join(", ")}`]:[],...n.map(s=>`- ${s} needs manual intervention`)]:[]}function BS(e){if(!e)return[];let{avgReworkCycles:t,avgVerificationRetries:r,avgDuration:n}=e.summary,o=n>0?[`- Avg delivery time: ${ue(n)}`]:[];return["","## Quality Metrics",`- Avg rework cycles: ${t}`,`- Avg verification retries: ${r}`,...o]}function OS(e,t){try{return e(t)}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return"";throw r}}function ZS(e,t){let r=IS(e.timestamp);return!Number.isNaN(r)&&r>=t}function cp(e){let{progressFs:t,qualityFs:r,projectRoot:n,loopStartTime:o,loopEndTime:s}=e,i=Math.floor(o/6e4)*6e4,u=Ue(t,n).filter(_=>ZS(_,i)),l=ip(n,".clancy","costs.log"),p=OS(e.readCostsFile,l),d=PS(p,o),h=dl(r,n),g=Om({entries:u,costs:d,quality:h,loopStartTime:o,loopEndTime:s});try{e.mkdir(ip(n,".clancy")),e.writeFile(ip(n,".clancy","session-report.md"),g)}catch(_){let w=_ instanceof Error?_.message:String(_);e.console.error(`Failed to write session report: ${w}`)}return g}function Zm(e){let t=e.trim().match(/^(\d{1,2}):(\d{2})$/);if(!t)return;let r=parseInt(t[1],10),n=parseInt(t[2],10),o=r>=0&&r<=23,s=n>=0&&n<=59;return o&&s?{hours:r,minutes:n}:void 0}function DS(e,t,r){let n=Zm(e),o=Zm(t);if(!n||!o)return 0;let s=r.getHours()*60+r.getMinutes(),i=n.hours*60+n.minutes,c=o.hours*60+o.minutes;if(!FS(s,i,c))return 0;let l=MS(s,c),p=r.getSeconds()*1e3+r.getMilliseconds();return Math.max(0,l*6e4-p)}function FS(e,t,r){if(t===r)return!1;let n=t<r,o=e>=t,s=e<r;return n?o&&s:o||s}function MS(e,t){let r=t-e,n=r+1440;return r<=0?n:r}var US=new Set(["lock-check","preflight","ticket-fetch","branch-setup"]);function qS(e){switch(e.status){case"completed":case"resumed":return{stop:!1};case"error":return{stop:!0,reason:e.error??"Unknown error"};case"dry-run":return{stop:!0,reason:"Dry run \u2014 loop not applicable"};case"aborted":return US.has(e.phase??"")?{stop:!0,reason:`Aborted at ${e.phase}`}:{stop:!1};default:return e.status}}async function Dm(e){let{console:t,clock:r}=e,n=r();KS(t);let o=await HS(e,n);await YS(e,n,o)}function KS(e){e.log(P("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510")),e.log(P("\u2502")+Ao(" \u{1F916} Clancy \u2014 autopilot mode ")+P("\u2502")),e.log(P("\u2502")+P(` "I'm on it. Proceed to the abandoned warehouse." `)+P("\u2502")),e.log(P("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"))}async function HS(e,t){let{console:r,clock:n}=e,o=JS(e.maxIterations),s=o.length;for(let i of o){await VS(e);let c=n();r.log(""),r.log(Ao(`\u{1F501} Iteration ${i}/${s}`));let u=await e.runIteration(),l=ue(n()-c);r.log(P(` Iteration ${i} took ${l}`));let p=qS(u);if(p.stop){let h=ue(n()-t);return r.log(""),r.log(`${p.reason}`),r.log(P(` Total: ${i} iteration${i>1?"s":""} in ${h}`)),i}i===s||await e.sleep(2e3)}return s}var WS=100;function JS(e){let t=Math.min(Math.max(0,e),WS);return Array.from({length:t},(r,n)=>n+1)}async function VS(e){let{quietStart:t,quietEnd:r,console:n}=e;if(!t||!r)return;let o=e.now?e.now():new Date,s=DS(t,r,o);if(s<=0)return;let i=Math.ceil(s/6e4);n.log(""),n.log(Xl(`\u23F8 Quiet hours active (${t}\u2013${r}). Sleeping ${i} minutes.`)),await e.sleep(s),n.log(P(" Quiet hours ended. Resuming."))}async function YS(e,t,r){let{console:n,clock:o}=e,s=o(),i=ue(s-t);n.log(""),n.log(Er(`\u{1F3C1} Completed ${r} iterations`)+P(` (${i})`));let c=e.buildReport(t,s);if(n.log(""),n.log(P("\u2500\u2500\u2500 Session Report \u2500\u2500\u2500")),n.log(c),e.webhookUrl){let u=GS(c);try{await e.sendNotification(e.webhookUrl,u)}catch(l){let p=l instanceof Error?l.message:String(l);n.error(`Webhook notification failed: ${p}`)}}}function GS(e){let t=e.split(/\r?\n/).filter(n=>n.startsWith("- Tickets")||n.startsWith("- Total"));return`Clancy autopilot: ${t.length>0?t.join(". "):"session complete"}`}var Fm=5;function sv(e){if(!e)return Fm;let t=Math.floor(Number(e));return t>0?t:Fm}function iv(e){return async()=>{let t=rt({projectRoot:e.projectRoot,argv:e.argv,isAfk:!0}),r=Tr({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});return e.runPipeline(t,r)}}function av(e){return(t,r)=>e.buildSessionReport({progressFs:e.progressFs,qualityFs:e.qualityFs,readCostsFile:e.readCostsFile,writeFile:e.writeFile,mkdir:e.mkdir,console:e.console,projectRoot:e.projectRoot,loopStartTime:t,loopEndTime:r})}function cv(e,t=Cr){return(r,n)=>t({webhookUrl:r,message:n,fetch:e})}async function uv(){let e=process.cwd(),t=process.env,r=ep(e),n=tp(),o=rp(),s=np(),i=sp(),c=op(),u=globalThis.fetch.bind(globalThis),l=(p,d,h)=>QS(p,[...d],{...h,stdio:[...h.stdio]});await Dm({maxIterations:sv(t.MAX_ITERATIONS),runIteration:iv({projectRoot:e,exec:r,lockFs:n,progressFs:o,costFs:s,envFs:i,qualityFs:c,spawn:l,fetch:u,runPipeline:nt,argv:process.argv}),buildReport:av({progressFs:o,qualityFs:c,projectRoot:e,console,readCostsFile:p=>ev(p,"utf8"),writeFile:(p,d)=>tv(p,d,"utf8"),mkdir:p=>XS(p,{recursive:!0}),buildSessionReport:cp}),sendNotification:cv(u),sleep:p=>nv(p),console,clock:Date.now,quietStart:t.CLANCY_QUIET_START,quietEnd:t.CLANCY_QUIET_END,webhookUrl:t.CLANCY_NOTIFY_WEBHOOK})}process.argv[1]&&ov(import.meta.url)===rv(process.argv[1])&&uv().catch(e=>{let t=e instanceof Error?e.message:String(e);console.error(t)});export{cv as buildNotify,av as buildReportFactory,iv as buildRunIteration,sv as parseMaxIterations};
|