@processfocus/cli 0.1.0-next.0
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/LICENSE.md +28 -0
- package/README.md +736 -0
- package/dist/bundled-db-import.mjs +475 -0
- package/dist/bundled-graphql-schema.mjs +55 -0
- package/dist/main.mjs +1444 -0
- package/dist/prepare-deployment-artifact.mjs +4 -0
- package/dist/resources/cedar/policies.cedar +315 -0
- package/dist/resources/cedar/schema.cedarschema +276 -0
- package/dist/resources/system-migrations/20251230050207_wild_ikaris/migration.sql +1 -0
- package/dist/resources/system-migrations/20251230050207_wild_ikaris/snapshot.json +10 -0
- package/dist/resources/system-migrations/20260215222342_legacy_deploy_placeholder/migration.sql +1 -0
- package/dist/resources/system-migrations/20260217210625_legacy_deploy_placeholder/migration.sql +1 -0
- package/dist/resources/system-migrations/20260225225114_legacy_deploy_placeholder/migration.sql +1 -0
- package/dist/resources/system-migrations/20260304233747_legacy_deploy_placeholder/migration.sql +1 -0
- package/dist/resources/system-migrations/20260313015405_legacy_deploy_placeholder/migration.sql +1 -0
- package/dist/resources/system-migrations/20260317191043_legacy_deploy_placeholder/migration.sql +1 -0
- package/dist/resources/system-migrations/20260401023429_legacy_deploy_placeholder/migration.sql +1 -0
- package/dist/resources/system-migrations/20260401074807_legacy_deploy_placeholder/migration.sql +1 -0
- package/dist/resources/system-migrations/20260407221320_legacy_deploy_placeholder/migration.sql +1 -0
- package/dist/resources/system-migrations/20260409221005_lyrical_slapstick/migration.sql +588 -0
- package/dist/resources/system-migrations/20260409221005_lyrical_slapstick/snapshot.json +5580 -0
- package/dist/resources/system-migrations/20260410054541_updated-at-triggers/migration.sql +259 -0
- package/dist/resources/system-migrations/20260410054541_updated-at-triggers/snapshot.json +5580 -0
- package/dist/resources/system-migrations/20260506185000_external-participants/migration.sql +27 -0
- package/dist/resources/system-migrations/20260525081848_confused_mac_gargan/migration.sql +16 -0
- package/dist/resources/system-migrations/20260525081848_confused_mac_gargan/snapshot.json +5929 -0
- package/dist/resources/system-migrations/20260525211724_ordinary_archangel/migration.sql +1 -0
- package/dist/resources/system-migrations/20260525211724_ordinary_archangel/snapshot.json +5954 -0
- package/dist/resources/system-migrations/20260526022120_cultured_daredevil/migration.sql +1 -0
- package/dist/resources/system-migrations/20260526022120_cultured_daredevil/snapshot.json +5979 -0
- package/dist/resources/system-migrations/20260607222956_blue_maelstrom/migration.sql +26 -0
- package/dist/resources/system-migrations/20260607222956_blue_maelstrom/snapshot.json +6139 -0
- package/dist/resources/system-migrations/20260608074412_productive_guardian/migration.sql +4 -0
- package/dist/resources/system-migrations/20260608074412_productive_guardian/snapshot.json +6179 -0
- package/dist/resources/system-migrations/20260609042621_huge_hellcat/migration.sql +3 -0
- package/dist/resources/system-migrations/20260609042621_huge_hellcat/snapshot.json +6209 -0
- package/dist/resources/system-migrations/20260626224225_glorious_tenebrous/migration.sql +107 -0
- package/dist/resources/system-migrations/20260626224225_glorious_tenebrous/snapshot.json +6221 -0
- package/dist/resources/system-migrations/20260722090215_mighty_colonel_america/migration.sql +26 -0
- package/dist/resources/system-migrations/20260722090215_mighty_colonel_america/snapshot.json +6490 -0
- package/dist/resources/system-migrations/20260722234847_brainy_quasimodo/migration.sql +1 -0
- package/dist/resources/system-migrations/20260722234847_brainy_quasimodo/snapshot.json +6500 -0
- package/dist/resources/system-migrations/20260727044204_nostalgic_lightspeed/migration.sql +51 -0
- package/dist/resources/system-migrations/20260727044204_nostalgic_lightspeed/snapshot.json +6670 -0
- package/dist/resources/system-migrations/20260727044743_green_thaddeus_ross/migration.sql +30 -0
- package/dist/resources/system-migrations/20260727044743_green_thaddeus_ross/snapshot.json +6670 -0
- package/dist/resources/system-migrations/20260727085203_safe_flatman/migration.sql +80 -0
- package/dist/resources/system-migrations/20260727085203_safe_flatman/snapshot.json +6803 -0
- package/dist/resources/system-migrations/20260727192244_natural_franklin_richards/migration.sql +14 -0
- package/dist/resources/system-migrations/20260727192244_natural_franklin_richards/snapshot.json +6947 -0
- package/dist/resources/system-migrations/20260727230751_updated-at-triggers/migration.sql +1 -0
- package/dist/resources/system-migrations/20260727230751_updated-at-triggers/snapshot.json +6947 -0
- package/dist/resources/system-migrations/20260727230758_pale_mother_askani/migration.sql +25 -0
- package/dist/resources/system-migrations/20260727230758_pale_mother_askani/snapshot.json +7121 -0
- package/dist/resources/system-migrations/20260831084613_nostalgic_hannibal_king/migration.sql +4 -0
- package/dist/resources/system-migrations/20260831084613_nostalgic_hannibal_king/snapshot.json +6852 -0
- package/dist/resources/system-migrations/20260906234923_stiff_maria_hill/migration.sql +77 -0
- package/dist/resources/system-migrations/20260906234923_stiff_maria_hill/snapshot.json +7396 -0
- package/dist/resources/system-migrations/20260907104651_delegation-rename-snapshots/migration.sql +2 -0
- package/dist/resources/system-migrations/20260907104651_delegation-rename-snapshots/snapshot.json +7416 -0
- package/dist/resources/system-migrations/20260907113440_abandoned_vertigo/migration.sql +2 -0
- package/dist/resources/system-migrations/20260907113440_abandoned_vertigo/snapshot.json +7466 -0
- package/dist/resources/system-migrations/20260908002610_mute_sharon_ventura/migration.sql +87 -0
- package/dist/resources/system-migrations/20260908002610_mute_sharon_ventura/snapshot.json +7491 -0
- package/dist/resources/system-migrations/20260914100808_slippery_ultragirl/migration.sql +1 -0
- package/dist/resources/system-migrations/20260914100808_slippery_ultragirl/snapshot.json +7501 -0
- package/dist/resources/system-migrations/20260919083020_passkey-name/migration.sql +1 -0
- package/dist/resources/system-migrations/20260919083020_passkey-name/snapshot.json +7511 -0
- package/dist/resources/system-migrations/20260919094049_passkey-last-used/migration.sql +1 -0
- package/dist/resources/system-migrations/20260919094049_passkey-last-used/snapshot.json +7521 -0
- package/package.json +36 -0
|
@@ -0,0 +1,475 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var a2=Object.create;var{getPrototypeOf:c2,defineProperty:Iw,getOwnPropertyNames:l2}=Object;var LC=Object.prototype.hasOwnProperty;function d2(e){return this[e]}var u2,p2,zr=(e,t,r)=>{var n=e!=null&&typeof e==="object";if(n){var o=t?u2??=new WeakMap:p2??=new WeakMap,i=o.get(e);if(i)return i}r=e!=null?a2(c2(e)):{};let s=t||!e||!e.__esModule||!LC.call(e,"default")?Iw(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of l2(e))if(!LC.call(s,a))Iw(s,a,{get:d2.bind(e,a),enumerable:!0})}if(n)o.set(e,s);return s};var Ln=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var f2=(e)=>e;function m2(e,t){this[e]=f2.bind(null,t)}var $C=(e,t)=>{for(var r in t)Iw(e,r,{get:t[r],enumerable:!0,configurable:!0,set:m2.bind(t,r)})};var po=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};var y2=import.meta.require;import*as Cw from"effect/Effect";import*as Dd from"effect/FiberRef";var kh,_w,Oh,h2;var qC=po(()=>{kh=Dd.unsafeMake(!1),_w=Dd.unsafeMake(void 0),Oh=Dd.unsafeMake("immediate"),h2=Dd.get(Oh)});import{Context as g2}from"effect";var Nd;var jC=po(()=>{Nd=class Nd extends g2.Tag("processfocus:internal-tag/db-info/DatabaseConnectionInfo")(){}});var Ua=(e)=>/^[a-z]+:/.test(e)?e:`file://${e}`,Dh=(e)=>{let t=e.match(/^([a-z]+):/)?.[1];return t===void 0||t==="file"};var Ow=5000;import{join as HC,resolve as WC}from"path";import*as tl from"effect/Config";import*as Fd from"effect/ConfigProvider";import*as KC from"effect/Layer";var Dw=(e)=>{let t=process.env.SQLITE_DATABASE_PATH;if(t)return t;let r=e??process.env.PF_ORG;if(!r)return;return HC(WC(r),"db","pf.db")},rl,Nw="Database path not configured. Set SQLITE_DATABASE_PATH or PF_ORG environment variable.",Fw=(e)=>KC.setConfigProvider(Fd.fromMap(new Map([["SQLITE_DATABASE_PATH",e]])).pipe(Fd.orElse(()=>Fd.fromEnv())));var VC=po(()=>{rl=tl.string("SQLITE_DATABASE_PATH").pipe(tl.orElse(()=>tl.string("PF_ORG").pipe(tl.map((e)=>HC(WC(e),"db","pf.db")))))});var S2,v2,QC,x2=(e)=>typeof e==="object"&&e!==null,ds=(e,t,r)=>{let n=r?.maxDepth??16,o=r?.codePredicate,i=e,s=new WeakSet,a=0;while(i!=null&&a<n){if(a+=1,i instanceof Error){if(s.has(i))return!1;if(s.add(i),t(i.message))return!0;let c=i.code;if(typeof c==="string"&&o?.(c)===!0)return!0;i=i.cause;continue}if(x2(i)){if(s.has(i))return!1;s.add(i);let c=i.message;if(typeof c==="string"&&t(c))return!0;let l=i.code;if(typeof l==="string"&&o?.(l)===!0)return!0;i=i.cause;continue}if(typeof i==="string"&&t(i))return!0;break}return!1},w2=(e)=>QC.test(e)||S2.some((t)=>e.toLowerCase().includes(t)),b2=(e)=>{let t=e.toUpperCase();return v2.some((r)=>t===r||t.includes(r))},nl=(e)=>ds(e,w2,{codePredicate:b2}),Uw=(e)=>ds(e,(t)=>QC.test(t));var JC=po(()=>{S2=["sqlite_busy","sqlite_locked","database is locked"],v2=["SQLITE_BUSY","SQLITE_LOCKED"],QC=/write[- ]write\s+conflict|concurrent\s+write\s+conflict/iu});var ol=po(()=>{qC();jC();VC();JC()});import*as zC from"effect/Context";import*as Jo from"effect/Effect";import*as GC from"effect/Exit";import*as YC from"effect/FiberHandle";import{dual as bte}from"effect/Function";import*as XC from"effect/Hash";import*as ZC from"effect/Layer";import*as Nh from"effect/Mailbox";import*as e_ from"effect/Scope";import*as t_ from"effect/Stream";function Bw(e){return typeof e==="string"?e:XC.hash(e)}var gf,E2,Fh,r_=(e,t)=>{let r=Array(t.length);for(let n=0;n<t.length;n++)r[n]=`${e}:${Bw(t[n])}`;return r},T2=(e)=>{let t=[];for(let r in e){t.push(r);for(let n of r_(r,e[r]))t.push(n)}return t};var Uh=po(()=>{gf=class gf extends zC.Tag("@effect/experimental/Reactivity")(){};E2=Jo.sync(()=>{let e=new Map,t=(a)=>{if(Array.isArray(a))for(let c=0;c<a.length;c++){let l=e.get(Bw(a[c]));if(l===void 0)continue;for(let d of l)d()}else{let c=a;for(let l in c){let d=r_(l,c[l]);for(let m=0;m<d.length;m++){let h=e.get(d[m]);if(h===void 0)continue;for(let S of h)S()}let u=e.get(l);if(u!==void 0)for(let m of u)m()}}},r=(a)=>Jo.sync(()=>t(a)),n=(a,c)=>Jo.zipLeft(c,r(a)),o=(a,c)=>{let l=Array.isArray(a)?a.map(Bw):T2(a);for(let d=0;d<l.length;d++){let u=e.get(l[d]);if(u===void 0)u=new Set,e.set(l[d],u);u.add(c)}return()=>{for(let d=0;d<l.length;d++){let u=e.get(l[d]);if(u.delete(c),u.size===0)e.delete(l[d])}}},i=(a,c)=>Jo.gen(function*(){let l=yield*Jo.scope,d=yield*Nh.make(),u=yield*YC.makeRuntime(),m=!1,h=!1,S=(w)=>{if(w._tag==="Failure")d.unsafeDone(GC.failCause(w.cause));else d.unsafeOffer(w.value);if(h)h=!1,u(c).addObserver(S);else m=!1};function x(){if(m){h=!0;return}m=!0,u(c).addObserver(S)}let v=o(a,x);return yield*e_.addFinalizer(l,Jo.sync(v)),x(),d}),s=(a,c)=>i(a,c).pipe(Jo.map(Nh.toStream),t_.unwrapScoped);return gf.of({mutation:n,query:i,stream:s,unsafeInvalidate:t,invalidate:r,unsafeRegister:o})}),Fh=ZC.scoped(gf,E2)});import*as fo from"effect/Effect";import*as l_ from"effect/Effectable";import*as d_ from"effect/FiberRef";import{dual as Tte,identity as u_}from"effect/Function";import{globalValue as p_}from"effect/GlobalValue";import*as R2 from"effect/Layer";import*as qw from"effect/Option";import*as A2 from"effect/Predicate";import*as f_ from"effect/Stream";class li{value;params;_tag="Literal";constructor(e,t){this.value=e,this.params=t}}class Mh{value;_tag="Identifier";constructor(e){this.value=e}}class y_{value;_tag="Parameter";constructor(e){this.value=e}}class Bh{value;_tag="ArrayHelper";constructor(e){this.value=e}}function Ww(e){return typeof e==="string"?e:(vf in e)?e:new Ba([e])}class Lh{value;returningIdentifier;_tag="RecordInsertHelper";constructor(e,t){this.value=e,this.returningIdentifier=t}returning(e){return new Lh(this.value,Ww(e))}}class $h{value;alias;returningIdentifier;_tag="RecordUpdateHelper";constructor(e,t,r){this.value=e,this.alias=t,this.returningIdentifier=r}returning(e){return new $h(this.value,this.alias,Ww(e))}}class qh{value;omit;returningIdentifier;_tag="RecordUpdateHelperSingle";constructor(e,t,r){this.value=e,this.omit=t,this.returningIdentifier=r}returning(e){return new qh(this.value,this.omit,Ww(e))}}function Lw(e){if(typeof e==="string")return[new li(e)];return e.segments}function C2(){if(arguments.length===1)return new Bh(arguments[0]);let e=arguments[0],t=arguments[1];return t.length===0?jh("1=0"):new Ba([new Mh(e),new li(" IN "),new Bh(t)])}function xf(e,t=!0,r=""){let n=new li(e);return(o)=>{if(o.length===0)return jh(r);else if(o.length===1)return new Ba(Lw(o[0]));let i=[];if(t)i.push(new li("("));i.push.apply(i,Lw(o[0]));for(let s=1;s<o.length;s++)i.push(n),i.push.apply(i,Lw(o[s]));if(t)i.push(new li(")"));return new Ba(i)}}class Vw{dialect;parameterPlaceholder;onIdentifier;onRecordUpdate;onCustom;onInsert;onRecordUpdateSingle;disableTransforms;constructor(e,t,r,n,o,i,s,a=!1){this.dialect=e,this.parameterPlaceholder=t,this.onIdentifier=r,this.onRecordUpdate=n,this.onCustom=o,this.onInsert=i,this.onRecordUpdateSingle=s,this.disableTransforms=a}compile(e,t=!1,r){t=t||this.disableTransforms;let n=t?k2:_2;if(n in e)return e[n];let o=e.segments,i=o.length,s="",a=[],c=0,l=r??((h)=>this.parameterPlaceholder(++c,h)),d=(h)=>this.parameterPlaceholder(c,h),u=O2(l);for(let h=0;h<i;h++){let S=o[h];switch(S._tag){case"Literal":{if(s+=S.value,S.params)a.push.apply(a,S.params);break}case"Identifier":{s+=this.onIdentifier(S.value,t);break}case"Parameter":{s+=l(S.value),a.push(S.value);break}case"ArrayHelper":{s+=`(${u(S.value)})`,a.push.apply(a,S.value);break}case"RecordInsertHelper":{let x=Object.keys(S.value[0]);if(this.onInsert){let v=Array(S.value.length),w="";for(let R=0;R<S.value.length;R++){let b=Array(x.length);v[R]=b,w+=R===0?"(":",(";for(let A=0;A<x.length;A++){let D=x[A],B=S.value[R][D],J=Sf(B,this.onCustom,d,t);b[A]=J,w+=A===0?l(B):`,${l(B)}`}w+=")"}let[P,F]=this.onInsert(x.map((R)=>this.onIdentifier(R,t)),w,v,typeof S.returningIdentifier==="string"?[S.returningIdentifier,[]]:S.returningIdentifier?this.compile(S.returningIdentifier,t,l):void 0);s+=P,a.push.apply(a,F)}else{let v="";for(let w=0;w<S.value.length;w++){v+=w===0?"(":",(";for(let P=0;P<x.length;P++){let F=S.value[w][x[P]],R=Sf(F,this.onCustom,d,t);a.push(R),v+=P===0?l(F):`,${l(F)}`}v+=")"}if(s+=`${c_(x,this.onIdentifier,t)} VALUES ${v}`,typeof S.returningIdentifier==="string")s+=` RETURNING ${S.returningIdentifier}`;else if(S.returningIdentifier){s+=" RETURNING ";let[w,P]=this.compile(S.returningIdentifier,t,l);s+=w,a.push.apply(a,P)}}break}case"RecordUpdateHelperSingle":{let x=Object.keys(S.value);if(S.omit.length>0)x=x.filter((v)=>!S.omit.includes(v));if(this.onRecordUpdateSingle){let[v,w]=this.onRecordUpdateSingle(x.map((P)=>this.onIdentifier(P,t)),x.map((P)=>Sf(S.value[P],this.onCustom,d,t)),typeof S.returningIdentifier==="string"?[S.returningIdentifier,[]]:S.returningIdentifier?this.compile(S.returningIdentifier,t,l):void 0);s+=v,a.push.apply(a,w)}else{for(let v=0,w=x.length;v<w;v++){let P=this.onIdentifier(x[v],t);if(v===0)s+=`${P} = ${l(S.value[x[v]])}`;else s+=`, ${P} = ${l(S.value[x[v]])}`;a.push(Sf(S.value[x[v]],this.onCustom,d,t))}if(typeof S.returningIdentifier==="string")if(this.dialect==="mssql")s+=` OUTPUT ${S.returningIdentifier==="*"?"INSERTED.*":S.returningIdentifier}`;else s+=` RETURNING ${S.returningIdentifier}`;else if(S.returningIdentifier){s+=this.dialect==="mssql"?" OUTPUT ":" RETURNING ";let[v,w]=this.compile(S.returningIdentifier,t,l);s+=v,a.push.apply(a,w)}}break}case"RecordUpdateHelper":{let x=Object.keys(S.value[0]),v=Array(S.value.length),w="";for(let R=0;R<S.value.length;R++){let b=Array(x.length);v[R]=b,w+=R===0?"(":",(";for(let A=0;A<x.length;A++){let D=x[A],B=S.value[R][D];b[A]=Sf(B,this.onCustom,d,t),w+=A===0?l(B):`,${l(B)}`}w+=")"}let[P,F]=this.onRecordUpdate(w,S.alias,c_(x,this.onIdentifier,t),v,typeof S.returningIdentifier==="string"?[S.returningIdentifier,[]]:S.returningIdentifier?this.compile(S.returningIdentifier,t,l):void 0);s+=P,a.push.apply(a,F);break}case"Custom":{let[x,v]=this.onCustom(S,l,t);s+=x,a.push.apply(a,v);break}}}let m=[s,a];if(r!==void 0)return m;return e[n]=m}get withoutTransform(){return new Vw(this.dialect,this.parameterPlaceholder,this.onIdentifier,this.onRecordUpdate,this.onCustom,this.onInsert,this.onRecordUpdateSingle,!0)}}function x_(e){let t=new RegExp(e,"g"),r=e+e,n=e+"."+e;return function(o){return e+o.replace(t,r).replace(/\./g,n)+e}}var n_="db.operation.name",o_="db.query.text",vf,jw=(e)=>typeof e==="object"&&e!==null&&(vf in e),m_,i_=(e,t,r)=>fo.withFiberRuntime((n)=>{let o=n.getFiberRef(m_);if(o._tag==="None")return r(e);return fo.flatMap(o.value(e,Kw(e.acquirer,e.compiler,e.spanAttributes,e.transformRows),n.getFiberRefs(),t),r)}),Hw,Ba,P2=(e)=>e instanceof Bh||e instanceof Lh||e instanceof $h||e instanceof qh||e instanceof Mh,s_,Kw=(e,t,r,n)=>{let o=n===void 0?s_.noTransforms:s_.transforms;if(o.has(e))return o.get(e);let i=Object.assign(function(a,...c){if(Array.isArray(a)&&"raw"in a)return I2(e,t,a,c,r,n);else if(typeof a==="string")return new Mh(a);throw"absurd"},{unsafe(s,a){return new Hw([new li(s,a)],e,t,r,n)},literal(s){return new Ba([new li(s)])},in:C2,insert(s){return new Lh(Array.isArray(s)?s:[s],void 0)},update(s,a){return new qh(s,a??[],void 0)},updateValues(s,a){return new $h(s,a,void 0)},and:h_,or:g_,csv:S_,join:xf,onDialect(s){return s[t.dialect]()},onDialectOrElse(s){return s[t.dialect]!==void 0?s[t.dialect]():s.orElse()}});return o.set(e,i),i},I2=(e,t,r,n,o,i)=>{let s=r[0].length>0?[new li(r[0])]:[];for(let a=0;a<n.length;a++){let c=n[a];if(jw(c))for(let l of c.segments)s.push(l);else if(P2(c))s.push(c);else s.push(new y_(c));if(r[a+1].length>0)s.push(new li(r[a+1]))}return new Hw(s,e,t,o,i)},jh=(e,t)=>new Ba([new li(e,t)]),h_,g_,a_,S_=(...e)=>{if(e[e.length-1].length===0)return jh("");if(e.length===1)return a_(e[0]);return new Ba([new li(`${e[0]} `),...a_(e[1]).segments])},_2,k2,v_=(e)=>new Vw(e.dialect,e.placeholder,e.onIdentifier,e.onRecordUpdate,e.onCustom,e.onInsert,e.onRecordUpdateSingle),O2=(e)=>(t)=>{if(t.length===0)return"";let r=e(t[0]);for(let n=1;n<t.length;n++)r+=`,${e(t[n])}`;return r},c_=(e,t,r)=>{if(e.length===0)return"()";let n=`(${t(e[0],r)}`;for(let o=1;o<e.length;o++)n+=`,${t(e[o],r)}`;return n+")"},Sf=(e,t,r,n)=>{if(e===void 0)return null;else if(jw(e)){let o=e.segments[0];if(o._tag==="Custom")return t(o,r,n)[1][0]??null;else if(o._tag==="Parameter")return o.value;return null}return e},$w,w_=(e)=>v_({dialect:"sqlite",placeholder(t){return"?"},onIdentifier:e?function(t,r){return r?$w(t):$w(e(t))}:$w,onRecordUpdate(){return["",[]]},onCustom(){return["",[]]}});var b_=po(()=>{vf=Symbol.for("@effect/sql/Fragment"),m_=p_("@effect/sql/Statement/currentTransformer",()=>d_.unsafeMake(qw.none()));Hw=class Hw extends l_.Class{segments;acquirer;compiler;spanAttributes;transformRows;get[vf](){return u_}constructor(e,t,r,n,o){super();this.segments=e,this.acquirer=t,this.compiler=r,this.spanAttributes=n,this.transformRows=o}withConnection(e,t,r=!1){return fo.useSpan("sql.execute",{kind:"client",captureStackTrace:!1},(n)=>i_(this,n,(o)=>{let[i,s]=o.compile(r);for(let[a,c]of this.spanAttributes)n.attribute(a,c);return n.attribute(n_,e),n.attribute(o_,i),fo.scoped(fo.flatMap(this.acquirer,(a)=>t(a,i,s)))}))}get withoutTransform(){return this.withConnection("executeWithoutTransform",(e,t,r)=>e.execute(t,r,void 0),!0)}get raw(){return this.withConnection("executeRaw",(e,t,r)=>e.executeRaw(t,r),!0)}get stream(){return f_.unwrapScoped(fo.flatMap(fo.makeSpanScoped("sql.execute",{kind:"client",captureStackTrace:!1}),(e)=>i_(this,e,(t)=>{let[r,n]=t.compile();for(let[o,i]of this.spanAttributes)e.attribute(o,i);return e.attribute(n_,"executeStream"),e.attribute(o_,r),fo.map(this.acquirer,(o)=>o.executeStream(r,n,this.transformRows))})))}get values(){return this.withConnection("executeValues",(e,t,r)=>e.executeValues(t,r))}get unprepared(){return this.withConnection("executeUnprepared",(e,t,r)=>e.executeUnprepared(t,r,this.transformRows))}compile(e){return this.compiler.compile(this,e??!1)}commit(){return this.withConnection("execute",(e,t,r)=>e.execute(t,r,this.transformRows))}toJSON(){let[e,t]=this.compile();return{_id:"@effect/sql/Statement",segments:this.segments,sql:e,params:t}}};Ba=class Ba{segments;get[vf](){return u_}constructor(e){this.segments=e}};s_=p_("@effect/sql/Statement/constructorCache",()=>({transforms:new WeakMap,noTransforms:new WeakMap}));h_=xf(" AND ",!0,"1=1"),g_=xf(" OR ",!0,"1=1"),a_=xf(", ",!1),_2=Symbol.for("@effect/sql/Statement/statementCache"),k2=Symbol.for("@effect/sql/Statement/statementCacheNoTransform");$w=x_('"')});var Qw,Hh;var Wh=po(()=>{b_();Qw=Kw,Hh=w_});import*as E_ from"effect/Clock";import*as us from"effect/Context";import*as _t from"effect/Effect";import*as T_ from"effect/Exit";import*as R_ from"effect/FiberRef";import*as A_ from"effect/Mailbox";import*as P_ from"effect/Option";import*as Ud from"effect/Scope";import*as I_ from"effect/Stream";import*as C_ from"effect/Tracer";function k_({acquirer:e,beginTransaction:t="BEGIN",commit:r="COMMIT",compiler:n,reactiveMailbox:o,rollback:i="ROLLBACK",rollbackSavepoint:s=(u)=>`ROLLBACK TO SAVEPOINT ${u}`,savepoint:a=(u)=>`SAVEPOINT ${u}`,spanAttributes:c,transactionAcquirer:l,transformRows:d}){return _t.gen(function*(){let u=_t.flatMap(_t.serviceOption(Gw),P_.match({onNone:()=>e,onSome:([x])=>_t.succeed(x)}));l=l??e;let m=Yw({transactionTag:Gw,spanAttributes:c,acquireConnection:_t.flatMap(Ud.make(),(x)=>_t.map(Ud.extend(l,x),(v)=>[x,v])),begin:(x)=>x.executeUnprepared(t,[],void 0),savepoint:(x,v)=>x.executeUnprepared(a(`effect_sql_${v}`),[],void 0),commit:(x)=>x.executeUnprepared(r,[],void 0),rollback:(x)=>x.executeUnprepared(i,[],void 0),rollbackSavepoint:(x,v)=>x.executeUnprepared(s(`effect_sql_${v}`),[],void 0)}),h=yield*gf,S=Object.assign(Qw(u,n,c,d),{[zw]:zw,safe:void 0,withTransaction:m,reserve:l,withoutTransforms(){if(d===void 0)return this;let x=Qw(u,n.withoutTransform,c,void 0),v=Object.assign(x,{...this,...x});return v.safe=v,v.withoutTransforms=()=>v,v},reactive:o?(x,v)=>o(x,v).pipe(_t.map(A_.toStream),I_.unwrapScoped):h.stream,reactiveMailbox:o??h.query});return S.safe=S,S})}var zw,__,Gw,Yw=(e)=>(t)=>_t.uninterruptibleMask((r)=>_t.useSpan("sql.transaction",{kind:"client",captureStackTrace:!1},(n)=>_t.withFiberRuntime((o)=>{for(let[d,u]of e.spanAttributes)n.attribute(d,u);let i=o.currentContext,s=us.get(o.currentDefaultServices,E_.Clock),a=us.getOption(i,e.transactionTag),c=a._tag==="Some"?_t.succeed([void 0,a.value[0]]):e.acquireConnection,l=a._tag==="Some"?a.value[1]+1:0;return _t.flatMap(c,([d,u])=>(l===0?e.begin(u):e.savepoint(u,l)).pipe(_t.zipRight(_t.locally(r(t),R_.currentContext,us.add(i,e.transactionTag,[u,l]).pipe(us.add(C_.ParentSpan,n)))),_t.exit,_t.flatMap((m)=>{let h;if(T_.isSuccess(m))if(l===0)n.event("db.transaction.commit",s.unsafeCurrentTimeNanos()),h=_t.orDie(e.commit(u));else n.event("db.transaction.savepoint",s.unsafeCurrentTimeNanos()),h=_t.void;else n.event("db.transaction.rollback",s.unsafeCurrentTimeNanos()),h=_t.orDie(l>0?e.rollbackSavepoint(u,l):e.rollback(u));let S=d!==void 0?_t.ensuring(h,Ud.close(d,m)):h;return _t.zipRight(S,m)})))})));var O_=po(()=>{Uh();Wh();zw=Symbol.for("@effect/sql/SqlClient"),__=us.GenericTag("@effect/sql/SqlClient"),Gw=us.GenericTag("@effect/sql/SqlClient/TransactionConnection")});import*as F2 from"effect/Context";var ps,Kh,Vh;var wf=po(()=>{O_();ps=__,Kh=k_,Vh=Yw});import*as D_ from"effect/Data";import*as U2 from"effect/Predicate";import*as tr from"effect/Schema";var Qh,Bd=(e,t)=>{class r extends D_.Error{_tag=t}return r.prototype[e]=e,r.prototype.name=t,r},N_,Md,B2,il;var sl=po(()=>{Qh=Symbol.for("@effect/platform/Error"),N_=tr.Literal("Clipboard","Command","FileSystem","KeyValueStore","Path","Stream","Terminal");Md=class Md extends tr.TaggedError("@effect/platform/Error/BadArgument")("BadArgument",{module:N_,method:tr.String,description:tr.optional(tr.String),cause:tr.optional(tr.Defect)}){[Qh]=Qh;get message(){return`${this.module}.${this.method}${this.description?`: ${this.description}`:""}`}};B2=tr.Literal("AlreadyExists","BadResource","Busy","InvalidData","NotFound","PermissionDenied","TimedOut","UnexpectedEof","Unknown","WouldBlock","WriteZero");il=class il extends tr.TaggedError("@effect/platform/Error/SystemError")("SystemError",{reason:B2,module:N_,method:tr.String,description:tr.optional(tr.String),syscall:tr.optional(tr.String),pathOrDescriptor:tr.optional(tr.Union(tr.String,tr.Number)),cause:tr.optional(tr.Defect)}){[Qh]=Qh;get message(){return`${this.reason}: ${this.module}.${this.method}${this.pathOrDescriptor!==void 0?` (${this.pathOrDescriptor})`:""}${this.description?`: ${this.description}`:""}`}}});var M2,di;var Jh=po(()=>{sl();M2=Symbol.for("@effect/sql/SqlError");di=class di extends Bd(M2,"SqlError"){}});var rb=Ln(function(ek){Object.defineProperty(ek,"__esModule",{value:!0});ek.Dependable=ek.DependencyGroup=void 0;var X_=Symbol.for("jsii.rtti");class Z_{static[X_]={fqn:"constructs.DependencyGroup",version:"10.8.1"};_deps=[];constructor(...e){let t=this;Xh.implement(this,{get dependencyRoots(){let r=[];for(let n of t._deps)r.push(...Xh.of(n).dependencyRoots);return r}}),this.add(...e)}add(...e){this._deps.push(...e)}}ek.DependencyGroup=Z_;var Y_=Symbol.for("@aws-cdk/core.DependableTrait");class Xh{static[X_]={fqn:"constructs.Dependable",version:"10.8.1"};static implement(e,t){e[Y_]=t}static of(e){let t=e[Y_];if(!t)throw Error(`${e} does not implement IDependable. Use "Dependable.implement()" to implement`);return t}static get(e){return this.of(e)}}ek.Dependable=Xh});var rk=Ln(function(ui){var lH=ui&&ui.__createBinding||(Object.create?function(e,t,r,n){if(n===void 0)n=r;var o=Object.getOwnPropertyDescriptor(t,r);if(!o||("get"in o?!t.__esModule:o.writable||o.configurable))o={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,n,o)}:function(e,t,r,n){if(n===void 0)n=r;e[n]=t[r]}),dH=ui&&ui.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),uH=ui&&ui.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)if(Object.prototype.hasOwnProperty.call(r,o))n[n.length]=o;return n},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null){for(var n=e(t),o=0;o<n.length;o++)if(n[o]!=="default")lH(r,t,n[o])}return dH(r,t),r}}();Object.defineProperty(ui,"__esModule",{value:!0});ui.ADDR_SEP=void 0;ui.addressOf=mH;var pH=uH(y2("crypto")),fH="Default";ui.ADDR_SEP=`
|
|
3
|
+
`;function mH(e){let t=pH.createHash("sha1");for(let r of e){if(r===fH)continue;t.update(r),t.update(ui.ADDR_SEP)}return"c8"+t.digest("hex")}});var ik=Ln(function(ok){Object.defineProperty(ok,"__esModule",{value:!0});ok.captureStackTrace=nk;function nk(e){e=e||nk;let t={stack:""},r=Error.stackTraceLimit;try{Error.stackTraceLimit=Number.MAX_SAFE_INTEGER,Error.captureStackTrace(t,e)}finally{Error.stackTraceLimit=r}if(!t.stack)return[];return t.stack.split(`
|
|
4
|
+
`).slice(1).map((n)=>n.replace(/^\s*at\s+/,""))}});var fk=Ln(function(uk){Object.defineProperty(uk,"__esModule",{value:!0});uk.RootConstruct=uk.ConstructOrder=uk.Construct=uk.Node=void 0;var nb=Symbol.for("jsii.rtti"),ak=rb(),ck=rk(),hH=ik(),lk=Symbol.for("constructs.Construct");class Rf{host;static[nb]={fqn:"constructs.Node",version:"10.8.1"};static PATH_SEP="/";static of(e){return e.node}scope;id;path;_locked=!1;_children;_context;_metadata;_dependencies;_defaultChild;_validations;_addr;_scopes;constructor(e,t,r){if(this.host=e,r=r??"",this.id=sk(r),this.scope=t,t&&!this.id)throw Error("Only root constructs may have an empty ID");if(t)t.node.addChild(e,this.id),this.path=t.node.path?`${t.node.path}${Rf.PATH_SEP}${this.id}`:this.id,this._scopes=[...t.node._scopes,this.host];else this.path=this.id,this._scopes=[this.host]}get scopes(){return[...this._scopes]}get addr(){if(!this._addr)this._addr=ck.addressOf(this._scopes.map((e)=>e.node.id));return this._addr}tryFindChild(e){return this._children?.[sk(e)]}findChild(e){let t=this.tryFindChild(e);if(!t)throw Error(`No child with id: '${e}'`);return t}get defaultChild(){if(this._defaultChild!==void 0)return this._defaultChild;let e=this.tryFindChild("Resource"),t=this.tryFindChild("Default");if(e&&t)throw Error(`Cannot determine default child for ${this.path}. There is both a child with id "Resource" and id "Default"`);return t||e}set defaultChild(e){this._defaultChild=e}get children(){return Object.values(this._children??{})}findAll(e=Tf.PREORDER){let t=[];return r(this.host),t;function r(n){if(e===Tf.PREORDER)t.push(n);for(let o of n.node.children)r(o);if(e===Tf.POSTORDER)t.push(n)}}setContext(e,t){if(this.children.length>0){let r=this.children.map((n)=>n.node.id);throw Error("Cannot set context after children have been added: "+r.join(","))}if(!this._context)this._context={};this._context[e]=t}getContext(e){let t=this._context?.[e];if(t!==void 0)return t;if(t===void 0&&!this.scope?.node)throw Error(`No context value present for ${e} key`);return this.scope&&this.scope.node.getContext(e)}getAllContext(e){let t={...e};for(let r of this._scopes)Object.assign(t,r.node._context);return t}tryGetContext(e){let t=this._context?.[e];if(t!==void 0)return t;return this.scope&&this.scope.node.tryGetContext(e)}get metadata(){return[...this._metadata??[]]}addMetadata(e,t,r={}){if(t==null)return;let n=this;function o(){if(r.stackTraceOverride&&r.stackTraceOverride.length>0)return r.stackTraceOverride;return r.stackTrace??!1?hH.captureStackTrace(r.traceFromFunction??n.addMetadata):void 0}if(!this._metadata)this._metadata=[];this._metadata.push({type:e,data:t,trace:o()})}get root(){return this._scopes[0]}get locked(){if(this._locked)return!0;if(this.scope&&this.scope.node.locked)return!0;return!1}addDependency(...e){if(!this._dependencies)this._dependencies=new Set;for(let t of e)this._dependencies.add(t)}removeDependency(...e){if(!this._dependencies)this._dependencies=new Set;for(let t of e)this._dependencies.delete(t)}get dependencies(){let e=[];if(this._dependencies)for(let t of this._dependencies)for(let r of ak.Dependable.of(t).dependencyRoots)e.push(r);return e}tryRemoveChild(e){if(!this._children||!(e in this._children))return!1;return delete this._children[e],!0}addValidation(e){if(!this._validations)this._validations=[];this._validations.push(e)}validate(){return(this._validations??[]).flatMap((e)=>e.validate())}lock(){this._locked=!0}with(...e){let t=this.findAll();for(let r of e)for(let n of t)if(r.supports(n))r.applyTo(n);return this.host}addChild(e,t){if(this.locked){if(!this.path)throw Error("Cannot add children during synthesis");throw Error(`Cannot add children to "${this.path}" during synthesis`)}if(!this._children)this._children={};if(this._children[t]){let r=this.id??"",n=this.host.constructor.name;throw Error(`There is already a Construct with name '${t}' in ${n}${r.length>0?" ["+r+"]":""}`)}this._children[t]=e}}uk.Node=Rf;class Zh{static[nb]={fqn:"constructs.Construct",version:"10.8.1"};static isConstruct(e){return e&&typeof e==="object"&&e[lk]}node;constructor(e,t){this.node=new Rf(this,e,t),ak.Dependable.implement(this,{dependencyRoots:[this]})}with(...e){return this.node.with(...e)}toString(){return this.node.path||"<root>"}}uk.Construct=Zh;var Tf;(function(e){e[e.PREORDER=0]="PREORDER",e[e.POSTORDER=1]="POSTORDER"})(Tf||(uk.ConstructOrder=Tf={}));var gH=new RegExp(`[${Rf.PATH_SEP}${ck.ADDR_SEP}]`,"g");function sk(e){return e.replace(gH,"--")}Object.defineProperty(Zh.prototype,lk,{value:!0,enumerable:!1,writable:!1});class dk extends Zh{static[nb]={fqn:"constructs.RootConstruct",version:"10.8.1"};constructor(e){super(void 0,e??"")}}uk.RootConstruct=dk});var $n=Ln(function(ja){var wH=ja&&ja.__createBinding||(Object.create?function(e,t,r,n){if(n===void 0)n=r;var o=Object.getOwnPropertyDescriptor(t,r);if(!o||("get"in o?!t.__esModule:o.writable||o.configurable))o={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,n,o)}:function(e,t,r,n){if(n===void 0)n=r;e[n]=t[r]}),mk=ja&&ja.__exportStar||function(e,t){for(var r in e)if(r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r))wH(t,e,r)};Object.defineProperty(ja,"__esModule",{value:!0});mk(fk(),ja);mk(rb(),ja)});var Xd=Ln(function(wg,Lb){Object.defineProperty(wg,"__esModule",{value:!0});wg.default=E4;function E4(e){if(e===void 0||e===null)throw TypeError("Expected a string but received a ".concat(e));if(e.constructor.name!=="String")throw TypeError("Expected a string but received a ".concat(e.constructor.name))}Lb.exports=wg.default;Lb.exports.default=wg.default});var qb=Ln(function(bg,$b){Object.defineProperty(bg,"__esModule",{value:!0});bg.default=A4;function R4(e){return Object.prototype.toString.call(e)==="[object RegExp]"}function A4(e,t){for(var r=0;r<t.length;r++){var n=t[r];if(e===n||R4(n)&&n.test(e))return!0}return!1}$b.exports=bg.default;$b.exports.default=bg.default});var Z0=Ln(function(Eg,jb){Object.defineProperty(Eg,"__esModule",{value:!0});Eg.default=void 0;var I4=function(t,r){return t.indexOf(r)!==-1},ise=Eg.default=I4;jb.exports=Eg.default;jb.exports.default=Eg.default});var Rg=Ln(function(Tg,Wb){Object.defineProperty(Tg,"__esModule",{value:!0});Tg.default=C4;function Hb(e){return Hb=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Hb(e)}function C4(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;if(Hb(e)!=="object"||e===null)e={};for(var r in t)if(typeof e[r]>"u")e[r]=t[r];return e}Wb.exports=Tg.default;Wb.exports.default=Tg.default});var Vb=Ln(function(Ag,Kb){Object.defineProperty(Ag,"__esModule",{value:!0});Ag.default=N4;var k4=eO(Xd()),O4=eO(Rg());function eO(e){return e&&e.__esModule?e:{default:e}}var D4={require_tld:!0,allow_underscores:!1,allow_trailing_dot:!1,allow_numeric_tld:!1,allow_wildcard:!1,ignore_max_length:!1};function N4(e,t){if((0,k4.default)(e),t=(0,O4.default)(t,D4),t.allow_trailing_dot&&e[e.length-1]===".")e=e.substring(0,e.length-1);if(t.allow_wildcard===!0&&e.indexOf("*.")===0)e=e.substring(2);var r=e.split("."),n=r[r.length-1];if(t.require_tld){if(r.length<2)return!1;if(!t.allow_numeric_tld&&!/^([a-z\u00A1-\u00A8\u00AA-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]{2,}|xn[a-z0-9-]{2,})$/i.test(n))return!1;if(/\s/.test(n))return!1}if(!t.allow_numeric_tld&&/^\d+$/.test(n))return!1;return r.every(function(o){if(o.length>63&&!t.ignore_max_length)return!1;if(!/^[a-z_\u00a1-\uffff0-9-]+$/i.test(o))return!1;if(/[\uff01-\uff5e]/.test(o))return!1;if(/^-|-$/.test(o))return!1;if(!t.allow_underscores&&/_/.test(o))return!1;return!0})}Kb.exports=Ag.default;Kb.exports.default=Ag.default});var Gb=Ln(function(Pg,zb){Object.defineProperty(Pg,"__esModule",{value:!0});Pg.default=Jb;var U4=B4(Xd());function B4(e){return e&&e.__esModule?e:{default:e}}function Qb(e){return Qb=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Qb(e)}var tO="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",Ja="(".concat(tO,"[.]){3}").concat(tO),M4=new RegExp("^".concat(Ja,"$")),an="(?:[0-9a-fA-F]{1,4})",L4=new RegExp("^("+"(?:".concat(an,":){7}(?:").concat(an,"|:)|")+"(?:".concat(an,":){6}(?:").concat(Ja,"|:").concat(an,"|:)|")+"(?:".concat(an,":){5}(?::").concat(Ja,"|(:").concat(an,"){1,2}|:)|")+"(?:".concat(an,":){4}(?:(:").concat(an,"){0,1}:").concat(Ja,"|(:").concat(an,"){1,3}|:)|")+"(?:".concat(an,":){3}(?:(:").concat(an,"){0,2}:").concat(Ja,"|(:").concat(an,"){1,4}|:)|")+"(?:".concat(an,":){2}(?:(:").concat(an,"){0,3}:").concat(Ja,"|(:").concat(an,"){1,5}|:)|")+"(?:".concat(an,":){1}(?:(:").concat(an,"){0,4}:").concat(Ja,"|(:").concat(an,"){1,6}|:)|")+"(?::((?::".concat(an,"){0,5}:").concat(Ja,"|(?::").concat(an,"){1,7}|:))")+")(%[0-9a-zA-Z.]{1,})?$");function Jb(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};(0,U4.default)(e);var r=(Qb(t)==="object"?t.version:arguments[1])||"";if(!r)return Jb(e,{version:4})||Jb(e,{version:6});if(r.toString()==="4")return M4.test(e);if(r.toString()==="6")return L4.test(e);return!1}zb.exports=Pg.default;zb.exports.default=Pg.default});var iO=Ln(function(Ig,Xb){Object.defineProperty(Ig,"__esModule",{value:!0});Ig.default=Y4;var q4=Zd(Xd()),rO=Zd(qb()),Yb=Zd(Z0()),j4=Zd(Vb()),nO=Zd(Gb()),H4=Zd(Rg());function Zd(e){return e&&e.__esModule?e:{default:e}}function W4(e,t){return J4(e)||Q4(e,t)||V4(e,t)||K4()}function K4(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
5
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function V4(e,t){if(e){if(typeof e=="string")return oO(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?oO(e,t):void 0}}function oO(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Q4(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,o,i,s,a=[],c=!0,l=!1;try{if(i=(r=r.call(e)).next,t===0){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=i.call(r)).done)&&(a.push(n.value),a.length!==t);c=!0);}catch(d){l=!0,o=d}finally{try{if(!c&&r.return!=null&&(s=r.return(),Object(s)!==s))return}finally{if(l)throw o}}return a}}function J4(e){if(Array.isArray(e))return e}var z4={protocols:["http","https","ftp"],require_tld:!0,require_protocol:!1,require_host:!0,require_port:!1,require_valid_protocol:!0,allow_underscores:!1,allow_trailing_dot:!1,allow_protocol_relative_urls:!1,allow_fragments:!0,allow_query_components:!0,validate_length:!0,max_allowed_length:2084},G4=/^\[([^\]]+)\](?::([0-9]+))?$/;function Y4(e,t){if((0,q4.default)(e),!e||/[\s<>]/.test(e))return!1;if(e.indexOf("mailto:")===0)return!1;if(t=(0,H4.default)(t,z4),t.validate_length&&e.length>t.max_allowed_length)return!1;if(!t.allow_fragments&&(0,Yb.default)(e,"#"))return!1;if(!t.allow_query_components&&((0,Yb.default)(e,"?")||(0,Yb.default)(e,"&")))return!1;var r,n,o,i,s,a,c,l;c=e.split("#"),e=c.shift(),c=e.split("?"),e=c.shift();var d=e.match(/^([a-z][a-z0-9+\-.]*):/i),u=!1,m=function(se){if(u=!0,r=se.toLowerCase(),t.require_valid_protocol&&t.protocols.indexOf(r)===-1)return!1;return e.substring(d[0].length)};if(d){var h=d[1],S=e.substring(d[0].length),x=S.slice(0,2)==="//";if(!x){var v=S.indexOf("/"),w=v===-1?S:S.substring(0,v),P=w.indexOf("@");if(P!==-1){var F=w.substring(0,P),R=/^[a-zA-Z0-9\-_.%:]*$/,b=R.test(F),A=/%[0-9a-fA-F]{2}/.test(F);if(b&&!A){if(t.require_protocol)return!1}else if(e=m(h),e===!1)return!1}else{var D=/^[0-9]/.test(S);if(D){if(t.require_protocol)return!1}else if(e=m(h),e===!1)return!1}}else if(e=m(h),e===!1)return!1}else if(t.require_protocol)return!1;if(e.slice(0,2)==="//"){if(!u&&!t.allow_protocol_relative_urls)return!1;e=e.slice(2)}if(e==="")return!1;if(c=e.split("/"),e=c.shift(),e===""&&!t.require_host)return!0;if(c=e.split("@"),c.length>1){if(t.disallow_auth)return!1;if(c[0]==="")return!1;if(n=c.shift(),n.indexOf(":")>=0&&n.split(":").length>2)return!1;var B=n.split(":"),J=W4(B,2),G=J[0],ce=J[1];if(G===""&&ce==="")return!1}i=c.join("@"),a=null,l=null;var re=i.match(G4);if(re)o="",l=re[1],a=re[2]||null;else if(c=i.split(":"),o=c.shift(),c.length)a=c.join(":");if(a!==null&&a.length>0){if(s=parseInt(a,10),!/^[0-9]+$/.test(a)||s<=0||s>65535)return!1}else if(t.require_port)return!1;if(t.host_whitelist)return(0,rO.default)(o,t.host_whitelist);if(o===""&&!t.require_host)return!0;if(!(0,nO.default)(o)&&!(0,j4.default)(o,t)&&(!l||!(0,nO.default)(l,6)))return!1;if(o=o||l,t.host_blacklist&&(0,rO.default)(o,t.host_blacklist))return!1;return!0}Xb.exports=Ig.default;Xb.exports.default=Ig.default});var fO=Ln(function(Dg,oE){Object.defineProperty(Dg,"__esModule",{value:!0});Dg.default=dK;var cK=lK(Xd());function lK(e){return e&&e.__esModule?e:{default:e}}function nE(e){return nE=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},nE(e)}function dK(e,t){(0,cK.default)(e);var r,n;if(nE(t)==="object")r=t.min||0,n=t.max;else r=arguments[1],n=arguments[2];var o=encodeURI(e).split(/%..|./).length-1;return o>=r&&(typeof n>"u"||o<=n)}oE.exports=Dg.default;oE.exports.default=Dg.default});var hO=Ln(function(Ng,sE){Object.defineProperty(Ng,"__esModule",{value:!0});Ng.default=TK;var pK=ru(Xd()),mO=ru(qb()),iE=ru(fO()),fK=ru(Vb()),yO=ru(Gb()),mK=ru(Rg());function ru(e){return e&&e.__esModule?e:{default:e}}var yK={allow_display_name:!1,allow_underscores:!1,require_display_name:!1,allow_utf8_local_part:!0,require_tld:!0,blacklisted_chars:"",ignore_max_length:!1,host_blacklist:[],host_whitelist:[]},hK=/^([^\x00-\x1F\x7F-\x9F\cX]+)</i,gK=/^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~]+$/i,SK=/^[a-z\d]+$/,vK=/^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f]))*$/i,xK=/^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\u00A1-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+$/i,wK=/^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*$/i,bK=254;function EK(e){var t=e.replace(/^"(.+)"$/,"$1");if(!t.trim())return!1;var r=/[\.";<>]/.test(t);if(r){if(t===e)return!1;var n=t.split('"').length===t.split("\\\"").length;if(!n)return!1}return!0}function TK(e,t){if((0,pK.default)(e),t=(0,mK.default)(t,yK),t.require_display_name||t.allow_display_name){var r=e.match(hK);if(r){var n=r[1];if(e=e.replace(n,"").replace(/(^<|>$)/g,""),n.endsWith(" "))n=n.slice(0,-1);if(!EK(n))return!1}else if(t.require_display_name)return!1}if(!t.ignore_max_length&&e.length>bK)return!1;var o=e.split("@"),i=o.pop(),s=i.toLowerCase();if(t.host_blacklist.length>0&&(0,mO.default)(s,t.host_blacklist))return!1;if(t.host_whitelist.length>0&&!(0,mO.default)(s,t.host_whitelist))return!1;var a=o.join("@");if(t.domain_specific_validation&&(s==="gmail.com"||s==="googlemail.com")){a=a.toLowerCase();var c=a.split("+")[0];if(!(0,iE.default)(c.replace(/\./g,""),{min:6,max:30}))return!1;var l=c.split(".");for(var d=0;d<l.length;d++)if(!SK.test(l[d]))return!1}if(t.ignore_max_length===!1&&(!(0,iE.default)(a,{max:64})||!(0,iE.default)(i,{max:254})))return!1;if(!(0,fK.default)(i,{require_tld:t.require_tld,ignore_max_length:t.ignore_max_length,allow_underscores:t.allow_underscores})){if(!t.allow_ip_domain)return!1;if(!(0,yO.default)(i)){if(!i.startsWith("[")||!i.endsWith("]"))return!1;var u=i.slice(1,-1);if(u.length===0||!(0,yO.default)(u))return!1}}if(t.blacklisted_chars){if(a.search(new RegExp("[".concat(t.blacklisted_chars,"]+"),"g"))!==-1)return!1}if(a[0]==='"'&&a[a.length-1]==='"')return a=a.slice(1,a.length-1),t.allow_utf8_local_part?wK.test(a):vK.test(a);var m=t.allow_utf8_local_part?xK:gK,h=a.split(".");for(var S=0;S<h.length;S++)if(!m.test(h[S]))return!1;return!0}sE.exports=Ng.default;sE.exports.default=Ng.default});var yL=Ln(function(YLe,px){var qM,jM,HM,WM,KM,VM,QM,JM,zM,GM,YM,XM,ZM,dx,gA,eL,tL,rL,lp,nL,oL,iL,sL,aL,cL,lL,dL,uL,ux,pL,fL,mL;(function(e){var t=typeof global==="object"?global:typeof self==="object"?self:typeof this==="object"?this:{};if(typeof define==="function"&&define.amd)define("tslib",["exports"],function(n){e(r(t,r(n)))});else if(typeof px==="object"&&typeof YLe==="object")e(r(t,r(YLe)));else e(r(t));function r(n,o){if(n!==t)if(typeof Object.create==="function")Object.defineProperty(n,"__esModule",{value:!0});else n.__esModule=!0;return function(i,s){return n[i]=o?o(i,s):s}}})(function(e){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,s){i.__proto__=s}||function(i,s){for(var a in s)if(Object.prototype.hasOwnProperty.call(s,a))i[a]=s[a]};qM=function(i,s){if(typeof s!=="function"&&s!==null)throw TypeError("Class extends value "+String(s)+" is not a constructor or null");t(i,s);function a(){this.constructor=i}i.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)},jM=Object.assign||function(i){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var l in s)if(Object.prototype.hasOwnProperty.call(s,l))i[l]=s[l]}return i},HM=function(i,s){var a={};for(var c in i)if(Object.prototype.hasOwnProperty.call(i,c)&&s.indexOf(c)<0)a[c]=i[c];if(i!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var l=0,c=Object.getOwnPropertySymbols(i);l<c.length;l++)if(s.indexOf(c[l])<0&&Object.prototype.propertyIsEnumerable.call(i,c[l]))a[c[l]]=i[c[l]]}return a},WM=function(i,s,a,c){var l=arguments.length,d=l<3?s:c===null?c=Object.getOwnPropertyDescriptor(s,a):c,u;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")d=Reflect.decorate(i,s,a,c);else for(var m=i.length-1;m>=0;m--)if(u=i[m])d=(l<3?u(d):l>3?u(s,a,d):u(s,a))||d;return l>3&&d&&Object.defineProperty(s,a,d),d},KM=function(i,s){return function(a,c){s(a,c,i)}},VM=function(i,s,a,c,l,d){function u(A){if(A!==void 0&&typeof A!=="function")throw TypeError("Function expected");return A}var m=c.kind,h=m==="getter"?"get":m==="setter"?"set":"value",S=!s&&i?c.static?i:i.prototype:null,x=s||(S?Object.getOwnPropertyDescriptor(S,c.name):{}),v,w=!1;for(var P=a.length-1;P>=0;P--){var F={};for(var R in c)F[R]=R==="access"?{}:c[R];for(var R in c.access)F.access[R]=c.access[R];F.addInitializer=function(A){if(w)throw TypeError("Cannot add initializers after decoration has completed");d.push(u(A||null))};var b=(0,a[P])(m==="accessor"?{get:x.get,set:x.set}:x[h],F);if(m==="accessor"){if(b===void 0)continue;if(b===null||typeof b!=="object")throw TypeError("Object expected");if(v=u(b.get))x.get=v;if(v=u(b.set))x.set=v;if(v=u(b.init))l.unshift(v)}else if(v=u(b))if(m==="field")l.unshift(v);else x[h]=v}if(S)Object.defineProperty(S,c.name,x);w=!0},QM=function(i,s,a){var c=arguments.length>2;for(var l=0;l<s.length;l++)a=c?s[l].call(i,a):s[l].call(i);return c?a:void 0},JM=function(i){return typeof i==="symbol"?i:"".concat(i)},zM=function(i,s,a){if(typeof s==="symbol")s=s.description?"[".concat(s.description,"]"):"";return Object.defineProperty(i,"name",{configurable:!0,value:a?"".concat(a," ",s):s})},GM=function(i,s){if(typeof Reflect==="object"&&typeof Reflect.metadata==="function")return Reflect.metadata(i,s)},YM=function(i,s,a,c){function l(d){return d instanceof a?d:new a(function(u){u(d)})}return new(a||(a=Promise))(function(d,u){function m(x){try{S(c.next(x))}catch(v){u(v)}}function h(x){try{S(c.throw(x))}catch(v){u(v)}}function S(x){x.done?d(x.value):l(x.value).then(m,h)}S((c=c.apply(i,s||[])).next())})},XM=function(i,s){var a={label:0,sent:function(){if(d[0]&1)throw d[1];return d[1]},trys:[],ops:[]},c,l,d,u=Object.create((typeof Iterator==="function"?Iterator:Object).prototype);return u.next=m(0),u.throw=m(1),u.return=m(2),typeof Symbol==="function"&&(u[Symbol.iterator]=function(){return this}),u;function m(S){return function(x){return h([S,x])}}function h(S){if(c)throw TypeError("Generator is already executing.");while(u&&(u=0,S[0]&&(a=0)),a)try{if(c=1,l&&(d=S[0]&2?l.return:S[0]?l.throw||((d=l.return)&&d.call(l),0):l.next)&&!(d=d.call(l,S[1])).done)return d;if(l=0,d)S=[S[0]&2,d.value];switch(S[0]){case 0:case 1:d=S;break;case 4:return a.label++,{value:S[1],done:!1};case 5:a.label++,l=S[1],S=[0];continue;case 7:S=a.ops.pop(),a.trys.pop();continue;default:if((d=a.trys,!(d=d.length>0&&d[d.length-1]))&&(S[0]===6||S[0]===2)){a=0;continue}if(S[0]===3&&(!d||S[1]>d[0]&&S[1]<d[3])){a.label=S[1];break}if(S[0]===6&&a.label<d[1]){a.label=d[1],d=S;break}if(d&&a.label<d[2]){a.label=d[2],a.ops.push(S);break}if(d[2])a.ops.pop();a.trys.pop();continue}S=s.call(i,a)}catch(x){S=[6,x],l=0}finally{c=d=0}if(S[0]&5)throw S[1];return{value:S[0]?S[1]:void 0,done:!0}}},ZM=function(i,s){for(var a in i)if(a!=="default"&&!Object.prototype.hasOwnProperty.call(s,a))ux(s,i,a)},ux=Object.create?function(i,s,a,c){if(c===void 0)c=a;var l=Object.getOwnPropertyDescriptor(s,a);if(!l||("get"in l?!s.__esModule:l.writable||l.configurable))l={enumerable:!0,get:function(){return s[a]}};Object.defineProperty(i,c,l)}:function(i,s,a,c){if(c===void 0)c=a;i[c]=s[a]},dx=function(i){var s=typeof Symbol==="function"&&Symbol.iterator,a=s&&i[s],c=0;if(a)return a.call(i);if(i&&typeof i.length==="number")return{next:function(){if(i&&c>=i.length)i=void 0;return{value:i&&i[c++],done:!i}}};throw TypeError(s?"Object is not iterable.":"Symbol.iterator is not defined.")},gA=function(i,s){var a=typeof Symbol==="function"&&i[Symbol.iterator];if(!a)return i;var c=a.call(i),l,d=[],u;try{while((s===void 0||s-- >0)&&!(l=c.next()).done)d.push(l.value)}catch(m){u={error:m}}finally{try{if(l&&!l.done&&(a=c.return))a.call(c)}finally{if(u)throw u.error}}return d},eL=function(){for(var i=[],s=0;s<arguments.length;s++)i=i.concat(gA(arguments[s]));return i},tL=function(){for(var i=0,s=0,a=arguments.length;s<a;s++)i+=arguments[s].length;for(var c=Array(i),l=0,s=0;s<a;s++)for(var d=arguments[s],u=0,m=d.length;u<m;u++,l++)c[l]=d[u];return c},rL=function(i,s,a){if(a||arguments.length===2){for(var c=0,l=s.length,d;c<l;c++)if(d||!(c in s)){if(!d)d=Array.prototype.slice.call(s,0,c);d[c]=s[c]}}return i.concat(d||Array.prototype.slice.call(s))},lp=function(i){return this instanceof lp?(this.v=i,this):new lp(i)},nL=function(i,s,a){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var c=a.apply(i,s||[]),l,d=[];return l=Object.create((typeof AsyncIterator==="function"?AsyncIterator:Object).prototype),m("next"),m("throw"),m("return",u),l[Symbol.asyncIterator]=function(){return this},l;function u(P){return function(F){return Promise.resolve(F).then(P,v)}}function m(P,F){if(c[P]){if(l[P]=function(R){return new Promise(function(b,A){d.push([P,R,b,A])>1||h(P,R)})},F)l[P]=F(l[P])}}function h(P,F){try{S(c[P](F))}catch(R){w(d[0][3],R)}}function S(P){P.value instanceof lp?Promise.resolve(P.value.v).then(x,v):w(d[0][2],P)}function x(P){h("next",P)}function v(P){h("throw",P)}function w(P,F){if(P(F),d.shift(),d.length)h(d[0][0],d[0][1])}},oL=function(i){var s,a;return s={},c("next"),c("throw",function(l){throw l}),c("return"),s[Symbol.iterator]=function(){return this},s;function c(l,d){s[l]=i[l]?function(u){return(a=!a)?{value:lp(i[l](u)),done:!1}:d?d(u):u}:d}},iL=function(i){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var s=i[Symbol.asyncIterator],a;return s?s.call(i):(i=typeof dx==="function"?dx(i):i[Symbol.iterator](),a={},c("next"),c("throw"),c("return"),a[Symbol.asyncIterator]=function(){return this},a);function c(d){a[d]=i[d]&&function(u){return new Promise(function(m,h){u=i[d](u),l(m,h,u.done,u.value)})}}function l(d,u,m,h){Promise.resolve(h).then(function(S){d({value:S,done:m})},u)}},sL=function(i,s){if(Object.defineProperty)Object.defineProperty(i,"raw",{value:s});else i.raw=s;return i};var r=Object.create?function(i,s){Object.defineProperty(i,"default",{enumerable:!0,value:s})}:function(i,s){i.default=s},n=function(i){return n=Object.getOwnPropertyNames||function(s){var a=[];for(var c in s)if(Object.prototype.hasOwnProperty.call(s,c))a[a.length]=c;return a},n(i)};aL=function(i){if(i&&i.__esModule)return i;var s={};if(i!=null){for(var a=n(i),c=0;c<a.length;c++)if(a[c]!=="default")ux(s,i,a[c])}return r(s,i),s},cL=function(i){return i&&i.__esModule?i:{default:i}},lL=function(i,s,a,c){if(a==="a"&&!c)throw TypeError("Private accessor was defined without a getter");if(typeof s==="function"?i!==s||!c:!s.has(i))throw TypeError("Cannot read private member from an object whose class did not declare it");return a==="m"?c:a==="a"?c.call(i):c?c.value:s.get(i)},dL=function(i,s,a,c,l){if(c==="m")throw TypeError("Private method is not writable");if(c==="a"&&!l)throw TypeError("Private accessor was defined without a setter");if(typeof s==="function"?i!==s||!l:!s.has(i))throw TypeError("Cannot write private member to an object whose class did not declare it");return c==="a"?l.call(i,a):l?l.value=a:s.set(i,a),a},uL=function(i,s){if(s===null||typeof s!=="object"&&typeof s!=="function")throw TypeError("Cannot use 'in' operator on non-object");return typeof i==="function"?s===i:i.has(s)},pL=function(i,s,a){if(s!==null&&s!==void 0){if(typeof s!=="object"&&typeof s!=="function")throw TypeError("Object expected.");var c,l;if(a){if(!Symbol.asyncDispose)throw TypeError("Symbol.asyncDispose is not defined.");c=s[Symbol.asyncDispose]}if(c===void 0){if(!Symbol.dispose)throw TypeError("Symbol.dispose is not defined.");if(c=s[Symbol.dispose],a)l=c}if(typeof c!=="function")throw TypeError("Object not disposable.");if(l)c=function(){try{l.call(this)}catch(d){return Promise.reject(d)}};i.stack.push({value:s,dispose:c,async:a})}else if(a)i.stack.push({async:!0});return s};var o=typeof SuppressedError==="function"?SuppressedError:function(i,s,a){var c=Error(a);return c.name="SuppressedError",c.error=i,c.suppressed=s,c};fL=function(i){function s(d){i.error=i.hasError?new o(d,i.error,"An error was suppressed during disposal."):d,i.hasError=!0}var a,c=0;function l(){while(a=i.stack.pop())try{if(!a.async&&c===1)return c=0,i.stack.push(a),Promise.resolve().then(l);if(a.dispose){var d=a.dispose.call(a.value);if(a.async)return c|=2,Promise.resolve(d).then(l,function(u){return s(u),l()})}else c|=1}catch(u){s(u)}if(c===1)return i.hasError?Promise.reject(i.error):Promise.resolve();if(i.hasError)throw i.error}return l()},mL=function(i,s){if(typeof i==="string"&&/^\.\.?\//.test(i))return i.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(a,c,l,d,u){return c?s?".jsx":".js":l&&(!d||!u)?a:l+d+"."+u.toLowerCase()+"js"});return i},e("__extends",qM),e("__assign",jM),e("__rest",HM),e("__decorate",WM),e("__param",KM),e("__esDecorate",VM),e("__runInitializers",QM),e("__propKey",JM),e("__setFunctionName",zM),e("__metadata",GM),e("__awaiter",YM),e("__generator",XM),e("__exportStar",ZM),e("__createBinding",ux),e("__values",dx),e("__read",gA),e("__spread",eL),e("__spreadArrays",tL),e("__spreadArray",rL),e("__await",lp),e("__asyncGenerator",nL),e("__asyncDelegator",oL),e("__asyncValues",iL),e("__makeTemplateObject",sL),e("__importStar",aL),e("__importDefault",cL),e("__classPrivateFieldGet",lL),e("__classPrivateFieldSet",dL),e("__classPrivateFieldIn",uL),e("__addDisposableResource",pL),e("__disposeResources",fL),e("__rewriteRelativeImportExtension",mL)})});var NL=Ln(function(){/*! *****************************************************************************
|
|
6
|
+
Copyright (C) Microsoft. All rights reserved.
|
|
7
|
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
|
8
|
+
this file except in compliance with the License. You may obtain a copy of the
|
|
9
|
+
License at http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
|
|
11
|
+
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
12
|
+
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
|
13
|
+
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
|
14
|
+
MERCHANTABLITY OR NON-INFRINGEMENT.
|
|
15
|
+
|
|
16
|
+
See the Apache Version 2.0 License for specific language governing permissions
|
|
17
|
+
and limitations under the License.
|
|
18
|
+
***************************************************************************** */var DL;(function(e){(function(t){var r=typeof globalThis==="object"?globalThis:typeof global==="object"?global:typeof self==="object"?self:typeof this==="object"?this:a(),n=o(e);if(typeof r.Reflect<"u")n=o(r.Reflect,n);if(t(n,r),typeof r.Reflect>"u")r.Reflect=e;function o(c,l){return function(d,u){if(Object.defineProperty(c,d,{configurable:!0,writable:!0,value:u}),l)l(d,u)}}function i(){try{return Function("return this;")()}catch(c){}}function s(){try{return(0,eval)("(function() { return this; })()")}catch(c){}}function a(){return i()||s()}})(function(t,r){var n=Object.prototype.hasOwnProperty,o=typeof Symbol==="function",i=o&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",s=o&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",a=typeof Object.create==="function",c={__proto__:[]}instanceof Array,l=!a&&!c,d={create:a?function(){return Pw(Object.create(null))}:c?function(){return Pw({__proto__:null})}:function(){return Pw({})},has:l?function(q,K){return n.call(q,K)}:function(q,K){return K in q},get:l?function(q,K){return n.call(q,K)?q[K]:void 0}:function(q,K){return q[K]}},u=Object.getPrototypeOf(Function),m=typeof Map==="function"&&typeof Map.prototype.entries==="function"?Map:r2(),h=typeof Set==="function"&&typeof Set.prototype.entries==="function"?Set:n2(),S=typeof WeakMap==="function"?WeakMap:o2(),x=o?Symbol.for("@reflect-metadata:registry"):void 0,v=Zj(),w=e2(v);function P(q,K,Y,ue){if(!fe(Y)){if(!ut(q))throw TypeError();if(!Be(K))throw TypeError();if(!Be(ue)&&!fe(ue)&&!qt(ue))throw TypeError();if(qt(ue))ue=void 0;return Y=jt(Y),Z(q,K,Y,ue)}else{if(!ut(q))throw TypeError();if(!Mn(K))throw TypeError();return re(q,K)}}t("decorate",P);function F(q,K){function Y(ue,$e){if(!Be(ue))throw TypeError();if(!fe($e)&&!Ao($e))throw TypeError();et(q,K,ue,$e)}return Y}t("metadata",F);function R(q,K,Y,ue){if(!Be(Y))throw TypeError();if(!fe(ue))ue=jt(ue);return et(q,K,Y,ue)}t("defineMetadata",R);function b(q,K,Y){if(!Be(K))throw TypeError();if(!fe(Y))Y=jt(Y);return se(q,K,Y)}t("hasMetadata",b);function A(q,K,Y){if(!Be(K))throw TypeError();if(!fe(Y))Y=jt(Y);return te(q,K,Y)}t("hasOwnMetadata",A);function D(q,K,Y){if(!Be(K))throw TypeError();if(!fe(Y))Y=jt(Y);return Ne(q,K,Y)}t("getMetadata",D);function B(q,K,Y){if(!Be(K))throw TypeError();if(!fe(Y))Y=jt(Y);return ze(q,K,Y)}t("getOwnMetadata",B);function J(q,K){if(!Be(q))throw TypeError();if(!fe(K))K=jt(K);return xt(q,K)}t("getMetadataKeys",J);function G(q,K){if(!Be(q))throw TypeError();if(!fe(K))K=jt(K);return dt(q,K)}t("getOwnMetadataKeys",G);function ce(q,K,Y){if(!Be(K))throw TypeError();if(!fe(Y))Y=jt(Y);if(!Be(K))throw TypeError();if(!fe(Y))Y=jt(Y);var ue=hf(K,Y,!1);if(fe(ue))return!1;return ue.OrdinaryDeleteMetadata(q,K,Y)}t("deleteMetadata",ce);function re(q,K){for(var Y=q.length-1;Y>=0;--Y){var ue=q[Y],$e=ue(K);if(!fe($e)&&!qt($e)){if(!Mn($e))throw TypeError();K=$e}}return K}function Z(q,K,Y,ue){for(var $e=q.length-1;$e>=0;--$e){var Qr=q[$e],xn=Qr(K,Y,ue);if(!fe(xn)&&!qt(xn)){if(!Be(xn))throw TypeError();ue=xn}}return ue}function se(q,K,Y){var ue=te(q,K,Y);if(ue)return!0;var $e=Aw(K);if(!qt($e))return se(q,$e,Y);return!1}function te(q,K,Y){var ue=hf(K,Y,!1);if(fe(ue))return!1;return Ve(ue.OrdinaryHasOwnMetadata(q,K,Y))}function Ne(q,K,Y){var ue=te(q,K,Y);if(ue)return ze(q,K,Y);var $e=Aw(K);if(!qt($e))return Ne(q,$e,Y);return}function ze(q,K,Y){var ue=hf(K,Y,!1);if(fe(ue))return;return ue.OrdinaryGetOwnMetadata(q,K,Y)}function et(q,K,Y,ue){var $e=hf(Y,ue,!0);$e.OrdinaryDefineOwnMetadata(q,K,Y,ue)}function xt(q,K){var Y=dt(q,K),ue=Aw(q);if(ue===null)return Y;var $e=xt(ue,K);if($e.length<=0)return Y;if(Y.length<=0)return $e;var Qr=new h,xn=[];for(var Et=0,xe=Y;Et<xe.length;Et++){var Re=xe[Et],Pe=Qr.has(Re);if(!Pe)Qr.add(Re),xn.push(Re)}for(var ke=0,It=$e;ke<It.length;ke++){var Re=It[ke],Pe=Qr.has(Re);if(!Pe)Qr.add(Re),xn.push(Re)}return xn}function dt(q,K){var Y=hf(q,K,!1);if(!Y)return[];return Y.OrdinaryOwnMetadataKeys(q,K)}function Le(q){if(q===null)return 1;switch(typeof q){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return q===null?1:6;default:return 6}}function fe(q){return q===void 0}function qt(q){return q===null}function on(q){return typeof q==="symbol"}function Be(q){return typeof q==="object"?q!==null:typeof q==="function"}function xr(q,K){switch(Le(q)){case 0:return q;case 1:return q;case 2:return q;case 3:return q;case 4:return q;case 5:return q}var Y=K===3?"string":K===5?"number":"default",ue=Vs(q,i);if(ue!==void 0){var $e=ue.call(q,Y);if(Be($e))throw TypeError();return $e}return uo(q,Y==="default"?"number":Y)}function uo(q,K){if(K==="string"){var Y=q.toString;if(Ht(Y)){var ue=Y.call(q);if(!Be(ue))return ue}var $e=q.valueOf;if(Ht($e)){var ue=$e.call(q);if(!Be(ue))return ue}}else{var $e=q.valueOf;if(Ht($e)){var ue=$e.call(q);if(!Be(ue))return ue}var Qr=q.toString;if(Ht(Qr)){var ue=Qr.call(q);if(!Be(ue))return ue}}throw TypeError()}function Ve(q){return!!q}function lt(q){return""+q}function jt(q){var K=xr(q,3);if(on(K))return K;return lt(K)}function ut(q){return Array.isArray?Array.isArray(q):q instanceof Object?q instanceof Array:Object.prototype.toString.call(q)==="[object Array]"}function Ht(q){return typeof q==="function"}function Mn(q){return typeof q==="function"}function Ao(q){switch(Le(q)){case 3:return!0;case 4:return!0;default:return!1}}function ls(q,K){return q===K||q!==q&&K!==K}function Vs(q,K){var Y=q[K];if(Y===void 0||Y===null)return;if(!Ht(Y))throw TypeError();return Y}function yf(q){var K=Vs(q,s);if(!Ht(K))throw TypeError();var Y=K.call(q);if(!Be(Y))throw TypeError();return Y}function Gn(q){return q.value}function UC(q){var K=q.next();return K.done?!1:K}function BC(q){var K=q.return;if(K)K.call(q)}function Aw(q){var K=Object.getPrototypeOf(q);if(typeof q!=="function"||q===u)return K;if(K!==u)return K;var Y=q.prototype,ue=Y&&Object.getPrototypeOf(Y);if(ue==null||ue===Object.prototype)return K;var $e=ue.constructor;if(typeof $e!=="function")return K;if($e===q)return K;return $e}function Xj(){var q;if(!fe(x)&&typeof r.Reflect<"u"&&!(x in r.Reflect)&&typeof r.Reflect.defineMetadata==="function")q=t2(r.Reflect);var K,Y,ue,$e=new S,Qr={registerProvider:xn,getProvider:xe,setProvider:Pe};return Qr;function xn(ke){if(!Object.isExtensible(Qr))throw Error("Cannot add provider to a frozen registry.");switch(!0){case q===ke:break;case fe(K):K=ke;break;case K===ke:break;case fe(Y):Y=ke;break;case Y===ke:break;default:if(ue===void 0)ue=new h;ue.add(ke);break}}function Et(ke,It){if(!fe(K)){if(K.isProviderFor(ke,It))return K;if(!fe(Y)){if(Y.isProviderFor(ke,It))return K;if(!fe(ue)){var cr=yf(ue);while(!0){var Jr=UC(cr);if(!Jr)return;var Li=Gn(Jr);if(Li.isProviderFor(ke,It))return BC(cr),Li}}}}if(!fe(q)&&q.isProviderFor(ke,It))return q;return}function xe(ke,It){var cr=$e.get(ke),Jr;if(!fe(cr))Jr=cr.get(It);if(!fe(Jr))return Jr;if(Jr=Et(ke,It),!fe(Jr)){if(fe(cr))cr=new m,$e.set(ke,cr);cr.set(It,Jr)}return Jr}function Re(ke){if(fe(ke))throw TypeError();return K===ke||Y===ke||!fe(ue)&&ue.has(ke)}function Pe(ke,It,cr){if(!Re(cr))throw Error("Metadata provider not registered.");var Jr=xe(ke,It);if(Jr!==cr){if(!fe(Jr))return!1;var Li=$e.get(ke);if(fe(Li))Li=new m,$e.set(ke,Li);Li.set(It,cr)}return!0}}function Zj(){var q;if(!fe(x)&&Be(r.Reflect)&&Object.isExtensible(r.Reflect))q=r.Reflect[x];if(fe(q))q=Xj();if(!fe(x)&&Be(r.Reflect)&&Object.isExtensible(r.Reflect))Object.defineProperty(r.Reflect,x,{enumerable:!1,configurable:!1,writable:!1,value:q});return q}function e2(q){var K=new S,Y={isProviderFor:function(Re,Pe){var ke=K.get(Re);if(fe(ke))return!1;return ke.has(Pe)},OrdinaryDefineOwnMetadata:xn,OrdinaryHasOwnMetadata:$e,OrdinaryGetOwnMetadata:Qr,OrdinaryOwnMetadataKeys:Et,OrdinaryDeleteMetadata:xe};return v.registerProvider(Y),Y;function ue(Re,Pe,ke){var It=K.get(Re),cr=!1;if(fe(It)){if(!ke)return;It=new m,K.set(Re,It),cr=!0}var Jr=It.get(Pe);if(fe(Jr)){if(!ke)return;if(Jr=new m,It.set(Pe,Jr),!q.setProvider(Re,Pe,Y)){if(It.delete(Pe),cr)K.delete(Re);throw Error("Wrong provider for target.")}}return Jr}function $e(Re,Pe,ke){var It=ue(Pe,ke,!1);if(fe(It))return!1;return Ve(It.has(Re))}function Qr(Re,Pe,ke){var It=ue(Pe,ke,!1);if(fe(It))return;return It.get(Re)}function xn(Re,Pe,ke,It){var cr=ue(ke,It,!0);cr.set(Re,Pe)}function Et(Re,Pe){var ke=[],It=ue(Re,Pe,!1);if(fe(It))return ke;var cr=It.keys(),Jr=yf(cr),Li=0;while(!0){var MC=UC(Jr);if(!MC)return ke.length=Li,ke;var i2=Gn(MC);try{ke[Li]=i2}catch(s2){try{BC(Jr)}finally{throw s2}}Li++}}function xe(Re,Pe,ke){var It=ue(Pe,ke,!1);if(fe(It))return!1;if(!It.delete(Re))return!1;if(It.size===0){var cr=K.get(Pe);if(!fe(cr)){if(cr.delete(ke),cr.size===0)K.delete(cr)}}return!0}}function t2(q){var{defineMetadata:K,hasOwnMetadata:Y,getOwnMetadata:ue,getOwnMetadataKeys:$e,deleteMetadata:Qr}=q,xn=new S,Et={isProviderFor:function(xe,Re){var Pe=xn.get(xe);if(!fe(Pe)&&Pe.has(Re))return!0;if($e(xe,Re).length){if(fe(Pe))Pe=new h,xn.set(xe,Pe);return Pe.add(Re),!0}return!1},OrdinaryDefineOwnMetadata:K,OrdinaryHasOwnMetadata:Y,OrdinaryGetOwnMetadata:ue,OrdinaryOwnMetadataKeys:$e,OrdinaryDeleteMetadata:Qr};return Et}function hf(q,K,Y){var ue=v.getProvider(q,K);if(!fe(ue))return ue;if(Y){if(v.setProvider(q,K,w))return w;throw Error("Illegal state.")}return}function r2(){var q={},K=[],Y=function(){function Et(xe,Re,Pe){this._index=0,this._keys=xe,this._values=Re,this._selector=Pe}return Et.prototype["@@iterator"]=function(){return this},Et.prototype[s]=function(){return this},Et.prototype.next=function(){var xe=this._index;if(xe>=0&&xe<this._keys.length){var Re=this._selector(this._keys[xe],this._values[xe]);if(xe+1>=this._keys.length)this._index=-1,this._keys=K,this._values=K;else this._index++;return{value:Re,done:!1}}return{value:void 0,done:!0}},Et.prototype.throw=function(xe){if(this._index>=0)this._index=-1,this._keys=K,this._values=K;throw xe},Et.prototype.return=function(xe){if(this._index>=0)this._index=-1,this._keys=K,this._values=K;return{value:xe,done:!0}},Et}(),ue=function(){function Et(){this._keys=[],this._values=[],this._cacheKey=q,this._cacheIndex=-2}return Object.defineProperty(Et.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),Et.prototype.has=function(xe){return this._find(xe,!1)>=0},Et.prototype.get=function(xe){var Re=this._find(xe,!1);return Re>=0?this._values[Re]:void 0},Et.prototype.set=function(xe,Re){var Pe=this._find(xe,!0);return this._values[Pe]=Re,this},Et.prototype.delete=function(xe){var Re=this._find(xe,!1);if(Re>=0){var Pe=this._keys.length;for(var ke=Re+1;ke<Pe;ke++)this._keys[ke-1]=this._keys[ke],this._values[ke-1]=this._values[ke];if(this._keys.length--,this._values.length--,ls(xe,this._cacheKey))this._cacheKey=q,this._cacheIndex=-2;return!0}return!1},Et.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=q,this._cacheIndex=-2},Et.prototype.keys=function(){return new Y(this._keys,this._values,$e)},Et.prototype.values=function(){return new Y(this._keys,this._values,Qr)},Et.prototype.entries=function(){return new Y(this._keys,this._values,xn)},Et.prototype["@@iterator"]=function(){return this.entries()},Et.prototype[s]=function(){return this.entries()},Et.prototype._find=function(xe,Re){if(!ls(this._cacheKey,xe)){this._cacheIndex=-1;for(var Pe=0;Pe<this._keys.length;Pe++)if(ls(this._keys[Pe],xe)){this._cacheIndex=Pe;break}}if(this._cacheIndex<0&&Re)this._cacheIndex=this._keys.length,this._keys.push(xe),this._values.push(void 0);return this._cacheIndex},Et}();return ue;function $e(Et,xe){return Et}function Qr(Et,xe){return xe}function xn(Et,xe){return[Et,xe]}}function n2(){var q=function(){function K(){this._map=new m}return Object.defineProperty(K.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),K.prototype.has=function(Y){return this._map.has(Y)},K.prototype.add=function(Y){return this._map.set(Y,Y),this},K.prototype.delete=function(Y){return this._map.delete(Y)},K.prototype.clear=function(){this._map.clear()},K.prototype.keys=function(){return this._map.keys()},K.prototype.values=function(){return this._map.keys()},K.prototype.entries=function(){return this._map.entries()},K.prototype["@@iterator"]=function(){return this.keys()},K.prototype[s]=function(){return this.keys()},K}();return q}function o2(){var q=16,K=d.create(),Y=ue();return function(){function xe(){this._key=ue()}return xe.prototype.has=function(Re){var Pe=$e(Re,!1);return Pe!==void 0?d.has(Pe,this._key):!1},xe.prototype.get=function(Re){var Pe=$e(Re,!1);return Pe!==void 0?d.get(Pe,this._key):void 0},xe.prototype.set=function(Re,Pe){var ke=$e(Re,!0);return ke[this._key]=Pe,this},xe.prototype.delete=function(Re){var Pe=$e(Re,!1);return Pe!==void 0?delete Pe[this._key]:!1},xe.prototype.clear=function(){this._key=ue()},xe}();function ue(){var xe;do xe="@@WeakMap@@"+Et();while(d.has(K,xe));return K[xe]=!0,xe}function $e(xe,Re){if(!n.call(xe,Y)){if(!Re)return;Object.defineProperty(xe,Y,{value:d.create()})}return xe[Y]}function Qr(xe,Re){for(var Pe=0;Pe<Re;++Pe)xe[Pe]=Math.random()*255|0;return xe}function xn(xe){if(typeof Uint8Array==="function"){var Re=new Uint8Array(xe);if(typeof crypto<"u")crypto.getRandomValues(Re);else if(typeof msCrypto<"u")msCrypto.getRandomValues(Re);else Qr(Re,xe);return Re}return Qr(Array(xe),xe)}function Et(){var xe=xn(q);xe[6]=xe[6]&79|64,xe[8]=xe[8]&191|128;var Re="";for(var Pe=0;Pe<q;++Pe){var ke=xe[Pe];if(Pe===4||Pe===6||Pe===8)Re+="-";if(ke<16)Re+="0";Re+=ke.toString(16).toLowerCase()}return Re}}function Pw(q){return q.__=void 0,delete q.__,q}})})(DL||(DL={}))});var b1=Ln(function(oQe,Qx){/*! *****************************************************************************
|
|
19
|
+
Copyright (c) Microsoft Corporation.
|
|
20
|
+
|
|
21
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
22
|
+
purpose with or without fee is hereby granted.
|
|
23
|
+
|
|
24
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
25
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
26
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
27
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
28
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
29
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
30
|
+
PERFORMANCE OF THIS SOFTWARE.
|
|
31
|
+
***************************************************************************** */var r1,n1,o1,i1,s1,a1,c1,l1,d1,Vx,SP,u1,p1,Up,f1,m1,y1,h1,g1,S1,v1,x1,w1;(function(e){var t=typeof global==="object"?global:typeof self==="object"?self:typeof this==="object"?this:{};if(typeof define==="function"&&define.amd)define("tslib",["exports"],function(n){e(r(t,r(n)))});else if(typeof Qx==="object"&&typeof oQe==="object")e(r(t,r(oQe)));else e(r(t));function r(n,o){if(n!==t)if(typeof Object.create==="function")Object.defineProperty(n,"__esModule",{value:!0});else n.__esModule=!0;return function(i,s){return n[i]=o?o(i,s):s}}})(function(e){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)if(n.hasOwnProperty(o))r[o]=n[o]};r1=function(r,n){t(r,n);function o(){this.constructor=r}r.prototype=n===null?Object.create(n):(o.prototype=n.prototype,new o)},n1=Object.assign||function(r){for(var n,o=1,i=arguments.length;o<i;o++){n=arguments[o];for(var s in n)if(Object.prototype.hasOwnProperty.call(n,s))r[s]=n[s]}return r},o1=function(r,n){var o={};for(var i in r)if(Object.prototype.hasOwnProperty.call(r,i)&&n.indexOf(i)<0)o[i]=r[i];if(r!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var s=0,i=Object.getOwnPropertySymbols(r);s<i.length;s++)if(n.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(r,i[s]))o[i[s]]=r[i[s]]}return o},i1=function(r,n,o,i){var s=arguments.length,a=s<3?n:i===null?i=Object.getOwnPropertyDescriptor(n,o):i,c;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")a=Reflect.decorate(r,n,o,i);else for(var l=r.length-1;l>=0;l--)if(c=r[l])a=(s<3?c(a):s>3?c(n,o,a):c(n,o))||a;return s>3&&a&&Object.defineProperty(n,o,a),a},s1=function(r,n){return function(o,i){n(o,i,r)}},a1=function(r,n){if(typeof Reflect==="object"&&typeof Reflect.metadata==="function")return Reflect.metadata(r,n)},c1=function(r,n,o,i){function s(a){return a instanceof o?a:new o(function(c){c(a)})}return new(o||(o=Promise))(function(a,c){function l(m){try{u(i.next(m))}catch(h){c(h)}}function d(m){try{u(i.throw(m))}catch(h){c(h)}}function u(m){m.done?a(m.value):s(m.value).then(l,d)}u((i=i.apply(r,n||[])).next())})},l1=function(r,n){var o={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,s,a,c;return c={next:l(0),throw:l(1),return:l(2)},typeof Symbol==="function"&&(c[Symbol.iterator]=function(){return this}),c;function l(u){return function(m){return d([u,m])}}function d(u){if(i)throw TypeError("Generator is already executing.");while(o)try{if(i=1,s&&(a=u[0]&2?s.return:u[0]?s.throw||((a=s.return)&&a.call(s),0):s.next)&&!(a=a.call(s,u[1])).done)return a;if(s=0,a)u=[u[0]&2,a.value];switch(u[0]){case 0:case 1:a=u;break;case 4:return o.label++,{value:u[1],done:!1};case 5:o.label++,s=u[1],u=[0];continue;case 7:u=o.ops.pop(),o.trys.pop();continue;default:if((a=o.trys,!(a=a.length>0&&a[a.length-1]))&&(u[0]===6||u[0]===2)){o=0;continue}if(u[0]===3&&(!a||u[1]>a[0]&&u[1]<a[3])){o.label=u[1];break}if(u[0]===6&&o.label<a[1]){o.label=a[1],a=u;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(u);break}if(a[2])o.ops.pop();o.trys.pop();continue}u=n.call(r,o)}catch(m){u=[6,m],s=0}finally{i=a=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}},w1=function(r,n,o,i){if(i===void 0)i=o;r[i]=n[o]},d1=function(r,n){for(var o in r)if(o!=="default"&&!n.hasOwnProperty(o))n[o]=r[o]},Vx=function(r){var n=typeof Symbol==="function"&&Symbol.iterator,o=n&&r[n],i=0;if(o)return o.call(r);if(r&&typeof r.length==="number")return{next:function(){if(r&&i>=r.length)r=void 0;return{value:r&&r[i++],done:!r}}};throw TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")},SP=function(r,n){var o=typeof Symbol==="function"&&r[Symbol.iterator];if(!o)return r;var i=o.call(r),s,a=[],c;try{while((n===void 0||n-- >0)&&!(s=i.next()).done)a.push(s.value)}catch(l){c={error:l}}finally{try{if(s&&!s.done&&(o=i.return))o.call(i)}finally{if(c)throw c.error}}return a},u1=function(){for(var r=[],n=0;n<arguments.length;n++)r=r.concat(SP(arguments[n]));return r},p1=function(){for(var r=0,n=0,o=arguments.length;n<o;n++)r+=arguments[n].length;for(var i=Array(r),s=0,n=0;n<o;n++)for(var a=arguments[n],c=0,l=a.length;c<l;c++,s++)i[s]=a[c];return i},Up=function(r){return this instanceof Up?(this.v=r,this):new Up(r)},f1=function(r,n,o){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var i=o.apply(r,n||[]),s,a=[];return s={},c("next"),c("throw"),c("return"),s[Symbol.asyncIterator]=function(){return this},s;function c(S){if(i[S])s[S]=function(x){return new Promise(function(v,w){a.push([S,x,v,w])>1||l(S,x)})}}function l(S,x){try{d(i[S](x))}catch(v){h(a[0][3],v)}}function d(S){S.value instanceof Up?Promise.resolve(S.value.v).then(u,m):h(a[0][2],S)}function u(S){l("next",S)}function m(S){l("throw",S)}function h(S,x){if(S(x),a.shift(),a.length)l(a[0][0],a[0][1])}},m1=function(r){var n,o;return n={},i("next"),i("throw",function(s){throw s}),i("return"),n[Symbol.iterator]=function(){return this},n;function i(s,a){n[s]=r[s]?function(c){return(o=!o)?{value:Up(r[s](c)),done:s==="return"}:a?a(c):c}:a}},y1=function(r){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var n=r[Symbol.asyncIterator],o;return n?n.call(r):(r=typeof Vx==="function"?Vx(r):r[Symbol.iterator](),o={},i("next"),i("throw"),i("return"),o[Symbol.asyncIterator]=function(){return this},o);function i(a){o[a]=r[a]&&function(c){return new Promise(function(l,d){c=r[a](c),s(l,d,c.done,c.value)})}}function s(a,c,l,d){Promise.resolve(d).then(function(u){a({value:u,done:l})},c)}},h1=function(r,n){if(Object.defineProperty)Object.defineProperty(r,"raw",{value:n});else r.raw=n;return r},g1=function(r){if(r&&r.__esModule)return r;var n={};if(r!=null){for(var o in r)if(Object.hasOwnProperty.call(r,o))n[o]=r[o]}return n.default=r,n},S1=function(r){return r&&r.__esModule?r:{default:r}},v1=function(r,n){if(!n.has(r))throw TypeError("attempted to get private field on non-instance");return n.get(r)},x1=function(r,n,o){if(!n.has(r))throw TypeError("attempted to set private field on non-instance");return n.set(r,o),o},e("__extends",r1),e("__assign",n1),e("__rest",o1),e("__decorate",i1),e("__param",s1),e("__metadata",a1),e("__awaiter",c1),e("__generator",l1),e("__exportStar",d1),e("__createBinding",w1),e("__values",Vx),e("__read",SP),e("__spread",u1),e("__spreadArrays",p1),e("__await",Up),e("__asyncGenerator",f1),e("__asyncDelegator",m1),e("__asyncValues",y1),e("__makeTemplateObject",h1),e("__importStar",g1),e("__importDefault",S1),e("__classPrivateFieldGet",v1),e("__classPrivateFieldSet",x1)})});var $j=(e)=>{if(e.startsWith("file://"))return e.slice(7);if(e.startsWith("file:"))return e.slice(5);return e};var NC=po(()=>{ol()});import{mkdirSync as Hee}from"fs";import{dirname as Wee}from"path";import*as Wj from"effect/Cause";import*as Kj from"effect/Config";import*as Rw from"effect/Context";import*as ct from"effect/Effect";import*as Vj from"effect/Exit";import*as el from"effect/Layer";import*as Qj from"effect/Option";import*as ff from"effect/Scope";import*as Jj from"effect/Stream";var Kee="db.system.name",Vee,qj,Qee=(e)=>{let t=[];for(let r=0;Object.hasOwn(e,String(r));r++)t.push(e[String(r)]??null);return t.length>0?t:Object.values(e)},Jee=(e)=>{if(e===":memory:")return;let t=Wee(e);if(t!==""&&t!==".")Hee(t,{recursive:!0})},jj=(e,t)=>ct.tryPromise({try:async()=>{Jee(e);let{connect:r}=await import("@tursodatabase/database"),n={experimental:["multiprocess_wal"]};if(t?.defaultQueryTimeout!==void 0)n.defaultQueryTimeout=t.defaultQueryTimeout;return await r(e,n)},catch:(r)=>new di({cause:r,message:"Failed to open database"})}),Hj=(e)=>ct.tryPromise({try:()=>e.close(),catch:(t)=>t}).pipe(ct.catchAll((t)=>ct.logWarning("Failed to close Turso connection",Wj.fail(t)))),zee=(e,t)=>ct.gen(function*(){let r=Hh(),n=[[Kee,"sqlite"]],o=yield*jj(e,t);yield*ct.addFinalizer(()=>Hj(o));class i{db;runPragmas;pragmasExecuted=!1;constructor(d,u){this.db=d;this.runPragmas=u}ensurePragmas(){if(this.pragmasExecuted||!this.runPragmas)return ct.void;return ct.gen(this,function*(){yield*this.runDirect("PRAGMA foreign_keys = ON",[]),yield*this.runDirect("PRAGMA journal_mode = wal",[]);let d=t?.busy_timeout??1500;if(d>0)yield*this.runDirect(`PRAGMA busy_timeout = ${d}`,[]);this.pragmasExecuted=!0})}runDirect(d,u){return ct.tryPromise({try:()=>this.db.all(d,[...u]),catch:(m)=>new di({cause:m,message:"Failed to execute statement"})})}runValuesDirect(d,u){return ct.tryPromise({try:async()=>(await this.db.all(d,[...u])).map((m)=>Qee(m)),catch:(m)=>new di({cause:m,message:"Failed to execute statement"})})}runValues(d,u=[]){return ct.gen(this,function*(){return yield*this.ensurePragmas(),yield*this.runValuesDirect(d,u)})}run=ct.fn("TursoConnection.run")(function*(d,u=[]){return yield*this.ensurePragmas(),yield*this.runDirect(d,u)});runRaw=ct.fn("TursoConnection.runRaw")(function*(d,u=[]){return yield*this.ensurePragmas(),yield*this.runDirect(d,u)});execute(d,u,m){return m?ct.map(this.run(d,u),m):this.run(d,u)}executeRaw(d,u){return this.runRaw(d,u)}executeValues(d,u){return this.runValues(d,u)}executeUnprepared(d,u,m){return this.execute(d,u,m)}executeStream(){return Jj.fail(new di({message:"executeStream not implemented for Turso"}))}beginTransactionBody=ct.fn("TursoConnection.beginTransaction")(function*(){let d=yield*jj(e,t),u=new i(d,!0);return yield*u.ensurePragmas(),yield*u.executeRaw("BEGIN",[]),u});get beginTransaction(){return this.beginTransactionBody()}commitBody=ct.fn("TursoConnection.commit")(function(){return this.executeRaw("COMMIT",[])});get commit(){return this.commitBody()}rollbackBody=ct.fn("TursoConnection.rollback")(function(){return this.executeRaw("ROLLBACK",[])});get rollback(){return this.rollbackBody()}get close(){return Hj(this.db)}}let s=new i(o,!0),a=yield*ct.makeSemaphore(1),c=Vh({transactionTag:qj,spanAttributes:n,acquireConnection:ct.uninterruptibleMask((d)=>ff.make().pipe(ct.flatMap((u)=>d(s.beginTransaction).pipe(ct.tap((m)=>ff.addFinalizer(u,m.close)),ct.map((m)=>[u,m]),ct.tapError(()=>ff.close(u,Vj.void)))))),begin:()=>ct.void,savepoint:(d,u)=>d.executeRaw(`SAVEPOINT effect_sql_${u};`,[]),commit:(d)=>d.commit,rollback:(d)=>d.rollback,rollbackSavepoint:(d,u)=>d.executeRaw(`ROLLBACK TO SAVEPOINT effect_sql_${u};`,[])}),l=ct.flatMap(ct.serviceOption(qj),Qj.match({onNone:()=>a.withPermits(1)(ct.succeed(s)),onSome:([d])=>ct.succeed(d)}));return Object.assign(yield*Kh({acquirer:l,compiler:r,spanAttributes:n}),{withTransaction:c})}),Gee=(e)=>el.scopedContext(ct.gen(function*(){let t=yield*rl,r=Ua(t),n=yield*zee($j(r),e);return Rw.make(ps,n)})).pipe(el.provide(Fh)),FC=(e)=>Gee(e).pipe(el.provideMerge(Vee)),glt;var zj=po(()=>{Uh();wf();Jh();Wh();ol();NC();Vee=el.effect(Nd,rl.pipe(Kj.map(Ua))),qj=Rw.GenericTag("processfocus:internal-tag/layer-turso-local/TursoTransaction"),glt=FC()});var Gj=po(()=>{zj();NC()});ol();import{Runtime as Yj}from"@processfocus/runtime";import{ConfigProvider as Yee,DateTime as Xee,Effect as Ks,FiberRef as Zee,Layer as mf}from"effect";Uh();wf();Jh();Wh();ol();import{Session as U_}from"@tursodatabase/serverless";import*as $_ from"effect/Cause";import*as zo from"effect/Config";import*as La from"effect/Context";import*as oe from"effect/Effect";import*as q_ from"effect/Exit";import*as $d from"effect/FiberRef";import*as $a from"effect/Layer";import*as j_ from"effect/Option";import*as Gh from"effect/Redacted";import*as qa from"effect/Schedule";import*as Yh from"effect/Scope";import*as H_ from"effect/Stream";var L2="db.system.name",$2=5,B_=qa.exponential("100 millis",2).pipe(qa.intersect(qa.recurs($2)),qa.jittered),zh=(e)=>nl(e)&&!Uw(e),q2=zo.redacted("TURSO_AUTH_TOKEN").pipe(zo.orElse(()=>zo.succeed(void 0))),j2=zo.string("TURSO_CONCURRENT_TX").pipe(zo.map((e)=>e==="1"),zo.orElse(()=>zo.succeed(!1))),H2=$a.effect(Nd,rl.pipe(zo.map(Ua))),M_=La.GenericTag("processfocus:internal-tag/layer-turso-cloud/TursoCloudTransaction");class W_ extends La.Tag("processfocus:internal-tag/layer-turso-cloud/TursoCloudBatch")(){}var W2=(e)=>e.rows.map((t)=>Object.fromEntries(e.columns.map((r,n)=>[r,t[n]]))),K2=(e)=>e.rows,L_=(e)=>{let t=e.lastInsertRowid===void 0?void 0:typeof e.lastInsertRowid==="bigint"?e.lastInsertRowid:BigInt(e.lastInsertRowid);return{columns:Array.from(e.columns),columnTypes:Array.from(e.columnTypes??[]),rows:Array.from(e.rows),rowsAffected:e.rowsAffected??0,lastInsertRowid:t}},Xw=(e)=>{if(e instanceof Error){let t=e.code,r=typeof t==="string"?` ${t}`:"",n=e.cause?`; caused by ${Xw(e.cause)}`:"";return`${e.name}${r}: ${e.message}${n}`}return String(e)},V2="Turso blocked SQL reads; a database organization plan limit may be responsible - check Turso usage and plan settings",Q2=(e)=>ds(e,(t)=>t.includes("SQL read operations are forbidden")||t.includes("reads are blocked")),Ld=(e,t)=>new di({cause:Error(`${e}: ${Xw(t)}`,{cause:t}),message:Q2(t)?`${e} (${V2})`:e}),J2=(e)=>ds(e,(t)=>t.includes("HTTP error! status: 404")),z2=(e)=>oe.tryPromise({try:()=>e.session.close(),catch:(t)=>t}).pipe(oe.catchAll((t)=>oe.logWarning("Failed to close Turso connection",$_.fail(t)))),bf=(e)=>e.semaphore.withPermits(1)(z2(e)),G2=(e,t,r,n)=>oe.gen(function*(){let o=Hh(),i=[[L2,"sqlite"]],s=n?.refreshAuthToken,a=(v)=>oe.map(oe.makeSemaphore(1),(w)=>v?{session:new U_({url:e,authToken:Gh.value(v)}),semaphore:w}:{session:new U_({url:e}),semaphore:w}),c=(v,w)=>{if(v===void 0||w===void 0)return v===w;return Gh.value(v)===Gh.value(w)},l=t,d=yield*oe.acquireRelease(oe.map(a(l),(v)=>({current:v})),(v)=>bf(v.current));class u{sdk;runPragmas;closeSdkAfterTransaction;pragmasExecuted=!1;sdkClosed=!1;constructor(v,w,P){this.sdk=v;this.runPragmas=w;this.closeSdkAfterTransaction=P}withStatementSdk(v,w="Failed to execute statement"){return this.withStatementSdkEffect((P)=>oe.tryPromise({try:()=>v(P),catch:(F)=>Ld(w,F)}))}withStatementSdkEffect(v){return oe.suspend(()=>{let w=this.sdk??d.current;return w.semaphore.withPermits(1)(v(w.session))})}closeTransactionSdk(){if(!this.sdk||!this.closeSdkAfterTransaction||this.sdkClosed)return oe.void;return this.sdkClosed=!0,bf(this.sdk)}refreshSdkOnTokenChange(){if(this.sdk||!this.runPragmas||!s)return oe.succeed(!1);return oe.gen(this,function*(){let v=yield*s;if(c(l,v))return!1;let w=d.current;return d.current=yield*a(v),l=v,this.pragmasExecuted=!1,yield*bf(w),!0})}recreateSdk(){if(this.sdk||!this.runPragmas)return oe.void;return oe.gen(this,function*(){let v=d.current;d.current=yield*a(l),this.pragmasExecuted=!1,yield*bf(v)})}runWithTokenRefresh(v){let w=this.retryTursoLock(v);return w.pipe(oe.catchAll((P)=>oe.gen(this,function*(){if(yield*this.refreshSdkOnTokenChange())return yield*w;if(J2(P.cause))return yield*this.recreateSdk(),yield*w;return yield*oe.fail(P)})))}retryTursoLock(v,w=nl){return v.pipe(oe.retry({schedule:B_,while:w}))}ensurePragmas(){if(this.pragmasExecuted||!this.runPragmas)return oe.void;return oe.gen(this,function*(){yield*this.runDirect("PRAGMA foreign_keys = ON",[]),this.pragmasExecuted=!0})}runDirect(v,w){return oe.gen(this,function*(){let P=yield*this.withStatementSdk((F)=>F.execute(v,Array.from(w)));return W2(L_(P))})}run=oe.fn("TursoCloudConnection.run")(function*(v,w=[]){return yield*this.runWithTokenRefresh(oe.gen(this,function*(){return yield*this.ensurePragmas(),yield*this.runDirect(v,w)}))});runRaw=oe.fn("TursoCloudConnection.runRaw")(function*(v,w=[]){return yield*this.runWithTokenRefresh(oe.gen(this,function*(){return yield*this.ensurePragmas(),yield*this.withStatementSdk((P)=>P.execute(v,Array.from(w)).then(L_))}))});runBatch=oe.fn("TursoCloudConnection.runBatch")(function*(v){if(v.foreignKeys==="enforced"){yield*this.ensurePragmas(),yield*this.retryTursoLock(this.withStatementSdk((w)=>w.batch(Array.from(v.statements),"immediate"),"Failed to execute batch"),zh);return}yield*this.withStatementSdkEffect((w)=>oe.gen(this,function*(){this.pragmasExecuted=!1;let P=yield*this.retryTursoLock(oe.tryPromise({try:async()=>{await w.execute("PRAGMA foreign_keys = OFF",[]),await w.batch(Array.from(v.statements),"immediate")},catch:(R)=>Ld("Failed to execute batch",R)}),zh).pipe(oe.match({onFailure:(R)=>({kind:"failed",cause:R}),onSuccess:()=>({kind:"succeeded"})})),F=yield*this.retryTursoLock(oe.tryPromise({try:()=>w.execute("PRAGMA foreign_keys = ON",[]).then(()=>{return}),catch:(R)=>Ld("Failed to restore foreign keys",R)}),zh).pipe(oe.match({onFailure:(R)=>({kind:"failed",cause:R}),onSuccess:()=>({kind:"succeeded"})}));if(F.kind==="succeeded")this.pragmasExecuted=!0;else if(P.kind==="failed")return yield*oe.fail(new di({message:"Failed to execute batch",cause:Error(`Failed to restore foreign keys after batch failure: ${Xw(F.cause)}`,{cause:P.cause})}));else return yield*oe.fail(F.cause);if(P.kind==="failed")return yield*oe.fail(P.cause)}))});execute(v,w,P){return P?oe.map(this.run(v,w),P):this.run(v,w)}executeRaw(v,w){return this.runRaw(v,w)}executeValues(v,w){return oe.map(this.runRaw(v,w),(P)=>K2(P).map((F)=>Array.from(F)))}executeUnprepared(v,w,P){return this.execute(v,w,P)}executeStream(){return H_.fail(new di({message:"executeStream not implemented for Turso"}))}beginTransactionBody=oe.fn("TursoCloudConnection.beginTransaction")(function*(){return yield*this.runWithTokenRefresh(oe.gen(this,function*(){yield*this.ensurePragmas();let v=yield*a(l),w=yield*$d.get(kh);return yield*$d.set(Oh,w&&r?"concurrent":"immediate"),yield*oe.tryPromise({try:async()=>{await v.session.execute("PRAGMA foreign_keys = ON",[]),await v.session.sequence(w?r?"BEGIN CONCURRENT":"BEGIN IMMEDIATE":n?.deferredTransactions?"BEGIN DEFERRED":"BEGIN IMMEDIATE")},catch:(P)=>Ld("Failed to begin transaction",P)}).pipe(oe.tapError(()=>bf(v))),new u(v,!1,!0)}))});get beginTransaction(){return this.beginTransactionBody()}commitBody=oe.fn("TursoCloudConnection.commit")(function(){return oe.uninterruptible(oe.tryPromise({try:()=>{if(!this.sdk)return Promise.reject(Error("Transaction connection missing"));return this.sdk.session.sequence("COMMIT")},catch:(v)=>Ld("Failed to commit transaction",v)}).pipe(oe.retry({schedule:B_,while:zh}),oe.tap(()=>this.closeTransactionSdk())))});get commit(){return this.commitBody()}rollbackBody=oe.fn("TursoCloudConnection.rollback")(function(){return this.retryTursoLock(oe.tryPromise({try:()=>{if(!this.sdk)return Promise.reject(Error("Transaction connection missing"));return this.sdk.session.sequence("ROLLBACK")},catch:(v)=>Ld("Failed to rollback transaction",v)})).pipe(oe.ensuring(this.closeTransactionSdk()))});get rollback(){return this.rollbackBody()}}let m=new u(void 0,!0,!1),h=Vh({transactionTag:M_,spanAttributes:i,acquireConnection:oe.uninterruptibleMask((v)=>Yh.make().pipe(oe.flatMap((w)=>v(m.beginTransaction).pipe(oe.map((P)=>[w,P]),oe.tapError(()=>Yh.close(w,q_.void)))))),begin:()=>oe.void,savepoint:(v,w)=>v.executeRaw(`SAVEPOINT effect_sql_${w};`,[]),commit:(v)=>v.commit.pipe(oe.catchAll((w)=>v.rollback.pipe(oe.catchAll((P)=>oe.logWarning("Failed to rollback transaction after commit failure").pipe(oe.annotateLogs({rollbackError:P}))),oe.zipRight($d.get(kh).pipe(oe.flatMap((P)=>P?$d.set(_w,w):oe.fail(w))))))),rollback:(v)=>v.rollback,rollbackSavepoint:(v,w)=>v.executeRaw(`ROLLBACK TO SAVEPOINT effect_sql_${w};`,[])}),S=oe.flatMap(oe.serviceOption(M_),j_.match({onNone:()=>oe.succeed(m),onSome:([v])=>oe.succeed(v)})),x=Object.assign(yield*Kh({acquirer:S,compiler:o,spanAttributes:i}),{withTransaction:h});return{batch:{execute:(v)=>m.runBatch(v)},client:x}}),Y2=(e)=>$a.scopedContext(oe.gen(function*(){let t=yield*rl,r=Ua(t),n=e?.authToken??(yield*q2),o=yield*j2,{batch:i,client:s}=yield*G2(r,n,o,e);return La.make(ps,s).pipe(La.add(W_,i))})).pipe($a.provide(Fh)),X2=(e)=>Y2(e).pipe($a.provideMerge(H2)),K_=X2();import{Context as Z2,Data as eH}from"effect";class Zw extends eH.TaggedError("FlowCrossProcessError"){}class Ef extends Z2.Tag("processfocus:internal-tag/org-to-db/DbOperations")(){}import{createHash as R6}from"crypto";wf();import{Data as eS,Effect as Dt,HashMap as En,Option as ea,Ref as qe}from"effect";var V_=(e)=>{let t=e.PF_LOCAL_FRONTEND_ORIGIN??e.OAUTH_ISSUER_URL;return t?{rpID:new URL(t).hostname,origin:t}:void 0};import{Effect as tH}from"effect";var Q_=(e)=>tH.promise(()=>Bun.password.hash(e,{algorithm:"argon2id"}));import{Duration as rH,Effect as nH,Schedule as J_}from"effect";var oH=["HTTP status 502"],z_=502,iH=8,sH=(e)=>typeof e==="object"&&e!==null,eb=(e)=>oH.some((t)=>e.includes(t)),tb=(e)=>{let t=e,r=new Set,n=0;while(t!=null&&!r.has(t)&&n<iH){if(r.add(t),n+=1,t instanceof Error){if(eb(t.message))return!0;t=t.cause;continue}if(sH(t)){let o=t.message;if(typeof o==="string"&&eb(o))return!0;let i=t.status;if(typeof i==="number"&&i===z_)return!0;t=t.cause;continue}if(typeof t==="string"&&eb(t))return!0;if(typeof t==="number"&&t===z_)return!0;break}return!1},aH=J_.addDelay(J_.recurs(1),()=>rH.millis(250)),G_=(e)=>e.pipe(nH.retry({schedule:aH,while:tb}));import{Effect as Si}from"effect";var bH=zr($n(),1);var eg=(e)=>typeof e==="object"&&e!==null&&("isAuthenticationConfig"in e)&&e.isAuthenticationConfig===!0;import*as Jf from"path";sl();import*as al from"effect/Duration";import*as pi from"effect/Either";import{dual as fre,identity as EH}from"effect/Function";import*as ob from"effect/Inspectable";import*as tg from"effect/Option";import{pipeArguments as TH}from"effect/Pipeable";import*as RH from"effect/Predicate";import*as jd from"effect/Record";var yk=Symbol.for("@effect/platform/Cookies");var hk=Symbol.for("@effect/platform/Cookies/Cookie"),AH=Symbol.for("@effect/platform/Cookies/CookieError");class qd extends Bd(AH,"CookieError"){get message(){return this.reason}}var PH={[yk]:yk,...ob.BaseProto,toJSON(){return{_id:"@effect/platform/Cookies",cookies:jd.map(this.cookies,(e)=>e.toJSON())}},pipe(){return TH(this,arguments)}},IH=(e)=>{let t=Object.create(PH);return t.cookies=e,t},CH=(e)=>{let t={};for(let r of e)t[r.name]=r;return IH(t)};var Hd=CH([]);var _H=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,kH=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,OH=/^[\u0009\u0020-\u003a\u003c-\u007e\u0080-\u00ff]+$/,DH=/^[\u0020-\u003a\u003c-\u007e]+$/,NH={[hk]:hk,...ob.BaseProto,toJSON(){return{_id:"@effect/platform/Cookies/Cookie",name:this.name,value:this.value,options:this.options}}};function FH(e,t,r){if(!kH.test(e))return pi.left(new qd({reason:"InvalidName"}));let n=encodeURIComponent(t);if(n&&!_H.test(n))return pi.left(new qd({reason:"InvalidValue"}));if(r!==void 0){if(r.domain!==void 0&&!OH.test(r.domain))return pi.left(new qd({reason:"InvalidDomain"}));if(r.path!==void 0&&!DH.test(r.path))return pi.left(new qd({reason:"InvalidPath"}));if(r.maxAge!==void 0&&!al.isFinite(al.decode(r.maxAge)))return pi.left(new qd({reason:"InfinityMaxAge"}))}return pi.right(Object.assign(Object.create(NH),{name:e,value:t,valueEncoded:n,options:r}))}var UH=(e,t,r)=>pi.getOrThrowWith(FH(e,t,r),EH);function BH(e){let t=e.name+"="+e.valueEncoded;if(e.options===void 0)return t;let r=e.options;if(r.maxAge!==void 0){let n=al.toSeconds(r.maxAge);t+="; Max-Age="+Math.trunc(n)}if(r.domain!==void 0)t+="; Domain="+r.domain;if(r.path!==void 0)t+="; Path="+r.path;if(r.priority!==void 0)switch(r.priority){case"low":t+="; Priority=Low";break;case"medium":t+="; Priority=Medium";break;case"high":t+="; Priority=High";break}if(r.expires!==void 0)t+="; Expires="+r.expires.toUTCString();if(r.httpOnly)t+="; HttpOnly";if(r.secure)t+="; Secure";if(r.partitioned)t+="; Partitioned";if(r.sameSite!==void 0)switch(r.sameSite){case"lax":t+="; SameSite=Lax";break;case"strict":t+="; SameSite=Strict";break;case"none":t+="; SameSite=None";break}return t}function MH(e){let t={},r=e.length,n=0,o=0;while(!0){if(o===r)break;if(o=e.indexOf(";",n),o===-1)o=r;let i=e.indexOf("=",n);if(i===-1)break;if(i>o){n=o+1;continue}let s=e.substring(n,i++).trim();if(t[s]===void 0){let a=e.charCodeAt(i)===34?e.substring(i+1,o-1).trim():e.substring(i,o).trim();t[s]=a.indexOf("%")!==-1?LH(a):a}n=o+1}return t}var LH=(e)=>{try{return decodeURIComponent(e)}catch{return e}};import*as xk from"effect/Brand";import*as wk from"effect/Context";import*as rg from"effect/Data";sl();import*as Ha from"effect/Channel";import*as gk from"effect/Chunk";import{GenericTag as $H}from"effect/Context";import*as Gr from"effect/Effect";import{identity as qH,pipe as sb}from"effect/Function";import*as jH from"effect/Layer";import*as Sk from"effect/Option";import*as If from"effect/Sink";import*as cl from"effect/Stream";var ab=$H("@effect/platform/FileSystem"),Pf=(e)=>typeof e==="bigint"?e:BigInt(e);var Af=BigInt(1024),Sre=Af*Af*Af*Af*Af;var vk=(e)=>ab.of({...e,exists:(t)=>sb(e.access(t),Gr.as(!0),Gr.catchTag("SystemError",(r)=>r.reason==="NotFound"?Gr.succeed(!1):Gr.fail(r))),readFileString:(t,r)=>Gr.tryMap(e.readFile(t),{try:(n)=>new TextDecoder(r).decode(n),catch:(n)=>new Md({module:"FileSystem",method:"readFileString",description:"invalid encoding",cause:n})}),stream:(t,r)=>sb(e.open(t,{flag:"r"}),r?.offset?Gr.tap((n)=>n.seek(r.offset,"start")):qH,Gr.map((n)=>HH(n,r)),cl.unwrapScoped),sink:(t,r)=>sb(e.open(t,{flag:"w",...r}),Gr.map((n)=>If.forEach((o)=>n.writeAll(o))),If.unwrapScoped),writeFileString:(t,r,n)=>Gr.flatMap(Gr.try({try:()=>new TextEncoder().encode(r),catch:(o)=>new Md({module:"FileSystem",method:"writeFileString",description:"could not encode string",cause:o})}),(o)=>e.writeFile(t,o,n))});var HH=(e,{bufferSize:t=16,bytesToRead:r,chunkSize:n=Pf(65536)}={})=>{let o=r!==void 0?Pf(r):void 0,i=Pf(n);function s(a){if(o!==void 0&&o<=a)return Ha.void;let c=o!==void 0&&o-a<i?o-a:i;return Ha.flatMap(e.readAlloc(c),Sk.match({onNone:()=>Ha.void,onSome:(l)=>Ha.flatMap(Ha.write(gk.of(l)),(d)=>s(a+BigInt(l.length)))}))}return cl.bufferChunks(cl.fromChannel(s(BigInt(0))),{capacity:t})};var Wa=Pf;var Cf=ab,bk=vk;var ng=Symbol.for("@effect/platform/FileSystem/File");var Ek=xk.nominal(),Tk=rg.tagged("Create"),Rk=rg.tagged("Update"),Ak=rg.tagged("Remove");class cb extends wk.Tag("@effect/platform/FileSystem/WatchBackend")(){}import*as Ik from"effect/FiberRef";import*as Ck from"effect/FiberRefs";import{dual as og,identity as Pre}from"effect/Function";import{globalValue as KH}from"effect/GlobalValue";import{symbolRedactable as VH}from"effect/Inspectable";import*as QH from"effect/Predicate";import*as _k from"effect/Record";import*as lb from"effect/Redacted";import*as ig from"effect/Schema";import*as JH from"effect/String";var Pk=Symbol.for("@effect/platform/Headers");var kf=Object.assign(Object.create(null),{[Pk]:Pk,[VH](e){return zH(this,Ck.getOrDefault(e,GH))}}),db=(e)=>Object.assign(Object.create(kf),e);var Wd=Object.create(kf),Qs=(e)=>{if(e===void 0)return Wd;else if(Symbol.iterator in e){let r=Object.create(kf);for(let[n,o]of e)r[n.toLowerCase()]=o;return r}let t=Object.create(kf);for(let[r,n]of Object.entries(e))if(Array.isArray(n))t[r.toLowerCase()]=n.join(", ");else if(n!==void 0)t[r.toLowerCase()]=n;return t},kk=(e)=>Object.setPrototypeOf(e,kf);var Ok=og(3,(e,t,r)=>{let n=db(e);return n[t.toLowerCase()]=r,n}),Dk=og(2,(e,t)=>db({...e,...Qs(t)})),Nk=og(2,(e,t)=>{let r=db(e);return Object.assign(r,t),r});var zH=og(2,(e,t)=>{let r={...e},n=(o)=>{if(typeof o==="string"){let i=o.toLowerCase();if(i in e)r[i]=lb.make(e[i])}else for(let i in e)if(o.test(i))r[i]=lb.make(e[i])};if(Array.isArray(t))for(let o=0;o<t.length;o++)n(t[o]);else n(t);return r}),GH=KH("@effect/platform/Headers/currentRedactedNames",()=>Ik.unsafeMake(["authorization","cookie","set-cookie","x-api-key"]));import*as Uk from"effect/Data";import*as Of from"effect/Effect";import{identity as kre}from"effect/Function";import*as sg from"effect/Inspectable";import*as YH from"effect/Schema";import*as XH from"effect/Stream";var pb=Symbol.for("@effect/platform/HttpBody"),Fk=Symbol.for("@effect/platform/HttpBody/HttpBodyError"),ZH=Uk.tagged("HttpBodyError"),eW=(e)=>ZH({[Fk]:Fk,reason:e});class fb{[pb];constructor(){this[pb]=pb}[sg.NodeInspectSymbol](){return this.toJSON()}toString(){return sg.format(this)}}class Bk extends fb{_tag="Empty";toJSON(){return{_id:"@effect/platform/HttpBody",_tag:"Empty"}}}var mb=new Bk;class Mk extends fb{body;contentType;_tag="Uint8Array";constructor(e,t){super();this.body=e,this.contentType=t}get contentLength(){return this.body.length}toJSON(){return{_id:"@effect/platform/HttpBody",_tag:"Uint8Array",body:this.contentType.startsWith("text/")||this.contentType.endsWith("json")?new TextDecoder().decode(this.body):`Uint8Array(${this.body.length})`,contentType:this.contentType,contentLength:this.contentLength}}}var Lk=(e,t)=>new Mk(e,t??"application/octet-stream"),tW=new TextEncoder,yb=(e,t)=>Lk(tW.encode(e),t??"text/plain"),hb=(e,t)=>yb(JSON.stringify(e),t??"application/json"),$k=(e,t)=>Of.try({try:()=>hb(e,t),catch:(r)=>eW({_tag:"JsonError",error:r})});sl();import*as lW from"effect/Cause";import*as Df from"effect/Effect";import*as dW from"effect/ParseResult";import{hasProperty as hne}from"effect/Predicate";import*as aW from"effect/Stream";import*as nW from"effect/Context";import*as ll from"effect/Effect";import*as qk from"effect/Effectable";import{dual as jk}from"effect/Function";import*as Kd from"effect/Inspectable";import*as oW from"effect/Runtime";import*as gb from"effect/Stream";var ag=Symbol.for("@effect/platform/HttpServerResponse"),iW=Symbol.for("@effect/platform/HttpServerRespondable");class Ka extends qk.StructuralClass{status;statusText;cookies;body;[ag];headers;constructor(e,t,r,n,o){super();if(this.status=e,this.statusText=t,this.cookies=n,this.body=o,this[ag]=ag,o.contentType||o.contentLength){let i={...r};if(o.contentType)i["content-type"]=o.contentType;if(o.contentLength)i["content-length"]=o.contentLength.toString();this.headers=i}else this.headers=r}commit(){return ll.succeed(this)}[iW](){return ll.succeed(this)}[Kd.NodeInspectSymbol](){return this.toJSON()}toString(){return Kd.format(this)}toJSON(){return{_id:"@effect/platform/HttpServerResponse",status:this.status,statusText:this.statusText,headers:Kd.redact(this.headers),cookies:this.cookies.toJSON(),body:this.body.toJSON()}}}var Hk=(e)=>typeof e==="object"&&e!==null&&(ag in e),Wk=(e)=>new Ka(e?.status??204,e?.statusText,e?.headers?Qs(e.headers):Wd,e?.cookies??Hd,mb),Kk=(e,t)=>{let r=kk({location:e.toString()});return new Ka(t?.status??302,t?.statusText,t?.headers?Nk(r,Qs(t.headers)):r,t?.cookies??Hd,mb)};var Vk=(e,t)=>{let r=t?.headers?Qs(t.headers):Wd;return new Ka(t?.status??200,t?.statusText,r,t?.cookies??Hd,yb(e,Sb(t,r)))};var Qk=(e,t)=>{let r=t?.headers?Qs(t.headers):Wd;return ll.map($k(e,Sb(t,r)),(n)=>new Ka(t?.status??200,t?.statusText,r,t?.cookies??Hd,n))},Jk=(e,t)=>{let r=t?.headers?Qs(t.headers):Wd;return new Ka(t?.status??200,t?.statusText,r,t?.cookies??Hd,hb(e,Sb(t,r)))};var Sb=(e,t)=>{if(e?.contentType)return e.contentType;else if(e?.headers)return t["content-type"];else return},zk=jk(3,(e,t,r)=>new Ka(e.status,e.statusText,Ok(e.headers,t,r),e.cookies,e.body));var Gk=jk(2,(e,t)=>new Ka(e.status,e.statusText,Dk(e.headers,t),e.cookies,e.body));var Yk=Hk,cg=Wk,lg=Kk;var Vd=Vk;var cW=Qk;var vb=Jk;var dg=zk,Qd=Gk;var xb=Symbol.for("@effect/platform/HttpServerRespondable");var ug=(e)=>{if(Yk(e))return Df.succeed(e);return Df.orDie(e[xb]())};import*as Va from"effect/Cause";import*as Zk from"effect/Effect";import*as uW from"effect/FiberId";import{globalValue as Sne}from"effect/GlobalValue";import*as e0 from"effect/Option";import*as pW from"effect/Predicate";var t0=Symbol.for("@effect/platform/HttpServerError");var mW=t0;class wb extends Bd(mW,"RouteNotFound"){constructor(e){super(e);this.stack=`${this.name}: ${this.message}`}[xb](){return cg({status:404})}get message(){return`${this.request.method} ${this.request.url} not found`}}import*as l0 from"effect/Effect";import*as d0 from"effect/Either";import*as EW from"effect/Option";import*as TW from"effect/Runtime";import*as RW from"effect/Stream";import*as vW from"effect/Channel";import*as bb from"effect/Context";import*as Js from"effect/Effect";import*as xW from"effect/Inspectable";import*as s0 from"effect/Option";import*as wW from"effect/Schema";import*as mg from"effect/Stream";import*as r0 from"effect/Context";import*as pg from"effect/Effect";import{dual as hW}from"effect/Function";import*as gW from"effect/Inspectable";import*as fg from"effect/Option";import*as SW from"effect/Schema";class n0 extends r0.Reference()("@effect/platform/HttpIncomingMessage/MaxBodySize",{defaultValue:fg.none}){}var o0=hW(2,(e,t)=>pg.provideService(e,n0,fg.map(t,Wa)));var a0=bb.GenericTag("@effect/platform/HttpServerRequest"),c0=bb.GenericTag("@effect/platform/HttpServerRequest/ParsedSearchParams");var lr=a0,u0=c0;import*as yg from"effect/Context";import*as fi from"effect/Effect";import*as Eb from"effect/FiberRef";import{constFalse as jne,dual as Hne}from"effect/Function";import*as AW from"effect/Function";import{globalValue as Kne}from"effect/GlobalValue";import*as Tb from"effect/Layer";import*as PW from"effect/Option";var p0=(e)=>e;var Rb=p0;import*as sn from"effect/Chunk";import*as zs from"effect/Context";import*as wr from"effect/Effect";import*as P0 from"effect/Effectable";import*as Qa from"effect/FiberRef";import{dual as Uf}from"effect/Function";import{globalValue as $W}from"effect/GlobalValue";import*as Jd from"effect/Inspectable";import*as Bf from"effect/Layer";import*as $i from"effect/Option";import*as I0 from"effect/Predicate";import*as qW from"effect/Schema";import*as C0 from"effect/Tracer";var f0=/\+/g,m0=function(){};m0.prototype=Object.create(null);function y0(e){let t=new m0;if(typeof e!=="string")return t;let r=e.length,n="",o="",i=-1,s=-1,a=!1,c=!1,l=!1,d=!1,u=!1,m=0;for(let h=0;h<r+1;h++)if(m=h!==r?e.charCodeAt(h):38,m===38){if(u=s>i,!u)s=h;if(n=e.slice(i+1,s),u||n.length>0){if(l)n=n.replace(f0," ");if(a)try{n=decodeURIComponent(n)||n}catch{}if(u){if(o=e.slice(s+1,h),d)o=o.replace(f0," ");if(c)try{o=decodeURIComponent(o)||o}catch{}}let S=t[n];if(S===void 0)t[n]=o;else if(S.pop)S.push(o);else t[n]=[S,o]}o="",i=h,s=h,a=!1,c=!1,l=!1,d=!1}else if(m===61)if(s<=i)s=h;else c=!0;else if(m===43)if(s>i)d=!0;else l=!0;else if(m===37)if(s>i)c=!0;else a=!0;return t}var _W=/^https?:\/\/.*?\//,Ab=/(\/:[^/()]*?)\?(\/?)/,v0=(e={})=>new x0(e);class x0{constructor(e={}){this.options={ignoreTrailingSlash:!0,ignoreDuplicateSlashes:!0,caseSensitive:!1,maxParamLength:100,...e}}options;routes=[];trees={};on(e,t,r){let n=t.match(Ab);if(n&&n.index!==void 0){kW(t.length===n.index+n[0].length,"Optional Parameter needs to be the last parameter of the path");let i=t.replace(Ab,"$1$2"),s=t.replace(Ab,"$2");this.on(e,i,r),this.on(e,s,r);return}if(this.options.ignoreDuplicateSlashes)t=h0(t);if(this.options.ignoreTrailingSlash)t=g0(t);let o=typeof e==="string"?[e]:e;for(let i of o)this._on(i,t,r)}all(e,t){this.on(BW,e,t)}_on(e,t,r){if(this.trees[e]===void 0)this.trees[e]=new Nf("/");let n=t;if(n==="*"&&this.trees[e].prefix.length!==0){let c=this.trees[e];this.trees[e]=new Nf(""),this.trees[e].staticChildren["/"]=c}let o=this.trees[e].prefix.length,i=this.trees[e],s=[];for(let c=0;c<=n.length;c++){if(n.charCodeAt(c)===58&&n.charCodeAt(c+1)===58){c++;continue}let l=n.charCodeAt(c)===58&&n.charCodeAt(c+1)!==58,d=n.charCodeAt(c)===42;if(l||d||c===n.length&&c!==o){let u=n.slice(o,c);if(!this.options.caseSensitive)u=u.toLowerCase();u=u.split("::").join(":"),u=u.split("%").join("%25"),i=i.createStaticChild(u)}if(l){let u=!1,m=[],h=c+1;for(let S=h;;S++){let x=n.charCodeAt(S),v=x===40,w=x===45||x===46,P=x===47||S===n.length;if(v||w||P){let F=n.slice(h,S);if(s.push(F),u=u||v||w,v){let A=DW(n,S),D=n.slice(S,A+1);m.push(NW(D)),S=A+1}else m.push("(.*?)");let R=S;for(;S<n.length;S++){let A=n.charCodeAt(S);if(A===47)break;if(A===58)if(n.charCodeAt(S+1)===58)S++;else break}let b=n.slice(R,S);if(b)b=b.split("::").join(":"),b=b.split("%").join("%25"),m.push(FW(b));if(h=S+1,P||n.charCodeAt(S)===47||S===n.length){let A=u?"()"+b:b,D=n.slice(c,S);n=n.slice(0,c+1)+A+n.slice(S),c+=A.length;let B=u?new RegExp("^"+m.join("")+"$"):void 0;i=i.createParametricChild(B,b,D),o=c+1;break}}}}else if(d){if(s.push("*"),i=i.createWildcardChild(),o=c+1,c!==n.length-1)throw Error("Wildcard must be the last character in the route")}}if(!this.options.caseSensitive)n=n.toLowerCase();if(n==="*")n="/*";for(let c of this.routes)if(c.method===e&&c.pattern===n)throw Error(`Method '${e}' already declared for route '${n}'`);let a={method:e,path:t,pattern:n,params:s,handler:r};this.routes.push(a),i.addRoute(a)}has(e,t){let r=this.trees[e];if(r===void 0)return!1;let n=r.getStaticChild(t);if(n===void 0)return!1;return n.isLeafNode}find(e,t){let r=this.trees[e];if(r===void 0)return;if(t.charCodeAt(0)!==47)t=t.replace(_W,"/");if(this.options.ignoreDuplicateSlashes)t=h0(t);let n,o,i;try{n=UW(t),t=n.path,o=n.querystring,i=n.shouldDecodeParam}catch(m){return}if(this.options.ignoreTrailingSlash)t=g0(t);let s=t;if(this.options.caseSensitive===!1)t=t.toLowerCase();let a=this.options.maxParamLength,c=r.prefix.length,l=[],d=t.length,u=[];while(!0){if(c===d&&r.isLeafNode){let h=r.handlerStorage?.find();if(h!==void 0)return{handler:h.handler,params:h.createParams(l),searchParams:y0(o)}}let m=r.getNextNode(t,c,u,l.length);if(m===void 0){if(u.length===0)return;let h=u.pop();c=h.brotherPathIndex,l.splice(h.paramsCount),m=h.brotherNode}if(r=m,r._tag==="StaticNode"){c+=r.prefix.length;continue}if(r._tag==="WildcardNode"){let h=s.slice(c);if(i)h=S0(h);l.push(h),c=d;continue}if(r._tag==="ParametricNode"){let h=s.indexOf("/",c);if(h===-1)h=d;let S=s.slice(c,h);if(i)S=S0(S);if(r.regex!==void 0){let x=r.regex.exec(S);if(x===null)continue;for(let v=1;v<x.length;v++){let w=x[v];if(w.length>a)return;l.push(w)}}else{if(S.length>a)return;l.push(S)}c=h}}}}class w0{handlers=[];unconstrainedHandler;find(){return this.unconstrainedHandler}add(e){let t={params:e.params,handler:e.handler,createParams:OW(e.params)};this.handlers.push(t),this.unconstrainedHandler=this.handlers[0]}}class Pb{isLeafNode=!1;routes;handlerStorage;addRoute(e){if(this.routes===void 0)this.routes=[e];else this.routes.push(e);if(this.handlerStorage===void 0)this.handlerStorage=new w0;this.isLeafNode=!0,this.handlerStorage.add(e)}}class Ib extends Pb{staticChildren={};findStaticMatchingChild(e,t){let r=this.staticChildren[e.charAt(t)];if(r===void 0||!r.matchPrefix(e,t))return;return r}getStaticChild(e,t=0){if(e.length===t)return this;let r=this.findStaticMatchingChild(e,t);if(r===void 0)return;return r.getStaticChild(e,t+r.prefix.length)}createStaticChild(e){if(e.length===0)return this;let t=this.staticChildren[e.charAt(0)];if(t){let n=1;for(;n<t.prefix.length;n++)if(e.charCodeAt(n)!==t.prefix.charCodeAt(n)){t=t.split(this,n);break}return t.createStaticChild(e.slice(n))}let r=e.charAt(0);return this.staticChildren[r]=new Nf(e),this.staticChildren[r]}}class Nf extends Ib{_tag="StaticNode";constructor(e){super();this.setPrefix(e)}prefix;matchPrefix;parametricChildren=[];wildcardChild;setPrefix(e){if(this.prefix=e,e.length===1)this.matchPrefix=(t,r)=>!0;else{let t=e.length;this.matchPrefix=function(r,n){for(let o=1;o<t;o++)if(r.charCodeAt(n+o)!==this.prefix.charCodeAt(o))return!1;return!0}}}getParametricChild(e){if(e===void 0)return this.parametricChildren.find((r)=>r.isRegex===!1);let t=e.source;return this.parametricChildren.find((r)=>{if(r.regex===void 0)return!1;return r.regex.source===t})}createParametricChild(e,t,r){let n=this.getParametricChild(e);if(n!==void 0)return n.nodePaths.add(r),n;return n=new b0(e,t,r),this.parametricChildren.push(n),this.parametricChildren.sort((o,i)=>{if(!o.isRegex)return 1;if(!i.isRegex)return-1;if(o.staticSuffix===void 0)return 1;if(i.staticSuffix===void 0)return-1;if(i.staticSuffix.endsWith(o.staticSuffix))return 1;if(o.staticSuffix.endsWith(i.staticSuffix))return-1;return 0}),n}createWildcardChild(){if(this.wildcardChild===void 0)this.wildcardChild=new E0;return this.wildcardChild}split(e,t){let r=this.prefix.slice(0,t),n=this.prefix.slice(t);this.setPrefix(n);let o=new Nf(r);return o.staticChildren[n.charAt(0)]=this,e.staticChildren[r.charAt(0)]=o,o}getNextNode(e,t,r,n){let o=this.findStaticMatchingChild(e,t),i=0;if(o===void 0){if(this.parametricChildren.length===0)return this.wildcardChild;o=this.parametricChildren[0],i=1}if(this.wildcardChild!==void 0)r.push({paramsCount:n,brotherPathIndex:t,brotherNode:this.wildcardChild});for(let s=this.parametricChildren.length-1;s>=i;s--)r.push({paramsCount:n,brotherPathIndex:t,brotherNode:this.parametricChildren[s]});return o}}class b0 extends Ib{regex;staticSuffix;_tag="ParametricNode";constructor(e,t,r){super();this.regex=e,this.staticSuffix=t,this.isRegex=!!e,this.nodePaths=new Set([r])}isRegex;nodePaths;getNextNode(e,t){return this.findStaticMatchingChild(e,t)}}class E0 extends Pb{_tag="WildcardNode";getNextNode(e,t,r,n){return}}var kW=(e,t)=>{if(!e)throw Error(t)};function h0(e){return e.replace(/\/\/+/g,"/")}function g0(e){if(e.length>1&&e.charCodeAt(e.length-1)===47)return e.slice(0,-1);return e}function OW(e){let t=e.length;return function(r){let n={};for(let o=0;o<t;o++)n[e[o]]=r[o];return n}}function DW(e,t){let r=1;while(t<e.length){if(t++,e[t]==="\\"){t++;continue}if(e[t]===")")r--;else if(e[t]==="(")r++;if(!r)return t}throw TypeError('Invalid regexp expression in "'+e+'"')}function NW(e){if(e.charCodeAt(1)===94)e=e.slice(0,1)+e.slice(2);if(e.charCodeAt(e.length-2)===36)e=e.slice(0,e.length-2)+e.slice(e.length-1);return e}function FW(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function T0(e,t){if(e===50){if(t===53)return"%";if(t===51)return"#";if(t===52)return"$";if(t===54)return"&";if(t===66)return"+";if(t===98)return"+";if(t===67)return",";if(t===99)return",";if(t===70)return"/";if(t===102)return"/";return}if(e===51){if(t===65)return":";if(t===97)return":";if(t===66)return";";if(t===98)return";";if(t===68)return"=";if(t===100)return"=";if(t===70)return"?";if(t===102)return"?";return}if(e===52&&t===48)return"@";return}function UW(e){let t=!1,r=!1,n="";for(let i=1;i<e.length;i++){let s=e.charCodeAt(i);if(s===37){let a=e.charCodeAt(i+1),c=e.charCodeAt(i+2);if(T0(a,c)===void 0)t=!0;else{if(r=!0,a===50&&c===53)t=!0,e=e.slice(0,i+1)+"25"+e.slice(i+1),i+=2;i+=2}}else if(s===63||s===59||s===35){n=e.slice(i+1),e=e.slice(0,i);break}}return{path:t?decodeURI(e):e,querystring:n,shouldDecodeParam:r}}function S0(e){let t=e.indexOf("%");if(t===-1)return e;let r="",n=t;for(let o=t;o<e.length;o++)if(e.charCodeAt(o)===37){let i=e.charCodeAt(o+1),s=e.charCodeAt(o+2),a=T0(i,s);r+=e.slice(n,o)+a,n=o+3}return e.slice(0,t)+r+e.slice(n)}var BW=["ACL","BIND","CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LINK","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCALENDAR","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REBIND","REPORT","SEARCH","SOURCE","SUBSCRIBE","TRACE","UNBIND","UNLINK","UNLOCK","UNSUBSCRIBE"];var R0=v0;var Ff=Symbol.for("@effect/platform/HttpRouter"),gg=Symbol.for("@effect/platform/HttpRouter/Route"),Sg=Symbol.for("@effect/platform/HttpRouter/RouteContext"),Cb=zs.GenericTag("@effect/platform/HttpRouter/RouteContext"),jW=(e)=>I0.hasProperty(e,Ff);var _0=$W("@effect/platform/HttpRouter/currentRouterConfig",()=>Qa.unsafeMake({}));class zd extends P0.StructuralClass{routes;mounts;[Ff];constructor(e,t){super();this.routes=e,this.mounts=t,this[Ff]=Ff,this.httpApp=k0(this).pipe(wr.flatMap((r)=>this.httpApp=r))}httpApp;commit(){return this.httpApp}toJSON(){return{_id:"Router",routes:this.routes.toJSON(),mounts:this.mounts.toJSON()}}toString(){return Jd.format(this)}[Jd.NodeInspectSymbol](){return this.toJSON()}}var k0=(e)=>wr.map(Qa.get(_0),(t)=>{let r=R0(t),n=sn.toReadonlyArray(e.mounts).map(([i,s,a])=>[i,new _b(new Mf("*",a?.includePrefix?`${i}/*`:"/*",s,a?.includePrefix?$i.none():$i.some(i),!1),{}),a]),o=n.length;return sn.forEach(e.routes,(i)=>{if(i.method==="*")r.all(i.path,i);else r.on(i.method,i.path,i)}),wr.withFiberRuntime((i)=>{let s=zs.unsafeMake(new Map(i.getFiberRef(Qa.currentContext).unsafeMap)),a=zs.unsafeGet(s,lr);if(o>0){let m=a.url.indexOf("?"),h=m===-1?a.url:a.url.slice(0,m);for(let S=0;S<o;S++){let[x,v,w]=n[S];if(h===x||h.startsWith(x+"/")){if(s.unsafeMap.set(Cb.key,v),w?.includePrefix!==!0)s.unsafeMap.set(lr.key,A0(a,x));return wr.locally(wr.flatMap(v.route.handler,ug),Qa.currentContext,s)}}}let c=r.find(a.method,a.url);if(c===void 0&&a.method==="HEAD")c=r.find("GET",a.url);if(c===void 0)return wr.fail(new wb({request:a}));let l=c.handler;if(l.prefix._tag==="Some")s.unsafeMap.set(lr.key,A0(a,l.prefix.value));s.unsafeMap.set(u0.key,c.searchParams),s.unsafeMap.set(Cb.key,new _b(l,c.params));let d=zs.getOption(s,C0.ParentSpan);if(d._tag==="Some"&&d.value._tag==="Span")d.value.attribute("http.route",l.path);let u=wr.flatMap(l.handler,ug);return wr.locally(l.uninterruptible?u:wr.interruptible(u),Qa.currentContext,s)})});function A0(e,t){let r=t.length;return e.modify({url:e.url.length<=r?"/":e.url.slice(r)})}class Mf extends Jd.Class{method;path;handler;prefix;uninterruptible;[gg];constructor(e,t,r,n=$i.none(),o=!1){super();this.method=e,this.path=t,this.handler=r,this.prefix=n,this.uninterruptible=o,this[gg]=gg}toJSON(){return{_id:"@effect/platform/HttpRouter/Route",method:this.method,path:this.path,prefix:this.prefix.toJSON()}}}class _b{route;params;[Sg];constructor(e,t){this.route=e,this.params=t,this[Sg]=Sg}}var O0=new zd(sn.empty(),sn.empty());var D0=Uf(2,(e,t)=>N0(e,t)),N0=(...e)=>new zd(e.reduce((t,r)=>sn.appendAll(t,r.routes),sn.empty()),e.reduce((t,r)=>sn.appendAll(t,r.mounts),sn.empty())),HW=(e)=>e.endsWith("/")?e.slice(0,-1):e;var F0=Uf(2,(e,t)=>(t=HW(t),new zd(sn.map(e.routes,(r)=>new Mf(r.method,r.path==="/"?t:t+r.path,r.handler,$i.orElse($i.map(r.prefix,(n)=>t+n),()=>$i.some(t)),r.uninterruptible)),sn.map(e.mounts,([r,n])=>[r==="/"?t:t+r,n])))),U0=Uf(3,(e,t,r)=>D0(e,F0(r,t)));var kb=(e)=>Uf((t)=>jW(t[0]),(t,r,n,o)=>new zd(sn.append(t.routes,new Mf(e,r,n,$i.none(),o?.uninterruptible??!1)),t.mounts));var B0=kb("GET"),M0=kb("POST");var L0=Uf(2,(e,t)=>new zd(sn.map(e.routes,(r)=>new Mf(r.method,r.path,t(wr.flatMap(r.handler,ug)),r.prefix,r.uninterruptible)),sn.map(e.mounts,([r,n])=>[r,t(n)])));var KW=O0;var VW=U0;var Gd=B0,mi=M0;var Ob=L0;import*as Gs from"effect/Effect";var q0=(e,t,r)=>(...n)=>Gs.async((o)=>{try{e(...n,(i,s)=>{if(i)o(Gs.fail(t?t(i,n):i));else o(Gs.succeed(s))})}catch(i){o(r?Gs.fail(r(i,n)):Gs.die(i))}});var br=q0;sl();import*as Ae from"effect/Effect";import{pipe as j0}from"effect/Function";import*as H0 from"effect/Layer";import*as Mr from"effect/Option";import*as vg from"effect/Stream";import*as W0 from"crypto";import*as Ue from"fs";import*as K0 from"os";import*as Yd from"path";sl();var rr=(e,t)=>(r,[n])=>{let o="Unknown";switch(r.code){case"ENOENT":o="NotFound";break;case"EACCES":o="PermissionDenied";break;case"EEXIST":o="AlreadyExists";break;case"EISDIR":o="BadResource";break;case"ENOTDIR":o="BadResource";break;case"EBUSY":o="Busy";break;case"ELOOP":o="BadResource";break}return new il({reason:o,module:e,method:t,pathOrDescriptor:n,syscall:r.syscall,description:r.message,cause:r})};var dr=(e)=>(t)=>new Md({module:"FileSystem",method:e,cause:t}),JW=(()=>{let e=br(Ue.access,rr("FileSystem","access"),dr("access"));return(t,r)=>{let n=Ue.constants.F_OK;if(r?.readable)n|=Ue.constants.R_OK;if(r?.writable)n|=Ue.constants.W_OK;return e(t,n)}})(),zW=(()=>{let e=br(Ue.cp,rr("FileSystem","copy"),dr("copy"));return(t,r,n)=>e(t,r,{force:n?.overwrite??!1,preserveTimestamps:n?.preserveTimestamps??!1,recursive:!0})})(),GW=(()=>{let e=br(Ue.copyFile,rr("FileSystem","copyFile"),dr("copyFile"));return(t,r)=>e(t,r)})(),YW=(()=>{let e=br(Ue.chmod,rr("FileSystem","chmod"),dr("chmod"));return(t,r)=>e(t,r)})(),XW=(()=>{let e=br(Ue.chown,rr("FileSystem","chown"),dr("chown"));return(t,r,n)=>e(t,r,n)})(),ZW=(()=>{let e=br(Ue.link,rr("FileSystem","link"),dr("link"));return(t,r)=>e(t,r)})(),e4=(()=>{let e=br(Ue.mkdir,rr("FileSystem","makeDirectory"),dr("makeDirectory"));return(t,r)=>e(t,{recursive:r?.recursive??!1,mode:r?.mode})})(),Db=(e)=>{let t=br(Ue.mkdtemp,rr("FileSystem",e),dr(e));return(r)=>Ae.suspend(()=>{let n=r?.prefix??"",o=typeof r?.directory==="string"?Yd.join(r.directory,"."):K0.tmpdir();return t(n?Yd.join(o,n):o+"/")})},t4=Db("makeTempDirectory"),Nb=(e)=>{let t=br(Ue.rm,rr("FileSystem",e),dr(e));return(r,n)=>t(r,{recursive:n?.recursive??!1,force:n?.force??!1})},r4=Nb("remove"),n4=(()=>{let e=Db("makeTempDirectoryScoped"),t=Nb("makeTempDirectoryScoped");return(r)=>Ae.acquireRelease(e(r),(n)=>Ae.orDie(t(n,{recursive:!0})))})(),V0=(e)=>{let t=br(Ue.open,rr("FileSystem",e),dr(e)),r=br(Ue.close,rr("FileSystem",e),dr(e));return(n,o)=>j0(Ae.acquireRelease(t(n,o?.flag??"r",o?.mode),(i)=>Ae.orDie(r(i))),Ae.map((i)=>i4(Ek(i),o?.flag?.startsWith("a")??!1)))},o4=V0("open"),i4=(()=>{let e=(d)=>br(Ue.read,rr("FileSystem",d),dr(d)),t=e("read"),r=e("readAlloc"),n=br(Ue.fstat,rr("FileSystem","stat"),dr("stat")),o=br(Ue.ftruncate,rr("FileSystem","truncate"),dr("truncate")),i=br(Ue.fsync,rr("FileSystem","sync"),dr("sync")),s=(d)=>br(Ue.write,rr("FileSystem",d),dr(d)),a=s("write"),c=s("writeAll");class l{fd;append;[ng];semaphore=Ae.unsafeMakeSemaphore(1);position=0n;constructor(d,u){this.fd=d,this.append=u,this[ng]=ng}get stat(){return Ae.map(n(this.fd),J0)}get sync(){return i(this.fd)}seek(d,u){let m=Wa(d);return this.semaphore.withPermits(1)(Ae.sync(()=>{if(u==="start")this.position=m;else if(u==="current")this.position=this.position+m;return this.position}))}read(d){return this.semaphore.withPermits(1)(Ae.map(Ae.suspend(()=>t(this.fd,{buffer:d,position:this.position})),(u)=>{let m=Wa(u);return this.position=this.position+m,m}))}readAlloc(d){let u=Number(d);return this.semaphore.withPermits(1)(Ae.flatMap(Ae.sync(()=>Buffer.allocUnsafeSlow(u)),(m)=>Ae.map(r(this.fd,{buffer:m,position:this.position}),(h)=>{if(h===0)return Mr.none();if(this.position=this.position+BigInt(h),h===u)return Mr.some(m);let S=Buffer.allocUnsafeSlow(h);return m.copy(S,0,0,h),Mr.some(S)})))}truncate(d){return this.semaphore.withPermits(1)(Ae.map(o(this.fd,d?Number(d):void 0),()=>{if(!this.append){let u=BigInt(d??0);if(this.position>u)this.position=u}}))}write(d){return this.semaphore.withPermits(1)(Ae.map(Ae.suspend(()=>a(this.fd,d,void 0,void 0,this.append?void 0:Number(this.position))),(u)=>{let m=Wa(u);if(!this.append)this.position=this.position+m;return m}))}writeAllChunk(d){return Ae.flatMap(Ae.suspend(()=>c(this.fd,d,void 0,void 0,this.append?void 0:Number(this.position))),(u)=>{if(u===0)return Ae.fail(new il({module:"FileSystem",method:"writeAll",reason:"WriteZero",pathOrDescriptor:this.fd,description:"write returned 0 bytes written"}));if(!this.append)this.position=this.position+BigInt(u);return u<d.length?this.writeAllChunk(d.subarray(u)):Ae.void})}writeAll(d){return this.semaphore.withPermits(1)(this.writeAllChunk(d))}}return(d,u)=>new l(d,u)})(),Q0=(e)=>{let t=Db(e),r=V0(e),n=(o)=>Ae.sync(()=>W0.randomBytes(o).toString("hex"));return(o)=>j0(Ae.zip(t(o),n(6)),Ae.map(([i,s])=>Yd.join(i,s+(o?.suffix??""))),Ae.tap((i)=>Ae.scoped(r(i,{flag:"w+"}))))},s4=Q0("makeTempFile"),a4=(()=>{let e=Q0("makeTempFileScoped"),t=Nb("makeTempFileScoped");return(r)=>Ae.acquireRelease(e(r),(n)=>Ae.orDie(t(Yd.dirname(n),{recursive:!0})))})(),c4=(e,t)=>Ae.tryPromise({try:()=>Ue.promises.readdir(e,t),catch:(r)=>rr("FileSystem","readDirectory")(r,[e])}),l4=(e)=>Ae.async((t,r)=>{try{Ue.readFile(e,{signal:r},(n,o)=>{if(n)t(Ae.fail(rr("FileSystem","readFile")(n,[e])));else t(Ae.succeed(o))})}catch(n){t(Ae.fail(dr("readFile")(n)))}}),d4=(()=>{let e=br(Ue.readlink,rr("FileSystem","readLink"),dr("readLink"));return(t)=>e(t)})(),u4=(()=>{let e=br(Ue.realpath,rr("FileSystem","realPath"),dr("realPath"));return(t)=>e(t)})(),p4=(()=>{let e=br(Ue.rename,rr("FileSystem","rename"),dr("rename"));return(t,r)=>e(t,r)})(),J0=(e)=>({type:e.isFile()?"File":e.isDirectory()?"Directory":e.isSymbolicLink()?"SymbolicLink":e.isBlockDevice()?"BlockDevice":e.isCharacterDevice()?"CharacterDevice":e.isFIFO()?"FIFO":e.isSocket()?"Socket":"Unknown",mtime:Mr.fromNullable(e.mtime),atime:Mr.fromNullable(e.atime),birthtime:Mr.fromNullable(e.birthtime),dev:e.dev,rdev:Mr.fromNullable(e.rdev),ino:Mr.fromNullable(e.ino),mode:e.mode,nlink:Mr.fromNullable(e.nlink),uid:Mr.fromNullable(e.uid),gid:Mr.fromNullable(e.gid),size:Wa(e.size),blksize:Mr.map(Mr.fromNullable(e.blksize),Wa),blocks:Mr.fromNullable(e.blocks)}),Fb=(()=>{let e=br(Ue.stat,rr("FileSystem","stat"),dr("stat"));return(t)=>Ae.map(e(t),J0)})(),f4=(()=>{let e=br(Ue.symlink,rr("FileSystem","symlink"),dr("symlink"));return(t,r)=>e(t,r)})(),m4=(()=>{let e=br(Ue.truncate,rr("FileSystem","truncate"),dr("truncate"));return(t,r)=>e(t,r!==void 0?Number(r):void 0)})(),y4=(()=>{let e=br(Ue.utimes,rr("FileSystem","utime"),dr("utime"));return(t,r,n)=>e(t,r,n)})(),h4=(e,t)=>vg.asyncScoped((r)=>Ae.acquireRelease(Ae.sync(()=>{let n=Ue.watch(e,{recursive:t?.recursive},(o,i)=>{if(!i)return;switch(o){case"rename":{r.fromEffect(Ae.matchEffect(Fb(i),{onSuccess:(s)=>Ae.succeed(Tk({path:i})),onFailure:(s)=>s._tag==="SystemError"&&s.reason==="NotFound"?Ae.succeed(Ak({path:i})):Ae.fail(s)}));return}case"change":{r.single(Rk({path:i}));return}}});return n.on("error",(o)=>{r.fail(new il({module:"FileSystem",reason:"Unknown",method:"watch",pathOrDescriptor:e,cause:o}))}),n.on("close",()=>{r.end()}),n}),(n)=>Ae.sync(()=>n.close()))),g4=(e,t,r)=>Fb(t).pipe(Ae.map((n)=>e.pipe(Mr.flatMap((o)=>o.register(t,n,r)),Mr.getOrElse(()=>h4(t,r)))),vg.unwrap),S4=(e,t,r)=>Ae.async((n,o)=>{try{Ue.writeFile(e,t,{signal:o,flag:r?.flag,mode:r?.mode},(i)=>{if(i)n(Ae.fail(rr("FileSystem","writeFile")(i,[e])));else n(Ae.void)})}catch(i){n(Ae.fail(dr("writeFile")(i)))}}),v4=Ae.map(Ae.serviceOption(cb),(e)=>bk({access:JW,chmod:YW,chown:XW,copy:zW,copyFile:GW,link:ZW,makeDirectory:e4,makeTempDirectory:t4,makeTempDirectoryScoped:n4,makeTempFile:s4,makeTempFileScoped:a4,open:o4,readDirectory:c4,readFile:l4,readLink:d4,realPath:u4,remove:r4,rename:p4,stat:Fb,symlink:f4,truncate:m4,utimes:y4,watch(t,r){return g4(e,t,r)},writeFile:S4})),z0=H0.effect(Cf,v4);var G0=z0;var b4=G0;import{Config as e6,Context as t6,Data as r6,Effect as ZO,Layer as DE}from"effect";import{Data as nu,Effect as dae,Match as uae,Option as pae}from"effect";import*as FK from"effect/SchemaAST";import{Schema as aK,SchemaAST as uO}from"effect";var Ub=Symbol.for("pf/form/annotation/Required");var Bb=Symbol.for("pf/form/annotation/EmailInput"),Mb=Symbol.for("pf/form/annotation/PhoneInput");var xg=Symbol.for("pf/form/annotation/FileInput");var cO=zr(iO(),1);import{Schema as eu}from"effect";var tu=Symbol.for("processfocus:internal-tag/form-schema/structural-only"),lO=Symbol.for("processfocus:internal-tag/form-schema/structural-type");var dO=(e,t)=>eu.Undefined.annotations({[tu]:!0,[lO]:e,...t}),cse=dO("structural"),lse=dO("divider");var sK=(e)=>cO.default(e,{protocols:["https"],require_protocol:!0,require_tld:!0}),dse=eu.String.pipe(eu.filter(sK,{message:()=>"Must be a valid HTTPS URL (e.g. https://example.com/path)"}),eu.annotations({arbitrary:()=>(e)=>e.webUrl({validSchemes:["https"]})}));var use=eu.Boolean.pipe(eu.filter((e)=>e===!0,{message:()=>"This field is required",jsonSchema:{type:"boolean",enum:[!0]},[Ub]:!0}));var Og=(e)=>aK.isPropertySignature(e)?e.ast._tag==="PropertySignatureDeclaration"?uO.annotations(e.ast.type,e.ast.annotations):uO.annotations(e.ast.from.type,{...e.ast.from.annotations,...e.ast.to.annotations}):e.ast;var gO=zr(hO(),1);import{Schema as aE}from"effect";var wse=aE.Trim.pipe(aE.filter((e)=>gO.default(e,{require_tld:!1,allow_utf8_local_part:!0,allow_ip_domain:!0}),{message:()=>"must be a valid email address"}),aE.annotations({identifier:"Email",title:"Email address",description:"A valid email address",jsonSchema:{format:"email"},[Bb]:!0}));import{Either as Tse,Schema as Rse}from"effect";import{ArrayFormatter as Pse}from"effect/ParseResult";import{Schema as cE}from"effect";var PK=/^\+?[\d\s\-()]+$/,IK=(e)=>(e.match(/\d/g)||[]).length,CK=(e)=>{if(!PK.test(e))return!1;let t=IK(e);return t>=7&&t<=15},Ose=cE.Trim.pipe(cE.filter((e)=>CK(e),{message:()=>"must be a valid phone number (7-15 digits)"}),cE.annotations({identifier:"Phone",title:"Phone number",description:"A valid phone number",jsonSchema:{format:"phone"},[Mb]:!0}));import{Schema as Fse}from"effect";import{TitleAnnotationId as Qse}from"effect/SchemaAST";import{cleanupAllPlugins as Xse,getMatchingPlugin as OK,registerWalkerPlugin as Zse,unregisterWalkerPlugin as eae}from"@processfocus/runtime";class UK extends nu.TaggedError("UnknownSchemaFieldTypeError"){get message(){return`Cannot create form field "${this.fieldName}": schema type "${this.schemaType}" is not supported`}}class BK extends nu.TaggedError("IndexSignaturesNotSupportedError"){get message(){return"Index signatures are not supported in schemas"}}class MK extends nu.TaggedError("UnrecognizedASTNodeError"){get message(){return`AST node type "${this.nodeTag}" is not recognized`}}class LK extends nu.TaggedError("InvalidPropertyKeyError"){get message(){return`Property keys must be strings or numbers, got: ${String(this.propertyKey)}`}}class $K extends nu.TaggedError("InvalidFieldPermissionError"){get message(){return`Cannot apply field permission to "${this.fieldName}": ${this.reason}`}}class qK extends nu.TaggedError("InvalidStaticLinkError"){get message(){return`Cannot create link field "${this.fieldName}": url must use http, https, or mailto and text must be a string`}}var KK=zr($n(),1);var ou=(e,t)=>typeof e==="object"&&e!==null&&(t in e)&&e[t]===!0,lE=(e)=>ou(e,"isDocumentStore"),dl=(e)=>ou(e,"isForm"),SO=(e)=>ou(e,"isInvitation");var Ug=(e)=>ou(e,"isOrgUnit");var iu=(e)=>ou(e,"isProcess"),vO=(e)=>ou(e,"isRole");import{Context as QK,Data as Bg,Effect as $ae}from"effect";var nr=(e)=>e.startsWith("/")?e:`/${e}`;var Lf=(e)=>e.split("/").filter((n)=>n.length>0).map((n)=>n.replace(/-/g," ").split(/\s+/).filter((i)=>i.length>0).map((i)=>i.charAt(0).toUpperCase()+i.slice(1).toLowerCase()).join("")).join("");class JK extends Bg.TaggedError("SourceStepNotFoundError"){}class zK extends Bg.TaggedError("EdgeNotFoundError"){}class GK extends Bg.TaggedError("ConditionFunctionMissingError"){}class YK extends Bg.TaggedError("ConditionEvaluationError"){}class XK extends QK.Tag("processfocus:internal-tag/process/ConditionEvaluator")(){}var ZK=zr($n(),1);var eV=zr($n(),1);var tV=zr($n(),1);import{DateTime as Qae}from"effect";function ul(e,t){if(e.process!==t)throw Error(`Step "${e.node.path}" belongs to a different process than "${t.node.path}"`)}function xO(e,t){return ul(e,t),new Mg(e,t)}function wO(e,t,r,n){return ul(e,r),ul(t,r),r.addEdge(e,t,{condition:n?.condition?.fn,conditionText:n?.condition?.text,schedule:n?.schedule?.fn,scheduleText:n?.schedule?.text}),new Mg(t,r)}class Mg{step;process;__scopeState;__scopeSteps;constructor(e,t){this.step=e;this.process=t}end(e,t){if(e)return ul(e,this.process),this.step.process.addEdge(this.step,e,{condition:t?.condition?.fn,conditionText:t?.condition?.text,schedule:t?.schedule?.fn,scheduleText:t?.schedule?.text}),this.process.addEndEdge(e),e;return this.process.addEndEdge(this.step),this.step}next(e,t){return wO(this.step,e,this.process,t)}else(){return new bO(this.step,this.process)}elseEnd(e,t){if(e)return this.else().end(e,t);return this.else().end()}elseNext(e,t){return this.else().next(e,t)}}class bO{step;process;constructor(e,t){this.step=e;this.process=t}next(e,t){return ul(e,this.process),this.process.addEdge(this.step,e,{isElse:!0,conditionText:t?.text}),new Mg(e,this.process)}end(e,t){if(e)return ul(e,this.process),this.process.addEdge(this.step,e,{isElse:!0,conditionText:t?.text}),this.process.addEndEdge(e),e;return this.process.addElseEndEdge(this.step),this.step}}import{Context as sV,Data as RO,Effect as dce}from"effect";import{Context as oV,Data as EO,Effect as ice}from"effect";var rV=zr($n(),1);import{Schema as Xae}from"effect";class iV extends EO.TaggedError("ForEachStepRequiresItemsError"){}class dE extends EO.TaggedError("NotAForEachStepError"){}class TO extends oV.Tag("processfocus:internal-tag/process/CurrentStepJobContext")(){}class aV extends RO.TaggedError("ForEachStepNotFoundError"){}class cV extends RO.TaggedError("ForEachItemsError"){}class lV extends sV.Tag("processfocus:internal-tag/process/ForEachItemsResolver")(){}import{Data as vV,Effect as sle,JSONSchema as ale,Option as cle,Schema as lle,SchemaAST as dle}from"effect";import{Data as IO,Effect as mce,Either as yce,Schema as hce,SchemaAST as gce}from"effect";class uV extends IO.TaggedError("FieldNameCollisionError"){get message(){return`Field name collision: "${this.wrapperField}" is already present as "${this.fieldName}" in its parent struct`}}class pV extends IO.TaggedError("InvalidFlattenAnnotationError"){get message(){return`Invalid schema: field "${this.fieldName}" has flatten annotation but is not a struct (AST tag: ${this.astTag}). Only use Wrapper() with Schema.Struct().`}}import{Match as wce}from"effect";import{Schema as qce,SchemaAST as jce}from"effect";import{Data as yV,Effect as Ice,Schema as qi,SchemaAST as Cce}from"effect";class pE extends yV.TaggedError("FormDecorationError"){}var kce=qi.Array(qi.Struct({value:qi.String,label:qi.String})),Oce=qi.Array(qi.Struct({value:qi.String,startsAt:qi.String,endsAt:qi.String,label:qi.optional(qi.String)}));import{Effect as Qce,Option as Jce,Schema as zce,SchemaAST as Gce}from"effect";class xV extends vV.TaggedError("LookupFieldNotFoundError"){}var wV=zr($n(),1);var bV=zr($n(),1);import{Data as su,Effect as Ale,String as Ple,JSONSchema as Ile,Option as Cle,SchemaAST as _le,Schema as kle}from"effect";class EV extends su.TaggedError("ListItemQueryNotDefinedError"){get message(){return`List ${this.listPath} has no itemQuery defined`}}class TV extends su.TaggedError("ListItemUpdateNotDefinedError"){get message(){return`List ${this.listPath} has no update function defined`}}class RV extends su.TaggedError("ListItemDeleteNotDefinedError"){get message(){return`List ${this.listPath} has no delete function defined`}}class AV extends su.TaggedError("ListCreateError"){}class PV extends su.TaggedError("ListCreateNotDefinedError"){}class IV extends su.TaggedError("ListUpdateValidationError"){}var CV=zr($n(),1);var HO=zr($n(),1);import{EventEmitter as _V}from"events";function kV(){let e=arguments[0];for(let t=1,r=arguments.length;t<r;t++){if(!arguments[t])continue;for(let n in arguments[t])e[n]=arguments[t][n]}return e}var wn=kV;if(typeof Object.assign==="function")wn=Object.assign;function hi(e,t,r,n){let o=e._nodes.get(t),i=null;if(!o)return i;if(n==="mixed")i=o.out&&o.out[r]||o.undirected&&o.undirected[r];else if(n==="directed")i=o.out&&o.out[r];else i=o.undirected&&o.undirected[r];return i}function qn(e){return typeof e==="object"&&e!==null}function NO(e){let t;for(t in e)return!1;return!0}function yi(e,t,r){Object.defineProperty(e,t,{enumerable:!1,configurable:!1,writable:!0,value:r})}function ji(e,t,r){let n={enumerable:!0,configurable:!0};if(typeof r==="function")n.get=r;else n.value=r,n.writable=!1;Object.defineProperty(e,t,n)}function kO(e){if(!qn(e))return!1;if(e.attributes&&!Array.isArray(e.attributes))return!1;return!0}function OV(){let e=Math.floor(Math.random()*256)&255;return()=>e++}function Ys(){let e=arguments,t=null,r=-1;return{[Symbol.iterator](){return this},next(){let n=null;do{if(t===null){if(r++,r>=e.length)return{done:!0};t=e[r][Symbol.iterator]()}if(n=t.next(),n.done){t=null;continue}break}while(!0);return n}}}function cu(){return{[Symbol.iterator](){return this},next(){return{done:!0}}}}class $g extends Error{constructor(e){super();this.name="GraphError",this.message=e}}class we extends $g{constructor(e){super(e);if(this.name="InvalidArgumentsGraphError",typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,we.prototype.constructor)}}class le extends $g{constructor(e){super(e);if(this.name="NotFoundGraphError",typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,le.prototype.constructor)}}class Ge extends $g{constructor(e){super(e);if(this.name="UsageGraphError",typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,Ge.prototype.constructor)}}function FO(e,t){this.key=e,this.attributes=t,this.clear()}FO.prototype.clear=function(){this.inDegree=0,this.outDegree=0,this.undirectedDegree=0,this.undirectedLoops=0,this.directedLoops=0,this.in={},this.out={},this.undirected={}};function UO(e,t){this.key=e,this.attributes=t,this.clear()}UO.prototype.clear=function(){this.inDegree=0,this.outDegree=0,this.directedLoops=0,this.in={},this.out={}};function BO(e,t){this.key=e,this.attributes=t,this.clear()}BO.prototype.clear=function(){this.undirectedDegree=0,this.undirectedLoops=0,this.undirected={}};function lu(e,t,r,n,o){this.key=t,this.attributes=o,this.undirected=e,this.source=r,this.target=n}lu.prototype.attach=function(){let e="out",t="in";if(this.undirected)e=t="undirected";let r=this.source.key,n=this.target.key;if(this.source[e][n]=this,this.undirected&&r===n)return;this.target[t][r]=this};lu.prototype.attachMulti=function(){let e="out",t="in",r=this.source.key,n=this.target.key;if(this.undirected)e=t="undirected";let o=this.source[e],i=o[n];if(typeof i>"u"){if(o[n]=this,!(this.undirected&&r===n))this.target[t][r]=this;return}i.previous=this,this.next=i,o[n]=this,this.target[t][r]=this};lu.prototype.detach=function(){let e=this.source.key,t=this.target.key,r="out",n="in";if(this.undirected)r=n="undirected";delete this.source[r][t],delete this.target[n][e]};lu.prototype.detachMulti=function(){let e=this.source.key,t=this.target.key,r="out",n="in";if(this.undirected)r=n="undirected";if(this.previous===void 0)if(this.next===void 0)delete this.source[r][t],delete this.target[n][e];else this.next.previous=void 0,this.source[r][t]=this.next,this.target[n][e]=this.next;else if(this.previous.next=this.next,this.next!==void 0)this.next.previous=this.previous};var MO=0,LO=1,DV=2,$O=3;function Xs(e,t,r,n,o,i,s){let a,c,l,d;if(n=""+n,r===MO){if(a=e._nodes.get(n),!a)throw new le(`Graph.${t}: could not find the "${n}" node in the graph.`);l=o,d=i}else if(r===$O){if(o=""+o,c=e._edges.get(o),!c)throw new le(`Graph.${t}: could not find the "${o}" edge in the graph.`);let u=c.source.key,m=c.target.key;if(n===u)a=c.target;else if(n===m)a=c.source;else throw new le(`Graph.${t}: the "${n}" node is not attached to the "${o}" edge (${u}, ${m}).`);l=i,d=s}else{if(c=e._edges.get(n),!c)throw new le(`Graph.${t}: could not find the "${n}" edge in the graph.`);if(r===LO)a=c.source;else a=c.target;l=o,d=i}return[a,l,d]}function NV(e,t,r){e.prototype[t]=function(n,o,i){let[s,a]=Xs(this,t,r,n,o,i);return s.attributes[a]}}function FV(e,t,r){e.prototype[t]=function(n,o){let[i]=Xs(this,t,r,n,o);return i.attributes}}function UV(e,t,r){e.prototype[t]=function(n,o,i){let[s,a]=Xs(this,t,r,n,o,i);return s.attributes.hasOwnProperty(a)}}function BV(e,t,r){e.prototype[t]=function(n,o,i,s){let[a,c,l]=Xs(this,t,r,n,o,i,s);return a.attributes[c]=l,this.emit("nodeAttributesUpdated",{key:a.key,type:"set",attributes:a.attributes,name:c}),this}}function MV(e,t,r){e.prototype[t]=function(n,o,i,s){let[a,c,l]=Xs(this,t,r,n,o,i,s);if(typeof l!=="function")throw new we(`Graph.${t}: updater should be a function.`);let d=a.attributes,u=l(d[c]);return d[c]=u,this.emit("nodeAttributesUpdated",{key:a.key,type:"set",attributes:a.attributes,name:c}),this}}function LV(e,t,r){e.prototype[t]=function(n,o,i){let[s,a]=Xs(this,t,r,n,o,i);return delete s.attributes[a],this.emit("nodeAttributesUpdated",{key:s.key,type:"remove",attributes:s.attributes,name:a}),this}}function $V(e,t,r){e.prototype[t]=function(n,o,i){let[s,a]=Xs(this,t,r,n,o,i);if(!qn(a))throw new we(`Graph.${t}: provided attributes are not a plain object.`);return s.attributes=a,this.emit("nodeAttributesUpdated",{key:s.key,type:"replace",attributes:s.attributes}),this}}function qV(e,t,r){e.prototype[t]=function(n,o,i){let[s,a]=Xs(this,t,r,n,o,i);if(!qn(a))throw new we(`Graph.${t}: provided attributes are not a plain object.`);return wn(s.attributes,a),this.emit("nodeAttributesUpdated",{key:s.key,type:"merge",attributes:s.attributes,data:a}),this}}function jV(e,t,r){e.prototype[t]=function(n,o,i){let[s,a]=Xs(this,t,r,n,o,i);if(typeof a!=="function")throw new we(`Graph.${t}: provided updater is not a function.`);return s.attributes=a(s.attributes),this.emit("nodeAttributesUpdated",{key:s.key,type:"update",attributes:s.attributes}),this}}var HV=[{name:(e)=>`get${e}Attribute`,attacher:NV},{name:(e)=>`get${e}Attributes`,attacher:FV},{name:(e)=>`has${e}Attribute`,attacher:UV},{name:(e)=>`set${e}Attribute`,attacher:BV},{name:(e)=>`update${e}Attribute`,attacher:MV},{name:(e)=>`remove${e}Attribute`,attacher:LV},{name:(e)=>`replace${e}Attributes`,attacher:$V},{name:(e)=>`merge${e}Attributes`,attacher:qV},{name:(e)=>`update${e}Attributes`,attacher:jV}];function WV(e){HV.forEach(function({name:t,attacher:r}){r(e,t("Node"),MO),r(e,t("Source"),LO),r(e,t("Target"),DV),r(e,t("Opposite"),$O)})}function KV(e,t,r){e.prototype[t]=function(n,o){let i;if(this.type!=="mixed"&&r!=="mixed"&&r!==this.type)throw new Ge(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new Ge(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);let s=""+n,a=""+o;if(o=arguments[2],i=hi(this,s,a,r),!i)throw new le(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(r!=="mixed")throw new Ge(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(n=""+n,i=this._edges.get(n),!i)throw new le(`Graph.${t}: could not find the "${n}" edge in the graph.`)}return i.attributes[o]}}function VV(e,t,r){e.prototype[t]=function(n){let o;if(this.type!=="mixed"&&r!=="mixed"&&r!==this.type)throw new Ge(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>1){if(this.multi)throw new Ge(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);let i=""+n,s=""+arguments[1];if(o=hi(this,i,s,r),!o)throw new le(`Graph.${t}: could not find an edge for the given path ("${i}" - "${s}").`)}else{if(r!=="mixed")throw new Ge(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(n=""+n,o=this._edges.get(n),!o)throw new le(`Graph.${t}: could not find the "${n}" edge in the graph.`)}return o.attributes}}function QV(e,t,r){e.prototype[t]=function(n,o){let i;if(this.type!=="mixed"&&r!=="mixed"&&r!==this.type)throw new Ge(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new Ge(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);let s=""+n,a=""+o;if(o=arguments[2],i=hi(this,s,a,r),!i)throw new le(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(r!=="mixed")throw new Ge(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(n=""+n,i=this._edges.get(n),!i)throw new le(`Graph.${t}: could not find the "${n}" edge in the graph.`)}return i.attributes.hasOwnProperty(o)}}function JV(e,t,r){e.prototype[t]=function(n,o,i){let s;if(this.type!=="mixed"&&r!=="mixed"&&r!==this.type)throw new Ge(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>3){if(this.multi)throw new Ge(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);let a=""+n,c=""+o;if(o=arguments[2],i=arguments[3],s=hi(this,a,c,r),!s)throw new le(`Graph.${t}: could not find an edge for the given path ("${a}" - "${c}").`)}else{if(r!=="mixed")throw new Ge(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(n=""+n,s=this._edges.get(n),!s)throw new le(`Graph.${t}: could not find the "${n}" edge in the graph.`)}return s.attributes[o]=i,this.emit("edgeAttributesUpdated",{key:s.key,type:"set",attributes:s.attributes,name:o}),this}}function zV(e,t,r){e.prototype[t]=function(n,o,i){let s;if(this.type!=="mixed"&&r!=="mixed"&&r!==this.type)throw new Ge(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>3){if(this.multi)throw new Ge(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);let a=""+n,c=""+o;if(o=arguments[2],i=arguments[3],s=hi(this,a,c,r),!s)throw new le(`Graph.${t}: could not find an edge for the given path ("${a}" - "${c}").`)}else{if(r!=="mixed")throw new Ge(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(n=""+n,s=this._edges.get(n),!s)throw new le(`Graph.${t}: could not find the "${n}" edge in the graph.`)}if(typeof i!=="function")throw new we(`Graph.${t}: updater should be a function.`);return s.attributes[o]=i(s.attributes[o]),this.emit("edgeAttributesUpdated",{key:s.key,type:"set",attributes:s.attributes,name:o}),this}}function GV(e,t,r){e.prototype[t]=function(n,o){let i;if(this.type!=="mixed"&&r!=="mixed"&&r!==this.type)throw new Ge(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new Ge(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);let s=""+n,a=""+o;if(o=arguments[2],i=hi(this,s,a,r),!i)throw new le(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(r!=="mixed")throw new Ge(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(n=""+n,i=this._edges.get(n),!i)throw new le(`Graph.${t}: could not find the "${n}" edge in the graph.`)}return delete i.attributes[o],this.emit("edgeAttributesUpdated",{key:i.key,type:"remove",attributes:i.attributes,name:o}),this}}function YV(e,t,r){e.prototype[t]=function(n,o){let i;if(this.type!=="mixed"&&r!=="mixed"&&r!==this.type)throw new Ge(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new Ge(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);let s=""+n,a=""+o;if(o=arguments[2],i=hi(this,s,a,r),!i)throw new le(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(r!=="mixed")throw new Ge(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(n=""+n,i=this._edges.get(n),!i)throw new le(`Graph.${t}: could not find the "${n}" edge in the graph.`)}if(!qn(o))throw new we(`Graph.${t}: provided attributes are not a plain object.`);return i.attributes=o,this.emit("edgeAttributesUpdated",{key:i.key,type:"replace",attributes:i.attributes}),this}}function XV(e,t,r){e.prototype[t]=function(n,o){let i;if(this.type!=="mixed"&&r!=="mixed"&&r!==this.type)throw new Ge(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new Ge(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);let s=""+n,a=""+o;if(o=arguments[2],i=hi(this,s,a,r),!i)throw new le(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(r!=="mixed")throw new Ge(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(n=""+n,i=this._edges.get(n),!i)throw new le(`Graph.${t}: could not find the "${n}" edge in the graph.`)}if(!qn(o))throw new we(`Graph.${t}: provided attributes are not a plain object.`);return wn(i.attributes,o),this.emit("edgeAttributesUpdated",{key:i.key,type:"merge",attributes:i.attributes,data:o}),this}}function ZV(e,t,r){e.prototype[t]=function(n,o){let i;if(this.type!=="mixed"&&r!=="mixed"&&r!==this.type)throw new Ge(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new Ge(`Graph.${t}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);let s=""+n,a=""+o;if(o=arguments[2],i=hi(this,s,a,r),!i)throw new le(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(r!=="mixed")throw new Ge(`Graph.${t}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(n=""+n,i=this._edges.get(n),!i)throw new le(`Graph.${t}: could not find the "${n}" edge in the graph.`)}if(typeof o!=="function")throw new we(`Graph.${t}: provided updater is not a function.`);return i.attributes=o(i.attributes),this.emit("edgeAttributesUpdated",{key:i.key,type:"update",attributes:i.attributes}),this}}var e5=[{name:(e)=>`get${e}Attribute`,attacher:KV},{name:(e)=>`get${e}Attributes`,attacher:VV},{name:(e)=>`has${e}Attribute`,attacher:QV},{name:(e)=>`set${e}Attribute`,attacher:JV},{name:(e)=>`update${e}Attribute`,attacher:zV},{name:(e)=>`remove${e}Attribute`,attacher:GV},{name:(e)=>`replace${e}Attributes`,attacher:YV},{name:(e)=>`merge${e}Attributes`,attacher:XV},{name:(e)=>`update${e}Attributes`,attacher:ZV}];function t5(e){e5.forEach(function({name:t,attacher:r}){r(e,t("Edge"),"mixed"),r(e,t("DirectedEdge"),"directed"),r(e,t("UndirectedEdge"),"undirected")})}var r5=[{name:"edges",type:"mixed"},{name:"inEdges",type:"directed",direction:"in"},{name:"outEdges",type:"directed",direction:"out"},{name:"inboundEdges",type:"mixed",direction:"in"},{name:"outboundEdges",type:"mixed",direction:"out"},{name:"directedEdges",type:"directed"},{name:"undirectedEdges",type:"undirected"}];function n5(e,t,r,n){let o=!1;for(let i in t){if(i===n)continue;let s=t[i];if(o=r(s.key,s.attributes,s.source.key,s.target.key,s.source.attributes,s.target.attributes,s.undirected),e&&o)return s.key}return}function o5(e,t,r,n){let o,i,s,a=!1;for(let c in t){if(c===n)continue;o=t[c];do{if(i=o.source,s=o.target,a=r(o.key,o.attributes,i.key,s.key,i.attributes,s.attributes,o.undirected),e&&a)return o.key;o=o.next}while(o!==void 0)}return}function fE(e,t){let r=Object.keys(e),n=r.length,o,i=0;return{[Symbol.iterator](){return this},next(){do if(!o){if(i>=n)return{done:!0};let s=r[i++];if(s===t){o=void 0;continue}o=e[s]}else o=o.next;while(!o);return{done:!1,value:{edge:o.key,attributes:o.attributes,source:o.source.key,target:o.target.key,sourceAttributes:o.source.attributes,targetAttributes:o.target.attributes,undirected:o.undirected}}}}}function i5(e,t,r,n){let o=t[r];if(!o)return;let{source:i,target:s}=o;if(n(o.key,o.attributes,i.key,s.key,i.attributes,s.attributes,o.undirected)&&e)return o.key}function s5(e,t,r,n){let o=t[r];if(!o)return;let i=!1;do{if(i=n(o.key,o.attributes,o.source.key,o.target.key,o.source.attributes,o.target.attributes,o.undirected),e&&i)return o.key;o=o.next}while(o!==void 0);return}function mE(e,t){let r=e[t];if(r.next!==void 0)return{[Symbol.iterator](){return this},next(){if(!r)return{done:!0};let o={edge:r.key,attributes:r.attributes,source:r.source.key,target:r.target.key,sourceAttributes:r.source.attributes,targetAttributes:r.target.attributes,undirected:r.undirected};return r=r.next,{done:!1,value:o}}};let n=!1;return{[Symbol.iterator](){return this},next(){if(n===!0)return{done:!0};return n=!0,{done:!1,value:{edge:r.key,attributes:r.attributes,source:r.source.key,target:r.target.key,sourceAttributes:r.source.attributes,targetAttributes:r.target.attributes,undirected:r.undirected}}}}}function a5(e,t){if(e.size===0)return[];if(t==="mixed"||t===e.type)return Array.from(e._edges.keys());let r=t==="undirected"?e.undirectedSize:e.directedSize,n=Array(r),o=t==="undirected",i=e._edges.values(),s=0,a,c;while(a=i.next(),a.done!==!0)if(c=a.value,c.undirected===o)n[s++]=c.key;return n}function qO(e,t,r,n){if(t.size===0)return;let o=r!=="mixed"&&r!==t.type,i=r==="undirected",s,a,c=!1,l=t._edges.values();while(s=l.next(),s.done!==!0){if(a=s.value,o&&a.undirected!==i)continue;let{key:d,attributes:u,source:m,target:h}=a;if(c=n(d,u,m.key,h.key,m.attributes,h.attributes,a.undirected),e&&c)return d}return}function c5(e,t){if(e.size===0)return cu();let r=t!=="mixed"&&t!==e.type,n=t==="undirected",o=e._edges.values();return{[Symbol.iterator](){return this},next(){let i,s;while(!0){if(i=o.next(),i.done)return i;if(s=i.value,r&&s.undirected!==n)continue;break}return{value:{edge:s.key,attributes:s.attributes,source:s.source.key,target:s.target.key,sourceAttributes:s.source.attributes,targetAttributes:s.target.attributes,undirected:s.undirected},done:!1}}}}function yE(e,t,r,n,o,i){let s=t?o5:n5,a;if(r!=="undirected"){if(n!=="out"){if(a=s(e,o.in,i),e&&a)return a}if(n!=="in"){if(a=s(e,o.out,i,!n?o.key:void 0),e&&a)return a}}if(r!=="directed"){if(a=s(e,o.undirected,i),e&&a)return a}return}function l5(e,t,r,n){let o=[];return yE(!1,e,t,r,n,function(i){o.push(i)}),o}function d5(e,t,r){let n=cu();if(e!=="undirected"){if(t!=="out"&&typeof r.in<"u")n=Ys(n,fE(r.in));if(t!=="in"&&typeof r.out<"u")n=Ys(n,fE(r.out,!t?r.key:void 0))}if(e!=="directed"&&typeof r.undirected<"u")n=Ys(n,fE(r.undirected));return n}function hE(e,t,r,n,o,i,s){let a=r?s5:i5,c;if(t!=="undirected"){if(typeof o.in<"u"&&n!=="out"){if(c=a(e,o.in,i,s),e&&c)return c}if(typeof o.out<"u"&&n!=="in"&&(n||o.key!==i)){if(c=a(e,o.out,i,s),e&&c)return c}}if(t!=="directed"){if(typeof o.undirected<"u"){if(c=a(e,o.undirected,i,s),e&&c)return c}}return}function u5(e,t,r,n,o){let i=[];return hE(!1,e,t,r,n,o,function(s){i.push(s)}),i}function p5(e,t,r,n){let o=cu();if(e!=="undirected"){if(typeof r.in<"u"&&t!=="out"&&n in r.in)o=Ys(o,mE(r.in,n));if(typeof r.out<"u"&&t!=="in"&&n in r.out&&(t||r.key!==n))o=Ys(o,mE(r.out,n))}if(e!=="directed"){if(typeof r.undirected<"u"&&n in r.undirected)o=Ys(o,mE(r.undirected,n))}return o}function f5(e,t){let{name:r,type:n,direction:o}=t;e.prototype[r]=function(i,s){if(n!=="mixed"&&this.type!=="mixed"&&n!==this.type)return[];if(!arguments.length)return a5(this,n);if(arguments.length===1){i=""+i;let a=this._nodes.get(i);if(typeof a>"u")throw new le(`Graph.${r}: could not find the "${i}" node in the graph.`);return l5(this.multi,n==="mixed"?this.type:n,o,a)}if(arguments.length===2){i=""+i,s=""+s;let a=this._nodes.get(i);if(!a)throw new le(`Graph.${r}: could not find the "${i}" source node in the graph.`);if(!this._nodes.has(s))throw new le(`Graph.${r}: could not find the "${s}" target node in the graph.`);return u5(n,this.multi,o,a,s)}throw new we(`Graph.${r}: too many arguments (expecting 0, 1 or 2 and got ${arguments.length}).`)}}function m5(e,t){let{name:r,type:n,direction:o}=t,i="forEach"+r[0].toUpperCase()+r.slice(1,-1);e.prototype[i]=function(l,d,u){if(n!=="mixed"&&this.type!=="mixed"&&n!==this.type)return;if(arguments.length===1)return u=l,qO(!1,this,n,u);if(arguments.length===2){l=""+l,u=d;let m=this._nodes.get(l);if(typeof m>"u")throw new le(`Graph.${i}: could not find the "${l}" node in the graph.`);return yE(!1,this.multi,n==="mixed"?this.type:n,o,m,u)}if(arguments.length===3){l=""+l,d=""+d;let m=this._nodes.get(l);if(!m)throw new le(`Graph.${i}: could not find the "${l}" source node in the graph.`);if(!this._nodes.has(d))throw new le(`Graph.${i}: could not find the "${d}" target node in the graph.`);return hE(!1,n,this.multi,o,m,d,u)}throw new we(`Graph.${i}: too many arguments (expecting 1, 2 or 3 and got ${arguments.length}).`)};let s="map"+r[0].toUpperCase()+r.slice(1);e.prototype[s]=function(){let l=Array.prototype.slice.call(arguments),d=l.pop(),u;if(l.length===0){let m=0;if(n!=="directed")m+=this.undirectedSize;if(n!=="undirected")m+=this.directedSize;u=Array(m);let h=0;l.push((S,x,v,w,P,F,R)=>{u[h++]=d(S,x,v,w,P,F,R)})}else u=[],l.push((m,h,S,x,v,w,P)=>{u.push(d(m,h,S,x,v,w,P))});return this[i].apply(this,l),u};let a="filter"+r[0].toUpperCase()+r.slice(1);e.prototype[a]=function(){let l=Array.prototype.slice.call(arguments),d=l.pop(),u=[];return l.push((m,h,S,x,v,w,P)=>{if(d(m,h,S,x,v,w,P))u.push(m)}),this[i].apply(this,l),u};let c="reduce"+r[0].toUpperCase()+r.slice(1);e.prototype[c]=function(){let l=Array.prototype.slice.call(arguments);if(l.length<2||l.length>4)throw new we(`Graph.${c}: invalid number of arguments (expecting 2, 3 or 4 and got ${l.length}).`);if(typeof l[l.length-1]==="function"&&typeof l[l.length-2]!=="function")throw new we(`Graph.${c}: missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array.`);let d,u;if(l.length===2)d=l[0],u=l[1],l=[];else if(l.length===3)d=l[1],u=l[2],l=[l[0]];else if(l.length===4)d=l[2],u=l[3],l=[l[0],l[1]];let m=u;return l.push((h,S,x,v,w,P,F)=>{m=d(m,h,S,x,v,w,P,F)}),this[i].apply(this,l),m}}function y5(e,t){let{name:r,type:n,direction:o}=t,i="find"+r[0].toUpperCase()+r.slice(1,-1);e.prototype[i]=function(c,l,d){if(n!=="mixed"&&this.type!=="mixed"&&n!==this.type)return!1;if(arguments.length===1)return d=c,qO(!0,this,n,d);if(arguments.length===2){c=""+c,d=l;let u=this._nodes.get(c);if(typeof u>"u")throw new le(`Graph.${i}: could not find the "${c}" node in the graph.`);return yE(!0,this.multi,n==="mixed"?this.type:n,o,u,d)}if(arguments.length===3){c=""+c,l=""+l;let u=this._nodes.get(c);if(!u)throw new le(`Graph.${i}: could not find the "${c}" source node in the graph.`);if(!this._nodes.has(l))throw new le(`Graph.${i}: could not find the "${l}" target node in the graph.`);return hE(!0,n,this.multi,o,u,l,d)}throw new we(`Graph.${i}: too many arguments (expecting 1, 2 or 3 and got ${arguments.length}).`)};let s="some"+r[0].toUpperCase()+r.slice(1,-1);e.prototype[s]=function(){let c=Array.prototype.slice.call(arguments),l=c.pop();if(c.push((u,m,h,S,x,v,w)=>l(u,m,h,S,x,v,w)),this[i].apply(this,c))return!0;return!1};let a="every"+r[0].toUpperCase()+r.slice(1,-1);e.prototype[a]=function(){let c=Array.prototype.slice.call(arguments),l=c.pop();if(c.push((u,m,h,S,x,v,w)=>!l(u,m,h,S,x,v,w)),this[i].apply(this,c))return!1;return!0}}function h5(e,t){let{name:r,type:n,direction:o}=t,i=r.slice(0,-1)+"Entries";e.prototype[i]=function(s,a){if(n!=="mixed"&&this.type!=="mixed"&&n!==this.type)return cu();if(!arguments.length)return c5(this,n);if(arguments.length===1){s=""+s;let c=this._nodes.get(s);if(!c)throw new le(`Graph.${i}: could not find the "${s}" node in the graph.`);return d5(n,o,c)}if(arguments.length===2){s=""+s,a=""+a;let c=this._nodes.get(s);if(!c)throw new le(`Graph.${i}: could not find the "${s}" source node in the graph.`);if(!this._nodes.has(a))throw new le(`Graph.${i}: could not find the "${a}" target node in the graph.`);return p5(n,o,c,a)}throw new we(`Graph.${i}: too many arguments (expecting 0, 1 or 2 and got ${arguments.length}).`)}}function g5(e){r5.forEach((t)=>{f5(e,t),m5(e,t),y5(e,t),h5(e,t)})}var S5=[{name:"neighbors",type:"mixed"},{name:"inNeighbors",type:"directed",direction:"in"},{name:"outNeighbors",type:"directed",direction:"out"},{name:"inboundNeighbors",type:"mixed",direction:"in"},{name:"outboundNeighbors",type:"mixed",direction:"out"},{name:"directedNeighbors",type:"directed"},{name:"undirectedNeighbors",type:"undirected"}];function qg(){this.A=null,this.B=null}qg.prototype.wrap=function(e){if(this.A===null)this.A=e;else if(this.B===null)this.B=e};qg.prototype.has=function(e){if(this.A!==null&&e in this.A)return!0;if(this.B!==null&&e in this.B)return!0;return!1};function $f(e,t,r,n,o){for(let i in n){let s=n[i],{source:a,target:c}=s,l=a===r?c:a;if(t&&t.has(l.key))continue;let d=o(l.key,l.attributes);if(e&&d)return l.key}return}function gE(e,t,r,n,o){if(t!=="mixed"){if(t==="undirected")return $f(e,null,n,n.undirected,o);if(typeof r==="string")return $f(e,null,n,n[r],o)}let i=new qg,s;if(t!=="undirected"){if(r!=="out"){if(s=$f(e,null,n,n.in,o),e&&s)return s;i.wrap(n.in)}if(r!=="in"){if(s=$f(e,i,n,n.out,o),e&&s)return s;i.wrap(n.out)}}if(t!=="directed"){if(s=$f(e,i,n,n.undirected,o),e&&s)return s}return}function v5(e,t,r){if(e!=="mixed"){if(e==="undirected")return Object.keys(r.undirected);if(typeof t==="string")return Object.keys(r[t])}let n=[];return gE(!1,e,t,r,function(o){n.push(o)}),n}function qf(e,t,r){let n=Object.keys(r),o=n.length,i=0;return{[Symbol.iterator](){return this},next(){let s=null;do{if(i>=o){if(e)e.wrap(r);return{done:!0}}let a=r[n[i++]],{source:c,target:l}=a;if(s=c===t?l:c,e&&e.has(s.key)){s=null;continue}}while(s===null);return{done:!1,value:{neighbor:s.key,attributes:s.attributes}}}}}function x5(e,t,r){if(e!=="mixed"){if(e==="undirected")return qf(null,r,r.undirected);if(typeof t==="string")return qf(null,r,r[t])}let n=cu(),o=new qg;if(e!=="undirected"){if(t!=="out")n=Ys(n,qf(o,r,r.in));if(t!=="in")n=Ys(n,qf(o,r,r.out))}if(e!=="directed")n=Ys(n,qf(o,r,r.undirected));return n}function w5(e,t){let{name:r,type:n,direction:o}=t;e.prototype[r]=function(i){if(n!=="mixed"&&this.type!=="mixed"&&n!==this.type)return[];i=""+i;let s=this._nodes.get(i);if(typeof s>"u")throw new le(`Graph.${r}: could not find the "${i}" node in the graph.`);return v5(n==="mixed"?this.type:n,o,s)}}function b5(e,t){let{name:r,type:n,direction:o}=t,i="forEach"+r[0].toUpperCase()+r.slice(1,-1);e.prototype[i]=function(l,d){if(n!=="mixed"&&this.type!=="mixed"&&n!==this.type)return;l=""+l;let u=this._nodes.get(l);if(typeof u>"u")throw new le(`Graph.${i}: could not find the "${l}" node in the graph.`);gE(!1,n==="mixed"?this.type:n,o,u,d)};let s="map"+r[0].toUpperCase()+r.slice(1);e.prototype[s]=function(l,d){let u=[];return this[i](l,(m,h)=>{u.push(d(m,h))}),u};let a="filter"+r[0].toUpperCase()+r.slice(1);e.prototype[a]=function(l,d){let u=[];return this[i](l,(m,h)=>{if(d(m,h))u.push(m)}),u};let c="reduce"+r[0].toUpperCase()+r.slice(1);e.prototype[c]=function(l,d,u){if(arguments.length<3)throw new we(`Graph.${c}: missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array.`);let m=u;return this[i](l,(h,S)=>{m=d(m,h,S)}),m}}function E5(e,t){let{name:r,type:n,direction:o}=t,i=r[0].toUpperCase()+r.slice(1,-1),s="find"+i;e.prototype[s]=function(l,d){if(n!=="mixed"&&this.type!=="mixed"&&n!==this.type)return;l=""+l;let u=this._nodes.get(l);if(typeof u>"u")throw new le(`Graph.${s}: could not find the "${l}" node in the graph.`);return gE(!0,n==="mixed"?this.type:n,o,u,d)};let a="some"+i;e.prototype[a]=function(l,d){if(this[s](l,d))return!0;return!1};let c="every"+i;e.prototype[c]=function(l,d){if(this[s](l,(m,h)=>!d(m,h)))return!1;return!0}}function T5(e,t){let{name:r,type:n,direction:o}=t,i=r.slice(0,-1)+"Entries";e.prototype[i]=function(s){if(n!=="mixed"&&this.type!=="mixed"&&n!==this.type)return cu();s=""+s;let a=this._nodes.get(s);if(typeof a>"u")throw new le(`Graph.${i}: could not find the "${s}" node in the graph.`);return x5(n==="mixed"?this.type:n,o,a)}}function R5(e){S5.forEach((t)=>{w5(e,t),b5(e,t),E5(e,t),T5(e,t)})}function Lg(e,t,r,n,o){let i=n._nodes.values(),s=n.type,a,c,l,d,u,m,h;while(a=i.next(),a.done!==!0){let S=!1;if(c=a.value,s!=="undirected"){d=c.out;for(l in d){u=d[l];do{if(m=u.target,S=!0,h=o(c.key,m.key,c.attributes,m.attributes,u.key,u.attributes,u.undirected),e&&h)return u;u=u.next}while(u)}}if(s!=="directed"){d=c.undirected;for(l in d){if(t&&c.key>l)continue;u=d[l];do{if(m=u.target,m.key!==l)m=u.source;if(S=!0,h=o(c.key,m.key,c.attributes,m.attributes,u.key,u.attributes,u.undirected),e&&h)return u;u=u.next}while(u)}}if(r&&!S){if(h=o(c.key,null,c.attributes,null,null,null,null),e&&h)return null}}return}function A5(e,t){let r={key:e};if(!NO(t.attributes))r.attributes=wn({},t.attributes);return r}function P5(e,t,r){let n={key:t,source:r.source.key,target:r.target.key};if(!NO(r.attributes))n.attributes=wn({},r.attributes);if(e==="mixed"&&r.undirected)n.undirected=!0;return n}function I5(e){if(!qn(e))throw new we('Graph.import: invalid serialized node. A serialized node should be a plain object with at least a "key" property.');if(!("key"in e))throw new we("Graph.import: serialized node is missing its key.");if("attributes"in e&&(!qn(e.attributes)||e.attributes===null))throw new we("Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.")}function C5(e){if(!qn(e))throw new we('Graph.import: invalid serialized edge. A serialized edge should be a plain object with at least a "source" & "target" property.');if(!("source"in e))throw new we("Graph.import: serialized edge is missing its source.");if(!("target"in e))throw new we("Graph.import: serialized edge is missing its target.");if("attributes"in e&&(!qn(e.attributes)||e.attributes===null))throw new we("Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.");if("undirected"in e&&typeof e.undirected!=="boolean")throw new we("Graph.import: invalid undirectedness information. Undirected should be boolean or omitted.")}var _5=OV(),k5=new Set(["directed","undirected","mixed"]),OO=new Set(["domain","_events","_eventsCount","_maxListeners"]),O5=[{name:(e)=>`${e}Edge`,generateKey:!0},{name:(e)=>`${e}DirectedEdge`,generateKey:!0,type:"directed"},{name:(e)=>`${e}UndirectedEdge`,generateKey:!0,type:"undirected"},{name:(e)=>`${e}EdgeWithKey`},{name:(e)=>`${e}DirectedEdgeWithKey`,type:"directed"},{name:(e)=>`${e}UndirectedEdgeWithKey`,type:"undirected"}],D5={allowSelfLoops:!0,multi:!1,type:"mixed"};function N5(e,t,r){if(r&&!qn(r))throw new we(`Graph.addNode: invalid attributes. Expecting an object but got "${r}"`);if(t=""+t,r=r||{},e._nodes.has(t))throw new Ge(`Graph.addNode: the "${t}" node already exist in the graph.`);let n=new e.NodeDataClass(t,r);return e._nodes.set(t,n),e.emit("nodeAdded",{key:t,attributes:r}),n}function DO(e,t,r){let n=new e.NodeDataClass(t,r);return e._nodes.set(t,n),e.emit("nodeAdded",{key:t,attributes:r}),n}function jO(e,t,r,n,o,i,s,a){if(!n&&e.type==="undirected")throw new Ge(`Graph.${t}: you cannot add a directed edge to an undirected graph. Use the #.addEdge or #.addUndirectedEdge instead.`);if(n&&e.type==="directed")throw new Ge(`Graph.${t}: you cannot add an undirected edge to a directed graph. Use the #.addEdge or #.addDirectedEdge instead.`);if(a&&!qn(a))throw new we(`Graph.${t}: invalid attributes. Expecting an object but got "${a}"`);if(i=""+i,s=""+s,a=a||{},!e.allowSelfLoops&&i===s)throw new Ge(`Graph.${t}: source & target are the same ("${i}"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false.`);let c=e._nodes.get(i),l=e._nodes.get(s);if(!c)throw new le(`Graph.${t}: source node "${i}" not found.`);if(!l)throw new le(`Graph.${t}: target node "${s}" not found.`);let d={key:null,undirected:n,source:i,target:s,attributes:a};if(r)o=e._edgeKeyGenerator();else if(o=""+o,e._edges.has(o))throw new Ge(`Graph.${t}: the "${o}" edge already exists in the graph.`);if(!e.multi&&(n?typeof c.undirected[s]<"u":typeof c.out[s]<"u"))throw new Ge(`Graph.${t}: an edge linking "${i}" to "${s}" already exists. If you really want to add multiple edges linking those nodes, you should create a multi graph by using the 'multi' option.`);let u=new lu(n,o,c,l,a);e._edges.set(o,u);let m=i===s;if(n){if(c.undirectedDegree++,l.undirectedDegree++,m)c.undirectedLoops++,e._undirectedSelfLoopCount++}else if(c.outDegree++,l.inDegree++,m)c.directedLoops++,e._directedSelfLoopCount++;if(e.multi)u.attachMulti();else u.attach();if(n)e._undirectedSize++;else e._directedSize++;return d.key=o,e.emit("edgeAdded",d),o}function F5(e,t,r,n,o,i,s,a,c){if(!n&&e.type==="undirected")throw new Ge(`Graph.${t}: you cannot merge/update a directed edge to an undirected graph. Use the #.mergeEdge/#.updateEdge or #.addUndirectedEdge instead.`);if(n&&e.type==="directed")throw new Ge(`Graph.${t}: you cannot merge/update an undirected edge to a directed graph. Use the #.mergeEdge/#.updateEdge or #.addDirectedEdge instead.`);if(a){if(c){if(typeof a!=="function")throw new we(`Graph.${t}: invalid updater function. Expecting a function but got "${a}"`)}else if(!qn(a))throw new we(`Graph.${t}: invalid attributes. Expecting an object but got "${a}"`)}i=""+i,s=""+s;let l;if(c)l=a,a=void 0;if(!e.allowSelfLoops&&i===s)throw new Ge(`Graph.${t}: source & target are the same ("${i}"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false.`);let d=e._nodes.get(i),u=e._nodes.get(s),m,h;if(!r){if(m=e._edges.get(o),m){if(m.source.key!==i||m.target.key!==s){if(!n||m.source.key!==s||m.target.key!==i)throw new Ge(`Graph.${t}: inconsistency detected when attempting to merge the "${o}" edge with "${i}" source & "${s}" target vs. ("${m.source.key}", "${m.target.key}").`)}h=m}}if(!h&&!e.multi&&d)h=n?d.undirected[s]:d.out[s];if(h){let P=[h.key,!1,!1,!1];if(c?!l:!a)return P;if(c){let F=h.attributes;h.attributes=l(F),e.emit("edgeAttributesUpdated",{type:"replace",key:h.key,attributes:h.attributes})}else wn(h.attributes,a),e.emit("edgeAttributesUpdated",{type:"merge",key:h.key,attributes:h.attributes,data:a});return P}if(a=a||{},c&&l)a=l(a);let S={key:null,undirected:n,source:i,target:s,attributes:a};if(r)o=e._edgeKeyGenerator();else if(o=""+o,e._edges.has(o))throw new Ge(`Graph.${t}: the "${o}" edge already exists in the graph.`);let x=!1,v=!1;if(!d){if(d=DO(e,i,{}),x=!0,i===s)u=d,v=!0}if(!u)u=DO(e,s,{}),v=!0;m=new lu(n,o,d,u,a),e._edges.set(o,m);let w=i===s;if(n){if(d.undirectedDegree++,u.undirectedDegree++,w)d.undirectedLoops++,e._undirectedSelfLoopCount++}else if(d.outDegree++,u.inDegree++,w)d.directedLoops++,e._directedSelfLoopCount++;if(e.multi)m.attachMulti();else m.attach();if(n)e._undirectedSize++;else e._directedSize++;return S.key=o,e.emit("edgeAdded",S),[o,!0,x,v]}function au(e,t){e._edges.delete(t.key);let{source:r,target:n,attributes:o}=t,i=t.undirected,s=r===n;if(i){if(r.undirectedDegree--,n.undirectedDegree--,s)r.undirectedLoops--,e._undirectedSelfLoopCount--}else if(r.outDegree--,n.inDegree--,s)r.directedLoops--,e._directedSelfLoopCount--;if(e.multi)t.detachMulti();else t.detach();if(i)e._undirectedSize--;else e._directedSize--;e.emit("edgeDropped",{key:t.key,attributes:o,source:r.key,target:n.key,undirected:i})}class Gt extends _V{constructor(e){super();if(e=wn({},D5,e),typeof e.multi!=="boolean")throw new we(`Graph.constructor: invalid 'multi' option. Expecting a boolean but got "${e.multi}".`);if(!k5.has(e.type))throw new we(`Graph.constructor: invalid 'type' option. Should be one of "mixed", "directed" or "undirected" but got "${e.type}".`);if(typeof e.allowSelfLoops!=="boolean")throw new we(`Graph.constructor: invalid 'allowSelfLoops' option. Expecting a boolean but got "${e.allowSelfLoops}".`);let t=e.type==="mixed"?FO:e.type==="directed"?UO:BO;yi(this,"NodeDataClass",t);let r="geid_"+_5()+"_",n=0,o=()=>{let i;do i=r+n++;while(this._edges.has(i));return i};yi(this,"_attributes",{}),yi(this,"_nodes",new Map),yi(this,"_edges",new Map),yi(this,"_directedSize",0),yi(this,"_undirectedSize",0),yi(this,"_directedSelfLoopCount",0),yi(this,"_undirectedSelfLoopCount",0),yi(this,"_edgeKeyGenerator",o),yi(this,"_options",e),OO.forEach((i)=>yi(this,i,this[i])),ji(this,"order",()=>this._nodes.size),ji(this,"size",()=>this._edges.size),ji(this,"directedSize",()=>this._directedSize),ji(this,"undirectedSize",()=>this._undirectedSize),ji(this,"selfLoopCount",()=>this._directedSelfLoopCount+this._undirectedSelfLoopCount),ji(this,"directedSelfLoopCount",()=>this._directedSelfLoopCount),ji(this,"undirectedSelfLoopCount",()=>this._undirectedSelfLoopCount),ji(this,"multi",this._options.multi),ji(this,"type",this._options.type),ji(this,"allowSelfLoops",this._options.allowSelfLoops),ji(this,"implementation",()=>"graphology")}_resetInstanceCounters(){this._directedSize=0,this._undirectedSize=0,this._directedSelfLoopCount=0,this._undirectedSelfLoopCount=0}hasNode(e){return this._nodes.has(""+e)}hasDirectedEdge(e,t){if(this.type==="undirected")return!1;if(arguments.length===1){let r=""+e,n=this._edges.get(r);return!!n&&!n.undirected}else if(arguments.length===2){e=""+e,t=""+t;let r=this._nodes.get(e);if(!r)return!1;return r.out.hasOwnProperty(t)}throw new we(`Graph.hasDirectedEdge: invalid arity (${arguments.length}, instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target.`)}hasUndirectedEdge(e,t){if(this.type==="directed")return!1;if(arguments.length===1){let r=""+e,n=this._edges.get(r);return!!n&&n.undirected}else if(arguments.length===2){e=""+e,t=""+t;let r=this._nodes.get(e);if(!r)return!1;return r.undirected.hasOwnProperty(t)}throw new we(`Graph.hasDirectedEdge: invalid arity (${arguments.length}, instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target.`)}hasEdge(e,t){if(arguments.length===1){let r=""+e;return this._edges.has(r)}else if(arguments.length===2){e=""+e,t=""+t;let r=this._nodes.get(e);if(!r)return!1;return typeof r.out<"u"&&r.out.hasOwnProperty(t)||typeof r.undirected<"u"&&r.undirected.hasOwnProperty(t)}throw new we(`Graph.hasEdge: invalid arity (${arguments.length}, instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target.`)}directedEdge(e,t){if(this.type==="undirected")return;if(e=""+e,t=""+t,this.multi)throw new Ge("Graph.directedEdge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.directedEdges instead.");let r=this._nodes.get(e);if(!r)throw new le(`Graph.directedEdge: could not find the "${e}" source node in the graph.`);if(!this._nodes.has(t))throw new le(`Graph.directedEdge: could not find the "${t}" target node in the graph.`);let n=r.out&&r.out[t]||void 0;if(n)return n.key}undirectedEdge(e,t){if(this.type==="directed")return;if(e=""+e,t=""+t,this.multi)throw new Ge("Graph.undirectedEdge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.undirectedEdges instead.");let r=this._nodes.get(e);if(!r)throw new le(`Graph.undirectedEdge: could not find the "${e}" source node in the graph.`);if(!this._nodes.has(t))throw new le(`Graph.undirectedEdge: could not find the "${t}" target node in the graph.`);let n=r.undirected&&r.undirected[t]||void 0;if(n)return n.key}edge(e,t){if(this.multi)throw new Ge("Graph.edge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.edges instead.");e=""+e,t=""+t;let r=this._nodes.get(e);if(!r)throw new le(`Graph.edge: could not find the "${e}" source node in the graph.`);if(!this._nodes.has(t))throw new le(`Graph.edge: could not find the "${t}" target node in the graph.`);let n=r.out&&r.out[t]||r.undirected&&r.undirected[t]||void 0;if(n)return n.key}areDirectedNeighbors(e,t){e=""+e,t=""+t;let r=this._nodes.get(e);if(!r)throw new le(`Graph.areDirectedNeighbors: could not find the "${e}" node in the graph.`);if(this.type==="undirected")return!1;return t in r.in||t in r.out}areOutNeighbors(e,t){e=""+e,t=""+t;let r=this._nodes.get(e);if(!r)throw new le(`Graph.areOutNeighbors: could not find the "${e}" node in the graph.`);if(this.type==="undirected")return!1;return t in r.out}areInNeighbors(e,t){e=""+e,t=""+t;let r=this._nodes.get(e);if(!r)throw new le(`Graph.areInNeighbors: could not find the "${e}" node in the graph.`);if(this.type==="undirected")return!1;return t in r.in}areUndirectedNeighbors(e,t){e=""+e,t=""+t;let r=this._nodes.get(e);if(!r)throw new le(`Graph.areUndirectedNeighbors: could not find the "${e}" node in the graph.`);if(this.type==="directed")return!1;return t in r.undirected}areNeighbors(e,t){e=""+e,t=""+t;let r=this._nodes.get(e);if(!r)throw new le(`Graph.areNeighbors: could not find the "${e}" node in the graph.`);if(this.type!=="undirected"){if(t in r.in||t in r.out)return!0}if(this.type!=="directed"){if(t in r.undirected)return!0}return!1}areInboundNeighbors(e,t){e=""+e,t=""+t;let r=this._nodes.get(e);if(!r)throw new le(`Graph.areInboundNeighbors: could not find the "${e}" node in the graph.`);if(this.type!=="undirected"){if(t in r.in)return!0}if(this.type!=="directed"){if(t in r.undirected)return!0}return!1}areOutboundNeighbors(e,t){e=""+e,t=""+t;let r=this._nodes.get(e);if(!r)throw new le(`Graph.areOutboundNeighbors: could not find the "${e}" node in the graph.`);if(this.type!=="undirected"){if(t in r.out)return!0}if(this.type!=="directed"){if(t in r.undirected)return!0}return!1}inDegree(e){e=""+e;let t=this._nodes.get(e);if(!t)throw new le(`Graph.inDegree: could not find the "${e}" node in the graph.`);if(this.type==="undirected")return 0;return t.inDegree}outDegree(e){e=""+e;let t=this._nodes.get(e);if(!t)throw new le(`Graph.outDegree: could not find the "${e}" node in the graph.`);if(this.type==="undirected")return 0;return t.outDegree}directedDegree(e){e=""+e;let t=this._nodes.get(e);if(!t)throw new le(`Graph.directedDegree: could not find the "${e}" node in the graph.`);if(this.type==="undirected")return 0;return t.inDegree+t.outDegree}undirectedDegree(e){e=""+e;let t=this._nodes.get(e);if(!t)throw new le(`Graph.undirectedDegree: could not find the "${e}" node in the graph.`);if(this.type==="directed")return 0;return t.undirectedDegree}inboundDegree(e){e=""+e;let t=this._nodes.get(e);if(!t)throw new le(`Graph.inboundDegree: could not find the "${e}" node in the graph.`);let r=0;if(this.type!=="directed")r+=t.undirectedDegree;if(this.type!=="undirected")r+=t.inDegree;return r}outboundDegree(e){e=""+e;let t=this._nodes.get(e);if(!t)throw new le(`Graph.outboundDegree: could not find the "${e}" node in the graph.`);let r=0;if(this.type!=="directed")r+=t.undirectedDegree;if(this.type!=="undirected")r+=t.outDegree;return r}degree(e){e=""+e;let t=this._nodes.get(e);if(!t)throw new le(`Graph.degree: could not find the "${e}" node in the graph.`);let r=0;if(this.type!=="directed")r+=t.undirectedDegree;if(this.type!=="undirected")r+=t.inDegree+t.outDegree;return r}inDegreeWithoutSelfLoops(e){e=""+e;let t=this._nodes.get(e);if(!t)throw new le(`Graph.inDegreeWithoutSelfLoops: could not find the "${e}" node in the graph.`);if(this.type==="undirected")return 0;return t.inDegree-t.directedLoops}outDegreeWithoutSelfLoops(e){e=""+e;let t=this._nodes.get(e);if(!t)throw new le(`Graph.outDegreeWithoutSelfLoops: could not find the "${e}" node in the graph.`);if(this.type==="undirected")return 0;return t.outDegree-t.directedLoops}directedDegreeWithoutSelfLoops(e){e=""+e;let t=this._nodes.get(e);if(!t)throw new le(`Graph.directedDegreeWithoutSelfLoops: could not find the "${e}" node in the graph.`);if(this.type==="undirected")return 0;return t.inDegree+t.outDegree-t.directedLoops*2}undirectedDegreeWithoutSelfLoops(e){e=""+e;let t=this._nodes.get(e);if(!t)throw new le(`Graph.undirectedDegreeWithoutSelfLoops: could not find the "${e}" node in the graph.`);if(this.type==="directed")return 0;return t.undirectedDegree-t.undirectedLoops*2}inboundDegreeWithoutSelfLoops(e){e=""+e;let t=this._nodes.get(e);if(!t)throw new le(`Graph.inboundDegreeWithoutSelfLoops: could not find the "${e}" node in the graph.`);let r=0,n=0;if(this.type!=="directed")r+=t.undirectedDegree,n+=t.undirectedLoops*2;if(this.type!=="undirected")r+=t.inDegree,n+=t.directedLoops;return r-n}outboundDegreeWithoutSelfLoops(e){e=""+e;let t=this._nodes.get(e);if(!t)throw new le(`Graph.outboundDegreeWithoutSelfLoops: could not find the "${e}" node in the graph.`);let r=0,n=0;if(this.type!=="directed")r+=t.undirectedDegree,n+=t.undirectedLoops*2;if(this.type!=="undirected")r+=t.outDegree,n+=t.directedLoops;return r-n}degreeWithoutSelfLoops(e){e=""+e;let t=this._nodes.get(e);if(!t)throw new le(`Graph.degreeWithoutSelfLoops: could not find the "${e}" node in the graph.`);let r=0,n=0;if(this.type!=="directed")r+=t.undirectedDegree,n+=t.undirectedLoops*2;if(this.type!=="undirected")r+=t.inDegree+t.outDegree,n+=t.directedLoops*2;return r-n}source(e){e=""+e;let t=this._edges.get(e);if(!t)throw new le(`Graph.source: could not find the "${e}" edge in the graph.`);return t.source.key}target(e){e=""+e;let t=this._edges.get(e);if(!t)throw new le(`Graph.target: could not find the "${e}" edge in the graph.`);return t.target.key}extremities(e){e=""+e;let t=this._edges.get(e);if(!t)throw new le(`Graph.extremities: could not find the "${e}" edge in the graph.`);return[t.source.key,t.target.key]}opposite(e,t){e=""+e,t=""+t;let r=this._edges.get(t);if(!r)throw new le(`Graph.opposite: could not find the "${t}" edge in the graph.`);let n=r.source.key,o=r.target.key;if(e===n)return o;if(e===o)return n;throw new le(`Graph.opposite: the "${e}" node is not attached to the "${t}" edge (${n}, ${o}).`)}hasExtremity(e,t){e=""+e,t=""+t;let r=this._edges.get(e);if(!r)throw new le(`Graph.hasExtremity: could not find the "${e}" edge in the graph.`);return r.source.key===t||r.target.key===t}isUndirected(e){e=""+e;let t=this._edges.get(e);if(!t)throw new le(`Graph.isUndirected: could not find the "${e}" edge in the graph.`);return t.undirected}isDirected(e){e=""+e;let t=this._edges.get(e);if(!t)throw new le(`Graph.isDirected: could not find the "${e}" edge in the graph.`);return!t.undirected}isSelfLoop(e){e=""+e;let t=this._edges.get(e);if(!t)throw new le(`Graph.isSelfLoop: could not find the "${e}" edge in the graph.`);return t.source===t.target}addNode(e,t){return N5(this,e,t).key}mergeNode(e,t){if(t&&!qn(t))throw new we(`Graph.mergeNode: invalid attributes. Expecting an object but got "${t}"`);e=""+e,t=t||{};let r=this._nodes.get(e);if(r){if(t)wn(r.attributes,t),this.emit("nodeAttributesUpdated",{type:"merge",key:e,attributes:r.attributes,data:t});return[e,!1]}return r=new this.NodeDataClass(e,t),this._nodes.set(e,r),this.emit("nodeAdded",{key:e,attributes:t}),[e,!0]}updateNode(e,t){if(t&&typeof t!=="function")throw new we(`Graph.updateNode: invalid updater function. Expecting a function but got "${t}"`);e=""+e;let r=this._nodes.get(e);if(r){if(t){let o=r.attributes;r.attributes=t(o),this.emit("nodeAttributesUpdated",{type:"replace",key:e,attributes:r.attributes})}return[e,!1]}let n=t?t({}):{};return r=new this.NodeDataClass(e,n),this._nodes.set(e,r),this.emit("nodeAdded",{key:e,attributes:n}),[e,!0]}dropNode(e){e=""+e;let t=this._nodes.get(e);if(!t)throw new le(`Graph.dropNode: could not find the "${e}" node in the graph.`);let r;if(this.type!=="undirected"){for(let n in t.out){r=t.out[n];do au(this,r),r=r.next;while(r)}for(let n in t.in){r=t.in[n];do au(this,r),r=r.next;while(r)}}if(this.type!=="directed")for(let n in t.undirected){r=t.undirected[n];do au(this,r),r=r.next;while(r)}this._nodes.delete(e),this.emit("nodeDropped",{key:e,attributes:t.attributes})}dropEdge(e){let t;if(arguments.length>1){let r=""+arguments[0],n=""+arguments[1];if(t=hi(this,r,n,this.type),!t)throw new le(`Graph.dropEdge: could not find the "${r}" -> "${n}" edge in the graph.`)}else if(e=""+e,t=this._edges.get(e),!t)throw new le(`Graph.dropEdge: could not find the "${e}" edge in the graph.`);return au(this,t),this}dropDirectedEdge(e,t){if(arguments.length<2)throw new Ge("Graph.dropDirectedEdge: it does not make sense to try and drop a directed edge by key. What if the edge with this key is undirected? Use #.dropEdge for this purpose instead.");if(this.multi)throw new Ge("Graph.dropDirectedEdge: cannot use a {source,target} combo when dropping an edge in a MultiGraph since we cannot infer the one you want to delete as there could be multiple ones.");e=""+e,t=""+t;let r=hi(this,e,t,"directed");if(!r)throw new le(`Graph.dropDirectedEdge: could not find a "${e}" -> "${t}" edge in the graph.`);return au(this,r),this}dropUndirectedEdge(e,t){if(arguments.length<2)throw new Ge("Graph.dropUndirectedEdge: it does not make sense to drop a directed edge by key. What if the edge with this key is undirected? Use #.dropEdge for this purpose instead.");if(this.multi)throw new Ge("Graph.dropUndirectedEdge: cannot use a {source,target} combo when dropping an edge in a MultiGraph since we cannot infer the one you want to delete as there could be multiple ones.");let r=hi(this,e,t,"undirected");if(!r)throw new le(`Graph.dropUndirectedEdge: could not find a "${e}" -> "${t}" edge in the graph.`);return au(this,r),this}clear(){this._edges.clear(),this._nodes.clear(),this._resetInstanceCounters(),this.emit("cleared")}clearEdges(){let e=this._nodes.values(),t;while(t=e.next(),t.done!==!0)t.value.clear();this._edges.clear(),this._resetInstanceCounters(),this.emit("edgesCleared")}getAttribute(e){return this._attributes[e]}getAttributes(){return this._attributes}hasAttribute(e){return this._attributes.hasOwnProperty(e)}setAttribute(e,t){return this._attributes[e]=t,this.emit("attributesUpdated",{type:"set",attributes:this._attributes,name:e}),this}updateAttribute(e,t){if(typeof t!=="function")throw new we("Graph.updateAttribute: updater should be a function.");let r=this._attributes[e];return this._attributes[e]=t(r),this.emit("attributesUpdated",{type:"set",attributes:this._attributes,name:e}),this}removeAttribute(e){return delete this._attributes[e],this.emit("attributesUpdated",{type:"remove",attributes:this._attributes,name:e}),this}replaceAttributes(e){if(!qn(e))throw new we("Graph.replaceAttributes: provided attributes are not a plain object.");return this._attributes=e,this.emit("attributesUpdated",{type:"replace",attributes:this._attributes}),this}mergeAttributes(e){if(!qn(e))throw new we("Graph.mergeAttributes: provided attributes are not a plain object.");return wn(this._attributes,e),this.emit("attributesUpdated",{type:"merge",attributes:this._attributes,data:e}),this}updateAttributes(e){if(typeof e!=="function")throw new we("Graph.updateAttributes: provided updater is not a function.");return this._attributes=e(this._attributes),this.emit("attributesUpdated",{type:"update",attributes:this._attributes}),this}updateEachNodeAttributes(e,t){if(typeof e!=="function")throw new we("Graph.updateEachNodeAttributes: expecting an updater function.");if(t&&!kO(t))throw new we("Graph.updateEachNodeAttributes: invalid hints. Expecting an object having the following shape: {attributes?: [string]}");let r=this._nodes.values(),n,o;while(n=r.next(),n.done!==!0)o=n.value,o.attributes=e(o.key,o.attributes);this.emit("eachNodeAttributesUpdated",{hints:t?t:null})}updateEachEdgeAttributes(e,t){if(typeof e!=="function")throw new we("Graph.updateEachEdgeAttributes: expecting an updater function.");if(t&&!kO(t))throw new we("Graph.updateEachEdgeAttributes: invalid hints. Expecting an object having the following shape: {attributes?: [string]}");let r=this._edges.values(),n,o,i,s;while(n=r.next(),n.done!==!0)o=n.value,i=o.source,s=o.target,o.attributes=e(o.key,o.attributes,i.key,s.key,i.attributes,s.attributes,o.undirected);this.emit("eachEdgeAttributesUpdated",{hints:t?t:null})}forEachAdjacencyEntry(e){if(typeof e!=="function")throw new we("Graph.forEachAdjacencyEntry: expecting a callback.");Lg(!1,!1,!1,this,e)}forEachAdjacencyEntryWithOrphans(e){if(typeof e!=="function")throw new we("Graph.forEachAdjacencyEntryWithOrphans: expecting a callback.");Lg(!1,!1,!0,this,e)}forEachAssymetricAdjacencyEntry(e){if(typeof e!=="function")throw new we("Graph.forEachAssymetricAdjacencyEntry: expecting a callback.");Lg(!1,!0,!1,this,e)}forEachAssymetricAdjacencyEntryWithOrphans(e){if(typeof e!=="function")throw new we("Graph.forEachAssymetricAdjacencyEntryWithOrphans: expecting a callback.");Lg(!1,!0,!0,this,e)}nodes(){return Array.from(this._nodes.keys())}forEachNode(e){if(typeof e!=="function")throw new we("Graph.forEachNode: expecting a callback.");let t=this._nodes.values(),r,n;while(r=t.next(),r.done!==!0)n=r.value,e(n.key,n.attributes)}findNode(e){if(typeof e!=="function")throw new we("Graph.findNode: expecting a callback.");let t=this._nodes.values(),r,n;while(r=t.next(),r.done!==!0)if(n=r.value,e(n.key,n.attributes))return n.key;return}mapNodes(e){if(typeof e!=="function")throw new we("Graph.mapNode: expecting a callback.");let t=this._nodes.values(),r,n,o=Array(this.order),i=0;while(r=t.next(),r.done!==!0)n=r.value,o[i++]=e(n.key,n.attributes);return o}someNode(e){if(typeof e!=="function")throw new we("Graph.someNode: expecting a callback.");let t=this._nodes.values(),r,n;while(r=t.next(),r.done!==!0)if(n=r.value,e(n.key,n.attributes))return!0;return!1}everyNode(e){if(typeof e!=="function")throw new we("Graph.everyNode: expecting a callback.");let t=this._nodes.values(),r,n;while(r=t.next(),r.done!==!0)if(n=r.value,!e(n.key,n.attributes))return!1;return!0}filterNodes(e){if(typeof e!=="function")throw new we("Graph.filterNodes: expecting a callback.");let t=this._nodes.values(),r,n,o=[];while(r=t.next(),r.done!==!0)if(n=r.value,e(n.key,n.attributes))o.push(n.key);return o}reduceNodes(e,t){if(typeof e!=="function")throw new we("Graph.reduceNodes: expecting a callback.");if(arguments.length<2)throw new we("Graph.reduceNodes: missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array.");let r=t,n=this._nodes.values(),o,i;while(o=n.next(),o.done!==!0)i=o.value,r=e(r,i.key,i.attributes);return r}nodeEntries(){let e=this._nodes.values();return{[Symbol.iterator](){return this},next(){let t=e.next();if(t.done)return t;let r=t.value;return{value:{node:r.key,attributes:r.attributes},done:!1}}}}export(){let e=Array(this._nodes.size),t=0;this._nodes.forEach((n,o)=>{e[t++]=A5(o,n)});let r=Array(this._edges.size);return t=0,this._edges.forEach((n,o)=>{r[t++]=P5(this.type,o,n)}),{options:{type:this.type,multi:this.multi,allowSelfLoops:this.allowSelfLoops},attributes:this.getAttributes(),nodes:e,edges:r}}import(e,t=!1){if(e instanceof Gt)return e.forEachNode((a,c)=>{if(t)this.mergeNode(a,c);else this.addNode(a,c)}),e.forEachEdge((a,c,l,d,u,m,h)=>{if(t)if(h)this.mergeUndirectedEdgeWithKey(a,l,d,c);else this.mergeDirectedEdgeWithKey(a,l,d,c);else if(h)this.addUndirectedEdgeWithKey(a,l,d,c);else this.addDirectedEdgeWithKey(a,l,d,c)}),this;if(!qn(e))throw new we("Graph.import: invalid argument. Expecting a serialized graph or, alternatively, a Graph instance.");if(e.attributes){if(!qn(e.attributes))throw new we("Graph.import: invalid attributes. Expecting a plain object.");if(t)this.mergeAttributes(e.attributes);else this.replaceAttributes(e.attributes)}let r,n,o,i,s;if(e.nodes){if(o=e.nodes,!Array.isArray(o))throw new we("Graph.import: invalid nodes. Expecting an array.");for(r=0,n=o.length;r<n;r++){i=o[r],I5(i);let{key:a,attributes:c}=i;if(t)this.mergeNode(a,c);else this.addNode(a,c)}}if(e.edges){let a=!1;if(this.type==="undirected")a=!0;if(o=e.edges,!Array.isArray(o))throw new we("Graph.import: invalid edges. Expecting an array.");for(r=0,n=o.length;r<n;r++){s=o[r],C5(s);let{source:c,target:l,attributes:d,undirected:u=a}=s,m;if("key"in s)m=t?u?this.mergeUndirectedEdgeWithKey:this.mergeDirectedEdgeWithKey:u?this.addUndirectedEdgeWithKey:this.addDirectedEdgeWithKey,m.call(this,s.key,c,l,d);else m=t?u?this.mergeUndirectedEdge:this.mergeDirectedEdge:u?this.addUndirectedEdge:this.addDirectedEdge,m.call(this,c,l,d)}}return this}nullCopy(e){let t=new Gt(wn({},this._options,e));return t.replaceAttributes(wn({},this.getAttributes())),t}emptyCopy(e){let t=this.nullCopy(e);return this._nodes.forEach((r,n)=>{let o=wn({},r.attributes);r=new t.NodeDataClass(n,o),t._nodes.set(n,r)}),t}copy(e){if(e=e||{},typeof e.type==="string"&&e.type!==this.type&&e.type!=="mixed")throw new Ge(`Graph.copy: cannot create an incompatible copy from "${this.type}" type to "${e.type}" because this would mean losing information about the current graph.`);if(typeof e.multi==="boolean"&&e.multi!==this.multi&&e.multi!==!0)throw new Ge("Graph.copy: cannot create an incompatible copy by downgrading a multi graph to a simple one because this would mean losing information about the current graph.");if(typeof e.allowSelfLoops==="boolean"&&e.allowSelfLoops!==this.allowSelfLoops&&e.allowSelfLoops!==!0)throw new Ge("Graph.copy: cannot create an incompatible copy from a graph allowing self loops to one that does not because this would mean losing information about the current graph.");let t=this.emptyCopy(e),r=this._edges.values(),n,o;while(n=r.next(),n.done!==!0)o=n.value,jO(t,"copy",!1,o.undirected,o.key,o.source.key,o.target.key,wn({},o.attributes));return t}toJSON(){return this.export()}toString(){return"[object Graph]"}inspect(){let e={};this._nodes.forEach((o,i)=>{e[i]=o.attributes});let t={},r={};this._edges.forEach((o,i)=>{let s=o.undirected?"--":"->",a="",c=o.source.key,l=o.target.key,d;if(o.undirected&&c>l)d=c,c=l,l=d;let u=`(${c})${s}(${l})`;if(!i.startsWith("geid_"))a+=`[${i}]: `;else if(this.multi){if(typeof r[u]>"u")r[u]=0;else r[u]++;a+=`${r[u]}. `}a+=u,t[a]=o.attributes});let n={};for(let o in this)if(this.hasOwnProperty(o)&&!OO.has(o)&&typeof this[o]!=="function"&&typeof o!=="symbol")n[o]=this[o];return n.attributes=this._attributes,n.nodes=e,n.edges=t,yi(n,"constructor",this.constructor),n}}if(typeof Symbol<"u")Gt.prototype[Symbol.for("nodejs.util.inspect.custom")]=Gt.prototype.inspect;O5.forEach((e)=>{["add","merge","update"].forEach((t)=>{let r=e.name(t),n=t==="add"?jO:F5;if(e.generateKey)Gt.prototype[r]=function(o,i,s){return n(this,r,!0,(e.type||this.type)==="undirected",null,o,i,s,t==="update")};else Gt.prototype[r]=function(o,i,s,a){return n(this,r,!1,(e.type||this.type)==="undirected",o,i,s,a,t==="update")}})});WV(Gt);t5(Gt);g5(Gt);R5(Gt);class SE extends Gt{constructor(e){let t=wn({type:"directed"},e);if("multi"in t&&t.multi!==!1)throw new we("DirectedGraph.from: inconsistent indication that the graph should be multi in given options!");if(t.type!=="directed")throw new we('DirectedGraph.from: inconsistent "'+t.type+'" type in given options!');super(t)}}class vE extends Gt{constructor(e){let t=wn({type:"undirected"},e);if("multi"in t&&t.multi!==!1)throw new we("UndirectedGraph.from: inconsistent indication that the graph should be multi in given options!");if(t.type!=="undirected")throw new we('UndirectedGraph.from: inconsistent "'+t.type+'" type in given options!');super(t)}}class xE extends Gt{constructor(e){let t=wn({multi:!0},e);if("multi"in t&&t.multi!==!0)throw new we("MultiGraph.from: inconsistent indication that the graph should be simple in given options!");super(t)}}class wE extends Gt{constructor(e){let t=wn({type:"directed",multi:!0},e);if("multi"in t&&t.multi!==!0)throw new we("MultiDirectedGraph.from: inconsistent indication that the graph should be simple in given options!");if(t.type!=="directed")throw new we('MultiDirectedGraph.from: inconsistent "'+t.type+'" type in given options!');super(t)}}class bE extends Gt{constructor(e){let t=wn({type:"undirected",multi:!0},e);if("multi"in t&&t.multi!==!0)throw new we("MultiUndirectedGraph.from: inconsistent indication that the graph should be simple in given options!");if(t.type!=="undirected")throw new we('MultiUndirectedGraph.from: inconsistent "'+t.type+'" type in given options!');super(t)}}function du(e){e.from=function(t,r){let n=wn({},t.options,r),o=new e(n);return o.import(t),o}}du(Gt);du(SE);du(vE);du(xE);du(wE);du(bE);Gt.Graph=Gt;Gt.DirectedGraph=SE;Gt.UndirectedGraph=vE;Gt.MultiGraph=xE;Gt.MultiDirectedGraph=wE;Gt.MultiUndirectedGraph=bE;Gt.InvalidArgumentsGraphError=we;Gt.NotFoundGraphError=le;Gt.UsageGraphError=Ge;class bn extends HO.Construct{static START_NODE="__start__";static END_NODE="__end__";isProcess=!0;static isVirtualNode(e){return e===bn.START_NODE||e===bn.END_NODE}graph;process;props;orgUnit;constructor(e,t,r){super(e,t);if(this.graph=new Gt({multi:!0,type:"directed"}),this.graph.addNode(bn.START_NODE),this.graph.addNode(bn.END_NODE),this.process=this,this.props=r,this.orgUnit=e,r.responsibilities){let n=new Set;for(let o of r.responsibilities){let i=o.role.node.path;if(n.has(i))throw Error(`Duplicate role "${o.role.name}" in responsibilities for process "${r.name}"`);n.add(i)}}}startMutationName(){return`start${Lf(this.node.path)}`}start(e){return this.graph.addDirectedEdge(bn.START_NODE,e.node.path),xO(e,this)}addEndEdge(e){let t=e.node.path;if(this.graph.hasDirectedEdge(t,bn.END_NODE))throw Error(`Step "${t}" already has .end() called`);this.graph.addDirectedEdge(t,bn.END_NODE)}addElseEndEdge(e){let t=e.node.path,r=this.graph.outEdges(t)??[];for(let n of r)if(this.graph.target(n)===bn.END_NODE){if(this.graph.getEdgeAttributes(n).isElse)throw Error(`Step "${t}" already has .elseEnd() called`)}this.graph.addDirectedEdge(t,bn.END_NODE,{isElse:!0})}validateFlows(){let e=new Set,t=[bn.START_NODE];while(t.length>0){let a=t.pop();if(a===void 0||e.has(a))continue;e.add(a);for(let c of this.graph.outNeighbors(a))t.push(c)}let r=[],n=[],o=[],i=[],s=[];for(let a of this.realNodes())if(!e.has(a))r.push(a);else if(this.graph.outDegree(a)===0)n.push(a);else{let c=this.graph.outEdges(a)??[],l=!1,d=0;for(let u of c){let m=this.graph.getEdgeAttributes(u);if(m.condition)l=!0;if(m.isElse)d++}if(l){if(d===0)o.push(a);else if(d>1)i.push(a)}else if(d>0)s.push(a)}return{unreachable:r,dangling:n,missingElse:o,multipleElse:i,orphanElse:s}}startNodes(){return this.graph.outNeighbors(bn.START_NODE).map((e)=>this.graph.getNodeAttributes(e))}getGraph(){return this.graph}realNodes(){return this.graph.nodes().filter((e)=>!bn.isVirtualNode(e))}addNode(e){let t=e.node.path;if(!this.graph.hasNode(t))this.graph.addNode(t,e)}addEdge(e,t,r){let n=e.node.path,o=t.node.path,i=(this.graph.outEdges(n)??[]).filter((s)=>this.graph.target(s)===o);if(r?.isOnError!==!0&&i.some((s)=>this.graph.getEdgeAttributes(s).isOnError!==!0))throw Error(`Flow from "${n}" to "${o}" already exists`);this.graph.addDirectedEdge(n,o,r)}forms(){let e=[];for(let t of this.graph.nodes()){let r=this.graph.getNodeAttributes(t);if(dl(r))e.push({form:r,path:t})}return e}}var rde=new Set([...Intl.supportedValuesOf("timeZone"),"UTC"]);import{Schema as lQ}from"effect";import{Schema as pr}from"effect";import{Schema as Pn}from"effect";import{Schema as Yr}from"effect";var za=Yr.Int.pipe(Yr.between(0,6),Yr.brand("DayOfWeek"));var WO=Yr.Struct({hour:Yr.Int.pipe(Yr.between(0,23)),minute:Yr.Int.pipe(Yr.between(0,59))}),jg=Yr.Struct({open:WO,close:WO}),uu=Yr.Struct({day:za,ranges:Yr.Array(jg)}),ide=Yr.Array(uu),jf=Yr.Int.pipe(Yr.between(1,12),Yr.brand("Month")),Hf=Yr.Int.pipe(Yr.between(1,31),Yr.brand("DayOfMonth")),EE=Yr.Int.pipe(Yr.between(1,5),Yr.brand("NthOccurrence")),ur=(e)=>e.hour*60+e.minute,Zs=(e)=>ur(e.close)<ur(e.open);var KO=Pn.Struct({id:Pn.String,type:Pn.String,name:Pn.String,startDate:Pn.DateTimeUtcFromSelf,endDate:Pn.DateTimeUtcFromSelf,isActive:Pn.Boolean,weeklySchedule:Pn.optional(Pn.Array(uu))}),lde=Pn.Struct({id:Pn.String,type:Pn.String,name:Pn.String,startDate:Pn.DateTimeUtc,endDate:Pn.DateTimeUtc,isActive:Pn.Boolean,weeklySchedule:Pn.optional(Pn.Array(uu))});import{Schema as In}from"effect";var U5=In.TaggedStruct("FixedHoliday",{name:In.String,month:jf,day:Hf}),B5=In.TaggedStruct("NthWeekdayHoliday",{name:In.String,month:jf,weekday:za,nth:EE}),M5=In.TaggedStruct("LastWeekdayHoliday",{name:In.String,month:jf,weekday:za}),L5=In.TaggedStruct("EasterRelativeHoliday",{name:In.String,daysOffset:In.Int}),TE=In.Union(U5,B5,M5,L5),fde=In.Struct({date:In.DateTimeUtcFromSelf,name:In.String,rule:In.optional(TE)}),RE=In.decodeSync(jf),$5=In.decodeSync(Hf),VO=In.decodeSync(za),q5=In.decodeSync(EE),yo=(e,t,r)=>({_tag:"FixedHoliday",name:e,month:RE(t),day:$5(r)}),pl=(e,t,r,n)=>({_tag:"NthWeekdayHoliday",name:e,month:RE(t),weekday:VO(r),nth:q5(n)}),j5=(e,t,r)=>({_tag:"LastWeekdayHoliday",name:e,month:RE(t),weekday:VO(r)}),Ga=(e,t)=>({_tag:"EasterRelativeHoliday",name:e,daysOffset:t});var mde=[yo("New Year's Day",1,1),pl("Martin Luther King Jr. Day",1,1,3),pl("Presidents' Day",2,1,3),j5("Memorial Day",5,1),yo("Independence Day",7,4),pl("Labor Day",9,1,1),pl("Columbus Day",10,1,2),yo("Veterans Day",11,11),pl("Thanksgiving",11,4,4),yo("Christmas Day",12,25)],yde=[yo("Nieuwjaarsdag",1,1),yo("Koningsdag",4,27),yo("Bevrijdingsdag",5,5),yo("Eerste Kerstdag",12,25),yo("Tweede Kerstdag",12,26),Ga("Goede Vrijdag",-2),Ga("Eerste Paasdag",0),Ga("Tweede Paasdag",1),Ga("Hemelvaartsdag",39),Ga("Eerste Pinksterdag",49),Ga("Tweede Pinksterdag",50)],hde=[yo("New Year's Day",1,1),yo("Day after New Year's Day",1,2),yo("Waitangi Day",2,6),Ga("Good Friday",-2),Ga("Easter Monday",1),yo("Anzac Day",4,25),pl("Queen's Birthday",6,1,1),pl("Labour Day",10,1,4),yo("Christmas Day",12,25),yo("Boxing Day",12,26)];var H5=pr.Struct({date:pr.DateTimeUtcFromSelf,slots:pr.Union(pr.Array(jg),pr.Literal("closed")),note:pr.optional(pr.String)}),Cde=pr.Struct({date:pr.DateTimeUtc,slots:pr.Union(pr.Array(jg),pr.Literal("closed")),note:pr.optional(pr.String)}),_de=pr.Struct({weeklySchedule:pr.Array(uu),holidays:pr.Array(TE),exceptions:pr.Array(H5),nonWorkingDays:pr.Array(za),periods:pr.Array(KO),requireActivePeriod:pr.optional(pr.String),startDayOfWeek:pr.optional(za),timezone:pr.optional(pr.String)});import{Context as QO,Data as W5}from"effect";class Hg extends W5.TaggedError("BusinessCalendarError"){}class AE extends QO.Tag("processfocus:internal-tag/business-calendar/BusinessCalendarService")(){}class PE extends QO.Tag("processfocus:internal-tag/business-calendar/BusinessCalendarConfigService")(){}import{Cause as YO,DateTime as ht,Deferred as Qg,Duration as Kf,Effect as kt,Exit as iQ,Layer as sQ,Option as gi,SynchronizedRef as Jg}from"effect";import{DateTime as Yo,Effect as ho}from"effect";import{Data as pu}from"effect";class K5 extends pu.TaggedError("DateOutOfRangeError"){}class V5 extends pu.TaggedError("NoBusinessHoursError"){}class Q5 extends pu.TaggedError("InvalidCalendarConfigError"){}class Wg extends pu.TaggedError("InvalidDateError"){}class Wf extends pu.TaggedError("InvalidYearError"){}class J5 extends pu.TaggedError("ValidationError"){}var JO=1583,zO=9999,Kg=(e)=>{if(!Number.isInteger(e))return ho.fail(new Wf({year:e,message:`Year must be an integer, got ${e}`}));if(e<JO)return ho.fail(new Wf({year:e,message:`Year must be >= ${JO} for Gregorian calendar, got ${e}`}));if(e>zO)return ho.fail(new Wf({year:e,message:`Year must be <= ${zO}, got ${e}`}));return ho.succeed(e)},z5=(e,t)=>new Date(e,t,0).getDate(),G5=(e,t,r)=>{let n=z5(e,t);if(r>n)return ho.fail(new Wg({year:e,month:t,day:r,message:`Invalid date: ${e}-${t}-${r}. Month ${t} has only ${n} days in year ${e}`}));return ho.void},Vg=(e,t,r)=>ho.try({try:()=>Yo.unsafeMake({year:e,month:t,day:r,hour:0,minute:0,second:0,millis:0}),catch:(n)=>new Wg({year:e,month:t,day:r,message:`Failed to create date: ${n}`})}),Y5=(e)=>ho.gen(function*(){yield*Kg(e);let t=e%19,r=Math.floor(e/100),n=e%100,o=Math.floor(r/4),i=r%4,s=Math.floor((r+8)/25),a=Math.floor((r-s+1)/3),c=(19*t+r-o-a+15)%30,l=Math.floor(n/4),d=n%4,u=(32+2*i+2*l-c-d)%7,m=Math.floor((t+11*c+22*u)/451),h=Math.floor((c+u-7*m+114)/31),S=(c+u-7*m+114)%31+1;return yield*Vg(e,h,S)}),X5=(e,t,r,n)=>ho.gen(function*(){yield*Kg(e);let o=yield*Vg(e,t,1),s=Yo.toParts(o).weekDay,a=r-s;if(a<0)a+=7;if(o=Yo.add(o,{days:a}),o=Yo.add(o,{days:(n-1)*7}),Yo.toParts(o).month!==t)return;return o}),Z5=(e,t,r)=>ho.gen(function*(){yield*Kg(e);let n=t===12?1:t+1,o=t===12?e+1:e,i=yield*Vg(o,n,1);i=Yo.add(i,{days:-1});let c=Yo.toParts(i).weekDay-r;if(c<0)c+=7;return Yo.add(i,{days:-c})}),eQ=(e,t)=>ho.gen(function*(){return yield*Kg(t),yield*G5(t,e.month,e.day),{date:yield*Vg(t,e.month,e.day),name:e.name,rule:e}}),tQ=(e,t)=>ho.gen(function*(){let r=yield*X5(t,e.month,e.weekday,e.nth);if(!r)return;return{date:r,name:e.name,rule:e}}),rQ=(e,t)=>ho.gen(function*(){return{date:yield*Z5(t,e.month,e.weekday),name:e.name,rule:e}}),nQ=(e,t)=>ho.gen(function*(){let r=yield*Y5(t);return{date:Yo.add(r,{days:e.daysOffset}),name:e.name,rule:e}}),oQ=(e,t)=>{switch(e._tag){case"FixedHoliday":return eQ(e,t);case"NthWeekdayHoliday":return tQ(e,t);case"LastWeekdayHoliday":return rQ(e,t);case"EasterRelativeHoliday":return nQ(e,t)}},GO=(e,t)=>ho.gen(function*(){let r=[];for(let n of e){let o=yield*oQ(n,t);if(o)r.push(o)}return r.sort((n,o)=>{let i=Yo.toEpochMillis(n.date),s=Yo.toEpochMillis(o.date);return i-s})}),IE=(e,t)=>{let r=Yo.toParts(e);for(let n of t){let o=Yo.toParts(n.date);if(r.year===o.year&&r.month===o.month&&r.day===o.day)return n}return};var CE=1e4,aQ=1e5,Vf=365,cQ=(e)=>kt.gen(function*(){let t=e.timezone?ht.zoneUnsafeMakeNamed(e.timezone):ht.zoneUnsafeMakeNamed("UTC"),r=(R)=>{let b=ht.setZone(R,t);return ht.toParts(b)},n=(R,b,A,D,B)=>{let J=ht.unsafeMakeZoned({year:R,month:b,day:A,hours:D,minutes:B,seconds:0,millis:0},{timeZone:t,adjustForTimeZone:!0});return ht.toUtc(J)},o=yield*Jg.make(new Map),i=(R)=>GO(e.holidays,R).pipe(kt.catchAllCause((b)=>{if(YO.isInterrupted(b)||YO.isDie(b))return kt.failCause(b);return kt.logWarning("Failed to compute holidays for year",b).pipe(kt.annotateLogs({year:R}),kt.as([]))})),s=(R)=>kt.uninterruptibleMask((b)=>kt.gen(function*(){let A=yield*Jg.modifyEffect(o,(D)=>{let B=D.get(R);if(B!==void 0){if(B._tag==="Done")return kt.succeed([{_tag:"hit",holidays:B.holidays},D]);return kt.succeed([{_tag:"join",deferred:B.deferred},D])}return Qg.make().pipe(kt.map((J)=>{let G=new Map(D);return G.set(R,{_tag:"InFlight",deferred:J}),[{_tag:"owner",deferred:J},G]}))});switch(A._tag){case"hit":return A.holidays;case"join":return yield*b(Qg.await(A.deferred).pipe(kt.catchAll(()=>s(R))));case"owner":{let D=yield*kt.exit(b(kt.gen(function*(){return yield*kt.yieldNow(),yield*i(R)})));if(iQ.isSuccess(D))return yield*Qg.succeed(A.deferred,D.value),yield*Jg.update(o,(B)=>{let J=B.get(R);if(J?._tag==="InFlight"&&J.deferred===A.deferred){let G=new Map(B);return G.set(R,{_tag:"Done",holidays:D.value}),G}return B}),D.value;return yield*Jg.update(o,(B)=>{let J=B.get(R);if(J?._tag==="InFlight"&&J.deferred===A.deferred){let G=new Map(B);return G.delete(R),G}return B}),yield*Qg.fail(A.deferred,"abandoned"),yield*kt.failCause(D.cause)}}})),a=(R)=>{let b=r(R);for(let A of e.exceptions){let D=r(A.date);if(b.year===D.year&&b.month===D.month&&b.day===D.day)return A}return},c=(R)=>{let b=ht.toEpochMillis(R);return[...e.periods].filter((A)=>{let D=ht.toEpochMillis(A.startDate),B=ht.toEpochMillis(A.endDate);return A.isActive&&b>=D&&b<=B})},l=(R)=>{if(!e.requireActivePeriod)return!0;let b=ht.toEpochMillis(R);for(let A of e.periods){if(A.type!==e.requireActivePeriod||!A.isActive)continue;let D=ht.toEpochMillis(A.startDate),B=ht.toEpochMillis(A.endDate);if(b>=D&&b<=B)return!0}return!1},d=(R)=>{let b=c(R);for(let A of b)if(A.weeklySchedule)return A.weeklySchedule;return e.weeklySchedule},u=(R,b)=>R.find((A)=>A.day===b),m=(R,b)=>{let A=ur(R),D=ur(b.open),B=ur(b.close);if(Zs(b))return A>=D||A<B;return A>=D&&A<B},h=(R,b)=>{let A=ur(R),D=ur(b.close);if(Zs(b)){if(A>=ur(b.open))return 1440-A+D;return D-A}return D-A},S=1440,x=(R,b,A,D)=>Math.max(0,Math.min(b,D)-Math.max(R,A)),v=(R,b,A)=>{if(A<=b)return 0;let D=ur(R.open),B=ur(R.close);if(Zs(R))return x(D,1440,b,A)+x(0,B,b,A);return x(D,B,b,A)},w=(R)=>{let b=a(R);if(b){if(b.slots==="closed")return[];return b.slots}let A=r(R),D=d(R);return u(D,A.weekDay)?.ranges??[]},P=(R,b)=>{let A=r(R),D=r(b);return A.year===D.year&&A.month===D.month&&A.day===D.day},F={isBusinessDay:(R)=>kt.gen(function*(){let b=r(R),A=a(R);if(A?.slots==="closed")return!1;if(e.nonWorkingDays.includes(b.weekDay))return!1;let D=yield*s(b.year),B=ht.unsafeMake({year:b.year,month:b.month,day:b.day});if(IE(B,D))return!1;if(!l(R))return!1;let J=d(R),G=u(J,b.weekDay);if(A&&typeof A.slots!=="string")return!0;if(!G||G.ranges.length===0)return!1;return!0}),isBusinessHours:(R)=>kt.gen(function*(){if(!(yield*F.isBusinessDay(R)))return!1;let A=r(R),D={hour:A.hours,minute:A.minutes},B=a(R);if(B&&typeof B.slots!=="string"){for(let ce of B.slots)if(m(D,ce))return!0;return!1}let J=d(R),G=u(J,A.weekDay);if(!G)return!1;for(let ce of G.ranges)if(m(D,ce))return!0;return!1}),addBusinessDays:(R,b)=>kt.gen(function*(){if(b===0||!Number.isFinite(b))return R;let A=Math.max(-CE,Math.min(CE,Math.round(b))),D=R,B=Math.abs(A),J=A>0?1:-1,G=0;while(B>0&&G<CE*2)if(G++,D=ht.add(D,{days:J}),yield*F.isBusinessDay(D))B--;return D}),addBusinessHours:(R,b)=>kt.gen(function*(){if(b<=0||!Number.isFinite(b))return R;let A=Math.min(aQ,b),D=R,B=Math.round(A*60),J=0,G=B+Vf*24*60;while(B>0&&J<G){if(J++,!(yield*F.isBusinessHours(D))){let dt=yield*F.nextBusinessDay(D),Le=yield*F.businessDayStart(dt);if(gi.isNone(Le)){D=ht.add(dt,{days:1});continue}D=Le.value;continue}let re=r(D),Z={hour:re.hours,minute:re.minutes},se=a(D),te;if(se&&typeof se.slots!=="string")te=se.slots;else{let dt=d(D);te=u(dt,re.weekDay)?.ranges??[]}let Ne=0;for(let dt of te)if(m(Z,dt)){Ne=h(Z,dt);break}if(Ne>=B)return ht.add(D,{minutes:B});B-=Ne,D=ht.add(D,{minutes:Ne});let ze=r(D),et={hour:ze.hours,minute:ze.minutes},xt=!1;for(let dt of te){let Le=ur(dt.open),fe=ur(et);if(Le>fe&&!Zs(dt)){let qt=Le-fe;D=ht.add(D,{minutes:qt}),xt=!0;break}}if(!xt){let dt=yield*F.nextBusinessDay(D),Le=yield*F.businessDayStart(dt);if(gi.isNone(Le)){D=ht.add(dt,{days:1});continue}D=Le.value}}return D}),nextBusinessDay:(R)=>kt.gen(function*(){let b=ht.add(R,{days:1}),A=r(b);b=n(A.year,A.month,A.day,0,0);let D=0;while(D<Vf){if(D++,yield*F.isBusinessDay(b))return b;b=ht.add(b,{days:1})}return yield*new Hg({message:`No business day found within ${Vf} days of ${ht.toUtc(R)}, possible misconfigured calendar`})}),previousBusinessDay:(R)=>kt.gen(function*(){let b=r(R),A=n(b.year,b.month,b.day,0,0);A=ht.add(A,{days:-1});let D=0;while(D<Vf){if(D++,yield*F.isBusinessDay(A))return A;A=ht.add(A,{days:-1})}return yield*new Hg({message:`No business day found within ${Vf} days of ${ht.toUtc(R)}, possible misconfigured calendar`})}),businessDayStart:(R)=>kt.gen(function*(){if(!(yield*F.isBusinessDay(R)))return gi.none();let A=r(R),D=a(R);if(D&&typeof D.slots!=="string"){let re=D.slots,Z=re[0];if(!Z)return gi.none();let se=Z.open;for(let te of re)if(ur(te.open)<ur(se))se=te.open;return gi.some(n(A.year,A.month,A.day,se.hour,se.minute))}let B=d(R),J=u(B,A.weekDay),G=J?.ranges[0];if(!J||!G)return gi.none();let ce=G.open;for(let re of J.ranges)if(ur(re.open)<ur(ce))ce=re.open;return gi.some(n(A.year,A.month,A.day,ce.hour,ce.minute))}),businessDayEnd:(R)=>kt.gen(function*(){if(!(yield*F.isBusinessDay(R)))return gi.none();let A=r(R),D=a(R);if(D&&typeof D.slots!=="string"){let re=D.slots,Z=re[0];if(!Z)return gi.none();let se=Z.close;for(let te of re)if(Zs(te))se=te.close;else if(ur(te.close)>ur(se)&&!Zs({open:Z.open,close:se}))se=te.close;return gi.some(n(A.year,A.month,A.day,se.hour,se.minute))}let B=d(R),J=u(B,A.weekDay),G=J?.ranges[0];if(!J||!G)return gi.none();let ce=G.close;for(let re of J.ranges)if(Zs(re))ce=re.close;else if(ur(re.close)>ur(ce)&&!Zs({open:G.open,close:ce}))ce=re.close;return gi.some(n(A.year,A.month,A.day,ce.hour,ce.minute))}),businessHoursRemaining:(R)=>kt.gen(function*(){if(!(yield*F.isBusinessHours(R)))return Kf.zero;let A=r(R),D={hour:A.hours,minute:A.minutes},B=a(R),J;if(B&&typeof B.slots!=="string")J=B.slots;else{let re=d(R);J=u(re,A.weekDay)?.ranges??[]}let G=0,ce=!1;for(let re of J)if(m(D,re))G+=h(D,re),ce=!0;else if(ce&&ur(re.open)>ur(D))G+=ur(re.close)-ur(re.open);return Kf.minutes(G)}),businessDaysBetween:(R,b)=>kt.gen(function*(){let A=ht.toEpochMillis(R),D=ht.toEpochMillis(b);if(A>=D)return 0;let B=0,J=R;while(ht.toEpochMillis(J)<D){if(yield*F.isBusinessDay(J))B++;J=ht.add(J,{days:1})}return B}),businessHoursBetween:(R,b)=>kt.gen(function*(){let A=ht.toEpochMillis(R),D=ht.toEpochMillis(b);if(A>=D)return Kf.zero;let B=(Ne,ze,et)=>kt.gen(function*(){if(!(yield*F.isBusinessDay(Ne)))return 0;let dt=w(Ne),Le=0;for(let fe of dt)Le+=v(fe,ze,et);return Le}),J=r(R),G=r(b),ce=J.hours*60+J.minutes,re=G.hours*60+G.minutes;if(P(R,b)){let Ne=yield*B(R,ce,re);return Kf.minutes(Ne)}let Z=0;Z+=yield*B(R,ce,1440);let se=n(J.year,J.month,J.day,12,0);se=ht.add(se,{days:1});let te=n(G.year,G.month,G.day,12,0);while(ht.toEpochMillis(se)<ht.toEpochMillis(te)){Z+=yield*B(se,0,1440);let Ne=r(se);se=ht.add(n(Ne.year,Ne.month,Ne.day,12,0),{days:1})}return Z+=yield*B(b,0,re),Kf.minutes(Z)}),isHoliday:(R)=>kt.gen(function*(){let b=r(R),A=yield*s(b.year),D=ht.unsafeMake({year:b.year,month:b.month,day:b.day});return IE(D,A)!==void 0}),getHolidaysForYear:(R)=>s(R),getActivePeriods:(R)=>kt.succeed(c(R)),getActivePeriodsByType:(R,b)=>kt.succeed(c(R).filter((A)=>A.type===b)),isWithinPeriodType:(R,b)=>kt.succeed(c(R).some((A)=>A.type===b)),getPeriodsForDateRange:(R,b,A)=>kt.succeed([...e.periods].filter((D)=>{if(A&&D.type!==A)return!1;let B=ht.toEpochMillis(D.startDate),J=ht.toEpochMillis(D.endDate),G=ht.toEpochMillis(R),ce=ht.toEpochMillis(b);return B<=ce&&J>=G})),getEffectiveSchedule:(R)=>kt.sync(()=>{let b=a(R);if(b){if(b.slots==="closed")return[];return[{day:r(R).weekDay,ranges:[...b.slots]}]}return[...d(R)]})};return F}),Hde=sQ.effect(AE,kt.flatMap(PE,cQ));import{DateTime as Vde}from"effect";import{DateTime as zde,Duration as Gde,Effect as Yde}from"effect";var yue=lQ.decodeSync(Hf);import{Data as zg,Effect as vue}from"effect";class dQ extends zg.TaggedError("EmbeddedFormNotStartStepError"){}class uQ extends zg.TaggedError("UnsupportedEmbeddedFormFieldError"){}class pQ extends zg.TaggedError("EmbeddedFormMetadataBuildError"){}class fQ extends zg.TaggedError("EmbeddedProcessHasMultipleStartStepsError"){}import{Data as SQ,Effect as zue}from"effect";var hQ=zr($n(),1);class vQ extends SQ.TaggedError("OrganisationFrontendManifestBuildError"){}import*as fl from"path";import{RUNTIME_ARTIFACT_FORMAT as xQ,RUNTIME_ARTIFACT_VERSION as wQ,Runtime as XO,parseServerPluginRegistrations as bQ}from"@processfocus/runtime";import{Config as EQ,Context as TQ,Data as RQ,Effect as Po,Either as dpe,Layer as AQ}from"effect";class fu extends RQ.TaggedError("processfocus:internal-tag/OrganisationLoadError"){}class Gg extends TQ.Tag("processfocus:internal-tag/process/OrganisationProvider")(){}var PQ=(e)=>Po.gen(function*(){let t=yield*Cf,r=fl.resolve(process.cwd(),e),n=fl.join(r,"org.js"),o=fl.join(r,"src/index.ts"),s=(yield*t.exists(n))?n:o;if(!(yield*t.exists(s)))return yield*new fu({message:`Failed to load organisation from ${e}: Organisation file not found: ${s}`,orgPath:e});let c=yield*Po.tryPromise({try:async()=>await import(s),catch:(S)=>new fu({message:`Failed to load organisation from ${e}: ${S instanceof Error?S.message:String(S)}`,orgPath:e,cause:S})}),l=yield*XO.loadArtifact(Po.succeed({format:xQ,version:wQ,organisation:c.org})).pipe(Po.mapError((S)=>new fu({message:`Failed to load organisation from ${e}: ${S.message}`,orgPath:e}))),{CustomDbLayer:d,CustomGraphqlSchema:u,CustomJobLayer:m}=c,h=yield*bQ(c.ServerPlugins).pipe(Po.mapError((S)=>new fu({message:`Failed to load organisation from ${e}: ${S.message}`,orgPath:e,cause:S})));return{org:l.organisation,resolvedPath:r,...d?{customDbLayer:d}:{},...u?{customGraphqlSchema:u}:{},...m?{customJobLayer:m}:{},serverPlugins:h}}),IQ=(e)=>XO.loadOrganisation({load:PQ},e),CQ=({org:e,orgPath:t,customDbLayer:r,customGraphqlSchema:n,customJobLayer:o,serverPlugins:i=[]})=>Po.gen(function*(){let s=yield*Cf,a=fl.join(t,"dist/graphql/org.graphql"),c=fl.join(t,"graphql/org.graphql"),d=(yield*s.exists(a))?a:c;return{organisation:e,orgPath:t,schemaPath:d,...r?{customDbLayer:r}:{},...n?{customGraphqlSchema:n}:{},...o?{customJobLayer:o}:{},serverPlugins:i}});var _Q=({name:e,customDbLayer:t,customJobLayer:r,serverPlugins:n=[]})=>Po.gen(function*(){if(yield*Po.log(`Loaded organisation: ${e}`),t)yield*Po.log("Loaded custom database layer from organisation");if(r)yield*Po.log("Loaded custom job layer from organisation");if(n.length>0)yield*Po.log(`Loaded ${n.length} server plugin registration(s) from organisation`)}),ppe=AQ.effect(Gg,Po.gen(function*(){let e=yield*EQ.string("PF_ORG").pipe(Po.mapError(()=>new fu({message:"PF_ORG environment variable is not set",orgPath:"<env>"})));yield*Po.log(`Loading organisation from: ${e}`);let{org:t,resolvedPath:r,customDbLayer:n,customGraphqlSchema:o,customJobLayer:i,serverPlugins:s}=yield*IQ(e);return yield*_Q({name:t.name,customDbLayer:n,customJobLayer:i,serverPlugins:s}),yield*CQ({org:t,orgPath:r,customDbLayer:n,customGraphqlSchema:o,customJobLayer:i,serverPlugins:s})}));var kQ=zr($n(),1);var OQ=zr($n(),1);import{Duration as gpe}from"effect";import{Context as DQ,Data as Yg,DateTime as wpe,Effect as bpe,Option as Epe,Schema as Tpe,SchemaAST as Rpe}from"effect";class NQ extends Yg.TaggedError("SourceStepNotFoundForScheduleError"){}class FQ extends Yg.TaggedError("EdgeNotFoundForScheduleError"){}class UQ extends Yg.TaggedError("ScheduleFunctionMissingError"){}class BQ extends Yg.TaggedError("ScheduleEvaluationError"){}class MQ extends DQ.Tag("processfocus:internal-tag/process/ScheduleEvaluator")(){}var LQ=zr($n(),1);import{Context as _E,Data as Qf,Effect as Dpe,Option as Npe,Schema as Fpe}from"effect";class $Q extends Qf.TaggedError("StepNotFoundError"){}class qQ extends Qf.TaggedError("NotASystemStepError"){}class jQ extends Qf.TaggedError("SystemStepExecutionError"){}class HQ extends Qf.TaggedError("OutputValidationError"){}class WQ extends Qf.TaggedError("LongDurationDispatchError"){}class KQ extends _E.Tag("processfocus:internal-tag/process/LongDurationDispatcher")(){}class VQ extends _E.Tag("processfocus:internal-tag/process/StepProcessStateReader")(){}class QQ extends _E.Tag("processfocus:internal-tag/process/SystemStepExecutor")(){}import{Context as JQ,Data as zQ}from"effect";class GQ extends zQ.TaggedError("UsageCostError"){}class YQ extends JQ.Tag("processfocus:internal-tag/process/UsageCostService")(){}var XQ=zr($n(),1);var kE=(e)=>typeof e==="object"&&e!==null&&("isCustomEntitiesConfig"in e)&&e.isCustomEntitiesConfig===!0;var ZQ=zr($n(),1);var OE=(e)=>typeof e==="object"&&e!==null&&("isPoliciesConfig"in e)&&e.isPoliciesConfig===!0;class NE extends r6.TaggedError("CedarPoliciesDirNotFoundError"){get message(){return`CEDAR_PATH directory does not exist: ${this.path}`}}class Xg extends t6.Tag("processfocus:internal-tag/auth-config/CedarPoliciesProvider")(){}var eD=(e)=>e.node.children.flatMap((t)=>OE(t)?[...t.policyFiles]:[]),tD=(e)=>e.node.children.flatMap((t)=>kE(t)?[...t.schemaFiles]:[]),n6=DE.effect(Xg,ZO.gen(function*(){let e=yield*Cf,t=yield*e6.string("CEDAR_PATH");if(!(yield*e.exists(t)))return yield*new NE({path:t});let n=yield*e.readDirectory(t),o=n.filter((c)=>c.endsWith(".cedar")),i=n.filter((c)=>c.endsWith(".cedarschema")),s=o.map((c)=>Jf.join(t,c)),a=i.map((c)=>Jf.join(t,c));return{policyPaths:s,schemaPaths:a}})).pipe(DE.provide(b4)),o6=DE.effect(Xg,ZO.gen(function*(){let e=yield*Gg,r=eD(e.organisation).map((i)=>Jf.join(e.orgPath,i)),o=tD(e.organisation).map((i)=>Jf.join(e.orgPath,i));return{policyPaths:r,schemaPaths:o}}));import{Schema as Qe}from"effect";var Zg=Qe.Struct({rpName:Qe.String,rpID:Qe.String,origin:Qe.Union(Qe.String,Qe.Array(Qe.String))}),rD=["google","github","microsoft","apple","discord","spotify","slack","linkedin","twitch","yahoo","x","keycloak","cognito","jumpcloud","facebook"];var ml=Qe.Struct({clientID:Qe.String,clientSecret:Qe.String,scopes:Qe.Array(Qe.String),pkce:Qe.optional(Qe.Boolean),query:Qe.optional(Qe.Record({key:Qe.String,value:Qe.String}))}),i6=ml.pipe(Qe.extend(Qe.Struct({responseMode:Qe.optional(Qe.Literal("query","form_post"))}))),s6=ml.pipe(Qe.extend(Qe.Struct({tenant:Qe.String}))),a6=ml.pipe(Qe.extend(Qe.Struct({team:Qe.String}))),c6=ml.pipe(Qe.extend(Qe.Struct({baseUrl:Qe.String,realm:Qe.String}))),l6=ml.pipe(Qe.extend(Qe.Struct({domain:Qe.String,region:Qe.String,userPoolId:Qe.String}))),d6=Qe.Literal(...rD),nD=ml.pipe(Qe.extend(Qe.Struct({invitedOrgUnits:Qe.optional(Qe.Array(Qe.String)),orgUnitAsRole:Qe.optional(Qe.Boolean),serviceAccountKey:Qe.optional(Qe.String),adminEmail:Qe.optional(Qe.String)}))),u6=Qe.Struct({secret:Qe.String,audience:Qe.String});var oD=(e)=>Si.gen(function*(){let t=e.name,r=yield*iD(e,void 0,e.timeZone??"UTC",e.businessCalendar?.startDayOfWeek),n=nr(e.node.path),o=p6(e,n),i=f6(e,n);return{name:t,rootOrgUnit:r,weeklySchedule:o,holidayRules:i}}),p6=(e,t)=>{if(!e.businessCalendar?.weeklySchedule)return[];return e.businessCalendar.weeklySchedule.map((r)=>({orgUnitPath:t,dayOfWeek:r.day,timeRanges:r.ranges.map((n)=>({open:{hour:n.open.hour,minute:n.open.minute},close:{hour:n.close.hour,minute:n.close.minute}}))}))},f6=(e,t)=>{if(!e.businessCalendar?.holidays)return[];return e.businessCalendar.holidays.map((r)=>({orgUnitPath:t,name:r.name,rule:r}))},iD=(e,t,r,n)=>Si.gen(function*(){let o=nr(e.node.path),i=yield*m6(e),s=y6(e,o),a=e.node.children.filter(Ug),c=yield*Si.forEach(a,(l)=>iD(l,o,r,n),{concurrency:"unbounded"});return{name:e.name,orgUnitLevel:e.type??"unit",path:o,parentOrgUnitPath:t,acronym:e.acronym,timezone:r,startDayOfWeek:n,processes:i,roles:s,children:c}}),m6=(e)=>Si.gen(function*(){let r=e.node.children.filter(iu);if(r.length===0)return[];return yield*Si.forEach(r,(n)=>S6(n),{concurrency:"unbounded"})}),y6=(e,t)=>e.node.children.filter(vO).map((o)=>({orgUnitPath:t,name:o.name,path:nr(o.node.path)})),h6=(e,t)=>{let r=nr(e.node.path),n=new Set,o=[],i=t.nodes().filter((s)=>!bn.isVirtualNode(s));for(let s of i){let c=t.getNodeAttributes(s).props.phase,l=c?nr(c.node.path):void 0;if(c&&l&&!n.has(l))n.add(l),o.push({processPath:r,name:c.name,path:l,order:o.length+1})}return o},g6=(e)=>(e.props.responsibilities??[]).map((r,n)=>({processPath:nr(e.node.path),rolePath:nr(r.role.node.path),responsibility:r.responsibility,order:n+1})),sD=(e)=>{if(!e)return;return{value:e.value,unit:e.unit,warningAt:e.warningAt}},S6=(e)=>Si.gen(function*(){let t=e.getGraph(),r=nr(e.node.path),n=nr(e.orgUnit.node.path),o=yield*v6(t,r),i=yield*w6(t),s=g6(e),a=h6(e,t),c=sD(e.props.sla);return{orgUnitPath:n,name:e.props.name,path:r,purpose:e.props.purpose,steps:o,flows:i,responsibilities:s,phases:a,...c&&{sla:c}}}),v6=(e,t)=>Si.gen(function*(){let r=e.nodes().filter((n)=>!bn.isVirtualNode(n));return yield*Si.forEach(r,(n)=>x6(e,n,t),{concurrency:"unbounded"})}),x6=(e,t,r)=>{let n=e.getNodeAttributes(t),o=n.props.role?nr(n.props.role.node.path):void 0,i=dl(n)?n.totalFields:void 0,s=dl(n)&&n.supportingRoles?n.supportingRoles.map((h)=>nr(h.node.path)):void 0,a=n.props.phase?nr(n.props.phase.node.path):void 0,c=sD(n.props.sla),l=n.hasForEach===!0?!0:void 0,d=n.isForm&&n.embed?!0:void 0,u=n.isSystemStep?n.retries:void 0,m=T6(n);return Si.succeed({name:n.props.name??n.node.id,purpose:n.props.purpose??"",processPath:r,path:nr(n.node.path),...o!==void 0&&{rolePath:o},...s!==void 0&&{supportingRolePaths:s},...i!==void 0&&{formFields:i},...a!==void 0&&{phasePath:a},...c&&{sla:c},...l!==void 0&&{hasForEach:l},...d!==void 0&&{embedded:d},...u!==void 0&&{retryLimit:u},...m!==void 0&&{documentStoreReferences:m}})},w6=(e)=>Si.gen(function*(){let t=e.edges().filter((r)=>{let n=e.source(r),o=e.target(r);return!bn.isVirtualNode(n)&&!bn.isVirtualNode(o)});return yield*Si.forEach(t,(r)=>b6(e,r),{concurrency:"unbounded"})}),b6=(e,t)=>Si.sync(()=>{let r=e.source(t),n=e.target(t),o=e.getNodeAttributes(r),i=e.getNodeAttributes(n),s=e.getEdgeAttributes(t),a=nr(o.node.path),c=nr(i.node.path),l=s.conditionText?s.conditionText:s.condition?"conditional":void 0,d=s.scheduleText?s.scheduleText:s.schedule?"scheduled":void 0;return{sourceStepPath:a,targetStepPath:c,...l&&{condition:l},...d&&{schedule:d},isElse:s.isElse??!1,isOnError:s.isOnError??!1,taggedErrors:s.taggedErrors??null}}),aD=(e)=>{let t=[];for(let r of e.node.children)if(SO(r))t.push({id:r.node.id,email:r.email.toLowerCase(),rolePaths:r.roles.map((n)=>nr(n.node.path))});return t},FE=(e)=>{let t=[],r=!0,n=!1,o;for(let i of e.node.children)if(eg(i)){r=i.inviteOnly,n=i.delegatedAccess;for(let s of i.identityProviders)t.push({name:s.name,config:s.config});if(i.passkey)o=i.passkey}return o?{inviteOnly:r,delegatedAccess:n,identityProviders:t,passkey:o}:{inviteOnly:r,delegatedAccess:n,identityProviders:t}},UE=(e)=>{let t=[];for(let r of e.node.children)if(eg(r))for(let n of r.secretClients)t.push({clientId:n.clientId,secret:n.secret,audience:n.audience});return t},E6=(e)=>{let t=[],r=new Set,n=(o)=>{let i=o.annotations[xg];if(typeof i==="object"&&i!==null&&"documentStore"in i&&typeof i.documentStore==="string"&&i.documentStore.length>0&&!r.has(i.documentStore))r.add(i.documentStore),t.push(i.documentStore);if(o._tag==="Refinement"||o._tag==="Transformation"){n(o.from);return}if(o._tag==="TypeLiteral")for(let s of o.propertySignatures)n(s.type);if(o._tag==="Union")for(let s of o.types)n(s)};return n(Og(e)),t},T6=(e)=>{if(!dl(e))return;let t=e.output;if(!t)return;let r=[],n=new Set;for(let o of Object.values(t)){let i=E6(o);for(let s of i)if(!n.has(s))n.add(s),r.push(s)}return r.length>0?r:void 0},cD=(e)=>{let t=[],r=(n)=>{let o=nr(n.node.path);for(let i of n.node.children)if(lE(i))t.push({orgUnitPath:o,name:i.node.id,path:nr(i.node.path),...i.acceptedTypes.length>0&&{acceptedTypes:i.acceptedTypes},...i.maxFileSize!==104857600&&{maxFileSize:i.maxFileSize}});else if(Ug(i))r(i)};return r(e),t};var lD=(e)=>{let t=[];for(let r of e.children)t.push(r),t.push(...lD(r));return t},A6=(e)=>[`source:${e.sourceStepPath}`,`target:${e.targetStepPath}`,`else:${e.isElse?1:0}`,`onError:${e.isOnError?1:0}`,`tags:${e.taggedErrors?[...e.taggedErrors].sort().join("\x1F"):""}`].join("\x1E");class dD extends eS.TaggedError("SourceStepNotFound"){}class uD extends eS.TaggedError("TargetStepNotFound"){}class BE extends eS.TaggedError("OrgUnitPkNotFound"){}class pD extends eS.TaggedError("InvitationRoleNotFound"){}var fD=Dt.fn("OrgToDb.upsertOrgUnitsAndRoles")(function*(e,t,r,n,o,i){let s=yield*t.upsertOrgUnit({name:e.name,orgUnitLevel:e.orgUnitLevel,path:e.path,parentOrgUnitPath:e.parentOrgUnitPath,acronym:e.acronym,timezone:e.timezone},r);yield*qe.update(o,(a)=>En.set(a,e.path,s)),yield*qe.update(i.orgUnits,(a)=>[...a,e.path]),yield*Dt.forEach(e.roles,(a)=>Dt.gen(function*(){let c=yield*t.upsertRole(a,s);yield*qe.update(n,(l)=>En.set(l,a.path,c)),yield*qe.update(i.roles,(l)=>[...l,a.path])}),{concurrency:1}),yield*Dt.forEach(e.children,(a)=>fD(a,t,s,n,o,i),{concurrency:1})}),mD=Dt.fn("OrgToDb.upsertProcessesStepsFlowsAndResponsibilities")(function*(e,t,r,n,o,i){let s=yield*qe.get(r),a=En.get(s,e.path);if(ea.isNone(a))return yield*new BE({path:e.path});let c=a.value,l=yield*qe.get(n);yield*Dt.forEach(e.processes,(d)=>Dt.gen(function*(){let u=yield*t.upsertProcess({orgUnitPath:d.orgUnitPath,name:d.name,path:d.path,purpose:d.purpose,...d.sla&&{sla:d.sla}},c);yield*qe.update(o.processes,(x)=>[...x,d.path]);let m=new Map;yield*Dt.forEach(d.phases,(x)=>Dt.gen(function*(){let v=yield*t.upsertPhase(x,u);m.set(x.path,v),yield*qe.update(o.phases,(w)=>[...w,x.path])}),{concurrency:1});let h=yield*qe.make(En.empty());yield*Dt.forEach(d.steps,(x)=>Dt.gen(function*(){let v;if(x.phasePath)v=m.get(x.phasePath);let w=yield*t.upsertStep(x,u,v);yield*qe.update(h,(P)=>En.set(P,x.path,w)),yield*qe.update(i,(P)=>En.set(P,x.path,w)),yield*qe.update(o.steps,(P)=>[...P,x.path])}),{concurrency:1});let S=new Map;yield*Dt.forEach(d.flows,(x)=>Dt.gen(function*(){let v=yield*qe.get(h),w=En.get(v,x.sourceStepPath);if(ea.isNone(w))return yield*new dD({stepPath:x.sourceStepPath});let P=En.get(v,x.targetStepPath);if(ea.isNone(P))return yield*new uD({stepPath:x.targetStepPath});let F=A6({sourceStepPath:x.sourceStepPath,targetStepPath:x.targetStepPath,isElse:x.isElse,isOnError:x.isOnError,taggedErrors:x.taggedErrors}),R=S.get(F)??0;S.set(F,R+1);let b=`${R6("sha256").update(F).digest("hex")}:${R}`;yield*t.upsertFlow(b,x,w.value,P.value),yield*qe.update(o.flows,(A)=>[...A,b])}),{concurrency:1}),yield*Dt.forEach(d.responsibilities,(x)=>Dt.gen(function*(){let v=En.get(l,x.rolePath);if(ea.isNone(v))return;yield*t.upsertRoleResponsibility(x,u,v.value),yield*qe.update(o.responsibilities,(w)=>[...w,{processPath:d.path,rolePath:x.rolePath}])}),{concurrency:1})}),{concurrency:1}),yield*Dt.forEach(e.children,(d)=>mD(d,t,r,n,o,i),{concurrency:1})}),yD=(e)=>Dt.gen(function*(){let t=yield*oD(e),r=yield*ps,n=yield*Ef;yield*Dt.gen(function*(){let i=yield*qe.make(En.empty()),s=yield*qe.make(En.empty()),a=yield*qe.make([]),c=yield*qe.make([]),l=yield*qe.make([]),d=yield*qe.make([]),u=yield*qe.make([]),m=yield*qe.make([]),h=yield*qe.make([]),S=yield*qe.make(En.empty()),x=yield*qe.make(En.empty());yield*r.withTransaction(Dt.gen(function*(){yield*fD(t.rootOrgUnit,n,void 0,i,s,{orgUnits:a,roles:c}),yield*mD(t.rootOrgUnit,n,s,i,{processes:d,phases:l,steps:u,flows:m,responsibilities:h},S);let v=FE(e),w=yield*qe.make([]);if(yield*Dt.forEach(v.identityProviders,(Ve)=>Dt.gen(function*(){yield*n.upsertOAuthProvider(Ve.name,{...Ve.config,inviteOnly:v.inviteOnly,delegatedAccess:v.delegatedAccess}),yield*qe.update(w,(lt)=>[...lt,Ve.name])}),{concurrency:1}),v.passkey){let Ve=v.passkey;Ve={...Ve,...V_(process.env),inviteOnly:v.inviteOnly,delegatedAccess:v.delegatedAccess},yield*n.upsertOAuthProvider("passkey",Ve),yield*qe.update(w,(lt)=>[...lt,"passkey"])}let P=aD(e),F=yield*qe.make([]),R=yield*qe.get(i);yield*Dt.forEach(P,(Ve)=>Dt.gen(function*(){let lt=[];for(let jt of Ve.rolePaths){let ut=En.get(R,jt);if(ea.isNone(ut))return yield*new pD({invitationId:Ve.id,rolePath:jt});lt.push(ut.value)}yield*n.upsertInvitation({id:Ve.id,email:Ve.email},lt),yield*qe.update(F,(jt)=>[...jt,Ve.id])}),{concurrency:1});let b=UE(e).filter((Ve)=>Ve.secret.length>0),A=yield*qe.make([]);yield*Dt.forEach(b,(Ve)=>Dt.gen(function*(){let lt=yield*Q_(Ve.secret);yield*n.upsertOAuthClient(Ve.clientId,lt,Ve.audience),yield*qe.update(A,(jt)=>[...jt,Ve.clientId])}),{concurrency:1});let D=yield*qe.get(s),B=ea.getOrUndefined(En.get(D,t.rootOrgUnit.path)),J=[],G=[];if(B)yield*Dt.forEach(t.weeklySchedule,(Ve)=>Dt.gen(function*(){yield*n.upsertWeeklySchedule(Ve,B),J.push({orgUnitPath:Ve.orgUnitPath,dayOfWeek:Ve.dayOfWeek})}),{concurrency:1}),yield*Dt.forEach(t.holidayRules,(Ve)=>Dt.gen(function*(){yield*n.upsertHolidayRule(Ve,B),G.push({orgUnitPath:Ve.orgUnitPath,holidayTitle:Ve.name})}),{concurrency:1});let ce=cD(e),re=yield*qe.make([]);yield*Dt.forEach(ce,(Ve)=>Dt.gen(function*(){let lt=En.get(D,Ve.orgUnitPath);if(ea.isNone(lt))return yield*new BE({path:Ve.orgUnitPath});let jt=yield*n.upsertDocumentStore(Ve,lt.value);yield*qe.update(re,(ut)=>[...ut,Ve.path]),yield*qe.update(x,(ut)=>En.set(ut,Ve.path,jt))}),{concurrency:1});let Z=yield*qe.make([]),se=yield*qe.get(S),te=yield*qe.get(x);for(let Ve of[t.rootOrgUnit,...lD(t.rootOrgUnit)])for(let lt of Ve.processes)for(let jt of lt.steps)if(jt.documentStoreReferences&&jt.documentStoreReferences.length>0){let ut=En.get(se,jt.path);if(ea.isSome(ut)){let Ht=ut.value;for(let Mn of jt.documentStoreReferences){let Ao=En.get(te,Mn);if(ea.isSome(Ao)){let ls=Ao.value;yield*n.upsertStepDocumentStore(Ht,ls),yield*qe.update(Z,(Vs)=>[...Vs,{stepPath:jt.path,documentStorePath:Mn}])}}}}let Ne=yield*qe.get(m),ze=yield*qe.get(u),et=yield*qe.get(c),xt=yield*qe.get(l),dt=yield*qe.get(d),Le=yield*qe.get(a),fe=yield*qe.get(h),qt=yield*qe.get(Z),on=yield*qe.get(re),Be=yield*qe.get(w),xr=yield*qe.get(A),uo=yield*qe.get(F);yield*n.deleteOrphanedStepDocumentStores([...qt]),yield*n.deleteOrphanedFlows([...Ne]),yield*n.deleteOrphanedRoleResponsibilities([...fe]),yield*n.deleteOrphanedSteps([...ze]),yield*n.deleteOrphanedRoles([...et]),yield*n.deleteOrphanedPhases([...xt]),yield*n.deleteOrphanedProcesses([...dt]),yield*n.deleteOrphanedWeeklySchedules(J),yield*n.deleteOrphanedHolidayRules(G),yield*n.deleteOrphanedDocumentStores([...on]),yield*n.deleteOrphanedOrgUnits([...Le]),yield*n.deleteOrphanedOAuthProviders([...Be]),yield*n.deleteOrphanedOAuthClients([...xr]),yield*n.deleteOrphanedInvitations([...uo])}))}).pipe(Dt.tapError((i)=>tb(i)?Dt.logWarning("Transient Turso HTTP 502 during org import transaction attempt"):Dt.void),G_)});import{Context as P6,Effect as I6,FiberRef as C6}from"effect";class Io extends P6.Tag("processfocus:internal-tag/request-time/RequestTime")(){}var he=()=>I6.flatMap(Io,C6.get);var T=Symbol.for("drizzle:entityKind");function j(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,T))throw Error(`Class "${t.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let r=Object.getPrototypeOf(e)?.constructor;if(r)while(r){if(T in r&&r[T]===t[T])return!0;r=Object.getPrototypeOf(r)}return!1}var cn=class{static[T]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}};var fr=class{static[T]="Subquery";constructor(e,t,r,n=!1,o=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:n,usedTables:o}}},tS=class extends fr{static[T]="WithSubquery"};var zf=Symbol.for("drizzle:OriginalColumn");var ME=(e)=>e;ME.isNoop=!0;var at=class{static[T]="Column";codec;name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;length;isLengthExact;isAlias;config;table;onInit(){}constructor(e,t){this.config=t,this.onInit(),this.table=e,this.name=t.name,this.isAlias=!1,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity,this.length=t.length,this.isLengthExact=t.isLengthExact}mapFromDriverValue=ME;mapToDriverValue=ME;postBuild(){return this}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}[zf](){return this}};var Co=Symbol.for("drizzle:Name");var ta=Symbol.for("drizzle:Schema"),_o=Symbol.for("drizzle:Columns"),hD=Symbol.for("drizzle:ExtraConfigColumns"),yl=Symbol.for("drizzle:OriginalName"),LE=Symbol.for("drizzle:BaseName"),Ya=Symbol.for("drizzle:IsAlias"),gD=Symbol.for("drizzle:ExtraConfigBuilder"),_6=Symbol.for("drizzle:IsDrizzleTable"),de=class{static[T]="Table";static Symbol={Name:Co,Schema:ta,OriginalName:yl,Columns:_o,ExtraConfigColumns:hD,BaseName:LE,IsAlias:Ya,ExtraConfigBuilder:gD};[Co];[yl];[ta];[_o];[hD];[LE];[Ya]=!1;[_6]=!0;[gD]=void 0;constructor(e,t,r){this[Co]=this[yl]=e,this[ta]=t,this[LE]=r}};function ra(e){return e[Co]}function hl(e){return`${e[ta]??"public"}.${e[Co]}`}function SD(e,...t){return e(...t)}var vD={startActiveSpan(e,t){return t()}};var Ot=Symbol.for("drizzle:ViewBaseConfig");function na(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function k6(e){let t={sql:"",params:[]};for(let r of e)t.sql+=r.sql,t.params.push(...r.params);return t}function O6(e){let t={sql:"",params:[]},r=[];for(let n of e)r.push(n.sql),t.params.push(...n.params);return t._sql=Object.assign(r,{raw:r}),t}var ln=class{static[T]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new me([this])}},me=class e{static[T]="SQL";decoder=Xa;shouldInlineParams=!1;usedTables=[];constructor(t){this.queryChunks=t;for(let r of t)if(j(r,de)){let n=r[de.Symbol.Schema];this.usedTables.push(n===void 0?r[de.Symbol.Name]:n+"."+r[de.Symbol.Name])}}append(t){return this.queryChunks.push(...t.queryChunks),this}toQuery(t){return vD.startActiveSpan("drizzle.buildSQL",(r)=>{let n=this.buildQueryFromSourceParams(this.queryChunks,t);return r?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(t,r){let n=Object.assign({},r,{inlineParams:r.inlineParams||this.shouldInlineParams,paramStartIndex:r.paramStartIndex||{value:0}}),{escapeName:o,escapeParam:i,codecs:s,inlineParams:a,paramStartIndex:c,invokeSource:l}=n,d=t.map((u)=>{if(j(u,ln))return{sql:u.value.join(""),params:[]};if(j(u,Gf))return{sql:o(u.value),params:[]};if(u===void 0)return{sql:"",params:[]};if(Array.isArray(u)){let m=[new ln("(")];for(let[h,S]of u.entries())if(m.push(S),h<u.length-1)m.push(new ln(", "));return m.push(new ln(")")),this.buildQueryFromSourceParams(m,n)}if(j(u,e))return this.buildQueryFromSourceParams(u.queryChunks,{...n,inlineParams:a||u.shouldInlineParams});if(j(u,de)){let m=u[de.Symbol.Schema],h=u[de.Symbol.Name];if(l==="mssql-view-with-schemabinding")return{sql:(m===void 0?o("dbo"):o(m))+"."+o(h),params:[]};return{sql:m===void 0||u[Ya]?o(h):o(m)+"."+o(h),params:[]}}if(j(u,at)){let m=u.name;if(r.invokeSource==="indexes")return{sql:o(m),params:[]};let h=l==="mssql-check"?void 0:u.table[de.Symbol.Schema];return{sql:u.isAlias?o(u.name):u.table[Ya]||h===void 0?o(u.table[de.Symbol.Name])+"."+o(m):o(h)+"."+o(u.table[de.Symbol.Name])+"."+o(m),params:[]}}if(j(u,Lr)){let m=u[Ot].schema,h=u[Ot].name;return{sql:m===void 0||u[Ot].isAlias?o(h):o(m)+"."+o(h),params:[]}}if(j(u,jn)){if(j(u.value,e))return this.buildQueryFromSourceParams([u.value],n);let m=s&&j(u.encoder,at);if(j(u.value,Hi)){let x=i(c.value++,u);return u.codec=m?(v)=>s.apply(u.encoder,"normalizeParam",v):void 0,{sql:m?s.apply(u.encoder,"castParam",x):x,params:[u]}}let h;if(u.value===null)h=u.value;else{if(h=u.encoder.mapToDriverValue.isNoop?u.value:u.encoder.mapToDriverValue(u.value),j(h,e))return this.buildQueryFromSourceParams([h],n);if(m)h=s.apply(u.encoder,"normalizeParam",h)}if(a)return{sql:this.mapInlineParam(h,n),params:[]};let S=i(c.value++,h);return{sql:m?s.apply(u.encoder,"castParam",S):S,params:[h]}}if(j(u,Hi))return{sql:i(c.value++,u),params:[u]};if(j(u,e.Aliased)&&u.fieldAlias!==void 0)return{sql:(u.origin!==void 0?o(u.origin)+".":"")+o(u.fieldAlias),params:[]};if(j(u,fr)){if(u._.isWith)return{sql:o(u._.alias),params:[]};return this.buildQueryFromSourceParams([new ln("("),u._.sql,new ln(") "),new Gf(u._.alias)],n)}if(typeof u==="function"&&"enumName"in u){if("schema"in u&&u.schema)return{sql:o(u.schema)+"."+o(u.enumName),params:[]};return{sql:o(u.enumName),params:[]}}if(na(u)){if(u.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([u.getSQL()],n);return this.buildQueryFromSourceParams([new ln("("),u.getSQL(),new ln(")")],n)}if(a)return{sql:this.mapInlineParam(u,n),params:[]};return{sql:i(c.value++,u),params:[u]}});if(r.tagged)return O6(d);return k6(d)}mapInlineParam(t,{escapeString:r}){if(t===null)return"null";if(typeof t==="number"||typeof t==="boolean"||typeof t==="bigint")return t.toString();if(typeof t==="string")return r(t);if(typeof t==="object"){let n=t.toString();if(n==="[object Object]")return r(JSON.stringify(t));return r(n)}throw Error("Unexpected param value: "+t)}getSQL(){return this}as(t){if(t===void 0)return this;return new e.Aliased(this,t)}mapWith(t){return this.decoder=typeof t==="function"?{mapFromDriverValue:t}:t,this}inlineParams(){return this.shouldInlineParams=!0,this}if(t){return t?this:void 0}},Gf=class{static[T]="Name";brand;constructor(e){this.value=e}getSQL(){return new me([this])}};function rS(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}var Xa={mapFromDriverValue:(e)=>e};Xa.mapFromDriverValue.isNoop=!0;var Yf={mapToDriverValue:(e)=>e};Yf.mapToDriverValue.isNoop=!0;var xD={...Xa,...Yf},jn=class{static[T]="Param";brand;constructor(e,t=Yf,r){this.value=e,this.encoder=t,this.codec=r}getSQL(){return new me([this])}};function f(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new ln(e[0]));for(let[n,o]of t.entries())r.push(o,new ln(e[n+1]));return new me(r)}(function(e){function t(){return new me([])}e.empty=t;function r(l){return new me(l)}e.fromList=r;function n(l){return new me([new ln(l)])}e.raw=n;function o(l,d){let u=[];for(let[m,h]of l.entries()){if(m>0&&d!==void 0)u.push(d);u.push(h)}return new me(u)}e.join=o;function i(l){return new Gf(l)}e.identifier=i;function s(l){return new Hi(l)}e.placeholder=s;function a(l,d){return new jn(l,d)}e.param=a;function c(l){let d=mu(l);if(!d.length)return;return f.raw(d)}e.comment=c})(f||(f={}));function mu(e){let t=mu.encodeInput(e);if(!t.length)return"";return`/*${t}*/`}(function(e){function t(i,s){let a;if(typeof i==="object"&&typeof s==="object")a=r({...i,...s});else if(i&&s)a=[r(i),r(s)].filter((c)=>c.length).join(",");else if(s)a=r(s);else if(i)a=r(i);else return"";if(!a.length)return"";return`/*${a}*/`}e.merge=t;function r(i){if(typeof i==="string"){if(!i.length)return i;return o(i)}let s=[];for(let[a,c]of Object.entries(i)){if(c===null||c===void 0||c==="")continue;let l=n(a),d=n(String(c));s.push(`${l}='${d}'`)}if(!s.length)return"";return s.sort().join(",")}e.encodeInput=r;function n(i){return encodeURIComponent(i).replace(/'/g,"\\'")}e.sanitizeObjectElement=n;function o(i){return i.replace(/\/\*/g,"/ *").replace(/\*\//g,"* /")}e.sanitizeStringInput=o})(mu||(mu={}));(function(e){class t{static[T]="SQL.Aliased";isSelectionField=!1;origin;constructor(r,n){this.sql=r,this.fieldAlias=n}getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(me||(me={}));var Hi=class{static[T]="Placeholder";constructor(e){this.name=e}getSQL(){return new me([this])}};function oa(e,t){return e.map((r)=>{if(j(r,Hi)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(j(r,jn)&&j(r.value,Hi)){if(!(r.value.name in t))throw Error(`No value for placeholder "${r.value.name}" was provided`);if(t[r.value.name]===null)return t[r.value.name];let n=r.encoder.mapToDriverValue.isNoop?t[r.value.name]:r.encoder.mapToDriverValue(t[r.value.name]);return r.codec?r.codec(n):n}return r})}var D6=Symbol.for("drizzle:IsDrizzleView"),Lr=class{static[T]="View";[Ot];[D6]=!0;get[Co](){return this[Ot].name}get[ta](){return this[Ot].schema}get[Ya](){return this[Ot].isAlias}get[yl](){return this[Ot].originalName}get[_o](){return this[Ot].selectedFields}constructor({name:e,schema:t,selectedFields:r,query:n}){this[Ot]={name:e,originalName:e,schema:t,selectedFields:r,query:n,isExisting:!n,isAlias:!1}}};at.prototype.getSQL=function(){return new me([this])};fr.prototype.getSQL=function(){return new me([this])};var gl=class{static[T]="ColumnTableAliasProxyHandler";constructor(e,t){this.table=e,this.ignoreColumnAlias=t}get(e,t){if(t==="table")return this.table;if(t==="isAlias"&&this.ignoreColumnAlias)return!1;return e[t]}},$E=class{static[T]="ViewSelectionAliasProxyHandler";constructor(e,t,r){this.view=e,this.selection=t,this.ignoreColumnAlias=r}get(e,t){let r=e[t];if(j(r,at))return new Proxy(r,new gl(this.view,this.ignoreColumnAlias));if(j(r,fr)||j(r,me)||j(r,me.Aliased)||na(r)||typeof r!=="object"||r===null)return r;return new Proxy(r,this)}},Sl=class{static[T]="TableAliasProxyHandler";constructor(e,t,r){this.alias=e,this.replaceOriginalName=t,this.ignoreColumnAlias=r}get(e,t){if(t===de.Symbol.IsAlias)return!0;if(t===de.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===de.Symbol.OriginalName)return this.alias;if(t===Ot)return{...e[Ot],name:this.alias,isAlias:!0,selectedFields:new Proxy(e[Ot].selectedFields,new $E(new Proxy(e,this),e[Ot].selectedFields,this.ignoreColumnAlias))};if(t===de.Symbol.Columns){let n=e[de.Symbol.Columns];if(!n)return n;if(j(e,Lr))return new Proxy(e[de.Symbol.Columns],new $E(new Proxy(e,this),e[de.Symbol.Columns],this.ignoreColumnAlias));let o={};return Object.keys(n).map((i)=>{o[i]=new Proxy(n[i],new gl(new Proxy(e,this),this.ignoreColumnAlias))}),o}let r=e[t];if(j(r,at))return new Proxy(r,new gl(new Proxy(e,this),this.ignoreColumnAlias));return r}},wD=class{static[T]="ColumnAliasProxyHandler";constructor(e){this.alias=e}get(e,t){if(t==="isAlias")return!0;if(t==="name")return this.alias;if(t==="keyAsName")return!1;if(t===zf)return()=>e;return e[t]}};function Hn(e,t){return new Proxy(e,new Sl(t,!1,!1))}function bD(e,t){return new Proxy(e,new wD(t))}function Wi(e,t){return new Proxy(e,new gl(new Proxy(e.table,new Sl(t,!1,!1)),!1))}function nS(e,t){return new me.Aliased(yu(e.sql,t),e.fieldAlias)}function yu(e,t){return f.join(e.queryChunks.map((r)=>{if(j(r,at))return Wi(r,t);if(j(r,me))return yu(r,t);if(j(r,me.Aliased))return nS(r,t);return r}))}at.prototype.as=function(e){return bD(this,e)};function hu(e){return e[zf]()}function fs(e,t){return new Proxy(e,new Sl(t,!1))}var ED=class{static[T]="ColumnBuilder";config;constructor(e,t,r){this.config={name:e,keyAsName:e==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:r,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e,t){if(this.config.name!=="")return;this.config.name=t(e)}};var TD=class{static[T]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:n,foreignColumns:o}=e();return{name:r,columns:n,foreignTable:o[0].table,foreignColumns:o}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e,this}onDelete(e){return this._onDelete=e,this}build(e){return new N6(e,this)}},N6=class{static[T]="SQLiteForeignKey";reference;onUpdate;onDelete;constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),n=t.map((s)=>s.name),o=r.map((s)=>s.name),i=[this.table[Co],...n,r[0].table[Co],...o];return e??`${i.join("_")}_fk`}isNameExplicit(){return!!this.reference().name}};var Cn=class extends ED{static[T]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e){return this.config.isUnique=!0,this.config.uniqueName=e,this}generatedAlwaysAs(e,t){return this.config.generated={as:e,type:"always",mode:t?.mode??"virtual"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:n})=>((o,i)=>{let s=new TD(()=>{let a=o();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)})(r,n))}},$r=class extends at{static[T]="SQLiteColumn";table;constructor(e,t){super(e,t);this.table=e}};function qE(e,t,r){let n={},o=e.reduce((i,{path:s,field:a,codec:c,arrayDimensions:l},d)=>{let u;if(j(a,at))u=a;else if(j(a,me))u=a.decoder;else if(j(a,fr))u=a._.sql.decoder;else u=a.sql.decoder;let m=i;for(let[h,S]of s.entries())if(h<s.length-1){if(!(S in m))m[S]={};m=m[S]}else{let x=t[d],v=m[S]=x===null?null:u.mapFromDriverValue(c?c(x,l):x);if(r&&j(a,at)&&s.length===2){let w=s[0];if(!(w in n))n[w]=v===null?ra(a.table):!1;else if(typeof n[w]==="string"&&n[w]!==ra(a.table))n[w]=!1}}return i},{});if(r&&Object.keys(n).length>0){for(let[i,s]of Object.entries(n))if(typeof s==="string"&&!r[s])o[i]=null}return o}var iS=Object.getPrototypeOf(()=>null).constructor;function F6(e,t={}){let r=[],n=[];n.push(`const [ ${e.map((c,l)=>`c${l}`).join(", ")} ] = rows[i];`);let o={},i={},s=Array.from({length:e.length});for(let c=0;c<e.length;++c){let{field:l,path:d,codec:u,arrayDimensions:m}=e[c],h,S,x,v=!1;if(j(l,at))v=!0,h=l,x=`field: decoder${c}`;else if(j(l,me))h=l.decoder,x=`field: { decoder: decoder${c} }`;else if(j(l,fr))h=l._.sql.decoder,x=`field: { _: { sql: { decoder: decoder${c} } } }`;else h=l.sql.decoder,x=`field: { sql: { decoder: decoder${c} } }`;if(S=`decoder${c}.mapFromDriverValue`,h.mapFromDriverValue.isNoop)S="";if(S)r.push(`const { ${x}${u?`, codec: codec${c}`:""} } = columns[${c}];`);else if(u)r.push(`const { codec: codec${c} } = columns[${c}];`);let w=`c${c}`,P=w;if(u)P=`codec${c}(${P}, ${m})`;if(S)P=`${S}(${P})`;if(s[c]=w===P?`${w}`:`${w} === null ? ${w} : ${P}`,d.length!==2||!v)continue;if(i[d[0]]===void 0)i[d[0]]=[`c${c}`];else i[d[0]]?.push(`c${c}`);let[F]=d,R=ra(l.table);o[F]=t[R]?!1:typeof o[F]==="string"?o[F]===R?R:!1:R}n.push("mapped[i] = {");let a=[];for(let c=0;c<e.length;++c){let{path:l}=e[c],d=l.map((S)=>JSON.stringify(S)),u=s[c],m=l.slice(0,-1),h=0;while(h<a.length&&h<m.length&&a[h]===m[h])h++;for(let S=a.length-1;S>=h;--S)n.push(`${"\t".repeat(S+1)}},`);for(let S=h;S<m.length;++S)n.push(`${"\t".repeat(S+1)}${d[S]}: ${S===0&&m.length===1&&typeof o[l[0]]==="string"?`${i[l[0]]?.map((x)=>`${x} === null`).join(" && ")} ? null : {`:"{"}`);a=m,n.push(`${"\t".repeat(l.length)}${d[l.length-1]}: ${u},`)}for(let c=a.length-1;c>=0;--c)n.push(`${"\t".repeat(c+1)}},`);return n.push("};"),`${r.length?`${r.join(`
|
|
32
|
+
`)}
|
|
33
|
+
`:""}for (let i = 0; i < length; ++i) {
|
|
34
|
+
${n.join(`
|
|
35
|
+
`)}
|
|
36
|
+
}`}function jE(e,t){let r=` "use strict";
|
|
37
|
+
const { columns } = this;
|
|
38
|
+
const { length } = rows;
|
|
39
|
+
const mapped = Array.from({ length });
|
|
40
|
+
${F6(e,t)}
|
|
41
|
+
return mapped;
|
|
42
|
+
//# sourceURL=drizzle:jit-query-mapper`;return Object.assign(new iS("rows",r).bind({columns:e}),{body:`function jitQueryMapper (rows) {
|
|
43
|
+
${r}
|
|
44
|
+
}`})}function RD(e){if(!e)return!1;try{let t=new iS("input",'"use strict"; return input;')(!0);if(t!==!0)console.warn(`Unable to use jit mappers due to incompatibility: corrupted jit function output.
|
|
45
|
+
Falling back to premade mappers.
|
|
46
|
+
Error details:`),console.error(`Expected to receive \`true\`, got: ${t}`);return!0}catch(t){return console.warn(`Unable to use jit mappers due to incompatibility.
|
|
47
|
+
Falling back to premade mappers.
|
|
48
|
+
Error details:`),console.error(t),!1}}function vi(e,t,r){return Object.entries(e).reduce((n,[o,i])=>{if(typeof o!=="string")return n;let s=t?[...t,o]:[o];if(j(i,at))n.push({path:s,field:i,codec:r?.get(i,"normalize"),arrayDimensions:i.dimensions});else if(j(i,me)||j(i,me.Aliased)){let a=oS(i);n.push(a?{path:s,field:i,codec:r?.get(a,"normalize"),arrayDimensions:a.dimensions}:{path:s,field:i})}else if(j(i,fr)){let a=oS(i._.sql);n.push(a?{path:s,field:i,codec:r?.get(a,"normalize"),arrayDimensions:a.dimensions}:{path:s,field:i})}else if(j(i,de))n.push(...vi(i[de.Symbol.Columns],s,r));else n.push(...vi(i,s,r));return n},[])}function oS(e){let t=e.getSQL();if(j(t.decoder,at))return t.decoder}function Xf(e,t){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let[o,i]of r.entries())if(i!==n[o])return!1;return!0}function sS(e,t){let r=Object.entries(t).filter(([,n])=>n!==void 0).map(([n,o])=>{if(j(o,me)||j(o,at))return[n,o];else return[n,new jn(o,e[de.Symbol.Columns][n])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function aS(e,t){for(let r of t)for(let n of Object.getOwnPropertyNames(r.prototype)){if(n==="constructor")continue;Object.defineProperty(e.prototype,n,Object.getOwnPropertyDescriptor(r.prototype,n)||Object.create(null))}}function cS(e){return e[de.Symbol.Columns]}function Zf(e){return j(e,fr)?e._.alias:j(e,Lr)?e[Ot].name:j(e,me)?void 0:e[de.Symbol.IsAlias]?e[de.Symbol.Name]:e[de.Symbol.BaseName]}function ot(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}var HE=typeof TextDecoder>"u"?null:new TextDecoder;var Cye={INT8_MIN:-128,INT8_MAX:127,INT8_UNSIGNED_MAX:255,INT16_MIN:-32768,INT16_MAX:32767,INT16_UNSIGNED_MAX:65535,INT24_MIN:-8388608,INT24_MAX:8388607,INT24_UNSIGNED_MAX:16777215,INT32_MIN:-2147483648,INT32_MAX:2147483647,INT32_UNSIGNED_MAX:4294967295,INT48_MIN:-140737488355328,INT48_MAX:140737488355327,INT48_UNSIGNED_MAX:281474976710655,INT64_MIN:-9223372036854775808n,INT64_MAX:9223372036854775807n,INT64_UNSIGNED_MAX:18446744073709551615n};var AD=class extends Cn{static[T]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new PD(e,this.config)}},PD=class extends $r{static[T]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;mapJson;forJsonSelect;constructor(e,t){super(e,t);this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver,this.mapJson=t.customTypeParams.fromJson,this.forJsonSelect=t.customTypeParams.forJsonSelect}getSQLType(){return this.sqlName}mapFromDriverValue=(e)=>typeof this.mapFrom==="function"?this.mapFrom(e):e;mapFromJsonValue(e){return typeof this.mapJson==="function"?this.mapJson(e):this.mapFromDriverValue(e)}jsonSelectIdentifier(e,t){if(typeof this.forJsonSelect==="function")return this.forJsonSelect(e,t);let r=this.getSQLType().toLowerCase(),n=r.indexOf("(");switch(n+1?r.slice(0,n):r){case"numeric":case"decimal":case"bigint":return t`cast(${e} as text)`;case"blob":return t`hex(${e})`;default:return e}}mapToDriverValue=(e)=>typeof this.mapTo==="function"?this.mapTo(e):e};function vl(e){return(t,r)=>{let{name:n,config:o}=ot(t,r);return new AD(n,o,e)}}var lS=class extends Cn{static[T]="SQLiteBaseIntegerBuilder";constructor(e,t,r){super(e,t,r);this.config.autoIncrement=!1}primaryKey(e){if(e?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}},dS=class extends $r{static[T]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}},ID=class extends lS{static[T]="SQLiteIntegerBuilder";constructor(e){super(e,"number int53","SQLiteInteger")}build(e){return new CD(e,this.config)}},CD=class extends dS{static[T]="SQLiteInteger"},_D=class extends lS{static[T]="SQLiteTimestampBuilder";constructor(e,t){super(e,"object date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(f`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new kD(e,this.config)}},kD=class extends dS{static[T]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue=(e)=>{if(typeof e==="string")return new Date(e.replaceAll('"',""));if(this.config.mode==="timestamp")return new Date(e*1000);return new Date(e)};mapToDriverValue=(e)=>{if(typeof e==="number")return e;let t=e.getTime();if(this.config.mode==="timestamp")return Math.floor(t/1000);return t}},OD=class extends lS{static[T]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new DD(e,this.config)}},DD=class extends dS{static[T]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue=(e)=>Number(e)===1;mapToDriverValue=(e)=>e?1:0};function ge(e,t){let{name:r,config:n}=ot(e,t);if(n?.mode==="timestamp"||n?.mode==="timestamp_ms")return new _D(r,n.mode);if(n?.mode==="boolean")return new OD(r,n.mode);return new ID(r)}var ND=class extends Cn{static[T]="SQLiteTextBuilder";constructor(e,t){super(e,t.enum?.length?"string enum":"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new FD(e,this.config)}},FD=class extends $r{static[T]="SQLiteText";enumValues=this.config.enumValues;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}},UD=class extends Cn{static[T]="SQLiteTextJsonBuilder";constructor(e){super(e,"object json","SQLiteTextJson")}build(e){return new BD(e,this.config)}},BD=class extends $r{static[T]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue=(e)=>JSON.parse(e);mapToDriverValue=(e)=>JSON.stringify(e)};function I(e,t={}){let{name:r,config:n}=ot(e,t);if(n.mode==="json")return new UD(r);return new ND(r,n)}function MD(e){let t="";for(let r=0;r<e.length;r+=2){let n=e.slice(r,r+2),o=Number.parseInt(n,16);t+=String.fromCodePoint(o)}return t}var U6=class extends Cn{static[T]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint int64","SQLiteBigInt")}build(e){return new B6(e,this.config)}},B6=class extends $r{static[T]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue=(e)=>{if(typeof e==="string")return BigInt(MD(e));if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return BigInt(t.toString("utf8"))}return BigInt(HE.decode(e))};mapToDriverValue=(e)=>Buffer.from(e.toString())},M6=class extends Cn{static[T]="SQLiteBlobJsonBuilder";constructor(e){super(e,"object json","SQLiteBlobJson")}build(e){return new L6(e,this.config)}},L6=class extends $r{static[T]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue=(e)=>{if(typeof e==="string")return JSON.parse(MD(e));if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return JSON.parse(t.toString("utf8"))}return JSON.parse(HE.decode(e))};mapToDriverValue=(e)=>Buffer.from(JSON.stringify(e))},$6=class extends Cn{static[T]="SQLiteBlobBufferBuilder";constructor(e){super(e,"object buffer","SQLiteBlobBuffer")}build(e){return new q6(e,this.config)}},q6=class extends $r{static[T]="SQLiteBlobBuffer";mapFromDriverValue=(e)=>{if(Buffer.isBuffer(e))return e;if(typeof e==="string")return Buffer.from(e,"hex");return Buffer.from(e)};getSQLType(){return"blob"}};function LD(e,t){let{name:r,config:n}=ot(e,t);if(n?.mode==="json")return new M6(r);if(n?.mode==="bigint")return new U6(r);return new $6(r)}var j6=class extends Cn{static[T]="SQLiteNumericBuilder";constructor(e){super(e,"string numeric","SQLiteNumeric")}build(e){return new H6(e,this.config)}},H6=class extends $r{static[T]="SQLiteNumeric";mapFromDriverValue=(e)=>{if(typeof e==="string")return e;return String(e)};getSQLType(){return"numeric"}},W6=class extends Cn{static[T]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new K6(e,this.config)}},K6=class extends $r{static[T]="SQLiteNumericNumber";mapFromDriverValue=(e)=>{if(typeof e==="number")return e;return Number(e)};mapToDriverValue=String;getSQLType(){return"numeric"}},V6=class extends Cn{static[T]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint int64","SQLiteNumericBigInt")}build(e){return new Q6(e,this.config)}},Q6=class extends $r{static[T]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}};function $D(e,t){let{name:r,config:n}=ot(e,t),o=n?.mode;return o==="number"?new W6(r):o==="bigint"?new V6(r):new j6(r)}var J6=class extends Cn{static[T]="SQLiteRealBuilder";constructor(e){super(e,"number double","SQLiteReal")}build(e){return new z6(e,this.config)}},z6=class extends $r{static[T]="SQLiteReal";getSQLType(){return"real"}};function qD(e){return new J6(e??"")}function jD(){return{blob:LD,customType:vl,integer:ge,numeric:$D,real:qD,text:I}}function G6(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((t)=>t.toLowerCase()).join("_")}function Y6(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((t,r,n)=>t+(n===0?r.toLowerCase():`${r[0].toUpperCase()}${r.slice(1)}`),"")}function uS(e){if(e==="snake_case")return G6;if(e==="camelCase")return Y6;return(t)=>t}var pS=Symbol.for("drizzle:SQLiteInlineForeignKeys"),_n=class extends de{static[T]="SQLiteTable";static Symbol=Object.assign({},de.Symbol,{InlineForeignKeys:pS});[de.Symbol.Columns];[pS]=[];[de.Symbol.ExtraConfigBuilder]=void 0};function fS(e,t,r,n,o,i=e){let s=uS(o),a=new _n(e,n,i),c=typeof t==="function"?t(jD()):t,l=Object.fromEntries(Object.entries(c).map(([u,m])=>{let h=m;h.setName(u,s);let S=h.build(a).postBuild();return a[pS].push(...h.buildForeignKeys(S,a)),[u,S]})),d=Object.assign(a,l);if(d[de.Symbol.Columns]=l,d[de.Symbol.ExtraConfigColumns]=l,r)d[_n.Symbol.ExtraConfigBuilder]=r;return d}function HD(e){return(t,r,n)=>fS(t,r,n,void 0,e)}var pt=HD(void 0);var WD=class{static[T]="SQLiteCheckBuilder";brand;constructor(e,t){this.name=e,this.value=t}build(e){return new KD(e,this)}},KD=class{static[T]="SQLiteCheck";name;value;constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}};function Yn(e,t){return new WD(e,t)}var WE=class{static[T]="SQLiteIndexBuilderOn";constructor(e,t){this.name=e,this.unique=t}on(...e){return new VD(this.name,e,this.unique)}},VD=class{static[T]="SQLiteIndexBuilder";config;constructor(e,t,r){this.config={name:e,columns:t,unique:r,where:void 0}}where(e){return this.config.where=e,this}build(e){return new QD(this.config,e)}},QD=class{static[T]="SQLiteIndex";config;isNameExplicit;constructor(e,t){this.config={...e,table:t},this.isNameExplicit=!!e.name}};function Ye(e){return new WE(e,!1)}function Tt(e){return new WE(e,!0)}function Ki(e){if(j(e,_n))return[`${e[de.Symbol.BaseName]}`];if(j(e,fr))return e._.usedTables??[];if(j(e,me))return e.usedTables??[];return[]}var Za=class extends Lr{static[T]="SQLiteViewBase"};var qr=class e{static[T]="SelectionProxyHandler";config;constructor(t){this.config={...t}}get(t,r){if(r==="_")return{...t._,selectedFields:new Proxy(t._.selectedFields,this)};if(r===Ot)return{...t[Ot],selectedFields:new Proxy(t[Ot].selectedFields,this)};if(typeof r==="symbol")return t[r];let n=(j(t,fr)?t._.selectedFields:j(t,Lr)?t[Ot].selectedFields:t)[r];if(j(n,me.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!n.isSelectionField)return n.sql;let o=n.clone();return o.isSelectionField=!0,o.origin=this.config.alias,o}if(j(n,me)){if(this.config.sqlBehavior==="sql")return n;throw Error(`You tried to reference "${r}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(j(n,at)){if(this.config.alias)return new Proxy(n,new gl(new Proxy(n.table,new Sl(this.config.alias,this.config.replaceOriginalName??!1,!0)),!0));return n}if(typeof n!=="object"||n===null)return n;return new Proxy(n,new e(this.config))}};var JD=class{static[T]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}withoutSelectionCastCodecs(){return this}};var xi=class{static[T]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,r;if(this.fields)r=this.fields;else if(j(e,fr))r=Object.fromEntries(Object.keys(e._.selectedFields).map((n)=>[n,e[n]]));else if(j(e,Za))r=e[Ot].selectedFields;else if(j(e,me))r={};else r=cS(e);return new gu({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}},KE=class extends JD{static[T]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:r,session:n,dialect:o,withList:i,distinct:s}){super();this.config={withList:i,table:e,fields:{...t},distinct:s,setOperators:[]},this.isPartialSelect=r,this.session=n,this.dialect=o,this._={selectedFields:t,config:this.config},this.tableName=Zf(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of Ki(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let n=this.tableName,o=Zf(t);for(let i of Ki(t))this.usedTables.add(i);if(typeof o==="string"&&this.config.joins?.some((i)=>i.alias===o))throw Error(`Alias "${o}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof n==="string")this.config.fields={[n]:this.config.fields};if(typeof o==="string"&&!j(t,me)){let i=j(t,fr)?t._.selectedFields:j(t,Lr)?t[Ot].selectedFields:t[de.Symbol.Columns];this.config.fields[o]=i}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new qr({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:r,table:t,joinType:e,alias:o}),typeof o==="string")switch(e){case"left":this.joinsNotNullableMap[o]=!1;break;case"right":this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([i])=>[i,!1])),this.joinsNotNullableMap[o]=!0;break;case"cross":case"inner":this.joinsNotNullableMap[o]=!0;break;case"full":this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([i])=>[i,!1])),this.joinsNotNullableMap[o]=!1;break}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(e,t){return(r)=>{let n=typeof r==="function"?r(X6()):r;if(!Xf(this.getSelectedFields(),n.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:t,rightSelect:n}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new qr({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new qr({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=e,this}groupBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new qr({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new qr({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=r;else this.config.orderBy=r}else{let t=e;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=t;else this.config.orderBy=t}return this}limit(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=e;else this.config.limit=e;return this}offset(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=e;else this.config.offset=e;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){return this.dialect.sqlToQuery(this.getSQL())}as(e){let t=[];if(t.push(...Ki(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...Ki(r.table));return new Proxy(new fr(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new qr({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new qr({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}withoutSelectionCastCodecs(){return this}$dynamic(){return this}},gu=class extends KE{static[T]="SQLiteSelect";_prepare(e=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let t=vi(this.config.fields),r=this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),t,"all",void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return r.joinsNotNullableMap=this.joinsNotNullableMap,r}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enabled:!0,autoInvalidate:!0}:e===!1?{enabled:!1}:{enabled:!0,autoInvalidate:!0,...e},this}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.all()}};aS(gu,[cn]);function mS(e,t){return(r,n,...o)=>{let i=[n,...o].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of i)if(!Xf(r.getSelectedFields(),s.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return r.addSetOperators(i)}}var X6=()=>({union:VE,unionAll:QE,intersect:JE,except:zE}),VE=mS("union",!1),QE=mS("union",!0),JE=mS("intersect",!1),zE=mS("except",!1);function jr(e,t){if(rS(t)&&!na(e)&&!j(e,jn)&&!j(e,Hi)&&!j(e,at)&&!j(e,de)&&!j(e,Lr))return new jn(e,t);return e}var p=(e,t)=>f`${e} = ${jr(t,e)}`,ec=(e,t)=>f`${e} <> ${jr(t,e)}`;function _(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new me(t);return new me([new ln("("),f.join(t.map((r)=>f`(${r})`),new ln(" and ")),new ln(")")])}function Rt(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new me(t);return new me([new ln("("),f.join(t.map((r)=>f`(${r})`),new ln(" or ")),new ln(")")])}function ko(e){return j(e,me)?f`not (${e})`:f`not ${e}`}var Xt=(e,t)=>f`${e} > ${jr(t,e)}`,tc=(e,t)=>f`${e} >= ${jr(t,e)}`,ms=(e,t)=>f`${e} < ${jr(t,e)}`,dn=(e,t)=>f`${e} <= ${jr(t,e)}`;function Fe(e,t){if(Array.isArray(t)){if(t.length===0)return f`false`;return f`${e} in ${t.map((r)=>jr(r,e))}`}return f`${e} in ${jr(t,e)}`}function un(e,t){if(Array.isArray(t)){if(t.length===0)return f`true`;return f`${e} not in ${t.map((r)=>jr(r,e))}`}return f`${e} not in ${jr(t,e)}`}function Se(e){return f`(${e} is null)`}function Nt(e){return f`(${e} is not null)`}function xl(e){return f`exists ${e}`}function wl(e){return f`not exists ${e}`}function Su(e,t,r){return f`${e} between ${jr(t,e)} and ${jr(r,e)}`}function vu(e,t,r){return f`${e} not between ${jr(t,e)} and ${jr(r,e)}`}function rc(e,t){return f`${e} like ${t}`}function xu(e,t){return f`${e} not like ${t}`}function wu(e,t){return f`${e} ilike ${t}`}function bu(e,t){return f`${e} not ilike ${t}`}function yS(e,t){if(Array.isArray(t)){if(t.length===0)throw Error("arrayContains requires at least one value");let r=jr(t,e);return f`${e} @> ${f`${Array.isArray(r)?new jn(r):r}`}`}return f`${e} @> ${jr(t,e)}`}function hS(e,t){if(Array.isArray(t)){if(t.length===0)throw Error("arrayContained requires at least one value");let r=jr(t,e);return f`${e} <@ ${f`${Array.isArray(r)?new jn(r):r}`}`}return f`${e} <@ ${jr(t,e)}`}function gS(e,t){if(Array.isArray(t)){if(t.length===0)throw Error("arrayOverlaps requires at least one value");let r=jr(t,e);return f`${e} && ${f`${Array.isArray(r)?new jn(r):r}`}`}return f`${e} && ${jr(t,e)}`}function Oo(e){return f`${e} asc`}function Hr(e){return f`${e} desc`}var zD=class{static[T]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:n,foreignColumns:o}=e();return{name:r,columns:n,foreignTable:o[0].table,foreignColumns:o}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e===void 0?"no action":e,this}onDelete(e){return this._onDelete=e===void 0?"no action":e,this}build(e){return new Z6(e,this)}},Z6=class{static[T]="PgForeignKey";reference;onUpdate;onDelete;name;constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),n=t.map((s)=>s.name),o=r.map((s)=>s.name),i=[this.table[Co],...n,r[0].table[Co],...o];return e??`${i.join("_")}_fk`}isNameExplicit(){return!!this.reference().name}};var Ce=class{static[T]="PgColumnBuilder";foreignKeyConfigs=[];config;constructor(e,t,r){this.config={name:e,keyAsName:e==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:r,generated:void 0,defaultFn:void 0,onUpdateFn:void 0,generatedIdentity:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e,t){if(this.config.name!=="")return;this.config.name=t(e)}array(e){let t=e??"[]";return this.config.dimensions=t.length/2,this}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,config:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,config:n})=>SD((o,i)=>{let s=new zD(()=>{let a=o();return{name:i.name,columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)},r,n))}buildExtraConfigColumn(e){return new eJ(e,{...this.config,dimensions:this.config.dimensions??0})}},ve=class extends at{static[T]="PgColumn";table;dimensions;constructor(e,t){super(e,t);this.table=e,this.dimensions=t.dimensions??0}postBuild(){if(this.dimensions){let e=this.mapFromDriverValue.bind(this),t=this.mapToDriverValue.bind(this);this.mapFromDriverValue=this.mapFromDriverValue.isNoop?this.mapFromDriverValue:(r)=>this.mapArrayElements(r,e,this.dimensions),this.mapToDriverValue=this.mapToDriverValue.isNoop?this.mapToDriverValue:(r)=>this.mapArrayElements(r,t,this.dimensions)}return this}mapArrayElements(e,t,r){if(r>0&&Array.isArray(e))return e.map((n)=>n===null?null:this.mapArrayElements(n,t,r-1));return t(e)}},eJ=class extends ve{static[T]="ExtraConfigColumn";codec=void 0;getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}};var nc=class extends Ce{static[T]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(e){if(e){let{name:t,...r}=e;this.config.generatedIdentity={type:"always",sequenceName:t,sequenceOptions:r}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(e){if(e){let{name:t,...r}=e;this.config.generatedIdentity={type:"byDefault",sequenceName:t,sequenceOptions:r}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}};var tJ=class extends nc{static[T]="PgBigInt53Builder";constructor(e){super(e,"number int53","PgBigInt53")}build(e){return new rJ(e,this.config)}},rJ=class extends ve{static[T]="PgBigInt53";codec="bigint:number";getSQLType(){return"bigint"}},nJ=class extends nc{static[T]="PgBigInt64Builder";constructor(e){super(e,"bigint int64","PgBigInt64")}build(e){return new oJ(e,this.config)}},oJ=class extends ve{static[T]="PgBigInt64";codec="bigint";getSQLType(){return"bigint"}},iJ=class extends nc{static[T]="PgBigIntStringBuilder";constructor(e){super(e,"string int64","PgBigIntString")}build(e){return new sJ(e,this.config)}},sJ=class extends ve{static[T]="PgBigIntString";codec="bigint:string";getSQLType(){return"bigint"}};function GD(e,t){let{name:r,config:n}=ot(e,t);if(n.mode==="number")return new tJ(r);if(n.mode==="string")return new iJ(r);return new nJ(r)}var aJ=class extends Ce{static[T]="PgBigSerial53Builder";constructor(e){super(e,"number int53","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new cJ(e,this.config)}},cJ=class extends ve{static[T]="PgBigSerial53";codec="bigserial:number";getSQLType(){return"bigserial"}},lJ=class extends Ce{static[T]="PgBigSerial64Builder";constructor(e){super(e,"bigint int64","PgBigSerial64");this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new dJ(e,this.config)}},dJ=class extends ve{static[T]="PgBigSerial64";codec="bigserial";getSQLType(){return"bigserial"}};function YD(e,t){let{name:r,config:n}=ot(e,t);if(n.mode==="number")return new aJ(r);return new lJ(r)}var uJ=class extends Ce{static[T]="PgBooleanBuilder";constructor(e){super(e,"boolean","PgBoolean")}build(e){return new pJ(e,this.config)}},pJ=class extends ve{static[T]="PgBoolean";codec="bool";getSQLType(){return"boolean"}};function XD(e){return new uJ(e??"")}var fJ=class extends Ce{static[T]="PgCharBuilder";constructor(e,t){super(e,t.enum?.length?"string enum":"string","PgChar");this.config.length=t.length??1,this.config.setLength=t.length!==void 0,this.config.enumValues=t.enum}build(e){return new mJ(e,this.config)}},mJ=class extends ve{static[T]="PgChar";codec="char";enumValues;setLength;constructor(e,t){super(e,t);this.enumValues=t.enumValues,this.setLength=t.setLength}getSQLType(){return this.setLength?`char(${this.length})`:"char"}};function ZD(e,t={}){let{name:r,config:n}=ot(e,t);return new fJ(r,n)}var yJ=class extends Ce{static[T]="PgCidrBuilder";constructor(e){super(e,"string cidr","PgCidr")}build(e){return new hJ(e,this.config)}},hJ=class extends ve{static[T]="PgCidr";codec="cidr";getSQLType(){return"cidr"}};function eN(e){return new yJ(e??"")}function tN(e,t,r){for(let n=t;n<e.length;n++){let o=e[n];if(o==="\\"){n++;continue}if(o==='"')return[e.slice(t,n).replace(/\\/g,""),n+1];if(r)continue;if(o===","||o==="}")return[e.slice(t,n).replace(/\\/g,""),n]}return[e.slice(t).replace(/\\/g,""),e.length]}function rN(e,t=0){let r=[],n=t,o=!1;while(n<e.length){let i=e[n];if(i===","){if(o||n===t)r.push("");o=!0,n++;continue}if(o=!1,i==="\\"){n+=2;continue}if(i==='"'){let[c,l]=tN(e,n+1,!0);r.push(c),n=l;continue}if(i==="}")return[r,n+1];if(i==="{"){let[c,l]=rN(e,n+1);r.push(c),n=l;continue}let[s,a]=tN(e,n,!1);r.push(s),n=a}return[r,n]}function SS(e){let[t]=rN(e,1);return t}function vS(e){return`{${e.map((t)=>{if(Array.isArray(t))return vS(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}function gJ(e){let t=[];for(let r=0;r<e.length;r+=2)t.push(Number.parseInt(e.slice(r,r+2),16));return new Uint8Array(t)}function nN(e,t){let n=new DataView(new ArrayBuffer(8));for(let o=0;o<8;o++)n.setUint8(o,e[t+o]);return n.getFloat64(0,!0)}function GE(e){let t=gJ(e),r=0,n=t[r];r+=1;let o=new DataView(t.buffer),i=o.getUint32(r,n===1);r+=4;let s;if(i&536870912)s=o.getUint32(r,n===1),r+=4;if((i&65535)===1){let a=nN(t,r);r+=8;let c=nN(t,r);return r+=8,{srid:s,point:[a,c]}}throw Error("Unsupported geometry type")}var SJ={int2:"smallint",integer:"int",int4:"int",int8:"bigint",decimal:"numeric",real:"float4",double:"float8","double precision":"float8",serial2:"smallserial",serial4:"serial",serial8:"bigserial",character:"char","character varying":"varchar","time with time zone":"timetz","time without time zone":"time","timestamp with time zone":"timestamptz","timestamp without time zone":"timestamp",boolean:"bool","bit varying":"varbit"};function aN(e){return SJ[e]??e}var kn=(e)=>f`${e}::text`,kr=(e,t)=>f`${e}::text${f.raw("[]".repeat(t))}`,vJ=(e)=>(t,r)=>{if(!r)return e(t);let n=[];for(let s=0;s<r;s++)n.push(f.identifier(`s${s}`));let o=t;for(let s of n)o=f`${o}[${s}]`;let i=f`array(\
|
|
49
|
+
select ${e(o)} \
|
|
50
|
+
from generate_subscripts(${t}, ${f.raw(r.toString())}) ${n[r-1]} \
|
|
51
|
+
order by ${n[r-1]})`;for(let s=r-1;s>0;s--)i=f`array(\
|
|
52
|
+
select ${i} \
|
|
53
|
+
from generate_subscripts(${t}, ${f.raw(s.toString())}) ${n[s-1]} \
|
|
54
|
+
order by ${n[s-1]})`;return f`case when ${t} is null then null else ${i} end`},Wt=(e)=>{let t=(r,n)=>{let o=n-1;if(n>1)for(let i=0;i<r.length;++i)t(r[i],o);else for(let i=0;i<r.length;++i)r[i]=e(r[i]);return r};return t},oN=(e,t=!1)=>{let r=(n,o)=>{let i=o-1,s=Array.from({length:n.length});if(o>1)for(let a=0;a<n.length;++a)s[a]=r(n[a],i);else for(let a=0;a<n.length;++a)s[a]=e(n[a]);return s};return t?(n,o)=>vS(r(n,o)):r},iN=(e)=>{let t=Wt(e);return(r,n)=>t(SS(r),n)},xS=(e)=>{let[t,r,n]=e.slice(1,-1).split(",");return[Number.parseFloat(t),Number.parseFloat(r),Number.parseFloat(n)]},wS=(e)=>{let[t,r,n]=e.slice(1,-1).split(",");return{a:Number.parseFloat(t),b:Number.parseFloat(r),c:Number.parseFloat(n)}},bS=(e)=>{let[t,r]=e.slice(1,-1).split(",");return[Number.parseFloat(t),Number.parseFloat(r)]},ES=(e)=>{let[t,r]=e.slice(1,-1).split(",");return{x:Number.parseFloat(t),y:Number.parseFloat(r)}},TS=(e)=>GE(e).point,RS=(e)=>{let t=GE(e);return{x:t.point[0],y:t.point[1]}},AS=(e)=>new Date(e),sN=(e)=>new Date(e+"+0000"),oc=(e)=>{let t=e.slice(1,-1);if(t.length===0)return[];return t.split(",").map(Number.parseFloat)},HSe={bytea:{castInJson:(e)=>f`encode(${e}, 'base64')`,castArrayInJson:vJ((e)=>f`encode(${e}, 'base64')`),normalizeInJson:(e)=>Buffer.from(e,"base64"),normalizeArrayInJson:Wt((e)=>Buffer.from(e,"base64"))},bigint:{castInJson:kn,castArrayInJson:kr,normalizeInJson:BigInt,normalizeArrayInJson:Wt(BigInt)},"bigint:number":{castInJson:kn,castArrayInJson:kr,normalize:Number,normalizeArray:Wt(Number),normalizeInJson:Number,normalizeArrayInJson:Wt(Number)},"bigint:string":{castInJson:kn,castArrayInJson:kr},bigserial:{castInJson:kn,castArrayInJson:kr,normalizeInJson:BigInt,normalizeArrayInJson:Wt(BigInt),normalize:BigInt,normalizeArray:Wt(BigInt)},"bigserial:number":{castInJson:kn,castArrayInJson:kr,normalize:Number,normalizeArray:Wt(Number),normalizeInJson:Number,normalizeArrayInJson:Wt(Number)},date:{normalizeInJson:AS,normalizeArrayInJson:Wt(AS)},"date:string":{},enum:{castArray:kr,normalizeParamArray:vS},"geometry(point)":{castInJson:kn,castArrayInJson:kr,normalize:RS,normalizeArray:Wt(RS),normalizeInJson:RS,normalizeArrayInJson:Wt(RS)},"geometry(point):tuple":{castInJson:kn,castArrayInJson:kr,normalize:TS,normalizeArray:Wt(TS),normalizeInJson:TS,normalizeArrayInJson:Wt(TS)},interval:{castArrayInJson:kr},json:{normalizeParamArray:oN((e)=>JSON.stringify(e),!0)},jsonb:{normalizeParamArray:oN((e)=>JSON.stringify(e),!0)},line:{castInJson:kn,castArrayInJson:kr,normalize:wS,normalizeArray:Wt(wS),normalizeInJson:wS,normalizeArrayInJson:Wt(wS)},"line:tuple":{castInJson:kn,castArrayInJson:kr,normalize:xS,normalizeArray:Wt(xS),normalizeInJson:xS,normalizeArrayInJson:Wt(xS)},numeric:{castInJson:kn,castArrayInJson:kr,castArray:kr},"numeric:number":{castInJson:kn,castArrayInJson:kr,castArray:kr,normalize:Number,normalizeArray:Wt(Number),normalizeInJson:Number,normalizeArrayInJson:Wt(Number)},"numeric:bigint":{castInJson:kn,castArrayInJson:kr,castArray:kr,normalize:BigInt,normalizeArray:Wt(BigInt),normalizeInJson:BigInt,normalizeArrayInJson:Wt(BigInt)},point:{castInJson:kn,castArrayInJson:kr,normalize:ES,normalizeArray:Wt(ES),normalizeInJson:ES,normalizeArrayInJson:Wt(ES)},"point:tuple":{castInJson:kn,castArrayInJson:kr,normalize:bS,normalizeArray:Wt(bS),normalizeInJson:bS,normalizeArrayInJson:Wt(bS)},timestamp:{castInJson:kn,castArrayInJson:kr,normalizeInJson:sN,normalizeArrayInJson:Wt(sN)},timestamptz:{castInJson:kn,castArrayInJson:kr,normalizeInJson:AS,normalizeArrayInJson:Wt(AS)},"timestamp:string":{castInJson:kn,castArrayInJson:kr},"timestamptz:string":{castInJson:kn,castArrayInJson:kr},halfvec:{normalize:oc,normalizeArray:iN(oc),normalizeInJson:oc,normalizeArrayInJson:Wt(oc)},vector:{normalize:oc,normalizeArray:iN(oc),normalizeInJson:oc,normalizeArrayInJson:Wt(oc)}};var xJ=class extends Ce{static[T]="PgCustomColumnBuilder";constructor(e,t,r){super(e,"custom","PgCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new wJ(e,this.config)}},wJ=class extends ve{static[T]="PgCustomColumn";codec;sqlName;mapFromJsonValue;jsonSelectIdentifier;constructor(e,t){super(e,t);this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapToDriverValue=t.customTypeParams.toDriver??this.mapToDriverValue,this.mapFromDriverValue=t.customTypeParams.fromDriver??this.mapFromDriverValue,this.mapFromJsonValue=t.customTypeParams.fromJson,this.jsonSelectIdentifier=t.customTypeParams.forJsonSelect;let r=typeof t.customTypeParams.codec==="string"||typeof t.customTypeParams.codec>"u"?t.customTypeParams.codec:t.customTypeParams.codec(t.fieldConfig);if(this.codec=typeof r==="string"?aN(r):void 0,this.dimensions&&t.customTypeParams.fromJson)this.mapFromJsonValue=(n)=>{if(n===null)return n;let o=typeof n==="string"?SS(n):n;return this.mapJsonArrayElements(o,t.customTypeParams.fromJson,this.dimensions)}}mapJsonArrayElements(e,t,r){if(r>0&&Array.isArray(e))return e.map((n)=>n===null?null:this.mapJsonArrayElements(n,t,r-1));return t(e)}getSQLType(){return this.sqlName}};function cN(e){return(t,r)=>{let{name:n,config:o}=ot(t,r);return new xJ(n,o,e)}}var ic=class extends Ce{static[T]="PgDateColumnBaseBuilder";defaultNow(){return this.default(f`now()`)}};var bJ=class extends ic{static[T]="PgDateBuilder";constructor(e){super(e,"object date","PgDate")}build(e){return new EJ(e,this.config)}},EJ=class extends ve{static[T]="PgDate";codec="date";getSQLType(){return"date"}mapToDriverValue=function(e){if(typeof e==="string")return e;return e.toISOString()}},TJ=class extends ic{static[T]="PgDateStringBuilder";constructor(e){super(e,"string date","PgDateString")}build(e){return new RJ(e,this.config)}},RJ=class extends ve{static[T]="PgDateString";codec="date:string";getSQLType(){return"date"}mapToDriverValue=(e)=>{if(typeof e==="string")return e;return e.toISOString()}};function lN(e,t){let{name:r,config:n}=ot(e,t);if(n?.mode==="date")return new bJ(r);return new TJ(r)}var AJ=class extends Ce{static[T]="PgDoublePrecisionBuilder";constructor(e){super(e,"number double","PgDoublePrecision")}build(e){return new PJ(e,this.config)}},PJ=class extends ve{static[T]="PgDoublePrecision";codec="float8";getSQLType(){return"double precision"}};function dN(e){return new AJ(e??"")}var IJ=class extends Ce{static[T]="PgInetBuilder";constructor(e){super(e,"string inet","PgInet")}build(e){return new CJ(e,this.config)}},CJ=class extends ve{static[T]="PgInet";codec="inet";getSQLType(){return"inet"}};function uN(e){return new IJ(e??"")}var _J=class extends nc{static[T]="PgIntegerBuilder";constructor(e){super(e,"number int32","PgInteger")}build(e){return new kJ(e,this.config)}},kJ=class extends ve{static[T]="PgInteger";codec="int";getSQLType(){return"integer"}};function pN(e){return new _J(e??"")}var OJ=class extends Ce{static[T]="PgIntervalBuilder";constructor(e,t){super(e,"string interval","PgInterval");this.config.intervalConfig=t}build(e){return new DJ(e,this.config)}},DJ=class extends ve{static[T]="PgInterval";codec="interval";fields;precision;constructor(e,t){super(e,t);this.fields=t.intervalConfig.fields,this.precision=t.intervalConfig.precision}getSQLType(){return`interval${this.fields?` ${this.fields}`:""}${this.precision?`(${this.precision})`:""}`}};function fN(e,t={}){let{name:r,config:n}=ot(e,t);return new OJ(r,n)}var NJ=class extends Ce{static[T]="PgJsonBuilder";constructor(e){super(e,"object json","PgJson")}build(e){return new FJ(e,this.config)}},FJ=class extends ve{static[T]="PgJson";codec="json";constructor(e,t){super(e,t)}getSQLType(){return"json"}};function mN(e){return new NJ(e??"")}var UJ=class extends Ce{static[T]="PgJsonbBuilder";constructor(e){super(e,"object json","PgJsonb")}build(e){return new BJ(e,this.config)}},BJ=class extends ve{static[T]="PgJsonb";codec="jsonb";constructor(e,t){super(e,t)}getSQLType(){return"jsonb"}};function yN(e){return new UJ(e??"")}var MJ=class extends Ce{static[T]="PgLineBuilder";constructor(e){super(e,"array line","PgLine")}build(e){return new LJ(e,this.config)}},LJ=class extends ve{static[T]="PgLine";codec="line:tuple";mode="tuple";getSQLType(){return"line"}mapToDriverValue=(e)=>`{${e[0]},${e[1]},${e[2]}}`},$J=class extends Ce{static[T]="PgLineABCBuilder";constructor(e){super(e,"object line","PgLineABC")}build(e){return new qJ(e,this.config)}},qJ=class extends ve{static[T]="PgLineABC";codec="line";mode="abc";getSQLType(){return"line"}mapToDriverValue=(e)=>`{${e.a},${e.b},${e.c}}`};function hN(e,t){let{name:r,config:n}=ot(e,t);if(!n?.mode||n.mode==="tuple")return new MJ(r);return new $J(r)}var jJ=class extends Ce{static[T]="PgMacaddrBuilder";constructor(e){super(e,"string macaddr","PgMacaddr")}build(e){return new HJ(e,this.config)}},HJ=class extends ve{static[T]="PgMacaddr";codec="macaddr";getSQLType(){return"macaddr"}};function gN(e){return new jJ(e??"")}var WJ=class extends Ce{static[T]="PgMacaddr8Builder";constructor(e){super(e,"string macaddr8","PgMacaddr8")}build(e){return new KJ(e,this.config)}},KJ=class extends ve{static[T]="PgMacaddr8";codec="macaddr8";getSQLType(){return"macaddr8"}};function SN(e){return new WJ(e??"")}var VJ=class extends Ce{static[T]="PgNumericBuilder";constructor(e,t,r){super(e,"string numeric","PgNumeric");this.config.precision=t,this.config.scale=r}build(e){return new QJ(e,this.config)}},QJ=class extends ve{static[T]="PgNumeric";codec="numeric";precision;scale;constructor(e,t){super(e,t);this.precision=t.precision,this.scale=t.scale}getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}},JJ=class extends Ce{static[T]="PgNumericNumberBuilder";constructor(e,t,r){super(e,"number","PgNumericNumber");this.config.precision=t,this.config.scale=r}build(e){return new zJ(e,this.config)}},zJ=class extends ve{static[T]="PgNumericNumber";codec="numeric:number";precision;scale;constructor(e,t){super(e,t);this.precision=t.precision,this.scale=t.scale}mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}},GJ=class extends Ce{static[T]="PgNumericBigIntBuilder";constructor(e,t,r){super(e,"bigint int64","PgNumericBigInt");this.config.precision=t,this.config.scale=r}build(e){return new YJ(e,this.config)}},YJ=class extends ve{static[T]="PgNumericBigInt";codec="numeric:bigint";precision;scale;constructor(e,t){super(e,t);this.precision=t.precision,this.scale=t.scale}mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}};function vN(e,t){let{name:r,config:n}=ot(e,t),o=n?.mode;return o==="number"?new JJ(r,n?.precision,n?.scale):o==="bigint"?new GJ(r,n?.precision,n?.scale):new VJ(r,n?.precision,n?.scale)}var XJ=class extends Ce{static[T]="PgPointTupleBuilder";constructor(e){super(e,"array point","PgPointTuple")}build(e){return new ZJ(e,this.config)}},ZJ=class extends ve{static[T]="PgPointTuple";codec="point:tuple";mode="tuple";getSQLType(){return"point"}mapToDriverValue=(e)=>`(${e[0]},${e[1]})`},e8=class extends Ce{static[T]="PgPointObjectBuilder";constructor(e){super(e,"object point","PgPointObject")}build(e){return new t8(e,this.config)}},t8=class extends ve{static[T]="PgPointObject";codec="point";mode="xy";getSQLType(){return"point"}mapToDriverValue=(e)=>`(${e.x},${e.y})`};function xN(e,t){let{name:r,config:n}=ot(e,t);if(!n?.mode||n.mode==="tuple")return new XJ(r);return new e8(r)}var r8=class extends Ce{static[T]="PgGeometryBuilder";constructor(e,t){super(e,"array geometry","PgGeometry");this.config.srid=t}build(e){return new n8(e,this.config)}},n8=class extends ve{static[T]="PgGeometry";codec="geometry(point):tuple";srid=this.config.srid;mode="tuple";getSQLType(){return`geometry(point${this.srid===void 0?"":`,${this.srid}`})`}mapToDriverValue=(e)=>`point(${e[0]} ${e[1]})`},o8=class extends Ce{static[T]="PgGeometryObjectBuilder";constructor(e,t){super(e,"object geometry","PgGeometryObject");this.config.srid=t}build(e){return new i8(e,this.config)}},i8=class extends ve{static[T]="PgGeometryObject";codec="geometry(point)";srid=this.config.srid;mode="object";getSQLType(){return`geometry(point${this.srid===void 0?"":`,${this.srid}`})`}mapToDriverValue=(e)=>`point(${e.x} ${e.y})`};function wN(e,t){let{name:r,config:n}=ot(e,t);if(!n?.mode||n.mode==="tuple")return new r8(r,n?.srid);return new o8(r,n?.srid)}var s8=class extends Ce{static[T]="PgRealBuilder";constructor(e,t){super(e,"number float","PgReal");this.config.length=t}build(e){return new a8(e,this.config)}},a8=class extends ve{static[T]="PgReal";codec="float4";constructor(e,t){super(e,t)}getSQLType(){return"real"}};function bN(e){return new s8(e??"")}var c8=class extends Ce{static[T]="PgSerialBuilder";constructor(e){super(e,"number int32","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new l8(e,this.config)}},l8=class extends ve{static[T]="PgSerial";codec="serial";getSQLType(){return"serial"}};function EN(e){return new c8(e??"")}var d8=class extends nc{static[T]="PgSmallIntBuilder";constructor(e){super(e,"number int16","PgSmallInt")}build(e){return new u8(e,this.config)}},u8=class extends ve{static[T]="PgSmallInt";codec="smallint";getSQLType(){return"smallint"}};function TN(e){return new d8(e??"")}var p8=class extends Ce{static[T]="PgSmallSerialBuilder";constructor(e){super(e,"number int16","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new f8(e,this.config)}},f8=class extends ve{static[T]="PgSmallSerial";codec="smallserial";getSQLType(){return"smallserial"}};function RN(e){return new p8(e??"")}var m8=class extends Ce{static[T]="PgTextBuilder";constructor(e,t){super(e,t.enum?.length?"string enum":"string","PgText");this.config.enumValues=t.enum}build(e){return new y8(e,this.config,this.config.enumValues)}},y8=class extends ve{static[T]="PgText";enumValues;codec="text";constructor(e,t,r){super(e,t);this.enumValues=r}getSQLType(){return"text"}};function AN(e,t={}){let{name:r,config:n}=ot(e,t);return new m8(r,n)}var h8=class extends ic{static[T]="PgTimeBuilder";constructor(e,t,r){super(e,"string time","PgTime");this.withTimezone=t,this.precision=r,this.config.withTimezone=t,this.config.precision=r}build(e){return new g8(e,this.config)}},g8=class extends ve{static[T]="PgTime";codec="time";withTimezone;precision;constructor(e,t){super(e,t);this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}};function PN(e,t={}){let{name:r,config:n}=ot(e,t);return new h8(r,n.withTimezone??!1,n.precision)}var S8=class extends ic{static[T]="PgTimestampBuilder";constructor(e,t,r){super(e,"object date","PgTimestamp");this.config.withTimezone=t,this.config.precision=r}build(e){return new v8(e,this.config)}},v8=class extends ve{static[T]="PgTimestamp";codec;withTimezone;precision;constructor(e,t){super(e,t);this.withTimezone=t.withTimezone,this.precision=t.precision,this.codec=this.withTimezone?"timestamptz":"timestamp"}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapToDriverValue=(e)=>{if(typeof e==="string")return e;return e.toISOString()}},x8=class extends ic{static[T]="PgTimestampStringBuilder";constructor(e,t,r){super(e,"string timestamp","PgTimestampString");this.config.withTimezone=t,this.config.precision=r}build(e){return new w8(e,this.config)}},w8=class extends ve{static[T]="PgTimestampString";codec;withTimezone;precision;constructor(e,t){super(e,t);this.withTimezone=t.withTimezone,this.precision=t.precision,this.codec=this.withTimezone?"timestamptz:string":"timestamp:string"}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}mapToDriverValue=(e)=>{if(typeof e==="string")return e;return e.toISOString()}};function IN(e,t={}){let{name:r,config:n}=ot(e,t);if(n?.mode==="string")return new x8(r,n.withTimezone??!1,n.precision);return new S8(r,n?.withTimezone??!1,n?.precision)}var b8=class extends Ce{static[T]="PgUUIDBuilder";constructor(e){super(e,"string uuid","PgUUID")}defaultRandom(){return this.default(f`gen_random_uuid()`)}build(e){return new E8(e,this.config)}},E8=class extends ve{static[T]="PgUUID";codec="uuid";getSQLType(){return"uuid"}};function CN(e){return new b8(e??"")}var T8=class extends Ce{static[T]="PgVarcharBuilder";constructor(e,t){super(e,t.enum?.length?"string enum":"string","PgVarchar");this.config.length=t.length,this.config.enumValues=t.enum}build(e){return new R8(e,this.config)}},R8=class extends ve{static[T]="PgVarchar";codec="varchar";enumValues;constructor(e,t){super(e,t);this.enumValues=t.enumValues}getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}};function _N(e,t={}){let{name:r,config:n}=ot(e,t);return new T8(r,n)}var A8=class extends Ce{static[T]="PgBinaryVectorBuilder";constructor(e,t){super(e,"string binary","PgBinaryVector");this.config.length=t.dimensions,this.config.isLengthExact=!0}build(e){return new P8(e,this.config)}},P8=class extends ve{static[T]="PgBinaryVector";codec="bit";getSQLType(){return`bit(${this.length})`}};function kN(e,t){let{name:r,config:n}=ot(e,t);return new A8(r,n)}var I8=class extends Ce{static[T]="PgHalfVectorBuilder";constructor(e,t){super(e,"array halfvector","PgHalfVector");this.config.length=t.dimensions,this.config.isLengthExact=!0}build(e){return new C8(e,this.config)}},C8=class extends ve{static[T]="PgHalfVector";codec="halfvec";getSQLType(){return`halfvec(${this.length})`}mapToDriverValue=(e)=>JSON.stringify(e)};function ON(e,t){let{name:r,config:n}=ot(e,t);return new I8(r,n)}var _8=class extends Ce{static[T]="PgSparseVectorBuilder";constructor(e,t){super(e,"string sparsevec","PgSparseVector");this.config.vectorDimensions=t.dimensions}build(e){return new k8(e,this.config)}},k8=class extends ve{static[T]="PgSparseVector";codec="sparsevec";vectorDimensions=this.config.vectorDimensions;getSQLType(){return`sparsevec(${this.vectorDimensions})`}};function DN(e,t){let{name:r,config:n}=ot(e,t);return new _8(r,n)}var O8=class extends Ce{static[T]="PgVectorBuilder";constructor(e,t){super(e,"array vector","PgVector");this.config.length=t.dimensions,this.config.isLengthExact=!0}build(e){return new D8(e,this.config)}},D8=class extends ve{static[T]="PgVector";codec="vector";getSQLType(){return`vector(${this.length})`}mapToDriverValue=(e)=>JSON.stringify(e)};function NN(e,t){let{name:r,config:n}=ot(e,t);return new O8(r,n)}function FN(){return{bigint:GD,bigserial:YD,boolean:XD,char:ZD,cidr:eN,customType:cN,date:lN,doublePrecision:dN,inet:uN,integer:pN,interval:fN,json:mN,jsonb:yN,line:hN,macaddr:gN,macaddr8:SN,numeric:vN,point:xN,geometry:wN,real:bN,serial:EN,smallint:TN,smallserial:RN,text:AN,time:PN,timestamp:IN,uuid:CN,varchar:_N,bit:kN,halfvec:ON,sparsevec:DN,vector:NN}}var YE=Symbol.for("drizzle:PgInlineForeignKeys"),XE=Symbol.for("drizzle:EnableRLS"),em=class extends de{static[T]="PgTable";static Symbol=Object.assign({},de.Symbol,{InlineForeignKeys:YE,EnableRLS:XE});[YE]=[];[XE]=!1;[de.Symbol.ExtraConfigBuilder]=void 0;[de.Symbol.ExtraConfigColumns]={}};function UN(e,t,r,n,o,i=e){let s=uS(o),a=new em(e,n,i),c=typeof t==="function"?t(FN()):t,l=Object.fromEntries(Object.entries(c).map(([m,h])=>{let S=h;S.setName(m,s);let x=S.build(a).postBuild();return a[YE].push(...S.buildForeignKeys(x,a)),[m,x]})),d=Object.fromEntries(Object.entries(c).map(([m,h])=>{let S=h;return S.setName(m,s),[m,S.buildExtraConfigColumn(a)]})),u=Object.assign(a,l);if(u[de.Symbol.Columns]=l,u[de.Symbol.ExtraConfigColumns]=d,r)u[em.Symbol.ExtraConfigBuilder]=r;return Object.assign(u,{enableRLS:()=>(u[em.Symbol.EnableRLS]=!0,u)})}function N8(e){return Object.assign((n,o,i)=>UN(n,o,i,void 0,e),{withRLS:(n,o,i)=>{let s=UN(n,o,i,void 0,e);return s[XE]=!0,s}})}var Hbe=N8(void 0);var BN=class{static[T]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new F8(e,this.columns,this.name)}},F8=class{static[T]="PgPrimaryKey";columns;name;isNameExplicit;constructor(e,t,r){this.table=e,this.columns=t,this.name=r,this.isNameExplicit=!!r}getName(){return this.name??`${this.table[em.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}};var MN=class{static[T]="Relation";referencedTableName;fieldName;constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[de.Symbol.Name]}},LN=class{static[T]="Relations";constructor(e,t){this.table=e,this.config=t}},Eu=class e extends MN{static[T]="One";constructor(t,r,n,o){super(t,r,n?.relationName);this.config=n,this.isNullable=o}withFieldName(t){let r=new e(this.sourceTable,this.referencedTable,this.config,this.isNullable);return r.fieldName=t,r}},ZE=class e extends MN{static[T]="Many";constructor(t,r,n){super(t,r,n?.relationName);this.config=n}withFieldName(t){let r=new e(this.sourceTable,this.referencedTable,this.config);return r.fieldName=t,r}};function $N(){return{and:_,between:Su,eq:p,exists:xl,gt:Xt,gte:tc,ilike:wu,inArray:Fe,isNull:Se,isNotNull:Nt,like:rc,lt:ms,lte:dn,ne:ec,not:ko,notBetween:vu,notExists:wl,notLike:xu,notIlike:bu,notInArray:un,or:Rt,sql:f}}function qN(){return{sql:f,asc:Oo,desc:Hr}}function jN(e,t){if(Object.keys(e).length===1&&"default"in e&&!j(e.default,de))e=e.default;let r={},n={},o={};for(let[i,s]of Object.entries(e))if(j(s,de)){let a=hl(s),c=n[a];r[a]=i,o[i]={tsName:i,dbName:s[de.Symbol.Name],schema:s[de.Symbol.Schema],columns:s[de.Symbol.Columns],relations:c?.relations??{},primaryKey:c?.primaryKey??[]};for(let d of Object.values(s[de.Symbol.Columns]))if(d.primary)o[i].primaryKey.push(d);let l=s[de.Symbol.ExtraConfigBuilder]?.(s[de.Symbol.ExtraConfigColumns]);if(l){for(let d of Object.values(l))if(j(d,BN))o[i].primaryKey.push(...d.columns)}}else if(j(s,LN)){let a=hl(s.table),c=r[a],l=s.config(t(s.table));for(let[d,u]of Object.entries(l))if(c){let m=o[c];m.relations[d]=u}else{if(!(a in n))n[a]={relations:{}};n[a].relations[d]=u}}return{tables:o,tableNamesMap:r}}function At(e,t){return new LN(e,(r)=>Object.fromEntries(Object.entries(t(r)).map(([n,o])=>[n,o.withFieldName(n)])))}function U8(e){return function(r,n){return new Eu(e,r,n,n?.fields.reduce((o,i)=>o&&i.notNull,!0)??!1)}}function B8(e){return function(r,n){return new ZE(e,r,n)}}function HN(e,t,r){if(j(r,Eu)&&r.config)return{fields:r.config.fields,references:r.config.references};let n=t[hl(r.referencedTable)];if(!n)throw Error(`Table "${r.referencedTable[de.Symbol.Name]}" not found in schema`);let o=e[n];if(!o)throw Error(`Table "${n}" not found in schema`);let i=r.sourceTable,s=t[hl(i)];if(!s)throw Error(`Table "${i[de.Symbol.Name]}" not found in schema`);let a=[];for(let c of Object.values(o.relations))if(r.relationName&&r!==c&&c.relationName===r.relationName||!r.relationName&&c.referencedTable===r.sourceTable)a.push(c);if(a.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${n}"`):Error(`There are multiple relations between "${n}" and "${r.sourceTable[de.Symbol.Name]}". Please specify relation name`);if(a[0]&&j(a[0],Eu)&&a[0].config)return{fields:a[0].config.references,references:a[0].config.fields};throw Error(`There is not enough information to infer relation "${s}.${r.fieldName}"`)}function WN(e){return{one:U8(e),many:B8(e)}}function PS(e,t,r,n,o=(i)=>i){let i={};for(let[s,a]of n.entries())if(a.isJson){let c=t.relations[a.tsKey],l=r[s],d=typeof l==="string"?JSON.parse(l):l;i[a.tsKey]=j(c,Eu)?d&&PS(e,e[a.relationTableTsKey],d,a.selection,o):d.map((u)=>PS(e,e[a.relationTableTsKey],u,a.selection,o))}else{let c=o(r[s]),l=a.field,d;if(j(l,at))d=l;else if(j(l,me))d=l.decoder;else d=l.sql.decoder;i[a.tsKey]=c===null?null:d.mapFromDriverValue(c)}return i}var ia=class extends Error{static[T]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}},bl=class e extends Error{static[T]="DrizzleQueryError";constructor(t,r,n){super(`Failed query: ${t}
|
|
55
|
+
params: ${r}`);if(this.query=t,this.params=r,this.cause=n,this.name="DrizzleQueryError",Error.captureStackTrace(this,e),n)this.cause=n}},KN=class extends ia{static[T]="TransactionRollbackError";constructor(){super({message:"Rollback"});this.name="TransactionRollbackError"}};function VN(e,t){for(let r of Object.values(e))for(let[n,o]of Object.entries(r.relations)){if(!j(o,El))continue;o.sourceTable=r.table,o.fieldName=n}for(let[r,n]of Object.entries(e))for(let[o,i]of Object.entries(n.relations)){if(!j(i,El))continue;let s,{targetTableName:a,alias:c,sourceColumns:l,targetColumns:d,throughTable:u,sourceTable:m,through:h,where:S,sourceColumnTableNames:x,targetColumnTableNames:v}=i,w=`relations -> ${n.name}: { ${o}: r.${j(i,tm)?"one":"many"}.${a}(...) }`;if(o in n.table[_o])throw Error(`${w}: relation name collides with column "${o}" of table "${n.name}"`);if(typeof c==="string"&&!c)throw Error(`${w}: "alias" cannot be an empty string - omit it if you don't need it`);if(l?.length===0)throw Error(`${w}: "from" cannot be empty`);if(d?.length===0)throw Error(`${w}: "to" cannot be empty`);if(l&&d){if(l.length!==d.length&&!u)throw Error(`${w}: "from" and "to" fields without "through" must have the same length`);for(let F of x)if(F!==r)throw Error(`${w}: all "from" columns must belong to table "${r}", found column of table "${F}"`);for(let F of v)if(F!==a)throw Error(`${w}: all "to" columns must belong to table "${a}", found column of table "${F}"`);if(h){if(h.source.length!==l.length||h.target.length!==d.length)throw Error(`${w}: ".through(column)" must be used either on all columns in "from" and "to" or not defined on any of them`);for(let F of h.source)if(t[F._.tableName]!==u)throw Error(`${w}: ".through(column)" must be used on the same table by all columns of the relation`);for(let F of h.target)if(t[F._.tableName]!==u)throw Error(`${w}: ".through(column)" must be used on the same table by all columns of the relation`)}continue}if(l||d)throw Error(`${w}: relation must have either both "from" and "to" defined, or none of them`);let P=e[a];if(!P)throw Error(`${w}: not enough data provided to build the relation - "from"/"to" are not defined, and no reverse relations of table "${a}" were found"`);if(c){let F=Object.values(P.relations).filter((R)=>j(R,El)&&R.alias===c&&R!==i);if(F.length>1)throw Error(`${w}: not enough data provided to build the relation - "from"/"to" are not defined, and multiple relations with alias "${c}" found in table "${a}": ${F.map((R)=>`"${R.fieldName}"`).join(", ")}`);if(s=F[0],!s)throw Error(`${w}: not enough data provided to build the relation - "from"/"to" are not defined, and there is no reverse relation of table "${a}" with alias "${c}"`)}else{let F=Object.values(P.relations).filter((R)=>j(R,El)&&R.targetTable===m&&!R.alias&&R!==i);if(F.length>1)throw Error(`${w}: not enough data provided to build the relation - "from"/"to" are not defined, and multiple relations between "${a}" and "${r}" were found.
|
|
56
|
+
Hint: you can specify "alias" on both sides of the relation with the same value`);if(s=F[0],!s)throw Error(`${w}: not enough data provided to build the relation - "from"/"to" are not defined, and no reverse relation of table "${a}" with target table "${r}" was found`)}if(!s.sourceColumns||!s.targetColumns)throw Error(`${w}: not enough data provided to build the relation - "from"/"to" are not defined, and reverse relation "${a}.${s.fieldName}" does not have "from"/"to" defined`);i.sourceColumns=s.targetColumns,i.targetColumns=s.sourceColumns,i.through=s.through?{source:s.through.target,target:s.through.source}:void 0,i.throughTable=s.throughTable,i.isReversed=!S,i.where=S??s.where}return e}function QN(e,t){let r={};for(let[n,o]of Object.entries(e))r[n]={table:o,name:n,relations:t[n]??{}};return VN(r,e)}var El=class{static[T]="RelationV2";fieldName;sourceColumns;targetColumns;alias;where;sourceTable;targetTable;through;throughTable;isReversed;sourceColumnTableNames=[];targetColumnTableNames=[];constructor(e,t){this.targetTableName=t,this.targetTable=e}},tm=class extends El{static[T]="OneV2";relationType="one";optional;constructor(e,t,r,n){super(t,r);if(this.alias=n?.alias,this.where=n?.where,n?.from)this.sourceColumns=(Array.isArray(n.from)?n.from:[n.from]).map((o)=>(this.throughTable??=o._.through?e[o._.through._.tableName]:void 0,this.sourceColumnTableNames.push(o._.tableName),o._.column));if(n?.to)this.targetColumns=(Array.isArray(n.to)?n.to:[n.to]).map((o)=>(this.throughTable??=o._.through?e[o._.through._.tableName]:void 0,this.targetColumnTableNames.push(o._.tableName),o._.column));if(this.throughTable)this.through={source:(Array.isArray(n?.from)?n.from:(n?.from)?[n.from]:[]).map((o)=>o._.through),target:(Array.isArray(n?.to)?n.to:(n?.to)?[n.to]:[]).map((o)=>o._.through)};this.optional=n?.optional??!0}},JN=class extends El{static[T]="ManyV2";relationType="many";constructor(e,t,r,n){super(t,r);if(this.config=n,this.alias=n?.alias,this.where=n?.where,n?.from)this.sourceColumns=(Array.isArray(n.from)?n.from:[n.from]).map((o)=>(this.throughTable??=o._.through?e[o._.through._.tableName]:void 0,this.sourceColumnTableNames.push(o._.tableName),o._.column));if(n?.to)this.targetColumns=(Array.isArray(n.to)?n.to:[n.to]).map((o)=>(this.throughTable??=o._.through?e[o._.through._.tableName]:void 0,this.targetColumnTableNames.push(o._.tableName),o._.column));if(this.throughTable)this.through={source:(Array.isArray(n?.from)?n.from:(n?.from)?[n.from]:[]).map((o)=>o._.through),target:(Array.isArray(n?.to)?n.to:(n?.to)?[n.to]:[]).map((o)=>o._.through)}}},zN=class{static[T]="AggregatedField";table;onTable(e){return this.table=e,this}},GN=class extends zN{static[T]="AggregatedFieldCount";query;getSQL(){if(!this.query){if(!this.table)throw Error("Table must be set before building aggregate field");this.query=f`select count(*) as ${f.identifier("r")} from ${sc(this.table)}`.mapWith(Number)}return this.query}},Tl={and:_,between:Su,eq:p,exists:xl,gt:Xt,gte:tc,ilike:wu,inArray:Fe,arrayContains:yS,arrayContained:hS,arrayOverlaps:gS,isNull:Se,isNotNull:Nt,like:rc,lt:ms,lte:dn,ne:ec,not:ko,notBetween:vu,notExists:wl,notLike:xu,notIlike:bu,notInArray:un,or:Rt,sql:f},YN={sql:f,asc:Oo,desc:Hr};function Tu(e,t,r,n,o=!1,i=!1,s=!0){let a=t?1:e.length,c=r.map(({field:l,codec:d,arrayDimensions:u})=>{let m;if(j(l,at))m=l;else if(j(l,me))m=l.decoder;else if(j(l,me.Aliased))m=l.sql.decoder;else if(j(l,de)||j(l,Lr))m=Xa;else m=l.getSQL().decoder;if(s&&l.mapFromJsonValue)return(h)=>l.mapFromJsonValue(h);return m.mapFromDriverValue.isNoop?d?(h)=>d(h,u):void 0:d?(h)=>m.mapFromDriverValue(d(h,u)):(h)=>m.mapFromDriverValue(h)});for(let l=0;l<a;++l){let d=t?e:e[l];for(let u=0;u<r.length;++u){let m=r[u];if(m.selection){if(d[m.key]===null)continue;if(o){if(d[m.key]=JSON.parse(d[m.key]),d[m.key]===null)continue}else if(i&&typeof d[m.key]==="string")d[m.key]=JSON.parse(d[m.key]);if(m.isArray){Tu(d[m.key],!1,m.selection,n,!1,i);continue}Tu(d[m.key],!0,m.selection,n,!1,i);continue}if(n)d[m.key]=n(d[m.key]);if(d[m.key]===null)continue;let h=c[u];if(!h)continue;d[m.key]=h(d[m.key])}}return e}function XN(e,t,r,n,o=!1,i=!1){let s=t?1:e.length,a=r.map(({field:l,codec:d,arrayDimensions:u})=>{let m;if(j(l,at))m=l;else if(j(l,me))m=l.decoder;else if(j(l,me.Aliased))m=l.sql.decoder;else if(j(l,de)||j(l,Lr))m=Xa;else m=l.getSQL().decoder;return m.mapFromDriverValue.isNoop?d?(h)=>d(h,u):void 0:d?(h)=>m.mapFromDriverValue(d(h,u)):(h)=>m.mapFromDriverValue(h)}),c=Array.from({length:s});for(let l=0;l<s;++l){let d=t?e:e[l],u={};for(let m=0;m<r.length;++m){let h=r[m],S=d[m];if(h.selection){if(S===null){u[h.key]=null;continue}if(o){if(S=JSON.parse(S),S===null){u[h.key]=null;continue}}else if(i&&typeof S==="string")S=JSON.parse(S);if(h.isArray)Tu(S,!1,h.selection,n,!1,i);else Tu(S,!0,h.selection,n,!1,i);u[h.key]=S;continue}if(n)S=n(S);if(S===null){u[h.key]=null;continue}let x=a[m];u[h.key]=x?x(S):S}c[l]=u}return t?c[0]:c}function rT({selection:e,isFirst:t,parseJson:r,parseJsonIfString:n,rootJsonMappers:o,arrayModeRoot:i},s){return(a)=>{if(t&&!a[0])return a[0];return i?XN(t?a[0]:a,t,e,s,r,n):Tu(t?a[0]:a,t,e,s,r,n,o)}}function tT(e,t,r,n,o,i,s,a,c,l){let d=[],u=[],m=!1,h=e.map(()=>`c${c.n++}`),S=e.map((x,v)=>l?h[v]:`${JSON.stringify(x.key)}: ${h[v]}`);d.push(l?`let [ ${S.join(", ")} ] = ${t};`:`let { ${S.join(", ")} } = ${t};`);for(let[x,{field:v,key:w,codec:P,isArray:F,selection:R,arrayDimensions:b}]of e.entries()){let A=`${r}[${x}]`,D=JSON.stringify(w),B=h[x];if(R){if(o)d.push(`if (${B} !== null) ${B} = JSON.parse(${B});`),m=!0;else if(i)d.push(`if (typeof ${B} === 'string') ${B} = JSON.parse(${B});`),m=!0;let Z=`s${c.n++}`,se=a.length;if(a.push(`const { selection: ${Z} } = ${A};`),F){let te=`j${c.n++}`,Ne=tT(R,`${B}[${te}]`,Z,n,!1,i,!0,a,c,!1);if(Ne.hasWork){m=!0,d.push(`if (${B} !== null) {`),d.push(` for (let ${te} = 0; ${te} < ${B}.length; ++${te}) {`);for(let ze of Ne.bodyStmts)d.push(` ${ze}`);d.push(` ${B}[${te}] = ${Ne.literal};`),d.push("\t}"),d.push("}")}else a.splice(se,1)}else{let te=tT(R,B,Z,n,!1,i,!0,a,c,!1);if(te.hasWork){m=!0,d.push(`if (${B} !== null) {`);for(let Ne of te.bodyStmts)d.push(` ${Ne}`);d.push(` ${B} = ${te.literal};`),d.push("}")}else a.splice(se,1)}u.push(`${D}: ${B}`);continue}let J="",G="",ce=!1;if(j(v,at)){if(s&&v.mapFromJsonValue){ce=!0;let Z=c.n++;G=`field: dec${Z}`,J=`dec${Z}.mapFromJsonValue`}else if(!v.mapFromDriverValue.isNoop){let Z=c.n++;G=`field: dec${Z}`,J=`dec${Z}.mapFromDriverValue`}}else if(j(v,me)){if(s&&v.decoder.mapFromJsonValue){ce=!0;let Z=c.n++;G=`field: { decoder: dec${Z} }`,J=`dec${Z}.mapFromJsonValue`}else if(!v.decoder.mapFromDriverValue.isNoop){let Z=c.n++;G=`field: { decoder: dec${Z} }`,J=`dec${Z}.mapFromDriverValue`}}else if(j(v,me.Aliased)){if(s&&v.sql.decoder.mapFromJsonValue){ce=!0;let Z=c.n++;G=`field: { sql: { decoder: dec${Z} } }`,J=`dec${Z}.mapFromJsonValue`}else if(!v.sql.decoder.mapFromDriverValue.isNoop){let Z=c.n++;G=`field: { sql: { decoder: dec${Z} } }`,J=`dec${Z}.mapFromDriverValue`}}else if(j(v,de)||j(v,Lr));else{let Z=v.getSQL();if(s&&Z.decoder.mapFromJsonValue){ce=!0;let se=c.n++;a.push(`const dec${se} = ${A}.field.getSQL().decoder;`),J=`dec${se}.mapFromJsonValue`}else if(!Z.decoder.mapFromDriverValue.isNoop){let se=c.n++;a.push(`const dec${se} = ${A}.field.getSQL().decoder;`),J=`dec${se}.mapFromDriverValue`}}let re="";if(!ce&&P)re=`codec${c.n++}`;if(G||re){let Z=[];if(G)Z.push(G);if(re)Z.push(`codec: ${re}`);a.push(`const { ${Z.join(", ")} } = ${A};`)}if(n){if(m=!0,d.push(`${B} = mapColumnValue(${B});`),J||re){let Z=B;if(re)Z=`${re}(${Z}, ${b})`;if(J)Z=`${J}(${Z})`;d.push(`if (${B} !== null) ${B} = ${Z};`)}u.push(`${D}: ${B}`)}else if(J||re){m=!0;let Z=B;if(re)Z=`${re}(${Z}, ${b})`;if(J)Z=`${J}(${Z})`;u.push(`${D}: ${B} === null ? null : ${Z}`)}else u.push(`${D}: ${B}`)}return{bodyStmts:d,literal:`{ ${u.join(", ")} }`,hasWork:m}}function CS({selection:e,isFirst:t,parseJson:r,parseJsonIfString:n,rootJsonMappers:o,arrayModeRoot:i},s){let a=[],c=tT(e,"row","selection",s,r,n,i?!1:o,a,{n:0},!!i),l=[];l.push(` "use strict";
|
|
57
|
+
const { selection${s?", mapColumnValue":""} } = this;`);for(let u of a)l.push(` ${u}`);if(i)if(t){l.push("\tconst row = rows[0];"),l.push("\tif (!row) return undefined;");for(let u of c.bodyStmts)l.push(` ${u}`);l.push(` return ${c.literal};`)}else{l.push("\tconst { length } = rows;"),l.push("\tconst mapped = Array.from({ length });"),l.push("\tfor (let i = 0; i < length; ++i) {"),l.push("\t\tconst row = rows[i];");for(let u of c.bodyStmts)l.push(` ${u}`);l.push(` mapped[i] = ${c.literal};`),l.push("\t}"),l.push("\treturn mapped;")}else if(!c.hasWork)l.push(t?"\treturn rows[0];":"\treturn rows;");else if(t){l.push("\tconst row = rows[0];"),l.push("\tif (!row) return undefined;");for(let u of c.bodyStmts)l.push(` ${u}`);l.push(` rows[0] = ${c.literal};`),l.push("\treturn rows[0];")}else{l.push("\tfor (let i = 0; i < rows.length; ++i) {"),l.push("\t\tconst row = rows[i];");for(let u of c.bodyStmts)l.push(` ${u}`);l.push(` rows[i] = ${c.literal};`),l.push("\t}"),l.push("\treturn rows;")}l.push("\t//# sourceURL=drizzle:jit-relational-query-mapper");let d=l.join(`
|
|
58
|
+
`);return Object.assign(new iS("rows",d).bind({selection:e,mapColumnValue:s}),{body:`function jitRqbMapper (rows) {
|
|
59
|
+
${d}
|
|
60
|
+
}`})}var ZN=class{static[T]="RelationsBuilderTable";_;constructor(e,t){this._={name:t,table:e}}},eF=class{static[T]="RelationsBuilderColumn";_;constructor(e,t,r){this._={tableName:t,column:e,key:r}}through(e){return new tF(this._.column,this._.tableName,this._.key,e)}},tF=class{static[T]="RelationsBuilderColumn";_;constructor(e,t,r,n){this._={tableName:t,column:e,through:n,key:r}}},rF=class{static[T]="RelationsHelperStatic";_;constructor(e){this._={tables:e};let t={},r={};for(let[n,o]of Object.entries(e))t[n]=(i)=>new tm(e,o,n,i),r[n]=(i)=>new JN(e,o,n,i);this.one=t,this.many=r}one;many;aggs={count(){return new GN}}};function nF(e){let t=new rF(e),r=Object.entries(e).reduce((n,[o,i])=>{let s=new ZN(i,o),a=Object.entries(i[_o]).reduce((c,[l,d])=>(c[l]=new eF(d,o,l),c),{});return n[o]=Object.assign(s,a),n},{});return Object.assign(t,r)}function oF(e){return Object.fromEntries(Object.entries(e).filter(([t,r])=>j(r,de)||j(r,Lr)))}function nT(e,t){let r=oF(e);return QN(r,t?t(nF(r)):{})}function oT(e,t){let r=e[_o][t];return r?j(r,at)?r:j(r,me.Aliased)?f`${e}.${f.identifier(r.fieldAlias)}`:f`${e}.${f.identifier(t)}`:f`${e}.${f.identifier(t)}`}function IS(e,t){if(typeof t!=="object"||j(t,Hi))return p(e,t);let r=Object.entries(t);if(!r.length)return;let n=[];for(let[o,i]of r){if(i===void 0)continue;switch(o){case"NOT":{let s=IS(e,i);if(!s)continue;n.push(ko(s));continue}case"OR":if(!i.length)continue;n.push(Rt(...i.map((s)=>IS(e,s))));continue;case"AND":if(!i.length)continue;n.push(_(...i.map((s)=>IS(e,s))));continue;case"isNotNull":case"isNull":if(!i)continue;n.push(Tl[o](e));continue;case"in":n.push(Tl.inArray(e,i));continue;case"notIn":n.push(Tl.notInArray(e,i));continue;default:n.push(Tl[o](e,i));continue}}if(!n.length)return;return _(...n)}function ys(e,t,r={},n={},o=0){let i=Object.entries(t);if(!i.length)return;let s=[];for(let[a,c]of i){if(c===void 0)continue;switch(a){case"RAW":{let l=typeof c==="function"?c(e,Tl):c.getSQL();s.push(l);continue}case"OR":if(!c?.length)continue;s.push(Rt(...c.map((l)=>ys(e,l,r,n,o))));continue;case"AND":if(!c?.length)continue;s.push(_(...c.map((l)=>ys(e,l,r,n,o))));continue;case"NOT":{if(c===void 0)continue;let l=ys(e,c,r,n,o);if(!l)continue;s.push(ko(l));continue}default:{if(e[_o][a]){let w=IS(oT(e,a),c);if(w)s.push(w);continue}let l=r[a];if(!l)throw new ia({message:`Unknown relational filter field: "${a}"`});let d=Hn(l.targetTable,`f${o}`),u=l.throughTable?Hn(l.throughTable,`ft${o}`):void 0,m=n[l.targetTableName],{filter:h,joinCondition:S}=_S(l,e,d,u),x=_(h,typeof c==="boolean"?void 0:ys(d,c,m.relations,n,o+1)),v=u?f`(select * from ${sc(d)} inner join ${sc(u)} on ${S}${f` where ${x}`.if(x)} limit 1)`:f`(select * from ${sc(d)}${f` where ${x}`.if(x)} limit 1)`;if(x)s.push((c?xl:wl)(v))}}}return _(...s)}function iT(e,t){if(typeof t==="function"){let n=t(e,YN);return j(n,me)?n:Array.isArray(n)?n.length?f.join(n.map((o)=>j(o,me)?o:Oo(o)),f`, `):void 0:j(n,at)?Oo(n):void 0}let r=Object.entries(t).filter(([n,o])=>o);if(!r.length)return;return f.join(r.map(([n,o])=>(o==="asc"?Oo:Hr)(oT(e,n))),f`, `)}function sT(e,t,r,n){let o=[],i=[];for(let[s,a]of Object.entries(t)){if(!a)continue;let c=(typeof a==="function"?a(e,{sql:Tl.sql}):a).getSQL(),l=r?oS(c):void 0,d=l&&(!n||!l.jsonSelectIdentifier)?f`${r.apply(l,n?"castInJson":"cast",f`(${c})`)} as ${f.identifier(s)}`:f`(${c}) as ${f.identifier(s)}`;d.decoder=c.decoder,o.push(d),i.push(l&&(!n||!l.mapFromJsonValue)?{key:s,field:d,codec:r.get(l,n?"normalizeInJson":"normalize"),arrayDimensions:l.dimensions}:{key:s,field:d})}return{sql:o.length?f.join(o,f`, `):void 0,selection:i}}function _S(e,t,r,n){if(e.through){let o=e.sourceColumns.map((s,a)=>{let c=e.through.source[a];return p(f`${t}.${f.identifier(s.name)}`,f`${n}.${f.identifier(j(c._.column,at)?c._.column.name:c._.key)}`)}),i=e.targetColumns.map((s,a)=>{let c=e.through.target[a];return p(f`${n}.${f.identifier(j(c._.column,at)?c._.column.name:c._.key)}`,f`${r}.${f.identifier(s.name)}`)});return{filter:_(e.where?ys(e.isReversed?t:r,e.where):void 0,...o),joinCondition:_(...i)}}return{filter:_(...e.sourceColumns.map((o,i)=>{let s=e.targetColumns[i];return p(f`${t}.${f.identifier(o.name)}`,f`${r}.${f.identifier(s.name)}`)}),e.where?ys(e.isReversed?t:r,e.where):void 0)}}function sc(e){return f`${e[Ya]?f`${f`${f.identifier(e[ta]??"")}.`.if(e[ta])}${f.identifier(e[yl])} as ${e}`:e}`}function aT(e){let{localMigrations:t,dbMigrations:r}=e,n=new Set(r.map((o)=>o.name).filter((o)=>o!==null));return t.filter((o)=>!o.name||!n.has(o.name))}var cT={sqlite:1,pg:1,effect:1,mysql:1,mssql:1,cockroach:1,singlestore:1},lT={mysql:(e)=>{if(e.includes("name"))return 1;return 0},pg:(e)=>{if(e.includes("name"))return 1;return 0},effect:(e)=>{if(e.includes("name"))return 1;return 0},mssql:(e)=>{if(e.includes("name"))return 1;return 0},cockroach:(e)=>{if(e.includes("name"))return 1;return 0},singlestore:(e)=>{if(e.includes("name"))return 1;return 0},sqlite:(e)=>{if(e.includes("name"))return 1;return 0}};function iF(e,t,r){if(t.all(f`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${e}`).length===0)return{newDb:!0};let n=t.all(f`SELECT name as column_name FROM pragma_table_info(${e})`),o=lT.sqlite(n.map((i)=>i.column_name));for(let i=o;i<cT.sqlite;i++){let s=K8[i];if(!s)throw Error(`No upgrade path from migration table version ${i} to ${i+1}`);s(e,t,r)}return{newDb:!1}}var K8={0:(e,t,r)=>{let n=f`${f.identifier(e)}`,o=t.all(f`SELECT id, hash, created_at FROM ${n} ORDER BY id ASC`);r.sort((l,d)=>l.folderMillis!==d.folderMillis?l.folderMillis-d.folderMillis:(l.name??"").localeCompare(d.name??""));let i=new Map,s=new Map;for(let l of r){if(!i.has(l.folderMillis))i.set(l.folderMillis,[]);i.get(l.folderMillis).push(l),s.set(l.hash,l)}let a=[],c=[];for(let l of o){let d=String(l.created_at),u=Number(d.substring(0,d.length-3)+"000"),m=i.get(u),h,S=null;if(m&&m.length===1)h=m[0],S="millis";else if(m&&m.length>1){if(h=m.find((x)=>x.hash&&l.hash&&x.hash===l.hash),h)S="hash"}else if(h=s.get(l.hash),h)S="hash";if(h)a.push({id:l.id,name:h.name,hash:l.hash,created_at:d,matchedBy:l.id?"id":S});else c.push(l)}if(c.length>0)throw Error(`While upgrading your database migrations table we found ${c.length} (${c.map((l)=>`[id: ${l.id}, created_at: ${l.created_at}]`).join(", ")}) migrations in the database that do not match any local migration. This means that some migrations were applied to the database but are missing from the local environment`);t.transaction((l)=>{l.run(f`ALTER TABLE ${n} ADD COLUMN ${f.identifier("name")} text`),l.run(f`ALTER TABLE ${n} ADD COLUMN ${f.identifier("applied_at")} TEXT`);for(let d of a){let u=f`UPDATE ${n} SET ${f.identifier("name")} = ${d.name}, ${f.identifier("applied_at")} = NULL WHERE`;if(d.id)u.append(f` ${f.identifier("id")} = ${d.id}`);else if(d.matchedBy==="millis")u.append(f` ${f.identifier("created_at")} = ${d.created_at}`);else u.append(f` ${f.identifier("hash")} = ${d.hash}`);l.run(u)}})}};async function sF(e,t,r){if((await t.session.all(f`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${e}`)).length===0)return{newDb:!0};let n=await t.session.all(f`SELECT name as column_name FROM pragma_table_info(${e})`),o=lT.sqlite(n.map((i)=>i.column_name));for(let i=o;i<cT.sqlite;i++){let s=V8[i];if(!s)throw Error(`No upgrade path from migration table version ${i} to ${i+1}`);await s(e,t,r)}return{newDb:!1}}var V8={0:async(e,t,r)=>{let n=f`${f.identifier(e)}`,o=await t.session.all(f`SELECT id, hash, created_at FROM ${n} ORDER BY id ASC`);r.sort((d,u)=>d.folderMillis!==u.folderMillis?d.folderMillis-u.folderMillis:(d.name??"").localeCompare(u.name??""));let i=new Map,s=new Map;for(let d of r){if(!i.has(d.folderMillis))i.set(d.folderMillis,[]);i.get(d.folderMillis).push(d),s.set(d.hash,d)}let a=[],c=[];for(let d of o){let u=String(d.created_at),m=Number(u.substring(0,u.length-3)+"000"),h=i.get(m),S,x=null;if(h&&h.length===1)S=h[0],x="millis";else if(h&&h.length>1){if(S=h.find((v)=>v.hash&&d.hash&&v.hash===d.hash),S)x="hash"}else if(S=s.get(d.hash),S)x="hash";if(S)a.push({id:d.id,name:S.name,hash:d.hash,created_at:u,matchedBy:d.id?"id":x});else c.push(d)}if(c.length>0)throw Error(`While upgrading your database migrations table we found ${c.length} (${c.map((d)=>`[id: ${d.id}, created_at: ${d.created_at}]`).join(", ")}) migrations in the database that do not match any local migration. This means that some migrations were applied to the database but are missing from the local environment`);let l=[f`ALTER TABLE ${n} ADD COLUMN ${f.identifier("name")} text`,f`ALTER TABLE ${n} ADD COLUMN ${f.identifier("applied_at")} TEXT`];for(let d of a){let u=f`UPDATE ${n} SET ${f.identifier("name")} = ${d.name}, ${f.identifier("applied_at")} = NULL WHERE`;if(d.id)u.append(f` ${f.identifier("id")} = ${d.id}`);else if(d.matchedBy==="millis")u.append(f` ${f.identifier("created_at")} = ${d.created_at}`);else u.append(f` ${f.identifier("hash")} = ${d.hash}`);l.push(u)}await t.transaction(async(d)=>{for(let u of l)await d.run(u)})}};var rm=class{static[T]="SQLiteDialect";constructor(e){}escapeName(e){return`"${e.replace(/"/g,'""')}"`}escapeParam(e){return"?"}escapeString(e){return`'${e.replace(/'/g,"''")}'`}buildWithCTE(e){if(!e?.length)return;let t=[f`with `];for(let[r,n]of e.entries())if(t.push(f`${f.identifier(n._.alias)} as (${n._.sql})`),r<e.length-1)t.push(f`, `);return t.push(f` `),f.join(t)}buildDeleteQuery({table:e,where:t,returning:r,withList:n,limit:o,orderBy:i}){let s=this.buildWithCTE(n),a=r?f` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0;return f`${s}delete from ${e}${t?f` where ${t}`:void 0}${a}${this.buildOrderBy(i)}${this.buildLimit(o)}`}buildUpdateSet(e,t){let r=e[de.Symbol.Columns],n=Object.keys(r).filter((i)=>t[i]!==void 0||r[i]?.onUpdateFn!==void 0),o=n.length;return f.join(n.flatMap((i,s)=>{let a=r[i],c=a.onUpdateFn?.(),l=t[i]??(j(c,me)?c:f.param(c,a)),d=f`${f.identifier(a.name)} = ${l}`;if(s<o-1)return[d,f.raw(", ")];return[d]}))}buildUpdateQuery({table:e,set:t,where:r,returning:n,withList:o,joins:i,from:s,limit:a,orderBy:c}){let l=this.buildWithCTE(o),d=this.buildUpdateSet(e,t),u=s&&f.join([f.raw(" from "),this.buildFromTable(s)]),m=this.buildJoins(i),h=n?f` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0;return f`${l}update ${e} set ${d}${u}${m}${r?f` where ${r}`:void 0}${h}${this.buildOrderBy(c)}${this.buildLimit(a)}`}buildSelection(e,{isSingleTable:t=!1}={}){let r=e.length,n=e.flatMap(({field:o},i)=>{let s=[];if(j(o,me.Aliased)&&o.isSelectionField){if(!t&&o.origin!==void 0)s.push(f.identifier(o.origin),f.raw("."));s.push(f.identifier(o.fieldAlias))}else if(j(o,me.Aliased)||j(o,me)){let a=j(o,me.Aliased)?o.sql:o;if(t){let c=new me(a.queryChunks.map((l)=>{if(j(l,at))return f.identifier(l.name);return l}));s.push(a.shouldInlineParams?c.inlineParams():c)}else s.push(a);if(j(o,me.Aliased))s.push(f` as ${f.identifier(o.fieldAlias)}`)}else if(j(o,at))if(o.columnType==="SQLiteNumericBigInt")if(t)s.push(o.isAlias?f`cast(${f.identifier(hu(o).name)} as text) as ${o}`:f`cast(${f.identifier(o.name)} as text)`);else s.push(o.isAlias?f`cast(${hu(o)} as text) as ${o}`:f`cast(${o} as text)`);else if(t)s.push(o.isAlias?f`${f.identifier(hu(o).name)} as ${o}`:f.identifier(o.name));else s.push(o.isAlias?f`${hu(o)} as ${o}`:o);else if(j(o,fr)){let a=Object.entries(o._.selectedFields);if(a.length===1){let c=a[0][1],l=j(c,me)?c.decoder:j(c,at)?{mapFromDriverValue:(d)=>c.mapFromDriverValue(d)}:c.sql.decoder;if(l)o._.sql.decoder=l}s.push(o)}if(i<r-1)s.push(f`, `);return s});return f.join(n)}buildJoins(e){if(!e||e.length===0)return;let t=[];if(e)for(let[r,n]of e.entries()){if(r===0)t.push(f` `);let o=n.table,i=n.on?f` on ${n.on}`:void 0;if(j(o,_n)){let s=o[_n.Symbol.Name],a=o[_n.Symbol.Schema],c=o[_n.Symbol.OriginalName],l=s===c?void 0:n.alias;t.push(f`${f.raw(n.joinType)} join ${a?f`${f.identifier(a)}.`:void 0}${f.identifier(c)}${l&&f` ${f.identifier(l)}`}${i}`)}else t.push(f`${f.raw(n.joinType)} join ${o}${i}`);if(r<e.length-1)t.push(f` `)}return f.join(t)}buildLimit(e){return typeof e==="object"||typeof e==="number"&&e>=0?f` limit ${e}`:void 0}buildOrderBy(e){let t=[];if(e){for(let[r,n]of e.entries())if(t.push(n),r<e.length-1)t.push(f`, `)}return t.length>0?f` order by ${f.join(t)}`:void 0}buildFromTable(e){if(j(e,de)&&e[de.Symbol.IsAlias])return f`${f`${f.identifier(e[de.Symbol.Schema]??"")}.`.if(e[de.Symbol.Schema])}${f.identifier(e[de.Symbol.OriginalName])} ${f.identifier(e[de.Symbol.Name])}`;if(j(e,Lr)&&e[Ot].isAlias){let t=f`${f.identifier(e[Ot].originalName)}`;if(e[Ot].schema)t=f`${f.identifier(e[Ot].schema)}.${t}`;return f`${t} ${f.identifier(e[Ot].name)}`}return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:r,where:n,having:o,table:i,joins:s,orderBy:a,groupBy:c,limit:l,offset:d,distinct:u,setOperators:m}){let h=r??vi(t);for(let B of h)if(j(B.field,at)&&ra(B.field.table)!==(j(i,fr)?i._.alias:j(i,Za)?i[Ot].name:j(i,me)?void 0:ra(i))&&!((J)=>s?.some(({alias:G})=>G===(J[de.Symbol.IsAlias]?ra(J):J[de.Symbol.BaseName])))(B.field.table)){let J=ra(B.field.table);throw Error(`Your "${B.path.join("->")}" field references a column "${J}"."${B.field.name}", but the table "${J}" is not part of the query! Did you forget to join it?`)}let S=!s||s.length===0,x=this.buildWithCTE(e),v=u?f` distinct`:void 0,w=this.buildSelection(h,{isSingleTable:S}),P=this.buildFromTable(i),F=this.buildJoins(s),R=n?f` where ${n}`:void 0,b=o?f` having ${o}`:void 0,A=[];if(c){for(let[B,J]of c.entries())if(A.push(J),B<c.length-1)A.push(f`, `)}let D=f`${x}select${v} ${w} from ${P}${F}${R}${A.length>0?f` group by ${f.join(A)}`:void 0}${b}${this.buildOrderBy(a)}${this.buildLimit(l)}${d?f` offset ${d}`:void 0}`;if(m.length>0)return this.buildSetOperations(D,m);return D}buildSetOperations(e,t){let[r,...n]=t;if(!r)throw Error("Cannot pass undefined values to any set operator");if(n.length===0)return this.buildSetOperationQuery({leftSelect:e,setOperator:r});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:r}),n)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:r,rightSelect:n,limit:o,orderBy:i,offset:s}}){let a=f`${e.getSQL()} `,c=f`${n.getSQL()}`,l;if(i&&i.length>0){let h=[];for(let S of i)if(j(S,$r))h.push(f.identifier(S.name));else if(j(S,me)){for(let x=0;x<S.queryChunks.length;x++){let v=S.queryChunks[x];if(j(v,$r))S.queryChunks[x]=f.identifier(v.name)}h.push(f`${S}`)}else h.push(f`${S}`);l=f` order by ${f.join(h,f`, `)}`}let d=typeof o==="object"||typeof o==="number"&&o>=0?f` limit ${o}`:void 0,u=f.raw(`${t} ${r?"all ":""}`),m=s?f` offset ${s}`:void 0;return f`${a}${u}${c}${l}${d}${m}`}buildInsertQuery({table:e,values:t,onConflict:r,returning:n,withList:o,select:i}){let s=[],a=e[de.Symbol.Columns],c=Object.entries(a).filter(([h,S])=>!S.shouldDisableInsert()),l=c.map(([,h])=>f.identifier(h.name));if(i){let h=t;if(j(h,me))s.push(h);else s.push(h.getSQL())}else{let h=t;s.push(f.raw("values "));for(let[S,x]of h.entries()){let v=[];for(let[w,P]of c){let F=x[w];if(F===void 0||j(F,jn)&&F.value===void 0){let R;if(P.default!==null&&P.default!==void 0)R=j(P.default,me)?P.default:f.param(P.default,P);else if(P.defaultFn!==void 0){let b=P.defaultFn();R=j(b,me)?b:f.param(b,P)}else if(!P.default&&P.onUpdateFn!==void 0){let b=P.onUpdateFn();R=j(b,me)?b:f.param(b,P)}else R=f`null`;v.push(R)}else v.push(F)}if(s.push(v),S<h.length-1)s.push(f`, `)}}let d=this.buildWithCTE(o),u=f.join(s),m=n?f` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0;return f`${d}insert into ${e} ${l} ${u}${r?.length?f.join(r):void 0}${m}`}sqlToQuery(e,t){return e.toQuery({escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:t})}_buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:n,tableConfig:o,queryConfig:i,tableAlias:s,nestedQueryRelation:a,joinOn:c}){let l=[],d,u,m=[],h,S=[];if(i===!0)l=Object.entries(o.columns).map(([v,w])=>({dbKey:w.name,tsKey:v,field:Wi(w,s),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let v=Object.fromEntries(Object.entries(o.columns).map(([A,D])=>[A,Wi(D,s)]));if(i.where){let A=typeof i.where==="function"?i.where(v,$N()):i.where;h=A&&yu(A,s)}let w=[],P=[];if(i.columns){let A=!1;for(let[D,B]of Object.entries(i.columns)){if(B===void 0)continue;if(D in o.columns){if(!A&&B===!0)A=!0;P.push(D)}}if(P.length>0)P=A?P.filter((D)=>i.columns?.[D]===!0):Object.keys(o.columns).filter((D)=>!P.includes(D))}else P=Object.keys(o.columns);for(let A of P){let D=o.columns[A];w.push({tsKey:A,value:D})}let F=[];if(i.with)F=Object.entries(i.with).filter((A)=>!!A[1]).map(([A,D])=>({tsKey:A,queryConfig:D,relation:o.relations[A]}));let R;if(i.extras){R=typeof i.extras==="function"?i.extras(v,{sql:f}):i.extras;for(let[A,D]of Object.entries(R))w.push({tsKey:A,value:nS(D,s)})}for(let{tsKey:A,value:D}of w)l.push({dbKey:j(D,me.Aliased)?D.fieldAlias:o.columns[A].name,tsKey:A,field:j(D,at)?Wi(D,s):D,relationTableTsKey:void 0,isJson:!1,selection:[]});let b=typeof i.orderBy==="function"?i.orderBy(v,qN()):i.orderBy??[];if(!Array.isArray(b))b=[b];m=b.map((A)=>{if(j(A,at))return Wi(A,s);return yu(A,s)}),d=i.limit,u=i.offset;for(let{tsKey:A,queryConfig:D,relation:B}of F){let J=HN(t,r,B),G=r[hl(B.referencedTable)],ce=`${s}_${A}`,re=_(...J.fields.map((te,Ne)=>p(Wi(J.references[Ne],ce),Wi(te,s)))),Z=this._buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:e[G],tableConfig:t[G],queryConfig:j(B,Eu)?D===!0?{limit:1}:{...D,limit:1}:D,tableAlias:ce,joinOn:re,nestedQueryRelation:B}),se=f`(${Z.sql})`.as(A);l.push({dbKey:A,tsKey:A,field:se,relationTableTsKey:G,isJson:!0,selection:Z.selection})}}if(l.length===0)throw new ia({message:`No fields selected for table "${o.tsName}" ("${s}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});let x;if(h=_(c,h),a){let v=f`json_array(${f.join(l.map(({field:P})=>j(P,$r)?f.identifier(P.name):j(P,me.Aliased)?P.sql:P),f`, `)})`;if(j(a,ZE))v=f`coalesce(json_group_array(${v}), json_array())`;let w=[{dbKey:"data",tsKey:"data",field:v.as("data"),isJson:!0,relationTableTsKey:o.tsName,selection:l}];if(d!==void 0||u!==void 0||m.length>0)x=this.buildSelectQuery({table:Hn(n,s),fields:{},fieldsFlat:[{path:[],field:f.raw("*")}],where:h,limit:d,offset:u,orderBy:m,setOperators:[]}),h=void 0,d=void 0,u=void 0,m=void 0;else x=Hn(n,s);x=this.buildSelectQuery({table:j(x,_n)?x:new fr(x,{},s),fields:{},fieldsFlat:w.map(({field:P})=>({path:[],field:j(P,at)?Wi(P,s):P})),joins:S,where:h,limit:d,offset:u,orderBy:m,setOperators:[]})}else x=this.buildSelectQuery({table:Hn(n,s),fields:{},fieldsFlat:l.map(({field:v})=>({path:[],field:j(v,at)?Wi(v,s):v})),joins:S,where:h,limit:d,offset:u,orderBy:m,setOperators:[]});return{tableTsKey:o.tsName,sql:x,selection:l}}nestedSelectionerror(){throw new ia({message:"Views with nested selections are not supported by the relational query builder"})}buildRqbColumn(e,t,r){if(j(t,at)){let n=f`${e}.${f.identifier(t.name)}`;switch(t.columnType){case"SQLiteBigInt":case"SQLiteBlobJson":case"SQLiteBlobBuffer":return f`hex(${n}) as ${f.identifier(r)}`;case"SQLiteNumeric":case"SQLiteNumericNumber":case"SQLiteNumericBigInt":return f`cast(${n} as text) as ${f.identifier(r)}`;case"SQLiteCustomColumn":return f`${t.jsonSelectIdentifier(n,f)} as ${f.identifier(r)}`;default:return f`${n} as ${f.identifier(r)}`}}return f`${e}.${j(t,me.Aliased)?f.identifier(t.fieldAlias):na(t)?f.identifier(r):this.nestedSelectionerror()} as ${f.identifier(r)}`}unwrapAllColumns=(e,t)=>f.join(Object.entries(e[_o]).map(([r,n])=>(t.push({key:r,field:n}),this.buildRqbColumn(e,n,r))),f`, `);getSelectedTableColumns=(e,t)=>{let r=[],n=e[_o],o=Object.entries(t),i;for(let[s,a]of o){if(a===void 0)continue;if(i=i||a,a){let c=n[s];r.push({column:c,tsName:s})}}if(i===!1)for(let[s,a]of Object.entries(n)){if(t[s]===!1)continue;r.push({column:a,tsName:s})}return r};buildColumns=(e,t,r)=>r?.columns?(()=>{let n=[],o=this.getSelectedTableColumns(e,r?.columns);for(let{column:i,tsName:s}of o)n.push(this.buildRqbColumn(e,i,s)),t.push({key:s,field:i});return n.length?f.join(n,f`, `):void 0})():this.unwrapAllColumns(e,t);buildRelationalQuery({schema:e,table:t,tableConfig:r,queryConfig:n,relationWhere:o,mode:i,isNested:s,errorPath:a,depth:c,throughJoin:l,jsonb:d}){let u=[],m=i==="first",h=n===!0?void 0:n,S=a??"",x=c??0;if(!x)t=Hn(t,`d${x}`);let v=m?1:h?.limit,w=h?.offset,P=this.buildColumns(t,u,h),F=h?.where&&o?_(ys(t,h.where,r.relations,e),o):h?.where?ys(t,h.where,r.relations,e):o,R=h?.orderBy?iT(t,h.orderBy):void 0,b=h?.extras?sT(t,h.extras):void 0;if(b)u.push(...b.selection);let A=h?(()=>{let{with:B}=h;if(!B)return;let J=Object.entries(B).filter(([G,ce])=>ce);if(!J.length)return;return f.join(J.map(([G,ce])=>{let re=r.relations[G],Z=j(re,tm),se=Hn(re.targetTable,`d${x+1}`),te=re.throughTable?Hn(re.throughTable,`tr${x}`):void 0,{filter:Ne,joinCondition:ze}=_S(re,t,se,te),et=te?f` inner join ${sc(te)} on ${ze}`:void 0,xt=this.buildRelationalQuery({table:se,mode:Z?"first":"many",schema:e,queryConfig:ce,tableConfig:e[re.targetTableName],relationWhere:Ne,isNested:!0,errorPath:`${S.length?`${S}.`:""}${G}`,depth:x+1,throughJoin:et,jsonb:d});u.push({field:se,key:G,selection:xt.selection,isArray:!Z,isOptional:(re.optional??!1)||ce!==!0&&!!ce.where});let dt=f.join(xt.selection.map((fe)=>f`${f.raw(this.escapeString(fe.key))}, ${fe.selection?f`${d}(${f.identifier(fe.key)})`:f.identifier(fe.key)}`),f`, `),Le=s?d:f`json`;return Z?f`(select ${Le}_object(${dt}) as ${f.identifier("r")} from (${xt.sql}) as ${f.identifier("t")}) as ${f.identifier(G)}`:f`coalesce((select ${Le}_group_array(json_object(${dt})) as ${f.identifier("r")} from (${xt.sql}) as ${f.identifier("t")}), ${d}_array()) as ${f.identifier(G)}`}),f`, `)})():void 0,D=[P,b?.sql,A].filter((B)=>B!==void 0);if(!D.length)throw new ia({message:`No fields selected for table "${r.name}"${S?` ("${S}")`:""}`});return{sql:f`select ${f.join(D,f`, `)} from ${sc(t)}${l}${f` where ${F}`.if(F)}${f` order by ${R}`.if(R)}${f` limit ${v}`.if(v!==void 0)}${f` offset ${w}`.if(w!==void 0)}`,selection:u}}},aF=class extends rm{static[T]="SQLiteSyncDialect";migrate(e,t,r){let n=r===void 0?"__drizzle_migrations":typeof r==="string"?"__drizzle_migrations":r.migrationsTable??"__drizzle_migrations",{newDb:o}=iF(n,t,e);if(o){let a=f`
|
|
61
|
+
CREATE TABLE IF NOT EXISTS ${f.identifier(n)} (
|
|
62
|
+
id INTEGER PRIMARY KEY,
|
|
63
|
+
hash text NOT NULL,
|
|
64
|
+
created_at numeric,
|
|
65
|
+
name text,
|
|
66
|
+
applied_at TEXT
|
|
67
|
+
)`;t.run(a)}let i=t.all(f`SELECT id, hash, created_at, name FROM ${f.identifier(n)}`);if(typeof r==="object"&&r.init){if(i.length)return{exitCode:"databaseMigrations"};if(e.length>1)return{exitCode:"localMigrations"};let[a]=e;if(!a)return;t.run(f`insert into ${f.identifier(n)} ("hash", "created_at", "name", "applied_at") values(${a.hash}, ${a.folderMillis}, ${a.name}, ${new Date().toISOString()})`);return}let s=aT({localMigrations:e,dbMigrations:i});t.run(f`BEGIN`);try{for(let a of s){for(let c of a.sql)t.run(f.raw(c));t.run(f`INSERT INTO ${f.identifier(n)} ("hash", "created_at", "name", "applied_at") values(${a.hash}, ${a.folderMillis}, ${a.name}, ${new Date().toISOString()})`)}t.run(f`COMMIT`)}catch(a){throw t.run(f`ROLLBACK`),a}}},cF=class extends rm{static[T]="SQLiteAsyncDialect";async migrate(e,t,r){let n=r===void 0?"__drizzle_migrations":typeof r==="string"?"__drizzle_migrations":r.migrationsTable??"__drizzle_migrations",{newDb:o}=await sF(n,t,e);if(o){let a=f`
|
|
68
|
+
CREATE TABLE IF NOT EXISTS ${f.identifier(n)} (
|
|
69
|
+
id INTEGER PRIMARY KEY,
|
|
70
|
+
hash text NOT NULL,
|
|
71
|
+
created_at numeric,
|
|
72
|
+
name text,
|
|
73
|
+
applied_at TEXT
|
|
74
|
+
)
|
|
75
|
+
`;await t.session.run(a)}let i=await t.session.all(f`SELECT id, hash, created_at, name FROM ${f.identifier(n)};`);if(typeof r==="object"&&r.init){if(i.length)return{exitCode:"databaseMigrations"};if(e.length>1)return{exitCode:"localMigrations"};let[a]=e;if(!a)return;await t.session.run(f`insert into ${f.identifier(n)} ("hash", "created_at", "name", "applied_at") values(${a.hash}, ${a.folderMillis}, ${a.name}, ${new Date().toISOString()})`);return}let s=aT({localMigrations:e,dbMigrations:i});await t.session.transaction(async(a)=>{for(let c of s){for(let l of c.sql)await a.run(f.raw(l));await a.run(f`insert into ${f.identifier(n)} ("hash", "created_at", "name", "applied_at") values(${c.hash}, ${c.folderMillis}, ${c.name}, ${new Date().toISOString()})`)}})}};var Rl=class{static[T]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=j(e,rm)?e:void 0,this.dialectConfig=j(e,rm)?void 0:e}$with=(e,t)=>{let r=this;return{as:(o)=>{if(typeof o==="function")o=o(r);return new Proxy(new tS(o.getSQL(),t??("getSelectedFields"in o?o.getSelectedFields()??{}:{}),e,!0),new qr({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(o){return new xi({fields:o??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function n(o){return new xi({fields:o??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:n}}select(e){return new xi({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new xi({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new aF(this.dialectConfig);return this.dialect}};var dT=class{static[T]="SQLiteViewBuilderCore";constructor(e){this.name=e}config={}},lF=class extends dT{static[T]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new Rl);let t=new qr({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new kS({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}},dF=class extends dT{static[T]="SQLiteManualViewBuilder";columns;constructor(e,t,r){super(e);this.columns=cS(fS(e,t,void 0,void 0,r))}existing(){return new Proxy(new kS({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new qr({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new kS({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new qr({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}},kS=class extends Za{static[T]="SQLiteView";constructor({config:e}){super(e)}};function uF(e){return(t,r)=>{if(r)return new dF(t,r,e);return new lF(t)}}var Al=uF(void 0);var fF=class{static[T]="SQLiteAsyncRelationalQueryBuilder";constructor(e,t,r,n,o,i,s,a){this.mode=e,this.fullSchema=t,this.schema=r,this.tableNamesMap=n,this.table=o,this.tableConfig=i,this.dialect=s,this.session=a}findMany(e){return this.mode==="sync"?new pF(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new uT(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new pF(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new uT(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}},uT=class extends cn{static[T]="SQLiteAsyncRelationalQuery";mode;constructor(e,t,r,n,o,i,s,a,c){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=n,this.tableConfig=o,this.dialect=i,this.session=s,this.config=a,this.mode=c}getSQL(){return this.dialect._buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){let{query:t,builtQuery:r}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](r,void 0,this.mode==="first"?"get":"all",(n,o)=>{let i=n.map((s)=>PS(this.schema,this.tableConfig,s,t.selection,o));if(this.mode==="first")return i[0];return i})}prepare(){return this._prepare(!1)}_toSQL(){let e=this.dialect._buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName});return{query:e,builtQuery:this.dialect.sqlToQuery(e.sql)}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}},pF=class extends uT{static[T]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}};var OS=class e extends me{static[T]="SQLiteCountBuilder";dialect;session;static buildCount(t,r,n){let o=f`select count(*) from ${t}${f` where ${r}`.if(r)}`;return n?f`(${o})`:o}constructor(t){super(e.buildCount(t.source,t.filters,!0).queryChunks);this.countConfig=t,this.dialect=t.dialect,this.session=t.session,this.mapWith((r)=>{if(typeof r==="number")return r;return Number(r??0)})}executableSql;build(){if(!this.executableSql){let{source:t,filters:r}=this.countConfig;this.executableSql=e.buildCount(t,r)}return this.dialect.sqlToQuery(this.executableSql)}executeRaw(t){return this.session.prepareOneTimeQuery(this.build(),void 0,"get",(r)=>{let n=r[0]?.[0];if(typeof n==="number")return n;return n?Number(n):0}).get(t)}async execute(t){return await this.executeRaw(t)}},mF=class extends OS{static[T]="SQLiteSyncCountBuilder";sync(e){return this.executeRaw(e)}};aS(OS,[cn]);var hF=class{static[T]="SQLiteAsyncRelationalQueryBuilderV2";constructor(e,t,r,n,o,i,s,a){this.mode=e,this.schema=t,this.table=r,this.tableConfig=n,this.dialect=o,this.session=i,this.rowMode=s,this.forbidJsonb=a}findMany(e){return this.mode==="sync"?new yF(this.schema,this.table,this.tableConfig,this.dialect,this.session,e??!0,"many",this.rowMode,this.forbidJsonb):new pT(this.schema,this.table,this.tableConfig,this.dialect,this.session,e??!0,"many",this.rowMode,this.forbidJsonb)}findFirst(e){return this.mode==="sync"?new yF(this.schema,this.table,this.tableConfig,this.dialect,this.session,e??!0,"first",this.rowMode,this.forbidJsonb):new pT(this.schema,this.table,this.tableConfig,this.dialect,this.session,e??!0,"first",this.rowMode,this.forbidJsonb)}},pT=class extends cn{static[T]="SQLiteAsyncRelationalQueryV2";mode;table;constructor(e,t,r,n,o,i,s,a,c){super();this.schema=e,this.tableConfig=r,this.dialect=n,this.session=o,this.config=i,this.rowMode=a,this.forbidJsonb=c,this.mode=s,this.table=t}getSQL(){return this.dialect.buildRelationalQuery({schema:this.schema,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,mode:this.mode,jsonb:this.forbidJsonb?f`json`:f`jsonb`}).sql}_prepare(e=!0){let{query:t,builtQuery:r}=this._toSQL();return this.session[e?"prepareOneTimeRelationalQuery":"prepareRelationalQuery"](r,void 0,this.mode==="first"?"get":"all",rT({isFirst:this.mode==="first",parseJson:!this.rowMode,parseJsonIfString:!1,rootJsonMappers:!0,selection:t.selection}),{isFirst:this.mode==="first",parseJson:!this.rowMode,parseJsonIfString:!1,rootJsonMappers:!0,selection:t.selection})}prepare(){return this._prepare(!1)}_getQuery(){let e=this.forbidJsonb?f`json`:f`jsonb`,t=this.dialect.buildRelationalQuery({schema:this.schema,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,mode:this.mode,isNested:this.rowMode,jsonb:e});if(this.rowMode)t.sql=f`select json_object(${f.join(t.selection.map((r)=>f`${f.raw(this.dialect.escapeString(r.key))}, ${r.selection?f`${e}(${f.identifier(r.key)})`:f.identifier(r.key)}`),f`, `)}) as ${f.identifier("r")} from (${t.sql}) as ${f.identifier("t")}`;return t}_toSQL(){let e=this._getQuery();return{query:e,builtQuery:this.dialect.sqlToQuery(e.sql)}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare().get();return this._prepare().all()}async execute(){return this.executeRaw()}},yF=class extends pT{static[T]="SQLiteSyncRelationalQueryV2";sync(){return this.executeRaw()}};var nm=class extends cn{static[T]="SQLiteRaw";config;constructor(e,t,r,n,o){super();this.execute=e,this.getSQL=t,this.dialect=n,this.mapBatchResult=o,this.config={action:r}}getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}};var DS=class extends cn{static[T]="SQLiteDelete";config;constructor(e,t,r,n){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:n}}where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[de.Symbol.Columns],new qr({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[_n.Symbol.Columns]){return this.config.returning=vi(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){return this.dialect.sqlToQuery(this.getSQL())}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",void 0,{type:"delete",tables:Ki(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(e){return this._prepare().execute(e)}$dynamic(){return this}};var NS=class{static[T]="SQLiteInsertBuilder";constructor(e,t,r,n){this.table=e,this.session=t,this.dialect=r,this.withList=n}values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error("values() must be called with at least one value");let t=e.map((r)=>{let n={},o=this.table[de.Symbol.Columns];for(let i of Object.keys(r)){let s=r[i];n[i]=j(s,me)?s:new jn(s,o[i])}return n});return new fT(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new Rl):e;if(!j(t,me)&&!Xf(this.table[_o],t._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new fT(this.table,t,this.session,this.dialect,this.withList,!0)}},fT=class extends cn{static[T]="SQLiteInsert";config;constructor(e,t,r,n,o,i){super();this.session=r,this.dialect=n,this.config={table:e,values:t,withList:o,select:i}}returning(e=this.config.table[_n.Symbol.Columns]){return this.config.returning=vi(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(f` on conflict do nothing`);else{let t=Array.isArray(e.target)?f`${e.target}`:f`${[e.target]}`,r=e.where?f` where ${e.where}`:f``;this.config.onConflict.push(f` on conflict ${t} do nothing${r}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let t=e.where?f` where ${e.where}`:void 0,r=e.targetWhere?f` where ${e.targetWhere}`:void 0,n=e.setWhere?f` where ${e.setWhere}`:void 0,o=Array.isArray(e.target)?f`${e.target}`:f`${[e.target]}`,i=this.dialect.buildUpdateSet(this.config.table,sS(this.config.table,e.set));return this.config.onConflict.push(f` on conflict ${o}${r} do update set ${i}${t}${n}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){return this.dialect.sqlToQuery(this.getSQL())}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",void 0,{type:"insert",tables:Ki(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}};var FS=class{static[T]="SQLiteUpdateBuilder";constructor(e,t,r,n){this.table=e,this.session=t,this.dialect=r,this.withList=n}set(e){return new gF(this.table,sS(this.table,e),this.session,this.dialect,this.withList)}},gF=class extends cn{static[T]="SQLiteUpdate";config;constructor(e,t,r,n,o){super();this.session=r,this.dialect=n,this.config={set:t,table:e,withList:o,joins:[]}}from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let n=Zf(t);if(typeof n==="string"&&this.config.joins.some((o)=>o.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(typeof r==="function"){let o=this.config.from?j(t,_n)?t[de.Symbol.Columns]:j(t,fr)?t._.selectedFields:j(t,Za)?t[Ot].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[de.Symbol.Columns],new qr({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),o&&new Proxy(o,new qr({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:t,joinType:e,alias:n}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[de.Symbol.Columns],new qr({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.config.table[_n.Symbol.Columns]){return this.config.returning=vi(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){return this.dialect.sqlToQuery(this.getSQL())}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",void 0,{type:"insert",tables:Ki(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}};var US=class{static[T]="BaseSQLiteDatabase";_query;query;constructor(e,t,r,n,o,i,s){this.resultKind=e,this.dialect=t,this.session=r,this.rowModeRQB=i,this.forbidJsonb=s,this._=o?{schema:o.schema,fullSchema:o.fullSchema,tableNamesMap:o.tableNamesMap,relations:n}:{schema:void 0,fullSchema:{},tableNamesMap:{},relations:n},this._query={};let a=this._query;if(this._.schema)for(let[c,l]of Object.entries(this._.schema))a[c]=new fF(e,o.fullSchema,this._.schema,this._.tableNamesMap,o.fullSchema[c],l,t,r);this.query={};for(let[c,l]of Object.entries(n))this.query[c]=new hF(e,n,n[l.name].table,l,t,r,i,s);this.$cache={invalidate:async(c)=>{}}}$with=(e,t)=>{let r=this;return{as:(o)=>{if(typeof o==="function")o=o(new Rl(r.dialect));return new Proxy(new tS(o.getSQL(),t??("getSelectedFields"in o?o.getSelectedFields()??{}:{}),e,!0),new qr({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return this.resultKind==="async"?new OS({source:e,filters:t,session:this.session,dialect:this.dialect}):new mF({source:e,filters:t,session:this.session,dialect:this.dialect})}with(...e){let t=this;function r(a){return new xi({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function n(a){return new xi({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function o(a){return new FS(a,t.session,t.dialect,e)}function i(a){return new NS(a,t.session,t.dialect,e)}function s(a){return new DS(a,t.session,t.dialect,e)}return{select:r,selectDistinct:n,update:o,insert:i,delete:s}}select(e){return new xi({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new xi({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new FS(e,this.session,this.dialect)}$cache;insert(e){return new NS(e,this.session,this.dialect)}delete(e){return new DS(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?f.raw(e):e.getSQL();if(this.resultKind==="async")return new nm(async()=>this.session.run(t),()=>t,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(t)}all(e){let t=typeof e==="string"?f.raw(e):e.getSQL();if(this.resultKind==="async")return new nm(async()=>this.session.all(t),()=>t,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(t)}get(e){let t=typeof e==="string"?f.raw(e):e.getSQL();if(this.resultKind==="async")return new nm(async()=>this.session.get(t),()=>t,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(t)}values(e){let t=typeof e==="string"?f.raw(e):e.getSQL();if(this.resultKind==="async")return new nm(async()=>this.session.values(t),()=>t,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session));return this.session.values(t)}transaction(e,t){return this.session.transaction(e,t)}};var SF=class{static[T]="Cache"},om=class extends SF{static[T]="NoopCache";strategy(){return"all"}async get(e){}async put(e,t,r,n){}async onMutate(e){}};async function BS(e,t){let r=`${e}-${JSON.stringify(t,(i,s)=>typeof s==="bigint"?`${s}n`:s)}`,n=new TextEncoder().encode(r),o=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(o)].map((i)=>i.toString(16).padStart(2,"0")).join("")}var vF=class extends cn{static[T]="ExecuteResultSync";constructor(e){super();this.resultCb=e}async execute(){return this.resultCb()}sync(){return this.resultCb()}},mT=class{static[T]="PreparedQuery";joinsNotNullableMap;constructor(e,t,r,n,o,i){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=n,this.queryMetadata=o,this.cacheConfig=i,n&&n.strategy()==="all"&&i===void 0)this.cacheConfig={enabled:!0,autoInvalidate:!0};if(!this.cacheConfig?.enabled)this.cacheConfig=void 0}async queryWithCache(e,t,r){if(this.cache===void 0||j(this.cache,om)||this.queryMetadata===void 0)try{return await r()}catch(n){throw new bl(e,t,n)}if(this.cacheConfig&&!this.cacheConfig.enabled)try{return await r()}catch(n){throw new bl(e,t,n)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[n]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return n}catch(n){throw new bl(e,t,n)}if(!this.cacheConfig)try{return await r()}catch(n){throw new bl(e,t,n)}if(this.queryMetadata.type==="select"){let n=await this.cache.get(this.cacheConfig.tag??await BS(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(n===void 0){let o;try{o=await r()}catch(i){throw new bl(e,t,i)}return await this.cache.put(this.cacheConfig.tag??await BS(e,t),o,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),o}return n}try{return await r()}catch(n){throw new bl(e,t,n)}}getQuery(){return this.query}mapRunResult(e,t){return e}mapAllResult(e,t){throw Error("Not implemented")}mapGetResult(e,t){throw Error("Not implemented")}execute(e){if(this.mode==="async")return this[this.executeMethod](e);return new vF(()=>this[this.executeMethod](e))}mapResult(e,t){switch(this.executeMethod){case"run":return this.mapRunResult(e,t);case"all":return this.mapAllResult(e,t);case"get":return this.mapGetResult(e,t)}}},yT=class{static[T]="SQLiteSession";constructor(e){this.dialect=e}prepareOneTimeQuery(e,t,r,n,o,i){return this.prepareQuery(e,t,r,n,o,i)}prepareOneTimeRelationalQuery(e,t,r,n,o){return this.prepareRelationalQuery(e,t,r,n,o)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run").run()}catch(r){throw new ia({cause:r,message:`Failed to run the query '${t.sql}'`})}}extractRawRunValueFromBatchResult(e){return e}all(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run").all()}extractRawAllValueFromBatchResult(e){throw Error("Not implemented")}get(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run").get()}extractRawGetValueFromBatchResult(e){throw Error("Not implemented")}values(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run").values()}extractRawValuesValueFromBatchResult(e){throw Error("Not implemented")}},hT=class extends US{static[T]="SQLiteTransaction";constructor(e,t,r,n,o,i=0,s,a){super(e,t,r,n,o,s,a);this.relations=n,this.schema=o,this.nestedIndex=i}rollback(){throw new KN}};var Q8=class{static[T]="ConsoleLogWriter";write(e){console.log(e)}},xF=class{static[T]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new Q8}logQuery(e,t){let r=t.map((o)=>{try{return JSON.stringify(o)}catch{return String(o)}}),n=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${n}`)}},wF=class{static[T]="NoopLogger";logQuery(){}};var EF=class extends yT{static[T]="SQLiteRemoteSession";logger;cache;constructor(e,t,r,n,o,i={}){super(t);this.client=e,this.relations=r,this.schema=n,this.batchCLient=o,this.options=i,this.logger=i.logger??new wF,this.cache=i.cache??new om}prepareQuery(e,t,r,n,o,i){return new bF(this.client,e,this.logger,this.cache,o,i,t,r,this.options.useJitMappers,n)}prepareRelationalQuery(e,t,r,n,o){return new bF(this.client,e,this.logger,this.cache,void 0,void 0,t,r,this.options.useJitMappers,n,!0,o)}async batch(e){let t=[],r=[];for(let n of e){let o=n._prepare(),i=o.getQuery();t.push(o),r.push({sql:i.sql,params:i.params,method:i.method})}return(await this.batchCLient(r)).map((n,o)=>t[o].mapResult(n,!0))}async transaction(e,t){let r=new J8("async",this.dialect,this,this.relations,this.schema,void 0,!0);await this.run(f.raw(`begin${t?.behavior?" "+t.behavior:""}`));try{let n=await e(r);return await this.run(f`commit`),n}catch(n){throw await this.run(f`rollback`),n}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}},J8=class e extends hT{static[T]="SQLiteProxyTransaction";async transaction(t){let r=`sp${this.nestedIndex}`,n=new e("async",this.dialect,this.session,this.relations,this.schema,this.nestedIndex+1,!0);await this.session.run(f.raw(`savepoint ${r}`));try{let o=await t(n);return await this.session.run(f.raw(`release savepoint ${r}`)),o}catch(o){throw await this.session.run(f.raw(`rollback to savepoint ${r}`)),o}}},bF=class extends mT{static[T]="SQLiteProxyPreparedQuery";method;jitMapper;constructor(e,t,r,n,o,i,s,a,c,l,d,u){super("async",a,t,n,o,i);this.client=e,this.logger=r,this.fields=s,this.useJitMappers=c,this.customResultMapper=l,this.isRqbV2Query=d,this.rqbConfig=u,this.method=a}getQuery(){return{...this.query,method:this.method}}async run(e){let t=oa(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>await this.client(this.query.sql,t,"run"))}mapAllResult(e,t){if(t)e=e.rows;if(!this.fields&&!this.customResultMapper)return e;if(this.isRqbV2Query){for(let r=0;r<e.length;++r)e[r]=JSON.parse(e[r]);return this.useJitMappers?(this.jitMapper=this.jitMapper??CS(this.rqbConfig))(e):this.customResultMapper(e)}if(this.customResultMapper)return this.customResultMapper(e);return this.useJitMappers?(this.jitMapper=this.jitMapper??jE(this.fields,this.joinsNotNullableMap))(e):e.map((r)=>qE(this.fields,r,this.joinsNotNullableMap))}async all(e){if(this.isRqbV2Query)return this.allRqbV2(e);let{query:t,logger:r,client:n}=this,o=oa(t.params,e??{});r.logQuery(t.sql,o);let{rows:i}=await this.queryWithCache(t.sql,o,async()=>await n(t.sql,o,"all"));return this.mapAllResult(i)}async get(e){if(this.isRqbV2Query)return this.getRqbV2(e);let{query:t,logger:r,client:n}=this,o=oa(t.params,e??{});r.logQuery(t.sql,o);let i=await this.queryWithCache(t.sql,o,async()=>await n(t.sql,o,"get"));return this.mapGetResult(i.rows)}async allRqbV2(e){let{query:t,logger:r,client:n}=this,o=oa(t.params,e??{});r.logQuery(t.sql,o);let{rows:i}=await n(t.sql,o,"all");return this.mapAllResult(i)}async getRqbV2(e){let{query:t,logger:r,client:n}=this,o=oa(t.params,e??{});r.logQuery(t.sql,o);let{rows:i}=await n(t.sql,o,"get");return this.mapGetResult(i)}mapGetResult(e,t){if(t)e=e.rows;let r=e;if(!this.fields&&!this.customResultMapper)return r;if(!r)return;if(this.isRqbV2Query)return this.useJitMappers?(this.jitMapper=this.jitMapper??CS(this.rqbConfig))([JSON.parse(r)]):this.customResultMapper([JSON.parse(r)]);if(this.customResultMapper)return this.customResultMapper([e]);return this.useJitMappers?(this.jitMapper=this.jitMapper??jE(this.fields,this.joinsNotNullableMap))([r])[0]:qE(this.fields,r,this.joinsNotNullableMap)}async values(e){let t=oa(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),(await this.queryWithCache(this.query.sql,t,async()=>await this.client(this.query.sql,t,"values"))).rows}};var TF=class extends US{static[T]="SqliteRemoteDatabase";async batch(e){return this.session.batch(e)}};function gT(e,t,r){let n=new cF,o,i,s,a={};if(t){if(typeof t==="function")s=t,a=r??{};else s=void 0,a=t;if(a.logger===!0)o=new xF;else if(a.logger!==!1)o=a.logger,i=a.cache}let c;if(a.schema){let u=jN(a.schema,WN);c={fullSchema:a.schema,schema:u.tables,tableNamesMap:u.tableNamesMap}}let l=a.relations??{},d=new TF("async",n,new EF(e,n,l,c,s,{logger:o,cache:i,useJitMappers:RD(a.jit)}),l,c,!0);if(d.$cache=i,d.$cache)d.$cache.invalidate=i?.onMutate;return d}import*as G8 from"effect/Context";import*as IF from"effect/Effect";import*as CF from"effect/Layer";wf();Jh();import*as On from"effect/Effect";import*as RF from"effect/Effectable";import*as AF from"effect/Runtime";var im=void 0,z8={...RF.CommitPrototype,commit(){return On.runtime().pipe(On.flatMap((e)=>On.tryPromise({try:()=>{let t=im;im=e;let r=this.execute();return im=t,r},catch:(t)=>new di({cause:t,message:"Failed to execute QueryPromise"})})))}},ST=(e)=>{if(On.EffectTypeId in e)return;Object.assign(e,z8)},PF=On.gen(function*(){let e=yield*ps,t=yield*On.runtime();return(r,n,o)=>{let i=AF.runPromise(im?im:t),s=e.unsafe(r,n);if(o==="execute")return i(On.either(On.map(s.raw,(c)=>({rows:[c]})))).then((c)=>{if(c._tag==="Left")throw c.left.cause;return c.right});let a=o==="all"||o==="values"?s.values:s.withoutTransform;if(o==="get")a=On.map(a,(c)=>c[0]??[]);return i(On.either(On.map(a,(c)=>({rows:c})))).then((c)=>{if(c._tag==="Left")throw c.left.cause;return c.right})}});var _F=(e)=>IF.gen(function*(){return gT(yield*PF,e)});ST(cn.prototype);ST(gu.prototype);function vT(e){return f`count(${e||f.raw("*")})`.mapWith(Number)}import{Context as Kz,Effect as Vz,Layer as Qz}from"effect";var Zt={};$C(Zt,{calendarPeriod:()=>Do,calendarPeriodRelations:()=>Lz,completedJob:()=>No,dateException:()=>Vi,dateExceptionRelations:()=>$z,delegation:()=>gt,delegationHistory:()=>Wn,delegationHistoryRelations:()=>Iz,delegationRelations:()=>Az,documentStore:()=>wt,documentStoreRelations:()=>jz,externalParticipant:()=>Nn,externalParticipantRelations:()=>gz,file:()=>Dr,fileRelations:()=>Hz,flow:()=>Q,flowRelations:()=>hz,holidayInstance:()=>Or,holidayInstanceRelations:()=>qz,invitation:()=>k,invitationRelations:()=>Nz,invitationRole:()=>Oe,invitationRoleRelations:()=>Uz,jobQueue:()=>Ke,oauthClient:()=>Ft,oauthClientRelations:()=>Bz,oauthProvider:()=>mt,oauthStorage:()=>Rr,orgUnit:()=>V,orgUnitRelations:()=>lz,passkeyCredential:()=>Xe,passkeyCredentialRelations:()=>Tz,permittedClientEmail:()=>go,permittedClientEmailRelations:()=>Dz,permittedClientRole:()=>Xn,permittedClientRoleRelations:()=>Oz,permittedRole:()=>Dn,permittedRoleRelations:()=>kz,phase:()=>Xr,phaseRelations:()=>pz,process:()=>z,processExecution:()=>W,processExecutionRelations:()=>vz,processItsActiveProcesses:()=>cc,processItsNoDrafts:()=>cz,processItsStartStep:()=>ac,processRelations:()=>dz,processState:()=>M,processStateItsIsDraft:()=>Fo,processStateRelations:()=>Sz,providerUser:()=>O,providerUserRelations:()=>Rz,providerUserRole:()=>rt,providerUserRoleRelations:()=>Cz,publicCompletionInvitationAttempt:()=>nt,publicCompletionInvitationAttemptRelations:()=>wz,registrationSession:()=>Zr,registrationSessionRelations:()=>Fz,role:()=>N,roleRelations:()=>uz,roleResponsibility:()=>mr,roleResponsibilityRelations:()=>fz,scheduledFlow:()=>Me,scheduledFlowRelations:()=>bz,secretGeneration:()=>We,secretGenerationRelations:()=>Pz,step:()=>U,stepDocumentStore:()=>Wr,stepDocumentStoreRelations:()=>Wz,stepItsCanStartProcess:()=>bi,stepRelations:()=>mz,stepSupportingRole:()=>Tr,stepSupportingRoleRelations:()=>yz,toDo:()=>C,toDoRelations:()=>xz,user:()=>X,userRelations:()=>Ez,userSettings:()=>Mt,userSettingsRelations:()=>_z,weeklySchedule:()=>en,weeklyScheduleRelations:()=>Mz});import{DateTime as NF}from"effect";import MS from"crypto";function sm(e){if(!Ru(e))throw Error("Parameter was not an error")}function Ru(e){return!!e&&typeof e==="object"&&X8(e)==="[object Error]"||e instanceof Error}function X8(e){return Object.prototype.toString.call(e)}var Z8="Layerr";function xT(){return Z8}function kF(e){let t,r="";if(e.length===0)t={};else if(Ru(e[0]))t={cause:e[0]},r=e.slice(1).join(" ")||"";else if(e[0]&&typeof e[0]==="object")t=Object.assign({},e[0]),r=e.slice(1).join(" ")||"";else if(typeof e[0]==="string")t={},r=r=e.join(" ")||"";else throw Error("Invalid arguments passed to Layerr");return{options:t,shortMessage:r}}class wi extends Error{constructor(e,t){let r=[...arguments],{options:n,shortMessage:o}=kF(r),i=o;if(n.cause)i=`${i}: ${n.cause.message}`;super(i);if(this.message=i,n.name&&typeof n.name==="string")this.name=n.name;else this.name=xT();if(n.cause)Object.defineProperty(this,"_cause",{value:n.cause});if(Object.defineProperty(this,"_info",{value:{}}),n.info&&typeof n.info==="object")Object.assign(this._info,n.info);if(Error.captureStackTrace){let s=n.constructorOpt||this.constructor;Error.captureStackTrace(this,s)}}static cause(e){if(sm(e),!e._cause)return null;return Ru(e._cause)?e._cause:null}static fullStack(e){sm(e);let t=wi.cause(e);if(t)return`${e.stack}
|
|
76
|
+
caused by: ${wi.fullStack(t)}`;return e.stack??""}static info(e){sm(e);let t={},r=wi.cause(e);if(r)Object.assign(t,wi.info(r));if(e._info)Object.assign(t,e._info);return t}toString(){let e=this.name||this.constructor.name||this.constructor.prototype.name;if(this.message)e=`${e}: ${this.message}`;return e}}var DF="0123456789ABCDEFGHJKMNPQRSTVWXYZ",cm=32,OF=281474976710655,ez=10,tz=16,am=Object.freeze({source:"ulid"});function rz(e){let t=e||nz(),r=t&&(t.crypto||t.msCrypto)||(typeof MS<"u"?MS:null);if(typeof r?.getRandomValues==="function")return()=>{let n=new Uint8Array(1);return r.getRandomValues(n),n[0]/255};else if(typeof r?.randomBytes==="function")return()=>r.randomBytes(1).readUInt8()/255;else if(MS?.randomBytes)return()=>MS.randomBytes(1).readUInt8()/255;throw new wi({info:{code:"PRNG_DETECT",...am}},"Failed to find a reliable PRNG")}function nz(){if(sz())return self;if(typeof window<"u")return window;if(typeof global<"u")return global;if(typeof globalThis<"u")return globalThis;return null}function oz(e,t){let r="";for(;e>0;e--)r=az(t)+r;return r}function iz(e,t){if(isNaN(e))throw new wi({info:{code:"ENC_TIME_NAN",...am}},`Time must be a number: ${e}`);else if(e>OF)throw new wi({info:{code:"ENC_TIME_SIZE_EXCEED",...am}},`Cannot encode a time larger than ${OF}: ${e}`);else if(e<0)throw new wi({info:{code:"ENC_TIME_NEG",...am}},`Time must be positive: ${e}`);else if(Number.isInteger(e)===!1)throw new wi({info:{code:"ENC_TIME_TYPE",...am}},`Time must be an integer: ${e}`);let r,n="";for(let o=t;o>0;o--)r=e%cm,n=DF.charAt(r)+n,e=(e-r)/cm;return n}function sz(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function az(e){let t=Math.floor(e()*cm);if(t===cm)t=cm-1;return DF.charAt(t)}function ft(e,t){let r=t||rz(),n=isNaN(e)?Date.now():e;return iz(n,ez)+oz(tz,r)}var Er=vl({dataType(){return"text collate nocase"}}),Xo=vl({dataType(){return"text"},toDriver(e){return JSON.stringify(e)},fromDriver(e){return e==null?{}:JSON.parse(e)}}),ee=vl({dataType(){return"real"},toDriver(e){return NF.toEpochMillis(e)/86400000+2440587.5},fromDriver(e){let t=(e-2440587.5)*86400000;return NF.unsafeMake(t)}}),V=pt("pf_org_unit",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`ou-${ft()}`),name:Er("name").notNull(),orgUnitLevel:I("org_unit_level",{length:64}).notNull(),parentOrgUnitId:I("parent_org_unit",{length:41}).references(()=>V.id),path:I("path",{length:2048}).notNull(),acronym:Er("acronym"),timezone:I("timezone",{length:64}).notNull().default("UTC"),startDayOfWeek:ge("start_day_of_week").default(0),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({pathidxIdx:Tt("pf_org_unit_pathidx_idx").on(e.path).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_org_unit_updated_at_id_idx").on(e.updatedAt,e.id),nameLengthCheck:Yn("name_length_check",f.raw('length("pf_org_unit"."name") <= 1024')),acronymLengthCheck:Yn("acronym_length_check",f.raw('length("pf_org_unit"."acronym") <= 64'))})),z=pt("pf_process",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`prc-${ft()}`),orgUnitId:I("org_unit_id",{length:41}).notNull().references(()=>V.id),name:Er("name").notNull(),path:I("path",{length:2048}).notNull(),purpose:Er("purpose").notNull(),slaValue:ge("sla_value"),slaUnit:I("sla_unit",{length:16}),slaWarning:ge("sla_warning"),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({pathidxIdx:Tt("pf_process_pathidx_idx").on(e.path).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_process_updated_at_id_idx").on(e.updatedAt,e.id),nameLengthCheck:Yn("name_length_check",f.raw('length("pf_process"."name") <= 1024'))})),N=pt("pf_role",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`role-${ft()}`),orgUnitId:I("org_unit_id",{length:41}).notNull().references(()=>V.id),name:Er("name").notNull(),path:I("path",{length:2048}).notNull(),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({pathidxIdx:Tt("pf_role_pathidx_idx").on(e.path).where(f`_deleted = 0`),orgunitunameidxIdx:Tt("pf_role_orgunitunameidx_idx").on(e.orgUnitId,e.name).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_role_updated_at_id_idx").on(e.updatedAt,e.id),nameLengthCheck:Yn("name_length_check",f.raw('length("pf_role"."name") <= 1024'))})),Xr=pt("pf_phase",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`ph-${ft()}`),processId:I("process_id",{length:41}).notNull().references(()=>z.id),name:Er("name").notNull(),path:I("path",{length:2048}).notNull(),phaseOrder:ge("phase_order").notNull(),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({pathidxIdx:Tt("pf_phase_pathidx_idx").on(e.path).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_phase_updated_at_id_idx").on(e.updatedAt,e.id),nameLengthCheck:Yn("name_length_check",f.raw('length("pf_phase"."name") <= 1024'))})),mr=pt("pf_role_responsibility",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`rr-${ft()}`),processId:I("process_id",{length:41}).notNull().references(()=>z.id),roleId:I("role_id",{length:41}).notNull().references(()=>N.id),responsibility:Er("responsibility").notNull(),responsibilityOrder:ge("responsibility_order").notNull(),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({processroleidxIdx:Tt("pf_role_responsibility_processroleidx_idx").on(e.processId,e.roleId).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_role_responsibility_updated_at_id_idx").on(e.updatedAt,e.id)})),U=pt("pf_step",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`step-${ft()}`),name:Er("name").notNull(),path:I("path",{length:2048}).notNull(),purpose:Er("purpose").notNull(),processId:I("process_id",{length:41}).notNull().references(()=>z.id),roleId:I("role_id",{length:41}).references(()=>N.id),formFields:ge("form_fields"),phaseId:I("phase_id",{length:41}).references(()=>Xr.id),slaValue:ge("sla_value"),slaUnit:I("sla_unit",{length:16}),slaWarning:ge("sla_warning"),hasForEach:ge("has_for_each",{mode:"boolean"}).notNull().default(!1),embedded:ge("embedded",{mode:"boolean"}).notNull().default(!1),retryLimit:ge("retry_limit"),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({pathidxIdx:Tt("pf_step_pathidx_idx").on(e.path).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_step_updated_at_id_idx").on(e.updatedAt,e.id),nameLengthCheck:Yn("name_length_check",f.raw('length("pf_step"."name") <= 1024'))})),Tr=pt("pf_step_supporting_role",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`ssr-${ft()}`),stepId:I("step_id",{length:41}).notNull().references(()=>U.id),roleId:I("role_id",{length:41}).notNull().references(()=>N.id),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({steproleidxIdx:Tt("pf_step_supporting_role_steproleidx_idx").on(e.stepId,e.roleId).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_step_supporting_role_updated_at_id_idx").on(e.updatedAt,e.id)})),Q=pt("pf_flow",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`flow-${ft()}`),flowKey:I("flow_key",{length:128}).notNull(),sourceStepId:I("source_step",{length:41}).notNull().references(()=>U.id),targetStepId:I("target_step",{length:41}).notNull().references(()=>U.id),condition:Er("condition"),schedule:Er("schedule"),fallbackBranch:ge("fallback_branch",{mode:"boolean"}).notNull().default(!1),errorBranch:ge("error_branch",{mode:"boolean"}).notNull().default(!1),errorTags:Xo("error_tags"),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({sourcetargetidxIdx:Ye("pf_flow_sourcetargetidx_idx").on(e.sourceStepId,e.targetStepId).where(f`_deleted = 0`),flowkeyidxIdx:Tt("pf_flow_flowkeyidx_idx").on(e.flowKey).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_flow_updated_at_id_idx").on(e.updatedAt,e.id)})),Nn=pt("pf_external_participant",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`xp-${ft()}`),email:I("email",{length:320}).notNull(),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({emailidxIdx:Tt("pf_external_participant_emailidx_idx").on(e.email).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_external_participant_updated_at_id_idx").on(e.updatedAt,e.id)})),M=pt("pf_process_state",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`pst-${ft()}`),processId:I("process_id",{length:41}).notNull().references(()=>z.id),startStepId:I("start_step",{length:41}).notNull().references(()=>U.id),state:Xo("state").notNull(),startedByUserId:I("started_by_user",{length:41}).references(()=>X.id),startedByExternalParticipantId:I("started_by_external_participant",{length:41}).references(()=>Nn.id),startedByRoleId:I("started_by_role",{length:41}).references(()=>N.id),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({updatedAtIdIdx:Ye("pf_process_state_updated_at_id_idx").on(e.updatedAt,e.id),singleStarterCheck:Yn("single_starter_check",f`${e.startedByUserId} is null or ${e.startedByExternalParticipantId} is null`)})),W=pt("pf_process_execution",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`pex-${ft()}`),withoutWaiting:ge("without_waiting",{mode:"boolean"}).notNull().default(!1),processStateId:I("process_state_id",{length:41}).notNull().references(()=>M.id),finishedAt:ee("finished_at"),businessDuration:ge("business_duration"),abandonedAt:ee("abandoned_at"),abandonedReason:Er("abandoned_reason"),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({updatedAtIdIdx:Ye("pf_process_execution_updated_at_id_idx").on(e.updatedAt,e.id)})),C=pt("pf_to_do",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`todo-${ft()}`),processExecutionId:I("process_execution_id",{length:41}).notNull().references(()=>W.id),flowId:I("flow_id",{length:41}).notNull().references(()=>Q.id),completedByUserId:I("completed_by_user",{length:41}).references(()=>X.id),completedByExternalParticipantId:I("completed_by_external_participant",{length:41}).references(()=>Nn.id),assignedToProviderUserId:I("assigned_to_provider_user",{length:41}).references(()=>O.id),businessDuration:ge("business_duration"),slaTargetAt:ee("sla_target_at"),slaWarningAt:ee("sla_warning_at"),failureReason:Er("failure_reason"),correctionRequiredAt:ee("correction_required_at"),correctionFailureReason:Er("correction_failure_reason"),correctionInvitationAttemptId:I("correction_invitation_attempt_id",{length:41}),itemData:Xo("item_data"),barrierScheduledFlowId:I("barrier_scheduled_flow_id",{length:41}),completedByRoleId:I("completed_by_role",{length:41}).references(()=>N.id),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({updatedAtIdIdx:Ye("pf_to_do_updated_at_id_idx").on(e.updatedAt,e.id),singleCompleterCheck:Yn("single_completer_check",f`${e.completedByUserId} is null or ${e.completedByExternalParticipantId} is null`)})),nt=pt("pf_public_completion_invitation_attempt",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`pcia-${ft()}`),toDoId:I("to_do_id",{length:41}).notNull().references(()=>C.id),email:I("email",{length:320}).notNull(),providerMessageId:I("provider_message_id",{length:256}),providerSentTo:Er("provider_sent_to"),deliveryStatus:I("delivery_status",{length:32}),deliveryEventId:I("delivery_event_id",{length:256}),deliveryFailureKind:I("delivery_failure_kind",{length:64}),deliveryFailureReason:Er("delivery_failure_reason"),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({todoidxIdx:Ye("pf_public_completion_invitation_attempt_todoidx_idx").on(e.toDoId).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_public_completion_invitation_attempt_updated_at_id_idx").on(e.updatedAt,e.id)})),Me=pt("pf_scheduled_flow",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`sf-${ft()}`),processExecutionId:I("process_execution_id",{length:41}).notNull().references(()=>W.id),sourceStepId:I("source_step",{length:41}).notNull().references(()=>U.id),targetStepId:I("target_step",{length:41}).references(()=>U.id),scheduledAt:ee("scheduled_at"),forEachBarrier:ge("for_each_barrier",{mode:"boolean"}).notNull().default(!1),completedByRoleId:I("completed_by_role",{length:41}).references(()=>N.id),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({updatedAtIdIdx:Ye("pf_scheduled_flow_updated_at_id_idx").on(e.updatedAt,e.id)})),X=pt("pf_user",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`usr-${ft()}`),provider:I("provider",{length:128}).notNull(),sub:I("sub",{length:256}).notNull(),lastLoggedIn:ee("last_logged_in").notNull(),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({uniquesubIdx:Tt("pf_user_uniquesub_idx").on(e.provider,e.sub).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_user_updated_at_id_idx").on(e.updatedAt,e.id)})),Xe=pt("pf_passkey_credential",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`pkc-${ft()}`),userId:I("user_id",{length:41}).notNull().references(()=>X.id),passkeyCredentialId:I("passkey_credential_id",{length:2048}).notNull(),passkeyPublicKey:I("passkey_public_key",{length:2048}).notNull(),signatureCounter:I("signature_counter",{length:16}).notNull(),passkeyTransports:Xo("passkey_transports"),passkeyName:I("passkey_name",{length:128}),passkeyLastUsedAt:ee("passkey_last_used_at"),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({credentialidxIdx:Tt("pf_passkey_credential_credentialidx_idx").on(e.passkeyCredentialId).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_passkey_credential_updated_at_id_idx").on(e.updatedAt,e.id)})),O=pt("pf_provider_user",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`pu-${ft()}`),userId:I("user_id",{length:41}).notNull().references(()=>X.id),email:I("email",{length:320}).notNull(),name:Er("name").notNull(),firstName:Er("first_name").notNull(),lastName:Er("last_name").notNull(),picture:I("picture",{length:1024}).notNull(),locale:I("locale",{length:35}).notNull(),orgUnitId:I("org_unit_id",{length:41}).notNull().references(()=>V.id),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({emailidxIdx:Tt("pf_provider_user_emailidx_idx").on(e.email).where(f`_deleted = 0`),userUniqueIdx:Tt("pf_provider_user_user_unique_idx").on(e.userId).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_provider_user_updated_at_id_idx").on(e.updatedAt,e.id),nameLengthCheck:Yn("name_length_check",f.raw('length("pf_provider_user"."name") <= 1024')),firstNameLengthCheck:Yn("first_name_length_check",f.raw('length("pf_provider_user"."first_name") <= 128')),lastNameLengthCheck:Yn("last_name_length_check",f.raw('length("pf_provider_user"."last_name") <= 128'))})),gt=pt("pf_delegation",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`dlg-${ft()}`),ownerProviderUserId:I("owner_provider_user",{length:41}).notNull().references(()=>O.id),delegationName:I("delegation_name",{length:128}).notNull(),activeDelegationName:I("active_delegation_name",{length:128}),secretRevokedAt:ee("secret_revoked_at"),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({ownernameidxIdx:Tt("pf_delegation_ownernameidx_idx").on(e.ownerProviderUserId,e.activeDelegationName).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_delegation_updated_at_id_idx").on(e.updatedAt,e.id)})),We=pt("pf_secret_generation",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`dsg-${ft()}`),delegationId:I("delegation_id",{length:41}).notNull().references(()=>gt.id),secretVerifier:I("secret_verifier",{length:64}).notNull(),secretIssuedAt:ee("secret_issued_at").notNull(),secretExpiresAt:ee("secret_expires_at").notNull(),secretRevokedAt:ee("secret_revoked_at"),secretLastUsedAt:ee("secret_last_used_at"),parentSecretGenerationId:I("parent_secret_generation",{length:41}).references(()=>We.id),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({delegationidxIdx:Ye("pf_secret_generation_delegationidx_idx").on(e.delegationId).where(f`_deleted = 0`),verifieridxIdx:Tt("pf_secret_generation_verifieridx_idx").on(e.secretVerifier).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_secret_generation_updated_at_id_idx").on(e.updatedAt,e.id)})),Wn=pt("pf_delegation_history",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`dgh-${ft()}`),delegationId:I("delegation_id",{length:41}).notNull().references(()=>gt.id),secretGenerationId:I("secret_generation_id",{length:41}).notNull().references(()=>We.id),actorProviderUserId:I("actor_provider_user",{length:41}).notNull().references(()=>O.id),delegationEvent:I("delegation_event",{length:32}).notNull(),secretIssuedAt:ee("secret_issued_at").notNull(),oldDelegationName:I("old_delegation_name",{length:128}),newDelegationName:I("new_delegation_name",{length:128}),actorDelegationId:I("actor_delegation",{length:41}).references(()=>gt.id),actorSecretGenerationId:I("actor_secret_generation",{length:41}).references(()=>We.id),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({updatedAtIdIdx:Ye("pf_delegation_history_updated_at_id_idx").on(e.updatedAt,e.id)})),rt=pt("pf_provider_user_role",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`pur-${ft()}`),providerUserId:I("provider_user_id",{length:41}).notNull().references(()=>O.id),roleId:I("role_id",{length:41}).notNull().references(()=>N.id),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({provideruserroleidxIdx:Tt("pf_provider_user_role_provideruserroleidx_idx").on(e.providerUserId,e.roleId).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_provider_user_role_updated_at_id_idx").on(e.updatedAt,e.id)})),Mt=pt("pf_user_settings",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`us-${ft()}`),userId:I("user_id",{length:41}).notNull().references(()=>X.id),notificationPreference:Xo("notification_preference").notNull(),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({userUniqueIdx:Tt("pf_user_settings_user_unique_idx").on(e.userId).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_user_settings_updated_at_id_idx").on(e.updatedAt,e.id)})),Dn=pt("pf_permitted_role",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`pr-${ft()}`),providerUserId:I("provider_user_id",{length:41}).notNull().references(()=>O.id),roleId:I("role_id",{length:41}).notNull().references(()=>N.id),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({provideruserroleidxIdx:Tt("pf_permitted_role_provideruserroleidx_idx").on(e.providerUserId,e.roleId).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_permitted_role_updated_at_id_idx").on(e.updatedAt,e.id)})),Xn=pt("pf_permitted_client_role",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`pcr-${ft()}`),oauthClientId:I("oauth_client_id",{length:41}).notNull().references(()=>Ft.id),roleId:I("role_id",{length:41}).notNull().references(()=>N.id),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({oauthclientroleidxIdx:Tt("pf_permitted_client_role_oauthclientroleidx_idx").on(e.oauthClientId,e.roleId).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_permitted_client_role_updated_at_id_idx").on(e.updatedAt,e.id)})),go=pt("pf_permitted_client_email",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`pce-${ft()}`),oauthClientId:I("oauth_client_id",{length:41}).notNull().references(()=>Ft.id),email:I("email",{length:320}).notNull(),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({oauthclientemailidxIdx:Tt("pf_permitted_client_email_oauthclientemailidx_idx").on(e.oauthClientId,e.email).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_permitted_client_email_updated_at_id_idx").on(e.updatedAt,e.id)})),k=pt("pf_invitation",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`inv-${ft()}`),invitationId:I("invitation_id",{length:128}).notNull(),email:I("email",{length:320}).notNull(),invitationStatus:I("invitation_status",{length:32}).notNull().default("pending"),invitationSource:I("invitation_source",{length:32}).notNull().default("legacy"),invitationPendingEmail:I("invitation_pending_email",{length:320}),invitationAcceptedAt:ee("invitation_accepted_at"),invitationAcceptedByProvider:I("invitation_accepted_by_provider",{length:64}),invitationAcceptedBySubject:I("invitation_accepted_by_subject",{length:256}),acceptedByProviderUserId:I("accepted_by_provider_user",{length:41}).references(()=>O.id),invitationLegacyClosedAt:ee("invitation_legacy_closed_at"),invitationLegacyClosureReason:I("invitation_legacy_closure_reason",{length:128}),registrationTokenHash:I("registration_token_hash",{length:64}),registrationEncryptionVersion:ge("registration_encryption_version"),registrationEncryptionNonce:I("registration_encryption_nonce",{length:24}),registrationAuthenticationTag:I("registration_authentication_tag",{length:32}),registrationEncryptedToken:Er("registration_encrypted_token"),registrationLinkExpiresAt:ee("registration_link_expires_at"),registrationLinkGeneratedAt:ee("registration_link_generated_at"),registrationLinkGeneratedBy:I("registration_link_generated_by",{length:256}),registrationLinkRevealedAt:ee("registration_link_revealed_at"),registrationLinkRevealedBy:I("registration_link_revealed_by",{length:256}),registrationLinkRevokedAt:ee("registration_link_revoked_at"),registrationLinkRevokedBy:I("registration_link_revoked_by",{length:256}),registrationLinkGeneration:ge("registration_link_generation"),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({emailidxIdx:Ye("pf_invitation_emailidx_idx").on(e.email).where(f`_deleted = 0`),statusidxIdx:Ye("pf_invitation_statusidx_idx").on(e.invitationStatus).where(f`_deleted = 0`),invitationididxIdx:Tt("pf_invitation_invitationididx_idx").on(e.invitationId).where(f`_deleted = 0`),pendingemailidxIdx:Tt("pf_invitation_pendingemailidx_idx").on(e.invitationPendingEmail).where(f`_deleted = 0`),registrationtokenhashidxIdx:Tt("pf_invitation_registrationtokenhashidx_idx").on(e.registrationTokenHash).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_invitation_updated_at_id_idx").on(e.updatedAt,e.id)})),Zr=pt("pf_registration_session",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`rgs-${ft()}`),registrationSessionTokenHash:I("registration_session_token_hash",{length:64}).notNull(),invitationId:I("invitation_id",{length:41}).notNull().references(()=>k.id),registrationLinkGeneration:ge("registration_link_generation").notNull(),registrationSessionExpiresAt:ee("registration_session_expires_at").notNull(),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({invitationidxIdx:Ye("pf_registration_session_invitationidx_idx").on(e.invitationId).where(f`_deleted = 0`),tokenhashidxIdx:Tt("pf_registration_session_tokenhashidx_idx").on(e.registrationSessionTokenHash).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_registration_session_updated_at_id_idx").on(e.updatedAt,e.id)})),Oe=pt("pf_invitation_role",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`ir-${ft()}`),invitationId:I("invitation_id",{length:41}).notNull().references(()=>k.id),roleId:I("role_id",{length:41}).notNull().references(()=>N.id),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({invitationroleidxIdx:Tt("pf_invitation_role_invitationroleidx_idx").on(e.invitationId,e.roleId).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_invitation_role_updated_at_id_idx").on(e.updatedAt,e.id)})),Rr=pt("pf_oauth_storage",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`oas-${ft()}`),oauthKey:I("oauth_key",{length:2048}).notNull(),keyKind:I("key_kind",{length:64}).notNull(),keyValue:Xo("key_value").notNull(),keyExpiry:ee("key_expiry"),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({keyidxIdx:Tt("pf_oauth_storage_keyidx_idx").on(e.oauthKey),updatedAtIdIdx:Ye("pf_oauth_storage_updated_at_id_idx").on(e.updatedAt,e.id)})),mt=pt("pf_oauth_provider",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`opr-${ft()}`),providerName:I("provider_name",{length:64}).notNull(),providerConfig:Xo("provider_config").notNull(),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({nameidxIdx:Tt("pf_oauth_provider_nameidx_idx").on(e.providerName).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_oauth_provider_updated_at_id_idx").on(e.updatedAt,e.id)})),Ft=pt("pf_oauth_client",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`ocl-${ft()}`),clientId:I("client_id",{length:128}).notNull(),clientSecretHash:I("client_secret_hash",{length:256}).notNull(),audience:I("audience",{length:128}).notNull(),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({clientididxIdx:Tt("pf_oauth_client_clientididx_idx").on(e.clientId).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_oauth_client_updated_at_id_idx").on(e.updatedAt,e.id)})),Ke=pt("pf_job_queue",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`qjob-${ft()}`),queue:I("queue",{length:512}).notNull(),jobPayload:Xo("job_payload").notNull(),jobAttempts:ge("job_attempts").notNull().default(0),jobRetryLimit:ge("job_retry_limit").notNull().default(5),availableAt:ee("available_at").notNull().default(f`(julianday('now'))`),lockedUntil:ee("locked_until"),claimReceipt:I("claim_receipt",{length:64}),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({readyIdxIdx:Ye("pf_job_queue_ready_idx_idx").on(e.queue,e.lockedUntil,e.jobAttempts,e.availableAt).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_job_queue_updated_at_id_idx").on(e.updatedAt,e.id)})),No=pt("pf_completed_job",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`cj-${ft()}`),queue:I("queue",{length:512}).notNull(),jobId:I("job_id",{length:1024}).notNull(),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({jobIdIxIdx:Tt("pf_completed_job_job_id_ix_idx").on(e.queue,e.jobId).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_completed_job_updated_at_id_idx").on(e.updatedAt,e.id)})),en=pt("pf_weekly_schedule",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`ws-${ft()}`),orgUnitId:I("org_unit_id",{length:41}).notNull().references(()=>V.id),dayOfWeek:ge("day_of_week").notNull(),timeRanges:Xo("time_ranges").notNull(),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({orgunitdayidxIdx:Tt("pf_weekly_schedule_orgunitdayidx_idx").on(e.orgUnitId,e.dayOfWeek).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_weekly_schedule_updated_at_id_idx").on(e.updatedAt,e.id)})),Do=pt("pf_calendar_period",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`calp-${ft()}`),orgUnitId:I("org_unit_id",{length:41}).notNull().references(()=>V.id),periodKind:I("period_kind",{length:64}).notNull(),periodTitle:Er("period_title").notNull(),periodStart:ee("period_start").notNull(),periodEnd:ee("period_end").notNull(),periodActive:ge("period_active",{mode:"boolean"}).notNull(),periodSchedule:Xo("period_schedule"),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({kinddateidxIdx:Ye("pf_calendar_period_kinddateidx_idx").on(e.periodKind,e.periodStart,e.periodEnd).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_calendar_period_updated_at_id_idx").on(e.updatedAt,e.id),periodTitleLengthCheck:Yn("period_title_length_check",f.raw('length("pf_calendar_period"."period_title") <= 256'))})),Vi=pt("pf_date_exception",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`dex-${ft()}`),orgUnitId:I("org_unit_id",{length:41}).notNull().references(()=>V.id),exceptionDate:ee("exception_date").notNull(),exceptionSlots:Xo("exception_slots").notNull(),exceptionNote:Er("exception_note"),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({orgunitdateidxIdx:Tt("pf_date_exception_orgunitdateidx_idx").on(e.orgUnitId,e.exceptionDate).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_date_exception_updated_at_id_idx").on(e.updatedAt,e.id)})),Or=pt("pf_holiday_instance",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`hol-${ft()}`),orgUnitId:I("org_unit_id",{length:41}).notNull().references(()=>V.id),holidayTitle:Er("holiday_title").notNull(),holidayRule:Xo("holiday_rule").notNull(),holidayDate:ee("holiday_date"),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({orgunittitleidxIdx:Tt("pf_holiday_instance_orgunittitleidx_idx").on(e.orgUnitId,e.holidayTitle).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_holiday_instance_updated_at_id_idx").on(e.updatedAt,e.id),holidayTitleLengthCheck:Yn("holiday_title_length_check",f.raw('length("pf_holiday_instance"."holiday_title") <= 256'))})),wt=pt("pf_document_store",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`dstr-${ft()}`),orgUnitId:I("org_unit_id",{length:41}).notNull().references(()=>V.id),name:Er("name").notNull(),path:I("path",{length:2048}).notNull(),acceptedTypes:Xo("accepted_types"),sizeLimit:ge("size_limit"),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({pathidxIdx:Tt("pf_document_store_pathidx_idx").on(e.path).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_document_store_updated_at_id_idx").on(e.updatedAt,e.id),nameLengthCheck:Yn("name_length_check",f.raw('length("pf_document_store"."name") <= 1024'))})),Dr=pt("pf_file",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`file-${ft()}`),documentStoreId:I("document_store_id",{length:41}).notNull().references(()=>wt.id),fileSize:ge("file_size"),mediaKind:I("media_kind",{length:256}),uploadPending:ge("upload_pending",{mode:"boolean"}).notNull().default(!0),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({updatedAtIdIdx:Ye("pf_file_updated_at_id_idx").on(e.updatedAt,e.id)})),Wr=pt("pf_step_document_store",{id:I("id",{length:41}).primaryKey().$defaultFn(()=>`sds-${ft()}`),stepId:I("step_id",{length:41}).notNull().references(()=>U.id),documentStoreId:I("document_store_id",{length:41}).notNull().references(()=>wt.id),createdAt:ee("created_at").notNull().default(f`(julianday('now'))`),updatedAt:ee("updated_at").notNull().default(f`(julianday('now'))`),createdBy:I("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:I("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:ge("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({stepdocstoreidxIdx:Tt("pf_step_document_store_stepdocstoreidx_idx").on(e.stepId,e.documentStoreId).where(f`_deleted = 0`),updatedAtIdIdx:Ye("pf_step_document_store_updated_at_id_idx").on(e.updatedAt,e.id)})),cz=Al("pf_process_its_no_drafts",{id:I("id",{length:41}).notNull(),noDrafts:ge("no_drafts",{mode:"boolean"}).notNull()}).as(f`
|
|
77
|
+
select
|
|
78
|
+
id,
|
|
79
|
+
not exists (select 1 from pf_process_execution
|
|
80
|
+
join pf_process_state on pf_process_execution.process_state_id = pf_process_state.id and pf_process_state._deleted = false
|
|
81
|
+
where pf_process_state.process_id = pf_process.id and pf_process_execution._deleted = false) as no_drafts
|
|
82
|
+
from pf_process
|
|
83
|
+
`),ac=Al("pf_process_its_start_step",{id:I("id",{length:41}).notNull(),startStep:I("start_step",{length:41})}).as(f`
|
|
84
|
+
select
|
|
85
|
+
id,
|
|
86
|
+
(select pf_step.id from pf_step
|
|
87
|
+
join pf_step_its_can_start_process on pf_step.id = pf_step_its_can_start_process.id
|
|
88
|
+
where pf_step.process_id = pf_process.id
|
|
89
|
+
and pf_step_its_can_start_process.can_start_process = 1
|
|
90
|
+
and pf_step._deleted = false
|
|
91
|
+
limit 1) as start_step
|
|
92
|
+
from pf_process
|
|
93
|
+
`),cc=Al("pf_process_its_active_processes",{id:I("id",{length:41}).notNull(),activeProcesses:ge("active_processes").notNull()}).as(f`
|
|
94
|
+
select
|
|
95
|
+
pf_process.id,
|
|
96
|
+
count(distinct pf_to_do.id) as active_processes
|
|
97
|
+
from pf_process
|
|
98
|
+
left outer join pf_process_state on pf_process_state.process_id = pf_process.id and pf_process_state._deleted = false
|
|
99
|
+
left outer join pf_process_execution on pf_process_execution.process_state_id = pf_process_state.id and pf_process_execution._deleted = false
|
|
100
|
+
left outer join pf_to_do on pf_to_do.process_execution_id = pf_process_execution.id and pf_to_do._deleted = false
|
|
101
|
+
group by
|
|
102
|
+
pf_process.id
|
|
103
|
+
`),bi=Al("pf_step_its_can_start_process",{id:I("id",{length:41}).notNull(),canStartProcess:ge("can_start_process",{mode:"boolean"}).notNull()}).as(f`
|
|
104
|
+
select
|
|
105
|
+
id,
|
|
106
|
+
not exists (select 1 from pf_flow where pf_flow.target_step = pf_step.id and pf_flow._deleted = false) as can_start_process
|
|
107
|
+
from pf_step
|
|
108
|
+
`),Fo=Al("pf_process_state_its_is_draft",{id:I("id",{length:41}).notNull(),isDraft:ge("is_draft",{mode:"boolean"}).notNull()}).as(f`
|
|
109
|
+
select
|
|
110
|
+
id,
|
|
111
|
+
not exists (select 1 from pf_process_execution where pf_process_execution.process_state_id = pf_process_state.id and pf_process_execution._deleted = false) as is_draft
|
|
112
|
+
from pf_process_state
|
|
113
|
+
`),lz=At(V,({one:e,many:t})=>({parentOrgUnit:e(V,{fields:[V.parentOrgUnitId],references:[V.id]}),processes:t(z),roles:t(N),providerUsers:t(O),weeklySchedules:t(en),calendarPeriods:t(Do),dateExceptions:t(Vi),holidayInstances:t(Or),documentStores:t(wt),children:t(V)})),dz=At(z,({one:e,many:t})=>({orgUnit:e(V,{fields:[z.orgUnitId],references:[V.id]}),phases:t(Xr),roleResponsibilities:t(mr),steps:t(U),processStates:t(M)})),uz=At(N,({one:e,many:t})=>({orgUnit:e(V,{fields:[N.orgUnitId],references:[V.id]}),roleResponsibilities:t(mr),steps:t(U),stepSupportingRoles:t(Tr),processStates:t(M),toDos:t(C),scheduledFlows:t(Me),providerUserRoles:t(rt),permittedRoles:t(Dn),permittedClientRoles:t(Xn),invitationRoles:t(Oe)})),pz=At(Xr,({one:e,many:t})=>({process:e(z,{fields:[Xr.processId],references:[z.id]}),steps:t(U)})),fz=At(mr,({one:e})=>({process:e(z,{fields:[mr.processId],references:[z.id]}),role:e(N,{fields:[mr.roleId],references:[N.id]})})),mz=At(U,({one:e,many:t})=>({process:e(z,{fields:[U.processId],references:[z.id]}),role:e(N,{fields:[U.roleId],references:[N.id]}),phase:e(Xr,{fields:[U.phaseId],references:[Xr.id]}),stepSupportingRoles:t(Tr),flows:t(Q,{relationName:"flow_sourceStep"}),processStates:t(M),scheduledFlows:t(Me,{relationName:"scheduledFlow_sourceStep"}),stepDocumentStores:t(Wr)})),yz=At(Tr,({one:e})=>({step:e(U,{fields:[Tr.stepId],references:[U.id]}),role:e(N,{fields:[Tr.roleId],references:[N.id]})})),hz=At(Q,({one:e,many:t})=>({sourceStep:e(U,{relationName:"flow_sourceStep",fields:[Q.sourceStepId],references:[U.id]}),targetStep:e(U,{relationName:"flow_targetStep",fields:[Q.targetStepId],references:[U.id]}),toDos:t(C)})),gz=At(Nn,({many:e})=>({processStates:e(M),toDos:e(C)})),Sz=At(M,({one:e,many:t})=>({process:e(z,{fields:[M.processId],references:[z.id]}),startStep:e(U,{fields:[M.startStepId],references:[U.id]}),startedByUser:e(X,{fields:[M.startedByUserId],references:[X.id]}),startedByExternalParticipant:e(Nn,{fields:[M.startedByExternalParticipantId],references:[Nn.id]}),startedByRole:e(N,{fields:[M.startedByRoleId],references:[N.id]}),processExecutions:t(W)})),vz=At(W,({one:e,many:t})=>({processState:e(M,{fields:[W.processStateId],references:[M.id]}),toDos:t(C),scheduledFlows:t(Me)})),xz=At(C,({one:e,many:t})=>({processExecution:e(W,{fields:[C.processExecutionId],references:[W.id]}),flow:e(Q,{fields:[C.flowId],references:[Q.id]}),completedByUser:e(X,{fields:[C.completedByUserId],references:[X.id]}),completedByExternalParticipant:e(Nn,{fields:[C.completedByExternalParticipantId],references:[Nn.id]}),assignedToProviderUser:e(O,{fields:[C.assignedToProviderUserId],references:[O.id]}),completedByRole:e(N,{fields:[C.completedByRoleId],references:[N.id]}),publicCompletionInvitationAttempts:t(nt)})),wz=At(nt,({one:e})=>({toDo:e(C,{fields:[nt.toDoId],references:[C.id]})})),bz=At(Me,({one:e})=>({processExecution:e(W,{fields:[Me.processExecutionId],references:[W.id]}),sourceStep:e(U,{relationName:"scheduledFlow_sourceStep",fields:[Me.sourceStepId],references:[U.id]}),targetStep:e(U,{relationName:"scheduledFlow_targetStep",fields:[Me.targetStepId],references:[U.id]}),completedByRole:e(N,{fields:[Me.completedByRoleId],references:[N.id]})})),Ez=At(X,({one:e,many:t})=>({processStates:t(M),toDos:t(C),passkeyCredentials:t(Xe),providerUser:e(O,{fields:[X.id],references:[O.userId]}),userSettings:e(Mt,{fields:[X.id],references:[Mt.userId]})})),Tz=At(Xe,({one:e})=>({user:e(X,{fields:[Xe.userId],references:[X.id]})})),Rz=At(O,({one:e,many:t})=>({user:e(X,{fields:[O.userId],references:[X.id]}),orgUnit:e(V,{fields:[O.orgUnitId],references:[V.id]}),toDos:t(C),delegations:t(gt),delegationHistories:t(Wn),providerUserRoles:t(rt),permittedRoles:t(Dn),invitations:t(k)})),Az=At(gt,({one:e,many:t})=>({ownerProviderUser:e(O,{fields:[gt.ownerProviderUserId],references:[O.id]}),secretGenerations:t(We),delegationHistories:t(Wn,{relationName:"delegationHistory_delegation"})})),Pz=At(We,({one:e,many:t})=>({delegation:e(gt,{fields:[We.delegationId],references:[gt.id]}),parentSecretGeneration:e(We,{fields:[We.parentSecretGenerationId],references:[We.id]}),delegationHistories:t(Wn,{relationName:"delegationHistory_secretGeneration"}),children:t(We)})),Iz=At(Wn,({one:e})=>({delegation:e(gt,{relationName:"delegationHistory_delegation",fields:[Wn.delegationId],references:[gt.id]}),secretGeneration:e(We,{relationName:"delegationHistory_secretGeneration",fields:[Wn.secretGenerationId],references:[We.id]}),actorProviderUser:e(O,{fields:[Wn.actorProviderUserId],references:[O.id]}),actorDelegation:e(gt,{relationName:"delegationHistory_actorDelegation",fields:[Wn.actorDelegationId],references:[gt.id]}),actorSecretGeneration:e(We,{relationName:"delegationHistory_actorSecretGeneration",fields:[Wn.actorSecretGenerationId],references:[We.id]})})),Cz=At(rt,({one:e})=>({providerUser:e(O,{fields:[rt.providerUserId],references:[O.id]}),role:e(N,{fields:[rt.roleId],references:[N.id]})})),_z=At(Mt,({one:e})=>({user:e(X,{fields:[Mt.userId],references:[X.id]})})),kz=At(Dn,({one:e})=>({providerUser:e(O,{fields:[Dn.providerUserId],references:[O.id]}),role:e(N,{fields:[Dn.roleId],references:[N.id]})})),Oz=At(Xn,({one:e})=>({oauthClient:e(Ft,{fields:[Xn.oauthClientId],references:[Ft.id]}),role:e(N,{fields:[Xn.roleId],references:[N.id]})})),Dz=At(go,({one:e})=>({oauthClient:e(Ft,{fields:[go.oauthClientId],references:[Ft.id]})})),Nz=At(k,({one:e,many:t})=>({acceptedByProviderUser:e(O,{fields:[k.acceptedByProviderUserId],references:[O.id]}),registrationSessions:t(Zr),invitationRoles:t(Oe)})),Fz=At(Zr,({one:e})=>({invitation:e(k,{fields:[Zr.invitationId],references:[k.id]})})),Uz=At(Oe,({one:e})=>({invitation:e(k,{fields:[Oe.invitationId],references:[k.id]}),role:e(N,{fields:[Oe.roleId],references:[N.id]})})),Bz=At(Ft,({many:e})=>({permittedClientRoles:e(Xn),permittedClientEmails:e(go)})),Mz=At(en,({one:e})=>({orgUnit:e(V,{fields:[en.orgUnitId],references:[V.id]})})),Lz=At(Do,({one:e})=>({orgUnit:e(V,{fields:[Do.orgUnitId],references:[V.id]})})),$z=At(Vi,({one:e})=>({orgUnit:e(V,{fields:[Vi.orgUnitId],references:[V.id]})})),qz=At(Or,({one:e})=>({orgUnit:e(V,{fields:[Or.orgUnitId],references:[V.id]})})),jz=At(wt,({one:e,many:t})=>({orgUnit:e(V,{fields:[wt.orgUnitId],references:[V.id]}),files:t(Dr),stepDocumentStores:t(Wr)})),Hz=At(Dr,({one:e})=>({documentStore:e(wt,{fields:[Dr.documentStoreId],references:[wt.id]})})),Wz=At(Wr,({one:e})=>({step:e(U,{fields:[Wr.stepId],references:[U.id]}),documentStore:e(wt,{fields:[Wr.documentStoreId],references:[wt.id]})}));var Jz=nT(Zt,(e)=>({process:{orgUnit:e.one.orgUnit({from:e.process.orgUnitId,to:e.orgUnit.id,optional:!1})},providerUser:{user:e.one.user({from:e.providerUser.userId,to:e.user.id,optional:!1}),orgUnit:e.one.orgUnit({from:e.providerUser.orgUnitId,to:e.orgUnit.id,optional:!1})},providerUserRole:{role:e.one.role({from:e.providerUserRole.roleId,to:e.role.id,optional:!1})}})),zz={schema:Zt,relations:Jz};class pe extends Kz.Tag("processfocus:internal-tag/service-drizzle-sqlite/TypedSqliteDrizzle")(){}var FF=Qz.effect(pe,_F(zz).pipe(Vz.map((e)=>e)));import{createHash as yj,randomBytes as HZ}from"crypto";import{Data as hj,DateTime as ci,Effect as Je,Either as WZ,Layer as SC,Option as Ut,Stream as pj}from"effect";import{Context as Gz,Data as UF,Effect as BF}from"effect";class MF extends UF.TaggedError("processfocus:internal-tag/auth-api/DatabaseQueryError"){}class LF extends UF.TaggedError("processfocus:internal-tag/auth-api/DatabaseWriteError"){}var Kt=(e)=>(t)=>t.pipe(BF.mapError((r)=>new MF({message:e,cause:r}))),yr=(e)=>(t)=>t.pipe(BF.mapError((r)=>new LF({message:e,cause:r})));class Fn extends Gz.Tag("processfocus:internal-tag/auth-api/AuthenticationDatabase")(){}import{Data as Cd,DateTime as grt,Effect as Srt,Layer as vrt,Option as xrt,Runtime as wrt,Schema as St}from"effect";var lc=new TextEncoder,Au=new TextDecoder,LS=new TextDecoder("utf-8",{fatal:!0});function So(...e){let t=e.reduce((o,{length:i})=>o+i,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function wT(e,t,r){if(t<0||t>=4294967296)throw RangeError(`value must be >= 0 and <= 4294967295. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r)}function bT(e){let t=Math.floor(e/4294967296),r=e%4294967296,n=new Uint8Array(8);return wT(n,t,0),wT(n,r,4),n}function $S(e){let t=new Uint8Array(4);return wT(t,e),t}var Yz=/[^\x00-\x7f]/;function vo(e){if(typeof e=="string"&&e.length>=128){if(Yz.test(e))throw TypeError("non-ASCII string encountered in encode()");return lc.encode(e)}let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>127)throw TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}function qS(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?"base64url":"base64",omitPadding:t});let r=32768,n=[];for(let i=0;i<e.length;i+=r)n.push(String.fromCharCode.apply(null,e.subarray(i,i+r)));let o=btoa(n.join(""));return t?o.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):o}function jS(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?"base64url":"base64"});if(t){if(e.includes("+")||e.includes("/"))throw TypeError("Invalid base64url");e=e.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(e),n=new Uint8Array(r.length);for(let o=0;o<r.length;o++)n[o]=r.charCodeAt(o);return n}async function $F(e,t){let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,t))}class hs extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class dc extends hs{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}}class HS extends hs{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.claim=r,this.reason=n,this.payload=t}}class Pu extends hs{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class or extends hs{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class WS extends hs{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",t){super(e,t)}}class _e extends hs{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"}class Ar extends hs{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class Pl extends hs{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class ET extends hs{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}var Xz="The input to be decoded is not correctly encoded.";function lm(e){try{return jS(typeof e=="string"?e:Au.decode(e),!0)}catch(t){throw TypeError(Xz,{cause:t})}}function tn(e){return qS(typeof e=="string"?lc.encode(e):e,!0)}function sa(e,t){if(!(e instanceof Uint8Array))throw TypeError(`${t} must be an instance of Uint8Array`)}function Zo(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function uc(...e){let t=new Set;for(let r of e)if(r)for(let n of Object.keys(r)){if(t.has(n))return!1;t.add(n)}return!0}function Il(e,t){if(e!==void 0)throw TypeError(`${t} can only be called once`)}function Uo(e,t,r){try{return lm(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}function KS(e,t,r){try{return vo(e)}catch{throw new r(`The ${t} is not a valid base64url string`)}}function VS(e,t,r){let n;try{n=JSON.parse(LS.decode(lm(e)))}catch{throw new t(r)}if(!Zo(n))throw new t(r);return n}var QS={__proto__:null,b64:!0},JS={__proto__:null};function dm(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some((r)=>typeof r!="string")))throw TypeError(`"${e}" option must be an array of strings`);return t===void 0?void 0:new Set(t)}function zS(e,t){let{crit:r}=t??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function pc(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return[];if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some((s)=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=r===void 0?t:{__proto__:null,...r,...t};for(let s of n.crit){if(!(s in i))throw new or(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(o,s)||o[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(i[s]&&(!Object.hasOwn(n,s)||n[s]===void 0))throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return n.crit}function GS(e,t){if(t.includes("b64")){let r=e.b64;if(typeof r!="boolean")throw new Ar('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function Cl(e,t){let r,n;try{r=JSON.stringify(t),n=JSON.parse(r)}catch(o){throw new e("JOSE Header is not valid JSON",{cause:o})}if(!Zo(n))throw new e("JOSE Header is not a JSON object");return[n,r]}var Zz=(e)=>e[Symbol.toStringTag],eG=(e,t,r)=>{let{alg:n}=e;if(t.use!==void 0){let o=r==="sign"||r==="verify"?"sig":"enc";if(t.use!==o)throw TypeError(`Invalid key for this operation, its "use" must be "${o}" when present`)}if(t.alg!==void 0&&t.alg!==n)throw TypeError(`Invalid key for this operation, its "alg" must be "${n}" when present`);if(Array.isArray(t.key_ops)){let o=r==="encrypt"||r==="decrypt"?e.ops?.[r==="encrypt"?0:1]:r;if(o&&!t.key_ops.includes(o))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${o}" when present`)}};async function Qi(e,t,r){let{alg:n,secret:o}=e,i=r==="decrypt"||r==="sign";if(o&&t instanceof Uint8Array)return t;let s,a;if(Zo(t)){if(s=oG(t),typeof s.kty!="string")throw jF(n,t,o);if(!(o?s.kty==="oct"&&typeof s.k=="string":s.kty!=="oct"&&(i?s.kty==="AKP"&&typeof s.priv=="string"||typeof s.d=="string":s.d===void 0&&s.priv===void 0)))throw TypeError(o?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${i?"private":"public"} JWK`);if(eG(e,s,r),s.kty==="oct")return lm(s.k);if(!Object.isFrozen(t)){let{key_ops:d}=t;Array.isArray(d)&&Object.freeze(d),Object.freeze(t)}}else{if(!rG(t))throw jF(n,t,o);let d=o?"secret":i?"private":"public";if(t.type!==d&&(o||["secret","public","private"].includes(t.type)))throw TypeError(`${Zz(t)} instances must be of type "${d}" for the ${n} algorithm`);if(gs(t))return t;if(a=t,a.type==="secret")return a.export()}TT||=new WeakMap;let c=t,l=TT.get(c);if(l?.[n])return l[n];if(l||TT.set(c,l={}),a&&typeof a.toCryptoKey=="function"){let d=a.type==="public",u=tG[a.asymmetricKeyDetails?.namedCurve],m=e.resolve?.({crv:u,asymmetricKeyType:a.asymmetricKeyType})??e.subtle;return l[n]=a.toCryptoKey(m,d,e.usages[d?0:1])}return s??=a.export({format:"jwk"}),s.alg=n,l[n]=await PT(e,s)}var TT,tG={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function XS(e){if(!gs(e))throw Error("CryptoKey instance expected")}var gs=(e)=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},um=(e)=>e?.[Symbol.toStringTag]==="KeyObject",rG=(e)=>gs(e)||um(e);function HF(e,t,...r){if(r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var fc=(e,...t)=>HF("Key must be ",e,...t);function jF(e,t,r){let n=["CryptoKey","KeyObject","JSON Web Key"];return r&&n.push("Uint8Array"),TypeError(HF(`Key for the ${e} algorithm must be `,t,...n))}var YS=(e,t="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function RT(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Iu(e,t){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function AT(e,t,r){let n=e.algorithm;if(n.name!==t.name)throw YS(t.name);if(t.hash&&n.hash?.name!==t.hash)throw YS(t.hash,"algorithm.hash");if(t.namedCurve&&n.namedCurve!==t.namedCurve)throw YS(t.namedCurve,"algorithm.namedCurve");if(t.length!==void 0&&n.length!==t.length)throw YS(t.length,"algorithm.length");RT(e,r)}function nG(e){return{__proto__:null,...e}}function oG(e){let t=nG(e);if(t.ext!==void 0&&typeof t.ext!="boolean")throw TypeError('"ext" (Extractable) Parameter must be a boolean');if(t.key_ops!==void 0){let r=t.key_ops,n=Array.isArray(r)?[...r]:void 0;if(!n||n.some((o)=>typeof o!="string")||new Set(n).size!==n.length)throw TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=n}return t}function ZS(e){if(e!==void 0&&typeof e!="boolean")throw TypeError('"extractable" option must be a boolean');return e}async function PT(e,t,r){if(!e.kty.includes(t.kty))throw new or('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let n=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,o=!!(t.d||t.priv),i={...t,ext:r??t.ext};return i.kty!=="AKP"&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,n,i.ext??!o,t.key_ops??e.usages[o?1:0])}async function Ji(e,t,r,n=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey("raw",e,t,n,[r])),AT(e,t,r),e}var pm=(e)=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function ev(e,t){let r=e.byteLength<<3;if(r!==t)throw new _e(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)}var iG=(e)=>crypto.getRandomValues(new Uint8Array(e.ivBits>>3));function WF(e,t){if(t.length<<3!==e.ivBits)throw new _e("Invalid Initialization Vector length")}async function KF(e,t,r){if(!(t instanceof Uint8Array))throw TypeError(fc(t,"Uint8Array"));let n=e.cekBits>>1,o=await crypto.subtle.importKey("raw",t.subarray(n>>3),"AES-CBC",!1,[r]),i=await crypto.subtle.importKey("raw",t.subarray(0,n>>3),{hash:`SHA-${n<<1}`,name:"HMAC"},!1,["sign"]);return[o,i,n]}async function VF(e,t,r){return new Uint8Array((await crypto.subtle.sign("HMAC",e,t)).slice(0,r>>3))}async function sG(e,t,r,n,o){let[i,s,a]=await KF(e,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:n,name:"AES-CBC"},i,t)),l=So(o,n,c,bT(o.length*8)),d=await VF(s,l,a);return{ciphertext:c,tag:d,iv:n}}async function aG(e,t){let r={name:"HMAC",hash:"SHA-256"},n=await crypto.subtle.generateKey(r,!1,["sign","verify"]),o=await crypto.subtle.sign(r,n,e);return crypto.subtle.verify(r,n,o,t)}async function cG(e,t,r,n,o,i){let[s,a,c]=await KF(e,t,"decrypt"),l=So(i,n,r,bT(i.length*8)),d=await VF(a,l,c);try{if(await aG(o,d))return new Uint8Array(await crypto.subtle.decrypt({iv:n,name:"AES-CBC"},s,r))}catch{}throw new WS}async function tv(e,t,r,n,o){if(!gs(r)&&!(r instanceof Uint8Array))throw TypeError(fc(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(n?WF(e,n):n=iG(e),r instanceof Uint8Array&&ev(r,e.cekBits),e.cbc)return sG(e,t,r,n,o);let i=await Ji(r,e.subtle,"encrypt"),s=new Uint8Array(await crypto.subtle.encrypt({additionalData:o,iv:n,name:"AES-GCM",tagLength:128},i,t));return{ciphertext:s.subarray(0,-16),tag:s.subarray(-16),iv:n}}async function rv(e,t,r,n,o,i){if(!gs(t)&&!(t instanceof Uint8Array))throw TypeError(fc(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!n)throw new _e("JWE Initialization Vector missing");if(!o)throw new _e("JWE Authentication Tag missing");if(!e.cbc&&o.length!==16)throw new _e("Invalid Authentication Tag length");if(WF(e,n),t instanceof Uint8Array&&ev(t,e.cekBits),e.cbc)return cG(e,t,r,n,o,i);let s=await Ji(t,e.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},s,So(r,o)))}catch{throw new WS}}function fm(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}var lG=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],dG=[[],["deriveBits"]],iv=[[],[]];function nv(e){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${e}`},usages:lG,ops:["wrapKey","unwrapKey"]}}function ov(e){return{kty:["EC","OKP"],mode:e,subtle:{name:"ECDH"},resolve:({kty:t,crv:r,asymmetricKeyType:n})=>{if(r==="X25519"||n==="x25519")return{name:"X25519"};if(t==="OKP")throw new or('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:dG,ops:[void 0,"deriveBits"]}}function Cu(e,t=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:t?"AES-GCM":"AES-KW",length:e},usages:iv,ops:t?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function IT(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:iv,ops:["deriveBits","deriveBits"]}}var _l=fm({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:iv,ops:["encrypt","decrypt"]},"RSA-OAEP":nv(1),"RSA-OAEP-256":nv(256),"RSA-OAEP-384":nv(384),"RSA-OAEP-512":nv(512),"ECDH-ES":ov("direct-key-agreement"),"ECDH-ES+A128KW":ov("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":ov("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":ov("key-agreement-with-key-wrapping"),A128KW:Cu(128),A192KW:Cu(192),A256KW:Cu(256),A128GCMKW:Cu(128,!0),A192GCMKW:Cu(192,!0),A256GCMKW:Cu(256,!0),"PBES2-HS256+A128KW":IT(),"PBES2-HS384+A192KW":IT(),"PBES2-HS512+A256KW":IT()}),uG=["encrypt","decrypt"];function _u(e,t=!1){return{kty:["oct"],secret:!0,subtle:{name:t?"AES-CBC":"AES-GCM",length:e},usages:iv,ops:uG,cekBits:e,ivBits:t?128:96,cbc:t}}var pG=fm({A128GCM:_u(128),A192GCM:_u(192),A256GCM:_u(256),"A128CBC-HS256":_u(256,!0),"A192CBC-HS384":_u(384,!0),"A256CBC-HS512":_u(512,!0)});function QF(e,t){throw new or(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function aa(e){return(typeof e=="string"?_l[e]:void 0)??QF("alg","Algorithm")}function kl(e){return e.mode==="key-wrapping"||e.mode==="key-encryption"||e.mode==="key-agreement-with-key-wrapping"}function Ol(e){return(typeof e=="string"?pG[e]:void 0)??QF("enc","Encryption Algorithm")}function JF(e,t){if(e.algorithm.name!=="ECDH"&&e.algorithm.name!=="X25519")throw TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");RT(e,t)}async function fG(e,t,r){let n=await Ji(t,aa(e).subtle,"wrapKey",!0),o=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",o,n,"AES-KW"))}async function mG(e,t,r){let n=await Ji(t,aa(e).subtle,"unwrapKey",!0),o=await crypto.subtle.unwrapKey("raw",r,n,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",o))}function GF(e,t,r){AT(t,aa(e).subtle,r),Iu(e,t)}async function YF(e,t,r,n){if(!(e instanceof Uint8Array)||e.length<8)throw new _e("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new _e("PBES2 Count Input must be a positive integer");let o=So(vo(t),Uint8Array.of(0),e),i=parseInt(t.slice(13,16),10),s={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:o},a=await Ji(n,aa(t).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function CT(e){return So($S(e.length),e)}async function yG(e,t,r){let n=t>>3,i=Math.ceil(n/32),s=new Uint8Array(i*32);for(let a=1;a<=i;a++){let c=await $F("sha256",So($S(a),e,r));s.set(c,(a-1)*32)}return s.slice(0,n)}async function XF(e,t,r,n,o=new Uint8Array,i=new Uint8Array){JF(e),JF(t,"deriveBits");let s=So(CT(vo(r)),CT(o),CT(i),$S(n)),a=new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,e.algorithm.name==="X25519"?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3));return yG(a,n,s)}function ZF(e){XS(e);let t=e.algorithm.namedCurve;if(t!=="P-256"&&t!=="P-384"&&t!=="P-521"&&e.algorithm.name!=="X25519")throw new or("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function sv(e,t){let r=e[t];if(r!==void 0){if(typeof r!="string")throw new _e(`JOSE Header "${t}" (Agreement Party${t==="apu"?"U":"V"}Info) invalid`);return Uo(r,t,_e)}}function eU(e,t){if(!(e===void 0||t===void 0||e.byteLength!==t.byteLength)){for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return;throw new _e('JOSE Header "apu" and "apv" values must be distinct')}}function hG(e){if(e===void 0)throw new _e("JWE Encrypted Key missing")}function zF(e){if(e!==void 0)throw new _e("Encountered unexpected JWE Encrypted Key")}function gG(e){if(e!==void 0&&e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError("maxPBES2Count must be a positive safe integer or Infinity")}async function tU(e,t,r,n,o,i){let{alg:s}=e,a=e.mode;if(a==="direct-encryption")return zF(n),r;let c=a==="direct-key-agreement";switch(c?zF(n):hG(n),e.subtle.name){case"ECDH":{let{epk:l}=o;if(!Zo(l)||["d","k","p","q","dp","dq","qi","oth","priv"].some((S)=>Object.hasOwn(l,S)))throw new _e('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');ZF(r);let d=await PT(e,l),u=sv(o,"apu"),m=sv(o,"apv");eU(u,m);let h=await XF(d,r,c?t.alg:s,c?t.cekBits:parseInt(s.slice(-5,-2),10),u,m);if(c)return h;r=h;break}case"RSA-OAEP":return XS(r),GF(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,n));case"PBKDF2":{if(typeof o.p2c!="number")throw new _e('JOSE Header "p2c" (PBES2 Count) missing or invalid');gG(i);let l=i??1e4;if(o.p2c>l)throw new _e('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof o.p2s!="string")throw new _e('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let d=Uo(o.p2s,"p2s",_e);r=await YF(d,s,o.p2c,r);break}case"AES-GCM":{if(typeof o.iv!="string")throw new _e('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof o.tag!="string")throw new _e('JOSE Header "tag" (Authentication Tag) missing or invalid');let l=Uo(o.iv,"iv",_e),d=Uo(o.tag,"tag",_e);if(l.byteLength!==12)throw new _e("Invalid Initialization Vector length");if(d.byteLength!==16)throw new _e("Invalid Authentication Tag length");return rv(Ol(s.slice(0,-2)),r,n,l,d,new Uint8Array)}}return mG(s.slice(-6),r,n)}async function rU(e,t,r,n,o,i={}){let{alg:s,mode:a}=e,c=kl(e);if(o!==void 0&&!c)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let l=await Qi(a==="direct-encryption"?t:e,r,"encrypt");if(a==="direct-encryption")return[l,void 0,void 0];let d=c?o??pm(t):void 0;d&&ev(d,t.cekBits);let u,m;switch(e.subtle.name){case"ECDH":{ZF(l);let{apu:h,apv:S}=i;h!==void 0&&sa(h,'"apu"'),S!==void 0&&sa(S,'"apv"');let x=h??sv(n,"apu"),v=S??sv(n,"apv");eU(x,v);let w;i.epk!==void 0?w=await Qi(e,i.epk,"decrypt"):w=(await crypto.subtle.generateKey(l.algorithm,!0,["deriveBits"])).privateKey;let P=crypto.subtle,F=w;if(!F.extractable){if(typeof P.getPublicKey!="function")throw TypeError('CryptoKey for "epk" must be extractable');F=await P.getPublicKey(w,[])}let{x:R,y:b,crv:A,kty:D}=await P.exportKey("jwk",F),B=a==="direct-key-agreement",J=await XF(l,w,B?t.alg:s,B?t.cekBits:parseInt(s.slice(-5,-2),10),x,v),G={x:R,crv:A,kty:D};if(D==="EC"&&(G.y=b),m={epk:G},h!==void 0&&(m.apu=tn(h)),S!==void 0&&(m.apv=tn(S)),B)return[J,void 0,m];l=J;break}case"RSA-OAEP":{XS(l),GF(s,l,"encrypt"),u=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",l,d));break}case"PBKDF2":{let{p2c:h=2048,p2s:S=crypto.getRandomValues(new Uint8Array(16))}=i;l=await YF(S,s,h,l),m={p2c:h,p2s:tn(S)};break}case"AES-GCM":{let h=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(h instanceof Uint8Array))throw TypeError('"iv" must be an instance of Uint8Array');let S=await tv(Ol(s.slice(0,-2)),d,l,h,new Uint8Array);u=S.ciphertext,m={iv:tn(S.iv),tag:tn(S.tag)}}}if(u??=await fG(s.slice(-6),l,d),!(u instanceof Uint8Array)||!u.byteLength)throw TypeError("JWE key management algorithm did not produce an Encrypted Key");return[d,u,m]}function av(e,t){if(e.zip!==void 0&&e.zip!=="DEF")throw new or('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(e.zip!==void 0&&!t?.zip)throw new _e('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function nU(e){if(typeof globalThis[e]>"u")throw new or(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function oU(e,t,r=1/0){let n=e.writable.getWriter();n.write(t).catch(()=>{}),n.close().catch(()=>{});let o=[],i=0,s=e.readable.getReader();for(;;){let{value:a,done:c}=await s.read();if(c)break;if(o.push(a),i+=a.byteLength,r!==1/0&&i>r)throw new _e("Decompressed plaintext exceeded the configured limit")}return So(...o)}async function iU(e){return nU("CompressionStream"),oU(new CompressionStream("deflate-raw"),e)}async function sU(e,t){return nU("DecompressionStream"),oU(new DecompressionStream("deflate-raw"),e,t)}function SG(e){let{protected:t,ciphertext:r,iv:n,tag:o,aad:i}=e,s;return t!==void 0&&(s=VS(t,_e,"JWE Protected Header is invalid")),[s,Uo(r,"ciphertext",_e),n!==void 0?Uo(n,"iv",_e):void 0,o!==void 0?Uo(o,"tag",_e):void 0,KS((t??"")+(i!==void 0?`.${i}`:""),"aad",_e)]}function aU(e){return[e&&dm("keyManagementAlgorithms",e.keyManagementAlgorithms),e&&dm("contentEncryptionAlgorithms",e.contentEncryptionAlgorithms),e?.crit,e?.maxPBES2Count,e?.maxDecompressedLength]}async function vG(e,t,r,n=SG(e)){let[o,i,s,a,c]=n,{header:l,unprotected:d,aad:u}=e,m;if(l!==void 0||d!==void 0){if(!uc(o,l,d))throw new _e("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");m={...o,...l,...d}}else m=o??{};let[h,S,x,v,w]=t,{encrypted_key:P}=e;pc(_e,JS,x,o,m),av(m,o);let{alg:F,enc:R}=m;if(typeof F!="string"||!F)throw new _e("missing JWE Algorithm (alg) in JWE Header");let b=_l[F];if(P===""&&(!b||!kl(b)))throw new _e("JWE Encrypted Key incorrect type");let A=b?.mode==="integrated-encryption";if(!A&&(typeof R!="string"||!R))throw new _e("missing JWE Encryption Algorithm (enc) in JWE Header");if(h&&!h.has(F)||!h&&F.startsWith("PBES2"))throw new Pu('"alg" (Algorithm) Header Parameter value not allowed');let D;if(A){if(R!==void 0)throw new _e('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new _e("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new _e("JWE Authentication Tag must be empty for integrated encryption")}else{if(S&&!S.has(R))throw new Pu('"enc" (Encryption Algorithm) Header Parameter value not allowed');D=Ol(R)}let B;if(P!==void 0)try{B=Uo(P,"encrypted_key",_e)}catch(Z){if(!b||!kl(b))throw Z;B=new Uint8Array}let J=!1;typeof r=="function"&&(r=await r(o,e),J=!0);let G=b??aa(F);kl(G)&&B===void 0&&(B=new Uint8Array);let ce=await Qi(G.mode==="direct-encryption"?D:G,r,"decrypt"),re;if(G.mode==="integrated-encryption")re=await G.decrypt(ce,B,i,c,o,m);else{let Z=D,se;try{se=await tU(G,Z,ce,B,m,v),kl(G)&&se instanceof Uint8Array&&se.byteLength<<3!==Z.cekBits&&(se=pm(Z))}catch(te){if(te instanceof TypeError||te instanceof _e||te instanceof or)throw te;se=pm(Z)}re=await rv(Z,se,i,s,a,c)}if(m.zip==="DEF"){let Z=w??250000;if(Z===0)throw new or('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(Z!==1/0&&(!Number.isSafeInteger(Z)||Z<1))throw TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");re=await sU(re,Z).catch((se)=>{throw se instanceof _e?se:new _e("Failed to decompress plaintext",{cause:se})})}return{plaintext:re,...o&&{protectedHeader:o},...u!==void 0&&{additionalAuthenticatedData:Uo(u,"aad",_e)},...d&&{sharedUnprotectedHeader:d},...l&&{unprotectedHeader:l},...J&&{key:ce}}}async function cU(e,t,r){if(e instanceof Uint8Array&&(e=Au.decode(e)),typeof e!="string")throw new _e("Compact JWE must be a string or Uint8Array");let{0:n,1:o,2:i,3:s,4:a,length:c}=e.split(".");if(c!==5)throw new _e("Invalid Compact JWE");return vG({ciphertext:s,iv:i||void 0,protected:n,tag:a||void 0,encrypted_key:o||void 0},t,r)}async function _T(e,t,r){return cU(e,aU(r),t)}function lU(e,t,r){if(!uc(e,t,r))throw new _e("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function xG(e,t,r=!1){if(!e[1]&&!e[2]&&!e[3])throw new _e("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");t!==void 0&&(e[8]=t?.crit);let[,n,o,i,s,a,c,l,d]=e;if(s!==void 0&&sa(s,"JWE Additional Authenticated Data"),a!==void 0&&sa(a,"JWE Content Encryption Key"),c!==void 0&&sa(c,"JWE Initialization Vector"),!r&&n!==void 0&&(n=Cl(_e,n)[0],e[1]=n),o!==void 0&&(o=Cl(_e,o)[0],e[2]=o),!r&&i!==void 0&&(i=Cl(_e,i)[0],e[3]=i),l!==void 0&&!Zo(l))throw TypeError("JWE Key Management Parameters must be an object");lU(n,o,i);let u={...n,...o,...i};zS(_e,n),pc(_e,JS,d,n,u),av(u,n);let{alg:m,enc:h}=u;if(typeof m!="string"||!m)throw new _e('JWE "alg" (Algorithm) Header Parameter missing or invalid');let S=_l[m];if(S?.mode==="integrated-encryption"){if(h!==void 0)throw new _e('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(a!==void 0)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${m}`);if(c!==void 0)throw TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${m}`);return[u,void 0,S]}if(typeof h!="string"||!h)throw new _e('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[u,Ol(h),S]}async function wG(e,t,r){let[n,o,i]=t,[s,a,c,l,d,u,m,h,,S]=e,x=a,v=c,w=i??aa(n.alg),P,F,R;w.mode==="integrated-encryption"?R=await Qi(w,r,"encrypt"):[R,P,F]=await rU(w,o,r,n,u,h),F&&(S?v=v?{...v,...F}:F:x=x?{...x,...F}:F,lU(x,v,l));let b=x?tn(JSON.stringify(x)):"",A=d?.byteLength?tn(d):void 0,D=vo(A?`${b}.${A}`:b),B=s;n.zip==="DEF"&&(B=await iU(B).catch((Z)=>{throw new _e("Failed to compress plaintext",{cause:Z})}));let J,G,ce;w.mode==="integrated-encryption"?[P,J]=await w.encrypt(R,B,D,x,n,h):{ciphertext:J,tag:G,iv:ce}=await tv(o,B,R,m,D);let re={ciphertext:tn(J)};return ce&&(re.iv=tn(ce)),G&&(re.tag=tn(G)),P?.byteLength&&(re.encrypted_key=tn(P)),A&&(re.aad=A),x&&(re.protected=b),l&&(re.unprotected=l),v&&(re.header=v),re}async function dU(e,t,r){return wG(e,xG(e,r),t)}function uU(e){return[e.protected,e.encrypted_key,e.iv,e.ciphertext,e.tag].join(".")}var mm=[["verify"],["sign"]];function kT(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:mm}}function ku(e,t){let r={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:r,signing:t?{...r,saltLength:t}:r,usages:mm,minRsaBits:2048}}function OT(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:mm}}function pU(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:mm}}function DT(e){let t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:mm}}var NT=fm({HS256:kT(256),HS384:kT(384),HS512:kT(512),RS256:ku(256),RS384:ku(384),RS512:ku(512),PS256:ku(256,32),PS384:ku(384,48),PS512:ku(512,64),ES256:OT("P-256",256),ES384:OT("P-384",384),ES512:OT("P-521",512),EdDSA:pU(),Ed25519:pU(),"ML-DSA-44":DT(44),"ML-DSA-65":DT(65),"ML-DSA-87":DT(87)});function cv(e){let t=typeof e=="string"?NT[e]:void 0;if(!t)throw new or(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function fU(e){return[e&&dm("algorithms",e.algorithms),e?.crit]}function bG(e){return e===void 0?{}:VS(e,Ar,"JWS Protected Header is invalid")}function EG(e){try{return vo(e)}catch{throw new Ar("JWS Compact Serialization payload must use only ASCII characters")}}async function TG(e,t,r,n,o){let{protected:i,header:s,payload:a}=e,c=o??bG(i);if(!uc(c,s))throw new Ar("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let l={...c,...s},d=GS(c,pc(Ar,QS,t[1],c,l)),{alg:u}=l;if(typeof u!="string"||!u)throw new Ar('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(t[0]&&!t[0].has(u))throw new Pu('"alg" (Algorithm) Header Parameter value not allowed');if(d){if(typeof a!="string")throw new Ar("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new Ar("JWS Payload must be a string or an Uint8Array instance");let m=d||typeof a!="string"?a:n(a),h=!1;typeof r=="function"&&(r=await r(c,e),h=!0);let S=cv(u),x=So(i!==void 0?vo(i):new Uint8Array,vo("."),typeof m=="string"?t[2]??=KS(m,"payload",Ar):m),v=Uo(e.signature,"signature",Ar),w=await Qi(S,r,"verify"),P=await Ji(w,S.subtle,"verify");S.minRsaBits&&Iu(S.alg,P);let F=!1;try{F=await crypto.subtle.verify(S.signing,P,v,x)}catch{}if(!F)throw new ET;let R={payload:typeof m=="string"?Uo(m,"payload",Ar):m};return i!==void 0&&(R.protectedHeader=c),s!==void 0&&(R.unprotectedHeader=s),h?[{...R,key:w},d]:[R,d]}async function mU(e,t,r){if(e instanceof Uint8Array&&(e=Au.decode(e)),typeof e!="string")throw new Ar("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:i,length:s}=e.split(".");if(s!==3)throw new Ar("Invalid Compact JWS");return TG({payload:o,protected:n,signature:i},t,r,EG)}var ym=(e)=>Math.floor(e.getTime()/1000),RG={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},AG=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ou="check_failed";function FT(){throw TypeError("Invalid time period format")}function lv(e){typeof e!="string"&&FT();let t=AG.exec(e);(!t||t[4]&&t[1])&&FT();let r=parseFloat(t[2]),n=Math.round(r*RG[t[3][0].toLowerCase()]);return Number.isFinite(n)||FT(),t[1]==="-"||t[4]==="ago"?-n:n}function Du(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function UT(e,t){if(typeof t!="string")throw TypeError(`"${e}" claim must be a string`)}function PG(e){if(typeof e!="string"&&(!Array.isArray(e)||Array.from(e).some((t)=>typeof t!="string")))throw TypeError('"aud" claim must be a string or an array of strings')}function BT(e,t){return typeof e=="number"?Du(t,e):e instanceof Date?Du(t,ym(e)):ym(new Date)+lv(e)}var yU=(e)=>{let t=e.toLowerCase();return e.includes("/")?t:`application/${t}`},IG=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some((r)=>e.includes(r)):!1;function MT(e,t,r=!1){let n=e[t];if(!(n===void 0&&!r)){if(typeof n!="number")throw new dc(`"${t}" claim must be a number`,e,t,"invalid");return n}}function LT(e,t){throw new dc(`unexpected "${t}" claim value`,e,t,Ou)}function hU(e,t,r={}){let n;try{n=JSON.parse(LS.decode(t))}catch{}if(!Zo(n))throw new Pl("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o!==void 0&&(typeof e.typ!="string"||yU(e.typ)!==yU(o)))throw new dc('unexpected "typ" JWT header value',n,"typ",Ou);let{requiredClaims:i=[],issuer:s,subject:a,audience:c,maxTokenAge:l}=r,d=[...i];l!==void 0&&d.push("iat"),c!==void 0&&d.push("aud"),a!==void 0&&d.push("sub"),s!==void 0&&d.push("iss");for(let P of new Set(d.reverse()))if(!Object.hasOwn(n,P))throw new dc(`missing required "${P}" claim`,n,P,"missing");s!==void 0&&!(Array.isArray(s)?s:[s]).includes(n.iss)&<(n,"iss"),a!==void 0&&n.sub!==a&<(n,"sub"),c!==void 0&&!IG(n.aud,typeof c=="string"?[c]:c)&<(n,"aud");let{clockTolerance:u}=r,m=0;if(typeof u=="string")m=lv(u);else if(u!==void 0){if(typeof u!="number")throw TypeError("Invalid clockTolerance option type");m=u}Du("clockTolerance option",m);let{currentDate:h}=r,S=Du("currentDate option",ym(h===void 0?new Date:h)),x=MT(n,"iat",l!==void 0),v=MT(n,"nbf");if(v!==void 0&&v>S+m)throw new dc('"nbf" claim timestamp check failed',n,"nbf",Ou);let w=MT(n,"exp");if(w!==void 0&&w<=S-m)throw new HS('"exp" claim timestamp check failed',n,"exp",Ou);if(l!==void 0){let P=S-x,F=Du("maxTokenAge option",typeof l=="number"?l:lv(l));if(P-m>F)throw new HS('"iat" claim timestamp check failed (too far in the past)',n,"iat",Ou);if(P<-m)throw new dc('"iat" claim timestamp check failed (it should be in the past)',n,"iat",Ou)}return n}var gU;function mc(e){return gU.get(e)}function SU(e){let t=mc(e);for(let r of["iat","nbf","exp"]){let n=t[r];if(typeof n=="number"&&!Number.isFinite(n))throw TypeError(`"${r}" claim must be a finite number`)}return lc.encode(JSON.stringify(t))}class $T{constructor(e={}){if(!Zo(e))throw TypeError("JWT Claims Set MUST be an object");(gU||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return UT("iss",e),mc(this).iss=e,this}setSubject(e){return UT("sub",e),mc(this).sub=e,this}setAudience(e){return PG(e),mc(this).aud=e,this}setJti(e){return UT("jti",e),mc(this).jti=e,this}setNotBefore(e){return mc(this).nbf=BT(e,"setNotBefore"),this}setExpirationTime(e){return mc(this).exp=BT(e,"setExpirationTime"),this}setIssuedAt(e){let t=mc(this);return e===void 0?t.iat=ym(new Date):typeof e=="string"?t.iat=Du("setIssuedAt",ym(new Date)+lv(e)):t.iat=BT(e,"setIssuedAt"),this}}async function Ei(e,t,r){let[n,o]=await mU(e,fU(r),t);if(!o)throw new Pl("JWTs MUST NOT use unencoded payload");let i=hU(n.protectedHeader,n.payload,r);return{...n,payload:i}}class dv{#e;constructor(e){sa(e,"plaintext"),this.#e=[e]}setContentEncryptionKey(e){return Il(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return Il(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}setProtectedHeader(e){return Il(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return Il(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}async encrypt(e,t){return uU(await dU([...this.#e],e,t))}}async function CG(e,t,r){let[n,o,i,s]=e,a="";if(o!==void 0){let w=Cl(Ar,o);o=w[0],a=tn(w[1])}if(i!==void 0&&(i=Cl(Ar,i)[0]),!o&&!i)throw new Ar("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!uc(o,i))throw new Ar("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...o,...i};zS(Ar,o);let l=GS(o,pc(Ar,QS,s,o,c));l||r?.();let{alg:d}=c;if(typeof d!="string"||!d)throw new Ar('JWS "alg" (Algorithm) Header Parameter missing or invalid');let u=cv(d),m="",h=n,S;if(l){let w=e[4];w?(m=w[0]??=tn(n),h=w[1]??=vo(m)):(m=tn(n),S=lc.encode(`${a}.${m}`))}S??=So(vo(a),vo("."),h);let x=await Ji(await Qi(u,t,"sign"),u.subtle,"sign");u.minRsaBits&&Iu(u.alg,x);let v={signature:tn(new Uint8Array(await crypto.subtle.sign(u.signing,x,S))),payload:m};return o&&(v.protected=a),i&&(v.header=i),[v,l]}async function vU(e,t,r,n,o){let[i]=await CG([e,t,void 0,r],n,o);return`${i.protected}.${i.payload}.${i.signature}`}var _G=$T;class uv extends _G{#e;setProtectedHeader(e){return Il(this.#e,"setProtectedHeader"),this.#e=e,this}async sign(e,t){return vU(SU(this),this.#e,t?.crit,e,()=>{throw new Pl("JWTs MUST NOT use unencoded payload")})}}var Nu='"alg" (Algorithm)';function hm(e='JWK "alg" (Algorithm) Parameter'){throw new or(`Invalid or unsupported ${e} value`)}function pv(e,t){return(typeof e=="string"?NT[e]??_l[e]:void 0)??hm(t)}var kG=(e,t)=>{let r=(e.match(/.{1,64}/g)||[]).join(`
|
|
114
|
+
`);return`-----BEGIN ${t}-----
|
|
115
|
+
${r}
|
|
116
|
+
-----END ${t}-----`},xU=async(e,t,r)=>{if(um(r)){if(r.type!==e)throw TypeError(`key is not a ${e} key`);return r.export({format:"pem",type:t})}if(!gs(r))throw TypeError(fc(r,"CryptoKey","KeyObject"));if(!r.extractable)throw TypeError("CryptoKey is not extractable");if(r.type!==e)throw TypeError(`key is not a ${e} key`);return kG(qS(new Uint8Array(await crypto.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},wU=(e)=>xU("public","spki",e),bU=(e)=>xU("private","pkcs8",e),gm=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0},OG=(e)=>({data:e,pos:0}),qT=(e)=>{let t=e.data[e.pos++];if(t===void 0)throw Error("Unexpected end of ASN.1 input");return t},Sm=(e)=>{let t=qT(e);if(t&128){let r=t&127,n=0;for(let o=0;o<r;o++)n=n<<8|qT(e);return n}return t};var vm=(e,t,r)=>{if(qT(e)!==t)throw Error(r)},EU=(e,t)=>{if(t<0||e.pos+t>e.data.length)throw Error("Unexpected end of ASN.1 input");let r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},DG=(e)=>{vm(e,6,"Expected algorithm OID");let t=Sm(e);return EU(e,t)};function NG(e,t){if(vm(e,48,`Invalid ${t==="spki"?"SPKI":"PKCS#8"} structure`),Sm(e),t==="pkcs8"){vm(e,2,"Expected version field");let r=Sm(e);e.pos+=r}vm(e,48,"Expected algorithm identifier"),Sm(e)}var FG=(e)=>{let t=DG(e);if(gm(t,[43,101,110]))return"X25519";if(!gm(t,[42,134,72,206,61,2,1]))throw Error("Unsupported key algorithm");vm(e,6,"Expected curve OID");let r=Sm(e),n=EU(e,r);if(gm(n,[42,134,72,206,61,3,1,7]))return"P-256";if(gm(n,[43,129,4,0,34]))return"P-384";if(gm(n,[43,129,4,0,35]))return"P-521";throw Error("Unsupported named curve")},TU=async(e,t,r,n)=>{let o=ZS(n?.extractable),i=pv(r,Nu);i.secret&&hm(Nu);let s=e==="spki",a;if(i.resolve)try{let c=OG(t);NG(c,e),a=i.resolve({crv:FG(c)})}catch{throw new or("Invalid or unsupported key format")}else a=i.subtle;return crypto.subtle.importKey(e,t,a,o??s,i.usages[s?0:1])},RU=(e,t)=>jS(e.replace(t,"")),AU=(e,t,r)=>{let n=RU(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);return TU("pkcs8",n,t,r)},PU=(e,t,r)=>{let n=RU(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g);return TU("spki",n,t,r)};function fv(e){return wU(e)}function mv(e){return bU(e)}async function xm(e){if(um(e))if(e.type==="secret")e=e.export();else return e.export({format:"jwk"});if(e instanceof Uint8Array)return{kty:"oct",k:tn(e)};if(!gs(e))throw TypeError(fc(e,"CryptoKey","KeyObject","Uint8Array"));if(!e.extractable)throw TypeError("non-extractable CryptoKey cannot be exported as a JWK");let t=await crypto.subtle.exportKey("jwk",e);delete t.ext,delete t.key_ops,delete t.use,t.kty!=="AKP"&&delete t.alg;for(let r of Object.keys(t))t[r]===void 0&&delete t[r];return t}async function wm(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw TypeError('"spki" must be SPKI formatted string');return PU(e,t,r)}async function bm(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw TypeError('"pkcs8" must be PKCS#8 formatted string');return AU(e,t,r)}function UG(e){let t=e?.modulusLength??2048;if(typeof t!="number"||!Number.isInteger(t)||t<2048)throw new or("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function yv(e,t){let r=ZS(t?.extractable),n=pv(e,Nu);n.secret&&hm(Nu);let o;if(n.resolve){let i=t?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new or("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");o=n.resolve({crv:i})}else{if(n.crv!==void 0&&t?.crv!==void 0&&t.crv!==n.crv)throw new or(`Invalid or unsupported crv option provided, the only supported value for ${e} is ${n.crv}`);o=n.kty[0]==="RSA"?{...n.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:UG(t)}:n.subtle}return crypto.subtle.generateKey(o,r??!1,[...n.usages[1],...n.usages[0]])}var hv=(e)=>e.replace(/\/$/,"");var IU=()=>process.env.FRONTEND_JWT_TOKEN,BG=(e)=>{let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Buffer.from(r,"base64").toString("utf8")},MG=(e)=>{let t=e.split(".");if(t.length<2||!t[1])throw Error("FRONTEND_JWT_TOKEN is not a valid JWT");let r;try{r=JSON.parse(BG(t[1]))}catch{throw Error("FRONTEND_JWT_TOKEN payload is not valid JSON")}if(typeof r!=="object"||r===null)throw Error("FRONTEND_JWT_TOKEN payload must be an object");let n=r,o=n.properties?.clientId;if(typeof o!=="string"||o.length===0)throw Error("FRONTEND_JWT_TOKEN is missing properties.clientId claim");if(typeof n.iss!=="string"||n.iss.length===0)throw Error("FRONTEND_JWT_TOKEN is missing iss claim");let i=typeof n.aud==="string"?n.aud:Array.isArray(n.aud)&&typeof n.aud[0]==="string"?n.aud[0]:void 0;if(!i||i.length===0)throw Error("FRONTEND_JWT_TOKEN is missing aud claim");return{clientId:o,issuer:hv(n.iss),audience:i}},LG=()=>{let e=IU();if(!e)return;return MG(e)};var gv=()=>LG()?.clientId??process.env.OAUTH_CLIENT_ID??"frontend";import{Schema as yt}from"effect";function jT(e){return{...e}}var $G=yt.Struct({userId:yt.String,clientId:yt.String,roles:yt.optional(yt.Array(yt.String)),orgUnitId:yt.optional(yt.String),orgUnitPath:yt.optional(yt.String)}),qG=yt.Struct({userId:yt.String,email:yt.String,picture:yt.optional(yt.String),orgUnitId:yt.String,orgUnitPath:yt.String,roles:yt.Array(yt.String),humanSession:yt.optional(yt.Literal(!0)),delegationRoleSelection:yt.optional(yt.Array(yt.String)),delegation:yt.optional(yt.Struct({id:yt.String,generationId:yt.String,name:yt.String,expiresAt:yt.Number.pipe(yt.int(),yt.nonNegative())})),humanAuthentication:yt.optional(yt.Struct({providerUserId:yt.String,authenticatedAt:yt.Number.pipe(yt.int(),yt.nonNegative()),method:yt.Literal("passkey")}))});var yc=jT({user:yt.standardSchemaV1($G),providerUser:yt.standardSchemaV1(qG)});import{Effect as Tn,Either as HU}from"effect";import{Effect as WT}from"effect";import{Data as Ti}from"effect";class Dl extends Ti.TaggedError("processfocus:internal-tag/openauth/OAuthEndpointError"){}class Pr extends Ti.TaggedError("processfocus:internal-tag/openauth/ClientAuthError"){}class CU extends Ti.TaggedError("processfocus:internal-tag/openauth/MissingParameterError"){get description(){return`Missing parameter: ${this.parameter}`}}class _U extends Ti.TaggedError("processfocus:internal-tag/openauth/UnauthorizedClientError"){get description(){return`Client ${this.clientID} is not authorised to use this redirect_uri: ${this.redirectURI}`}}class kU extends Ti.TaggedError("processfocus:internal-tag/openauth/UnknownStateError"){get description(){return"The browser was in an unknown state. This could be because certain cookies expired or the browser was switched in the middle of an authentication flow."}}class OU extends Ti.TaggedError("processfocus:internal-tag/openauth/InvalidAuthorizationCodeError"){get description(){return"Authorization code has been used or expired"}}class DU extends Ti.TaggedError("processfocus:internal-tag/openauth/InvalidRefreshTokenError"){get description(){return"Refresh token has been used or expired"}}class NU extends Ti.TaggedError("processfocus:internal-tag/openauth/InvalidAccessTokenError"){get description(){return"Invalid access token"}}class FU extends Ti.TaggedError("processfocus:internal-tag/openauth/PKCEValidationError"){get description(){switch(this.reason){case"missing_verifier":return"Missing code_verifier";case"invalid_verifier":return"Code verifier does not match";case"required_for_public_client":return"PKCE is required for this client";default:return this.reason}}}class Sv extends Ti.TaggedError("processfocus:internal-tag/openauth/MissingHostError"){get description(){return"Missing host or x-forwarded-host header in request"}}class HT extends Ti.TaggedError("processfocus:internal-tag/openauth/JwtVerificationError"){}class Nl extends Ti.TaggedError("processfocus:internal-tag/openauth/InvariantViolationError"){}var HG=(e)=>e["x-forwarded-host"]??e.host,Fu=(e)=>{let t=e["cloudfront-forwarded-proto"]??e["x-forwarded-proto"]??"http";return t==="http"||t==="https"?t:void 0},Un=(e)=>{let t=HG(e);if(!t)return WT.fail(new Sv);let r=Fu(e);if(!r)return WT.fail(new Dl({error:"invalid_request",description:"Invalid forwarded protocol header",statusCode:400}));return WT.succeed(`${r}://${t}`)};import{Effect as UU}from"effect";var ei=(e,t)=>cW(e,t).pipe(UU.catchAll(()=>UU.succeed(Vd("Internal Server Error",{status:500})))),Fl=(e,t)=>ei(e,{...t,headers:{...t?.headers,"Cache-Control":"no-store",Pragma:"no-cache"}}),De=(e,t,r)=>ei({error:e,error_description:t},{status:r});import{Context as WG,Data as KG,Effect as aDe,Layer as cDe}from"effect";class KT extends KG.TaggedError("processfocus:internal-tag/ClientRegistryError"){}class Kn extends WG.Tag("processfocus:internal-tag/openauth/ClientRegistryService")(){}import{Context as zG,Data as $U,Effect as ca,Layer as LU}from"effect";import{Effect as rn,Stream as zT}from"effect";import{Context as VG,Data as QG,Effect as Em,Stream as JG}from"effect";var VT=String.fromCharCode(31);function Ul(e){return e.join(VT)}function BU(e){return e.split(VT)}function Tm(e){return e.map((t)=>t.replaceAll(VT,""))}class zi extends QG.TaggedError("processfocus:internal-tag/openauth/StorageError"){}class hr extends VG.Tag("processfocus:internal-tag/openauth/StorageService")(){}var Vt;((i)=>(i.get=(s)=>Em.gen(function*(){return yield*(yield*hr).get(Tm(s))}),i.take=(s)=>Em.gen(function*(){return yield*(yield*hr).take(Tm(s))}),i.set=(s,a,c)=>Em.gen(function*(){return yield*(yield*hr).set(Tm(s),a,c)}),i.remove=(s)=>Em.gen(function*(){return yield*(yield*hr).remove(Tm(s))}),i.scan=(s)=>JG.unwrap(Em.gen(function*(){return(yield*hr).scan(Tm(s))}))))(Vt||={});var QT="ES256",JT="RSA-OAEP-512",MU=rn.gen(function*(){let t=[],r=(n)=>new zi({message:"Failed to import key",cause:n});return yield*Vt.scan(["oauth:key"]).pipe(zT.runForEach(([n,o])=>rn.gen(function*(){let i=yield*rn.tryPromise({try:()=>wm(o.publicKey,"RS512",{extractable:!0}),catch:r}),s=yield*rn.tryPromise({try:()=>bm(o.privateKey,"RS512"),catch:r}),a=yield*rn.tryPromise({try:()=>xm(i),catch:r});a.kid=o.id,t.push({id:o.id,alg:"RS512",created:new Date(o.created),public:i,private:s,expired:new Date(1735858114000),jwk:a})}))),t}),GT=rn.gen(function*(){let e=[],t=(o)=>new zi({message:"Failed to import key",cause:o});if(yield*Vt.scan(["signing:key"]).pipe(zT.runForEach(([o,i])=>rn.gen(function*(){let s=yield*rn.tryPromise({try:()=>wm(i.publicKey,i.alg,{extractable:!0}),catch:t}),a=yield*rn.tryPromise({try:()=>bm(i.privateKey,i.alg),catch:t}),c=yield*rn.tryPromise({try:()=>xm(s),catch:t});c.kid=i.id,c.use="sig";let l={id:i.id,alg:QT,created:new Date(i.created),public:s,private:a,jwk:c};if(i.expired)l.expired=new Date(i.expired);e.push(l)}))),e.sort((o,i)=>i.created.getTime()-o.created.getTime()),e.filter((o)=>!o.expired).length)return e;let r=yield*rn.promise(()=>yv(QT,{extractable:!0})),n={id:crypto.randomUUID(),publicKey:yield*rn.promise(()=>fv(r.publicKey)),privateKey:yield*rn.promise(()=>mv(r.privateKey)),created:Date.now(),alg:QT};return yield*Vt.set(["signing:key",n.id],n),yield*GT}),YT=rn.gen(function*(){let e=[],t=(o)=>new zi({message:"Failed to import key",cause:o});if(yield*Vt.scan(["encryption:key"]).pipe(zT.runForEach(([o,i])=>rn.gen(function*(){let s=yield*rn.tryPromise({try:()=>wm(i.publicKey,i.alg,{extractable:!0}),catch:t}),a=yield*rn.tryPromise({try:()=>bm(i.privateKey,i.alg),catch:t}),c=yield*rn.tryPromise({try:()=>xm(s),catch:t});c.kid=i.id;let l={id:i.id,alg:JT,created:new Date(i.created),public:s,private:a,jwk:c};if(i.expired)l.expired=new Date(i.expired);e.push(l)}))),e.sort((o,i)=>i.created.getTime()-o.created.getTime()),e.filter((o)=>!o.expired).length)return e;let r=yield*rn.promise(()=>yv(JT,{extractable:!0})),n={id:crypto.randomUUID(),publicKey:yield*rn.promise(()=>fv(r.publicKey)),privateKey:yield*rn.promise(()=>mv(r.privateKey)),created:Date.now(),alg:JT};return yield*Vt.set(["encryption:key",n.id],n),yield*YT});class qU extends $U.TaggedError("processfocus:internal-tag/NoSigningKeysError"){}class jU extends $U.TaggedError("processfocus:internal-tag/NoEncryptionKeysError"){}class Kr extends zG.Tag("processfocus:internal-tag/openauth/KeyManagementService")(){}var vv=LU.effect(Kr,ca.gen(function*(){let e=yield*hr,t=LU.succeed(hr,e),r=yield*ca.cached(ca.gen(function*(){let[o,i]=yield*ca.all([GT,MU]).pipe(ca.provide(t));return[...o,...i]})),n=yield*ca.cached(YT.pipe(ca.provide(t)));return{allSigningKeys:r,signingKey:ca.gen(function*(){let i=(yield*r)[0];if(!i)return yield*new qU({message:"No signing keys available"});return i}),encryptionKey:ca.gen(function*(){let i=(yield*n)[0];if(!i)return yield*new jU({message:"No encryption keys available"});return i})}}));var WU=(e)=>e==="localhost"||e==="127.0.0.1"||e==="[::1]",KU=(e)=>{let t=e.replace(/\/+$/,"");return t===""?"/":t},GG=()=>!0,YG=(e,t)=>{if(!GG())return!1;if(typeof e!=="string")return!1;try{let r=new URL(e),n=new URL(t);return r.protocol===n.protocol&&WU(r.hostname)&&WU(n.hostname)&&r.hostname===n.hostname&&KU(r.pathname)===KU(n.pathname)}catch{return!1}};function XG(e){return e.replace(/["\r\n]/g,"")}function ZG(e){try{return{ok:!0,value:Buffer.from(e,"base64").toString("utf8")}}catch{return{ok:!1,error:new Pr({description:"Authorization header is not valid base64"})}}}function e3(e,t){try{return{ok:!0,clientId:decodeURIComponent(e),secret:decodeURIComponent(t)}}catch{return{ok:!1,error:new Pr({description:"Authorization header contains invalid percent encoding"})}}}var t3=(e)=>Tn.gen(function*(){let t=yield*Kr,r=yield*lr,n=yield*Un(r.headers).pipe(Tn.mapError(()=>new Pr({description:"Unable to determine token issuer from request headers"}))),o=yield*t.allSigningKeys.pipe(Tn.mapError(()=>new Pr({description:"Failed to load signing keys for client JWT verification"})));for(let i of o){let s=yield*Tn.tryPromise(()=>Ei(e,()=>Promise.resolve(i.public),{issuer:n})).pipe(Tn.either),a=yield*HU.match(s,{onLeft:()=>Tn.succeed(void 0),onRight:(d)=>{let u=d.payload.properties?.clientId;if(typeof u!=="string"||u.length===0)return Tn.fail(new Pr({description:"Client JWT is missing properties.clientId claim"}));return Tn.succeed(u)}});if(a!==void 0)return a;let c=yield*Tn.tryPromise(()=>Ei(e,()=>Promise.resolve(i.public))).pipe(Tn.either),l=yield*HU.match(c,{onLeft:()=>Tn.succeed(void 0),onRight:(d)=>{if(!YG(d.payload.iss,n))return Tn.succeed(void 0);let u=d.payload.properties?.clientId;if(typeof u!=="string"||u.length===0)return Tn.fail(new Pr({description:"Client JWT is missing properties.clientId claim"}));return Tn.succeed(u)}});if(l!==void 0)return l}return yield*new Pr({description:"Invalid client JWT"})}),Gi=(e)=>Tn.gen(function*(){let t=yield*Kn,n=(yield*lr).headers.authorization,o="none",i,s;if(n){let[l,d]=n.split(" "),u=l?.toLowerCase();if(!u||!d)return yield*new Pr({description:"Authorization header is malformed"});if(u==="basic"){let m=ZG(d);if(!m.ok)return yield*m.error;let h=m.value,S=h.indexOf(":");if(S===-1)return yield*new Pr({description:"Authorization header must contain client_id and client_secret"});let x=e3(h.slice(0,S),h.slice(S+1));if(!x.ok)return yield*x.error;if(i=x.clientId,s=x.secret,o="client_secret_basic",e.has("client_id")||e.has("oauth_client_id"))return yield*new Pr({description:"client_id must not be included in the body when Basic Authorization is used"})}else if(u==="bearer"){o="client_jwt",i=yield*t3(d);let m=e.get("oauth_client_id")??e.get("client_id");if(m&&m!==i)return yield*new Pr({description:"client_id in request body must match properties.clientId in client JWT"})}else return yield*new Pr({description:"Authorization header must use the Basic or Bearer scheme"})}else{let l=e.get("oauth_client_id")??e.get("client_id");if(l)i=l;let d=e.get("client_secret");if(d)s=d,o="client_secret_post"}if(!i)return yield*new Pr({description:"Missing client_id"});let a=yield*t.getClient(i);if(!a)return yield*new Pr({description:"Unknown client"});if(a.secretHash&&o!=="client_jwt"){if(!s)return yield*new Pr({description:"Client authentication is required"});if(!(yield*Tn.tryPromise({try:()=>Bun.password.verify(s,a.secretHash),catch:()=>new Pr({description:"Failed to verify client credentials"})}).pipe(Tn.withSpan("auth.verifyClientSecret"))))return yield*new Pr({description:"Invalid client credentials"})}else if(s)return yield*new Pr({description:"Public clients must not send client_secret"});if(a.isPublic&&o!=="none")return yield*new Pr({description:"Public clients cannot use Authorization headers"});let c=a.enforcedAuthMethod;if(c&&o!==c)return yield*new Pr({description:`Client must authenticate using ${c}`});if(!a.isPublic&&o==="none")return yield*new Pr({description:"Confidential clients must authenticate using Basic, client_secret_post, or Bearer client JWT"});return{client:a,method:o}}).pipe(Tn.withSpan("auth.authenticateClient")),Bl=(e)=>ei({error:"invalid_client",error_description:e},{status:401}).pipe(Tn.map((t)=>dg(t,"WWW-Authenticate",`Basic realm="token", error="invalid_client", error_description="${XG(e)}"`)));import{Clock as r3,Effect as Rm}from"effect";var Ss=(e,t)=>Rm.gen(function*(){let r=yield*Kr,n=yield*lr,o=yield*r3.currentTimeMillis;if(e.expiresAt!==void 0&&(!Number.isFinite(e.expiresAt)||e.expiresAt<=o))return yield*new Dl({error:"invalid_grant",description:"Credential expired",statusCode:400});let i=Math.min(e.ttl.refresh,e.expiresAt===void 0?1/0:(e.expiresAt-o)/1000),s=e.accessTtlOverride??e.ttl.access,a=Math.floor((e.timeUsed??o)/1000),c=Math.floor(Math.min(a+s,e.expiresAt===void 0?1/0:e.expiresAt/1000)),l=Math.floor(c-o/1000);if(l<=0)return yield*new Dl({error:"invalid_grant",description:"Credential expired",statusCode:400});let d=t?.generateRefreshToken??!0;if(e.nextToken!==void 0&&!d&&!t?.allowExistingRefreshToken)return yield*new Nl({message:"Invariant violation: nextToken requires storage write or explicit reuse opt-in"});let u=e.nextToken??(d?crypto.randomUUID():void 0);if(d&&u){let v={type:e.type,properties:e.properties,subject:e.subject,clientID:e.clientID,audience:e.audience,ttl:e.ttl,expiresAt:e.expiresAt,nextToken:crypto.randomUUID()};yield*Vt.set(["oauth:refresh",e.subject,u],v,i)}let m=yield*r.signingKey.pipe(Rm.withSpan("auth.getSigningKey")),h=yield*Un(n.headers),x={access:yield*Rm.promise(()=>new uv({mode:"access",type:e.type,properties:e.properties,aud:e.audience??e.clientID,iss:h,sub:e.subject}).setExpirationTime(c).setProtectedHeader({alg:m.alg,kid:m.id,typ:"JWT"}).sign(m.private)).pipe(Rm.withSpan("auth.signAccessToken")),expiresIn:l};if(!u)return x;return{...x,refresh:[e.subject,u].join(":"),refreshExpiresIn:Math.floor(i)}}).pipe(Rm.withSpan("auth.generateTokens"));import{Data as P3,Effect as Pt,Either as I3,Schema as nUe}from"effect";import{Effect as eR}from"effect";import{Context as n3,Duration as o3,Effect as wv,Ref as xv}from"effect";var i3=n3.GenericTag("processfocus:internal-tag/openauth/CookieService"),s3=()=>wv.gen(function*(){let t=(yield*lr).headers.cookie??"",r=MH(t),n=yield*xv.make([]);return{get:(i)=>wv.succeed(r[i]),set:(i,s,a={})=>xv.update(n,(c)=>[...c,{name:i,value:s,options:a}]),delete:(i,s={})=>xv.update(n,(a)=>[...a,{name:i,value:"",options:{...s,maxAge:0,expires:new Date(0)}}]),getPending:()=>xv.get(n)}}),Uu=(e,t,r={})=>{let n={maxAge:r.maxAge!==void 0?o3.seconds(r.maxAge):void 0,expires:r.expires,path:r.path,domain:r.domain,secure:r.secure,httpOnly:r.httpOnly,sameSite:r.sameSite},o=UH(e,t,n);return BH(o)},LDe=Rb((e)=>wv.gen(function*(){let t=yield*s3(),r=yield*e.pipe(wv.provideService(i3,t)),n=yield*t.getPending();if(n.length===0)return r;let o=n.map(({name:i,value:s,options:a})=>Uu(i,s,a));return Qd(r,{"Set-Cookie":o.join(", ")})}));function bv(e,t){let r=`${e}${t}`;return r.endsWith("/")?r.slice(0,-1):r}function XT(e){try{let t=new URL(e);if(t.hash)return{ok:!1};if(t.protocol!=="https:"&&t.protocol!=="http:")return{ok:!1};return{ok:!0,value:t.toString()}}catch{return{ok:!1}}}function ZT(e){let t=new URL(e);if(t.hash)throw Error(`Redirect URI must not contain a fragment: ${e}`);if(t.protocol!=="https:"&&t.protocol!=="http:")throw Error(`Redirect URI must use http or https: ${e}`);return t.toString()}function Ev(e,t){let r=XT(e);if(!r.ok)return!1;let n=new URL(r.value),o=bv(n.origin,n.pathname);return t.some((i)=>{let s=new URL(i);if(s.protocol==="http:"&&s.hostname==="localhost"&&s.port===""&&n.protocol==="http:"&&n.hostname==="localhost"){let c=bv(s.origin,s.pathname),l=bv("http://localhost",n.pathname);return c===l}return bv(s.origin,s.pathname)===o})}import{Context as a3,Data as c3,Effect as HDe,Layer as WDe}from"effect";class Tv extends c3.TaggedError("processfocus:internal-tag/openauth/OnRefreshScopeError"){}class vs extends a3.Tag("processfocus:internal-tag/openauth/IssuerCallbacks")(){}import{Context as l3,Data as d3,Effect as Ml,Layer as u3,Schema as Rv}from"effect";class Av extends d3.TaggedError("processfocus:internal-tag/openauth/DecryptionError"){}var VU=Rv.parseJson(Rv.Unknown);class la extends l3.Tag("processfocus:internal-tag/openauth/EncryptionService")(){}var Pv=u3.effect(la,Ml.gen(function*(){let e=yield*Kr;return{encrypt:(t)=>Ml.gen(function*(){let r=yield*e.encryptionKey,n=yield*Rv.encode(VU)(t).pipe(Ml.mapError((i)=>new zi({message:"Failed to encode value for encryption",cause:i})));return yield*Ml.promise(()=>new dv(new TextEncoder().encode(n)).setProtectedHeader({alg:"RSA-OAEP-512",enc:"A256GCM"}).encrypt(r.public))}),decrypt:(t)=>Ml.gen(function*(){let r=yield*e.encryptionKey,n=yield*Ml.tryPromise({try:()=>_T(t,r.private),catch:(i)=>new Av({message:"Failed to decrypt value",cause:i})}),o=new TextDecoder().decode(n.plaintext);return yield*Rv.decodeUnknown(VU)(o).pipe(Ml.mapError((i)=>new Av({message:"Failed to decode decrypted value",cause:i})))})}}));import{Context as p3,Effect as XDe,Layer as ZDe}from"effect";class Ri extends p3.Tag("processfocus:internal-tag/openauth/ProviderRegistryService")(){}function f3(e,t){if(!Ev(t,e.redirectUris))return{ok:!1};return{ok:!0,value:ZT(t)}}var Am=(e,t,r,n)=>{let o=new URL(e);if(o.searchParams.set("error",t),o.searchParams.set("error_description",r),n)o.searchParams.set("state",n);return eR.succeed(lg(o.toString(),{status:302}))},tR=eR.gen(function*(){let e=yield*Kn,t=yield*la,r=yield*Ri,n=yield*vs,o=yield*lr,i=o.url,s=i.indexOf("?"),a=s>=0?new URLSearchParams(i.slice(s+1)):new URLSearchParams,c=a.get("provider")??void 0,l=a.get("response_type")??void 0,d=a.get("redirect_uri")??void 0,u=a.get("state")??void 0,m=a.get("client_id")??void 0,h=a.get("audience")??void 0,S=a.get("code_challenge")??void 0,x=a.get("code_challenge_method")??void 0;if(!m)return yield*De("invalid_request","Missing parameter: client_id",400);if(!d)return yield*De("invalid_request","Missing parameter: redirect_uri",400);if(!l)return yield*De("invalid_request","Missing parameter: response_type",400);let v=m,w=d,P=e.staticClients.get(v);if(!P)return yield*De("unauthorized_client",`Unknown client: ${v}`,400);let F=f3(P,w);if(!F.ok)return yield*De("unauthorized_client",`Invalid redirect_uri for client: ${v}`,400);let R=F.value;if(l!=="code")return yield*Am(R,"invalid_request","Only response_type=code is supported",u);if(S&&x!=="S256")return yield*Am(R,"invalid_request","code_challenge_method must be S256",u);if(P.isPublic&&(!S||x!=="S256"))return yield*Am(R,"invalid_request","Public clients must use PKCE with code_challenge_method=S256",u);if(n.start)yield*n.start(o);if(!(yield*n.allow({clientID:v,redirectURI:R,audience:h},o)))return yield*De("unauthorized_client",`Client not allowed: ${v}`,400);let A={response_type:"code",redirect_uri:R,state:u,client_id:v,audience:h,pkce:S&&x?{challenge:S,method:"S256"}:void 0},D=[...r.staticProviders.keys()],B=D.includes("dummy"),J=yield*r.listProviders,G;if(c)if(D.includes(c))G=`/oauth/${c}/authorize`;else if(J.includes(c))G=`/oauth/${c}/authorize`;else if(B)yield*eR.logWarning(`Provider '${c}' not found, falling back to dummy provider`),G="/oauth/dummy/authorize";else return yield*Am(R,"invalid_request",`Provider '${c}' is not configured`,u);else if(D.length===1)G=`/oauth/${D[0]}/authorize`;else return yield*Am(R,"invalid_request","Missing parameter: provider",u);let ce=yield*t.encrypt(A),re=Fu(o.headers)==="https",Z=Uu("authorization",ce,{maxAge:86400,httpOnly:!0,secure:re,sameSite:re?"none":"lax"});return lg(G,{status:302}).pipe(dg("Set-Cookie",Z))});import{Effect as QU}from"effect";var m3={"Cache-Control":"public, max-age=3600, s-maxage=86400"},rR=QU.gen(function*(){let e=yield*Ri,t=yield*lr,r=yield*Un(t.headers),n=yield*e.listProviders,o=n.includes("passkey")?yield*e.isPasskeyOpenRegistration:!1,i={issuer:r,authorization_endpoint:`${r}/oauth/authorize`,token_endpoint:`${r}/oauth/token`,jwks_uri:`${r}/.well-known/jwks.json`,response_types_supported:["code"],token_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post","none"],code_challenge_methods_supported:["S256"],grant_types_supported:["authorization_code","refresh_token","client_credentials"],providers_supported:[...n],passkey_open_registration:o};return yield*ei(i).pipe(QU.map((s)=>Qd(s,m3)))});import{Effect as JU}from"effect";var y3={"Cache-Control":"public, max-age=3600, s-maxage=86400"},nR=JU.gen(function*(){let r={keys:(yield*(yield*Kr).allSigningKeys).map((n)=>({...n.jwk,alg:n.alg,exp:n.expired?Math.floor(n.expired.getTime()/1000):void 0}))};return yield*ei(r).pipe(JU.map((n)=>Qd(n,y3)))});import{Effect as zU}from"effect";var oR=(e)=>zU.gen(function*(){let t=e.get("token");if(!t)return yield*De("invalid_request","Missing token",400);let r=t.split(":"),n=r.pop(),o=r.join(":");if(o&&n)yield*Vt.remove(["oauth:refresh",o,n]);else yield*zU.logDebug("Token revocation: malformed token format");return yield*ei({success:!0})});import{Effect as w3}from"effect";import{Effect as Pm}from"effect";import{timingSafeEqual as h3}from"crypto";function GU(e,t){if(typeof e!=="string"||typeof t!=="string")return!1;if(e.length!==t.length)return!1;return h3(Buffer.from(e),Buffer.from(t))}async function g3(e,t){if(t==="plain")return e;let n=new TextEncoder().encode(e),o=await crypto.subtle.digest("SHA-256",n);return tn(new Uint8Array(o))}async function YU(e,t,r="S256"){let n=await g3(e,r);return GU(n,t)}var Iv=(e)=>Pm.gen(function*(){let t=e.get("code");if(!t)return yield*De("invalid_request","Missing code",400);let r=e.get("redirect_uri");if(!r)return yield*De("invalid_request","Missing redirect_uri",400);let n=yield*Gi(e).pipe(Pm.catchTag("processfocus:internal-tag/openauth/ClientAuthError",(h)=>Pm.succeed({error:h})));if("error"in n)return yield*Bl(n.error.description);let{client:o}=n,i=XT(r);if(!i.ok)return yield*De("invalid_redirect_uri","Redirect URI mismatch",400);let s=i.value,a=["oauth:code",t],c=yield*Vt.get(a);if(!c)return yield*De("invalid_grant","Authorization code has been used or expired",400);if(c.redirectURI!==s)return yield*De("invalid_redirect_uri","Redirect URI mismatch",400);let l=e.get("client_id");if(l&&l!==o.id)return yield*De("unauthorized_client","Client is not authorized to use this authorization code",403);if(c.clientID!==o.id)return yield*De("unauthorized_client","Client is not authorized to use this authorization code",403);if(o.isPublic&&!c.pkce)return yield*De("invalid_grant","PKCE is required for this client",400);if(c.pkce){let h=e.get("code_verifier");if(!h)return yield*De("invalid_grant","Missing code_verifier",400);if(!(yield*Pm.promise(()=>YU(h,c.pkce.challenge,c.pkce.method)).pipe(Pm.withSpan("auth.validatePKCE"))))return yield*De("invalid_grant","Code verifier does not match",400)}let d=yield*Ss({type:c.type,properties:c.properties,subject:c.subject,clientID:c.clientID,audience:c.audience,ttl:c.ttl,timeUsed:void 0,nextToken:void 0});yield*Vt.remove(a);let{refresh:u,refreshExpiresIn:m}=d;if(!u||m===void 0)return yield*new Nl({message:"Invariant violation: authorization_code flow must issue a refresh token"});return yield*Fl({access_token:d.access,expires_in:d.expiresIn,refresh_token:u,refresh_expires_in:m})});import{Effect as iR}from"effect";var Cv=(e)=>iR.gen(function*(){let t=yield*Ri,r=yield*Gi(e).pipe(iR.catchTag("processfocus:internal-tag/openauth/ClientAuthError",(i)=>iR.succeed({error:i})));if("error"in r)return yield*Bl(r.error.description);let{client:n}=r;if(n.isPublic)return yield*De("unauthorized_client","Public clients cannot use client_credentials",400);let o=e.get("provider");if(!o)return{needsSuccessCallback:!0,scope:e.get("scope")??void 0,clientId:n.id,clientAudience:n.audience};if(!t.hasProvider(o))return yield*De("invalid_request","Invalid provider parameter",400);return{needsUpstreamProvider:!0,provider:o,clientId:n.id,clientAudience:n.audience}});import{Clock as sR,Effect as gc,Option as x3}from"effect";import{Context as XU,Layer as QNe}from"effect";class hc extends XU.Tag("processfocus:internal-tag/openauth/TokenTtlConfig")(){}class Bu extends XU.Tag("processfocus:internal-tag/openauth/SubjectsConfig")(){}import{Context as S3,Effect as Yi,Layer as ZU,Stream as v3}from"effect";class da extends S3.Tag("processfocus:internal-tag/openauth/CookieAuthService")(){}var _v=ZU.effect(da,Yi.gen(function*(){let e=yield*la,t=yield*hr,r=ZU.succeed(hr,t);return{set:(n,o,i,s)=>Yi.gen(function*(){let a=yield*e.encrypt(i);return Uu(n,a,{maxAge:o,httpOnly:!0,secure:s,sameSite:s?"none":"lax"})}),get:(n,o)=>Yi.gen(function*(){let s=Object.fromEntries(n.split(";").map((a)=>{let[c,...l]=a.trim().split("=");return[c,l.join("=")]}))[o];if(!s)return;return yield*e.decrypt(s).pipe(Yi.tapError((a)=>Yi.logError("Failed to decrypt cookie").pipe(Yi.annotateLogs({key:o,error:a}))),Yi.orElseSucceed(()=>{return}))}),unset:(n)=>Yi.succeed(Uu(n,"",{maxAge:0,expires:new Date(0)})),invalidate:(n)=>Yi.gen(function*(){let o=[];yield*Vt.scan(["oauth:refresh",n]).pipe(v3.runForEach(([i])=>Yi.sync(()=>{o.push(i)})));for(let i of o)yield*Vt.remove(i)}).pipe(Yi.provide(r))}}));var kv=(e)=>gc.gen(function*(){let t=yield*hc,r=yield*da,n=yield*vs,o=e.get("refresh_token");if(!o)return yield*De("invalid_request","Missing refresh_token",400);let i=yield*Gi(e).pipe(gc.catchTag("processfocus:internal-tag/openauth/ClientAuthError",(A)=>gc.succeed({error:A})));if("error"in i)return yield*Bl(i.error.description);let{client:s}=i,a=o.split(":"),c=a.pop(),l=a.join(":"),d=["oauth:refresh",l,c],u=yield*Vt.get(d);if(!u)return yield*De("invalid_grant","Refresh token has been used or expired",400);if(u.clientID!==s.id)return yield*De("unauthorized_client","Client is not authorized to use this refresh token",403);let m=yield*sR.currentTimeMillis;if(u.expiresAt!==void 0&&(!Number.isFinite(u.expiresAt)||m>=u.expiresAt))return yield*Vt.remove(d),yield*De("invalid_grant","Credential expired",400);if(n.onRefresh){let A=yield*n.onRefresh({type:u.type,properties:u.properties,clientId:s.id,scope:e.get("scope")}).pipe(gc.option);if(x3.isNone(A))return yield*De("invalid_grant","Session is no longer valid",400);u={...u,properties:A.value.properties}}let{refreshReuse:h,refreshRetention:S}=t,x=!u.timeUsed;if(h<=0)yield*Vt.remove(d);else if(!u.timeUsed){let A=yield*sR.currentTimeMillis,D={...u,timeUsed:A};yield*Vt.set(d,D,h+S)}else if((yield*sR.currentTimeMillis)>u.timeUsed+h*1000)return yield*r.invalidate(l),yield*De("invalid_grant","Refresh token has been used or expired",400);let v=e.get("scope"),w=u,P;if(v&&n.onRefreshScope){let A=u.properties.userId;if(!A)return yield*De("invalid_scope","Cannot determine user for scope validation",400);let D=yield*n.onRefreshScope({userId:A,clientId:s.id,scope:v,currentProperties:u.properties}).pipe(gc.map((B)=>({success:!0,...B})),gc.catchAll(()=>gc.succeed({success:!1})));if(!D.success)return yield*De("invalid_scope","Failed to process scope request",400);w={...u,properties:D.properties},P=D.accessTokenTtl}let F=yield*Ss({type:w.type,properties:w.properties,subject:w.subject,clientID:w.clientID,audience:w.audience,ttl:w.ttl,expiresAt:w.expiresAt,accessTtlOverride:P,timeUsed:u.timeUsed,nextToken:u.nextToken},{generateRefreshToken:x,allowExistingRefreshToken:!x}),{refresh:R,refreshExpiresIn:b}=F;if(!R||b===void 0)return yield*new Nl({message:"Invariant violation: refresh_token flow must issue a refresh token"});return yield*Fl({access_token:F.access,refresh_token:R,expires_in:F.expiresIn,refresh_expires_in:b})}).pipe(gc.catchTag("processfocus:internal-tag/openauth/OAuthEndpointError",(t)=>De(t.error,t.description,t.statusCode)));var aR=(e)=>w3.gen(function*(){let t=e.get("grant_type");if(t==="authorization_code")return yield*Iv(e);if(t==="refresh_token")return yield*kv(e);if(t==="client_credentials"){let r=yield*Cv(e);if("status"in r)return r;if("needsSuccessCallback"in r)return{type:"client_credentials_direct",scope:r.scope,clientId:r.clientId,clientAudience:r.clientAudience};if("needsUpstreamProvider"in r)return{type:"client_credentials_upstream",provider:r.provider,clientId:r.clientId,clientAudience:r.clientAudience};return r}return yield*De("unsupported_grant_type","Invalid grant_type",400)});import{Effect as Ov,Either as b3}from"effect";var cR=Ov.gen(function*(){let e=yield*Kr,t=yield*Kn,r=yield*Bu,n=yield*lr,o=n.headers.authorization;if(!o)return yield*De("invalid_request","Missing Authorization header",400);let[i,s]=o.split(" ");if(i!=="Bearer")return yield*De("invalid_request","Missing or invalid Authorization header",400);if(!s)return yield*De("invalid_request","Missing token",400);let a=[...t.configuredClientIds],c=yield*e.signingKey,l=yield*Un(n.headers),d=yield*Ov.tryPromise({try:()=>Ei(s,()=>Promise.resolve(c.public),{issuer:l,audience:a}),catch:(x)=>new HT({message:"Access token verification failed",cause:x})}).pipe(Ov.either);if(b3.isLeft(d))return yield*De("invalid_token","Invalid token",401);let u=d.right,m=r[u.payload.type];if(!m)return yield*De("invalid_token","Invalid token",401);let h=m["~standard"].validate(u.payload.properties),S=yield*Ov.promise(async()=>h instanceof Promise?h:h);if(!S.issues&&u.payload.mode==="access")return yield*ei(S.value);return yield*De("invalid_token","Invalid token",401)});import{Effect as E3}from"effect";var eB=(e,t)=>{let r={};if(t.origin==="*")r["Access-Control-Allow-Origin"]="*";else if(typeof t.origin==="string")r["Access-Control-Allow-Origin"]=t.origin;else if(Array.isArray(t.origin)&&e){if(t.origin.includes(e))r["Access-Control-Allow-Origin"]=e,r.Vary="Origin"}if(t.credentials)r["Access-Control-Allow-Credentials"]="true";if(t.allowMethods&&t.allowMethods.length>0)r["Access-Control-Allow-Methods"]=t.allowMethods.join(", ");if(t.allowHeaders&&t.allowHeaders.length>0)r["Access-Control-Allow-Headers"]=t.allowHeaders.join(", ");if(t.exposeHeaders&&t.exposeHeaders.length>0)r["Access-Control-Expose-Headers"]=t.exposeHeaders.join(", ");if(t.maxAge!==void 0)r["Access-Control-Max-Age"]=t.maxAge.toString();return r},Im=(e={})=>Rb((t)=>E3.gen(function*(){let r=yield*lr,n=r.headers.origin;if(r.method==="OPTIONS"){let s=eB(n,e);return cg({status:204}).pipe(Qd(s))}let o=yield*t,i=eB(n,e);return Qd(o,i)}));import{Effect as T3}from"effect";var Dv={"X-Content-Type-Options":"nosniff","Referrer-Policy":"no-referrer","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'; frame-ancestors 'none'; sandbox"},tB=Rb((e)=>T3.gen(function*(){let t=yield*e,r={},n=t.headers;if(!n["x-content-type-options"])r["X-Content-Type-Options"]=Dv["X-Content-Type-Options"];if(!n["referrer-policy"])r["Referrer-Policy"]=Dv["Referrer-Policy"];if(!n["x-frame-options"])r["X-Frame-Options"]=Dv["X-Frame-Options"];if(!n["content-security-policy"])r["Content-Security-Policy"]=Dv["Content-Security-Policy"];return Qd(t,r)}));import{Data as R3,Effect as A3}from"effect";class rB extends R3.TaggedError("processfocus:internal-tag/openauth/ProviderCallbackError"){}var lR=(e,t)=>A3.tryPromise({try:t,catch:(r)=>new rB({message:e,cause:r})});class iB extends P3.TaggedError("processfocus:internal-tag/openauth/ResolveIssuerClientsError"){}function C3(e){let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw Error(`Origin must use http or https: ${e}`);return t.origin}var oB=(e,t,r,n,o)=>({name:e,invalidate:(i)=>r.invalidate(i),success:(i)=>Pt.gen(function*(){let s=yield*lr,a=s.headers.cookie??"",c=yield*r.get(a,"authorization");if(!c)return yield*De("invalid_request","Missing authorization state",400);let l=crypto.randomUUID(),d=typeof i==="object"&&i!==null?{provider:e,...i}:{provider:e};return yield*t.success({subject(m,h,S){return Pt.gen(function*(){let x=S?.subject??(yield*t.resolveSubject(m,h)),v=n.staticClients.get(c.client_id);yield*Vt.set(["oauth:code",l],{type:m,properties:h,clientID:c.client_id,redirectURI:c.redirect_uri,subject:x,audience:c.audience??v?.audience,ttl:{access:S?.ttl?.access??o.access,refresh:S?.ttl?.refresh??o.refresh},pkce:c.pkce},600);let w=new URL(c.redirect_uri);if(w.searchParams.set("code",l),c.state)w.searchParams.set("state",c.state);let P=yield*r.unset("authorization");return lg(w.toString(),{status:302}).pipe(dg("Set-Cookie",P))})},error(m,h){return Pt.gen(function*(){let S=new URL(c.redirect_uri);if(S.searchParams.set("error",m),S.searchParams.set("error_description",h),c.state)S.searchParams.set("state",c.state);let x=yield*r.unset("authorization");return lg(S.toString(),{status:302}).pipe(dg("Set-Cookie",x))})}},d,s)}),setCookie:(i,s,a)=>Pt.gen(function*(){let c=yield*lr,l=Fu(c.headers)==="https";return yield*r.set(i,s,a,l)}),getCookie:(i)=>Pt.gen(function*(){let a=(yield*lr).headers.cookie??"";return yield*r.get(a,i)}),deleteCookie:(i)=>r.unset(i)}),sB=Pt.gen(function*(){let e=yield*Kn,t=yield*da,r=yield*Ri,n=yield*hc,o=yield*vs,i=new Set;for(let w of e.staticClients.values())for(let P of w.corsOrigins)i.add(C3(P));let s=(w,P,F,R,b,A)=>Ss({type:F,properties:R,subject:b,clientID:w,audience:P,ttl:A,timeUsed:void 0,nextToken:void 0},{generateRefreshToken:!1}),a=Gd("/.well-known/jwks.json",nR.pipe(Im({origin:"*",allowMethods:["GET"]}))),c=Gd("/.well-known/oauth-authorization-server",rR.pipe(Pt.catchTag("processfocus:internal-tag/openauth/MissingHostError",(w)=>De("server_error",w.description,500)),Im({origin:"*",allowMethods:["GET"]}))),l=Gd("/oauth/authorize",tR),d=mi("/oauth/token",Pt.gen(function*(){let w=yield*lr;if(!(w.headers["content-type"]??"").includes("application/x-www-form-urlencoded"))return yield*De("invalid_request","Content-Type must be application/x-www-form-urlencoded",415);let F=yield*w.urlParamsBody,R=new Map;for(let[A,D]of F)R.set(A,D);let b=yield*aR(R);if("status"in b&&typeof b.status==="number")return b;if("type"in b){if(b.type==="client_credentials_direct")return yield*o.success({subject(D,B,J){return Pt.gen(function*(){let G=J?.subject??(yield*o.resolveSubject(D,B)),ce=yield*s(b.clientId,b.clientAudience,D,B,G,{access:J?.ttl?.access??n.access,refresh:J?.ttl?.refresh??n.refresh});return yield*Fl({access_token:ce.access,expires_in:ce.expiresIn})})},error(D,B){return De(D,B,400)}},{provider:"credentials",clientID:b.clientId,scope:b.scope},w);if(b.type==="client_credentials_upstream"){let A=yield*r.resolveProvider(b.provider);if(!A)return yield*De("invalid_request","Invalid provider parameter",400);if(!A.client)return yield*De("invalid_request","Provider does not support client_credentials",400);let D=R.get("provider_client_id")??R.get("client_id"),B=R.get("provider_client_secret")??R.get("client_secret");if(!D||!B)return yield*De("invalid_request","Missing client credentials for upstream provider",400);let J=yield*lR("Provider client credentials callback failed",()=>A.client({clientID:D,clientSecret:B,params:Object.fromEntries(R)})).pipe(Pt.either);if(I3.isLeft(J)){let Z=J.left;return yield*Pt.logError("Provider client callback failed").pipe(Pt.annotateLogs({message:Z.message,cause:String(Z.cause)})),yield*De("server_error","Authentication provider callback failed",500)}let G=J.right,ce=typeof G==="object"&&G!==null?{provider:b.provider,...G}:{provider:b.provider};return yield*o.success({subject(Z,se,te){return Pt.gen(function*(){let Ne=te?.subject??(yield*o.resolveSubject(Z,se)),ze=yield*s(b.clientId,b.clientAudience,Z,se,Ne,{access:te?.ttl?.access??n.access,refresh:te?.ttl?.refresh??n.refresh});return yield*Fl({access_token:ze.access,expires_in:ze.expiresIn})})},error(Z,se){return De(Z,se,400)}},ce,w)}}return yield*De("server_error","Unknown token endpoint result",500)}).pipe(i.size>0?Im({origin:Array.from(i),allowHeaders:["Content-Type","Authorization"],allowMethods:["POST"]}):(w)=>w)),u=Gd("/oauth/userinfo",cR.pipe(Pt.catchTag("processfocus:internal-tag/openauth/MissingHostError",(w)=>De("server_error",w.description,500)))),m=mi("/oauth/revoke",Pt.gen(function*(){let P=yield*(yield*lr).urlParamsBody,F=new Map;for(let[R,b]of P)F.set(R,b);return yield*oR(F)}).pipe(Im({origin:"*",allowMethods:["POST"]}))),h=KW.pipe(a,c,l,d,u,m);for(let[w,P]of r.staticProviders){let F=oB(w,o,t,e,n),R=P.init(F),b=`/oauth/${w}`,A=R.pipe(Ob((D)=>Pt.gen(function*(){let B=yield*lr,J=new URL(B.url,"http://localhost").pathname,G=`${b}${J}`,ce=B.modify({headers:Qs({...B.headers,"x-original-path":G})});return yield*D.pipe(Pt.provideService(lr,ce),Pt.catchTag("processfocus:internal-tag/openauth/ProviderCallbackError",(re)=>Pt.gen(function*(){return yield*Pt.logError("Provider callback failed").pipe(Pt.annotateLogs({providerName:w,message:re.message,cause:String(re.cause)})),yield*De("server_error","Authentication provider callback failed",500)})))})));h=h.pipe(VW(b,A))}let S=new Map,v=Pt.gen(function*(){let w=yield*lr,P=yield*Un(w.headers),F=new URL(w.url,P),R=F.pathname.split("/").filter(Boolean);if(R.length<2||R[0]!=="oauth")return yield*Vd("Provider not found",{status:404});let b=R[1];if(!b)return yield*Vd("Provider not found",{status:404});if(r.hasProvider(b))return yield*Vd("Not found",{status:404});let A=S.get(b);if(!A){let se=yield*r.resolveProvider(b);if(!se)return yield*Vd(`Provider '${b}' not found`,{status:404});A=se,S.set(b,A)}let D=oB(b,o,t,e,n),B=A.init(D),J=`/${R.slice(2).join("/")}`;yield*Pt.log("Dynamic provider handling").pipe(Pt.annotateLogs({providerName:b,subPath:J,originalUrl:F.toString()}));let G=new URL(J,P);G.search=F.search;let ce=Qs({...w.headers,"x-original-path":F.pathname}),re=w.modify({url:G.toString(),headers:ce}),Z=yield*B.pipe(Pt.provideService(lr,re),Pt.catchTag("processfocus:internal-tag/openauth/ProviderCallbackError",(se)=>Pt.gen(function*(){return yield*Pt.logError("Provider callback failed").pipe(Pt.annotateLogs({providerName:b,subPath:J,message:se.message,cause:String(se.cause)})),yield*De("server_error","Authentication provider callback failed",500)})),Pt.catchAllCause((se)=>Pt.gen(function*(){return yield*Pt.logError("Dynamic provider handler error").pipe(Pt.annotateLogs({providerName:b,subPath:J,cause:se.toString()})),Vd("Internal server error",{status:500})})));return yield*Pt.log("Dynamic provider response").pipe(Pt.annotateLogs({providerName:b,status:Z.status})),Z}).pipe(Pt.catchTag("processfocus:internal-tag/openauth/MissingHostError",(w)=>De("server_error",w.description,500)));return h=h.pipe(Gd("/oauth/:provider/authorize",v),Gd("/oauth/:provider/callback",v),mi("/oauth/:provider/callback",v),mi("/oauth/:provider/challenge",v),mi("/oauth/:provider/verify",v),mi("/oauth/:provider/register",v),mi("/oauth/:provider/register-options",v),mi("/oauth/:provider/register-verify",v),mi("/oauth/:provider/authenticate",v),mi("/oauth/:provider/auth-options",v),mi("/oauth/:provider/auth-verify",v),mi("/oauth/:provider/registration-session-exchange",v)),h.pipe(Ob((w)=>Pt.gen(function*(){let P=yield*lr;if(Fu(P.headers)===void 0)return yield*De("invalid_request","Invalid forwarded protocol header",400);return yield*w})),Ob(tB))});import{Effect as SUe}from"effect";import{Effect as IUe}from"effect";var aB=(e)=>{let t=typeof Uint8Array>"u"?[]:new Uint8Array(256),r=64;for(let n=0;n<64;n++)t[e.charCodeAt(n)]=n;return t},O3=aB("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),D3=aB("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),N3=/^[-A-Za-z0-9\-_]*$/,F3=/^[-A-Za-z0-9+/]*={0,3}$/,xs={};xs.toArrayBuffer=(e,t)=>{let r=e.length,n=e.length*0.75,o,i=0,s,a,c,l;if(e[e.length-1]==="="){if(n--,e[e.length-2]==="=")n--}let d=new ArrayBuffer(n),u=new Uint8Array(d),m=t?D3:O3;for(o=0;o<r;o+=4)s=m[e.charCodeAt(o)],a=m[e.charCodeAt(o+1)],c=m[e.charCodeAt(o+2)],l=m[e.charCodeAt(o+3)],u[i++]=s<<2|a>>4,u[i++]=(a&15)<<4|c>>2,u[i++]=(c&3)<<6|l&63;return d};xs.fromArrayBuffer=(e,t)=>{let r=new Uint8Array(e),n,o="",i=r.length,s=t?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(n=0;n<i;n+=3)o+=s[r[n]>>2],o+=s[(r[n]&3)<<4|r[n+1]>>4],o+=s[(r[n+1]&15)<<2|r[n+2]>>6],o+=s[r[n+2]&63];let a=i%3;if(a===2)o=o.substring(0,o.length-1)+(t?"":"=");else if(a===1)o=o.substring(0,o.length-2)+(t?"":"==");return o};xs.toString=(e,t)=>new TextDecoder().decode(xs.toArrayBuffer(e,t));xs.fromString=(e,t)=>xs.fromArrayBuffer(new TextEncoder().encode(e),t);xs.validate=(e,t)=>{if(!(typeof e==="string"||e instanceof String))return!1;try{return t?N3.test(e):F3.test(e)}catch(r){return!1}};xs.base64=xs;var vc=xs;function Mu(e,t="base64url"){let r=vc.toArrayBuffer(e,t==="base64url");return new Uint8Array(r)}function ws(e,t="base64url"){let r=new Uint8Array(e);return vc.fromArrayBuffer(r.buffer,t==="base64url")}function U3(e){let t=vc.toArrayBuffer(e,!0);return vc.fromArrayBuffer(t)}function Lu(e){return vc.toString(e,!0)}function B3(e){return vc.validate(e,!1)}function cB(e){return e=lB(e),vc.validate(e,!0)}function lB(e){return e.replace(/=/g,"")}function $u(e,t,r){if(t<24)return[t,1];let n=e.byteLength-r-1,o=new DataView(e.buffer,r+1),i,s=0;switch(t){case 24:{if(n>0)i=o.getUint8(0),s=2;break}case 25:{if(n>1)i=o.getUint16(0,!1),s=3;break}case 26:{if(n>3)i=o.getUint32(0,!1),s=5;break}case 27:{if(n>7){let a=o.getBigUint64(0,!1);if(a>=24n&&a<=Number.MAX_SAFE_INTEGER)return[Number(a),9]}break}}if(i&&i>=24)return[i,s];throw Error("Length not supported or not well formed")}var Nv=0,Cm=1,SR=2,vR=3,xR=4,wR=5,bR=6,dB=7;function bs(e,t){let r=e<<5;if(t<0)throw Error("CBOR Data Item argument must not be negative");let n;if(typeof t=="number"){if(!Number.isInteger(t))throw Error("CBOR Data Item argument must be an integer");n=BigInt(t)}else n=t;if(e==Cm){if(n==0n)throw Error("CBOR Data Item argument cannot be zero when negative");n=n-1n}if(n>18446744073709551615n)throw Error("CBOR number out of range");let o=new Uint8Array(8);if(new DataView(o.buffer).setBigUint64(0,n,!1),n<=23)return[r|o[7]];else if(n<=255)return[r|24,o[7]];else if(n<=65535)return[r|25,...o.slice(6)];else if(n<=4294967295)return[r|26,...o.slice(4)];else return[r|27,...o]}class Uv{constructor(e,t){Object.defineProperty(this,"tagId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tagValue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tagId=e,this.tagValue=t}get tag(){return this.tagId}get value(){return this.tagValue}}function uB(e,t,r){return $u(e,t,r)}function M3(e,t,r){let[n,o]=uB(e,t,r);return[-n-1,o]}function pB(e,t,r){let[n,o]=$u(e,t,r),i=r+o;return[new Uint8Array(e.buffer.slice(i,i+n)),o+n]}var L3=new TextDecoder;function $3(e,t,r){let[n,o]=pB(e,t,r);return[L3.decode(n),o]}function q3(e,t,r){if(t===0)return[[],1];let[n,o]=$u(e,t,r),i=o,s=[];for(let a=0;a<n;a++){if(e.byteLength-r-i<=0)throw Error("array is not supported or well formed");let[l,d]=Ll(e,r+i);s.push(l),i+=d}return[s,i]}var Fv="Map is not supported or well formed";function j3(e,t,r){if(t===0)return[new Map,1];let[n,o]=$u(e,t,r),i=o,s=new Map;for(let a=0;a<n;a++){let c=e.byteLength-r-i;if(c<=0)throw Error(Fv);let[l,d]=Ll(e,r+i);if(i+=d,c-=d,c<=0)throw Error(Fv);if(typeof l!=="string"&&typeof l!=="number")throw Error(Fv);if(s.has(l))throw Error(Fv);let[u,m]=Ll(e,r+i);i+=m,s.set(l,u)}return[s,i]}function H3(e,t){if(t+3>e.byteLength)throw Error("CBOR stream ended before end of Float 16");let r=e.getUint16(t+1,!1);if(r==31744)return[1/0,3];else if(r==32256)return[NaN,3];else if(r==64512)return[-1/0,3];throw Error("Float16 data is unsupported")}function W3(e,t){if(t+5>e.byteLength)throw Error("CBOR stream ended before end of Float 32");return[e.getFloat32(t+1,!1),5]}function K3(e,t){if(t+9>e.byteLength)throw Error("CBOR stream ended before end of Float 64");return[e.getFloat64(t+1,!1),9]}function V3(e,t,r){let[n,o]=$u(e,t,r),[i,s]=Ll(e,r+o);return[new Uv(n,i),o+s]}function Ll(e,t){if(t>=e.byteLength)throw Error("CBOR stream ended before tag value");let r=e.getUint8(t),n=r>>5,o=r&31;switch(n){case Nv:return uB(e,o,t);case Cm:return M3(e,o,t);case SR:return pB(e,o,t);case vR:return $3(e,o,t);case xR:return q3(e,o,t);case wR:return j3(e,o,t);case bR:return V3(e,o,t);case dB:switch(o){case 20:return[!1,1];case 21:return[!0,1];case 22:return[null,1];case 23:return[void 0,1];case 25:return H3(e,t);case 26:return W3(e,t);case 27:return K3(e,t)}}throw Error(`Unsupported or not well formed at ${t}`)}function Q3(e){if(e===!0)return 245;else if(e===!1)return 244;else if(e===null)return 246;return 247}function J3(e){if(Math.fround(e)==e||!Number.isFinite(e)||Number.isNaN(e)){let t=new Uint8Array(5);return t[0]=250,new DataView(t.buffer).setFloat32(1,e,!1),t}else{let t=new Uint8Array(9);return t[0]=251,new DataView(t.buffer).setFloat64(1,e,!1),t}}function z3(e){if(typeof e=="number"){if(Number.isSafeInteger(e))if(e<0)return bs(Cm,Math.abs(e));else return bs(Nv,e);return[J3(e)]}else if(e<0n)return bs(Cm,e*-1n);else return bs(Nv,e)}var G3=new TextEncoder;function Y3(e,t){t.push(...bs(vR,e.length)),t.push(G3.encode(e))}function X3(e,t){t.push(...bs(SR,e.length)),t.push(e)}function Z3(e,t){t.push(...bs(xR,e.length));for(let r of e)_m(r,t)}function e9(e,t){t.push(new Uint8Array(bs(wR,e.size)));for(let[r,n]of e.entries())_m(r,t),_m(n,t)}function t9(e,t){t.push(...bs(bR,e.tag)),_m(e.value,t)}function _m(e,t){if(typeof e=="boolean"||e===null||e==null){t.push(Q3(e));return}if(typeof e=="number"||typeof e=="bigint"){t.push(...z3(e));return}if(typeof e=="string"){Y3(e,t);return}if(e instanceof Uint8Array){X3(e,t);return}if(Array.isArray(e)){Z3(e,t);return}if(e instanceof Map){e9(e,t);return}if(e instanceof Uv){t9(e,t);return}throw Error("Not implemented")}function ER(e,t){if(e.byteLength===0||e.byteLength<=t||t<0)throw Error("No data");if(e instanceof Uint8Array)return Ll(new DataView(e.buffer),t);else if(e instanceof ArrayBuffer)return Ll(new DataView(e),t);return Ll(e,t)}function TR(e){let t=[];_m(e,t);let r=0;for(let i of t)if(typeof i=="number")r+=1;else r+=i.length;let n=new Uint8Array(r),o=0;for(let i of t)if(typeof i=="number")n[o]=i,o+=1;else n.set(i,o),o+=i.length;return n}function qu(e){let t=new Uint8Array(e),r=ER(t,0),[n]=r;return n}function fB(e){return TR(e)}function mB(e){let t=e.get(Ze.kty);return RR(t)&&t===ti.OKP}function xc(e){let t=e.get(Ze.kty);return RR(t)&&t===ti.EC2}function Hu(e){let t=e.get(Ze.kty);return RR(t)&&t===ti.RSA}var Ze;(function(e){e[e.kty=1]="kty",e[e.alg=3]="alg",e[e.crv=-1]="crv",e[e.x=-2]="x",e[e.y=-3]="y",e[e.n=-1]="n",e[e.e=-2]="e"})(Ze||(Ze={}));var ti;(function(e){e[e.OKP=1]="OKP",e[e.EC2=2]="EC2",e[e.RSA=3]="RSA"})(ti||(ti={}));function RR(e){return Object.values(ti).indexOf(e)>=0}var Zn;(function(e){e[e.P256=1]="P256",e[e.P384=2]="P384",e[e.P521=3]="P521",e[e.ED25519=6]="ED25519",e[e.SECP256K1=8]="SECP256K1"})(Zn||(Zn={}));function yB(e){return Object.values(Zn).indexOf(e)>=0}var tt;(function(e){e[e.ES256=-7]="ES256",e[e.EdDSA=-8]="EdDSA",e[e.ES384=-35]="ES384",e[e.ES512=-36]="ES512",e[e.PS256=-37]="PS256",e[e.PS384=-38]="PS384",e[e.PS512=-39]="PS512",e[e.ES256K=-47]="ES256K",e[e.RS256=-257]="RS256",e[e.RS384=-258]="RS384",e[e.RS512=-259]="RS512",e[e.RS1=-65535]="RS1"})(tt||(tt={}));function Es(e){return Object.values(tt).indexOf(e)>=0}function wc(e){if([tt.RS1].indexOf(e)>=0)return"SHA-1";else if([tt.ES256,tt.PS256,tt.RS256].indexOf(e)>=0)return"SHA-256";else if([tt.ES384,tt.PS384,tt.RS384].indexOf(e)>=0)return"SHA-384";else if([tt.ES512,tt.PS512,tt.RS512,tt.EdDSA].indexOf(e)>=0)return"SHA-512";throw Error(`Could not map COSE alg value of ${e} to a WebCrypto alg`)}var km=void 0;function Ai(){return new Promise((t,r)=>{if(km)return t(km);let n=o9.stubThisGlobalThisCrypto();if(n)return km=n,t(km);return r(new hB)})}class hB extends Error{constructor(){super("An instance of the Crypto API could not be located");this.name="MissingWebCrypto"}}var o9={stubThisGlobalThisCrypto:()=>globalThis.crypto,setCachedCrypto:(e)=>{km=e}};async function gB(e,t){let r=await Ai(),n=wc(t),o=await r.subtle.digest(n,e);return new Uint8Array(o)}async function AR(e){return(await Ai()).getRandomValues(e),e}async function Wu(e){let t=await Ai(),{keyData:r,algorithm:n}=e;return t.subtle.importKey("jwk",r,n,!1,["verify"])}async function Bv(e){let{cosePublicKey:t,signature:r,data:n,shaHashOverride:o}=e,i=await Ai(),s=t.get(Ze.alg),a=t.get(Ze.crv),c=t.get(Ze.x),l=t.get(Ze.y);if(!s)throw Error("Public key was missing alg (EC2)");if(!a)throw Error("Public key was missing crv (EC2)");if(!c)throw Error("Public key was missing x (EC2)");if(!l)throw Error("Public key was missing y (EC2)");let d;if(a===Zn.P256)d="P-256";else if(a===Zn.P384)d="P-384";else if(a===Zn.P521)d="P-521";else throw Error(`Unexpected COSE crv value of ${a} (EC2)`);let u={kty:"EC",crv:d,x:ws(c),y:ws(l),ext:!1},h=await Wu({keyData:u,algorithm:{name:"ECDSA",namedCurve:d}}),S=wc(s);if(o)S=wc(o);let x={name:"ECDSA",hash:{name:S}};return i.subtle.verify(x,h,r,n)}function PR(e){if([tt.EdDSA].indexOf(e)>=0)return"Ed25519";else if([tt.ES256,tt.ES384,tt.ES512,tt.ES256K].indexOf(e)>=0)return"ECDSA";else if([tt.RS256,tt.RS384,tt.RS512,tt.RS1].indexOf(e)>=0)return"RSASSA-PKCS1-v1_5";else if([tt.PS256,tt.PS384,tt.PS512].indexOf(e)>=0)return"RSA-PSS";throw Error(`Could not map COSE alg value of ${e} to a WebCrypto key alg name`)}async function Mv(e){let{cosePublicKey:t,signature:r,data:n,shaHashOverride:o}=e,i=await Ai(),s=t.get(Ze.alg),a=t.get(Ze.n),c=t.get(Ze.e);if(!s)throw Error("Public key was missing alg (RSA)");if(!Es(s))throw Error(`Public key had invalid alg ${s} (RSA)`);if(!a)throw Error("Public key was missing n (RSA)");if(!c)throw Error("Public key was missing e (RSA)");let l={kty:"RSA",alg:"",n:ws(a),e:ws(c),ext:!1},d={name:PR(s),hash:{name:wc(s)}},u={name:PR(s)};if(o)d.hash.name=wc(o);if(d.name==="RSASSA-PKCS1-v1_5"){if(d.hash.name==="SHA-256")l.alg="RS256";else if(d.hash.name==="SHA-384")l.alg="RS384";else if(d.hash.name==="SHA-512")l.alg="RS512";else if(d.hash.name==="SHA-1")l.alg="RS1"}else if(d.name==="RSA-PSS"){let h=0;if(d.hash.name==="SHA-256")l.alg="PS256",h=32;else if(d.hash.name==="SHA-384")l.alg="PS384",h=48;else if(d.hash.name==="SHA-512")l.alg="PS512",h=64;u.saltLength=h}else throw Error(`Unexpected RSA key algorithm ${s} (${d.name})`);let m=await Wu({keyData:l,algorithm:d});return i.subtle.verify(u,m,r,n)}function Lv(e){let t=$v(e);return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20,32)].join("-")}function fn(e){let t;if(typeof e==="string")if(cB(e))t=U3(e);else if(B3(e))t=e;else throw Error("Certificate is not a valid base64 or base64url string");else t=ws(e,"base64");let r="";for(let n=0;n<Math.ceil(t.length/64);n+=1){let o=64*n;r+=`${t.substr(o,64)}
|
|
117
|
+
`}return r=`-----BEGIN CERTIFICATE-----
|
|
118
|
+
${r}-----END CERTIFICATE-----
|
|
119
|
+
`,r}function Ku(e){let t=qu(e),r=Uint8Array.from([4]),n=t.get(Ze.x),o=t.get(Ze.y);if(!n)throw Error("COSE public key was missing x");if(o)return Pi([r,n,o]);return Pi([r,n])}function SB(e){return i9.stubThis(qu(e))}var i9={stubThis:(e)=>e};function IR(e){let t=Lu(e),r=JSON.parse(t);return s9.stubThis(r)}var s9={stubThis:(e)=>e};function bc(e){return a9.stubThis(qu(e))}var a9={stubThis:(e)=>e};async function vB(){let e=new Uint8Array(32);return await AR(e),c9.stubThis(e)}var c9={stubThis:(e)=>e};var Cs={};$C(Cs,{Any:()=>fa,BaseBlock:()=>mn,BaseStringBlock:()=>Qv,BitString:()=>Is,BmpString:()=>Yu,Boolean:()=>Qu,CharacterString:()=>sp,Choice:()=>Mm,Constructed:()=>Rn,DATE:()=>Yv,DEFAULT_MAX_CONTENT_LENGTH:()=>OB,DEFAULT_MAX_DEPTH:()=>_B,DEFAULT_MAX_NODES:()=>kB,DateTime:()=>Zv,Duration:()=>ex,EndOfContent:()=>zv,Enumerated:()=>Ju,GeneralString:()=>ip,GeneralizedTime:()=>ap,GraphicString:()=>op,HexBlock:()=>Rs,IA5String:()=>np,Integer:()=>Ac,Null:()=>As,NumericString:()=>Zu,ObjectIdentifier:()=>zu,OctetString:()=>Ps,Primitive:()=>Rc,PrintableString:()=>ep,RawData:()=>lM,RelativeObjectIdentifier:()=>Gu,Repeated:()=>Vu,Sequence:()=>xo,Set:()=>qo,TIME:()=>tx,TeletexString:()=>tp,TimeOfDay:()=>Xv,UTCTime:()=>jl,UniversalString:()=>Xu,Utf8String:()=>Zi,ValueBlock:()=>Vn,VideotexString:()=>rp,ViewWriter:()=>Um,VisibleString:()=>ql,compareSchema:()=>ua,fromBER:()=>ya,verifySchema:()=>O9});/*!
|
|
120
|
+
* MIT License
|
|
121
|
+
*
|
|
122
|
+
* Copyright (c) 2017-2024 Peculiar Ventures, LLC
|
|
123
|
+
*
|
|
124
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
125
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
126
|
+
* in the Software without restriction, including without limitation the rights
|
|
127
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
128
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
129
|
+
* furnished to do so, subject to the following conditions:
|
|
130
|
+
*
|
|
131
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
132
|
+
* copies or substantial portions of the Software.
|
|
133
|
+
*
|
|
134
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
135
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
136
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
137
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
138
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
139
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
140
|
+
* SOFTWARE.
|
|
141
|
+
*
|
|
142
|
+
*/class ye{static isArrayBuffer(e){return Object.prototype.toString.call(e)==="[object ArrayBuffer]"}static toArrayBuffer(e){if(this.isArrayBuffer(e))return e;if(e.byteLength===e.buffer.byteLength)return e.buffer;if(e.byteOffset===0&&e.byteLength===e.buffer.byteLength)return e.buffer;return this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let r=ye.toUint8Array(e),n=ye.toUint8Array(t);if(r.length!==n.byteLength)return!1;for(let o=0;o<r.length;o++)if(r[o]!==n[o])return!1;return!0}static concat(...e){let t;if(Array.isArray(e[0])&&!(e[1]instanceof Function))t=e[0];else if(Array.isArray(e[0])&&e[1]instanceof Function)t=e[0];else if(e[e.length-1]instanceof Function)t=e.slice(0,e.length-1);else t=e;let r=0;for(let i of t)r+=i.byteLength;let n=new Uint8Array(r),o=0;for(let i of t){let s=this.toUint8Array(i);n.set(s,o),o+=s.length}if(e[e.length-1]instanceof Function)return this.toView(n,e[e.length-1]);return n.buffer}}var CR="string",l9=/^[0-9a-f\s]+$/i,d9=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,u9=/^[a-zA-Z0-9-_]+$/;class _R{static fromString(e){let t=unescape(encodeURIComponent(e)),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r.buffer}static toString(e){let t=ye.toUint8Array(e),r="";for(let o=0;o<t.length;o++)r+=String.fromCharCode(t[o]);return decodeURIComponent(escape(r))}}class Xi{static toString(e,t=!1){let r=ye.toArrayBuffer(e),n=new DataView(r),o="";for(let i=0;i<r.byteLength;i+=2){let s=n.getUint16(i,t);o+=String.fromCharCode(s)}return o}static fromString(e,t=!1){let r=new ArrayBuffer(e.length*2),n=new DataView(r);for(let o=0;o<e.length;o++)n.setUint16(o*2,e.charCodeAt(o),t);return r}}class Ee{static isHex(e){return typeof e===CR&&l9.test(e)}static isBase64(e){return typeof e===CR&&d9.test(e)}static isBase64Url(e){return typeof e===CR&&u9.test(e)}static ToString(e,t="utf8"){let r=ye.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(r);case"binary":return this.ToBinary(r);case"hex":return this.ToHex(r);case"base64":return this.ToBase64(r);case"base64url":return this.ToBase64Url(r);case"utf16le":return Xi.toString(r,!0);case"utf16":case"utf16be":return Xi.toString(r);default:throw Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return Xi.fromString(e,!0);case"utf16":case"utf16be":return Xi.fromString(e);default:throw Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=ye.toUint8Array(e);if(typeof btoa<"u"){let r=this.ToString(t,"binary");return btoa(r)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!Ee.isBase64(t))throw TypeError("Argument 'base64Text' is not Base64 encoded");if(typeof atob<"u")return this.FromBinary(atob(t));else return new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!Ee.isBase64Url(t))throw TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=Ee.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return _R.fromString(e);case"utf16":case"utf16be":return Xi.fromString(e);case"utf16le":case"usc2":return Xi.fromString(e,!0);default:throw Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=Ee.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return _R.toString(e);case"utf16":case"utf16be":return Xi.toString(e);case"utf16le":case"usc2":return Xi.toString(e,!0);default:throw Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,r=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);return r.buffer}static ToBinary(e){let t=ye.toUint8Array(e),r="";for(let n=0;n<t.length;n++)r+=String.fromCharCode(t[n]);return r}static ToHex(e){let t=ye.toUint8Array(e),r="",n=t.length;for(let o=0;o<n;o++){let i=t[o];if(i<16)r+="0";r+=i.toString(16)}return r}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!Ee.isHex(t))throw TypeError("Argument 'hexString' is not HEX encoded");if(t.length%2)t=`0${t}`;let r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n=n+2){let o=t.slice(n,n+2);r[n/2]=parseInt(o,16)}return r.buffer}static ToUtf16String(e,t=!1){return Xi.toString(e,t)}static FromUtf16String(e,t=!1){return Xi.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let r=0;r<t;r++)e+="=";return e}static formatString(e){return(e===null||e===void 0?void 0:e.replace(/[\n\r\t ]/g,""))||""}}Ee.DEFAULT_UTF8_ENCODING="utf8";function xB(...e){let t=e.map((o)=>o.byteLength).reduce((o,i)=>o+i),r=new Uint8Array(t),n=0;return e.map((o)=>new Uint8Array(o)).forEach((o)=>{for(let i of o)r[n++]=i}),r.buffer}function qv(e,t){if(!(e&&t))return!1;if(e.byteLength!==t.byteLength)return!1;let r=new Uint8Array(e),n=new Uint8Array(t);for(let o=0;o<e.byteLength;o++)if(r[o]!==n[o])return!1;return!0}/*!
|
|
143
|
+
Copyright (c) Peculiar Ventures, LLC
|
|
144
|
+
*/function $l(e,t){let r=0;if(e.length===1)return e[0];for(let n=e.length-1;n>=0;n--)r+=e[e.length-1-n]*Math.pow(2,t*n);return r}function Ec(e,t,r=-1){let n=r,o=e,i=0,s=Math.pow(2,t);for(let a=1;a<8;a++){if(e<s){let c;if(n<0)c=new ArrayBuffer(a),i=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),i=n}let l=new Uint8Array(c);for(let d=a-1;d>=0;d--){let u=Math.pow(2,d*t);l[i-d-1]=Math.floor(o/u),o-=l[i-d-1]*u}return c}s*=Math.pow(2,t)}return new ArrayBuffer(0)}function jv(...e){let t=0,r=0;for(let i of e)t+=i.length;let n=new ArrayBuffer(t),o=new Uint8Array(n);for(let i of e)o.set(i,r),r+=i.length;return o}function kR(){let e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=e[0]===255&&e[1]&128,c=e[0]===0&&(e[1]&128)===0;if(a||c)this.warnings.push("Needlessly long format")}let t=new ArrayBuffer(this.valueHex.byteLength),r=new Uint8Array(t);for(let a=0;a<this.valueHex.byteLength;a++)r[a]=0;r[0]=e[0]&128;let n=$l(r,8),o=new ArrayBuffer(this.valueHex.byteLength),i=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)i[a]=e[a];return i[0]&=127,$l(i,8)-n}function wB(e){let t=e<0?e*-1:e,r=128;for(let n=1;n<8;n++){if(t<=r){if(e<0){let s=r-t,a=Ec(s,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Ec(t,8,n),i=new Uint8Array(o);if(i[0]&128){let s=o.slice(0),a=new Uint8Array(s);o=new ArrayBuffer(o.byteLength+1),i=new Uint8Array(o);for(let c=0;c<s.byteLength;c++)i[c+1]=a[c];i[0]=0}return o}r*=Math.pow(2,8)}return new ArrayBuffer(0)}function bB(e,t){if(e.byteLength!==t.byteLength)return!1;let r=new Uint8Array(e),n=new Uint8Array(t);for(let o=0;o<r.length;o++)if(r[o]!==n[o])return!1;return!0}function Lo(e,t){let r=e.toString(10);if(t<r.length)return"";let n=t-r.length,o=Array.from({length:n});for(let s=0;s<n;s++)o[s]="0";return o.join("").concat(r)}var kBe=Math.log(2);/*!
|
|
145
|
+
* Copyright (c) 2014, GMO GlobalSign
|
|
146
|
+
* Copyright (c) 2015-2022, Peculiar Ventures
|
|
147
|
+
* All rights reserved.
|
|
148
|
+
*
|
|
149
|
+
* Author 2014-2019, Yury Strozhevsky
|
|
150
|
+
*
|
|
151
|
+
* Redistribution and use in source and binary forms, with or without modification,
|
|
152
|
+
* are permitted provided that the following conditions are met:
|
|
153
|
+
*
|
|
154
|
+
* * Redistributions of source code must retain the above copyright notice, this
|
|
155
|
+
* list of conditions and the following disclaimer.
|
|
156
|
+
*
|
|
157
|
+
* * Redistributions in binary form must reproduce the above copyright notice, this
|
|
158
|
+
* list of conditions and the following disclaimer in the documentation and/or
|
|
159
|
+
* other materials provided with the distribution.
|
|
160
|
+
*
|
|
161
|
+
* * Neither the name of the copyright holder nor the names of its
|
|
162
|
+
* contributors may be used to endorse or promote products derived from
|
|
163
|
+
* this software without specific prior written permission.
|
|
164
|
+
*
|
|
165
|
+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
|
166
|
+
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
167
|
+
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
168
|
+
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
|
169
|
+
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
|
170
|
+
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
|
171
|
+
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
|
172
|
+
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
173
|
+
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
|
174
|
+
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
175
|
+
*
|
|
176
|
+
*/function Hv(){if(typeof BigInt>"u")throw Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function DR(e){let t=0,r=0;for(let o=0;o<e.length;o++){let i=e[o];t+=i.byteLength}let n=new Uint8Array(t);for(let o=0;o<e.length;o++){let i=e[o];n.set(new Uint8Array(i),r),r+=i.byteLength}return n.buffer}function ma(e,t,r,n){if(!(t instanceof Uint8Array))return e.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1;if(!t.byteLength)return e.error="Wrong parameter: inputBuffer has zero length",!1;if(r<0)return e.error="Wrong parameter: inputOffset less than zero",!1;if(n<0)return e.error="Wrong parameter: inputLength less than zero",!1;if(t.byteLength-r-n<0)return e.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1;return!0}class Um{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return DR(this.items)}}var Dm=[new Uint8Array([1])],EB="0123456789",OR="name",TB="valueHexView",m9="isHexOnly",y9="idBlock",h9="tagClass",g9="tagNumber",S9="isConstructed",v9="fromBER",x9="toBER",w9="local",$o="",Ts=new ArrayBuffer(0),Vv=new Uint8Array(0),Fm="EndOfContent",AB="OCTET STRING",PB="BIT STRING";function Rs(e){var t;return t=class extends e{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}constructor(...n){var o;super(...n);let i=n[0]||{};this.isHexOnly=(o=i.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=i.valueHex?ye.toUint8Array(i.valueHex):Vv}fromBER(n,o,i,s){let a=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!ma(this,a,o,i))return-1;let c=o+i;if(this.valueHexView=a.subarray(o,c),!this.valueHexView.length)return this.warnings.push("Zero buffer length"),o;return this.blockLength=i,c}toBER(n=!1){if(!this.isHexOnly)return this.error="Flag 'isHexOnly' is not set, abort",Ts;if(n)return new ArrayBuffer(this.valueHexView.byteLength);return this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:Ee.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}class Tc{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:t=$o,warnings:r=[],valueBeforeDecode:n=Vv}={}){this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=ye.toUint8Array(n)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:Ee.ToHex(this.valueBeforeDecodeView)}}}Tc.NAME="baseBlock";class Vn extends Tc{fromBER(e,t,r,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}Vn.NAME="valueBlock";class NR extends Rs(Tc){constructor({idBlock:e={}}={}){var t,r,n,o;super();if(e)this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?ye.toUint8Array(e.valueHex):Vv,this.tagClass=(r=e.tagClass)!==null&&r!==void 0?r:-1,this.tagNumber=(n=e.tagNumber)!==null&&n!==void 0?n:-1,this.isConstructed=(o=e.isConstructed)!==null&&o!==void 0?o:!1;else this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",Ts}if(this.isConstructed)t|=32;if(this.tagNumber<31&&!this.isHexOnly){let n=new Uint8Array(1);if(!e){let o=this.tagNumber;o&=31,t|=o,n[0]=t}return n.buffer}if(!this.isHexOnly){let n=Ec(this.tagNumber,7),o=new Uint8Array(n),i=n.byteLength,s=new Uint8Array(i+1);if(s[0]=t|31,!e){for(let a=0;a<i-1;a++)s[a+1]=o[a]|128;s[i]=o[i-1]}return s.buffer}let r=new Uint8Array(this.valueHexView.byteLength+1);if(r[0]=t|31,!e){let n=this.valueHexView;for(let o=0;o<n.length-1;o++)r[o+1]=n[o]|128;r[this.valueHexView.byteLength]=n[n.length-1]}return r.buffer}fromBER(e,t,r){let n=ye.toUint8Array(e);if(!ma(this,n,t,r))return-1;let o=n.subarray(t,t+r);if(o.length===0)return this.error="Zero buffer length",-1;switch(o[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(o[0]&32)===32,this.isHexOnly=!1;let s=o[0]&31;if(s!==31)this.tagNumber=s,this.blockLength=1;else{let a=0;while(!0){let l=a+1;if(l>=o.length)return this.error="End of input reached before message was fully decoded",-1;if(a++,(o[l]&128)===0)break}this.blockLength=a+1;let c=this.valueHexView=new Uint8Array(a);for(let l=0;l<a;l++)c[l]=o[l+1]&127;if(this.blockLength<=9)this.tagNumber=$l(c,7);else this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded")}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}}NR.NAME="identificationBlock";class FR extends Tc{constructor({lenBlock:e={}}={}){var t,r,n;super();this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(r=e.longFormUsed)!==null&&r!==void 0?r:!1,this.length=(n=e.length)!==null&&n!==void 0?n:0}fromBER(e,t,r){let n=ye.toUint8Array(e);if(!ma(this,n,t,r))return-1;let o=n.subarray(t,t+r);if(o.length===0)return this.error="Zero buffer length",-1;if(o[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=o[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(o[0]&128),this.longFormUsed===!1)return this.length=o[0],this.blockLength=1,t+this.blockLength;let i=o[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>o.length)return this.error="End of input reached before message was fully decoded",-1;let s=t+1,a=n.subarray(s,s+i);if(a[i-1]===0)this.warnings.push("Needlessly long encoded length");if(this.length=$l(a,8),this.longFormUsed&&this.length<=127)this.warnings.push("Unnecessary usage of long length form");return this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,r;if(this.length>127)this.longFormUsed=!0;if(this.isIndefiniteForm){if(t=new ArrayBuffer(1),e===!1)r=new Uint8Array(t),r[0]=128;return t}if(this.longFormUsed){let n=Ec(this.length,8);if(n.byteLength>127)return this.error="Too big length",Ts;if(t=new ArrayBuffer(n.byteLength+1),e)return t;let o=new Uint8Array(n);r=new Uint8Array(t),r[0]=n.byteLength|128;for(let i=0;i<n.byteLength;i++)r[i+1]=o[i];return t}if(t=new ArrayBuffer(1),e===!1)r=new Uint8Array(t),r[0]=this.length;return t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}}FR.NAME="lengthBlock";var Te={};class mn extends Tc{constructor({name:e=$o,optional:t=!1,primitiveSchema:r,...n}={},o){super(n);if(this.name=e,this.optional=t,r)this.primitiveSchema=r;this.idBlock=new NR(n),this.lenBlock=new FR(n),this.valueBlock=o?new o(n):new Vn(n)}fromBER(e,t,r,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length,n);if(o===-1)return this.error=this.valueBlock.error,o;if(!this.idBlock.error.length)this.blockLength+=this.idBlock.blockLength;if(!this.lenBlock.error.length)this.blockLength+=this.lenBlock.blockLength;if(!this.valueBlock.error.length)this.blockLength+=this.valueBlock.blockLength;return o}toBER(e,t){let r=t||new Um;if(!t)IB(this);let n=this.idBlock.toBER(e);if(r.write(n),this.lenBlock.isIndefiniteForm)r.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,r),r.write(new ArrayBuffer(2));else{let o=this.valueBlock.toBER(e);this.lenBlock.length=o.byteLength;let i=this.lenBlock.toBER(e);r.write(i),r.write(o)}if(!t)return r.final();return Ts}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};if(this.primitiveSchema)e.primitiveSchema=this.primitiveSchema.toJSON();return e}toString(e="ascii"){if(e==="ascii")return this.onAsciiEncoding();return Ee.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,t=Ee.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${t}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),r=e.toBER();return bB(t,r)}}mn.NAME="BaseBlock";function IB(e){var t;if(e instanceof Te.Constructed){for(let r of e.valueBlock.value)if(IB(r))e.lenBlock.isIndefiniteForm=!0}return!!((t=e.lenBlock)===null||t===void 0?void 0:t.isIndefiniteForm)}class Qv extends mn{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=$o,...t}={},r){super(t,r);if(e)this.fromString(e)}fromBER(e,t,r){let n=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);if(n===-1)return this.error=this.valueBlock.error,n;if(this.fromBuffer(this.valueBlock.valueHexView),!this.idBlock.error.length)this.blockLength+=this.idBlock.blockLength;if(!this.lenBlock.error.length)this.blockLength+=this.lenBlock.blockLength;if(!this.valueBlock.error.length)this.blockLength+=this.valueBlock.blockLength;return n}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}}Qv.NAME="BaseStringBlock";class UR extends Rs(Vn){constructor({isHexOnly:e=!0,...t}={}){super(t);this.isHexOnly=e}}UR.NAME="PrimitiveValueBlock";var CB;class Rc extends mn{constructor(e={}){super(e,UR);this.idBlock.isConstructed=!1}}CB=Rc;(()=>{Te.Primitive=CB})();Rc.NAME="PRIMITIVE";var _B=100,kB=1e4,OB=16777216,b9="Maximum ASN.1 nesting depth exceeded",E9="Maximum ASN.1 node count exceeded",T9="Maximum ASN.1 content length exceeded";function Bm(e={}){var t,r,n;return{depth:0,maxDepth:(t=e.maxDepth)!==null&&t!==void 0?t:_B,nodesCount:0,maxNodes:(r=e.maxNodes)!==null&&r!==void 0?r:kB,maxContentLength:(n=e.maxContentLength)!==null&&n!==void 0?n:OB}}function R9(e){let t=new mn({},Vn);return t.error=e,{offset:-1,result:t}}function A9(e){if(e.nodesCount+=1,e.nodesCount>e.maxNodes)return E9;return}function P9(e,t){if(e>t.maxContentLength)return T9;return}function BR(e,t,r,n){let o=n.depth+1;if(o>n.maxDepth)return R9(b9);n.depth=o;try{return Jv(e,t,r,n)}finally{n.depth-=1}}function I9(e,t){if(e instanceof t)return e;let r=new t;return r.idBlock=e.idBlock,r.lenBlock=e.lenBlock,r.warnings=e.warnings,r.valueBeforeDecodeView=e.valueBeforeDecodeView,r}function Jv(e,t=0,r=e.length,n=Bm()){let o=t,i=new mn({},Vn),s=new Tc;if(!ma(s,e,t,r))return i.error=s.error,{offset:-1,result:i};if(!e.subarray(t,t+r).length)return i.error="Zero buffer length",{offset:-1,result:i};let c=A9(n);if(c)return i.error=c,{offset:-1,result:i};let l=i.idBlock.fromBER(e,t,r);if(i.idBlock.warnings.length)i.warnings.concat(i.idBlock.warnings);if(l===-1)return i.error=i.idBlock.error,{offset:-1,result:i};if(t=l,r-=i.idBlock.blockLength,l=i.lenBlock.fromBER(e,t,r),i.lenBlock.warnings.length)i.warnings.concat(i.lenBlock.warnings);if(l===-1)return i.error=i.lenBlock.error,{offset:-1,result:i};t=l,r-=i.lenBlock.blockLength;let d=i.lenBlock.isIndefiniteForm?r:i.lenBlock.length,u=P9(d,n);if(u)return i.error=u,{offset:-1,result:i};if(!i.idBlock.isConstructed&&i.lenBlock.isIndefiniteForm)return i.error="Indefinite length form used for primitive encoding form",{offset:-1,result:i};let m=mn;switch(i.idBlock.tagClass){case 1:if(i.idBlock.tagNumber>=37&&i.idBlock.isHexOnly===!1)return i.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:i};switch(i.idBlock.tagNumber){case 0:if(i.idBlock.isConstructed&&i.lenBlock.length>0)return i.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:i};m=Te.EndOfContent;break;case 1:m=Te.Boolean;break;case 2:m=Te.Integer;break;case 3:m=Te.BitString;break;case 4:m=Te.OctetString;break;case 5:m=Te.Null;break;case 6:m=Te.ObjectIdentifier;break;case 10:m=Te.Enumerated;break;case 12:m=Te.Utf8String;break;case 13:m=Te.RelativeObjectIdentifier;break;case 14:m=Te.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:m=Te.Sequence;break;case 17:m=Te.Set;break;case 18:m=Te.NumericString;break;case 19:m=Te.PrintableString;break;case 20:m=Te.TeletexString;break;case 21:m=Te.VideotexString;break;case 22:m=Te.IA5String;break;case 23:m=Te.UTCTime;break;case 24:m=Te.GeneralizedTime;break;case 25:m=Te.GraphicString;break;case 26:m=Te.VisibleString;break;case 27:m=Te.GeneralString;break;case 28:m=Te.UniversalString;break;case 29:m=Te.CharacterString;break;case 30:m=Te.BmpString;break;case 31:m=Te.DATE;break;case 32:m=Te.TimeOfDay;break;case 33:m=Te.DateTime;break;case 34:m=Te.Duration;break;default:{let h=i.idBlock.isConstructed?new Te.Constructed:new Te.Primitive;h.idBlock=i.idBlock,h.lenBlock=i.lenBlock,h.warnings=i.warnings,i=h}}break;case 2:case 3:case 4:default:m=i.idBlock.isConstructed?Te.Constructed:Te.Primitive}return i=I9(i,m),l=i.fromBER(e,t,d,n),i.valueBeforeDecodeView=e.subarray(o,o+i.blockLength),{offset:l,result:i}}function ya(e,t={}){if(!e.byteLength){let r=new mn({},Vn);return r.error="Input buffer has zero length",{offset:-1,result:r}}return Jv(ye.toUint8Array(e).slice(),0,e.byteLength,Bm(t))}function C9(e,t){if(e)return 1;return t}class pa extends Vn{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r);this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r,n){let o=ye.toUint8Array(e),i=n!==null&&n!==void 0?n:Bm();if(!ma(this,o,t,r))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+r),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let s=t;while(C9(this.isIndefiniteForm,r)>0){let a=BR(o,s,r,i);if(a.offset===-1)return this.error=a.result.error,this.warnings.concat(a.result.warnings),-1;if(s=a.offset,this.blockLength+=a.result.blockLength,r-=a.result.blockLength,this.value.push(a.result),this.isIndefiniteForm&&a.result.constructor.NAME===Fm)break}if(this.isIndefiniteForm)if(this.value[this.value.length-1].constructor.NAME===Fm)this.value.pop();else this.warnings.push("No EndOfContent block encoded");return s}toBER(e,t){let r=t||new Um;for(let n=0;n<this.value.length;n++)this.value[n].toBER(e,r);if(!t)return r.final();return Ts}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}}pa.NAME="ConstructedValueBlock";var DB;class Rn extends mn{constructor(e={}){super(e,pa);this.idBlock.isConstructed=!0}fromBER(e,t,r,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length,n);if(o===-1)return this.error=this.valueBlock.error,o;if(!this.idBlock.error.length)this.blockLength+=this.idBlock.blockLength;if(!this.lenBlock.error.length)this.blockLength+=this.lenBlock.blockLength;if(!this.valueBlock.error.length)this.blockLength+=this.valueBlock.blockLength;return o}onAsciiEncoding(){let e=[];for(let r of this.valueBlock.value)e.push(r.toString("ascii").split(`
|
|
177
|
+
`).map((n)=>` ${n}`).join(`
|
|
178
|
+
`));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
|
|
179
|
+
${e.join(`
|
|
180
|
+
`)}`:`${t} :`}}DB=Rn;(()=>{Te.Constructed=DB})();Rn.NAME="CONSTRUCTED";class MR extends Vn{fromBER(e,t,r){return t}toBER(e){return Ts}}MR.override="EndOfContentValueBlock";var NB;class zv extends mn{constructor(e={}){super(e,MR);this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}NB=zv;(()=>{Te.EndOfContent=NB})();zv.NAME=Fm;var FB;class As extends mn{constructor(e={}){super(e,Vn);this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,r){if(this.lenBlock.length>0)this.warnings.push("Non-zero length of value block for Null type");if(!this.idBlock.error.length)this.blockLength+=this.idBlock.blockLength;if(!this.lenBlock.error.length)this.blockLength+=this.lenBlock.blockLength;if(this.blockLength+=r,t+r>e.byteLength)return this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1;return t+r}toBER(e,t){let r=new ArrayBuffer(2);if(!e){let n=new Uint8Array(r);n[0]=5,n[1]=0}if(t)t.write(r);return r}onAsciiEncoding(){return`${this.constructor.NAME}`}}FB=As;(()=>{Te.Null=FB})();As.NAME="NULL";class LR extends Rs(Vn){get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...t}={}){super(t);if(t.valueHex)this.valueHexView=ye.toUint8Array(t.valueHex);else this.valueHexView=new Uint8Array(1);if(e)this.value=e}fromBER(e,t,r){let n=ye.toUint8Array(e);if(!ma(this,n,t,r))return-1;if(this.valueHexView=n.subarray(t,t+r),r>1)this.warnings.push("Boolean value encoded in more then 1 octet");return this.isHexOnly=!0,kR.call(this),this.blockLength=r,t+r}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}LR.NAME="BooleanValueBlock";var UB;class Qu extends mn{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,LR);this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}}UB=Qu;(()=>{Te.Boolean=UB})();Qu.NAME="BOOLEAN";class $R extends Rs(pa){constructor({isConstructed:e=!1,...t}={}){super(t);this.isConstructed=e}fromBER(e,t,r,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=pa.prototype.fromBER.call(this,e,t,r,n),o===-1)return o;for(let i=0;i<this.value.length;i++){let s=this.value[i].constructor.NAME;if(s===Fm)if(this.isIndefiniteForm)break;else return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1;if(s!==AB)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,r),this.blockLength=r;return o}toBER(e,t){if(this.isConstructed)return pa.prototype.toBER.call(this,e,t);return e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}$R.NAME="OctetStringValueBlock";var qR;class Ps extends mn{constructor({idBlock:e={},lenBlock:t={},...r}={}){var n,o;(n=r.isConstructed)!==null&&n!==void 0||(r.isConstructed=!!((o=r.value)===null||o===void 0?void 0:o.length));super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},$R);this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,r,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,r===0){if(this.idBlock.error.length===0)this.blockLength+=this.idBlock.blockLength;if(this.lenBlock.error.length===0)this.blockLength+=this.lenBlock.blockLength;return t}if(!this.valueBlock.isConstructed){let i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+r);try{if(i.byteLength){let s=n!==null&&n!==void 0?n:Bm(),a=BR(i,0,i.byteLength,s);if(a.offset!==-1&&a.offset===r)this.valueBlock.value=[a.result]}}catch{}}return super.fromBER(e,t,r,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Rn.prototype.onAsciiEncoding.call(this);let e=this.constructor.NAME,t=Ee.ToHex(this.valueBlock.valueHexView);return`${e} : ${t}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)if(t instanceof qR)e.push(t.valueBlock.valueHexView);return ye.concat(e)}}qR=Ps;(()=>{Te.OctetString=qR})();Ps.NAME=AB;class jR extends Rs(pa){constructor({unusedBits:e=0,isConstructed:t=!1,...r}={}){super(r);this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,r,n){if(!r)return t;let o=-1;if(this.isConstructed){if(o=pa.prototype.fromBER.call(this,e,t,r,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Fm)if(this.isIndefiniteForm)break;else return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1;if(c!==PB)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let i=ye.toUint8Array(e);if(!ma(this,i,t,r))return-1;let s=i.subarray(t,t+r);if(this.unusedBits=s[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=s.subarray(1);try{if(a.byteLength){let c=n!==null&&n!==void 0?n:Bm(),l=BR(a,0,a.byteLength,c);if(l.offset!==-1&&l.offset===r-1)this.value=[l.result]}}catch{}}return this.valueHexView=s.subarray(1),this.blockLength=s.length,t+r}toBER(e,t){if(this.isConstructed)return pa.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){let n=new Uint8Array(1);return n[0]=0,n.buffer}let r=new Uint8Array(this.valueHexView.length+1);return r[0]=this.unusedBits,r.set(this.valueHexView,1),r.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}}jR.NAME="BitStringValueBlock";var BB;class Is extends mn{constructor({idBlock:e={},lenBlock:t={},...r}={}){var n,o;(n=r.isConstructed)!==null&&n!==void 0||(r.isConstructed=!!((o=r.value)===null||o===void 0?void 0:o.length));super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},jR);this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,r,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,r,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Rn.prototype.onAsciiEncoding.call(this);else{let e=[],t=this.valueBlock.valueHexView;for(let i of t)e.push(i.toString(2).padStart(8,"0"));let r=e.join(""),n=this.constructor.NAME,o=r.substring(0,r.length-this.valueBlock.unusedBits);return`${n} : ${o}`}}}BB=Is;(()=>{Te.BitString=BB})();Is.NAME=PB;var MB;function _9(e,t){let r=new Uint8Array([0]),n=new Uint8Array(e),o=new Uint8Array(t),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l=0,d=c<s?s:c,u=0;for(let m=d;m>=0;m--,u++){switch(!0){case u<a.length:l=i[s-u]+a[c-u]+r[0];break;default:l=i[s-u]+r[0]}switch(r[0]=l/10,!0){case u>=i.length:i=jv(new Uint8Array([l%10]),i);break;default:i[s-u]=l%10}}if(r[0]>0)i=jv(r,i);return i}function RB(e){if(e>=Dm.length)for(let t=Dm.length;t<=e;t++){let r=new Uint8Array([0]),n=Dm[t-1].slice(0);for(let o=n.length-1;o>=0;o--){let i=new Uint8Array([(n[o]<<1)+r[0]]);r[0]=i[0]/10,n[o]=i[0]%10}if(r[0]>0)n=jv(r,n);Dm.push(n)}return Dm[e]}function k9(e,t){let r=0,n=new Uint8Array(e),o=new Uint8Array(t),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l,d=0;for(let u=c;u>=0;u--,d++)switch(l=i[s-d]-a[c-d]-r,!0){case l<0:r=1,i[s-d]=l+10;break;default:r=0,i[s-d]=l}if(r>0)for(let u=s-c+1;u>=0;u--,d++)if(l=i[s-d]-r,l<0)r=1,i[s-d]=l+10;else{r=0,i[s-d]=l;break}return i.slice()}class Gv extends Rs(Vn){setValueHex(){if(this.valueHexView.length>=4)this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0;else if(this.isHexOnly=!1,this.valueHexView.length>0)this._valueDec=kR.call(this)}constructor({value:e,...t}={}){super(t);if(this._valueDec=0,t.valueHex)this.setValueHex();if(e!==void 0)this.valueDec=e}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(wB(e))}get valueDec(){return this._valueDec}fromDER(e,t,r,n=0){let o=this.fromBER(e,t,r);if(o===-1)return o;let i=this.valueHexView;if(i[0]===0&&(i[1]&128)!==0)this.valueHexView=i.subarray(1);else if(n!==0){if(i.length<n){if(n-i.length>1)n=i.length+1;this.valueHexView=i.subarray(n-i.length)}}return o}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let r=new Uint8Array(this.valueHexView.length+1);r[0]=0,r.set(t,1),this.valueHexView=r}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,r){let n=super.fromBER(e,t,r);if(n===-1)return n;return this.setValueHex(),n}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),r=0,n,o=this.valueHexView,i="",s=!1;for(let a=o.byteLength-1;a>=0;a--){n=o[a];for(let c=0;c<8;c++){if((n&1)===1)switch(r){case e:t=k9(RB(r),t),i="-";break;default:t=_9(t,RB(r))}r++,n>>=1}}for(let a=0;a<t.length;a++){if(t[a])s=!0;if(s)i+=EB.charAt(t[a])}if(s===!1)i+=EB.charAt(0);return i}}MB=Gv;Gv.NAME="IntegerValueBlock";(()=>{Object.defineProperty(MB.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}})})();var Nm;class Ac extends mn{constructor(e={}){super(e,Gv);this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Hv(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Hv();let t=BigInt(e),r=new Um,n=t.toString(16).replace(/^-/,""),o=new Uint8Array(Ee.FromHex(n));if(t<0){let s=new Uint8Array(o.length+(o[0]&128?1:0));s[0]|=128;let c=BigInt(`0x${Ee.ToHex(s)}`)+t,l=ye.toUint8Array(Ee.FromHex(c.toString(16)));l[0]|=128,r.write(l)}else{if(o[0]&128)r.write(new Uint8Array([0]));r.write(o)}return new Nm({valueHex:r.final()})}convertToDER(){let e=new Nm({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Nm({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}Nm=Ac;(()=>{Te.Integer=Nm})();Ac.NAME="INTEGER";var LB;class Ju extends Ac{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}LB=Ju;(()=>{Te.Enumerated=LB})();Ju.NAME="ENUMERATED";class Wv extends Rs(Vn){constructor({valueDec:e=-1,isFirstSid:t=!1,...r}={}){super(r);this.valueDec=e,this.isFirstSid=t}fromBER(e,t,r){if(!r)return t;let n=ye.toUint8Array(e);if(!ma(this,n,t,r))return-1;let o=n.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(let s=0;s<r;s++)if(this.valueHexView[s]=o[s]&127,this.blockLength++,(o[s]&128)===0)break;let i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength;s++)i[s]=this.valueHexView[s];if(this.valueHexView=i,(o[this.blockLength-1]&128)!==0)return this.error="End of input reached before message was fully decoded",-1;if(this.valueHexView[0]===0)this.warnings.push("Needlessly long format of SID encoding");if(this.blockLength<=8)this.valueDec=$l(this.valueHexView,7);else this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only");return t+this.blockLength}set valueBigInt(e){Hv();let t=BigInt(e).toString(2);while(t.length%7)t="0"+t;let r=new Uint8Array(t.length/7);for(let n=0;n<r.length;n++)r[n]=parseInt(t.slice(n*7,n*7+7),2)+(n+1<r.length?128:0);this.fromBER(r.buffer,0,r.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let n=this.valueHexView,o=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)o[i]=n[i]|128;return o[this.blockLength-1]=n[this.blockLength-1],o.buffer}let t=Ec(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Ts;let r=new Uint8Array(t.byteLength);if(!e){let n=new Uint8Array(t),o=t.byteLength-1;for(let i=0;i<o;i++)r[i]=n[i]|128;r[o]=n[o]}return r}toString(){let e="";if(this.isHexOnly)e=Ee.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;if(this.valueDec<=39)e="0.";else if(this.valueDec<=79)e="1.",t-=40;else e="2.",t-=80;e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}}Wv.NAME="sidBlock";class HR extends Vn{constructor({value:e=$o,...t}={}){super(t);if(this.value=[],e)this.fromString(e)}fromBER(e,t,r){let n=t;while(r>0){let o=new Wv;if(n=o.fromBER(e,n,r),n===-1)return this.blockLength=0,this.error=o.error,n;if(this.value.length===0)o.isFirstSid=!0;this.blockLength+=o.blockLength,r-=o.blockLength,this.value.push(o)}return n}toBER(e){let t=[];for(let r=0;r<this.value.length;r++){let n=this.value[r].toBER(e);if(n.byteLength===0)return this.error=this.value[r].error,Ts;t.push(n)}return DR(t)}fromString(e){this.value=[];let t=0,r=0,n="",o=!1;do{if(r=e.indexOf(".",t),r===-1)n=e.substring(t);else n=e.substring(t,r);if(t=r+1,o){let i=this.value[0],s=0;switch(i.valueDec){case 0:break;case 1:s=40;break;case 2:s=80;break;default:this.value=[];return}let a=parseInt(n,10);if(isNaN(a))return;i.valueDec=a+s,o=!1}else{let i=new Wv;if(n>Number.MAX_SAFE_INTEGER){Hv();let s=BigInt(n);i.valueBigInt=s}else if(i.valueDec=parseInt(n,10),isNaN(i.valueDec))return;if(!this.value.length)i.isFirstSid=!0,o=!0;this.value.push(i)}}while(r!==-1)}toString(){let e="",t=!1;for(let r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;let n=this.value[r].toString();if(r!==0)e=`${e}.`;if(t)if(n=`{${n}}`,this.value[r].isFirstSid)e=`2.{${n} - 80}`;else e+=n;else e+=n}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}}HR.NAME="ObjectIdentifierValueBlock";var $B;class zu extends mn{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,HR);this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}$B=zu;(()=>{Te.ObjectIdentifier=$B})();zu.NAME="OBJECT IDENTIFIER";class Kv extends Rs(Tc){constructor({valueDec:e=0,...t}={}){super(t);this.valueDec=e}fromBER(e,t,r){if(r===0)return t;let n=ye.toUint8Array(e);if(!ma(this,n,t,r))return-1;let o=n.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(let s=0;s<r;s++)if(this.valueHexView[s]=o[s]&127,this.blockLength++,(o[s]&128)===0)break;let i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength;s++)i[s]=this.valueHexView[s];if(this.valueHexView=i,(o[this.blockLength-1]&128)!==0)return this.error="End of input reached before message was fully decoded",-1;if(this.valueHexView[0]===0)this.warnings.push("Needlessly long format of SID encoding");if(this.blockLength<=8)this.valueDec=$l(this.valueHexView,7);else this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only");return t+this.blockLength}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let n=this.valueHexView,o=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)o[i]=n[i]|128;return o[this.blockLength-1]=n[this.blockLength-1],o.buffer}let t=Ec(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Ts;let r=new Uint8Array(t.byteLength);if(!e){let n=new Uint8Array(t),o=t.byteLength-1;for(let i=0;i<o;i++)r[i]=n[i]|128;r[o]=n[o]}return r.buffer}toString(){let e="";if(this.isHexOnly)e=Ee.ToHex(this.valueHexView);else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}Kv.NAME="relativeSidBlock";class WR extends Vn{constructor({value:e=$o,...t}={}){super(t);if(this.value=[],e)this.fromString(e)}fromBER(e,t,r){let n=t;while(r>0){let o=new Kv;if(n=o.fromBER(e,n,r),n===-1)return this.blockLength=0,this.error=o.error,n;this.blockLength+=o.blockLength,r-=o.blockLength,this.value.push(o)}return n}toBER(e,t){let r=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,Ts;r.push(o)}return DR(r)}fromString(e){this.value=[];let t=0,r=0,n="";do{if(r=e.indexOf(".",t),r===-1)n=e.substring(t);else n=e.substring(t,r);t=r+1;let o=new Kv;if(o.valueDec=parseInt(n,10),isNaN(o.valueDec))return!0;this.value.push(o)}while(r!==-1);return!0}toString(){let e="",t=!1;for(let r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;let n=this.value[r].toString();if(r!==0)e=`${e}.`;if(t)n=`{${n}}`,e+=n;else e+=n}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}}WR.NAME="RelativeObjectIdentifierValueBlock";var qB;class Gu extends mn{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,WR);this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}qB=Gu;(()=>{Te.RelativeObjectIdentifier=qB})();Gu.NAME="RelativeObjectIdentifier";var jB;class xo extends Rn{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}jB=xo;(()=>{Te.Sequence=jB})();xo.NAME="SEQUENCE";var HB;class qo extends Rn{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=17}}HB=qo;(()=>{Te.Set=HB})();qo.NAME="SET";class KR extends Rs(Vn){constructor({...e}={}){super(e);this.isHexOnly=!0,this.value=$o}toJSON(){return{...super.toJSON(),value:this.value}}}KR.NAME="StringValueBlock";class VR extends KR{}VR.NAME="SimpleStringValueBlock";class jo extends Qv{constructor({...e}={}){super(e,VR)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,ye.toUint8Array(e))}fromString(e){let t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);this.valueBlock.value=e}}jo.NAME="SIMPLE STRING";class QR extends jo{fromBuffer(e){this.valueBlock.valueHexView=ye.toUint8Array(e);try{this.valueBlock.value=Ee.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=Ee.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(Ee.FromUtf8String(e)),this.valueBlock.value=e}}QR.NAME="Utf8StringValueBlock";var WB;class Zi extends QR{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}WB=Zi;(()=>{Te.Utf8String=WB})();Zi.NAME="UTF8String";class JR extends jo{fromBuffer(e){this.valueBlock.value=Ee.ToUtf16String(e),this.valueBlock.valueHexView=ye.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(Ee.FromUtf16String(e))}}JR.NAME="BmpStringValueBlock";var KB;class Yu extends JR{constructor({...e}={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}KB=Yu;(()=>{Te.BmpString=KB})();Yu.NAME="BMPString";class zR extends jo{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),r=new Uint8Array(t);for(let n=0;n<r.length;n+=4)r[n]=r[n+3],r[n+1]=r[n+2],r[n+2]=0,r[n+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let n=0;n<t;n++){let o=Ec(e.charCodeAt(n),8),i=new Uint8Array(o);if(i.length>4)continue;let s=4-i.length;for(let a=i.length-1;a>=0;a--)r[n*4+a+s]=i[a]}this.valueBlock.value=e}}zR.NAME="UniversalStringValueBlock";var VB;class Xu extends zR{constructor({...e}={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}VB=Xu;(()=>{Te.UniversalString=VB})();Xu.NAME="UniversalString";var QB;class Zu extends jo{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}QB=Zu;(()=>{Te.NumericString=QB})();Zu.NAME="NumericString";var JB;class ep extends jo{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}JB=ep;(()=>{Te.PrintableString=JB})();ep.NAME="PrintableString";var zB;class tp extends jo{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}zB=tp;(()=>{Te.TeletexString=zB})();tp.NAME="TeletexString";var GB;class rp extends jo{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}GB=rp;(()=>{Te.VideotexString=GB})();rp.NAME="VideotexString";var YB;class np extends jo{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}YB=np;(()=>{Te.IA5String=YB})();np.NAME="IA5String";var XB;class op extends jo{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}XB=op;(()=>{Te.GraphicString=XB})();op.NAME="GraphicString";var ZB;class ql extends jo{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}ZB=ql;(()=>{Te.VisibleString=ZB})();ql.NAME="VisibleString";var eM;class ip extends jo{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}eM=ip;(()=>{Te.GeneralString=eM})();ip.NAME="GeneralString";var tM;class sp extends jo{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}tM=sp;(()=>{Te.CharacterString=tM})();sp.NAME="CharacterString";var rM;class jl extends ql{constructor({value:e,valueDate:t,...r}={}){super(r);if(this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let n=0;n<e.length;n++)this.valueBlock.valueHexView[n]=e.charCodeAt(n)}if(t)this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer());this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,ye.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let r=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(r===null){this.error="Wrong input string for conversion";return}let n=parseInt(r[1],10);if(n>=50)this.year=1900+n;else this.year=2000+n;this.month=parseInt(r[2],10),this.day=parseInt(r[3],10),this.hour=parseInt(r[4],10),this.minute=parseInt(r[5],10),this.second=parseInt(r[6],10)}toString(e="iso"){if(e==="iso"){let t=[,,,,,,,];return t[0]=Lo(this.year<2000?this.year-1900:this.year-2000,2),t[1]=Lo(this.month,2),t[2]=Lo(this.day,2),t[3]=Lo(this.hour,2),t[4]=Lo(this.minute,2),t[5]=Lo(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}}rM=jl;(()=>{Te.UTCTime=rM})();jl.NAME="UTCTime";var nM;class ap extends jl{constructor(e={}){var t;super(e);(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){let e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let t=!1,r="",n="",o=0,i,s=0,a=0;if(e[e.length-1]==="Z")r=e.substring(0,e.length-1),t=!0;else{let d=new Number(e[e.length-1]);if(isNaN(d.valueOf()))throw Error("Wrong input string for conversion");r=e}if(t){if(r.indexOf("+")!==-1)throw Error("Wrong input string for conversion");if(r.indexOf("-")!==-1)throw Error("Wrong input string for conversion")}else{let d=1,u=r.indexOf("+"),m="";if(u===-1)u=r.indexOf("-"),d=-1;if(u!==-1){if(m=r.substring(u+1),r=r.substring(0,u),m.length!==2&&m.length!==4)throw Error("Wrong input string for conversion");let h=parseInt(m.substring(0,2),10);if(isNaN(h.valueOf()))throw Error("Wrong input string for conversion");if(s=d*h,m.length===4){if(h=parseInt(m.substring(2,4),10),isNaN(h.valueOf()))throw Error("Wrong input string for conversion");a=d*h}}}let c=r.indexOf(".");if(c===-1)c=r.indexOf(",");if(c!==-1){let d=new Number(`0${r.substring(c)}`);if(isNaN(d.valueOf()))throw Error("Wrong input string for conversion");o=d.valueOf(),n=r.substring(0,c)}else n=r;switch(!0){case n.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,c!==-1)throw Error("Wrong input string for conversion");break;case n.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,c!==-1){let d=60*o;this.minute=Math.floor(d),d=60*(d-this.minute),this.second=Math.floor(d),d=1000*(d-this.second),this.millisecond=Math.floor(d)}break;case n.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,c!==-1){let d=60*o;this.second=Math.floor(d),d=1000*(d-this.second),this.millisecond=Math.floor(d)}break;case n.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,c!==-1){let d=1000*o;this.millisecond=Math.floor(d)}break;default:throw Error("Wrong input string for conversion")}let l=i.exec(n);if(l===null)throw Error("Wrong input string for conversion");for(let d=1;d<l.length;d++)switch(d){case 1:this.year=parseInt(l[d],10);break;case 2:this.month=parseInt(l[d],10);break;case 3:this.day=parseInt(l[d],10);break;case 4:this.hour=parseInt(l[d],10)+s;break;case 5:this.minute=parseInt(l[d],10)+a;break;case 6:this.second=parseInt(l[d],10);break;default:throw Error("Wrong input string for conversion")}if(t===!1){let d=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=d.getUTCFullYear(),this.month=d.getUTCMonth(),this.day=d.getUTCDay(),this.hour=d.getUTCHours(),this.minute=d.getUTCMinutes(),this.second=d.getUTCSeconds(),this.millisecond=d.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];if(t.push(Lo(this.year,4)),t.push(Lo(this.month,2)),t.push(Lo(this.day,2)),t.push(Lo(this.hour,2)),t.push(Lo(this.minute,2)),t.push(Lo(this.second,2)),this.millisecond!==0)t.push("."),t.push(Lo(this.millisecond,3));return t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}nM=ap;(()=>{Te.GeneralizedTime=nM})();ap.NAME="GeneralizedTime";var oM;class Yv extends Zi{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}oM=Yv;(()=>{Te.DATE=oM})();Yv.NAME="DATE";var iM;class Xv extends Zi{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}iM=Xv;(()=>{Te.TimeOfDay=iM})();Xv.NAME="TimeOfDay";var sM;class Zv extends Zi{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}sM=Zv;(()=>{Te.DateTime=sM})();Zv.NAME="DateTime";var aM;class ex extends Zi{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}aM=ex;(()=>{Te.Duration=aM})();ex.NAME="Duration";var cM;class tx extends Zi{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}cM=tx;(()=>{Te.TIME=cM})();tx.NAME="TIME";class fa{constructor({name:e=$o,optional:t=!1}={}){this.name=e,this.optional=t}}class Mm extends fa{constructor({value:e=[],...t}={}){super(t);this.value=e}}class Vu extends fa{constructor({value:e=new fa,local:t=!1,...r}={}){super(r);this.value=e,this.local=t}}class lM{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=ye.toUint8Array(e)}constructor({data:e=Vv}={}){this.dataView=ye.toUint8Array(e)}fromBER(e,t,r){let n=t+r;return this.dataView=ye.toUint8Array(e).subarray(t,n),n}toBER(e){return this.dataView.slice().buffer}}function ua(e,t,r){if(r instanceof Mm){for(let i of r.value)if(ua(e,t,i).verified)return{verified:!0,result:e};{let i={verified:!1,result:{error:"Wrong values for Choice type"}};if(r.hasOwnProperty(OR))i.name=r.name;return i}}if(r instanceof fa){if(r.hasOwnProperty(OR))e[r.name]=t;return{verified:!0,result:e}}if(e instanceof Object===!1)return{verified:!1,result:{error:"Wrong root object"}};if(t instanceof Object===!1)return{verified:!1,result:{error:"Wrong ASN.1 data"}};if(r instanceof Object===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(y9 in r===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(v9 in r.idBlock===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(x9 in r.idBlock===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};let n=r.idBlock.toBER(!1);if(n.byteLength===0)return{verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(r.idBlock.fromBER(n,0,n.byteLength)===-1)return{verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(r.idBlock.hasOwnProperty(h9)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagClass!==t.idBlock.tagClass)return{verified:!1,result:e};if(r.idBlock.hasOwnProperty(g9)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagNumber!==t.idBlock.tagNumber)return{verified:!1,result:e};if(r.idBlock.hasOwnProperty(S9)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!(m9 in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isHexOnly!==t.idBlock.isHexOnly)return{verified:!1,result:e};if(r.idBlock.isHexOnly){if(TB in r.idBlock===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};let i=r.idBlock.valueHexView,s=t.idBlock.valueHexView;if(i.length!==s.length)return{verified:!1,result:e};for(let a=0;a<i.length;a++)if(i[a]!==s[1])return{verified:!1,result:e}}if(r.name){if(r.name=r.name.replace(/^\s+|\s+$/g,$o),r.name)e[r.name]=t}if(r instanceof Te.Constructed){let i=0,s={verified:!1,result:{error:"Unknown error"}},a=r.valueBlock.value.length;if(a>0){if(r.valueBlock.value[0]instanceof Vu)a=t.valueBlock.value.length}if(a===0)return{verified:!0,result:e};if(t.valueBlock.value.length===0&&r.valueBlock.value.length!==0){let c=!0;for(let l=0;l<r.valueBlock.value.length;l++)c=c&&(r.valueBlock.value[l].optional||!1);if(c)return{verified:!0,result:e};if(r.name){if(r.name=r.name.replace(/^\s+|\s+$/g,$o),r.name)delete e[r.name]}return e.error="Inconsistent object length",{verified:!1,result:e}}for(let c=0;c<a;c++)if(c-i>=t.valueBlock.value.length){if(r.valueBlock.value[c].optional===!1){let l={verified:!1,result:e};if(e.error="Inconsistent length between ASN.1 data and schema",r.name){if(r.name=r.name.replace(/^\s+|\s+$/g,$o),r.name)delete e[r.name],l.name=r.name}return l}}else if(r.valueBlock.value[0]instanceof Vu){if(s=ua(e,t.valueBlock.value[c],r.valueBlock.value[0].value),s.verified===!1)if(r.valueBlock.value[0].optional)i++;else{if(r.name){if(r.name=r.name.replace(/^\s+|\s+$/g,$o),r.name)delete e[r.name]}return s}if(OR in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){let l={};if(w9 in r.valueBlock.value[0]&&r.valueBlock.value[0].local)l=t;else l=e;if(typeof l[r.valueBlock.value[0].name]>"u")l[r.valueBlock.value[0].name]=[];l[r.valueBlock.value[0].name].push(t.valueBlock.value[c])}}else if(s=ua(e,t.valueBlock.value[c-i],r.valueBlock.value[c]),s.verified===!1)if(r.valueBlock.value[c].optional)i++;else{if(r.name){if(r.name=r.name.replace(/^\s+|\s+$/g,$o),r.name)delete e[r.name]}return s}if(s.verified===!1){let c={verified:!1,result:e};if(r.name){if(r.name=r.name.replace(/^\s+|\s+$/g,$o),r.name)delete e[r.name],c.name=r.name}return c}return{verified:!0,result:e}}if(r.primitiveSchema&&TB in t.valueBlock){let i=Jv(t.valueBlock.valueHexView);if(i.offset===-1){let s={verified:!1,result:i.result};if(r.name){if(r.name=r.name.replace(/^\s+|\s+$/g,$o),r.name)delete e[r.name],s.name=r.name}return s}return ua(e,i.result,r.primitiveSchema)}return{verified:!0,result:e}}function O9(e,t){if(t instanceof Object===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};let r=Jv(ye.toUint8Array(e));if(r.offset===-1)return{verified:!1,result:r.result};return ua(r.result,r.result,t)}function dM(e){return Object.prototype.toString.call(e)}function D9(e){if(ArrayBuffer.isView(e))return!0;if(!e||typeof e!=="object")return!1;let t=e;return typeof t.byteOffset==="number"&&typeof t.byteLength==="number"&&nx(t.buffer)}function rx(e){return dM(e)==="[object ArrayBuffer]"}function uM(e){return typeof SharedArrayBuffer<"u"&&dM(e)==="[object SharedArrayBuffer]"}function nx(e){return rx(e)||uM(e)}function GR(e){return D9(e)}function _s(e){return nx(e)||GR(e)}function YR(e){if(!_s(e))throw TypeError("Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView")}function eo(e){if(YR(e),nx(e))return new Uint8Array(e);return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function Qt(e){if(YR(e),rx(e))return e;let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(eo(e)),t}function Lm(e,t,r={}){let n=eo(e),o=eo(t);if(!r.constantTime&&n.byteLength!==o.byteLength)return!1;let i=Math.max(n.byteLength,o.byteLength),s=n.byteLength^o.byteLength;for(let a=0;a<i;a++)s|=(n[a]??0)^(o[a]??0);return s===0}function ox(e){let t=eo(e),r="";for(let n of t)r+=String.fromCharCode(n);return r}function ix(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r)&255;return t}function U9(e){return typeof e==="string"}var B9=/^[0-9a-f]$/i,M9=[" ","\t",`
|
|
181
|
+
`,"\r",":","-","."];function L9(e){if(e.separators==="none")return[];if(!e.separators||e.separators==="common")return M9;return e.separators}function $9(e){if(!e)throw TypeError("Hex separators must be non-empty strings")}function q9(e,t,r){for(let n of r)if(e.startsWith(n,t))return n;return}function j9(e){let t=/[A-F]/.test(e),r=/[a-f]/.test(e);return t&&!r?"upper":"lower"}function H9(e){let t=/\r\n|\n/.exec(e);if(!t)return;return t[0]===`\r
|
|
182
|
+
`?`\r
|
|
183
|
+
`:`
|
|
184
|
+
`}function mM(e){return e.replace(/[^0-9a-f]/gi,"")}function W9(e){let t=e.match(/[0-9A-Fa-f]+|[^0-9A-Fa-f]+/g)??[];if(t.length<3)return;let r=t.filter((s,a)=>a%2===0),n=t.filter((s,a)=>a%2===1),o=n[0];if(!o||n.some((s)=>s!==o))return;if(r.some((s)=>s.length===0||s.length%2!==0))return;let i=r[0]?.length??0;if(!i)return;if(r.slice(0,-1).some((s)=>s.length!==i))return;if((r[r.length-1]?.length??0)>i)return;return{size:i/2,separator:o}}function K9(e){let t=e.trim(),r=/^0x/i.test(t)?"0x":"",n=r?t.slice(2):t,o=H9(n),i=n.split(/\r\n|\n/).filter((l)=>l.length>0),s=i[0]?.trim()??"",a=W9(s),c={case:j9(t),prefix:r};if(a)c.group=a;if(o&&i.length>1){let l=mM(i[0]??"").length/2;if(l>0&&i.slice(0,-1).every((d)=>mM(d).length/2===l))c.line={bytesPerLine:l,separator:o}}return c}function V9(e,t){let r=t.allowPrefix??!0,n=[...L9(t)].sort((a,c)=>c.length-a.length);for(let a of n)$9(a);let o=e.trim();if(/^0x/i.test(o)){if(!r)throw TypeError("Hexadecimal text must not include a 0x prefix");o=o.slice(2)}let i="",s=!1;for(let a=0;a<o.length;){let c=o[a]??"";if(B9.test(c)){i+=c,s=!1,a+=1;continue}let l=q9(o,a,n);if(!l)throw TypeError("Input is not valid hexadecimal text");if(t.strict&&(s||i.length===0))throw TypeError("Hexadecimal text contains misplaced separators");s=!0,a+=l.length}if(t.strict&&s&&i.length>0)throw TypeError("Hexadecimal text must not end with a separator");if(i.length%2!==0){if(!t.allowOddLength)throw TypeError("Hexadecimal text must contain an even number of characters");i=`0${i}`}return i.toLowerCase()}function yM(e,t){if(!t)return e.join("");if(!Number.isInteger(t.size)||t.size<1)throw RangeError("Hex group size must be a positive integer");let r=[];for(let n=0;n<e.length;n+=t.size)r.push(e.slice(n,n+t.size).join(""));return r.join(t.separator)}function sx(e,t={}){return V9(e,t)}function hM(e,t={}){if(typeof e!=="string")return!1;try{return sx(e,t),!0}catch{return!1}}function $m(e,t={}){let r=eo(e),n=t.case??"lower",o=Array.from(r,(s)=>{let a=s.toString(16).padStart(2,"0");return n==="upper"?a.toUpperCase():a}),i="";if(t.line){let s=t.line.bytesPerLine;if(!Number.isInteger(s)||s<1)throw RangeError("Hex bytesPerLine must be a positive integer");let a=t.line.separator??`
|
|
185
|
+
`,c=[];for(let l=0;l<o.length;l+=s)c.push(yM(o.slice(l,l+s),t.group));i=c.join(a)}else i=yM(o,t.group);return`${t.prefix??""}${i}`}function ax(e,t={}){let r=sx(e,t),n=new Uint8Array(r.length/2);for(let o=0;o<r.length;o+=2)n[o/2]=Number.parseInt(r.slice(o,o+2),16);return n}function Q9(e,t={}){let r=sx(e,t);return{bytes:ax(r),format:K9(e),normalized:r}}function J9(e,t){return $m(e,t)}var nMe={compact:Object.freeze({}),upper:Object.freeze({case:"upper"}),colon:Object.freeze({group:{size:1,separator:":"}}),colonUpper:Object.freeze({case:"upper",group:{size:1,separator:":"}}),groupsOf4:Object.freeze({group:{size:4,separator:" "}}),prefixed:Object.freeze({prefix:"0x"})};function gM(e){return new TextEncoder().encode(e)}function SM(e){return new TextDecoder("utf-8",{fatal:!1}).decode(eo(e))}function eA(e,t={}){let r=new ArrayBuffer(e.length*2),n=new DataView(r);for(let o=0;o<e.length;o++)n.setUint16(o*2,e.charCodeAt(o),t.littleEndian??!1);return new Uint8Array(r)}function tA(e,t={}){let r=Qt(e),n=new DataView(r),o="";for(let i=0;i<r.byteLength;i+=2)o+=String.fromCharCode(n.getUint16(i,t.littleEndian??!1));return o}var z9=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function vM(){return globalThis.Buffer}function jm(e){return e.replace(/[\n\r\t ]/g,"")}function G9(e){let t=e.length%4;return t?e+"=".repeat(4-t):e}function cx(e){if(typeof e!=="string")return!1;let t=jm(e);return t===""||z9.test(t)}function nA(e,t){let r=eo(e),n=vM();if(n)return n.from(r).toString("base64");return btoa(ox(r))}function oA(e,t){let r=jm(e);if(!cx(r))throw TypeError("Input is not valid Base64 text");let n=vM();if(n)return new Uint8Array(n.from(r,"base64"));return ix(atob(r))}var Hl={encode:nA,decode:oA,is:cx,normalize:jm,pad:G9};var Y9=/^[A-Za-z0-9_-]*$/;function sA(e){return e.replace(/[\n\r\t ]/g,"")}function aA(e){return typeof e==="string"&&Y9.test(sA(e))}function xM(e,t){return Hl.encode(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function wM(e,t){let r=sA(e);if(!aA(r))throw TypeError("Input is not valid Base64Url text");return Hl.decode(Hl.pad(r.replace(/-/g,"+").replace(/_/g,"/")))}var X9=/^[A-Z0-9][A-Z0-9 ._-]*[A-Z0-9]$/i,bM=/-----BEGIN ([^-]+)-----([\s\S]*?)-----END \1-----/g;function EM(e){if(!X9.test(e))throw TypeError(`Invalid PEM label '${e}'`)}function Z9(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}function eY(e){let r=e.trim().replace(/\r\n/g,`
|
|
186
|
+
`).split(`
|
|
187
|
+
`).map((i)=>i.trim()).filter(Boolean),n={},o=0;for(;o<r.length;o++){let i=r[o],s=i.indexOf(":");if(s<=0)break;n[i.slice(0,s).trim()]=i.slice(s+1).trim()}return{headers:Object.keys(n).length?n:void 0,base64Lines:r.slice(o),base64Text:r.slice(o).join("")}}function tY(e){return/\r\n/.test(e)?`\r
|
|
188
|
+
`:`
|
|
189
|
+
`}function TM(e,t={}){let r=[],n=t.label,o;bM.lastIndex=0;while(o=bM.exec(e)){let i=o[1].trim();if(n&&i!==n)continue;EM(i);let s=eY(o[2]);r.push({label:i,data:Hl.decode(s.base64Text),headers:s.headers,lineLength:s.base64Lines[0]?.length??64,newline:tY(o[0])})}if(t.strict&&r.length===0)throw TypeError(n?`No PEM block with label '${n}' was found`:"No PEM blocks were found");return r}function lx(e,t,r={}){EM(e);let n=r.lineLength??64;if(!Number.isInteger(n)||n<1)throw RangeError("PEM lineLength must be a positive integer");let o=r.newline??`
|
|
190
|
+
`,i=[`-----BEGIN ${e}-----`];if(r.headers){for(let[s,a]of Object.entries(r.headers))i.push(`${s}: ${a}`);i.push("")}return i.push(...Z9(Hl.encode(t),n)),i.push(`-----END ${e}-----`),`${i.join(o)}${o}`}function RM(e,t={}){return TM(e,t).map(({lineLength:r,newline:n,...o})=>o)}function AM(e,t){let[r]=RM(e,{label:t,strict:!0});return r.data}function PM(e,t={}){let[r]=TM(e,{...t,strict:!0}),n={label:r.label,headers:r.headers,lineLength:r.lineLength,newline:r.newline};return{bytes:r.data,format:n,normalized:lx(r.label,r.data,n)}}function IM(e,t){return lx(t.label,e,t)}var Hm={name:"pem",encode:(e,t)=>{if(!t?.label)throw TypeError("PEM label is required");return lx(t.label,e,t)},decode:(e,t)=>AM(e,t?.label),format:IM,is:(e)=>typeof e==="string"&&/-----BEGIN [^-]+-----/.test(e),parse:PM};function ks(e){return e.trim().toLowerCase()}function rY(e){return e instanceof Error?e:Error(String(e))}function CM(e,t,r){for(let n of[r.name,...r.aliases??[]])e.delete(ks(n));t.delete(ks(r.name))}function lA(e,t,r){let n=e[r];if(typeof n!=="function")throw Error(`Converter '${t}' does not support ${r}()`);return n}function nY(e,t,r){let n=ks(r.name||e),o=t.trim();if(!o)return 0;let i=!1;if(r.is)i=r.is(t);let s=!1;try{r.decode(t),s=!0}catch{s=!1}if(!i&&!s)return 0;switch(n){case"pem":return/-----BEGIN [^-]+-----/.test(t)?1:0;case"hex":{let a=o.replace(/^0x/i,"").replace(/[\s:.-]/g,"");if(!a||/[^0-9a-f]/i.test(a)||a.length%2!==0)return 0;if(/^0x/i.test(o)||/[:\s.-]/.test(o))return 0.95;if(/[a-f]/.test(o)||/[A-F]/.test(o))return 0.8;return 0.45}case"base64url":if(/[-_]/.test(o))return 0.95;if(/=/.test(o))return 0.1;return 0.6;case"base64":if(/[+/=]/.test(o))return 0.9;return 0.55;case"binary":case"utf8":case"utf16be":case"utf16le":return 0;default:return i&&s?0.75:0.5}}function dA(e=[]){let t=new Map,r=new Set,n={register(o,i={}){if(!o.name||!ks(o.name))throw TypeError("Converter name is required");let s=[...new Set([o.name,...o.aliases??[]].map(ks))],a=new Set;for(let c of s){let l=t.get(c);if(!l)continue;if(!i.override)throw Error(`Converter '${c}' is already registered`);a.add(l)}for(let c of a)CM(t,r,c);for(let c of s)t.set(c,o);return r.add(ks(o.name)),this},unregister(o){let i=t.get(ks(o));if(!i)return!1;return CM(t,r,i),!0},has(o){return t.has(ks(o))},get(o){let i=t.get(ks(o));if(!i)throw Error(`Converter '${o}' is not registered`);return i},list(){return[...r].map((o)=>this.get(o))},encode(o,i,s){return this.get(o).encode(i,s)},decode(o,i,s){return this.get(o).decode(i,s)},tryDecode(o,i,s){try{return{ok:!0,bytes:this.decode(o,i,s)}}catch(a){return{ok:!1,error:rY(a)}}},normalize(o,i,s){let a=this.get(o);return lA(a,o,"normalize").call(a,i,s)},parse(o,i,s){let a=this.get(o);return lA(a,o,"parse").call(a,i,s)},format(o,i,s){let a=this.get(o);return lA(a,o,"format").call(a,i,s)},transcode(o,i){let s=this.decode(i.from,o,i.fromOptions);return this.encode(i.to,s,i.toOptions)},detect(o,i={}){let s=i.formats?.length?i.formats.map((c)=>String(c)):this.list().map((c)=>c.name).filter((c)=>!["binary","utf8","utf16be","utf16le"].includes(ks(c))),a=new Map;for(let c of s){let l=this.get(c),d=nY(c,o,l);if(d<=0)continue;let u=l.name,m=a.get(u);if(!m||d>m.confidence)a.set(u,{format:u,confidence:d})}return[...a.values()].sort((c,l)=>l.confidence-c.confidence)}};for(let o of e)n.register(o);return n}var _M={name:"binary",aliases:["latin1"],encode:ox,decode:ix,is:U9},kM={name:"hex",encode:$m,decode:ax,format:J9,is:hM,normalize:sx,parse:Q9},OM={name:"base64",aliases:["b64"],encode:nA,decode:oA,is:cx,normalize:jm},DM={name:"base64url",aliases:["base64-url","b64url"],encode:xM,decode:wM,is:aA,normalize:sA},NM={name:"utf8",aliases:["utf-8"],encode:(e)=>SM(e),decode:(e)=>gM(e),is:(e)=>typeof e==="string"},FM={name:"utf16be",aliases:["utf16","utf-16","utf-16be"],encode:(e)=>tA(e),decode:(e)=>eA(e),is:(e)=>typeof e==="string"},UM={name:"utf16le",aliases:["utf-16le","ucs2","usc2"],encode:(e)=>tA(e,{littleEndian:!0}),decode:(e)=>eA(e,{littleEndian:!0}),is:(e)=>typeof e==="string"},BM=[_M,kM,OM,DM,NM,FM,UM,Hm],Os=dA(BM);function uA(e,t,...r){return Os.encode(e,t,...r)}function pA(e,t,...r){return Os.decode(e,t,...r)}function oY(e,t,...r){return Os.tryDecode(e,t,...r)}function iY(e,t,...r){return Os.normalize(e,t,...r)}function sY(e,t,...r){return Os.parse(e,t,...r)}function aY(e,t,r){return Os.format(e,t,r)}function cY(e,t){return Os.transcode(e,t)}function lY(e,t){return Os.detect(e,t)}function dY(e){return e.toLowerCase()}var MM={encode:uA,decode:pA,tryDecode:oY,normalize:iY,parse:sY,format:aY,transcode:cY,detect:lY,to(e,t,...r){return uA(e,t,...r)},from(e,t,...r){return pA(e,t,...r)},toString(e,t="utf8"){return uA(t,e)},fromString(e,t="utf8"){if(dY(t)==="hex")return Qt(ax(e,{allowOddLength:!0}));return Qt(pA(t,e))},toBase64:nA,fromBase64:(e)=>Qt(oA(e)),toBase64Url:xM,fromBase64Url:(e)=>Qt(wM(e)),toHex:$m,fromHex:(e)=>Qt(ax(e,{allowOddLength:!0})),toBinary:ox,fromBinary:(e)=>Qt(ix(e)),toUtf8String:SM,fromUtf8String:(e)=>Qt(gM(e)),toUtf16String:(e,t=!1)=>tA(e,{littleEndian:t}),fromUtf16String:(e,t=!1)=>Qt(eA(e,{littleEndian:t})),isHex:hM,isBase64:cx,isBase64Url:aA,formatString:jm};var L;(function(e){e[e.Sequence=0]="Sequence",e[e.Set=1]="Set",e[e.Choice=2]="Choice"})(L||(L={}));var E;(function(e){e[e.Any=1]="Any",e[e.Boolean=2]="Boolean",e[e.OctetString=3]="OctetString",e[e.BitString=4]="BitString",e[e.Integer=5]="Integer",e[e.Enumerated=6]="Enumerated",e[e.ObjectIdentifier=7]="ObjectIdentifier",e[e.Utf8String=8]="Utf8String",e[e.BmpString=9]="BmpString",e[e.UniversalString=10]="UniversalString",e[e.NumericString=11]="NumericString",e[e.PrintableString=12]="PrintableString",e[e.TeletexString=13]="TeletexString",e[e.VideotexString=14]="VideotexString",e[e.IA5String=15]="IA5String",e[e.GraphicString=16]="GraphicString",e[e.VisibleString=17]="VisibleString",e[e.GeneralString=18]="GeneralString",e[e.CharacterString=19]="CharacterString",e[e.UTCTime=20]="UTCTime",e[e.GeneralizedTime=21]="GeneralizedTime",e[e.DATE=22]="DATE",e[e.TimeOfDay=23]="TimeOfDay",e[e.DateTime=24]="DateTime",e[e.Duration=25]="Duration",e[e.TIME=26]="TIME",e[e.Null=27]="Null",e[e.RelativeObjectIdentifier=28]="RelativeObjectIdentifier"})(E||(E={}));class ha{unusedBits=0;value=new ArrayBuffer(0);constructor(e,t=0){if(e)if(typeof e==="number")this.fromNumber(e);else if(_s(e))this.unusedBits=t,this.value=Qt(e);else throw TypeError("Unsupported type of 'params' argument for BitString")}fromASN(e){if(!(e instanceof Is))throw TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=Qt(e.valueBlock.valueHex),this}toASN(){return new Is({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new Is({name:e})}toNumber(){let e="",t=new Uint8Array(this.value);for(let r of t)e+=r.toString(2).padStart(8,"0");if(e=e.split("").reverse().join(""),this.unusedBits)e=e.slice(this.unusedBits).padStart(this.unusedBits,"0");return parseInt(e,2)}fromNumber(e){let t=e.toString(2),r=t.length+7>>3;this.unusedBits=(r<<3)-t.length;let n=new Uint8Array(r);t=t.padStart(r<<3,"0").split("").reverse().join("");let o=0;while(o<r)n[o]=parseInt(t.slice(o<<3,(o<<3)+8),2),o++;this.value=n.buffer}}class ae{buffer;get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){if(typeof e==="number")this.buffer=new ArrayBuffer(e);else if(_s(e))this.buffer=Qt(e);else if(Array.isArray(e))this.buffer=new Uint8Array(e).buffer;else this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof Ps))throw TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=Qt(e.valueBlock.valueHex),this}toASN(){return new Ps({valueHex:this.buffer})}toSchema(e){return new Ps({name:e})}}var uY={fromASN:(e)=>e instanceof As?null:Qt(e.valueBeforeDecodeView),toASN:(e)=>{if(e===null)return new As;let t=ya(e);if(t.result.error)throw Error(t.result.error);return t.result}},pY={fromASN:(e)=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:(e)=>new Ac({value:+e})},fY={fromASN:(e)=>e.valueBlock.valueDec,toASN:(e)=>new Ju({value:e})},bt={fromASN:(e)=>Qt(e.valueBlock.valueHexView),toASN:(e)=>new Ac({valueHex:e})};var mY={fromASN:(e)=>Qt(e.valueBlock.valueHexView),toASN:(e)=>new Is({valueHex:e})},yY={fromASN:(e)=>e.valueBlock.toString(),toASN:(e)=>new zu({value:e})},hY={fromASN:(e)=>e.valueBlock.toString(),toASN:(e)=>new Gu({value:e})},gY={fromASN:(e)=>e.valueBlock.value,toASN:(e)=>new Qu({value:e})},cp={fromASN:(e)=>Qt(e.valueBlock.valueHexView),toASN:(e)=>new Ps({valueHex:e})},LM={fromASN:(e)=>new ae(e.getValue()),toASN:(e)=>e.toASN()};function Ii(e){return{fromASN:(t)=>t.valueBlock.value,toASN:(t)=>new e({value:t})}}var fA=Ii(Zi),SY=Ii(Yu),vY=Ii(Xu),xY=Ii(Zu),wY=Ii(ep),bY=Ii(tp),EY=Ii(rp),TY=Ii(np),RY=Ii(op),AY=Ii(ql),PY=Ii(ip),IY=Ii(sp),CY={fromASN:(e)=>e.toDate(),toASN:(e)=>new jl({valueDate:e})},_Y={fromASN:(e)=>e.toDate(),toASN:(e)=>new ap({valueDate:e})},kY={fromASN:()=>null,toASN:()=>new As};function Pc(e){switch(e){case E.Any:return uY;case E.BitString:return mY;case E.BmpString:return SY;case E.Boolean:return gY;case E.CharacterString:return IY;case E.Enumerated:return fY;case E.GeneralString:return PY;case E.GeneralizedTime:return _Y;case E.GraphicString:return RY;case E.IA5String:return TY;case E.Integer:return pY;case E.Null:return kY;case E.NumericString:return xY;case E.ObjectIdentifier:return yY;case E.RelativeObjectIdentifier:return hY;case E.OctetString:return cp;case E.PrintableString:return wY;case E.TeletexString:return bY;case E.UTCTime:return CY;case E.UniversalString:return vY;case E.Utf8String:return fA;case E.VideotexString:return EY;case E.VisibleString:return AY;default:return null}}function Ci(e){if(typeof e==="function"&&e.prototype)if(e.prototype.toASN&&e.prototype.fromASN)return!0;else return Ci(e.prototype);else return!!(e&&typeof e==="object"&&("toASN"in e)&&("fromASN"in e))}function yA(e){if(e){let t=Object.getPrototypeOf(e);if(t?.prototype?.constructor===Array)return!0;return yA(t)}return!1}function $M(e,t){if(!(e&&t))return!1;if(e.byteLength!==t.byteLength)return!1;let r=new Uint8Array(e),n=new Uint8Array(t);for(let o=0;o<e.byteLength;o++)if(r[o]!==n[o])return!1;return!0}class hA{items=new WeakMap;has(e){return this.items.has(e)}get(e,t=!1){let r=this.items.get(e);if(!r)throw Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(t&&!r.schema)throw Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return r}cache(e){let t=this.get(e);if(!t.schema)t.schema=this.create(e,!0)}createDefault(e){let t={type:L.Sequence,items:{}},r=this.findParentSchema(e);if(r)Object.assign(t,r),t.items=Object.assign({},t.items,r.items);return t}create(e,t){let r=this.items.get(e)||this.createDefault(e),n=[];for(let o in r.items){let i=r.items[o],s=t?o:"",a;if(typeof i.type==="number"){let l=E[i.type],d=Cs[l];if(!d)throw Error(`Cannot get ASN1 class by name '${l}'`);a=new d({name:s})}else if(Ci(i.type))a=new i.type().toSchema(s);else if(i.optional)if(this.get(i.type).type===L.Choice)a=new fa({name:s});else a=this.create(i.type,!1),a.name=s;else a=new fa({name:s});let c=!!i.optional||i.defaultValue!==void 0;if(i.repeated)a.name="",a=new(i.repeated==="set"?qo:xo)({name:"",value:[new Vu({name:s,value:a})]});if(i.context!==null&&i.context!==void 0)if(i.implicit)if(typeof i.type==="number"||Ci(i.type)){let l=i.repeated?Rn:Rc;n.push(new l({name:s,optional:c,idBlock:{tagClass:3,tagNumber:i.context}}))}else{this.cache(i.type);let l=!!i.repeated,d=!l?this.get(i.type,!0).schema:a;d="valueBlock"in d?d.valueBlock.value:d.value,n.push(new Rn({name:!l?s:"",optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:d}))}else n.push(new Rn({optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:[a]}));else a.optional=c,n.push(a)}switch(r.type){case L.Sequence:return new xo({value:n,name:""});case L.Set:return new qo({value:n,name:""});case L.Choice:return new Mm({value:n,name:""});default:throw Error("Unsupported ASN1 type in use")}}set(e,t){return this.items.set(e,t),this}findParentSchema(e){let t=Object.getPrototypeOf(e);if(t)return this.items.get(t)||this.findParentSchema(t);return null}}var yn=new hA;var H=(e)=>(t)=>{let r;if(!yn.has(t))r=yn.createDefault(t),yn.set(t,r);else r=yn.get(t);Object.assign(r,e)};var g=(e)=>(t,r)=>{let n;if(!yn.has(t.constructor))n=yn.createDefault(t.constructor),yn.set(t.constructor,n);else n=yn.get(t.constructor);let o=Object.assign({},e);if(typeof o.type==="number"&&!o.converter){let i=Pc(e.type);if(!i)throw Error(`Cannot get default converter for property '${r}' of ${t.constructor.name}`);o.converter=i}o.raw=e.raw,n.items[r]=o};class Wl extends Error{schemas=[]}class Ir{static parse(e,t,r){let n=ya(Qt(e),r?.berOptions);if(n.result.error)throw Error(n.result.error);return this.fromASN(n.result,t,r)}static fromASN(e,t,r){try{if(Ci(t))return new t().fromASN(e);let n=yn.get(t);yn.cache(t);let o=n.schema,i=this.handleChoiceTypes(e,n,t,o,r);if(i?.result)return i.result;if(i?.targetSchema)o=i.targetSchema;let s=this.handleSequenceTypes(e,n,t,o),a=new t;if(yA(t))return this.handleArrayTypes(e,n,t,r);return this.processSchemaItems(n,s,a,r),a}catch(n){if(n instanceof Wl)n.schemas.push(t.name);throw n}}static handleChoiceTypes(e,t,r,n,o){if(e.constructor===Rn&&t.type===L.Choice&&e.idBlock.tagClass===3)for(let i in t.items){let s=t.items[i];if(s.context===e.idBlock.tagNumber&&s.implicit){if(typeof s.type==="function"&&yn.has(s.type)){let a=yn.get(s.type);if(a&&a.type===L.Sequence){let c=new xo;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in c.valueBlock){c.valueBlock.value=e.valueBlock.value;let l=this.fromASN(c,s.type,o),d=new r;return d[i]=l,{result:d}}}}}}else if(e.constructor===Rn&&t.type!==L.Choice){let i=new Rn({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:t.schema.valueBlock.value});for(let s in t.items)delete e[s];return{targetSchema:i}}return null}static handleSequenceTypes(e,t,r,n){if(t.type===L.Sequence){let o=ua({},e,n);if(!o.verified)throw new Wl(`Data does not match to ${r.name} ASN1 schema.${o.result.error?` ${o.result.error}`:""}`);return o}else{let o=ua({},e,n);if(!o.verified)throw new Wl(`Data does not match to ${r.name} ASN1 schema.${o.result.error?` ${o.result.error}`:""}`);return o}}static processRepeatedField(e,t,r){let n=e.slice(t);if(n.length===1&&n[0].constructor.name==="Sequence"){let o=n[0];if(o.valueBlock&&o.valueBlock.value&&Array.isArray(o.valueBlock.value))n=o.valueBlock.value}if(typeof r.type==="number"){let o=Pc(r.type);if(!o)throw Error(`No converter for ASN.1 type ${r.type}`);return n.filter((i)=>i&&i.valueBlock).map((i)=>{try{return o.fromASN(i)}catch{return}}).filter((i)=>i!==void 0)}else return n.filter((o)=>o&&o.valueBlock).map((o)=>{try{return this.fromASN(o,r.type)}catch{return}}).filter((o)=>o!==void 0)}static processPrimitiveField(e,t){let r=Pc(t.type);if(!r)throw Error(`No converter for ASN.1 type ${t.type}`);return r.fromASN(e)}static isOptionalChoiceField(e){return e.optional&&typeof e.type==="function"&&yn.has(e.type)&&yn.get(e.type).type===L.Choice}static processOptionalChoiceField(e,t){try{return{processed:!0,value:this.fromASN(e,t.type)}}catch(r){if(r instanceof Wl&&/Wrong values for Choice type/.test(r.message))return{processed:!1};throw r}}static handleArrayTypes(e,t,r,n){if(!(("value"in e.valueBlock)&&Array.isArray(e.valueBlock.value)))throw Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");let o=t.itemType;if(typeof o==="number"){let i=Pc(o);if(!i)throw Error(`Cannot get default converter for array item of ${r.name} ASN1 schema`);return r.from(e.valueBlock.value,(s)=>i.fromASN(s))}else return r.from(e.valueBlock.value,(i)=>this.fromASN(i,o,n))}static processSchemaItems(e,t,r,n){for(let o in e.items){let i=t.result[o];if(!i)continue;let s=e.items[o],a=s.type,c;if(typeof a==="number"||Ci(a))c=this.processPrimitiveSchemaItem(i,s,a,n);else c=this.processComplexSchemaItem(i,s,a,n);if(c&&typeof c==="object"&&"value"in c&&"raw"in c)r[o]=c.value,r[`${o}Raw`]=c.raw;else r[o]=c}}static processPrimitiveSchemaItem(e,t,r,n){let o=t.converter??(Ci(r)?new r:null);if(!o)throw Error("Converter is empty");if(t.repeated)return this.processRepeatedPrimitiveItem(e,t,o,n);else return this.processSinglePrimitiveItem(e,t,r,o,n)}static processRepeatedPrimitiveItem(e,t,r,n){if(t.implicit){let i=new(t.repeated==="sequence"?xo:qo);i.valueBlock=e.valueBlock;let s=ya(i.toBER(!1),n?.berOptions);if(s.offset===-1)throw Error(`Cannot parse the child item. ${s.result.error}`);if(!(("value"in s.result.valueBlock)&&Array.isArray(s.result.valueBlock.value)))throw Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");let a=s.result.valueBlock.value;return Array.from(a,(c)=>r.fromASN(c))}else return Array.from(e,(o)=>r.fromASN(o))}static processSinglePrimitiveItem(e,t,r,n,o){let i=e;if(t.implicit){let s;if(Ci(r))s=new r().toSchema("");else{let a=E[r],c=Cs[a];if(!c)throw Error(`Cannot get '${a}' class from asn1js module`);s=new c}s.valueBlock=i.valueBlock,i=ya(s.toBER(!1),o?.berOptions).result}return n.fromASN(i)}static processComplexSchemaItem(e,t,r,n){if(t.repeated){if(!Array.isArray(e))throw Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");return Array.from(e,(o)=>this.fromASN(o,r,n))}else{let o=this.handleImplicitTagging(e,t,r);if(this.isOptionalChoiceField(t))try{return this.fromASN(o,r,n)}catch(i){if(i instanceof Wl&&/Wrong values for Choice type/.test(i.message))return;throw i}else{let i=this.fromASN(o,r,n);if(t.raw)return{value:i,raw:e.valueBeforeDecodeView};return i}}}static handleImplicitTagging(e,t,r){if(t.implicit&&typeof t.context==="number"){let n=yn.get(r);if(n.type===L.Sequence){let o=new xo;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in o.valueBlock)return o.valueBlock.value=e.valueBlock.value,o}else if(n.type===L.Set){let o=new qo;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in o.valueBlock)return o.valueBlock.value=e.valueBlock.value,o}}return e}}class Wm{static serialize(e){if(e instanceof mn)return e.toBER(!1);return this.toASN(e).toBER(!1)}static toASN(e){if(e&&typeof e==="object"&&Ci(e))return e.toASN();if(!(e&&typeof e==="object"))throw TypeError("Parameter 1 should be type of Object.");let t=e.constructor,r=yn.get(t);yn.cache(t);let n=[];if(r.itemType){if(!Array.isArray(e))throw TypeError("Parameter 1 should be type of Array.");if(typeof r.itemType==="number"){let i=Pc(r.itemType);if(!i)throw Error(`Cannot get default converter for array item of ${t.name} ASN1 schema`);n=e.map((s)=>i.toASN(s))}else n=e.map((i)=>this.toAsnItem({type:r.itemType},"[]",t,i))}else for(let i in r.items){let s=r.items[i],a=e[i];if(a===void 0||s.defaultValue===a||typeof s.defaultValue==="object"&&typeof a==="object"&&$M(this.serialize(s.defaultValue),this.serialize(a)))continue;let c=Wm.toAsnItem(s,i,t,a);if(typeof s.context==="number")if(s.implicit)if(!s.repeated&&(typeof s.type==="number"||Ci(s.type))){let l={};l.valueHex=c instanceof As?Qt(c.valueBeforeDecodeView):c.valueBlock.toBER(),n.push(new Rc({optional:s.optional,idBlock:{tagClass:3,tagNumber:s.context},...l}))}else n.push(new Rn({optional:s.optional,idBlock:{tagClass:3,tagNumber:s.context},value:c.valueBlock.value}));else n.push(new Rn({optional:s.optional,idBlock:{tagClass:3,tagNumber:s.context},value:[c]}));else if(s.repeated)n=n.concat(c);else n.push(c)}let o;switch(r.type){case L.Sequence:o=new xo({value:n});break;case L.Set:o=new qo({value:n});break;case L.Choice:if(!n[0])throw Error(`Schema '${t.name}' has wrong data. Choice cannot be empty.`);o=n[0];break}return o}static toAsnItem(e,t,r,n){let o;if(typeof e.type==="number"){let i=e.converter;if(!i)throw Error(`Property '${t}' doesn't have converter for type ${E[e.type]} in schema '${r.name}'`);if(e.repeated){if(!Array.isArray(n))throw TypeError("Parameter 'objProp' should be type of Array.");let s=Array.from(n,(c)=>i.toASN(c));o=new(e.repeated==="sequence"?xo:qo)({value:s})}else o=i.toASN(n)}else if(e.repeated){if(!Array.isArray(n))throw TypeError("Parameter 'objProp' should be type of Array.");let i=Array.from(n,(a)=>this.toASN(a));o=new(e.repeated==="sequence"?xo:qo)({value:i})}else o=this.toASN(n);return o}}class Ie extends Array{constructor(e=[]){if(typeof e==="number")super(e);else{super();for(let t of e)this.push(t)}}}class ne{static serialize(e){return Wm.serialize(e)}static parse(e,t,r){return Ir.parse(e,t,r)}static toString(e,t){let r=_s(e)?Qt(e):ne.serialize(e),n=ya(r,t?.berOptions);if(n.offset===-1)throw Error(`Cannot decode ASN.1 data. ${n.result.error}`);return n.result.toString()}}var hL=zr(yL(),1),{__extends:XLe,__assign:ZLe,__rest:e1e,__decorate:y,__param:t1e,__esDecorate:r1e,__runInitializers:n1e,__propKey:o1e,__setFunctionName:i1e,__metadata:s1e,__awaiter:a1e,__generator:c1e,__exportStar:l1e,__createBinding:d1e,__values:u1e,__read:p1e,__spread:f1e,__spreadArrays:m1e,__spreadArray:y1e,__await:h1e,__asyncGenerator:g1e,__asyncDelegator:S1e,__asyncValues:v1e,__makeTemplateObject:x1e,__importStar:w1e,__importDefault:b1e,__classPrivateFieldGet:be,__classPrivateFieldSet:vt,__classPrivateFieldIn:E1e,__addDisposableResource:T1e,__disposeResources:R1e,__rewriteRelativeImportExtension:A1e}=hL.default;class fx{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){let t=e.split(".");if(t.length!==4)throw Error("Invalid IPv4 address");return t.map((r)=>{let n=parseInt(r,10);if(isNaN(n)||n<0||n>255)throw Error("Invalid IPv4 address part");return n})}static parseIPv6(e){let r=this.expandIPv6(e).split(":");if(r.length!==8)throw Error("Invalid IPv6 address");return r.reduce((n,o)=>{let i=parseInt(o,16);if(isNaN(i)||i<0||i>65535)throw Error("Invalid IPv6 address part");return n.push(i>>8&255),n.push(i&255),n},[])}static expandIPv6(e){if(!e.includes("::"))return e;let t=e.split("::");if(t.length>2)throw Error("Invalid IPv6 address");let r=t[0]?t[0].split(":"):[],n=t[1]?t[1].split(":"):[],o=8-(r.length+n.length);if(o<0)throw Error("Invalid IPv6 address");return[...r,...Array(o).fill("0"),...n].join(":")}static formatIPv6(e){let t=[];for(let r=0;r<16;r+=2)t.push((e[r]<<8|e[r+1]).toString(16));return this.compressIPv6(t.join(":"))}static compressIPv6(e){let t=e.split(":"),r=-1,n=0,o=-1,i=0;for(let s=0;s<t.length;s++)if(t[s]==="0"){if(o===-1)o=s;i++}else{if(i>n)r=o,n=i;o=-1,i=0}if(i>n)r=o,n=i;if(n>1){let s=t.slice(0,r).join(":"),a=t.slice(r+n).join(":");return`${s}::${a}`}return e}static parseCIDR(e){let[t,r]=e.split("/"),n=parseInt(r,10);if(this.isIPv4(t)){if(n<0||n>32)throw Error("Invalid IPv4 prefix length");return[this.parseIPv4(t),n]}else{if(n<0||n>128)throw Error("Invalid IPv6 prefix length");return[this.parseIPv6(t),n]}}static decodeIP(e){if(e.length===64&&parseInt(e,16)===0)return"::/0";if(e.length!==16)return e;let t=parseInt(e.slice(8),16).toString(2).split("").reduce((n,o)=>n+ +o,0),r=e.slice(0,8).replace(/(.{2})/g,(n)=>`${parseInt(n,16)}.`);return r=r.slice(0,-1),`${r}/${t}`}static toString(e){let t=new Uint8Array(e);if(t.length===4)return Array.from(t).join(".");if(t.length===16)return this.formatIPv6(t);if(t.length===8||t.length===32){let r=t.length/2,n=t.slice(0,r),o=t.slice(r);if(t.every((a)=>a===0))return t.length===8?"0.0.0.0/0":"::/0";let s=o.reduce((a,c)=>a+(c.toString(2).match(/1/g)||[]).length,0);if(t.length===8)return`${Array.from(n).join(".")}/${s}`;else return`${this.formatIPv6(n)}/${s}`}return this.decodeIP($m(e))}static fromString(e){if(e.includes("/")){let[r,n]=this.parseCIDR(e),o=new Uint8Array(r.length),i=n;for(let a=0;a<o.length;a++)if(i>=8)o[a]=255,i-=8;else if(i>0)o[a]=255<<8-i,i=0;let s=new Uint8Array(r.length*2);return s.set(r,0),s.set(o,r.length),s.buffer}let t=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(t).buffer}}var SA,vA,xA,hn=class{teletexString;printableString;universalString;utf8String;bmpString;constructor(t={}){Object.assign(this,t)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};y([g({type:E.TeletexString})],hn.prototype,"teletexString",void 0);y([g({type:E.PrintableString})],hn.prototype,"printableString",void 0);y([g({type:E.UniversalString})],hn.prototype,"universalString",void 0);y([g({type:E.Utf8String})],hn.prototype,"utf8String",void 0);y([g({type:E.BmpString})],hn.prototype,"bmpString",void 0);hn=y([H({type:L.Choice})],hn);var dp=class extends hn{ia5String;anyValue;constructor(t={}){super(t);Object.assign(this,t)}toString(){return this.ia5String||(this.anyValue?$m(this.anyValue):super.toString())}};y([g({type:E.IA5String})],dp.prototype,"ia5String",void 0);y([g({type:E.Any})],dp.prototype,"anyValue",void 0);dp=y([H({type:L.Choice})],dp);class up{type="";value=new dp;constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier})],up.prototype,"type",void 0);y([g({type:dp})],up.prototype,"value",void 0);var Ic=SA=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,SA.prototype)}};Ic=SA=y([H({type:L.Set,itemType:up})],Ic);var wA=vA=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,vA.prototype)}};wA=vA=y([H({type:L.Sequence,itemType:Ic})],wA);var ir=xA=class extends wA{constructor(t){super(t);Object.setPrototypeOf(this,xA.prototype)}};ir=xA=y([H({type:L.Sequence})],ir);var OY={fromASN:(e)=>fx.toString(cp.fromASN(e)),toASN:(e)=>cp.toASN(fx.fromString(e))};class Kl{typeId="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier})],Kl.prototype,"typeId",void 0);y([g({type:E.Any,context:0})],Kl.prototype,"value",void 0);class mx{nameAssigner;partyName=new hn;constructor(e={}){Object.assign(this,e)}}y([g({type:hn,optional:!0,context:0,implicit:!0})],mx.prototype,"nameAssigner",void 0);y([g({type:hn,context:1,implicit:!0})],mx.prototype,"partyName",void 0);var je=class{otherName;rfc822Name;dNSName;x400Address;directoryName;ediPartyName;uniformResourceIdentifier;iPAddress;registeredID;constructor(t={}){Object.assign(this,t)}};y([g({type:Kl,context:0,implicit:!0})],je.prototype,"otherName",void 0);y([g({type:E.IA5String,context:1,implicit:!0})],je.prototype,"rfc822Name",void 0);y([g({type:E.IA5String,context:2,implicit:!0})],je.prototype,"dNSName",void 0);y([g({type:E.Any,context:3,implicit:!0})],je.prototype,"x400Address",void 0);y([g({type:ir,context:4,implicit:!1})],je.prototype,"directoryName",void 0);y([g({type:mx,context:5})],je.prototype,"ediPartyName",void 0);y([g({type:E.IA5String,context:6,implicit:!0})],je.prototype,"uniformResourceIdentifier",void 0);y([g({type:E.OctetString,context:7,implicit:!0,converter:OY})],je.prototype,"iPAddress",void 0);y([g({type:E.ObjectIdentifier,context:8,implicit:!0})],je.prototype,"registeredID",void 0);je=y([H({type:L.Choice})],je);var yx="1.3.6.1.5.5.7",Cc="1.3.6.1.5.5.7.1";var Vl="1.3.6.1.5.5.7.3";var bA="1.3.6.1.5.5.7.48.1",EA="1.3.6.1.5.5.7.48.2",TA="1.3.6.1.5.5.7.48.3",RA="1.3.6.1.5.5.7.48.5",it="2.5.29";var AA,hx=`${Cc}.1`;class _c{accessMethod="";accessLocation=new je;constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier})],_c.prototype,"accessMethod",void 0);y([g({type:je})],_c.prototype,"accessLocation",void 0);var Ql=AA=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,AA.prototype)}};Ql=AA=y([H({type:L.Sequence,itemType:_c})],Ql);var Km=`${it}.35`;class pp extends ae{}class ga{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){if(e)Object.assign(this,e)}}y([g({type:pp,context:0,optional:!0,implicit:!0})],ga.prototype,"keyIdentifier",void 0);y([g({type:je,context:1,optional:!0,implicit:!0,repeated:"sequence"})],ga.prototype,"authorityCertIssuer",void 0);y([g({type:E.Integer,context:2,optional:!0,implicit:!0,converter:bt})],ga.prototype,"authorityCertSerialNumber",void 0);var fp=`${it}.19`;class kc{cA=!1;pathLenConstraint;constructor(e={}){Object.assign(this,e)}}y([g({type:E.Boolean,defaultValue:!1})],kc.prototype,"cA",void 0);y([g({type:E.Integer,optional:!0})],kc.prototype,"pathLenConstraint",void 0);var PA,gr=PA=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,PA.prototype)}};gr=PA=y([H({type:L.Sequence,itemType:je})],gr);var IA,DY=`${it}.29`,gL=IA=class extends gr{constructor(t){super(t);Object.setPrototypeOf(this,IA.prototype)}};gL=IA=y([H({type:L.Sequence})],gL);var CA,Sx=`${it}.32`,p$e=`${Sx}.0`,Sa=class{ia5String;visibleString;bmpString;utf8String;constructor(t={}){Object.assign(this,t)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};y([g({type:E.IA5String})],Sa.prototype,"ia5String",void 0);y([g({type:E.VisibleString})],Sa.prototype,"visibleString",void 0);y([g({type:E.BmpString})],Sa.prototype,"bmpString",void 0);y([g({type:E.Utf8String})],Sa.prototype,"utf8String",void 0);Sa=y([H({type:L.Choice})],Sa);class vx{organization=new Sa;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}}y([g({type:Sa})],vx.prototype,"organization",void 0);y([g({type:E.Integer,repeated:"sequence"})],vx.prototype,"noticeNumbers",void 0);class xx{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}}y([g({type:vx,optional:!0})],xx.prototype,"noticeRef",void 0);y([g({type:Sa,optional:!0})],xx.prototype,"explicitText",void 0);var gx=class{cPSuri;userNotice;constructor(t={}){Object.assign(this,t)}};y([g({type:E.IA5String})],gx.prototype,"cPSuri",void 0);y([g({type:xx})],gx.prototype,"userNotice",void 0);gx=y([H({type:L.Choice})],gx);class wx{policyQualifierId="";qualifier=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier})],wx.prototype,"policyQualifierId",void 0);y([g({type:E.Any})],wx.prototype,"qualifier",void 0);class mp{policyIdentifier="";policyQualifiers;constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier})],mp.prototype,"policyIdentifier",void 0);y([g({type:wx,repeated:"sequence",optional:!0})],mp.prototype,"policyQualifiers",void 0);var Vm=CA=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,CA.prototype)}};Vm=CA=y([H({type:L.Sequence,itemType:mp})],Vm);var g$e=`${it}.20`,Qm=class{value;constructor(t=0){this.value=t}};y([g({type:E.Integer})],Qm.prototype,"value",void 0);Qm=y([H({type:L.Choice})],Qm);var E$e=`${it}.27`,SL=class extends Qm{};SL=y([H({type:L.Choice})],SL);var _A,bx=`${it}.31`,es;(function(e){e[e.unused=1]="unused",e[e.keyCompromise=2]="keyCompromise",e[e.cACompromise=4]="cACompromise",e[e.affiliationChanged=8]="affiliationChanged",e[e.superseded=16]="superseded",e[e.cessationOfOperation=32]="cessationOfOperation",e[e.certificateHold=64]="certificateHold",e[e.privilegeWithdrawn=128]="privilegeWithdrawn",e[e.aACompromise=256]="aACompromise"})(es||(es={}));class Ex extends ha{toJSON(){let e=[],t=this.toNumber();if(t&es.aACompromise)e.push("aACompromise");if(t&es.affiliationChanged)e.push("affiliationChanged");if(t&es.cACompromise)e.push("cACompromise");if(t&es.certificateHold)e.push("certificateHold");if(t&es.cessationOfOperation)e.push("cessationOfOperation");if(t&es.keyCompromise)e.push("keyCompromise");if(t&es.privilegeWithdrawn)e.push("privilegeWithdrawn");if(t&es.superseded)e.push("superseded");if(t&es.unused)e.push("unused");return e}toString(){return`[${this.toJSON().join(", ")}]`}}var va=class{fullName;nameRelativeToCRLIssuer;constructor(t={}){Object.assign(this,t)}};y([g({type:je,context:0,repeated:"sequence",implicit:!0})],va.prototype,"fullName",void 0);y([g({type:Ic,context:1,implicit:!0})],va.prototype,"nameRelativeToCRLIssuer",void 0);va=y([H({type:L.Choice})],va);class xa{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}}y([g({type:va,context:0,optional:!0})],xa.prototype,"distributionPoint",void 0);y([g({type:Ex,context:1,optional:!0,implicit:!0})],xa.prototype,"reasons",void 0);y([g({type:je,context:2,optional:!0,repeated:"sequence",implicit:!0})],xa.prototype,"cRLIssuer",void 0);var Oc=_A=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,_A.prototype)}};Oc=_A=y([H({type:L.Sequence,itemType:xa})],Oc);var kA,F$e=`${it}.46`,vL=kA=class extends Oc{constructor(t){super(t);Object.setPrototypeOf(this,kA.prototype)}};vL=kA=y([H({type:L.Sequence,itemType:xa})],vL);var q$e=`${it}.28`;class wo{static ONLY=!1;distributionPoint;onlyContainsUserCerts=wo.ONLY;onlyContainsCACerts=wo.ONLY;onlySomeReasons;indirectCRL=wo.ONLY;onlyContainsAttributeCerts=wo.ONLY;constructor(e={}){Object.assign(this,e)}}y([g({type:va,context:0,optional:!0})],wo.prototype,"distributionPoint",void 0);y([g({type:E.Boolean,context:1,defaultValue:wo.ONLY,implicit:!0})],wo.prototype,"onlyContainsUserCerts",void 0);y([g({type:E.Boolean,context:2,defaultValue:wo.ONLY,implicit:!0})],wo.prototype,"onlyContainsCACerts",void 0);y([g({type:Ex,context:3,optional:!0,implicit:!0})],wo.prototype,"onlySomeReasons",void 0);y([g({type:E.Boolean,context:4,defaultValue:wo.ONLY,implicit:!0})],wo.prototype,"indirectCRL",void 0);y([g({type:E.Boolean,context:5,defaultValue:wo.ONLY,implicit:!0})],wo.prototype,"onlyContainsAttributeCerts",void 0);var OA=`${it}.21`,Jm;(function(e){e[e.unspecified=0]="unspecified",e[e.keyCompromise=1]="keyCompromise",e[e.cACompromise=2]="cACompromise",e[e.affiliationChanged=3]="affiliationChanged",e[e.superseded=4]="superseded",e[e.cessationOfOperation=5]="cessationOfOperation",e[e.certificateHold=6]="certificateHold",e[e.removeFromCRL=8]="removeFromCRL",e[e.privilegeWithdrawn=9]="privilegeWithdrawn",e[e.aACompromise=10]="aACompromise"})(Jm||(Jm={}));var yp=class{reason=Jm.unspecified;constructor(t=Jm.unspecified){this.reason=t}toJSON(){return Jm[this.reason]}toString(){return this.toJSON()}};y([g({type:E.Enumerated})],yp.prototype,"reason",void 0);yp=y([H({type:L.Choice})],yp);var DA,hp=`${it}.37`,Jl=DA=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,DA.prototype)}};Jl=DA=y([H({type:L.Sequence,itemType:E.ObjectIdentifier})],Jl);var G$e=`${hp}.0`,xL=`${Vl}.1`,wL=`${Vl}.2`,bL=`${Vl}.3`,EL=`${Vl}.4`,TL=`${Vl}.8`,RL=`${Vl}.9`;var tqe=`${it}.54`,NA=class{value;constructor(t=new ArrayBuffer(0)){this.value=t}};y([g({type:E.Integer,converter:bt})],NA.prototype,"value",void 0);NA=y([H({type:L.Choice})],NA);var FA=`${it}.24`,gp=class{value=new Date;constructor(t){if(t)this.value=t}};y([g({type:E.GeneralizedTime})],gp.prototype,"value",void 0);gp=y([H({type:L.Choice})],gp);var UA,BA=`${it}.18`,AL=UA=class extends gr{constructor(t){super(t);Object.setPrototypeOf(this,UA.prototype)}};AL=UA=y([H({type:L.Sequence})],AL);var Tx=`${it}.15`,ts;(function(e){e[e.digitalSignature=1]="digitalSignature",e[e.nonRepudiation=2]="nonRepudiation",e[e.keyEncipherment=4]="keyEncipherment",e[e.dataEncipherment=8]="dataEncipherment",e[e.keyAgreement=16]="keyAgreement",e[e.keyCertSign=32]="keyCertSign",e[e.cRLSign=64]="cRLSign",e[e.encipherOnly=128]="encipherOnly",e[e.decipherOnly=256]="decipherOnly"})(ts||(ts={}));class zm extends ha{toJSON(){let e=this.toNumber(),t=[];if(e&ts.cRLSign)t.push("crlSign");if(e&ts.dataEncipherment)t.push("dataEncipherment");if(e&ts.decipherOnly)t.push("decipherOnly");if(e&ts.digitalSignature)t.push("digitalSignature");if(e&ts.encipherOnly)t.push("encipherOnly");if(e&ts.keyAgreement)t.push("keyAgreement");if(e&ts.keyCertSign)t.push("keyCertSign");if(e&ts.keyEncipherment)t.push("keyEncipherment");if(e&ts.nonRepudiation)t.push("nonRepudiation");return t}toString(){return`[${this.toJSON().join(", ")}]`}}var MA,vqe=`${it}.30`;class Gm{base=new je;minimum=0;maximum;constructor(e={}){Object.assign(this,e)}}y([g({type:je})],Gm.prototype,"base",void 0);y([g({type:E.Integer,context:0,defaultValue:0,implicit:!0})],Gm.prototype,"minimum",void 0);y([g({type:E.Integer,context:1,optional:!0,implicit:!0})],Gm.prototype,"maximum",void 0);var Rx=MA=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,MA.prototype)}};Rx=MA=y([H({type:L.Sequence,itemType:Gm})],Rx);class LA{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}}y([g({type:Rx,context:0,optional:!0,implicit:!0})],LA.prototype,"permittedSubtrees",void 0);y([g({type:Rx,context:1,optional:!0,implicit:!0})],LA.prototype,"excludedSubtrees",void 0);var Tqe=`${it}.36`;class $A{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer,context:0,implicit:!0,optional:!0,converter:bt})],$A.prototype,"requireExplicitPolicy",void 0);y([g({type:E.Integer,context:1,implicit:!0,optional:!0,converter:bt})],$A.prototype,"inhibitPolicyMapping",void 0);var qA,Cqe=`${it}.33`;class Ax{issuerDomainPolicy="";subjectDomainPolicy="";constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier})],Ax.prototype,"issuerDomainPolicy",void 0);y([g({type:E.ObjectIdentifier})],Ax.prototype,"subjectDomainPolicy",void 0);var PL=qA=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,qA.prototype)}};PL=qA=y([H({type:L.Sequence,itemType:Ax})],PL);var jA,vp=`${it}.17`,Sp=jA=class extends gr{constructor(t){super(t);Object.setPrototypeOf(this,jA.prototype)}};Sp=jA=y([H({type:L.Sequence})],Sp);class to{type="";values=[];constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier})],to.prototype,"type",void 0);y([g({type:E.Any,repeated:"set"})],to.prototype,"values",void 0);var HA,Hqe=`${it}.9`,IL=HA=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,HA.prototype)}};IL=HA=y([H({type:L.Sequence,itemType:to})],IL);var Px=`${it}.14`;class ri extends pp{}var Yqe=`${it}.16`;class WA{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}}y([g({type:E.GeneralizedTime,context:0,implicit:!0,optional:!0})],WA.prototype,"notBefore",void 0);y([g({type:E.GeneralizedTime,context:1,implicit:!0,optional:!0})],WA.prototype,"notAfter",void 0);var Ym;(function(e){e[e.keyUpdateAllowed=1]="keyUpdateAllowed",e[e.newExtensions=2]="newExtensions",e[e.pKIXCertificate=4]="pKIXCertificate"})(Ym||(Ym={}));class KA extends ha{toJSON(){let e=[],t=this.toNumber();if(t&Ym.pKIXCertificate)e.push("pKIXCertificate");if(t&Ym.newExtensions)e.push("newExtensions");if(t&Ym.keyUpdateAllowed)e.push("keyUpdateAllowed");return e}toString(){return`[${this.toJSON().join(", ")}]`}}class VA{entrustVers="";entrustInfoFlags=new KA;constructor(e={}){Object.assign(this,e)}}y([g({type:E.GeneralString})],VA.prototype,"entrustVers",void 0);y([g({type:KA})],VA.prototype,"entrustInfoFlags",void 0);var QA,sje=`${Cc}.11`,CL=QA=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,QA.prototype)}};CL=QA=y([H({type:L.Sequence,itemType:_c})],CL);class ie{algorithm="";parameters;constructor(e={}){Object.assign(this,e)}isEqual(e){return e instanceof ie&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&Lm(e.parameters,this.parameters)||e.parameters===this.parameters)}}y([g({type:E.ObjectIdentifier})],ie.prototype,"algorithm",void 0);y([g({type:E.Any,optional:!0})],ie.prototype,"parameters",void 0);class bo{algorithm=new ie;subjectPublicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:ie})],bo.prototype,"algorithm",void 0);y([g({type:E.BitString})],bo.prototype,"subjectPublicKey",void 0);var Nr=class{utcTime;generalTime;constructor(t){if(t)if(typeof t==="string"||typeof t==="number"||t instanceof Date){let r=new Date(t);if(r.setMilliseconds(0),r.getUTCFullYear()>2049)this.generalTime=r;else this.utcTime=r}else Object.assign(this,t)}getTime(){let t=this.utcTime||this.generalTime;if(!t)throw Error("Cannot get time from CHOICE object");return t}};y([g({type:E.UTCTime})],Nr.prototype,"utcTime",void 0);y([g({type:E.GeneralizedTime})],Nr.prototype,"generalTime",void 0);Nr=y([H({type:L.Choice})],Nr);class zl{notBefore=new Nr(new Date);notAfter=new Nr(new Date);constructor(e){if(e)this.notBefore=new Nr(e.notBefore),this.notAfter=new Nr(e.notAfter)}}y([g({type:Nr})],zl.prototype,"notBefore",void 0);y([g({type:Nr})],zl.prototype,"notAfter",void 0);var JA;class Eo{static CRITICAL=!1;extnID="";critical=Eo.CRITICAL;extnValue=new ae;constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier})],Eo.prototype,"extnID",void 0);y([g({type:E.Boolean,defaultValue:Eo.CRITICAL})],Eo.prototype,"critical",void 0);y([g({type:ae})],Eo.prototype,"extnValue",void 0);var _i=JA=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,JA.prototype)}};_i=JA=y([H({type:L.Sequence,itemType:Eo})],_i);var wa;(function(e){e[e.v1=0]="v1",e[e.v2=1]="v2",e[e.v3=2]="v3"})(wa||(wa={}));class To{version=wa.v1;serialNumber=new ArrayBuffer(0);signature=new ie;issuer=new ir;validity=new zl;subject=new ir;subjectPublicKeyInfo=new bo;issuerUniqueID;subjectUniqueID;extensions;constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer,context:0,defaultValue:wa.v1})],To.prototype,"version",void 0);y([g({type:E.Integer,converter:bt})],To.prototype,"serialNumber",void 0);y([g({type:ie})],To.prototype,"signature",void 0);y([g({type:ir})],To.prototype,"issuer",void 0);y([g({type:zl})],To.prototype,"validity",void 0);y([g({type:ir})],To.prototype,"subject",void 0);y([g({type:bo})],To.prototype,"subjectPublicKeyInfo",void 0);y([g({type:E.BitString,context:1,implicit:!0,optional:!0})],To.prototype,"issuerUniqueID",void 0);y([g({type:E.BitString,context:2,implicit:!0,optional:!0})],To.prototype,"subjectUniqueID",void 0);y([g({type:_i,context:3,optional:!0})],To.prototype,"extensions",void 0);class nn{tbsCertificate=new To;tbsCertificateRaw;signatureAlgorithm=new ie;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:To,raw:!0})],nn.prototype,"tbsCertificate",void 0);y([g({type:ie})],nn.prototype,"signatureAlgorithm",void 0);y([g({type:E.BitString})],nn.prototype,"signatureValue",void 0);class ba{userCertificate=new ArrayBuffer(0);revocationDate=new Nr;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer,converter:bt})],ba.prototype,"userCertificate",void 0);y([g({type:Nr})],ba.prototype,"revocationDate",void 0);y([g({type:Eo,optional:!0,repeated:"sequence"})],ba.prototype,"crlEntryExtensions",void 0);class ki{version;signature=new ie;issuer=new ir;thisUpdate=new Nr;nextUpdate;revokedCertificates;crlExtensions;constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer,optional:!0})],ki.prototype,"version",void 0);y([g({type:ie})],ki.prototype,"signature",void 0);y([g({type:ir})],ki.prototype,"issuer",void 0);y([g({type:Nr})],ki.prototype,"thisUpdate",void 0);y([g({type:Nr,optional:!0})],ki.prototype,"nextUpdate",void 0);y([g({type:ba,repeated:"sequence",optional:!0})],ki.prototype,"revokedCertificates",void 0);y([g({type:Eo,optional:!0,context:0,repeated:"sequence"})],ki.prototype,"crlExtensions",void 0);class Gl{tbsCertList=new ki;tbsCertListRaw;signatureAlgorithm=new ie;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:ki,raw:!0})],Gl.prototype,"tbsCertList",void 0);y([g({type:ie})],Gl.prototype,"signatureAlgorithm",void 0);y([g({type:E.BitString})],Gl.prototype,"signature",void 0);var kL={"2.5.4.6":"C","2.5.4.10":"O","2.5.4.11":"OU","2.5.4.3":"CN"};function xp(e){let t=Ir.parse(e,nn),r=t.tbsCertificate,n={combined:""};r.issuer.forEach(([s])=>{let a=kL[s.type];if(a)n[a]=s.value.toString()}),n.combined=OL(n);let o={combined:""};r.subject.forEach(([s])=>{let a=kL[s.type];if(a)o[a]=s.value.toString()}),o.combined=OL(o);let i=!1;if(r.extensions){for(let s of r.extensions)if(s.extnID===fp)i=Ir.parse(s.extnValue,kc).cA}return{issuer:n,subject:o,version:r.version,basicConstraintsCA:i,notBefore:r.validity.notBefore.getTime(),notAfter:r.validity.notAfter.getTime(),parsedCertificate:t}}function OL(e){let t=[];if(e.C)t.push(e.C);if(e.O)t.push(e.O);if(e.OU)t.push(e.OU);if(e.CN)t.push(e.CN);return t.join(" : ")}var Lze=zr(NL());class Ds{issuer=new ir;serialNumber=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:ir})],Ds.prototype,"issuer",void 0);y([g({type:E.Integer,converter:bt})],Ds.prototype,"serialNumber",void 0);var Yl=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(t={}){Object.assign(this,t)}};y([g({type:ri,context:0,implicit:!0})],Yl.prototype,"subjectKeyIdentifier",void 0);y([g({type:Ds})],Yl.prototype,"issuerAndSerialNumber",void 0);Yl=y([H({type:L.Choice})],Yl);var Bn;(function(e){e[e.v0=0]="v0",e[e.v1=1]="v1",e[e.v2=2]="v2",e[e.v3=3]="v3",e[e.v4=4]="v4",e[e.v5=5]="v5"})(Bn||(Bn={}));var Xl=class extends ie{};Xl=y([H({type:L.Sequence})],Xl);var Xm=class extends ie{};Xm=y([H({type:L.Sequence})],Xm);var Ho=class extends ie{};Ho=y([H({type:L.Sequence})],Ho);var Zm=class extends ie{};Zm=y([H({type:L.Sequence})],Zm);var FL=class extends ie{};FL=y([H({type:L.Sequence})],FL);var Ix=class extends ie{};Ix=y([H({type:L.Sequence})],Ix);class Ns{attrType="";attrValues=[];constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier})],Ns.prototype,"attrType",void 0);y([g({type:E.Any,repeated:"set"})],Ns.prototype,"attrValues",void 0);var zA;class ni{version=Bn.v0;sid=new Yl;digestAlgorithm=new Xl;signedAttrs;signedAttrsRaw;signatureAlgorithm=new Xm;signature=new ae;unsignedAttrs;constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer})],ni.prototype,"version",void 0);y([g({type:Yl})],ni.prototype,"sid",void 0);y([g({type:Xl})],ni.prototype,"digestAlgorithm",void 0);y([g({type:Ns,repeated:"set",context:0,implicit:!0,optional:!0,raw:!0})],ni.prototype,"signedAttrs",void 0);y([g({type:Xm})],ni.prototype,"signatureAlgorithm",void 0);y([g({type:ae})],ni.prototype,"signature",void 0);y([g({type:Ns,repeated:"set",context:1,implicit:!0,optional:!0})],ni.prototype,"unsignedAttrs",void 0);var ey=zA=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,zA.prototype)}};ey=zA=y([H({type:L.Set,itemType:ni})],ey);var UL=class extends ni{};UL=y([H({type:L.Sequence})],UL);var BL=class extends Nr{};BL=y([H({type:L.Choice})],BL);class Cx{acIssuer=new je;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}}y([g({type:je})],Cx.prototype,"acIssuer",void 0);y([g({type:E.Integer})],Cx.prototype,"acSerial",void 0);y([g({type:to,repeated:"sequence"})],Cx.prototype,"attrs",void 0);var GA,ty=GA=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,GA.prototype)}};ty=GA=y([H({type:L.Sequence,itemType:E.ObjectIdentifier})],ty);class ry{pathLenConstraint;permittedAttrs;excludedAttrs;permitUnSpecified=!0;constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer,optional:!0})],ry.prototype,"pathLenConstraint",void 0);y([g({type:ty,implicit:!0,context:0,optional:!0})],ry.prototype,"permittedAttrs",void 0);y([g({type:ty,implicit:!0,context:1,optional:!0})],ry.prototype,"excludedAttrs",void 0);y([g({type:E.Boolean,defaultValue:!0})],ry.prototype,"permitUnSpecified",void 0);class rs{issuer=new gr;serial=new ArrayBuffer(0);issuerUID=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:gr})],rs.prototype,"issuer",void 0);y([g({type:E.Integer,converter:bt})],rs.prototype,"serial",void 0);y([g({type:E.BitString,optional:!0})],rs.prototype,"issuerUID",void 0);var YA;(function(e){e[e.publicKey=0]="publicKey",e[e.publicKeyCert=1]="publicKeyCert",e[e.otherObjectTypes=2]="otherObjectTypes"})(YA||(YA={}));class ns{digestedObjectType=YA.publicKey;otherObjectTypeID;digestAlgorithm=new ie;objectDigest=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:E.Enumerated})],ns.prototype,"digestedObjectType",void 0);y([g({type:E.ObjectIdentifier,optional:!0})],ns.prototype,"otherObjectTypeID",void 0);y([g({type:ie})],ns.prototype,"digestAlgorithm",void 0);y([g({type:E.BitString})],ns.prototype,"objectDigest",void 0);class wp{issuerName;baseCertificateID;objectDigestInfo;constructor(e={}){Object.assign(this,e)}}y([g({type:gr,optional:!0})],wp.prototype,"issuerName",void 0);y([g({type:rs,context:0,implicit:!0,optional:!0})],wp.prototype,"baseCertificateID",void 0);y([g({type:ns,context:1,implicit:!0,optional:!0})],wp.prototype,"objectDigestInfo",void 0);var Zl=class{v1Form;v2Form;constructor(t={}){Object.assign(this,t)}};y([g({type:je,repeated:"sequence"})],Zl.prototype,"v1Form",void 0);y([g({type:wp,context:0,implicit:!0})],Zl.prototype,"v2Form",void 0);Zl=y([H({type:L.Choice})],Zl);class bp{notBeforeTime=new Date;notAfterTime=new Date;constructor(e={}){Object.assign(this,e)}}y([g({type:E.GeneralizedTime})],bp.prototype,"notBeforeTime",void 0);y([g({type:E.GeneralizedTime})],bp.prototype,"notAfterTime",void 0);class ed{baseCertificateID;entityName;objectDigestInfo;constructor(e={}){Object.assign(this,e)}}y([g({type:rs,implicit:!0,context:0,optional:!0})],ed.prototype,"baseCertificateID",void 0);y([g({type:gr,implicit:!0,context:1,optional:!0})],ed.prototype,"entityName",void 0);y([g({type:ns,implicit:!0,context:2,optional:!0})],ed.prototype,"objectDigestInfo",void 0);var XA;(function(e){e[e.v2=1]="v2"})(XA||(XA={}));class oi{version=XA.v2;holder=new ed;issuer=new Zl;signature=new ie;serialNumber=new ArrayBuffer(0);attrCertValidityPeriod=new bp;attributes=[];issuerUniqueID;extensions;constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer})],oi.prototype,"version",void 0);y([g({type:ed})],oi.prototype,"holder",void 0);y([g({type:Zl})],oi.prototype,"issuer",void 0);y([g({type:ie})],oi.prototype,"signature",void 0);y([g({type:E.Integer,converter:bt})],oi.prototype,"serialNumber",void 0);y([g({type:bp})],oi.prototype,"attrCertValidityPeriod",void 0);y([g({type:to,repeated:"sequence"})],oi.prototype,"attributes",void 0);y([g({type:E.BitString,optional:!0})],oi.prototype,"issuerUniqueID",void 0);y([g({type:_i,optional:!0})],oi.prototype,"extensions",void 0);class Ep{acinfo=new oi;signatureAlgorithm=new ie;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:oi})],Ep.prototype,"acinfo",void 0);y([g({type:ie})],Ep.prototype,"signatureAlgorithm",void 0);y([g({type:E.BitString})],Ep.prototype,"signatureValue",void 0);var ny;(function(e){e[e.unmarked=1]="unmarked",e[e.unclassified=2]="unclassified",e[e.restricted=4]="restricted",e[e.confidential=8]="confidential",e[e.secret=16]="secret",e[e.topSecret=32]="topSecret"})(ny||(ny={}));class oy extends ha{}class iy{type="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier,implicit:!0,context:0})],iy.prototype,"type",void 0);y([g({type:E.Any,implicit:!0,context:1})],iy.prototype,"value",void 0);class _x{policyId="";classList=new oy(ny.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier})],_x.prototype,"policyId",void 0);y([g({type:oy,defaultValue:new oy(ny.unclassified)})],_x.prototype,"classList",void 0);y([g({type:iy,repeated:"set"})],_x.prototype,"securityCategories",void 0);class sy{cotets;oid;string;constructor(e={}){Object.assign(this,e)}}y([g({type:ae})],sy.prototype,"cotets",void 0);y([g({type:E.ObjectIdentifier})],sy.prototype,"oid",void 0);y([g({type:E.Utf8String})],sy.prototype,"string",void 0);class ZA{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}}y([g({type:gr,implicit:!0,context:0,optional:!0})],ZA.prototype,"policyAuthority",void 0);y([g({type:sy,repeated:"sequence"})],ZA.prototype,"values",void 0);var $We=`${Cc}.4`,qWe=`${Cc}.6`,jWe=`${Cc}.10`,HWe=`${it}.55`,ay=`${yx}.10`,WWe=`${ay}.1`,KWe=`${ay}.2`,VWe=`${ay}.3`,QWe=`${ay}.4`,JWe=`${ay}.6`,eP="2.5.4",zWe=`${eP}.72`;var tP;class cy{targetCertificate=new rs;targetName;certDigestInfo;constructor(e={}){Object.assign(this,e)}}y([g({type:rs})],cy.prototype,"targetCertificate",void 0);y([g({type:je,optional:!0})],cy.prototype,"targetName",void 0);y([g({type:ns,optional:!0})],cy.prototype,"certDigestInfo",void 0);var Tp=class{targetName;targetGroup;targetCert;constructor(t={}){Object.assign(this,t)}};y([g({type:je,context:0,implicit:!0})],Tp.prototype,"targetName",void 0);y([g({type:je,context:1,implicit:!0})],Tp.prototype,"targetGroup",void 0);y([g({type:cy,context:2,implicit:!0})],Tp.prototype,"targetCert",void 0);Tp=y([H({type:L.Choice})],Tp);var kx=tP=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,tP.prototype)}};kx=tP=y([H({type:L.Sequence,itemType:Tp})],kx);var rP,ML=rP=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,rP.prototype)}};ML=rP=y([H({type:L.Sequence,itemType:kx})],ML);class nP{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}}y([g({type:gr,implicit:!0,context:0,optional:!0})],nP.prototype,"roleAuthority",void 0);y([g({type:je,implicit:!0,context:1})],nP.prototype,"roleName",void 0);class Ox{service=new je;ident=new je;authInfo;constructor(e={}){Object.assign(this,e)}}y([g({type:je})],Ox.prototype,"service",void 0);y([g({type:je})],Ox.prototype,"ident",void 0);y([g({type:ae,optional:!0})],Ox.prototype,"authInfo",void 0);var oP;class Dx{otherCertFormat="";otherCert=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier})],Dx.prototype,"otherCertFormat",void 0);y([g({type:E.Any})],Dx.prototype,"otherCert",void 0);var Dc=class{certificate;v2AttrCert;other;constructor(t={}){Object.assign(this,t)}};y([g({type:nn})],Dc.prototype,"certificate",void 0);y([g({type:Ep,context:2,implicit:!0})],Dc.prototype,"v2AttrCert",void 0);y([g({type:Dx,context:3,implicit:!0})],Dc.prototype,"other",void 0);Dc=y([H({type:L.Choice})],Dc);var Nc=oP=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,oP.prototype)}};Nc=oP=y([H({type:L.Set,itemType:Dc})],Nc);class Wo{contentType="";content=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier})],Wo.prototype,"contentType",void 0);y([g({type:E.Any,context:0})],Wo.prototype,"content",void 0);var td=class{single;any;constructor(t={}){Object.assign(this,t)}};y([g({type:ae})],td.prototype,"single",void 0);y([g({type:E.Any})],td.prototype,"any",void 0);td=y([H({type:L.Choice})],td);class Rp{eContentType="";eContent;constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier})],Rp.prototype,"eContentType",void 0);y([g({type:td,context:0,optional:!0})],Rp.prototype,"eContent",void 0);var ly=class{value;constructedValue;constructor(t={}){Object.assign(this,t)}};y([g({type:ae,context:0,implicit:!0,optional:!0})],ly.prototype,"value",void 0);y([g({type:ae,converter:LM,context:0,implicit:!0,optional:!0,repeated:"sequence"})],ly.prototype,"constructedValue",void 0);ly=y([H({type:L.Choice})],ly);class rd{contentType="";contentEncryptionAlgorithm=new Zm;encryptedContent;constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier})],rd.prototype,"contentType",void 0);y([g({type:Zm})],rd.prototype,"contentEncryptionAlgorithm",void 0);y([g({type:ly,optional:!0})],rd.prototype,"encryptedContent",void 0);class nd{keyAttrId="";keyAttr;constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier})],nd.prototype,"keyAttrId",void 0);y([g({type:E.Any,optional:!0})],nd.prototype,"keyAttr",void 0);var iP;class dy{subjectKeyIdentifier=new ri;date;other;constructor(e={}){Object.assign(this,e)}}y([g({type:ri})],dy.prototype,"subjectKeyIdentifier",void 0);y([g({type:E.GeneralizedTime,optional:!0})],dy.prototype,"date",void 0);y([g({type:nd,optional:!0})],dy.prototype,"other",void 0);var Ap=class{rKeyId;issuerAndSerialNumber;constructor(t={}){Object.assign(this,t)}};y([g({type:dy,context:0,implicit:!0,optional:!0})],Ap.prototype,"rKeyId",void 0);y([g({type:Ds,optional:!0})],Ap.prototype,"issuerAndSerialNumber",void 0);Ap=y([H({type:L.Choice})],Ap);class Fx{rid=new Ap;encryptedKey=new ae;constructor(e={}){Object.assign(this,e)}}y([g({type:Ap})],Fx.prototype,"rid",void 0);y([g({type:ae})],Fx.prototype,"encryptedKey",void 0);var Nx=iP=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,iP.prototype)}};Nx=iP=y([H({type:L.Sequence,itemType:Fx})],Nx);class Ux{algorithm=new ie;publicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:ie})],Ux.prototype,"algorithm",void 0);y([g({type:E.BitString})],Ux.prototype,"publicKey",void 0);var od=class{subjectKeyIdentifier;originatorKey;issuerAndSerialNumber;constructor(t={}){Object.assign(this,t)}};y([g({type:ri,context:0,implicit:!0,optional:!0})],od.prototype,"subjectKeyIdentifier",void 0);y([g({type:Ux,context:1,implicit:!0,optional:!0})],od.prototype,"originatorKey",void 0);y([g({type:Ds,optional:!0})],od.prototype,"issuerAndSerialNumber",void 0);od=y([H({type:L.Choice})],od);class Fc{version=Bn.v3;originator=new od;ukm;keyEncryptionAlgorithm=new Ho;recipientEncryptedKeys=new Nx;constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer})],Fc.prototype,"version",void 0);y([g({type:od,context:0})],Fc.prototype,"originator",void 0);y([g({type:ae,context:1,optional:!0})],Fc.prototype,"ukm",void 0);y([g({type:Ho})],Fc.prototype,"keyEncryptionAlgorithm",void 0);y([g({type:Nx})],Fc.prototype,"recipientEncryptedKeys",void 0);var Pp=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(t={}){Object.assign(this,t)}};y([g({type:ri,context:0,implicit:!0})],Pp.prototype,"subjectKeyIdentifier",void 0);y([g({type:Ds})],Pp.prototype,"issuerAndSerialNumber",void 0);Pp=y([H({type:L.Choice})],Pp);class id{version=Bn.v0;rid=new Pp;keyEncryptionAlgorithm=new Ho;encryptedKey=new ae;constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer})],id.prototype,"version",void 0);y([g({type:Pp})],id.prototype,"rid",void 0);y([g({type:Ho})],id.prototype,"keyEncryptionAlgorithm",void 0);y([g({type:ae})],id.prototype,"encryptedKey",void 0);class Ip{keyIdentifier=new ae;date;other;constructor(e={}){Object.assign(this,e)}}y([g({type:ae})],Ip.prototype,"keyIdentifier",void 0);y([g({type:E.GeneralizedTime,optional:!0})],Ip.prototype,"date",void 0);y([g({type:nd,optional:!0})],Ip.prototype,"other",void 0);class sd{version=Bn.v4;kekid=new Ip;keyEncryptionAlgorithm=new Ho;encryptedKey=new ae;constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer})],sd.prototype,"version",void 0);y([g({type:Ip})],sd.prototype,"kekid",void 0);y([g({type:Ho})],sd.prototype,"keyEncryptionAlgorithm",void 0);y([g({type:ae})],sd.prototype,"encryptedKey",void 0);class ad{version=Bn.v0;keyDerivationAlgorithm;keyEncryptionAlgorithm=new Ho;encryptedKey=new ae;constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer})],ad.prototype,"version",void 0);y([g({type:Ix,context:0,optional:!0})],ad.prototype,"keyDerivationAlgorithm",void 0);y([g({type:Ho})],ad.prototype,"keyEncryptionAlgorithm",void 0);y([g({type:ae})],ad.prototype,"encryptedKey",void 0);class Bx{oriType="";oriValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier})],Bx.prototype,"oriType",void 0);y([g({type:E.Any})],Bx.prototype,"oriValue",void 0);var Ea=class{ktri;kari;kekri;pwri;ori;constructor(t={}){Object.assign(this,t)}};y([g({type:id,optional:!0})],Ea.prototype,"ktri",void 0);y([g({type:Fc,context:1,implicit:!0,optional:!0})],Ea.prototype,"kari",void 0);y([g({type:sd,context:2,implicit:!0,optional:!0})],Ea.prototype,"kekri",void 0);y([g({type:ad,context:3,implicit:!0,optional:!0})],Ea.prototype,"pwri",void 0);y([g({type:Bx,context:4,implicit:!0,optional:!0})],Ea.prototype,"ori",void 0);Ea=y([H({type:L.Choice})],Ea);var sP,uy=sP=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,sP.prototype)}};uy=sP=y([H({type:L.Set,itemType:Ea})],uy);var aP,LL=`${yx}.16`,FKe=`${LL}.2`,UKe=`${LL}.4`;class py{otherRevInfoFormat="";otherRevInfo=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier})],py.prototype,"otherRevInfoFormat",void 0);y([g({type:E.Any})],py.prototype,"otherRevInfo",void 0);var Mx=class{other=new py;constructor(t={}){Object.assign(this,t)}};y([g({type:py,context:1,implicit:!0})],Mx.prototype,"other",void 0);Mx=y([H({type:L.Choice})],Mx);var Cp=aP=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,aP.prototype)}};Cp=aP=y([H({type:L.Set,itemType:Mx})],Cp);class fy{certs;crls;constructor(e={}){Object.assign(this,e)}}y([g({type:Nc,context:0,implicit:!0,optional:!0})],fy.prototype,"certs",void 0);y([g({type:Cp,context:1,implicit:!0,optional:!0})],fy.prototype,"crls",void 0);var cP,lP=cP=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,cP.prototype)}};lP=cP=y([H({type:L.Set,itemType:Ns})],lP);class _p{version=Bn.v0;originatorInfo;recipientInfos=new uy;encryptedContentInfo=new rd;unprotectedAttrs;constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer})],_p.prototype,"version",void 0);y([g({type:fy,context:0,implicit:!0,optional:!0})],_p.prototype,"originatorInfo",void 0);y([g({type:uy})],_p.prototype,"recipientInfos",void 0);y([g({type:rd})],_p.prototype,"encryptedContentInfo",void 0);y([g({type:lP,context:1,implicit:!0,optional:!0})],_p.prototype,"unprotectedAttrs",void 0);var $L="1.2.840.113549.1.7.1",Lx="1.2.840.113549.1.7.2";var dP,$x=dP=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,dP.prototype)}};$x=dP=y([H({type:L.Set,itemType:Xl})],$x);class os{version=Bn.v0;digestAlgorithms=new $x;encapContentInfo=new Rp;certificates;crls;signerInfos=new ey;constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer})],os.prototype,"version",void 0);y([g({type:$x})],os.prototype,"digestAlgorithms",void 0);y([g({type:Rp})],os.prototype,"encapContentInfo",void 0);y([g({type:Nc,context:0,implicit:!0,optional:!0})],os.prototype,"certificates",void 0);y([g({type:Cp,context:1,implicit:!0,optional:!0})],os.prototype,"crls",void 0);y([g({type:ey})],os.prototype,"signerInfos",void 0);var Ta="1.2.840.10045.2.1";var my="1.2.840.10045.4.1",qx="1.2.840.10045.4.3.1",yy="1.2.840.10045.4.3.2",hy="1.2.840.10045.4.3.3",gy="1.2.840.10045.4.3.4";var Sy="1.2.840.10045.3.1.7";var vy="1.3.132.0.34";var uP="1.3.132.0.35";function xy(e){return new ie({algorithm:e})}var jL=xy(my),IVe=xy(qx),HL=xy(yy),WL=xy(hy),KL=xy(gy);var wy=class{fieldType;parameters;constructor(t={}){Object.assign(this,t)}};y([g({type:E.ObjectIdentifier})],wy.prototype,"fieldType",void 0);y([g({type:E.Any})],wy.prototype,"parameters",void 0);wy=y([H({type:L.Sequence})],wy);class VL extends ae{}var kp=class{a;b;seed;constructor(t={}){Object.assign(this,t)}};y([g({type:E.OctetString})],kp.prototype,"a",void 0);y([g({type:E.OctetString})],kp.prototype,"b",void 0);y([g({type:E.BitString,optional:!0})],kp.prototype,"seed",void 0);kp=y([H({type:L.Sequence})],kp);var pP;(function(e){e[e.ecpVer1=1]="ecpVer1"})(pP||(pP={}));var Fs=class{version=pP.ecpVer1;fieldID;curve;base;order;cofactor;constructor(t={}){Object.assign(this,t)}};y([g({type:E.Integer})],Fs.prototype,"version",void 0);y([g({type:wy})],Fs.prototype,"fieldID",void 0);y([g({type:kp})],Fs.prototype,"curve",void 0);y([g({type:VL})],Fs.prototype,"base",void 0);y([g({type:E.Integer,converter:bt})],Fs.prototype,"order",void 0);y([g({type:E.Integer,optional:!0})],Fs.prototype,"cofactor",void 0);Fs=y([H({type:L.Sequence})],Fs);var Oi=class{namedCurve;implicitCurve;specifiedCurve;constructor(t={}){Object.assign(this,t)}};y([g({type:E.ObjectIdentifier})],Oi.prototype,"namedCurve",void 0);y([g({type:E.Null})],Oi.prototype,"implicitCurve",void 0);y([g({type:Fs})],Oi.prototype,"specifiedCurve",void 0);Oi=y([H({type:L.Choice})],Oi);class by{version=1;privateKey=new ae;parameters;publicKey;constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer})],by.prototype,"version",void 0);y([g({type:ae})],by.prototype,"privateKey",void 0);y([g({type:Oi,context:0,optional:!0})],by.prototype,"parameters",void 0);y([g({type:E.BitString,context:1,optional:!0})],by.prototype,"publicKey",void 0);class Uc{r=new ArrayBuffer(0);s=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer,converter:bt})],Uc.prototype,"r",void 0);y([g({type:E.Integer,converter:bt})],Uc.prototype,"s",void 0);var Di="1.2.840.113549.1.1.1",QL="1.2.840.113549.1.1.7",JL="1.2.840.113549.1.1.9",Bc="1.2.840.113549.1.1.10",zL="1.2.840.113549.1.1.2",GL="1.2.840.113549.1.1.4",Op="1.2.840.113549.1.1.5",YL="1.2.840.113549.1.1.14";var jx="1.2.840.113549.1.1.11",Dp="1.2.840.113549.1.1.12",Np="1.2.840.113549.1.1.13",fP="1.2.840.113549.1.1.15",mP="1.2.840.113549.1.1.16",cd="1.3.14.3.2.26",Hx="2.16.840.1.101.3.4.2.4",ld="2.16.840.1.101.3.4.2.1",dd="2.16.840.1.101.3.4.2.2",ud="2.16.840.1.101.3.4.2.3",XL="2.16.840.1.101.3.4.2.5",ZL="2.16.840.1.101.3.4.2.6",e1="1.2.840.113549.2.2",t1="1.2.840.113549.2.5",Mc="1.2.840.113549.1.1.8";function An(e){return new ie({algorithm:e,parameters:null})}var XVe=An(e1),ZVe=An(t1),Ra=An(cd),e5e=An(Hx),t5e=An(ld),r5e=An(dd),n5e=An(ud),o5e=An(XL),i5e=An(ZL),Wx=new ie({algorithm:Mc,parameters:ne.serialize(Ra)}),yP=new ie({algorithm:JL,parameters:ne.serialize(cp.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))}),s5e=An(Di),a5e=An(zL),c5e=An(GL),l5e=An(Op),d5e=An(fP),u5e=An(mP),p5e=An(Dp),f5e=An(Np),m5e=An(fP),y5e=An(mP);class Ey{hashAlgorithm=new ie(Ra);maskGenAlgorithm=new ie({algorithm:Mc,parameters:ne.serialize(Ra)});pSourceAlgorithm=new ie(yP);constructor(e={}){Object.assign(this,e)}}y([g({type:ie,context:0,defaultValue:Ra})],Ey.prototype,"hashAlgorithm",void 0);y([g({type:ie,context:1,defaultValue:Wx})],Ey.prototype,"maskGenAlgorithm",void 0);y([g({type:ie,context:2,defaultValue:yP})],Ey.prototype,"pSourceAlgorithm",void 0);var b5e=new ie({algorithm:QL,parameters:ne.serialize(new Ey)});class Aa{hashAlgorithm=new ie(Ra);maskGenAlgorithm=new ie({algorithm:Mc,parameters:ne.serialize(Ra)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}}y([g({type:ie,context:0,defaultValue:Ra})],Aa.prototype,"hashAlgorithm",void 0);y([g({type:ie,context:1,defaultValue:Wx})],Aa.prototype,"maskGenAlgorithm",void 0);y([g({type:E.Integer,context:2,defaultValue:20})],Aa.prototype,"saltLength",void 0);y([g({type:E.Integer,context:3,defaultValue:1})],Aa.prototype,"trailerField",void 0);var C5e=new ie({algorithm:Bc,parameters:ne.serialize(new Aa)});class Fp{digestAlgorithm=new ie;digest=new ae;constructor(e={}){Object.assign(this,e)}}y([g({type:ie})],Fp.prototype,"digestAlgorithm",void 0);y([g({type:ae})],Fp.prototype,"digest",void 0);var hP;class Ty{prime=new ArrayBuffer(0);exponent=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer,converter:bt})],Ty.prototype,"prime",void 0);y([g({type:E.Integer,converter:bt})],Ty.prototype,"exponent",void 0);y([g({type:E.Integer,converter:bt})],Ty.prototype,"coefficient",void 0);var Kx=hP=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,hP.prototype)}};Kx=hP=y([H({type:L.Sequence,itemType:Ty})],Kx);class is{version=0;modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);privateExponent=new ArrayBuffer(0);prime1=new ArrayBuffer(0);prime2=new ArrayBuffer(0);exponent1=new ArrayBuffer(0);exponent2=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);otherPrimeInfos;constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer})],is.prototype,"version",void 0);y([g({type:E.Integer,converter:bt})],is.prototype,"modulus",void 0);y([g({type:E.Integer,converter:bt})],is.prototype,"publicExponent",void 0);y([g({type:E.Integer,converter:bt})],is.prototype,"privateExponent",void 0);y([g({type:E.Integer,converter:bt})],is.prototype,"prime1",void 0);y([g({type:E.Integer,converter:bt})],is.prototype,"prime2",void 0);y([g({type:E.Integer,converter:bt})],is.prototype,"exponent1",void 0);y([g({type:E.Integer,converter:bt})],is.prototype,"exponent2",void 0);y([g({type:E.Integer,converter:bt})],is.prototype,"coefficient",void 0);y([g({type:Kx,optional:!0})],is.prototype,"otherPrimeInfos",void 0);class pd{modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer,converter:bt})],pd.prototype,"modulus",void 0);y([g({type:E.Integer,converter:bt})],pd.prototype,"publicExponent",void 0);var gP;(function(e){e[e.Transient=0]="Transient",e[e.Singleton=1]="Singleton",e[e.ResolutionScoped=2]="ResolutionScoped",e[e.ContainerScoped=3]="ContainerScoped"})(gP||(gP={}));var Qn=gP;var E1=zr(b1(),1),{__extends:Ry,__assign:iQe,__rest:sQe,__decorate:aQe,__param:cQe,__metadata:lQe,__awaiter:T1,__generator:R1,__exportStar:dQe,__createBinding:uQe,__values:Ay,__read:Bp,__spread:Us,__spreadArrays:pQe,__await:fQe,__asyncGenerator:mQe,__asyncDelegator:yQe,__asyncValues:hQe,__makeTemplateObject:gQe,__importStar:SQe,__importDefault:vQe,__classPrivateFieldGet:xQe,__classPrivateFieldSet:wQe}=E1.default;var LY="injectionTokens";function vP(e){var t=Reflect.getMetadata("design:paramtypes",e)||[],r=Reflect.getOwnMetadata(LY,e)||{};return Object.keys(r).forEach(function(n){t[+n]=r[n]}),t}function Py(e){return!!e.useClass}function Mp(e){return!!e.useFactory}var Jx=function(){function e(t){this.wrap=t,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}return e.prototype.createProxy=function(t){var r=this,n={},o=!1,i,s=function(){if(!o)i=t(r.wrap()),o=!0;return i};return new Proxy(n,this.createHandler(s))},e.prototype.createHandler=function(t){var r={},n=function(o){r[o]=function(){var i=[];for(var s=0;s<arguments.length;s++)i[s]=arguments[s];i[0]=t();var a=Reflect[o];return a.apply(void 0,Us(i))}};return this.reflectMethods.forEach(n),r},e}();function Lc(e){return typeof e==="string"||typeof e==="symbol"}function xP(e){return typeof e==="object"&&"token"in e&&"multiple"in e}function zx(e){return typeof e==="object"&&"token"in e&&"transform"in e}function A1(e){return typeof e==="function"||e instanceof Jx}function fd(e){return!!e.useToken}function md(e){return e.useValue!=null}function P1(e){return Py(e)||md(e)||fd(e)||Mp(e)}var $Y=function(){function e(){this._registryMap=new Map}return e.prototype.entries=function(){return this._registryMap.entries()},e.prototype.getAll=function(t){return this.ensure(t),this._registryMap.get(t)},e.prototype.get=function(t){this.ensure(t);var r=this._registryMap.get(t);return r[r.length-1]||null},e.prototype.set=function(t,r){this.ensure(t),this._registryMap.get(t).push(r)},e.prototype.setAll=function(t,r){this._registryMap.set(t,r)},e.prototype.has=function(t){return this.ensure(t),this._registryMap.get(t).length>0},e.prototype.clear=function(){this._registryMap.clear()},e.prototype.ensure=function(t){if(!this._registryMap.has(t))this._registryMap.set(t,[])},e}(),Iy=$Y;var qY=function(e){Ry(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(Iy),I1=qY;var jY=function(){function e(){this.scopedResolutions=new Map}return e}(),Cy=jY;function HY(e,t){if(e===null)return"at position #"+t;var r=e.split(",")[t].trim();return'"'+r+'" at position #'+t}function WY(e,t,r){if(r===void 0)r=" ";return Us([e],t.message.split(`
|
|
191
|
+
`).map(function(n){return r+n})).join(`
|
|
192
|
+
`)}function wP(e,t,r){var n=Bp(e.toString().match(/constructor\(([\w, ]+)\)/)||[],2),o=n[1],i=o===void 0?null:o,s=HY(i,t);return WY("Cannot inject the dependency "+s+' of "'+e.name+'" constructor. Reason:',r)}function C1(e){if(typeof e.dispose!=="function")return!1;var t=e.dispose;if(t.length>0)return!1;return!0}var KY=function(e){Ry(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(Iy);var VY=function(e){Ry(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(Iy);var QY=function(){function e(){this.preResolution=new KY,this.postResolution=new VY}return e}(),_1=QY;var bP=new Map,JY=function(){function e(t){this.parent=t,this._registry=new I1,this.interceptors=new _1,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(t,r,n){if(n===void 0)n={lifecycle:Qn.Transient};this.ensureNotDisposed();var o;if(!P1(r))o={useClass:r};else o=r;if(fd(o)){var i=[t],s=o;while(s!=null){var a=s.useToken;if(i.includes(a))throw Error("Token registration cycle detected! "+Us(i,[a]).join(" -> "));i.push(a);var c=this._registry.get(a);if(c&&fd(c.provider))s=c.provider;else s=null}}if(n.lifecycle===Qn.Singleton||n.lifecycle==Qn.ContainerScoped||n.lifecycle==Qn.ResolutionScoped){if(md(o)||Mp(o))throw Error('Cannot use lifecycle "'+Qn[n.lifecycle]+'" with ValueProviders or FactoryProviders')}return this._registry.set(t,{provider:o,options:n}),this},e.prototype.registerType=function(t,r){if(this.ensureNotDisposed(),Lc(r))return this.register(t,{useToken:r});return this.register(t,{useClass:r})},e.prototype.registerInstance=function(t,r){return this.ensureNotDisposed(),this.register(t,{useValue:r})},e.prototype.registerSingleton=function(t,r){if(this.ensureNotDisposed(),Lc(t)){if(Lc(r))return this.register(t,{useToken:r},{lifecycle:Qn.Singleton});else if(r)return this.register(t,{useClass:r},{lifecycle:Qn.Singleton});throw Error('Cannot register a type name as a singleton without a "to" token')}var n=t;if(r&&!Lc(r))n=r;return this.register(t,{useClass:n},{lifecycle:Qn.Singleton})},e.prototype.resolve=function(t,r,n){if(r===void 0)r=new Cy;if(n===void 0)n=!1;this.ensureNotDisposed();var o=this.getRegistration(t);if(!o&&Lc(t)){if(n)return;throw Error('Attempted to resolve unregistered dependency token: "'+t.toString()+'"')}if(this.executePreResolutionInterceptor(t,"Single"),o){var i=this.resolveRegistration(o,r);return this.executePostResolutionInterceptor(t,i,"Single"),i}if(A1(t)){var i=this.construct(t,r);return this.executePostResolutionInterceptor(t,i,"Single"),i}throw Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")},e.prototype.executePreResolutionInterceptor=function(t,r){var n,o;if(this.interceptors.preResolution.has(t)){var i=[];try{for(var s=Ay(this.interceptors.preResolution.getAll(t)),a=s.next();!a.done;a=s.next()){var c=a.value;if(c.options.frequency!="Once")i.push(c);c.callback(t,r)}}catch(l){n={error:l}}finally{try{if(a&&!a.done&&(o=s.return))o.call(s)}finally{if(n)throw n.error}}this.interceptors.preResolution.setAll(t,i)}},e.prototype.executePostResolutionInterceptor=function(t,r,n){var o,i;if(this.interceptors.postResolution.has(t)){var s=[];try{for(var a=Ay(this.interceptors.postResolution.getAll(t)),c=a.next();!c.done;c=a.next()){var l=c.value;if(l.options.frequency!="Once")s.push(l);l.callback(t,r,n)}}catch(d){o={error:d}}finally{try{if(c&&!c.done&&(i=a.return))i.call(a)}finally{if(o)throw o.error}}this.interceptors.postResolution.setAll(t,s)}},e.prototype.resolveRegistration=function(t,r){if(this.ensureNotDisposed(),t.options.lifecycle===Qn.ResolutionScoped&&r.scopedResolutions.has(t))return r.scopedResolutions.get(t);var n=t.options.lifecycle===Qn.Singleton,o=t.options.lifecycle===Qn.ContainerScoped,i=n||o,s;if(md(t.provider))s=t.provider.useValue;else if(fd(t.provider))s=i?t.instance||(t.instance=this.resolve(t.provider.useToken,r)):this.resolve(t.provider.useToken,r);else if(Py(t.provider))s=i?t.instance||(t.instance=this.construct(t.provider.useClass,r)):this.construct(t.provider.useClass,r);else if(Mp(t.provider))s=t.provider.useFactory(this);else s=this.construct(t.provider,r);if(t.options.lifecycle===Qn.ResolutionScoped)r.scopedResolutions.set(t,s);return s},e.prototype.resolveAll=function(t,r,n){var o=this;if(r===void 0)r=new Cy;if(n===void 0)n=!1;this.ensureNotDisposed();var i=this.getAllRegistrations(t);if(!i&&Lc(t)){if(n)return[];throw Error('Attempted to resolve unregistered dependency token: "'+t.toString()+'"')}if(this.executePreResolutionInterceptor(t,"All"),i){var s=i.map(function(c){return o.resolveRegistration(c,r)});return this.executePostResolutionInterceptor(t,s,"All"),s}var a=[this.construct(t,r)];return this.executePostResolutionInterceptor(t,a,"All"),a},e.prototype.isRegistered=function(t,r){if(r===void 0)r=!1;return this.ensureNotDisposed(),this._registry.has(t)||r&&(this.parent||!1)&&this.parent.isRegistered(t,!0)},e.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},e.prototype.clearInstances=function(){var t,r;this.ensureNotDisposed();try{for(var n=Ay(this._registry.entries()),o=n.next();!o.done;o=n.next()){var i=Bp(o.value,2),s=i[0],a=i[1];this._registry.setAll(s,a.filter(function(c){return!md(c.provider)}).map(function(c){return c.instance=void 0,c}))}}catch(c){t={error:c}}finally{try{if(o&&!o.done&&(r=n.return))r.call(n)}finally{if(t)throw t.error}}},e.prototype.createChildContainer=function(){var t,r;this.ensureNotDisposed();var n=new e(this);try{for(var o=Ay(this._registry.entries()),i=o.next();!i.done;i=o.next()){var s=Bp(i.value,2),a=s[0],c=s[1];if(c.some(function(l){var d=l.options;return d.lifecycle===Qn.ContainerScoped}))n._registry.setAll(a,c.map(function(l){if(l.options.lifecycle===Qn.ContainerScoped)return{provider:l.provider,options:l.options};return l}))}}catch(l){t={error:l}}finally{try{if(i&&!i.done&&(r=o.return))r.call(o)}finally{if(t)throw t.error}}return n},e.prototype.beforeResolution=function(t,r,n){if(n===void 0)n={frequency:"Always"};this.interceptors.preResolution.set(t,{callback:r,options:n})},e.prototype.afterResolution=function(t,r,n){if(n===void 0)n={frequency:"Always"};this.interceptors.postResolution.set(t,{callback:r,options:n})},e.prototype.dispose=function(){return T1(this,void 0,void 0,function(){var t;return R1(this,function(r){switch(r.label){case 0:return this.disposed=!0,t=[],this.disposables.forEach(function(n){var o=n.dispose();if(o)t.push(o)}),[4,Promise.all(t)];case 1:return r.sent(),[2]}})})},e.prototype.getRegistration=function(t){if(this.isRegistered(t))return this._registry.get(t);if(this.parent)return this.parent.getRegistration(t);return null},e.prototype.getAllRegistrations=function(t){if(this.isRegistered(t))return this._registry.getAll(t);if(this.parent)return this.parent.getAllRegistrations(t);return null},e.prototype.construct=function(t,r){var n=this;if(t instanceof Jx)return t.createProxy(function(i){return n.resolve(i,r)});var o=function(){var i=bP.get(t);if(!i||i.length===0)if(t.length===0)return new t;else throw Error('TypeInfo not known for "'+t.name+'"');var s=i.map(n.resolveParams(r,t));return new(t.bind.apply(t,Us([void 0],s)))}();if(C1(o))this.disposables.add(o);return o},e.prototype.resolveParams=function(t,r){var n=this;return function(o,i){var s,a,c;try{if(xP(o))if(zx(o))return o.multiple?(s=n.resolve(o.transform)).transform.apply(s,Us([n.resolveAll(o.token,new Cy,o.isOptional)],o.transformArgs)):(a=n.resolve(o.transform)).transform.apply(a,Us([n.resolve(o.token,t,o.isOptional)],o.transformArgs));else return o.multiple?n.resolveAll(o.token,new Cy,o.isOptional):n.resolve(o.token,t,o.isOptional);else if(zx(o))return(c=n.resolve(o.transform,t)).transform.apply(c,Us([n.resolve(o.token,t)],o.transformArgs));return n.resolve(o,t)}catch(l){throw Error(wP(r,i,l))}}},e.prototype.ensureNotDisposed=function(){if(this.disposed)throw Error("This container has been disposed, you cannot interact with a disposed container")},e}(),sr=new JY;function zY(e){return function(t){if(bP.set(t,vP(t)),e&&e.token)if(!Array.isArray(e.token))sr.register(e.token,t);else e.token.forEach(function(r){sr.register(r,t)})}}var $c=zY;if(typeof Reflect>"u"||!Reflect.getMetadata)throw Error(`tsyringe requires a reflect polyfill. Please add 'import "reflect-metadata"' to the top of your entry point.`);var TP;class Lp{attrId="";attrValues=[];constructor(e={}){Object.assign(e)}}y([g({type:E.ObjectIdentifier})],Lp.prototype,"attrId",void 0);y([g({type:E.Any,repeated:"set"})],Lp.prototype,"attrValues",void 0);var k1=TP=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,TP.prototype)}};k1=TP=y([H({type:L.Sequence,itemType:Lp})],k1);var RP,O1=RP=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,RP.prototype)}};O1=RP=y([H({type:L.Sequence,itemType:Wo})],O1);var yd="1.2.840.113549.1.12.10.1";var IJe=`${yd}.1`,CJe=`${yd}.2`,_Je=`${yd}.3`,kJe=`${yd}.4`,OJe=`${yd}.5`,DJe=`${yd}.6`,Gx="1.2.840.113549.1.9";class AP{certId="";certValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier})],AP.prototype,"certId",void 0);y([g({type:E.Any,context:0})],AP.prototype,"certValue",void 0);var D1=`${Gx}.22`,MJe=`${D1}.1`,LJe=`${D1}.2`;class PP{crlId="";crltValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier})],PP.prototype,"crlId",void 0);y([g({type:E.Any,context:0})],PP.prototype,"crltValue",void 0);var GY=`${Gx}.23`,WJe=`${GY}.1`;class IP extends ae{}class hd{encryptionAlgorithm=new ie;encryptedData=new IP;constructor(e={}){Object.assign(this,e)}}y([g({type:ie})],hd.prototype,"encryptionAlgorithm",void 0);y([g({type:IP})],hd.prototype,"encryptedData",void 0);var CP,_P;(function(e){e[e.v1=0]="v1"})(_P||(_P={}));class OP extends ae{}var kP=CP=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,CP.prototype)}};kP=CP=y([H({type:L.Sequence,itemType:to})],kP);class gd{version=_P.v1;privateKeyAlgorithm=new ie;privateKey=new OP;attributes;constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer})],gd.prototype,"version",void 0);y([g({type:ie})],gd.prototype,"privateKeyAlgorithm",void 0);y([g({type:OP})],gd.prototype,"privateKey",void 0);y([g({type:kP,implicit:!0,context:0,optional:!0})],gd.prototype,"attributes",void 0);var N1=class extends gd{};N1=y([H({type:L.Sequence})],N1);var F1=class extends hd{};F1=y([H({type:L.Sequence})],F1);class DP{secretTypeId="";secretValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier})],DP.prototype,"secretTypeId",void 0);y([g({type:E.Any,context:0})],DP.prototype,"secretValue",void 0);class Sd{mac=new Fp;macSalt=new ae;iterations=1;constructor(e={}){Object.assign(this,e)}}y([g({type:Fp})],Sd.prototype,"mac",void 0);y([g({type:ae})],Sd.prototype,"macSalt",void 0);y([g({type:E.Integer,defaultValue:1})],Sd.prototype,"iterations",void 0);class $p{version=3;authSafe=new Wo;macData=new Sd;constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer})],$p.prototype,"version",void 0);y([g({type:Wo})],$p.prototype,"authSafe",void 0);y([g({type:Sd,optional:!0})],$p.prototype,"macData",void 0);var NP;class _y{bagId="";bagValue=new ArrayBuffer(0);bagAttributes;constructor(e={}){Object.assign(this,e)}}y([g({type:E.ObjectIdentifier})],_y.prototype,"bagId",void 0);y([g({type:E.Any,context:0})],_y.prototype,"bagValue",void 0);y([g({type:Lp,repeated:"set",optional:!0})],_y.prototype,"bagAttributes",void 0);var U1=NP=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,NP.prototype)}};U1=NP=y([H({type:L.Sequence,itemType:_y})],U1);var FP,UP,BP,Vr="1.2.840.113549.1.9",j8e=`${Vr}.0`,G1=`${Vr}.24`,Oy=`${Vr}.25`,Y1=`${Vr}.26`,X1=`${Vr}.27`,H8e=`${G1}.1`,W8e=`${G1}.2`,K8e=`${Vr}.1`,V8e=`${Vr}.2`,Q8e=`${Vr}.3`,J8e=`${Vr}.4`,z8e=`${Vr}.5`,G8e=`${Vr}.6`,KP=`${Vr}.7`,Y8e=`${Vr}.8`,X8e=`${Vr}.9`,Z8e=`${Vr}.13`,Dy=`${Vr}.14`,eze=`${Vr}.15`,tze=`${Vr}.20`,rze=`${Vr}.21`;var nze=`${Oy}.1`,oze=`${Oy}.2`,ize=`${Oy}.3`,sze=`${Oy}.4`,aze=`${Oy}.5`,Ny="1.3.6.1.5.5.7.9",cze=`${Ny}.1`,lze=`${Ny}.2`,dze=`${Ny}.3`,uze=`${Ny}.4`,pze=`${Ny}.5`,fze=`${Y1}.1`,mze=`${Y1}.2`,yze=`${X1}.1`,hze=`${X1}.2`,gze=`${Vr}.16`,Sze=`${Vr}.22`,vze=`${Vr}.23`,xze=`${eP}.65`,Yx=class extends hn{ia5String;constructor(t={}){super(t)}toString(){return{}.toString(),this.ia5String||super.toString()}};y([g({type:E.IA5String})],Yx.prototype,"ia5String",void 0);Yx=y([H({type:L.Choice})],Yx);var B1=class extends Wo{};B1=y([H({type:L.Sequence})],B1);var M1=class extends $p{};M1=y([H({type:L.Sequence})],M1);var L1=class extends hd{};L1=y([H({type:L.Sequence})],L1);var MP=class{value;constructor(t=""){this.value=t}toString(){return this.value}};y([g({type:E.IA5String})],MP.prototype,"value",void 0);MP=y([H({type:L.Choice})],MP);var $1=class extends Yx{};$1=y([H({type:L.Choice})],$1);var q1=class extends hn{};q1=y([H({type:L.Choice})],q1);var LP=class{value;constructor(t=new Date){this.value=t}};y([g({type:E.GeneralizedTime})],LP.prototype,"value",void 0);LP=y([H({type:L.Choice})],LP);var j1=class extends hn{};j1=y([H({type:L.Choice})],j1);var $P=class{value;constructor(t="M"){this.value=t}toString(){return this.value}};y([g({type:E.PrintableString})],$P.prototype,"value",void 0);$P=y([H({type:L.Choice})],$P);var Xx=class{value;constructor(t=""){this.value=t}toString(){return this.value}};y([g({type:E.PrintableString})],Xx.prototype,"value",void 0);Xx=y([H({type:L.Choice})],Xx);var H1=class extends Xx{};H1=y([H({type:L.Choice})],H1);var W1=class extends hn{};W1=y([H({type:L.Choice})],W1);var qP=class{value;constructor(t=""){this.value=t}toString(){return this.value}};y([g({type:E.ObjectIdentifier})],qP.prototype,"value",void 0);qP=y([H({type:L.Choice})],qP);var K1=class extends Nr{};K1=y([H({type:L.Choice})],K1);var jP=class{value;constructor(t=0){this.value=t}toString(){return this.value.toString()}};y([g({type:E.Integer})],jP.prototype,"value",void 0);jP=y([H({type:L.Choice})],jP);var V1=class extends ni{};V1=y([H({type:L.Sequence})],V1);var ky=class extends hn{};ky=y([H({type:L.Choice})],ky);var Q1=FP=class extends _i{constructor(t){super(t);Object.setPrototypeOf(this,FP.prototype)}};Q1=FP=y([H({type:L.Sequence})],Q1);var J1=UP=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,UP.prototype)}};J1=UP=y([H({type:L.Set,itemType:Ns})],J1);var HP=class{value;constructor(t=""){this.value=t}toString(){return this.value}};y([g({type:E.BmpString})],HP.prototype,"value",void 0);HP=y([H({type:L.Choice})],HP);var WP=class extends ie{};WP=y([H({type:L.Sequence})],WP);var z1=BP=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,BP.prototype)}};z1=BP=y([H({type:L.Sequence,itemType:WP})],z1);var VP,Fy=VP=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,VP.prototype)}};Fy=VP=y([H({type:L.Sequence,itemType:to})],Fy);class Pa{version=0;subject=new ir;subjectPKInfo=new bo;attributes=new Fy;constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer})],Pa.prototype,"version",void 0);y([g({type:ir})],Pa.prototype,"subject",void 0);y([g({type:bo})],Pa.prototype,"subjectPKInfo",void 0);y([g({type:Fy,implicit:!0,context:0,optional:!0})],Pa.prototype,"attributes",void 0);class vd{certificationRequestInfo=new Pa;certificationRequestInfoRaw;signatureAlgorithm=new ie;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}y([g({type:Pa,raw:!0})],vd.prototype,"certificationRequestInfo",void 0);y([g({type:ie})],vd.prototype,"signatureAlgorithm",void 0);y([g({type:E.BitString})],vd.prototype,"signature",void 0);/*!
|
|
193
|
+
* MIT License
|
|
194
|
+
*
|
|
195
|
+
* Copyright (c) Peculiar Ventures. All rights reserved.
|
|
196
|
+
*
|
|
197
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
198
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
199
|
+
* in the Software without restriction, including without limitation the rights
|
|
200
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
201
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
202
|
+
* furnished to do so, subject to the following conditions:
|
|
203
|
+
*
|
|
204
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
205
|
+
* copies or substantial portions of the Software.
|
|
206
|
+
*
|
|
207
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
208
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
209
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
210
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
211
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
212
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
213
|
+
* SOFTWARE.
|
|
214
|
+
*
|
|
215
|
+
*/var uh="crypto.algorithm";class B${getAlgorithms(){return sr.resolveAll(uh)}toAsnAlgorithm(e){({...e});for(let t of this.getAlgorithms()){let r=t.toAsnAlgorithm(e);if(r)return r}if(/^[0-9.]+$/.test(e.name)){let t=new ie({algorithm:e.name});if("parameters"in e){let r=e;t.parameters=r.parameters}return t}throw Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(let r of this.getAlgorithms()){let n=r.toWebAlgorithm(e);if(n)return n}return{name:e.algorithm,parameters:e.parameters}}}var xd="crypto.algorithmProvider";sr.registerSingleton(xd,B$);var rw,Vo="1.3.36.3.3.2.8.1.1",Z1=`${Vo}.1`,e$=`${Vo}.2`,t$=`${Vo}.3`,r$=`${Vo}.4`,n$=`${Vo}.5`,o$=`${Vo}.6`,i$=`${Vo}.7`,s$=`${Vo}.8`,a$=`${Vo}.9`,c$=`${Vo}.10`,l$=`${Vo}.11`,d$=`${Vo}.12`,u$=`${Vo}.13`,p$=`${Vo}.14`,f$="brainpoolP160r1",m$="brainpoolP160t1",y$="brainpoolP192r1",h$="brainpoolP192t1",g$="brainpoolP224r1",S$="brainpoolP224t1",v$="brainpoolP256r1",x$="brainpoolP256t1",w$="brainpoolP320r1",b$="brainpoolP320t1",E$="brainpoolP384r1",T$="brainpoolP384t1",R$="brainpoolP512r1",A$="brainpoolP512t1",Fr="ECDSA",lh=rw=class{toAsnAlgorithm(t){switch(t.name.toLowerCase()){case Fr.toLowerCase():if("hash"in t)switch((typeof t.hash==="string"?t.hash:t.hash.name).toLowerCase()){case"sha-1":return jL;case"sha-256":return HL;case"sha-384":return WL;case"sha-512":return KL}else if("namedCurve"in t){let r="";switch(t.namedCurve){case"P-256":r=Sy;break;case"K-256":r=rw.SECP256K1;break;case"P-384":r=vy;break;case"P-521":r=uP;break;case f$:r=Z1;break;case m$:r=e$;break;case y$:r=t$;break;case h$:r=r$;break;case g$:r=n$;break;case S$:r=o$;break;case v$:r=i$;break;case x$:r=s$;break;case w$:r=a$;break;case b$:r=c$;break;case E$:r=l$;break;case T$:r=d$;break;case R$:r=u$;break;case A$:r=p$;break}if(r)return new ie({algorithm:Ta,parameters:ne.serialize(new Oi({namedCurve:r}))})}}return null}toWebAlgorithm(t){switch(t.algorithm){case my:return{name:Fr,hash:{name:"SHA-1"}};case yy:return{name:Fr,hash:{name:"SHA-256"}};case hy:return{name:Fr,hash:{name:"SHA-384"}};case gy:return{name:Fr,hash:{name:"SHA-512"}};case Ta:{if(!t.parameters)throw TypeError("Cannot get required parameters from EC algorithm");switch(ne.parse(t.parameters,Oi).namedCurve){case Sy:return{name:Fr,namedCurve:"P-256"};case rw.SECP256K1:return{name:Fr,namedCurve:"K-256"};case vy:return{name:Fr,namedCurve:"P-384"};case uP:return{name:Fr,namedCurve:"P-521"};case Z1:return{name:Fr,namedCurve:f$};case e$:return{name:Fr,namedCurve:m$};case t$:return{name:Fr,namedCurve:y$};case r$:return{name:Fr,namedCurve:h$};case n$:return{name:Fr,namedCurve:g$};case o$:return{name:Fr,namedCurve:S$};case i$:return{name:Fr,namedCurve:v$};case s$:return{name:Fr,namedCurve:x$};case a$:return{name:Fr,namedCurve:w$};case c$:return{name:Fr,namedCurve:b$};case l$:return{name:Fr,namedCurve:E$};case d$:return{name:Fr,namedCurve:T$};case u$:return{name:Fr,namedCurve:R$};case p$:return{name:Fr,namedCurve:A$}}}}return null}};lh.SECP256K1="1.3.132.0.10";lh=rw=y([$c()],lh);sr.registerSingleton(uh,lh);var M$=Symbol("name"),L$=Symbol("value");class Ct{constructor(e,t={},r=""){this[M$]=e,this[L$]=r;for(let n in t)this[n]=t[n]}}Ct.NAME=M$;Ct.VALUE=L$;class $${static toTextObject(e){let t=new Ct("Algorithm Identifier",{},Bs.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case Ta:{let r=new lh().toWebAlgorithm(e);if(r&&"namedCurve"in r)t["Named Curve"]=r.namedCurve;else t.Parameters=e.parameters;break}default:t.Parameters=e.parameters}return t}}class Bs{static toString(e){let t=this.items[e];if(t)return t;return e}}Bs.items={[cd]:"sha1",[Hx]:"sha224",[ld]:"sha256",[dd]:"sha384",[ud]:"sha512",[Di]:"rsaEncryption",[Op]:"sha1WithRSAEncryption",[YL]:"sha224WithRSAEncryption",[jx]:"sha256WithRSAEncryption",[Dp]:"sha384WithRSAEncryption",[Np]:"sha512WithRSAEncryption",[Ta]:"ecPublicKey",[my]:"ecdsaWithSHA1",[qx]:"ecdsaWithSHA224",[yy]:"ecdsaWithSHA256",[hy]:"ecdsaWithSHA384",[gy]:"ecdsaWithSHA512",[xL]:"TLS WWW server authentication",[wL]:"TLS WWW client authentication",[bL]:"Code Signing",[EL]:"E-mail Protection",[TL]:"Time Stamping",[RL]:"OCSP Signing",[Lx]:"Signed Data"};class Ca{static serialize(e){return this.serializeObj(e).join(`
|
|
216
|
+
`)}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,t=0){let r=[],n=this.pad(t++),o="",i=e[Ct.VALUE];if(i)o=` ${i}`;r.push(`${n}${e[Ct.NAME]}:${o}`),n=this.pad(t);for(let s in e){if(typeof s==="symbol")continue;let a=e[s],c=s?`${s}: `:"";if(typeof a==="string"||typeof a==="number"||typeof a==="boolean")r.push(`${n}${c}${a}`);else if(a instanceof Date)r.push(`${n}${c}${a.toUTCString()}`);else if(Array.isArray(a))for(let l of a)l[Ct.NAME]=s,r.push(...this.serializeObj(l,t));else if(a instanceof Ct)a[Ct.NAME]=s,r.push(...this.serializeObj(a,t));else if(ye.isBufferSource(a))if(s)r.push(`${n}${c}`),r.push(...this.serializeBufferSource(a,t+1));else r.push(...this.serializeBufferSource(a,t));else if("toTextObject"in a){let l=a.toTextObject();l[Ct.NAME]=s,r.push(...this.serializeObj(l,t))}else throw TypeError("Cannot serialize data in text format. Unsupported type.")}return r}static serializeBufferSource(e,t=0){let r=this.pad(t),n=ye.toUint8Array(e),o=[];for(let i=0;i<n.length;){let s=[];for(let a=0;a<16&&i<n.length;a++){if(a===8)s.push("");let c=n[i++].toString(16).padStart(2,"0");s.push(c)}o.push(`${r}${s.join(" ")}`)}return o}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}}Ca.oidSerializer=Bs;Ca.algorithmSerializer=$$;var qp;class _a{get rawData(){if(!be(this,qp,"f"))vt(this,qp,ne.serialize(this.asn),"f");return be(this,qp,"f")}constructor(...e){if(qp.set(this,void 0),ye.isBufferSource(e[0]))this.asn=ne.parse(e[0],e[1]),vt(this,qp,ye.toArrayBuffer(e[0]),"f"),this.onInit(this.asn);else this.asn=e[0],this.onInit(this.asn)}equal(e){if(e instanceof _a)return qv(e.rawData,this.rawData);return!1}toString(e="text"){switch(e){case"asn":return ne.toString(this.rawData);case"text":return Ca.serialize(this.toTextObject());case"hex":return Ee.ToHex(this.rawData);case"base64":return Ee.ToBase64(this.rawData);case"base64url":return Ee.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){let e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new Ct(this.getTextName(),{},e)}}qp=new WeakMap;_a.NAME="ASN";class si extends _a{constructor(...e){let t;if(ye.isBufferSource(e[0]))t=ye.toArrayBuffer(e[0]);else t=ne.serialize(new Eo({extnID:e[0],critical:e[1],extnValue:new ae(ye.toArrayBuffer(e[2]))}));super(t,Eo)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){let e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){let e=this.toTextObjectEmpty(this.critical?"critical":void 0);if(e[Ct.NAME]===si.NAME)e[Ct.NAME]=Bs.toString(this.type);return e}}var q$;class qc{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&e.extractable!==void 0}constructor(){if(this.items=new Map,this[q$]="CryptoProvider",typeof self<"u"&&typeof crypto<"u")this.set(qc.DEFAULT,crypto);else if(typeof global<"u"&&global.crypto&&global.crypto.subtle)this.set(qc.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,t){return this.items.forEach(e,t)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(e=qc.DEFAULT){let t=this.items.get(e.toLowerCase());if(!t)throw Error(`Cannot get Crypto by name '${e}'`);return t}set(e,t){if(typeof e==="string"){if(!t)throw TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),t)}else this.items.set(qc.DEFAULT,e);return this}}q$=Symbol.toStringTag;qc.DEFAULT="default";var gn=new qc,eX=/^[0-2](?:\.[1-9][0-9]*)+$/;function tX(e){return new RegExp(eX).test(e)}class sI{constructor(e={}){this.items={};for(let t in e)this.register(t,e[t])}get(e){return this.items[e]||null}findId(e){if(!tX(e))return this.get(e);return e}register(e,t){this.items[e]=t,this.items[t]=e}}var Ko=new sI;Ko.register("CN","2.5.4.3");Ko.register("L","2.5.4.7");Ko.register("ST","2.5.4.8");Ko.register("O","2.5.4.10");Ko.register("OU","2.5.4.11");Ko.register("C","2.5.4.6");Ko.register("DC","0.9.2342.19200300.100.1.25");Ko.register("E","1.2.840.113549.1.9.1");Ko.register("G","2.5.4.42");Ko.register("I","2.5.4.43");Ko.register("SN","2.5.4.4");Ko.register("T","2.5.4.12");function rX(e,t){return`\\${Ee.ToHex(Ee.FromUtf8String(t)).toUpperCase()}`}function nX(e){return e.replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,rX)}class jc{static isASCII(e){for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,t={}){this.extraNames=new sI,this.asn=new ir;for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];this.extraNames.register(r,n)}if(typeof e==="string")this.asn=this.fromString(e);else if(e instanceof ir)this.asn=e;else if(ye.isBufferSource(e))this.asn=ne.parse(e,ir);else this.asn=this.fromJSON(e)}getField(e){let t=this.extraNames.findId(e)||Ko.findId(e),r=[];for(let n of this.asn)for(let o of n)if(o.type===t)r.push(o.value.toString());return r}getName(e){return this.extraNames.get(e)||Ko.get(e)}toString(){return this.asn.map((e)=>e.map((t)=>{let r=this.getName(t.type)||t.type,n=t.value.anyValue?`#${Ee.ToHex(t.value.anyValue)}`:nX(t.value.toString());return`${r}=${n}`}).join("+")).join(", ")}toJSON(){var e;let t=[];for(let r of this.asn){let n={};for(let o of r){let i=this.getName(o.type)||o.type;(e=n[i])!==null&&e!==void 0||(n[i]=[]),n[i].push(o.value.anyValue?`#${Ee.ToHex(o.value.anyValue)}`:o.value.toString())}t.push(n)}return t}fromString(e){let t=new ir,r=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+"\\](?=[,+]|$))|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g,n=null,o=",";while(n=r.exec(`${e},`)){let[,i,s]=n,a=s[s.length-1];if(a===","||a==="+")s=s.slice(0,s.length-1),n[3]=a;let c=n[3];i=this.getTypeOid(i);let l=this.createAttribute(i,s);if(o==="+")t[t.length-1].push(l);else t.push(new Ic([l]));o=c}return t}fromJSON(e){let t=new ir;for(let r of e){let n=new Ic;for(let o in r){let i=this.getTypeOid(o),s=r[o];for(let a of s){let c=this.createAttribute(i,a);n.push(c)}}t.push(n)}return t}getTypeOid(e){if(!/[\d.]+/.test(e))e=this.getName(e)||"";if(!e)throw Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(e,t){let r=new up({type:e});if(typeof t==="object")for(let n in t)switch(n){case"ia5String":r.value.ia5String=t[n];break;case"utf8String":r.value.utf8String=t[n];break;case"universalString":r.value.universalString=t[n];break;case"bmpString":r.value.bmpString=t[n];break;case"printableString":r.value.printableString=t[n];break}else if(t[0]==="#")r.value.anyValue=Ee.FromHex(t.slice(1));else{let n=this.processStringValue(t);if(e===this.getName("E")||e===this.getName("DC"))r.value.ia5String=n;else if(jc.isPrintableString(n))r.value.printableString=n;else r.value.utf8String=n}return r}processStringValue(e){let t=/"(.*?[^\\])?"/.exec(e);if(t)e=t[1];return e.replace(/\\0a/ig,`
|
|
217
|
+
`).replace(/\\0d/ig,"\r").replace(/\\0g/ig,"\t").replace(/\\(.)/g,"$1")}toArrayBuffer(){return ne.serialize(this.asn)}async getThumbprint(...e){var t;let r,n="SHA-1";if(e.length>=1&&!((t=e[0])===null||t===void 0?void 0:t.subtle))n=e[0]||n,r=e[1]||gn.get();else r=e[0]||gn.get();return await r.subtle.digest(n,this.toArrayBuffer())}}var j$="Cannot initialize GeneralName from ASN.1 data.",P$=`${j$} Unsupported string format in use.`,oX=`${j$} Value doesn't match to GUID regular expression.`,I$=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,C$="1.3.6.1.4.1.311.25.1",_$="1.3.6.1.4.1.311.20.2.3",QP="dns",JP="dn",zP="email",GP="ip",YP="url",XP="guid",ZP="upn",Zx="id";class Ia extends _a{constructor(...e){let t;if(e.length===2)switch(e[0]){case JP:{let r=new jc(e[1]).toArrayBuffer(),n=ne.parse(r,ir);t=new je({directoryName:n});break}case QP:t=new je({dNSName:e[1]});break;case zP:t=new je({rfc822Name:e[1]});break;case XP:{let r=new RegExp(I$,"i").exec(e[1]);if(!r)throw Error("Cannot parse GUID value. Value doesn't match to regular expression");let n=r.slice(1).map((o,i)=>{if(i<3)return Ee.ToHex(new Uint8Array(Ee.FromHex(o)).reverse());return o}).join("");t=new je({otherName:new Kl({typeId:C$,value:ne.serialize(new ae(Ee.FromHex(n)))})});break}case GP:t=new je({iPAddress:e[1]});break;case Zx:t=new je({registeredID:e[1]});break;case ZP:{t=new je({otherName:new Kl({typeId:_$,value:ne.serialize(fA.toASN(e[1]))})});break}case YP:t=new je({uniformResourceIdentifier:e[1]});break;default:throw Error("Cannot create GeneralName. Unsupported type of the name")}else if(ye.isBufferSource(e[0]))t=ne.parse(e[0],je);else t=e[0];super(t)}onInit(e){if(e.dNSName!=null)this.type=QP,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=zP,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=GP,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=YP,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=Zx,this.value=e.registeredID;else if(e.directoryName!=null)this.type=JP,this.value=new jc(e.directoryName).toString();else if(e.otherName!=null)if(e.otherName.typeId===C$){this.type=XP;let t=ne.parse(e.otherName.value,ae),r=new RegExp(I$,"i").exec(Ee.ToHex(t));if(!r)throw Error(oX);this.value=r.slice(1).map((n,o)=>{if(o<3)return Ee.ToHex(new Uint8Array(Ee.FromHex(n)).reverse());return n}).join("-")}else if(e.otherName.typeId===_$)this.type=ZP,this.value=ne.parse(e.otherName.value,hn).toString();else throw Error(P$);else throw Error(P$)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case JP:case QP:case XP:case GP:case Zx:case ZP:case YP:e=this.type.toUpperCase();break;case zP:e="Email";break;default:throw Error("Unsupported GeneralName type")}let t=this.value;if(this.type===Zx)t=Bs.toString(t);return new Ct(e,void 0,t)}}class Hc extends _a{constructor(e){let t;if(e instanceof gr)t=e;else if(Array.isArray(e)){let r=[];for(let n of e)if(n instanceof je)r.push(n);else{let o=ne.parse(new Ia(n.type,n.value).rawData,je);r.push(o)}t=new gr(r)}else if(ye.isBufferSource(e))t=ne.parse(e,gr);else throw Error("Cannot initialize GeneralNames. Incorrect incoming arguments");super(t)}onInit(e){let t=[];for(let r of e){let n=null;try{n=new Ia(r)}catch{continue}t.push(n)}this.items=t}toJSON(){return this.items.map((e)=>e.toJSON())}toTextObject(){let e=super.toTextObjectEmpty();for(let t of this.items){let r=t.toTextObject(),n=e[r[Ct.NAME]];if(!Array.isArray(n))n=[],e[r[Ct.NAME]]=n;n.push(r)}return e}}Hc.NAME="GeneralNames";var ch="-{5}",dh="\\n",iX=`[^${dh}]+`,sX=`${ch}BEGIN (${iX}(?=${ch}))${ch}`,aX=`${ch}END \\1${ch}`,Jp="\\n",cX=`[^:${dh}]+`,lX=`(?:[^${dh}]+${Jp}(?: +[^${dh}]+${Jp})*)`,dX="[a-zA-Z0-9=+/]+",uX=`(?:${dX}${Jp})+`,k$=`${sX}${Jp}(?:((?:${cX}: ${lX})+))?${Jp}?(${uX})${aX}`;class ro{static isPem(e){return typeof e==="string"&&new RegExp(k$,"g").test(e.replace(/\r/g,""))}static decodeWithHeaders(e){e=e.replace(/\r/g,"");let t=new RegExp(k$,"g"),r=[],n=null;while(n=t.exec(e)){let o=n[3].replace(new RegExp(`[${dh}]+`,"g"),""),i={type:n[1],headers:[],rawData:Ee.FromBase64(o)},s=n[2];if(s){let a=s.split(new RegExp(Jp,"g")),c=null;for(let l of a){let[d,u]=l.split(/:(.*)/);if(u===void 0){if(!c)throw Error("Cannot parse PEM string. Incorrect header value");c.value+=d.trim()}else{if(c)i.headers.push(c);c={key:d,value:u.trim()}}}if(c)i.headers.push(c)}r.push(i)}return r}static decode(e){return this.decodeWithHeaders(e).map((r)=>r.rawData)}static decodeFirst(e){let t=this.decode(e);if(!t.length)throw RangeError("PEM string doesn't contain any objects");return t[0]}static encode(e,t){if(Array.isArray(e)){let r=[];if(t)e.forEach((n)=>{if(!ye.isBufferSource(n))throw TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");r.push(this.encodeStruct({type:t,rawData:ye.toArrayBuffer(n)}))});else e.forEach((n)=>{if(!("type"in n))throw TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");r.push(this.encodeStruct(n))});return r.join(`
|
|
218
|
+
`)}else{if(!t)throw Error("Required argument 'tag' is missed");return this.encodeStruct({type:t,rawData:ye.toArrayBuffer(e)})}}static encodeStruct(e){var t;let r=e.type.toLocaleUpperCase(),n=[];if(n.push(`-----BEGIN ${r}-----`),(t=e.headers)===null||t===void 0?void 0:t.length){for(let c of e.headers)n.push(`${c.key}: ${c.value}`);n.push("")}let o=Ee.ToBase64(e.rawData),i,s=0,a=Array();while(s<o.length){if(o.length-s<64)i=o.substring(s);else i=o.substring(s,s+64),s+=64;if(i.length!==0){if(a.push(i),i.length<64)break}else break}return n.push(...a),n.push(`-----END ${r}-----`),n.join(`
|
|
219
|
+
`)}}ro.CertificateTag="CERTIFICATE";ro.CrlTag="CRL";ro.CertificateRequestTag="CERTIFICATE REQUEST";ro.PublicKeyTag="PUBLIC KEY";ro.PrivateKeyTag="PRIVATE KEY";class ii extends _a{static isAsnEncoded(e){return ye.isBufferSource(e)||typeof e==="string"}static toArrayBuffer(e){if(typeof e==="string")if(ro.isPem(e))return ro.decode(e)[0];else if(Ee.isHex(e))return Ee.FromHex(e);else if(Ee.isBase64(e))return Ee.FromBase64(e);else if(Ee.isBase64Url(e))return Ee.FromBase64Url(e);else throw TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url");else{let t=ye.toUint8Array(e);if(t.length>0&&t[0]===48)return ye.toArrayBuffer(e);let r=Ee.ToBinary(e);if(ro.isPem(r))return ro.decode(r)[0];else if(Ee.isHex(r))return Ee.FromHex(r);else if(Ee.isBase64(r))return Ee.FromBase64(r);else if(Ee.isBase64Url(r))return Ee.FromBase64Url(r);throw TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}}constructor(...e){if(ii.isAsnEncoded(e[0]))super(ii.toArrayBuffer(e[0]),e[1]);else super(e[0])}toString(e="pem"){switch(e){case"pem":return ro.encode(this.rawData,this.tag);default:return super.toString(e)}}}class ss extends ii{static async create(e,t=gn.get()){if(e instanceof ss)return e;else if(qc.isCryptoKey(e)){if(e.type!=="public")throw TypeError("Public key is required");let r=await t.subtle.exportKey("spki",e);return new ss(r)}else if(e.publicKey)return e.publicKey;else if(ye.isBufferSource(e))return new ss(e);else throw TypeError("Unsupported PublicKeyType")}constructor(e){if(ii.isAsnEncoded(e))super(e,bo);else super(e);this.tag=ro.PublicKeyTag}async export(...e){let t,r=["verify"],n={hash:"SHA-256",...this.algorithm};if(e.length>1)n=e[0]||n,r=e[1]||r,t=e[2]||gn.get();else t=e[0]||gn.get();let o=this.rawData,i=ne.parse(this.rawData,bo);if(i.algorithm.algorithm===Bc)o=pX(i,o);return t.subtle.importKey("spki",o,n,!0,r)}onInit(e){let t=sr.resolve(xd),r=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case Di:{let n=ne.parse(e.subjectPublicKey,pd),o=ye.toUint8Array(n.modulus);r.publicExponent=ye.toUint8Array(n.publicExponent),r.modulusLength=(!o[0]?o.slice(1):o).byteLength<<3;break}}}async getThumbprint(...e){var t;let r,n="SHA-1";if(e.length>=1&&!((t=e[0])===null||t===void 0?void 0:t.subtle))n=e[0]||n,r=e[1]||gn.get();else r=e[0]||gn.get();return await r.subtle.digest(n,this.rawData)}async getKeyIdentifier(...e){let t,r="SHA-1";if(e.length===1)if(typeof e[0]==="string")r=e[0],t=gn.get();else t=e[0];else if(e.length===2)r=e[0],t=e[1];else t=gn.get();let n=ne.parse(this.rawData,bo);return await t.subtle.digest(r,n.subjectPublicKey)}toTextObject(){let e=this.toTextObjectEmpty(),t=ne.parse(this.rawData,bo);switch(e.Algorithm=Ca.serializeAlgorithm(t.algorithm),t.algorithm.algorithm){case Ta:e["EC Point"]=t.subjectPublicKey;break;case Di:default:e["Raw Data"]=t.subjectPublicKey}return e}}function pX(e,t){return e.algorithm=new ie({algorithm:Di,parameters:null}),t=ne.serialize(e),t}class wd extends si{static async create(e,t=!1,r=gn.get()){if("name"in e&&"serialNumber"in e)return new wd(e,t);let o=await(await ss.create(e,r)).getKeyIdentifier(r);return new wd(Ee.ToHex(o),t)}constructor(...e){if(ye.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]==="string"){let t=new ga({keyIdentifier:new pp(Ee.FromHex(e[0]))});super(Km,e[1],ne.serialize(t))}else{let t=e[0],r=t.name instanceof Hc?ne.parse(t.name.rawData,gr):t.name,n=new ga({authorityCertIssuer:r,authorityCertSerialNumber:Ee.FromHex(t.serialNumber)});super(Km,e[1],ne.serialize(n))}}onInit(e){super.onInit(e);let t=ne.parse(e.extnValue,ga);if(t.keyIdentifier)this.keyId=Ee.ToHex(t.keyIdentifier);if(t.authorityCertIssuer||t.authorityCertSerialNumber)this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?Ee.ToHex(t.authorityCertSerialNumber):""}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=ne.parse(this.value,ga);if(t.authorityCertIssuer)e["Authority Issuer"]=new Hc(t.authorityCertIssuer).toTextObject();if(t.authorityCertSerialNumber)e["Authority Serial Number"]=t.authorityCertSerialNumber;if(t.keyIdentifier)e[""]=t.keyIdentifier;return e}}wd.NAME="Authority Key Identifier";class aI extends si{constructor(...e){if(ye.isBufferSource(e[0])){super(e[0]);let t=ne.parse(this.value,kc);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{let t=new kc({cA:e[0],pathLenConstraint:e[1]});super(fp,e[2],ne.serialize(t));this.ca=e[0],this.pathLength=e[1]}}toTextObject(){let e=this.toTextObjectWithoutValue();if(this.ca)e.CA=this.ca;if(this.pathLength!==void 0)e["Path Length"]=this.pathLength;return e}}aI.NAME="Basic Constraints";var O$;(function(e){e.serverAuth="1.3.6.1.5.5.7.3.1",e.clientAuth="1.3.6.1.5.5.7.3.2",e.codeSigning="1.3.6.1.5.5.7.3.3",e.emailProtection="1.3.6.1.5.5.7.3.4",e.timeStamping="1.3.6.1.5.5.7.3.8",e.ocspSigning="1.3.6.1.5.5.7.3.9"})(O$||(O$={}));class cI extends si{constructor(...e){if(ye.isBufferSource(e[0])){super(e[0]);let t=ne.parse(this.value,Jl);this.usages=t.map((r)=>r)}else{let t=new Jl(e[0]);super(hp,e[1],ne.serialize(t));this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[""]=this.usages.map((t)=>Bs.toString(t)).join(", "),e}}cI.NAME="Extended Key Usages";var D$;(function(e){e[e.digitalSignature=1]="digitalSignature",e[e.nonRepudiation=2]="nonRepudiation",e[e.keyEncipherment=4]="keyEncipherment",e[e.dataEncipherment=8]="dataEncipherment",e[e.keyAgreement=16]="keyAgreement",e[e.keyCertSign=32]="keyCertSign",e[e.cRLSign=64]="cRLSign",e[e.encipherOnly=128]="encipherOnly",e[e.decipherOnly=256]="decipherOnly"})(D$||(D$={}));class lI extends si{constructor(...e){if(ye.isBufferSource(e[0])){super(e[0]);let t=ne.parse(this.value,zm);this.usages=t.toNumber()}else{let t=new zm(e[0]);super(Tx,e[1],ne.serialize(t));this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=ne.parse(this.value,zm);return e[""]=t.toJSON().join(", "),e}}lI.NAME="Key Usages";class zp extends si{static async create(e,t=!1,r=gn.get()){let o=await(await ss.create(e,r)).getKeyIdentifier(r);return new zp(Ee.ToHex(o),t)}constructor(...e){if(ye.isBufferSource(e[0])){super(e[0]);let t=ne.parse(this.value,ri);this.keyId=Ee.ToHex(t)}else{let t=typeof e[0]==="string"?Ee.FromHex(e[0]):e[0],r=new ri(t);super(Px,e[1],ne.serialize(r));this.keyId=Ee.ToHex(t)}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=ne.parse(this.value,ri);return e[""]=t,e}}zp.NAME="Subject Key Identifier";class dI extends si{constructor(...e){if(ye.isBufferSource(e[0]))super(e[0]);else super(vp,e[1],new Hc(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=ne.parse(e.extnValue,Sp);this.names=new Hc(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let r in t)e[r]=t[r];return e}}dI.NAME="Subject Alternative Name";class no{static register(e,t){this.items.set(e,t)}static create(e){let t=new si(e),r=this.items.get(t.type);if(r)return new r(e);return t}}no.items=new Map;class uI extends si{constructor(...e){var t;if(ye.isBufferSource(e[0])){super(e[0]);let r=ne.parse(this.value,Vm);this.policies=r.map((n)=>n.policyIdentifier)}else{let r=e[0],n=(t=e[1])!==null&&t!==void 0?t:!1,o=new Vm(r.map((i)=>new mp({policyIdentifier:i})));super(Sx,n,ne.serialize(o));this.policies=r}}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map((t)=>new Ct("",{},Bs.toString(t))),e}}uI.NAME="Certificate Policies";no.register(Sx,uI);class ph extends si{constructor(...e){var t;if(ye.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&typeof e[0][0]==="string"){let n=e[0].map((i)=>new xa({distributionPoint:new va({fullName:[new je({uniformResourceIdentifier:i})]})})),o=new Oc(n);super(bx,e[1],ne.serialize(o))}else{let r=new Oc(e[0]);super(bx,e[1],ne.serialize(r))}(t=this.distributionPoints)!==null&&t!==void 0||(this.distributionPoints=[])}onInit(e){super.onInit(e);let t=ne.parse(e.extnValue,Oc);this.distributionPoints=t}toTextObject(){let e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map((t)=>{var r;let n={};if(t.distributionPoint)n[""]=(r=t.distributionPoint.fullName)===null||r===void 0?void 0:r.map((o)=>new Ia(o).toString()).join(", ");if(t.reasons)n.Reasons=t.reasons.toString();if(t.cRLIssuer)n["CRL Issuer"]=t.cRLIssuer.map((o)=>o.toString()).join(", ");return n}),e}}ph.NAME="CRL Distribution Points";class pI extends si{constructor(...e){var t,r,n,o;if(ye.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof Ql){let i=new Ql(e[0]);super(hx,e[1],ne.serialize(i))}else{let i=e[0],s=new Ql;tw(s,i,bA,"ocsp"),tw(s,i,EA,"caIssuers"),tw(s,i,TA,"timeStamping"),tw(s,i,RA,"caRepository");super(hx,e[1],ne.serialize(s))}(t=this.ocsp)!==null&&t!==void 0||(this.ocsp=[]),(r=this.caIssuers)!==null&&r!==void 0||(this.caIssuers=[]),(n=this.timeStamping)!==null&&n!==void 0||(this.timeStamping=[]),(o=this.caRepository)!==null&&o!==void 0||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],ne.parse(e.extnValue,Ql).forEach((r)=>{switch(r.accessMethod){case bA:this.ocsp.push(new Ia(r.accessLocation));break;case EA:this.caIssuers.push(new Ia(r.accessLocation));break;case TA:this.timeStamping.push(new Ia(r.accessLocation));break;case RA:this.caRepository.push(new Ia(r.accessLocation));break}})}toTextObject(){let e=this.toTextObjectWithoutValue();if(this.ocsp.length)ew(e,"OCSP",this.ocsp);if(this.caIssuers.length)ew(e,"CA Issuers",this.caIssuers);if(this.timeStamping.length)ew(e,"Time Stamping",this.timeStamping);if(this.caRepository.length)ew(e,"CA Repository",this.caRepository);return e}}pI.NAME="Authority Info Access";function ew(e,t,r){if(r.length===1)e[t]=r[0].toTextObject();else{let n=new Ct("");r.forEach((o,i)=>{let s=o.toTextObject(),a=`${s[Ct.NAME]} ${i+1}`,c=n[a];if(!Array.isArray(c))c=[],n[a]=c;c.push(s)}),e[t]=n}}function tw(e,t,r,n){let o=t[n];if(o)(Array.isArray(o)?o:[o]).forEach((s)=>{if(typeof s==="string")s=new Ia("url",s);e.push(new _c({accessMethod:r,accessLocation:ne.parse(s.rawData,je)}))})}class fI extends si{constructor(...e){if(ye.isBufferSource(e[0]))super(e[0]);else super(BA,e[1],new Hc(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=ne.parse(e.extnValue,gr);this.names=new Hc(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let r in t)e[r]=t[r];return e}}fI.NAME="Issuer Alternative Name";class Gp extends _a{constructor(...e){let t;if(ye.isBufferSource(e[0]))t=ye.toArrayBuffer(e[0]);else{let r=e[0],n=Array.isArray(e[1])?e[1].map((o)=>ye.toArrayBuffer(o)):[];t=ne.serialize(new to({type:r,values:n}))}super(t,to)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Value=this.values.map((t)=>new Ct("",{"":t})),e}toTextObjectWithoutValue(){let e=this.toTextObjectEmpty();if(e[Ct.NAME]===Gp.NAME)e[Ct.NAME]=Bs.toString(this.type);return e}}Gp.NAME="Attribute";class mI extends Gp{constructor(...e){var t;if(ye.isBufferSource(e[0]))super(e[0]);else{let r=new ky({printableString:e[0]});super(KP,[ne.serialize(r)])}(t=this.password)!==null&&t!==void 0||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){let t=ne.parse(this.values[0],ky);this.password=t.toString()}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[Ct.VALUE]=this.password,e}}mI.NAME="Challenge Password";class ow extends Gp{constructor(...e){var t;if(ye.isBufferSource(e[0]))super(e[0]);else{let r=e[0],n=new _i;for(let o of r)n.push(ne.parse(o.rawData,Eo));super(Dy,[ne.serialize(n)])}(t=this.items)!==null&&t!==void 0||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){let t=ne.parse(this.values[0],_i);this.items=t.map((r)=>no.create(ne.serialize(r)))}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.items.map((r)=>r.toTextObject());for(let r of t)e[r[Ct.NAME]]=r;return e}}ow.NAME="Extensions";class fh{static register(e,t){this.items.set(e,t)}static create(e){let t=new Gp(e),r=this.items.get(t.type);if(r)return new r(e);return t}}fh.items=new Map;var mh="crypto.signatureFormatter";class H${toAsnSignature(e,t){return ye.toArrayBuffer(t)}toWebSignature(e,t){return ye.toArrayBuffer(t)}}var nw,rI=nw=class{static createPssParams(t,r){let n=nw.getHashAlgorithm(t);if(!n)return null;return new Aa({hashAlgorithm:n,maskGenAlgorithm:new ie({algorithm:Mc,parameters:ne.serialize(n)}),saltLength:r})}static getHashAlgorithm(t){let r=sr.resolve(xd);if(typeof t==="string")return r.toAsnAlgorithm({name:t});if(typeof t==="object"&&t&&"name"in t)return r.toAsnAlgorithm(t);return null}toAsnAlgorithm(t){switch(t.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if("hash"in t){let r;if(typeof t.hash==="string")r=t.hash;else if(t.hash&&typeof t.hash==="object"&&"name"in t.hash&&typeof t.hash.name==="string")r=t.hash.name.toUpperCase();else throw Error("Cannot get hash algorithm name");switch(r.toLowerCase()){case"sha-1":return new ie({algorithm:Op,parameters:null});case"sha-256":return new ie({algorithm:jx,parameters:null});case"sha-384":return new ie({algorithm:Dp,parameters:null});case"sha-512":return new ie({algorithm:Np,parameters:null})}}else return new ie({algorithm:Di,parameters:null});break;case"rsa-pss":if("hash"in t){if(!(("saltLength"in t)&&typeof t.saltLength==="number"))throw Error("Cannot get 'saltLength' from 'alg' argument");let r=nw.createPssParams(t.hash,t.saltLength);if(!r)throw Error("Cannot create PSS parameters");return new ie({algorithm:Bc,parameters:ne.serialize(r)})}else return new ie({algorithm:Bc,parameters:null})}return null}toWebAlgorithm(t){switch(t.algorithm){case Di:return{name:"RSASSA-PKCS1-v1_5"};case Op:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case jx:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case Dp:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case Np:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case Bc:if(t.parameters){let r=ne.parse(t.parameters,Aa);return{name:"RSA-PSS",hash:sr.resolve(xd).toWebAlgorithm(r.hashAlgorithm),saltLength:r.saltLength}}else return{name:"RSA-PSS"}}return null}};rI=nw=y([$c()],rI);sr.registerSingleton(uh,rI);var nI=class{toAsnAlgorithm(t){switch(t.name.toLowerCase()){case"sha-1":return new ie({algorithm:cd});case"sha-256":return new ie({algorithm:ld});case"sha-384":return new ie({algorithm:dd});case"sha-512":return new ie({algorithm:ud})}return null}toWebAlgorithm(t){switch(t.algorithm){case cd:return{name:"SHA-1"};case ld:return{name:"SHA-256"};case dd:return{name:"SHA-384"};case ud:return{name:"SHA-512"}}return null}};nI=y([$c()],nI);sr.registerSingleton(uh,nI);class Ni{addPadding(e,t){let r=ye.toUint8Array(t),n=new Uint8Array(e);return n.set(r,e-r.length),n.buffer}removePadding(e,t=!1){let r=ye.toUint8Array(e);for(let n=0;n<r.length;n++){if(!r[n])continue;r=r.slice(n);break}if(t&&r[0]>127){let n=new Uint8Array(r.length+1);return n.set(r,1),n.buffer}return r.buffer}toAsnSignature(e,t){if(e.name==="ECDSA"){let r=e.namedCurve,n=Ni.namedCurveSize.get(r)||Ni.defaultNamedCurveSize,o=new Uc,i=ye.toUint8Array(t);return o.r=this.removePadding(i.slice(0,n),!0),o.s=this.removePadding(i.slice(n,n+n),!0),ne.serialize(o)}return null}toWebSignature(e,t){if(e.name==="ECDSA"){let r=ne.parse(t,Uc),n=e.namedCurve,o=Ni.namedCurveSize.get(n)||Ni.defaultNamedCurveSize,i=this.addPadding(o,this.removePadding(r.r)),s=this.addPadding(o,this.removePadding(r.s));return xB(i,s)}return null}}Ni.namedCurveSize=new Map;Ni.defaultNamedCurveSize=32;var eI="1.3.101.110",N$="1.3.101.111",tI="1.3.101.112",F$="1.3.101.113",oI=class{toAsnAlgorithm(t){let r=null;switch(t.name.toLowerCase()){case"ed25519":r=tI;break;case"x25519":r=eI;break;case"eddsa":switch(t.namedCurve.toLowerCase()){case"ed25519":r=tI;break;case"ed448":r=F$;break}break;case"ecdh-es":switch(t.namedCurve.toLowerCase()){case"x25519":r=eI;break;case"x448":r=N$;break}}if(r)return new ie({algorithm:r});return null}toWebAlgorithm(t){switch(t.algorithm){case tI:return{name:"Ed25519"};case F$:return{name:"EdDSA",namedCurve:"Ed448"};case eI:return{name:"X25519"};case N$:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};oI=y([$c()],oI);sr.registerSingleton(uh,oI);var Uy,By,My,Ly,$y,qy,jy,jp;class W$ extends ii{get subjectName(){if(!be(this,By,"f"))vt(this,By,new jc(this.asn.certificationRequestInfo.subject),"f");return be(this,By,"f")}get subject(){if(!be(this,My,"f"))vt(this,My,this.subjectName.toString(),"f");return be(this,My,"f")}get signatureAlgorithm(){if(!be(this,Ly,"f")){let e=sr.resolve(xd);vt(this,Ly,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return be(this,Ly,"f")}get signature(){if(!be(this,$y,"f"))vt(this,$y,this.asn.signature,"f");return be(this,$y,"f")}get publicKey(){if(!be(this,qy,"f"))vt(this,qy,new ss(this.asn.certificationRequestInfo.subjectPKInfo),"f");return be(this,qy,"f")}get attributes(){if(!be(this,jy,"f"))vt(this,jy,this.asn.certificationRequestInfo.attributes.map((e)=>fh.create(ne.serialize(e))),"f");return be(this,jy,"f")}get extensions(){if(!be(this,jp,"f")){vt(this,jp,[],"f");let e=this.getAttribute(Dy);if(e instanceof ow)vt(this,jp,e.items,"f")}return be(this,jp,"f")}get tbs(){if(!be(this,Uy,"f"))vt(this,Uy,this.asn.certificationRequestInfoRaw||ne.serialize(this.asn.certificationRequestInfo),"f");return be(this,Uy,"f")}constructor(e){let t=ii.isAsnEncoded(e)?[e,vd]:[e];super(t[0],t[1]);Uy.set(this,void 0),By.set(this,void 0),My.set(this,void 0),Ly.set(this,void 0),$y.set(this,void 0),qy.set(this,void 0),jy.set(this,void 0),jp.set(this,void 0),this.tag=ro.CertificateRequestTag}onInit(e){}getAttribute(e){for(let t of this.attributes)if(t.type===e)return t;return null}getAttributes(e){return this.attributes.filter((t)=>t.type===e)}getExtension(e){for(let t of this.extensions)if(t.type===e)return t;return null}getExtensions(e){return this.extensions.filter((t)=>t.type===e)}async verify(e=gn.get()){let t={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(t,["verify"],e),n=sr.resolveAll(mh).reverse(),o=null;for(let s of n)if(o=s.toWebSignature(t,this.signature),o)break;if(!o)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await e.subtle.verify(this.signatureAlgorithm,r,o,this.tbs)}toTextObject(){let e=this.toTextObjectEmpty(),t=ne.parse(this.rawData,vd),r=t.certificationRequestInfo,n=new Ct("",{Version:`${wa[r.version]} (${r.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){let o=new Ct("");for(let i of this.attributes){let s=i.toTextObject();o[s[Ct.NAME]]=s}n.Attributes=o}return e.Data=n,e.Signature=new Ct("",{Algorithm:Ca.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}}Uy=new WeakMap,By=new WeakMap,My=new WeakMap,Ly=new WeakMap,$y=new WeakMap,qy=new WeakMap,jy=new WeakMap,jp=new WeakMap;W$.NAME="PKCS#10 Certificate Request";var Hy,Wy,Ky,Vy,Qy,Jy,zy,Gy,Yy,Xy,Hp,Zy;class Wc extends ii{get publicKey(){if(!be(this,Zy,"f"))vt(this,Zy,new ss(this.asn.tbsCertificate.subjectPublicKeyInfo),"f");return be(this,Zy,"f")}get serialNumber(){if(!be(this,Wy,"f")){let e=this.asn.tbsCertificate,t=new Uint8Array(e.serialNumber);if(t.length>1&&t[0]===0&&t[1]>127)t=t.slice(1);vt(this,Wy,Ee.ToHex(t),"f")}return be(this,Wy,"f")}get subjectName(){if(!be(this,Ky,"f"))vt(this,Ky,new jc(this.asn.tbsCertificate.subject),"f");return be(this,Ky,"f")}get subject(){if(!be(this,Vy,"f"))vt(this,Vy,this.subjectName.toString(),"f");return be(this,Vy,"f")}get issuerName(){if(!be(this,Qy,"f"))vt(this,Qy,new jc(this.asn.tbsCertificate.issuer),"f");return be(this,Qy,"f")}get issuer(){if(!be(this,Jy,"f"))vt(this,Jy,this.issuerName.toString(),"f");return be(this,Jy,"f")}get notBefore(){if(!be(this,zy,"f")){let e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw Error("Cannot get 'notBefore' value");vt(this,zy,e,"f")}return be(this,zy,"f")}get notAfter(){if(!be(this,Gy,"f")){let e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw Error("Cannot get 'notAfter' value");vt(this,Gy,e,"f")}return be(this,Gy,"f")}get signatureAlgorithm(){if(!be(this,Yy,"f")){let e=sr.resolve(xd);vt(this,Yy,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return be(this,Yy,"f")}get signature(){if(!be(this,Xy,"f"))vt(this,Xy,this.asn.signatureValue,"f");return be(this,Xy,"f")}get extensions(){if(!be(this,Hp,"f")){if(vt(this,Hp,[],"f"),this.asn.tbsCertificate.extensions)vt(this,Hp,this.asn.tbsCertificate.extensions.map((e)=>no.create(ne.serialize(e))),"f")}return be(this,Hp,"f")}get tbs(){if(!be(this,Hy,"f"))vt(this,Hy,this.asn.tbsCertificateRaw||ne.serialize(this.asn.tbsCertificate),"f");return be(this,Hy,"f")}constructor(e){let t=ii.isAsnEncoded(e)?[e,nn]:[e];super(t[0],t[1]);Hy.set(this,void 0),Wy.set(this,void 0),Ky.set(this,void 0),Vy.set(this,void 0),Qy.set(this,void 0),Jy.set(this,void 0),zy.set(this,void 0),Gy.set(this,void 0),Yy.set(this,void 0),Xy.set(this,void 0),Hp.set(this,void 0),Zy.set(this,void 0),this.tag=ro.CertificateTag}onInit(e){}getExtension(e){for(let t of this.extensions)if(typeof e==="string"){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter((t)=>{if(typeof e==="string")return t.type===e;else return t instanceof e})}async verify(e={},t=gn.get()){let r,n,o=e.publicKey;try{if(!o)r={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(r,["verify"],t);else if("publicKey"in o)r={...o.publicKey.algorithm,...this.signatureAlgorithm},n=await o.publicKey.export(r,["verify"],t);else if(o instanceof ss)r={...o.algorithm,...this.signatureAlgorithm},n=await o.export(r,["verify"],t);else if(ye.isBufferSource(o)){let c=new ss(o);r={...c.algorithm,...this.signatureAlgorithm},n=await c.export(r,["verify"],t)}else r={...o.algorithm,...this.signatureAlgorithm},n=o}catch{return!1}let i=sr.resolveAll(mh).reverse(),s=null;for(let c of i)if(s=c.toWebSignature(r,this.signature),s)break;if(!s)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");let a=await t.subtle.verify(this.signatureAlgorithm,n,s,this.tbs);if(e.signatureOnly)return a;else{let l=(e.date||new Date).getTime();return a&&this.notBefore.getTime()<l&&l<this.notAfter.getTime()}}async getThumbprint(...e){let t,r="SHA-1";if(e[0])if(!e[0].subtle)r=e[0]||r,t=e[1];else t=e[0];return t!==null&&t!==void 0||(t=gn.get()),await t.subtle.digest(r,this.rawData)}async isSelfSigned(e=gn.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){let e=this.toTextObjectEmpty(),t=ne.parse(this.rawData,nn),r=t.tbsCertificate,n=new Ct("",{Version:`${wa[r.version]} (${r.version})`,"Serial Number":r.serialNumber,"Signature Algorithm":Ca.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new Ct("",{"Not Before":r.validity.notBefore.getTime(),"Not After":r.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(r.issuerUniqueID)n["Issuer Unique ID"]=r.issuerUniqueID;if(r.subjectUniqueID)n["Subject Unique ID"]=r.subjectUniqueID;if(this.extensions.length){let o=new Ct("");for(let i of this.extensions){let s=i.toTextObject();o[s[Ct.NAME]]=s}n.Extensions=o}return e.Data=n,e.Signature=new Ct("",{Algorithm:Ca.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}}Hy=new WeakMap,Wy=new WeakMap,Ky=new WeakMap,Vy=new WeakMap,Qy=new WeakMap,Jy=new WeakMap,zy=new WeakMap,Gy=new WeakMap,Yy=new WeakMap,Xy=new WeakMap,Hp=new WeakMap,Zy=new WeakMap;Wc.NAME="Certificate";class K$ extends Array{constructor(e){super();if(ii.isAsnEncoded(e))this.import(e);else if(e instanceof Wc)this.push(e);else if(Array.isArray(e))for(let t of e)this.push(t)}export(e){let t=new os;t.version=1,t.encapContentInfo.eContentType=$L,t.encapContentInfo.eContent=new td({single:new ae}),t.certificates=new Nc(this.map((o)=>new Dc({certificate:ne.parse(o.rawData,nn)})));let r=new Wo({contentType:Lx,content:ne.serialize(t)}),n=ne.serialize(r);if(e==="raw")return n;return this.toString(e)}import(e){let t=ii.toArrayBuffer(e),r=ne.parse(t,Wo);if(r.contentType!==Lx)throw TypeError("Cannot parse CMS package. Incoming data is not a SignedData object.");let n=ne.parse(r.content,os);this.clear();for(let o of n.certificates||[])if(o.certificate)this.push(new Wc(o.certificate))}clear(){while(this.pop());}toString(e="pem"){let t=this.export("raw");switch(e){case"pem":return ro.encode(t,"CMS");case"pem-chain":return this.map((r)=>r.toString("pem")).join(`
|
|
220
|
+
`);case"asn":return ne.toString(t);case"hex":return Ee.ToHex(t);case"base64":return Ee.ToBase64(t);case"base64url":return Ee.ToBase64Url(t);case"text":return Ca.serialize(this.toTextObject());default:throw TypeError("Argument 'format' is unsupported value")}}toTextObject(){let e=ne.parse(this.export("raw"),Wo),t=ne.parse(e.content,os);return new Ct("X509Certificates",{"Content Type":Bs.toString(e.contentType),Content:new Ct("",{Version:`${Bn[t.version]} (${t.version})`,Certificates:new Ct("",{Certificate:this.map((n)=>n.toTextObject())})})})}}class yI{constructor(e={}){if(this.certificates=[],e.certificates)this.certificates=e.certificates}async build(e,t=gn.get()){let r=new K$(e),n=e;while(n=await this.findIssuer(n,t)){let o=await n.getThumbprint(t);for(let i of r){let s=await i.getThumbprint(t);if(qv(o,s))throw Error("Cannot build a certificate chain. Circular dependency.")}r.push(n)}return r}async findIssuer(e,t=gn.get()){if(!await e.isSelfSigned(t)){let r=e.getExtension(Km);for(let n of this.certificates){if(n.subject!==e.issuer)continue;if(r){if(r.keyId){let o=n.getExtension(Px);if(o&&o.keyId!==r.keyId)continue}else if(r.certId){let o=n.getExtension(vp);if(o&&!(r.certId.serialNumber===n.serialNumber&&qv(ne.serialize(r.certId.name),ne.serialize(o))))continue}}try{let o={...n.publicKey.algorithm,...e.signatureAlgorithm},i=await n.publicKey.export(o,["verify"],t);if(!await e.verify({publicKey:i,signatureOnly:!0},t))continue}catch{continue}return n}}return null}}function V$(e,t=gn.get()){let r=ye.toUint8Array(Ee.FromHex(e||"")),n=r&&r.length&&r.some((i)=>i>0)?new Uint8Array(r):void 0;if(!n)n=t.getRandomValues(new Uint8Array(16));let o=0;while(o<n.length-1&&n[o]===0)o++;if(n=n.slice(o),n[0]>127){let i=new Uint8Array(n.length+1);i[0]=0,i.set(n,1),n=i}return n.buffer}var eh,th,Wp,Kp,Vp,U$;(function(e){e[e.unspecified=0]="unspecified",e[e.keyCompromise=1]="keyCompromise",e[e.cACompromise=2]="cACompromise",e[e.affiliationChanged=3]="affiliationChanged",e[e.superseded=4]="superseded",e[e.cessationOfOperation=5]="cessationOfOperation",e[e.certificateHold=6]="certificateHold",e[e.removeFromCRL=8]="removeFromCRL",e[e.privilegeWithdrawn=9]="privilegeWithdrawn",e[e.aACompromise=10]="aACompromise"})(U$||(U$={}));class iI extends _a{get serialNumber(){if(!be(this,eh,"f"))vt(this,eh,Ee.ToHex(this.asn.userCertificate),"f");return be(this,eh,"f")}get revocationDate(){if(!be(this,th,"f"))vt(this,th,this.asn.revocationDate.getTime(),"f");return be(this,th,"f")}get reason(){if(be(this,Wp,"f")===void 0)this.extensions;return be(this,Wp,"f")}get invalidity(){if(be(this,Kp,"f")===void 0)this.extensions;return be(this,Kp,"f")}get extensions(){if(!be(this,Vp,"f")){if(vt(this,Vp,[],"f"),this.asn.crlEntryExtensions)vt(this,Vp,this.asn.crlEntryExtensions.map((e)=>{let t=no.create(ne.serialize(e));switch(t.type){case OA:if(be(this,Wp,"f")===void 0)vt(this,Wp,ne.parse(t.value,yp).reason,"f");break;case FA:if(be(this,Kp,"f")===void 0)vt(this,Kp,ne.parse(t.value,gp).value,"f");break}return t}),"f")}return be(this,Vp,"f")}constructor(...e){let t;if(ye.isBufferSource(e[0]))t=ye.toArrayBuffer(e[0]);else if(typeof e[0]==="string")t=ne.serialize(new ba({userCertificate:V$(e[0]),revocationDate:new Nr(e[1]),crlEntryExtensions:e[2]}));else if(e[0]instanceof ba)t=e[0];if(!t)throw TypeError("Cannot create X509CrlEntry instance. Wrong constructor arguments.");super(t,ba);eh.set(this,void 0),th.set(this,void 0),Wp.set(this,void 0),Kp.set(this,void 0),Vp.set(this,void 0)}onInit(e){}}eh=new WeakMap,th=new WeakMap,Wp=new WeakMap,Kp=new WeakMap,Vp=new WeakMap;var rh,nh,oh,ih,sh,ah,Qp;class hI extends ii{get version(){return this.asn.tbsCertList.version}get signatureAlgorithm(){if(!be(this,nh,"f")){let e=sr.resolve(xd);vt(this,nh,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return be(this,nh,"f")}get signature(){return this.asn.signature}get issuer(){return this.issuerName.toString()}get issuerName(){if(!be(this,oh,"f"))vt(this,oh,new jc(this.asn.tbsCertList.issuer),"f");return be(this,oh,"f")}get thisUpdate(){if(!be(this,ih,"f")){let e=this.asn.tbsCertList.thisUpdate.getTime();if(!e)throw Error("Cannot get 'thisUpdate' value");vt(this,ih,e,"f")}return be(this,ih,"f")}get nextUpdate(){var e;if(be(this,sh,"f")===void 0)vt(this,sh,((e=this.asn.tbsCertList.nextUpdate)===null||e===void 0?void 0:e.getTime())||void 0,"f");return be(this,sh,"f")}get entries(){var e;if(!be(this,ah,"f"))vt(this,ah,((e=this.asn.tbsCertList.revokedCertificates)===null||e===void 0?void 0:e.map((t)=>new iI(t)))||[],"f");return be(this,ah,"f")}get extensions(){if(!be(this,Qp,"f")){if(vt(this,Qp,[],"f"),this.asn.tbsCertList.crlExtensions)vt(this,Qp,this.asn.tbsCertList.crlExtensions.map((e)=>no.create(ne.serialize(e))),"f")}return be(this,Qp,"f")}get tbs(){if(!be(this,rh,"f"))vt(this,rh,this.asn.tbsCertListRaw||ne.serialize(this.asn.tbsCertList),"f");return be(this,rh,"f")}get tbsCertListSignatureAlgorithm(){return this.asn.tbsCertList.signature}get certListSignatureAlgorithm(){return this.asn.signatureAlgorithm}constructor(e){super(e,ii.isAsnEncoded(e)?Gl:void 0);this.tag=ro.CrlTag,rh.set(this,void 0),nh.set(this,void 0),oh.set(this,void 0),ih.set(this,void 0),sh.set(this,void 0),ah.set(this,void 0),Qp.set(this,void 0)}onInit(e){}getExtension(e){for(let t of this.extensions)if(typeof e==="string"){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter((t)=>{if(typeof e==="string")return t.type===e;else return t instanceof e})}async verify(e,t=gn.get()){if(!this.certListSignatureAlgorithm.isEqual(this.tbsCertListSignatureAlgorithm))throw Error("algorithm identifier in the sequence tbsCertList and CertificateList mismatch");let r,n,o=e.publicKey;try{if(o instanceof Wc)r={...o.publicKey.algorithm,...o.signatureAlgorithm},n=await o.publicKey.export(r,["verify"]);else if(o instanceof ss)r={...o.algorithm,...this.signatureAlgorithm},n=await o.export(r,["verify"]);else r={...o.algorithm,...this.signatureAlgorithm},n=o}catch{return!1}let i=sr.resolveAll(mh).reverse(),s=null;for(let a of i)if(s=a.toWebSignature(r,this.signature),s)break;if(!s)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return await t.subtle.verify(this.signatureAlgorithm,n,s,this.tbs)}async getThumbprint(...e){let t,r="SHA-1";if(e[0])if(!e[0].subtle)r=e[0]||r,t=e[1];else t=e[0];return t!==null&&t!==void 0||(t=gn.get()),await t.subtle.digest(r,this.rawData)}findRevoked(e){let t=typeof e==="string"?e:e.serialNumber,r=V$(t);for(let n of this.asn.tbsCertList.revokedCertificates||[])if(ye.isEqual(n.userCertificate,r))return new iI(ne.serialize(n));return null}}rh=new WeakMap,nh=new WeakMap,oh=new WeakMap,ih=new WeakMap,sh=new WeakMap,ah=new WeakMap,Qp=new WeakMap;no.register(fp,aI);no.register(hp,cI);no.register(Tx,lI);no.register(Px,zp);no.register(Km,wd);no.register(vp,dI);no.register(bx,ph);no.register(hx,pI);no.register(BA,fI);fh.register(KP,mI);fh.register(Dy,ow);sr.registerSingleton(mh,H$);sr.registerSingleton(mh,Ni);Ni.namedCurveSize.set("P-256",32);Ni.namedCurveSize.set("K-256",32);Ni.namedCurveSize.set("P-384",48);Ni.namedCurveSize.set("P-521",66);function iw(e){return fX.stubThis(e)}var fX={stubThis:(e)=>globalThis.fetch(e)};var Q$={};async function J$(e){let{extensions:t}=e;if(!t)return!1;let r,n,o;t.forEach((u)=>{if(u instanceof wd)r=u;else if(u instanceof zp)n=u;else if(u instanceof ph)o=u});let i=void 0;if(r&&r.keyId)i=r.keyId;else if(n)i=n.keyId;if(i){let u=Q$[i];if(u){let m=new Date;if(!u.nextUpdate||u.nextUpdate>m)return u.revokedCerts.indexOf(e.serialNumber)>=0}}let s=o?.distributionPoints?.[0].distributionPoint?.fullName?.[0].uniformResourceIdentifier;if(!s)return!1;let a;try{a=await(await iw(s)).arrayBuffer()}catch(u){return!1}let c;try{c=new hI(a)}catch(u){return!1}let l={revokedCerts:[],nextUpdate:void 0};if(c.nextUpdate)l.nextUpdate=c.nextUpdate;let d=c.entries;if(d){for(let u of d){let m=u.serialNumber;l.revokedCerts.push(m)}if(i)Q$[i]=l;return l.revokedCerts.indexOf(e.serialNumber)>=0}return!1}function z$(e){let t;try{t=qu(e)}catch(r){throw Error(`Error decoding authenticator extensions: ${r.message}`)}return G$(t)}function G$(e){let t={};for(let[r,n]of e)if(n instanceof Map)t[r]=G$(n);else t[r]=n;return t}function gI(e){if(e.byteLength<37)throw Error(`Authenticator data was ${e.byteLength} bytes, expected at least 37 bytes`);let t=0,r=sw(e),n=e.slice(t,t+=32),o=e.slice(t,t+=1),i=o[0],s={up:!!(i&1),uv:!!(i&4),be:!!(i&8),bs:!!(i&16),at:!!(i&64),ed:!!(i&128),flagsInt:i},a=e.slice(t,t+4),c=r.getUint32(t,!1);t+=4;let l=void 0,d=void 0,u=void 0;if(s.at){l=e.slice(t,t+=16);let S=r.getUint16(t);t+=2,d=e.slice(t,t+=S);let x=yX("a301634f4b500327206745643235353139"),v=e.slice(t,t+x.byteLength),w=!1;if(as(x,v))w=!0,e[t]=164;let P=qu(e.slice(t)),F=Uint8Array.from(fB(P));if(w)e[t]=163;u=F,t+=F.byteLength}let m=void 0,h=void 0;if(s.ed){let S=qu(e.slice(t));h=Uint8Array.from(fB(S)),m=z$(h),t+=h.byteLength}if(e.byteLength>t)throw Error("Leftover bytes detected while parsing authenticator data");return mX.stubThis({rpIdHash:n,flagsBuf:o,flags:s,counter:c,counterBuf:a,aaguid:l,credentialID:d,credentialPublicKey:u,extensionsData:m,extensionsDataBuffer:h})}var mX={stubThis:(e)=>e};function Fi(e,t=-7){if(typeof e==="string")e=aw(e);return gB(e,t)}async function oo(e,t=[]){if(t.length===0)return!0;let r=e.map((s)=>new Wc(s));for(let s=0;s<r.length;s++){let a=r[s],c=e[s];try{await Y$(a)}catch(l){throw Error(`Found revoked certificate in x5c:
|
|
221
|
+
${c}`)}try{X$(a.notBefore,a.notAfter)}catch(l){throw Error(`Found certificate out of validity period in x5c:
|
|
222
|
+
${c}`)}}let n=t.map((s)=>{try{return new Wc(s)}catch(a){let c=a;throw Error(`Could not parse trust anchor certificate:
|
|
223
|
+
${s}`,{cause:c})}}),o=[];for(let s=0;s<n.length;s++){let a=n[s];try{await Y$(a)}catch(c){continue}try{X$(a.notBefore,a.notAfter)}catch(c){continue}o.push(a)}if(o.length===0)throw Error("No specified trust anchor was valid for verifying x5c");let i=!0;for(let s of o)try{let a=r.concat([s]),c=new Set(a.map((h)=>h.toString("pem"))).size;if(c!==a.length)throw Error("Invalid certificate path: found duplicate certificates");let l=r[0],d=[];if(r.length>1)d=r.slice(1);let m=await new yI({certificates:[...d,s]}).build(l);if(m.length<c)continue;if(m[m.length-1].subject!==s.subject)continue;i=!1;break}catch(a){throw Error("Unexpected error while validating certificate path",{cause:a})}if(i)throw new Z$;return!0}async function Y$(e){if(await J$(e))throw Error("Found revoked certificate in certificate path")}function X$(e,t){let r=new Date(Date.now());if(e>r||t<r)throw Error("Certificate is not yet valid or expired")}class Z$ extends Error{constructor(){super("x5c could not be chained to any specified trust anchor");this.name="InvalidX5CChain"}}function SI(e){let t;if(e==="1.2.840.10045.4.3.2")t=tt.ES256;else if(e==="1.2.840.10045.4.3.3")t=tt.ES384;else if(e==="1.2.840.10045.4.3.4")t=tt.ES512;else if(e==="1.2.840.113549.1.1.11")t=tt.RS256;else if(e==="1.2.840.113549.1.1.12")t=tt.RS384;else if(e==="1.2.840.113549.1.1.13")t=tt.RS512;else if(e==="1.2.840.113549.1.1.5")t=tt.RS1;else throw Error(`Unable to map X.509 signature algorithm ${e} to a COSE algorithm`);return t}function cw(e){let t=new Map,r=Ir.parse(e,nn),{tbsCertificate:n}=r,{subjectPublicKeyInfo:o,signature:i}=n,s=i.algorithm,a=o.algorithm.algorithm;if(a===Ta){if(!o.algorithm.parameters)throw Error("Certificate public key was missing parameters (EC2)");let c=Ir.parse(new Uint8Array(o.algorithm.parameters),Oi),l=-999,{namedCurve:d}=c;if(d===Sy)l=Zn.P256;else if(d===vy)l=Zn.P384;else throw Error(`Certificate public key contained unexpected namedCurve ${d} (EC2)`);let u=new Uint8Array(o.subjectPublicKey),m,h;if(u[0]===4){let x=1,v=(u.length-1)/2;m=u.slice(x,x+=v),h=u.slice(x)}else throw Error('TODO: Figure out how to handle public keys in "compressed form"');let S=new Map;S.set(Ze.kty,ti.EC2),S.set(Ze.alg,SI(s)),S.set(Ze.crv,l),S.set(Ze.x,m),S.set(Ze.y,h),t=S}else if(a===Di){let c=Ir.parse(o.subjectPublicKey,pd),l=new Map;l.set(Ze.kty,ti.RSA),l.set(Ze.alg,SI(s)),l.set(Ze.n,new Uint8Array(c.modulus)),l.set(Ze.e,new Uint8Array(c.publicExponent)),t=l}else throw Error(`Certificate public key contained unexpected algorithm ID ${a}`);return t}function Ui(e){let{signature:t,data:r,credentialPublicKey:n,x509Certificate:o,hashAlgorithm:i}=e;if(!o&&!n)throw Error('Must declare either "leafCert" or "credentialPublicKey"');if(o&&n)throw Error('Must not declare both "leafCert" and "credentialPublicKey"');let s=new Map;if(n)s=bc(n);else if(o)s=cw(o);return hX.stubThis(eq({cosePublicKey:s,signature:t,data:r,shaHashOverride:i}))}var hX={stubThis:(e)=>e};function tq(e){let t=e.split(".");return[JSON.parse(Lu(t[0])),JSON.parse(Lu(t[1])),t[2]]}function rq(e){let t;if(e==="ES256")t=tt.ES256;else if(e==="ES384")t=tt.ES384;else if(e==="ES512")t=tt.ES512;else if(e==="RS256")t=tt.RS256;else if(e==="RS384")t=tt.RS384;else if(e==="RS512")t=tt.RS512;else throw Error(`Unable to map JWS algorithm "${e}" to a COSE algorithm`);return t}function nq(e,t){let[r,n,o]=e.split("."),i=cw(t),s=aw(`${r}.${n}`),a=Mu(o),c=JSON.parse(Lu(r)),l=rq(c.alg);if(xc(i))return Bv({data:s,signature:a,cosePublicKey:i,shaHashOverride:l});else if(Hu(i))return Mv({data:s,signature:a,cosePublicKey:i,shaHashOverride:l});let d=i.get(Ze.kty);throw Error(`JWT verification with public key of kty ${d} is not supported by this method`)}function oq(e){let t=e.replace("-----BEGIN CERTIFICATE-----","").replace("-----END CERTIFICATE-----","").replace(/[\n ]/g,"");return Mu(t,"base64")}var iq=`-----BEGIN CERTIFICATE-----
|
|
224
|
+
MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG
|
|
225
|
+
A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv
|
|
226
|
+
b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw
|
|
227
|
+
MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i
|
|
228
|
+
YWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxT
|
|
229
|
+
aWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZ
|
|
230
|
+
jc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavp
|
|
231
|
+
xy0Sy6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp
|
|
232
|
+
1Wrjsok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdG
|
|
233
|
+
snUOhugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJ
|
|
234
|
+
U26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N8
|
|
235
|
+
9iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E
|
|
236
|
+
BTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0B
|
|
237
|
+
AQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOz
|
|
238
|
+
yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE
|
|
239
|
+
38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP
|
|
240
|
+
AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad
|
|
241
|
+
DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME
|
|
242
|
+
HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==
|
|
243
|
+
-----END CERTIFICATE-----
|
|
244
|
+
`;var sq=`-----BEGIN CERTIFICATE-----
|
|
245
|
+
MIIFYDCCA0igAwIBAgIJAOj6GWMU0voYMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV
|
|
246
|
+
BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMTYwNTI2MTYyODUyWhcNMjYwNTI0MTYy
|
|
247
|
+
ODUyWjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B
|
|
248
|
+
AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS
|
|
249
|
+
Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7
|
|
250
|
+
tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj
|
|
251
|
+
nar86461qO0rOs2cXjp3kOG1FEJ5MVmFmBGtnrKpa73XpXyTqRxB/M0n1n/W9nGq
|
|
252
|
+
C4FSYa04T6N5RIZGBN2z2MT5IKGbFlbC8UrW0DxW7AYImQQcHtGl/m00QLVWutHQ
|
|
253
|
+
oVJYnFPlXTcHYvASLu+RhhsbDmxMgJJ0mcDpvsC4PjvB+TxywElgS70vE0XmLD+O
|
|
254
|
+
JtvsBslHZvPBKCOdT0MS+tgSOIfga+z1Z1g7+DVagf7quvmag8jfPioyKvxnK/Eg
|
|
255
|
+
sTUVi2ghzq8wm27ud/mIM7AY2qEORR8Go3TVB4HzWQgpZrt3i5MIlCaY504LzSRi
|
|
256
|
+
igHCzAPlHws+W0rB5N+er5/2pJKnfBSDiCiFAVtCLOZ7gLiMm0jhO2B6tUXHI/+M
|
|
257
|
+
RPjy02i59lINMRRev56GKtcd9qO/0kUJWdZTdA2XoS82ixPvZtXQpUpuL12ab+9E
|
|
258
|
+
aDK8Z4RHJYYfCT3Q5vNAXaiWQ+8PTWm2QgBR/bkwSWc+NpUFgNPN9PvQi8WEg5Um
|
|
259
|
+
AGMCAwEAAaOBpjCBozAdBgNVHQ4EFgQUNmHhAHyIBQlRi0RsR/8aTMnqTxIwHwYD
|
|
260
|
+
VR0jBBgwFoAUNmHhAHyIBQlRi0RsR/8aTMnqTxIwDwYDVR0TAQH/BAUwAwEB/zAO
|
|
261
|
+
BgNVHQ8BAf8EBAMCAYYwQAYDVR0fBDkwNzA1oDOgMYYvaHR0cHM6Ly9hbmRyb2lk
|
|
262
|
+
Lmdvb2dsZWFwaXMuY29tL2F0dGVzdGF0aW9uL2NybC8wDQYJKoZIhvcNAQELBQAD
|
|
263
|
+
ggIBACDIw41L3KlXG0aMiS//cqrG+EShHUGo8HNsw30W1kJtjn6UBwRM6jnmiwfB
|
|
264
|
+
Pb8VA91chb2vssAtX2zbTvqBJ9+LBPGCdw/E53Rbf86qhxKaiAHOjpvAy5Y3m00m
|
|
265
|
+
qC0w/Zwvju1twb4vhLaJ5NkUJYsUS7rmJKHHBnETLi8GFqiEsqTWpG/6ibYCv7rY
|
|
266
|
+
DBJDcR9W62BW9jfIoBQcxUCUJouMPH25lLNcDc1ssqvC2v7iUgI9LeoM1sNovqPm
|
|
267
|
+
QUiG9rHli1vXxzCyaMTjwftkJLkf6724DFhuKug2jITV0QkXvaJWF4nUaHOTNA4u
|
|
268
|
+
JU9WDvZLI1j83A+/xnAJUucIv/zGJ1AMH2boHqF8CY16LpsYgBt6tKxxWH00XcyD
|
|
269
|
+
CdW2KlBCeqbQPcsFmWyWugxdcekhYsAWyoSf818NUsZdBWBaR/OukXrNLfkQ79Iy
|
|
270
|
+
ZohZbvabO/X+MVT3rriAoKc8oE2Uws6DF+60PV7/WIPjNvXySdqspImSN78mflxD
|
|
271
|
+
qwLqRBYkA3I75qppLGG9rp7UCdRjxMl8ZDBld+7yvHVgt1cVzJx9xnyGCC23Uaic
|
|
272
|
+
MDSXYrB4I4WHXPGjxhZuCuPBLTdOLU8YRvMYdEvYebWHMpvwGCF6bAx3JBpIeOQ1
|
|
273
|
+
wDB5y0USicV3YgYGmi+NZfhA4URSh77Yd6uuJOJENRaNVTzk
|
|
274
|
+
-----END CERTIFICATE-----
|
|
275
|
+
`,aq=`-----BEGIN CERTIFICATE-----
|
|
276
|
+
MIIFHDCCAwSgAwIBAgIJANUP8luj8tazMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV
|
|
277
|
+
BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMTkxMTIyMjAzNzU4WhcNMzQxMTE4MjAz
|
|
278
|
+
NzU4WjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B
|
|
279
|
+
AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS
|
|
280
|
+
Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7
|
|
281
|
+
tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj
|
|
282
|
+
nar86461qO0rOs2cXjp3kOG1FEJ5MVmFmBGtnrKpa73XpXyTqRxB/M0n1n/W9nGq
|
|
283
|
+
C4FSYa04T6N5RIZGBN2z2MT5IKGbFlbC8UrW0DxW7AYImQQcHtGl/m00QLVWutHQ
|
|
284
|
+
oVJYnFPlXTcHYvASLu+RhhsbDmxMgJJ0mcDpvsC4PjvB+TxywElgS70vE0XmLD+O
|
|
285
|
+
JtvsBslHZvPBKCOdT0MS+tgSOIfga+z1Z1g7+DVagf7quvmag8jfPioyKvxnK/Eg
|
|
286
|
+
sTUVi2ghzq8wm27ud/mIM7AY2qEORR8Go3TVB4HzWQgpZrt3i5MIlCaY504LzSRi
|
|
287
|
+
igHCzAPlHws+W0rB5N+er5/2pJKnfBSDiCiFAVtCLOZ7gLiMm0jhO2B6tUXHI/+M
|
|
288
|
+
RPjy02i59lINMRRev56GKtcd9qO/0kUJWdZTdA2XoS82ixPvZtXQpUpuL12ab+9E
|
|
289
|
+
aDK8Z4RHJYYfCT3Q5vNAXaiWQ+8PTWm2QgBR/bkwSWc+NpUFgNPN9PvQi8WEg5Um
|
|
290
|
+
AGMCAwEAAaNjMGEwHQYDVR0OBBYEFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMB8GA1Ud
|
|
291
|
+
IwQYMBaAFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMA8GA1UdEwEB/wQFMAMBAf8wDgYD
|
|
292
|
+
VR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4ICAQBOMaBc8oumXb2voc7XCWnu
|
|
293
|
+
XKhBBK3e2KMGz39t7lA3XXRe2ZLLAkLM5y3J7tURkf5a1SutfdOyXAmeE6SRo83U
|
|
294
|
+
h6WszodmMkxK5GM4JGrnt4pBisu5igXEydaW7qq2CdC6DOGjG+mEkN8/TA6p3cno
|
|
295
|
+
L/sPyz6evdjLlSeJ8rFBH6xWyIZCbrcpYEJzXaUOEaxxXxgYz5/cTiVKN2M1G2ok
|
|
296
|
+
QBUIYSY6bjEL4aUN5cfo7ogP3UvliEo3Eo0YgwuzR2v0KR6C1cZqZJSTnghIC/vA
|
|
297
|
+
D32KdNQ+c3N+vl2OTsUVMC1GiWkngNx1OO1+kXW+YTnnTUOtOIswUP/Vqd5SYgAI
|
|
298
|
+
mMAfY8U9/iIgkQj6T2W6FsScy94IN9fFhE1UtzmLoBIuUFsVXJMTz+Jucth+IqoW
|
|
299
|
+
Fua9v1R93/k98p41pjtFX+H8DslVgfP097vju4KDlqN64xV1grw3ZLl4CiOe/A91
|
|
300
|
+
oeLm2UHOq6wn3esB4r2EIQKb6jTVGu5sYCcdWpXr0AUVqcABPdgL+H7qJguBw09o
|
|
301
|
+
jm6xNIrw2OocrDKsudk/okr/AwqEyPKw9WnMlQgLIKw1rODG2NvU9oR3GVGdMkUB
|
|
302
|
+
ZutL8VuFkERQGt6vQ2OCw0sV47VMkuYbacK/xyZFiRcrPJPb41zgbQj9XAEyLKCH
|
|
303
|
+
ex0SdDrx+tWUDqG8At2JHA==
|
|
304
|
+
-----END CERTIFICATE-----
|
|
305
|
+
`,cq=`
|
|
306
|
+
-----BEGIN CERTIFICATE-----
|
|
307
|
+
MIIFHDCCAwSgAwIBAgIJAMNrfES5rhgxMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV
|
|
308
|
+
BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMjExMTE3MjMxMDQyWhcNMzYxMTEzMjMx
|
|
309
|
+
MDQyWjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B
|
|
310
|
+
AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS
|
|
311
|
+
Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7
|
|
312
|
+
tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj
|
|
313
|
+
nar86461qO0rOs2cXjp3kOG1FEJ5MVmFmBGtnrKpa73XpXyTqRxB/M0n1n/W9nGq
|
|
314
|
+
C4FSYa04T6N5RIZGBN2z2MT5IKGbFlbC8UrW0DxW7AYImQQcHtGl/m00QLVWutHQ
|
|
315
|
+
oVJYnFPlXTcHYvASLu+RhhsbDmxMgJJ0mcDpvsC4PjvB+TxywElgS70vE0XmLD+O
|
|
316
|
+
JtvsBslHZvPBKCOdT0MS+tgSOIfga+z1Z1g7+DVagf7quvmag8jfPioyKvxnK/Eg
|
|
317
|
+
sTUVi2ghzq8wm27ud/mIM7AY2qEORR8Go3TVB4HzWQgpZrt3i5MIlCaY504LzSRi
|
|
318
|
+
igHCzAPlHws+W0rB5N+er5/2pJKnfBSDiCiFAVtCLOZ7gLiMm0jhO2B6tUXHI/+M
|
|
319
|
+
RPjy02i59lINMRRev56GKtcd9qO/0kUJWdZTdA2XoS82ixPvZtXQpUpuL12ab+9E
|
|
320
|
+
aDK8Z4RHJYYfCT3Q5vNAXaiWQ+8PTWm2QgBR/bkwSWc+NpUFgNPN9PvQi8WEg5Um
|
|
321
|
+
AGMCAwEAAaNjMGEwHQYDVR0OBBYEFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMB8GA1Ud
|
|
322
|
+
IwQYMBaAFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMA8GA1UdEwEB/wQFMAMBAf8wDgYD
|
|
323
|
+
VR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4ICAQBTNNZe5cuf8oiq+jV0itTG
|
|
324
|
+
zWVhSTjOBEk2FQvh11J3o3lna0o7rd8RFHnN00q4hi6TapFhh4qaw/iG6Xg+xOan
|
|
325
|
+
63niLWIC5GOPFgPeYXM9+nBb3zZzC8ABypYuCusWCmt6Tn3+Pjbz3MTVhRGXuT/T
|
|
326
|
+
QH4KGFY4PhvzAyXwdjTOCXID+aHud4RLcSySr0Fq/L+R8TWalvM1wJJPhyRjqRCJ
|
|
327
|
+
erGtfBagiALzvhnmY7U1qFcS0NCnKjoO7oFedKdWlZz0YAfu3aGCJd4KHT0MsGiL
|
|
328
|
+
Zez9WP81xYSrKMNEsDK+zK5fVzw6jA7cxmpXcARTnmAuGUeI7VVDhDzKeVOctf3a
|
|
329
|
+
0qQLwC+d0+xrETZ4r2fRGNw2YEs2W8Qj6oDcfPvq9JySe7pJ6wcHnl5EZ0lwc4xH
|
|
330
|
+
7Y4Dx9RA1JlfooLMw3tOdJZH0enxPXaydfAD3YifeZpFaUzicHeLzVJLt9dvGB0b
|
|
331
|
+
HQLE4+EqKFgOZv2EoP686DQqbVS1u+9k0p2xbMA105TBIk7npraa8VM0fnrRKi7w
|
|
332
|
+
lZKwdH+aNAyhbXRW9xsnODJ+g8eF452zvbiKKngEKirK5LGieoXBX7tZ9D1GNBH2
|
|
333
|
+
Ob3bKOwwIWdEFle/YF/h6zWgdeoaNGDqVBrLr2+0DtWoiB1aDEjLWl9FmyIUyUm7
|
|
334
|
+
mD/vFDkzF+wm7cyWpQpCVQ==
|
|
335
|
+
-----END CERTIFICATE-----
|
|
336
|
+
`,lq=`
|
|
337
|
+
-----BEGIN CERTIFICATE-----
|
|
338
|
+
MIIFHDCCAwSgAwIBAgIJAPHBcqaZ6vUdMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV
|
|
339
|
+
BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMjIwMzIwMTgwNzQ4WhcNNDIwMzE1MTgw
|
|
340
|
+
NzQ4WjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B
|
|
341
|
+
AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS
|
|
342
|
+
Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7
|
|
343
|
+
tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj
|
|
344
|
+
nar86461qO0rOs2cXjp3kOG1FEJ5MVmFmBGtnrKpa73XpXyTqRxB/M0n1n/W9nGq
|
|
345
|
+
C4FSYa04T6N5RIZGBN2z2MT5IKGbFlbC8UrW0DxW7AYImQQcHtGl/m00QLVWutHQ
|
|
346
|
+
oVJYnFPlXTcHYvASLu+RhhsbDmxMgJJ0mcDpvsC4PjvB+TxywElgS70vE0XmLD+O
|
|
347
|
+
JtvsBslHZvPBKCOdT0MS+tgSOIfga+z1Z1g7+DVagf7quvmag8jfPioyKvxnK/Eg
|
|
348
|
+
sTUVi2ghzq8wm27ud/mIM7AY2qEORR8Go3TVB4HzWQgpZrt3i5MIlCaY504LzSRi
|
|
349
|
+
igHCzAPlHws+W0rB5N+er5/2pJKnfBSDiCiFAVtCLOZ7gLiMm0jhO2B6tUXHI/+M
|
|
350
|
+
RPjy02i59lINMRRev56GKtcd9qO/0kUJWdZTdA2XoS82ixPvZtXQpUpuL12ab+9E
|
|
351
|
+
aDK8Z4RHJYYfCT3Q5vNAXaiWQ+8PTWm2QgBR/bkwSWc+NpUFgNPN9PvQi8WEg5Um
|
|
352
|
+
AGMCAwEAAaNjMGEwHQYDVR0OBBYEFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMB8GA1Ud
|
|
353
|
+
IwQYMBaAFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMA8GA1UdEwEB/wQFMAMBAf8wDgYD
|
|
354
|
+
VR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4ICAQB8cMqTllHc8U+qCrOlg3H7
|
|
355
|
+
174lmaCsbo/bJ0C17JEgMLb4kvrqsXZs01U3mB/qABg/1t5Pd5AORHARs1hhqGIC
|
|
356
|
+
W/nKMav574f9rZN4PC2ZlufGXb7sIdJpGiO9ctRhiLuYuly10JccUZGEHpHSYM2G
|
|
357
|
+
tkgYbZba6lsCPYAAP83cyDV+1aOkTf1RCp/lM0PKvmxYN10RYsK631jrleGdcdkx
|
|
358
|
+
oSK//mSQbgcWnmAEZrzHoF1/0gso1HZgIn0YLzVhLSA/iXCX4QT2h3J5z3znluKG
|
|
359
|
+
1nv8NQdxei2DIIhASWfu804CA96cQKTTlaae2fweqXjdN1/v2nqOhngNyz1361mF
|
|
360
|
+
mr4XmaKH/ItTwOe72NI9ZcwS1lVaCvsIkTDCEXdm9rCNPAY10iTunIHFXRh+7KPz
|
|
361
|
+
lHGewCq/8TOohBRn0/NNfh7uRslOSZ/xKbN9tMBtw37Z8d2vvnXq/YWdsm1+JLVw
|
|
362
|
+
n6yYD/yacNJBlwpddla8eaVMjsF6nBnIgQOf9zKSe06nSTqvgwUHosgOECZJZ1Eu
|
|
363
|
+
zbH4yswbt02tKtKEFhx+v+OTge/06V+jGsqTWLsfrOCNLuA8H++z+pUENmpqnnHo
|
|
364
|
+
vaI47gC+TNpkgYGkkBT6B/m/U01BuOBBTzhIlMEZq9qkDWuM2cA5kW5V3FJUcfHn
|
|
365
|
+
w1IdYIg2Wxg7yHcQZemFQg==
|
|
366
|
+
-----END CERTIFICATE-----
|
|
367
|
+
`;var dq=`-----BEGIN CERTIFICATE-----
|
|
368
|
+
MIICEjCCAZmgAwIBAgIQaB0BbHo84wIlpQGUKEdXcTAKBggqhkjOPQQDAzBLMR8w
|
|
369
|
+
HQYDVQQDDBZBcHBsZSBXZWJBdXRobiBSb290IENBMRMwEQYDVQQKDApBcHBsZSBJ
|
|
370
|
+
bmMuMRMwEQYDVQQIDApDYWxpZm9ybmlhMB4XDTIwMDMxODE4MjEzMloXDTQ1MDMx
|
|
371
|
+
NTAwMDAwMFowSzEfMB0GA1UEAwwWQXBwbGUgV2ViQXV0aG4gUm9vdCBDQTETMBEG
|
|
372
|
+
A1UECgwKQXBwbGUgSW5jLjETMBEGA1UECAwKQ2FsaWZvcm5pYTB2MBAGByqGSM49
|
|
373
|
+
AgEGBSuBBAAiA2IABCJCQ2pTVhzjl4Wo6IhHtMSAzO2cv+H9DQKev3//fG59G11k
|
|
374
|
+
xu9eI0/7o6V5uShBpe1u6l6mS19S1FEh6yGljnZAJ+2GNP1mi/YK2kSXIuTHjxA/
|
|
375
|
+
pcoRf7XkOtO4o1qlcaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUJtdk
|
|
376
|
+
2cV4wlpn0afeaxLQG2PxxtcwDgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2cA
|
|
377
|
+
MGQCMFrZ+9DsJ1PW9hfNdBywZDsWDbWFp28it1d/5w2RPkRX3Bbn/UbDTNLx7Jr3
|
|
378
|
+
jAGGiQIwHFj+dJZYUJR786osByBelJYsVZd2GbHQu209b5RCmGQ21gpSAk9QZW4B
|
|
379
|
+
1bWeT0vT
|
|
380
|
+
-----END CERTIFICATE-----
|
|
381
|
+
`;var uq=`-----BEGIN CERTIFICATE-----
|
|
382
|
+
MIIDXzCCAkegAwIBAgILBAAAAAABIVhTCKIwDQYJKoZIhvcNAQELBQAwTDEgMB4G
|
|
383
|
+
A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkdsb2JhbFNp
|
|
384
|
+
Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDkwMzE4MTAwMDAwWhcNMjkwMzE4
|
|
385
|
+
MTAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMzETMBEG
|
|
386
|
+
A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI
|
|
387
|
+
hvcNAQEBBQADggEPADCCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWtiHL8
|
|
388
|
+
RgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsT
|
|
389
|
+
gHeMCOFJ0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmm
|
|
390
|
+
KPZpO/bLyCiR5Z2KYVc3rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zd
|
|
391
|
+
QQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjlOCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZ
|
|
392
|
+
XriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2xmmFghcCAwEAAaNCMEAw
|
|
393
|
+
DgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI/wS3+o
|
|
394
|
+
LkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZU
|
|
395
|
+
RUm7lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMp
|
|
396
|
+
jjM5RcOO5LlXbKr8EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK
|
|
397
|
+
6fBdRoyV3XpYKBovHd7NADdBj+1EbddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQX
|
|
398
|
+
mcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18YIvDQVETI53O9zJrlAGomecs
|
|
399
|
+
Mx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7rkpeDMdmztcpH
|
|
400
|
+
WD9f
|
|
401
|
+
-----END CERTIFICATE-----
|
|
402
|
+
`,pq=`-----BEGIN CERTIFICATE-----
|
|
403
|
+
MIIFWjCCA0KgAwIBAgISEdK7udcjGJ5AXwqdLdDfJWfRMA0GCSqGSIb3DQEBDAUA
|
|
404
|
+
MEYxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRwwGgYD
|
|
405
|
+
VQQDExNHbG9iYWxTaWduIFJvb3QgUjQ2MB4XDTE5MDMyMDAwMDAwMFoXDTQ2MDMy
|
|
406
|
+
MDAwMDAwMFowRjELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYt
|
|
407
|
+
c2ExHDAaBgNVBAMTE0dsb2JhbFNpZ24gUm9vdCBSNDYwggIiMA0GCSqGSIb3DQEB
|
|
408
|
+
AQUAA4ICDwAwggIKAoICAQCsrHQy6LNl5brtQyYdpokNRbopiLKkHWPd08EsCVeJ
|
|
409
|
+
OaFV6Wc0dwxu5FUdUiXSE2te4R2pt32JMl8Nnp8semNgQB+msLZ4j5lUlghYruQG
|
|
410
|
+
vGIFAha/r6gjA7aUD7xubMLL1aa7DOn2wQL7Id5m3RerdELv8HQvJfTqa1VbkNud
|
|
411
|
+
316HCkD7rRlr+/fKYIje2sGP1q7Vf9Q8g+7XFkyDRTNrJ9CG0Bwta/OrffGFqfUo
|
|
412
|
+
0q3v84RLHIf8E6M6cqJaESvWJ3En7YEtbWaBkoe0G1h6zD8K+kZPTXhc+CtI4wSE
|
|
413
|
+
y132tGqzZfxCnlEmIyDLPRT5ge1lFgBPGmSXZgjPjHvjK8Cd+RTyG/FWaha/LIWF
|
|
414
|
+
zXg4mutCagI0GIMXTpRW+LaCtfOW3T3zvn8gdz57GSNrLNRyc0NXfeD412lPFzYE
|
|
415
|
+
+cCQYDdF3uYM2HSNrpyibXRdQr4G9dlkbgIQrImwTDsHTUB+JMWKmIJ5jqSngiCN
|
|
416
|
+
I/onccnfxkF0oE32kRbcRoxfKWMxWXEM2G/CtjJ9++ZdU6Z+Ffy7dXxd7Pj2Fxzs
|
|
417
|
+
x2sZy/N78CsHpdlseVR2bJ0cpm4O6XkMqCNqo98bMDGfsVR7/mrLZqrcZdCinkqa
|
|
418
|
+
ByFrgY/bxFn63iLABJzjqls2k+g9vXqhnQt2sQvHnf3PmKgGwvgqo6GDoLclcqUC
|
|
419
|
+
4wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNV
|
|
420
|
+
HQ4EFgQUA1yrc4GHqMywptWU4jaWSf8FmSwwDQYJKoZIhvcNAQEMBQADggIBAHx4
|
|
421
|
+
7PYCLLtbfpIrXTncvtgdokIzTfnvpCo7RGkerNlFo048p9gkUbJUHJNOxO97k4Vg
|
|
422
|
+
JuoJSOD1u8fpaNK7ajFxzHmuEajwmf3lH7wvqMxX63bEIaZHU1VNaL8FpO7XJqti
|
|
423
|
+
2kM3S+LGteWygxk6x9PbTZ4IevPuzz5i+6zoYMzRx6Fcg0XERczzF2sUyQQCPtIk
|
|
424
|
+
pnnpHs6i58FZFZ8d4kuaPp92CC1r2LpXFNqD6v6MVenQTqnMdzGxRBF6XLE+0xRF
|
|
425
|
+
FRhiJBPSy03OXIPBNvIQtQ6IbbjhVp+J3pZmOUdkLG5NrmJ7v2B0GbhWrJKsFjLt
|
|
426
|
+
rWhV/pi60zTe9Mlhww6G9kuEYO4Ne7UyWHmRVSyBQ7N0H3qqJZ4d16GLuc1CLgSk
|
|
427
|
+
ZoNNiTW2bKg2SnkheCLQQrzRQDGQob4Ez8pn7fXwgNNgyYMqIgXQBztSvwyeqiv5
|
|
428
|
+
u+YfjyW6hY0XHgL+XVAEV8/+LbzvXMAaq7afJMbfc2hIkCwU9D9SGuTSyxTDYWnP
|
|
429
|
+
4vkYxboznxSjBF25cfe1lNj2M8FawTSLfJvdkzrnE6JwYZ+vj+vYxXX4M2bUdGc6
|
|
430
|
+
N3ec592kD3ZDZopD8p/7DEJ4Y9HiD2971KE9dJeFt0g5QdYg/NA6s/rob8SKunE3
|
|
431
|
+
vouXsXgxT7PntgMTzlSdriVZzH81Xwj3QEUxeCp6
|
|
432
|
+
-----END CERTIFICATE-----
|
|
433
|
+
`;class fq{constructor(){Object.defineProperty(this,"pemCertificates",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.pemCertificates=new Map}setRootCertificates(e){let{identifier:t,certificates:r}=e,n=[];for(let o of r)if(o instanceof Uint8Array)n.push(fn(o));else n.push(o);this.pemCertificates.set(t,n)}getRootCertificates(e){let{identifier:t}=e;return this.pemCertificates.get(t)??[]}}var Kc=new fq;Kc.setRootCertificates({identifier:"android-key",certificates:[sq,aq,cq,lq]});Kc.setRootCertificates({identifier:"android-safetynet",certificates:[iq]});Kc.setRootCertificates({identifier:"apple",certificates:[dq]});Kc.setRootCertificates({identifier:"mds",certificates:[uq,pq]});async function mq(e){let t=tq(e),r=t[0],n=t[1],o=r.x5c.map(fn);try{let m=Kc.getRootCertificates({identifier:"mds"});await oo(o,m)}catch(m){throw Error("BLOB certificate path could not be validated",{cause:m})}let i=o[0];if(!await nq(e,oq(i)))throw Error("BLOB signature could not be verified");let a=[];for(let m of n.entries)if(m.aaguid&&m.metadataStatement)a.push(m.metadataStatement);let[c,l,d]=n.nextUpdate.split("-"),u=new Date(parseInt(c,10),parseInt(l,10)-1,parseInt(d,10));return{statements:a,parsedNextUpdate:u,payload:n}}async function yq(e){let{cosePublicKey:t,signature:r,data:n}=e,o=await Ai(),i=t.get(Ze.alg),s=t.get(Ze.crv),a=t.get(Ze.x);if(!i)throw Error("Public key was missing alg (OKP)");if(!Es(i))throw Error(`Public key had invalid alg ${i} (OKP)`);if(!s)throw Error("Public key was missing crv (OKP)");if(!a)throw Error("Public key was missing x (OKP)");let c;if(s===Zn.ED25519)c="Ed25519";else throw Error(`Unexpected COSE crv value of ${s} (OKP)`);let l={kty:"OKP",crv:c,alg:"EdDSA",x:ws(a),ext:!1},u=await Wu({keyData:l,algorithm:{name:c,namedCurve:c}}),m={name:c};return o.subtle.verify(m,u,r,n)}function gq(e,t){let r=Ir.parse(e,Uc),n=new Uint8Array(r.r),o=new Uint8Array(r.s),i=gX(t),s=hq(n,i),a=hq(o,i);return Pi([s,a])}function gX(e){switch(e){case Zn.P256:return 32;case Zn.P384:return 48;case Zn.P521:return 66;default:throw Error(`Unexpected COSE crv value of ${e} (EC2)`)}}function hq(e,t){let r;if(e.length<t)r=new Uint8Array(t),r.set(e,t-e.length);else if(e.length===t)r=e;else if(e.length===t+1&&e[0]===0&&(e[1]&128)===128)r=e.subarray(1);else throw Error(`Invalid signature component length ${e.length}, expected ${t}`);return r}function eq(e){let{cosePublicKey:t,signature:r,data:n,shaHashOverride:o}=e;if(xc(t)){let s=t.get(Ze.crv);if(!yB(s))throw Error(`unknown COSE curve ${s}`);let a=gq(r,s);return Bv({cosePublicKey:t,signature:a,data:n,shaHashOverride:o})}else if(Hu(t))return Mv({cosePublicKey:t,signature:r,data:n,shaHashOverride:o});else if(mB(t))return yq({cosePublicKey:t,signature:r,data:n});let i=t.get(Ze.kty);throw Error(`Signature verification with public key of kty ${i} is not supported by this method`)}function as(e,t){if(e.length!=t.length)return!1;return e.every((r,n)=>r===t[n])}function $v(e){return Array.from(e,(r)=>r.toString(16).padStart(2,"0")).join("")}function yX(e){if(!e)return Uint8Array.from([]);if(!(e.length!==0&&e.length%2===0&&!/[^a-fA-F0-9]/u.test(e)))throw Error("Invalid hex string");let r=e.match(/.{1,2}/g)??[];return Uint8Array.from(r.map((n)=>parseInt(n,16)))}function Pi(e){let t=0,r=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(r);return e.forEach((o)=>{n.set(o,t),t+=o.length}),n}function SX(e){return new globalThis.TextDecoder("utf-8").decode(e)}function aw(e){return new globalThis.TextEncoder().encode(e)}function vX(e){return Uint8Array.from(e.split("").map((t)=>t.charCodeAt(0)))}function sw(e){return new DataView(e.buffer,e.byteOffset,e.length)}async function vI(){let e=new Uint8Array(32);return await AR(e),xX.stubThis(e)}var xX={stubThis:(e)=>e};var Sq=[-8,-7,-36,-37,-38,-39,-257,-258,-259,-65535],wX={residentKey:"preferred",userVerification:"preferred"},bX=[-8,-7,-257];async function vq(e){let{rpName:t,rpID:r,userName:n,userID:o,challenge:i=await vI(),userDisplayName:s="",timeout:a=60000,attestationType:c="none",excludeCredentials:l=[],authenticatorSelection:d=wX,extensions:u,supportedAlgorithmIDs:m=bX,preferredAuthenticatorType:h}=e,S=m.map((P)=>({alg:P,type:"public-key"}));if(d.residentKey===void 0){if(d.requireResidentKey)d.residentKey="required"}else d.requireResidentKey=d.residentKey==="required";let x=i;if(typeof x==="string")x=aw(x);if(typeof o==="string")throw Error("String values for `userID` are no longer supported. See https://simplewebauthn.dev/docs/advanced/server/custom-user-ids");let v=o;if(!v)v=await vB();let w=[];if(h){if(h==="securityKey")w.push("security-key"),d.authenticatorAttachment="cross-platform";else if(h==="localDevice")w.push("client-device"),d.authenticatorAttachment="platform";else if(h==="remoteDevice")w.push("hybrid"),d.authenticatorAttachment="cross-platform"}return{challenge:ws(x),rp:{name:t,id:r},user:{id:ws(v),name:n,displayName:s},pubKeyCredParams:S,timeout:a,attestation:c,excludeCredentials:l.map((P)=>{if(!cB(P.id))throw Error(`excludeCredential id "${P.id}" is not a valid base64url string`);return{...P,id:lB(P.id),type:"public-key"}}),authenticatorSelection:d,extensions:{...u,credProps:!0},hints:w}}function xI({be:e,bs:t}){let r=t,n="singleDevice";if(e)n="multiDevice";if(n==="singleDevice"&&r)throw new xq("Single-device credential indicated that it was backed up, which should be impossible.");return{credentialDeviceType:n,credentialBackedUp:r}}class xq extends Error{constructor(e){super(e);this.name="InvalidBackupFlags"}}async function wI(e,t){try{return await Promise.any(t.map((n)=>new Promise((o,i)=>{Fi(vX(n)).then((s)=>{if(as(e,s))o(n);else i()})})))}catch(r){if(r.name==="AggregateError")throw new wq;throw r}}class wq extends Error{constructor(){super("Unexpected RP ID hash");this.name="UnexpectedRPIDHash"}}async function bq(e){let{attStmt:t,clientDataHash:r,rpIdHash:n,credentialID:o,credentialPublicKey:i,aaguid:s,rootCertificates:a}=e,c=Uint8Array.from([0]),l=Ku(i),d=Pi([c,n,r,o,l]),u=t.get("sig"),m=t.get("x5c");if(!m)throw Error("No attestation certificate provided in attestation statement (FIDOU2F)");if(!u)throw Error("No attestation signature provided in attestation statement (FIDOU2F)");let h=Number.parseInt($v(s),16);if(h!==0)throw Error(`AAGUID "${h}" was not expected value`);try{await oo(m.map(fn),a)}catch(S){throw Error(`${S.message} (FIDOU2F)`)}return Ui({signature:u,data:d,x509Certificate:m[0],hashAlgorithm:tt.ES256})}var Eq="1.3.6.1.4.1.45724.1.1.4";function lw(e,t){if(!e)return!0;let r=e.find((s)=>s.extnID===Eq);if(!r)return!0;let n=Ir.parse(r.extnValue,ae),o=new Uint8Array(n.buffer);if(!as(t,o)){let s=$v(o),a=$v(t);throw Error(`Certificate extension id-fido-gen-ce-aaguid (${Eq}) value of "${s}" was present but not equal to attestation statement AAGUID value of "${a}"`)}return!0}function Tq(e){return(t,...r)=>{}}var EX={url:"",no:0,nextUpdate:new Date(0)},TX="https://mds.fidoalliance.org/",ai;(function(e){e[e.DISABLED=0]="DISABLED",e[e.REFRESHING=1]="REFRESHING",e[e.READY=2]="READY"})(ai||(ai={}));var bd=Tq("MetadataService");class Rq{constructor(){Object.defineProperty(this,"mdsCache",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"statementCache",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:ai.DISABLED}),Object.defineProperty(this,"verificationMode",{enumerable:!0,configurable:!0,writable:!0,value:"strict"})}async initialize(e={}){this.statementCache={};let{mdsServers:t=[TX],statements:r,verificationMode:n}=e;if(this.setState(ai.REFRESHING),r?.length){let o=0;r.forEach((i)=>{if(i.aaguid)this.statementCache[i.aaguid]={entry:{metadataStatement:i,statusReports:[],timeOfLastStatusChange:"1970-01-01"},url:EX.url},o+=1}),bd(`Cached ${o} local statements`)}if(t?.length){let o=Object.keys(this.statementCache).length,i=t.length;for(let c of t)try{let l={url:c,no:0,nextUpdate:new Date(0)},d=await this.downloadBlob(l);await this.verifyBlob(d,l)}catch(l){bd(`Could not download BLOB from ${c}:`,l),i-=1}let a=Object.keys(this.statementCache).length-o;bd(`Cached ${a} statements from ${i} metadata server(s)`)}if(n)this.verificationMode=n;this.setState(ai.READY)}async getStatement(e){if(this.state===ai.DISABLED)return;if(!e)return;if(e instanceof Uint8Array)e=Lv(e);await this.pauseUntilReady();let t=this.statementCache[e];if(!t){if(this.verificationMode==="strict")throw Error(`No metadata statement found for aaguid "${e}"`);return}if(t.url){let n=this.mdsCache[t.url];if(new Date>n.nextUpdate)try{this.setState(ai.REFRESHING);let i=await this.downloadBlob(n);await this.verifyBlob(i,n)}finally{this.setState(ai.READY)}}let{entry:r}=t;for(let n of r.statusReports){let{status:o}=n;if(o==="USER_VERIFICATION_BYPASS"||o==="ATTESTATION_KEY_COMPROMISE"||o==="USER_KEY_REMOTE_COMPROMISE"||o==="USER_KEY_PHYSICAL_COMPROMISE")throw Error(`Detected compromised aaguid "${e}"`)}return r.metadataStatement}async downloadBlob(e){let{url:t}=e;return await(await iw(t)).text()}async verifyBlob(e,t){let{url:r,no:n}=t,{payload:o,parsedNextUpdate:i}=await mq(e);if(o.no<=n)throw Error(`Latest BLOB no. ${o.no} is not greater than previous no. ${n}`);for(let s of o.entries)if(s.aaguid)this.statementCache[s.aaguid]={entry:s,url:r};if(r)this.mdsCache[r]={...t,no:o.no,nextUpdate:i};else if(i<new Date)bd(`\u26A0\uFE0F This MDS blob (serial: ${o.no}) contains stale data as of ${i.toISOString()}. Please consider re-initializing MetadataService with a newer MDS blob.`)}pauseUntilReady(){if(this.state===ai.READY)return new Promise((t)=>{t()});return new Promise((t,r)=>{let i=700,s=globalThis.setInterval(()=>{if(i<1)clearInterval(s),r("State did not become ready in 70 seconds");else if(this.state===ai.READY)clearInterval(s),t();i-=1},100)})}setState(e){if(this.state=e,e===ai.DISABLED)bd("MetadataService is DISABLED");else if(e===ai.REFRESHING)bd("MetadataService is REFRESHING");else if(e===ai.READY)bd("MetadataService is READY")}}var Vc=new Rq;async function Qc({statement:e,credentialPublicKey:t,x5c:r,attestationStatementAlg:n}){let{authenticationAlgorithms:o,authenticatorGetInfo:i,attestationRootCertificates:s}=e,a=new Set;o.forEach((v)=>{let w=Aq[v];if(w)a.add(w)});let c=bc(t),l=c.get(Ze.kty),d=c.get(Ze.alg);if(!l)throw Error("Credential public key was missing kty");if(!d)throw Error("Credential public key was missing alg");if(!l)throw Error("Credential public key was missing kty");let u={kty:l,alg:d};if(xc(c)){let v=c.get(Ze.crv);u.crv=v}let m=!1;for(let v of a){if(v.alg===u.alg&&v.kty===u.kty)if((v.kty===ti.EC2||v.kty===ti.OKP)&&v.crv===u.crv)m=!0;else m=!0;if(m)break}if(!m){let v=o.map((F)=>`'${F}' (COSE info: ${Pq(Aq[F])})`),w=JSON.stringify(v,null,2).replace(/"/g,""),P=Pq(u);throw Error(`Public key parameters ${P} did not match any of the following metadata algorithms:
|
|
434
|
+
${w}`)}if(n!==void 0&&i?.algorithms!==void 0){let v=i.algorithms.map((w)=>w.alg);if(v.indexOf(n)<0)throw Error(`Attestation statement alg ${n} did not match one of ${v}`)}let h=r.map(fn),S=s.map(fn),x=!1;if(h.length===1&&S.indexOf(h[0])>=0)x=!0;if(!x)try{await oo(h,S)}catch(v){throw Error(`Could not validate certificate path with any metadata root certificates: ${v.message}`)}return!0}var Aq={secp256r1_ecdsa_sha256_raw:{kty:2,alg:-7,crv:1},secp256r1_ecdsa_sha256_der:{kty:2,alg:-7,crv:1},rsassa_pss_sha256_raw:{kty:3,alg:-37},rsassa_pss_sha256_der:{kty:3,alg:-37},secp256k1_ecdsa_sha256_raw:{kty:2,alg:-47,crv:8},secp256k1_ecdsa_sha256_der:{kty:2,alg:-47,crv:8},rsassa_pss_sha384_raw:{kty:3,alg:-38},rsassa_pkcsv15_sha256_raw:{kty:3,alg:-257},rsassa_pkcsv15_sha384_raw:{kty:3,alg:-258},rsassa_pkcsv15_sha512_raw:{kty:3,alg:-259},rsassa_pkcsv15_sha1_raw:{kty:3,alg:-65535},secp384r1_ecdsa_sha384_raw:{kty:2,alg:-35,crv:2},secp512r1_ecdsa_sha256_raw:{kty:2,alg:-36,crv:3},ed25519_eddsa_sha512_raw:{kty:1,alg:-8,crv:6}};function Pq(e){let{kty:t,alg:r,crv:n}=e,o="";if(t!==ti.RSA)o=`{ kty: ${t}, alg: ${r}, crv: ${n} }`;else o=`{ kty: ${t}, alg: ${r} }`;return o}async function Iq(e){let{attStmt:t,clientDataHash:r,authData:n,credentialPublicKey:o,aaguid:i,rootCertificates:s}=e,a=t.get("sig"),c=t.get("x5c"),l=t.get("alg");if(!a)throw Error("No attestation signature provided in attestation statement (Packed)");if(!l)throw Error("Attestation statement did not contain alg (Packed)");if(!Es(l))throw Error(`Attestation statement contained invalid alg ${l} (Packed)`);let d=Pi([n,r]),u=!1;if(c){let{subject:m,basicConstraintsCA:h,version:S,notBefore:x,notAfter:v,parsedCertificate:w}=xp(c[0]),{OU:P,CN:F,O:R,C:b}=m;if(P!=="Authenticator Attestation")throw Error('Certificate OU was not "Authenticator Attestation" (Packed|Full)');if(!F)throw Error("Certificate CN was empty (Packed|Full)");if(!R)throw Error("Certificate O was empty (Packed|Full)");if(!b||b.length!==2)throw Error("Certificate C was not two-character ISO 3166 code (Packed|Full)");if(h)throw Error("Certificate basic constraints CA was not `false` (Packed|Full)");if(S!==2)throw Error("Certificate version was not `3` (ASN.1 value of 2) (Packed|Full)");let A=new Date;if(x>A)throw Error(`Certificate not good before "${x.toString()}" (Packed|Full)`);if(A=new Date,v<A)throw Error(`Certificate not good after "${v.toString()}" (Packed|Full)`);try{await lw(w.tbsCertificate.extensions,i)}catch(B){throw Error(`${B.message} (Packed|Full)`)}let D=await Vc.getStatement(i);if(D){if(D.attestationTypes.indexOf("basic_full")<0)throw Error("Metadata does not indicate support for full attestations (Packed|Full)");try{await Qc({statement:D,credentialPublicKey:o,x5c:c,attestationStatementAlg:l})}catch(B){throw Error(`${B.message} (Packed|Full)`)}}else try{await oo(c.map(fn),s)}catch(B){throw Error(`${B.message} (Packed|Full)`)}u=await Ui({signature:a,data:d,x509Certificate:c[0],hashAlgorithm:l})}else u=await Ui({signature:a,data:d,credentialPublicKey:o,hashAlgorithm:l});return u}async function Cq(e){let{attStmt:t,clientDataHash:r,authData:n,aaguid:o,rootCertificates:i,verifyTimestampMS:s=!0,credentialPublicKey:a,attestationSafetyNetEnforceCTSCheck:c}=e,l=t.get("alg"),d=t.get("response");if(!t.get("ver"))throw Error("No ver value in attestation (SafetyNet)");if(!d)throw Error("No response was included in attStmt by authenticator (SafetyNet)");let h=SX(d).split("."),S=JSON.parse(Lu(h[0])),x=JSON.parse(Lu(h[1])),v=h[2],{nonce:w,ctsProfileMatch:P,timestampMs:F}=x;if(s){let se=Date.now();if(F>Date.now())throw Error(`Payload timestamp "${F}" was later than "${se}" (SafetyNet)`);let te=F+60000;if(se=Date.now(),te<se)throw Error(`Payload timestamp "${te}" has expired (SafetyNet)`)}let R=Pi([n,r]),b=await Fi(R),A=ws(b,"base64");if(w!==A)throw Error("Could not verify payload nonce (SafetyNet)");if(c&&!P)throw Error("Could not verify device integrity (SafetyNet)");let D=Mu(S.x5c[0],"base64"),B=xp(D),{subject:J}=B;if(J.CN!=="attest.android.com")throw Error('Certificate common name was not "attest.android.com" (SafetyNet)');let G=await Vc.getStatement(o);if(G)try{await Qc({statement:G,credentialPublicKey:a,x5c:S.x5c,attestationStatementAlg:l})}catch(se){throw Error(`${se.message} (SafetyNet)`)}else try{await oo(S.x5c.map(fn),i)}catch(se){throw Error(`${se.message} (SafetyNet)`)}let ce=aw(`${h[0]}.${h[1]}`),re=Mu(v);return await Ui({signature:re,data:ce,x509Certificate:D,hashAlgorithm:l})}var _q={196:"TPM_ST_RSP_COMMAND",32768:"TPM_ST_NULL",32769:"TPM_ST_NO_SESSIONS",32770:"TPM_ST_SESSIONS",32788:"TPM_ST_ATTEST_NV",32789:"TPM_ST_ATTEST_COMMAND_AUDIT",32790:"TPM_ST_ATTEST_SESSION_AUDIT",32791:"TPM_ST_ATTEST_CERTIFY",32792:"TPM_ST_ATTEST_QUOTE",32793:"TPM_ST_ATTEST_TIME",32794:"TPM_ST_ATTEST_CREATION",32801:"TPM_ST_CREATION",32802:"TPM_ST_VERIFIED",32803:"TPM_ST_AUTH_SECRET",32804:"TPM_ST_HASHCHECK",32805:"TPM_ST_AUTH_SIGNED",32809:"TPM_ST_FU_MANIFEST"},Ms={0:"TPM_ALG_ERROR",1:"TPM_ALG_RSA",4:"TPM_ALG_SHA",4:"TPM_ALG_SHA1",5:"TPM_ALG_HMAC",6:"TPM_ALG_AES",7:"TPM_ALG_MGF1",8:"TPM_ALG_KEYEDHASH",10:"TPM_ALG_XOR",11:"TPM_ALG_SHA256",12:"TPM_ALG_SHA384",13:"TPM_ALG_SHA512",16:"TPM_ALG_NULL",18:"TPM_ALG_SM3_256",19:"TPM_ALG_SM4",20:"TPM_ALG_RSASSA",21:"TPM_ALG_RSAES",22:"TPM_ALG_RSAPSS",23:"TPM_ALG_OAEP",24:"TPM_ALG_ECDSA",25:"TPM_ALG_ECDH",26:"TPM_ALG_ECDAA",27:"TPM_ALG_SM2",28:"TPM_ALG_ECSCHNORR",29:"TPM_ALG_ECMQV",32:"TPM_ALG_KDF1_SP800_56A",33:"TPM_ALG_KDF2",34:"TPM_ALG_KDF1_SP800_108",35:"TPM_ALG_ECC",37:"TPM_ALG_SYMCIPHER",38:"TPM_ALG_CAMELLIA",64:"TPM_ALG_CTR",65:"TPM_ALG_OFB",66:"TPM_ALG_CBC",67:"TPM_ALG_CFB",68:"TPM_ALG_ECB"},kq={0:"TPM_ECC_NONE",1:"TPM_ECC_NIST_P192",2:"TPM_ECC_NIST_P224",3:"TPM_ECC_NIST_P256",4:"TPM_ECC_NIST_P384",5:"TPM_ECC_NIST_P521",16:"TPM_ECC_BN_P256",17:"TPM_ECC_BN_P638",32:"TPM_ECC_SM2_P256"},Oq={"id:414D4400":{name:"AMD",id:"AMD"},"id:414E5400":{name:"Ant Group",id:"ANT"},"id:41544D4C":{name:"Atmel",id:"ATML"},"id:4252434D":{name:"Broadcom",id:"BRCM"},"id:4353434F":{name:"Cisco",id:"CSCO"},"id:464C5953":{name:"Flyslice Technologies",id:"FLYS"},"id:524F4343":{name:"Fuzhou Rockchip",id:"ROCC"},"id:474F4F47":{name:"Google",id:"GOOG"},"id:48504900":{name:"HPI",id:"HPI"},"id:48504500":{name:"HPE",id:"HPE"},"id:48495349":{name:"Huawei",id:"HISI"},"id:49424d00":{name:"IBM",id:"IBM"},"id:49424D00":{name:"IBM",id:"IBM"},"id:49465800":{name:"Infineon",id:"IFX"},"id:494E5443":{name:"Intel",id:"INTC"},"id:4C454E00":{name:"Lenovo",id:"LEN"},"id:4D534654":{name:"Microsoft",id:"MSFT"},"id:4E534D20":{name:"National Semiconductor",id:"NSM"},"id:4E545A00":{name:"Nationz",id:"NTZ"},"id:4E534700":{name:"NSING",id:"NSG"},"id:4E544300":{name:"Nuvoton Technology",id:"NTC"},"id:51434F4D":{name:"Qualcomm",id:"QCOM"},"id:534D534E":{name:"Samsung",id:"SMSN"},"id:53454345":{name:"SecEdge",id:"SECE"},"id:534E5300":{name:"Sinosun",id:"SNS"},"id:534D5343":{name:"SMSC",id:"SMSC"},"id:53544D20":{name:"STMicroelectronics",id:"STM"},"id:54584E00":{name:"Texas Instruments",id:"TXN"},"id:57454300":{name:"Winbond",id:"WEC"},"id:5345414C":{name:"Wisekey",id:"SEAL"},"id:FFFFF1D0":{name:"FIDO Alliance",id:"FIDO"}},Dq={TPM_ECC_NIST_P256:1,TPM_ECC_NIST_P384:2,TPM_ECC_NIST_P521:3,TPM_ECC_BN_P256:1,TPM_ECC_SM2_P256:1};function Nq(e){let t=0,r=sw(e),n=r.getUint32(t);t+=4;let o=r.getUint16(t);t+=2;let i=_q[o],s=r.getUint16(t);t+=2;let a=e.slice(t,t+=s),c=r.getUint16(t);t+=2;let l=e.slice(t,t+=c),d=e.slice(t,t+=8),u=r.getUint32(t);t+=4;let m=r.getUint32(t);t+=4;let h=!!e.slice(t,t+=1),S={clock:d,resetCount:u,restartCount:m,safe:h},x=e.slice(t,t+=8),v=r.getUint16(t);t+=2;let w=e.slice(t,t+=v),P=sw(w),F=r.getUint16(t);t+=2;let R=e.slice(t,t+=F),b={nameAlg:Ms[P.getUint16(0)],nameAlgBuffer:w.slice(0,2),name:w,qualifiedName:R};return{magic:n,type:i,qualifiedSigner:a,extraData:l,clockInfo:S,firmwareVersion:x,attested:b}}function Fq(e){let t=0,r=sw(e),n=Ms[r.getUint16(t)];t+=2;let o=Ms[r.getUint16(t)];t+=2;let i=r.getUint32(t);t+=4;let s={fixedTPM:!!(i&1),stClear:!!(i&2),fixedParent:!!(i&8),sensitiveDataOrigin:!!(i&16),userWithAuth:!!(i&32),adminWithPolicy:!!(i&64),noDA:!!(i&512),encryptedDuplication:!!(i&1024),restricted:!!(i&32768),decrypt:!!(i&65536),signOrEncrypt:!!(i&131072)},a=r.getUint16(t);t+=2;let c=e.slice(t,t+=a),l={},d=Uint8Array.from([]);if(n==="TPM_ALG_RSA"){let u=Ms[r.getUint16(t)];t+=2;let m=Ms[r.getUint16(t)];t+=2;let h=r.getUint16(t);t+=2;let S=r.getUint32(t);t+=4,l.rsa={symmetric:u,scheme:m,keyBits:h,exponent:S};let x=r.getUint16(t);t+=2,d=e.slice(t,t+=x)}else if(n==="TPM_ALG_ECC"){let u=Ms[r.getUint16(t)];t+=2;let m=Ms[r.getUint16(t)];t+=2;let h=kq[r.getUint16(t)];t+=2;let S=Ms[r.getUint16(t)];t+=2,l.ecc={symmetric:u,scheme:m,curveID:h,kdf:S};let x=r.getUint16(t);t+=2;let v=e.slice(t,t+=x),w=r.getUint16(t);t+=2;let P=e.slice(t,t+=w);d=Pi([v,P])}else throw Error(`Unexpected type "${n}" (TPM)`);return{type:n,nameAlg:o,objectAttributes:s,authPolicy:c,parameters:l,unique:d}}async function Uq(e){let{aaguid:t,attStmt:r,authData:n,credentialPublicKey:o,clientDataHash:i,rootCertificates:s}=e,a=r.get("ver"),c=r.get("sig"),l=r.get("alg"),d=r.get("x5c"),u=r.get("pubArea"),m=r.get("certInfo");if(a!=="2.0")throw Error(`Unexpected ver "${a}", expected "2.0" (TPM)`);if(!c)throw Error("No attestation signature provided in attestation statement (TPM)");if(!l)throw Error("Attestation statement did not contain alg (TPM)");if(!Es(l))throw Error(`Attestation statement contained invalid alg ${l} (TPM)`);if(!d)throw Error("No attestation certificate provided in attestation statement (TPM)");if(!u)throw Error("Attestation statement did not contain pubArea (TPM)");if(!m)throw Error("Attestation statement did not contain certInfo (TPM)");let h=Fq(u),{unique:S,type:x,parameters:v}=h,w=bc(o);if(x==="TPM_ALG_RSA"){if(!Hu(w))throw Error(`Credential public key with kty ${w.get(Ze.kty)} did not match ${x}`);let Be=w.get(Ze.n),xr=w.get(Ze.e);if(!Be)throw Error("COSE public key missing n (TPM|RSA)");if(!xr)throw Error("COSE public key missing e (TPM|RSA)");if(!as(S,Be))throw Error("PubArea unique is not same as credentialPublicKey (TPM|RSA)");if(!v.rsa)throw Error("Parsed pubArea type is RSA, but missing parameters.rsa (TPM|RSA)");let uo=xr,Ve=v.rsa.exponent||65537,lt=uo[0]+(uo[1]<<8)+(uo[2]<<16);if(Ve!==lt)throw Error(`Unexpected public key exp ${lt}, expected ${Ve} (TPM|RSA)`)}else if(x==="TPM_ALG_ECC"){if(!xc(w))throw Error(`Credential public key with kty ${w.get(Ze.kty)} did not match ${x}`);let Be=w.get(Ze.crv),xr=w.get(Ze.x),uo=w.get(Ze.y);if(!Be)throw Error("COSE public key missing crv (TPM|ECC)");if(!xr)throw Error("COSE public key missing x (TPM|ECC)");if(!uo)throw Error("COSE public key missing y (TPM|ECC)");if(!as(S,Pi([xr,uo])))throw Error("PubArea unique is not same as public key x and y (TPM|ECC)");if(!v.ecc)throw Error("Parsed pubArea type is ECC, but missing parameters.ecc (TPM|ECC)");let Ve=v.ecc.curveID,lt=Dq[Ve];if(lt!==Be)throw Error(`Public area key curve ID "${Ve}" mapped to "${lt}" which did not match public key crv of "${Be}" (TPM|ECC)`)}else throw Error(`Unsupported pubArea.type "${x}"`);let P=Nq(m),{magic:F,type:R,attested:b,extraData:A}=P;if(F!==4283712327)throw Error(`Unexpected magic value "${F}", expected "0xff544347" (TPM)`);if(R!=="TPM_ST_ATTEST_CERTIFY")throw Error(`Unexpected type "${R}", expected "TPM_ST_ATTEST_CERTIFY" (TPM)`);let D=await Fi(u,AX(b.nameAlg)),B=Pi([b.nameAlgBuffer,D]);if(!as(b.name,B))throw Error("Attested name comparison failed (TPM)");let J=Pi([n,i]),G=await Fi(J,l);if(!as(A,G))throw Error("CertInfo extra data did not equal hashed attestation (TPM)");if(d.length<1)throw Error("No certificates present in x5c array (TPM)");let ce=xp(d[0]),{basicConstraintsCA:re,version:Z,subject:se,notAfter:te,notBefore:Ne}=ce;if(re)throw Error("Certificate basic constraints CA was not `false` (TPM)");if(Z!==2)throw Error("Certificate version was not `3` (ASN.1 value of 2) (TPM)");if(se.combined.length>0)throw Error("Certificate subject was not empty (TPM)");let ze=new Date;if(Ne>ze)throw Error(`Certificate not good before "${Ne.toString()}" (TPM)`);if(ze=new Date,te<ze)throw Error(`Certificate not good after "${te.toString()}" (TPM)`);let et=Ir.parse(d[0],nn);if(!et.tbsCertificate.extensions)throw Error("Certificate was missing extensions (TPM)");let xt,dt;if(et.tbsCertificate.extensions.forEach((Be)=>{if(Be.extnID===vp)xt=Ir.parse(Be.extnValue,Sp);else if(Be.extnID===hp)dt=Ir.parse(Be.extnValue,Jl)}),!xt)throw Error("Certificate did not contain subjectAltName extension (TPM)");if(!xt[0].directoryName?.[0].length)throw Error("Certificate subjectAltName extension directoryName was empty (TPM)");let{tcgAtTpmManufacturer:Le,tcgAtTpmModel:fe,tcgAtTpmVersion:qt}=RX(xt[0].directoryName);if(!Le||!fe||!qt)throw Error("Certificate contained incomplete subjectAltName data (TPM)");if(!dt)throw Error("Certificate did not contain ExtendedKeyUsage extension (TPM)");if(!Oq[Le])throw Error(`Could not match TPM manufacturer "${Le}" (TPM)`);if(dt[0]!=="2.23.133.8.3")throw Error(`Unexpected extKeyUsage "${dt[0]}", expected "2.23.133.8.3" (TPM)`);try{await lw(et.tbsCertificate.extensions,t)}catch(Be){throw Error(`${Be.message} (TPM)`)}let on=await Vc.getStatement(t);if(on)try{await Qc({statement:on,credentialPublicKey:o,x5c:d,attestationStatementAlg:l})}catch(Be){throw Error(`${Be.message} (TPM)`)}else try{await oo(d.map(fn),s)}catch(Be){throw Error(`${Be.message} (TPM)`)}return Ui({signature:c,data:m,x509Certificate:d[0],hashAlgorithm:l})}function RX(e){let o,i,s;return e.forEach((a)=>{a.forEach((c)=>{if(c.type==="2.23.133.2.1")o=c.value.toString();else if(c.type==="2.23.133.2.2")i=c.value.toString();else if(c.type==="2.23.133.2.3")s=c.value.toString()})}),{tcgAtTpmManufacturer:o,tcgAtTpmModel:i,tcgAtTpmVersion:s}}function AX(e){if(e==="TPM_ALG_SHA256")return tt.ES256;else if(e==="TPM_ALG_SHA384")return tt.ES384;else if(e==="TPM_ALG_SHA512")return tt.ES512;throw Error(`Unexpected TPM attested name alg ${e}`)}var bI,Bq="1.3.6.1.4.1.11129.2.1.17",EI;(function(e){e[e.verified=0]="verified",e[e.selfSigned=1]="selfSigned",e[e.unverified=2]="unverified",e[e.failed=3]="failed"})(EI||(EI={}));class Zp{verifiedBootKey=new ae;deviceLocked=!1;verifiedBootState=EI.verified;verifiedBootHash;constructor(e={}){Object.assign(this,e)}}y([g({type:ae})],Zp.prototype,"verifiedBootKey",void 0);y([g({type:E.Boolean})],Zp.prototype,"deviceLocked",void 0);y([g({type:E.Enumerated})],Zp.prototype,"verifiedBootState",void 0);y([g({type:ae,optional:!0})],Zp.prototype,"verifiedBootHash",void 0);var Yp=bI=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,bI.prototype)}};Yp=bI=y([H({type:L.Set,itemType:E.Integer})],Yp);class He{purpose;algorithm;keySize;digest;padding;ecCurve;rsaPublicExponent;mgfDigest;rollbackResistance;earlyBootOnly;activeDateTime;originationExpireDateTime;usageExpireDateTime;usageCountLimit;noAuthRequired;userAuthType;authTimeout;allowWhileOnBody;trustedUserPresenceRequired;trustedConfirmationRequired;unlockedDeviceRequired;allApplications;applicationId;creationDateTime;origin;rollbackResistant;rootOfTrust;osVersion;osPatchLevel;attestationApplicationId;attestationIdBrand;attestationIdDevice;attestationIdProduct;attestationIdSerial;attestationIdImei;attestationIdMeid;attestationIdManufacturer;attestationIdModel;vendorPatchLevel;bootPatchLevel;deviceUniqueAttestation;attestationIdSecondImei;moduleHash;constructor(e={}){Object.assign(this,e)}}y([g({context:1,type:Yp,optional:!0})],He.prototype,"purpose",void 0);y([g({context:2,type:E.Integer,optional:!0})],He.prototype,"algorithm",void 0);y([g({context:3,type:E.Integer,optional:!0})],He.prototype,"keySize",void 0);y([g({context:5,type:Yp,optional:!0})],He.prototype,"digest",void 0);y([g({context:6,type:Yp,optional:!0})],He.prototype,"padding",void 0);y([g({context:10,type:E.Integer,optional:!0})],He.prototype,"ecCurve",void 0);y([g({context:200,type:E.Integer,optional:!0})],He.prototype,"rsaPublicExponent",void 0);y([g({context:203,type:Yp,optional:!0})],He.prototype,"mgfDigest",void 0);y([g({context:303,type:E.Null,optional:!0})],He.prototype,"rollbackResistance",void 0);y([g({context:305,type:E.Null,optional:!0})],He.prototype,"earlyBootOnly",void 0);y([g({context:400,type:E.Integer,optional:!0})],He.prototype,"activeDateTime",void 0);y([g({context:401,type:E.Integer,optional:!0})],He.prototype,"originationExpireDateTime",void 0);y([g({context:402,type:E.Integer,optional:!0})],He.prototype,"usageExpireDateTime",void 0);y([g({context:405,type:E.Integer,optional:!0})],He.prototype,"usageCountLimit",void 0);y([g({context:503,type:E.Null,optional:!0})],He.prototype,"noAuthRequired",void 0);y([g({context:504,type:E.Integer,optional:!0})],He.prototype,"userAuthType",void 0);y([g({context:505,type:E.Integer,optional:!0})],He.prototype,"authTimeout",void 0);y([g({context:506,type:E.Null,optional:!0})],He.prototype,"allowWhileOnBody",void 0);y([g({context:507,type:E.Null,optional:!0})],He.prototype,"trustedUserPresenceRequired",void 0);y([g({context:508,type:E.Null,optional:!0})],He.prototype,"trustedConfirmationRequired",void 0);y([g({context:509,type:E.Null,optional:!0})],He.prototype,"unlockedDeviceRequired",void 0);y([g({context:600,type:E.Null,optional:!0})],He.prototype,"allApplications",void 0);y([g({context:601,type:ae,optional:!0})],He.prototype,"applicationId",void 0);y([g({context:701,type:E.Integer,optional:!0})],He.prototype,"creationDateTime",void 0);y([g({context:702,type:E.Integer,optional:!0})],He.prototype,"origin",void 0);y([g({context:703,type:E.Null,optional:!0})],He.prototype,"rollbackResistant",void 0);y([g({context:704,type:Zp,optional:!0})],He.prototype,"rootOfTrust",void 0);y([g({context:705,type:E.Integer,optional:!0})],He.prototype,"osVersion",void 0);y([g({context:706,type:E.Integer,optional:!0})],He.prototype,"osPatchLevel",void 0);y([g({context:709,type:ae,optional:!0})],He.prototype,"attestationApplicationId",void 0);y([g({context:710,type:ae,optional:!0})],He.prototype,"attestationIdBrand",void 0);y([g({context:711,type:ae,optional:!0})],He.prototype,"attestationIdDevice",void 0);y([g({context:712,type:ae,optional:!0})],He.prototype,"attestationIdProduct",void 0);y([g({context:713,type:ae,optional:!0})],He.prototype,"attestationIdSerial",void 0);y([g({context:714,type:ae,optional:!0})],He.prototype,"attestationIdImei",void 0);y([g({context:715,type:ae,optional:!0})],He.prototype,"attestationIdMeid",void 0);y([g({context:716,type:ae,optional:!0})],He.prototype,"attestationIdManufacturer",void 0);y([g({context:717,type:ae,optional:!0})],He.prototype,"attestationIdModel",void 0);y([g({context:718,type:E.Integer,optional:!0})],He.prototype,"vendorPatchLevel",void 0);y([g({context:719,type:E.Integer,optional:!0})],He.prototype,"bootPatchLevel",void 0);y([g({context:720,type:E.Null,optional:!0})],He.prototype,"deviceUniqueAttestation",void 0);y([g({context:723,type:ae,optional:!0})],He.prototype,"attestationIdSecondImei",void 0);y([g({context:724,type:ae,optional:!0})],He.prototype,"moduleHash",void 0);var ka;(function(e){e[e.software=0]="software",e[e.trustedEnvironment=1]="trustedEnvironment",e[e.strongBox=2]="strongBox"})(ka||(ka={}));var Xp;(function(e){e[e.KM2=1]="KM2",e[e.KM3=2]="KM3",e[e.KM4=3]="KM4",e[e.KM4_1=4]="KM4_1",e[e.keyMint1=100]="keyMint1",e[e.keyMint2=200]="keyMint2",e[e.keyMint3=300]="keyMint3",e[e.keyMint4=400]="keyMint4"})(Xp||(Xp={}));class Bi{attestationVersion=Xp.KM4;attestationSecurityLevel=ka.software;keymasterVersion=0;keymasterSecurityLevel=ka.software;attestationChallenge=new ae;uniqueId=new ae;softwareEnforced=new He;teeEnforced=new He;constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer})],Bi.prototype,"attestationVersion",void 0);y([g({type:E.Enumerated})],Bi.prototype,"attestationSecurityLevel",void 0);y([g({type:E.Integer})],Bi.prototype,"keymasterVersion",void 0);y([g({type:E.Enumerated})],Bi.prototype,"keymasterSecurityLevel",void 0);y([g({type:ae})],Bi.prototype,"attestationChallenge",void 0);y([g({type:ae})],Bi.prototype,"uniqueId",void 0);y([g({type:He})],Bi.prototype,"softwareEnforced",void 0);y([g({type:He})],Bi.prototype,"teeEnforced",void 0);class Ls{attestationVersion=Xp.keyMint4;attestationSecurityLevel=ka.software;keyMintVersion=0;keyMintSecurityLevel=ka.software;attestationChallenge=new ae;uniqueId=new ae;softwareEnforced=new He;hardwareEnforced=new He;constructor(e={}){Object.assign(this,e)}toLegacyKeyDescription(){return new Bi({attestationVersion:this.attestationVersion,attestationSecurityLevel:this.attestationSecurityLevel,keymasterVersion:this.keyMintVersion,keymasterSecurityLevel:this.keyMintSecurityLevel,attestationChallenge:this.attestationChallenge,uniqueId:this.uniqueId,softwareEnforced:this.softwareEnforced,teeEnforced:this.hardwareEnforced})}static fromLegacyKeyDescription(e){return new Ls({attestationVersion:e.attestationVersion,attestationSecurityLevel:e.attestationSecurityLevel,keyMintVersion:e.keymasterVersion,keyMintSecurityLevel:e.keymasterSecurityLevel,attestationChallenge:e.attestationChallenge,uniqueId:e.uniqueId,softwareEnforced:e.softwareEnforced,hardwareEnforced:e.teeEnforced})}}y([g({type:E.Integer})],Ls.prototype,"attestationVersion",void 0);y([g({type:E.Enumerated})],Ls.prototype,"attestationSecurityLevel",void 0);y([g({type:E.Integer})],Ls.prototype,"keyMintVersion",void 0);y([g({type:E.Enumerated})],Ls.prototype,"keyMintSecurityLevel",void 0);y([g({type:ae})],Ls.prototype,"attestationChallenge",void 0);y([g({type:ae})],Ls.prototype,"uniqueId",void 0);y([g({type:He})],Ls.prototype,"softwareEnforced",void 0);y([g({type:He})],Ls.prototype,"hardwareEnforced",void 0);var TI,RI=class extends He{};RI=y([H({type:L.Choice})],RI);var ef=TI=class extends Ie{constructor(t){super(t);Object.setPrototypeOf(this,TI.prototype)}findProperty(t){let r=this.find((n)=>n[t]!==void 0);if(r)return r[t];return}};ef=TI=y([H({type:L.Sequence,itemType:RI})],ef);class $s{attestationVersion=Xp.KM4;attestationSecurityLevel=ka.software;keymasterVersion=0;keymasterSecurityLevel=ka.software;attestationChallenge=new ae;uniqueId=new ae;softwareEnforced=new ef;teeEnforced=new ef;get keyMintVersion(){return this.keymasterVersion}set keyMintVersion(e){this.keymasterVersion=e}get keyMintSecurityLevel(){return this.keymasterSecurityLevel}set keyMintSecurityLevel(e){this.keymasterSecurityLevel=e}get hardwareEnforced(){return this.teeEnforced}set hardwareEnforced(e){this.teeEnforced=e}constructor(e={}){Object.assign(this,e)}}y([g({type:E.Integer})],$s.prototype,"attestationVersion",void 0);y([g({type:E.Enumerated})],$s.prototype,"attestationSecurityLevel",void 0);y([g({type:E.Integer})],$s.prototype,"keymasterVersion",void 0);y([g({type:E.Enumerated})],$s.prototype,"keymasterSecurityLevel",void 0);y([g({type:ae})],$s.prototype,"attestationChallenge",void 0);y([g({type:ae})],$s.prototype,"uniqueId",void 0);y([g({type:ef})],$s.prototype,"softwareEnforced",void 0);y([g({type:ef})],$s.prototype,"teeEnforced",void 0);var Mq=class extends $s{constructor(t={}){if("keymasterVersion"in t&&!("keyMintVersion"in t))t.keyMintVersion=t.keymasterVersion;if("keymasterSecurityLevel"in t&&!("keyMintSecurityLevel"in t))t.keyMintSecurityLevel=t.keymasterSecurityLevel;if("teeEnforced"in t&&!("hardwareEnforced"in t))t.hardwareEnforced=t.teeEnforced;super(t)}};Mq=y([H({type:L.Sequence})],Mq);class dw{packageName;version;constructor(e={}){Object.assign(this,e)}}y([g({type:E.OctetString})],dw.prototype,"packageName",void 0);y([g({type:E.Integer})],dw.prototype,"version",void 0);class AI{packageInfos;signatureDigests;constructor(e={}){Object.assign(this,e)}}y([g({type:dw,repeated:"set"})],AI.prototype,"packageInfos",void 0);y([g({type:E.OctetString,repeated:"set"})],AI.prototype,"signatureDigests",void 0);async function Lq(e){let{authData:t,clientDataHash:r,attStmt:n,credentialPublicKey:o,aaguid:i,rootCertificates:s}=e,a=n.get("x5c"),c=n.get("sig"),l=n.get("alg");if(!a)throw Error("No attestation certificate provided in attestation statement (Android Key)");if(!c)throw Error("No attestation signature provided in attestation statement (Android Key)");if(!l)throw Error("Attestation statement did not contain alg (Android Key)");if(!Es(l))throw Error(`Attestation statement contained invalid alg ${l} (Android Key)`);let d=Ir.parse(a[0],nn),u=new Uint8Array(d.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey),m=Ku(o);if(!as(m,u))throw Error("Credential public key does not equal leaf cert public key (Android Key)");let h=d.tbsCertificate.extensions?.find((R)=>R.extnID===Bq);if(!h)throw Error("Certificate did not contain extKeyStore (Android Key)");let S=Ir.parse(h.extnValue,Bi),{attestationChallenge:x,teeEnforced:v,softwareEnforced:w}=S;if(!as(new Uint8Array(x.buffer),r))throw Error("Attestation challenge was not equal to client data hash (Android Key)");if(v.allApplications!==void 0)throw Error('teeEnforced contained "allApplications [600]" tag (Android Key)');if(w.allApplications!==void 0)throw Error('teeEnforced contained "allApplications [600]" tag (Android Key)');let P=await Vc.getStatement(i);if(P)try{await Qc({statement:P,credentialPublicKey:o,x5c:a,attestationStatementAlg:l})}catch(R){let b=R;throw Error(`${b.message} (Android Key)`,{cause:b})}else{let R=a.slice(0,-1).map(fn),b=a.slice(-1).map(fn);try{await oo(R,b)}catch(A){let D=A;throw Error(`${D.message} (Android Key)`,{cause:D})}if(s.length>0&&s.indexOf(b[0])<0)throw Error("x5c root certificate was not a known root certificate (Android Key)")}let F=Pi([t,r]);return Ui({signature:c,data:F,x509Certificate:a[0],hashAlgorithm:l})}async function $q(e){let{attStmt:t,authData:r,clientDataHash:n,credentialPublicKey:o,rootCertificates:i}=e,s=t.get("x5c");if(!s)throw Error("No attestation certificate provided in attestation statement (Apple)");try{await oo(s.map(fn),i)}catch(v){throw Error(`${v.message} (Apple)`)}let a=Ir.parse(s[0],nn),{extensions:c,subjectPublicKeyInfo:l}=a.tbsCertificate;if(!c)throw Error("credCert missing extensions (Apple)");let d=c.find((v)=>v.extnID==="1.2.840.113635.100.8.2");if(!d)throw Error('credCert missing "1.2.840.113635.100.8.2" extension (Apple)');let u=Pi([r,n]),m=await Fi(u),h=new Uint8Array(d.extnValue.buffer).slice(6);if(!as(m,h))throw Error("credCert nonce was not expected value (Apple)");let S=Ku(o),x=new Uint8Array(l.subjectPublicKey);if(!as(S,x))throw Error("Credential public key does not equal credCert public key (Apple)");return!0}async function qq(e){let{response:t,expectedChallenge:r,expectedOrigin:n,expectedRPID:o,expectedType:i,requireUserPresence:s=!0,requireUserVerification:a=!0,supportedAlgorithmIDs:c=Sq,attestationSafetyNetEnforceCTSCheck:l=!0}=e,{id:d,rawId:u,type:m,response:h}=t;if(!d)throw Error("Missing credential ID");if(d!==u)throw Error("Credential ID was not base64url-encoded");if(m!=="public-key")throw Error(`Unexpected credential type ${m}, expected "public-key"`);let S=IR(h.clientDataJSON),{type:x,origin:v,challenge:w,tokenBinding:P}=S;if(Array.isArray(i)){if(!i.includes(x)){let Be=i.join(", ");throw Error(`Unexpected registration response type "${x}", expected one of: ${Be}`)}}else if(i){if(x!==i)throw Error(`Unexpected registration response type "${x}", expected "${i}"`)}else if(x!=="webauthn.create")throw Error(`Unexpected registration response type: ${x}`);if(typeof r==="function"){if(!await r(w))throw Error(`Custom challenge verifier returned false for registration response challenge "${w}"`)}else if(w!==r)throw Error(`Unexpected registration response challenge "${w}", expected "${r}"`);if(Array.isArray(n)){if(!n.includes(v))throw Error(`Unexpected registration response origin "${v}", expected one of: ${n.join(", ")}`)}else if(v!==n)throw Error(`Unexpected registration response origin "${v}", expected "${n}"`);if(P){if(typeof P!=="object")throw Error(`Unexpected value for TokenBinding "${P}"`);if(["present","supported","not-supported"].indexOf(P.status)<0)throw Error(`Unexpected tokenBinding.status value of "${P.status}"`)}let F=Mu(h.attestationObject),R=SB(F),b=R.get("fmt"),A=R.get("authData"),D=R.get("attStmt"),B=gI(A),{aaguid:J,rpIdHash:G,flags:ce,credentialID:re,counter:Z,credentialPublicKey:se,extensionsData:te}=B,Ne;if(o){let Be=[];if(typeof o==="string")Be=[o];else Be=o;Ne=await wI(G,Be)}if(s&&!ce.up)throw Error("User presence was required, but user was not present");if(a&&!ce.uv)throw Error("User verification was required, but user could not be verified");if(!re)throw Error("No credential ID was provided by authenticator");if(!se)throw Error("No public key was provided by authenticator");if(!J)throw Error("No AAGUID was present during registration");let et=bc(se).get(Ze.alg);if(typeof et!=="number")throw Error("Credential public key was missing numeric alg");if(!c.includes(et)){let Be=c.join(", ");throw Error(`Unexpected public key alg "${et}", expected one of "${Be}"`)}let xt=await Fi(Mu(h.clientDataJSON)),dt=Kc.getRootCertificates({identifier:b}),Le={aaguid:J,attStmt:D,authData:A,clientDataHash:xt,credentialID:re,credentialPublicKey:se,rootCertificates:dt,rpIdHash:G,attestationSafetyNetEnforceCTSCheck:l},fe=!1;if(b==="fido-u2f")fe=await bq(Le);else if(b==="packed")fe=await Iq(Le);else if(b==="android-safetynet")fe=await Cq(Le);else if(b==="android-key")fe=await Lq(Le);else if(b==="tpm")fe=await Uq(Le);else if(b==="apple")fe=await $q(Le);else if(b==="none"){if(D.size>0)throw Error("None attestation had unexpected attestation statement");fe=!0}else throw Error(`Unsupported Attestation Format: ${b}`);if(!fe)return{verified:!1};let{credentialDeviceType:qt,credentialBackedUp:on}=xI(ce);return{verified:!0,registrationInfo:{fmt:b,aaguid:Lv(J),credentialType:m,credential:{id:ws(re),publicKey:se,counter:Z,transports:t.response.transports},attestationObject:F,userVerified:ce.uv,credentialDeviceType:qt,credentialBackedUp:on,origin:S.origin,rpID:Ne,authenticatorExtensionResults:te}}}import{Data as PX,Effect as Ed,Either as RXe,Schema as Lt}from"effect";class jq extends PX.TaggedError("processfocus:internal-tag/openauth/PasskeyVerificationError"){}var Hq=Lt.Struct({id:Lt.String,rawId:Lt.String,type:Lt.Literal("public-key"),clientExtensionResults:Lt.Record({key:Lt.String,value:Lt.Unknown}),response:Lt.Struct({clientDataJSON:Lt.String,attestationObject:Lt.String,transports:Lt.optional(Lt.Array(Lt.String))})}),IX=(e)=>({id:e.id,rawId:e.rawId,type:e.type,clientExtensionResults:{},response:{clientDataJSON:e.response.clientDataJSON,attestationObject:e.response.attestationObject,...e.response.transports&&{transports:e.response.transports.slice()}}}),CX=Lt.Struct({id:Lt.String,rawId:Lt.String,type:Lt.Literal("public-key"),clientExtensionResults:Lt.Record({key:Lt.String,value:Lt.Unknown}),response:Lt.Struct({clientDataJSON:Lt.String,authenticatorData:Lt.String,signature:Lt.String,userHandle:Lt.String})});var CXe=Lt.Struct({challengeId:Lt.String,response:Hq,sessionBearer:Lt.optional(Lt.String)}),_Xe=Lt.Struct({challengeId:Lt.String,response:CX}),kXe=Lt.Struct({token:Lt.String});var _X=(e)=>Buffer.from(e).toString("base64url"),kX=(e)=>{let t=Buffer.from(e,"base64url");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)},PI=Hq,OX=(e)=>{if(!e||e.length===0)return;return e.map((t)=>({id:t.id,type:"public-key",...t.transports&&t.transports.length>0&&{transports:t.transports.slice()}}))},DX=(e,t,r,n)=>{let o=OX(n);return Ed.promise(()=>vq({rpName:e.rpName,rpID:e.rpID,userName:t,userDisplayName:t,userID:r,attestationType:"none",authenticatorSelection:{residentKey:"required",requireResidentKey:!0,userVerification:"required"},...o&&{excludeCredentials:o}}))};var II=(e)=>DX({rpName:e.rpName,rpID:e.rpID},e.email,kX(e.userHandle),e.excludeCredentials),CI=(e)=>Ed.tryPromise({try:()=>qq({response:IX(e.response),expectedChallenge:e.expectedChallenge,expectedOrigin:typeof e.origin==="string"?e.origin:[...e.origin],expectedRPID:e.rpID,requireUserVerification:!0}),catch:(t)=>new jq({message:"Passkey registration verification failed",cause:t})}).pipe(Ed.tapError((t)=>Ed.logError("Registration verification failed").pipe(Ed.annotateLogs({error:t}))),Ed.map((t)=>{if(!t.verified||!t.registrationInfo)return{verified:!1};let r=e.response.response.transports;return{verified:!0,credential:{id:t.registrationInfo.credential.id,publicKey:_X(t.registrationInfo.credential.publicKey),counter:t.registrationInfo.credential.counter,...r&&{transports:r}}}}),Ed.orElseSucceed(()=>({verified:!1})));import{Clock as LXe,Effect as $Xe,Layer as qXe,Schema as Wq,Stream as jXe}from"effect";var KXe=Wq.parseJson(Wq.Unknown);import{Clock as uw,Effect as yh,Layer as NX,Stream as FX}from"effect";var _I=NX.sync(hr,()=>{let e=[];function t(r){let n=0,o=e.length-1;while(n<=o){let i=Math.floor((n+o)/2),s=r.localeCompare(e[i][0]);if(s===0)return{found:!0,index:i};else if(s<0)o=i-1;else n=i+1}return{found:!1,index:n}}return{get:(r)=>yh.gen(function*(){let n=t(Ul(r));if(!n.found)return;let o=e[n.index][1];if(o.expiry){if((yield*uw.currentTimeMillis)>=o.expiry){e.splice(n.index,1);return}}return o.value}),take:(r)=>yh.gen(function*(){let n=t(Ul(r));if(!n.found)return;let o=e[n.index][1];if(e.splice(n.index,1),o.expiry){if((yield*uw.currentTimeMillis)>=o.expiry)return}return o.value}),set:(r,n,o)=>yh.gen(function*(){let i=Ul(r),s=t(i),a={value:n};if(o){let l=yield*uw.currentTimeMillis;a.expiry=l+o*1000}let c=[i,a];if(!s.found)e.splice(s.index,0,c);else e[s.index]=c}),remove:(r)=>yh.sync(()=>{let n=Ul(r),o=t(n);if(o.found)e.splice(o.index,1)}),scan:(r)=>FX.fromIterableEffect(yh.gen(function*(){let n=yield*uw.currentTimeMillis,o=Ul(r),i=[];for(let[s,a]of e){if(!s.startsWith(o))continue;if(a.expiry&&n>=a.expiry)continue;i.push([BU(s),a.value])}return i}))}});import{Runtime as YXe}from"effect";import{Clock as ZX,DateTime as Vq,Effect as Ro,Option as of,Schema as Oa}from"effect";import{Context as LX}from"effect";class qs extends LX.Tag("processfocus:internal-tag/auth-api/DelegationDatabase")(){}import{createHash as zX}from"crypto";import{Context as GX,Data as YX,DateTime as Jc,Effect as Rd,FiberRef as Kq,Layer as XX,Option as rf}from"effect";import{Context as $X}from"effect";class hh extends $X.Tag("processfocus:internal-tag/auth-policy/AuthorizationService")(){}import{Context as qX,Effect as w7e,FiberRef as b7e}from"effect";class jX extends qX.Tag("processfocus:internal-tag/auth-policy/CurrentPrincipal")(){}import{Data as tf}from"effect";class HX extends tf.TaggedError("PolicyLoadError"){}class WX extends tf.TaggedError("SchemaLoadError"){}class KX extends tf.TaggedError("PolicyParseError"){}class VX extends tf.TaggedError("SchemaParseError"){}class QX extends tf.TaggedError("AuthorizationError"){}class JX extends tf.TaggedError("AuthorizationDeniedError"){}class Td{uid;owner;name;roles;orgUnit;constructor(e,t){this.uid={type:"PF::Delegation",id:e},this.owner={type:"PF::ProviderUser",id:t.owner},this.name=t.name,this.roles=t.roles.map((r)=>({type:"PF::Role",id:r})),this.orgUnit={type:"PF::OrgUnit",id:t.orgUnitId}}}class pw{uid;roles;orgUnit;constructor(e,t){this.uid={type:"PF::ProviderUser",id:e};let r=typeof t.roles==="string"?[t.roles]:t.roles;this.roles=r.map((n)=>({type:"PF::Role",id:n})),this.orgUnit={type:"PF::OrgUnit",id:t.orgUnitId}}}class io extends YX.TaggedError("InvalidDelegationSession"){}class nf extends GX.Tag("processfocus:internal-tag/auth-api/DelegationSessionService")(){}var kI=({db:e,authDb:t,auth:r})=>(n)=>Rd.gen(function*(){let o=yield*Jc.now,i=n.delegation;if(!i||n.humanAuthentication!==void 0)return yield*new io;let s=yield*e.findGeneration({generationId:i.generationId});if(rf.isNone(s))return yield*new io;let a=s.value,c=Jc.toEpochMillis(a.expiresAt);if(a.id!==i.id||a.userId!==n.userId||a.revokedAt!==null||a.generationRevokedAt!==null||i.expiresAt!==c||Jc.toEpochMillis(o)>=c)return yield*new io;let l=yield*t.findProviderUserByUserId(a.userId);if(rf.isNone(l)||l.value.email!==n.email)return yield*new io;let d=yield*t.findProviderUserRoles(a.userId),u=n.delegationRoleSelection===void 0?d:d.filter((v)=>n.delegationRoleSelection?.includes(v)),m=new Td(a.id,{owner:l.value.email,name:a.name,roles:u,orgUnitId:l.value.orgUnitPath});if(!(yield*r.canLogin(m,{uid:{type:"PF::Application",id:"frontend"}}).pipe(Rd.provideService(Io,Kq.unsafeMake(o)))))return yield*new io;let h=new Set([a.generationId]),S=new Set([a.id]),x=a;while(x.parentGenerationId!==null){if(h.has(x.parentGenerationId))return yield*new io;let v=yield*e.findGeneration({generationId:x.parentGenerationId});if(rf.isNone(v))return yield*new io;let w=v.value,P=Jc.toEpochMillis(w.expiresAt);if(S.has(w.id)||w.revokedAt!==null||w.generationRevokedAt!==null||Jc.toEpochMillis(o)>=P||Jc.toEpochMillis(x.expiresAt)>P)return yield*new io;h.add(w.generationId),S.add(w.id);let F=yield*t.findProviderUserByUserId(w.userId);if(rf.isNone(F))return yield*new io;let R=yield*t.findProviderUserRoles(w.userId);if(!(yield*r.canLogin(new Td(w.id,{owner:F.value.email,name:w.name,roles:R,orgUnitId:F.value.orgUnitPath}),{uid:{type:"PF::Application",id:"frontend"}}).pipe(Rd.provideService(Io,Kq.unsafeMake(o)))))return yield*new io;x=w}return yield*e.recordUse({generationId:a.generationId,usedAt:o}),{userId:a.userId,email:l.value.email,orgUnitId:l.value.orgUnitId,orgUnitPath:l.value.orgUnitPath,roles:u,...n.delegationRoleSelection===void 0?{}:{delegationRoleSelection:u},delegation:{id:a.id,generationId:a.generationId,name:a.name,expiresAt:c}}}).pipe(Rd.mapError(()=>new io)),L7e=XX.effect(nf,Rd.gen(function*(){let e=yield*qs,t=yield*Fn,r=yield*hh,n=yield*ps,o=kI({db:e,authDb:t,auth:r});return nf.of({check:o,exchange:(i)=>n.withTransaction(Rd.gen(function*(){if(!/^pfds_[A-Za-z0-9_-]{43}$/.test(i))return yield*new io;let s=zX("sha256").update(i).digest("base64url"),a=yield*e.findGeneration({verifier:s});if(rf.isNone(a))return yield*new io;let c=a.value,l=yield*t.findProviderUserByUserId(c.userId);if(rf.isNone(l))return yield*new io;let d=yield*o({userId:c.userId,email:l.value.email,orgUnitId:l.value.orgUnitId,orgUnitPath:l.value.orgUnitPath,roles:[],delegation:{id:c.id,generationId:c.generationId,name:c.name,expiresAt:Jc.toEpochMillis(c.expiresAt)}});return yield*e.recordLogin({delegationId:c.id,generationId:c.generationId,ownerId:c.ownerId,loggedInAt:yield*Jc.now}),d})).pipe(Rd.mapError(()=>new io))})}));var e7=Oa.Struct({secret:Oa.String.pipe(Oa.maxLength(48))}),t7=Oa.Struct({accessToken:Oa.String.pipe(Oa.minLength(1),Oa.maxLength(16384))}),Jn=(e,t=200)=>vb(e,{status:t,headers:{"cache-control":"no-store",pragma:"no-cache","x-content-type-options":"nosniff"}}),r7=Ro.gen(function*(){let e=gv(),t=yield*Ro.serviceOption(nf),r=yield*Ro.serviceOption(qs),n=yield*Kr,o=0,i=0,s=yield*Ro.context();return Ro.gen(function*(){let a=yield*lr,c=new URL(a.url,"https://localhost");if(c.pathname==="/oauth/delegation/availability"){if(a.method!=="GET")return Jn({error:"method_not_allowed"},405);let w=new URL(yield*Un(a.headers));if(c.search||w.protocol!=="https:"&&!["localhost","127.0.0.1","[::1]"].includes(w.hostname))return Jn({error:"invalid_request"},400);let{client:P,method:F}=yield*Gi(new Map);if(P.id!==e||F!=="client_jwt")return Jn({error:"invalid_client"},401);let R=of.isSome(r)&&(yield*r.value.isSecretLoginEnabled().pipe(Ro.orElseSucceed(()=>!1)));return Jn({secretLoginEnabled:R})}if(of.isNone(t))return Jn({error:"delegated_access_unavailable"},403);if(a.method!=="POST")return Jn({error:"method_not_allowed"},405);let l=new URL(a.url,"https://localhost").pathname==="/oauth/delegation/session",d=new URL(yield*Un(a.headers));if(d.protocol!=="https:"&&!["localhost","127.0.0.1","[::1]"].includes(d.hostname))return Jn({error:"invalid_request"},400);if(new URL(a.url,"https://localhost").search||a.headers["content-type"]?.split(";")[0]!=="application/json")return Jn({error:"invalid_request"},400);let u=yield*ZX.currentTimeMillis;if(u>=o+60000)o=u,i=0;if(!l&&++i>30)return Jn({error:"rate_limited"},429);let{client:m,method:h}=yield*Gi(new Map);if(m.id!==e||h!=="client_jwt")return Jn({error:"invalid_client"},401);if(l){let w=yield*a.json.pipe(o0(of.some(20480)),Ro.flatMap(Oa.decodeUnknown(t7,{onExcessProperty:"error"}))),P=yield*n.allSigningKeys,F=yield*Vq.now,R=yield*Ro.tryPromise(()=>Ei(w.accessToken,async(J)=>{let G=P.find((ce)=>ce.id===J.kid&&ce.alg===J.alg);if(!G)throw Error("Unknown signing key");return G.public},{issuer:d.toString().replace(/\/$/,""),audience:m.audience,requiredClaims:["exp","sub"],currentDate:Vq.toDateUtc(F)})).pipe(Ro.option);if(of.isNone(R))return Jn({error:"invalid_token"},401);let b=R.value.payload,A=b.properties;if(b.mode!=="access"||b.type!=="providerUser"||typeof A!=="object"||A===null||!("delegation"in A))return Jn({error:"invalid_token"},401);let D=yield*Ro.promise(async()=>yc.providerUser["~standard"].validate(A));if(D.issues||!D.value.delegation||b.exp===void 0||b.exp*1000>D.value.delegation.expiresAt)return Jn({error:"invalid_token"},401);let B=yield*t.value.check(D.value).pipe(Ro.option);if(of.isNone(B))return Jn({error:"invalid_token"},401);return Jn({session:B.value})}let S=yield*a.json.pipe(o0(of.some(1024)),Ro.flatMap(Oa.decodeUnknown(e7,{onExcessProperty:"error"}))),x=yield*t.value.exchange(S.secret),v=yield*Ss({type:"providerUser",properties:x,subject:`delegation:${x.delegation.id}:${x.delegation.generationId}`,clientID:m.id,audience:m.audience,ttl:{access:600,refresh:7776000},expiresAt:x.delegation.expiresAt,timeUsed:void 0,nextToken:void 0});return Jn({access_token:v.access,refresh_token:v.refresh,expires_in:v.expiresIn,refresh_expires_in:v.refreshExpiresIn})}).pipe(Ro.provide(s),Ro.catchAll(()=>Ro.succeed(Jn({error:"invalid_grant"},400))))});import{createHash as Qq,randomBytes as Jq,randomUUID as OI}from"crypto";import{Data as n7,DateTime as Sr,Effect as Jt,FiberRef as sf,Option as cs,Schema as Sn}from"effect";class Ur extends n7.TaggedError("DelegationRequestError"){}var gh=Sn.Struct({requestId:Sn.optional(Sn.UUID),name:Sn.String.pipe(Sn.minLength(1),Sn.maxLength(128)),lifetimeDays:Sn.Literal(1,7,14)}),DI={id:Sn.String.pipe(Sn.minLength(1)),generationId:Sn.String.pipe(Sn.minLength(1)),expectedName:gh.fields.name},o7=Sn.Union(Sn.Struct({operation:Sn.Literal("rename"),...DI,name:gh.fields.name}),Sn.Struct({operation:Sn.Literal("replace"),...DI,name:gh.fields.name,lifetimeDays:gh.fields.lifetimeDays}),Sn.Struct({operation:Sn.Literal("revoke"),...DI})),i7=(e,t)=>({id:e.id,name:e.name,generationId:e.generationId,createdAt:Sr.formatIso(e.createdAt),expiresAt:Sr.formatIso(e.expiresAt),revokedAt:e.revokedAt===null?null:Sr.formatIso(e.revokedAt),status:e.revokedAt!==null?"revoked":Sr.lessThanOrEqualTo(e.expiresAt,t)?"expired":"active",lastUsedAt:e.lastUsedAt===null?null:Sr.formatIso(e.lastUsedAt)}),zn=(e,t=200)=>vb(e,{status:t,headers:{"cache-control":"no-store",pragma:"no-cache","x-content-type-options":"nosniff"}}),s7=Jt.gen(function*(){let e=yield*Jt.serviceOption(qs),t=yield*Jt.serviceOption(hh),r=yield*Fn,n=cs.isSome(e)&&cs.isSome(t)?kI({db:e.value,authDb:r,auth:t.value}):void 0,o=yield*ps,i=yield*Kr,s=yield*Kn;return Jt.gen(function*(){let c=yield*lr;if(c.method!=="GET"&&c.method!=="POST"&&c.method!=="PATCH")return zn({error:"method_not_allowed"},405);let l=c.headers.authorization?.match(/^Bearer ([^ ]+)$/)?.[1];if(!l)return zn({error:"invalid_token"},401);let d=yield*i.allSigningKeys,u=yield*Un(c.headers).pipe(Jt.mapError(()=>new Ur({status:401,error:"invalid_token"}))),m=yield*Sr.now,h=yield*Jt.tryPromise({try:()=>Ei(l,async(te)=>{let Ne=d.find((ze)=>ze.id===te.kid&&ze.alg===te.alg);if(!Ne)throw Error("Unknown signing key");return Ne.public},{issuer:u,audience:[...s.staticClients.values()].map((te)=>te.audience),requiredClaims:["exp","sub"],currentDate:Sr.toDateUtc(m)}),catch:()=>new Ur({status:401,error:"invalid_token"})}),S=h.payload.exp;if(typeof S!=="number"||h.payload.mode!=="access"||h.payload.type!=="providerUser")return zn({error:"invalid_token"},401);let x=yield*Jt.promise(async()=>yc.providerUser["~standard"].validate(h.payload.properties));if(x.issues)return zn({error:"invalid_token"},401);let v=x.value;if(v.delegation!==void 0&&n===void 0)return zn({error:"invalid_token"},401);if(cs.isNone(e))return zn({error:"delegation_unavailable"},403);let w=e.value,P=c.method==="PATCH"?yield*c.json.pipe(Jt.flatMap(Sn.decodeUnknown(o7,{onExcessProperty:"error"})),Jt.mapError(()=>new Ur({status:400,error:"invalid_request"}))):void 0,F=new URL(c.url,"https://auth.invalid").searchParams.getAll("ownerUserId");if(F.length>1||F[0]==="")return zn({error:"invalid_request"},400);let R=F[0]??v.userId,b=v,A=Jt.gen(function*(){if(Sr.toEpochMillis(yield*Sr.now)>=S*1000)return yield*new Ur({status:401,error:"invalid_token"});let te=b.delegation!==void 0&&n!==void 0?yield*n(b).pipe(Jt.mapError(()=>new Ur({status:401,error:"invalid_token"}))):b,Ne=new Set,ze=new Set,et=te.delegation?.generationId??null;while(et!==null){if(ze.has(et))return yield*new Ur({status:401,error:"invalid_token"});ze.add(et);let Ht=yield*w.findGeneration({generationId:et});if(cs.isNone(Ht))return yield*new Ur({status:401,error:"invalid_token"});Ne.add(Ht.value.id),et=Ht.value.parentGenerationId}let xt=(Ht,Mn)=>Sr.unsafeMake(Math.min(Sr.toEpochMillis(Sr.add(Ht,{days:Mn})),te.delegation?.expiresAt??Number.POSITIVE_INFINITY)),dt=yield*w.findOwnerId(te.userId),Le=yield*r.findProviderUserByUserId(te.userId);if(cs.isNone(dt)||cs.isNone(Le))return yield*new Ur({status:401,error:"invalid_token"});let fe=yield*w.findOwnerId(R),qt=yield*r.findProviderUserByUserId(R);if(cs.isNone(fe)||cs.isNone(qt))return yield*new Ur({status:403,error:c.method==="PATCH"?"operation_denied":"issuance_denied"});if(cs.isNone(t))return yield*new Ur({status:403,error:c.method==="PATCH"?"operation_denied":"issuance_denied"});let on=t.value,Be=te.delegation===void 0?yield*r.findProviderUserRoles(te.userId):te.roles,xr=te.delegation===void 0?new pw(Le.value.email,{roles:Be,orgUnitId:Le.value.orgUnitPath}):new Td(te.delegation.id,{owner:Le.value.email,name:te.delegation.name,roles:Be,orgUnitId:Le.value.orgUnitPath}),uo=yield*r.findProviderUserRoles(R),Ve=new pw(qt.value.email,{roles:uo,orgUnitId:qt.value.orgUnitPath}),lt=(Ht)=>new Td(Ht.id,{owner:qt.value.email,name:Ht.name,roles:uo,orgUnitId:qt.value.orgUnitPath}),jt=(Ht)=>Jt.gen(function*(){let Mn=(ls)=>on.canIssueDelegationSecret(xr,Ve,{ownerProviderUserId:R,humanSession:te.delegation===void 0&&te.humanSession===!0,humanAuthentication:ls}).pipe(Jt.provideService(Io,sf.unsafeMake(Ht)));if(yield*Mn(te.humanAuthentication))return"allowed";if(te.delegation!==void 0||te.userId!==R)return"issuance_denied";if(!(yield*Mn({providerUserId:te.userId,authenticatedAt:Sr.toEpochMillis(Ht),method:"passkey"})))return"issuance_denied";let Ao=yield*r.findOAuthProviderByName("passkey");return Le.value.provider==="passkey"&&cs.isSome(Ao)?"verification_required":"unsupported_authentication"}),ut=(Ht,Mn)=>Jt.gen(function*(){let Ao=yield*Jt.all({rename:on.canManageDelegation(xr,lt(Ht),"rename"),replace:on.canManageDelegation(xr,lt(Ht),"replace"),revoke:on.canManageDelegation(xr,lt(Ht),"revoke")}).pipe(Jt.provideService(Io,sf.unsafeMake(Mn)));return{...i7(Ht,Mn),allowedActions:{rename:Ht.revokedAt===null&&Ao.rename,replace:!Ne.has(Ht.id)&&Ht.revokedAt===null&&Ao.replace&&(yield*jt(Mn))!=="issuance_denied",revoke:Ht.revokedAt===null&&Ao.revoke}}});return{session:te,ancestorIds:Ne,issuanceExpiry:xt,actorId:dt.value,ownerId:fe.value,owner:qt.value,principal:xr,ownerPrincipal:Ve,resource:lt,withActions:ut,issuanceDecision:jt,auth:on}});if(c.method==="GET"){let{session:te,ownerId:Ne,owner:ze,principal:et,ownerPrincipal:xt,withActions:dt,issuanceDecision:Le,auth:fe}=yield*A,qt=sf.unsafeMake(m);if(!(yield*fe.canListDelegationTokens(et,xt).pipe(Jt.provideService(Io,qt))))return zn({error:"issuance_denied"},403);let Be=yield*w.list(Ne);return zn({owner:{userId:R,email:ze.email},issuanceDeadline:te.delegation===void 0?null:Sr.formatIso(Sr.unsafeMake(te.delegation.expiresAt)),canIssue:(yield*Le(m))!=="issuance_denied",delegations:yield*Jt.forEach(Be,(xr)=>dt(xr,m))})}let D=yield*w.findOwnerId(R);if(cs.isNone(D)){if(R===v.userId)return zn({error:"invalid_token"},401);return zn({error:c.method==="PATCH"?"operation_denied":"issuance_denied"},403)}if(P!==void 0){let te=P,Ne=te.operation==="revoke"?te.expectedName:te.name.trim();if(!Ne)return zn({error:"invalid_request"},400);let ze=yield*o.withTransaction(Jt.gen(function*(){yield*w.releaseExpiredNames(D.value,m);let{session:et,ancestorIds:xt,issuanceExpiry:dt,actorId:Le,ownerId:fe,principal:qt,ownerPrincipal:on,resource:Be,withActions:xr,issuanceDecision:uo,auth:Ve}=yield*A,lt=yield*Sr.now;yield*w.releaseExpiredNames(fe,lt);let jt=yield*w.list(fe),ut=jt.find((Gn)=>Gn.id===te.id);if(!ut)return yield*new Ur({status:403,error:"operation_denied"});if(!(yield*Ve.canManageDelegation(qt,Be(ut),te.operation).pipe(Jt.provideService(Io,sf.unsafeMake(lt))))||ut.revokedAt!==null)return yield*new Ur({status:403,error:"operation_denied"});if(te.operation==="replace"&&xt.has(ut.id))return yield*new Ur({status:403,error:"operation_denied"});if(te.operation==="replace"&&R!==et.userId&&!(yield*Ve.canIssueDelegationSecret(qt,on,{ownerProviderUserId:R,humanSession:et.delegation===void 0&&et.humanSession===!0,humanAuthentication:et.humanAuthentication}).pipe(Jt.provideService(Io,sf.unsafeMake(lt)))))return yield*new Ur({status:403,error:"operation_denied"});if(ut.generationId!==te.generationId||ut.name!==te.expectedName)return yield*new Ur({status:409,error:"stale_delegation"});if(te.operation==="replace"&&Ne!==ut.name&&!(yield*Ve.canManageDelegation(qt,Be(ut),"rename").pipe(Jt.provideService(Io,sf.unsafeMake(lt)))))return yield*new Ur({status:403,error:"operation_denied"});if(te.operation==="replace"){let Gn=yield*uo(lt);if(Gn!=="allowed")return yield*new Ur({status:403,error:Gn})}let Mn=te.operation==="replace"||Sr.greaterThan(ut.expiresAt,lt);if(te.operation!=="revoke"&&Mn&&jt.some((Gn)=>Gn.id!==ut.id&&Gn.name===Ne&&Gn.revokedAt===null&&Sr.greaterThan(Gn.expiresAt,lt)))return yield*new Ur({status:409,error:"name_conflict"});if(te.operation==="revoke"){let Gn=Sr.unsafeMake(Math.floor(Sr.toEpochMillis(lt)/1000)*1000);return yield*w.revoke({id:ut.id,revokedAt:Gn}),yield*w.revokeGeneration({generationId:ut.generationId,revokedAt:Gn}),yield*w.recordChange({delegationId:ut.id,generationId:ut.generationId,actorId:Le,actorDelegation:et.delegation,event:"revoked",occurredAt:lt}),yield*xr({...ut,revokedAt:Gn},lt)}if(yield*w.updateName({id:ut.id,name:Ne,activeName:Mn?Ne:null}),Ne!==ut.name)yield*w.recordChange({delegationId:ut.id,generationId:ut.generationId,actorId:Le,actorDelegation:et.delegation,event:"renamed",oldName:ut.name,newName:Ne,occurredAt:lt});if(te.operation==="rename")return yield*xr({...ut,name:Ne},lt);let Ao=`dsg-${OI()}`,ls=`pfds_${Jq(32).toString("base64url")}`,Vs=Sr.unsafeMake(Math.floor(Sr.toEpochMillis(lt)/1000)*1000),yf=dt(Vs,te.lifetimeDays);return yield*w.revokeGeneration({generationId:ut.generationId,revokedAt:lt}),yield*w.recordChange({delegationId:ut.id,generationId:ut.generationId,actorId:Le,actorDelegation:et.delegation,event:"replaced",occurredAt:lt}),yield*w.insertGeneration({id:Ao,parentGenerationId:et.delegation?.generationId??null,delegationId:ut.id,verifier:Qq("sha256").update(ls).digest("base64url"),issuedAt:Vs,expiresAt:yf}),yield*w.recordIssuance({delegationId:ut.id,generationId:Ao,actorId:Le,actorDelegation:et.delegation,issuedAt:Vs}),{...yield*xr({...ut,name:Ne,generationId:Ao,createdAt:Vs,expiresAt:yf,lastUsedAt:null},lt),secret:ls}}));return zn(ze)}let B=yield*c.json.pipe(Jt.flatMap(Sn.decodeUnknown(gh,{onExcessProperty:"error"})),Jt.mapError(()=>new Ur({status:400,error:"invalid_request"}))),J=B.name.trim();if(J.length===0)return zn({error:"invalid_request"},400);let G=`dlg-${OI()}`,ce=`dsg-${B.requestId??OI()}`,re=`pfds_${Jq(32).toString("base64url")}`,Z=Qq("sha256").update(re).digest("base64url"),se=yield*o.withTransaction(Jt.gen(function*(){yield*w.releaseExpiredNames(D.value,m);let{session:te,issuanceExpiry:Ne,actorId:ze,ownerId:et,withActions:xt,issuanceDecision:dt}=yield*A,Le=yield*Sr.now,fe=yield*dt(Le);if(fe!=="allowed")return yield*new Ur({status:403,error:fe});if(yield*w.hasGeneration(ce))return yield*new Ur({status:409,error:"submission_replayed"});let qt=Sr.unsafeMake(Math.floor(Sr.toEpochMillis(Le)/1000)*1000),on=Ne(qt,B.lifetimeDays);if(yield*w.releaseExpiredNames(et,Le),!(yield*w.claimName({id:G,ownerId:et,name:J})))return yield*new Ur({status:409,error:"name_conflict"});return yield*w.insertGeneration({id:ce,parentGenerationId:te.delegation?.generationId??null,delegationId:G,verifier:Z,issuedAt:qt,expiresAt:on}),yield*w.recordIssuance({delegationId:G,generationId:ce,actorId:ze,actorDelegation:te.delegation,issuedAt:qt}),{...yield*xt({id:G,name:J,generationId:ce,createdAt:qt,expiresAt:on,revokedAt:null,lastUsedAt:null},Le),secret:re}}));return zn(se,201)}).pipe(Jt.catchTag("DelegationRequestError",({status:c,error:l})=>Jt.succeed(zn({error:l},c))),Jt.catchAll(()=>Jt.logError("Unexpected delegation management failure").pipe(Jt.as(zn({error:"internal_error"},500)))))});import{Data as a7}from"effect";class NI extends a7.TaggedError("InvariantViolationError"){}import{Data as g7,DateTime as yw,Effect as vr,Either as qI,Option as fw,Schema as Br}from"effect";ol();import{Data as Pd,DateTime as DZe,Effect as UI,Option as BI}from"effect";import{Effect as uZe,Either as pZe,Option as fZe,Schema as FI}from"effect";var yZe=FI.Struct({inviteOnly:FI.optional(FI.Boolean)});import{Effect as SZe,Schedule as zq}from"effect";var vZe=zq.addDelay(zq.recurs(1),()=>100);import{DateTime as EZe,Effect as TZe,Option as RZe,Schema as Ad}from"effect";var af=(e)=>e.provider==="passkey"?e.sub:Buffer.from(e.userId).toString("base64url");var CZe=Ad.Struct({recoveryId:Ad.String,userId:Ad.String,userHandle:Ad.String,email:Ad.String,invitationId:Ad.String,actor:Ad.String});class u7 extends Pd.TaggedError("processfocus:internal-tag/RootOrgUnitNotFoundError"){}var Yq=10;class Xq extends Pd.TaggedError("processfocus:internal-tag/PasskeyOpenRegistrationDeniedError"){}class p7 extends Pd.TaggedError("processfocus:internal-tag/PasskeyInvitationRegistrationDeniedError"){}class $I extends Pd.TaggedError("processfocus:internal-tag/PasskeyIdentityNotFoundError"){}class f7 extends Pd.TaggedError("processfocus:internal-tag/PasskeyCounterError"){}class MI extends Pd.TaggedError("processfocus:internal-tag/PasskeyCredentialAlreadyOwnedError"){}class LI extends Pd.TaggedError("processfocus:internal-tag/PasskeyManagementDeniedError"){}var m7=(e,t)=>ds(e,(r)=>/unique/i.test(r)&&t.some((n)=>n.test(r)));var y7=(e)=>m7(e,[/passkey_credential_id/i,/pf_passkey_credential/i]),h7=UI.fn("passkey.withRoles")(function*(e){let t=yield*Fn,r=yield*t.findProviderUserRoles(e),n=yield*t.findProviderUserByUserId(e);if(BI.isNone(n))return yield*new $I({userHandle:e});return{...n.value,roles:r}});var Zq=(e)=>UI.gen(function*(){let t=yield*Fn,r=yield*t.findProviderUserByUserId(e.userId);if(BI.isNone(r))return yield*new $I({userHandle:e.userHandle});if(af({...r.value,userId:r.value.id})!==e.userHandle)return yield*new LI({reason:"user_handle_mismatch"});if((yield*t.listPasskeyCredentialsForUser(e.userId)).length===0)return yield*new LI({reason:"no_existing_passkey"});let o=yield*t.findPasskeyCredentialById(e.credential.id);if(BI.isSome(o))return yield*new MI({credentialId:e.credential.id});return yield*t.createPasskeyCredential({userId:e.userId,credentialId:e.credential.id,publicKey:e.credential.publicKey,counter:e.credential.counter,name:e.name,...e.credential.transports&&{transports:e.credential.transports}}).pipe(UI.mapError((i)=>y7(i)?new MI({credentialId:e.credential.id}):i)),yield*h7(e.userId)});class cf extends g7.TaggedError("PasskeyManagementRequestError"){}var HI=Br.Trim.pipe(Br.minLength(1),Br.maxLength(128)),tj=Br.String.pipe(Br.minLength(1)),S7=Br.Struct({id:tj,name:HI}),v7=Br.Struct({id:tj}),x7=Br.Struct({name:HI}),w7=Br.Struct({challengeId:Br.String.pipe(Br.minLength(1)),response:PI}),b7=Br.Struct({type:Br.Literal("management"),challenge:Br.String,userId:Br.String,userHandle:Br.String,name:HI}),E7=300,Cr=(e,t=200)=>vb(e,{status:t,headers:{"cache-control":"no-store",pragma:"no-cache","x-content-type-options":"nosniff"}}),T7=(e)=>e.delegation===void 0&&(e.humanSession===!0||e.humanAuthentication?.method==="passkey"&&e.humanAuthentication.providerUserId===e.userId),mw=(e,t,r)=>({organisation:{name:e},account:t,credentials:r.map((n)=>({id:n.id,name:n.name,createdAt:yw.formatIso(n.createdAt),lastUsedAt:n.lastUsedAt===null?null:yw.formatIso(n.lastUsedAt)}))}),ej=(e)=>["passkey","management",e],jI=()=>new cf({status:400,error:"invalid_request"}),R7=vr.gen(function*(){let e=yield*Fn,t=yield*Kr,r=yield*Kn,n=yield*ps,o=yield*hr,i=(c)=>c.pipe(vr.provideService(Fn,e)),s=(c)=>c.pipe(vr.provideService(hr,o));return vr.gen(function*(){let c=yield*lr;if(c.method!=="GET"&&c.method!=="PATCH"&&c.method!=="POST"&&c.method!=="DELETE")return Cr({error:"method_not_allowed"},405);let l=c.headers.authorization?.match(/^Bearer ([^ ]+)$/)?.[1];if(!l)return Cr({error:"invalid_token"},401);let d=yield*t.allSigningKeys,u=yield*Un(c.headers).pipe(vr.mapError(()=>new cf({status:401,error:"invalid_token"}))),m=yield*yw.now,h=yield*vr.tryPromise({try:()=>Ei(l,async(ze)=>{let et=d.find((xt)=>xt.id===ze.kid&&xt.alg===ze.alg);if(!et)throw Error("Unknown signing key");return et.public},{issuer:u,audience:[...r.staticClients.values()].map((ze)=>ze.audience),requiredClaims:["exp","sub"],currentDate:yw.toDateUtc(m)}),catch:()=>new cf({status:401,error:"invalid_token"})});if(typeof h.payload.exp!=="number"||h.payload.mode!=="access"||h.payload.type!=="providerUser")return Cr({error:"invalid_token"},401);let S=yield*vr.promise(async()=>yc.providerUser["~standard"].validate(h.payload.properties));if(S.issues)return Cr({error:"invalid_token"},401);let x=S.value;if(!T7(x))return Cr({error:"management_denied"},403);if(new URL(c.url,"https://auth.invalid").searchParams.getAll("ownerUserId").length>0)return Cr({error:"invalid_request"},400);let w=yield*e.findOAuthProviderByName("passkey");if(fw.isNone(w))return Cr({error:"management_denied"},403);let P=yield*e.findProviderUserByUserId(x.userId);if(fw.isNone(P))return Cr({error:"invalid_token"},401);let F=yield*e.listPasskeyCredentialsForUser(x.userId);if(F.length===0)return Cr({error:"management_denied"},403);let R=yield*e.findRootOrgUnit(),b=fw.match(R,{onNone:()=>"Organisation",onSome:(ze)=>ze.name}),A=mw(b,{userId:P.value.id,email:P.value.email},F);if(c.method==="GET")return Cr(A);if(c.method==="DELETE"){let ze=yield*c.json.pipe(vr.flatMap(Br.decodeUnknown(v7,{onExcessProperty:"error"})),vr.mapError(()=>jI())),et=yield*e.removePasskeyCredential({userId:x.userId,id:ze.id});if(et==="last_credential")return Cr({error:"last_credential"},409);if(et==="not_found")return Cr({error:"management_denied"},403);let xt=yield*e.listPasskeyCredentialsForUser(x.userId);return Cr(mw(b,{userId:P.value.id,email:P.value.email},xt))}if(c.method==="PATCH"){let ze=yield*c.json.pipe(vr.flatMap(Br.decodeUnknown(S7,{onExcessProperty:"error"})),vr.mapError(()=>jI()));if(!(yield*e.renamePasskeyCredential({userId:x.userId,id:ze.id,name:ze.name})))return Cr({error:"management_denied"},403);let xt=yield*e.listPasskeyCredentialsForUser(x.userId);return Cr(mw(b,{userId:P.value.id,email:P.value.email},xt))}let D=yield*c.json.pipe(vr.mapError(()=>jI())),B=Br.decodeUnknownEither(x7,{onExcessProperty:"error"})(D),J=Br.decodeUnknownEither(w7)(D);if(qI.isRight(B)&&qI.isLeft(J)){let ze=yield*Br.decodeUnknown(Zg)(w.value.config).pipe(vr.mapError(()=>new cf({status:500,error:"internal_error"}))),et=af({...P.value,userId:P.value.id}),xt=yield*II({rpName:ze.rpName,rpID:ze.rpID,email:P.value.email,userHandle:et,excludeCredentials:F.map((Le)=>({id:Le.credentialId,...Le.transports&&{transports:Le.transports}}))}),dt=crypto.randomUUID();return yield*s(Vt.set(ej(dt),{type:"management",challenge:xt.challenge,userId:x.userId,userHandle:et,name:B.right.name},E7)),Cr({challengeId:dt,options:xt})}if(qI.isLeft(J))return Cr({error:"invalid_request"},400);let G=J.right,ce=yield*s(Vt.take(ej(G.challengeId))),re=Br.decodeUnknownOption(b7)(ce);if(fw.isNone(re)||re.value.userId!==x.userId)return Cr({error:"invalid_request"},400);let Z=yield*Br.decodeUnknown(Zg)(w.value.config).pipe(vr.mapError(()=>new cf({status:500,error:"internal_error"}))),se=yield*CI({origin:Z.origin,rpID:Z.rpID,expectedChallenge:re.value.challenge,response:G.response});if(!se.verified)return Cr({error:"verification_failed"},400);let te=yield*n.withTransaction(i(Zq({userId:x.userId,userHandle:re.value.userHandle,name:re.value.name,credential:se.credential}))).pipe(vr.catchTag("processfocus:internal-tag/PasskeyCredentialAlreadyOwnedError",(ze)=>vr.succeed("already_registered")),vr.catchTag("processfocus:internal-tag/PasskeyManagementDeniedError",(ze)=>vr.succeed("management_denied")),vr.catchTag("processfocus:internal-tag/PasskeyIdentityNotFoundError",(ze)=>vr.succeed("management_denied")));if(te==="already_registered")return Cr({error:"already_registered"},409);if(te==="management_denied")return Cr({error:"management_denied"},403);let Ne=yield*e.listPasskeyCredentialsForUser(x.userId);return Cr(mw(b,{userId:P.value.id,email:P.value.email},Ne))}).pipe(vr.catchTag("PasskeyManagementRequestError",({status:c,error:l})=>vr.succeed(Cr({error:l},c))),vr.catchAll(()=>vr.logError("Unexpected passkey management failure").pipe(vr.as(Cr({error:"internal_error"},500)))))});import{DateTime as ttt,Duration as rtt,Effect as ntt,Option as ott}from"effect";import{Effect as Ntt}from"effect";import{Data as Sh,DateTime as Stt,Effect as vtt,Either as xtt,Option as wtt,Schema as so}from"effect";import{Data as A7,Effect as utt,Schema as zc}from"effect";class P7 extends A7.TaggedError("processfocus:internal-tag/GoogleDirectoryError"){}var ptt=zc.Struct({client_email:zc.String,private_key:zc.String}),ftt=zc.Struct({access_token:zc.String}),mtt=zc.Struct({orgUnitPath:zc.optionalWith(zc.String,{exact:!0})});class I7 extends Sh.TaggedError("processfocus:internal-tag/RootOrgUnitNotFoundError"){}class C7 extends Sh.TaggedError("processfocus:internal-tag/InviteRequiredError"){}class _7 extends Sh.TaggedError("processfocus:internal-tag/DummyProviderUserNotFoundError"){}class nj extends Sh.TaggedError("processfocus:internal-tag/VerifiedEmailRequiredError"){}class k7 extends Sh.TaggedError("processfocus:internal-tag/ProviderUserEmailAlreadyOwnedError"){}var Ptt=so.Struct({sub:so.String,email:so.String,name:so.String,given_name:so.optionalWith(so.String,{exact:!0}),family_name:so.optionalWith(so.String,{exact:!0}),picture:so.optionalWith(so.String,{exact:!0}),locale:so.optionalWith(so.String,{exact:!0}),email_verified:so.optionalWith(so.Boolean,{exact:!0})}),Itt=so.Struct({sub:so.String});import{Clock as qtt,Effect as jtt}from"effect";class O7 extends Cd.TaggedError("ClientJwtMintError"){}class D7 extends Cd.TaggedError("FrontendJwtCreateError"){}class N7 extends Cd.TaggedError("ProviderUserAuthenticationError"){}class F7 extends Cd.TaggedError("UnsupportedProviderError"){}class U7 extends Cd.TaggedError("ProviderConfigurationError"){}class B7 extends Cd.TaggedError("InvalidProviderConfigError"){}class M7 extends Cd.TaggedError("InvalidRoleScopeError"){}var ent=St.Struct({clientID:St.String,clientSecret:St.String,scopes:St.mutable(St.Array(St.String)),pkce:St.optional(St.Boolean),query:St.optional(St.Record({key:St.String,value:St.String})),responseMode:St.optional(St.Literal("query","form_post")),tenant:St.optional(St.String),team:St.optional(St.String),baseUrl:St.optional(St.String),realm:St.optional(St.String),domain:St.optional(St.String),region:St.optional(St.String),userPoolId:St.optional(St.String)}).pipe(St.extend(St.Record({key:St.String,value:St.Unknown})));var tnt=St.Struct({rpName:St.String,rpID:St.String,origin:St.Union(St.String,St.mutable(St.Array(St.String)))});import{Data as ao}from"effect";class Mi extends ao.TaggedError("UpdateDeletedDocumentError"){}class oj extends ao.TaggedError("NoProviderUserID"){}class ij extends ao.TaggedError("ProviderUserNotFound"){}class L7 extends ao.TaggedError("NotAuthorized"){}class $7 extends ao.TaggedError("ProcessStateNotFound"){}class q7 extends ao.TaggedError("PublicCompletionInvitationNotFound"){}class j7 extends ao.TaggedError("MissingGeneratedSchemaError"){}class H7 extends ao.TaggedError("InputValidationError"){get message(){if(this.errors.length===1){let t=this.errors[0];if(!t)return"Validation failed";if(!t.field)return`Validation failed: ${t.message}`;return`Validation failed for field '${t.field}': ${t.message}`}return`Validation failed for fields:
|
|
435
|
+
- ${this.errors.map((t)=>t.field?`'${t.field}': ${t.message}`:t.message).join(`
|
|
436
|
+
- `)}`}}class W7 extends ao.TaggedError("ExecutionIdConflictError"){get message(){return`executionId is already used for a different process start: ${this.executionId}`}}class K7 extends ao.TaggedError("StepCompletionConflictError"){get message(){return"The process changed while completing this step. Refresh and try again."}}class V7 extends ao.TaggedError("UpdateProviderUserError"){}class Q7 extends ao.TaggedError("DocumentStoreNotFoundError"){get message(){return`Document store not found: ${this.path}`}}class J7 extends ao.TaggedError("ListNotFoundError"){get message(){return`List not found: ${this.listPath}`}}class z7 extends ao.TaggedError("ExportRowLimitError"){get message(){return`Export for list "${this.listPath}" matched ${this.rowCount} rows, exceeding the limit of ${this.maxRows}`}}class G7 extends ao.TaggedError("ExportNonScalarError"){get message(){return`Export for list "${this.listPath}" contains non-scalar value in field "${this.field}" (type: ${this.valueType}). Only strings, numbers, booleans, and nulls are supported.`}}class Y7 extends ao.TaggedError("AuthorizedPageTimeoutError"){}import{Data as X7,Effect as Ent,Schema as js}from"effect";var Z7="graphql-api",eZ=`${Z7}:public-todo`,Tnt=js.Struct({v:js.Literal(1),tid:js.String,externalParticipantEmail:js.optional(js.String),publicCompletionInvitationAttemptId:js.optional(js.String),iat:js.Number,exp:js.Number,aud:js.Literal(eZ)});class tZ extends X7.TaggedError("PublicTodoTokenError"){}import{Data as rZ,Effect as Pnt}from"effect";class nZ extends rZ.TaggedError("RegistrationLinkCryptoError"){}import{Context as oZ}from"effect";class WI extends oZ.Tag("processfocus:internal-tag/graphql-db-operations/BusinessCalendarQueries")(){}import{Data as iZ,DateTime as Bnt,Effect as Mnt}from"effect";class sZ extends iZ.TaggedError("processfocus:internal-tag/InvalidCalendarDataError"){}import{Context as aZ}from"effect";class KI extends aZ.Tag("processfocus:internal-tag/graphql-db-operations/CleanupOperations")(){}import{Context as cZ}from"effect";class VI extends cZ.Tag("processfocus:internal-tag/graphql-db-operations/CompletedJobOperations")(){}import{Context as lZ}from"effect";class QI extends lZ.Tag("processfocus:internal-tag/graphql-db-operations/DraftProcessExecutionQueries")(){}import{Context as dZ}from"effect";class JI extends dZ.Tag("processfocus:internal-tag/graphql-db-operations/ExecutionDurationQueries")(){}import{Context as uZ}from"effect";class zI extends uZ.Tag("processfocus:internal-tag/graphql-db-operations/ExecutionQueries")(){}import{Context as pZ,Data as fZ}from"effect";class GI extends fZ.TaggedError("InvalidExternalParticipantEmail"){}var sj=(e)=>{let t=e.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t))return null;return t};class YI extends pZ.Tag("processfocus:internal-tag/graphql-db-operations/ExternalParticipantOperations")(){}import{Context as mZ}from"effect";class XI extends mZ.Tag("processfocus:internal-tag/graphql-db-operations/FileOperations")(){}import{Context as hZ}from"effect";import{Context as yZ}from"effect";var vh={notifications:{todoAssignment:{email:!1},executionFailure:{email:!1}}},_d=(e)=>{if(!e||typeof e!=="object")return vh;let r=e.notifications??{},n=r.todoAssignment??{},o=r.executionFailure??{};return{notifications:{todoAssignment:{email:typeof n.email==="boolean"?n.email:!1},executionFailure:{email:typeof o.email==="boolean"?o.email:!1}}}},ZI=(e)=>({notifications:{todoAssignment:{email:e.notifications.todoAssignment.email},executionFailure:{email:e.notifications.executionFailure.email}}}),ar={Pending:"pending",Accepted:"accepted",LegacyClosed:"legacy_closed"},Gc={Model:"model",Dashboard:"dashboard",Process:"process",Legacy:"legacy"},kd={NotGenerated:"not_generated",Active:"active",Expired:"expired",Revoked:"revoked"};class xh extends yZ.Tag("processfocus:internal-tag/graphql-db-operations/SettingsQueries")(){}var wh=(e)=>Array.isArray(e)&&e.every((t)=>typeof t==="string")?e:null,hw=(e)=>({providerUserId:e.providerUserId,userId:e.userId,email:e.email,name:e.name,firstName:e.firstName,lastName:e.lastName,todoAssignmentEmailEnabled:_d(e.notificationPreference).notifications.todoAssignment.email,executionFailureEmailEnabled:_d(e.notificationPreference).notifications.executionFailure.email});class eC extends hZ.Tag("processfocus:internal-tag/graphql-db-operations/FlowExecutionOperations")(){}function gw(e){if(e===null||e<=5)return"Simple";if(e<=15)return"Medium";return"Complex"}import{Effect as cot}from"effect";import{Context as gZ,Data as SZ}from"effect";class bh extends SZ.TaggedError("StepNotFoundError"){}class tC extends gZ.Tag("processfocus:internal-tag/graphql-db-operations/ProcessExecutionOperations")(){}import{Context as vZ}from"effect";class rC extends vZ.Tag("processfocus:internal-tag/graphql-db-operations/FlowQueries")(){}import{Context as xZ}from"effect";class nC extends xZ.Tag("processfocus:internal-tag/graphql-db-operations/OAuthClientQueries")(){}import{Context as wZ}from"effect";class oC extends wZ.Tag("processfocus:internal-tag/graphql-db-operations/OrgQueries")(){}import{Context as aj}from"effect";class iC extends aj.Tag("processfocus:internal-tag/graphql-db-operations/ProcessQueries")(){}class sC extends aj.Tag("processfocus:internal-tag/graphql-db-operations/ProcessCollectionQueries")(){}import{Context as bZ}from"effect";class aC extends bZ.Tag("processfocus:internal-tag/graphql-db-operations/ProviderUserQueries")(){}import{Context as EZ,Data as TZ}from"effect";class cC extends TZ.TaggedError("ProcessNotFoundError"){}class lC extends EZ.Tag("processfocus:internal-tag/graphql-db-operations/WorkflowQueries")(){}import{DateTime as _ot,Effect as kot,Either as Oot}from"effect";import{Effect as cj}from"effect";var zt=(e)=>{let t=e[0];return t===void 0?cj.dieMessage("Database write returned no row"):cj.succeed(t)};import{Context as RZ}from"effect";class dC extends RZ.Tag("processfocus:internal-tag/graphql-db-operations/ScheduledFlowOperations")(){}import{Context as AZ,Data as lj}from"effect";class PZ extends lj.TaggedError("TodoNotFoundError"){}class Sw extends lj.TaggedError("InvalidProcessStateError"){}class uC extends AZ.Tag("processfocus:internal-tag/graphql-db-operations/StepCompletionOperations")(){}import{Context as IZ}from"effect";class pC extends IZ.Tag("processfocus:internal-tag/graphql-db-operations/StepRoleQueries")(){}import{Context as CZ}from"effect";class fC extends CZ.Tag("processfocus:internal-tag/graphql-db-operations/SystemUserOperations")(){}import{Context as _Z}from"effect";class mC extends _Z.Tag("processfocus:internal-tag/graphql-db-operations/TodoQueries")(){}import{Context as kZ,Effect as OZ,FiberRef as DZ,Option as zot,Schema as Od}from"effect";var Got=Od.Struct({version:Od.Literal(1),ownerUserId:Od.String,ownerEmail:Od.String,delegationId:Od.String,generationId:Od.String,name:Od.String});class dj extends kZ.Tag("processfocus:internal-tag/graphql-db-operations/UserDetails")(){}var st=()=>OZ.flatMap(dj,DZ.get);import{DateTime as Da,Effect as co,Layer as NZ,Option as yC}from"effect";var hC=NZ.effect(qs,co.gen(function*(){let e=yield*pe,t=e.select({id:Wn.secretGenerationId}).from(Wn).where(p(Wn.delegationEvent,"replaced"));return qs.of({hasGeneration:(r)=>e.select({id:We.id}).from(We).where(p(We.id,r)).limit(1).pipe(co.map((n)=>n.length>0),Kt("Failed to check Secret Generation")),findGeneration:(r)=>e.select({id:gt.id,name:gt.delegationName,generationId:We.id,parentGenerationId:We.parentSecretGenerationId,ownerId:O.id,userId:O.userId,createdAt:We.secretIssuedAt,expiresAt:We.secretExpiresAt,revokedAt:gt.secretRevokedAt,generationRevokedAt:We.secretRevokedAt,lastUsedAt:We.secretLastUsedAt}).from(We).innerJoin(gt,p(gt.id,We.delegationId)).innerJoin(O,p(O.id,gt.ownerProviderUserId)).innerJoin(X,p(X.id,O.userId)).where(_("verifier"in r?p(We.secretVerifier,r.verifier):p(We.id,r.generationId),p(We._deleted,!1),un(We.id,t),p(gt._deleted,!1),p(O._deleted,!1),p(X._deleted,!1))).pipe(co.map((n)=>yC.fromNullable(n[0]).pipe(yC.map((o)=>({...o,expiresAt:Da.unsafeMake(Math.round(Da.toEpochMillis(o.expiresAt)/1000)*1000)})))),Kt("Failed to resolve Secret Generation")),recordUse:({generationId:r,usedAt:n})=>e.update(We).set({secretLastUsedAt:n}).where(_(p(We.id,r),Rt(Se(We.secretLastUsedAt),dn(We.secretLastUsedAt,Da.subtract(n,{seconds:30}))))).pipe(co.asVoid,yr("Failed to record delegated use")),recordLogin:({delegationId:r,generationId:n,ownerId:o,loggedInAt:i})=>e.insert(Wn).values({delegationId:r,secretGenerationId:n,actorProviderUserId:o,actorDelegationId:r,actorSecretGenerationId:n,delegationEvent:"login",secretIssuedAt:i}).pipe(co.asVoid,yr("Failed to record delegated login")),isSecretLoginEnabled:()=>e.select({config:mt.providerConfig}).from(mt).where(p(mt._deleted,!1)).pipe(co.map((r)=>r.some(({config:n})=>typeof n==="object"&&n!==null&&("delegatedAccess"in n)&&n.delegatedAccess===!0)),Kt("Failed to read secret-login presentation configuration")),findOwnerId:(r)=>e.select({id:O.id}).from(O).innerJoin(X,p(X.id,O.userId)).where(_(p(O.userId,r),p(O._deleted,!1),p(X._deleted,!1))).pipe(co.map((n)=>yC.fromNullable(n[0]?.id)),Kt("Failed to resolve Delegation owner")),list:(r)=>e.select({id:gt.id,name:gt.delegationName,generationId:We.id,createdAt:We.secretIssuedAt,expiresAt:We.secretExpiresAt,revokedAt:gt.secretRevokedAt,lastUsedAt:We.secretLastUsedAt}).from(gt).innerJoin(We,p(We.delegationId,gt.id)).where(_(p(gt.ownerProviderUserId,r),p(gt._deleted,!1),p(We._deleted,!1),un(We.id,t))).orderBy(We.secretIssuedAt,gt.id).pipe(co.map((n)=>n.map((o)=>({...o,createdAt:Da.unsafeMake(Math.round(Da.toEpochMillis(o.createdAt)/1000)*1000),expiresAt:Da.unsafeMake(Math.round(Da.toEpochMillis(o.expiresAt)/1000)*1000),revokedAt:o.revokedAt===null?null:Da.unsafeMake(Math.round(Da.toEpochMillis(o.revokedAt)/1000)*1000)}))),Kt("Failed to list Delegations")),releaseExpiredNames:(r,n)=>e.update(gt).set({activeDelegationName:null}).where(_(p(gt.ownerProviderUserId,r),Rt(Nt(gt.secretRevokedAt),Fe(gt.id,e.select({id:We.delegationId}).from(We).where(_(p(We._deleted,!1),un(We.id,t),dn(We.secretExpiresAt,n))))))).pipe(co.asVoid,yr("Failed to release expired Delegation names")),claimName:({id:r,ownerId:n,name:o})=>e.insert(gt).values({id:r,ownerProviderUserId:n,delegationName:o,activeDelegationName:o}).onConflictDoNothing().returning({id:gt.id}).pipe(co.map((i)=>i.length===1),yr("Failed to claim Delegation name")),updateName:({id:r,name:n,activeName:o})=>e.update(gt).set({delegationName:n,activeDelegationName:o}).where(p(gt.id,r)).pipe(co.asVoid,yr("Failed to rename Delegation")),revokeGeneration:({generationId:r,revokedAt:n})=>e.update(We).set({secretRevokedAt:n}).where(_(p(We.id,r),Se(We.secretRevokedAt))).pipe(co.asVoid,yr("Failed to revoke Secret Generation")),revoke:({id:r,revokedAt:n})=>e.update(gt).set({secretRevokedAt:n,activeDelegationName:null}).where(_(p(gt.id,r),Se(gt.secretRevokedAt))).pipe(co.asVoid,yr("Failed to revoke Delegation")),recordChange:(r)=>e.insert(Wn).values({delegationId:r.delegationId,secretGenerationId:r.generationId,actorProviderUserId:r.actorId,actorDelegationId:r.actorDelegation?.id,actorSecretGenerationId:r.actorDelegation?.generationId,delegationEvent:r.event,secretIssuedAt:r.occurredAt,...r.event==="renamed"?{oldDelegationName:r.oldName,newDelegationName:r.newName}:{}}).pipe(co.asVoid,yr("Failed to record Delegation change")),insertGeneration:({id:r,delegationId:n,parentGenerationId:o,verifier:i,issuedAt:s,expiresAt:a})=>e.insert(We).values({id:r,delegationId:n,parentSecretGenerationId:o??null,secretVerifier:i,secretIssuedAt:s,secretExpiresAt:a}).pipe(co.asVoid,yr("Failed to store Secret Generation")),recordIssuance:({delegationId:r,generationId:n,actorId:o,actorDelegation:i,issuedAt:s})=>e.insert(Wn).values({delegationId:r,secretGenerationId:n,actorProviderUserId:o,actorDelegationId:i?.id,actorSecretGenerationId:i?.generationId,delegationEvent:"issued",secretIssuedAt:s}).pipe(co.asVoid,yr("Failed to record Delegation issuance"))})}));ol();import{Duration as FZ,Effect as UZ,Schedule as uj}from"effect";var BZ=["socket connection was closed unexpectedly"],MZ=["ECONNRESET"],LZ=(e,t)=>t.some((r)=>e.includes(r)),$Z=(e,t)=>t.some((r)=>e===r);var Eh=(e)=>nl(e)||ds(e,(t)=>LZ(t,BZ),{codePredicate:(t)=>$Z(t,MZ)}),qZ=uj.addDelay(uj.recurs(3),()=>FZ.millis(100)),Na=(e)=>e.pipe(UZ.retry({schedule:qZ,while:Eh}));var KZ=32,fj=(e)=>yj("sha256").update(Buffer.from(e,"base64url")).digest("base64url"),VZ=()=>{let e=HZ(KZ);return{rawBearer:e.toString("base64url"),tokenHash:yj("sha256").update(e).digest("base64url")}};class gC extends hj.TaggedError("ProviderUserNotFoundError"){}class gj extends hj.TaggedError("OrgUnitNotFoundError"){}var Sj=String.fromCharCode(31),QZ=String.fromCharCode(65535),Th=(e)=>e.join(Sj),JZ=(e)=>`${e}${QZ}`,zZ=(e)=>e.split(Sj),GZ=Je.gen(function*(){let e=yield*pe,t=yield*ci.now;return(yield*e.delete(Rr).where(_(ko(Se(Rr.keyExpiry)),dn(Rr.keyExpiry,t))).returning({id:Rr.id})).length}),YZ=(e)=>e[0]??"unknown",mj=(e)=>({id:e.id,name:e.name,orgUnitLevel:e.orgUnitLevel,path:e.path,parentOrgUnitId:e.parentOrgUnitId}),Rh=(e)=>({id:e.providerUser.userId,email:e.providerUser.email,locale:e.providerUser.locale,picture:e.providerUser.picture,provider:e.user.provider,sub:e.user.sub,orgUnitId:e.providerUser.orgUnitId,orgUnitPath:e.orgUnit.path}),XZ=SC.effect(Fn,Je.gen(function*(){let e=yield*pe;return{findRecoveryInvitation:(t,r)=>Je.gen(function*(){let n=yield*e.select({id:k.id}).from(k).innerJoin(O,p(k.acceptedByProviderUserId,O.id)).where(_(p(O.userId,t),p(O.email,r),p(O._deleted,!1),p(k.email,r),Fe(k.invitationStatus,[ar.Accepted,ar.LegacyClosed]),p(k._deleted,!1))).limit(1);return Ut.fromNullable(n[0]?.id)}).pipe(Kt("Failed to find recovery invitation")),findRootOrgUnit:()=>Je.gen(function*(){let r=(yield*e.select().from(V).where(_(Se(V.parentOrgUnitId),p(V._deleted,!1))).limit(1))[0];if(!r)return Ut.none();return Ut.some(mj(r))}).pipe(Kt("Failed to find root organization unit")),findProviderUserByProviderSub:(t,r)=>Je.gen(function*(){let o=(yield*e.select().from(O).innerJoin(X,p(O.userId,X.id)).innerJoin(V,p(O.orgUnitId,V.id)).where(_(p(X.provider,t),p(X.sub,r),p(O._deleted,!1),p(X._deleted,!1),p(V._deleted,!1))).limit(1))[0];if(!o)return Ut.none();return Ut.some(Rh({providerUser:o.pf_provider_user,user:o.pf_user,orgUnit:o.pf_org_unit}))}).pipe(Kt("Failed to find provider user by provider subject")),findProviderUserByEmail:(t)=>Je.gen(function*(){let n=(yield*e.select().from(O).innerJoin(X,p(O.userId,X.id)).innerJoin(V,p(O.orgUnitId,V.id)).where(_(f`lower(${O.email}) = ${t.toLowerCase()}`,p(O._deleted,!1),p(X._deleted,!1),p(V._deleted,!1))).limit(1))[0];if(!n)return Ut.none();return Ut.some(Rh({providerUser:n.pf_provider_user,user:n.pf_user,orgUnit:n.pf_org_unit}))}).pipe(Kt("Failed to find provider user by email")),findProviderUserById:(t)=>Je.gen(function*(){let n=(yield*e.select().from(O).innerJoin(X,p(O.userId,X.id)).innerJoin(V,p(O.orgUnitId,V.id)).where(_(p(O.id,t),p(O._deleted,!1),p(X._deleted,!1),p(V._deleted,!1))).limit(1))[0];if(!n)return Ut.none();return Ut.some(Rh({providerUser:n.pf_provider_user,user:n.pf_user,orgUnit:n.pf_org_unit}))}).pipe(Kt("Failed to find provider user by id")),findProviderUserByUserId:(t)=>Je.gen(function*(){let n=(yield*e.select().from(O).innerJoin(X,p(O.userId,X.id)).innerJoin(V,p(O.orgUnitId,V.id)).where(_(p(O.userId,t),p(O._deleted,!1),p(X._deleted,!1),p(V._deleted,!1))).limit(1))[0];if(!n)return Ut.none();return Ut.some(Rh({providerUser:n.pf_provider_user,user:n.pf_user,orgUnit:n.pf_org_unit}))}).pipe(Kt("Failed to find provider user by user id")),createProviderUser:(t)=>Je.gen(function*(){let r=yield*ci.now,n=yield*e.insert(X).values({provider:t.provider,sub:t.sub,lastLoggedIn:r}).returning(),o=yield*zt(n),i=yield*e.insert(O).values({userId:o.id,email:t.email,name:t.name,firstName:t.firstName,lastName:t.lastName,picture:t.picture,locale:t.locale,orgUnitId:t.orgUnitId}).returning(),s=yield*zt(i),c=(yield*e.select({path:V.path}).from(V).where(p(V.id,t.orgUnitId)).limit(1))[0];if(!c)return yield*new gj({orgUnitId:t.orgUnitId});return Rh({providerUser:s,user:o,orgUnit:c})}).pipe(yr("Failed to create provider user")),findPasskeyCredentialById:(t)=>Je.gen(function*(){let n=(yield*e.select({userId:Xe.userId,email:O.email,sub:X.sub,provider:X.provider,credentialId:Xe.passkeyCredentialId,publicKey:Xe.passkeyPublicKey,counter:Xe.signatureCounter,transports:Xe.passkeyTransports}).from(Xe).innerJoin(X,p(Xe.userId,X.id)).innerJoin(O,p(O.userId,X.id)).where(_(p(Xe.passkeyCredentialId,t),p(Xe._deleted,!1),p(X._deleted,!1),p(O._deleted,!1))).limit(1))[0];if(!n)return Ut.none();let o=Array.isArray(n.transports)?n.transports.filter((i)=>typeof i==="string"):void 0;return Ut.some({userId:n.userId,email:n.email,provider:n.provider,sub:n.sub,credentialId:n.credentialId,publicKey:n.publicKey,counter:Number(n.counter),...o&&{transports:o}})}).pipe(Kt("Failed to find passkey credential")),createPasskeyCredential:(t)=>e.insert(Xe).values({userId:t.userId,passkeyCredentialId:t.credentialId,passkeyPublicKey:t.publicKey,signatureCounter:String(t.counter),...t.transports&&{passkeyTransports:[...t.transports]},...t.name!==void 0&&{passkeyName:t.name}}).pipe(yr("Failed to create passkey credential"),Je.asVoid),listPasskeyCredentialsForUser:(t)=>e.select({id:Xe.id,name:Xe.passkeyName,createdAt:Xe.createdAt,lastUsedAt:Xe.passkeyLastUsedAt,credentialId:Xe.passkeyCredentialId,transports:Xe.passkeyTransports}).from(Xe).where(_(p(Xe.userId,t),p(Xe._deleted,!1))).orderBy(Oo(Xe.createdAt),Oo(Xe.id)).pipe(Je.map((r)=>r.map((n)=>{let o=Array.isArray(n.transports)?n.transports.filter((i)=>typeof i==="string"):void 0;return{id:n.id,name:n.name,createdAt:n.createdAt,lastUsedAt:n.lastUsedAt??null,credentialId:n.credentialId,...o&&{transports:o}}})),Kt("Failed to list passkey credentials")),renamePasskeyCredential:(t)=>e.update(Xe).set({passkeyName:t.name}).where(_(p(Xe.id,t.id),p(Xe.userId,t.userId),p(Xe._deleted,!1))).returning({id:Xe.id}).pipe(Je.map((r)=>r.length===1)).pipe(yr("Failed to rename passkey credential")),removePasskeyCredential:(t)=>Je.gen(function*(){let r=yield*ci.now;if((yield*e.update(Xe).set({_deleted:!0,updatedAt:r,updatedBy:"SYSTEM"}).where(_(p(Xe.id,t.id),p(Xe.userId,t.userId),p(Xe._deleted,!1),Xt(e.select({count:vT()}).from(e.select({id:Xe.id}).from(Xe).where(_(p(Xe.userId,t.userId),p(Xe._deleted,!1))).as("remaining")),1))).returning({id:Xe.id}).pipe(yr("Failed to remove passkey credential"))).length===1)return"removed";return(yield*e.select({id:Xe.id}).from(Xe).where(_(p(Xe.id,t.id),p(Xe.userId,t.userId),p(Xe._deleted,!1))).limit(1).pipe(yr("Failed to remove passkey credential"))).length===1?"last_credential":"not_found"}),advancePasskeyCredentialCounter:(t,r,n,o)=>e.update(Xe).set({signatureCounter:String(n),...o!==void 0&&{passkeyLastUsedAt:o}}).where(_(p(Xe.passkeyCredentialId,t),p(Xe.signatureCounter,String(r)),p(Xe._deleted,!1))).returning({id:Xe.id}).pipe(Je.map((i)=>i.length===1)).pipe(yr("Failed to advance passkey credential counter")),updateLastLoggedIn:(t,r)=>e.update(X).set({lastLoggedIn:r}).where(p(X.id,t)).pipe(yr("Failed to update last logged in"),Je.asVoid),updateProviderUserProfilePicture:(t,r)=>e.update(O).set({picture:r}).where(p(O.userId,t)).pipe(yr("Failed to update provider user profile picture"),Je.asVoid),findAllOAuthProviders:()=>Je.gen(function*(){return(yield*e.select({name:mt.providerName,config:mt.providerConfig}).from(mt).where(p(mt._deleted,!1))).map((r)=>({name:r.name,config:r.config}))}).pipe(Kt("Failed to list OAuth providers")),findOAuthProviderByName:(t)=>Je.gen(function*(){let n=(yield*e.select({name:mt.providerName,config:mt.providerConfig}).from(mt).where(_(p(mt.providerName,t),p(mt._deleted,!1))).limit(1))[0];return n?Ut.some({name:n.name,config:n.config}):Ut.none()}).pipe(Kt("Failed to find OAuth provider")),findProviderUserRoles:(t)=>Je.gen(function*(){return(yield*e.select({path:N.path}).from(rt).innerJoin(O,p(rt.providerUserId,O.id)).innerJoin(N,p(rt.roleId,N.id)).where(_(p(O.userId,t),p(rt._deleted,!1),p(O._deleted,!1),p(N._deleted,!1)))).map((n)=>n.path)}).pipe(Kt("Failed to find provider user roles")),findInvitationRoleIds:(t)=>Je.gen(function*(){let r=t.toLowerCase();return(yield*e.select({roleId:Oe.roleId}).from(k).innerJoin(Oe,p(Oe.invitationId,k.id)).innerJoin(N,p(N.id,Oe.roleId)).where(_(p(k.invitationPendingEmail,r),p(k.invitationStatus,"pending"),p(k._deleted,!1),p(Oe._deleted,!1),p(N._deleted,!1)))).map((o)=>o.roleId)}).pipe(Kt("Failed to find invitation role ids")),hasPendingInvitation:(t)=>Je.gen(function*(){let r=t.toLowerCase();return(yield*e.select({id:k.id}).from(k).where(_(p(k.invitationPendingEmail,r),p(k.invitationStatus,"pending"),p(k._deleted,!1))).limit(1)).length>0}).pipe(Kt("Failed to check pending invitation")),acceptPendingInvitationForUser:(t)=>Je.gen(function*(){let r=t.email.toLowerCase(),o=(yield*e.select({id:O.id}).from(O).where(_(p(O.userId,t.userId),p(O._deleted,!1))).limit(1))[0];if(!o)return yield*new gC({userId:t.userId});let i=t.invitationPin?[p(k.id,t.invitationPin.invitationId),f`coalesce(${k.registrationLinkGeneration}, 0) = ${t.invitationPin.linkGeneration}`]:[],s=yield*e.update(k).set({invitationStatus:"accepted",invitationPendingEmail:null,invitationAcceptedAt:t.acceptedAt,invitationAcceptedByProvider:t.provider,invitationAcceptedBySubject:t.subject,acceptedByProviderUserId:o.id,registrationTokenHash:null,registrationEncryptionVersion:null,registrationEncryptionNonce:null,registrationAuthenticationTag:null,registrationEncryptedToken:null,registrationLinkExpiresAt:null,registrationLinkGeneration:f`coalesce(${k.registrationLinkGeneration}, 0) + 1`,updatedAt:t.acceptedAt,updatedBy:"SYSTEM"}).where(_(p(k.invitationPendingEmail,r),p(k.invitationStatus,"pending"),p(k._deleted,!1),...i)).returning({id:k.id}),a=s[0];if(a)yield*e.update(Zr).set({_deleted:!0,updatedAt:t.acceptedAt,updatedBy:"SYSTEM"}).where(_(p(Zr.invitationId,a.id),p(Zr._deleted,!1)));return s.length>0}).pipe(yr("Failed to accept pending invitation")),exchangeRegistrationLink:(t)=>Je.gen(function*(){let r=fj(t),n=yield*ci.now;if((yield*e.select({id:mt.id}).from(mt).where(_(p(mt.providerName,"passkey"),p(mt._deleted,!1))).limit(1)).length===0)return Ut.none();let s=(yield*e.select({id:k.id,email:k.email,generation:k.registrationLinkGeneration,expiresAt:k.registrationLinkExpiresAt,pendingEmail:k.invitationPendingEmail}).from(k).where(_(p(k.registrationTokenHash,r),p(k.invitationStatus,"pending"),p(k._deleted,!1))).limit(1))[0];if(!s||s.generation===null||!s.expiresAt||!s.pendingEmail)return Ut.none();if(ci.lessThanOrEqualTo(s.expiresAt,n))return Ut.none();if((yield*e.select({roleId:Oe.roleId}).from(Oe).innerJoin(N,p(N.id,Oe.roleId)).where(_(p(Oe.invitationId,s.id),p(Oe._deleted,!1),p(N._deleted,!1))).limit(1)).length===0)return Ut.none();if((yield*e.select({id:O.id}).from(O).where(_(p(O.email,s.pendingEmail),p(O._deleted,!1))).limit(1)).length>0)return Ut.none();let{rawBearer:l,tokenHash:d}=VZ(),u=ci.add(n,{minutes:Yq});return yield*e.insert(Zr).values({registrationSessionTokenHash:d,invitationId:s.id,registrationLinkGeneration:s.generation,registrationSessionExpiresAt:u,createdAt:n,updatedAt:n,createdBy:"SYSTEM",updatedBy:"SYSTEM"}),Ut.some({email:s.pendingEmail,sessionBearer:l,expiresAt:u,invitationId:s.id,linkGeneration:s.generation})}).pipe(yr("Failed to exchange registration link")),resolveInvitationRegistrationSession:(t)=>Je.gen(function*(){let r=fj(t),n=yield*ci.now;if((yield*e.select({id:mt.id}).from(mt).where(_(p(mt.providerName,"passkey"),p(mt._deleted,!1))).limit(1)).length===0)return Ut.none();let s=(yield*e.select({sessionId:Zr.id,sessionHash:Zr.registrationSessionTokenHash,sessionGeneration:Zr.registrationLinkGeneration,sessionExpiresAt:Zr.registrationSessionExpiresAt,invitationId:k.id,pendingEmail:k.invitationPendingEmail,invitationStatus:k.invitationStatus,invitationDeleted:k._deleted,linkGeneration:k.registrationLinkGeneration}).from(Zr).innerJoin(k,p(k.id,Zr.invitationId)).where(_(p(Zr.registrationSessionTokenHash,r),p(Zr._deleted,!1),Xt(Zr.registrationSessionExpiresAt,n))).limit(1))[0];if(!s||s.invitationDeleted||s.invitationStatus!=="pending"||!s.pendingEmail||s.linkGeneration===null||s.sessionGeneration!==s.linkGeneration)return Ut.none();if((yield*e.select({roleId:Oe.roleId}).from(Oe).innerJoin(N,p(N.id,Oe.roleId)).where(_(p(Oe.invitationId,s.invitationId),p(Oe._deleted,!1),p(N._deleted,!1))).limit(1)).length===0)return Ut.none();if((yield*e.select({id:O.id}).from(O).where(_(p(O.email,s.pendingEmail),p(O._deleted,!1))).limit(1)).length>0)return Ut.none();return Ut.some({email:s.pendingEmail,invitationId:s.invitationId,linkGeneration:s.linkGeneration,sessionTokenHash:s.sessionHash,sessionId:s.sessionId})}).pipe(Kt("Failed to resolve registration session")),deleteRegistrationSessionsForInvitation:(t)=>Je.gen(function*(){let r=yield*ci.now;yield*e.update(Zr).set({_deleted:!0,updatedAt:r,updatedBy:"SYSTEM"}).where(_(p(Zr.invitationId,t),p(Zr._deleted,!1)))}).pipe(yr("Failed to delete registration sessions")),findRoleIdsByPaths:(t)=>Je.gen(function*(){if(t.length===0)return[];return(yield*e.select({id:N.id}).from(N).where(_(Fe(N.path,t),p(N._deleted,!1)))).map((n)=>n.id)}).pipe(Kt("Failed to find role ids by paths")),assignProviderUserRoles:(t,r)=>Je.gen(function*(){if(r.length===0)return;let o=(yield*e.select({id:O.id}).from(O).where(_(p(O.userId,t),p(O._deleted,!1))).limit(1))[0];if(!o)return yield*new gC({userId:t});let i=yield*ci.now;yield*e.insert(rt).values(r.map((s)=>({providerUserId:o.id,roleId:s,createdAt:i,updatedAt:i})))}).pipe(yr("Failed to assign provider user roles")),findAllOAuthClients:()=>Je.gen(function*(){return yield*e.select({clientId:Ft.clientId,secretHash:Ft.clientSecretHash,audience:Ft.audience}).from(Ft).where(p(Ft._deleted,!1))}).pipe(Kt("Failed to list OAuth clients")),findOAuthClientById:(t)=>Je.gen(function*(){let n=(yield*e.select({clientId:Ft.clientId,secretHash:Ft.clientSecretHash,audience:Ft.audience}).from(Ft).where(_(p(Ft.clientId,t),p(Ft._deleted,!1))).limit(1))[0];return n?Ut.some(n):Ut.none()}).pipe(Kt("Failed to find OAuth client")),validateRolePaths:(t)=>Je.gen(function*(){if(t.length===0)return[];return(yield*e.select({path:N.path}).from(N).where(_(Fe(N.path,t),p(N._deleted,!1)))).map((n)=>n.path)}).pipe(Kt("Failed to validate role paths")),upsertM2MUser:(t,r,n)=>Je.gen(function*(){let i=n?.updateLastLoggedIn!==!1,s=_(p(X.provider,"client_credentials"),p(X.sub,t),p(X._deleted,!1)),a=()=>e.select({id:X.id}).from(X).where(s).limit(1);if(i){let m=yield*e.update(X).set({lastLoggedIn:r,updatedAt:r}).where(s).returning({id:X.id}).pipe(Na,Je.catchAll((h)=>Eh(h)?Je.logWarning("Non-critical last_logged_in update failed, continuing authentication").pipe(Je.annotateLogs({error:h,clientId:t}),Je.as([])):Je.fail(h)));if(m[0])return m[0].id}let c=yield*a();if(c[0])return c[0].id;let l=e.insert(X).values({provider:"client_credentials",sub:t,lastLoggedIn:r,createdAt:r,updatedAt:r,createdBy:"SYSTEM",updatedBy:"SYSTEM"}),d=i?yield*l.onConflictDoUpdate({target:[X.provider,X.sub],targetWhere:f`_deleted = 0`,set:{lastLoggedIn:r,updatedAt:r}}).returning({id:X.id}).pipe(Na,Je.either):yield*l.returning({id:X.id}).pipe(Na,Je.either);if(WZ.isLeft(d)){let m=yield*a();if(m[0])return m[0].id;return yield*Je.fail(d.left)}return(yield*zt(d.right)).id}).pipe(yr("Failed to upsert M2M user")),findPermittedRolesWithOrgUnit:(t)=>Je.gen(function*(){return yield*e.select({rolePath:N.path,orgUnitId:N.orgUnitId,orgUnitPath:V.path}).from(Dn).innerJoin(O,p(Dn.providerUserId,O.id)).innerJoin(N,p(Dn.roleId,N.id)).innerJoin(V,p(N.orgUnitId,V.id)).where(_(p(O.userId,t),p(Dn._deleted,!1),p(O._deleted,!1),p(N._deleted,!1),p(V._deleted,!1)))}).pipe(Kt("Failed to find permitted roles")),findOrgUnitByPath:(t)=>Je.gen(function*(){let n=(yield*e.select().from(V).where(p(V.path,t)).limit(1))[0];if(!n)return Ut.none();return Ut.some(mj(n))}).pipe(Kt("Failed to find organization unit by path")),validateRolePathsWithOrgUnit:(t)=>Je.gen(function*(){if(t.length===0)return[];return yield*e.select({rolePath:N.path,orgUnitId:N.orgUnitId,orgUnitPath:V.path}).from(N).innerJoin(V,p(N.orgUnitId,V.id)).where(_(Fe(N.path,t),p(N._deleted,!1),p(V._deleted,!1)))}).pipe(Kt("Failed to validate role paths with org unit")),findPermittedClientRole:(t,r)=>Je.gen(function*(){let o=(yield*e.select({rolePath:N.path,orgUnitId:N.orgUnitId,orgUnitPath:V.path,updatedAt:Xn.updatedAt}).from(Ft).innerJoin(Xn,p(Xn.oauthClientId,Ft.id)).innerJoin(N,p(Xn.roleId,N.id)).innerJoin(V,p(N.orgUnitId,V.id)).where(_(p(Ft.clientId,t),p(N.path,r),p(Ft._deleted,!1),p(Xn._deleted,!1),p(N._deleted,!1),p(V._deleted,!1))).limit(1))[0];if(!o)return Ut.none();return Ut.some({rolePath:o.rolePath,orgUnitId:o.orgUnitId,orgUnitPath:o.orgUnitPath,updatedAt:o.updatedAt})}).pipe(Kt("Failed to find permitted client role")),findPermittedClientEmail:(t,r)=>Je.gen(function*(){let o=(yield*e.select({email:go.email,updatedAt:go.updatedAt}).from(Ft).innerJoin(go,p(go.oauthClientId,Ft.id)).where(_(p(Ft.clientId,t),p(go.email,r),p(Ft._deleted,!1),p(go._deleted,!1))).limit(1))[0];if(!o)return Ut.none();return Ut.some({email:o.email,updatedAt:o.updatedAt})}).pipe(Kt("Failed to find permitted client email"))}})),Ah=(e)=>e.pipe(Na,Je.mapError((t)=>new zi({message:t.message,cause:t}))),ZZ=SC.merge(XZ,hC),eee=SC.effect(hr,Je.gen(function*(){let e=yield*pe;return{get:(t)=>Ah(Je.gen(function*(){let r=Th(t),n=yield*ci.now,o=yield*e.select().from(Rr).where(_(p(Rr.oauthKey,r),Rt(Se(Rr.keyExpiry),Xt(Rr.keyExpiry,n)))).limit(1);if(o.length===0)return;let i=o[0];if(!i)return;return i.keyValue})),take:(t)=>Ah(Je.gen(function*(){let r=Th(t),n=yield*ci.now;return(yield*e.delete(Rr).where(_(p(Rr.oauthKey,r),Rt(Se(Rr.keyExpiry),Xt(Rr.keyExpiry,n)))).returning({value:Rr.keyValue}))[0]?.value})),set:(t,r,n)=>Ah(Je.gen(function*(){let o=Th(t),i=YZ(t),s=n===void 0?void 0:ci.unsafeMake(Date.now()+n*1000);yield*e.insert(Rr).values({oauthKey:o,keyKind:i,keyValue:r,keyExpiry:s}).onConflictDoUpdate({target:Rr.oauthKey,set:{keyValue:r,keyKind:i,keyExpiry:s}})})),remove:(t)=>Ah(Je.gen(function*(){let r=Th(t);yield*e.delete(Rr).where(p(Rr.oauthKey,r))})),scan:(t)=>pj.unwrap(Ah(Je.gen(function*(){let r=Th(t),n=JZ(r),o=yield*ci.now,i=yield*e.select().from(Rr).where(_(tc(Rr.oauthKey,r),ms(Rr.oauthKey,n),Rt(Se(Rr.keyExpiry),Xt(Rr.keyExpiry,o))));return pj.fromIterable(i.map((s)=>[zZ(s.oauthKey),s.keyValue]))})))}}));import{Effect as vw,Layer as tee}from"effect";var vC=tee.effect(WI,vw.gen(function*(){let e=yield*pe;return{getCalendarData:(t)=>vw.gen(function*(){if(t.length===0)return new Map;let[r,n,o,i,s]=yield*vw.all([e.select({id:V.id,timezone:V.timezone}).from(V).where(Fe(V.id,t)),e.select({orgUnitId:en.orgUnitId,dayOfWeek:en.dayOfWeek,timeRanges:en.timeRanges}).from(en).where(Fe(en.orgUnitId,t)),e.select({orgUnitId:Vi.orgUnitId,exceptionDate:f`(${Vi.exceptionDate} - 2440587.5) * 86400000`.as("exception_date_ms"),exceptionSlots:Vi.exceptionSlots,exceptionNote:Vi.exceptionNote}).from(Vi).where(Fe(Vi.orgUnitId,t)),e.select({orgUnitId:Or.orgUnitId,holidayTitle:Or.holidayTitle,holidayRule:Or.holidayRule,holidayDate:f`CASE WHEN ${Or.holidayDate} IS NOT NULL THEN (${Or.holidayDate} - 2440587.5) * 86400000 ELSE NULL END`.as("holiday_date_ms")}).from(Or).where(Fe(Or.orgUnitId,t)),e.select({orgUnitId:Do.orgUnitId,periodKind:Do.periodKind,periodTitle:Do.periodTitle,periodStart:f`(${Do.periodStart} - 2440587.5) * 86400000`.as("period_start_ms"),periodEnd:f`(${Do.periodEnd} - 2440587.5) * 86400000`.as("period_end_ms"),periodActive:Do.periodActive,periodSchedule:Do.periodSchedule}).from(Do).where(Fe(Do.orgUnitId,t))],{concurrency:"unbounded"}),a=new Map;for(let l of r)a.set(l.id,l.timezone);let c=new Map;for(let l of t)c.set(l,{orgUnitId:l,timezone:a.get(l)??"UTC",weeklySchedule:[],dateExceptions:[],holidays:[],periods:[]});for(let l of n){let d=c.get(l.orgUnitId);if(d){let u={orgUnitId:l.orgUnitId,dayOfWeek:l.dayOfWeek,timeRanges:l.timeRanges};d.weeklySchedule.push(u)}}for(let l of o){let d=c.get(l.orgUnitId);if(d){let u={orgUnitId:l.orgUnitId,exceptionDate:l.exceptionDate,exceptionSlots:l.exceptionSlots};if(l.exceptionNote!==null)u.exceptionNote=l.exceptionNote;d.dateExceptions.push(u)}}for(let l of i){let d=c.get(l.orgUnitId);if(d){let u={orgUnitId:l.orgUnitId,holidayTitle:l.holidayTitle,holidayRule:l.holidayRule};if(l.holidayDate!==null)u.holidayDate=l.holidayDate;d.holidays.push(u)}}for(let l of s){let d=c.get(l.orgUnitId);if(d){let u={orgUnitId:l.orgUnitId,periodKind:l.periodKind,periodTitle:l.periodTitle,periodStart:l.periodStart,periodEnd:l.periodEnd,periodActive:l.periodActive};if(l.periodSchedule!==null)u.periodSchedule=l.periodSchedule;d.periods.push(u)}}return c}),getRootOrgUnit:()=>vw.gen(function*(){return(yield*e.select({id:V.id}).from(V).where(Se(V.parentOrgUnitId)).limit(1))[0]?.id??null})}}));import{Effect as xC,Layer as ree}from"effect";var nee=ree.effect(VI,xC.gen(function*(){let e=yield*pe;return{isJobCompleted:(t,r)=>xC.gen(function*(){return(yield*e.select({id:No.id}).from(No).where(_(p(No.queue,t),p(No.jobId,r),p(No._deleted,!1))).limit(1)).length>0}),markJobCompleted:(t,r)=>e.insert(No).values({queue:t,jobId:r}),clearJobCompleted:(t,r)=>xC.gen(function*(){let n=yield*he(),o=yield*st();yield*e.update(No).set({_deleted:!0,updatedAt:n,updatedBy:o.by}).where(_(p(No.queue,t),p(No.jobId,r),p(No._deleted,!1)))})}}));import{Effect as vj,Layer as oee}from"effect";var wC=oee.effect(JI,vj.gen(function*(){let e=yield*pe;return{getExecutionTimestamps:(t,r)=>vj.gen(function*(){if(t.length===0)return[];let n=e.$with("ranked_executions").as(e.select({processId:M.processId,orgUnitId:z.orgUnitId,createdAt:f`(${W.createdAt} - 2440587.5) * 86400000`.as("created_at_ms"),finishedAt:f`(${W.finishedAt} - 2440587.5) * 86400000`.as("finished_at_ms"),rowNum:f`ROW_NUMBER() OVER (PARTITION BY ${M.processId} ORDER BY ${W.finishedAt} DESC)`.as("row_num")}).from(W).innerJoin(M,p(W.processStateId,M.id)).innerJoin(z,p(M.processId,z.id)).where(_(Nt(W.finishedAt),p(W._deleted,!1),p(M._deleted,!1),p(z._deleted,!1),Fe(M.processId,t))));return(yield*e.with(n).select({processId:n.processId,orgUnitId:n.orgUnitId,createdAt:n.createdAt,finishedAt:n.finishedAt}).from(n).where(dn(n.rowNum,r))).map((i)=>({processId:i.processId,orgUnitId:i.orgUnitId,createdAt:i.createdAt,finishedAt:i.finishedAt}))})}}));import{Effect as Ph,Layer as iee}from"effect";var bC=iee.effect(zI,Ph.gen(function*(){let e=yield*pe,t=fs(V,"role_org_unit"),r=fs(N,"completing_role"),n=fs(O,"assigned_provider_user"),o=(S)=>Ph.gen(function*(){if(S.length===0)return[];return(yield*e.select({executionId:C.processExecutionId,updatedBy:C.updatedBy,todoId:C.id,stepId:U.id,stepName:U.name,stepPath:U.path,completed:C._deleted,failureReason:C.failureReason,correctionRequiredAt:f`CASE WHEN ${C.correctionRequiredAt} IS NULL THEN NULL ELSE (${C.correctionRequiredAt} - 2440587.5) * 86400000 END`.as("correction_required_at_millis"),correctionFailureReason:C.correctionFailureReason,completedByUserId:C.completedByUserId,providerUserId:O.id,providerUserFirstName:O.firstName,providerUserLastName:O.lastName,providerUserEmail:O.email,providerUserPicture:O.picture,providerUserOrgUnit:V.name,assignedProviderUserEmail:n.email,externalParticipantId:Nn.id,externalParticipantEmail:Nn.email,roleId:N.id,roleName:N.name,roleOrgUnitPath:t.path,completingRoleId:r.id,completingRoleName:r.name,completingRolePath:r.path,itemData:C.itemData,createdAt:f`(${C.createdAt} - 2440587.5) * 86400000`.as("created_at_millis"),updatedAt:f`(${C.updatedAt} - 2440587.5) * 86400000`.as("updated_at_millis")}).from(C).innerJoin(Q,p(C.flowId,Q.id)).innerJoin(U,p(Q.targetStepId,U.id)).leftJoin(N,p(U.roleId,N.id)).leftJoin(t,p(N.orgUnitId,t.id)).leftJoin(r,p(C.completedByRoleId,r.id)).leftJoin(X,p(C.completedByUserId,X.id)).leftJoin(O,_(p(X.id,O.userId),p(O._deleted,!1))).leftJoin(V,p(O.orgUnitId,V.id)).leftJoin(n,p(C.assignedToProviderUserId,n.id)).leftJoin(Nn,p(C.completedByExternalParticipantId,Nn.id)).where(Fe(C.processExecutionId,S)).orderBy(C.updatedAt)).map((v)=>({executionId:v.executionId,updatedBy:v.updatedBy,todoId:v.todoId,stepId:v.stepId,stepName:v.stepName,stepPath:v.stepPath,completed:v.completed,failureReason:v.failureReason,correctionRequiredAt:v.correctionRequiredAt,correctionFailureReason:v.correctionFailureReason,completedByUserId:v.completedByUserId,providerUserId:v.providerUserId,providerUserFirstName:v.providerUserFirstName,providerUserLastName:v.providerUserLastName,providerUserEmail:v.providerUserEmail,providerUserPicture:v.providerUserPicture,providerUserOrgUnit:v.providerUserOrgUnit,assignedProviderUserEmail:v.assignedProviderUserEmail,externalParticipantId:v.externalParticipantId,externalParticipantEmail:v.externalParticipantEmail,roleId:v.roleId,roleName:v.roleName,roleOrgUnitPath:v.roleOrgUnitPath,completingRoleId:v.completingRoleId,completingRoleName:v.completingRoleName,completingRolePath:v.completingRolePath,itemData:v.itemData,createdAt:v.createdAt,updatedAt:v.updatedAt}))}),i=fs(U,"start_step"),s=fs(N,"start_step_role"),a=fs(V,"start_step_role_org_unit"),c=fs(N,"started_by_role"),l=fs(Nn,"start_external_participant"),d=(S)=>Ph.gen(function*(){let x=e.$with("duration_stats").as(e.select({processId:M.processId,minDurationMs:f`MIN(${W.businessDuration})`.as("min_duration_ms"),maxDurationMs:f`MAX(${W.businessDuration})`.as("max_duration_ms")}).from(W).innerJoin(M,p(W.processStateId,M.id)).where(_(Nt(W.finishedAt),Nt(W.businessDuration),p(W._deleted,!1),p(M._deleted,!1))).groupBy(M.processId)),v=e.with(x).select({id:W.id,processStateId:W.processStateId,withoutWaiting:W.withoutWaiting,processName:z.name,processPath:z.path,finishedAt:f`CASE WHEN ${W.finishedAt} IS NULL THEN NULL ELSE strftime('%Y-%m-%dT%H:%M:%SZ', ${W.finishedAt}) END`.as("finished_at_iso"),abandonedAt:f`CASE WHEN ${W.abandonedAt} IS NULL THEN NULL ELSE strftime('%Y-%m-%dT%H:%M:%SZ', ${W.abandonedAt}) END`.as("abandoned_at_iso"),abandonedReason:W.abandonedReason,startedAt:f`strftime('%Y-%m-%dT%H:%M:%SZ', ${W.createdAt})`.as("started_at_iso"),updatedAt:f`CAST(ROUND((${W.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`.as("updated_at_millis"),deleted:W._deleted,startedAtMs:f`(${W.createdAt} - 2440587.5) * 86400000`.as("started_at_millis"),finishedAtMs:f`CASE WHEN ${W.finishedAt} IS NULL THEN NULL ELSE (${W.finishedAt} - 2440587.5) * 86400000 END`.as("finished_at_millis"),startStepId:i.id,startStepName:i.name,startStepPath:i.path,startStepRoleId:s.id,startStepRoleName:s.name,startStepRoleOrgUnitPath:a.path,startedByRoleId:c.id,startedByRoleName:c.name,startedByRolePath:c.path,startStepEmbedded:i.embedded,startStepExternalParticipantId:l.id,startStepExternalParticipantEmail:l.email,processStateCreatedAt:f`strftime('%Y-%m-%dT%H:%M:%SZ', ${M.createdAt})`.as("process_state_created_at_iso"),startedByEmail:O.email,createdBy:W.createdBy,startedById:O.id,startedByFirstName:O.firstName,startedByLastName:O.lastName,startedByPicture:O.picture,startedByOrgUnit:V.name,processSlaValue:z.slaValue,processSlaUnit:z.slaUnit,processSlaWarning:z.slaWarning,typicalDurationMinMs:x.minDurationMs,typicalDurationMaxMs:x.maxDurationMs,processOrgUnitId:z.orgUnitId}).from(W).innerJoin(M,p(W.processStateId,M.id)).innerJoin(z,p(M.processId,z.id)).innerJoin(i,p(M.startStepId,i.id)).leftJoin(s,p(i.roleId,s.id)).leftJoin(a,p(s.orgUnitId,a.id)).leftJoin(c,p(M.startedByRoleId,c.id)).leftJoin(X,p(M.startedByUserId,X.id)).leftJoin(O,_(p(X.id,O.userId),p(O._deleted,!1))).leftJoin(V,p(O.orgUnitId,V.id)).leftJoin(l,p(M.startedByExternalParticipantId,l.id)).leftJoin(x,p(M.processId,x.processId)).where(S.whereClause),w=S.newestFirst?v.orderBy(Hr(W.createdAt),W.id):v.orderBy(W.updatedAt,W.id),P=S.limit!==void 0?w.limit(S.limit):w;return(yield*S.offset!==void 0?P.offset(S.offset):P).map((b)=>({id:b.id,processStateId:b.processStateId,withoutWaiting:b.withoutWaiting,processName:b.processName,processPath:b.processPath,status:b.abandonedAt!=null?"Abandoned":b.abandonedReason!=null?"Failed":b.finishedAt!=null?"Completed":"Running",startedAt:b.startedAt,finishedAt:b.finishedAt,durationMs:b.finishedAtMs!=null?Math.round(b.finishedAtMs-b.startedAtMs):null,updatedAt:b.updatedAt,deleted:b.deleted,startStepId:b.startStepId,startStepName:b.startStepName,startStepPath:b.startStepPath,startStepRoleId:b.startStepRoleId,startStepRoleName:b.startStepRoleName,startStepRoleOrgUnitPath:b.startStepRoleOrgUnitPath,startedByRoleId:b.startedByRoleId,startedByRoleName:b.startedByRoleName,startedByRolePath:b.startedByRolePath,startStepEmbedded:b.startStepEmbedded,startStepExternalParticipantId:b.startStepExternalParticipantId,startStepExternalParticipantEmail:b.startStepExternalParticipantEmail,processStateCreatedAt:b.processStateCreatedAt,startedByEmail:b.startedByEmail,createdBy:b.createdBy,startedById:b.startedById,startedByFirstName:b.startedByFirstName,startedByLastName:b.startedByLastName,startedByPicture:b.startedByPicture,startedByOrgUnit:b.startedByOrgUnit,processSlaValue:b.processSlaValue,processSlaUnit:b.processSlaUnit,processSlaWarning:b.processSlaWarning,typicalDurationMinMs:b.typicalDurationMinMs,typicalDurationMaxMs:b.typicalDurationMaxMs,processOrgUnitId:b.processOrgUnitId,abandonedReason:b.abandonedReason}))}),u=(S)=>{if(!S)return;let x=f`CAST(ROUND((${W.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`;return Rt(Xt(x,S.updatedAt),_(p(x,S.updatedAt),Xt(W.id,S.id)))},m=(S)=>Ph.gen(function*(){let v=(yield*e.select({state:M.state}).from(W).innerJoin(M,p(W.processStateId,M.id)).where(p(W.id,S)).limit(1))[0];if(!v)return null;return v.state}),h=_(Se(W.finishedAt),Se(W.abandonedAt),Se(W.abandonedReason));return{pullExecution:(S,x,v=!1,w)=>d({whereClause:_(w===void 0?void 0:Rt(u({id:"",updatedAt:w}),h),v&&S?Rt(u(S),h):u(S)),limit:x}),getExecutions:(S)=>S.length===0?Ph.succeed([]):d({whereClause:Fe(W.id,S)}),listExecutions:(S)=>d({whereClause:_(p(W._deleted,!1),S.processPath!=null?p(z.path,S.processPath):void 0),limit:S.limit,offset:S.offset,newestFirst:!0}),getTodosForExecutions:o,getProcessStateByExecutionId:m}}));import{Effect as xj,Layer as see}from"effect";var EC=see.effect(YI,xj.gen(function*(){let e=yield*pe;return{upsertByEmail:(t)=>xj.gen(function*(){let r=sj(t);if(r===null)return yield*new GI({email:t,message:"External participant email must be a valid email address"});let n=yield*he(),o=yield*st(),i=yield*e.insert(Nn).values({email:r,createdAt:n,updatedAt:n,createdBy:o.by,updatedBy:o.by}).onConflictDoUpdate({target:Nn.email,targetWhere:f`_deleted = 0`,set:{updatedAt:n,updatedBy:o.by}}).returning({id:Nn.id});return(yield*zt(i)).id})}}));import{Effect as Yc,Layer as aee}from"effect";var cee=aee.effect(XI,Yc.gen(function*(){let e=yield*pe;return{createFile:(t,r,n)=>Yc.gen(function*(){let o=yield*he(),i=yield*e.insert(Dr).values({documentStoreId:t,mediaKind:r??null,uploadPending:!0,createdBy:n,createdAt:o,updatedAt:o}).returning({id:Dr.id});return(yield*zt(i)).id}),getFileWithStore:(t)=>Yc.gen(function*(){let n=(yield*e.select({id:Dr.id,documentStoreId:Dr.documentStoreId,fileSize:Dr.fileSize,uploadPending:Dr.uploadPending,storeName:wt.name,acceptedTypes:wt.acceptedTypes,sizeLimit:wt.sizeLimit}).from(Dr).innerJoin(wt,p(Dr.documentStoreId,wt.id)).where(p(Dr.id,t)).limit(1))[0];if(!n)return null;return{...n,acceptedTypes:n.acceptedTypes??null}}),markFileUploaded:(t,r,n)=>Yc.gen(function*(){let i={uploadPending:!1,updatedAt:yield*he()};if(r!==void 0)i.fileSize=r;if(n!==void 0)i.mediaKind=n;yield*e.update(Dr).set(i).where(p(Dr.id,t))}),getDocumentStoreByPath:(t)=>Yc.gen(function*(){return(yield*e.select({id:wt.id,name:wt.name}).from(wt).where(p(wt.path,t)).limit(1))[0]??null}),isStepLinkedToDocumentStore:(t,r)=>Yc.gen(function*(){return((yield*e.select({count:f`count(*)`}).from(Wr).innerJoin(U,p(Wr.stepId,U.id)).innerJoin(wt,p(Wr.documentStoreId,wt.id)).where(_(p(U.path,t),p(wt.path,r),p(Wr._deleted,!1))).limit(1))[0]?.count??0)>0}),getFileOwnerInfo:(t)=>Yc.gen(function*(){let n=(yield*e.select({createdBy:Dr.createdBy,orgUnitPath:V.path,documentStorePath:wt.path}).from(Dr).innerJoin(wt,p(Dr.documentStoreId,wt.id)).innerJoin(V,p(wt.orgUnitId,V.id)).where(p(Dr.id,t)).limit(1))[0];if(!n?.createdBy)return null;return{createdBy:n.createdBy,orgUnitPath:n.orgUnitPath,documentStorePath:n.documentStorePath}}),deleteFile:(t)=>Yc.gen(function*(){return(yield*e.delete(Dr).where(p(Dr.id,t)).returning({id:Dr.id})).length>0})}}));import{Effect as Yt,Layer as lee}from"effect";var dee=lee.effect(eC,Yt.gen(function*(){let e=yield*pe,t=Hn(U,"source_step"),r=Hn(U,"target_step");return{queryFlowById:(n)=>Yt.gen(function*(){let i=(yield*e.select({id:Q.id,condition:Q.condition,schedule:Q.schedule,sourceStepPath:t.path,targetStepId:r.id,targetStepPath:r.path,fallbackBranch:Q.fallbackBranch,isOnError:Q.errorBranch,taggedErrors:Q.errorTags}).from(Q).innerJoin(t,p(Q.sourceStepId,t.id)).innerJoin(r,p(Q.targetStepId,r.id)).where(_(p(Q.id,n),p(Q._deleted,!1))).limit(1))[0];if(!i)return null;return{...i,taggedErrors:wh(i.taggedErrors)}}),getProcessStateByExecutionId:(n)=>Yt.gen(function*(){let o=yield*e.select({processStateId:M.id,withoutWaiting:W.withoutWaiting,createdBy:W.createdBy,state:M.state}).from(W).innerJoin(M,p(W.processStateId,M.id)).where(p(W.id,n)).limit(1);if(!o[0])return null;return{processStateId:o[0].processStateId,withoutWaiting:o[0].withoutWaiting,createdBy:o[0].createdBy,state:o[0].state}}),isProcessExecutionOpen:(n)=>Yt.gen(function*(){return(yield*e.select({id:W.id}).from(W).where(_(p(W.id,n),Se(W.finishedAt),Se(W.abandonedAt))).limit(1)).length>0}),queryTodoNotificationInfo:(n)=>Yt.gen(function*(){if(n.length===0)return[];return yield*e.select({todoId:C.id,processExecutionId:C.processExecutionId,assignedToProviderUserId:C.assignedToProviderUserId,roleId:U.roleId,stepPath:U.path,processName:z.name,stepName:U.name,itemData:C.itemData}).from(C).innerJoin(Q,p(C.flowId,Q.id)).innerJoin(U,p(Q.targetStepId,U.id)).innerJoin(z,p(U.processId,z.id)).where(_(Fe(C.id,n),p(C._deleted,!1),p(Q._deleted,!1),p(U._deleted,!1),p(z._deleted,!1)))}),insertToDo:({processExecutionId:n,flowId:o,assignedToProviderUserId:i,slaTargetAt:s,slaWarningAt:a,itemData:c,barrierScheduledFlowId:l})=>Yt.gen(function*(){let d=yield*he(),u=yield*st(),m=yield*e.insert(C).values({processExecutionId:n,flowId:o,assignedToProviderUserId:i??null,slaTargetAt:s??null,slaWarningAt:a??null,itemData:c??null,barrierScheduledFlowId:l??null,createdAt:d,updatedAt:d,createdBy:u.by,updatedBy:u.by}).returning({id:C.id});return(yield*zt(m)).id}),insertToDos:({processExecutionId:n,flowId:o,items:i,slaTargetAt:s,slaWarningAt:a,barrierScheduledFlowId:c})=>Yt.gen(function*(){let l=yield*he(),d=yield*st();return(yield*e.insert(C).values(i.map((m)=>({processExecutionId:n,flowId:o,slaTargetAt:s??null,slaWarningAt:a??null,itemData:m,barrierScheduledFlowId:c??null,createdAt:l,updatedAt:l,createdBy:d.by,updatedBy:d.by}))).returning({id:C.id})).map((m)=>m.id)}),queryFlowsBySourceStepId:(n)=>Yt.gen(function*(){return(yield*e.select({id:Q.id,condition:Q.condition,schedule:Q.schedule,sourceStepPath:t.path,targetStepId:r.id,targetStepPath:r.path,fallbackBranch:Q.fallbackBranch,isOnError:Q.errorBranch,taggedErrors:Q.errorTags}).from(Q).innerJoin(t,p(Q.sourceStepId,t.id)).innerJoin(r,p(Q.targetStepId,r.id)).where(_(p(Q.sourceStepId,n),p(Q._deleted,!1)))).map((i)=>({...i,taggedErrors:wh(i.taggedErrors)}))}),countActiveTodos:(n)=>Yt.gen(function*(){let o=yield*e.select({count:f`COUNT(*)`.as("count")}).from(C).where(_(p(C.processExecutionId,n),p(C._deleted,!1)));return Number(o[0]?.count??0)}),countPendingFlowJobs:(n,o)=>Yt.gen(function*(){let i=yield*e.select({count:f`COUNT(*)`.as("count")}).from(Ke).where(_(p(Ke.queue,o),p(Ke._deleted,!1),f`(
|
|
437
|
+
(
|
|
438
|
+
json_extract(${Ke.jobPayload}, '$.sourceScheduledFlowId') IS NULL
|
|
439
|
+
AND json_extract(${Ke.jobPayload}, '$.processExecutionId') = ${n}
|
|
440
|
+
)
|
|
441
|
+
OR
|
|
442
|
+
(
|
|
443
|
+
json_extract(${Ke.jobPayload}, '$.sourceScheduledFlowId') IS NOT NULL
|
|
444
|
+
AND json_extract(${Ke.jobPayload}, '$.processExecutionId') = ${n}
|
|
445
|
+
AND EXISTS (
|
|
446
|
+
SELECT 1 FROM ${Me}
|
|
447
|
+
WHERE ${Me.id} = json_extract(${Ke.jobPayload}, '$.payload.scheduledFlowId')
|
|
448
|
+
AND ${Me._deleted} = false
|
|
449
|
+
)
|
|
450
|
+
)
|
|
451
|
+
)`));return Number(i[0]?.count??0)}),insertFlowDispatchJobs:(n)=>Yt.gen(function*(){if(n.length===0)return;let o=yield*he(),i=yield*st();yield*e.insert(Ke).values(n.map(({sourceScheduledFlowId:s,processExecutionId:a,storageQueue:c,...l})=>({queue:c??l.queue,jobPayload:{sourceScheduledFlowId:s,...a===void 0?{}:{processExecutionId:a},...l},createdAt:o,updatedAt:o,createdBy:i.by,updatedBy:i.by})))}),queryFlowDispatchJobs:(n)=>Yt.gen(function*(){return(yield*e.select({id:Ke.id,payload:Ke.jobPayload}).from(Ke).where(_(p(Ke._deleted,!1),f`json_extract(${Ke.jobPayload}, '$.sourceScheduledFlowId') = ${n}`))).map(({id:i,payload:s})=>({id:i,...s})).sort((i,s)=>i.sequence-s.sequence)}),queryFlowDispatchIdsByStorageQueue:(n,o,i)=>Yt.gen(function*(){let s=f`json_extract(${Ke.jobPayload}, '$.sourceScheduledFlowId')`;return(yield*e.select({sourceScheduledFlowId:s}).from(Ke).where(_(p(Ke._deleted,!1),p(Ke.queue,n),Rt(Se(Ke.lockedUntil),dn(Ke.lockedUntil,o)))).groupBy(s).orderBy(f`MIN(${Ke.createdAt})`,s).limit(i)).map((c)=>c.sourceScheduledFlowId)}),claimFlowDispatchJobs:(n,o,i,s)=>Yt.gen(function*(){return(yield*e.update(Ke).set({lockedUntil:i,claimReceipt:s}).where(_(p(Ke._deleted,!1),f`json_extract(${Ke.jobPayload}, '$.sourceScheduledFlowId') = ${n}`,Rt(Se(Ke.lockedUntil),dn(Ke.lockedUntil,o)))).returning({id:Ke.id,payload:Ke.jobPayload})).map(({id:c,payload:l})=>({id:c,...l})).sort((c,l)=>c.sequence-l.sequence)}),releaseFlowDispatchJobs:(n,o)=>e.update(Ke).set({lockedUntil:null,claimReceipt:null}).where(_(p(Ke._deleted,!1),p(Ke.claimReceipt,o),f`json_extract(${Ke.jobPayload}, '$.sourceScheduledFlowId') = ${n}`)),extendFlowDispatchClaim:(n,o,i)=>Yt.gen(function*(){return(yield*e.update(Ke).set({lockedUntil:i}).where(_(p(Ke._deleted,!1),p(Ke.claimReceipt,o),f`json_extract(${Ke.jobPayload}, '$.sourceScheduledFlowId') = ${n}`)).returning({id:Ke.id})).length>0}),deleteFlowDispatchJob:(n,o)=>Yt.gen(function*(){return(yield*e.delete(Ke).where(o===void 0?p(Ke.id,n):_(p(Ke.id,n),p(Ke.claimReceipt,o))).returning({id:Ke.id})).length>0}),setProcessExecutionFinished:(n,o)=>Yt.gen(function*(){let i=yield*he(),s=yield*st();yield*e.update(W).set({finishedAt:i,businessDuration:o,updatedAt:i,updatedBy:s.by}).where(p(W.id,n))}),setProcessExecutionFailed:(n,o)=>Yt.gen(function*(){let i=yield*he(),s=yield*st();yield*e.update(W).set({finishedAt:i,abandonedReason:o,updatedAt:i,updatedBy:s.by}).where(_(p(W.id,n),Se(W.finishedAt),Se(W.abandonedAt)))}),getProcessIdForExecution:(n)=>Yt.gen(function*(){return(yield*e.select({processId:M.processId}).from(W).innerJoin(M,p(W.processStateId,M.id)).where(p(W.id,n)).limit(1))[0]?.processId??null}),getExecutionDetailsForCompletion:(n)=>Yt.gen(function*(){return(yield*e.select({createdAtMs:f`(${W.createdAt} - 2440587.5) * 86400000`.as("created_at_ms"),orgUnitId:z.orgUnitId}).from(W).innerJoin(M,p(W.processStateId,M.id)).innerJoin(z,p(M.processId,z.id)).where(p(W.id,n)).limit(1))[0]??null}),getTargetStepSlaInfo:(n)=>Yt.gen(function*(){return(yield*e.select({slaValue:r.slaValue,slaUnit:r.slaUnit,slaWarning:r.slaWarning,orgUnitId:z.orgUnitId}).from(Q).innerJoin(r,p(Q.targetStepId,r.id)).innerJoin(z,p(r.processId,z.id)).where(_(p(Q.id,n),p(Q._deleted,!1))).limit(1))[0]??null}),targetStepHasRole:(n)=>Yt.gen(function*(){let o=yield*e.select({roleId:r.roleId}).from(Q).innerJoin(r,p(Q.targetStepId,r.id)).where(_(p(Q.id,n),p(Q._deleted,!1))).limit(1);if(!o[0])return null;return o[0].roleId!==null}),targetStepHasForEach:(n)=>Yt.gen(function*(){let o=yield*e.select({hasForEach:r.hasForEach}).from(Q).innerJoin(r,p(Q.targetStepId,r.id)).where(_(p(Q.id,n),p(Q._deleted,!1))).limit(1);if(!o[0])return null;return o[0].hasForEach}),countActiveTodosForStep:(n,o)=>Yt.gen(function*(){let i=yield*e.select({count:f`COUNT(*)`.as("count")}).from(C).innerJoin(Q,p(C.flowId,Q.id)).where(_(p(C.processExecutionId,n),p(Q.targetStepId,o),p(C._deleted,!1)));return Number(i[0]?.count??0)}),getStepRetryLimitByPath:(n)=>Yt.gen(function*(){let o=yield*e.select({retryLimit:U.retryLimit}).from(U).where(_(p(U.path,n),p(U._deleted,!1))).limit(1);if(!o[0])return yield*Yt.logWarning("getStepRetryLimitByPath: step not found",{stepPath:n}),null;return o[0].retryLimit}),queryNotificationRecipientByProviderUserId:(n)=>Yt.gen(function*(){let i=(yield*e.select({providerUserId:O.id,userId:O.userId,email:O.email,name:O.name,firstName:O.firstName,lastName:O.lastName,notificationPreference:Mt.notificationPreference}).from(O).leftJoin(Mt,_(p(Mt.userId,O.userId),p(Mt._deleted,!1))).where(_(p(O.id,n),p(O._deleted,!1))).limit(1))[0];return i?hw(i):null}),queryNotificationRecipientsByRoleId:(n)=>Yt.gen(function*(){return(yield*e.select({providerUserId:O.id,userId:O.userId,email:O.email,name:O.name,firstName:O.firstName,lastName:O.lastName,notificationPreference:Mt.notificationPreference}).from(rt).innerJoin(O,p(rt.providerUserId,O.id)).leftJoin(Mt,_(p(Mt.userId,O.userId),p(Mt._deleted,!1))).where(_(p(rt.roleId,n),p(rt._deleted,!1),p(O._deleted,!1)))).map(hw)}),queryNotificationRecipientsByRolePath:(n)=>Yt.gen(function*(){return(yield*e.select({providerUserId:O.id,userId:O.userId,email:O.email,name:O.name,firstName:O.firstName,lastName:O.lastName,notificationPreference:Mt.notificationPreference}).from(rt).innerJoin(O,p(rt.providerUserId,O.id)).innerJoin(N,p(rt.roleId,N.id)).leftJoin(Mt,_(p(Mt.userId,O.userId),p(Mt._deleted,!1))).where(_(p(N.path,n),p(rt._deleted,!1),p(O._deleted,!1),p(N._deleted,!1)))).map(hw)})}}));import{Layer as Iee}from"effect";import{Effect as xw,Layer as uee}from"effect";var wj=uee.effect(KI,xw.gen(function*(){let e=yield*pe;return{cleanupExecutions:()=>xw.gen(function*(){yield*e.delete(nt);let r=(yield*e.select({id:C.id}).from(C)).length;yield*e.delete(C);let o=(yield*e.select({id:Me.id}).from(Me)).length;yield*e.delete(Me);let s=(yield*e.select({id:Ke.id}).from(Ke)).length;yield*e.delete(Ke),yield*e.delete(No);let c=(yield*e.select({id:W.id}).from(W)).length;yield*e.delete(W);let d=(yield*e.select({id:M.id}).from(M)).length;return yield*e.delete(M),yield*xw.log("Cleanup completed").pipe(xw.annotateLogs({todosDeleted:r,scheduledFlowsDeleted:o,executionsDeleted:c,statesDeleted:d,jobsDeleted:s})),{todosDeleted:r,scheduledFlowsDeleted:o,executionsDeleted:c,statesDeleted:d,jobsDeleted:s}})}}));import{Effect as df,Layer as pee}from"effect";var bj=pee.effect(QI,df.gen(function*(){let e=yield*pe;return{pullDraftProcessExecution:(t,r)=>df.gen(function*(){let n=yield*st();if(!n.id)return[];let o=[p(Fo.isDraft,!0),p(M.startedByUserId,n.id)];if(t){let s=f`CAST(ROUND((${M.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`,a=Rt(Xt(s,t.updatedAt),_(p(s,t.updatedAt),Xt(M.id,t.id)));if(a)o.push(a)}return(yield*e.select({id:M.id,processId:M.processId,startStepId:M.startStepId,startedByUserId:M.startedByUserId,startedByEmail:O.email,name:z.name,startStepPath:U.path,state:M.state,lastSaved:M.updatedAt,updatedAt:f`CAST(ROUND((${M.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`.as("updated_at_millis"),deleted:M._deleted}).from(M).innerJoin(z,p(M.processId,z.id)).innerJoin(U,p(M.startStepId,U.id)).innerJoin(Fo,p(M.id,Fo.id)).leftJoin(O,_(p(M.startedByUserId,O.userId),p(O._deleted,!1))).where(_(...o)).orderBy(M.updatedAt,M.id).limit(r)).map((s)=>({...s,state:s.state}))}),insertProcessState:(t,r,n,o)=>df.gen(function*(){let i=yield*he(),s=yield*st(),c=(yield*e.select({id:U.id}).from(U).where(_(p(U.path,n),p(U.processId,r),p(U._deleted,!1))).limit(1))[0];if(!c)return yield*new bh({path:n,message:`Step not found for path: ${n}`});if((yield*e.insert(M).values({id:t,processId:r,startStepId:c.id,state:o,startedByUserId:s.id,createdAt:i,updatedAt:i,createdBy:s.by,updatedBy:s.by}).onConflictDoNothing({target:M.id}).returning({id:M.id})).length===0)return yield*new Mi({processStateId:t,message:`Draft process execution already exists: ${t}`});return t}),updateProcessState:(t,r,n)=>df.gen(function*(){let o=yield*he(),i=yield*st();if(n.id!==t)return yield*new Mi({processStateId:t,message:"Assumed master state targets a different document"});let s=i.id;if(!s)return yield*new Mi({processStateId:t,message:"Draft process execution requires a persisted user owner"});if(n.deleted)return yield*new Mi({processStateId:t,message:`Cannot update deleted process execution state: ${t}`});let a=f`CAST(ROUND((${M.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`,c=JSON.stringify(n.state),l=f`
|
|
452
|
+
NOT EXISTS (
|
|
453
|
+
SELECT fullkey, atom, type FROM json_tree(${M.state})
|
|
454
|
+
EXCEPT
|
|
455
|
+
SELECT fullkey, atom, type FROM json_tree(${c})
|
|
456
|
+
)
|
|
457
|
+
AND NOT EXISTS (
|
|
458
|
+
SELECT fullkey, atom, type FROM json_tree(${c})
|
|
459
|
+
EXCEPT
|
|
460
|
+
SELECT fullkey, atom, type FROM json_tree(${M.state})
|
|
461
|
+
)
|
|
462
|
+
`;if((yield*e.update(M).set({state:r,updatedAt:o,updatedBy:i.by,_deleted:!1}).where(_(p(M.id,t),p(M.processId,n.processId),l,p(M._deleted,!1),p(a,Math.round(n.updatedAt)),p(M.startedByUserId,s),Fe(M.id,e.select({id:Fo.id}).from(Fo).where(p(Fo.isDraft,!0))))).returning({id:M.id})).length===0)return yield*new Mi({processStateId:t,message:`Cannot update deleted process execution state: ${t}`});return t}),deleteProcessState:(t,r)=>df.gen(function*(){let n=yield*he(),o=yield*st();if(r.id!==t)return yield*new Mi({processStateId:t,message:"Assumed master state targets a different document"});let i=o.id;if(!i)return yield*new Mi({processStateId:t,message:"Draft process execution requires a persisted user owner"});if(r.deleted)return yield*new Mi({processStateId:t,message:`Cannot delete from a deleted assumed master state: ${t}`});let s=f`CAST(ROUND((${M.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`,a=JSON.stringify(r.state),c=f`
|
|
463
|
+
NOT EXISTS (
|
|
464
|
+
SELECT fullkey, atom, type FROM json_tree(${M.state})
|
|
465
|
+
EXCEPT
|
|
466
|
+
SELECT fullkey, atom, type FROM json_tree(${a})
|
|
467
|
+
)
|
|
468
|
+
AND NOT EXISTS (
|
|
469
|
+
SELECT fullkey, atom, type FROM json_tree(${a})
|
|
470
|
+
EXCEPT
|
|
471
|
+
SELECT fullkey, atom, type FROM json_tree(${M.state})
|
|
472
|
+
)
|
|
473
|
+
`;if((yield*e.update(M).set({_deleted:!0,updatedAt:n,updatedBy:o.by}).where(_(p(M.id,t),p(M.processId,r.processId),c,p(M._deleted,!1),p(s,Math.round(r.updatedAt)),p(M.startedByUserId,i),Fe(M.id,e.select({id:Fo.id}).from(Fo).where(p(Fo.isDraft,!0))))).returning({id:M.id})).length===0)return yield*new Mi({processStateId:t,message:`Cannot delete inaccessible, changed, or non-draft process execution state: ${t}`});return t}),getProcessStates:(t)=>df.gen(function*(){let r=yield*st();if(!r.id||t.length===0)return[];return(yield*e.select({id:M.id,processId:M.processId,startStepId:M.startStepId,startedByUserId:M.startedByUserId,startedByEmail:O.email,name:z.name,startStepPath:U.path,state:M.state,lastSaved:M.updatedAt,updatedAt:f`CAST(ROUND((${M.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`.as("updated_at_millis"),deleted:M._deleted}).from(M).innerJoin(z,p(M.processId,z.id)).innerJoin(U,p(M.startStepId,U.id)).innerJoin(Fo,p(M.id,Fo.id)).leftJoin(O,_(p(M.startedByUserId,O.userId),p(O._deleted,!1))).where(_(Fe(M.id,t),p(Fo.isDraft,!0),p(M.startedByUserId,r.id))).orderBy(M.updatedAt,M.id)).map((o)=>({...o,state:o.state}))})}}));import{Effect as ww,Layer as fee}from"effect";var Ej=fee.effect(tC,ww.gen(function*(){let e=yield*pe;return{insertProcessState:(t,r,n,o,i)=>ww.gen(function*(){let s=yield*he(),a=yield*st(),l=(yield*e.select({id:U.id}).from(U).where(_(p(U.path,r),p(U._deleted,!1))).limit(1))[0];if(!l)return yield*new bh({path:r,message:`Step not found for path: ${r}`});let d=yield*e.insert(M).values({processId:t,startStepId:l.id,state:n,startedByUserId:o===void 0?a.id:null,...o!==void 0?{startedByExternalParticipantId:o}:{},...i!==void 0?{startedByRoleId:i}:{},createdAt:s,updatedAt:s,createdBy:a.by,updatedBy:a.by}).returning({id:M.id});return{processStateId:(yield*zt(d)).id,stepId:l.id}}),insertProcessExecution:(t,r,n=!1)=>ww.gen(function*(){let o=yield*he(),i=yield*st(),s=yield*e.insert(W).values({...r!==void 0?{id:r}:{},processStateId:t,withoutWaiting:n,createdAt:o,updatedAt:o,createdBy:i.by,updatedBy:i.by}).returning({id:W.id});return(yield*zt(s)).id}),getProcessExecutionStartInfo:(t)=>ww.gen(function*(){let n=(yield*e.select({executionId:W.id,withoutWaiting:W.withoutWaiting,processId:M.processId,stepId:U.id,startStepPath:U.path,state:M.state}).from(W).innerJoin(M,_(p(W.processStateId,M.id),p(M._deleted,!1))).innerJoin(U,_(p(M.startStepId,U.id),p(U._deleted,!1))).where(_(p(W.id,t),p(W._deleted,!1))).limit(1))[0];if(!n)return null;return{executionId:n.executionId,withoutWaiting:n.withoutWaiting,processId:n.processId,stepId:n.stepId,startStepPath:n.startStepPath,state:n.state}})}}));import{Effect as mee,Layer as yee}from"effect";var TC=yee.effect(rC,mee.gen(function*(){let e=yield*pe;return{queryFlowsBySourceStepId:(t)=>e.select({id:Q.id,sourceStepId:Q.sourceStepId,targetStepId:Q.targetStepId}).from(Q).where(_(p(Q.sourceStepId,t),p(Q._deleted,!1)))}}));import{Effect as Tj,Layer as hee,Option as Rj}from"effect";var RC=hee.effect(nC,Tj.gen(function*(){let e=yield*pe;return{queryOAuthClientByClientId:(t)=>Tj.gen(function*(){let r=yield*e.query.oauthClient.findMany({where:{clientId:t,_deleted:!1}});if(r.length&&r[0]){let n=r[0],o={id:n.id,clientId:n.clientId};return Rj.some(o)}return Rj.none()}),addPermittedClientRole:(t,r)=>e.insert(Xn).values({oauthClientId:t,roleId:r}).onConflictDoUpdate({target:[Xn.oauthClientId,Xn.roleId],targetWhere:f`_deleted = 0`,set:{updatedAt:f`julianday('now')`}}),addPermittedClientEmail:(t,r)=>e.insert(go).values({oauthClientId:t,email:r}).onConflictDoUpdate({target:[go.oauthClientId,go.email],targetWhere:f`_deleted = 0`,set:{updatedAt:f`julianday('now')`}})}}));import{Effect as AC,Layer as gee}from"effect";var See=(e)=>{let t=new Map,r=[];for(let s of e){if(s.parentOrgUnitId===null){r.push(s);continue}let a=t.get(s.parentOrgUnitId);if(a===void 0)t.set(s.parentOrgUnitId,[s]);else a.push(s)}let n=new Map,o=new Set,i=[];for(let s of r)o.add(s.id),i.push({unit:s,depth:1});for(let s=0;s<i.length;s++){let a=i[s];if(a===void 0)break;let{unit:c,depth:l}=a,d=n.get(c.orgUnitLevel);if(d===void 0||l>d)n.set(c.orgUnitLevel,l);for(let u of t.get(c.id)??[]){if(o.has(u.id))continue;o.add(u.id),i.push({unit:u,depth:l+1})}}return Array.from(n.entries()).map(([s,a])=>({level:s,maxDepth:a})).sort((s,a)=>s.maxDepth-a.maxDepth)},Aj=gee.effect(oC,AC.gen(function*(){let e=yield*pe;return{queryRoot:AC.gen(function*(){return(yield*e.select().from(V).where(_(Se(V.parentOrgUnitId),ko(V._deleted))).limit(1))[0]??null}),queryChildren:(t)=>e.select().from(V).where(_(p(V.parentOrgUnitId,t),ko(V._deleted))),queryProcesses:(t)=>e.select().from(z).where(_(p(z.orgUnitId,t),p(z._deleted,!1))),queryRoles:(t)=>e.select().from(N).where(_(p(N.orgUnitId,t),p(N._deleted,!1))),queryOrgLevels:AC.gen(function*(){let t=yield*e.select({id:V.id,parentOrgUnitId:V.parentOrgUnitId,orgUnitLevel:V.orgUnitLevel}).from(V).where(ko(V._deleted));return See(t)})}}));import{Effect as uf,Layer as Pj}from"effect";var Ij=Pj.effect(iC,uf.gen(function*(){let e=yield*pe;return{queryAllProcesses:uf.gen(function*(){return yield*e.query.process.findMany({columns:{id:!0,name:!0,path:!0,purpose:!0,orgUnitId:!0},where:{_deleted:!1},with:{orgUnit:{columns:{id:!0,name:!0,orgUnitLevel:!0}}}}).pipe(Na)}),listProcesses:(t)=>uf.gen(function*(){let r=[p(z._deleted,!1)];if(t.processPath!=null)r.push(p(z.path,t.processPath));return(yield*e.select({id:z.id,path:z.path,name:z.name,category:V.name,purpose:z.purpose,startStepPath:U.path,activeInstances:cc.activeProcesses}).from(z).innerJoin(V,p(z.orgUnitId,V.id)).innerJoin(ac,p(z.id,ac.id)).innerJoin(U,p(ac.startStep,U.id)).leftJoin(cc,p(z.id,cc.id)).where(_(...r)).orderBy(z.path,z.id).limit(t.limit).offset(t.offset)).map((o)=>({...o,activeInstances:o.activeInstances??0}))}).pipe(Na)}})),Cj=Pj.effect(sC,uf.gen(function*(){let e=yield*pe,t=(n,o)=>uf.gen(function*(){let i=e.$with("duration_stats").as(e.select({processId:M.processId,minDurationMs:f`MIN((${W.finishedAt} - ${W.createdAt}) * 86400000)`.as("min_duration_ms"),maxDurationMs:f`MAX((${W.finishedAt} - ${W.createdAt}) * 86400000)`.as("max_duration_ms")}).from(W).innerJoin(M,p(W.processStateId,M.id)).where(_(Nt(W.finishedAt),p(W._deleted,!1),p(M._deleted,!1))).groupBy(M.processId)),s=e.with(i).select({id:z.id,name:z.name,path:z.path,purpose:z.purpose,updatedAt:f`CAST(ROUND((${z.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`.as("updated_at_millis"),deleted:z._deleted,orgUnitId:V.id,orgUnitName:V.name,orgUnitLevel:V.orgUnitLevel,startStepPath:U.path,formFieldCount:U.formFields,activeInstances:cc.activeProcesses,minDurationMs:i.minDurationMs,maxDurationMs:i.maxDurationMs}).from(z).innerJoin(V,p(z.orgUnitId,V.id)).innerJoin(ac,p(z.id,ac.id)).innerJoin(U,p(ac.startStep,U.id)).leftJoin(cc,p(z.id,cc.id)).leftJoin(i,p(z.id,i.processId)).where(n).orderBy(z.updatedAt,z.id);return(yield*o!==void 0?s.limit(o):s).map((l)=>({id:l.id,name:l.name,path:l.path,purpose:l.purpose,updatedAt:l.updatedAt,deleted:l.deleted,orgUnit:{id:l.orgUnitId,name:l.orgUnitName,orgUnitLevel:l.orgUnitLevel},startStepPath:l.startStepPath,formFieldCount:l.formFieldCount??0,activeInstances:l.activeInstances??0,minDurationMs:l.minDurationMs,maxDurationMs:l.maxDurationMs}))}),r=(n)=>{if(!n)return;let o=f`CAST(ROUND((${z.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`;return Rt(Xt(o,n.updatedAt),_(p(o,n.updatedAt),Xt(z.id,n.id)))};return{pullProcess:(n,o)=>t(r(n),o),getProcesses:(n)=>n.length===0?uf.succeed([]):t(Fe(z.id,n))}}));import{DateTime as Ew,Effect as lo,Layer as vee,Option as Hs}from"effect";var bw=(e)=>({id:e.id,userId:e.user.id,email:e.email,name:e.name,firstName:e.firstName,lastName:e.lastName,picture:e.picture,locale:e.locale,provider:e.user.provider,sub:e.user.sub,orgUnitId:e.orgUnitId,orgUnitPath:e.orgUnit.path,createdAt:Ew.toDateUtc(e.createdAt),updatedAt:Ew.toDateUtc(e.updatedAt),createdBy:e.createdBy,updatedBy:e.updatedBy}),_j=(e)=>e.replace(/[\\%_]/g,"\\$&"),kj=vee.effect(aC,lo.gen(function*(){let e=yield*pe;return{queryProviderUserByUserId:(t)=>lo.gen(function*(){let r=yield*e.query.providerUser.findMany({with:{user:!0,orgUnit:!0},where:{userId:t}});if(r.length&&r[0])return Hs.some(bw(r[0]));else return Hs.none()}),queryProviderUserByProviderUserId:(t)=>lo.gen(function*(){let r=yield*e.query.providerUser.findMany({with:{user:!0,orgUnit:!0},where:{id:t}});if(r.length&&r[0])return Hs.some(bw(r[0]));else return Hs.none()}),queryProviderUserByEmail:(t)=>lo.gen(function*(){let r=t.trim().toLowerCase(),o=(yield*e.select({providerUser:O,user:X,orgUnit:V}).from(O).innerJoin(X,p(O.userId,X.id)).innerJoin(V,p(O.orgUnitId,V.id)).where(_(f`lower(${O.email}) = ${r}`,p(O._deleted,!1),p(X._deleted,!1),p(V._deleted,!1))).limit(1))[0];if(!o)return Hs.none();return Hs.some(bw({...o.providerUser,user:o.user,orgUnit:o.orgUnit}))}),queryProviderUsers:(t,r)=>lo.gen(function*(){let n=t.trim();if(r.limit<=0)return[];return(yield*e.query.providerUser.findMany({with:{user:!0,orgUnit:!0},where:n.length===0?{_deleted:!1}:{_deleted:!1,OR:[{RAW:(i)=>f`${i.name} like ${`%${_j(n)}%`} escape ${"\\"}`},{RAW:(i)=>f`${i.email} like ${`%${_j(n)}%`} escape ${"\\"}`}]},orderBy:{name:"asc",email:"asc"},limit:r.limit,offset:r.offset})).map(bw)}),queryAllRoles:()=>lo.gen(function*(){return(yield*e.query.role.findMany({where:{_deleted:!1}})).map((r)=>({id:r.id,name:r.name,path:r.path}))}),queryProviderUserRoleIds:(t)=>lo.gen(function*(){return(yield*e.query.providerUserRole.findMany({where:{providerUserId:t,_deleted:!1}})).map((n)=>n.roleId)}),queryProviderUserRolePaths:(t)=>lo.gen(function*(){return(yield*e.query.providerUserRole.findMany({with:{role:!0},where:{providerUserId:t,_deleted:!1}})).map((n)=>n.role.path)}),queryProviderUserRolePathsByProviderUserIds:(t)=>lo.gen(function*(){if(t.length===0)return new Map;let r=yield*e.query.providerUserRole.findMany({with:{role:!0},where:{RAW:(o)=>_(Fe(o.providerUserId,[...t]),p(o._deleted,!1))??f`false`}}),n=new Map;for(let o of r){let i=n.get(o.providerUserId)??[];i.push(o.role.path),n.set(o.providerUserId,i)}return n}),replacePermittedRoles:(t,r)=>lo.gen(function*(){if(yield*e.delete(Dn).where(p(Dn.providerUserId,t)),r.length>0)yield*e.insert(Dn).values(r.map((n)=>({providerUserId:t,roleId:n})))}),queryRoleByPath:(t)=>lo.gen(function*(){let r=yield*e.query.role.findMany({where:{path:t,_deleted:!1}});if(r.length&&r[0]){let n=r[0];return Hs.some({id:n.id,name:n.name,path:n.path})}return Hs.none()}),addPermittedRole:(t,r)=>e.insert(Dn).values({providerUserId:t,roleId:r}).onConflictDoUpdate({target:[Dn.providerUserId,Dn.roleId],targetWhere:f`_deleted = 0`,set:{updatedAt:f`julianday('now')`}}),findInvitationRoleIds:(t)=>lo.gen(function*(){let r=t.toLowerCase();return(yield*e.select({roleId:Oe.roleId}).from(k).innerJoin(Oe,p(Oe.invitationId,k.id)).innerJoin(N,p(N.id,Oe.roleId)).where(_(p(k.invitationPendingEmail,r),p(k.invitationStatus,"pending"),p(k._deleted,!1),p(Oe._deleted,!1),p(N._deleted,!1)))).map((o)=>o.roleId)}),findRootOrgUnit:()=>lo.gen(function*(){let r=(yield*e.select({id:V.id,path:V.path}).from(V).where(_(Se(V.parentOrgUnitId),p(V._deleted,!1))).limit(1))[0];return r?Hs.some({id:r.id,path:r.path}):Hs.none()}),createProviderUserFromInvitation:(t)=>lo.gen(function*(){let r=yield*Ew.now,n=t.email.toLowerCase(),o=yield*e.insert(X).values({provider:"m2m",sub:`m2m:${n}`,lastLoggedIn:r}).returning(),i=yield*zt(o),s=yield*e.insert(O).values({userId:i.id,email:n,name:n.split("@")[0]??n,firstName:"",lastName:"",picture:"",locale:"",orgUnitId:t.orgUnitId}).returning(),a=yield*zt(s);return{userId:i.id,providerUserId:a.id}}),acceptPendingInvitationForProviderUser:(t)=>lo.gen(function*(){let r=yield*Ew.now,n=t.email.toLowerCase();return(yield*e.update(k).set({invitationStatus:"accepted",invitationPendingEmail:null,invitationAcceptedAt:r,invitationAcceptedByProvider:t.provider,invitationAcceptedBySubject:t.subject,acceptedByProviderUserId:t.providerUserId,registrationTokenHash:null,registrationEncryptionVersion:null,registrationEncryptionNonce:null,registrationAuthenticationTag:null,registrationEncryptedToken:null,registrationLinkExpiresAt:null,registrationLinkGeneration:f`coalesce(${k.registrationLinkGeneration}, 0) + 1`,updatedAt:r,updatedBy:"SYSTEM"}).where(_(p(k.invitationPendingEmail,n),p(k.invitationStatus,"pending"),p(k._deleted,!1))).returning({id:k.id})).length>0}),assignProviderUserRoles:(t,r)=>lo.gen(function*(){if(r.length===0)return;yield*e.insert(rt).values(r.map((n)=>({providerUserId:t,roleId:n})))})}}));import{Effect as Oj,Layer as xee}from"effect";var PC=xee.effect(lC,Oj.gen(function*(){let e=yield*pe;return{queryWorkflowByProcessPath:(t)=>Oj.gen(function*(){let n=(yield*e.select({id:z.id,name:z.name,path:z.path,purpose:z.purpose}).from(z).where(_(p(z.path,t),p(z._deleted,!1))).limit(1))[0];if(!n)return yield*new cC({path:t,message:`Process not found: ${t}`});let o=yield*e.select({id:U.id,name:U.name,path:U.path,purpose:U.purpose,processId:U.processId,roleId:U.roleId,roleName:N.name,rolePath:N.path,phaseId:Xr.id,phaseName:Xr.name,phasePath:Xr.path,phaseOrder:Xr.phaseOrder,isStartStep:bi.canStartProcess,isEmbedded:U.embedded}).from(U).leftJoin(N,p(U.roleId,N.id)).leftJoin(Xr,p(U.phaseId,Xr.id)).innerJoin(bi,p(U.id,bi.id)).where(_(p(U.processId,n.id),p(U._deleted,!1),Rt(Se(U.roleId),p(N._deleted,!1)))),i=o.map((l)=>l.id),s=i.length>0?yield*e.select({id:Q.id,sourceStepId:Q.sourceStepId,targetStepId:Q.targetStepId,condition:Q.condition,fallbackBranch:Q.fallbackBranch,errorBranch:Q.errorBranch,errorTags:Q.errorTags,schedule:Q.schedule}).from(Q).where(_(p(Q._deleted,!1),Rt(Fe(Q.sourceStepId,i),Fe(Q.targetStepId,i)))):[],a=yield*e.select({roleId:mr.roleId,roleName:N.name,rolePath:N.path,responsibility:mr.responsibility,order:mr.responsibilityOrder}).from(mr).innerJoin(N,p(mr.roleId,N.id)).where(_(p(mr.processId,n.id),p(mr._deleted,!1),p(N._deleted,!1)));return{processId:n.id,processName:n.name,processPath:n.path,processPurpose:n.purpose,steps:o.map((l)=>({id:l.id,name:l.name,path:l.path,purpose:l.purpose,processId:l.processId,roleId:l.roleId,roleName:l.roleName,rolePath:l.rolePath,phaseId:l.phaseId,phaseName:l.phaseName,phasePath:l.phasePath,phaseOrder:l.phaseOrder,isStartStep:l.isStartStep,isEmbedded:l.isEmbedded})),flows:s.map((l)=>({id:l.id,sourceStepId:l.sourceStepId,targetStepId:l.targetStepId,condition:l.condition,isElse:l.fallbackBranch,isOnError:l.errorBranch,taggedErrors:wh(l.errorTags),schedule:l.schedule})),responsibilities:a.map((l)=>({roleId:l.roleId,roleName:l.roleName,rolePath:l.rolePath,responsibility:l.responsibility,order:l.order}))}})}}));import{DateTime as _r,Effect as Bt,Layer as wee}from"effect";var bee=(e)=>{let t=String(e);return t.includes("pf_provider_user_role_provideruserroleidx_idx")||t.includes("UNIQUE constraint failed: pf_provider_user_role.provider_user_id, pf_provider_user_role.role_id")},IC=wee.effect(xh,Bt.gen(function*(){let e=yield*pe,t=(l)=>Bt.gen(function*(){return yield*e.select({id:N.id,name:N.name,path:N.path}).from(Oe).innerJoin(N,p(N.id,Oe.roleId)).where(_(p(Oe.invitationId,l),p(Oe._deleted,!1),p(N._deleted,!1))).orderBy(N.path)}),r=(l)=>{if(l===ar.Accepted)return ar.Accepted;if(l===ar.LegacyClosed)return ar.LegacyClosed;return ar.Pending},n=(l)=>{if(l===Gc.Model)return Gc.Model;if(l===Gc.Dashboard)return Gc.Dashboard;if(l===Gc.Process)return Gc.Process;return Gc.Legacy},o=(l)=>l?_r.toDateUtc(l):null,i=(l)=>{if(l.lifecycleStatus!==ar.Pending)return kd.NotGenerated;if(l.tokenHash){if(l.expiresAt&&_r.toEpochMillis(l.expiresAt)<=_r.toEpochMillis(l.now))return kd.Expired;return kd.Active}if(l.revokedAt)return kd.Revoked;return kd.NotGenerated},s={registrationTokenHash:null,registrationEncryptionVersion:null,registrationEncryptionNonce:null,registrationAuthenticationTag:null,registrationEncryptedToken:null,registrationLinkExpiresAt:null,registrationLinkGeneration:f`coalesce(${k.registrationLinkGeneration}, 0) + 1`},a=(l,d)=>Bt.gen(function*(){let u=yield*t(l.id),m=r(l.invitationStatus);return{id:l.id,email:l.email,status:m,source:n(l.invitationSource),roles:u,acceptedAt:o(l.invitationAcceptedAt),acceptedByProvider:l.invitationAcceptedByProvider,acceptedBySubject:l.invitationAcceptedBySubject,acceptedByProviderUserId:l.acceptedByProviderUserId,legacyClosedAt:o(l.invitationLegacyClosedAt),legacyClosureReason:l.invitationLegacyClosureReason,registrationLinkStatus:i({lifecycleStatus:m,tokenHash:l.registrationTokenHash,expiresAt:l.registrationLinkExpiresAt,revokedAt:l.registrationLinkRevokedAt,now:d}),registrationLinkExpiresAt:o(l.registrationLinkExpiresAt),registrationLinkGeneratedAt:o(l.registrationLinkGeneratedAt),registrationLinkGeneratedBy:l.registrationLinkGeneratedBy,registrationLinkRevealedAt:o(l.registrationLinkRevealedAt),registrationLinkRevealedBy:l.registrationLinkRevealedBy,registrationLinkRevokedAt:o(l.registrationLinkRevokedAt),registrationLinkRevokedBy:l.registrationLinkRevokedBy,registrationLinkGeneration:l.registrationLinkGeneration??0}}),c={id:k.id,email:k.email,invitationStatus:k.invitationStatus,invitationSource:k.invitationSource,invitationAcceptedAt:k.invitationAcceptedAt,invitationAcceptedByProvider:k.invitationAcceptedByProvider,invitationAcceptedBySubject:k.invitationAcceptedBySubject,acceptedByProviderUserId:k.acceptedByProviderUserId,invitationLegacyClosedAt:k.invitationLegacyClosedAt,invitationLegacyClosureReason:k.invitationLegacyClosureReason,registrationTokenHash:k.registrationTokenHash,registrationLinkExpiresAt:k.registrationLinkExpiresAt,registrationLinkGeneratedAt:k.registrationLinkGeneratedAt,registrationLinkGeneratedBy:k.registrationLinkGeneratedBy,registrationLinkRevealedAt:k.registrationLinkRevealedAt,registrationLinkRevealedBy:k.registrationLinkRevealedBy,registrationLinkRevokedAt:k.registrationLinkRevokedAt,registrationLinkRevokedBy:k.registrationLinkRevokedBy,registrationLinkGeneration:k.registrationLinkGeneration};return{queryAllUsers:(l,d)=>Bt.gen(function*(){let u=(l-1)*d,h=(yield*e.select({count:f`count(*)`}).from(X).where(p(X._deleted,!1)))[0]?.count??0;return{items:(yield*e.select({id:X.id,provider:X.provider,sub:X.sub,lastLoggedIn:X.lastLoggedIn,providerUserId:O.id,providerUserName:O.name,providerUserEmail:O.email}).from(X).leftJoin(O,_(p(O.userId,X.id),p(O._deleted,!1))).where(p(X._deleted,!1)).orderBy(Hr(X.lastLoggedIn),X.id).limit(d).offset(u)).map((v)=>({id:v.id,provider:v.provider,sub:v.sub,lastLoggedIn:_r.toDateUtc(v.lastLoggedIn),isProviderUser:v.providerUserId!==null,providerUserName:v.providerUserName,providerUserEmail:v.providerUserEmail})),totalCount:h}}),queryAllOAuthProviders:(l,d)=>Bt.gen(function*(){let u=(l-1)*d,h=(yield*e.select({count:f`count(*)`}).from(mt).where(p(mt._deleted,!1)))[0]?.count??0;return{items:(yield*e.select({id:mt.id,providerName:mt.providerName}).from(mt).where(p(mt._deleted,!1)).orderBy(mt.providerName).limit(d).offset(u)).map((v)=>({id:v.id,providerName:v.providerName})),totalCount:h}}),queryAllInvitations:(l,d,u=ar.Pending)=>Bt.gen(function*(){let m=(l-1)*d,h=_(p(k._deleted,!1),p(k.invitationStatus,u)),x=(yield*e.select({count:f`count(*)`}).from(k).where(h))[0]?.count??0,v=yield*e.select(c).from(k).where(h).orderBy(k.email).limit(d).offset(m),w=yield*_r.now,P=[];for(let F of v)P.push(yield*a(F,w));return{items:P,totalCount:x}}),queryInvitationDetail:(l)=>Bt.gen(function*(){let u=(yield*e.select(c).from(k).where(_(p(k.id,l),p(k._deleted,!1))).limit(1))[0];if(!u)return null;return yield*a(u,yield*_r.now)}),queryPendingInvitationByEmail:(l)=>Bt.gen(function*(){let u=(yield*e.select(c).from(k).where(_(p(k.invitationPendingEmail,l),p(k.invitationStatus,ar.Pending),p(k._deleted,!1))).limit(1))[0];if(!u)return null;return yield*a(u,yield*_r.now)}),queryInvitationByNormalizedEmail:(l)=>Bt.gen(function*(){let u=(yield*e.select(c).from(k).where(_(p(k.invitationPendingEmail,l),p(k.invitationStatus,ar.Pending),p(k._deleted,!1))).limit(1))[0];if(u)return yield*a(u,yield*_r.now);let h=(yield*e.select(c).from(k).where(_(p(k.email,l),p(k._deleted,!1))).orderBy(Hr(k.createdAt)).limit(1))[0];if(!h)return null;return yield*a(h,yield*_r.now)}),queryUserDetail:(l)=>Bt.gen(function*(){let u=(yield*e.select({id:X.id,provider:X.provider,sub:X.sub,lastLoggedIn:X.lastLoggedIn,providerUserId:O.id,providerUserEmail:O.email,providerUserName:O.name,providerUserFirstName:O.firstName,providerUserLastName:O.lastName,notificationPreference:Mt.notificationPreference}).from(X).leftJoin(O,_(p(O.userId,X.id),p(O._deleted,!1))).leftJoin(Mt,_(p(Mt.userId,X.id),p(Mt._deleted,!1))).where(_(p(X.id,l),p(X._deleted,!1))).limit(1))[0];if(!u)return null;let m=[];if(u.providerUserId)m=(yield*e.select({roleId:N.id}).from(rt).innerJoin(N,_(p(rt.roleId,N.id),p(N._deleted,!1))).where(_(p(rt.providerUserId,u.providerUserId),p(rt._deleted,!1)))).map((x)=>x.roleId);let h=u.notificationPreference?_d(u.notificationPreference):vh;return{id:u.id,provider:u.provider,sub:u.sub,lastLoggedIn:_r.toDateUtc(u.lastLoggedIn),providerUser:u.providerUserId?{id:u.providerUserId,email:u.providerUserEmail??"",name:u.providerUserName??"",firstName:u.providerUserFirstName??"",lastName:u.providerUserLastName??"",roleIds:m,notificationPreferences:h}:null}}),queryProviderUserDetail:(l)=>Bt.gen(function*(){let u=(yield*e.select({id:O.id,email:O.email,name:O.name,firstName:O.firstName,lastName:O.lastName,notificationPreference:Mt.notificationPreference}).from(O).leftJoin(Mt,_(p(Mt.userId,O.userId),p(Mt._deleted,!1))).where(_(p(O.id,l),p(O._deleted,!1))).limit(1))[0];if(!u)return null;let m=yield*e.select({roleId:N.id}).from(rt).innerJoin(N,_(p(rt.roleId,N.id),p(N._deleted,!1))).where(_(p(rt.providerUserId,l),p(rt._deleted,!1))),h=u.notificationPreference?_d(u.notificationPreference):vh;return{id:u.id,email:u.email??"",name:u.name??"",firstName:u.firstName??"",lastName:u.lastName??"",roleIds:m.map((S)=>S.roleId),notificationPreferences:h}}),queryAllRoles:()=>Bt.gen(function*(){return yield*e.select({id:N.id,name:N.name,path:N.path}).from(N).where(p(N._deleted,!1)).orderBy(N.path)}),queryRolesByIds:(l)=>Bt.gen(function*(){if(l.length===0)return[];return yield*e.select({id:N.id,name:N.name,path:N.path}).from(N).where(_(Fe(N.id,[...l]),p(N._deleted,!1)))}),queryPaginatedRoles:(l,d)=>Bt.gen(function*(){let u=(l-1)*d,h=(yield*e.select({count:f`count(*)`}).from(N).where(p(N._deleted,!1)))[0]?.count??0;return{items:yield*e.select({id:N.id,name:N.name,path:N.path}).from(N).where(p(N._deleted,!1)).orderBy(N.path).limit(d).offset(u),totalCount:h}}),queryProviderUserRoleIds:(l)=>Bt.gen(function*(){return(yield*e.select({roleId:N.id}).from(rt).innerJoin(N,_(p(rt.roleId,N.id),p(N._deleted,!1))).where(_(p(rt.providerUserId,l),p(rt._deleted,!1)))).map((u)=>u.roleId)}),replaceProviderUserRoles:(l,d)=>Bt.gen(function*(){if(yield*e.delete(rt).where(p(rt.providerUserId,l)),d.length>0){let u=yield*_r.now,m=d.map((h)=>({providerUserId:l,roleId:h,createdAt:u,updatedAt:u,createdBy:"SYSTEM",updatedBy:"SYSTEM",_deleted:!1}));yield*e.insert(rt).values(m)}}),createInvitation:(l)=>Bt.gen(function*(){let d=yield*_r.now,u=yield*e.insert(k).values({invitationId:l.invitationId,email:l.email,invitationStatus:ar.Pending,invitationSource:l.source,invitationPendingEmail:l.email,createdAt:d,updatedAt:d,createdBy:l.createdBy,updatedBy:l.updatedBy,_deleted:!1}).returning({id:k.id});return(yield*zt(u)).id}),updateInvitationDetails:(l,d)=>Bt.gen(function*(){let u=yield*_r.now,h=(yield*e.select({id:k.id,email:k.email}).from(k).where(_(p(k.id,l),p(k.invitationStatus,ar.Pending),p(k._deleted,!1))).limit(1))[0];if(!h)return!1;let S=h.email!==d.email;if((yield*e.update(k).set({email:d.email,invitationPendingEmail:d.email,updatedAt:u,updatedBy:d.updatedBy}).where(_(p(k.id,l),p(k.invitationStatus,ar.Pending),p(k._deleted,!1))).returning({id:k.id})).length===0)return!1;if(S)yield*e.update(k).set({...s,registrationLinkRevokedAt:u,registrationLinkRevokedBy:d.updatedBy,updatedAt:u,updatedBy:d.updatedBy}).where(_(p(k.id,l),p(k.invitationStatus,ar.Pending),p(k._deleted,!1),Nt(k.registrationTokenHash)));return!0}),replaceInvitationRoles:(l,d,u)=>Bt.gen(function*(){let m=yield*_r.now;if((yield*e.select({id:k.id}).from(k).where(_(p(k.id,l),p(k.invitationStatus,ar.Pending),p(k._deleted,!1))).limit(1)).length===0)return;let S=yield*e.select({id:Oe.id,roleId:Oe.roleId,deleted:Oe._deleted}).from(Oe).where(p(Oe.invitationId,l)),x=new Map(S.map((A)=>[A.roleId,A])),v=new Set(d),w=new Set(S.filter((A)=>!A.deleted).map((A)=>A.roleId)),P=d.some((A)=>!w.has(A))||[...w].some((A)=>!v.has(A)),F=S.filter((A)=>!A.deleted&&!v.has(A.roleId)).map((A)=>A.id);if(F.length>0)yield*e.update(Oe).set({_deleted:!0,updatedAt:m,updatedBy:u}).where(Fe(Oe.id,F));if(d.length===0){if(P)yield*e.update(k).set({...s,registrationLinkRevokedAt:m,registrationLinkRevokedBy:u,updatedAt:m,updatedBy:u}).where(_(p(k.id,l),p(k.invitationStatus,ar.Pending),p(k._deleted,!1),Nt(k.registrationTokenHash)));return}let R=d.flatMap((A)=>{let D=x.get(A);return D?.deleted?[D.id]:[]});if(R.length>0)yield*e.update(Oe).set({_deleted:!1,updatedAt:m,updatedBy:u}).where(Fe(Oe.id,R));let b=d.filter((A)=>!x.has(A));if(b.length>0)yield*e.insert(Oe).values(b.map((A)=>({invitationId:l,roleId:A,createdAt:m,updatedAt:m,createdBy:u,updatedBy:u,_deleted:!1})));if(P)yield*e.update(k).set({...s,registrationLinkRevokedAt:m,registrationLinkRevokedBy:u,updatedAt:m,updatedBy:u}).where(_(p(k.id,l),p(k.invitationStatus,ar.Pending),p(k._deleted,!1),Nt(k.registrationTokenHash)))}),deleteInvitation:(l,d)=>Bt.gen(function*(){let u=yield*_r.now;if((yield*e.update(k).set({_deleted:!0,invitationPendingEmail:null,...s,registrationLinkRevokedAt:u,registrationLinkRevokedBy:d,updatedAt:u,updatedBy:d}).where(_(p(k.id,l),p(k.invitationStatus,ar.Pending),p(k._deleted,!1))).returning({id:k.id})).length===0)return!1;return yield*e.update(Oe).set({_deleted:!0,updatedAt:u,updatedBy:d}).where(_(p(Oe.invitationId,l),p(Oe._deleted,!1))),!0}),storeRegistrationLink:(l,d)=>Bt.gen(function*(){let u=yield*_r.now,m=_r.unsafeMake(d.expiresAt),h=d.requireActiveLink?_(Nt(k.registrationTokenHash),Xt(k.registrationLinkExpiresAt,u)):Rt(Se(k.registrationTokenHash),dn(k.registrationLinkExpiresAt,u));return(yield*e.update(k).set({registrationTokenHash:d.tokenHash,registrationEncryptionVersion:d.encryptionVersion,registrationEncryptionNonce:d.nonce,registrationAuthenticationTag:d.authenticationTag,registrationEncryptedToken:d.ciphertext,registrationLinkExpiresAt:m,registrationLinkGeneratedAt:u,registrationLinkGeneratedBy:d.actor,registrationLinkRevealedAt:null,registrationLinkRevealedBy:null,registrationLinkRevokedAt:null,registrationLinkRevokedBy:null,registrationLinkGeneration:d.generation,updatedAt:u,updatedBy:d.actor}).where(_(p(k.id,l),p(k.invitationStatus,ar.Pending),p(k._deleted,!1),f`coalesce(${k.registrationLinkGeneration}, 0) = ${d.expectedPreviousGeneration}`,h)).returning({id:k.id})).length>0}),recordRegistrationLinkReveal:(l,d,u)=>Bt.gen(function*(){let m=yield*_r.now;return(yield*e.update(k).set({registrationLinkRevealedAt:m,registrationLinkRevealedBy:d,updatedAt:m,updatedBy:d}).where(_(p(k.id,l),p(k.invitationStatus,ar.Pending),p(k._deleted,!1),p(k.registrationTokenHash,u.tokenHash),f`coalesce(${k.registrationLinkGeneration}, 0) = ${u.generation}`,Xt(k.registrationLinkExpiresAt,m))).returning({id:k.id})).length>0}),queryLiveRegistrationLink:(l,d)=>Bt.gen(function*(){let u=_r.unsafeMake(d),h=(yield*e.select({invitationId:k.id,tokenHash:k.registrationTokenHash,encryptionVersion:k.registrationEncryptionVersion,nonce:k.registrationEncryptionNonce,authenticationTag:k.registrationAuthenticationTag,ciphertext:k.registrationEncryptedToken,expiresAt:k.registrationLinkExpiresAt,generation:k.registrationLinkGeneration}).from(k).where(_(p(k.id,l),p(k.invitationStatus,ar.Pending),p(k._deleted,!1),Nt(k.registrationTokenHash),Xt(k.registrationLinkExpiresAt,u))).limit(1))[0];if(!h?.tokenHash||h.encryptionVersion===null||!h.nonce||!h.authenticationTag||!h.ciphertext||!h.expiresAt||h.generation===null)return null;return{invitationId:h.invitationId,tokenHash:h.tokenHash,encryptionVersion:h.encryptionVersion,nonce:h.nonce,authenticationTag:h.authenticationTag,ciphertext:h.ciphertext,expiresAt:_r.toDateUtc(h.expiresAt),generation:h.generation}}),revokeRegistrationLink:(l,d,u)=>Bt.gen(function*(){let m=yield*_r.now,h=u?[p(k.registrationTokenHash,u.tokenHash),f`coalesce(${k.registrationLinkGeneration}, 0) = ${u.generation}`]:[Nt(k.registrationTokenHash)];return(yield*e.update(k).set({...s,registrationLinkRevokedAt:m,registrationLinkRevokedBy:d,updatedAt:m,updatedBy:d}).where(_(p(k.id,l),p(k.invitationStatus,ar.Pending),p(k._deleted,!1),...h)).returning({id:k.id})).length>0}),clearRegistrationLink:(l,d)=>Bt.gen(function*(){let u=yield*_r.now;yield*e.update(k).set({...s,registrationLinkRevokedAt:u,registrationLinkRevokedBy:d,updatedAt:u,updatedBy:d}).where(_(p(k.id,l),p(k._deleted,!1),Nt(k.registrationTokenHash)))}),isPasskeyProviderEnabled:()=>Bt.gen(function*(){return(yield*e.select({id:mt.id}).from(mt).where(_(p(mt.providerName,"passkey"),p(mt._deleted,!1))).limit(1)).length>0}),queryNotificationPreferences:(l)=>Bt.gen(function*(){let u=(yield*e.select({notificationPreference:Mt.notificationPreference}).from(Mt).where(_(p(Mt.userId,l),p(Mt._deleted,!1))).limit(1))[0];if(!u?.notificationPreference)return vh;return _d(u.notificationPreference)}),updateNotificationPreferences:(l,d,u)=>Bt.gen(function*(){let m=yield*_r.now;yield*e.insert(Mt).values({userId:l,notificationPreference:ZI(d),createdAt:m,updatedAt:m,updatedBy:u}).onConflictDoUpdate({target:Mt.userId,targetWhere:f`_deleted = 0`,set:{notificationPreference:ZI(d),updatedAt:m,updatedBy:u}})}),queryProviderUserByEmail:(l)=>Bt.gen(function*(){let d=l.trim().toLowerCase();return(yield*e.select({id:O.id,email:O.email}).from(O).where(_(f`lower(${O.email}) = ${d}`,p(O._deleted,!1))).limit(1))[0]??null}),queryRoleByPath:(l)=>Bt.gen(function*(){return(yield*e.select({id:N.id,path:N.path}).from(N).where(_(p(N.path,l),p(N._deleted,!1))).limit(1))[0]??null}),grantProviderUserRole:(l,d,u)=>Bt.gen(function*(){let h=(yield*e.select({id:rt.id,deleted:rt._deleted}).from(rt).where(_(p(rt.providerUserId,l),p(rt.roleId,d))).limit(1))[0];if(h&&!h.deleted)return{alreadyHadRole:!0};let S=yield*_r.now;if(h?.deleted)return yield*e.update(rt).set({_deleted:!1,updatedAt:S,updatedBy:u}).where(p(rt.id,h.id)),{alreadyHadRole:!1};return{alreadyHadRole:(yield*e.insert(rt).values({providerUserId:l,roleId:d,createdAt:S,updatedAt:S,createdBy:u,updatedBy:u,_deleted:!1}).returning({id:rt.id}).pipe(Bt.catchAll((v)=>bee(v)?Bt.succeed([]):Bt.fail(v)))).length===0}})}}));import{strict as Eee}from"assert";import{DateTime as Qo,Effect as $t,Layer as Tee,Schema as Xc}from"effect";var Dj=Tee.effect(uC,$t.gen(function*(){let e=yield*pe,t=(r,n)=>$t.gen(function*(){return(yield*e.select({id:C.id,createdBy:C.createdBy,processExecutionId:C.processExecutionId,processStateId:W.processStateId,startedByUserId:M.startedByUserId,targetStepId:U.id,targetStepPath:U.path,processPath:z.path,orgUnitPath:V.path,assignedToProviderUserId:C.assignedToProviderUserId,assignedToProviderUserEmail:O.email,correctionRequiredAt:C.correctionRequiredAt,createdAtMs:f`(${C.createdAt} - 2440587.5) * 86400000`.as("created_at_ms"),orgUnitId:z.orgUnitId,itemData:C.itemData,hasForEach:U.hasForEach,barrierScheduledFlowId:C.barrierScheduledFlowId,completed:C._deleted}).from(C).innerJoin(W,p(C.processExecutionId,W.id)).innerJoin(M,p(W.processStateId,M.id)).innerJoin(z,p(M.processId,z.id)).innerJoin(V,p(z.orgUnitId,V.id)).innerJoin(Q,p(C.flowId,Q.id)).innerJoin(U,p(Q.targetStepId,U.id)).leftJoin(O,p(C.assignedToProviderUserId,O.id)).where(n?p(C.id,r):_(p(C.id,r),p(C._deleted,!1))).limit(1))[0]??null});return{queryTodoById:(r)=>t(r,!1),queryTodoForCompletionById:(r)=>t(r,!0),queryPublicTodoInfo:(r)=>$t.gen(function*(){let o=(yield*e.select({todoId:C.id,deleted:C._deleted,failureReason:C.failureReason,correctionRequiredAt:C.correctionRequiredAt,abandonedAt:W.abandonedAt,stepPath:U.path,itemData:C.itemData}).from(C).innerJoin(W,p(C.processExecutionId,W.id)).innerJoin(Q,p(C.flowId,Q.id)).innerJoin(U,p(Q.targetStepId,U.id)).where(p(C.id,r)).limit(1))[0];if(!o)return{todoId:r,status:"unavailable",stepPath:null,latestPublicCompletionInvitationRecipientEmail:null,itemData:null};let i=o.failureReason!=null||o.correctionRequiredAt!=null?"unavailable":o.deleted?o.abandonedAt?"unavailable":"completed":"active",s=i!=="unavailable"?yield*e.select({email:nt.email}).from(nt).where(_(p(nt.toDoId,r),p(nt._deleted,!1))).orderBy(Hr(nt.createdAt),Hr(nt.id)).limit(1):[];return{todoId:o.todoId,status:i,stepPath:o.stepPath,latestPublicCompletionInvitationRecipientEmail:s[0]?.email??null,itemData:o.itemData}}),queryLatestPublicCompletionInvitationAttempt:(r)=>$t.gen(function*(){return(yield*e.select({id:nt.id,email:nt.email}).from(nt).where(_(p(nt.toDoId,r),p(nt._deleted,!1))).orderBy(Hr(nt.createdAt),Hr(nt.id)).limit(1))[0]??null}),createPublicCompletionInvitationAttempt:({todoId:r,recipientEmail:n})=>$t.gen(function*(){let o=yield*he(),i=yield*st(),s=yield*e.insert(nt).values({toDoId:r,email:n,createdAt:o,updatedAt:o,createdBy:i.by,updatedBy:i.by}).returning({id:nt.id});return(yield*zt(s)).id}),recordPublicCompletionInvitationAttemptReceipt:(r,n)=>$t.gen(function*(){let o=yield*he(),i=yield*st();return(yield*e.update(nt).set({providerMessageId:n.providerMessageId,providerSentTo:n.providerSentTo,updatedAt:o,updatedBy:i.by}).where(_(p(nt.id,r),p(nt._deleted,!1))).returning({id:nt.id})).length>0}),queryPublicCompletionInvitationAttemptCallbackTarget:(r,n)=>$t.gen(function*(){if((yield*e.select({id:nt.id}).from(nt).where(_(p(nt.toDoId,r),p(nt._deleted,!1))).orderBy(Hr(nt.createdAt),Hr(nt.id)).limit(1))[0]?.id!==n)return null;return(yield*e.select({attemptId:nt.id,todoId:C.id,providerMessageId:nt.providerMessageId,providerSentTo:nt.providerSentTo,processExecutionId:C.processExecutionId,assignedToProviderUserId:C.assignedToProviderUserId,roleId:U.roleId,stepPath:U.path,stepName:U.name,processName:z.name}).from(nt).innerJoin(C,p(nt.toDoId,C.id)).innerJoin(Q,p(C.flowId,Q.id)).innerJoin(U,p(Q.targetStepId,U.id)).innerJoin(z,p(U.processId,z.id)).where(_(p(nt.id,n),p(nt.toDoId,r),p(nt._deleted,!1),p(C._deleted,!1),Se(C.completedByUserId),Se(C.completedByExternalParticipantId),Se(C.completedByRoleId),Se(C.failureReason),Se(C.correctionRequiredAt),p(Q._deleted,!1),p(U._deleted,!1),p(z._deleted,!1))).limit(1))[0]??null}),recordPublicCompletionInvitationAttemptDeliveryEvent:(r,n)=>$t.gen(function*(){let o=yield*he(),i=yield*st();return(yield*e.update(nt).set({deliveryStatus:n.deliveryStatus,deliveryEventId:n.deliveryEventId,deliveryFailureKind:n.deliveryStatus==="failed"?n.deliveryFailureKind??null:null,deliveryFailureReason:n.deliveryStatus==="failed"?n.deliveryFailureReason??null:null,...n.providerMessageId!==void 0&&{providerMessageId:n.providerMessageId},updatedAt:o,updatedBy:i.by}).where(_(p(nt.id,r),p(nt._deleted,!1))).returning({id:nt.id})).length>0}),enterPublicCompletionCorrectionRequired:(r)=>$t.gen(function*(){let n=yield*he(),o=yield*st(),s=(yield*e.update(C).set({correctionRequiredAt:n,correctionFailureReason:r.failureReason,correctionInvitationAttemptId:r.invitationAttemptId,updatedAt:n,updatedBy:o.by}).where(_(p(C.id,r.todoId),p(C._deleted,!1),Se(C.completedByUserId),Se(C.completedByExternalParticipantId),Se(C.completedByRoleId),Se(C.failureReason),Se(C.correctionRequiredAt))).returning({id:C.id,processExecutionId:C.processExecutionId}))[0];if(!s)return!1;return yield*e.update(W).set({updatedAt:n,updatedBy:o.by}).where(p(W.id,s.processExecutionId)),!0}),queryPublicCompletionCorrectionRecipient:(r)=>$t.gen(function*(){return(yield*e.select({recipientEmail:nt.email,failureReason:C.correctionFailureReason}).from(C).innerJoin(nt,p(C.correctionInvitationAttemptId,nt.id)).where(_(p(C.id,r),p(C._deleted,!1),Se(C.completedByUserId),Se(C.completedByExternalParticipantId),Se(C.completedByRoleId),Se(C.failureReason),Nt(C.correctionRequiredAt),p(nt._deleted,!1))).limit(1))[0]??null}),clearPublicCompletionCorrectionRequired:(r)=>$t.gen(function*(){let n=yield*he(),o=yield*st(),s=(yield*e.update(C).set({correctionRequiredAt:null,correctionFailureReason:null,correctionInvitationAttemptId:null,updatedAt:n,updatedBy:o.by}).where(_(p(C.id,r),p(C._deleted,!1),Se(C.completedByUserId),Se(C.completedByExternalParticipantId),Se(C.completedByRoleId),Se(C.failureReason),Nt(C.correctionRequiredAt))).returning({id:C.id,processExecutionId:C.processExecutionId}))[0];if(!s)return!1;return yield*e.update(W).set({updatedAt:n,updatedBy:o.by}).where(p(W.id,s.processExecutionId)),!0}),updateProcessState:(r,n)=>$t.gen(function*(){let o=yield*he(),i=yield*st();yield*e.update(M).set({state:f`json_patch(${M.state}, ${globalThis.JSON.stringify(n)})`,updatedAt:o,updatedBy:i.by}).where(p(M.id,r))}),updateProcessStateIfUnchanged:(r,n,o)=>$t.gen(function*(){let i=yield*he(),s=yield*st(),a=Qo.toEpochMillis(i)>Qo.toEpochMillis(n)?i:Qo.add(n,{millis:1}),l=(yield*e.update(M).set({state:f`json_patch(${M.state}, ${globalThis.JSON.stringify(o)})`,updatedAt:a,updatedBy:s.by}).where(_(p(M.id,r),f`ROUND((${M.updatedAt} - 2440587.5) * 86400000) = ${Math.round(Qo.toEpochMillis(n))}`)).returning({updatedAtMs:f`ROUND((${M.updatedAt} - 2440587.5) * 86400000)`}))[0];return l?{kind:"updated",updatedAt:Qo.unsafeMake(l.updatedAtMs)}:{kind:"conflict"}}),appendProcessStateArrayItem:(r,n,o)=>$t.gen(function*(){let i=yield*he(),s=yield*st(),a=`$.${n}`,c=globalThis.JSON.stringify(o);yield*e.update(M).set({state:f`json_set(COALESCE(${M.state}, json('{}')), ${a}, json_insert(COALESCE(json_extract(${M.state}, ${a}), json('[]')), '$[#]', json(${c})))`,updatedAt:i,updatedBy:s.by}).where(p(M.id,r))}),appendProcessStateArrayItemIfUnchanged:(r,n,o,i)=>$t.gen(function*(){let s=yield*he(),a=yield*st(),c=Qo.toEpochMillis(s)>Qo.toEpochMillis(n)?s:Qo.add(n,{millis:1}),l=`$.${o}`,d=globalThis.JSON.stringify(i),m=(yield*e.update(M).set({state:f`json_set(COALESCE(${M.state}, json('{}')), ${l}, json_insert(COALESCE(json_extract(${M.state}, ${l}), json('[]')), '$[#]', json(${d})))`,updatedAt:c,updatedBy:a.by}).where(_(p(M.id,r),f`ROUND((${M.updatedAt} - 2440587.5) * 86400000) = ${Math.round(Qo.toEpochMillis(n))}`)).returning({updatedAtMs:f`ROUND((${M.updatedAt} - 2440587.5) * 86400000)`}))[0];return m?{kind:"updated",updatedAt:Qo.unsafeMake(m.updatedAtMs)}:{kind:"conflict"}}),completeToDo:(r,n,o,i,s)=>$t.gen(function*(){let a=yield*he(),c=yield*st();yield*e.update(C).set({completedByUserId:n,...i!==void 0?{completedByExternalParticipantId:i}:{},...s!==void 0?{completedByRoleId:s}:{},businessDuration:o,failureReason:null,correctionRequiredAt:null,correctionFailureReason:null,correctionInvitationAttemptId:null,_deleted:!0,updatedAt:a,updatedBy:c.by}).where(p(C.id,r));let l=yield*e.select({id:C.id,processExecutionId:C.processExecutionId,flowId:C.flowId,processName:z.name,processPath:z.path,processOrgUnitPath:V.path,stepName:U.name,stepPath:U.path,rolePath:N.path,assignedToProviderUserId:C.assignedToProviderUserId,assignedToProviderUserEmail:O.email,role:N.name,description:U.purpose,formFields:U.formFields,updatedAt:f`(${C.updatedAt} - 2440587.5) * 86400000`.as("updated_at_millis"),createdAt:f`strftime('%Y-%m-%dT%H:%M:%fZ', (${C.createdAt} - 2440587.5) * 86400, 'unixepoch')`.as("created_at_iso"),slaTargetAt:f`CASE WHEN ${C.slaTargetAt} IS NOT NULL THEN strftime('%Y-%m-%dT%H:%M:%fZ', (${C.slaTargetAt} - 2440587.5) * 86400, 'unixepoch') ELSE NULL END`.as("sla_target_at_iso"),slaWarningAt:f`CASE WHEN ${C.slaWarningAt} IS NOT NULL THEN strftime('%Y-%m-%dT%H:%M:%fZ', (${C.slaWarningAt} - 2440587.5) * 86400, 'unixepoch') ELSE NULL END`.as("sla_warning_at_iso"),deleted:C._deleted}).from(C).innerJoin(W,p(C.processExecutionId,W.id)).innerJoin(M,p(W.processStateId,M.id)).innerJoin(z,p(M.processId,z.id)).innerJoin(V,p(z.orgUnitId,V.id)).innerJoin(Q,p(C.flowId,Q.id)).innerJoin(U,p(Q.targetStepId,U.id)).leftJoin(N,p(U.roleId,N.id)).leftJoin(O,p(C.assignedToProviderUserId,O.id)).where(p(C.id,r)).limit(1);Eee(l[0]);let d=l[0];return{id:d.id,processExecutionId:d.processExecutionId,flowId:d.flowId,processName:d.processName,processPath:d.processPath,processOrgUnitPath:d.processOrgUnitPath,stepName:d.stepName,stepPath:d.stepPath,rolePath:d.rolePath,assignedToProviderUserId:d.assignedToProviderUserId,assignedToProviderUserEmail:d.assignedToProviderUserEmail,role:d.role,description:d.description,status:"Active",priority:"Medium",assignedAt:d.createdAt,dueAt:d.slaTargetAt,dueWarningAt:d.slaWarningAt,formComplexity:gw(d.formFields),updatedAt:d.updatedAt,deleted:d.deleted,summary:[]}}),completeToDoIfOpen:(r)=>$t.gen(function*(){let n=yield*he(),o=yield*st();if((yield*e.update(C).set({completedByUserId:r.userId,completedByExternalParticipantId:r.externalParticipantId,completedByRoleId:r.completedByRoleId,businessDuration:r.businessDurationMs,failureReason:null,correctionRequiredAt:null,correctionFailureReason:null,correctionInvitationAttemptId:null,_deleted:!0,updatedAt:n,updatedBy:o.by}).where(_(p(C.id,r.todoId),p(C._deleted,!1))).returning({id:C.id}))[0])return{kind:"completed"};let a=(yield*e.select({deleted:C._deleted,completedByUserId:C.completedByUserId,completedByExternalParticipantId:C.completedByExternalParticipantId,completedByRoleId:C.completedByRoleId,businessDuration:C.businessDuration}).from(C).where(p(C.id,r.todoId)).limit(1))[0];if(!a)return{kind:"not-found"};if(a.deleted&&a.completedByUserId===r.userId&&a.completedByExternalParticipantId===r.externalParticipantId&&a.completedByRoleId===r.completedByRoleId)return{kind:"already-completed"};return{kind:"conflict"}}),completeAsyncToDo:(r,n,o,i)=>$t.gen(function*(){let s=yield*he(),a=yield*st();return(yield*e.update(C).set({completedByUserId:n,businessDuration:o,failureReason:null,correctionRequiredAt:null,correctionFailureReason:null,correctionInvitationAttemptId:null,_deleted:!0,...i!==void 0?{completedByRoleId:i}:{},updatedAt:s,updatedBy:a.by}).where(_(p(C.id,r),p(C._deleted,!1))).returning({id:C.id})).length>0}),failToDo:(r,n)=>$t.gen(function*(){let o=yield*he(),i=yield*st();yield*e.update(C).set({failureReason:n,correctionRequiredAt:null,correctionFailureReason:null,correctionInvitationAttemptId:null,completedByUserId:null,_deleted:!1,updatedAt:o,updatedBy:i.by}).where(_(p(C.id,r),p(C._deleted,!1)))}),failAsyncToDo:(r,n)=>$t.gen(function*(){let o=yield*he(),i=yield*st();return(yield*e.update(C).set({failureReason:n,updatedAt:o,updatedBy:i.by}).where(_(p(C.id,r),p(C._deleted,!1),Se(C.failureReason),Se(C.correctionRequiredAt))).returning({id:C.id})).length>0}),getProcessStateByTodoId:(r)=>$t.gen(function*(){let n=yield*e.select({processExecutionId:W.id,processStateId:M.id,state:M.state,updatedAtMs:f`ROUND((${M.updatedAt} - 2440587.5) * 86400000)`,processStartedAt:f`(${W.createdAt} - 2440587.5) * 86400000`.as("process_started_at_millis")}).from(C).innerJoin(W,p(C.processExecutionId,W.id)).innerJoin(M,p(W.processStateId,M.id)).where(_(p(C.id,r),p(C._deleted,!1))).limit(1);if(!n[0])return null;let o=Xc.Record({key:Xc.String,value:Xc.Unknown}),i=Xc.decodeUnknownEither(o)(n[0].state??{});if(i._tag==="Left")return yield*new Sw({processStateId:n[0].processStateId,message:"Process state has invalid format in database"});return{processExecutionId:n[0].processExecutionId,processStateId:n[0].processStateId,state:i.right,updatedAt:Qo.unsafeMake(n[0].updatedAtMs),processStartedAt:Qo.unsafeFromDate(new Date(n[0].processStartedAt))}}),countActiveTodos:(r)=>$t.gen(function*(){let n=yield*e.select({count:f`COUNT(*)`.as("count")}).from(C).where(_(p(C.processExecutionId,r),p(C._deleted,!1)));return Number(n[0]?.count??0)}),countPendingFlowJobs:(r,n)=>$t.gen(function*(){let o=yield*e.select({count:f`COUNT(*)`.as("count")}).from(Ke).where(_(p(Ke.queue,n),p(Ke._deleted,!1),f`json_extract(${Ke.jobPayload}, '$.processExecutionId') = ${r}`));return Number(o[0]?.count??0)}),setProcessExecutionFinished:(r,n)=>$t.gen(function*(){let o=yield*he(),i=yield*st();yield*e.update(W).set({finishedAt:o,businessDuration:n,updatedAt:o,updatedBy:i.by}).where(p(W.id,r))}),getProcessStatesByTodoIds:(r)=>$t.gen(function*(){if(r.length===0)return[];let n=yield*e.select({todoId:C.id,processExecutionId:W.id,processStateId:M.id,state:M.state,stepPath:U.path,itemData:C.itemData,processStartedAt:f`(${W.createdAt} - 2440587.5) * 86400000`.as("process_started_at_millis")}).from(C).innerJoin(W,p(C.processExecutionId,W.id)).innerJoin(M,p(W.processStateId,M.id)).innerJoin(Q,p(C.flowId,Q.id)).innerJoin(U,p(Q.targetStepId,U.id)).where(Fe(C.id,r)),o=Xc.Record({key:Xc.String,value:Xc.Unknown}),i=[];for(let s of n){let a=Xc.decodeUnknownEither(o)(s.state??{});if(a._tag==="Left")return yield*new Sw({processStateId:s.processStateId,message:"Process state has invalid format in database"});i.push({todoId:s.todoId,processExecutionId:s.processExecutionId,processStateId:s.processStateId,state:a.right,stepPath:s.stepPath,processStartedAt:Qo.unsafeFromDate(new Date(s.processStartedAt)),itemData:s.itemData})}return i}),getCompletedStepsForExecution:(r)=>$t.gen(function*(){let n=yield*e.select({stepPath:U.path,userId:X.id,userSub:X.sub,providerUserId:f`COALESCE(${O.id}, ${X.id})`.as("assigned_to_provider_user_id"),providerUserName:f`COALESCE(${O.name}, ${X.sub})`.as("provider_user_name"),providerUserFirstName:f`COALESCE(${O.firstName}, ${X.sub})`.as("provider_user_first_name"),providerUserLastName:f`COALESCE(${O.lastName}, '')`.as("provider_user_last_name"),providerUserEmail:f`COALESCE(${O.email}, ${X.sub})`.as("provider_user_email"),providerUserPicture:f`COALESCE(${O.picture}, '')`.as("provider_user_picture"),completedAt:f`(${W.createdAt} - 2440587.5) * 86400000`.as("completed_at_millis")}).from(W).innerJoin(M,p(W.processStateId,M.id)).innerJoin(U,p(M.startStepId,U.id)).innerJoin(X,p(M.startedByUserId,X.id)).leftJoin(O,p(X.id,O.userId)).where(p(W.id,r)),o=yield*e.select({stepPath:U.path,userId:X.id,userSub:X.sub,providerUserId:f`COALESCE(${O.id}, ${X.id})`.as("assigned_to_provider_user_id"),providerUserName:f`COALESCE(${O.name}, ${X.sub})`.as("provider_user_name"),providerUserFirstName:f`COALESCE(${O.firstName}, ${X.sub})`.as("provider_user_first_name"),providerUserLastName:f`COALESCE(${O.lastName}, '')`.as("provider_user_last_name"),providerUserEmail:f`COALESCE(${O.email}, ${X.sub})`.as("provider_user_email"),providerUserPicture:f`COALESCE(${O.picture}, '')`.as("provider_user_picture"),completedAt:f`(${C.updatedAt} - 2440587.5) * 86400000`.as("completed_at_millis")}).from(C).innerJoin(Q,p(C.flowId,Q.id)).innerJoin(U,p(Q.targetStepId,U.id)).innerJoin(X,p(C.completedByUserId,X.id)).leftJoin(O,p(X.id,O.userId)).where(_(p(C.processExecutionId,r),p(C._deleted,!0),Nt(C.completedByUserId)));return[...n,...o].map((s)=>({stepPath:s.stepPath,userId:s.userId,userSub:s.userSub,providerUserId:s.providerUserId,providerUserName:s.providerUserName,providerUserFirstName:s.providerUserFirstName,providerUserLastName:s.providerUserLastName,providerUserEmail:s.providerUserEmail,providerUserPicture:s.providerUserPicture,completedAt:Qo.unsafeFromDate(new Date(s.completedAt))}))}),queryFailedTodosForExecution:(r)=>$t.gen(function*(){return(yield*e.select({todoId:C.id,stepPath:U.path,isSystemStep:f`CASE WHEN ${U.roleId} IS NULL THEN 1 ELSE 0 END`.as("is_system_step")}).from(C).innerJoin(Q,p(C.flowId,Q.id)).innerJoin(U,p(Q.targetStepId,U.id)).where(_(p(C.processExecutionId,r),p(C._deleted,!1),Nt(C.failureReason)))).map((o)=>({todoId:o.todoId,stepPath:o.stepPath,isSystemStep:o.isSystemStep}))}),clearTodoFailures:(r)=>$t.gen(function*(){if(r.length===0)return;let n=yield*he(),o=yield*st();yield*e.update(C).set({failureReason:null,updatedAt:n,updatedBy:o.by}).where(Fe(C.id,r))}),clearProcessExecutionFinished:(r)=>$t.gen(function*(){let n=yield*he(),o=yield*st();yield*e.update(W).set({finishedAt:null,businessDuration:null,abandonedReason:null,updatedAt:n,updatedBy:o.by}).where(p(W.id,r))}),reopenFailedSystemStartExecution:(r)=>$t.gen(function*(){let n=yield*he(),o=yield*st();return(yield*e.update(W).set({finishedAt:null,businessDuration:null,abandonedReason:null,updatedAt:n,updatedBy:o.by}).where(_(p(W.id,r),Nt(W.finishedAt),Se(W.abandonedAt),Nt(W.abandonedReason))).returning({id:W.id})).length>0}),queryActiveTodoStepPaths:(r)=>$t.gen(function*(){return(yield*e.selectDistinct({stepPath:U.path}).from(C).innerJoin(Q,p(C.flowId,Q.id)).innerJoin(U,p(Q.targetStepId,U.id)).where(_(p(C.processExecutionId,r),p(C._deleted,!1),Se(C.failureReason)))).map((o)=>o.stepPath)}),setProcessExecutionAbandoned:(r,n)=>$t.gen(function*(){let o=yield*he(),i=yield*st();yield*e.update(W).set({finishedAt:o,abandonedAt:o,updatedAt:o,updatedBy:i.by,...n===void 0?{}:{abandonedReason:n}}).where(p(W.id,r))}),softDeleteActiveTodosForExecution:(r)=>$t.gen(function*(){let n=yield*he(),o=yield*st();return(yield*e.update(C).set({_deleted:!0,failureReason:"Execution abandoned",updatedAt:n,updatedBy:o.by}).where(_(p(C.processExecutionId,r),p(C._deleted,!1))).returning({id:C.id})).map((s)=>s.id)})}}));import{Effect as Ih,Layer as Ree}from"effect";var CC=Ree.effect(pC,Ih.gen(function*(){let e=yield*pe,t=(n)=>Ih.gen(function*(){return(yield*e.select({path:N.path}).from(Tr).innerJoin(N,p(Tr.roleId,N.id)).innerJoin(U,p(Tr.stepId,U.id)).where(_(p(U.path,n),p(Tr._deleted,!1),p(N._deleted,!1))).orderBy(Oo(Tr.createdAt))).map((i)=>i.path)}),r={rolePath:null,supportingRolePaths:[],startsProcess:!1,embedded:!1};return{queryRolePathsByStepPath:(n)=>Ih.gen(function*(){let i=(yield*e.select({rolePath:N.path,canStartProcess:bi.canStartProcess,embedded:U.embedded}).from(U).leftJoin(N,p(U.roleId,N.id)).innerJoin(bi,p(U.id,bi.id)).where(_(p(U.path,n),p(U._deleted,!1),Rt(Se(N.id),p(N._deleted,!1)))).limit(1))[0];if(!i)return{...r};let s=yield*t(n);return{rolePath:i.rolePath,supportingRolePaths:s,startsProcess:i.canStartProcess,embedded:i.embedded}}),queryRolePathsByStepPaths:(n)=>Ih.gen(function*(){if(n.length===0)return new Map;let o=yield*e.select({stepId:U.id,stepPath:U.path,rolePath:N.path,canStartProcess:bi.canStartProcess,embedded:U.embedded}).from(U).leftJoin(N,p(U.roleId,N.id)).innerJoin(bi,p(U.id,bi.id)).where(_(Fe(U.path,n),p(U._deleted,!1),Rt(Se(N.id),p(N._deleted,!1)))),i=o.map((l)=>l.stepId),s=i.length>0?yield*e.select({stepPath:U.path,rolePath:N.path}).from(Tr).innerJoin(N,p(Tr.roleId,N.id)).innerJoin(U,p(Tr.stepId,U.id)).where(_(Fe(U.id,i),p(Tr._deleted,!1),p(N._deleted,!1))).orderBy(Oo(Tr.createdAt)):[],a=new Map;for(let l of s){let d=a.get(l.stepPath);if(d)d.push(l.rolePath);else a.set(l.stepPath,[l.rolePath])}let c=new Map;for(let l of n)c.set(l,{...r});for(let l of o)c.set(l.stepPath,{rolePath:l.rolePath,supportingRolePaths:a.get(l.stepPath)??[],startsProcess:l.canStartProcess,embedded:l.embedded});return c}),queryRoleIdByPath:(n)=>Ih.gen(function*(){return(yield*e.select({id:N.id}).from(N).where(_(p(N.path,n),p(N._deleted,!1))).limit(1))[0]?.id})}}));import{Effect as Nj,Layer as Aee}from"effect";var _C=Aee.effect(fC,Nj.gen(function*(){let e=yield*pe;return{registerInvitation:(t)=>Nj.gen(function*(){let r=yield*he(),n=yield*st(),o=t.email.trim().toLowerCase();yield*e.insert(k).values({invitationId:t.invitationId,email:o,invitationStatus:"pending",invitationSource:"process",invitationPendingEmail:o,createdAt:r,updatedAt:r,createdBy:n.by,updatedBy:n.by})})}}));import{Effect as Ch,Layer as Pee}from"effect";var Zc=f`CAST(ROUND((${C.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`,kC=(e)=>e.select({id:C.id,processExecutionId:C.processExecutionId,flowId:C.flowId,processName:z.name,processPath:z.path,processOrgUnitPath:V.path,stepName:U.name,stepPath:U.path,rolePath:N.path,assignedToProviderUserId:C.assignedToProviderUserId,assignedToProviderUserEmail:O.email,role:N.name,description:U.purpose,formFields:U.formFields,correctionRequiredAt:C.correctionRequiredAt,updatedAt:Zc.as("updated_at_millis"),createdAt:f`strftime('%Y-%m-%dT%H:%M:%fZ', (${C.createdAt} - 2440587.5) * 86400, 'unixepoch')`.as("created_at_iso"),slaTargetAt:f`CASE WHEN ${C.slaTargetAt} IS NOT NULL THEN strftime('%Y-%m-%dT%H:%M:%fZ', (${C.slaTargetAt} - 2440587.5) * 86400, 'unixepoch') ELSE NULL END`.as("sla_target_at_iso"),slaWarningAt:f`CASE WHEN ${C.slaWarningAt} IS NOT NULL THEN strftime('%Y-%m-%dT%H:%M:%fZ', (${C.slaWarningAt} - 2440587.5) * 86400, 'unixepoch') ELSE NULL END`.as("sla_warning_at_iso"),deleted:C._deleted}).from(C).innerJoin(W,p(C.processExecutionId,W.id)).innerJoin(M,p(W.processStateId,M.id)).innerJoin(z,p(M.processId,z.id)).innerJoin(V,p(z.orgUnitId,V.id)).innerJoin(Q,p(C.flowId,Q.id)).innerJoin(U,p(Q.targetStepId,U.id)).innerJoin(N,p(U.roleId,N.id)).leftJoin(O,p(C.assignedToProviderUserId,O.id)),OC=(e)=>({id:e.id,processExecutionId:e.processExecutionId,flowId:e.flowId,processName:e.processName,processPath:e.processPath,processOrgUnitPath:e.processOrgUnitPath,stepName:e.stepName,stepPath:e.stepPath,rolePath:e.rolePath,assignedToProviderUserId:e.assignedToProviderUserId,assignedToProviderUserEmail:e.assignedToProviderUserEmail,role:e.role,description:e.description,status:e.correctionRequiredAt?"Correction Required":e.deleted?"Completed":"Active",priority:"Medium",assignedAt:e.createdAt,dueAt:e.slaTargetAt,dueWarningAt:e.slaWarningAt,formComplexity:gw(e.formFields),updatedAt:e.updatedAt,deleted:e.deleted,summary:[]}),DC=Pee.effect(mC,Ch.gen(function*(){let e=yield*pe;return{pullTodo:(t,r,n)=>Ch.gen(function*(){if(n.kind==="live-backfill"&&n.head===null)return[];let o=[];if(n.kind==="live-backfill")o.push(p(C._deleted,!1));if(n.kind==="live-backfill"&&n.head){let a=Rt(ms(Zc,n.head.updatedAt),_(p(Zc,n.head.updatedAt),dn(C.id,n.head.id)));if(a)o.push(a)}if(t){let a=Rt(Xt(Zc,t.updatedAt),_(p(Zc,t.updatedAt),Xt(C.id,t.id)));if(a)o.push(a)}return(yield*kC(e).where(o.length>0?_(...o):void 0).orderBy(Zc,C.id).limit(r)).map(OC)}),getTodoReplicationHead:()=>Ch.gen(function*(){return(yield*e.select({id:C.id,updatedAt:Zc}).from(C).orderBy(Hr(Zc),Hr(C.id)).limit(1))[0]??null}),getTodos:(t)=>Ch.gen(function*(){if(t.length===0)return[];return(yield*kC(e).where(Fe(C.id,t)).orderBy(C.updatedAt,C.id)).map(OC)}),listTodos:(t)=>Ch.gen(function*(){let r=[];if(t.processPath!=null)r.push(p(z.path,t.processPath));if(t.state)switch(t.state.kind){case"correction-required":r.push(Nt(C.correctionRequiredAt));break;case"correction-free":r.push(Se(C.correctionRequiredAt),p(C._deleted,t.state.deleted));break}return(yield*kC(e).where(r.length>0?_(...r):void 0).orderBy(Hr(C.createdAt),C.id).limit(t.limit).offset(t.offset)).map(OC)})}}));var Ect=Iee.mergeAll(vC,wj,Aj,Ij,Cj,kj,RC,Ej,bj,wC,bC,EC,TC,IC,_C,DC,Dj,CC,PC);import{strict as _h}from"assert";import{Effect as er,Layer as Cee}from"effect";var Fj=Cee.succeed(Ef,{upsertOrgUnit:(e,t)=>er.gen(function*(){let r=yield*pe,n=yield*he(),o=yield*r.insert(V).values({name:e.name,orgUnitLevel:e.orgUnitLevel,path:e.path,parentOrgUnitId:t??null,acronym:e.acronym??null,timezone:e.timezone,startDayOfWeek:e.startDayOfWeek??null,createdAt:n,updatedAt:n}).onConflictDoUpdate({target:V.path,targetWhere:f`_deleted = 0`,set:{name:e.name,orgUnitLevel:e.orgUnitLevel,parentOrgUnitId:t??null,acronym:e.acronym??null,timezone:e.timezone,startDayOfWeek:e.startDayOfWeek??null,updatedAt:n}}).returning({id:V.id});return(yield*zt(o)).id}),upsertProcess:(e,t)=>er.gen(function*(){let r=yield*pe,n=yield*he(),o=e.sla?.value??null,i=e.sla?.unit??null,s=e.sla?.warningAt??null,a=yield*r.insert(z).values({orgUnitId:t,name:e.name,path:e.path,purpose:e.purpose,slaValue:o,slaUnit:i,slaWarning:s,createdAt:n,updatedAt:n}).onConflictDoUpdate({target:z.path,targetWhere:f`_deleted = 0`,set:{name:e.name,purpose:e.purpose,orgUnitId:t,slaValue:o,slaUnit:i,slaWarning:s,updatedAt:n}}).returning({id:z.id});return(yield*zt(a)).id}),upsertRole:(e,t)=>er.gen(function*(){let r=yield*pe,n=yield*he(),o=yield*r.insert(N).values({orgUnitId:t,name:e.name,path:e.path,createdAt:n,updatedAt:n}).onConflictDoUpdate({target:N.path,targetWhere:f`_deleted = 0`,set:{name:e.name,orgUnitId:t,_deleted:!1,updatedAt:n}}).returning({id:N.id});return(yield*zt(o)).id}),upsertPhase:(e,t)=>er.gen(function*(){let r=yield*pe,n=yield*he(),o=yield*r.insert(Xr).values({processId:t,name:e.name,path:e.path,phaseOrder:e.order,createdAt:n,updatedAt:n}).onConflictDoUpdate({target:Xr.path,targetWhere:f`_deleted = 0`,set:{name:e.name,processId:t,phaseOrder:e.order,_deleted:!1,updatedAt:n}}).returning({id:Xr.id});return(yield*zt(o)).id}),upsertStep:(e,t,r)=>er.gen(function*(){let n=yield*pe,o=yield*he(),i=null;if(e.rolePath){let x=yield*n.select({id:N.id}).from(N).where(p(N.path,e.rolePath)).limit(1);_h(x[0],`Role not found for path: ${e.rolePath}`),i=x[0].id}let s=e.formFields??null,a=e.sla?.value??null,c=e.sla?.unit??null,l=e.sla?.warningAt??null,d=e.hasForEach??!1,u=e.embedded??!1,m=e.retryLimit??null,h=yield*n.insert(U).values({name:e.name,purpose:e.purpose,processId:t,roleId:i,formFields:s,phaseId:r??null,path:e.path,slaValue:a,slaUnit:c,slaWarning:l,hasForEach:d,embedded:u,retryLimit:m,createdAt:o,updatedAt:o}).onConflictDoUpdate({target:U.path,targetWhere:f`_deleted = 0`,set:{name:e.name,purpose:e.purpose,processId:t,roleId:i,formFields:s,phaseId:r??null,slaValue:a,slaUnit:c,slaWarning:l,hasForEach:d,embedded:u,retryLimit:m,_deleted:!1,updatedAt:o}}).returning({id:U.id}),S=(yield*zt(h)).id;if(e.supportingRolePaths!==void 0){yield*n.update(Tr).set({_deleted:!0,updatedAt:o}).where(_(p(Tr.stepId,S),p(Tr._deleted,!1)));for(let x of e.supportingRolePaths){let v=yield*n.select({id:N.id}).from(N).where(p(N.path,x)).limit(1);_h(v[0],`Supporting role not found for path: ${x}`),yield*n.insert(Tr).values({stepId:S,roleId:v[0].id,createdAt:o,updatedAt:o}).onConflictDoUpdate({target:[Tr.stepId,Tr.roleId],targetWhere:f`_deleted = 0`,set:{_deleted:!1,updatedAt:o}})}}return S}),upsertRoleResponsibility:(e,t,r)=>er.gen(function*(){let n=yield*pe,o=yield*he();yield*n.insert(mr).values({processId:t,roleId:r,responsibility:e.responsibility,responsibilityOrder:e.order,createdAt:o,updatedAt:o}).onConflictDoUpdate({target:[mr.processId,mr.roleId],targetWhere:f`_deleted = 0`,set:{responsibility:e.responsibility,responsibilityOrder:e.order,_deleted:!1,updatedAt:o}})}),upsertFlow:(e,t,r,n)=>er.gen(function*(){let o=yield*pe,i=yield*he(),s=t.taggedErrors?[...t.taggedErrors].sort():null,a=yield*o.select({id:U.id,processId:U.processId}).from(U).where(Fe(U.id,[r,n])),c=a.find((m)=>m.id===r),l=a.find((m)=>m.id===n);if(_h(c,`Source step not found: ${r}`),_h(l,`Target step not found: ${n}`),c.processId!==l.processId)return yield*new Zw({sourceStepId:r,targetStepId:n,sourceProcessId:c.processId,targetProcessId:l.processId});let u=(yield*o.select({id:Q.id}).from(Q).where(_(p(Q.flowKey,e),p(Q._deleted,!1))).limit(1))[0]??(yield*o.select({id:Q.id}).from(Q).where(_(p(Q.sourceStepId,r),p(Q.targetStepId,n),t.condition===void 0?Se(Q.condition):p(Q.condition,t.condition),t.schedule===void 0?Se(Q.schedule):p(Q.schedule,t.schedule),p(Q.fallbackBranch,t.isElse),p(Q.errorBranch,t.isOnError??!1),s===null?Se(Q.errorTags):p(Q.errorTags,s),p(Q._deleted,!1),rc(Q.flowKey,"legacy:%"))).limit(1))[0];if(u){yield*o.update(Q).set({flowKey:e,sourceStepId:r,targetStepId:n,condition:t.condition??null,schedule:t.schedule??null,fallbackBranch:t.isElse,errorBranch:t.isOnError??!1,errorTags:s,_deleted:!1,updatedAt:i}).where(p(Q.id,u.id));return}yield*o.insert(Q).values({flowKey:e,sourceStepId:r,targetStepId:n,condition:t.condition??null,schedule:t.schedule??null,fallbackBranch:t.isElse,errorBranch:t.isOnError??!1,errorTags:s,createdAt:i,updatedAt:i})}),deleteOrphanedFlows:(e)=>er.gen(function*(){let t=yield*pe,r=yield*he();if(e.length===0){yield*t.update(Q).set({_deleted:!0,updatedAt:r});return}let o=(yield*t.select({id:Q.id,flowKey:Q.flowKey}).from(Q)).filter((i)=>!e.includes(i.flowKey)).map((i)=>i.id);if(o.length>0)yield*t.update(Q).set({_deleted:!0,updatedAt:r}).where(Fe(Q.id,o))}),deleteOrphanedSteps:(e)=>er.gen(function*(){let t=yield*pe,r=yield*he();if(e.length===0)yield*t.update(U).set({_deleted:!0,updatedAt:r});else yield*t.update(U).set({_deleted:!0,updatedAt:r}).where(un(U.path,e))}),deleteOrphanedRoles:(e)=>er.gen(function*(){let t=yield*pe,r=yield*he();if(e.length===0)yield*t.update(N).set({_deleted:!0,updatedAt:r});else yield*t.update(N).set({_deleted:!0,updatedAt:r}).where(un(N.path,e))}),deleteOrphanedProcesses:(e)=>er.gen(function*(){let t=yield*pe,r=yield*he();if(e.length===0)yield*t.update(z).set({_deleted:!0,updatedAt:r});else yield*t.update(z).set({_deleted:!0,updatedAt:r}).where(un(z.path,e))}),deleteOrphanedOrgUnits:(e)=>er.gen(function*(){let t=yield*pe,r=yield*he();if(e.length===0)yield*t.update(V).set({_deleted:!0,updatedAt:r});else yield*t.update(V).set({_deleted:!0,updatedAt:r}).where(un(V.path,e))}),deleteOrphanedPhases:(e)=>er.gen(function*(){let t=yield*pe,r=yield*he();if(e.length===0)yield*t.update(Xr).set({_deleted:!0,updatedAt:r});else yield*t.update(Xr).set({_deleted:!0,updatedAt:r}).where(un(Xr.path,e))}),deleteOrphanedRoleResponsibilities:(e)=>er.gen(function*(){let t=yield*pe,r=yield*he();if(e.length===0){yield*t.update(mr).set({_deleted:!0,updatedAt:r});return}let n=new Map,o=yield*t.select({id:z.id,path:z.path}).from(z).where(p(z._deleted,!1));for(let d of o)n.set(d.path,d.id);let i=new Map,s=yield*t.select({id:N.id,path:N.path}).from(N).where(p(N._deleted,!1));for(let d of s)i.set(d.path,d.id);let a=e.map(({processPath:d,rolePath:u})=>{let m=n.get(d),h=i.get(u);return m&&h?{processId:m,roleId:h}:null}).filter((d)=>d!==null),l=(yield*t.select({id:mr.id,processId:mr.processId,roleId:mr.roleId}).from(mr)).filter((d)=>!a.some((u)=>u.processId===d.processId&&u.roleId===d.roleId)).map((d)=>d.id);if(l.length>0)yield*t.update(mr).set({_deleted:!0,updatedAt:r}).where(Fe(mr.id,l))}),upsertOAuthProvider:(e,t)=>er.gen(function*(){let r=yield*pe,n=yield*he();yield*r.insert(mt).values({providerName:e,providerConfig:t,createdAt:n,updatedAt:n}).onConflictDoUpdate({target:mt.providerName,targetWhere:f`_deleted = 0`,set:{providerConfig:t,updatedAt:n}})}),deleteOrphanedOAuthProviders:(e)=>er.gen(function*(){let t=yield*pe,r=yield*he();if(e.length===0)yield*t.update(mt).set({_deleted:!0,updatedAt:r});else yield*t.update(mt).set({_deleted:!0,updatedAt:r}).where(un(mt.providerName,e))}),upsertInvitation:(e,t)=>er.gen(function*(){let r=yield*pe,n=yield*he(),o=e.email.toLowerCase(),s=(yield*r.select({id:k.id,email:k.email,invitationStatus:k.invitationStatus}).from(k).where(_(p(k.invitationId,e.id),p(k._deleted,!1))).limit(1))[0];if(s&&s.invitationStatus!=="pending")return s.id;let a={registrationTokenHash:null,registrationEncryptionVersion:null,registrationEncryptionNonce:null,registrationAuthenticationTag:null,registrationEncryptedToken:null,registrationLinkExpiresAt:null,registrationLinkGeneration:f`coalesce(${k.registrationLinkGeneration}, 0) + 1`,registrationLinkRevokedAt:n,registrationLinkRevokedBy:"SYSTEM"};yield*r.update(k).set({_deleted:!0,invitationPendingEmail:null,...a,updatedAt:n}).where(_(p(k.invitationPendingEmail,o),ec(k.invitationId,e.id),p(k.invitationStatus,"pending"),p(k._deleted,!1))),yield*r.insert(k).values({invitationId:e.id,email:o,invitationStatus:"pending",invitationSource:"model",invitationPendingEmail:o,createdAt:n,updatedAt:n}).onConflictDoUpdate({target:k.invitationId,targetWhere:f`_deleted = 0`,set:{email:o,invitationSource:"model",invitationPendingEmail:o,_deleted:!1,updatedAt:n},setWhere:p(k.invitationStatus,"pending")});let l=(yield*r.select({id:k.id,email:k.email,invitationStatus:k.invitationStatus}).from(k).where(_(p(k.invitationId,e.id),p(k._deleted,!1))).limit(1))[0];if(_h(l,`Invitation upsert did not produce a row for ${e.id}`),l.invitationStatus!=="pending")return l.id;let d=l.id,u=s!==void 0&&s.email!==o;if((yield*r.update(k).set({updatedAt:n}).where(_(p(k.id,d),p(k.invitationStatus,"pending"),p(k._deleted,!1))).returning({id:k.id})).length===0)return d;let h=yield*r.select({id:Oe.id,roleId:Oe.roleId,deleted:Oe._deleted}).from(Oe).where(p(Oe.invitationId,d)),S=new Set(h.map((b)=>b.roleId)),x=new Set(h.filter((b)=>!b.deleted).map((b)=>b.roleId)),v=new Set(t),w=t.filter((b)=>!S.has(b)),P=h.filter((b)=>!b.deleted&&!v.has(b.roleId)).map((b)=>b.id),F=t.some((b)=>!x.has(b))||[...x].some((b)=>!v.has(b));if(u||F)yield*r.update(k).set({...a,updatedAt:n}).where(_(p(k.id,d),p(k.invitationStatus,"pending"),p(k._deleted,!1),Nt(k.registrationTokenHash)));if(w.length>0)yield*r.insert(Oe).values(w.map((b)=>({invitationId:d,roleId:b,createdAt:n,updatedAt:n})));if(P.length>0)yield*r.update(Oe).set({_deleted:!0,updatedAt:n}).where(Fe(Oe.id,P));let R=t.filter((b)=>S.has(b));if(R.length>0){let b=h.filter((A)=>R.includes(A.roleId)).map((A)=>A.id);if(b.length>0)yield*r.update(Oe).set({_deleted:!1,updatedAt:n}).where(Fe(Oe.id,b))}return d}),deleteOrphanedInvitations:(e)=>er.gen(function*(){let t=yield*pe,r=yield*he(),n=e.length===0?_(p(k.invitationSource,"model"),p(k.invitationStatus,"pending"),p(k._deleted,!1)):_(p(k.invitationSource,"model"),p(k.invitationStatus,"pending"),p(k._deleted,!1),un(k.invitationId,e)),o=yield*t.update(k).set({_deleted:!0,invitationPendingEmail:null,updatedAt:r}).where(n).returning({id:k.id});if(o.length>0)yield*t.update(Oe).set({_deleted:!0,updatedAt:r}).where(_(Fe(Oe.invitationId,o.map((i)=>i.id)),p(Oe._deleted,!1)))}),upsertOAuthClient:(e,t,r)=>er.gen(function*(){let n=yield*pe,o=yield*he();yield*n.insert(Ft).values({clientId:e,clientSecretHash:t,audience:r,createdAt:o,updatedAt:o}).onConflictDoUpdate({target:Ft.clientId,targetWhere:f`_deleted = 0`,set:{clientSecretHash:t,audience:r,_deleted:!1,updatedAt:o}})}),deleteOrphanedOAuthClients:(e)=>er.gen(function*(){let t=yield*pe,r=yield*he();if(e.length===0)yield*t.update(Ft).set({_deleted:!0,updatedAt:r});else yield*t.update(Ft).set({_deleted:!0,updatedAt:r}).where(un(Ft.clientId,e))}),upsertWeeklySchedule:(e,t)=>er.gen(function*(){let r=yield*pe,n=yield*he();yield*r.insert(en).values({orgUnitId:t,dayOfWeek:e.dayOfWeek,timeRanges:e.timeRanges,createdAt:n,updatedAt:n}).onConflictDoUpdate({target:[en.orgUnitId,en.dayOfWeek],targetWhere:f`_deleted = 0`,set:{timeRanges:e.timeRanges,_deleted:!1,updatedAt:n}})}),deleteOrphanedWeeklySchedules:(e)=>er.gen(function*(){let t=yield*pe,r=yield*he();if(e.length===0){yield*t.update(en).set({_deleted:!0,updatedAt:r});return}let n=new Map,o=yield*t.select({id:V.id,path:V.path}).from(V).where(p(V._deleted,!1));for(let c of o)n.set(c.path,c.id);let i=e.map(({orgUnitPath:c,dayOfWeek:l})=>{let d=n.get(c);return d?{orgUnitId:d,dayOfWeek:l}:null}).filter((c)=>c!==null),a=(yield*t.select({id:en.id,orgUnitId:en.orgUnitId,dayOfWeek:en.dayOfWeek}).from(en)).filter((c)=>!i.some((l)=>l.orgUnitId===c.orgUnitId&&l.dayOfWeek===c.dayOfWeek)).map((c)=>c.id);if(a.length>0)yield*t.update(en).set({_deleted:!0,updatedAt:r}).where(Fe(en.id,a))}),upsertHolidayRule:(e,t)=>er.gen(function*(){let r=yield*pe,n=yield*he();yield*r.insert(Or).values({orgUnitId:t,holidayTitle:e.name,holidayRule:e.rule,createdAt:n,updatedAt:n}).onConflictDoUpdate({target:[Or.orgUnitId,Or.holidayTitle],targetWhere:f`_deleted = 0`,set:{holidayRule:e.rule,_deleted:!1,updatedAt:n}})}),deleteOrphanedHolidayRules:(e)=>er.gen(function*(){let t=yield*pe,r=yield*he();if(e.length===0){yield*t.update(Or).set({_deleted:!0,updatedAt:r});return}let n=new Map,o=yield*t.select({id:V.id,path:V.path}).from(V).where(p(V._deleted,!1));for(let c of o)n.set(c.path,c.id);let i=e.map(({orgUnitPath:c,holidayTitle:l})=>{let d=n.get(c);return d&&l?{orgUnitId:d,holidayTitle:l}:null}).filter((c)=>c!==null),a=(yield*t.select({id:Or.id,orgUnitId:Or.orgUnitId,holidayTitle:Or.holidayTitle}).from(Or)).filter((c)=>!i.some((l)=>l.orgUnitId===c.orgUnitId&&l.holidayTitle===c.holidayTitle)).map((c)=>c.id);if(a.length>0)yield*t.update(Or).set({_deleted:!0,updatedAt:r}).where(Fe(Or.id,a))}),upsertDocumentStore:(e,t)=>er.gen(function*(){let r=yield*pe,n=yield*he(),o=yield*r.insert(wt).values({orgUnitId:t,name:e.name,path:e.path,acceptedTypes:e.acceptedTypes??null,sizeLimit:e.maxFileSize??null,createdAt:n,updatedAt:n}).onConflictDoUpdate({target:wt.path,targetWhere:f`_deleted = 0`,set:{name:e.name,orgUnitId:t,acceptedTypes:e.acceptedTypes??null,sizeLimit:e.maxFileSize??null,updatedAt:n}}).returning({id:wt.id});return(yield*zt(o)).id}),deleteOrphanedDocumentStores:(e)=>er.gen(function*(){let t=yield*pe,r=yield*he();if(e.length===0)yield*t.update(wt).set({_deleted:!0,updatedAt:r});else yield*t.update(wt).set({_deleted:!0,updatedAt:r}).where(un(wt.path,e))}),upsertStepDocumentStore:(e,t)=>er.gen(function*(){let r=yield*pe,n=yield*he();yield*r.insert(Wr).values({stepId:e,documentStoreId:t,createdAt:n,updatedAt:n}).onConflictDoUpdate({target:[Wr.stepId,Wr.documentStoreId],targetWhere:f`_deleted = 0`,set:{_deleted:!1,updatedAt:n}})}),deleteOrphanedStepDocumentStores:(e)=>er.gen(function*(){let t=yield*pe,r=yield*he();if(e.length===0){yield*t.update(Wr).set({_deleted:!0,updatedAt:r});return}let n=new Map,o=yield*t.select({id:U.id,path:U.path}).from(U).where(p(U._deleted,!1));for(let d of o)n.set(d.path,d.id);let i=new Map,s=yield*t.select({id:wt.id,path:wt.path}).from(wt).where(p(wt._deleted,!1));for(let d of s)i.set(d.path,d.id);let a=e.map(({stepPath:d,documentStorePath:u})=>{let m=n.get(d),h=i.get(u);return m&&h?{stepId:m,documentStoreId:h}:null}).filter((d)=>d!==null),l=(yield*t.select({id:Wr.id,stepId:Wr.stepId,documentStoreId:Wr.documentStoreId}).from(Wr)).filter((d)=>!a.some((u)=>u.stepId===d.stepId&&u.documentStoreId===d.documentStoreId)).map((d)=>d.id);if(l.length>0)yield*t.update(Wr).set({_deleted:!0,updatedAt:r}).where(Fe(Wr.id,l))})});import{Effect as Ws,Layer as _ee,Option as Uj}from"effect";var kee=_ee.effect(dC,Ws.gen(function*(){let e=yield*pe,t=Hn(U,"source_step"),r=Hn(U,"target_step");return{insertScheduledFlow:(n,o,i)=>Ws.gen(function*(){let s=yield*he(),a=yield*st(),c=yield*e.insert(Me).values({processExecutionId:n,sourceStepId:o,targetStepId:i?.targetStepId,scheduledAt:i?.scheduledAt,forEachBarrier:i?.forEachBarrier??!1,completedByRoleId:i?.completedByRoleId,createdAt:s,updatedAt:s,createdBy:a.by,updatedBy:a.by}).returning({id:Me.id});return(yield*zt(c)).id}),insertOrGetScheduledFlow:(n,o,i,s)=>Ws.gen(function*(){let a=yield*he(),c=yield*st(),l=yield*e.insert(Me).values({id:n,processExecutionId:o,sourceStepId:i,targetStepId:s?.targetStepId,scheduledAt:s?.scheduledAt,forEachBarrier:s?.forEachBarrier??!1,completedByRoleId:s?.completedByRoleId,createdAt:a,updatedAt:a,createdBy:c.by,updatedBy:c.by}).onConflictDoNothing({target:Me.id}).returning({id:Me.id});if(l[0])return l[0].id;let d=yield*e.select({id:Me.id}).from(Me).where(p(Me.id,n)).limit(1);return(yield*zt(d)).id}),getScheduledFlow:(n)=>Ws.gen(function*(){let o=yield*e.select({processExecutionId:Me.processExecutionId,createdBy:Me.createdBy,sourceStepId:Me.sourceStepId,targetStepId:Me.targetStepId,scheduledAt:Me.scheduledAt,forEachBarrier:Me.forEachBarrier,completedByRoleId:Me.completedByRoleId}).from(Me).where(p(Me.id,n)).limit(1);if(!o[0])return Uj.none();return Uj.some({processExecutionId:o[0].processExecutionId,createdBy:o[0].createdBy,sourceStepId:o[0].sourceStepId,targetStepId:o[0].targetStepId,scheduledAt:o[0].scheduledAt,forEachBarrier:o[0].forEachBarrier,completedByRoleId:o[0].completedByRoleId})}),deleteScheduledFlow:(n)=>Ws.gen(function*(){return(yield*e.delete(Me).where(p(Me.id,n)).returning({id:Me.id})).length>0}),hasPendingScheduledFlows:(n)=>Ws.gen(function*(){if((yield*e.select({id:Me.id}).from(Me).where(p(Me.processExecutionId,n)).limit(1)).length>0)return!0;return(yield*e.select({id:C.id}).from(C).innerJoin(Q,p(C.flowId,Q.id)).innerJoin(U,p(Q.targetStepId,U.id)).where(_(p(C.processExecutionId,n),Se(C.businessDuration),Se(C.failureReason),p(C._deleted,!1),Se(U.roleId))).limit(1)).length>0}),getPendingStartScheduledFlowId:(n,o)=>Ws.gen(function*(){return(yield*e.select({id:Me.id}).from(Me).where(_(p(Me.processExecutionId,n),p(Me.sourceStepId,o),Se(Me.targetStepId),Se(Me.scheduledAt),p(Me.forEachBarrier,!1))).limit(1))[0]?.id??null}),queryPendingAbandonStepPaths:(n)=>Ws.gen(function*(){let o=yield*e.select({sourceStepPath:t.path,targetStepPath:r.path}).from(Me).innerJoin(t,_(p(Me.sourceStepId,t.id),p(t._deleted,!1))).leftJoin(r,_(p(Me.targetStepId,r.id),p(r._deleted,!1))).where(_(p(Me.processExecutionId,n),p(Me._deleted,!1)));return[...new Set(o.map((i)=>i.targetStepPath??i.sourceStepPath))]}),deleteScheduledFlowsForExecution:(n)=>Ws.gen(function*(){yield*e.delete(Me).where(p(Me.processExecutionId,n))}),wasBarrierScheduledFlow:(n)=>Ws.gen(function*(){return(yield*e.select({id:C.id}).from(C).where(p(C.barrierScheduledFlowId,n)).limit(1)).length>0})}}));import{Data as Fa}from"effect";class pf extends Fa.TaggedError("OrgLoadError"){}class Oee extends Fa.TaggedError("BuildError"){}class Dee extends Fa.TaggedError("GraphqlSchemaError"){}class Nee extends Fa.TaggedError("PolicyFileError"){}class Fee extends Fa.TaggedError("InitError"){}class Uee extends Fa.TaggedError("MigrationError"){constructor(e){super({...e,message:e.statement?`Migration failed: ${e.reason}. Statement: ${e.statement}`:`Migration failed: ${e.reason}`})}}class Bee extends Fa.TaggedError("AuthLoginError"){}class Mee extends Fa.TaggedError("CliError"){}class Lee extends Fa.TaggedError("CustomDomainError"){}import{Console as vn,Data as Tw,Effect as $ee}from"effect";class Bj extends Tw.TaggedError("FlowValidationError"){}class qee extends Tw.TaggedError("MissingElseBranchError"){}class jee extends Tw.TaggedError("MultipleElseBranchError"){}class Mj extends Tw.TaggedError("MultipleStartNodesError"){}var Lj=(e)=>$ee.gen(function*(){let t=e.validateAllFlows();if(t.length>0){yield*vn.error(`
|
|
474
|
+
\u274C Flow Validation Error:`);for(let r of t){if(yield*vn.error(` Process: ${r.processPath}`),r.unreachable.length>0){yield*vn.error(" Unreachable steps (not connected to start):");for(let n of r.unreachable)yield*vn.error(` - ${n}`)}if(r.dangling.length>0){yield*vn.error(" Dangling steps (missing .end()):");for(let n of r.dangling)yield*vn.error(` - ${n}`)}if(r.missingElse.length>0){yield*vn.error(" Missing else branch (conditional flow without .else()):");for(let n of r.missingElse)yield*vn.error(` - ${n}`)}if(r.multipleElse.length>0){yield*vn.error(" Multiple else branches (only one allowed):");for(let n of r.multipleElse)yield*vn.error(` - ${n}`)}if(r.orphanElse.length>0){yield*vn.error(" Orphan else branch (else without conditional flow):");for(let n of r.orphanElse)yield*vn.error(` - ${n}`)}}return yield*vn.error(" Tip: Ensure all steps are connected via process.start() and call .end() on terminal steps"),yield*vn.error(" Tip: Steps with conditional flows must have exactly one .else() or .elseEnd() branch"),yield*vn.error(" Tip: An else branch requires at least one conditional flow from the same step"),yield*new Bj({flowErrors:t})}for(let r of e.processes()){let n=r.startNodes();if(n.length>1){yield*vn.error(`
|
|
475
|
+
\u274C Multiple Start Nodes Error:`),yield*vn.error(` Process: ${r.node.path}`),yield*vn.error(` Found ${n.length} start nodes, but only 1 is supported`),yield*vn.error(" Start nodes:");for(let o of n)yield*vn.error(` - ${o.node.path}`);return yield*new Mj({processPath:r.node.path,startNodeCount:n.length})}}});var ete=mf.effect(Io,Ks.map(Xee.now,(e)=>Zee.unsafeMake(e))),tte=Ks.tryPromise({try:async()=>{await Promise.resolve().then(() => Gj());return FC({busy_timeout:Ow})},catch:(e)=>new pf({path:"<built-org>",cause:e})}),rte=Ks.succeed(K_),nte=(e)=>{if(e.configureOrg&&Ks.isEffect(e.configureOrg))return e.configureOrg.pipe(Ks.provide(mf.setConfigProvider(Yee.fromEnv())));if(e.org)return Ks.succeed(e.org);return Ks.fail(new pf({path:"<built-org>",cause:Error("Built org bundle must export either 'configureOrg' or 'org'.")}))},Dlt=(e,t)=>Ks.gen(function*(){let r=Dw(t);if(!r)return yield*new pf({path:"<built-org>",cause:Nw});let n=yield*Yj.loadOrganisation({load:nte},e);yield*Lj(n).pipe(Ks.mapError((s)=>new pf({path:"<built-org>",cause:s._tag??s})));let o=Dh(r)?yield*tte:yield*rte,i=mf.mergeAll(Fj,ete).pipe(mf.provideMerge(FF),mf.provideMerge(o),mf.provide(Fw(r)));return yield*Yj.hydrateOrganisation({hydrate:(s)=>yD(s).pipe(Ks.provide(i))},{transaction:(s)=>s},n),{orgName:n.name,processPaths:n.processes().map((s)=>nr(s.node.path))}});export{Dlt as createBundledDbImport};
|