@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
package/dist/main.mjs
ADDED
|
@@ -0,0 +1,1444 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
var Xre=Object.create;var{getPrototypeOf:Zre,defineProperty:Dk,getOwnPropertyNames:ene}=Object;var aq=Object.prototype.hasOwnProperty;function tne(e){return this[e]}var rne,nne,so=(e,t,r)=>{var n=e!=null&&typeof e==="object";if(n){var o=t?rne??=new WeakMap:nne??=new WeakMap,i=o.get(e);if(i)return i}r=e!=null?Xre(Zre(e)):{};let s=t||!e||!e.__esModule||!aq.call(e,"default")?Dk(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of ene(e))if(!aq.call(s,a))Dk(s,a,{get:tne.bind(e,a),enumerable:!0})}if(n)o.set(e,s);return s};var Si=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var one=(e)=>e;function ine(e,t){this[e]=one.bind(null,t)}var cq=(e,t)=>{for(var r in t)Dk(e,r,{get:t[r],enumerable:!0,configurable:!0,set:ine.bind(t,r)})};var vi=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};var sne=import.meta.require;import*as lq from"effect/Data";import*as ane from"effect/Predicate";import*as Gr from"effect/Schema";var hT,eh=(e,t)=>{class r extends lq.Error{_tag=t}return r.prototype[e]=e,r.prototype.name=t,r},dq,ts,cne,Wf;var El=vi(()=>{hT=Symbol.for("@effect/platform/Error"),dq=Gr.Literal("Clipboard","Command","FileSystem","KeyValueStore","Path","Stream","Terminal");ts=class ts extends Gr.TaggedError("@effect/platform/Error/BadArgument")("BadArgument",{module:dq,method:Gr.String,description:Gr.optional(Gr.String),cause:Gr.optional(Gr.Defect)}){[hT]=hT;get message(){return`${this.module}.${this.method}${this.description?`: ${this.description}`:""}`}};cne=Gr.Literal("AlreadyExists","BadResource","Busy","InvalidData","NotFound","PermissionDenied","TimedOut","UnexpectedEof","Unknown","WouldBlock","WriteZero");Wf=class Wf extends Gr.TaggedError("@effect/platform/Error/SystemError")("SystemError",{reason:cne,module:dq,method:Gr.String,description:Gr.optional(Gr.String),syscall:Gr.optional(Gr.String),pathOrDescriptor:Gr.optional(Gr.Union(Gr.String,Gr.Number)),cause:Gr.optional(Gr.Defect)}){[hT]=hT;get message(){return`${this.reason}: ${this.module}.${this.method}${this.pathOrDescriptor!==void 0?` (${this.pathOrDescriptor})`:""}${this.description?`: ${this.description}`:""}`}}});var $O=Si(function($z){Object.defineProperty($z,"__esModule",{value:!0});$z.Dependable=$z.DependencyGroup=void 0;var Lz=Symbol.for("jsii.rtti");class Bz{static[Lz]={fqn:"constructs.DependencyGroup",version:"10.8.1"};_deps=[];constructor(...e){let t=this;SI.implement(this,{get dependencyRoots(){let r=[];for(let n of t._deps)r.push(...SI.of(n).dependencyRoots);return r}}),this.add(...e)}add(...e){this._deps.push(...e)}}$z.DependencyGroup=Bz;var Mz=Symbol.for("@aws-cdk/core.DependableTrait");class SI{static[Lz]={fqn:"constructs.Dependable",version:"10.8.1"};static implement(e,t){e[Mz]=t}static of(e){let t=e[Mz];if(!t)throw Error(`${e} does not implement IDependable. Use "Dependable.implement()" to implement`);return t}static get(e){return this.of(e)}}$z.Dependable=SI});var jz=Si(function(rc){var fue=rc&&rc.__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]}),mue=rc&&rc.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),yue=rc&&rc.__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")fue(r,t,n[o])}return mue(r,t),r}}();Object.defineProperty(rc,"__esModule",{value:!0});rc.ADDR_SEP=void 0;rc.addressOf=Sue;var hue=yue(sne("crypto")),gue="Default";rc.ADDR_SEP=`
|
|
4
|
+
`;function Sue(e){let t=hue.createHash("sha1");for(let r of e){if(r===gue)continue;t.update(r),t.update(rc.ADDR_SEP)}return"c8"+t.digest("hex")}});var Vz=Si(function(Wz){Object.defineProperty(Wz,"__esModule",{value:!0});Wz.captureStackTrace=Hz;function Hz(e){e=e||Hz;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(`
|
|
5
|
+
`).slice(1).map((n)=>n.replace(/^\s*at\s+/,""))}});var Zz=Si(function(Yz){Object.defineProperty(Yz,"__esModule",{value:!0});Yz.RootConstruct=Yz.ConstructOrder=Yz.Construct=Yz.Node=void 0;var qO=Symbol.for("jsii.rtti"),Kz=$O(),Gz=jz(),xue=Vz(),Qz=Symbol.for("constructs.Construct");class zx{host;static[qO]={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=zz(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}${zx.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=Gz.addressOf(this._scopes.map((e)=>e.node.id));return this._addr}tryFindChild(e){return this._children?.[zz(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=Vx.PREORDER){let t=[];return r(this.host),t;function r(n){if(e===Vx.PREORDER)t.push(n);for(let o of n.node.children)r(o);if(e===Vx.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?xue.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 Kz.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}}Yz.Node=zx;class vI{static[qO]={fqn:"constructs.Construct",version:"10.8.1"};static isConstruct(e){return e&&typeof e==="object"&&e[Qz]}node;constructor(e,t){this.node=new zx(this,e,t),Kz.Dependable.implement(this,{dependencyRoots:[this]})}with(...e){return this.node.with(...e)}toString(){return this.node.path||"<root>"}}Yz.Construct=vI;var Vx;(function(e){e[e.PREORDER=0]="PREORDER",e[e.POSTORDER=1]="POSTORDER"})(Vx||(Yz.ConstructOrder=Vx={}));var Eue=new RegExp(`[${zx.PATH_SEP}${Gz.ADDR_SEP}]`,"g");function zz(e){return e.replace(Eue,"--")}Object.defineProperty(vI.prototype,Qz,{value:!0,enumerable:!1,writable:!1});class Jz extends vI{static[qO]={fqn:"constructs.RootConstruct",version:"10.8.1"};constructor(e){super(void 0,e??"")}}Yz.RootConstruct=Jz});var wi=Si(function(Tp){var Aue=Tp&&Tp.__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]}),eK=Tp&&Tp.__exportStar||function(e,t){for(var r in e)if(r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r))Aue(t,e,r)};Object.defineProperty(Tp,"__esModule",{value:!0});eK(Zz(),Tp);eK($O(),Tp)});var ng=Si(function(xI,VO){Object.defineProperty(xI,"__esModule",{value:!0});xI.default=Rue;function Rue(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))}VO.exports=xI.default;VO.exports.default=xI.default});var KO=Si(function(EI,zO){Object.defineProperty(EI,"__esModule",{value:!0});EI.default=_ue;function Cue(e){return Object.prototype.toString.call(e)==="[object RegExp]"}function _ue(e,t){for(var r=0;r<t.length;r++){var n=t[r];if(e===n||Cue(n)&&n.test(e))return!0}return!1}zO.exports=EI.default;zO.exports.default=EI.default});var nK=Si(function(bI,GO){Object.defineProperty(bI,"__esModule",{value:!0});bI.default=void 0;var Due=function(t,r){return t.indexOf(r)!==-1},hVe=bI.default=Due;GO.exports=bI.default;GO.exports.default=bI.default});var TI=Si(function(wI,JO){Object.defineProperty(wI,"__esModule",{value:!0});wI.default=Oue;function QO(e){return QO=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},QO(e)}function Oue(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;if(QO(e)!=="object"||e===null)e={};for(var r in t)if(typeof e[r]>"u")e[r]=t[r];return e}JO.exports=wI.default;JO.exports.default=wI.default});var XO=Si(function(AI,YO){Object.defineProperty(AI,"__esModule",{value:!0});AI.default=Lue;var Fue=oK(ng()),Uue=oK(TI());function oK(e){return e&&e.__esModule?e:{default:e}}var Mue={require_tld:!0,allow_underscores:!1,allow_trailing_dot:!1,allow_numeric_tld:!1,allow_wildcard:!1,ignore_max_length:!1};function Lue(e,t){if((0,Fue.default)(e),t=(0,Uue.default)(t,Mue),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})}YO.exports=AI.default;YO.exports.default=AI.default});var rN=Si(function(II,tN){Object.defineProperty(II,"__esModule",{value:!0});II.default=eN;var $ue=que(ng());function que(e){return e&&e.__esModule?e:{default:e}}function ZO(e){return ZO=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},ZO(e)}var iK="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",Ap="(".concat(iK,"[.]){3}").concat(iK),jue=new RegExp("^".concat(Ap,"$")),wo="(?:[0-9a-fA-F]{1,4})",Hue=new RegExp("^("+"(?:".concat(wo,":){7}(?:").concat(wo,"|:)|")+"(?:".concat(wo,":){6}(?:").concat(Ap,"|:").concat(wo,"|:)|")+"(?:".concat(wo,":){5}(?::").concat(Ap,"|(:").concat(wo,"){1,2}|:)|")+"(?:".concat(wo,":){4}(?:(:").concat(wo,"){0,1}:").concat(Ap,"|(:").concat(wo,"){1,3}|:)|")+"(?:".concat(wo,":){3}(?:(:").concat(wo,"){0,2}:").concat(Ap,"|(:").concat(wo,"){1,4}|:)|")+"(?:".concat(wo,":){2}(?:(:").concat(wo,"){0,3}:").concat(Ap,"|(:").concat(wo,"){1,5}|:)|")+"(?:".concat(wo,":){1}(?:(:").concat(wo,"){0,4}:").concat(Ap,"|(:").concat(wo,"){1,6}|:)|")+"(?::((?::".concat(wo,"){0,5}:").concat(Ap,"|(?::").concat(wo,"){1,7}|:))")+")(%[0-9a-zA-Z.]{1,})?$");function eN(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};(0,$ue.default)(e);var r=(ZO(t)==="object"?t.version:arguments[1])||"";if(!r)return eN(e,{version:4})||eN(e,{version:6});if(r.toString()==="4")return jue.test(e);if(r.toString()==="6")return Hue.test(e);return!1}tN.exports=II.default;tN.exports.default=II.default});var lK=Si(function(RI,oN){Object.defineProperty(RI,"__esModule",{value:!0});RI.default=tpe;var Vue=og(ng()),sK=og(KO()),nN=og(nK()),zue=og(XO()),aK=og(rN()),Kue=og(TI());function og(e){return e&&e.__esModule?e:{default:e}}function Gue(e,t){return Xue(e)||Yue(e,t)||Jue(e,t)||Que()}function Que(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
6
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Jue(e,t){if(e){if(typeof e=="string")return cK(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)?cK(e,t):void 0}}function cK(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 Yue(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 Xue(e){if(Array.isArray(e))return e}var Zue={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},epe=/^\[([^\]]+)\](?::([0-9]+))?$/;function tpe(e,t){if((0,Vue.default)(e),!e||/[\s<>]/.test(e))return!1;if(e.indexOf("mailto:")===0)return!1;if(t=(0,Kue.default)(t,Zue),t.validate_length&&e.length>t.max_allowed_length)return!1;if(!t.allow_fragments&&(0,nN.default)(e,"#"))return!1;if(!t.allow_query_components&&((0,nN.default)(e,"?")||(0,nN.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,p=function(le){if(u=!0,r=le.toLowerCase(),t.require_valid_protocol&&t.protocols.indexOf(r)===-1)return!1;return e.substring(d[0].length)};if(d){var y=d[1],g=e.substring(d[0].length),E=g.slice(0,2)==="//";if(!E){var S=g.indexOf("/"),x=S===-1?g:g.substring(0,S),w=x.indexOf("@");if(w!==-1){var _=x.substring(0,w),T=/^[a-zA-Z0-9\-_.%:]*$/,b=T.test(_),I=/%[0-9a-fA-F]{2}/.test(_);if(b&&!I){if(t.require_protocol)return!1}else if(e=p(y),e===!1)return!1}else{var O=/^[0-9]/.test(g);if(O){if(t.require_protocol)return!1}else if(e=p(y),e===!1)return!1}}else if(e=p(y),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 L=n.split(":"),Y=Gue(L,2),Z=Y[0],ee=Y[1];if(Z===""&&ee==="")return!1}i=c.join("@"),a=null,l=null;var ae=i.match(epe);if(ae)o="",l=ae[1],a=ae[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,sK.default)(o,t.host_whitelist);if(o===""&&!t.require_host)return!0;if(!(0,aK.default)(o)&&!(0,zue.default)(o,t)&&(!l||!(0,aK.default)(l,6)))return!1;if(o=o||l,t.host_blacklist&&(0,sK.default)(o,t.host_blacklist))return!1;return!0}oN.exports=RI.default;oN.exports.default=RI.default});var hK=Si(function(kI,dN){Object.defineProperty(kI,"__esModule",{value:!0});kI.default=mpe;var ppe=fpe(ng());function fpe(e){return e&&e.__esModule?e:{default:e}}function lN(e){return lN=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},lN(e)}function mpe(e,t){(0,ppe.default)(e);var r,n;if(lN(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)}dN.exports=kI.default;dN.exports.default=kI.default});var vK=Si(function(DI,pN){Object.defineProperty(DI,"__esModule",{value:!0});DI.default=Ppe;var hpe=ag(ng()),gK=ag(KO()),uN=ag(hK()),gpe=ag(XO()),SK=ag(rN()),Spe=ag(TI());function ag(e){return e&&e.__esModule?e:{default:e}}var vpe={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:[]},xpe=/^([^\x00-\x1F\x7F-\x9F\cX]+)</i,Epe=/^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~]+$/i,bpe=/^[a-z\d]+$/,wpe=/^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f]))*$/i,Tpe=/^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\u00A1-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+$/i,Ape=/^([\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,Ipe=254;function Rpe(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 Ppe(e,t){if((0,hpe.default)(e),t=(0,Spe.default)(t,vpe),t.require_display_name||t.allow_display_name){var r=e.match(xpe);if(r){var n=r[1];if(e=e.replace(n,"").replace(/(^<|>$)/g,""),n.endsWith(" "))n=n.slice(0,-1);if(!Rpe(n))return!1}else if(t.require_display_name)return!1}if(!t.ignore_max_length&&e.length>Ipe)return!1;var o=e.split("@"),i=o.pop(),s=i.toLowerCase();if(t.host_blacklist.length>0&&(0,gK.default)(s,t.host_blacklist))return!1;if(t.host_whitelist.length>0&&!(0,gK.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,uN.default)(c.replace(/\./g,""),{min:6,max:30}))return!1;var l=c.split(".");for(var d=0;d<l.length;d++)if(!bpe.test(l[d]))return!1}if(t.ignore_max_length===!1&&(!(0,uN.default)(a,{max:64})||!(0,uN.default)(i,{max:254})))return!1;if(!(0,gpe.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,SK.default)(i)){if(!i.startsWith("[")||!i.endsWith("]"))return!1;var u=i.slice(1,-1);if(u.length===0||!(0,SK.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?Ape.test(a):wpe.test(a);var p=t.allow_utf8_local_part?Tpe:Epe,y=a.split(".");for(var g=0;g<y.length;g++)if(!p.test(y[g]))return!1;return!0}pN.exports=DI.default;pN.exports.default=DI.default});import*as o5 from"effect/Context";import*as Ca from"effect/Effect";import*as i5 from"effect/Exit";import*as s5 from"effect/FiberHandle";import{dual as IYe}from"effect/Function";import*as a5 from"effect/Hash";import*as c5 from"effect/Layer";import*as xR from"effect/Mailbox";import*as l5 from"effect/Scope";import*as d5 from"effect/Stream";function hF(e){return typeof e==="string"?e:a5.hash(e)}var gE,Vxe,ER,u5=(e,t)=>{let r=Array(t.length);for(let n=0;n<t.length;n++)r[n]=`${e}:${hF(t[n])}`;return r},zxe=(e)=>{let t=[];for(let r in e){t.push(r);for(let n of u5(r,e[r]))t.push(n)}return t};var bR=vi(()=>{gE=class gE extends o5.Tag("@effect/experimental/Reactivity")(){};Vxe=Ca.sync(()=>{let e=new Map,t=(a)=>{if(Array.isArray(a))for(let c=0;c<a.length;c++){let l=e.get(hF(a[c]));if(l===void 0)continue;for(let d of l)d()}else{let c=a;for(let l in c){let d=u5(l,c[l]);for(let p=0;p<d.length;p++){let y=e.get(d[p]);if(y===void 0)continue;for(let g of y)g()}let u=e.get(l);if(u!==void 0)for(let p of u)p()}}},r=(a)=>Ca.sync(()=>t(a)),n=(a,c)=>Ca.zipLeft(c,r(a)),o=(a,c)=>{let l=Array.isArray(a)?a.map(hF):zxe(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)=>Ca.gen(function*(){let l=yield*Ca.scope,d=yield*xR.make(),u=yield*s5.makeRuntime(),p=!1,y=!1,g=(x)=>{if(x._tag==="Failure")d.unsafeDone(i5.failCause(x.cause));else d.unsafeOffer(x.value);if(y)y=!1,u(c).addObserver(g);else p=!1};function E(){if(p){y=!0;return}p=!0,u(c).addObserver(g)}let S=o(a,E);return yield*l5.addFinalizer(l,Ca.sync(S)),E(),d}),s=(a,c)=>i(a,c).pipe(Ca.map(xR.toStream),d5.unwrapScoped);return gE.of({mutation:n,query:i,stream:s,unsafeInvalidate:t,invalidate:r,unsafeRegister:o})}),ER=c5.scoped(gE,Vxe)});import*as hs from"effect/Effect";import*as S5 from"effect/Effectable";import*as v5 from"effect/FiberRef";import{dual as PYe,identity as x5}from"effect/Function";import{globalValue as E5}from"effect/GlobalValue";import*as Kxe from"effect/Layer";import*as xF from"effect/Option";import*as Gxe from"effect/Predicate";import*as b5 from"effect/Stream";class dc{value;params;_tag="Literal";constructor(e,t){this.value=e,this.params=t}}class TR{value;_tag="Identifier";constructor(e){this.value=e}}class T5{value;_tag="Parameter";constructor(e){this.value=e}}class wR{value;_tag="ArrayHelper";constructor(e){this.value=e}}function wF(e){return typeof e==="string"?e:(vE in e)?e:new kp([e])}class AR{value;returningIdentifier;_tag="RecordInsertHelper";constructor(e,t){this.value=e,this.returningIdentifier=t}returning(e){return new AR(this.value,wF(e))}}class IR{value;alias;returningIdentifier;_tag="RecordUpdateHelper";constructor(e,t,r){this.value=e,this.alias=t,this.returningIdentifier=r}returning(e){return new IR(this.value,this.alias,wF(e))}}class RR{value;omit;returningIdentifier;_tag="RecordUpdateHelperSingle";constructor(e,t,r){this.value=e,this.omit=t,this.returningIdentifier=r}returning(e){return new RR(this.value,this.omit,wF(e))}}function SF(e){if(typeof e==="string")return[new dc(e)];return e.segments}function Yxe(){if(arguments.length===1)return new wR(arguments[0]);let e=arguments[0],t=arguments[1];return t.length===0?PR("1=0"):new kp([new TR(e),new dc(" IN "),new wR(t)])}function xE(e,t=!0,r=""){let n=new dc(e);return(o)=>{if(o.length===0)return PR(r);else if(o.length===1)return new kp(SF(o[0]));let i=[];if(t)i.push(new dc("("));i.push.apply(i,SF(o[0]));for(let s=1;s<o.length;s++)i.push(n),i.push.apply(i,SF(o[s]));if(t)i.push(new dc(")"));return new kp(i)}}class AF{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?Zxe:Xxe;if(n in e)return e[n];let o=e.segments,i=o.length,s="",a=[],c=0,l=r??((y)=>this.parameterPlaceholder(++c,y)),d=(y)=>this.parameterPlaceholder(c,y),u=eEe(l);for(let y=0;y<i;y++){let g=o[y];switch(g._tag){case"Literal":{if(s+=g.value,g.params)a.push.apply(a,g.params);break}case"Identifier":{s+=this.onIdentifier(g.value,t);break}case"Parameter":{s+=l(g.value),a.push(g.value);break}case"ArrayHelper":{s+=`(${u(g.value)})`,a.push.apply(a,g.value);break}case"RecordInsertHelper":{let E=Object.keys(g.value[0]);if(this.onInsert){let S=Array(g.value.length),x="";for(let T=0;T<g.value.length;T++){let b=Array(E.length);S[T]=b,x+=T===0?"(":",(";for(let I=0;I<E.length;I++){let O=E[I],L=g.value[T][O],Y=SE(L,this.onCustom,d,t);b[I]=Y,x+=I===0?l(L):`,${l(L)}`}x+=")"}let[w,_]=this.onInsert(E.map((T)=>this.onIdentifier(T,t)),x,S,typeof g.returningIdentifier==="string"?[g.returningIdentifier,[]]:g.returningIdentifier?this.compile(g.returningIdentifier,t,l):void 0);s+=w,a.push.apply(a,_)}else{let S="";for(let x=0;x<g.value.length;x++){S+=x===0?"(":",(";for(let w=0;w<E.length;w++){let _=g.value[x][E[w]],T=SE(_,this.onCustom,d,t);a.push(T),S+=w===0?l(_):`,${l(_)}`}S+=")"}if(s+=`${g5(E,this.onIdentifier,t)} VALUES ${S}`,typeof g.returningIdentifier==="string")s+=` RETURNING ${g.returningIdentifier}`;else if(g.returningIdentifier){s+=" RETURNING ";let[x,w]=this.compile(g.returningIdentifier,t,l);s+=x,a.push.apply(a,w)}}break}case"RecordUpdateHelperSingle":{let E=Object.keys(g.value);if(g.omit.length>0)E=E.filter((S)=>!g.omit.includes(S));if(this.onRecordUpdateSingle){let[S,x]=this.onRecordUpdateSingle(E.map((w)=>this.onIdentifier(w,t)),E.map((w)=>SE(g.value[w],this.onCustom,d,t)),typeof g.returningIdentifier==="string"?[g.returningIdentifier,[]]:g.returningIdentifier?this.compile(g.returningIdentifier,t,l):void 0);s+=S,a.push.apply(a,x)}else{for(let S=0,x=E.length;S<x;S++){let w=this.onIdentifier(E[S],t);if(S===0)s+=`${w} = ${l(g.value[E[S]])}`;else s+=`, ${w} = ${l(g.value[E[S]])}`;a.push(SE(g.value[E[S]],this.onCustom,d,t))}if(typeof g.returningIdentifier==="string")if(this.dialect==="mssql")s+=` OUTPUT ${g.returningIdentifier==="*"?"INSERTED.*":g.returningIdentifier}`;else s+=` RETURNING ${g.returningIdentifier}`;else if(g.returningIdentifier){s+=this.dialect==="mssql"?" OUTPUT ":" RETURNING ";let[S,x]=this.compile(g.returningIdentifier,t,l);s+=S,a.push.apply(a,x)}}break}case"RecordUpdateHelper":{let E=Object.keys(g.value[0]),S=Array(g.value.length),x="";for(let T=0;T<g.value.length;T++){let b=Array(E.length);S[T]=b,x+=T===0?"(":",(";for(let I=0;I<E.length;I++){let O=E[I],L=g.value[T][O];b[I]=SE(L,this.onCustom,d,t),x+=I===0?l(L):`,${l(L)}`}x+=")"}let[w,_]=this.onRecordUpdate(x,g.alias,g5(E,this.onIdentifier,t),S,typeof g.returningIdentifier==="string"?[g.returningIdentifier,[]]:g.returningIdentifier?this.compile(g.returningIdentifier,t,l):void 0);s+=w,a.push.apply(a,_);break}case"Custom":{let[E,S]=this.onCustom(g,l,t);s+=E,a.push.apply(a,S);break}}}let p=[s,a];if(r!==void 0)return p;return e[n]=p}get withoutTransform(){return new AF(this.dialect,this.parameterPlaceholder,this.onIdentifier,this.onRecordUpdate,this.onCustom,this.onInsert,this.onRecordUpdateSingle,!0)}}function C5(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 p5="db.operation.name",f5="db.query.text",vE,EF=(e)=>typeof e==="object"&&e!==null&&(vE in e),w5,m5=(e,t,r)=>hs.withFiberRuntime((n)=>{let o=n.getFiberRef(w5);if(o._tag==="None")return r(e);return hs.flatMap(o.value(e,TF(e.acquirer,e.compiler,e.spanAttributes,e.transformRows),n.getFiberRefs(),t),r)}),bF,kp,Qxe=(e)=>e instanceof wR||e instanceof AR||e instanceof IR||e instanceof RR||e instanceof TR,y5,TF=(e,t,r,n)=>{let o=n===void 0?y5.noTransforms:y5.transforms;if(o.has(e))return o.get(e);let i=Object.assign(function(a,...c){if(Array.isArray(a)&&"raw"in a)return Jxe(e,t,a,c,r,n);else if(typeof a==="string")return new TR(a);throw"absurd"},{unsafe(s,a){return new bF([new dc(s,a)],e,t,r,n)},literal(s){return new kp([new dc(s)])},in:Yxe,insert(s){return new AR(Array.isArray(s)?s:[s],void 0)},update(s,a){return new RR(s,a??[],void 0)},updateValues(s,a){return new IR(s,a,void 0)},and:A5,or:I5,csv:R5,join:xE,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},Jxe=(e,t,r,n,o,i)=>{let s=r[0].length>0?[new dc(r[0])]:[];for(let a=0;a<n.length;a++){let c=n[a];if(EF(c))for(let l of c.segments)s.push(l);else if(Qxe(c))s.push(c);else s.push(new T5(c));if(r[a+1].length>0)s.push(new dc(r[a+1]))}return new bF(s,e,t,o,i)},PR=(e,t)=>new kp([new dc(e,t)]),A5,I5,h5,R5=(...e)=>{if(e[e.length-1].length===0)return PR("");if(e.length===1)return h5(e[0]);return new kp([new dc(`${e[0]} `),...h5(e[1]).segments])},Xxe,Zxe,P5=(e)=>new AF(e.dialect,e.placeholder,e.onIdentifier,e.onRecordUpdate,e.onCustom,e.onInsert,e.onRecordUpdateSingle),eEe=(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},g5=(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+")"},SE=(e,t,r,n)=>{if(e===void 0)return null;else if(EF(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},vF,_5=(e)=>P5({dialect:"sqlite",placeholder(t){return"?"},onIdentifier:e?function(t,r){return r?vF(t):vF(e(t))}:vF,onRecordUpdate(){return["",[]]},onCustom(){return["",[]]}});var k5=vi(()=>{vE=Symbol.for("@effect/sql/Fragment"),w5=E5("@effect/sql/Statement/currentTransformer",()=>v5.unsafeMake(xF.none()));bF=class bF extends S5.Class{segments;acquirer;compiler;spanAttributes;transformRows;get[vE](){return x5}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 hs.useSpan("sql.execute",{kind:"client",captureStackTrace:!1},(n)=>m5(this,n,(o)=>{let[i,s]=o.compile(r);for(let[a,c]of this.spanAttributes)n.attribute(a,c);return n.attribute(p5,e),n.attribute(f5,i),hs.scoped(hs.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 b5.unwrapScoped(hs.flatMap(hs.makeSpanScoped("sql.execute",{kind:"client",captureStackTrace:!1}),(e)=>m5(this,e,(t)=>{let[r,n]=t.compile();for(let[o,i]of this.spanAttributes)e.attribute(o,i);return e.attribute(p5,"executeStream"),e.attribute(f5,r),hs.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}}};kp=class kp{segments;get[vE](){return x5}constructor(e){this.segments=e}};y5=E5("@effect/sql/Statement/constructorCache",()=>({transforms:new WeakMap,noTransforms:new WeakMap}));A5=xE(" AND ",!0,"1=1"),I5=xE(" OR ",!0,"1=1"),h5=xE(", ",!1),Xxe=Symbol.for("@effect/sql/Statement/statementCache"),Zxe=Symbol.for("@effect/sql/Statement/statementCacheNoTransform");vF=C5('"')});var IF,CR;var _R=vi(()=>{k5();IF=TF,CR=_5});import*as D5 from"effect/Clock";import*as Vl from"effect/Context";import*as lr from"effect/Effect";import*as O5 from"effect/Exit";import*as N5 from"effect/FiberRef";import*as F5 from"effect/Mailbox";import*as U5 from"effect/Option";import*as Rg from"effect/Scope";import*as M5 from"effect/Stream";import*as L5 from"effect/Tracer";function $5({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 lr.gen(function*(){let u=lr.flatMap(lr.serviceOption(CF),U5.match({onNone:()=>e,onSome:([E])=>lr.succeed(E)}));l=l??e;let p=_F({transactionTag:CF,spanAttributes:c,acquireConnection:lr.flatMap(Rg.make(),(E)=>lr.map(Rg.extend(l,E),(S)=>[E,S])),begin:(E)=>E.executeUnprepared(t,[],void 0),savepoint:(E,S)=>E.executeUnprepared(a(`effect_sql_${S}`),[],void 0),commit:(E)=>E.executeUnprepared(r,[],void 0),rollback:(E)=>E.executeUnprepared(i,[],void 0),rollbackSavepoint:(E,S)=>E.executeUnprepared(s(`effect_sql_${S}`),[],void 0)}),y=yield*gE,g=Object.assign(IF(u,n,c,d),{[PF]:PF,safe:void 0,withTransaction:p,reserve:l,withoutTransforms(){if(d===void 0)return this;let E=IF(u,n.withoutTransform,c,void 0),S=Object.assign(E,{...this,...E});return S.safe=S,S.withoutTransforms=()=>S,S},reactive:o?(E,S)=>o(E,S).pipe(lr.map(F5.toStream),M5.unwrapScoped):y.stream,reactiveMailbox:o??y.query});return g.safe=g,g})}var PF,B5,CF,_F=(e)=>(t)=>lr.uninterruptibleMask((r)=>lr.useSpan("sql.transaction",{kind:"client",captureStackTrace:!1},(n)=>lr.withFiberRuntime((o)=>{for(let[d,u]of e.spanAttributes)n.attribute(d,u);let i=o.currentContext,s=Vl.get(o.currentDefaultServices,D5.Clock),a=Vl.getOption(i,e.transactionTag),c=a._tag==="Some"?lr.succeed([void 0,a.value[0]]):e.acquireConnection,l=a._tag==="Some"?a.value[1]+1:0;return lr.flatMap(c,([d,u])=>(l===0?e.begin(u):e.savepoint(u,l)).pipe(lr.zipRight(lr.locally(r(t),N5.currentContext,Vl.add(i,e.transactionTag,[u,l]).pipe(Vl.add(L5.ParentSpan,n)))),lr.exit,lr.flatMap((p)=>{let y;if(O5.isSuccess(p))if(l===0)n.event("db.transaction.commit",s.unsafeCurrentTimeNanos()),y=lr.orDie(e.commit(u));else n.event("db.transaction.savepoint",s.unsafeCurrentTimeNanos()),y=lr.void;else n.event("db.transaction.rollback",s.unsafeCurrentTimeNanos()),y=lr.orDie(l>0?e.rollbackSavepoint(u,l):e.rollback(u));let g=d!==void 0?lr.ensuring(y,Rg.close(d,p)):y;return lr.zipRight(g,p)})))})));var q5=vi(()=>{bR();_R();PF=Symbol.for("@effect/sql/SqlClient"),B5=Vl.GenericTag("@effect/sql/SqlClient"),CF=Vl.GenericTag("@effect/sql/SqlClient/TransactionConnection")});import*as nEe from"effect/Context";var Hs,kR,DR;var Pg=vi(()=>{q5();Hs=B5,kR=$5,DR=_F});var h3=Si(function(tit,rC){var j8,H8,W8,V8,z8,K8,G8,Q8,J8,Y8,X8,Z8,e3,eC,IM,t3,r3,n3,fS,o3,i3,s3,a3,c3,l3,d3,u3,p3,tC,f3,m3,y3;(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 rC==="object"&&typeof tit==="object")e(r(t,r(tit)));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]};j8=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)},H8=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},W8=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},V8=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 p=i.length-1;p>=0;p--)if(u=i[p])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},z8=function(i,s){return function(a,c){s(a,c,i)}},K8=function(i,s,a,c,l,d){function u(I){if(I!==void 0&&typeof I!=="function")throw TypeError("Function expected");return I}var p=c.kind,y=p==="getter"?"get":p==="setter"?"set":"value",g=!s&&i?c.static?i:i.prototype:null,E=s||(g?Object.getOwnPropertyDescriptor(g,c.name):{}),S,x=!1;for(var w=a.length-1;w>=0;w--){var _={};for(var T in c)_[T]=T==="access"?{}:c[T];for(var T in c.access)_.access[T]=c.access[T];_.addInitializer=function(I){if(x)throw TypeError("Cannot add initializers after decoration has completed");d.push(u(I||null))};var b=(0,a[w])(p==="accessor"?{get:E.get,set:E.set}:E[y],_);if(p==="accessor"){if(b===void 0)continue;if(b===null||typeof b!=="object")throw TypeError("Object expected");if(S=u(b.get))E.get=S;if(S=u(b.set))E.set=S;if(S=u(b.init))l.unshift(S)}else if(S=u(b))if(p==="field")l.unshift(S);else E[y]=S}if(g)Object.defineProperty(g,c.name,E);x=!0},G8=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},Q8=function(i){return typeof i==="symbol"?i:"".concat(i)},J8=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})},Y8=function(i,s){if(typeof Reflect==="object"&&typeof Reflect.metadata==="function")return Reflect.metadata(i,s)},X8=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 p(E){try{g(c.next(E))}catch(S){u(S)}}function y(E){try{g(c.throw(E))}catch(S){u(S)}}function g(E){E.done?d(E.value):l(E.value).then(p,y)}g((c=c.apply(i,s||[])).next())})},Z8=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=p(0),u.throw=p(1),u.return=p(2),typeof Symbol==="function"&&(u[Symbol.iterator]=function(){return this}),u;function p(g){return function(E){return y([g,E])}}function y(g){if(c)throw TypeError("Generator is already executing.");while(u&&(u=0,g[0]&&(a=0)),a)try{if(c=1,l&&(d=g[0]&2?l.return:g[0]?l.throw||((d=l.return)&&d.call(l),0):l.next)&&!(d=d.call(l,g[1])).done)return d;if(l=0,d)g=[g[0]&2,d.value];switch(g[0]){case 0:case 1:d=g;break;case 4:return a.label++,{value:g[1],done:!1};case 5:a.label++,l=g[1],g=[0];continue;case 7:g=a.ops.pop(),a.trys.pop();continue;default:if((d=a.trys,!(d=d.length>0&&d[d.length-1]))&&(g[0]===6||g[0]===2)){a=0;continue}if(g[0]===3&&(!d||g[1]>d[0]&&g[1]<d[3])){a.label=g[1];break}if(g[0]===6&&a.label<d[1]){a.label=d[1],d=g;break}if(d&&a.label<d[2]){a.label=d[2],a.ops.push(g);break}if(d[2])a.ops.pop();a.trys.pop();continue}g=s.call(i,a)}catch(E){g=[6,E],l=0}finally{c=d=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},e3=function(i,s){for(var a in i)if(a!=="default"&&!Object.prototype.hasOwnProperty.call(s,a))tC(s,i,a)},tC=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]},eC=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.")},IM=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(p){u={error:p}}finally{try{if(l&&!l.done&&(a=c.return))a.call(c)}finally{if(u)throw u.error}}return d},t3=function(){for(var i=[],s=0;s<arguments.length;s++)i=i.concat(IM(arguments[s]));return i},r3=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,p=d.length;u<p;u++,l++)c[l]=d[u];return c},n3=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))},fS=function(i){return this instanceof fS?(this.v=i,this):new fS(i)},o3=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),p("next"),p("throw"),p("return",u),l[Symbol.asyncIterator]=function(){return this},l;function u(w){return function(_){return Promise.resolve(_).then(w,S)}}function p(w,_){if(c[w]){if(l[w]=function(T){return new Promise(function(b,I){d.push([w,T,b,I])>1||y(w,T)})},_)l[w]=_(l[w])}}function y(w,_){try{g(c[w](_))}catch(T){x(d[0][3],T)}}function g(w){w.value instanceof fS?Promise.resolve(w.value.v).then(E,S):x(d[0][2],w)}function E(w){y("next",w)}function S(w){y("throw",w)}function x(w,_){if(w(_),d.shift(),d.length)y(d[0][0],d[0][1])}},i3=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:fS(i[l](u)),done:!1}:d?d(u):u}:d}},s3=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 eC==="function"?eC(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(p,y){u=i[d](u),l(p,y,u.done,u.value)})}}function l(d,u,p,y){Promise.resolve(y).then(function(g){d({value:g,done:p})},u)}},a3=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)};c3=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")tC(s,i,a[c])}return r(s,i),s},l3=function(i){return i&&i.__esModule?i:{default:i}},d3=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)},u3=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},p3=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)},f3=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};m3=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()},y3=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",j8),e("__assign",H8),e("__rest",W8),e("__decorate",V8),e("__param",z8),e("__esDecorate",K8),e("__runInitializers",G8),e("__propKey",Q8),e("__setFunctionName",J8),e("__metadata",Y8),e("__awaiter",X8),e("__generator",Z8),e("__exportStar",e3),e("__createBinding",tC),e("__values",eC),e("__read",IM),e("__spread",t3),e("__spreadArrays",r3),e("__spreadArray",n3),e("__await",fS),e("__asyncGenerator",o3),e("__asyncDelegator",i3),e("__asyncValues",s3),e("__makeTemplateObject",a3),e("__importStar",c3),e("__importDefault",l3),e("__classPrivateFieldGet",d3),e("__classPrivateFieldSet",u3),e("__classPrivateFieldIn",p3),e("__addDisposableResource",f3),e("__disposeResources",m3),e("__rewriteRelativeImportExtension",y3)})});var F3=Si(function(){/*! *****************************************************************************
|
|
7
|
+
Copyright (C) Microsoft. All rights reserved.
|
|
8
|
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
|
9
|
+
this file except in compliance with the License. You may obtain a copy of the
|
|
10
|
+
License at http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
|
|
12
|
+
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
13
|
+
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
|
14
|
+
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
|
15
|
+
MERCHANTABLITY OR NON-INFRINGEMENT.
|
|
16
|
+
|
|
17
|
+
See the Apache Version 2.0 License for specific language governing permissions
|
|
18
|
+
and limitations under the License.
|
|
19
|
+
***************************************************************************** */var N3;(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 mn(Object.create(null))}:c?function(){return mn({__proto__:null})}:function(){return mn({})},has:l?function(U,V){return n.call(U,V)}:function(U,V){return V in U},get:l?function(U,V){return n.call(U,V)?U[V]:void 0}:function(U,V){return U[V]}},u=Object.getPrototypeOf(Function),p=typeof Map==="function"&&typeof Map.prototype.entries==="function"?Map:yT(),y=typeof Set==="function"&&typeof Set.prototype.entries==="function"?Set:ge(),g=typeof WeakMap==="function"?WeakMap:pr(),E=o?Symbol.for("@reflect-metadata:registry"):void 0,S=$v(),x=_k(S);function w(U,V,re,pe){if(!be(re)){if(!ur(U))throw TypeError();if(!Xe(V))throw TypeError();if(!Xe(pe)&&!be(pe)&&!Sr(pe))throw TypeError();if(Sr(pe))pe=void 0;return re=Qo(re),ne(U,V,re,pe)}else{if(!ur(U))throw TypeError();if(!So(V))throw TypeError();return ae(U,V)}}t("decorate",w);function _(U,V){function re(pe,Ze){if(!Xe(pe))throw TypeError();if(!be(Ze)&&!Ps(Ze))throw TypeError();yt(U,V,pe,Ze)}return re}t("metadata",_);function T(U,V,re,pe){if(!Xe(re))throw TypeError();if(!be(pe))pe=Qo(pe);return yt(U,V,re,pe)}t("defineMetadata",T);function b(U,V,re){if(!Xe(V))throw TypeError();if(!be(re))re=Qo(re);return le(U,V,re)}t("hasMetadata",b);function I(U,V,re){if(!Xe(V))throw TypeError();if(!be(re))re=Qo(re);return ie(U,V,re)}t("hasOwnMetadata",I);function O(U,V,re){if(!Xe(V))throw TypeError();if(!be(re))re=Qo(re);return je(U,V,re)}t("getMetadata",O);function L(U,V,re){if(!Xe(V))throw TypeError();if(!be(re))re=Qo(re);return ft(U,V,re)}t("getOwnMetadata",L);function Y(U,V){if(!Xe(U))throw TypeError();if(!be(V))V=Qo(V);return Ut(U,V)}t("getMetadataKeys",Y);function Z(U,V){if(!Xe(U))throw TypeError();if(!be(V))V=Qo(V);return _t(U,V)}t("getOwnMetadataKeys",Z);function ee(U,V,re){if(!Xe(V))throw TypeError();if(!be(re))re=Qo(re);if(!Xe(V))throw TypeError();if(!be(re))re=Qo(re);var pe=Rd(V,re,!1);if(be(pe))return!1;return pe.OrdinaryDeleteMetadata(U,V,re)}t("deleteMetadata",ee);function ae(U,V){for(var re=U.length-1;re>=0;--re){var pe=U[re],Ze=pe(V);if(!be(Ze)&&!Sr(Ze)){if(!So(Ze))throw TypeError();V=Ze}}return V}function ne(U,V,re,pe){for(var Ze=U.length-1;Ze>=0;--Ze){var oo=U[Ze],Lo=oo(V,re,pe);if(!be(Lo)&&!Sr(Lo)){if(!Xe(Lo))throw TypeError();pe=Lo}}return pe}function le(U,V,re){var pe=ie(U,V,re);if(pe)return!0;var Ze=mT(V);if(!Sr(Ze))return le(U,Ze,re);return!1}function ie(U,V,re){var pe=Rd(V,re,!1);if(be(pe))return!1;return Ni(pe.OrdinaryHasOwnMetadata(U,V,re))}function je(U,V,re){var pe=ie(U,V,re);if(pe)return ft(U,V,re);var Ze=mT(V);if(!Sr(Ze))return je(U,Ze,re);return}function ft(U,V,re){var pe=Rd(V,re,!1);if(be(pe))return;return pe.OrdinaryGetOwnMetadata(U,V,re)}function yt(U,V,re,pe){var Ze=Rd(re,pe,!0);Ze.OrdinaryDefineOwnMetadata(U,V,re,pe)}function Ut(U,V){var re=_t(U,V),pe=mT(U);if(pe===null)return re;var Ze=Ut(pe,V);if(Ze.length<=0)return re;if(re.length<=0)return Ze;var oo=new y,Lo=[];for(var Qt=0,Oe=re;Qt<Oe.length;Qt++){var $e=Oe[Qt],He=oo.has($e);if(!He)oo.add($e),Lo.push($e)}for(var Ge=0,tr=Ze;Ge<tr.length;Ge++){var $e=tr[Ge],He=oo.has($e);if(!He)oo.add($e),Lo.push($e)}return Lo}function _t(U,V){var re=Rd(U,V,!1);if(!re)return[];return re.OrdinaryOwnMetadataKeys(U,V)}function nt(U){if(U===null)return 1;switch(typeof U){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return U===null?1:6;default:return 6}}function be(U){return U===void 0}function Sr(U){return U===null}function no(U){return typeof U==="symbol"}function Xe(U){return typeof U==="object"?U!==null:typeof U==="function"}function _n(U,V){switch(nt(U)){case 0:return U;case 1:return U;case 2:return U;case 3:return U;case 4:return U;case 5:return U}var re=V===3?"string":V===5?"number":"default",pe=gi(U,i);if(pe!==void 0){var Ze=pe.call(U,re);if(Xe(Ze))throw TypeError();return Ze}return Mo(U,re==="default"?"number":re)}function Mo(U,V){if(V==="string"){var re=U.toString;if(Rr(re)){var pe=re.call(U);if(!Xe(pe))return pe}var Ze=U.valueOf;if(Rr(Ze)){var pe=Ze.call(U);if(!Xe(pe))return pe}}else{var Ze=U.valueOf;if(Rr(Ze)){var pe=Ze.call(U);if(!Xe(pe))return pe}var oo=U.toString;if(Rr(oo)){var pe=oo.call(U);if(!Xe(pe))return pe}}throw TypeError()}function Ni(U){return!!U}function Tr(U){return""+U}function Qo(U){var V=_n(U,3);if(no(V))return V;return Tr(V)}function ur(U){return Array.isArray?Array.isArray(U):U instanceof Object?U instanceof Array:Object.prototype.toString.call(U)==="[object Array]"}function Rr(U){return typeof U==="function"}function So(U){return typeof U==="function"}function Ps(U){switch(nt(U)){case 3:return!0;case 4:return!0;default:return!1}}function Nc(U,V){return U===V||U!==U&&V!==V}function gi(U,V){var re=U[V];if(re===void 0||re===null)return;if(!Rr(re))throw TypeError();return re}function Hu(U){var V=gi(U,s);if(!Rr(V))throw TypeError();var re=V.call(U);if(!Xe(re))throw TypeError();return re}function vo(U){return U.value}function Zy(U){var V=U.next();return V.done?!1:V}function Ck(U){var V=U.return;if(V)V.call(U)}function mT(U){var V=Object.getPrototypeOf(U);if(typeof U!=="function"||U===u)return V;if(V!==u)return V;var re=U.prototype,pe=re&&Object.getPrototypeOf(re);if(pe==null||pe===Object.prototype)return V;var Ze=pe.constructor;if(typeof Ze!=="function")return V;if(Ze===U)return V;return Ze}function Bv(){var U;if(!be(E)&&typeof r.Reflect<"u"&&!(E in r.Reflect)&&typeof r.Reflect.defineMetadata==="function")U=kk(r.Reflect);var V,re,pe,Ze=new g,oo={registerProvider:Lo,getProvider:Oe,setProvider:He};return oo;function Lo(Ge){if(!Object.isExtensible(oo))throw Error("Cannot add provider to a frozen registry.");switch(!0){case U===Ge:break;case be(V):V=Ge;break;case V===Ge:break;case be(re):re=Ge;break;case re===Ge:break;default:if(pe===void 0)pe=new y;pe.add(Ge);break}}function Qt(Ge,tr){if(!be(V)){if(V.isProviderFor(Ge,tr))return V;if(!be(re)){if(re.isProviderFor(Ge,tr))return V;if(!be(pe)){var rn=Hu(pe);while(!0){var io=Zy(rn);if(!io)return;var Fc=vo(io);if(Fc.isProviderFor(Ge,tr))return Ck(rn),Fc}}}}if(!be(U)&&U.isProviderFor(Ge,tr))return U;return}function Oe(Ge,tr){var rn=Ze.get(Ge),io;if(!be(rn))io=rn.get(tr);if(!be(io))return io;if(io=Qt(Ge,tr),!be(io)){if(be(rn))rn=new p,Ze.set(Ge,rn);rn.set(tr,io)}return io}function $e(Ge){if(be(Ge))throw TypeError();return V===Ge||re===Ge||!be(pe)&&pe.has(Ge)}function He(Ge,tr,rn){if(!$e(rn))throw Error("Metadata provider not registered.");var io=Oe(Ge,tr);if(io!==rn){if(!be(io))return!1;var Fc=Ze.get(Ge);if(be(Fc))Fc=new p,Ze.set(Ge,Fc);Fc.set(tr,rn)}return!0}}function $v(){var U;if(!be(E)&&Xe(r.Reflect)&&Object.isExtensible(r.Reflect))U=r.Reflect[E];if(be(U))U=Bv();if(!be(E)&&Xe(r.Reflect)&&Object.isExtensible(r.Reflect))Object.defineProperty(r.Reflect,E,{enumerable:!1,configurable:!1,writable:!1,value:U});return U}function _k(U){var V=new g,re={isProviderFor:function($e,He){var Ge=V.get($e);if(be(Ge))return!1;return Ge.has(He)},OrdinaryDefineOwnMetadata:Lo,OrdinaryHasOwnMetadata:Ze,OrdinaryGetOwnMetadata:oo,OrdinaryOwnMetadataKeys:Qt,OrdinaryDeleteMetadata:Oe};return S.registerProvider(re),re;function pe($e,He,Ge){var tr=V.get($e),rn=!1;if(be(tr)){if(!Ge)return;tr=new p,V.set($e,tr),rn=!0}var io=tr.get(He);if(be(io)){if(!Ge)return;if(io=new p,tr.set(He,io),!U.setProvider($e,He,re)){if(tr.delete(He),rn)V.delete($e);throw Error("Wrong provider for target.")}}return io}function Ze($e,He,Ge){var tr=pe(He,Ge,!1);if(be(tr))return!1;return Ni(tr.has($e))}function oo($e,He,Ge){var tr=pe(He,Ge,!1);if(be(tr))return;return tr.get($e)}function Lo($e,He,Ge,tr){var rn=pe(Ge,tr,!0);rn.set($e,He)}function Qt($e,He){var Ge=[],tr=pe($e,He,!1);if(be(tr))return Ge;var rn=tr.keys(),io=Hu(rn),Fc=0;while(!0){var sq=Zy(io);if(!sq)return Ge.length=Fc,Ge;var Jre=vo(sq);try{Ge[Fc]=Jre}catch(Yre){try{Ck(io)}finally{throw Yre}}Fc++}}function Oe($e,He,Ge){var tr=pe(He,Ge,!1);if(be(tr))return!1;if(!tr.delete($e))return!1;if(tr.size===0){var rn=V.get(He);if(!be(rn)){if(rn.delete(Ge),rn.size===0)V.delete(rn)}}return!0}}function kk(U){var{defineMetadata:V,hasOwnMetadata:re,getOwnMetadata:pe,getOwnMetadataKeys:Ze,deleteMetadata:oo}=U,Lo=new g,Qt={isProviderFor:function(Oe,$e){var He=Lo.get(Oe);if(!be(He)&&He.has($e))return!0;if(Ze(Oe,$e).length){if(be(He))He=new y,Lo.set(Oe,He);return He.add($e),!0}return!1},OrdinaryDefineOwnMetadata:V,OrdinaryHasOwnMetadata:re,OrdinaryGetOwnMetadata:pe,OrdinaryOwnMetadataKeys:Ze,OrdinaryDeleteMetadata:oo};return Qt}function Rd(U,V,re){var pe=S.getProvider(U,V);if(!be(pe))return pe;if(re){if(S.setProvider(U,V,x))return x;throw Error("Illegal state.")}return}function yT(){var U={},V=[],re=function(){function Qt(Oe,$e,He){this._index=0,this._keys=Oe,this._values=$e,this._selector=He}return Qt.prototype["@@iterator"]=function(){return this},Qt.prototype[s]=function(){return this},Qt.prototype.next=function(){var Oe=this._index;if(Oe>=0&&Oe<this._keys.length){var $e=this._selector(this._keys[Oe],this._values[Oe]);if(Oe+1>=this._keys.length)this._index=-1,this._keys=V,this._values=V;else this._index++;return{value:$e,done:!1}}return{value:void 0,done:!0}},Qt.prototype.throw=function(Oe){if(this._index>=0)this._index=-1,this._keys=V,this._values=V;throw Oe},Qt.prototype.return=function(Oe){if(this._index>=0)this._index=-1,this._keys=V,this._values=V;return{value:Oe,done:!0}},Qt}(),pe=function(){function Qt(){this._keys=[],this._values=[],this._cacheKey=U,this._cacheIndex=-2}return Object.defineProperty(Qt.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),Qt.prototype.has=function(Oe){return this._find(Oe,!1)>=0},Qt.prototype.get=function(Oe){var $e=this._find(Oe,!1);return $e>=0?this._values[$e]:void 0},Qt.prototype.set=function(Oe,$e){var He=this._find(Oe,!0);return this._values[He]=$e,this},Qt.prototype.delete=function(Oe){var $e=this._find(Oe,!1);if($e>=0){var He=this._keys.length;for(var Ge=$e+1;Ge<He;Ge++)this._keys[Ge-1]=this._keys[Ge],this._values[Ge-1]=this._values[Ge];if(this._keys.length--,this._values.length--,Nc(Oe,this._cacheKey))this._cacheKey=U,this._cacheIndex=-2;return!0}return!1},Qt.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=U,this._cacheIndex=-2},Qt.prototype.keys=function(){return new re(this._keys,this._values,Ze)},Qt.prototype.values=function(){return new re(this._keys,this._values,oo)},Qt.prototype.entries=function(){return new re(this._keys,this._values,Lo)},Qt.prototype["@@iterator"]=function(){return this.entries()},Qt.prototype[s]=function(){return this.entries()},Qt.prototype._find=function(Oe,$e){if(!Nc(this._cacheKey,Oe)){this._cacheIndex=-1;for(var He=0;He<this._keys.length;He++)if(Nc(this._keys[He],Oe)){this._cacheIndex=He;break}}if(this._cacheIndex<0&&$e)this._cacheIndex=this._keys.length,this._keys.push(Oe),this._values.push(void 0);return this._cacheIndex},Qt}();return pe;function Ze(Qt,Oe){return Qt}function oo(Qt,Oe){return Oe}function Lo(Qt,Oe){return[Qt,Oe]}}function ge(){var U=function(){function V(){this._map=new p}return Object.defineProperty(V.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),V.prototype.has=function(re){return this._map.has(re)},V.prototype.add=function(re){return this._map.set(re,re),this},V.prototype.delete=function(re){return this._map.delete(re)},V.prototype.clear=function(){this._map.clear()},V.prototype.keys=function(){return this._map.keys()},V.prototype.values=function(){return this._map.keys()},V.prototype.entries=function(){return this._map.entries()},V.prototype["@@iterator"]=function(){return this.keys()},V.prototype[s]=function(){return this.keys()},V}();return U}function pr(){var U=16,V=d.create(),re=pe();return function(){function Oe(){this._key=pe()}return Oe.prototype.has=function($e){var He=Ze($e,!1);return He!==void 0?d.has(He,this._key):!1},Oe.prototype.get=function($e){var He=Ze($e,!1);return He!==void 0?d.get(He,this._key):void 0},Oe.prototype.set=function($e,He){var Ge=Ze($e,!0);return Ge[this._key]=He,this},Oe.prototype.delete=function($e){var He=Ze($e,!1);return He!==void 0?delete He[this._key]:!1},Oe.prototype.clear=function(){this._key=pe()},Oe}();function pe(){var Oe;do Oe="@@WeakMap@@"+Qt();while(d.has(V,Oe));return V[Oe]=!0,Oe}function Ze(Oe,$e){if(!n.call(Oe,re)){if(!$e)return;Object.defineProperty(Oe,re,{value:d.create()})}return Oe[re]}function oo(Oe,$e){for(var He=0;He<$e;++He)Oe[He]=Math.random()*255|0;return Oe}function Lo(Oe){if(typeof Uint8Array==="function"){var $e=new Uint8Array(Oe);if(typeof crypto<"u")crypto.getRandomValues($e);else if(typeof msCrypto<"u")msCrypto.getRandomValues($e);else oo($e,Oe);return $e}return oo(Array(Oe),Oe)}function Qt(){var Oe=Lo(U);Oe[6]=Oe[6]&79|64,Oe[8]=Oe[8]&191|128;var $e="";for(var He=0;He<U;++He){var Ge=Oe[He];if(He===4||He===6||He===8)$e+="-";if(Ge<16)$e+="0";$e+=Ge.toString(16).toLowerCase()}return $e}}function mn(U){return U.__=void 0,delete U.__,U}})})(N3||(N3={}))});var wY=Si(function(cht,MC){/*! *****************************************************************************
|
|
20
|
+
Copyright (c) Microsoft Corporation.
|
|
21
|
+
|
|
22
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
23
|
+
purpose with or without fee is hereby granted.
|
|
24
|
+
|
|
25
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
26
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
27
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
28
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
29
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
30
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
31
|
+
PERFORMANCE OF THIS SOFTWARE.
|
|
32
|
+
***************************************************************************** */var nY,oY,iY,sY,aY,cY,lY,dY,uY,UC,RL,pY,fY,$S,mY,yY,hY,gY,SY,vY,xY,EY,bY;(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 MC==="object"&&typeof cht==="object")e(r(t,r(cht)));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]};nY=function(r,n){t(r,n);function o(){this.constructor=r}r.prototype=n===null?Object.create(n):(o.prototype=n.prototype,new o)},oY=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},iY=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},sY=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},aY=function(r,n){return function(o,i){n(o,i,r)}},cY=function(r,n){if(typeof Reflect==="object"&&typeof Reflect.metadata==="function")return Reflect.metadata(r,n)},lY=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(p){try{u(i.next(p))}catch(y){c(y)}}function d(p){try{u(i.throw(p))}catch(y){c(y)}}function u(p){p.done?a(p.value):s(p.value).then(l,d)}u((i=i.apply(r,n||[])).next())})},dY=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(p){return d([u,p])}}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(p){u=[6,p],s=0}finally{i=a=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}},bY=function(r,n,o,i){if(i===void 0)i=o;r[i]=n[o]},uY=function(r,n){for(var o in r)if(o!=="default"&&!n.hasOwnProperty(o))n[o]=r[o]},UC=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.")},RL=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},pY=function(){for(var r=[],n=0;n<arguments.length;n++)r=r.concat(RL(arguments[n]));return r},fY=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},$S=function(r){return this instanceof $S?(this.v=r,this):new $S(r)},mY=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(g){if(i[g])s[g]=function(E){return new Promise(function(S,x){a.push([g,E,S,x])>1||l(g,E)})}}function l(g,E){try{d(i[g](E))}catch(S){y(a[0][3],S)}}function d(g){g.value instanceof $S?Promise.resolve(g.value.v).then(u,p):y(a[0][2],g)}function u(g){l("next",g)}function p(g){l("throw",g)}function y(g,E){if(g(E),a.shift(),a.length)l(a[0][0],a[0][1])}},yY=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:$S(r[s](c)),done:s==="return"}:a?a(c):c}:a}},hY=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 UC==="function"?UC(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)}},gY=function(r,n){if(Object.defineProperty)Object.defineProperty(r,"raw",{value:n});else r.raw=n;return r},SY=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},vY=function(r){return r&&r.__esModule?r:{default:r}},xY=function(r,n){if(!n.has(r))throw TypeError("attempted to get private field on non-instance");return n.get(r)},EY=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",nY),e("__assign",oY),e("__rest",iY),e("__decorate",sY),e("__param",aY),e("__metadata",cY),e("__awaiter",lY),e("__generator",dY),e("__exportStar",uY),e("__createBinding",bY),e("__values",UC),e("__read",RL),e("__spread",pY),e("__spreadArrays",fY),e("__await",$S),e("__asyncGenerator",mY),e("__asyncDelegator",yY),e("__asyncValues",hY),e("__makeTemplateObject",gY),e("__importStar",SY),e("__importDefault",vY),e("__classPrivateFieldGet",xY),e("__classPrivateFieldSet",EY)})});import*as WB from"effect/Effect";import*as dv from"effect/FiberRef";var n_,VB,o_,pIe;var JX=vi(()=>{n_=dv.unsafeMake(!1),VB=dv.unsafeMake(void 0),o_=dv.unsafeMake("immediate"),pIe=dv.get(o_)});import{Context as fIe}from"effect";var uv;var YX=vi(()=>{uv=class uv extends fIe.Tag("processfocus:internal-tag/db-info/DatabaseConnectionInfo")(){}});var Sf=(e)=>/^[a-z]+:/.test(e)?e:`file://${e}`,vf=(e)=>{let t=e.match(/^([a-z]+):/)?.[1];return t===void 0||t==="file"};var KB=5000;import{join as XX,resolve as ZX}from"path";import*as Ry from"effect/Config";import*as pv from"effect/ConfigProvider";import*as e7 from"effect/Layer";var As=(e)=>{let t=process.env.SQLITE_DATABASE_PATH;if(t)return t;let r=e??process.env.PF_ORG;if(!r)return;return XX(ZX(r),"db","pf.db")},Py,Is="Database path not configured. Set SQLITE_DATABASE_PATH or PF_ORG environment variable.",Fu=(e)=>e7.setConfigProvider(pv.fromMap(new Map([["SQLITE_DATABASE_PATH",e]])).pipe(pv.orElse(()=>pv.fromEnv())));var t7=vi(()=>{Py=Ry.string("SQLITE_DATABASE_PATH").pipe(Ry.orElse(()=>Ry.string("PF_ORG").pipe(Ry.map((e)=>XX(ZX(e),"db","pf.db")))))});var mIe,yIe,r7,hIe=(e)=>typeof e==="object"&&e!==null,Sd=(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(hIe(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},gIe=(e)=>r7.test(e)||mIe.some((t)=>e.toLowerCase().includes(t)),SIe=(e)=>{let t=e.toUpperCase();return yIe.some((r)=>t===r||t.includes(r))},Cy=(e)=>Sd(e,gIe,{codePredicate:SIe}),GB=(e)=>Sd(e,(t)=>r7.test(t));var n7=vi(()=>{mIe=["sqlite_busy","sqlite_locked","database is locked"],yIe=["SQLITE_BUSY","SQLITE_LOCKED"],r7=/write[- ]write\s+conflict|concurrent\s+write\s+conflict/iu});var Ki=vi(()=>{JX();YX();t7();n7()});var SCe,ia;var Hw=vi(()=>{El();SCe=Symbol.for("@effect/sql/SqlError");ia=class ia extends eh(SCe,"SqlError"){}});var Ite=(e)=>{if(e.startsWith("file://"))return e.slice(7);if(e.startsWith("file:"))return e.slice(5);return e};var q$=vi(()=>{Ki()});import{mkdirSync as FDe}from"fs";import{dirname as UDe}from"path";import*as _te from"effect/Cause";import*as kte from"effect/Config";import*as ak from"effect/Context";import*as Ct from"effect/Effect";import*as Dte from"effect/Exit";import*as Lf from"effect/Layer";import*as Ote from"effect/Option";import*as Dv from"effect/Scope";import*as Nte from"effect/Stream";var MDe="db.system.name",LDe,Rte,BDe=(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)},$De=(e)=>{if(e===":memory:")return;let t=UDe(e);if(t!==""&&t!==".")FDe(t,{recursive:!0})},Pte=(e,t)=>Ct.tryPromise({try:async()=>{$De(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 ia({cause:r,message:"Failed to open database"})}),Cte=(e)=>Ct.tryPromise({try:()=>e.close(),catch:(t)=>t}).pipe(Ct.catchAll((t)=>Ct.logWarning("Failed to close Turso connection",_te.fail(t)))),qDe=(e,t)=>Ct.gen(function*(){let r=CR(),n=[[MDe,"sqlite"]],o=yield*Pte(e,t);yield*Ct.addFinalizer(()=>Cte(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:(p)=>new ia({cause:p,message:"Failed to execute statement"})})}runValuesDirect(d,u){return Ct.tryPromise({try:async()=>(await this.db.all(d,[...u])).map((p)=>BDe(p)),catch:(p)=>new ia({cause:p,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,p){return p?Ct.map(this.run(d,u),p):this.run(d,u)}executeRaw(d,u){return this.runRaw(d,u)}executeValues(d,u){return this.runValues(d,u)}executeUnprepared(d,u,p){return this.execute(d,u,p)}executeStream(){return Nte.fail(new ia({message:"executeStream not implemented for Turso"}))}beginTransactionBody=Ct.fn("TursoConnection.beginTransaction")(function*(){let d=yield*Pte(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 Cte(this.db)}}let s=new i(o,!0),a=yield*Ct.makeSemaphore(1),c=DR({transactionTag:Rte,spanAttributes:n,acquireConnection:Ct.uninterruptibleMask((d)=>Dv.make().pipe(Ct.flatMap((u)=>d(s.beginTransaction).pipe(Ct.tap((p)=>Dv.addFinalizer(u,p.close)),Ct.map((p)=>[u,p]),Ct.tapError(()=>Dv.close(u,Dte.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(Rte),Ote.match({onNone:()=>a.withPermits(1)(Ct.succeed(s)),onSome:([d])=>Ct.succeed(d)}));return Object.assign(yield*kR({acquirer:l,compiler:r,spanAttributes:n}),{withTransaction:c})}),jDe=(e)=>Lf.scopedContext(Ct.gen(function*(){let t=yield*Py,r=Sf(t),n=yield*qDe(Ite(r),e);return ak.make(Hs,n)})).pipe(Lf.provide(ER)),j$=(e)=>jDe(e).pipe(Lf.provideMerge(LDe)),W5t;var Fte=vi(()=>{bR();Pg();Hw();_R();Ki();q$();LDe=Lf.effect(uv,Py.pipe(kte.map(Sf))),Rte=ak.GenericTag("processfocus:internal-tag/layer-turso-local/TursoTransaction"),W5t=j$()});var Ute=vi(()=>{Fte();q$()});import{Session as Mte}from"@tursodatabase/serverless";import*as qte from"effect/Cause";import*as qa from"effect/Config";import*as Bf from"effect/Context";import*as ye from"effect/Effect";import*as jte from"effect/Exit";import*as Nv from"effect/FiberRef";import*as $f from"effect/Layer";import*as Hte from"effect/Option";import*as lk from"effect/Redacted";import*as qf from"effect/Schedule";import*as dk from"effect/Scope";import*as Wte from"effect/Stream";var HDe="db.system.name",WDe=5,Lte,ck=(e)=>Cy(e)&&!GB(e),VDe,zDe,KDe,Bte,Vte,GDe=(e)=>e.rows.map((t)=>Object.fromEntries(e.columns.map((r,n)=>[r,t[n]]))),QDe=(e)=>e.rows,$te=(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}},H$=(e)=>{if(e instanceof Error){let t=e.code,r=typeof t==="string"?` ${t}`:"",n=e.cause?`; caused by ${H$(e.cause)}`:"";return`${e.name}${r}: ${e.message}${n}`}return String(e)},JDe="Turso blocked SQL reads; a database organization plan limit may be responsible - check Turso usage and plan settings",YDe=(e)=>Sd(e,(t)=>t.includes("SQL read operations are forbidden")||t.includes("reads are blocked")),Ov=(e,t)=>new ia({cause:Error(`${e}: ${H$(t)}`,{cause:t}),message:YDe(t)?`${e} (${JDe})`:e}),XDe=(e)=>Sd(e,(t)=>t.includes("HTTP error! status: 404")),ZDe=(e)=>ye.tryPromise({try:()=>e.session.close(),catch:(t)=>t}).pipe(ye.catchAll((t)=>ye.logWarning("Failed to close Turso connection",qte.fail(t)))),sT=(e)=>e.semaphore.withPermits(1)(ZDe(e)),e0e=(e,t,r,n)=>ye.gen(function*(){let o=CR(),i=[[HDe,"sqlite"]],s=n?.refreshAuthToken,a=(S)=>ye.map(ye.makeSemaphore(1),(x)=>S?{session:new Mte({url:e,authToken:lk.value(S)}),semaphore:x}:{session:new Mte({url:e}),semaphore:x}),c=(S,x)=>{if(S===void 0||x===void 0)return S===x;return lk.value(S)===lk.value(x)},l=t,d=yield*ye.acquireRelease(ye.map(a(l),(S)=>({current:S})),(S)=>sT(S.current));class u{sdk;runPragmas;closeSdkAfterTransaction;pragmasExecuted=!1;sdkClosed=!1;constructor(S,x,w){this.sdk=S;this.runPragmas=x;this.closeSdkAfterTransaction=w}withStatementSdk(S,x="Failed to execute statement"){return this.withStatementSdkEffect((w)=>ye.tryPromise({try:()=>S(w),catch:(_)=>Ov(x,_)}))}withStatementSdkEffect(S){return ye.suspend(()=>{let x=this.sdk??d.current;return x.semaphore.withPermits(1)(S(x.session))})}closeTransactionSdk(){if(!this.sdk||!this.closeSdkAfterTransaction||this.sdkClosed)return ye.void;return this.sdkClosed=!0,sT(this.sdk)}refreshSdkOnTokenChange(){if(this.sdk||!this.runPragmas||!s)return ye.succeed(!1);return ye.gen(this,function*(){let S=yield*s;if(c(l,S))return!1;let x=d.current;return d.current=yield*a(S),l=S,this.pragmasExecuted=!1,yield*sT(x),!0})}recreateSdk(){if(this.sdk||!this.runPragmas)return ye.void;return ye.gen(this,function*(){let S=d.current;d.current=yield*a(l),this.pragmasExecuted=!1,yield*sT(S)})}runWithTokenRefresh(S){let x=this.retryTursoLock(S);return x.pipe(ye.catchAll((w)=>ye.gen(this,function*(){if(yield*this.refreshSdkOnTokenChange())return yield*x;if(XDe(w.cause))return yield*this.recreateSdk(),yield*x;return yield*ye.fail(w)})))}retryTursoLock(S,x=Cy){return S.pipe(ye.retry({schedule:Lte,while:x}))}ensurePragmas(){if(this.pragmasExecuted||!this.runPragmas)return ye.void;return ye.gen(this,function*(){yield*this.runDirect("PRAGMA foreign_keys = ON",[]),this.pragmasExecuted=!0})}runDirect(S,x){return ye.gen(this,function*(){let w=yield*this.withStatementSdk((_)=>_.execute(S,Array.from(x)));return GDe($te(w))})}run=ye.fn("TursoCloudConnection.run")(function*(S,x=[]){return yield*this.runWithTokenRefresh(ye.gen(this,function*(){return yield*this.ensurePragmas(),yield*this.runDirect(S,x)}))});runRaw=ye.fn("TursoCloudConnection.runRaw")(function*(S,x=[]){return yield*this.runWithTokenRefresh(ye.gen(this,function*(){return yield*this.ensurePragmas(),yield*this.withStatementSdk((w)=>w.execute(S,Array.from(x)).then($te))}))});runBatch=ye.fn("TursoCloudConnection.runBatch")(function*(S){if(S.foreignKeys==="enforced"){yield*this.ensurePragmas(),yield*this.retryTursoLock(this.withStatementSdk((x)=>x.batch(Array.from(S.statements),"immediate"),"Failed to execute batch"),ck);return}yield*this.withStatementSdkEffect((x)=>ye.gen(this,function*(){this.pragmasExecuted=!1;let w=yield*this.retryTursoLock(ye.tryPromise({try:async()=>{await x.execute("PRAGMA foreign_keys = OFF",[]),await x.batch(Array.from(S.statements),"immediate")},catch:(T)=>Ov("Failed to execute batch",T)}),ck).pipe(ye.match({onFailure:(T)=>({kind:"failed",cause:T}),onSuccess:()=>({kind:"succeeded"})})),_=yield*this.retryTursoLock(ye.tryPromise({try:()=>x.execute("PRAGMA foreign_keys = ON",[]).then(()=>{return}),catch:(T)=>Ov("Failed to restore foreign keys",T)}),ck).pipe(ye.match({onFailure:(T)=>({kind:"failed",cause:T}),onSuccess:()=>({kind:"succeeded"})}));if(_.kind==="succeeded")this.pragmasExecuted=!0;else if(w.kind==="failed")return yield*ye.fail(new ia({message:"Failed to execute batch",cause:Error(`Failed to restore foreign keys after batch failure: ${H$(_.cause)}`,{cause:w.cause})}));else return yield*ye.fail(_.cause);if(w.kind==="failed")return yield*ye.fail(w.cause)}))});execute(S,x,w){return w?ye.map(this.run(S,x),w):this.run(S,x)}executeRaw(S,x){return this.runRaw(S,x)}executeValues(S,x){return ye.map(this.runRaw(S,x),(w)=>QDe(w).map((_)=>Array.from(_)))}executeUnprepared(S,x,w){return this.execute(S,x,w)}executeStream(){return Wte.fail(new ia({message:"executeStream not implemented for Turso"}))}beginTransactionBody=ye.fn("TursoCloudConnection.beginTransaction")(function*(){return yield*this.runWithTokenRefresh(ye.gen(this,function*(){yield*this.ensurePragmas();let S=yield*a(l),x=yield*Nv.get(n_);return yield*Nv.set(o_,x&&r?"concurrent":"immediate"),yield*ye.tryPromise({try:async()=>{await S.session.execute("PRAGMA foreign_keys = ON",[]),await S.session.sequence(x?r?"BEGIN CONCURRENT":"BEGIN IMMEDIATE":n?.deferredTransactions?"BEGIN DEFERRED":"BEGIN IMMEDIATE")},catch:(w)=>Ov("Failed to begin transaction",w)}).pipe(ye.tapError(()=>sT(S))),new u(S,!1,!0)}))});get beginTransaction(){return this.beginTransactionBody()}commitBody=ye.fn("TursoCloudConnection.commit")(function(){return ye.uninterruptible(ye.tryPromise({try:()=>{if(!this.sdk)return Promise.reject(Error("Transaction connection missing"));return this.sdk.session.sequence("COMMIT")},catch:(S)=>Ov("Failed to commit transaction",S)}).pipe(ye.retry({schedule:Lte,while:ck}),ye.tap(()=>this.closeTransactionSdk())))});get commit(){return this.commitBody()}rollbackBody=ye.fn("TursoCloudConnection.rollback")(function(){return this.retryTursoLock(ye.tryPromise({try:()=>{if(!this.sdk)return Promise.reject(Error("Transaction connection missing"));return this.sdk.session.sequence("ROLLBACK")},catch:(S)=>Ov("Failed to rollback transaction",S)})).pipe(ye.ensuring(this.closeTransactionSdk()))});get rollback(){return this.rollbackBody()}}let p=new u(void 0,!0,!1),y=DR({transactionTag:Bte,spanAttributes:i,acquireConnection:ye.uninterruptibleMask((S)=>dk.make().pipe(ye.flatMap((x)=>S(p.beginTransaction).pipe(ye.map((w)=>[x,w]),ye.tapError(()=>dk.close(x,jte.void)))))),begin:()=>ye.void,savepoint:(S,x)=>S.executeRaw(`SAVEPOINT effect_sql_${x};`,[]),commit:(S)=>S.commit.pipe(ye.catchAll((x)=>S.rollback.pipe(ye.catchAll((w)=>ye.logWarning("Failed to rollback transaction after commit failure").pipe(ye.annotateLogs({rollbackError:w}))),ye.zipRight(Nv.get(n_).pipe(ye.flatMap((w)=>w?Nv.set(VB,x):ye.fail(x))))))),rollback:(S)=>S.rollback,rollbackSavepoint:(S,x)=>S.executeRaw(`ROLLBACK TO SAVEPOINT effect_sql_${x};`,[])}),g=ye.flatMap(ye.serviceOption(Bte),Hte.match({onNone:()=>ye.succeed(p),onSome:([S])=>ye.succeed(S)})),E=Object.assign(yield*kR({acquirer:g,compiler:o,spanAttributes:i}),{withTransaction:y});return{batch:{execute:(S)=>p.runBatch(S)},client:E}}),t0e=(e)=>$f.scopedContext(ye.gen(function*(){let t=yield*Py,r=Sf(t),n=e?.authToken??(yield*VDe),o=yield*zDe,{batch:i,client:s}=yield*e0e(r,n,o,e);return Bf.make(Hs,s).pipe(Bf.add(Vte,i))})).pipe($f.provide(ER)),r0e=(e)=>t0e(e).pipe($f.provideMerge(KDe)),zte;var Kte=vi(()=>{bR();Pg();Hw();_R();Ki();Lte=qf.exponential("100 millis",2).pipe(qf.intersect(qf.recurs(WDe)),qf.jittered),VDe=qa.redacted("TURSO_AUTH_TOKEN").pipe(qa.orElse(()=>qa.succeed(void 0))),zDe=qa.string("TURSO_CONCURRENT_TX").pipe(qa.map((e)=>e==="1"),qa.orElse(()=>qa.succeed(!1))),KDe=$f.effect(uv,Py.pipe(qa.map(Sf))),Bte=Bf.GenericTag("processfocus:internal-tag/layer-turso-cloud/TursoCloudTransaction");Vte=class Vte extends Bf.Tag("processfocus:internal-tag/layer-turso-cloud/TursoCloudBatch")(){};zte=r0e()});var Gte=vi(()=>{Kte()});import*as ar from"effect/Array";import*as m2 from"effect/ConfigError";import*as fx from"effect/Console";import*as We from"effect/Effect";import*as y2 from"effect/Either";import{dual as Ph,pipe as mx}from"effect/Function";import*as h2 from"effect/Inspectable";import*as qr from"effect/Option";import*as g2 from"effect/ParseResult";import{pipeArguments as Cse}from"effect/Pipeable";import*as S2 from"effect/Predicate";import*as Ch from"effect/Ref";var Pd=(e)=>e.replaceAll("'","'\\''");import*as mq from"effect/Brand";import*as yq from"effect/Context";import*as gT from"effect/Data";El();import*as Wu from"effect/Channel";import*as uq from"effect/Chunk";import{GenericTag as lne}from"effect/Context";import*as ao from"effect/Effect";import{identity as dne,pipe as Fk}from"effect/Function";import*as une from"effect/Layer";import*as pq from"effect/Option";import*as Hv from"effect/Sink";import*as Vf from"effect/Stream";var Uk=lne("@effect/platform/FileSystem"),jv=(e)=>typeof e==="bigint"?e:BigInt(e);var qv=BigInt(1024),NFe=qv*qv*qv*qv*qv;var fq=(e)=>Uk.of({...e,exists:(t)=>Fk(e.access(t),ao.as(!0),ao.catchTag("SystemError",(r)=>r.reason==="NotFound"?ao.succeed(!1):ao.fail(r))),readFileString:(t,r)=>ao.tryMap(e.readFile(t),{try:(n)=>new TextDecoder(r).decode(n),catch:(n)=>new ts({module:"FileSystem",method:"readFileString",description:"invalid encoding",cause:n})}),stream:(t,r)=>Fk(e.open(t,{flag:"r"}),r?.offset?ao.tap((n)=>n.seek(r.offset,"start")):dne,ao.map((n)=>pne(n,r)),Vf.unwrapScoped),sink:(t,r)=>Fk(e.open(t,{flag:"w",...r}),ao.map((n)=>Hv.forEach((o)=>n.writeAll(o))),Hv.unwrapScoped),writeFileString:(t,r,n)=>ao.flatMap(ao.try({try:()=>new TextEncoder().encode(r),catch:(o)=>new ts({module:"FileSystem",method:"writeFileString",description:"could not encode string",cause:o})}),(o)=>e.writeFile(t,o,n))});var pne=(e,{bufferSize:t=16,bytesToRead:r,chunkSize:n=jv(65536)}={})=>{let o=r!==void 0?jv(r):void 0,i=jv(n);function s(a){if(o!==void 0&&o<=a)return Wu.void;let c=o!==void 0&&o-a<i?o-a:i;return Wu.flatMap(e.readAlloc(c),pq.match({onNone:()=>Wu.void,onSome:(l)=>Wu.flatMap(Wu.write(uq.of(l)),(d)=>s(a+BigInt(l.length)))}))}return Vf.bufferChunks(Vf.fromChannel(s(BigInt(0))),{capacity:t})};var Vu=jv;var Bo=Uk,hq=fq;var ST=Symbol.for("@effect/platform/FileSystem/File");var gq=mq.nominal(),Sq=gT.tagged("Create"),vq=gT.tagged("Update"),xq=gT.tagged("Remove");class Mk extends yq.Tag("@effect/platform/FileSystem/WatchBackend")(){}import{dual as yne}from"effect/Function";function Eq(e,t){return function(r){if(Array.isArray(r))return r.reduce(t,e);let n=e;for(let o of r)n=t(n,o);return n}}function bq(e){return function(t){if(Array.isArray(t))return t.map(e);return function*(){for(let r of t)yield e(r)}()}}var wq=(e)=>(t)=>{let r=Object.keys(t);return e.imap(e.productAll(r.map((n)=>t[n])),(n)=>{let o={};for(let i=0;i<n.length;i++)o[r[i]]=n[i];return o},(n)=>r.map((o)=>n[o]))};var Cd=(e,t=(r,n)=>Eq(r,e)(n))=>({combine:e,combineMany:t});var hne=(e)=>Cd(()=>e,()=>e);var Tq=()=>Cd((e)=>e,(e)=>e);var gne=yne(3,(e,t,r)=>Cd((n,o)=>t(e.combine(r(n),r(o))),(n,o)=>t(e.combineMany(r(n),bq(r)(o)))));var Sne=(e,t)=>Cd(([r,n],[o,i])=>[e.combine(r,o),t.combine(n,i)]),Aq=(e)=>Cd((t,r)=>{let n=Math.min(t.length,r.length),o=[],i=0;for(let s of e){if(i>=n)break;o.push(s.combine(t[i],r[i])),i++}return o}),vne=(e,t)=>{let r=Aq(t);return Cd((n,o)=>[e.combine(n[0],o[0]),...r.combine(n.slice(1),o.slice(1))])};var xne=hne,Ene={of:xne,imap:gne,product:Sne,productMany:vne,productAll:Aq};var vT=()=>Cd((e,t)=>e.concat(t)),xT=wq(Ene);var Wv=(e,t)=>({combine:e.combine,combineMany:e.combineMany,empty:t,combineAll:(r)=>e.combineMany(t,r)});var Rq=()=>Wv(vT(),[]),Pq=(e)=>{let t={};for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r))t[r]=e[r].empty;return Wv(xT(e),t)};import*as zn from"effect/Array";import{dual as Pne}from"effect/Function";import*as ja from"effect/Option";var Lk={_tag:"Black"},ET={_tag:"Red"},Bk={_tag:"Green"};var $k={_tag:"Magenta"},bT={_tag:"Cyan"},wT={_tag:"White"},th=(e)=>{switch(e._tag){case"Black":return 0;case"Red":return 1;case"Green":return 2;case"Yellow":return 3;case"Blue":return 4;case"Magenta":return 5;case"Cyan":return 6;case"White":return 7}};var Cq={_tag:"Reset"},_q=(e)=>({_tag:"SetBold",bold:e}),jk=(e,t,r)=>({_tag:"SetColor",color:e,vivid:t,layer:r}),kq=(e)=>({_tag:"SetItalicized",italicized:e}),Dq=(e)=>({_tag:"SetStrikethrough",strikethrough:e}),Oq=(e)=>({_tag:"SetUnderlined",underlined:e}),wne=(e)=>{switch(e._tag){case"Reset":return 0;case"SetBold":return e.bold?1:22;case"SetColor":switch(e.layer){case"foreground":return e.vivid?90+th(e.color):30+th(e.color);case"background":return e.vivid?100+th(e.color):40+th(e.color)}case"SetItalicized":return e.italicized?3:23;case"SetStrikethrough":return e.strikethrough?9:29;case"SetUnderlined":return e.underlined?4:24}},Nq=(e)=>Tne("m",e),Tne=(e,t)=>`\x1B[${Array.from(t).map((n)=>`${wne(n)}`).join(";")}${e}`;var Cne="@effect/printer-ansi/Ansi",TT=Symbol.for(Cne),kn=(e)=>({...Uq.empty,...e}),Fq=Tq(),zf=Cd((e,t)=>ja.isSome(e)?e:t),_ne=xT({[TT]:Fq,commands:vT(),foreground:zf,background:zf,bold:zf,italicized:zf,strikethrough:zf,underlined:zf}),kne=Wv(Fq,TT),rh=Wv(zf,ja.none()),Uq=Pq({[TT]:kne,commands:Rq(),foreground:rh,background:rh,bold:rh,italicized:rh,strikethrough:rh,underlined:rh}),Mq=Uq.empty,co="\x1B[",Dne="\x07",One=";",Lq=kn({bold:ja.some(_q(!0))}),Bq=kn({italicized:ja.some(kq(!0))}),$q=kn({strikethrough:ja.some(Dq(!0))}),qq=kn({underlined:ja.some(Oq(!0))}),Hk=(e)=>kn({foreground:ja.some(jk(e,!0,"foreground"))}),Vv=(e)=>kn({foreground:ja.some(jk(e,!1,"foreground"))});var jq=Vv(ET),Hq=Vv(Bk);var Wq=Vv(wT),Vq=Hk(Lk);var zq=Hk(bT);var Wk=kn({commands:zn.of(Dne)}),Vk=(e,t)=>{if(t===void 0){let n=`${co}${Math.max(e+1,0)}G`;return kn({commands:zn.of(n)})}let r=`${co}${t+1}${One}${Math.max(e+1,0)}H`;return kn({commands:zn.of(r)})},zk=(e,t=0)=>{let r="";if(t<0)r+=`${co}${-t}A`;if(t>0)r+=`${co}${t}B`;if(e>0)r+=`${co}${e}C`;if(e<0)r+=`${co}${-e}D`;return kn({commands:zn.of(r)})};var Kk=(e=1)=>{let t=`${co}${e}B`;return kn({commands:zn.of(t)})};var Gk=kn({commands:zn.of(`${co}G`)}),Qk=kn({commands:zn.of(`${co}s`)}),Jk=kn({commands:zn.of(`${co}u`)});var Yk=kn({commands:zn.of(`${co}?25l`)}),Xk=kn({commands:zn.of(`${co}?25h`)}),Zk=(e)=>{let t="";for(let r=0;r<e;r++)t+=`${co}2K`+(r<e-1?`${co}1A`:"");if(e>0)t+=`${co}G`;return kn({commands:zn.of(t)})},Kq=kn({commands:zn.of(`${co}K`)}),Gq=kn({commands:zn.of(`${co}1K`)}),eD=kn({commands:zn.of(`${co}2K`)}),Qq=kn({commands:zn.of(`${co}J`)}),Jq=kn({commands:zn.of(`${co}1J`)}),Yq=kn({commands:zn.of(`${co}2J`)}),AT=(e)=>Fne(e),IT=Pne(2,(e,t)=>Nne(e,t)),Nne=(e,t)=>_ne.combine(e,t),Fne=(e)=>{let t=Nq(zn.getSomes([ja.some(Cq),e.foreground,e.background,e.bold,e.italicized,e.strikethrough,e.underlined])),r=zn.join(e.commands,"");return`${t}${r}`};var Jo=Lq,nh=Bq,Xq=$q,rs=qq,Zq=Vv;var Uc=jq,pa=Hq;var zu=Wq,Nr=Vq;var xo=zq;var Yo=IT;import*as Lc from"effect/Array";import*as os from"effect/Effect";import*as ns from"effect/Equal";import{dual as Bc,pipe as tj}from"effect/Function";import*as rt from"effect/Hash";import{pipeArguments as Vne}from"effect/Pipeable";import*as PT from"effect/Equal";import{dual as qne}from"effect/Function";import*as Fi from"effect/Hash";var RT="@effect/printer/Flatten",ej=Symbol.for(RT),jne={Flattened:(e)=>Fi.combine(Fi.hash(e.value))(Fi.string(RT)),AlreadyFlat:(e)=>Fi.combine(Fi.string("@effect/printer/Flattened/AlreadyFlat"))(Fi.string(RT)),NeverFlat:(e)=>Fi.combine(Fi.string("@effect/printer/Flattened/NeverFlat"))(Fi.string(RT))},Hne={Flattened:(e,t)=>rD(t)&&t._tag==="Flattened"&&PT.equals(e.value,t.value),AlreadyFlat:(e,t)=>rD(t)&&t._tag==="AlreadyFlat",NeverFlat:(e,t)=>rD(t)&&t._tag==="NeverFlat"},nD={[ej]:{_A:(e)=>e},[Fi.symbol](){return Fi.cached(this,jne[this._tag](this))},[PT.symbol](e){return Hne[this._tag](this,e)}},rD=(e)=>typeof e==="object"&&e!=null&&(ej in e),oh=(e)=>e._tag==="Flattened",zv=(e)=>e._tag==="AlreadyFlat",oD=(e)=>e._tag==="NeverFlat",bl=(e)=>(()=>{let t=Object.create(nD);return t._tag="Flattened",t.value=e,t})(),CT=(()=>{let e=Object.create(nD);return e._tag="AlreadyFlat",e})(),_T=(()=>{let e=Object.create(nD);return e._tag="NeverFlat",e})(),iD=qne(2,(e,t)=>{switch(e._tag){case"Flattened":return bl(t(e.value));case"AlreadyFlat":return CT;case"NeverFlat":return _T}});var Cs="@effect/printer/Doc",aD=Symbol.for(Cs),zne={Fail:(e)=>rt.combine(rt.hash(Cs))(rt.hash("@effect/printer/Doc/Fail")),Empty:(e)=>rt.combine(rt.hash(Cs))(rt.hash("@effect/printer/Doc/Empty")),Char:(e)=>rt.combine(rt.hash(Cs))(rt.string(e.char)),Text:(e)=>rt.combine(rt.hash(Cs))(rt.string(e.text)),Line:(e)=>rt.combine(rt.hash(Cs))(rt.hash("@effect/printer/Doc/Line")),FlatAlt:(e)=>rt.combine(rt.hash(Cs))(rt.combine(rt.hash(e.left))(rt.hash(e.right))),Cat:(e)=>rt.combine(rt.hash(Cs))(rt.combine(rt.hash(e.left))(rt.hash(e.right))),Nest:(e)=>rt.combine(rt.hash(Cs))(rt.combine(rt.hash(e.indent))(rt.hash(e.doc))),Union:(e)=>rt.combine(rt.hash(Cs))(rt.combine(rt.hash(e.left))(rt.hash(e.right))),Column:(e)=>rt.combine(rt.hash(Cs))(rt.hash(e.react)),WithPageWidth:(e)=>rt.combine(rt.hash(Cs))(rt.hash(e.react)),Nesting:(e)=>rt.combine(rt.hash(Cs))(rt.hash(e.react)),Annotated:(e)=>rt.combine(rt.hash(Cs))(rt.combine(rt.hash(e.annotation))(rt.hash(e.doc)))},Kne={Fail:(e,t)=>_s(t)&&t._tag==="Fail",Empty:(e,t)=>_s(t)&&t._tag==="Empty",Char:(e,t)=>_s(t)&&t._tag==="Char"&&e.char===t.char,Text:(e,t)=>_s(t)&&t._tag==="Text"&&e.text===t.text,Line:(e,t)=>_s(t)&&t._tag==="Line",FlatAlt:(e,t)=>_s(t)&&t._tag==="FlatAlt"&&ns.equals(t.left)(e.left)&&ns.equals(t.right)(e.right),Cat:(e,t)=>_s(t)&&t._tag==="Cat"&&ns.equals(t.left)(e.left)&&ns.equals(t.right)(e.right),Nest:(e,t)=>_s(t)&&t._tag==="Nest"&&e.indent===t.indent&&ns.equals(t.doc)(e.doc),Union:(e,t)=>_s(t)&&t._tag==="Union"&&ns.equals(t.left)(e.left)&&ns.equals(t.right)(e.right),Column:(e,t)=>_s(t)&&t._tag==="Column"&&ns.equals(t.react)(e.react),WithPageWidth:(e,t)=>_s(t)&&t._tag==="WithPageWidth"&&ns.equals(t.react)(e.react),Nesting:(e,t)=>_s(t)&&t._tag==="Nesting"&&ns.equals(t.react)(e.react),Annotated:(e,t)=>_s(t)&&t._tag==="Annotated"&&ns.equals(t.annotation)(e.annotation)&&ns.equals(t.doc)(e.doc)},fa={[aD]:{_A:(e)=>e},[rt.symbol](){return rt.cached(this,zne[this._tag](this))},[ns.symbol](e){return Kne[this._tag](this,e)},pipe(){return Vne(this,arguments)}},_s=(e)=>typeof e==="object"&&e!=null&&(aD in e);var Gv=(e)=>e._tag==="Empty",Ha=(e)=>e._tag==="Char",Wa=(e)=>e._tag==="Text";var Gu=(e)=>e._tag==="Cat",cD=(e)=>e._tag==="Nest";var Qv=(e)=>{let t=Object.create(fa);return t._tag="Char",t.char=e,t},Qu=(e)=>{let t=Object.create(fa);return t._tag="Text",t.text=e,t},Jv=Bc(2,(e,t)=>{let r=Object.create(fa);return r._tag="FlatAlt",r.left=e,r.right=t,r}),ih=Bc(2,(e,t)=>{let r=Object.create(fa);return r._tag="Union",r.left=e,r.right=t,r}),$o=Bc(2,(e,t)=>{let r=Object.create(fa);return r._tag="Cat",r.left=e,r.right=t,r}),Yv=(()=>{let e=Object.create(fa);return e._tag="Empty",e})(),rj=(()=>{let e=Object.create(fa);return e._tag="Fail",e})(),DT=(()=>{let e=Object.create(fa);return e._tag="Line",e})(),nj=Jv(DT,Qv(" ")),oj=Jv(DT,Yv);var lD=Qv(" ");var ij=(e)=>pj(lj(e)),sj=Bc(2,(e,t)=>$o(e,$o(nj,t))),aj=Bc(2,(e,t)=>$o(e,$o(oj,t)));var cj=Bc(2,(e,t)=>$o(e,$o(lD,t))),OT=Bc(2,(e,t)=>Lc.matchRight(Lc.fromIterable(e),{onEmpty:()=>Yv,onNonEmpty:(r,n)=>Lc.reduceRight(r,n,(o,i)=>t(i,o))})),lj=(e)=>OT(e,(t,r)=>aj(t,r));var dj=(e)=>OT(e,(t,r)=>cj(t,r)),uj=(e)=>OT(e,(t,r)=>sj(t,r));var pj=(e)=>{switch(e._tag){case"FlatAlt":{let t=sD(e.right);switch(t._tag){case"Flattened":return ih(t.value,e.left);case"AlreadyFlat":return ih(e.right,e.left);case"NeverFlat":return e.left}}case"Union":return e;default:{let t=sD(e);return oh(t)?ih(t.value,e):e}}},sh=(e)=>{let t=Object.create(fa);return t._tag="Column",t.react=e,t},ah=(e)=>{let t=Object.create(fa);return t._tag="Nesting",t.react=e,t};var Xv=(e)=>{let t=Object.create(fa);return t._tag="WithPageWidth",t.react=e,t},_d=Bc(2,(e,t)=>t===0?e:(()=>{let r=Object.create(fa);return r._tag="Nest",r.indent=t,r.doc=e,r})()),dD=(e)=>sh((t)=>ah((r)=>_d(e,t-r))),fj=Bc(2,(e,t)=>dD(_d(e,t))),mj=Bc(2,(e,t)=>fj($o(yj(t),e),t));var kT=(e)=>os.runSync(Mc(e)),Mc=(e)=>os.gen(function*(){switch(e._tag){case"Fail":return e;case"Empty":return e;case"Char":return e;case"Text":return e;case"Line":return rj;case"FlatAlt":return yield*Mc(e.right);case"Cat":{let t=yield*Mc(e.left),r=yield*Mc(e.right);return $o(t,r)}case"Nest":{let t=yield*Mc(e.doc);return _d(t,e.indent)}case"Union":return yield*Mc(e.left);case"Column":return sh((t)=>kT(e.react(t)));case"WithPageWidth":return Xv((t)=>kT(e.react(t)));case"Nesting":return ah((t)=>kT(e.react(t)));case"Annotated":{let t=yield*Mc(e.doc);return ch(t,e.annotation)}}}),sD=(e)=>os.runSync(Kv(e)),Kv=(e)=>os.gen(function*(){switch(e._tag){case"Fail":case"Line":return _T;case"Empty":case"Char":case"Text":return CT;case"FlatAlt":{let t=yield*Mc(e.right);return bl(t)}case"Cat":{let t=yield*Kv(e.left),r=yield*Kv(e.right);if(oD(t)||oD(r))return _T;if(oh(t)&&oh(r))return bl($o(t.value,r.value));if(oh(t)&&zv(r))return bl($o(t.value,e.right));if(zv(t)&&oh(r))return bl($o(e.left,r.value));if(zv(t)&&zv(r))return CT;throw Error("[BUG]: Doc.changesUponFlattening - unable to flatten a Cat document - please open an issue at https://github.com/IMax153/contentlayer/issues/new")}case"Nest":return yield*tj(Kv(e.doc),os.map(iD((t)=>_d(t,e.indent))));case"Union":return bl(e.left);case"Column":{let t=sh((r)=>os.runSync(Mc(e.react(r))));return bl(t)}case"WithPageWidth":{let t=Xv((r)=>os.runSync(Mc(e.react(r))));return bl(t)}case"Nesting":{let t=ah((r)=>os.runSync(Mc(e.react(r))));return bl(t)}case"Annotated":return yield*tj(Kv(e.doc),os.map(iD((t)=>ch(t,e.annotation))))}}),ch=Bc(2,(e,t)=>{let r=Object.create(fa);return r._tag="Annotated",r.doc=e,r.annotation=t,r});var yj=(e)=>{if(e<=0)return Yv;if(e===1)return Qv(" ");return Qu(hj(e))};var hj=(e)=>{let t="";for(let r=0;r<e;r++)t=t+=" ";return t};import*as Dd from"effect/Effect";import{dual as xD}from"effect/Function";import*as ks from"effect/List";import*as lh from"effect/Option";import*as Zv from"effect/Effect";import*as kd from"effect/Equal";import{dual as NT,pipe as Kf}from"effect/Function";import*as Rt from"effect/Hash";import*as uD from"effect/List";import*as Gne from"effect/Option";var Ju="@effect/printer/DocStream",Sj=Symbol.for(Ju),Qne={FailedStream:(e)=>Kf(Rt.string("@effect/printer/DocStream/FailedStream"),Rt.combine(Rt.string(Ju))),EmptyStream:(e)=>Kf(Rt.string("@effect/printer/DocStream/EmptyStream"),Rt.combine(Rt.string(Ju))),CharStream:(e)=>Kf(Rt.hash("@effect/printer/DocStream/CharStream"),Rt.combine(Rt.string(Ju)),Rt.combine(Rt.string(e.char)),Rt.combine(Rt.hash(e.stream))),TextStream:(e)=>Kf(Rt.string("@effect/printer/DocStream/TextStream"),Rt.combine(Rt.string(Ju)),Rt.combine(Rt.string(e.text)),Rt.combine(Rt.hash(e.stream))),LineStream:(e)=>Kf(Rt.string("@effect/printer/DocStream/LineStream"),Rt.combine(Rt.string(Ju)),Rt.combine(Rt.hash(e.stream))),PushAnnotationStream:(e)=>Kf(Rt.string("@effect/printer/DocStream/PopAnnotationStream"),Rt.combine(Rt.string(Ju)),Rt.combine(Rt.hash(e.annotation)),Rt.combine(Rt.hash(e.stream))),PopAnnotationStream:(e)=>Kf(Rt.string("@effect/printer/DocStream/PopAnnotationStream"),Rt.combine(Rt.string(Ju)),Rt.combine(Rt.hash(e.stream)))},Jne={FailedStream:(e,t)=>Gf(t)&&t._tag==="FailedStream",EmptyStream:(e,t)=>Gf(t)&&t._tag==="EmptyStream",CharStream:(e,t)=>Gf(t)&&t._tag==="CharStream"&&e.char===t.char&&kd.equals(e.stream,t.stream),TextStream:(e,t)=>Gf(t)&&t._tag==="TextStream"&&e.text===t.text&&kd.equals(e.stream,t.stream),LineStream:(e,t)=>Gf(t)&&t._tag==="LineStream"&&kd.equals(e.stream,t.stream),PushAnnotationStream:(e,t)=>Gf(t)&&t._tag==="PushAnnotationStream"&&kd.equals(e.annotation,t.annotation)&&kd.equals(e.stream,t.stream),PopAnnotationStream:(e,t)=>Gf(t)&&t._tag==="PopAnnotationStream"&&kd.equals(e.stream,t.stream)},Qf={[Sj]:{_A:(e)=>e},[Rt.symbol](){return Rt.cached(this,Qne[this._tag](this))},[kd.symbol](e){return Jne[this._tag](this,e)}},Gf=(e)=>typeof e==="object"&&e!=null&&(Sj in e);var vj=(e)=>e._tag==="EmptyStream";var xj=(e)=>e._tag==="LineStream";var pD=(()=>{let e=Object.create(Qf);return e._tag="FailedStream",e})(),fD=(()=>{let e=Object.create(Qf);return e._tag="EmptyStream",e})(),mD=NT(2,(e,t)=>{let r=Object.create(Qf);return r._tag="CharStream",r.char=t,r.stream=e,r}),yD=NT(2,(e,t)=>{let r=Object.create(Qf);return r._tag="TextStream",r.text=t,r.stream=e,r}),hD=NT(2,(e,t)=>{let r=Object.create(Qf);return r._tag="LineStream",r.indentation=t,r.stream=e,r}),Ej=NT(2,(e,t)=>{let r=Object.create(Qf);return r._tag="PushAnnotationStream",r.annotation=t,r.stream=e,r}),bj=(e)=>{let t=Object.create(Qf);return t._tag="PopAnnotationStream",t.stream=e,t};var wj={_tag:"Nil"},Va=(e,t,r)=>({_tag:"Cons",indent:e,document:t,pipeline:r}),Tj=(e)=>({_tag:"UndoAnnotation",pipeline:e});import*as Ij from"effect/Equal";import{pipe as Aj}from"effect/Function";import*as Ui from"effect/Hash";var gD="@effect/printer/PageWidth",FT=Symbol.for(gD),Zne={AvailablePerLine:(e)=>Aj(Ui.hash("@effect/printer/PageWidth/AvailablePerLine"),Ui.combine(Ui.hash(gD)),Ui.combine(Ui.hash(e.lineWidth)),Ui.combine(Ui.hash(e.ribbonFraction))),Unbounded:(e)=>Aj(Ui.hash("@effect/printer/PageWidth/Unbounded"),Ui.combine(Ui.hash(gD)))},eoe={AvailablePerLine:(e,t)=>SD(t)&&t._tag==="AvailablePerLine"&&e.lineWidth===t.lineWidth&&e.ribbonFraction===t.ribbonFraction,Unbounded:(e,t)=>SD(t)&&t._tag==="Unbounded"},Rj={[FT]:FT,[Ui.symbol](){return Ui.cached(this,Zne[this._tag](this))},[Ij.symbol](e){return eoe[this._tag](this,e)}},SD=(e)=>typeof e==="object"&&e!=null&&(FT in e);var Pj=(e,t)=>{let r=Object.create(Rj);return r._tag="AvailablePerLine",r.lineWidth=e,r.ribbonFraction=t,r},UT=(()=>{let e=Object.create(Rj);return e._tag="Unbounded",e})(),vD=Pj(80,1),MT=(e,t,r,n)=>{let o=e-n,i=Math.max(0,Math.min(e,Math.floor(e*t))),s=r+i-n;return Math.min(o,s)};var _j=(e)=>({pageWidth:e});var LT=xD(3,(e,t,r)=>Dd.runSync(toe(Va(0,e,wj),0,0,t,r))),toe=(e,t,r,n,o)=>{let i=(s,a,c)=>Dd.gen(function*(){switch(s._tag){case"Nil":return fD;case"Cons":switch(s.document._tag){case"Fail":return pD;case"Empty":return yield*i(s.pipeline,a,c);case"Char":{let l=yield*i(s.pipeline,a,c+1);return mD(l,s.document.char)}case"Text":{let l=s.document.text.length,d=yield*i(s.pipeline,a,c+l);return yD(d,s.document.text)}case"Line":{let l=yield*i(s.pipeline,s.indent,s.indent),d=vj(l)||xj(l)?0:s.indent;return hD(l,d)}case"FlatAlt":{let l=Va(s.indent,s.document.left,s.pipeline);return yield*i(l,a,c)}case"Cat":{let l=Va(s.indent,s.document.right,s.pipeline),d=Va(s.indent,s.document.left,l);return yield*i(d,a,c)}case"Nest":{let l=s.indent+s.document.indent,d=Va(l,s.document.doc,s.pipeline);return yield*i(d,a,c)}case"Union":{let l=Va(s.indent,s.document.left,s.pipeline),d=Va(s.indent,s.document.right,s.pipeline),u=i(l,a,c),p=i(d,a,c);return roe(n,a,c,u,p)}case"Column":{let l=s.document.react(c),d=Va(s.indent,l,s.pipeline);return yield*i(d,a,c)}case"WithPageWidth":{let l=s.document.react(o.pageWidth),d=Va(s.indent,l,s.pipeline);return yield*i(d,a,c)}case"Nesting":{let l=s.document.react(s.indent),d=Va(s.indent,l,s.pipeline);return yield*i(d,a,c)}case"Annotated":{let l=Tj(s.pipeline),d=Va(s.indent,s.document.doc,l),u=yield*i(d,a,c);return Ej(u,s.document.annotation)}}case"UndoAnnotation":{let l=yield*i(s.pipeline,t,r);return bj(l)}}});return i(e,t,r)},roe=(e,t,r,n,o)=>{let i=Dd.runSync(n),s=void 0;return e(i,t,r,()=>s??(s=Dd.runSync(o),s))?i:s??Dd.runSync(o)},kj=(e)=>Dd.runSync(ma(ks.of(e),0)),ma=(e,t)=>Dd.gen(function*(){if(ks.isNil(e))return fD;let{head:r,tail:n}=e;switch(r._tag){case"Fail":return pD;case"Empty":return yield*ma(n,t);case"Char":{let o=yield*ma(n,t+1);return mD(o,r.char)}case"Text":{let o=yield*ma(n,t+r.text.length);return yD(o,r.text)}case"Line":{let o=yield*ma(n,0);return hD(o,0)}case"FlatAlt":return yield*ma(ks.cons(r.left,n),t);case"Cat":{let o=ks.cons(r.left,ks.cons(r.right,n));return yield*ma(o,t)}case"Nest":return yield*ma(ks.cons(r.doc,n),t);case"Union":return yield*ma(ks.cons(r.right,n),t);case"Column":return yield*ma(ks.cons(r.react(t),n),t);case"WithPageWidth":return yield*ma(ks.cons(r.react(UT),n),t);case"Nesting":return yield*ma(ks.cons(r.react(0),n),t);case"Annotated":return yield*ma(ks.cons(r.doc,n),t)}}),Dj=xD(2,(e,t)=>{let r=t.pageWidth;if(r._tag==="AvailablePerLine")return LT(e,(n,o,i)=>{let s=MT(r.lineWidth,r.ribbonFraction,o,i);return noe(n,s)},t);return ED(e)}),noe=(e,t)=>{let r=t,n=e;while(r>=0)switch(n._tag){case"FailedStream":return!1;case"EmptyStream":return!0;case"CharStream":{r=r-1,n=n.stream;break}case"TextStream":{r=r-n.text.length,n=n.stream;break}case"LineStream":return!0;case"PushAnnotationStream":{n=n.stream;break}case"PopAnnotationStream":{n=n.stream;break}}return!1},Oj=xD(2,(e,t)=>{let r=t.pageWidth;if(r._tag==="AvailablePerLine")return LT(e,ooe(r.lineWidth,r.ribbonFraction),t);return ED(e)}),ooe=(e,t)=>(r,n,o,i)=>{let s=MT(e,t,n,o);return ioe(r,i,e,o,s)},ioe=(e,t,r,n,o)=>{let i,s=e,a=o;while(a>=0)switch(s._tag){case"FailedStream":return!1;case"EmptyStream":return!0;case"CharStream":{a=a-1,s=s.stream;break}case"TextStream":{a=a-s.text.length,s=s.stream;break}case"LineStream":{if(!i)i=lh.match(soe(t()),{onNone:()=>n,onSome:(c)=>Math.min(c,n)});if(i<s.indentation)return!1;a=r-s.indentation,s=s.stream;break}case"PushAnnotationStream":{s=s.stream;break}case"PopAnnotationStream":{s=s.stream;break}}return!1},soe=(e)=>{let t=e;while(t._tag==="LineStream"||t._tag==="PushAnnotationStream"||t._tag==="PopAnnotationStream"){if(t._tag==="LineStream")return lh.some(t.indentation);t=t.stream}return lh.none()},ED=(e)=>LT(e,(t)=>!aoe(t),{pageWidth:UT}),aoe=(e)=>{let t=e;while(!0)switch(t._tag){case"FailedStream":return!0;case"EmptyStream":return!1;case"CharStream":{t=t.stream;break}case"TextStream":{t=t.stream;break}case"LineStream":return!1;case"PushAnnotationStream":{t=t.stream;break}case"PopAnnotationStream":{t=t.stream;break}}throw Error("bug")};var ex=Qv,Me=Qu;var rr=Yv;var Dn=DT;var Vt=lD;var X=$o,bD=ij;var Ds=dj,Kn=uj;var ya=_d,Jf=dD;var BT=mj;var Se=ch;var Nj=Se(rr,Wk),Fj=(e,t)=>Se(rr,Vk(e,t)),Uj=(e,t)=>Se(rr,zk(e,t));var Mj=(e=1)=>Se(rr,Kk(e));var Lj=Se(rr,Gk),Bj=Se(rr,Qk),$j=Se(rr,Jk);var qj=Se(rr,Yk),jj=Se(rr,Xk),Hj=(e)=>Se(rr,Zk(e));var Wj=Se(rr,eD);var wD=vD;var TD=_j;var Vj=kj,zj=Dj,Kj=Oj;import*as Xo from"effect/Effect";import{dual as foe}from"effect/Function";import*as Yf from"effect/List";var Qj=foe(2,(e,t)=>{switch(t.style){case"compact":return AD(Vj(e));case"pretty":{let r=Object.assign({},wD,t.options);return AD(zj(e,TD(r)))}case"smart":{let r=Object.assign({},wD,t.options);return AD(Kj(e,TD(r)))}}}),AD=(e)=>Xo.runSync(dh(e,Yf.of(Mq))),Gj=(e)=>{if(Yf.isNil(e))throw Error("BUG: AnsiRender.unsafePeek - peeked at an empty stack - please report an issue at https://github.com/Effect-TS/printer/issues");return e.head},moe=(e)=>{if(Yf.isNil(e))throw Error("BUG: AnsiRender.unsafePop - popped from an empty stack - please report an issue at https://github.com/Effect-TS/printer/issues");return[e.head,e.tail]},dh=(e,t)=>{switch(e._tag){case"FailedStream":return Xo.dieMessage("BUG: AnsiRender.renderSafe - attempted to render a failed doc stream - please report an issue at https://github.com/Effect-TS/printer/issues");case"EmptyStream":return Xo.succeed("");case"CharStream":return Xo.map(Xo.suspend(()=>dh(e.stream,t)),(r)=>e.char+r);case"TextStream":return Xo.map(Xo.suspend(()=>dh(e.stream,t)),(r)=>e.text+r);case"LineStream":{let r=`
|
|
33
|
+
`;for(let n=0;n<e.indentation;n++)r=r+=" ";return Xo.map(Xo.suspend(()=>dh(e.stream,t)),(n)=>r+n)}case"PushAnnotationStream":{let r=Gj(t),n=IT(e.annotation,r);return Xo.map(Xo.suspend(()=>dh(e.stream,Yf.cons(e.annotation,t))),(o)=>AT(n)+o)}case"PopAnnotationStream":{let[,r]=moe(t),n=Gj(r);return Xo.map(Xo.suspend(()=>dh(e.stream,r)),(o)=>AT(n)+o)}}};var za=Nj,Jj=Fj,Yj=Uj;var uh=Mj;var wl=Lj,ph=Bj,fh=$j;var Od=qj,Xj=jj,Zj=Hj;var Ka=Wj;var ir=Qj;import*as Xf from"effect/Effect";import{dual as hoe}from"effect/Function";var eH=hoe(2,(e,t)=>Xf.runSync($T(e,t))),$T=(e,t)=>{let r=(n)=>Xf.gen(function*(){switch(n._tag){case"Fail":case"Empty":case"Char":case"Text":case"Line":return n;case"FlatAlt":{let o=yield*r(n.left),i=yield*r(n.right);return Jv(o,i)}case"Cat":{if(Gv(n.left))return yield*r(n.right);if(Gv(n.right))return yield*r(n.left);if(Ha(n.left)&&Ha(n.right))return Qu(n.left.char+n.right.char);if(Wa(n.left)&&Ha(n.right))return Qu(n.left.text+n.right.char);if(Ha(n.left)&&Wa(n.right))return Qu(n.left.char+n.right.text);if(Wa(n.left)&&Wa(n.right))return Qu(n.left.text+n.right.text);if(Ha(n.left)&&Gu(n.right)&&Ha(n.right.left)||Ha(n.left)&&Gu(n.right)&&Wa(n.right.left)||Wa(n.left)&&Gu(n.right)&&Ha(n.right.left)||Wa(n.left)&&Gu(n.right)&&Wa(n.right.left)){let s=yield*r($o(n.left,n.right.left));return yield*r($o(s,n.right.right))}if(Gu(n.left)&&Ha(n.left.right)||Gu(n.left)&&Wa(n.left.right)){let s=yield*r($o(n.left.right,n.right));return yield*r($o(n.left.left,s))}let o=yield*r(n.left),i=yield*r(n.right);return $o(o,i)}case"Nest":{if(n.indent===0)return yield*r(n.doc);if(Gv(n.doc)||Ha(n.doc)||Wa(n.doc))return n.doc;if(cD(n.doc)){let o=n.indent+n.doc.indent;return yield*r(_d(n.doc.doc,o))}return _d(yield*r(n.doc),n.indent)}case"Union":{let o=yield*r(n.left),i=yield*r(n.right);return ih(o,i)}case"Column":return t._tag==="Shallow"?n:sh((o)=>Xf.runSync($T(n.react(o),t)));case"WithPageWidth":return t._tag==="Shallow"?n:Xv((o)=>Xf.runSync($T(n.react(o),t)));case"Nesting":return t._tag==="Shallow"?n:ah((o)=>Xf.runSync($T(n.react(o),t)));case"Annotated":return ch(yield*r(n.doc),n.annotation)}});return r(e)};var yn={_tag:"Deep"},hn=eH;import*as mh from"effect/Array";import{dual as sH,pipe as iH}from"effect/Function";var tH=ET;var ID=$k,qT=bT,rH=wT;import*as jT from"effect/Array";import{dual as Soe}from"effect/Function";var dt=(e)=>({_tag:"Text",value:e}),ha=dt(""),Os=dt(" "),Il=(e)=>Yu(e,rH),nH=(e)=>Yu(e,tH),Yu=(e,t)=>({_tag:"Highlight",value:typeof e==="string"?dt(e):e,color:t}),HT=(e)=>({_tag:"Strong",value:typeof e==="string"?dt(e):e});var oH=(e)=>({_tag:"Weak",value:typeof e==="string"?dt(e):e});var PD=(e)=>e._tag==="Text";var xi=Soe(2,(e,t)=>({_tag:"Sequence",left:e,right:t})),Al=(e)=>{switch(e._tag){case"Text":case"URI":return e.value;case"Highlight":case"Weak":case"Strong":return Al(e.value);case"Sequence":return Al(e.left)+Al(e.right)}},Ns=(e)=>{let t=jT.fromIterable(e);if(jT.isNonEmptyReadonlyArray(t))return t.slice(1).reduce(xi,t[0]);return ha},CD=(e)=>em(e)===0,em=(e)=>{switch(e._tag){case"Text":case"URI":return e.value.length;case"Highlight":case"Strong":case"Weak":return em(e.value);case"Sequence":return em(e.left)+em(e.right)}},Nd=(e)=>{switch(e._tag){case"Highlight":return Se(Nd(e.value),Zq(e.color));case"Sequence":return X(Nd(e.left),Nd(e.right));case"Strong":return Se(Nd(e.value),Jo);case"Text":return Me(e.value);case"URI":return Se(Me(e.value),rs);case"Weak":return Se(Nd(e.value),Nr)}};var Xu=(e)=>e._tag==="Empty",aH=(e)=>e._tag==="Header",cH=(e)=>e._tag==="Paragraph",lH=(e)=>e._tag==="DescriptionList";var Qr={_tag:"Empty"},et=sH(2,(e,t)=>{if(Xu(e))return t;if(Xu(t))return e;return{_tag:"Sequence",left:e,right:t}});var _D=(e)=>{let t=mh.fromIterable(e);if(mh.isNonEmptyReadonlyArray(t))return t.slice(1).reduce(et,t[0]);return Qr},$c=(e)=>aH(e)||cH(e)?e.value:ha,Zu=(e)=>({_tag:"DescriptionList",definitions:e}),rx=(e)=>({_tag:"Enumeration",elements:e}),qc=(e)=>({_tag:"Header",value:typeof e==="string"?dt(e):e,level:1});var fe=(e)=>({_tag:"Paragraph",value:typeof e==="string"?dt(e):e}),Rl=sH(2,(e,t)=>lH(e)?Zu(mh.map(e.definitions,([r,n])=>t(r,n))):e),dH=(e)=>hn(tx(e),yn),vr=(e)=>ir(dH(e),{style:"pretty"}),tx=(e)=>{switch(e._tag){case"Empty":return rr;case"Header":return iH(Se(Nd(e.value),Jo),X(Dn));case"Paragraph":return iH(Nd(e.value),X(Dn));case"DescriptionList":{let t=e.definitions.map(([r,n])=>bD([Se(Nd(r),Jo),rr,BT(tx(n),2)]));return Kn(t)}case"Enumeration":{let t=e.elements.map((r)=>X(Me("- "),tx(r)));return BT(Kn(t),2)}case"Sequence":return Kn([tx(e.left),tx(e.right)])}};import*as $r from"effect/Array";import*as bt from"effect/Effect";import{dual as s2,pipe as bh}from"effect/Function";import*as Ga from"effect/Option";import{pipeArguments as pse}from"effect/Pipeable";import*as a2 from"effect/Redacted";import*as Yr from"effect/Schema";import*as c2 from"effect/Secret";import*as uH from"effect/Context";import{dual as voe}from"effect/Function";import*as xoe from"effect/Layer";var pH=uH.GenericTag("@effect/cli/CliConfig"),WT={isCaseSensitive:!1,autoCorrectLimit:2,finalCheckBuiltIn:!1,showAllNames:!0,showBuiltIns:!0,showTypes:!0};var Zo=voe(2,(e,t)=>e.isCaseSensitive?t:t.toLowerCase());import{TaggedError as woe}from"effect/Data";import{GenericTag as Eoe}from"effect/Context";var fH=Eoe("@effect/platform/Terminal");class kD extends woe("QuitException"){}var mH=(e)=>typeof e==="object"&&e!=null&&("_tag"in e)&&e._tag==="QuitException",Fr=fH;import*as On from"effect/Effect";import*as hH from"effect/Effectable";import{dual as gH}from"effect/Function";import*as SH from"effect/Pipeable";import*as yH from"effect/Data";var we=yH.taggedEnum();var Toe="@effect/cli/Prompt",vH=Symbol.for(Toe),OD={...hH.CommitPrototype,[vH]:{_Output:(e)=>e},commit(){return FD(this)},pipe(){return SH.pipeArguments(this,arguments)}},ND=(e)=>typeof e==="object"&&e!=null&&(vH in e);var ga=(e,t)=>{let r=Object.create(OD);return r._tag="Loop",r.initialState=e,r.render=t.render,r.process=t.process,r.clear=t.clear,r},Ud=gH(2,(e,t)=>Aoe(e,(r)=>Roe(t(r)))),Aoe=gH(2,(e,t)=>{let r=Object.create(OD);return r._tag="OnSuccess",r.prompt=e,r.onSuccess=t,r}),FD=On.fnUntraced(function*(e){let t=yield*Fr,r=yield*t.readInput;return yield*DD(e,t,r)},On.mapError(()=>new kD),On.scoped),DD=(e,t,r)=>On.suspend(()=>{let n=e;switch(n._tag){case"Loop":return Ioe(n,t,r);case"OnSuccess":return On.flatMap(DD(n.prompt,t,r),(o)=>DD(n.onSuccess(o),t,r));case"Succeed":return On.succeed(n.value)}}),Ioe=On.fnUntraced(function*(e,t,r){let n=On.isEffect(e.initialState)?yield*e.initialState:e.initialState,o=we.NextFrame({state:n});while(!0){let i=yield*e.render(n,o);yield*On.orDie(t.display(i));let s=yield*r.take;switch(o=yield*e.process(s,n),o._tag){case"Beep":continue;case"NextFrame":{yield*On.orDie(t.display(yield*e.clear(n,o))),n=o.state;continue}case"Submit":{yield*On.orDie(t.display(yield*e.clear(n,o)));let a=yield*e.render(n,o);return yield*On.orDie(t.display(a)),o.value}}}},(e,t,r)=>On.ensuring(e,On.orDie(r.display(ir(Xj,{style:"pretty"}))))),Roe=(e)=>{let t=Object.create(OD);return t._tag="Succeed",t.value=e,t};import*as ti from"effect/Array";import*as is from"effect/Effect";import*as Eo from"effect/Match";import*as ss from"effect/Option";import*as VT from"effect/Array";import*as zT from"effect/Effect";import{pipe as Poe}from"effect/Function";var nx={arrowUp:Me("\u2191"),arrowDown:Me("\u2193"),arrowLeft:Me("\u2190"),arrowRight:Me("\u2192"),radioOn:Me("\u25C9"),radioOff:Me("\u25EF"),checkboxOn:Me("\u2612"),checkboxOff:Me("\u2610"),tick:Me("\u2714"),cross:Me("\u2716"),ellipsis:Me("\u2026"),pointerSmall:Me("\u203A"),line:Me("\u2500"),pointer:Me("\u276F")},Coe={arrowUp:nx.arrowUp,arrowDown:nx.arrowDown,arrowLeft:nx.arrowLeft,arrowRight:nx.arrowRight,radioOn:Me("(*)"),radioOff:Me("( )"),checkboxOn:Me("[*]"),checkboxOff:Me("[ ]"),tick:Me("\u221A"),cross:Me("\xD7"),ellipsis:Me("..."),pointerSmall:Me("\xBB"),line:Me("\u2500"),pointer:Me(">")},ei=zT.map(zT.sync(()=>process.platform==="win32"),(e)=>e?Coe:nx);function Ei(e,t){if(t===0)return X(Ka,Jj(0));let r=0,n=e.split(/\r?\n/);for(let o of n)r+=1+Math.floor(Math.max(o.length-1,0)/t);return Zj(r)}function hh(e,t){let r=e.split(/\r?\n/);return t===0?r.length:Poe(VT.map(r,(n)=>Math.ceil(n.length/t)),VT.reduce(0,(n,o)=>n+o))}var _oe=ir(za,{style:"pretty"});function koe(e){return(t,r)=>is.gen(function*(){let o=yield*(yield*Fr).columns,i=X(Ka,wl),s=ss.match(t.error,{onNone:()=>rr,onSome:(c)=>uh(hh(c,o)).pipe(X(Ei(`
|
|
34
|
+
${c}`,o)))}),a=Ei(e.message,o);return s.pipe(X(a),X(i),hn(yn),ir({style:"pretty",options:{lineWidth:o}}))})}var Doe=/\r?\n/;function Ooe(e,t){return ss.match(e.error,{onNone:()=>rr,onSome:(r)=>{let n=r.split(Doe);if(ti.isNonEmptyReadonlyArray(n)){let o=(a)=>Se(Me(a),Yo(nh,Uc)),i=X(Se(t,Uc),Vt),s=ti.map(n,(a)=>o(a));return ph.pipe(X(Dn),X(i),X(Jf(Kn(s))),X(fh))}return rr}})}function EH(e,t=!1){return ti.reduce(e.dateParts,rr,(r,n,o)=>{let i=Me(n.toString());if(o===e.cursor&&!t){let s=Yo(rs,xo);return X(r,Se(i,s))}return X(r,i)})}function bH(e,t,r,n){let o=(s)=>Se(Me(s),Jo),i=X(e,Vt);return ti.match(n.message.split(/\r?\n/),{onEmpty:()=>Ds([i,t,r]),onNonEmpty:(s)=>{let a=ti.map(s,(c)=>o(c));return i.pipe(X(ya(Kn(a),2)),X(Vt),X(t),X(Vt),X(r))}})}function Noe(e,t){return is.gen(function*(){let n=yield*(yield*Fr).columns,o=yield*ei,i=Se(Me("?"),xo),s=Se(o.pointerSmall,Nr),a=EH(e),c=bH(i,s,a,t),l=Ooe(e,o.pointerSmall);return Od.pipe(X(c),X(l),hn(yn),ir({style:"pretty",options:{lineWidth:n}}))})}function Foe(e,t){return is.gen(function*(){let n=yield*(yield*Fr).columns,o=yield*ei,i=Se(o.tick,pa),s=Se(o.ellipsis,Nr),a=EH(e,!0);return bH(i,s,a,t).pipe(X(Dn),hn(yn),ir({style:"pretty",options:{lineWidth:n}}))})}function Uoe(e){return e.dateParts[e.cursor].increment(),we.NextFrame({state:{...e,typed:""}})}function Moe(e){return e.dateParts[e.cursor].decrement(),we.NextFrame({state:{...e,typed:""}})}function Loe(e){let t=e.dateParts[e.cursor].previousPart();return ss.match(t,{onNone:()=>we.Beep(),onSome:(r)=>we.NextFrame({state:{...e,typed:"",cursor:e.dateParts.indexOf(r)}})})}function Boe(e){let t=e.dateParts[e.cursor].nextPart();return ss.match(t,{onNone:()=>we.Beep(),onSome:(r)=>we.NextFrame({state:{...e,typed:"",cursor:e.dateParts.indexOf(r)}})})}function $oe(e){let t=e.dateParts[e.cursor].nextPart(),r=ss.match(t,{onNone:()=>e.dateParts.findIndex((n)=>!n.isToken()),onSome:(n)=>e.dateParts.indexOf(n)});return we.NextFrame({state:{...e,cursor:r}})}function qoe(e,t){if(/\d/.test(e)){let r=t.typed+e;return t.dateParts[t.cursor].setValue(r),we.NextFrame({state:{...t,typed:r}})}return we.Beep()}var joe={months:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],weekdays:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],weekdaysShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]};function Hoe(e){return(t,r)=>we.$match(r,{Beep:()=>is.succeed(_oe),NextFrame:({state:n})=>Noe(n,e),Submit:()=>Foe(t,e)})}function Woe(e){return(t,r)=>{switch(t.key.name){case"left":return is.succeed(Loe(r));case"right":return is.succeed(Boe(r));case"k":case"up":return is.succeed(Uoe(r));case"j":case"down":return is.succeed(Moe(r));case"tab":return is.succeed($oe(r));case"enter":case"return":return is.match(e.validate(r.value),{onFailure:(n)=>we.NextFrame({state:{...r,error:ss.some(n)}}),onSuccess:(n)=>we.Submit({value:n})});default:{let n=ss.getOrElse(t.input,()=>"");return is.succeed(qoe(n,r))}}}}var wH=(e)=>{let t={initial:new Date,dateMask:"YYYY-MM-DD HH:mm:ss",validate:is.succeed,...e,locales:{...joe,...e.locales}},r=zoe(t.dateMask,t.initial,t.locales),n=r.findIndex((i)=>!i.isToken()),o={dateParts:r,typed:"",cursor:n,value:t.initial,error:ss.none()};return ga(o,{render:Hoe(t),process:Woe(t),clear:koe(t)})},Voe=/\\(.)|"((?:\\["\\]|[^"])+)"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g,xH={1:({token:e,...t})=>new UD({token:e.replace(/\\(.)/g,"$1"),...t}),2:(e)=>new PH(e),3:(e)=>new CH(e),4:(e)=>new _H(e),5:(e)=>new kH(e),6:(e)=>new RH(e),7:(e)=>new IH(e),8:(e)=>new AH(e),9:(e)=>new TH(e)},zoe=(e,t,r)=>{let n=[],o=null;while(o=Voe.exec(e)){let s=o.shift(),a=o.findIndex((c)=>c!==void 0);if(a in xH){let c=o[a]||s;n.push(xH[a]({token:c,date:t,parts:n,locales:r}))}else n.push(new UD({token:o[a]||s,date:t,parts:n,locales:r}))}let i=n.reduce((s,a)=>{let c=s[s.length-1];if(a.isToken()&&c!==void 0&&c.isToken())c.setValue(a.token);else s.push(a);return s},ti.empty());return n.splice(0,n.length,...i),n};class Cl{token;date;parts;locales;constructor(e){this.token=e.token,this.locales=e.locales,this.date=e.date||new Date,this.parts=e.parts||[this]}isToken(){return!1}nextPart(){return ti.findFirstIndex(this.parts,(e)=>e===this).pipe(ss.flatMap((e)=>ti.findFirst(this.parts.slice(e+1),(t)=>!t.isToken())))}previousPart(){return ti.findFirstIndex(this.parts,(e)=>e===this).pipe(ss.flatMap((e)=>ti.findLast(this.parts.slice(0,e),(t)=>!t.isToken())))}toString(){return String(this.date)}}class UD extends Cl{increment(){}decrement(){}setValue(e){this.token=this.token+e}isToken(){return!0}toString(){return this.token}}class TH extends Cl{increment(){this.date.setMilliseconds(this.date.getMilliseconds()+1)}decrement(){this.date.setMilliseconds(this.date.getMilliseconds()-1)}setValue(e){this.date.setMilliseconds(Number.parseInt(e.slice(-this.token.length)))}toString(){return`${this.date.getMilliseconds()}`.padStart(4,"0").substring(0,this.token.length)}}class AH extends Cl{increment(){this.date.setSeconds(this.date.getSeconds()+1)}decrement(){this.date.setSeconds(this.date.getSeconds()-1)}setValue(e){this.date.setSeconds(Number.parseInt(e.slice(-2)))}toString(){let e=`${this.date.getSeconds()}`;return this.token.length>1?e.padStart(2,"0"):e}}class IH extends Cl{increment(){this.date.setMinutes(this.date.getMinutes()+1)}decrement(){this.date.setMinutes(this.date.getMinutes()-1)}setValue(e){this.date.setMinutes(Number.parseInt(e.slice(-2)))}toString(){let e=`${this.date.getMinutes()}`;return this.token.length>1?e.padStart(2,"0"):e}}class RH extends Cl{increment(){this.date.setHours(this.date.getHours()+1)}decrement(){this.date.setHours(this.date.getHours()-1)}setValue(e){this.date.setHours(Number.parseInt(e.slice(-2)))}toString(){let e=/h/.test(this.token)?this.date.getHours()%12||12:this.date.getHours();return this.token.length>1?`${e}`.padStart(2,"0"):`${e}`}}class PH extends Cl{increment(){this.date.setDate(this.date.getDate()+1)}decrement(){this.date.setDate(this.date.getDate()-1)}setValue(e){this.date.setDate(Number.parseInt(e.slice(-2)))}toString(){let e=this.date.getDate(),t=this.date.getDay();return Eo.value(this.token).pipe(Eo.when("DD",()=>`${e}`.padStart(2,"0")),Eo.when("Do",()=>`${e}${this.ordinalIndicator(e)}`),Eo.when("d",()=>`${t+1}`),Eo.when("ddd",()=>this.locales.weekdaysShort[t]),Eo.when("dddd",()=>this.locales.weekdays[t]),Eo.orElse(()=>`${e}`))}ordinalIndicator(e){return Eo.value(e%10).pipe(Eo.when(1,()=>"st"),Eo.when(2,()=>"nd"),Eo.when(3,()=>"rd"),Eo.orElse(()=>"th"))}}class CH extends Cl{increment(){this.date.setMonth(this.date.getMonth()+1)}decrement(){this.date.setMonth(this.date.getMonth()-1)}setValue(e){let t=Number.parseInt(e.slice(-2))-1;this.date.setMonth(t<0?0:t)}toString(){let e=this.date.getMonth();return Eo.value(this.token.length).pipe(Eo.when(2,()=>`${e+1}`.padStart(2,"0")),Eo.when(3,()=>this.locales.monthsShort[e]),Eo.when(4,()=>this.locales.months[e]),Eo.orElse(()=>`${e+1}`))}}class _H extends Cl{increment(){this.date.setFullYear(this.date.getFullYear()+1)}decrement(){this.date.setFullYear(this.date.getFullYear()-1)}setValue(e){this.date.setFullYear(Number.parseInt(e.slice(-4)))}toString(){let e=`${this.date.getFullYear()}`.padStart(4,"0");return this.token.length===2?e.substring(-2):e}}class kH extends Cl{increment(){this.date.setHours((this.date.getHours()+12)%24)}decrement(){this.increment()}setValue(e){}toString(){let e=this.date.getHours()>12?"pm":"am";return/A/.test(this.token)?e.toUpperCase():e}}El();import{GenericTag as Goe}from"effect/Context";import*as nm from"effect/Effect";import{identity as Qoe}from"effect/Function";import*as Joe from"effect/Layer";var KT=Symbol.for("@effect/platform/Path"),LD=Goe("@effect/platform/Path");function DH(e,t){let r="",n=0,o=-1,i=0,s;for(let a=0;a<=e.length;++a){if(a<e.length)s=e.charCodeAt(a);else if(s===47)break;else s=47;if(s===47){if(o===a-1||i===1);else if(o!==a-1&&i===2){if(r.length<2||n!==2||r.charCodeAt(r.length-1)!==46||r.charCodeAt(r.length-2)!==46){if(r.length>2){let c=r.lastIndexOf("/");if(c!==r.length-1){if(c===-1)r="",n=0;else r=r.slice(0,c),n=r.length-1-r.lastIndexOf("/");o=a,i=0;continue}}else if(r.length===2||r.length===1){r="",n=0,o=a,i=0;continue}}if(t){if(r.length>0)r+="/..";else r="..";n=2}}else{if(r.length>0)r+="/"+e.slice(o+1,a);else r=e.slice(o+1,a);n=a-o-1}o=a,i=0}else if(s===46&&i!==-1)++i;else i=-1}return r}function Yoe(e,t){let r=t.dir||t.root,n=t.base||(t.name||"")+(t.ext||"");if(!r)return n;if(r===t.root)return r+n;return r+e+n}function Xoe(e){if(e.protocol!=="file:")return nm.fail(new ts({module:"Path",method:"fromFileUrl",description:"URL must be of scheme file"}));else if(e.hostname!=="")return nm.fail(new ts({module:"Path",method:"fromFileUrl",description:"Invalid file URL host"}));let t=e.pathname;for(let r=0;r<t.length;r++)if(t[r]==="%"){let n=t.codePointAt(r+2)|32;if(t[r+1]==="2"&&n===102)return nm.fail(new ts({module:"Path",method:"fromFileUrl",description:"must not include encoded / characters"}))}return nm.succeed(decodeURIComponent(t))}var OH=function(){let t="",r=!1,n=void 0;for(let o=arguments.length-1;o>=-1&&!r;o--){let i;if(o>=0)i=arguments[o];else{let s=globalThis.process;if(n===void 0&&"process"in globalThis&&typeof s==="object"&&s!==null&&typeof s.cwd==="function")n=s.cwd();i=n}if(i.length===0)continue;t=i+"/"+t,r=i.charCodeAt(0)===47}if(t=DH(t,!r),r)if(t.length>0)return"/"+t;else return"/";else if(t.length>0)return t;else return"."},Zoe=47;function eie(e){let t=new URL("file://"),r=OH(e);if(e.charCodeAt(e.length-1)===Zoe&&r[r.length-1]!=="/")r+="/";return t.pathname=sie(r),nm.succeed(t)}var tie=/%/g,rie=/\\/g,nie=/\n/g,oie=/\r/g,iie=/\t/g;function sie(e){if(e.includes("%"))e=e.replace(tie,"%25");if(e.includes("\\"))e=e.replace(rie,"%5C");if(e.includes(`
|
|
35
|
+
`))e=e.replace(nie,"%0A");if(e.includes("\r"))e=e.replace(oie,"%0D");if(e.includes("\t"))e=e.replace(iie,"%09");return e}var MD=LD.of({[KT]:KT,resolve:OH,normalize(e){if(e.length===0)return".";let t=e.charCodeAt(0)===47,r=e.charCodeAt(e.length-1)===47;if(e=DH(e,!t),e.length===0&&!t)e=".";if(e.length>0&&r)e+="/";if(t)return"/"+e;return e},isAbsolute(e){return e.length>0&&e.charCodeAt(0)===47},join(){if(arguments.length===0)return".";let e;for(let t=0;t<arguments.length;++t){let r=arguments[t];if(r.length>0)if(e===void 0)e=r;else e+="/"+r}if(e===void 0)return".";return MD.normalize(e)},relative(e,t){if(e===t)return"";if(e=MD.resolve(e),t=MD.resolve(t),e===t)return"";let r=1;for(;r<e.length;++r)if(e.charCodeAt(r)!==47)break;let n=e.length,o=n-r,i=1;for(;i<t.length;++i)if(t.charCodeAt(i)!==47)break;let a=t.length-i,c=o<a?o:a,l=-1,d=0;for(;d<=c;++d){if(d===c){if(a>c){if(t.charCodeAt(i+d)===47)return t.slice(i+d+1);else if(d===0)return t.slice(i+d)}else if(o>c){if(e.charCodeAt(r+d)===47)l=d;else if(d===0)l=0}break}let p=e.charCodeAt(r+d),y=t.charCodeAt(i+d);if(p!==y)break;else if(p===47)l=d}let u="";for(d=r+l+1;d<=n;++d)if(d===n||e.charCodeAt(d)===47)if(u.length===0)u+="..";else u+="/..";if(u.length>0)return u+t.slice(i+l);else{if(i+=l,t.charCodeAt(i)===47)++i;return t.slice(i)}},dirname(e){if(e.length===0)return".";let t=e.charCodeAt(0),r=t===47,n=-1,o=!0;for(let i=e.length-1;i>=1;--i)if(t=e.charCodeAt(i),t===47){if(!o){n=i;break}}else o=!1;if(n===-1)return r?"/":".";if(r&&n===1)return"//";return e.slice(0,n)},basename(e,t){let r=0,n=-1,o=!0,i;if(t!==void 0&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";let s=t.length-1,a=-1;for(i=e.length-1;i>=0;--i){let c=e.charCodeAt(i);if(c===47){if(!o){r=i+1;break}}else{if(a===-1)o=!1,a=i+1;if(s>=0)if(c===t.charCodeAt(s)){if(--s===-1)n=i}else s=-1,n=a}}if(r===n)n=a;else if(n===-1)n=e.length;return e.slice(r,n)}else{for(i=e.length-1;i>=0;--i)if(e.charCodeAt(i)===47){if(!o){r=i+1;break}}else if(n===-1)o=!1,n=i+1;if(n===-1)return"";return e.slice(r,n)}},extname(e){let t=-1,r=0,n=-1,o=!0,i=0;for(let s=e.length-1;s>=0;--s){let a=e.charCodeAt(s);if(a===47){if(!o){r=s+1;break}continue}if(n===-1)o=!1,n=s+1;if(a===46){if(t===-1)t=s;else if(i!==1)i=1}else if(t!==-1)i=-1}if(t===-1||n===-1||i===0||i===1&&t===n-1&&t===r+1)return"";return e.slice(t,n)},format:function(t){if(t===null||typeof t!=="object")throw TypeError('The "pathObject" argument must be of type Object. Received type '+typeof t);return Yoe("/",t)},parse(e){let t={root:"",dir:"",base:"",ext:"",name:""};if(e.length===0)return t;let r=e.charCodeAt(0),n=r===47,o;if(n)t.root="/",o=1;else o=0;let i=-1,s=0,a=-1,c=!0,l=e.length-1,d=0;for(;l>=o;--l){if(r=e.charCodeAt(l),r===47){if(!c){s=l+1;break}continue}if(a===-1)c=!1,a=l+1;if(r===46){if(i===-1)i=l;else if(d!==1)d=1}else if(i!==-1)d=-1}if(i===-1||a===-1||d===0||d===1&&i===a-1&&i===s+1){if(a!==-1)if(s===0&&n)t.base=t.name=e.slice(1,a);else t.base=t.name=e.slice(s,a)}else{if(s===0&&n)t.name=e.slice(1,i),t.base=e.slice(1,a);else t.name=e.slice(s,i),t.base=e.slice(s,a);t.ext=e.slice(i,a)}if(s>0)t.dir=e.slice(0,s-1);else if(n)t.dir="/";return t},sep:"/",fromFileUrl:Xoe,toFileUrl:eie,toNamespacedPath:Qoe});var om=KT,Sa=LD;import*as JT from"effect/Array";import*as NH from"effect/Data";import*as zt from"effect/Effect";import{identity as lie}from"effect/Function";import*as _l from"effect/Option";var GT=(e,t,r)=>{let n=r===void 0?t:r,o=Math.min(t-n,e-Math.floor(n/2));if(o<0)o=0;let i=Math.min(o+n,t);return{startIndex:o,endIndex:i}};var FH="The selected directory contains files. Would you like to traverse the selected directory?",ox=NH.taggedEnum(),QT=ox.$is("Show"),die=ir(za,{style:"pretty"});function Sh(e,t){return _l.match(e,{onNone:()=>_l.match(t.startingPath,{onNone:()=>zt.sync(()=>process.cwd()),onSome:(r)=>zt.flatMap(Bo,(n)=>zt.orDie(n.exists(r)).pipe(zt.filterOrDieMessage(lie,`The provided starting path '${r}' does not exist`),zt.as(r)))}),onSome:(r)=>zt.succeed(r)})}function $D(e,t){return zt.gen(function*(){let r=yield*Bo,n=yield*Sa,o=yield*zt.orDie(r.readDirectory(e)).pipe(zt.map((i)=>["..",...i]));return yield*zt.filter(o,(i)=>{let s=t.filter(i),a=zt.isEffect(s)?s:zt.succeed(s),c=t.type==="directory"?zt.map(zt.orDie(r.stat(n.join(e,i))),(l)=>l.type==="Directory"):zt.succeed(!0);return zt.zipWith(a,c,(l,d)=>l&&d)},{concurrency:o.length})})}function uie(e){return(t,r)=>zt.gen(function*(){let o=yield*(yield*Fr).columns,i=yield*Sh(t.path,e),s=`
|
|
36
|
+
`.repeat(Math.min(t.files.length,e.maxPerPage)),a=Ei(i,o),c=QT(t.confirm)?FH:e.message,l=Ei(`
|
|
37
|
+
${c}`,o);return Ei(s,o).pipe(X(a),X(l),hn(yn),ir({style:"pretty",options:{lineWidth:o}}))})}var pie=/\r?\n/;function BD(e,t,r,n){let o=(s)=>Se(Me(s),Jo),i=X(r,Vt);return JT.match(t.split(pie),{onEmpty:()=>Ds([i,n,e]),onNonEmpty:(s)=>{let a=JT.map(s,(c)=>o(c));return i.pipe(X(ya(Kn(a),2)),X(Vt),X(n),X(Vt),X(e))}})}function fie(e,t,r,n,o){let i=Vt;if(r===t.startIndex&&t.startIndex>0)i=o.arrowUp;else if(r===t.endIndex-1&&t.endIndex<n)i=o.arrowDown;return e.cursor===r?o.pointer.pipe(Se(xo),X(i)):i.pipe(X(Vt))}function mie(e,t){return t?Se(Me(e),Yo(rs,xo)):Me(e)}function yie(e,t,r,n){let o=t.length,i=GT(e.cursor,o,n.maxPerPage),s=[];for(let a=i.startIndex;a<i.endIndex;a++){let c=e.cursor===a,l=fie(e,i,a,o,r),d=mie(t[a],c);s.push(X(l,d))}return Kn(s)}function hie(e,t){return zt.gen(function*(){let r=yield*Sa,o=yield*(yield*Fr).columns,i=yield*ei,s=yield*Sh(e.path,t),a=e.files[e.cursor],c=r.resolve(s,a),l=i.pointerSmall.pipe(X(Vt),X(Me(c)),Se(Nr));if(QT(e.confirm)){let g=Se(Me("?"),xo),E=Se(i.pointerSmall,Nr),S=Se(Me("(Y/n)"),Nr),x=BD(S,FH,g,E);return Od.pipe(X(x),X(Dn),X(l),hn(yn),ir({style:"pretty",options:{lineWidth:o}}))}let d=Se(i.tick,pa),u=Se(i.ellipsis,Nr),p=BD(rr,t.message,d,u),y=yie(e,e.files,i,t);return Od.pipe(X(p),X(Dn),X(l),X(Dn),X(y),hn(yn),ir({style:"pretty",options:{lineWidth:o}}))})}function gie(e,t){return zt.gen(function*(){let n=yield*(yield*Fr).columns,o=yield*ei,i=Se(o.tick,pa),s=Se(o.ellipsis,Nr);return BD(rr,t.message,i,s).pipe(X(Vt),X(Se(Me(e),zu)),X(Dn),ir({style:"pretty",options:{lineWidth:n}}))})}function Sie(e){return(t,r)=>we.$match(r,{Beep:()=>zt.succeed(die),NextFrame:({state:n})=>hie(n,e),Submit:({value:n})=>gie(n,e)})}function vie(e){let t=e.cursor-1;return zt.succeed(we.NextFrame({state:{...e,cursor:t<0?e.files.length-1:t}}))}function xie(e){return zt.succeed(we.NextFrame({state:{...e,cursor:(e.cursor+1)%e.files.length}}))}function Eie(e,t){return zt.gen(function*(){let r=yield*Bo,n=yield*Sa,o=yield*Sh(e.path,t),i=e.files[e.cursor],s=n.resolve(o,i);if((yield*zt.orDie(r.stat(s))).type==="Directory"){let c=yield*$D(s,t),l=c.filter((d)=>d!=="..");if(t.type==="directory"||t.type==="either")return l.length===0?we.Submit({value:s}):we.NextFrame({state:{...e,confirm:ox.Show()}});return we.NextFrame({state:{cursor:0,files:c,path:_l.some(s),confirm:ox.Hide()}})}return we.Submit({value:s})})}function bie(e){return(t,r)=>zt.gen(function*(){switch(t.key.name){case"k":case"up":return yield*vie(r);case"j":case"down":case"tab":return yield*xie(r);case"enter":case"return":return yield*Eie(r,e);case"y":case"t":{if(QT(r.confirm)){let n=yield*Sa,o=yield*Sh(r.path,e),i=r.files[r.cursor],s=n.resolve(o,i),a=yield*$D(s,e);return we.NextFrame({state:{cursor:0,files:a,path:_l.some(s),confirm:ox.Hide()}})}return we.Beep()}case"n":case"f":{if(QT(r.confirm)){let n=yield*Sa,o=yield*Sh(r.path,e),i=r.files[r.cursor],s=n.resolve(o,i);return we.Submit({value:s})}return we.Beep()}default:return we.Beep()}})}var UH=(e={})=>{let t={type:e.type??"file",message:e.message??"Choose a file",startingPath:_l.fromNullable(e.startingPath),maxPerPage:e.maxPerPage??10,filter:e.filter??(()=>zt.succeed(!0))},r=zt.gen(function*(){let n=_l.none(),o=yield*Sh(n,t),i=yield*$D(o,t),s=ox.Hide();return{cursor:0,files:i,path:n,confirm:s}});return ga(r,{render:Sie(t),process:bie(t),clear:uie(t)})};import*as vh from"effect/Array";import*as Jt from"effect/Effect";import*as LH from"effect/Number";import*as Nn from"effect/Option";import*as ep from"effect/Schema";var BH=ep.NumberFromString.pipe(ep.int(),ep.decodeUnknown),$H=ep.decodeUnknown(ep.NumberFromString),qH=ir(za,{style:"pretty"});function jH(e){return(t,r)=>Jt.gen(function*(){let o=yield*(yield*Fr).columns,i=X(Ka,wl),s=Nn.match(t.error,{onNone:()=>rr,onSome:(c)=>uh(hh(c,o)).pipe(X(Ei(`
|
|
38
|
+
${c}`,o)))}),a=Ei(e.message,o);return s.pipe(X(a),X(i),hn(yn),ir({style:"pretty",options:{lineWidth:o}}))})}function MH(e,t){let r=Nn.match(e.error,{onNone:()=>Yo(rs,xo),onSome:()=>Uc}),n=e.value===""?rr:Me(`${e.value}`);return t?n:Se(n,r)}var Tie=/\r?\n/;function Aie(e,t){return Nn.match(e.error,{onNone:()=>rr,onSome:(r)=>vh.match(r.split(Tie),{onEmpty:()=>rr,onNonEmpty:(n)=>{let o=(a)=>Se(Me(a),Yo(nh,Uc)),i=X(Se(t,Uc),Vt),s=vh.map(n,(a)=>o(a));return ph.pipe(X(Dn),X(i),X(Jf(Kn(s))),X(fh))}})})}function HH(e,t,r,n,o=!1){let i=(a)=>Se(Me(a),Jo),s=X(t,Vt);return vh.match(n.message.split(/\r?\n/),{onEmpty:()=>Ds([s,r,MH(e,o)]),onNonEmpty:(a)=>{let c=vh.map(a,(l)=>i(l));return s.pipe(X(ya(Kn(c),2)),X(Vt),X(r),X(Vt),X(MH(e,o)))}})}function WH(e,t){return Jt.gen(function*(){let n=yield*(yield*Fr).columns,o=yield*ei,i=Se(Me("?"),xo),s=Se(o.pointerSmall,Nr),a=Aie(e,o.pointerSmall);return HH(e,i,s,t).pipe(X(a),hn(yn),ir({style:"pretty",options:{lineWidth:n}}))})}function VH(e,t){return Jt.gen(function*(){let n=yield*(yield*Fr).columns,o=yield*ei,i=Se(o.tick,pa),s=Se(o.ellipsis,Nr);return HH(e,i,s,t,!0).pipe(X(Dn),hn(yn),ir({style:"pretty",options:{lineWidth:n}}))})}function zH(e){if(e.value.length<=0)return Jt.succeed(we.Beep());let t=e.value.slice(0,e.value.length-1);return Jt.succeed(we.NextFrame({state:{...e,value:t,error:Nn.none()}}))}function Iie(e,t){if(e.value.length===0&&t==="-")return Jt.succeed(we.NextFrame({state:{...e,value:"-",error:Nn.none()}}));return Jt.match(BH(e.value+t),{onFailure:()=>we.Beep(),onSuccess:(r)=>we.NextFrame({state:{...e,value:`${r}`,error:Nn.none()}})})}function Rie(e,t){if(t==="."&&e.value.includes("."))return Jt.succeed(we.Beep());if(e.value.length===0&&t==="-")return Jt.succeed(we.NextFrame({state:{...e,value:"-",error:Nn.none()}}));return Jt.match($H(e.value+t),{onFailure:()=>we.Beep(),onSuccess:(r)=>we.NextFrame({state:{...e,value:t==="."?`${r}.`:`${r}`,error:Nn.none()}})})}var KH={cursor:0,value:"",error:Nn.none()};function Pie(e){return(t,r)=>we.$match(r,{Beep:()=>Jt.succeed(qH),NextFrame:({state:n})=>WH(n,e),Submit:()=>VH(t,e)})}function Cie(e){return(t,r)=>{switch(t.key.name){case"backspace":return zH(r);case"k":case"up":return Jt.succeed(we.NextFrame({state:{...r,value:r.value===""||r.value==="-"?`${e.incrementBy}`:`${Number.parseInt(r.value)+e.incrementBy}`,error:Nn.none()}}));case"j":case"down":return Jt.succeed(we.NextFrame({state:{...r,value:r.value===""||r.value==="-"?`-${e.decrementBy}`:`${Number.parseInt(r.value)-e.decrementBy}`,error:Nn.none()}}));case"enter":case"return":return Jt.matchEffect(BH(r.value),{onFailure:()=>Jt.succeed(we.NextFrame({state:{...r,error:Nn.some("Must provide an integer value")}})),onSuccess:(n)=>Jt.match(e.validate(n),{onFailure:(o)=>we.NextFrame({state:{...r,error:Nn.some(o)}}),onSuccess:(o)=>we.Submit({value:o})})});default:{let n=Nn.getOrElse(t.input,()=>"");return Iie(r,n)}}}}var xh=(e)=>{let t={min:Number.NEGATIVE_INFINITY,max:Number.POSITIVE_INFINITY,incrementBy:1,decrementBy:1,validate:(r)=>{if(r<t.min)return Jt.fail(`${r} must be greater than or equal to ${t.min}`);if(r>t.max)return Jt.fail(`${r} must be less than or equal to ${t.max}`);return Jt.succeed(r)},...e};return ga(KH,{render:Pie(t),process:Cie(t),clear:jH(t)})};function _ie(e){return(t,r)=>we.$match(r,{Beep:()=>Jt.succeed(qH),NextFrame:({state:n})=>WH(n,e),Submit:()=>VH(t,e)})}function kie(e){return(t,r)=>{switch(t.key.name){case"backspace":return zH(r);case"k":case"up":return Jt.succeed(we.NextFrame({state:{...r,value:r.value===""||r.value==="-"?`${e.incrementBy}`:`${Number.parseFloat(r.value)+e.incrementBy}`,error:Nn.none()}}));case"j":case"down":return Jt.succeed(we.NextFrame({state:{...r,value:r.value===""||r.value==="-"?`-${e.decrementBy}`:`${Number.parseFloat(r.value)-e.decrementBy}`,error:Nn.none()}}));case"enter":case"return":return Jt.matchEffect($H(r.value),{onFailure:()=>Jt.succeed(we.NextFrame({state:{...r,error:Nn.some("Must provide a floating point value")}})),onSuccess:(n)=>Jt.flatMap(Jt.sync(()=>LH.round(n,e.precision)),(o)=>Jt.match(e.validate(o),{onFailure:(i)=>we.NextFrame({state:{...r,error:Nn.some(i)}}),onSuccess:(i)=>we.Submit({value:i})}))});default:{let n=Nn.getOrElse(t.input,()=>"");return Rie(r,n)}}}}var GH=(e)=>{let t={min:Number.NEGATIVE_INFINITY,max:Number.POSITIVE_INFINITY,incrementBy:1,decrementBy:1,precision:2,validate:(r)=>{if(r<t.min)return Jt.fail(`${r} must be greater than or equal to ${t.min}`);if(r>t.max)return Jt.fail(`${r} must be less than or equal to ${t.max}`);return Jt.succeed(r)},...e};return ga(KH,{render:_ie(t),process:kie(t),clear:jH(t)})};import*as YT from"effect/Array";import*as Fs from"effect/Effect";var Die=ir(za,{style:"pretty"}),Oie=/\r?\n/;function QH(e,t,r){let n=(i)=>Se(Me(i),Jo),o=X(e,Vt);return YT.match(r.message.split(Oie),{onEmpty:()=>Ds([o,t]),onNonEmpty:(i)=>{let s=YT.map(i,(a)=>n(a));return o.pipe(X(ya(Kn(s),2)),X(Vt),X(t),X(Vt))}})}function Nie(e,t,r,n,o){let i=Vt;if(n===r.startIndex&&r.startIndex>0)i=o.arrowUp;else if(n===r.endIndex-1&&r.endIndex<t.length)i=o.arrowDown;if(t[n].disabled){let s=Yo(Jo,Nr);return e===n?o.pointer.pipe(Se(s),X(i)):i.pipe(X(Vt))}return e===n?o.pointer.pipe(Se(xo),X(i)):i.pipe(X(Vt))}function Fie(e,t){let r=Me(e.title);if(t)return e.disabled?Se(r,Yo(rs,Nr)):Se(r,Yo(rs,xo));return e.disabled?Se(r,Yo(Xq,Nr)):r}function Uie(e,t){if(!e.disabled&&e.description&&t)return ex("-").pipe(X(Vt),X(Me(e.description)),Se(Nr));return rr}function Mie(e,t,r){let n=t.choices,o=GT(e,n.length,t.maxPerPage),i=[];for(let s=o.startIndex;s<o.endIndex;s++){let a=n[s],c=e===s,l=Nie(e,n,o,s,r),d=Fie(a,c),u=Uie(a,c);i.push(l.pipe(X(d),X(Vt),X(u)))}return Kn(i)}function Lie(e,t){return Fs.gen(function*(){let n=yield*(yield*Fr).columns,o=yield*ei,i=Mie(e,t,o),s=Se(Me("?"),xo),a=Se(o.pointerSmall,Nr),c=QH(s,a,t);return Od.pipe(X(c),X(Dn),X(i),ir({style:"pretty",options:{lineWidth:n}}))})}function Bie(e,t){return Fs.gen(function*(){let n=yield*(yield*Fr).columns,o=yield*ei,i=Me(t.choices[e].title),s=Se(o.tick,pa),a=Se(o.ellipsis,Nr);return QH(s,a,t).pipe(X(Vt),X(Se(i,zu)),X(Dn),ir({style:"pretty",options:{lineWidth:n}}))})}function $ie(e,t){if(e===0)return Fs.succeed(we.NextFrame({state:t.length-1}));return Fs.succeed(we.NextFrame({state:e-1}))}function qie(e,t){if(e===t.length-1)return Fs.succeed(we.NextFrame({state:0}));return Fs.succeed(we.NextFrame({state:e+1}))}function jie(e,t){return Fs.succeed(we.NextFrame({state:(e+1)%t.length}))}function Hie(e){return(t,r)=>we.$match(r,{Beep:()=>Fs.succeed(Die),NextFrame:({state:n})=>Lie(n,e),Submit:()=>Bie(t,e)})}function Wie(e){return Fs.gen(function*(){let r=yield*(yield*Fr).columns,n=X(Ka,wl),o=`
|
|
39
|
+
`.repeat(Math.min(e.choices.length,e.maxPerPage))+e.message;return Ei(o,r).pipe(X(n),hn(yn),ir({style:"pretty",options:{lineWidth:r}}))})}function Vie(e){return(t,r)=>{switch(t.key.name){case"k":case"up":return $ie(r,e.choices);case"j":case"down":return qie(r,e.choices);case"tab":return jie(r,e.choices);case"enter":case"return":{let n=e.choices[r];if(n.disabled)return Fs.succeed(we.Beep());return Fs.succeed(we.Submit({value:n.value}))}default:return Fs.succeed(we.Beep())}}}var jc=(e)=>{let t={maxPerPage:10,...e},r=0,n=-1;for(let o=0;o<t.choices.length;o++)if(t.choices[o].selected===!0){if(n!==-1)throw Error("InvalidArgumentException: only a single choice can be selected by default for Prompt.select");n=o}if(n!==-1)r=n;return ga(r,{render:Hie(t),process:Vie(t),clear:()=>Wie(t)})};import*as im from"effect/Array";import*as ri from"effect/Effect";import*as as from"effect/Option";import*as YH from"effect/Redacted";function jD(e,t){return e.value.length>0?e.value:t.default}var zie=ir(za,{style:"pretty"});function Kie(e,t){return ri.gen(function*(){let n=yield*(yield*Fr).columns,o=X(Ka,wl),i=as.match(e.error,{onNone:()=>rr,onSome:(l)=>uh(hh(l,n)).pipe(X(Ei(`
|
|
40
|
+
${l}`,n)))}),s=e.value.length>0?e.value:t.default,a=`? ${t.message} \u203A ${s}`,c=Ei(a,n);return i.pipe(X(c),X(o),hn(yn),ir({style:"pretty",options:{lineWidth:n}}))})}function JH(e,t,r){let n=jD(e,t),o=as.match(e.error,{onNone:()=>{if(r)return zu;if(e.value.length===0)return Nr;return Yo(rs,xo)},onSome:()=>Uc});switch(t.type){case"hidden":return rr;case"password":return Se(Me("*".repeat(n.length)),o);case"text":return Se(Me(n),o)}}function Gie(e,t){return as.match(e.error,{onNone:()=>rr,onSome:(r)=>im.match(r.split(/\r?\n/),{onEmpty:()=>rr,onNonEmpty:(n)=>{let o=(a)=>Me(a).pipe(Se(Yo(nh,Uc))),i=X(Se(t,Uc),Vt),s=im.map(n,(a)=>o(a));return ph.pipe(X(Dn),X(i),X(Jf(Kn(s))),X(fh))}})})}function XH(e,t,r,n,o=!1){let i=(c)=>Se(Me(c),Jo),s=n.message.split(/\r?\n/),a=X(t,Vt);if(im.isNonEmptyReadonlyArray(s)){let c=im.map(s,(l)=>i(l));return a.pipe(X(ya(Kn(c),2)),X(Vt),X(r),X(Vt),X(JH(e,n,o)))}return Ds([a,r,JH(e,n,o)])}function Qie(e,t){return ri.gen(function*(){let n=yield*(yield*Fr).columns,o=yield*ei,i=Se(Me("?"),xo),s=Se(o.pointerSmall,Nr),a=XH(e,i,s,t),c=Gie(e,o.pointerSmall),l=e.cursor-e.value.length;return a.pipe(X(c),X(Yj(l)),hn(yn),ir({style:"pretty",options:{lineWidth:n}}))})}function Jie(e,t){return ri.gen(function*(){let n=yield*(yield*Fr).columns,o=yield*ei,i=Se(o.tick,pa),s=Se(o.ellipsis,Nr);return XH(e,i,s,t,!0).pipe(X(Dn),hn(yn),ir({style:"pretty",options:{lineWidth:n}}))})}function Yie(e){if(e.cursor<=0)return ri.succeed(we.Beep());let t=e.value.slice(0,e.cursor-1),r=e.value.slice(e.cursor),n=e.cursor-1,o=`${t}${r}`;return ri.succeed(we.NextFrame({state:{...e,cursor:n,value:o,error:as.none()}}))}function Xie(e){if(e.cursor<=0)return ri.succeed(we.Beep());let t=e.cursor-1;return ri.succeed(we.NextFrame({state:{...e,cursor:t,error:as.none()}}))}function Zie(e){if(e.cursor>=e.value.length)return ri.succeed(we.Beep());let t=Math.min(e.cursor+1,e.value.length);return ri.succeed(we.NextFrame({state:{...e,cursor:t,error:as.none()}}))}function ese(e,t){if(e.value===t.default)return ri.succeed(we.Beep());let r=jD(e,t),n=r.length;return ri.succeed(we.NextFrame({state:{...e,value:r,cursor:n,error:as.none()}}))}function tse(e,t){let r=t.value.slice(0,t.cursor),n=t.value.slice(t.cursor),o=`${r}${e}${n}`,i=t.cursor+e.length;return ri.succeed(we.NextFrame({state:{...t,cursor:i,value:o,error:as.none()}}))}var rse={cursor:0,value:"",error:as.none()};function nse(e){return(t,r)=>we.$match(r,{Beep:()=>ri.succeed(zie),NextFrame:({state:n})=>Qie(n,e),Submit:()=>Jie(t,e)})}function ose(e){return(t,r)=>{switch(t.key.name){case"backspace":return Yie(r);case"left":return Xie(r);case"right":return Zie(r);case"enter":case"return":{let n=jD(r,e);return ri.match(e.validate(n),{onFailure:(o)=>we.NextFrame({state:{...r,value:n,error:as.some(o)}}),onSuccess:(o)=>we.Submit({value:o})})}case"tab":return ese(r,e);default:{let n=as.getOrElse(t.input,()=>"");return tse(n,r)}}}}function ise(e){return(t,r)=>Kie(t,e)}function ZH(e,t){let r={default:"",type:t,validate:ri.succeed,...e};return ga(rse,{render:nse(r),process:ose(r),clear:ise(r)})}var HD=(e)=>ZH(e,"hidden").pipe(Ud(YH.make));var ZT=(e)=>ZH(e,"text");import*as eA from"effect/Array";import*as kl from"effect/Effect";var sse=ir(za,{style:"pretty"});function ase(e){return kl.gen(function*(){let r=yield*(yield*Fr).columns,n=X(Ka,wl);return Ei(e.message,r).pipe(X(n),hn(yn),ir({style:"pretty",options:{lineWidth:r}}))})}function n2(e,t,r=!1){let n=Se(ex("/"),Nr),o=Yo(rs,r?zu:xo),i=e?Me(t.inactive):Se(Me(t.inactive),o),s=e?Se(Me(t.active),o):Me(t.active);return Ds([s,n,i])}function o2(e,t,r,n){let o=(a)=>Se(Me(a),Jo),i=n.message.split(/\r?\n/),s=X(t,Vt);if(eA.isNonEmptyReadonlyArray(i)){let a=eA.map(i,(c)=>o(c));return s.pipe(X(ya(Kn(a),2)),X(Vt),X(r),X(Vt),X(e))}return Ds([s,r,e])}function cse(e,t){return kl.gen(function*(){let r=yield*Fr,n=yield*ei,o=yield*r.columns,i=Se(Me("?"),xo),s=Se(n.pointerSmall,Nr),a=n2(e,t),c=o2(a,i,s,t);return Od.pipe(X(c),hn(yn),ir({style:"pretty",options:{lineWidth:o}}))})}function lse(e,t){return kl.gen(function*(){let r=yield*Fr,n=yield*ei,o=yield*r.columns,i=Se(n.tick,pa),s=Se(n.ellipsis,Nr),a=n2(e,t,!0);return o2(a,i,s,t).pipe(X(Dn),hn(yn),ir({style:"pretty",options:{lineWidth:o}}))})}var t2=kl.succeed(we.NextFrame({state:!0})),r2=kl.succeed(we.NextFrame({state:!1}));function dse(e){return(t,r)=>{switch(r._tag){case"Beep":return kl.succeed(sse);case"NextFrame":return cse(t,e);case"Submit":return lse(t,e)}}}function use(e,t){switch(e.key.name){case"0":case"j":case"delete":case"right":case"down":return r2;case"1":case"k":case"left":case"up":return t2;case" ":case"tab":return t?r2:t2;case"enter":case"return":return kl.succeed(we.Submit({value:t}));default:return kl.succeed(we.Beep())}}var tA=(e)=>{let t={initial:!1,active:"on",inactive:"off",...e};return ga(t.initial,{render:dse(t),process:use,clear:()=>ase(t)})};var fse="@effect/cli/Primitive",l2=Symbol.for(fse),rA={[l2]:{_A:(e)=>e},pipe(){return pse(this,arguments)}},mse=(e)=>typeof e==="object"&&e!=null&&(l2 in e),ix=(e)=>mse(e)&&yse(e),yse=(e)=>e._tag==="Bool";var hse=Yr.Literal("true","1","y","yes","on"),sx=Yr.is(hse),gse=Yr.Literal("false","0","n","no","off"),ax=Yr.is(gse),nA=(e)=>{let t=Object.create(rA);return t._tag="Bool",t.defaultValue=e,t},oA=(e)=>{let t=Object.create(rA);return t._tag="Choice",t.alternatives=e,t};var iA=(e,t)=>{let r=Object.create(rA);return r._tag="Path",r.pathType=e,r.pathExists=t,r};var sA=(()=>{let e=Object.create(rA);return e._tag="Text",e})(),cx=(e)=>Sse(e),aA=(e)=>vse(e),wh=(e)=>sm(e),Th=s2(3,(e,t,r)=>xse(e,t,r)),cA=s2(2,(e,t)=>wse(e,t)),Sse=(e)=>{switch(e._tag){case"Bool":return Ga.some("true | false");case"Choice":{let t=bh($r.map(e.alternatives,([r])=>r),$r.join(" | "));return Ga.some(t)}case"DateTime":return Ga.some("date");case"Float":case"Integer":case"Path":case"Redacted":case"Secret":case"Text":return Ga.none()}},vse=(e)=>{switch(e._tag){case"Bool":return dt("A true or false value.");case"Choice":{let t=bh($r.map(e.alternatives,([r])=>r),$r.join(", "));return dt(`One of the following: ${t}`)}case"DateTime":return dt("A date without a time-zone in the ISO-8601 format, such as 2007-12-03T10:15:30.");case"Float":return dt("A floating point number.");case"Integer":return dt("An integer.");case"Path":{if(e.pathType==="either"&&e.pathExists==="yes")return dt("An existing file or directory.");if(e.pathType==="file"&&e.pathExists==="yes")return dt("An existing file.");if(e.pathType==="directory"&&e.pathExists==="yes")return dt("An existing directory.");if(e.pathType==="either"&&e.pathExists==="no")return dt("A file or directory that must not exist.");if(e.pathType==="file"&&e.pathExists==="no")return dt("A file that must not exist.");if(e.pathType==="directory"&&e.pathExists==="no")return dt("A directory that must not exist.");if(e.pathType==="either"&&e.pathExists==="either")return dt("A file or directory.");if(e.pathType==="file"&&e.pathExists==="either")return dt("A file.");if(e.pathType==="directory"&&e.pathExists==="either")return dt("A directory.");throw Error(`[BUG]: Path.help - encountered invalid combination of path type ('${e.pathType}') and path existence ('${e.pathExists}')`)}case"Secret":case"Redacted":return dt("A user-defined piece of text that is confidential.");case"Text":return dt("A user-defined piece of text.")}},sm=(e)=>{switch(e._tag){case"Bool":return"boolean";case"Choice":return"choice";case"DateTime":return"date";case"Float":return"float";case"Integer":return"integer";case"Path":{if(e.pathType==="either")return"path";return e.pathType}case"Redacted":return"redacted";case"Secret":return"secret";case"Text":return"text"}},xse=(e,t,r)=>{switch(e._tag){case"Bool":return Ga.map(t,(n)=>Zo(r,n)).pipe(Ga.match({onNone:()=>bt.orElseFail(e.defaultValue,()=>"Missing default value for boolean parameter"),onSome:(n)=>sx(n)?bt.succeed(!0):ax(n)?bt.succeed(!1):bt.fail(`Unable to recognize '${n}' as a valid boolean`)}));case"Choice":return bt.orElseFail(t,()=>"Choice options to not have a default value").pipe(bt.flatMap((n)=>$r.findFirst(e.alternatives,([o])=>o===n)),bt.mapBoth({onFailure:()=>`Expected one of the following cases: ${bh($r.map(e.alternatives,([o])=>o),$r.join(", "))}`,onSuccess:([,n])=>n}));case"DateTime":return Eh(t,sm(e),Yr.decodeUnknown(Yr.Date));case"Float":return Eh(t,sm(e),Yr.decodeUnknown(Yr.NumberFromString));case"Integer":{let n=Yr.compose(Yr.NumberFromString,Yr.Int);return Eh(t,sm(e),Yr.decodeUnknown(n))}case"Path":return bt.flatMap(Bo,(n)=>bt.orElseFail(t,()=>"Path options do not have a default value").pipe(bt.tap((i)=>bt.orDie(n.exists(i)).pipe(bt.tap((s)=>Ese(i,e.pathExists,s).pipe(bt.zipRight(bse(i,e.pathType,n).pipe(bt.when(()=>e.pathExists!=="no"&&s)))))))));case"Redacted":return Eh(t,sm(e),Yr.decodeUnknown(Yr.String)).pipe(bt.map((n)=>a2.make(n)));case"Secret":return Eh(t,sm(e),Yr.decodeUnknown(Yr.String)).pipe(bt.map((n)=>c2.fromString(n)));case"Text":return Eh(t,sm(e),Yr.decodeUnknown(Yr.String))}},Eh=(e,t,r)=>bt.orElseFail(e,()=>`${t} options do not have a default value`).pipe(bt.flatMap((n)=>bt.orElseFail(r(n),()=>`'${n}' is not a ${t}`))),Ese=(e,t,r)=>{if(t==="no"&&r)return bt.fail(`Path '${e}' must not exist`);if(t==="yes"&&!r)return bt.fail(`Path '${e}' must exist`);return bt.void},bse=(e,t,r)=>{switch(t){case"file":{let n=r.stat(e).pipe(bt.map((o)=>o.type==="File"),bt.orDie);return bt.fail(`Expected path '${e}' to be a regular file`).pipe(bt.unlessEffect(n),bt.asVoid)}case"directory":{let n=r.stat(e).pipe(bt.map((o)=>o.type==="Directory"),bt.orDie);return bt.fail(`Expected path '${e}' to be a directory`).pipe(bt.unlessEffect(n),bt.asVoid)}case"either":return bt.void}},wse=(e,t)=>{switch(e._tag){case"Bool":{let r=fe("Select true or false"),n=et(t,r),o=Ga.getOrElse(e.defaultValue,()=>!1);return tA({message:vr(n).trimEnd(),initial:o,active:"true",inactive:"false"}).pipe(Ud((i)=>`${i}`))}case"Choice":{let r=fe("Select one of the following choices"),n=et(t,r);return jc({message:vr(n).trimEnd(),choices:$r.map(e.alternatives,([o])=>({title:o,value:o}))})}case"DateTime":{let r=fe("Enter a date"),n=et(t,r);return wH({message:vr(n).trimEnd()}).pipe(Ud((o)=>o.toISOString()))}case"Float":{let r=fe("Enter a floating point value"),n=et(t,r);return GH({message:vr(n).trimEnd()}).pipe(Ud((o)=>`${o}`))}case"Integer":{let r=fe("Enter an integer"),n=et(t,r);return xh({message:vr(n).trimEnd()}).pipe(Ud((o)=>`${o}`))}case"Path":{let r=fe("Select a file system path"),n=et(t,r);return UH({type:e.pathType,message:vr(n).trimEnd()})}case"Redacted":{let r=fe("Enter some text (value will be redacted)"),n=et(t,r);return HD({message:vr(n).trimEnd()})}case"Secret":{let r=fe("Enter some text (value will be redacted)"),n=et(t,r);return HD({message:vr(n).trimEnd()})}case"Text":{let r=fe("Enter some text"),n=et(t,r);return ZT({message:vr(n).trimEnd()})}}},d2=(e)=>{switch(e._tag){case"Bool":return'"${cur}"';case"DateTime":case"Float":case"Integer":case"Secret":case"Redacted":case"Text":return'$(compgen -f "${cur}")';case"Path":switch(e.pathType){case"file":return e.pathExists==="yes"||e.pathExists==="either"?'$(compgen -f "${cur}")':"";case"directory":return e.pathExists==="yes"||e.pathExists==="either"?'$(compgen -d "${cur}")':"";case"either":return e.pathExists==="yes"||e.pathExists==="either"?'$(compgen -f "${cur}")':""}case"Choice":return`$(compgen -W "${bh($r.map(e.alternatives,([r])=>r),$r.join(","))}" -- "\${cur}")`}},lA=(e)=>{switch(e._tag){case"Bool":return $r.empty();case"DateTime":case"Float":case"Integer":case"Redacted":case"Secret":case"Text":return $r.make("-r","-f");case"Path":switch(e.pathType){case"file":return e.pathExists==="yes"||e.pathExists==="either"?$r.make("-r","-F"):$r.make("-r");case"directory":return e.pathExists==="yes"||e.pathExists==="either"?$r.make("-r","-f","-a",'"(__fish_complete_directories (commandline -ct))"'):$r.make("-r");case"either":return e.pathExists==="yes"||e.pathExists==="either"?$r.make("-r","-F"):$r.make("-r")}case"Choice":{let t=bh($r.map(e.alternatives,([r])=>`${r}''`),$r.join(","));return $r.make("-r","-f","-a",`"{${t}}"`)}}},dA=(e)=>{switch(e._tag){case"Bool":return"";case"Choice":return`:CHOICE:(${bh($r.map(e.alternatives,([r])=>r),$r.join(" "))})`;case"DateTime":return"";case"Float":return"";case"Integer":return"";case"Path":switch(e.pathType){case"file":return e.pathExists==="yes"||e.pathExists==="either"?":PATH:_files":"";case"directory":return e.pathExists==="yes"||e.pathExists==="either"?":PATH:_files -/":"";case"either":return e.pathExists==="yes"||e.pathExists==="either"?":PATH:_files":""}case"Redacted":case"Secret":case"Text":return""}};import*as sr from"effect/Array";import{dual as WD,pipe as p2}from"effect/Function";import*as tp from"effect/Option";var Md={_tag:"Empty"},VD={_tag:"Empty"},rp=(e,t)=>({_tag:"Named",names:e,acceptedValues:t}),lx=(e)=>({_tag:"Optional",usage:e}),dx=(e)=>({_tag:"Repeated",usage:e}),zD=WD(2,(e,t)=>({_tag:"Alternation",left:e,right:t})),Ol=WD(2,(e,t)=>({_tag:"Concat",left:e,right:t})),uA=(e)=>{let t=KD(e,WT);if(sr.isNonEmptyReadonlyArray(t)){let r=sr.headNonEmpty(t),n=sr.tailNonEmpty(t);if(sr.isNonEmptyReadonlyArray(n))return p2(sr.map(t,(o)=>fe(o)),sr.reduceRight(Qr,(o,i)=>et(o,i)));return fe(r)}return Qr},KD=WD(2,(e,t)=>Dl(am(e,t),t)),am=(e,t)=>{switch(e._tag){case"Empty":return Md;case"Mixed":return VD;case"Named":{if(tp.isNone(sr.head(Dl(e,t))))return Md;return e}case"Optional":{if(e.usage._tag==="Empty")return Md;let r=am(e.usage,t);return r._tag==="Empty"?Md:r._tag==="Optional"?r:lx(r)}case"Repeated":{let r=am(e.usage,t);return r._tag==="Empty"?Md:dx(r)}case"Alternation":{let r=am(e.left,t),n=am(e.right,t);return r._tag==="Empty"?n:n._tag==="Empty"?r:zD(r,n)}case"Concat":{let r=am(e.left,t),n=am(e.right,t);return r._tag==="Empty"?n:n._tag==="Empty"?r:Ol(r,n)}}},Dl=(e,t)=>{switch(e._tag){case"Empty":return sr.of(dt(""));case"Mixed":return sr.of(dt("<command>"));case"Named":{let r=t.showTypes?tp.match(e.acceptedValues,{onNone:()=>ha,onSome:(i)=>xi(Os,dt(i))}):ha,n=t.showAllNames?e.names:e.names.length>1?p2(sr.filter(e.names,(i)=>i.startsWith("--")),sr.head,tp.map(sr.of),tp.getOrElse(()=>e.names)):e.names,o=dt(sr.join(n,", "));return t.showAllNames&&e.names.length>1?sr.of(Ns([dt("("),o,r,dt(")")])):sr.of(xi(o,r))}case"Optional":return sr.map(Dl(e.usage,t),(r)=>Ns([dt("["),r,dt("]")]));case"Repeated":return sr.map(Dl(e.usage,t),(r)=>xi(r,dt("...")));case"Alternation":{if(e.left._tag==="Repeated"||e.right._tag==="Repeated"||e.left._tag==="Concat"||e.right._tag==="Concat")return sr.appendAll(Dl(e.left,t),Dl(e.right,t));return sr.flatMap(Dl(e.left,t),(r)=>sr.map(Dl(e.right,t),(n)=>Ns([r,dt("|"),n])))}case"Concat":{let r=Dl(e.left,t),n=Dl(e.right,t),o=sr.isNonEmptyReadonlyArray(r)&&sr.isNonEmptyReadonlyArray(n)?Os:ha;return sr.flatMap(r,(i)=>sr.map(n,(s)=>Ns([i,o,s])))}}};var fA=Symbol.for("@effect/cli/ValidationError"),Hc={[fA]:fA},np=(e)=>typeof e==="object"&&e!=null&&(fA in e),mA=(e)=>e._tag==="CommandMismatch";var yA=(e)=>e._tag==="HelpRequested";var hA=(e)=>e._tag==="MultipleValuesDetected";var gA=(e)=>e._tag==="MissingValue";var op=(e)=>{let t=Object.create(Hc);return t._tag="CommandMismatch",t.error=e,t},GD=(e)=>{let t=Object.create(Hc);return t._tag="CorrectedFlag",t.error=e,t},Ld=(e)=>{let t=Object.create(Hc);return t._tag="InvalidArgument",t.error=e,t},cs=(e)=>{let t=Object.create(Hc);return t._tag="InvalidValue",t.error=e,t},ux=(e)=>{let t=Object.create(Hc);return t._tag="MissingFlag",t.error=e,t},Qa=(e)=>{let t=Object.create(Hc);return t._tag="MissingValue",t.error=e,t};var QD=(e,t)=>{let r=Object.create(Hc);return r._tag="MultipleValuesDetected",r.error=e,r.values=t,r},JD=(e)=>{let t=Object.create(Hc);return t._tag="NoBuiltInMatch",t.error=e,t},SA=(e,t,r)=>{let n=Object.create(Hc);return n._tag="UnclusteredFlag",n.error=e,n.unclustered=t,n.rest=r,n};var _se="@effect/cli/Args",YD=Symbol.for(_se),dm={[YD]:{_A:(e)=>e},pipe(){return Cse(this,arguments)}},vA=(e)=>typeof e==="object"&&e!=null&&(YD in e),kse=(e)=>e,v2=(e)=>e._tag==="Empty";var Dse=(e)=>e._tag==="WithDefault";var XD=function(){if(arguments.length===1)if(vA(arguments[0]))return sp(arguments[0],(e)=>[e]);else if(ar.isArray(arguments[0]))return f2(arguments[0]);else{let e=Object.entries(arguments[0]),t=sp(e[0][1],(n)=>({[e[0][0]]:n}));if(e.length===1)return t;let r=e.slice(1);for(let[n,o]of r)t=sp(i0(t,o),([i,s])=>({...i,[n]:s}));return t}return f2(arguments[0])};var x2=(e)=>o0(qr.fromNullable(e?.name),iA("directory",e?.exists||"either"));var _h=(()=>{let e=Object.create(dm);return e._tag="Empty",e})();var E2=(e)=>o0(qr.fromNullable(e?.name),sA);var ZD=(e)=>Wc(e);var e0=(e)=>Ah(e),sp=Ph(2,(e,t)=>b2(e,(r)=>We.succeed(t(r)))),b2=Ph(2,(e,t)=>I2(e,t));var w2=(e)=>s0(sp(e,qr.some),qr.none()),T2=(e)=>P2(e,qr.none(),qr.none()),t0=Ph(3,(e,t,r)=>Vc(e,t,r));var r0=Ph(2,(e,t)=>{if(kse(e)&&Dse(e))return s0(r0(e.args,t),e.fallback);return R2(e,t)});var A2=Ph(2,(e,t)=>cm(e,t)),n0=Ph(2,(e,t)=>lm(e,t)),f2=(e)=>{if(e.length===0)return _h;if(e.length===1)return sp(e[0],(r)=>[r]);let t=sp(e[0],(r)=>[r]);for(let r=1;r<e.length;r++){let n=e[r];t=sp(i0(t,n),([o,i])=>[...o,i])}return t},Wc=(e)=>{switch(e._tag){case"Empty":return Qr;case"Single":return Zu([[oH(e.name),et(fe(aA(e.primitiveType)),e.description)]]);case"Map":return Wc(e.args);case"Both":return et(Wc(e.left),Wc(e.right));case"Variadic":{let t=Wc(e.args);return Rl(t,(r,n)=>{let o=Ih(e),i=Rh(e),s=dt(qr.isSome(e.max)?` ${o} - ${i}`:o===0?"...":` ${o}+`),a=fe(qr.isSome(e.max)?`This argument must be repeated at least ${o} times and may be repeated up to ${i} times.`:o===0?"This argument may be repeated zero or more times.":`This argument must be repeated at least ${o} times.`);return[xi(r,s),et(n,a)]})}case"WithDefault":return Rl(Wc(e.args),(t,r)=>{let n=qr.isOption(e.fallback)?qr.match(e.fallback,{onNone:()=>fe("This setting is optional."),onSome:(o)=>{let i=S2.isObject(o)?o:String(o),s=h2.toStringUnknown(i,0);return fe(`This setting is optional. Defaults to: ${s}`)}}):fe("This setting is optional.");return[t,et(r,n)]});case"WithFallbackConfig":return Rl(Wc(e.args),(t,r)=>[t,et(r,fe("This argument can be set from environment variables."))])}};var Ih=(e)=>{switch(e._tag){case"Empty":case"WithDefault":case"WithFallbackConfig":return 0;case"Single":return 1;case"Map":return Ih(e.args);case"Both":{let t=Ih(e.left),r=Ih(e.right);return t+r}case"Variadic":{let t=Ih(e.args);return Math.floor(qr.getOrElse(e.min,()=>0)*t)}}},Rh=(e)=>{switch(e._tag){case"Empty":return 0;case"Single":return 1;case"Map":case"WithDefault":case"WithFallbackConfig":return Rh(e.args);case"Both":{let t=Rh(e.left),r=Rh(e.right);return t+r}case"Variadic":{let t=Rh(e.args);return Math.floor(qr.getOrElse(e.max,()=>Number.MAX_SAFE_INTEGER/2)*t)}}},Ah=(e)=>{switch(e._tag){case"Empty":return Md;case"Single":return rp(ar.of(e.name),cx(e.primitiveType));case"Map":return Ah(e.args);case"Both":return Ol(Ah(e.left),Ah(e.right));case"Variadic":return dx(Ah(e.args));case"WithDefault":case"WithFallbackConfig":return lx(Ah(e.args))}},o0=(e,t,r=Qr)=>{let n=Object.create(dm);return n._tag="Single",n.name=`<${qr.getOrElse(e,()=>wh(t))}>`,n.pseudoName=e,n.primitiveType=t,n.description=r,n},I2=(e,t)=>{let r=Object.create(dm);return r._tag="Map",r.args=e,r.f=t,r},i0=(e,t)=>{let r=Object.create(dm);return r._tag="Both",r.left=e,r.right=t,r},s0=(e,t)=>{let r=Object.create(dm);return r._tag="WithDefault",r.args=e,r.fallback=t,r},R2=(e,t)=>{let r=Object.create(dm);return r._tag="WithFallbackConfig",r.args=e,r.config=t,r},P2=(e,t,r)=>{let n=Object.create(dm);return n._tag="Variadic",n.args=e,n.min=t,n.max=r,n},Vc=(e,t,r)=>{switch(e._tag){case"Empty":return We.succeed([t,void 0]);case"Single":return We.suspend(()=>ar.matchLeft(t,{onEmpty:()=>{let n=cx(e.primitiveType);if(qr.isSome(e.pseudoName)&&qr.isSome(n))return We.fail(Qa(fe(`Missing argument <${e.pseudoName.value}> with choices ${n.value}`)));if(qr.isSome(e.pseudoName))return We.fail(Qa(fe(`Missing argument <${e.pseudoName.value}>`)));if(qr.isSome(n))return We.fail(Qa(fe(`Missing argument ${wh(e.primitiveType)} with choices ${n.value}`)));return We.fail(Qa(fe(`Missing argument ${wh(e.primitiveType)}`)))},onNonEmpty:(n,o)=>Th(e.primitiveType,qr.some(n),r).pipe(We.mapBoth({onFailure:(i)=>Ld(fe(i)),onSuccess:(i)=>[o,i]}))}));case"Map":return Vc(e.args,t,r).pipe(We.flatMap(([n,o])=>We.matchEffect(e.f(o),{onFailure:(i)=>We.fail(Ld(i)),onSuccess:(i)=>We.succeed([n,i])})));case"Both":return Vc(e.left,t,r).pipe(We.flatMap(([n,o])=>Vc(e.right,n,r).pipe(We.map(([i,s])=>[i,[o,s]]))));case"Variadic":{let n=qr.getOrElse(e.min,()=>0),o=qr.getOrElse(e.max,()=>Number.MAX_SAFE_INTEGER),i=(s,a)=>{if(a.length>=o)return We.succeed([s,a]);return Vc(e.args,s,r).pipe(We.matchEffect({onFailure:(c)=>a.length>=n&&ar.isEmptyReadonlyArray(s)?We.succeed([s,a]):We.fail(c),onSuccess:([c,l])=>i(c,ar.append(a,l))}))};return i(t,ar.empty()).pipe(We.map(([s,a])=>[s,a]))}case"WithDefault":return Vc(e.args,t,r).pipe(We.catchTag("MissingValue",()=>We.succeed([t,e.fallback])));case"WithFallbackConfig":return Vc(e.args,t,r).pipe(We.catchTag("MissingValue",(n)=>We.map(We.catchAll(e.config,(o)=>{if(m2.isMissingDataOnly(o)){let i=fe(String(o)),s=cs(i);return We.fail(s)}return We.fail(n)}),(o)=>[t,o])))}},cm=(e,t)=>{switch(e._tag){case"Empty":return _h;case"Single":{let r=et(e.description,fe(t));return o0(e.pseudoName,e.primitiveType,r)}case"Map":return I2(cm(e.args,t),e.f);case"Both":return i0(cm(e.left,t),cm(e.right,t));case"Variadic":return P2(cm(e.args,t),e.min,e.max);case"WithDefault":return s0(cm(e.args,t),e.fallback);case"WithFallbackConfig":return R2(cm(e.args,t),e.config)}},lm=(e,t)=>{switch(e._tag){case"Empty":return We.succeed(ar.empty());case"Single":{let r=Wc(e);return cA(e.primitiveType,r).pipe(We.zipLeft(fx.log()),We.flatMap((n)=>{let o=ar.of(n);return Vc(e,o,t).pipe(We.as(o))}))}case"Map":return lm(e.args,t).pipe(We.tap((r)=>Vc(e.args,r,t)));case"Both":return We.zipWith(lm(e.left,t),lm(e.right,t),(r,n)=>ar.appendAll(r,n)).pipe(We.tap((r)=>Vc(e,r,t)));case"Variadic":{let r=fe("How many times should this argument should be repeated?"),n=mx(Wc(e),et(r));return xh({message:vr(n).trimEnd(),min:Ih(e),max:Rh(e)}).pipe(We.zipLeft(fx.log()),We.flatMap((o)=>o<=0?We.succeed(ar.empty()):Ch.make(ar.empty()).pipe(We.flatMap((i)=>lm(e.args,t).pipe(We.flatMap((s)=>Ch.update(i,ar.appendAll(s))),We.repeatN(o-1),We.zipRight(Ch.get(i)),We.tap((s)=>Vc(e,s,t)))))))}case"WithDefault":{let r=fe("This argument is optional - use the default?"),n=mx(Wc(e.args),et(r));return jc({message:vr(n).trimEnd(),choices:[{title:`Default ['${JSON.stringify(e.fallback)}']`,value:!0},{title:"Custom",value:!1}]}).pipe(We.zipLeft(fx.log()),We.flatMap((o)=>o?We.succeed(ar.empty()):lm(e.args,t)))}case"WithFallbackConfig":{let r=fe("Try load this option from the environment?"),n=mx(Wc(e.args),et(r));return jc({message:vr(n).trimEnd(),choices:[{title:"Use environment variables",value:!0},{title:"Custom",value:!1}]}).pipe(We.zipLeft(fx.log()),We.flatMap((o)=>o?We.succeed(ar.empty()):lm(e.args,t)))}}},a0=(e)=>{switch(e._tag){case"Empty":case"Both":return"";case"Single":return Al($c(e.description));case"Map":case"Variadic":case"WithDefault":case"WithFallbackConfig":return a0(e.args)}},yx=(e)=>{switch(e._tag){case"Empty":return ar.empty();case"Single":{let t=a0(e);return mx(lA(e.primitiveType),ar.appendAll(t.length===0?ar.empty():ar.of(`-d '${Pd(t)}'`)),ar.join(" "),ar.of)}case"Both":return mx(yx(e.left),ar.appendAll(yx(e.right)));case"Map":case"Variadic":case"WithDefault":case"WithFallbackConfig":return yx(e.args)}},ip=(e,t={multiple:!1,optional:!1})=>{switch(e._tag){case"Empty":return ar.empty();case"Single":{let r=t.multiple?"*":"",n=t.optional?"::":":",o=a0(e),i=o.length>0?` -- ${Pd(o)}`:"",s=dA(e.primitiveType);return s.length===0?ar.empty():ar.of(`${r}${n}${e.name}${i}${s}`)}case"Map":return ip(e.args,t);case"Both":{let r=ip(e.left,t),n=ip(e.right,t);return ar.appendAll(r,n)}case"Variadic":return qr.isSome(e.max)&&e.max.value>1?ip(e.args,{...t,multiple:!0}):ip(e.args,t);case"WithDefault":case"WithFallbackConfig":return ip(e.args,{...t,optional:!0})}};var C2=x2;var l0=w2;var Ose=T2;var ap=E2;var Nse=r0,Nl=A2;import*as Bl from"effect/Array";import*as bW from"effect/Context";import*as ym from"effect/Effect";import*as wW from"effect/Effectable";import{dual as Rx,identity as Aae}from"effect/Function";import{globalValue as Iae}from"effect/GlobalValue";import{pipeArguments as Rae}from"effect/Pipeable";import*as W from"effect/Array";import*as bx from"effect/Console";import*as de from"effect/Effect";import*as rW from"effect/Either";import{dual as mm,pipe as qo}from"effect/Function";import*as nW from"effect/HashMap";import*as oW from"effect/HashSet";import*as Mn from"effect/Option";import*as iW from"effect/Order";import{pipeArguments as sae}from"effect/Pipeable";import*as Qc from"effect/Ref";import*as pm from"effect/SynchronizedRef";var d0=fe;import*as j from"effect/Array";import*as N2 from"effect/Config";import*as TA from"effect/ConfigError";import*as hx from"effect/Console";import*as Q from"effect/Effect";import*as um from"effect/Either";import{dual as pp,pipe as dp}from"effect/Function";import*as Fn from"effect/HashMap";import*as F2 from"effect/Inspectable";import*as _e from"effect/Option";import*as Oh from"effect/Order";import*as U2 from"effect/ParseResult";import{pipeArguments as Lse}from"effect/Pipeable";import*as AA from"effect/Predicate";import*as Nh from"effect/Ref";var k2=(e,t,r)=>{if(e.length===0&&t.length===0)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;let n=e.length,o=t.length,i=Array(n),s=Zo(r,e),a=Zo(r,t);for(let c=0;c<=n;c++)i[c]=Array(o),i[c][0]=c;for(let c=0;c<=o;c++)i[0][c]=c;for(let c=1;c<=n;c++)for(let l=1;l<=o;l++){let d=s.charAt(c-1)===a.charAt(l-1)?0:1;i[c][l]=Math.min(i[c][l-1]+1,Math.min(i[c-1][l]+1,i[c-1][l-1]+d))}return i[n][o]};var D2=(e)=>ZT(e).pipe(Ud((t)=>t.split(e.delimiter||",")));var Bse="@effect/cli/Options",u0=Symbol.for(Bse),$d={[u0]:{_A:(e)=>e},pipe(){return Lse(this,arguments)}},IA=(e)=>typeof e==="object"&&e!=null&&(u0 in e);var M2=(e)=>e._tag==="Empty",$se=(e)=>e._tag==="Single";var qd=function(){if(arguments.length===1)if(IA(arguments[0]))return Kc(arguments[0],(e)=>[e]);else if(j.isArray(arguments[0]))return O2(arguments[0]);else{let e=Object.entries(arguments[0]),t=Kc(e[0][1],(n)=>({[e[0][0]]:n}));if(e.length===1)return t;let r=e.slice(1);for(let[n,o]of r)t=Kc(y0(t,o),([i,s])=>({...i,[n]:s}));return t}return O2(arguments[0])},qse={ifPresent:!0,negationNames:[],aliases:[]},Fh=(e,t)=>{let{aliases:r,ifPresent:n,negationNames:o}={...qse,...t},i=up(e,r,nA(_e.some(n)));if(j.isNonEmptyReadonlyArray(o)){let s=j.headNonEmpty(o),a=j.tailNonEmpty(o),c=up(s,a,nA(_e.some(!n)));return Sx(q2(i,c),!n)}return Sx(i,!n)},L2=(e,t)=>{let r=oA(j.map(t,(n)=>[n,n]));return up(e,j.empty(),r)},RA=(e,t)=>up(e,j.empty(),oA(t));var B2=(e,t)=>up(e,j.empty(),iA("directory",t?.exists??"either"));var vx=(()=>{let e=Object.create($d);return e._tag="Empty",e})();var $2=(e)=>up(e,j.empty(),sA);var p0=(e)=>xa(e);var f0=(e)=>Fl(e),Kc=pp(2,(e,t)=>V2(e,(r)=>um.right(t(r))));var xx=(e)=>Sx(Kc(e,_e.some),_e.none()),q2=pp(2,(e,t)=>j2(e,t).pipe(Kc(um.merge))),j2=pp(2,(e,t)=>z2(e,t));var PA=pp(3,(e,t,r)=>Q2(t,xA(e),r).pipe(Q.flatMap(([n,o,i])=>va(e,i,r).pipe(Q.catchAll((s)=>_e.match(n,{onNone:()=>Q.fail(s),onSome:(a)=>Q.fail(a)})),Q.map((s)=>[n,o,s]))))),H2=(e)=>K2(e,_e.none(),_e.none()),CA=pp(2,(e,t)=>Bd(e,(r)=>{let n=j.append(r.aliases,t);return up(r.name,n,r.primitiveType,r.description,r.pseudoName)})),Sx=pp(2,(e,t)=>G2(e,t));var fp=pp(2,(e,t)=>Bd(e,(r)=>{let n=et(r.description,fe(t));return up(r.name,r.aliases,r.primitiveType,n,r.pseudoName)}));var m0=pp(2,(e,t)=>zc(e,t)),O2=(e)=>{if(e.length===0)return vx;if(e.length===1)return Kc(e[0],(r)=>[r]);let t=Kc(e[0],(r)=>[r]);for(let r=1;r<e.length;r++){let n=e[r];t=Kc(y0(t,n),([o,i])=>[...o,i])}return t},xa=(e)=>{switch(e._tag){case"Empty":return Qr;case"Single":return Zu(j.of([$c(uA(Fl(e))),et(fe(aA(e.primitiveType)),e.description)]));case"KeyValueMap":{let t=_e.getOrThrow(Ml(e.argumentOption));return Rl(xa(e.argumentOption),(r,n)=>{let o=fe("This setting is a property argument which:"),i=`${t} key1=value key2=value2`,s=`${t} key1=value ${t} key2=value2`,a=rx([fe(`May be specified a single time: '${i}'`),fe(`May be specified multiple times: '${s}'`)]),c=dp(n,et(o),et(a));return[r,c]})}case"Map":return xa(e.options);case"Both":case"OrElse":return et(xa(e.left),xa(e.right));case"Variadic":{let t=xa(e.argumentOption);return Rl(t,(r,n)=>{let o=cp(e),i=lp(e),s=dt(_e.isSome(e.max)?` ${o} - ${i}`:o===0?"...":` ${o}+`),a=fe(_e.isSome(e.max)?`This option must be repeated at least ${o} times and may be repeated up to ${i} times.`:o===0?"This option may be repeated zero or more times.":`This option must be repeated at least ${o} times.`);return[xi(r,s),et(n,a)]})}case"WithDefault":return Rl(xa(e.options),(t,r)=>{let n=_e.isOption(e.fallback)?_e.match(e.fallback,{onNone:()=>fe("This setting is optional."),onSome:(o)=>{let i=AA.isObject(o)?o:String(o),s=F2.toStringUnknown(i,0);return fe(`This setting is optional. Defaults to: ${s}`)}}):fe("This setting is optional.");return[t,et(r,n)]});case"WithFallback":{let t=N2.isConfig(e.effect)?fe("This option can be set from environment variables."):ND(e.effect)?fe("Will prompt the user for input if this option is not provided."):Qr;return Rl(xa(e.options),(r,n)=>[r,et(n,t)])}}},Ml=(e)=>{switch(e._tag){case"Empty":return _e.none();case"Single":return _e.some(e.fullName);case"Both":case"OrElse":{let t=j.getSomes([Ml(e.left),Ml(e.right)]);return j.match(t,{onEmpty:()=>_e.none(),onNonEmpty:(r)=>_e.some(j.join(r,", "))})}case"KeyValueMap":case"Variadic":return Ml(e.argumentOption);case"Map":case"WithFallback":case"WithDefault":return Ml(e.options)}},cp=(e)=>{switch(e._tag){case"Empty":case"WithDefault":case"WithFallback":return 0;case"Single":case"KeyValueMap":return 1;case"Map":return cp(e.options);case"Both":{let t=cp(e.left),r=cp(e.right);return t+r}case"OrElse":{let t=cp(e.left),r=cp(e.right);return Math.min(t,r)}case"Variadic":{let t=_e.getOrElse(e.min,()=>0),r=cp(e.argumentOption);return t*r}}},lp=(e)=>{switch(e._tag){case"Empty":return 0;case"Single":return 1;case"KeyValueMap":return Number.MAX_SAFE_INTEGER;case"Map":case"WithDefault":case"WithFallback":return lp(e.options);case"Both":{let t=lp(e.left),r=lp(e.right);return t+r}case"OrElse":{let t=lp(e.left),r=lp(e.right);return Math.min(t,r)}case"Variadic":{let t=_e.getOrElse(e.max,()=>Number.MAX_SAFE_INTEGER/2),r=lp(e.argumentOption);return Math.floor(t*r)}}},Fl=(e)=>{switch(e._tag){case"Empty":return Md;case"Single":{let t=ix(e.primitiveType)?_e.none():_e.orElse(cx(e.primitiveType),()=>_e.some(e.placeholder));return rp(Ea(e),t)}case"KeyValueMap":return Fl(e.argumentOption);case"Map":return Fl(e.options);case"Both":return Ol(Fl(e.left),Fl(e.right));case"OrElse":return zD(Fl(e.left),Fl(e.right));case"Variadic":return dx(Fl(e.argumentOption));case"WithDefault":case"WithFallback":return lx(Fl(e.options))}},EA=(e)=>{switch(e._tag){case"Single":return ix(e.primitiveType);case"Map":return EA(e.options);case"WithDefault":return EA(e.options);default:return!1}},y0=(e,t)=>{let r=Object.create($d);return r._tag="Both",r.left=e,r.right=t,r},W2=(e)=>e.length===1?[!0,`-${e}`]:[!1,`--${e}`],jse=(e)=>{let t=Object.create($d);return t._tag="KeyValueMap",t.argumentOption=e,t},V2=(e,t)=>{let r=Object.create($d);return r._tag="Map",r.options=e,r.f=t,r},z2=(e,t)=>{let r=Object.create($d);return r._tag="OrElse",r.left=e,r.right=t,r},up=(e,t,r,n=Qr,o=_e.none())=>{let i=Object.create($d);return i._tag="Single",i.name=e,i.fullName=W2(e)[1],i.placeholder=`${_e.getOrElse(o,()=>wh(r))}`,i.aliases=t,i.primitiveType=r,i.description=n,i.pseudoName=o,i},K2=(e,t,r)=>{if(!$se(e))throw Error("InvalidArgumentException: only single options can be variadic");let n=Object.create($d);return n._tag="Variadic",n.argumentOption=e,n.min=t,n.max=r,n},G2=(e,t)=>{let r=Object.create($d);return r._tag="WithDefault",r.options=e,r.fallback=t,r},Hse=(e,t)=>{let r=Object.create($d);return r._tag="WithFallback",r.options=e,r.effect=t,r},Bd=(e,t)=>{switch(e._tag){case"Empty":return vx;case"Single":return t(e);case"KeyValueMap":return jse(t(e.argumentOption));case"Map":return V2(Bd(e.options,t),e.f);case"Both":return y0(Bd(e.left,t),Bd(e.right,t));case"OrElse":return z2(Bd(e.left,t),Bd(e.right,t));case"Variadic":return K2(t(e.argumentOption),e.min,e.max);case"WithDefault":return G2(Bd(e.options,t),e.fallback);case"WithFallback":return Hse(Bd(e.options,t),e.effect)}},Ea=(e)=>{let t=(n)=>{switch(n._tag){case"Empty":return j.empty();case"Single":return j.prepend(n.aliases,n.name);case"KeyValueMap":case"Variadic":return t(n.argumentOption);case"Map":case"WithDefault":case"WithFallback":return t(n.options);case"Both":case"OrElse":{let o=t(n.left),i=t(n.right);return j.appendAll(o,i)}}},r=Oh.mapInput(Oh.boolean,(n)=>!n[0]);return dp(t(e),j.map((n)=>W2(n)),j.sort(r),j.map((n)=>n[1]))},xA=(e)=>{switch(e._tag){case"Empty":return j.empty();case"Single":case"KeyValueMap":case"Variadic":return j.of(e);case"Map":case"WithDefault":case"WithFallback":return xA(e.options);case"Both":case"OrElse":return j.appendAll(xA(e.left),xA(e.right))}},Wse=/=(.*)/,va=(e,t,r)=>{switch(e._tag){case"Empty":return Q.void;case"Single":{let n=j.filterMap(Ea(e),(i)=>Fn.get(t,i));if(j.isNonEmptyReadonlyArray(n)){let i=j.headNonEmpty(n),s=j.tailNonEmpty(n);if(j.isEmptyReadonlyArray(s)){if(j.isEmptyReadonlyArray(i))return Th(e.primitiveType,_e.none(),r).pipe(Q.mapError((c)=>cs(fe(c))));if(j.isNonEmptyReadonlyArray(i)&&j.isEmptyReadonlyArray(j.tailNonEmpty(i))){let c=j.headNonEmpty(i);return Th(e.primitiveType,_e.some(c),r).pipe(Q.mapError((l)=>cs(fe(l))))}return Q.fail(QD(Qr,i))}let a=fe(`More than one reference to option '${e.fullName}' detected`);return Q.fail(cs(a))}let o=fe(`Expected to find option: '${e.fullName}'`);return Q.fail(Qa(o))}case"KeyValueMap":{let n=(o)=>{let i=o.trim().split(Wse,2);if(j.isNonEmptyReadonlyArray(i)&&i.length===2&&i[1]!=="")return Q.succeed(i);let s=fe(`Expected a key/value pair but received '${o}'`);return Q.fail(Ld(s))};return va(e.argumentOption,t,r).pipe(Q.matchEffect({onFailure:(o)=>hA(o)?Q.forEach(o.values,(i)=>n(i)).pipe(Q.map(Fn.fromIterable)):Q.fail(o),onSuccess:(o)=>n(o).pipe(Q.map(Fn.make))}))}case"Map":return va(e.options,t,r).pipe(Q.flatMap((n)=>e.f(n)));case"Both":return va(e.left,t,r).pipe(Q.catchAll((n)=>va(e.right,t,r).pipe(Q.matchEffect({onFailure:(o)=>{let i=et(n.error,o.error);return Q.fail(Qa(i))},onSuccess:()=>Q.fail(n)}))),Q.zip(va(e.right,t,r)));case"OrElse":return va(e.left,t,r).pipe(Q.matchEffect({onFailure:(n)=>va(e.right,t,r).pipe(Q.mapBoth({onFailure:(o)=>gA(n)&&gA(o)?Qa(et(n.error,o.error)):cs(et(n.error,o.error)),onSuccess:(o)=>um.right(o)})),onSuccess:(n)=>va(e.right,t,r).pipe(Q.matchEffect({onFailure:()=>Q.succeed(um.left(n)),onSuccess:()=>{let o=_e.getOrElse(Ml(e.left),()=>"???"),i=_e.getOrElse(Ml(e.right),()=>"???"),s=fe(`Collision between two options detected - you can only specify one of either: ['${o}', '${i}']`);return Q.fail(cs(s))}}))}));case"Variadic":{let n=_e.getOrElse(e.min,()=>0),o=_e.getOrElse(e.max,()=>Number.MAX_SAFE_INTEGER),i=j.filterMap(Ea(e),(a)=>Fn.get(t,a)),s=(a)=>{if(a.length<n){let d=e.argumentOption.fullName,u=`Expected at least ${n} value(s) for option: '${d}'`;return Q.fail(cs(fe(u)))}if(a.length>o){let d=e.argumentOption.fullName,u=`Expected at most ${o} value(s) for option: '${d}'`;return Q.fail(cs(fe(u)))}let c=e.argumentOption.primitiveType,l=(d)=>Th(c,_e.some(d),r).pipe(Q.mapError((u)=>cs(fe(u))));return Q.forEach(a,(d)=>l(d))};if(j.every(i,j.isEmptyReadonlyArray))return s(j.empty());return va(e.argumentOption,t,r).pipe(Q.matchEffect({onFailure:(a)=>hA(a)?s(a.values):Q.fail(a),onSuccess:(a)=>s(j.of(a))}))}case"WithDefault":return va(e.options,t,r).pipe(Q.catchTag("MissingValue",()=>Q.succeed(e.fallback)));case"WithFallback":return va(e.options,t,r).pipe(Q.catchTag("MissingValue",(n)=>e.effect.pipe(Q.catchAll((o)=>{if(AA.isTagged(o,"QuitException"))return Q.die(o);if(TA.isConfigError(o)&&!TA.isMissingDataOnly(o)){let i=fe(String(o)),s=cs(i);return Q.fail(s)}return Q.fail(n)}))))}},zc=(e,t)=>{switch(e._tag){case"Empty":return Q.succeed(j.empty());case"Single":{let r=xa(e);return cA(e.primitiveType,r).pipe(Q.flatMap((n)=>{let o=j.make(Ea(e)[0],n);return J2(e,o,t).pipe(Q.as(o))}),Q.zipLeft(hx.log()))}case"KeyValueMap":{let r=fe("Enter `key=value` pairs separated by spaces");return D2({message:vr(r).trim(),delimiter:" "}).pipe(Q.flatMap((n)=>{let o=_e.getOrElse(Ml(e),()=>"");return va(e,Fn.make([o,n]),t).pipe(Q.as(j.prepend(n,o)))}),Q.zipLeft(hx.log()))}case"Map":return zc(e.options,t);case"Both":return Q.zipWith(zc(e.left,t),zc(e.right,t),(r,n)=>j.appendAll(r,n));case"OrElse":{let r=fe("Select which option you would like to use"),n=dp(xa(e),et(r)),o=(s,a)=>({title:s,value:a}),i=j.getSomes([_e.map(Ml(e.left),(s)=>o(s,e.left)),_e.map(Ml(e.right),(s)=>o(s,e.right))]);return jc({message:vr(n).trimEnd(),choices:i}).pipe(Q.flatMap((s)=>zc(s,t)))}case"Variadic":{let r=fe("How many times should this argument be repeated?"),n=dp(xa(e),et(r));return xh({message:vr(n).trimEnd(),min:cp(e),max:lp(e)}).pipe(Q.flatMap((o)=>o<=0?Q.succeed(j.empty()):Nh.make(j.empty()).pipe(Q.flatMap((i)=>zc(e.argumentOption,t).pipe(Q.flatMap((s)=>Nh.update(i,j.appendAll(s))),Q.repeatN(o-1),Q.zipRight(Nh.get(i)))))))}case"WithDefault":{if(EA(e.options))return zc(e.options,t);let r=fe("This option is optional - use the default?"),n=dp(xa(e.options),et(r));return jc({message:vr(n).trimEnd(),choices:[{title:"Yes",value:!0,description:`use the default ${_e.isOption(e.fallback)?_e.match(e.fallback,{onNone:()=>"",onSome:(o)=>`(${JSON.stringify(o)})`}):`(${JSON.stringify(e.fallback)})`}`},{title:"No",value:!1,description:"use a custom value"}]}).pipe(Q.zipLeft(hx.log()),Q.flatMap((o)=>o?Q.succeed(j.empty()):zc(e.options,t)))}case"WithFallback":{if(EA(e.options))return zc(e.options,t);if(ND(e.effect))return zc(e.options,t);let r=fe("Try load this option from the environment?"),n=dp(xa(e.options),et(r));return jc({message:vr(n).trimEnd(),choices:[{title:"Use environment variables",value:!0},{title:"Custom",value:!1}]}).pipe(Q.zipLeft(hx.log()),Q.flatMap((o)=>o?Q.succeed(j.empty()):zc(e.options,t)))}}},Q2=(e,t,r)=>{if(j.isNonEmptyReadonlyArray(t))return gx(e,t,r).pipe(Q.flatMap(([n,o,i])=>{if(Fn.isEmpty(i))return Q.succeed([_e.none(),e,i]);return Q2(n,o,r).pipe(Q.map(([s,a,c])=>[s,a,h0(i,j.fromIterable(c))]))}),Q.catchAll((n)=>Q.succeed([_e.some(n),e,Fn.empty()])));return j.isEmptyReadonlyArray(e)?Q.succeed([_e.none(),j.empty(),Fn.empty()]):Q.succeed([_e.none(),e,Fn.empty()])},gx=(e,t,r)=>j.matchLeft(t,{onEmpty:()=>Q.succeed([e,j.empty(),Fn.empty()]),onNonEmpty:(n,o)=>J2(n,e,r).pipe(Q.flatMap(({leftover:i,parsed:s})=>_e.match(s,{onNone:()=>gx(i,o,r).pipe(Q.map(([a,c,l])=>[a,j.prepend(c,n),l])),onSome:({name:a,values:c})=>Q.succeed([i,o,Fn.make([a,c])])})),Q.catchTags({CorrectedFlag:(i)=>gx(e,o,r).pipe(Q.catchSome(()=>_e.some(Q.fail(i))),Q.flatMap(([s,a,c])=>Q.fail(i).pipe(Q.when(()=>Fn.isEmpty(c)),Q.as([s,j.prepend(a,n),c])))),MissingFlag:()=>gx(e,o,r).pipe(Q.map(([i,s,a])=>[i,j.prepend(s,n),a])),UnclusteredFlag:(i)=>Y2(i.unclustered,i.rest,t,r).pipe(Q.catchAll(()=>Q.fail(i)))}))}),Vse=/^-{1}([^-]{2,}$)/,bA=/^(--[^=]+)(?:=(.+))?$/,zse=(e)=>j.matchLeft(e,{onEmpty:()=>Q.succeed(j.empty()),onNonEmpty:(t,r)=>{let n=t.trim();if(Vse.test(n)){let o=n.substring(1).split("").map((i)=>`-${i}`);return Q.fail(SA(Qr,o,r))}if(bA.test(n)){let o=bA.exec(n);if(o!==null&&o[2]!==void 0)return Q.succeed(j.appendAll([o[1],o[2]],r))}return Q.succeed(e)}}),J2=(e,t,r)=>{switch(e._tag){case"Single":return zse(t).pipe(Q.flatMap((n)=>j.matchLeft(n,{onEmpty:()=>{let o=fe(`Expected to find option: '${e.fullName}'`);return Q.fail(ux(o))},onNonEmpty:(o,i)=>{let s=(w)=>Zo(r,w),a=s(o),c=j.map(Ea(e),(w)=>s(w));if(j.contains(c,a)){if(ix(e.primitiveType))return j.matchLeft(i,{onEmpty:()=>{let w=_e.some({name:o,values:j.empty()});return Q.succeed({parsed:w,leftover:i})},onNonEmpty:(w,_)=>{if(sx(w)){let b=_e.some({name:o,values:j.of("true")});return Q.succeed({parsed:b,leftover:_})}if(ax(w)){let b=_e.some({name:o,values:j.of("false")});return Q.succeed({parsed:b,leftover:_})}let T=_e.some({name:o,values:j.empty()});return Q.succeed({parsed:T,leftover:i})}});return j.matchLeft(i,{onEmpty:()=>{let w=fe(`Expected a value following option: '${e.fullName}'`);return Q.fail(Qa(w))},onNonEmpty:(w,_)=>{let T=_e.some({name:o,values:j.of(w)});return Q.succeed({parsed:T,leftover:_})}})}if(o.startsWith("-")){if(e.name.length>r.autoCorrectLimit+1&&k2(o,e.fullName,r)<=r.autoCorrectLimit){let _=fe(`The flag '${o}' is not recognized. Did you mean '${e.fullName}'?`);return Q.fail(GD(_))}let w=fe(`Expected to find option: '${e.fullName}'`);return Q.fail(ux(w))}let l=-1,d=void 0;for(let w=0;w<i.length;w++){let _=i[w],T=s(_);if(j.contains(c,T)){l=w;break}let b=bA.exec(_);if(b!==null){let I=s(b[1]);if(j.contains(c,I)){l=w,d=b[2];break}}}if(l===-1){let w=fe(`Expected to find option: '${e.fullName}'`);return Q.fail(ux(w))}let u=i[l],p=d!==void 0?bA.exec(u)[1]:u,y=j.prepend(i.slice(0,l),o),g=i.slice(l+1);if(ix(e.primitiveType)){if(d!==void 0){if(sx(d)){let T=_e.some({name:p,values:j.of("true")}),b=j.appendAll(y,g);return Q.succeed({parsed:T,leftover:b})}if(ax(d)){let T=_e.some({name:p,values:j.of("false")}),b=j.appendAll(y,g);return Q.succeed({parsed:T,leftover:b})}}if(g.length>0){let T=g[0];if(sx(T)){let b=_e.some({name:p,values:j.of("true")}),I=j.appendAll(y,g.slice(1));return Q.succeed({parsed:b,leftover:I})}if(ax(T)){let b=_e.some({name:p,values:j.of("false")}),I=j.appendAll(y,g.slice(1));return Q.succeed({parsed:b,leftover:I})}}let w=_e.some({name:p,values:j.empty()}),_=j.appendAll(y,g);return Q.succeed({parsed:w,leftover:_})}if(d!==void 0){let w=_e.some({name:p,values:j.of(d)}),_=j.appendAll(y,g);return Q.succeed({parsed:w,leftover:_})}if(g.length===0){let w=fe(`Expected a value following option: '${e.fullName}'`);return Q.fail(Qa(w))}let E=g[0],S=_e.some({name:p,values:j.of(E)}),x=j.appendAll(y,g.slice(1));return Q.succeed({parsed:S,leftover:x})}})));case"KeyValueMap":{let n=j.map(Ea(e.argumentOption),(o)=>Zo(r,o));return j.matchLeft(t,{onEmpty:()=>Q.succeed({parsed:_e.none(),leftover:t}),onNonEmpty:(o,i)=>{let s=(E)=>{let S=j.empty(),x=E;while(j.isNonEmptyReadonlyArray(x)){let w=j.headNonEmpty(x).trim(),_=Zo(r,w);if(x.length>=2&&j.contains(n,_)){let T=x[1].trim(),[b,I]=T.split("=");if(b!==void 0&&I!==void 0&&I.length>0){S=j.append(S,T),x=x.slice(2);continue}}if(w.includes("=")){let[T,b]=w.split("=");if(T!==void 0&&b!==void 0&&b.length>0){S=j.append(S,w),x=x.slice(1);continue}}break}return[S,x]},a=Zo(r,o);if(j.contains(n,a)){let[E,S]=s(i);return Q.succeed({parsed:_e.some({name:o,values:E}),leftover:S})}if(o.startsWith("-"))return Q.succeed({parsed:_e.none(),leftover:t});let c=-1;for(let E=0;E<i.length;E++){let S=i[E],x=Zo(r,S);if(j.contains(n,x)){c=E;break}}if(c===-1)return Q.succeed({parsed:_e.none(),leftover:t});let l=i[c],d=j.prepend(i.slice(0,c),o),u=i.slice(c+1),[p,y]=s(u),g=j.appendAll(d,y);return Q.succeed({parsed:_e.some({name:l,values:p}),leftover:g})}})}case"Variadic":{let n=j.map(Ea(e.argumentOption),(l)=>Zo(r,l)),o=void 0,i=j.empty(),s=t,a=j.empty();while(j.isNonEmptyReadonlyArray(s)){let l=j.headNonEmpty(s),d=Zo(r,l);if(j.contains(n,d)){if(o===void 0)o=l;let u=s[1];if(u!==void 0&&u.length>0)i=j.append(i,u.trim());s=s.slice(2)}else a=j.append(a,j.headNonEmpty(s)),s=s.slice(1)}let c=_e.fromNullable(o).pipe(_e.orElse(()=>_e.some(e.argumentOption.fullName)),_e.map((l)=>({name:l,values:i})));return Q.succeed({parsed:c,leftover:a})}}},Y2=(e,t,r,n)=>{if(j.isNonEmptyReadonlyArray(e)){let o=j.headNonEmpty(e),i=j.tailNonEmpty(e);return gx(j.of(o),r,n).pipe(Q.flatMap(([s,a,c])=>{if(Fn.isEmpty(c))return Q.fail(SA(Qr,j.empty(),t));return Y2(i,t,a,n).pipe(Q.map(([l,d,u])=>[t,d,h0(c,j.fromIterable(u))]))}))}return Q.succeed([t,r,Fn.empty()])},h0=(e,t)=>{if(j.isNonEmptyReadonlyArray(t)){let r=j.headNonEmpty(t),n=j.tailNonEmpty(t),o=_e.match(Fn.get(e,r[0]),{onNone:()=>Fn.set(e,r[0],r[1]),onSome:(i)=>Fn.set(e,r[0],j.appendAll(i,r[1]))});return h0(o,n)}return e},Kse=(e)=>Pd(e.replaceAll("\\","\\\\")).replaceAll("[","\\[").replaceAll("]","\\]").replaceAll(":","\\:").replaceAll("$","\\$").replaceAll("`","\\`").replaceAll("(","\\(").replaceAll(")","\\)"),wA=(e)=>{switch(e._tag){case"Empty":case"Both":case"OrElse":return"";case"Single":return Al($c(e.description));case"KeyValueMap":case"Variadic":return wA(e.argumentOption);case"Map":case"WithDefault":case"WithFallback":return wA(e.options)}},kh=(e)=>{switch(e._tag){case"Empty":return j.empty();case"Single":{let t=Ea(e),r=j.join(t,"|"),n=d2(e.primitiveType);return j.make(`${r})`,` COMPREPLY=( ${n} )`," return 0"," ;;")}case"KeyValueMap":case"Variadic":return kh(e.argumentOption);case"Map":case"WithDefault":case"WithFallback":return kh(e.options);case"Both":case"OrElse":{let t=kh(e.left),r=kh(e.right);return j.appendAll(t,r)}}},Dh=(e)=>{switch(e._tag){case"Empty":return j.empty();case"Single":{let t=wA(e),r=Oh.mapInput(Oh.boolean,(n)=>!n[0]);return dp(j.prepend(e.aliases,e.name),j.map((n)=>[n.length===1,n]),j.sort(r),j.flatMap(([n,o])=>j.make(n?"-s":"-l",o)),j.appendAll(lA(e.primitiveType)),j.appendAll(t.length===0?j.empty():j.of(`-d '${Pd(t)}'`)),j.join(" "),j.of)}case"KeyValueMap":case"Variadic":return Dh(e.argumentOption);case"Map":case"WithDefault":case"WithFallback":return Dh(e.options);case"Both":case"OrElse":return dp(Dh(e.left),j.appendAll(Dh(e.right)))}},Ul=(e,t={conflicts:j.empty(),multiple:!1})=>{switch(e._tag){case"Empty":return j.empty();case"Single":{let r=Ea(e),n=wA(e),o=dA(e.primitiveType),i=t.multiple?"*":"",s=j.isNonEmptyReadonlyArray(t.conflicts)?`(${j.join(t.conflicts," ")})`:"";return j.map(r,(a)=>`${s}${i}${a}[${Kse(n)}]${o}`)}case"KeyValueMap":return Ul(e.argumentOption,{...t,multiple:!0});case"Map":case"WithDefault":case"WithFallback":return Ul(e.options,t);case"Both":{let r=Ul(e.left,t),n=Ul(e.right,t);return j.appendAll(r,n)}case"OrElse":{let r=Ea(e.left),n=Ea(e.right),o=Ul(e.left,{...t,conflicts:j.appendAll(t.conflicts,n)}),i=Ul(e.right,{...t,conflicts:j.appendAll(t.conflicts,r)});return j.appendAll(o,i)}case"Variadic":return _e.isSome(e.max)&&e.max.value>1?Ul(e.argumentOption,{...t,multiple:!0}):Ul(e.argumentOption,t)}};var g0=qd,mp=Fh,X2=L2;var Gse=B2;var fr=$2;var Un=xx;var Qse=H2;var Jse=CA,Ll=Sx;var At=fp;import*as Z2 from"effect/LogLevel";import*as Gc from"effect/Option";var Yse=(e)=>({_tag:"SetLogLevel",level:e}),Xse=(e)=>({_tag:"ShowCompletions",shellType:e}),Uh=(e,t)=>({_tag:"ShowHelp",usage:e,helpDoc:t}),v0=(e)=>({_tag:"ShowWizard",command:e}),Zse={_tag:"ShowVersion"};var x0=(e)=>e._tag==="ShowHelp",E0=(e)=>e._tag==="ShowWizard";var eae=RA("completions",[["sh","bash"],["bash","bash"],["fish","fish"],["zsh","zsh"]]).pipe(xx,fp("Generate a completion script for a specific shell.")),tae=RA("log-level",Z2.allLevels.map((e)=>[e._tag.toLowerCase(),e])).pipe(xx,fp("Sets the minimum log level for a command.")),rae=Fh("help").pipe(CA("h"),fp("Show the help documentation for a command.")),nae=Fh("version").pipe(fp("Show the version of the application.")),oae=Fh("wizard").pipe(fp("Start wizard mode for a command.")),jd=qd({completions:eae,logLevel:tae,help:rae,wizard:oae,version:nae}),eW=(e,t,r)=>Kc(jd,(n)=>{if(Gc.isSome(n.completions))return Gc.some(Xse(n.completions.value));if(Gc.isSome(n.logLevel))return Gc.some(Yse(n.logLevel.value));if(n.help)return Gc.some(Uh(t,r));if(n.wizard)return Gc.some(v0(e));if(n.version)return Gc.some(Zse);return Gc.none()});import{dual as n$e}from"effect/Function";var Ex=(e)=>({_tag:"BuiltIn",option:e}),Hd=(e,t)=>({_tag:"UserDefined",leftover:e,value:t}),b0=(e)=>e._tag==="BuiltIn",kA=(e)=>e._tag==="UserDefined";var aae="@effect/cli/CommandDescriptor",sW=Symbol.for(aae),Mh={[sW]:{_A:(e)=>e},pipe(){return sae(this,arguments)}},aW=(e)=>typeof e==="object"&&e!=null&&(sW in e),fm=(e)=>e._tag==="Standard";var cW=(e,t=vx,r=_h)=>{let n=Object.create(Mh);return n._tag="Standard",n.name=e,n.description=Qr,n.options=t,n.args=r,n};var T0=(e,t)=>Tx(e,t),Ax=(e)=>oW.fromIterable(yp(e)),A0=(e,t)=>pae(e,t),I0=(e,t)=>fae(e,t),R0=(e,t)=>mae(e,t),P0=(e)=>nW.fromIterable(Ix(e)),C0=(e)=>Lh(e),_0=mm(2,(e,t)=>lW(e,(r)=>rW.right(t(r)))),lW=mm(2,(e,t)=>{let r=Object.create(Mh);return r._tag="Map",r.command=e,r.f=t,r}),dW=mm(3,(e,t,r)=>wx(e,t,r)),uW=mm(2,(e,t)=>w0(e,t)),pW=mm(2,(e,t)=>{let r=Object.create(Mh);return r._tag="Subcommands",r.parent=e,r.children=W.map(t,([n,o])=>_0(o,(i)=>[n,i])),r}),k0=mm(3,(e,t,r)=>uae(e,t,r)),Tx=(e,t)=>{switch(e._tag){case"Standard":{let r=Xu(e.description)?Qr:et(qc("DESCRIPTION"),e.description),n=ZD(e.args),o=Xu(n)?Qr:et(qc("ARGUMENTS"),n),i=t.showBuiltIns?g0([e.options,jd]):e.options,s=p0(i),a=Xu(s)?Qr:et(qc("OPTIONS"),s);return et(r,et(o,a))}case"GetUserInput":return Xu(e.description)?Qr:et(qc("DESCRIPTION"),e.description);case"Map":return Tx(e.command,t);case"Subcommands":{let r=(o,i)=>{switch(o._tag){case"Standard":case"GetUserInput":{let s=$c(uA(Lh(o))),a=W.append(i,s),c=W.reduce(a,ha,(d,u)=>PD(d)&&d.value===""?u:PD(u)&&u.value===""?d:Ns([d,Os,u])),l=$c(o.description);return W.of([c,l])}case"Map":return r(o.command,i);case"Subcommands":{let s=r(o.parent,i);return Mn.match(W.head(s),{onNone:()=>W.flatMap(o.children,(a)=>r(a,i)),onSome:([a])=>{let c=W.flatMap(o.children,(l)=>r(l,W.append(i,a)));return W.appendAll(s,c)}})}}},n=(o)=>{let i=W.reduceRight(o,0,(a,[c])=>Math.max(em(c),a)),s=W.map(o,([a,c])=>fe(Ns([a,dt(" ".repeat(i-em(a)+2)),c])));if(W.isNonEmptyReadonlyArray(s))return rx(s);throw Error("[BUG]: Subcommands.usage - received empty list of subcommands to print")};return et(Tx(e.parent,t),et(qc("COMMANDS"),n(W.flatMap(e.children,(o)=>r(o,W.empty())))))}}},yp=(e)=>{switch(e._tag){case"Standard":case"GetUserInput":return W.of(e.name);case"Map":return yp(e.command);case"Subcommands":return yp(e.parent)}},Ix=(e)=>{let t=(r,n)=>{switch(r._tag){case"Standard":case"GetUserInput":return W.of([r.name,r]);case"Map":return t(r.command,n);case"Subcommands":return n?t(r.parent,!1):W.flatMap(r.children,(o)=>t(o,!0))}};return t(e,!1)},Lh=(e)=>{switch(e._tag){case"Standard":return Ol(rp(W.of(e.name),Mn.none()),Ol(f0(e.options),e0(e.args)));case"GetUserInput":return rp(W.of(e.name),Mn.none());case"Map":return Lh(e.command);case"Subcommands":return Ol(Lh(e.parent),VD)}},wx=(e,t,r)=>{let n=(o,i)=>W.matchLeft(i,{onEmpty:()=>{let s=fe(`Missing command name: '${o.name}'`);return de.fail(op(s))},onNonEmpty:(s,a)=>{let c=Zo(r,s),l=Zo(r,o.name);return de.succeed(a).pipe(de.when(()=>c===l),de.flatten,de.catchTag("NoSuchElementException",()=>{let d=fe(`Missing command name: '${o.name}'`);return de.fail(op(d))}))}});switch(e._tag){case"Standard":{let o=(a)=>W.matchLeft(a,{onEmpty:()=>{let c=fe(`Missing command name: '${e.name}'`);return de.fail(op(c))},onNonEmpty:(c)=>{let l=Zo(r,c),d=Zo(r,e.name);if(l===d){let p=Tx(e,r),y=Lh(e),g=eW(e,y,p),E=W.drop(a,1);return PA(g,E,r).pipe(de.flatMap((S)=>S[2]),de.catchTag("NoSuchElementException",()=>{let S=fe("No built-in option was matched");return de.fail(JD(S))}),de.map(Ex))}let u=fe(`Missing command name: '${e.name}'`);return de.fail(op(u))}}),i=(a)=>n(e,a).pipe(de.flatMap((c)=>{let[l,d]=cae(c);return PA(e.options,l,r).pipe(de.flatMap(([u,p,y])=>t0(e.args,W.appendAll(p,d),r).pipe(de.catchAll((g)=>Mn.match(u,{onNone:()=>de.fail(g),onSome:(E)=>de.fail(E)})),de.map(([g,E])=>Hd(g,{name:e.name,options:y,args:E})))))})),s=(a)=>{if(W.contains(a,"--help")||W.contains(a,"-h"))return o(W.make(e.name,"--help"));if(W.contains(a,"--wizard"))return o(W.make(e.name,"--wizard"));if(W.contains(a,"--version"))return o(W.make(e.name,"--version"));let c=fe(`Missing command name: '${e.name}'`);return de.fail(op(c))};return o(t).pipe(de.orElse(()=>i(t)),de.catchSome((a)=>{if(np(a)){if(r.finalCheckBuiltIn)return Mn.some(s(t).pipe(de.catchSome((c)=>np(c)?Mn.some(de.fail(a)):Mn.none())));return Mn.some(de.fail(a))}return Mn.none()}))}case"GetUserInput":return n(e,t).pipe(de.zipRight(FD(e.prompt)),de.catchTag("QuitException",(o)=>de.die(o)),de.map((o)=>Hd(W.drop(t,1),{name:e.name,value:o})));case"Map":return wx(e.command,t,r).pipe(de.flatMap((o)=>{if(kA(o))return e.f(o.value).pipe(de.map((i)=>Hd(o.leftover,i)));return de.succeed(o)}));case"Subcommands":{let o=yp(e),i=Ix(e),[s,a]=W.span(t,(g)=>!W.some(i,([E])=>E===g)),c=(g)=>de.suspend(()=>{let E=e.children[Symbol.iterator](),S=(x)=>wx(x,g,r).pipe(de.catchIf(mA,(w)=>{let _=E.next();return _.done?de.fail(w):S(_.value)}));return S(E.next().value)}),l=c(a),d=de.sync(()=>Ex(Uh(Lh(e),Tx(e,r)))),u=l.pipe(de.flatMap((g)=>{if(b0(g)&&x0(g.option)){let E=Mn.getOrElse(W.head(o),()=>""),S=Ex(Uh(Ol(rp(W.of(E),Mn.none()),g.option.usage),g.option.helpDoc));return de.succeed(S)}return de.fail(Ld(Qr))})),p=de.sync(()=>Ex(v0(e))),y=l.pipe(de.flatMap((g)=>{if(b0(g)&&E0(g.option))return de.succeed(g);return de.fail(Ld(Qr))}));return de.suspend(()=>wx(e.parent,s,r).pipe(de.flatMap((g)=>{switch(g._tag){case"BuiltIn":{if(x0(g.option))return W.isNonEmptyReadonlyArray(a)?de.orElse(u,()=>d):d;if(E0(g.option))return de.orElse(y,()=>p);return de.succeed(g)}case"UserDefined":{let E=W.appendAll(g.leftover,a);if(W.isNonEmptyReadonlyArray(E))return c(E).pipe(de.flatMap((S)=>{if(!kA(S))return de.succeed(S);let x=S.leftover;if(W.isEmptyReadonlyArray(x))return de.succeed(Hd(x,{...g.value,subcommand:Mn.some(S.value)}));let w=W.appendAll(s,x);return wx(e.parent,w,r).pipe(de.flatMap((_)=>{if(!kA(_))return de.succeed(Hd(x,{...g.value,subcommand:Mn.some(S.value)}));return de.succeed(Hd(_.leftover,{..._.value,subcommand:Mn.some(S.value)}))}),de.catchAll(()=>de.succeed(Hd(x,{...g.value,subcommand:Mn.some(S.value)}))))}),de.catchAll((S)=>{if(mA(S)){let x=Mn.getOrElse(W.head(o),()=>""),w=W.map(i,([b])=>`'${b}'`),_=w.length===1?"":" one of",T=fe(`Invalid subcommand for ${x} - use${_} ${W.join(w,", ")}`);return de.fail(op(T))}return de.fail(S)}));return de.succeed(Hd(g.leftover,{...g.value,subcommand:Mn.none()}))}}}),de.catchSome(()=>W.isEmptyReadonlyArray(t)?Mn.some(d):Mn.none())))}}},cae=(e)=>{let[t,r]=W.span(e,(n)=>n!=="--");return[t,W.drop(r,1)]},w0=(e,t)=>{switch(e._tag){case"Standard":{let r=typeof t==="string"?d0(t):t,n=Object.create(Mh);return n._tag="Standard",n.name=e.name,n.description=r,n.options=e.options,n.args=e.args,n}case"GetUserInput":{let r=typeof t==="string"?d0(t):t,n=Object.create(Mh);return n._tag="GetUserInput",n.name=e.name,n.description=r,n.prompt=e.prompt,n}case"Map":return lW(w0(e.command,t),e.f);case"Subcommands":{let r=Object.create(Mh);return r._tag="Subcommands",r.parent=w0(e.parent,t),r.children=e.children.slice(),r}}},lae=Il("Args Wizard - "),dae=Il("Options Wizard - "),uae=(e,t,r)=>{let n=(o,i)=>{switch(o._tag){case"GetUserInput":case"Standard":return de.gen(function*(){let s=Qc.get(i).pipe(de.flatMap((a)=>{let c=fe(qo(HT(Yu("COMMAND:",qT)),xi(Os),xi(Yu(W.join(a," "),ID))));return bx.log(vr(c))}));if(fm(o)){yield*s;let a=Yu(o.name,ID);if(!M2(o.options)){let c=fe(xi(dae,a));yield*bx.log(vr(c));let l=yield*m0(o.options,r);yield*Qc.updateAndGet(i,W.appendAll(l)),yield*s}if(!v2(o.args)){let c=fe(xi(lae,a));yield*bx.log(vr(c));let l=yield*n0(o.args,r);yield*Qc.updateAndGet(i,W.appendAll(l)),yield*s}}return yield*Qc.get(i)});case"Map":return n(o.command,i);case"Subcommands":{let s=fe("Select which command you would like to execute"),a=vr(s).trimEnd(),c=(d,u)=>({title:d,value:[d,u]}),l=qo(Ix(o),W.map(([d],u)=>c(d,u)));return n(o.parent,i).pipe(de.zipRight(jc({message:a,choices:l}).pipe(de.tap(([d])=>Qc.update(i,W.append(d))),de.zipLeft(bx.log()),de.flatMap(([,d])=>n(o.children[d],i)))))}}};return Qc.make(t).pipe(de.flatMap((o)=>n(e,o).pipe(de.zipRight(Qc.get(o)))))},D0=(e)=>{switch(e._tag){case"Standard":return Al($c(e.description));case"GetUserInput":return Al($c(e.description));case"Map":return D0(e.command);case"Subcommands":return""}},O0=(e,t,r)=>pm.make(t).pipe(de.flatMap((n)=>{let o=(i,s,a,c)=>{switch(i._tag){case"Standard":{let l={command:i,parentCommands:s,subcommands:a,level:c};return pm.updateEffect(n,(d)=>r(d,l))}case"GetUserInput":{let l={command:i,parentCommands:s,subcommands:a,level:c};return pm.updateEffect(n,(d)=>r(d,l))}case"Map":return o(i.command,s,a,c);case"Subcommands":{let l=yp(i.parent),d=Ix(i),u=W.appendAll(s,l);return o(i.parent,s,d,c).pipe(de.zipRight(de.forEach(i.children,(p)=>o(p,u,a,c+1))))}}};return de.suspend(()=>o(e,W.empty(),W.empty(),0)).pipe(de.zipRight(pm.get(n)))})),Ja=mm(2,(e,t)=>{let r=W.allocate(t+1).join(" ");return W.map(e,(n)=>`${r}${n}`)}),pae=(e,t)=>O0(e,W.empty(),(r,n)=>{let o=fm(n.command)?g0([n.command.options,jd]):jd,i=Ea(o),s=fm(n.command)?kh(n.command.options):W.empty(),a=qo(n.subcommands,W.map(([E])=>E),W.sort(iW.string)),c=W.appendAll(i,a),l=W.isEmptyReadonlyArray(n.parentCommands)?W.of(n.command.name):qo(n.parentCommands,W.append(n.command.name),W.map((E)=>E.replaceAll("-","__"))),d=W.join(l,","),u=W.join(l,"__"),p=W.isEmptyReadonlyArray(n.parentCommands)?W.empty():[`${d})`,` cmd="${u}"`," ;;"],y=[`${u})`,` opts="${W.join(c," ")}"`,` if [[ \${cur} == -* || \${COMP_CWORD} -eq ${n.level+1} ]] ; then`,' COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )'," return 0"," fi",' case "${prev}" in',...Ja(s,8)," *)"," COMPREPLY=()"," ;;"," esac",' COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )'," return 0"," ;;"],g=W.append(r,[p,y]);return de.succeed(g)}).pipe(de.map((r)=>{let n=W.unsafeGet(yp(e),0),o=`_${n}_bash_completions`,i=W.flatMap(r,([a])=>a),s=W.flatMap(r,([,a])=>a);return[`function ${o}() {`," local i cur prev opts cmd"," COMPREPLY=()",' cur="${COMP_WORDS[COMP_CWORD]}"',' prev="${COMP_WORDS[COMP_CWORD-1]}"',' cmd=""',' opts=""',' for i in "${COMP_WORDS[@]}"; do',' case "${cmd},${i}" in',' ",$1")',` cmd="${t}"`," ;;",...Ja(i,12)," *)"," ;;"," esac"," done",' case "${cmd}" in',...Ja(s,8)," esac","}",`complete -F ${o} -o nosort -o bashdefault -o default ${n}`]})),fae=(e,t)=>O0(e,W.empty(),(r,n)=>{let o=W.make("complete","-c",t),i=fm(n.command)?qd([jd,n.command.options]):jd,s=Dh(i),a=fm(n.command)?yx(n.command.args):W.empty(),c=(g)=>qo(W.map(s,(E)=>qo(o,W.appendAll(g),W.append(E),W.join(" "))),W.appendAll(W.map(a,(E)=>qo(o,W.appendAll(g),W.append(E),W.join(" "))))),l=(g)=>W.map(n.subcommands,([E,S])=>{let x=D0(S);return qo(o,W.appendAll(g),W.appendAll(W.make("-f","-a",`"${E}"`)),W.appendAll(x.length===0?W.empty():W.make("-d",`'${Pd(x)}'`)),W.join(" "))});if(W.isEmptyReadonlyArray(n.parentCommands)){let g=W.make("-n",'"__fish_use_subcommand"');return de.succeed(qo(r,W.appendAll(c(g)),W.appendAll(l(g))))}let d=qo(n.parentCommands,W.drop(1),W.append(n.command.name),W.map((g)=>`__fish_seen_subcommand_from ${g}`)),u=W.map(n.subcommands,([g])=>`not __fish_seen_subcommand_from ${g}`),p=qo(W.appendAll(d,u),W.join("; and ")),y=W.make("-n",`"${p}"`);return de.succeed(qo(r,W.appendAll(c(y)),W.appendAll(l(y))))}),mae=(e,t)=>O0(e,W.empty(),(r,n)=>{let o=W.isEmptyReadonlyArray(n.parentCommands)?W.of(n.command.name):qo(n.parentCommands,W.append(n.command.name),W.map((d)=>d.replaceAll("-","__"))),i=W.join(o,"__"),s=W.join(o," "),a=qo(n.subcommands,W.map(([d,u])=>{let p=D0(u);return`'${d}:${Pd(p)}' \\`})),c=W.isEmptyReadonlyArray(a)?"commands=()":`commands=(
|
|
41
|
+
${W.join(Ja(a,8),`
|
|
42
|
+
`)}
|
|
43
|
+
)`,l=[`(( $+functions[_${i}_commands] )) ||`,`_${i}_commands() {`,` local commands; ${c}`,` _describe -t commands '${s} commands' commands "$@"`,"}"];return de.succeed(W.appendAll(r,l))}).pipe(de.map((r)=>{let n=W.unsafeGet(yp(e),0),o=DA(e,W.empty(),W.empty()),i=`_${n}_zsh_completions`;return[`#compdef ${t}`,"","autoload -U is-at-least","",`function ${i}() {`," typeset -A opt_args"," typeset -a _arguments_options"," local ret=1",""," if is-at-least 5.2; then"," _arguments_options=(-s -S -C)"," else"," _arguments_options=(-s -C)"," fi","",' local context curcontext="$curcontext" state line',...Ja(o,4),"}","",...r,"",`if [ "$funcstack[1]" = "${i}" ]; then`,` ${i} "$@"`,"else",` compdef ${i} ${n}`,"fi"]})),DA=(e,t,r)=>{switch(e._tag){case"Standard":case"GetUserInput":{let n=fm(e)?qd([jd,e.options]):jd,o=fm(e)?e.args:_h,i=qo(Ul(n),W.map((a)=>`'${a}' \\`)),s=qo(ip(o),W.map((a)=>`'${a}' \\`));if(W.isEmptyReadonlyArray(t))return['_arguments "${_arguments_options[@]}" \\',...Ja(i,4),...Ja(s,4),` ":: :_${e.name}_commands" \\`,` "*::: :->${e.name}" \\`," && ret=0"];if(W.isEmptyReadonlyArray(r))return[`(${e.name})`,'_arguments "${_arguments_options[@]}" \\',...Ja(i,4),...Ja(s,4)," && ret=0",";;"];return[`(${e.name})`,'_arguments "${_arguments_options[@]}" \\',...Ja(i,4),...Ja(s,4),` ":: :_${W.append(t,e.name).join("__")}_commands" \\`,` "*::: :->${e.name}" \\`," && ret=0"]}case"Map":return DA(e.command,t,r);case"Subcommands":{let n=Ix(e),o=yp(e.parent),i=DA(e.parent,t,W.appendAll(r,n)),s=qo(e.children,W.flatMap((l)=>DA(l,W.appendAll(t,o),r))),a=qo(W.appendAll(t,o),W.join("-")),c=qo(o,W.flatMap((l)=>["case $state in",` (${l})`,' words=($line[1] "${words[@]}")'," (( CURRENT += 1 ))",` curcontext="\${curcontext%:*:*}:${a}-command-$line[1]:"`," case $line[1] in",...Ja(s,8)," esac"," ;;","esac"]),W.appendAll(W.isEmptyReadonlyArray(t)?W.empty():W.of(";;")));return W.appendAll(i,c)}}},fW=(e)=>{let t=Object.create(Hc);return t._tag="HelpRequested",t.error=Qr,t.command=e,t};var yae=np;var mW=yA;var yW=fW;import*as Mt from"effect/Array";import*as Ya from"effect/Console";import*as gW from"effect/Context";import*as Pr from"effect/Effect";import{dual as hae,pipe as M0}from"effect/Function";import*as SW from"effect/HashMap";import*as vW from"effect/Logger";import*as hp from"effect/Option";import{pipeArguments as gae}from"effect/Pipeable";import*as xW from"effect/Unify";var Sae={pipe(){return gae(this,arguments)}},EW=(e)=>{let t=Object.create(Sae);return t.name=e.name,t.version=e.version,t.executable=e.executable,t.command=e.command,t.summary=e.summary||ha,t.footer=e.footer||Qr,t},OA=hae(3,(e,t,r)=>Pr.contextWithEffect((n)=>{let o=hp.getOrElse(gW.getOption(n,pH),()=>WT),[i,s]=vae(e,t),a=Mt.appendAll(xae(e.command),s);return Pr.matchEffect(dW(e.command,a,o),{onFailure:(c)=>Pr.zipRight(U0(c.error),Pr.fail(c)),onSuccess:xW.unify((c)=>{switch(c._tag){case"UserDefined":return Mt.matchLeft(c.leftover,{onEmpty:()=>r(c.value).pipe(Pr.catchSome((l)=>np(l)&&yA(l)?hp.some(hW(e,i,s,Uh(C0(l.command),T0(l.command,o)),r,o,t)):hp.none())),onNonEmpty:(l)=>{let d=fe(`Received unknown argument: '${l}'`);return Pr.zipRight(U0(d),Pr.fail(cs(d)))}});case"BuiltIn":return hW(e,i,s,c.option,r,o,t).pipe(Pr.catchSome((l)=>np(l)?hp.some(Pr.zipRight(U0(l.error),Pr.fail(l))):hp.none()))}})})})),vae=(e,t)=>{if(e.executable!==void 0)return[e.executable,Mt.drop(t,2)];let[[r,n],o]=Mt.splitAt(t,2);return[`${r} ${n}`,o]},U0=(e)=>Ya.error(vr(e)),hW=(e,t,r,n,o,i,s)=>{switch(n._tag){case"SetLogLevel":{let a=Mt.take(s,2),c=[];for(let d=0;d<r.length;d++){if(wae(r[d])||r[d-1]==="--log-level")continue;c.push(r[d])}let l=Mt.appendAll(a,c);return OA(e,l,o).pipe(vW.withMinimumLogLevel(n.level))}case"ShowHelp":{let a=qc(Il(e.name)),c=fe(Ns([dt(`${e.name} ${e.version}`),CD(e.summary)?ha:Ns([Os,dt("--"),Os,e.summary])])),l=et(qc("USAGE"),M0(KD(n.usage,i),Mt.map((u)=>fe(xi(dt("$ "),u))),Mt.reduceRight(Qr,(u,p)=>et(u,p)))),d=M0(a,et(c),et(l),et(n.helpDoc),et(e.footer));return Ya.log(vr(d))}case"ShowCompletions":{let a=Mt.fromIterable(Ax(e.command))[0];switch(n.shellType){case"bash":return A0(e.command,a).pipe(Pr.flatMap((c)=>Ya.log(Mt.join(c,`
|
|
44
|
+
`))));case"fish":return I0(e.command,a).pipe(Pr.flatMap((c)=>Ya.log(Mt.join(c,`
|
|
45
|
+
`))));case"zsh":return R0(e.command,a).pipe(Pr.flatMap((c)=>Ya.log(Mt.join(c,`
|
|
46
|
+
`))))}}case"ShowWizard":{let a=CD(e.summary)?ha:Ns([Os,dt("--"),Os,e.summary]),c=et(fe(Ns([dt("The wizard mode will assist you with constructing commands for"),Os,Il(`${e.name} (${e.version})`),dt(".")])),fe("Please answer all prompts provided by the wizard.")),l=Zu([[dt("Instructions"),c]]),d=qc(Ns([Il("Wizard Mode for CLI Application:"),Os,Il(e.name),Os,Il(`(${e.version})`),a])),u=et(d,l),p=vr(u),y=Mt.fromIterable(Ax(e.command))[0],g=Eae(n,y,r);return Ya.log(p).pipe(Pr.zipRight(k0(n.command,g,i)),Pr.tap((E)=>Ya.log(vr(bae(E)))),Pr.flatMap((E)=>tA({message:"Would you like to run the command?",initial:!0,active:"yes",inactive:"no"}).pipe(Pr.flatMap((S)=>{let x=Mt.take(s,2),w=Mt.drop(E,1),_=Mt.appendAll(x,w);return S?Ya.log().pipe(Pr.zipRight(OA(e,_,o))):Pr.void}))),Pr.catchAll((E)=>{if(mH(E)){let S=fe(nH(`
|
|
47
|
+
|
|
48
|
+
Quitting wizard mode...`));return Ya.log(vr(S))}return Pr.fail(E)}))}case"ShowVersion":{let a=fe(e.version);return Ya.log(vr(a))}}},xae=(e)=>{let t=e,r=Mt.empty();while(t!==void 0)switch(t._tag){case"Standard":{r=Mt.of(t.name),t=void 0;break}case"GetUserInput":{r=Mt.of(t.name),t=void 0;break}case"Map":{t=t.command;break}case"Subcommands":{t=t.parent;break}}return r},Eae=(e,t,r)=>{let n=P0(e.command),[o,i]=Mt.span(r,(a)=>!SW.has(n,a)),s=Mt.matchLeft(i,{onEmpty:()=>Mt.filter(o,(a)=>a!=="--wizard"),onNonEmpty:(a)=>Mt.append(o,a)});return Mt.appendAll(t.split(/\s+/),s)},bae=(e)=>{let t=M0(Mt.filter(e,(n)=>n.length>0),Mt.join(" ")),r=dt("You may now execute your command directly with the following options and arguments:");return _D([fe(HT(Il("Wizard Mode Complete!"))),fe(r),fe(xi(dt(" "),Yu(t,qT)))])},wae=(e)=>e&&(e==="--log-level"||e.startsWith("--log-level="));var Pae="@effect/cli/Command",L0=Symbol.for(Pae),Cae=(e)=>{let t=[],r=0,n=[],o=0;function i(a){let c={};for(let l in a)c[l]=s(a[l]);return c}function s(a){if(Bl.isArray(a))return{_tag:"Array",children:Bl.map(a,s)};else if(vA(a))return t.push(a),{_tag:"Args",index:r++};else if(IA(a))return n.push(a),{_tag:"Options",index:o++};else return{_tag:"ParsedConfig",tree:i(a)}}return{args:t,options:n,tree:i(e)}},TW=(e,t,r)=>{let n={};for(let i in e)n[i]=o(e[i]);return n;function o(i){if(i._tag==="Args")return t[i.index];else if(i._tag==="Options")return r[i.index];else if(i._tag==="Array")return Bl.map(i.children,o);else return TW(i.tree,t,r)}},AW={...wW.CommitPrototype,[L0]:L0,commit(){return this.tag},pipe(){return Rae(this,arguments)}},B0=Iae("@effect/cli/Command/registeredDescriptors",()=>new WeakMap),_ae=(e)=>B0.get(e.tag)??e.descriptor,kae=(e,t,r,n=Aae)=>{let o=Object.create(AW);return o.descriptor=e,o.handler=t,o.transform=n,o.tag=r,o},IW=(e,t)=>{let r=Object.create(AW);return r.descriptor=t.descriptor??e.descriptor,r.handler=t.handler??e.handler,r.transform=t.transform?(n,o)=>t.transform(e.transform(n,o),o):e.transform,r.tag=e.tag,r},RW=Rx((e)=>aW(e[0]),(e,t)=>{let r=kae(e,t??((n)=>ym.failSync(()=>yW(_ae(r)))),bW.GenericTag(`@effect/cli/Command/(${Bl.fromIterable(Ax(e)).join("|")})`));return r}),Dae=(e,t)=>{let{args:r,options:n,tree:o}=Cae(t);return _0(cW(e,qd(n),XD(r)),({args:i,options:s})=>TW(o,i,s))},PW=(e,t={},r)=>RW(Dae(e,t),r);var Oae=Rx(2,(e,t)=>IW(e,{descriptor:t(e.descriptor)}));var CW=Rx(2,(e,t)=>Oae(e,uW(t))),_W=Rx(2,(e,t)=>{let r=pW(e.descriptor,Bl.map(t,(i)=>[i.tag,i.descriptor])),n=Bl.reduce(t,new Map,(i,s)=>(i.set(s.tag,s),B0.set(s.tag,s.descriptor),i));function o(i){if(i.subcommand._tag==="Some"){let[s,a]=i.subcommand.value,c=n.get(s),l=c.transform(c.handler(a),a);return ym.provideService(l,e.tag,i)}return e.handler(i)}return IW(e,{descriptor:r,handler:o})});var kW=Rx(2,(e,t)=>{let r=EW({...t,command:e.descriptor});B0.set(e.tag,e.descriptor);let n=(o)=>e.transform(e.handler(o),o);return(o)=>OA(r,o,n)});var qt=PW;var jt=CW;var Wd=_W;var Fae=kW;import*as NA from"effect/Chunk";import*as Bae from"effect/Effect";import{dual as $ae}from"effect/Function";import*as W0 from"effect/HashMap";import*as $W from"effect/Inspectable";import*as qW from"effect/Option";import{pipeArguments as qae}from"effect/Pipeable";import*as jW from"effect/Stream";import*as q0 from"effect/Brand";import*as Bh from"effect/Chunk";import{GenericTag as Uae}from"effect/Context";import*as $l from"effect/Effect";import{pipe as OW}from"effect/Function";import*as NW from"effect/Sink";import*as ql from"effect/Stream";var $0=Symbol.for("@effect/platform/CommandExecutor"),FW=Symbol.for("@effect/platform/Process"),UW=q0.nominal(),MW=q0.nominal(),LW=Uae("@effect/platform/CommandExecutor"),BW=(e)=>{let t=(n)=>ql.unwrapScoped($l.map(e(n),(o)=>o.stdout)),r=(n,o)=>{let i=new TextDecoder(o);return ql.splitLines(ql.mapChunks(t(n),Bh.map((s)=>i.decode(s))))};return{[$0]:$0,start:e,exitCode:(n)=>$l.scoped($l.flatMap(e(n),(o)=>o.exitCode)),stream:t,string:(n,o="utf-8")=>{let i=new TextDecoder(o);return OW(e(n),$l.flatMap((s)=>ql.run(s.stdout,Mae)),$l.map((s)=>i.decode(s)),$l.scoped)},lines:(n,o="utf-8")=>OW(r(n,o),ql.runCollect,$l.map(Bh.toArray)),streamLines:r}},Mae=NW.foldLeftChunks(new Uint8Array,(e,t)=>Bh.reduce(t,e,(r,n)=>{let o=new Uint8Array(r.length+n.length);return o.set(r),o.set(n,r.length),o}));var j0=Symbol.for("@effect/platform/Command");var HW=(e)=>Array.from(H0(e)),H0=(e)=>{switch(e._tag){case"StandardCommand":return NA.of(e);case"PipedCommand":return NA.appendAll(H0(e.left),H0(e.right))}};var WW={[j0]:j0,pipe(){return qae(this,arguments)},...$W.BaseProto},jae={...WW,_tag:"StandardCommand",toJSON(){return{_id:"@effect/platform/Command",_tag:this._tag,command:this.command,args:this.args,env:Object.fromEntries(this.env),extendEnv:this.extendEnv,cwd:this.cwd.toJSON(),shell:this.shell,gid:this.gid.toJSON(),uid:this.uid.toJSON()}}},Hae=(e)=>Object.assign(Object.create(jae),e),Wae={...WW,_tag:"PipedCommand",toJSON(){return{_id:"@effect/platform/Command",_tag:this._tag,left:this.left.toJSON(),right:this.right.toJSON()}}},Vae=(e)=>Object.assign(Object.create(Wae),e);var V0=$ae(2,(e,t)=>{switch(e._tag){case"StandardCommand":return Hae({...e,stdin:t});case"PipedCommand":return Vae({...e,left:V0(e.left,t)})}});var z0=HW;var K0=V0;var VW=LW,G0=FW,zW=UW,KW=MW,GW=BW;import*as Xa from"effect/Deferred";import*as at from"effect/Effect";import{constUndefined as rce,identity as nce,pipe as qh}from"effect/Function";import*as tV from"effect/Inspectable";import*as rV from"effect/Layer";import*as UA from"effect/Option";import*as nV from"effect/Sink";import*as hm from"effect/Stream";import*as MA from"child_process";El();var Ur=(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 Wf({reason:o,module:e,method:t,pathOrDescriptor:n,syscall:r.syscall,description:r.message,cause:r})};import*as FA from"effect/Channel";import*as jl from"effect/Deferred";import*as ba from"effect/Effect";import*as XW from"effect/Sink";import*as Qae from"effect/Cause";import*as ls from"effect/Channel";import*as QW from"effect/Chunk";import*as gn from"effect/Effect";import*as $h from"effect/Exit";import*as Jae from"effect/Fiber";import{dual as hqe}from"effect/Function";import*as Q0 from"effect/MutableRef";import*as JW from"effect/Runtime";import*as Px from"effect/Stream";var J0=(e,t,r)=>Px.fromChannel(Yae(e,t,r));var Yae=(e,t,r)=>ls.suspend(()=>Zae(e(),t,Q0.make(void 0),r)),YW=(e,t,{encoding:r,endOnDone:n=!0}={},o=gn.void)=>{let i=Xae(e,r),s=n?gn.async((a)=>{if("closed"in e&&e.closed)a(gn.void);else e.once("finish",()=>a(gn.void)),e.end()}):gn.void;return{awaitRead:()=>gn.void,emit:i,error:(a)=>gn.zipRight(s,t(a)),done:(a)=>gn.zipRight(s,o)}},Xae=(e,t)=>(r)=>r.length===0?gn.void:gn.async((n)=>{let o=r[Symbol.iterator](),i=o.next();function s(){let a=i;i=o.next();let c=e.write(a.value,t);if(i.done)n(gn.void);else if(c)s();else e.once("drain",s)}s()}),Zae=(e,t,r,n)=>{if(!e.readable)return ls.void;let o=gn.unsafeMakeLatch(!1);function i(){o.unsafeOpen()}function s(d){r.current=$h.fail(t(d)),o.unsafeOpen()}function a(){r.current=$h.void,o.unsafeOpen()}e.on("readable",i),e.on("error",s),e.on("end",a);let c=n?.chunkSize?Number(n.chunkSize):void 0,l=ls.suspend(function d(){let u=e.read(c);if(u===null){if(r.current)return ls.fromEffect(r.current);return o.unsafeClose(),ls.flatMap(o.await,d)}let p=[u];while(!0){if(u=e.read(c),u===null)return ls.flatMap(ls.write(QW.unsafeFromArray(p)),d);p.push(u)}});return ls.ensuring(l,gn.sync(()=>{if(e.off("readable",i),e.off("error",s),e.off("end",a),n?.closeOnDone!==!1&&"closed"in e&&!e.closed)e.destroy()}))};var ZW=(e,t,r)=>XW.fromChannel(ece(e,t,r)),ece=(e,t,r)=>FA.flatMap(ba.zip(ba.sync(()=>e()),jl.make()),([n,o])=>FA.embedInput(tce(n,o,t),YW(n,(i)=>jl.failCause(o,i),r,jl.complete(o,ba.void)))),tce=(e,t,r)=>ba.suspend(()=>{function n(o){jl.unsafeDone(t,ba.fail(r(o)))}return e.on("error",n),ba.ensuring(jl.await(t),ba.sync(()=>{e.removeListener("error",n)}))});var oce=(e)=>typeof e==="string"?e:"pipe",eV=(e)=>typeof e==="string"?e:"pipe",Cx=(e)=>e instanceof globalThis.Error?e:new globalThis.Error(String(e)),gp=(e,t,r)=>{let n=z0(r).reduce((o,i)=>{let s=`${i.command} ${i.args.join(" ")}`;return o.length===0?s:`${o} | ${s}`},"");return Ur("Command",e)(t,[n])},ice={[G0]:G0,...tV.BaseProto,toJSON(){return{_id:"@effect/platform/CommandExecutor/Process",pid:this.pid}}},_x=(e)=>(t)=>{switch(t._tag){case"StandardCommand":{let r=at.flatMap(Xa.make(),(i)=>at.async((s)=>{let a=MA.spawn(t.command,t.args,{stdio:[oce(t.stdin),eV(t.stdout),eV(t.stderr)],cwd:UA.getOrElse(t.cwd,rce),shell:t.shell,env:t.extendEnv?{...process.env,...Object.fromEntries(t.env)}:Object.fromEntries(t.env),detached:process.platform!=="win32"});return a.on("error",(c)=>{s(at.fail(gp("spawn",c,t)))}),a.on("exit",(...c)=>{Xa.unsafeDone(i,at.succeed(c))}),a.on("spawn",()=>{s(at.succeed([a,i]))}),at.sync(()=>{a.kill("SIGTERM")})})),n=process.platform==="win32"?(i,s)=>at.async((a)=>{MA.exec(`taskkill /pid ${i.pid} /T /F`,(c)=>{if(c)a(at.fail(gp("kill",Cx(c),t)));else a(at.void)})}):(i,s)=>at.try({try:()=>process.kill(-i.pid,s),catch:(a)=>gp("kill",Cx(a),t)}),o=(i,s)=>at.suspend(()=>i.kill(s)?at.void:at.fail(gp("kill",new globalThis.Error("Failed to kill process"),t)));return qh(UA.match(t.cwd,{onNone:()=>at.void,onSome:(i)=>e.access(i)}),at.zipRight(at.acquireRelease(r,([i,s])=>at.flatMap(Xa.isDone(s),(a)=>{if(!a)return n(i,"SIGTERM").pipe(at.orElse(()=>o(i,"SIGTERM")),at.zipRight(Xa.await(s)),at.ignore);return at.flatMap(Xa.await(s),([c])=>{if(c!==0&&c!==null)return n(i,"SIGTERM").pipe(at.ignore);return at.void})}))),at.map(([i,s])=>{let a=nV.drain;if(i.stdin!==null)a=ZW(()=>i.stdin,(g)=>gp("toWritable",Cx(g),t));let c=at.flatMap(Xa.await(s),([g,E])=>{if(g!==null)return at.succeed(zW(g));return at.fail(gp("exitCode",new globalThis.Error(`Process interrupted due to receipt of signal: ${E}`),t))}),l=at.negate(Xa.isDone(s)),d=(g="SIGTERM")=>n(i,g).pipe(at.orElse(()=>o(i,g)),at.zipRight(at.asVoid(Xa.await(s)))),u=KW(i.pid),p=J0(()=>i.stderr,(g)=>gp("fromReadable(stderr)",Cx(g),t)),y=J0(()=>i.stdout,(g)=>gp("fromReadable(stdout)",Cx(g),t));if(typeof t.stdout!=="string")y=hm.transduce(y,t.stdout);return Object.assign(Object.create(ice),{pid:u,exitCode:c,isRunning:l,kill:d,stdin:a,stderr:p,stdout:y})}),typeof t.stdin==="string"?nce:at.tap((i)=>at.forkDaemon(hm.run(t.stdin,i.stdin))))}case"PipedCommand":{let r=z0(t);if(r.length===1)return qh(r[0],_x(e));let n=r[0],o=r.slice(1),i=o.slice(0,o.length-1),s=o[o.length-1],a=i.reduce((c,l)=>qh(K0(l,c),_x(e),at.map((d)=>d.stdout),hm.unwrapScoped),qh(_x(e)(n),at.map((c)=>c.stdout),hm.unwrapScoped));return qh(K0(s,a),_x(e))}}},oV=rV.effect(VW,qh(Bo,at.map((e)=>GW(_x(e)))));var iV=oV;import*as Vd from"effect/Effect";var sV=(e,t,r)=>(...n)=>Vd.async((o)=>{try{e(...n,(i,s)=>{if(i)o(Vd.fail(t?t(i,n):i));else o(Vd.succeed(s))})}catch(i){o(r?Vd.fail(r(i,n)):Vd.die(i))}});var Sn=sV;El();import*as qe from"effect/Effect";import{pipe as aV}from"effect/Function";import*as cV from"effect/Layer";import*as Gn from"effect/Option";import*as LA from"effect/Stream";import*as lV from"crypto";import*as tt from"fs";import*as dV from"os";import*as jh from"path";var nn=(e)=>(t)=>new ts({module:"FileSystem",method:e,cause:t}),lce=(()=>{let e=Sn(tt.access,Ur("FileSystem","access"),nn("access"));return(t,r)=>{let n=tt.constants.F_OK;if(r?.readable)n|=tt.constants.R_OK;if(r?.writable)n|=tt.constants.W_OK;return e(t,n)}})(),dce=(()=>{let e=Sn(tt.cp,Ur("FileSystem","copy"),nn("copy"));return(t,r,n)=>e(t,r,{force:n?.overwrite??!1,preserveTimestamps:n?.preserveTimestamps??!1,recursive:!0})})(),uce=(()=>{let e=Sn(tt.copyFile,Ur("FileSystem","copyFile"),nn("copyFile"));return(t,r)=>e(t,r)})(),pce=(()=>{let e=Sn(tt.chmod,Ur("FileSystem","chmod"),nn("chmod"));return(t,r)=>e(t,r)})(),fce=(()=>{let e=Sn(tt.chown,Ur("FileSystem","chown"),nn("chown"));return(t,r,n)=>e(t,r,n)})(),mce=(()=>{let e=Sn(tt.link,Ur("FileSystem","link"),nn("link"));return(t,r)=>e(t,r)})(),yce=(()=>{let e=Sn(tt.mkdir,Ur("FileSystem","makeDirectory"),nn("makeDirectory"));return(t,r)=>e(t,{recursive:r?.recursive??!1,mode:r?.mode})})(),Y0=(e)=>{let t=Sn(tt.mkdtemp,Ur("FileSystem",e),nn(e));return(r)=>qe.suspend(()=>{let n=r?.prefix??"",o=typeof r?.directory==="string"?jh.join(r.directory,"."):dV.tmpdir();return t(n?jh.join(o,n):o+"/")})},hce=Y0("makeTempDirectory"),X0=(e)=>{let t=Sn(tt.rm,Ur("FileSystem",e),nn(e));return(r,n)=>t(r,{recursive:n?.recursive??!1,force:n?.force??!1})},gce=X0("remove"),Sce=(()=>{let e=Y0("makeTempDirectoryScoped"),t=X0("makeTempDirectoryScoped");return(r)=>qe.acquireRelease(e(r),(n)=>qe.orDie(t(n,{recursive:!0})))})(),uV=(e)=>{let t=Sn(tt.open,Ur("FileSystem",e),nn(e)),r=Sn(tt.close,Ur("FileSystem",e),nn(e));return(n,o)=>aV(qe.acquireRelease(t(n,o?.flag??"r",o?.mode),(i)=>qe.orDie(r(i))),qe.map((i)=>xce(gq(i),o?.flag?.startsWith("a")??!1)))},vce=uV("open"),xce=(()=>{let e=(d)=>Sn(tt.read,Ur("FileSystem",d),nn(d)),t=e("read"),r=e("readAlloc"),n=Sn(tt.fstat,Ur("FileSystem","stat"),nn("stat")),o=Sn(tt.ftruncate,Ur("FileSystem","truncate"),nn("truncate")),i=Sn(tt.fsync,Ur("FileSystem","sync"),nn("sync")),s=(d)=>Sn(tt.write,Ur("FileSystem",d),nn(d)),a=s("write"),c=s("writeAll");class l{fd;append;[ST];semaphore=qe.unsafeMakeSemaphore(1);position=0n;constructor(d,u){this.fd=d,this.append=u,this[ST]=ST}get stat(){return qe.map(n(this.fd),fV)}get sync(){return i(this.fd)}seek(d,u){let p=Vu(d);return this.semaphore.withPermits(1)(qe.sync(()=>{if(u==="start")this.position=p;else if(u==="current")this.position=this.position+p;return this.position}))}read(d){return this.semaphore.withPermits(1)(qe.map(qe.suspend(()=>t(this.fd,{buffer:d,position:this.position})),(u)=>{let p=Vu(u);return this.position=this.position+p,p}))}readAlloc(d){let u=Number(d);return this.semaphore.withPermits(1)(qe.flatMap(qe.sync(()=>Buffer.allocUnsafeSlow(u)),(p)=>qe.map(r(this.fd,{buffer:p,position:this.position}),(y)=>{if(y===0)return Gn.none();if(this.position=this.position+BigInt(y),y===u)return Gn.some(p);let g=Buffer.allocUnsafeSlow(y);return p.copy(g,0,0,y),Gn.some(g)})))}truncate(d){return this.semaphore.withPermits(1)(qe.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)(qe.map(qe.suspend(()=>a(this.fd,d,void 0,void 0,this.append?void 0:Number(this.position))),(u)=>{let p=Vu(u);if(!this.append)this.position=this.position+p;return p}))}writeAllChunk(d){return qe.flatMap(qe.suspend(()=>c(this.fd,d,void 0,void 0,this.append?void 0:Number(this.position))),(u)=>{if(u===0)return qe.fail(new Wf({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)):qe.void})}writeAll(d){return this.semaphore.withPermits(1)(this.writeAllChunk(d))}}return(d,u)=>new l(d,u)})(),pV=(e)=>{let t=Y0(e),r=uV(e),n=(o)=>qe.sync(()=>lV.randomBytes(o).toString("hex"));return(o)=>aV(qe.zip(t(o),n(6)),qe.map(([i,s])=>jh.join(i,s+(o?.suffix??""))),qe.tap((i)=>qe.scoped(r(i,{flag:"w+"}))))},Ece=pV("makeTempFile"),bce=(()=>{let e=pV("makeTempFileScoped"),t=X0("makeTempFileScoped");return(r)=>qe.acquireRelease(e(r),(n)=>qe.orDie(t(jh.dirname(n),{recursive:!0})))})(),wce=(e,t)=>qe.tryPromise({try:()=>tt.promises.readdir(e,t),catch:(r)=>Ur("FileSystem","readDirectory")(r,[e])}),Tce=(e)=>qe.async((t,r)=>{try{tt.readFile(e,{signal:r},(n,o)=>{if(n)t(qe.fail(Ur("FileSystem","readFile")(n,[e])));else t(qe.succeed(o))})}catch(n){t(qe.fail(nn("readFile")(n)))}}),Ace=(()=>{let e=Sn(tt.readlink,Ur("FileSystem","readLink"),nn("readLink"));return(t)=>e(t)})(),Ice=(()=>{let e=Sn(tt.realpath,Ur("FileSystem","realPath"),nn("realPath"));return(t)=>e(t)})(),Rce=(()=>{let e=Sn(tt.rename,Ur("FileSystem","rename"),nn("rename"));return(t,r)=>e(t,r)})(),fV=(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:Gn.fromNullable(e.mtime),atime:Gn.fromNullable(e.atime),birthtime:Gn.fromNullable(e.birthtime),dev:e.dev,rdev:Gn.fromNullable(e.rdev),ino:Gn.fromNullable(e.ino),mode:e.mode,nlink:Gn.fromNullable(e.nlink),uid:Gn.fromNullable(e.uid),gid:Gn.fromNullable(e.gid),size:Vu(e.size),blksize:Gn.map(Gn.fromNullable(e.blksize),Vu),blocks:Gn.fromNullable(e.blocks)}),Z0=(()=>{let e=Sn(tt.stat,Ur("FileSystem","stat"),nn("stat"));return(t)=>qe.map(e(t),fV)})(),Pce=(()=>{let e=Sn(tt.symlink,Ur("FileSystem","symlink"),nn("symlink"));return(t,r)=>e(t,r)})(),Cce=(()=>{let e=Sn(tt.truncate,Ur("FileSystem","truncate"),nn("truncate"));return(t,r)=>e(t,r!==void 0?Number(r):void 0)})(),_ce=(()=>{let e=Sn(tt.utimes,Ur("FileSystem","utime"),nn("utime"));return(t,r,n)=>e(t,r,n)})(),kce=(e,t)=>LA.asyncScoped((r)=>qe.acquireRelease(qe.sync(()=>{let n=tt.watch(e,{recursive:t?.recursive},(o,i)=>{if(!i)return;switch(o){case"rename":{r.fromEffect(qe.matchEffect(Z0(i),{onSuccess:(s)=>qe.succeed(Sq({path:i})),onFailure:(s)=>s._tag==="SystemError"&&s.reason==="NotFound"?qe.succeed(xq({path:i})):qe.fail(s)}));return}case"change":{r.single(vq({path:i}));return}}});return n.on("error",(o)=>{r.fail(new Wf({module:"FileSystem",reason:"Unknown",method:"watch",pathOrDescriptor:e,cause:o}))}),n.on("close",()=>{r.end()}),n}),(n)=>qe.sync(()=>n.close()))),Dce=(e,t,r)=>Z0(t).pipe(qe.map((n)=>e.pipe(Gn.flatMap((o)=>o.register(t,n,r)),Gn.getOrElse(()=>kce(t,r)))),LA.unwrap),Oce=(e,t,r)=>qe.async((n,o)=>{try{tt.writeFile(e,t,{signal:o,flag:r?.flag,mode:r?.mode},(i)=>{if(i)n(qe.fail(Ur("FileSystem","writeFile")(i,[e])));else n(qe.void)})}catch(i){n(qe.fail(nn("writeFile")(i)))}}),Nce=qe.map(qe.serviceOption(Mk),(e)=>hq({access:lce,chmod:pce,chown:fce,copy:dce,copyFile:uce,link:mce,makeDirectory:yce,makeTempDirectory:hce,makeTempDirectoryScoped:Sce,makeTempFile:Ece,makeTempFileScoped:bce,open:vce,readDirectory:wce,readFile:Tce,readLink:Ace,realPath:Ice,remove:gce,rename:Rce,stat:Z0,symlink:Pce,truncate:Cce,utimes:_ce,watch(t,r){return Dce(e,t,r)},writeFile:Oce})),mV=cV.effect(Bo,Nce);var BA=mV;El();import*as eO from"effect/Effect";import*as $A from"effect/Layer";import*as kx from"path";import*as qA from"url";var tO=(e)=>eO.try({try:()=>qA.fileURLToPath(e),catch:(t)=>new ts({module:"Path",method:"fromFileUrl",description:`Invalid file URL: ${e}`,cause:t})}),rO=(e)=>eO.try({try:()=>qA.pathToFileURL(e),catch:(t)=>new ts({module:"Path",method:"toFileUrl",description:`Invalid path: ${e}`,cause:t})}),Uce=$A.succeed(Sa,Sa.of({[om]:om,...kx.posix,fromFileUrl:tO,toFileUrl:rO})),Mce=$A.succeed(Sa,Sa.of({[om]:om,...kx.win32,fromFileUrl:tO,toFileUrl:rO})),hV=$A.succeed(Sa,Sa.of({[om]:om,...kx,fromFileUrl:tO,toFileUrl:rO}));var gV=hV;El();import*as Ar from"effect/Effect";import*as SV from"effect/Exit";import*as vV from"effect/Layer";import*as xV from"effect/Mailbox";import*as EV from"effect/Option";import*as Dx from"effect/RcRef";import*as jA from"readline";var bV=(e)=>e.key.ctrl&&(e.key.name==="c"||e.key.name==="d"),wV=Ar.fnUntraced(function*(e=bV){let t=process.stdin,r=process.stdout,n=yield*Dx.make({acquire:Ar.acquireRelease(Ar.sync(()=>{let d=jA.createInterface({input:t,escapeCodeTimeout:50});if(jA.emitKeypressEvents(t,d),t.isTTY)t.setRawMode(!0);return d}),(d)=>Ar.sync(()=>{if(t.isTTY)t.setRawMode(!1);d.close()}))}),o=Ar.sync(()=>r.columns??0),i=Ar.sync(()=>r.rows??0),s=Ar.sync(()=>Boolean(r.isTTY)),a=Ar.gen(function*(){yield*Dx.get(n);let d=yield*xV.make(),u=(p,y)=>{let g={input:EV.fromNullable(p),key:{name:y.name??"",ctrl:!!y.ctrl,meta:!!y.meta,shift:!!y.shift}};if(d.unsafeOffer(g),e(g))d.unsafeDone(SV.void)};return yield*Ar.addFinalizer(()=>Ar.sync(()=>t.off("keypress",u))),t.on("keypress",u),d}),c=Dx.get(n).pipe(Ar.flatMap((d)=>Ar.async((u)=>{let p=(y)=>u(Ar.succeed(y));return d.once("line",p),Ar.sync(()=>d.off("line",p))})),Ar.scoped),l=(d)=>Ar.uninterruptible(Ar.async((u)=>{r.write(d,(p)=>p?u(Ar.fail(new ts({module:"Terminal",method:"display",description:"Failed to write prompt to stdout",cause:p}))):u(Ar.void))}));return Fr.of({columns:o,rows:i,isTTY:s,readInput:a,readLine:c,display:l})}),TV=vV.scoped(Fr,wV(bV));var AV=TV;import{pipe as Xce}from"effect/Function";import*as JA from"effect/Layer";import*as _V from"effect/Channel";import*as vp from"effect/Context";import*as jr from"effect/Deferred";import*as ke from"effect/Effect";import*as kV from"effect/Exit";import*as DV from"effect/FiberRef";import*as Hh from"effect/FiberSet";import{identity as Nqe,pipe as Fqe}from"effect/Function";import*as VA from"effect/Layer";import*as Wh from"effect/Mailbox";import*as OV from"effect/Option";import*as NV from"effect/Pool";import*as zA from"effect/Runtime";import*as FV from"effect/Schedule";import*as KA from"effect/Schema";import*as GA from"effect/Scope";import*as Ox from"effect/Stream";import*as UV from"effect/Tracer";import*as IV from"effect/Context";import*as Sp from"effect/Effect";import{dual as kqe}from"effect/Function";import*as jce from"effect/Option";import*as Hce from"effect/ParseResult";import*as HA from"effect/Schema";class WA extends IV.Tag("@effect/platform/Transferable/Collector")(){}var RV=()=>{let e=[],t=(o)=>{e.push(...o)},r=()=>e,n=()=>{let o=e;return e=[],o};return WA.of({unsafeAddAll:t,addAll:(o)=>Sp.sync(()=>t(o)),unsafeRead:r,read:Sp.sync(r),unsafeClear:n,clear:Sp.sync(n)})};import*as zce from"effect/Predicate";import*as wa from"effect/Schema";var PV=Symbol.for("@effect/platform/WorkerError");var CV=PV;class zd extends wa.TaggedError()("WorkerError",{reason:wa.Literal("spawn","decode","send","unknown","encode"),cause:wa.Defect}){[CV]=CV;static Cause=wa.Cause({error:this,defect:wa.Defect});static encodeCause=wa.encodeSync(this.Cause);static decodeCause=wa.decodeSync(this.Cause);get message(){switch(this.reason){case"send":return"An error occurred calling .postMessage";case"spawn":return"An error occurred while spawning a worker";case"decode":return"An error occurred during decoding";case"encode":return"An error occurred during encoding";case"unknown":return"An unexpected error occurred"}}}var nO=Symbol.for("@effect/platform/Worker/PlatformWorker"),QA=vp.GenericTag("@effect/platform/Worker/PlatformWorker"),oO=Symbol.for("@effect/platform/Worker/WorkerManager"),iO=vp.GenericTag("@effect/platform/Worker/WorkerManager"),MV=vp.GenericTag("@effect/platform/Worker/Spawner"),LV=ke.gen(function*(){let e=yield*QA,t=0;return iO.of({[oO]:oO,spawn({encode:r,initialMessage:n}){return ke.gen(function*(){let o=t++,i=0,s=new Map,a=RV(),c=r?(S)=>ke.zipRight(a.clear,ke.provideService(r(S),WA,a)):ke.succeed,l=yield*jr.make(),d=yield*e.spawn(o);yield*d.run((S)=>{if(S[0]===0)return jr.complete(l,ke.void);return u(S[1])}).pipe(ke.onError((S)=>ke.forEach(s.values(),(x)=>(jr.DeferredTypeId in x)?jr.failCause(x,S):x.failCause(S))),ke.tapErrorCause(ke.logWarning),ke.retry(FV.spaced(1000)),ke.annotateLogs({package:"@effect/platform",module:"Worker"}),ke.interruptible,ke.forkScoped),yield*ke.addFinalizer(()=>ke.zipRight(ke.forEach(s.values(),(S)=>(jr.DeferredTypeId in S)?jr.interrupt(S):S.end,{discard:!0}),ke.sync(()=>s.clear())));let u=(S)=>ke.suspend(()=>{let x=s.get(S[0]);if(!x)return ke.void;switch(S[1]){case 0:return jr.DeferredTypeId in x?jr.succeed(x,S[2][0]):x.offerAll(S[2]);case 1:{if(S.length===2)return jr.DeferredTypeId in x?jr.interrupt(x):x.end;return jr.DeferredTypeId in x?jr.succeed(x,S[2][0]):ke.zipRight(x.offerAll(S[2]),x.end)}case 2:case 3:{if(S[1]===2)return jr.DeferredTypeId in x?jr.fail(x,S[2]):x.fail(S[2]);let w=zd.decodeCause(S[2]);return jr.DeferredTypeId in x?jr.failCause(x,w):x.failCause(w)}}}),p=(S,x)=>ke.withFiberRuntime((w)=>{let _=w.getFiberRef(DV.currentContext),T=vp.getOption(_,UV.ParentSpan).pipe(OV.filter((I)=>I._tag==="Span")),b=i++;return x.pipe(ke.tap((I)=>(s.set(b,I),c(S).pipe(ke.tap((O)=>d.send([b,0,O,T._tag==="Some"?[T.value.traceId,T.value.spanId,T.value.sampled]:void 0],a.unsafeRead())),ke.catchAllCause((O)=>Wh.isMailbox(I)?I.failCause(O):jr.failCause(I,O))))),ke.map((I)=>({id:b,mailbox:I})))}),y=({id:S},x)=>{let w=ke.sync(()=>s.delete(S));return kV.isFailure(x)?ke.zipRight(ke.orDie(d.send([S,1])),w):w},g=(S)=>Ox.fromChannel(_V.acquireUseRelease(p(S,Wh.make()),({mailbox:x})=>Wh.toChannel(x),y)),E=(S)=>ke.acquireUseRelease(p(S,jr.make()),({mailbox:x})=>jr.await(x),y);if(yield*jr.await(l),n)yield*ke.sync(n).pipe(ke.flatMap(E),ke.mapError((S)=>new zd({reason:"spawn",cause:S})));return{id:o,execute:g,executeEffect:E}})}})}),BV=VA.effect(iO,LV);var $V=()=>(e)=>QA.of({[nO]:nO,spawn(t){return ke.gen(function*(){let r=yield*MV,n,o=[];return{run:(a)=>ke.uninterruptibleMask((c)=>ke.gen(function*(){let l=yield*ke.scope,d=yield*e.setup({worker:r(t),scope:l});n=d,yield*GA.addFinalizer(l,ke.sync(()=>{n=void 0}));let u=(yield*ke.runtime()).pipe(zA.updateContext(vp.omit(GA.Scope))),p=yield*Hh.make(),y=zA.runFork(u);if(yield*e.listen({port:d,scope:l,emit(g){Hh.unsafeAdd(p,y(a(g)))},deferred:p.deferred}),o.length>0){for(let[g,E]of o)d.postMessage([0,g],E);o.length=0}return yield*c(Hh.join(p))}).pipe(ke.scoped)),send:(a,c)=>ke.try({try:()=>{if(n===void 0)o.push([a,c]);else n.postMessage([0,a],c)},catch:(l)=>new zd({reason:"send",cause:l})})}})}});var qV=$V,jV=QA;var HV=BV;import*as Kd from"effect/Deferred";import*as Mi from"effect/Effect";import*as WV from"effect/Exit";import*as Nx from"effect/Layer";import*as VV from"effect/Scope";var Qce=qV()({setup({scope:e,worker:t}){return Mi.flatMap(Kd.make(),(r)=>{let n="postMessage"in t?{postMessage(o,i){t.postMessage(o,i)},kill:()=>t.terminate(),worker:t}:{postMessage(o,i){t.send(o)},kill:()=>t.kill("SIGKILL"),worker:t};return t.on("exit",()=>{Kd.unsafeDone(r,WV.void)}),Mi.as(VV.addFinalizer(e,Mi.suspend(()=>(n.postMessage([1]),Kd.await(r))).pipe(Mi.interruptible,Mi.timeout(5000),Mi.catchAllCause(()=>Mi.sync(()=>n.kill())))),n)})},listen({deferred:e,emit:t,port:r}){return r.worker.on("message",(n)=>{t(n)}),r.worker.on("messageerror",(n)=>{Kd.unsafeDone(e,new zd({reason:"decode",cause:n}))}),r.worker.on("error",(n)=>{Kd.unsafeDone(e,new zd({reason:"unknown",cause:n}))}),r.worker.on("exit",(n)=>{Kd.unsafeDone(e,new zd({reason:"unknown",cause:Error(`exited with code ${n}`)}))}),Mi.void}}),zV=Nx.succeed(jV,Qce),KV=Nx.provide(HV,zV);var GV=KV;var Zce=Xce(JA.mergeAll(gV,iV,AV,GV),JA.provideMerge(BA));var ele=BA;import*as aO from"effect/Cause";import*as Jc from"effect/Effect";import*as XV from"effect/Exit";import*as sO from"effect/FiberRef";import*as YA from"effect/FiberRefs";import{dual as tle}from"effect/Function";import*as Vh from"effect/HashSet";import*as Fx from"effect/Logger";var rle=(e,t)=>{t(XV.isFailure(e)&&!aO.isInterruptedOnly(e.cause)?1:0)},YV=(e,t)=>{let r=YA.getOrDefault(e,sO.currentLoggers);if(!Vh.has(r,Fx.defaultLogger))return e;return YA.updateAs(e,{fiberId:t,fiberRef:sO.currentLoggers,value:r.pipe(Vh.remove(Fx.defaultLogger),Vh.add(Fx.prettyLoggerDefault))})},ZV=(e)=>tle((t)=>Jc.isEffect(t[0]),(t,r)=>{let n=r?.disableErrorReporting===!0?Jc.runFork(t,{updateRefs:r?.disablePrettyLogger===!0?void 0:YV}):Jc.runFork(Jc.tapErrorCause(t,(i)=>{if(aO.isInterruptedOnly(i))return Jc.void;return Jc.logError(i)}),{updateRefs:r?.disablePrettyLogger===!0?void 0:YV}),o=r?.teardown??rle;return e({fiber:n,teardown:o})});import{constVoid as nle}from"effect/Function";var e4=ZV(({fiber:e,teardown:t})=>{let r=setInterval(nle,2147483647),n=!1;e.addObserver((i)=>{if(!n)process.removeListener("SIGINT",o),process.removeListener("SIGTERM",o);clearInterval(r),t(i,(s)=>{if(n||s!==0)process.exit(s)})});function o(){n=!0,process.removeListener("SIGINT",o),process.removeListener("SIGTERM",o),e.unsafeInterruptAsFork(e.id())}process.on("SIGINT",o),process.on("SIGTERM",o)});var t4=e4;var sle=t4;import{DATABASE_UPLOAD_MODES as HOe}from"@processfocus/hosting-contract";import{Config as uT,Console as go,Effect as Fe,Option as kt}from"effect";import{Console as fO,Effect as Us}from"effect";import{readFileSync as ale}from"fs";import{join as cle}from"path";var XA=()=>process.env.BASE_URL,n4=()=>process.env.FRONTEND_BASE_URL??XA();var i4=(e)=>{try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"}catch{return!1}},lle=()=>{if(process.env.GRAPHQL_ENDPOINT)return!1;let e=XA();return e===void 0||i4(e)},dle=4000,ule=4020,ple=3000,fle=".graphql-port.json",mle=".auth-port.json",yle=".frontend-port.json",hle=()=>process.env.PF_RUNTIME_ROOT??process.env.NX_WORKSPACE_ROOT??process.cwd(),gle=(e)=>{if(typeof e!=="object"||e===null)return!1;let t=e;return"port"in t&&typeof t.port==="number"},cO=(e)=>{try{let t=cle(hle(),e),r=ale(t,"utf-8"),n=JSON.parse(r);return gle(n)?n.port:void 0}catch{return}},Ux=()=>cO(fle)??dle,lO=()=>cO(mle)??ule,Sle=()=>cO(yle)??ple;var s4=()=>`ws://localhost:${Ux()}/graphql`,a4=()=>`http://localhost:${lO()}`,o4=()=>`http://localhost:${Sle()}`;var c4=()=>{let e=n4();if(e){if(i4(e))return o4();return e}if(lle())return o4();return XA()??"http://localhost:3000"};import{Data as Gd}from"effect";class Hl extends Gd.TaggedError("OrgLoadError"){}class vn extends Gd.TaggedError("BuildError"){}class xp extends Gd.TaggedError("GraphqlSchemaError"){}class zh extends Gd.TaggedError("PolicyFileError"){}class Qd extends Gd.TaggedError("InitError"){}class Yc extends Gd.TaggedError("MigrationError"){constructor(e){super({...e,message:e.statement?`Migration failed: ${e.reason}. Statement: ${e.statement}`:`Migration failed: ${e.reason}`})}}class ni extends Gd.TaggedError("AuthLoginError"){}class ce extends Gd.TaggedError("CliError"){}class dO extends Gd.TaggedError("CustomDomainError"){}import{mkdirSync as vle,readFileSync as xle,writeFileSync as Ele}from"fs";import{homedir as ble}from"os";import{dirname as wle,join as Tle}from"path";var l4=()=>process.env.PFCLI_CREDENTIALS_PATH??Tle(ble(),".config","pf","credentials.json"),d4=(e)=>{let t=l4(),r=wle(t);vle(r,{recursive:!0,mode:448}),Ele(t,JSON.stringify(e,null,2),{mode:384})},Ale=(e)=>{if(typeof e!=="object"||e===null)return!1;let t=e;return t.version===1&&typeof t.baseUrl==="string"&&typeof t.accessToken==="string"&&typeof t.expiresAt==="string"&&typeof t.loginAt==="string"},u4=()=>{try{let e=xle(l4(),"utf8"),t=JSON.parse(e);return Ale(t)?t:null}catch{return null}},p4=(e)=>{let t=new Date(e.expiresAt).getTime();return Number.isNaN(t)||Date.now()>=t};import{negotiateHostingContract as Ile}from"@processfocus/hosting-contract";import{Duration as Rle,Effect as bi,Schema as ZA}from"effect";var uO='Authentication required. Run "pfcli auth login".',m4=new Set(["localhost","127.0.0.1"]),f4=ZA.parseJson(ZA.Unknown),Ple=(e)=>{let t=e/1000,r=t%1===0?String(t):t.toFixed(3).replace(/\.?0+$/,""),n=Number(r)===1?"second":"seconds";return`GraphQL request timed out after ${r} ${n}`},Cle=(e,t)=>t===void 0?e:e.pipe(bi.timeoutFail({duration:Rle.millis(t),onTimeout:()=>new ce({message:Ple(t)})})),oi=(e)=>{let t=e.replace(/\/+$/,"");try{let r=new URL(t);if(m4.has(r.hostname))return`http://localhost:${Ux()}/graphql`}catch{}return`${t}/graphql`},y4=(e)=>{let t=e.replace(/\/+$/,"");try{let r=new URL(t);if(m4.has(r.hostname))return s4()}catch{}return`${t.replace(/^http/,"ws")}/graphql`},Hr=(e,t,r,n,o={})=>bi.gen(function*(){let i=yield*ZA.encode(f4)({query:r,variables:n}).pipe(bi.mapError((l)=>new ce({message:"Failed to encode GraphQL request body",cause:l}))),s=yield*Cle(bi.tryPromise({try:(l)=>fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:i,signal:l}),catch:(l)=>new ce({message:"Failed to call GraphQL endpoint",cause:l})}),o.timeoutMs);if(s.status===401)return yield*new ce({message:uO});if(!s.ok){let l=yield*bi.tryPromise({try:async()=>{try{return await s.text()}catch{return""}},catch:(d)=>new ce({message:"Failed to read GraphQL error response body",cause:d})});return yield*new ce({message:`GraphQL request failed with ${s.status}: ${l}`})}let a=yield*bi.tryPromise({try:()=>s.text(),catch:(l)=>new ce({message:"Failed to read GraphQL response body",cause:l})}),c=yield*ZA.decodeUnknown(f4)(a).pipe(bi.map((l)=>l),bi.mapError((l)=>new ce({message:`Failed to parse GraphQL response from ${e}: ${a.slice(0,200)}`,cause:l})));if(c.errors&&c.errors.length>0){let l=c.errors.map((u)=>u.message??"GraphQL request failed").join(", ");if(l.toLowerCase().includes("unauthenticated"))return yield*new ce({message:uO});let d=c.errors.length===1&&typeof c.errors[0]?.extensions?.code==="string"?c.errors[0].extensions.code:void 0;return yield*new ce({message:`GraphQL error: ${l}`,graphqlErrorMessage:l,...d===void 0?{}:{graphqlErrorCode:d}})}if(!c.data)return yield*new ce({message:"GraphQL response missing data"});return c.data}),_le=`
|
|
49
|
+
query HostingContract {
|
|
50
|
+
hostingContract {
|
|
51
|
+
format
|
|
52
|
+
version
|
|
53
|
+
major
|
|
54
|
+
capabilities
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
`,kle=1e4,Dle=(e)=>bi.gen(function*(){let t=oi(e.baseUrl),r=yield*Hr(t,e.accessToken,_le,{},{timeoutMs:kle}).pipe(bi.catchAll(()=>bi.succeed(void 0)));if(r===void 0)return;yield*Ile(r.hostingContract).pipe(bi.catchTags({UnsupportedHostingContractError:(n)=>bi.fail(new ce({message:n.message,graphqlErrorMessage:n.upgradeHint})),HostingContractParseError:()=>bi.void,UnsupportedHostingCapabilityError:()=>bi.void}))}),ds=()=>bi.gen(function*(){let e=u4();if(!e||p4(e))return yield*new ce({message:uO});return yield*Dle(e),e}),Mr=(e,t={},r={})=>bi.gen(function*(){let n=yield*ds(),o=oi(n.baseUrl);return yield*Hr(o,n.accessToken,e,t,r)});import{Console as Ole,Effect as eI}from"effect";var pO=(e)=>{let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw Error(`Unsupported browser URL protocol: ${t.protocol||"unknown"}`);return t},Nle=(e,t)=>{if(pO(e),t==="darwin")return["open",e];if(t==="win32")return["rundll32.exe","url.dll,FileProtocolHandler",e];return["xdg-open",e]},Fle=(e,t,r,n=Ole.log)=>eI.gen(function*(){let o=yield*eI.try({try:()=>Nle(e,t),catch:(i)=>new ni({message:i instanceof Error?i.message:"Invalid browser URL",cause:i})});yield*n(`
|
|
58
|
+
Opening browser: ${e}`),yield*n(`If the browser does not open, visit the URL above.
|
|
59
|
+
`),yield*eI.tryPromise({try:()=>r(o),catch:()=>"browser-open-failed"}).pipe(eI.ignore)}),h4=(e)=>Fle(e,process.platform,(t)=>Bun.spawn([...t],{stdout:"ignore",stderr:"ignore"}).exited);import{randomBytes as Ule}from"crypto";import{Effect as Mle}from"effect";var tI=(e,t)=>{let r=Date.now(),n=new Date(r+t*1000).getTime();if(!Number.isFinite(t)||t<=0||!Number.isFinite(n)||n<=r)throw Error("Invalid login credential lifetime");let o;try{let a=e.split(".");if(a.length!==3||!a[0]||!a[1]||!a[2])throw Error("Invalid JWT");o=JSON.parse(Buffer.from(a[1],"base64url").toString("utf8"))}catch{throw Error("Invalid login credential expiry")}if(typeof o!=="object"||o===null||!("exp"in o)||typeof o.exp!=="number"||!Number.isFinite(o.exp))throw Error("Invalid login credential expiry");let i=new Date(o.exp*1000).getTime();if(!Number.isFinite(i))throw Error("Invalid login credential expiry");let s=Math.min(n,i);if(s<=r)throw Error("Login expired. Run pfcli auth login again.");return s};var Lle=`<!DOCTYPE html>
|
|
60
|
+
<html>
|
|
61
|
+
<head>
|
|
62
|
+
<title>Login Successful</title>
|
|
63
|
+
<style>
|
|
64
|
+
body {
|
|
65
|
+
font-family: system-ui, sans-serif;
|
|
66
|
+
display: flex;
|
|
67
|
+
justify-content: center;
|
|
68
|
+
align-items: center;
|
|
69
|
+
height: 100vh;
|
|
70
|
+
margin: 0;
|
|
71
|
+
background: #fff;
|
|
72
|
+
color: #111;
|
|
73
|
+
}
|
|
74
|
+
@media (prefers-color-scheme: dark) {
|
|
75
|
+
body { background: #111; color: #eee; }
|
|
76
|
+
}
|
|
77
|
+
</style>
|
|
78
|
+
</head>
|
|
79
|
+
<body>
|
|
80
|
+
<div style="text-align: center;">
|
|
81
|
+
<h1>Login successful!</h1>
|
|
82
|
+
<p>You can close this tab.</p>
|
|
83
|
+
</div>
|
|
84
|
+
</body>
|
|
85
|
+
</html>`,g4=Mle.sync(()=>{let e=Ule(32).toString("base64url"),{promise:t,resolve:r,reject:n}=Promise.withResolvers();t.catch(()=>{});let o=!1,i=(c)=>(o=!0,clearTimeout(a),n(Error(c)),new Response(c,{status:400,headers:{"Cache-Control":"no-store"}})),s=Bun.serve({hostname:"localhost",port:0,fetch(c){let l=new URL(c.url);if(l.pathname==="/callback"){if(o)return new Response("Login callback already completed",{status:409});let d=l.searchParams.get("access_token"),u=Number(l.searchParams.get("expires_in"));if(l.searchParams.get("state")!==e)return i("Invalid login callback state");if(l.searchParams.has("error"))return i(l.searchParams.get("error")==="expired"?"Login expired. Run pfcli auth login again.":"Login failed. Run pfcli auth login again.");if(d){let y;try{y=tI(d,u)}catch(g){return i(g instanceof Error?g.message:"Invalid login credential expiry")}return o=!0,clearTimeout(a),r({accessToken:d,expiresAt:y}),new Response(Lle,{headers:{"Content-Type":"text/html","Cache-Control":"no-store"}})}return i("Missing access token")}return new Response("Not found",{status:404})}}),a=setTimeout(()=>{o=!0,n(Error("Login timed out after 2 minutes"))},120000);return{port:s.port,state:e,tokens:t,stop:()=>{clearTimeout(a),s.stop()}}});var Ble=`
|
|
86
|
+
mutation RequestProviderUserPermissions($email: String!) {
|
|
87
|
+
requestProviderUserPermissions(email: $email) {
|
|
88
|
+
success
|
|
89
|
+
error
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
`,$le="ci-pipeline",qle=new Set(["localhost","127.0.0.1"]),jle=(e)=>{if(typeof e!=="object"||e===null)return!1;let t=e;return typeof t.access_token==="string"&&t.access_token.length>0&&typeof t.expires_in==="number"&&Number.isFinite(t.expires_in)&&t.expires_in>0},Hle=(e)=>({accessToken:e.access_token,expiresAt:tI(e.access_token,e.expires_in)}),Wle=(e)=>{if(typeof e!=="object"||e===null)return"OAuth token response did not contain an access token";let t=e,r=typeof t.error==="string"?t.error:null,n=typeof t.error_description==="string"?t.error_description:null;if(r&&n)return`${r}: ${n}`;return r??"OAuth token response did not contain an access token"},Vle=(e)=>{let t=e.replace(/\/+$/,"");try{let r=new URL(t);if(qle.has(r.hostname))return`${a4()}/oauth/token`}catch{}return`${t}/oauth/token`},S4=(e,t,r)=>Us.gen(function*(){let n=new URLSearchParams({grant_type:"client_credentials"});if(r)n.set("scope",r);let o=yield*Us.tryPromise({try:()=>fetch(e,{method:"POST",headers:{Authorization:`Basic ${Buffer.from(`${$le}:${t}`).toString("base64")}`,"Content-Type":"application/x-www-form-urlencoded"},body:n}),catch:(a)=>new ni({message:"Failed to call OAuth token endpoint",cause:a})}),i=yield*Us.tryPromise({try:()=>o.text(),catch:(a)=>new ni({message:"Failed to read OAuth token response body",cause:a})}),s=yield*Us.try({try:()=>JSON.parse(i),catch:(a)=>new ni({message:`Failed to parse OAuth token response: ${i.slice(0,200)}`,cause:a})});if(!o.ok||!jle(s))return yield*new ni({message:`OAuth token request failed: ${Wle(s)}`});return yield*Us.try({try:()=>Hle(s),catch:(a)=>new ni({message:a instanceof Error?a.message:"Invalid login credential expiry",cause:a})})}),v4=(e,t,r)=>Us.try({try:()=>{let n=Date.now(),o=new Date(r);if(r<=n)throw new ni({message:"Login expired. Run pfcli auth login again."});d4({version:1,baseUrl:e,accessToken:t,expiresAt:o.toISOString(),loginAt:new Date(n).toISOString()})},catch:(n)=>n instanceof ni?n:new ni({message:"Failed to write credentials",cause:n})}),zle=(e,t)=>Us.gen(function*(){let r=t.trim();if(r.length===0)return yield*new ni({message:"--ci-provider-user must not be empty"});let n=process.env.CI_PIPELINE_SECRET;if(!n)return yield*new ni({message:"CI_PIPELINE_SECRET environment variable is required for --ci-provider-user"});let o=Vle(e),i=oi(e),s=yield*S4(o,n),a=yield*Hr(i,s.accessToken,Ble,{email:r}).pipe(Us.mapError((l)=>new ni({message:l.message,cause:l})));if(!a.requestProviderUserPermissions.success)return yield*new ni({message:a.requestProviderUserPermissions.error??`CI provider user permission denied for ${r}`});let c=yield*S4(o,n,`email:${r}`);yield*v4(e,c.accessToken,c.expiresAt),yield*fO.log("Login successful! Credentials stored.")}),x4=(e,t={})=>Us.gen(function*(){if(t.ciProviderUser)return yield*zle(e,t.ciProviderUser);let r=yield*Us.try({try:()=>pO(new URL("/cli-auth",e).toString()),catch:(o)=>new ni({message:o instanceof Error?o.message:"Invalid login URL",cause:o})}),n=yield*Us.acquireUseRelease(g4,(o)=>Us.gen(function*(){return r.searchParams.set("port",String(o.port)),r.searchParams.set("state",o.state),yield*h4(r.toString()),yield*fO.log("Waiting for login..."),yield*Us.tryPromise({try:()=>o.tokens,catch:(i)=>new ni({message:i instanceof Error?i.message:String(i),cause:i})})}),(o)=>Us.sync(()=>o.stop()));yield*v4(e,n.accessToken,n.expiresAt),yield*fO.log("Login successful! Credentials stored.")});import{createHash as jG,randomUUID as eF}from"crypto";import{cpSync as vge,existsSync as lR,mkdirSync as xge,readFileSync as HG,readdirSync as Ege,renameSync as WG,rmSync as sc,rmdirSync as bge,writeFileSync as wge}from"fs";import{tmpdir as Tge}from"os";import*as De from"path";import{fileURLToPath as ZN,pathToFileURL as VG}from"url";El();import*as gm from"effect/Duration";import*as Za from"effect/Either";import{dual as tHe,identity as Kle}from"effect/Function";import*as mO from"effect/Inspectable";import*as rI from"effect/Option";import{pipeArguments as Gle}from"effect/Pipeable";import*as Qle from"effect/Predicate";import*as Gh from"effect/Record";var E4=Symbol.for("@effect/platform/Cookies");var b4=Symbol.for("@effect/platform/Cookies/Cookie"),Jle=Symbol.for("@effect/platform/Cookies/CookieError");class Kh extends eh(Jle,"CookieError"){get message(){return this.reason}}var Yle={[E4]:E4,...mO.BaseProto,toJSON(){return{_id:"@effect/platform/Cookies",cookies:Gh.map(this.cookies,(e)=>e.toJSON())}},pipe(){return Gle(this,arguments)}},Xle=(e)=>{let t=Object.create(Yle);return t.cookies=e,t},Zle=(e)=>{let t={};for(let r of e)t[r.name]=r;return Xle(t)};var Qh=Zle([]);var ede=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,tde=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,rde=/^[\u0009\u0020-\u003a\u003c-\u007e\u0080-\u00ff]+$/,nde=/^[\u0020-\u003a\u003c-\u007e]+$/,ode={[b4]:b4,...mO.BaseProto,toJSON(){return{_id:"@effect/platform/Cookies/Cookie",name:this.name,value:this.value,options:this.options}}};function ide(e,t,r){if(!tde.test(e))return Za.left(new Kh({reason:"InvalidName"}));let n=encodeURIComponent(t);if(n&&!ede.test(n))return Za.left(new Kh({reason:"InvalidValue"}));if(r!==void 0){if(r.domain!==void 0&&!rde.test(r.domain))return Za.left(new Kh({reason:"InvalidDomain"}));if(r.path!==void 0&&!nde.test(r.path))return Za.left(new Kh({reason:"InvalidPath"}));if(r.maxAge!==void 0&&!gm.isFinite(gm.decode(r.maxAge)))return Za.left(new Kh({reason:"InfinityMaxAge"}))}return Za.right(Object.assign(Object.create(ode),{name:e,value:t,valueEncoded:n,options:r}))}var sde=(e,t,r)=>Za.getOrThrowWith(ide(e,t,r),Kle);function ade(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=gm.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 cde(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?lde(a):a}n=o+1}return t}var lde=(e)=>{try{return decodeURIComponent(e)}catch{return e}};import*as T4 from"effect/FiberRef";import*as A4 from"effect/FiberRefs";import{dual as nI,identity as iHe}from"effect/Function";import{globalValue as dde}from"effect/GlobalValue";import{symbolRedactable as ude}from"effect/Inspectable";import*as pde from"effect/Predicate";import*as I4 from"effect/Record";import*as hO from"effect/Redacted";import*as oI from"effect/Schema";import*as fde from"effect/String";var w4=Symbol.for("@effect/platform/Headers");var Mx=Object.assign(Object.create(null),{[w4]:w4,[ude](e){return mde(this,A4.getOrDefault(e,yde))}}),gO=(e)=>Object.assign(Object.create(Mx),e);var Jh=Object.create(Mx),Jd=(e)=>{if(e===void 0)return Jh;else if(Symbol.iterator in e){let r=Object.create(Mx);for(let[n,o]of e)r[n.toLowerCase()]=o;return r}let t=Object.create(Mx);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},R4=(e)=>Object.setPrototypeOf(e,Mx);var P4=nI(3,(e,t,r)=>{let n=gO(e);return n[t.toLowerCase()]=r,n}),C4=nI(2,(e,t)=>gO({...e,...Jd(t)})),_4=nI(2,(e,t)=>{let r=gO(e);return Object.assign(r,t),r});var mde=nI(2,(e,t)=>{let r={...e},n=(o)=>{if(typeof o==="string"){let i=o.toLowerCase();if(i in e)r[i]=hO.make(e[i])}else for(let i in e)if(o.test(i))r[i]=hO.make(e[i])};if(Array.isArray(t))for(let o=0;o<t.length;o++)n(t[o]);else n(t);return r}),yde=dde("@effect/platform/Headers/currentRedactedNames",()=>T4.unsafeMake(["authorization","cookie","set-cookie","x-api-key"]));import*as D4 from"effect/Data";import*as Lx from"effect/Effect";import{identity as lHe}from"effect/Function";import*as iI from"effect/Inspectable";import*as hde from"effect/Schema";import*as gde from"effect/Stream";var vO=Symbol.for("@effect/platform/HttpBody"),k4=Symbol.for("@effect/platform/HttpBody/HttpBodyError"),Sde=D4.tagged("HttpBodyError"),vde=(e)=>Sde({[k4]:k4,reason:e});class xO{[vO];constructor(){this[vO]=vO}[iI.NodeInspectSymbol](){return this.toJSON()}toString(){return iI.format(this)}}class O4 extends xO{_tag="Empty";toJSON(){return{_id:"@effect/platform/HttpBody",_tag:"Empty"}}}var EO=new O4;class N4 extends xO{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 F4=(e,t)=>new N4(e,t??"application/octet-stream"),xde=new TextEncoder,bO=(e,t)=>F4(xde.encode(e),t??"text/plain"),wO=(e,t)=>bO(JSON.stringify(e),t??"application/json"),U4=(e,t)=>Lx.try({try:()=>wO(e,t),catch:(r)=>vde({_tag:"JsonError",error:r})});El();import*as Pde from"effect/Cause";import*as Bx from"effect/Effect";import*as Cde from"effect/ParseResult";import{hasProperty as GHe}from"effect/Predicate";import*as Ide from"effect/Stream";import*as bde from"effect/Context";import*as Sm from"effect/Effect";import*as M4 from"effect/Effectable";import{dual as L4}from"effect/Function";import*as Yh from"effect/Inspectable";import*as wde from"effect/Runtime";import*as TO from"effect/Stream";var sI=Symbol.for("@effect/platform/HttpServerResponse"),Tde=Symbol.for("@effect/platform/HttpServerRespondable");class Ep extends M4.StructuralClass{status;statusText;cookies;body;[sI];headers;constructor(e,t,r,n,o){super();if(this.status=e,this.statusText=t,this.cookies=n,this.body=o,this[sI]=sI,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 Sm.succeed(this)}[Tde](){return Sm.succeed(this)}[Yh.NodeInspectSymbol](){return this.toJSON()}toString(){return Yh.format(this)}toJSON(){return{_id:"@effect/platform/HttpServerResponse",status:this.status,statusText:this.statusText,headers:Yh.redact(this.headers),cookies:this.cookies.toJSON(),body:this.body.toJSON()}}}var B4=(e)=>typeof e==="object"&&e!==null&&(sI in e),$4=(e)=>new Ep(e?.status??204,e?.statusText,e?.headers?Jd(e.headers):Jh,e?.cookies??Qh,EO),q4=(e,t)=>{let r=R4({location:e.toString()});return new Ep(t?.status??302,t?.statusText,t?.headers?_4(r,Jd(t.headers)):r,t?.cookies??Qh,EO)};var j4=(e,t)=>{let r=t?.headers?Jd(t.headers):Jh;return new Ep(t?.status??200,t?.statusText,r,t?.cookies??Qh,bO(e,AO(t,r)))};var H4=(e,t)=>{let r=t?.headers?Jd(t.headers):Jh;return Sm.map(U4(e,AO(t,r)),(n)=>new Ep(t?.status??200,t?.statusText,r,t?.cookies??Qh,n))},W4=(e,t)=>{let r=t?.headers?Jd(t.headers):Jh;return new Ep(t?.status??200,t?.statusText,r,t?.cookies??Qh,wO(e,AO(t,r)))};var AO=(e,t)=>{if(e?.contentType)return e.contentType;else if(e?.headers)return t["content-type"];else return},V4=L4(3,(e,t,r)=>new Ep(e.status,e.statusText,P4(e.headers,t,r),e.cookies,e.body));var z4=L4(2,(e,t)=>new Ep(e.status,e.statusText,C4(e.headers,t),e.cookies,e.body));var K4=B4,aI=$4,cI=q4;var Xh=j4;var Rde=H4;var IO=W4;var lI=V4,Zh=z4;var RO=Symbol.for("@effect/platform/HttpServerRespondable");var dI=(e)=>{if(K4(e))return Bx.succeed(e);return Bx.orDie(e[RO]())};import*as bp from"effect/Cause";import*as Q4 from"effect/Effect";import*as _de from"effect/FiberId";import{globalValue as JHe}from"effect/GlobalValue";import*as J4 from"effect/Option";import*as kde from"effect/Predicate";var Y4=Symbol.for("@effect/platform/HttpServerError");var Ode=Y4;class PO extends eh(Ode,"RouteNotFound"){constructor(e){super(e);this.stack=`${this.name}: ${this.message}`}[RO](){return aI({status:404})}get message(){return`${this.request.method} ${this.request.url} not found`}}import*as iz from"effect/Effect";import*as sz from"effect/Either";import*as jde from"effect/Option";import*as Hde from"effect/Runtime";import*as Wde from"effect/Stream";import*as Lde from"effect/Channel";import*as CO from"effect/Context";import*as Yd from"effect/Effect";import*as Bde from"effect/Inspectable";import*as rz from"effect/Option";import*as $de from"effect/Schema";import*as fI from"effect/Stream";import*as X4 from"effect/Context";import*as uI from"effect/Effect";import{dual as Fde}from"effect/Function";import*as Ude from"effect/Inspectable";import*as pI from"effect/Option";import*as Mde from"effect/Schema";class Z4 extends X4.Reference()("@effect/platform/HttpIncomingMessage/MaxBodySize",{defaultValue:pI.none}){}var ez=Fde(2,(e,t)=>uI.provideService(e,Z4,pI.map(t,Vu)));var nz=CO.GenericTag("@effect/platform/HttpServerRequest"),oz=CO.GenericTag("@effect/platform/HttpServerRequest/ParsedSearchParams");var on=nz,az=oz;import*as mI from"effect/Context";import*as ec from"effect/Effect";import*as _O from"effect/FiberRef";import{constFalse as x2e,dual as E2e}from"effect/Function";import*as Vde from"effect/Function";import{globalValue as w2e}from"effect/GlobalValue";import*as kO from"effect/Layer";import*as zde from"effect/Option";var cz=(e)=>e;var DO=cz;import*as bo from"effect/Chunk";import*as Xd from"effect/Context";import*as xn from"effect/Effect";import*as wz from"effect/Effectable";import*as wp from"effect/FiberRef";import{dual as jx}from"effect/Function";import{globalValue as iue}from"effect/GlobalValue";import*as eg from"effect/Inspectable";import*as Hx from"effect/Layer";import*as Xc from"effect/Option";import*as Tz from"effect/Predicate";import*as sue from"effect/Schema";import*as Az from"effect/Tracer";var lz=/\+/g,dz=function(){};dz.prototype=Object.create(null);function uz(e){let t=new dz;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,p=0;for(let y=0;y<r+1;y++)if(p=y!==r?e.charCodeAt(y):38,p===38){if(u=s>i,!u)s=y;if(n=e.slice(i+1,s),u||n.length>0){if(l)n=n.replace(lz," ");if(a)try{n=decodeURIComponent(n)||n}catch{}if(u){if(o=e.slice(s+1,y),d)o=o.replace(lz," ");if(c)try{o=decodeURIComponent(o)||o}catch{}}let g=t[n];if(g===void 0)t[n]=o;else if(g.pop)g.push(o);else t[n]=[g,o]}o="",i=y,s=y,a=!1,c=!1,l=!1,d=!1}else if(p===61)if(s<=i)s=y;else c=!0;else if(p===43)if(s>i)d=!0;else l=!0;else if(p===37)if(s>i)c=!0;else a=!0;return t}var Qde=/^https?:\/\/.*?\//,OO=/(\/:[^/()]*?)\?(\/?)/,yz=(e={})=>new hz(e);class hz{constructor(e={}){this.options={ignoreTrailingSlash:!0,ignoreDuplicateSlashes:!0,caseSensitive:!1,maxParamLength:100,...e}}options;routes=[];trees={};on(e,t,r){let n=t.match(OO);if(n&&n.index!==void 0){Jde(t.length===n.index+n[0].length,"Optional Parameter needs to be the last parameter of the path");let i=t.replace(OO,"$1$2"),s=t.replace(OO,"$2");this.on(e,i,r),this.on(e,s,r);return}if(this.options.ignoreDuplicateSlashes)t=pz(t);if(this.options.ignoreTrailingSlash)t=fz(t);let o=typeof e==="string"?[e]:e;for(let i of o)this._on(i,t,r)}all(e,t){this.on(rue,e,t)}_on(e,t,r){if(this.trees[e]===void 0)this.trees[e]=new $x("/");let n=t;if(n==="*"&&this.trees[e].prefix.length!==0){let c=this.trees[e];this.trees[e]=new $x(""),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,p=[],y=c+1;for(let g=y;;g++){let E=n.charCodeAt(g),S=E===40,x=E===45||E===46,w=E===47||g===n.length;if(S||x||w){let _=n.slice(y,g);if(s.push(_),u=u||S||x,S){let I=Xde(n,g),O=n.slice(g,I+1);p.push(Zde(O)),g=I+1}else p.push("(.*?)");let T=g;for(;g<n.length;g++){let I=n.charCodeAt(g);if(I===47)break;if(I===58)if(n.charCodeAt(g+1)===58)g++;else break}let b=n.slice(T,g);if(b)b=b.split("::").join(":"),b=b.split("%").join("%25"),p.push(eue(b));if(y=g+1,w||n.charCodeAt(g)===47||g===n.length){let I=u?"()"+b:b,O=n.slice(c,g);n=n.slice(0,c+1)+I+n.slice(g),c+=I.length;let L=u?new RegExp("^"+p.join("")+"$"):void 0;i=i.createParametricChild(L,b,O),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(Qde,"/");if(this.options.ignoreDuplicateSlashes)t=pz(t);let n,o,i;try{n=tue(t),t=n.path,o=n.querystring,i=n.shouldDecodeParam}catch(p){return}if(this.options.ignoreTrailingSlash)t=fz(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 y=r.handlerStorage?.find();if(y!==void 0)return{handler:y.handler,params:y.createParams(l),searchParams:uz(o)}}let p=r.getNextNode(t,c,u,l.length);if(p===void 0){if(u.length===0)return;let y=u.pop();c=y.brotherPathIndex,l.splice(y.paramsCount),p=y.brotherNode}if(r=p,r._tag==="StaticNode"){c+=r.prefix.length;continue}if(r._tag==="WildcardNode"){let y=s.slice(c);if(i)y=mz(y);l.push(y),c=d;continue}if(r._tag==="ParametricNode"){let y=s.indexOf("/",c);if(y===-1)y=d;let g=s.slice(c,y);if(i)g=mz(g);if(r.regex!==void 0){let E=r.regex.exec(g);if(E===null)continue;for(let S=1;S<E.length;S++){let x=E[S];if(x.length>a)return;l.push(x)}}else{if(g.length>a)return;l.push(g)}c=y}}}}class gz{handlers=[];unconstrainedHandler;find(){return this.unconstrainedHandler}add(e){let t={params:e.params,handler:e.handler,createParams:Yde(e.params)};this.handlers.push(t),this.unconstrainedHandler=this.handlers[0]}}class NO{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 gz;this.isLeafNode=!0,this.handlerStorage.add(e)}}class FO extends NO{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 $x(e),this.staticChildren[r]}}class $x extends FO{_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 Sz(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 vz;return this.wildcardChild}split(e,t){let r=this.prefix.slice(0,t),n=this.prefix.slice(t);this.setPrefix(n);let o=new $x(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 Sz extends FO{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 vz extends NO{_tag="WildcardNode";getNextNode(e,t,r,n){return}}var Jde=(e,t)=>{if(!e)throw Error(t)};function pz(e){return e.replace(/\/\/+/g,"/")}function fz(e){if(e.length>1&&e.charCodeAt(e.length-1)===47)return e.slice(0,-1);return e}function Yde(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 Xde(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 Zde(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 eue(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xz(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 tue(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(xz(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 mz(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=xz(i,s);r+=e.slice(n,o)+a,n=o+3}return e.slice(0,t)+r+e.slice(n)}var rue=["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 Ez=yz;var qx=Symbol.for("@effect/platform/HttpRouter"),hI=Symbol.for("@effect/platform/HttpRouter/Route"),gI=Symbol.for("@effect/platform/HttpRouter/RouteContext"),UO=Xd.GenericTag("@effect/platform/HttpRouter/RouteContext"),aue=(e)=>Tz.hasProperty(e,qx);var Iz=iue("@effect/platform/HttpRouter/currentRouterConfig",()=>wp.unsafeMake({}));class tg extends wz.StructuralClass{routes;mounts;[qx];constructor(e,t){super();this.routes=e,this.mounts=t,this[qx]=qx,this.httpApp=Rz(this).pipe(xn.flatMap((r)=>this.httpApp=r))}httpApp;commit(){return this.httpApp}toJSON(){return{_id:"Router",routes:this.routes.toJSON(),mounts:this.mounts.toJSON()}}toString(){return eg.format(this)}[eg.NodeInspectSymbol](){return this.toJSON()}}var Rz=(e)=>xn.map(wp.get(Iz),(t)=>{let r=Ez(t),n=bo.toReadonlyArray(e.mounts).map(([i,s,a])=>[i,new MO(new Wx("*",a?.includePrefix?`${i}/*`:"/*",s,a?.includePrefix?Xc.none():Xc.some(i),!1),{}),a]),o=n.length;return bo.forEach(e.routes,(i)=>{if(i.method==="*")r.all(i.path,i);else r.on(i.method,i.path,i)}),xn.withFiberRuntime((i)=>{let s=Xd.unsafeMake(new Map(i.getFiberRef(wp.currentContext).unsafeMap)),a=Xd.unsafeGet(s,on);if(o>0){let p=a.url.indexOf("?"),y=p===-1?a.url:a.url.slice(0,p);for(let g=0;g<o;g++){let[E,S,x]=n[g];if(y===E||y.startsWith(E+"/")){if(s.unsafeMap.set(UO.key,S),x?.includePrefix!==!0)s.unsafeMap.set(on.key,bz(a,E));return xn.locally(xn.flatMap(S.route.handler,dI),wp.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 xn.fail(new PO({request:a}));let l=c.handler;if(l.prefix._tag==="Some")s.unsafeMap.set(on.key,bz(a,l.prefix.value));s.unsafeMap.set(az.key,c.searchParams),s.unsafeMap.set(UO.key,new MO(l,c.params));let d=Xd.getOption(s,Az.ParentSpan);if(d._tag==="Some"&&d.value._tag==="Span")d.value.attribute("http.route",l.path);let u=xn.flatMap(l.handler,dI);return xn.locally(l.uninterruptible?u:xn.interruptible(u),wp.currentContext,s)})});function bz(e,t){let r=t.length;return e.modify({url:e.url.length<=r?"/":e.url.slice(r)})}class Wx extends eg.Class{method;path;handler;prefix;uninterruptible;[hI];constructor(e,t,r,n=Xc.none(),o=!1){super();this.method=e,this.path=t,this.handler=r,this.prefix=n,this.uninterruptible=o,this[hI]=hI}toJSON(){return{_id:"@effect/platform/HttpRouter/Route",method:this.method,path:this.path,prefix:this.prefix.toJSON()}}}class MO{route;params;[gI];constructor(e,t){this.route=e,this.params=t,this[gI]=gI}}var Pz=new tg(bo.empty(),bo.empty());var Cz=jx(2,(e,t)=>_z(e,t)),_z=(...e)=>new tg(e.reduce((t,r)=>bo.appendAll(t,r.routes),bo.empty()),e.reduce((t,r)=>bo.appendAll(t,r.mounts),bo.empty())),cue=(e)=>e.endsWith("/")?e.slice(0,-1):e;var kz=jx(2,(e,t)=>(t=cue(t),new tg(bo.map(e.routes,(r)=>new Wx(r.method,r.path==="/"?t:t+r.path,r.handler,Xc.orElse(Xc.map(r.prefix,(n)=>t+n),()=>Xc.some(t)),r.uninterruptible)),bo.map(e.mounts,([r,n])=>[r==="/"?t:t+r,n])))),Dz=jx(3,(e,t,r)=>Cz(e,kz(r,t)));var LO=(e)=>jx((t)=>aue(t[0]),(t,r,n,o)=>new tg(bo.append(t.routes,new Wx(e,r,n,Xc.none(),o?.uninterruptible??!1)),t.mounts));var Oz=LO("GET"),Nz=LO("POST");var Fz=jx(2,(e,t)=>new tg(bo.map(e.routes,(r)=>new Wx(r.method,r.path,t(xn.flatMap(r.handler,dI)),r.prefix,r.uninterruptible)),bo.map(e.mounts,([r,n])=>[r,t(n)])));var due=Pz;var uue=Dz;var rg=Oz,tc=Nz;var BO=Fz;import{ARTIFACT_INVENTORY_FILENAME as Age,ARTIFACT_INVENTORY_FORMAT as Ige,ARTIFACT_INVENTORY_VERSION as Rge}from"@processfocus/runtime";import{Console as Lr,Effect as En}from"effect";var Iue=so(wi(),1);import*as aE from"path";import{Config as ege,Context as tge,Data as rge,Effect as DG,Layer as QN}from"effect";import{Data as cg,Effect as w4e,Match as T4e,Option as A4e}from"effect";import*as Bpe from"effect/SchemaAST";import{Schema as AVe,SchemaAST as IVe}from"effect";var jO=Symbol.for("pf/form/annotation/Required");var HO=Symbol.for("pf/form/annotation/EmailInput"),WO=Symbol.for("pf/form/annotation/PhoneInput");var tK=Symbol.for("pf/form/annotation/ComponentPluginType");var pK=so(lK(),1);import{Schema as ig}from"effect";var sg=Symbol.for("processfocus:internal-tag/form-schema/structural-only"),fK=Symbol.for("processfocus:internal-tag/form-schema/structural-type");var mK=(e,t)=>ig.Undefined.annotations({[sg]:!0,[fK]:e,...t}),vVe=mK("structural"),xVe=mK("divider");var upe=(e)=>pK.default(e,{protocols:["https"],require_protocol:!0,require_tld:!0}),EVe=ig.String.pipe(ig.filter(upe,{message:()=>"Must be a valid HTTPS URL (e.g. https://example.com/path)"}),ig.annotations({arbitrary:()=>(e)=>e.webUrl({validSchemes:["https"]})}));var bVe=ig.Boolean.pipe(ig.filter((e)=>e===!0,{message:()=>"This field is required",jsonSchema:{type:"boolean",enum:[!0]},[jO]:!0}));var xK=so(vK(),1);import{Schema as fN}from"effect";var NVe=fN.Trim.pipe(fN.filter((e)=>xK.default(e,{require_tld:!1,allow_utf8_local_part:!0,allow_ip_domain:!0}),{message:()=>"must be a valid email address"}),fN.annotations({identifier:"Email",title:"Email address",description:"A valid email address",jsonSchema:{format:"email"},[HO]:!0}));import{Either as MVe,Schema as LVe}from"effect";import{ArrayFormatter as $Ve}from"effect/ParseResult";import{Schema as mN}from"effect";var kpe=/^\+?[\d\s\-()]+$/,Dpe=(e)=>(e.match(/\d/g)||[]).length,Ope=(e)=>{if(!kpe.test(e))return!1;let t=Dpe(e);return t>=7&&t<=15},VVe=mN.Trim.pipe(mN.filter((e)=>Ope(e),{message:()=>"must be a valid phone number (7-15 digits)"}),mN.annotations({identifier:"Phone",title:"Phone number",description:"A valid phone number",jsonSchema:{format:"phone"},[WO]:!0}));import{Schema as GVe}from"effect";import{TitleAnnotationId as s4e}from"effect/SchemaAST";import{cleanupAllPlugins as u4e,getMatchingPlugin as Upe,registerWalkerPlugin as p4e,unregisterWalkerPlugin as f4e}from"@processfocus/runtime";class $pe extends cg.TaggedError("UnknownSchemaFieldTypeError"){get message(){return`Cannot create form field "${this.fieldName}": schema type "${this.schemaType}" is not supported`}}class qpe extends cg.TaggedError("IndexSignaturesNotSupportedError"){get message(){return"Index signatures are not supported in schemas"}}class jpe extends cg.TaggedError("UnrecognizedASTNodeError"){get message(){return`AST node type "${this.nodeTag}" is not recognized`}}class Hpe extends cg.TaggedError("InvalidPropertyKeyError"){get message(){return`Property keys must be strings or numbers, got: ${String(this.propertyKey)}`}}class Wpe extends cg.TaggedError("InvalidFieldPermissionError"){get message(){return`Cannot apply field permission to "${this.fieldName}": ${this.reason}`}}class Vpe extends cg.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 Zpe=so(wi(),1);import{createHash as Qpe}from"crypto";import{readFileSync as Jpe,realpathSync as AK,statSync as Ype}from"fs";import{basename as Xpe,extname as IK,isAbsolute as yN,relative as EK,resolve as bK,sep as wK}from"path";var Kx="/_pf/app-icons/",efe=new Map([[".ico","image/x-icon"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".png","image/png"],[".svg","image/svg+xml"],[".webp","image/webp"]]);class Zd extends Error{}var tfe=(e)=>{try{return AK(e)}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")throw new Zd(`AppIcons base path not found: ${e}`,{cause:t});throw t}};var rfe=(e)=>{if(!e.startsWith(Kx))throw Error(`AppIcons publicPath must be inside ${Kx}`);let t=e.slice(Kx.length);if(t.length===0||t.includes("\\")||t.split("/").some((r)=>r===""||r==="."||r===".."))throw Error(`AppIcons publicPath must be inside ${Kx}`);return e},nfe=(e,t)=>{if(e.trim().length===0)throw new Zd("AppIcons source must be a non-empty string");if(yN(e))throw new Zd("AppIcons source must be a relative org-local file");let r=bK(t??process.cwd()),n=bK(r,e),o=EK(r,n);if(o.length===0||o===".."||o.startsWith(`..${wK}`)||yN(o))throw new Zd("AppIcons source must be a relative org-local file");try{let i=tfe(r);if(!Ype(n).isFile())throw new Zd(`AppIcons source must be a file: ${e}`);let a=AK(n),c=EK(i,a);if(c.length===0||c===".."||c.startsWith(`..${wK}`)||yN(c))throw new Zd("AppIcons source must be a relative org-local file")}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")throw new Zd(`AppIcons source file not found: ${e}`,{cause:i});if(i instanceof Zd)throw i;throw Error(`Failed to inspect AppIcons source file: ${e}`,{cause:i})}return n},TK=(e)=>efe.get(IK(e).toLowerCase()),ofe=(e)=>{let t;try{t=Jpe(e)}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")throw Error(`AppIcons source file not found: ${e}`,{cause:i});throw Error(`Failed to read AppIcons source file: ${e}`,{cause:i})}let r=Qpe("sha256").update(t).digest("hex").slice(0,16),n=IK(e),o=Xpe(e,n);return`${Kx}${o}-${r}${n}`},ife=(e)=>e.node.findAll().filter((t)=>t.isAppIcons===!0),RK=(e)=>{let t=ife(e);if(t.length>1)throw Error("Organisation must declare at most one AppIcons set");return t[0]},PK=(e,t)=>{let r=e.publicPath===void 0?void 0:rfe(e.publicPath),n=nfe(e.source,t);return{sourcePath:n,publicPath:r===void 0?ofe(n):r}},CK=(e,t)=>{let r=RK(e);if(!r)return{metadata:[],manifest:[]};let n=new Map,o=(i)=>{let{sourcePath:s,publicPath:a}=PK(i,t?.basePath),c=n.get(a);if(c!==void 0&&c!==s)throw Error(`Duplicate AppIcons publicPath: ${a}`);return n.set(a,s),a};return{metadata:r.metadata.map((i)=>({url:o(i),rel:i.rel??"icon",type:i.type??TK(i.source),sizes:i.sizes})),manifest:r.manifest.map((i)=>({src:o(i),sizes:i.sizes,type:i.type??TK(i.source),purpose:i.purpose}))}},_K=(e,t)=>{let r=RK(e);if(!r)return[];let n=[...r.metadata,...r.manifest],o=new Map;for(let i of n){let{sourcePath:s,publicPath:a}=PK(i,t?.basePath),c=o.get(a);if(c!==void 0){if(c.sourcePath!==s)throw Error(`Duplicate AppIcons publicPath: ${a}`);continue}o.set(a,{sourcePath:s,publicPath:a})}return[...o.values()]};var kK=(e,t)=>typeof e==="object"&&e!==null&&(t in e)&&e[t]===!0;var DK=(e)=>kK(e,"isOrganisation"),Gx=(e)=>kK(e,"isProcess");import{Context as afe,Data as NI,Effect as rze}from"effect";var To=(e)=>e.startsWith("/")?e:`/${e}`;var Qx=(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 cfe extends NI.TaggedError("SourceStepNotFoundError"){}class lfe extends NI.TaggedError("EdgeNotFoundError"){}class dfe extends NI.TaggedError("ConditionFunctionMissingError"){}class ufe extends NI.TaggedError("ConditionEvaluationError"){}class pfe extends afe.Tag("processfocus:internal-tag/process/ConditionEvaluator")(){}var ffe=so(wi(),1);var mfe=so(wi(),1);var yfe=so(wi(),1);import{DateTime as lze}from"effect";import{Context as xfe,Data as FK,Effect as Pze}from"effect";import{Context as Sfe,Data as OK,Effect as wze}from"effect";var hfe=so(wi(),1);import{Schema as hze}from"effect";class vfe extends OK.TaggedError("ForEachStepRequiresItemsError"){}class hN extends OK.TaggedError("NotAForEachStepError"){}class NK extends Sfe.Tag("processfocus:internal-tag/process/CurrentStepJobContext")(){}class Efe extends FK.TaggedError("ForEachStepNotFoundError"){}class bfe extends FK.TaggedError("ForEachItemsError"){}class wfe extends xfe.Tag("processfocus:internal-tag/process/ForEachItemsResolver")(){}import{Data as Nfe,Effect as TKe,JSONSchema as AKe,Option as IKe,Schema as RKe,SchemaAST as PKe}from"effect";import{Data as LK,Effect as Dze,Either as Oze,Schema as Nze,SchemaAST as Fze}from"effect";class Afe extends LK.TaggedError("FieldNameCollisionError"){get message(){return`Field name collision: "${this.wrapperField}" is already present as "${this.fieldName}" in its parent struct`}}class Ife extends LK.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 Bze}from"effect";import{Schema as iKe,SchemaAST as sKe}from"effect";import{Data as Cfe,Effect as zze,Schema as Zc,SchemaAST as Kze}from"effect";class SN extends Cfe.TaggedError("FormDecorationError"){}var Qze=Zc.Array(Zc.Struct({value:Zc.String,label:Zc.String})),Jze=Zc.Array(Zc.Struct({value:Zc.String,startsAt:Zc.String,endsAt:Zc.String,label:Zc.optional(Zc.String)}));import{Effect as uKe,Option as pKe,Schema as fKe,SchemaAST as mKe}from"effect";class Ffe extends Nfe.TaggedError("LookupFieldNotFoundError"){}var Ufe=so(wi(),1);var Mfe=so(wi(),1);import{Data as lg,Effect as WKe,String as VKe,JSONSchema as zKe,Option as KKe,SchemaAST as GKe,Schema as QKe}from"effect";class Lfe extends lg.TaggedError("ListItemQueryNotDefinedError"){get message(){return`List ${this.listPath} has no itemQuery defined`}}class Bfe extends lg.TaggedError("ListItemUpdateNotDefinedError"){get message(){return`List ${this.listPath} has no update function defined`}}class $fe extends lg.TaggedError("ListItemDeleteNotDefinedError"){get message(){return`List ${this.listPath} has no delete function defined`}}class qfe extends lg.TaggedError("ListCreateError"){}class jfe extends lg.TaggedError("ListCreateNotDefinedError"){}class Hfe extends lg.TaggedError("ListUpdateValidationError"){}var Wfe=so(wi(),1);var Xme=so(wi(),1);import{EventEmitter as Vfe}from"events";function zfe(){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 jo=zfe;if(typeof Object.assign==="function")jo=Object.assign;function oc(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 Ti(e){return typeof e==="object"&&e!==null}function WK(e){let t;for(t in e)return!1;return!0}function nc(e,t,r){Object.defineProperty(e,t,{enumerable:!1,configurable:!1,writable:!0,value:r})}function el(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 qK(e){if(!Ti(e))return!1;if(e.attributes&&!Array.isArray(e.attributes))return!1;return!0}function Kfe(){let e=Math.floor(Math.random()*256)&255;return()=>e++}function eu(){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 ug(){return{[Symbol.iterator](){return this},next(){return{done:!0}}}}class UI extends Error{constructor(e){super();this.name="GraphError",this.message=e}}class Ne extends UI{constructor(e){super(e);if(this.name="InvalidArgumentsGraphError",typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,Ne.prototype.constructor)}}class ve extends UI{constructor(e){super(e);if(this.name="NotFoundGraphError",typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,ve.prototype.constructor)}}class mt extends UI{constructor(e){super(e);if(this.name="UsageGraphError",typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,mt.prototype.constructor)}}function VK(e,t){this.key=e,this.attributes=t,this.clear()}VK.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 zK(e,t){this.key=e,this.attributes=t,this.clear()}zK.prototype.clear=function(){this.inDegree=0,this.outDegree=0,this.directedLoops=0,this.in={},this.out={}};function KK(e,t){this.key=e,this.attributes=t,this.clear()}KK.prototype.clear=function(){this.undirectedDegree=0,this.undirectedLoops=0,this.undirected={}};function pg(e,t,r,n,o){this.key=t,this.attributes=o,this.undirected=e,this.source=r,this.target=n}pg.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};pg.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};pg.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]};pg.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 GK=0,QK=1,Gfe=2,JK=3;function tu(e,t,r,n,o,i,s){let a,c,l,d;if(n=""+n,r===GK){if(a=e._nodes.get(n),!a)throw new ve(`Graph.${t}: could not find the "${n}" node in the graph.`);l=o,d=i}else if(r===JK){if(o=""+o,c=e._edges.get(o),!c)throw new ve(`Graph.${t}: could not find the "${o}" edge in the graph.`);let u=c.source.key,p=c.target.key;if(n===u)a=c.target;else if(n===p)a=c.source;else throw new ve(`Graph.${t}: the "${n}" node is not attached to the "${o}" edge (${u}, ${p}).`);l=i,d=s}else{if(c=e._edges.get(n),!c)throw new ve(`Graph.${t}: could not find the "${n}" edge in the graph.`);if(r===QK)a=c.source;else a=c.target;l=o,d=i}return[a,l,d]}function Qfe(e,t,r){e.prototype[t]=function(n,o,i){let[s,a]=tu(this,t,r,n,o,i);return s.attributes[a]}}function Jfe(e,t,r){e.prototype[t]=function(n,o){let[i]=tu(this,t,r,n,o);return i.attributes}}function Yfe(e,t,r){e.prototype[t]=function(n,o,i){let[s,a]=tu(this,t,r,n,o,i);return s.attributes.hasOwnProperty(a)}}function Xfe(e,t,r){e.prototype[t]=function(n,o,i,s){let[a,c,l]=tu(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 Zfe(e,t,r){e.prototype[t]=function(n,o,i,s){let[a,c,l]=tu(this,t,r,n,o,i,s);if(typeof l!=="function")throw new Ne(`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 eme(e,t,r){e.prototype[t]=function(n,o,i){let[s,a]=tu(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 tme(e,t,r){e.prototype[t]=function(n,o,i){let[s,a]=tu(this,t,r,n,o,i);if(!Ti(a))throw new Ne(`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 rme(e,t,r){e.prototype[t]=function(n,o,i){let[s,a]=tu(this,t,r,n,o,i);if(!Ti(a))throw new Ne(`Graph.${t}: provided attributes are not a plain object.`);return jo(s.attributes,a),this.emit("nodeAttributesUpdated",{key:s.key,type:"merge",attributes:s.attributes,data:a}),this}}function nme(e,t,r){e.prototype[t]=function(n,o,i){let[s,a]=tu(this,t,r,n,o,i);if(typeof a!=="function")throw new Ne(`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 ome=[{name:(e)=>`get${e}Attribute`,attacher:Qfe},{name:(e)=>`get${e}Attributes`,attacher:Jfe},{name:(e)=>`has${e}Attribute`,attacher:Yfe},{name:(e)=>`set${e}Attribute`,attacher:Xfe},{name:(e)=>`update${e}Attribute`,attacher:Zfe},{name:(e)=>`remove${e}Attribute`,attacher:eme},{name:(e)=>`replace${e}Attributes`,attacher:tme},{name:(e)=>`merge${e}Attributes`,attacher:rme},{name:(e)=>`update${e}Attributes`,attacher:nme}];function ime(e){ome.forEach(function({name:t,attacher:r}){r(e,t("Node"),GK),r(e,t("Source"),QK),r(e,t("Target"),Gfe),r(e,t("Opposite"),JK)})}function sme(e,t,r){e.prototype[t]=function(n,o){let i;if(this.type!=="mixed"&&r!=="mixed"&&r!==this.type)throw new mt(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new mt(`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=oc(this,s,a,r),!i)throw new ve(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(r!=="mixed")throw new mt(`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 ve(`Graph.${t}: could not find the "${n}" edge in the graph.`)}return i.attributes[o]}}function ame(e,t,r){e.prototype[t]=function(n){let o;if(this.type!=="mixed"&&r!=="mixed"&&r!==this.type)throw new mt(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>1){if(this.multi)throw new mt(`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=oc(this,i,s,r),!o)throw new ve(`Graph.${t}: could not find an edge for the given path ("${i}" - "${s}").`)}else{if(r!=="mixed")throw new mt(`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 ve(`Graph.${t}: could not find the "${n}" edge in the graph.`)}return o.attributes}}function cme(e,t,r){e.prototype[t]=function(n,o){let i;if(this.type!=="mixed"&&r!=="mixed"&&r!==this.type)throw new mt(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new mt(`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=oc(this,s,a,r),!i)throw new ve(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(r!=="mixed")throw new mt(`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 ve(`Graph.${t}: could not find the "${n}" edge in the graph.`)}return i.attributes.hasOwnProperty(o)}}function lme(e,t,r){e.prototype[t]=function(n,o,i){let s;if(this.type!=="mixed"&&r!=="mixed"&&r!==this.type)throw new mt(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>3){if(this.multi)throw new mt(`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=oc(this,a,c,r),!s)throw new ve(`Graph.${t}: could not find an edge for the given path ("${a}" - "${c}").`)}else{if(r!=="mixed")throw new mt(`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 ve(`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 dme(e,t,r){e.prototype[t]=function(n,o,i){let s;if(this.type!=="mixed"&&r!=="mixed"&&r!==this.type)throw new mt(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>3){if(this.multi)throw new mt(`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=oc(this,a,c,r),!s)throw new ve(`Graph.${t}: could not find an edge for the given path ("${a}" - "${c}").`)}else{if(r!=="mixed")throw new mt(`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 ve(`Graph.${t}: could not find the "${n}" edge in the graph.`)}if(typeof i!=="function")throw new Ne(`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 ume(e,t,r){e.prototype[t]=function(n,o){let i;if(this.type!=="mixed"&&r!=="mixed"&&r!==this.type)throw new mt(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new mt(`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=oc(this,s,a,r),!i)throw new ve(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(r!=="mixed")throw new mt(`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 ve(`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 pme(e,t,r){e.prototype[t]=function(n,o){let i;if(this.type!=="mixed"&&r!=="mixed"&&r!==this.type)throw new mt(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new mt(`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=oc(this,s,a,r),!i)throw new ve(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(r!=="mixed")throw new mt(`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 ve(`Graph.${t}: could not find the "${n}" edge in the graph.`)}if(!Ti(o))throw new Ne(`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 fme(e,t,r){e.prototype[t]=function(n,o){let i;if(this.type!=="mixed"&&r!=="mixed"&&r!==this.type)throw new mt(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new mt(`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=oc(this,s,a,r),!i)throw new ve(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(r!=="mixed")throw new mt(`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 ve(`Graph.${t}: could not find the "${n}" edge in the graph.`)}if(!Ti(o))throw new Ne(`Graph.${t}: provided attributes are not a plain object.`);return jo(i.attributes,o),this.emit("edgeAttributesUpdated",{key:i.key,type:"merge",attributes:i.attributes,data:o}),this}}function mme(e,t,r){e.prototype[t]=function(n,o){let i;if(this.type!=="mixed"&&r!=="mixed"&&r!==this.type)throw new mt(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new mt(`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=oc(this,s,a,r),!i)throw new ve(`Graph.${t}: could not find an edge for the given path ("${s}" - "${a}").`)}else{if(r!=="mixed")throw new mt(`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 ve(`Graph.${t}: could not find the "${n}" edge in the graph.`)}if(typeof o!=="function")throw new Ne(`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 yme=[{name:(e)=>`get${e}Attribute`,attacher:sme},{name:(e)=>`get${e}Attributes`,attacher:ame},{name:(e)=>`has${e}Attribute`,attacher:cme},{name:(e)=>`set${e}Attribute`,attacher:lme},{name:(e)=>`update${e}Attribute`,attacher:dme},{name:(e)=>`remove${e}Attribute`,attacher:ume},{name:(e)=>`replace${e}Attributes`,attacher:pme},{name:(e)=>`merge${e}Attributes`,attacher:fme},{name:(e)=>`update${e}Attributes`,attacher:mme}];function hme(e){yme.forEach(function({name:t,attacher:r}){r(e,t("Edge"),"mixed"),r(e,t("DirectedEdge"),"directed"),r(e,t("UndirectedEdge"),"undirected")})}var gme=[{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 Sme(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 vme(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 vN(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 xme(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 Eme(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 xN(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 bme(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 YK(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:p,target:y}=a;if(c=n(d,u,p.key,y.key,p.attributes,y.attributes,a.undirected),e&&c)return d}return}function wme(e,t){if(e.size===0)return ug();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 EN(e,t,r,n,o,i){let s=t?vme:Sme,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 Tme(e,t,r,n){let o=[];return EN(!1,e,t,r,n,function(i){o.push(i)}),o}function Ame(e,t,r){let n=ug();if(e!=="undirected"){if(t!=="out"&&typeof r.in<"u")n=eu(n,vN(r.in));if(t!=="in"&&typeof r.out<"u")n=eu(n,vN(r.out,!t?r.key:void 0))}if(e!=="directed"&&typeof r.undirected<"u")n=eu(n,vN(r.undirected));return n}function bN(e,t,r,n,o,i,s){let a=r?Eme:xme,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 Ime(e,t,r,n,o){let i=[];return bN(!1,e,t,r,n,o,function(s){i.push(s)}),i}function Rme(e,t,r,n){let o=ug();if(e!=="undirected"){if(typeof r.in<"u"&&t!=="out"&&n in r.in)o=eu(o,xN(r.in,n));if(typeof r.out<"u"&&t!=="in"&&n in r.out&&(t||r.key!==n))o=eu(o,xN(r.out,n))}if(e!=="directed"){if(typeof r.undirected<"u"&&n in r.undirected)o=eu(o,xN(r.undirected,n))}return o}function Pme(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 bme(this,n);if(arguments.length===1){i=""+i;let a=this._nodes.get(i);if(typeof a>"u")throw new ve(`Graph.${r}: could not find the "${i}" node in the graph.`);return Tme(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 ve(`Graph.${r}: could not find the "${i}" source node in the graph.`);if(!this._nodes.has(s))throw new ve(`Graph.${r}: could not find the "${s}" target node in the graph.`);return Ime(n,this.multi,o,a,s)}throw new Ne(`Graph.${r}: too many arguments (expecting 0, 1 or 2 and got ${arguments.length}).`)}}function Cme(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,YK(!1,this,n,u);if(arguments.length===2){l=""+l,u=d;let p=this._nodes.get(l);if(typeof p>"u")throw new ve(`Graph.${i}: could not find the "${l}" node in the graph.`);return EN(!1,this.multi,n==="mixed"?this.type:n,o,p,u)}if(arguments.length===3){l=""+l,d=""+d;let p=this._nodes.get(l);if(!p)throw new ve(`Graph.${i}: could not find the "${l}" source node in the graph.`);if(!this._nodes.has(d))throw new ve(`Graph.${i}: could not find the "${d}" target node in the graph.`);return bN(!1,n,this.multi,o,p,d,u)}throw new Ne(`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 p=0;if(n!=="directed")p+=this.undirectedSize;if(n!=="undirected")p+=this.directedSize;u=Array(p);let y=0;l.push((g,E,S,x,w,_,T)=>{u[y++]=d(g,E,S,x,w,_,T)})}else u=[],l.push((p,y,g,E,S,x,w)=>{u.push(d(p,y,g,E,S,x,w))});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((p,y,g,E,S,x,w)=>{if(d(p,y,g,E,S,x,w))u.push(p)}),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 Ne(`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 Ne(`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 p=u;return l.push((y,g,E,S,x,w,_)=>{p=d(p,y,g,E,S,x,w,_)}),this[i].apply(this,l),p}}function _me(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,YK(!0,this,n,d);if(arguments.length===2){c=""+c,d=l;let u=this._nodes.get(c);if(typeof u>"u")throw new ve(`Graph.${i}: could not find the "${c}" node in the graph.`);return EN(!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 ve(`Graph.${i}: could not find the "${c}" source node in the graph.`);if(!this._nodes.has(l))throw new ve(`Graph.${i}: could not find the "${l}" target node in the graph.`);return bN(!0,n,this.multi,o,u,l,d)}throw new Ne(`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,p,y,g,E,S,x)=>l(u,p,y,g,E,S,x)),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,p,y,g,E,S,x)=>!l(u,p,y,g,E,S,x)),this[i].apply(this,c))return!1;return!0}}function kme(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 ug();if(!arguments.length)return wme(this,n);if(arguments.length===1){s=""+s;let c=this._nodes.get(s);if(!c)throw new ve(`Graph.${i}: could not find the "${s}" node in the graph.`);return Ame(n,o,c)}if(arguments.length===2){s=""+s,a=""+a;let c=this._nodes.get(s);if(!c)throw new ve(`Graph.${i}: could not find the "${s}" source node in the graph.`);if(!this._nodes.has(a))throw new ve(`Graph.${i}: could not find the "${a}" target node in the graph.`);return Rme(n,o,c,a)}throw new Ne(`Graph.${i}: too many arguments (expecting 0, 1 or 2 and got ${arguments.length}).`)}}function Dme(e){gme.forEach((t)=>{Pme(e,t),Cme(e,t),_me(e,t),kme(e,t)})}var Ome=[{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 MI(){this.A=null,this.B=null}MI.prototype.wrap=function(e){if(this.A===null)this.A=e;else if(this.B===null)this.B=e};MI.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 Jx(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 wN(e,t,r,n,o){if(t!=="mixed"){if(t==="undirected")return Jx(e,null,n,n.undirected,o);if(typeof r==="string")return Jx(e,null,n,n[r],o)}let i=new MI,s;if(t!=="undirected"){if(r!=="out"){if(s=Jx(e,null,n,n.in,o),e&&s)return s;i.wrap(n.in)}if(r!=="in"){if(s=Jx(e,i,n,n.out,o),e&&s)return s;i.wrap(n.out)}}if(t!=="directed"){if(s=Jx(e,i,n,n.undirected,o),e&&s)return s}return}function Nme(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 wN(!1,e,t,r,function(o){n.push(o)}),n}function Yx(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 Fme(e,t,r){if(e!=="mixed"){if(e==="undirected")return Yx(null,r,r.undirected);if(typeof t==="string")return Yx(null,r,r[t])}let n=ug(),o=new MI;if(e!=="undirected"){if(t!=="out")n=eu(n,Yx(o,r,r.in));if(t!=="in")n=eu(n,Yx(o,r,r.out))}if(e!=="directed")n=eu(n,Yx(o,r,r.undirected));return n}function Ume(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 ve(`Graph.${r}: could not find the "${i}" node in the graph.`);return Nme(n==="mixed"?this.type:n,o,s)}}function Mme(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 ve(`Graph.${i}: could not find the "${l}" node in the graph.`);wN(!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,(p,y)=>{u.push(d(p,y))}),u};let a="filter"+r[0].toUpperCase()+r.slice(1);e.prototype[a]=function(l,d){let u=[];return this[i](l,(p,y)=>{if(d(p,y))u.push(p)}),u};let c="reduce"+r[0].toUpperCase()+r.slice(1);e.prototype[c]=function(l,d,u){if(arguments.length<3)throw new Ne(`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 p=u;return this[i](l,(y,g)=>{p=d(p,y,g)}),p}}function Lme(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 ve(`Graph.${s}: could not find the "${l}" node in the graph.`);return wN(!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,(p,y)=>!d(p,y)))return!1;return!0}}function Bme(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 ug();s=""+s;let a=this._nodes.get(s);if(typeof a>"u")throw new ve(`Graph.${i}: could not find the "${s}" node in the graph.`);return Fme(n==="mixed"?this.type:n,o,a)}}function $me(e){Ome.forEach((t)=>{Ume(e,t),Mme(e,t),Lme(e,t),Bme(e,t)})}function FI(e,t,r,n,o){let i=n._nodes.values(),s=n.type,a,c,l,d,u,p,y;while(a=i.next(),a.done!==!0){let g=!1;if(c=a.value,s!=="undirected"){d=c.out;for(l in d){u=d[l];do{if(p=u.target,g=!0,y=o(c.key,p.key,c.attributes,p.attributes,u.key,u.attributes,u.undirected),e&&y)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(p=u.target,p.key!==l)p=u.source;if(g=!0,y=o(c.key,p.key,c.attributes,p.attributes,u.key,u.attributes,u.undirected),e&&y)return u;u=u.next}while(u)}}if(r&&!g){if(y=o(c.key,null,c.attributes,null,null,null,null),e&&y)return null}}return}function qme(e,t){let r={key:e};if(!WK(t.attributes))r.attributes=jo({},t.attributes);return r}function jme(e,t,r){let n={key:t,source:r.source.key,target:r.target.key};if(!WK(r.attributes))n.attributes=jo({},r.attributes);if(e==="mixed"&&r.undirected)n.undirected=!0;return n}function Hme(e){if(!Ti(e))throw new Ne('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 Ne("Graph.import: serialized node is missing its key.");if("attributes"in e&&(!Ti(e.attributes)||e.attributes===null))throw new Ne("Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.")}function Wme(e){if(!Ti(e))throw new Ne('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 Ne("Graph.import: serialized edge is missing its source.");if(!("target"in e))throw new Ne("Graph.import: serialized edge is missing its target.");if("attributes"in e&&(!Ti(e.attributes)||e.attributes===null))throw new Ne("Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.");if("undirected"in e&&typeof e.undirected!=="boolean")throw new Ne("Graph.import: invalid undirectedness information. Undirected should be boolean or omitted.")}var Vme=Kfe(),zme=new Set(["directed","undirected","mixed"]),jK=new Set(["domain","_events","_eventsCount","_maxListeners"]),Kme=[{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"}],Gme={allowSelfLoops:!0,multi:!1,type:"mixed"};function Qme(e,t,r){if(r&&!Ti(r))throw new Ne(`Graph.addNode: invalid attributes. Expecting an object but got "${r}"`);if(t=""+t,r=r||{},e._nodes.has(t))throw new mt(`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 HK(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 XK(e,t,r,n,o,i,s,a){if(!n&&e.type==="undirected")throw new mt(`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 mt(`Graph.${t}: you cannot add an undirected edge to a directed graph. Use the #.addEdge or #.addDirectedEdge instead.`);if(a&&!Ti(a))throw new Ne(`Graph.${t}: invalid attributes. Expecting an object but got "${a}"`);if(i=""+i,s=""+s,a=a||{},!e.allowSelfLoops&&i===s)throw new mt(`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 ve(`Graph.${t}: source node "${i}" not found.`);if(!l)throw new ve(`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 mt(`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 mt(`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 pg(n,o,c,l,a);e._edges.set(o,u);let p=i===s;if(n){if(c.undirectedDegree++,l.undirectedDegree++,p)c.undirectedLoops++,e._undirectedSelfLoopCount++}else if(c.outDegree++,l.inDegree++,p)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 Jme(e,t,r,n,o,i,s,a,c){if(!n&&e.type==="undirected")throw new mt(`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 mt(`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 Ne(`Graph.${t}: invalid updater function. Expecting a function but got "${a}"`)}else if(!Ti(a))throw new Ne(`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 mt(`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),p,y;if(!r){if(p=e._edges.get(o),p){if(p.source.key!==i||p.target.key!==s){if(!n||p.source.key!==s||p.target.key!==i)throw new mt(`Graph.${t}: inconsistency detected when attempting to merge the "${o}" edge with "${i}" source & "${s}" target vs. ("${p.source.key}", "${p.target.key}").`)}y=p}}if(!y&&!e.multi&&d)y=n?d.undirected[s]:d.out[s];if(y){let w=[y.key,!1,!1,!1];if(c?!l:!a)return w;if(c){let _=y.attributes;y.attributes=l(_),e.emit("edgeAttributesUpdated",{type:"replace",key:y.key,attributes:y.attributes})}else jo(y.attributes,a),e.emit("edgeAttributesUpdated",{type:"merge",key:y.key,attributes:y.attributes,data:a});return w}if(a=a||{},c&&l)a=l(a);let g={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 mt(`Graph.${t}: the "${o}" edge already exists in the graph.`);let E=!1,S=!1;if(!d){if(d=HK(e,i,{}),E=!0,i===s)u=d,S=!0}if(!u)u=HK(e,s,{}),S=!0;p=new pg(n,o,d,u,a),e._edges.set(o,p);let x=i===s;if(n){if(d.undirectedDegree++,u.undirectedDegree++,x)d.undirectedLoops++,e._undirectedSelfLoopCount++}else if(d.outDegree++,u.inDegree++,x)d.directedLoops++,e._directedSelfLoopCount++;if(e.multi)p.attachMulti();else p.attach();if(n)e._undirectedSize++;else e._directedSize++;return g.key=o,e.emit("edgeAdded",g),[o,!0,E,S]}function dg(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 Wr extends Vfe{constructor(e){super();if(e=jo({},Gme,e),typeof e.multi!=="boolean")throw new Ne(`Graph.constructor: invalid 'multi' option. Expecting a boolean but got "${e.multi}".`);if(!zme.has(e.type))throw new Ne(`Graph.constructor: invalid 'type' option. Should be one of "mixed", "directed" or "undirected" but got "${e.type}".`);if(typeof e.allowSelfLoops!=="boolean")throw new Ne(`Graph.constructor: invalid 'allowSelfLoops' option. Expecting a boolean but got "${e.allowSelfLoops}".`);let t=e.type==="mixed"?VK:e.type==="directed"?zK:KK;nc(this,"NodeDataClass",t);let r="geid_"+Vme()+"_",n=0,o=()=>{let i;do i=r+n++;while(this._edges.has(i));return i};nc(this,"_attributes",{}),nc(this,"_nodes",new Map),nc(this,"_edges",new Map),nc(this,"_directedSize",0),nc(this,"_undirectedSize",0),nc(this,"_directedSelfLoopCount",0),nc(this,"_undirectedSelfLoopCount",0),nc(this,"_edgeKeyGenerator",o),nc(this,"_options",e),jK.forEach((i)=>nc(this,i,this[i])),el(this,"order",()=>this._nodes.size),el(this,"size",()=>this._edges.size),el(this,"directedSize",()=>this._directedSize),el(this,"undirectedSize",()=>this._undirectedSize),el(this,"selfLoopCount",()=>this._directedSelfLoopCount+this._undirectedSelfLoopCount),el(this,"directedSelfLoopCount",()=>this._directedSelfLoopCount),el(this,"undirectedSelfLoopCount",()=>this._undirectedSelfLoopCount),el(this,"multi",this._options.multi),el(this,"type",this._options.type),el(this,"allowSelfLoops",this._options.allowSelfLoops),el(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 Ne(`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 Ne(`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 Ne(`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 mt("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 ve(`Graph.directedEdge: could not find the "${e}" source node in the graph.`);if(!this._nodes.has(t))throw new ve(`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 mt("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 ve(`Graph.undirectedEdge: could not find the "${e}" source node in the graph.`);if(!this._nodes.has(t))throw new ve(`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 mt("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 ve(`Graph.edge: could not find the "${e}" source node in the graph.`);if(!this._nodes.has(t))throw new ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`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 ve(`Graph.isSelfLoop: could not find the "${e}" edge in the graph.`);return t.source===t.target}addNode(e,t){return Qme(this,e,t).key}mergeNode(e,t){if(t&&!Ti(t))throw new Ne(`Graph.mergeNode: invalid attributes. Expecting an object but got "${t}"`);e=""+e,t=t||{};let r=this._nodes.get(e);if(r){if(t)jo(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 Ne(`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 ve(`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 dg(this,r),r=r.next;while(r)}for(let n in t.in){r=t.in[n];do dg(this,r),r=r.next;while(r)}}if(this.type!=="directed")for(let n in t.undirected){r=t.undirected[n];do dg(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=oc(this,r,n,this.type),!t)throw new ve(`Graph.dropEdge: could not find the "${r}" -> "${n}" edge in the graph.`)}else if(e=""+e,t=this._edges.get(e),!t)throw new ve(`Graph.dropEdge: could not find the "${e}" edge in the graph.`);return dg(this,t),this}dropDirectedEdge(e,t){if(arguments.length<2)throw new mt("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 mt("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=oc(this,e,t,"directed");if(!r)throw new ve(`Graph.dropDirectedEdge: could not find a "${e}" -> "${t}" edge in the graph.`);return dg(this,r),this}dropUndirectedEdge(e,t){if(arguments.length<2)throw new mt("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 mt("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=oc(this,e,t,"undirected");if(!r)throw new ve(`Graph.dropUndirectedEdge: could not find a "${e}" -> "${t}" edge in the graph.`);return dg(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 Ne("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(!Ti(e))throw new Ne("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(!Ti(e))throw new Ne("Graph.mergeAttributes: provided attributes are not a plain object.");return jo(this._attributes,e),this.emit("attributesUpdated",{type:"merge",attributes:this._attributes,data:e}),this}updateAttributes(e){if(typeof e!=="function")throw new Ne("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 Ne("Graph.updateEachNodeAttributes: expecting an updater function.");if(t&&!qK(t))throw new Ne("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 Ne("Graph.updateEachEdgeAttributes: expecting an updater function.");if(t&&!qK(t))throw new Ne("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 Ne("Graph.forEachAdjacencyEntry: expecting a callback.");FI(!1,!1,!1,this,e)}forEachAdjacencyEntryWithOrphans(e){if(typeof e!=="function")throw new Ne("Graph.forEachAdjacencyEntryWithOrphans: expecting a callback.");FI(!1,!1,!0,this,e)}forEachAssymetricAdjacencyEntry(e){if(typeof e!=="function")throw new Ne("Graph.forEachAssymetricAdjacencyEntry: expecting a callback.");FI(!1,!0,!1,this,e)}forEachAssymetricAdjacencyEntryWithOrphans(e){if(typeof e!=="function")throw new Ne("Graph.forEachAssymetricAdjacencyEntryWithOrphans: expecting a callback.");FI(!1,!0,!0,this,e)}nodes(){return Array.from(this._nodes.keys())}forEachNode(e){if(typeof e!=="function")throw new Ne("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 Ne("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 Ne("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 Ne("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 Ne("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 Ne("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 Ne("Graph.reduceNodes: expecting a callback.");if(arguments.length<2)throw new Ne("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++]=qme(o,n)});let r=Array(this._edges.size);return t=0,this._edges.forEach((n,o)=>{r[t++]=jme(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 Wr)return e.forEachNode((a,c)=>{if(t)this.mergeNode(a,c);else this.addNode(a,c)}),e.forEachEdge((a,c,l,d,u,p,y)=>{if(t)if(y)this.mergeUndirectedEdgeWithKey(a,l,d,c);else this.mergeDirectedEdgeWithKey(a,l,d,c);else if(y)this.addUndirectedEdgeWithKey(a,l,d,c);else this.addDirectedEdgeWithKey(a,l,d,c)}),this;if(!Ti(e))throw new Ne("Graph.import: invalid argument. Expecting a serialized graph or, alternatively, a Graph instance.");if(e.attributes){if(!Ti(e.attributes))throw new Ne("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 Ne("Graph.import: invalid nodes. Expecting an array.");for(r=0,n=o.length;r<n;r++){i=o[r],Hme(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 Ne("Graph.import: invalid edges. Expecting an array.");for(r=0,n=o.length;r<n;r++){s=o[r],Wme(s);let{source:c,target:l,attributes:d,undirected:u=a}=s,p;if("key"in s)p=t?u?this.mergeUndirectedEdgeWithKey:this.mergeDirectedEdgeWithKey:u?this.addUndirectedEdgeWithKey:this.addDirectedEdgeWithKey,p.call(this,s.key,c,l,d);else p=t?u?this.mergeUndirectedEdge:this.mergeDirectedEdge:u?this.addUndirectedEdge:this.addDirectedEdge,p.call(this,c,l,d)}}return this}nullCopy(e){let t=new Wr(jo({},this._options,e));return t.replaceAttributes(jo({},this.getAttributes())),t}emptyCopy(e){let t=this.nullCopy(e);return this._nodes.forEach((r,n)=>{let o=jo({},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 mt(`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 mt("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 mt("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,XK(t,"copy",!1,o.undirected,o.key,o.source.key,o.target.key,jo({},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)&&!jK.has(o)&&typeof this[o]!=="function"&&typeof o!=="symbol")n[o]=this[o];return n.attributes=this._attributes,n.nodes=e,n.edges=t,nc(n,"constructor",this.constructor),n}}if(typeof Symbol<"u")Wr.prototype[Symbol.for("nodejs.util.inspect.custom")]=Wr.prototype.inspect;Kme.forEach((e)=>{["add","merge","update"].forEach((t)=>{let r=e.name(t),n=t==="add"?XK:Jme;if(e.generateKey)Wr.prototype[r]=function(o,i,s){return n(this,r,!0,(e.type||this.type)==="undirected",null,o,i,s,t==="update")};else Wr.prototype[r]=function(o,i,s,a){return n(this,r,!1,(e.type||this.type)==="undirected",o,i,s,a,t==="update")}})});ime(Wr);hme(Wr);Dme(Wr);$me(Wr);class TN extends Wr{constructor(e){let t=jo({type:"directed"},e);if("multi"in t&&t.multi!==!1)throw new Ne("DirectedGraph.from: inconsistent indication that the graph should be multi in given options!");if(t.type!=="directed")throw new Ne('DirectedGraph.from: inconsistent "'+t.type+'" type in given options!');super(t)}}class AN extends Wr{constructor(e){let t=jo({type:"undirected"},e);if("multi"in t&&t.multi!==!1)throw new Ne("UndirectedGraph.from: inconsistent indication that the graph should be multi in given options!");if(t.type!=="undirected")throw new Ne('UndirectedGraph.from: inconsistent "'+t.type+'" type in given options!');super(t)}}class IN extends Wr{constructor(e){let t=jo({multi:!0},e);if("multi"in t&&t.multi!==!0)throw new Ne("MultiGraph.from: inconsistent indication that the graph should be simple in given options!");super(t)}}class RN extends Wr{constructor(e){let t=jo({type:"directed",multi:!0},e);if("multi"in t&&t.multi!==!0)throw new Ne("MultiDirectedGraph.from: inconsistent indication that the graph should be simple in given options!");if(t.type!=="directed")throw new Ne('MultiDirectedGraph.from: inconsistent "'+t.type+'" type in given options!');super(t)}}class PN extends Wr{constructor(e){let t=jo({type:"undirected",multi:!0},e);if("multi"in t&&t.multi!==!0)throw new Ne("MultiUndirectedGraph.from: inconsistent indication that the graph should be simple in given options!");if(t.type!=="undirected")throw new Ne('MultiUndirectedGraph.from: inconsistent "'+t.type+'" type in given options!');super(t)}}function fg(e){e.from=function(t,r){let n=jo({},t.options,r),o=new e(n);return o.import(t),o}}fg(Wr);fg(TN);fg(AN);fg(IN);fg(RN);fg(PN);Wr.Graph=Wr;Wr.DirectedGraph=TN;Wr.UndirectedGraph=AN;Wr.MultiGraph=IN;Wr.MultiDirectedGraph=RN;Wr.MultiUndirectedGraph=PN;Wr.InvalidArgumentsGraphError=Ne;Wr.NotFoundGraphError=ve;Wr.UsageGraphError=mt;var Zme=new Set([...Intl.supportedValuesOf("timeZone"),"UTC"]),CN=(e)=>{if(!Zme.has(e))throw Error(`Invalid timezone: "${e}". Must be a valid IANA timezone identifier (e.g., "Europe/Amsterdam", "America/New_York").`)};import{Schema as Rye}from"effect";import{Schema as an}from"effect";import{Schema as ii}from"effect";import{Schema as lo}from"effect";var Ip=lo.Int.pipe(lo.between(0,6),lo.brand("DayOfWeek"));var ZK=lo.Struct({hour:lo.Int.pipe(lo.between(0,23)),minute:lo.Int.pipe(lo.between(0,59))}),LI=lo.Struct({open:ZK,close:ZK}),mg=lo.Struct({day:Ip,ranges:lo.Array(LI)}),IGe=lo.Array(mg),Xx=lo.Int.pipe(lo.between(1,12),lo.brand("Month")),Zx=lo.Int.pipe(lo.between(1,31),lo.brand("DayOfMonth")),_N=lo.Int.pipe(lo.between(1,5),lo.brand("NthOccurrence")),sn=(e)=>e.hour*60+e.minute,ru=(e)=>sn(e.close)<sn(e.open);var eG=ii.Struct({id:ii.String,type:ii.String,name:ii.String,startDate:ii.DateTimeUtcFromSelf,endDate:ii.DateTimeUtcFromSelf,isActive:ii.Boolean,weeklySchedule:ii.optional(ii.Array(mg))}),_Ge=ii.Struct({id:ii.String,type:ii.String,name:ii.String,startDate:ii.DateTimeUtc,endDate:ii.DateTimeUtc,isActive:ii.Boolean,weeklySchedule:ii.optional(ii.Array(mg))});import{Schema as si}from"effect";var eye=si.TaggedStruct("FixedHoliday",{name:si.String,month:Xx,day:Zx}),tye=si.TaggedStruct("NthWeekdayHoliday",{name:si.String,month:Xx,weekday:Ip,nth:_N}),rye=si.TaggedStruct("LastWeekdayHoliday",{name:si.String,month:Xx,weekday:Ip}),nye=si.TaggedStruct("EasterRelativeHoliday",{name:si.String,daysOffset:si.Int}),kN=si.Union(eye,tye,rye,nye),NGe=si.Struct({date:si.DateTimeUtcFromSelf,name:si.String,rule:si.optional(kN)}),DN=si.decodeSync(Xx),oye=si.decodeSync(Zx),tG=si.decodeSync(Ip),iye=si.decodeSync(_N),ps=(e,t,r)=>({_tag:"FixedHoliday",name:e,month:DN(t),day:oye(r)}),vm=(e,t,r,n)=>({_tag:"NthWeekdayHoliday",name:e,month:DN(t),weekday:tG(r),nth:iye(n)}),sye=(e,t,r)=>({_tag:"LastWeekdayHoliday",name:e,month:DN(t),weekday:tG(r)}),Rp=(e,t)=>({_tag:"EasterRelativeHoliday",name:e,daysOffset:t});var FGe=[ps("New Year's Day",1,1),vm("Martin Luther King Jr. Day",1,1,3),vm("Presidents' Day",2,1,3),sye("Memorial Day",5,1),ps("Independence Day",7,4),vm("Labor Day",9,1,1),vm("Columbus Day",10,1,2),ps("Veterans Day",11,11),vm("Thanksgiving",11,4,4),ps("Christmas Day",12,25)],UGe=[ps("Nieuwjaarsdag",1,1),ps("Koningsdag",4,27),ps("Bevrijdingsdag",5,5),ps("Eerste Kerstdag",12,25),ps("Tweede Kerstdag",12,26),Rp("Goede Vrijdag",-2),Rp("Eerste Paasdag",0),Rp("Tweede Paasdag",1),Rp("Hemelvaartsdag",39),Rp("Eerste Pinksterdag",49),Rp("Tweede Pinksterdag",50)],MGe=[ps("New Year's Day",1,1),ps("Day after New Year's Day",1,2),ps("Waitangi Day",2,6),Rp("Good Friday",-2),Rp("Easter Monday",1),ps("Anzac Day",4,25),vm("Queen's Birthday",6,1,1),vm("Labour Day",10,1,4),ps("Christmas Day",12,25),ps("Boxing Day",12,26)];var aye=an.Struct({date:an.DateTimeUtcFromSelf,slots:an.Union(an.Array(LI),an.Literal("closed")),note:an.optional(an.String)}),JGe=an.Struct({date:an.DateTimeUtc,slots:an.Union(an.Array(LI),an.Literal("closed")),note:an.optional(an.String)}),YGe=an.Struct({weeklySchedule:an.Array(mg),holidays:an.Array(kN),exceptions:an.Array(aye),nonWorkingDays:an.Array(Ip),periods:an.Array(eG),requireActivePeriod:an.optional(an.String),startDayOfWeek:an.optional(Ip),timezone:an.optional(an.String)});import{Context as rG,Data as cye}from"effect";class BI extends cye.TaggedError("BusinessCalendarError"){}class ON extends rG.Tag("processfocus:internal-tag/business-calendar/BusinessCalendarService")(){}class NN extends rG.Tag("processfocus:internal-tag/business-calendar/BusinessCalendarConfigService")(){}import{Cause as sG,DateTime as Lt,Deferred as HI,Duration as tE,Effect as cr,Exit as wye,Layer as Tye,Option as ic,SynchronizedRef as WI}from"effect";import{DateTime as Aa,Effect as fs}from"effect";import{Data as yg}from"effect";class lye extends yg.TaggedError("DateOutOfRangeError"){}class dye extends yg.TaggedError("NoBusinessHoursError"){}class uye extends yg.TaggedError("InvalidCalendarConfigError"){}class $I extends yg.TaggedError("InvalidDateError"){}class eE extends yg.TaggedError("InvalidYearError"){}class pye extends yg.TaggedError("ValidationError"){}var nG=1583,oG=9999,qI=(e)=>{if(!Number.isInteger(e))return fs.fail(new eE({year:e,message:`Year must be an integer, got ${e}`}));if(e<nG)return fs.fail(new eE({year:e,message:`Year must be >= ${nG} for Gregorian calendar, got ${e}`}));if(e>oG)return fs.fail(new eE({year:e,message:`Year must be <= ${oG}, got ${e}`}));return fs.succeed(e)},fye=(e,t)=>new Date(e,t,0).getDate(),mye=(e,t,r)=>{let n=fye(e,t);if(r>n)return fs.fail(new $I({year:e,month:t,day:r,message:`Invalid date: ${e}-${t}-${r}. Month ${t} has only ${n} days in year ${e}`}));return fs.void},jI=(e,t,r)=>fs.try({try:()=>Aa.unsafeMake({year:e,month:t,day:r,hour:0,minute:0,second:0,millis:0}),catch:(n)=>new $I({year:e,month:t,day:r,message:`Failed to create date: ${n}`})}),yye=(e)=>fs.gen(function*(){yield*qI(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,p=Math.floor((t+11*c+22*u)/451),y=Math.floor((c+u-7*p+114)/31),g=(c+u-7*p+114)%31+1;return yield*jI(e,y,g)}),hye=(e,t,r,n)=>fs.gen(function*(){yield*qI(e);let o=yield*jI(e,t,1),s=Aa.toParts(o).weekDay,a=r-s;if(a<0)a+=7;if(o=Aa.add(o,{days:a}),o=Aa.add(o,{days:(n-1)*7}),Aa.toParts(o).month!==t)return;return o}),gye=(e,t,r)=>fs.gen(function*(){yield*qI(e);let n=t===12?1:t+1,o=t===12?e+1:e,i=yield*jI(o,n,1);i=Aa.add(i,{days:-1});let c=Aa.toParts(i).weekDay-r;if(c<0)c+=7;return Aa.add(i,{days:-c})}),Sye=(e,t)=>fs.gen(function*(){return yield*qI(t),yield*mye(t,e.month,e.day),{date:yield*jI(t,e.month,e.day),name:e.name,rule:e}}),vye=(e,t)=>fs.gen(function*(){let r=yield*hye(t,e.month,e.weekday,e.nth);if(!r)return;return{date:r,name:e.name,rule:e}}),xye=(e,t)=>fs.gen(function*(){return{date:yield*gye(t,e.month,e.weekday),name:e.name,rule:e}}),Eye=(e,t)=>fs.gen(function*(){let r=yield*yye(t);return{date:Aa.add(r,{days:e.daysOffset}),name:e.name,rule:e}}),bye=(e,t)=>{switch(e._tag){case"FixedHoliday":return Sye(e,t);case"NthWeekdayHoliday":return vye(e,t);case"LastWeekdayHoliday":return xye(e,t);case"EasterRelativeHoliday":return Eye(e,t)}},iG=(e,t)=>fs.gen(function*(){let r=[];for(let n of e){let o=yield*bye(n,t);if(o)r.push(o)}return r.sort((n,o)=>{let i=Aa.toEpochMillis(n.date),s=Aa.toEpochMillis(o.date);return i-s})}),FN=(e,t)=>{let r=Aa.toParts(e);for(let n of t){let o=Aa.toParts(n.date);if(r.year===o.year&&r.month===o.month&&r.day===o.day)return n}return};var UN=1e4,Aye=1e5,rE=365,Iye=(e)=>cr.gen(function*(){let t=e.timezone?Lt.zoneUnsafeMakeNamed(e.timezone):Lt.zoneUnsafeMakeNamed("UTC"),r=(T)=>{let b=Lt.setZone(T,t);return Lt.toParts(b)},n=(T,b,I,O,L)=>{let Y=Lt.unsafeMakeZoned({year:T,month:b,day:I,hours:O,minutes:L,seconds:0,millis:0},{timeZone:t,adjustForTimeZone:!0});return Lt.toUtc(Y)},o=yield*WI.make(new Map),i=(T)=>iG(e.holidays,T).pipe(cr.catchAllCause((b)=>{if(sG.isInterrupted(b)||sG.isDie(b))return cr.failCause(b);return cr.logWarning("Failed to compute holidays for year",b).pipe(cr.annotateLogs({year:T}),cr.as([]))})),s=(T)=>cr.uninterruptibleMask((b)=>cr.gen(function*(){let I=yield*WI.modifyEffect(o,(O)=>{let L=O.get(T);if(L!==void 0){if(L._tag==="Done")return cr.succeed([{_tag:"hit",holidays:L.holidays},O]);return cr.succeed([{_tag:"join",deferred:L.deferred},O])}return HI.make().pipe(cr.map((Y)=>{let Z=new Map(O);return Z.set(T,{_tag:"InFlight",deferred:Y}),[{_tag:"owner",deferred:Y},Z]}))});switch(I._tag){case"hit":return I.holidays;case"join":return yield*b(HI.await(I.deferred).pipe(cr.catchAll(()=>s(T))));case"owner":{let O=yield*cr.exit(b(cr.gen(function*(){return yield*cr.yieldNow(),yield*i(T)})));if(wye.isSuccess(O))return yield*HI.succeed(I.deferred,O.value),yield*WI.update(o,(L)=>{let Y=L.get(T);if(Y?._tag==="InFlight"&&Y.deferred===I.deferred){let Z=new Map(L);return Z.set(T,{_tag:"Done",holidays:O.value}),Z}return L}),O.value;return yield*WI.update(o,(L)=>{let Y=L.get(T);if(Y?._tag==="InFlight"&&Y.deferred===I.deferred){let Z=new Map(L);return Z.delete(T),Z}return L}),yield*HI.fail(I.deferred,"abandoned"),yield*cr.failCause(O.cause)}}})),a=(T)=>{let b=r(T);for(let I of e.exceptions){let O=r(I.date);if(b.year===O.year&&b.month===O.month&&b.day===O.day)return I}return},c=(T)=>{let b=Lt.toEpochMillis(T);return[...e.periods].filter((I)=>{let O=Lt.toEpochMillis(I.startDate),L=Lt.toEpochMillis(I.endDate);return I.isActive&&b>=O&&b<=L})},l=(T)=>{if(!e.requireActivePeriod)return!0;let b=Lt.toEpochMillis(T);for(let I of e.periods){if(I.type!==e.requireActivePeriod||!I.isActive)continue;let O=Lt.toEpochMillis(I.startDate),L=Lt.toEpochMillis(I.endDate);if(b>=O&&b<=L)return!0}return!1},d=(T)=>{let b=c(T);for(let I of b)if(I.weeklySchedule)return I.weeklySchedule;return e.weeklySchedule},u=(T,b)=>T.find((I)=>I.day===b),p=(T,b)=>{let I=sn(T),O=sn(b.open),L=sn(b.close);if(ru(b))return I>=O||I<L;return I>=O&&I<L},y=(T,b)=>{let I=sn(T),O=sn(b.close);if(ru(b)){if(I>=sn(b.open))return 1440-I+O;return O-I}return O-I},g=1440,E=(T,b,I,O)=>Math.max(0,Math.min(b,O)-Math.max(T,I)),S=(T,b,I)=>{if(I<=b)return 0;let O=sn(T.open),L=sn(T.close);if(ru(T))return E(O,1440,b,I)+E(0,L,b,I);return E(O,L,b,I)},x=(T)=>{let b=a(T);if(b){if(b.slots==="closed")return[];return b.slots}let I=r(T),O=d(T);return u(O,I.weekDay)?.ranges??[]},w=(T,b)=>{let I=r(T),O=r(b);return I.year===O.year&&I.month===O.month&&I.day===O.day},_={isBusinessDay:(T)=>cr.gen(function*(){let b=r(T),I=a(T);if(I?.slots==="closed")return!1;if(e.nonWorkingDays.includes(b.weekDay))return!1;let O=yield*s(b.year),L=Lt.unsafeMake({year:b.year,month:b.month,day:b.day});if(FN(L,O))return!1;if(!l(T))return!1;let Y=d(T),Z=u(Y,b.weekDay);if(I&&typeof I.slots!=="string")return!0;if(!Z||Z.ranges.length===0)return!1;return!0}),isBusinessHours:(T)=>cr.gen(function*(){if(!(yield*_.isBusinessDay(T)))return!1;let I=r(T),O={hour:I.hours,minute:I.minutes},L=a(T);if(L&&typeof L.slots!=="string"){for(let ee of L.slots)if(p(O,ee))return!0;return!1}let Y=d(T),Z=u(Y,I.weekDay);if(!Z)return!1;for(let ee of Z.ranges)if(p(O,ee))return!0;return!1}),addBusinessDays:(T,b)=>cr.gen(function*(){if(b===0||!Number.isFinite(b))return T;let I=Math.max(-UN,Math.min(UN,Math.round(b))),O=T,L=Math.abs(I),Y=I>0?1:-1,Z=0;while(L>0&&Z<UN*2)if(Z++,O=Lt.add(O,{days:Y}),yield*_.isBusinessDay(O))L--;return O}),addBusinessHours:(T,b)=>cr.gen(function*(){if(b<=0||!Number.isFinite(b))return T;let I=Math.min(Aye,b),O=T,L=Math.round(I*60),Y=0,Z=L+rE*24*60;while(L>0&&Y<Z){if(Y++,!(yield*_.isBusinessHours(O))){let _t=yield*_.nextBusinessDay(O),nt=yield*_.businessDayStart(_t);if(ic.isNone(nt)){O=Lt.add(_t,{days:1});continue}O=nt.value;continue}let ae=r(O),ne={hour:ae.hours,minute:ae.minutes},le=a(O),ie;if(le&&typeof le.slots!=="string")ie=le.slots;else{let _t=d(O);ie=u(_t,ae.weekDay)?.ranges??[]}let je=0;for(let _t of ie)if(p(ne,_t)){je=y(ne,_t);break}if(je>=L)return Lt.add(O,{minutes:L});L-=je,O=Lt.add(O,{minutes:je});let ft=r(O),yt={hour:ft.hours,minute:ft.minutes},Ut=!1;for(let _t of ie){let nt=sn(_t.open),be=sn(yt);if(nt>be&&!ru(_t)){let Sr=nt-be;O=Lt.add(O,{minutes:Sr}),Ut=!0;break}}if(!Ut){let _t=yield*_.nextBusinessDay(O),nt=yield*_.businessDayStart(_t);if(ic.isNone(nt)){O=Lt.add(_t,{days:1});continue}O=nt.value}}return O}),nextBusinessDay:(T)=>cr.gen(function*(){let b=Lt.add(T,{days:1}),I=r(b);b=n(I.year,I.month,I.day,0,0);let O=0;while(O<rE){if(O++,yield*_.isBusinessDay(b))return b;b=Lt.add(b,{days:1})}return yield*new BI({message:`No business day found within ${rE} days of ${Lt.toUtc(T)}, possible misconfigured calendar`})}),previousBusinessDay:(T)=>cr.gen(function*(){let b=r(T),I=n(b.year,b.month,b.day,0,0);I=Lt.add(I,{days:-1});let O=0;while(O<rE){if(O++,yield*_.isBusinessDay(I))return I;I=Lt.add(I,{days:-1})}return yield*new BI({message:`No business day found within ${rE} days of ${Lt.toUtc(T)}, possible misconfigured calendar`})}),businessDayStart:(T)=>cr.gen(function*(){if(!(yield*_.isBusinessDay(T)))return ic.none();let I=r(T),O=a(T);if(O&&typeof O.slots!=="string"){let ae=O.slots,ne=ae[0];if(!ne)return ic.none();let le=ne.open;for(let ie of ae)if(sn(ie.open)<sn(le))le=ie.open;return ic.some(n(I.year,I.month,I.day,le.hour,le.minute))}let L=d(T),Y=u(L,I.weekDay),Z=Y?.ranges[0];if(!Y||!Z)return ic.none();let ee=Z.open;for(let ae of Y.ranges)if(sn(ae.open)<sn(ee))ee=ae.open;return ic.some(n(I.year,I.month,I.day,ee.hour,ee.minute))}),businessDayEnd:(T)=>cr.gen(function*(){if(!(yield*_.isBusinessDay(T)))return ic.none();let I=r(T),O=a(T);if(O&&typeof O.slots!=="string"){let ae=O.slots,ne=ae[0];if(!ne)return ic.none();let le=ne.close;for(let ie of ae)if(ru(ie))le=ie.close;else if(sn(ie.close)>sn(le)&&!ru({open:ne.open,close:le}))le=ie.close;return ic.some(n(I.year,I.month,I.day,le.hour,le.minute))}let L=d(T),Y=u(L,I.weekDay),Z=Y?.ranges[0];if(!Y||!Z)return ic.none();let ee=Z.close;for(let ae of Y.ranges)if(ru(ae))ee=ae.close;else if(sn(ae.close)>sn(ee)&&!ru({open:Z.open,close:ee}))ee=ae.close;return ic.some(n(I.year,I.month,I.day,ee.hour,ee.minute))}),businessHoursRemaining:(T)=>cr.gen(function*(){if(!(yield*_.isBusinessHours(T)))return tE.zero;let I=r(T),O={hour:I.hours,minute:I.minutes},L=a(T),Y;if(L&&typeof L.slots!=="string")Y=L.slots;else{let ae=d(T);Y=u(ae,I.weekDay)?.ranges??[]}let Z=0,ee=!1;for(let ae of Y)if(p(O,ae))Z+=y(O,ae),ee=!0;else if(ee&&sn(ae.open)>sn(O))Z+=sn(ae.close)-sn(ae.open);return tE.minutes(Z)}),businessDaysBetween:(T,b)=>cr.gen(function*(){let I=Lt.toEpochMillis(T),O=Lt.toEpochMillis(b);if(I>=O)return 0;let L=0,Y=T;while(Lt.toEpochMillis(Y)<O){if(yield*_.isBusinessDay(Y))L++;Y=Lt.add(Y,{days:1})}return L}),businessHoursBetween:(T,b)=>cr.gen(function*(){let I=Lt.toEpochMillis(T),O=Lt.toEpochMillis(b);if(I>=O)return tE.zero;let L=(je,ft,yt)=>cr.gen(function*(){if(!(yield*_.isBusinessDay(je)))return 0;let _t=x(je),nt=0;for(let be of _t)nt+=S(be,ft,yt);return nt}),Y=r(T),Z=r(b),ee=Y.hours*60+Y.minutes,ae=Z.hours*60+Z.minutes;if(w(T,b)){let je=yield*L(T,ee,ae);return tE.minutes(je)}let ne=0;ne+=yield*L(T,ee,1440);let le=n(Y.year,Y.month,Y.day,12,0);le=Lt.add(le,{days:1});let ie=n(Z.year,Z.month,Z.day,12,0);while(Lt.toEpochMillis(le)<Lt.toEpochMillis(ie)){ne+=yield*L(le,0,1440);let je=r(le);le=Lt.add(n(je.year,je.month,je.day,12,0),{days:1})}return ne+=yield*L(b,0,ae),tE.minutes(ne)}),isHoliday:(T)=>cr.gen(function*(){let b=r(T),I=yield*s(b.year),O=Lt.unsafeMake({year:b.year,month:b.month,day:b.day});return FN(O,I)!==void 0}),getHolidaysForYear:(T)=>s(T),getActivePeriods:(T)=>cr.succeed(c(T)),getActivePeriodsByType:(T,b)=>cr.succeed(c(T).filter((I)=>I.type===b)),isWithinPeriodType:(T,b)=>cr.succeed(c(T).some((I)=>I.type===b)),getPeriodsForDateRange:(T,b,I)=>cr.succeed([...e.periods].filter((O)=>{if(I&&O.type!==I)return!1;let L=Lt.toEpochMillis(O.startDate),Y=Lt.toEpochMillis(O.endDate),Z=Lt.toEpochMillis(T),ee=Lt.toEpochMillis(b);return L<=ee&&Y>=Z})),getEffectiveSchedule:(T)=>cr.sync(()=>{let b=a(T);if(b){if(b.slots==="closed")return[];return[{day:r(T).weekDay,ranges:[...b.slots]}]}return[...d(T)]})};return _}),dQe=Tye.effect(ON,cr.flatMap(NN,Iye));import{DateTime as fQe}from"effect";import{DateTime as hQe,Duration as gQe,Effect as SQe}from"effect";var LN="processfocus/aws-runtime",hg="processfocus/executors";var Sg="deploy-manifest.json",nE=3,gg="processfocus/deploy-manifest",lG=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),Pye=(e)=>Array.isArray(e)&&e.every((t)=>typeof t==="string"),aG=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],Cye=Rye.decodeSync(Zx),Ms=(e,t)=>{if(!lG(e))throw Error(`${t} must be an object`);return e},ms=(e,t)=>{if(typeof e!=="string")throw Error(`${t} must be a string`);return e},_ye=(e,t)=>{let r=ms(e,t);if(!/^[0-9a-f]{64}$/.test(r))throw Error(`${t} must be a 64-character hex string`);return r},kye=(e,t)=>{if(typeof e!=="boolean")throw Error(`${t} must be a boolean`);return e},zI=(e,t)=>{let r=ms(e,t);if(!r.startsWith("/"))throw Error(`${t} must start with '/'`);return r},dG=(e,t)=>{let r=Ms(e,t),n=ms(r.id,`${t}.id`);if(n.length===0)throw Error(`${t}.id must not be empty`);return{id:n,extensions:Ms(r.extensions,`${t}.extensions`)}},Dye=(e)=>{if(e===void 0)return{};let t=Ms(e,`extensions.${hg}`);return Object.fromEntries(Object.entries(t).map(([r,n])=>[zI(r,`extensions.${hg} key`),dG(n,`extensions.${hg}.${r}`)]))},Oye=(e,t)=>{let r=ms(e,t);return CN(r),r},Nye=(e,t)=>{if(e===void 0||e===null)return;if(typeof e!=="number")throw Error(`${t} must be a number when provided`);return e},$N=(e,t)=>{if(!Number.isInteger(e))throw Error(`${t} must be an integer`);return e},uG=(e,t)=>{let r=$N(e,t);if(r<0||r>59)throw Error(`${t} must be between 0 and 59`);return r},MN=(e,t)=>{let r=Ms(e,t),n=$N(r.hour,`${t}.hour`),o=uG(r.minute,`${t}.minute`);if(n<0||n>23)throw Error(`${t}.hour must be between 0 and 23`);return{hour:n,minute:o}},Fye=(e,t)=>{let r=ms(e,t);if(!aG.includes(r))throw Error(`${t} must be one of: ${aG.join(", ")}`);return r},Uye=(e,t)=>{let r=$N(e,t);try{return Cye(r)}catch{throw Error(`${t} must be between 1 and 31`)}},Mye=(e,t)=>{if(e===void 0||e===null)return;let r=ms(e,t);return CN(r),r},VI=(e,t)=>{let r=Mye(e.timeZone,`${t}.timeZone`);return r?{timeZone:r}:{}},Lye=(e,t)=>{let r=Ms(e,t),n=ms(r.type,`${t}.type`);switch(n){case"hourly":return{type:n,minute:uG(r.minute,`${t}.minute`),...VI(r,t)};case"daily":return{type:n,at:MN(r.at,`${t}.at`),...VI(r,t)};case"weekly":return{type:n,weekday:Fye(r.weekday,`${t}.weekday`),at:MN(r.at,`${t}.at`),...VI(r,t)};case"monthly":return{type:n,dayOfMonth:Uye(r.dayOfMonth,`${t}.dayOfMonth`),at:MN(r.at,`${t}.at`),...VI(r,t)};default:throw Error(`${t}.type must be one of: hourly, daily, weekly, monthly`)}},Bye=(e,t="cronEntries")=>{if(e===void 0||e===null)return[];if(!Array.isArray(e))throw Error(`${t} must be an array`);return e.map((r,n)=>{let o=Ms(r,`${t}[${n}]`);return{processPath:zI(o.processPath,`${t}[${n}].processPath`),startMutationName:ms(o.startMutationName,`${t}[${n}].startMutationName`),cron:Lye(o.cron,`${t}[${n}].cron`)}})},$ye=(e)=>e.processes().flatMap((t)=>{let r=t.props.cron;if(!r)return[];let n=To(t.node.path),o=t.startNodes();if(o.length!==1)throw Error(`Process ${n} declares cron but has ${o.length} start steps. Cron requires exactly one start step.`);let i=o[0];if(!i?.isSystemStep){let s=i?To(i.node.path):"<unknown>";throw Error(`Process ${n} declares cron but start step ${s} is not a system step. Cron requires a single system start step.`)}return[{processPath:n,startMutationName:t.startMutationName(),cron:r}]}).sort((t,r)=>t.processPath.localeCompare(r.processPath)),KI=(e,t)=>{if(!Pye(e))throw Error(`${t} must be an array of strings`);if(e.some((r)=>r.length===0))throw Error(`${t} must not contain empty strings`);return e},cG=(e,t)=>{if(e===void 0)return;if(!Array.isArray(e))throw Error(`${t} must be an array`);return e.map((r,n)=>{let o=`${t}[${n}]`,i=Ms(r,o),s=KI(i.actions,`${o}.actions`),a=KI(i.resources,`${o}.resources`),c=i.effect;if(s.length===0)throw Error(`${o}.actions must not be empty`);if(a.length===0)throw Error(`${o}.resources must not be empty`);if(c!==void 0&&c!=="allow"&&c!=="deny")throw Error(`${o}.effect must be 'allow' or 'deny'`);return{actions:s,resources:a,...c!==void 0?{effect:c}:{}}})},BN=(e,t="awsRuntime")=>{if(e===void 0||e===null)return;let r=Ms(e,t),n=cG(r.graphqlLambdaRolePolicyStatements,`${t}.graphqlLambdaRolePolicyStatements`),o=cG(r.jobWorkerLambdaRolePolicyStatements,`${t}.jobWorkerLambdaRolePolicyStatements`),i={...n?{graphqlLambdaRolePolicyStatements:n}:{},...o?{jobWorkerLambdaRolePolicyStatements:o}:{}};return Object.keys(i).length>0?i:void 0},qye=(e,t="customDomains")=>{if(e===void 0)return;let r=Ms(e,t),n=Object.entries(r).map(([o,i])=>[o,ms(i,`${t}.${o}`)]);if(n.length===0)return;return Object.fromEntries(n)},jye=(e)=>{if(e===void 0||e===null)return;let t=Ms(e,"producer");return{name:ms(t.name,"producer.name"),version:ms(t.version,"producer.version")}},Hye=(e)=>{if(e===void 0||e===null)return{};return Ms(e,"extensions")},pG=(e)=>{let t=Ms(e,"organisation deploy manifest"),r=t.version;if(r!==nE)throw Error(`organisation deploy manifest version must be ${String(nE)}`);let n=t.format;if(n!==void 0&&n!==gg)throw Error(`organisation deploy manifest format must be ${gg}`);let o=jye(t.producer),i=t.dockerSteps;if(!Array.isArray(i))throw Error("dockerSteps must be an array");let s=t.documentStores;if(!Array.isArray(s))throw Error("documentStores must be an array");let a=Hye(t.extensions),c=a[LN],l=lG(c)?c:{},d=Array.isArray(t.awsFunctionNames)?KI(t.awsFunctionNames,"awsFunctionNames"):[],u=Array.isArray(l.awsFunctionNames)?KI(l.awsFunctionNames,"extensions.processfocus/aws-runtime.awsFunctionNames"):d,p=BN(t.awsRuntime),g=BN(l.awsRuntime)??p,E=i.map((w,_)=>{let T=Ms(w,`dockerSteps[${_}]`),b=T.command;return{stepPath:zI(T.stepPath,`dockerSteps[${_}].stepPath`),dockerContext:ms(T.dockerContext,`dockerSteps[${_}].dockerContext`),dockerfile:ms(T.dockerfile,`dockerSteps[${_}].dockerfile`),...b===void 0||b===null?{}:{command:ms(b,`dockerSteps[${_}].command`)}}}),S=Dye(a[hg]),x={...a};if(u.length>0||g!==void 0)x[LN]={awsFunctionNames:u,...g!==void 0?{awsRuntime:g}:{}};if(Object.keys(S).length>0)x[hg]=S;return{format:gg,version:r,...o!==void 0?{producer:o}:{},orgBundleSha256:_ye(t.orgBundleSha256,"orgBundleSha256"),organisationTimeZone:Oye(t.organisationTimeZone,"organisationTimeZone"),hasLongDurationSteps:kye(t.hasLongDurationSteps,"hasLongDurationSteps"),dockerSteps:E,documentStores:s.map((w,_)=>{let T=Ms(w,`documentStores[${_}]`);return{name:ms(T.name,`documentStores[${_}].name`),path:zI(T.path,`documentStores[${_}].path`),expirationDays:Nye(T.expirationDays,`documentStores[${_}].expirationDays`)}}),cronEntries:Bye(t.cronEntries),customDomains:qye(t.customDomains),extensions:x}},fG=(e)=>{let t=e.org.node.findAll(),r=t.find((l)=>l.isCustomDomain===!0),n=r?{...r.domains}:void 0,o=t.reduce((l,d)=>{let p=d.functionName;if(typeof p==="string")l.push(p);return l},[]),i={},s=t.reduce((l,d)=>{let u=d;if(u.isDockerStep===!0&&typeof u.dockerContext==="string"&&typeof u.dockerfile==="string"&&typeof u.node?.path==="string"){let p=To(u.node.path);if(u.executor!==void 0)i[p]=dG(u.executor,`Docker step ${p} executor`);l.push({stepPath:p,dockerContext:u.dockerContext,dockerfile:u.dockerfile,...typeof u.command==="string"?{command:u.command}:{}})}return l},[]),a=BN(e.customAwsRuntimeConfig,"CustomAwsRuntimeConfig"),c={};if(o.length>0||a!==void 0)c[LN]={awsFunctionNames:o,...a!==void 0?{awsRuntime:a}:{}};if(Object.keys(i).length>0)c[hg]=i;return{format:gg,version:nE,...e.producer!==void 0?{producer:e.producer}:{},orgBundleSha256:e.orgBundleSha256,organisationTimeZone:e.org.timeZone,hasLongDurationSteps:t.some((l)=>l.longDuration===!0),dockerSteps:s,documentStores:t.reduce((l,d)=>{let u=d;if(u.isDocumentStore===!0&&typeof u.node?.id==="string"&&typeof u.node?.path==="string")l.push({name:u.node.id,path:To(u.node.path),expirationDays:typeof u.expirationDays==="number"?u.expirationDays:void 0});return l},[]),cronEntries:$ye(e.org),customDomains:n,extensions:c}};import{Data as GI,Effect as oE}from"effect";var Wye=2;class mG extends GI.TaggedError("EmbeddedFormNotStartStepError"){}class yG extends GI.TaggedError("UnsupportedEmbeddedFormFieldError"){}class hG extends GI.TaggedError("EmbeddedFormMetadataBuildError"){}class gG extends GI.TaggedError("EmbeddedProcessHasMultipleStartStepsError"){}var qN=(e)=>{if(e._tag==="file")return e._tag;if(e._tag==="fieldset")for(let t of Object.values(e.children)){let r=qN(t);if(r)return r}if(e._tag==="list"||e._tag==="table")for(let t of Object.values(e.itemChildren)){let r=qN(t);if(r)return r}return null},Vye=(e,t)=>oE.gen(function*(){if(!t)return;for(let r of Object.values(t.components)){let n=qN(r);if(n)return yield*new yG({stepPath:To(e.node.path),fieldType:n,message:`Embedded form ${To(e.node.path)} uses unsupported field type ${n}. File fields are not supported in embedded forms yet.`})}}),zye=(e)=>oE.gen(function*(){let t=yield*e.clientFormDefinition().pipe(oE.mapError((o)=>new hG({stepPath:To(e.node.path),message:`Failed to build embed metadata for ${To(e.node.path)}`,cause:o})));yield*Vye(e,t);let r=e.process;return{stepPath:To(e.node.path),processName:r.props.name,processPath:To(r.node.path),mutationName:r.startMutationName(),inputTypeName:Qx(e.node.path),totalFields:e.totalFields,formDefinition:t,defaultValues:e.output?e.defaults():null,jsonSchema:e.output?e.submissionSchema():null,sites:e.embed?.sites??[],thankYou:e.embed?.thankYou??""}});var SG=(e)=>oE.gen(function*(){let t=[],r=new Set;for(let o of e.processes()){let i=o.startNodes();if(i.filter((a)=>a.isForm&&a.embed).length>0&&i.length!==1)return yield*new gG({processPath:To(o.node.path),message:`Embedded process ${To(o.node.path)} has ${i.length} start steps. Embedded forms currently require exactly one start step.`});for(let a of i){if(!a.isForm)continue;let c=a;if(c.embed){let l=To(c.node.path);r.add(l),t.push(c)}}}for(let o of e.processes())for(let{form:i,path:s}of o.forms()){let a=To(s);if(i.embed&&!r.has(a))return yield*new mG({stepPath:a,message:`Embedded form ${a} is not a process start step. Only start forms can be embedded anonymously.`})}let n=yield*oE.forEach(t,zye,{concurrency:"unbounded"});return{version:Wye,entries:n.sort((o,i)=>o.stepPath.localeCompare(i.stepPath))}});import{Data as uhe,Effect as Eg}from"effect";var QI="processfocus/browser-plugins",JI=1,vg="browser-plugins.json",jN=["analytics","formComponents"],vG=(e)=>jN.some((t)=>e===t);var iE="frontend-manifest.json",xg=3,XI=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),Pp=(e,t)=>{if(!XI(e))throw Error(`${t} must be an object`);return e},Kye=(e,t)=>{if(typeof e!=="string")throw Error(`${t} must be a string`);return e},nu=(e,t)=>{let r=Kye(e,t).trim();if(r.length===0)throw Error(`${t} must be a non-empty string`);return r};var YI=(e,t)=>{if(e===null)return null;if(Array.isArray(e))return e.map((r,n)=>YI(r,`${t}[${n}]`));switch(typeof e){case"boolean":case"string":return e;case"number":if(!Number.isFinite(e))throw Error(`${t} must be a finite number`);return e;case"object":{let r=Pp(e,t),n={};for(let[o,i]of Object.entries(r))n[o]=YI(i,`${t}.${o}`);return n}default:throw Error(`${t} must be JSON-serializable`)}};var Gye=(e,t)=>{let r=Pp(e,t);return{module:nu(r.module,`${t}.module`),type:nu(r.type,`${t}.type`),config:YI(r.config,`${t}.config`)}},Qye=(e)=>e.isFrontendClientPluginManifestProvider===!0,HN=(e)=>e.node.findAll().filter(Qye),Jye=(e)=>{let t=e;return t.isBrowserPluginArtifactProvider===!0&&t.isFrontendClientPluginManifestProvider===!0},xG=(e)=>e.node.findAll().filter(Jye),EG=(e)=>{let t=e;if(typeof t.buildBrowserPluginArtifact!=="function")throw Error(`${e.node.path} must expose buildBrowserPluginArtifact()`);let r=t.buildBrowserPluginArtifact.call(e),n=Pp(r,`${e.node.path} browser plugin artifact`),o=n.category;if(!vG(o)){let c=jN.map((l)=>JSON.stringify(l)).join(" or ");throw Error(`${e.node.path} browser plugin artifact.category must be ${c}`)}let i=n.hostInterfaceVersion;if(typeof i!=="number"||!Number.isInteger(i)||i<1)throw Error(`${e.node.path} browser plugin artifact.hostInterfaceVersion must be a positive integer`);let s=n.preparation,a;if(s!==void 0){let c=Pp(s,`${e.node.path} browser plugin artifact.preparation`);if(c.kind!=="stylesheet")throw Error(`${e.node.path} browser plugin artifact.preparation.kind must be "stylesheet"`);a={kind:"stylesheet",entrypoint:nu(c.entrypoint,`${e.node.path} browser plugin artifact.preparation.entrypoint`)}}return{identity:nu(n.identity,`${e.node.path} browser plugin artifact.identity`),category:o,hostInterfaceVersion:i,entrypoint:nu(n.entrypoint,`${e.node.path} browser plugin artifact.entrypoint`),...a!==void 0&&{preparation:a}}},WN=(e)=>{let t=e;if(typeof t.buildFrontendClientPluginManifest!=="function")throw Error(`${e.node.path} must expose buildFrontendClientPluginManifest()`);return Gye(t.buildFrontendClientPluginManifest.call(e),`${e.node.path} frontend client plugin`)};var rhe=so(wi(),1);import{createHash as Yye}from"crypto";import{readFileSync as Xye,realpathSync as IG,statSync as Zye}from"fs";import{basename as ehe,extname as the,isAbsolute as VN,relative as bG,resolve as wG,sep as TG}from"path";var nhe="/_pf/public-form-branding/";class ou extends Error{}var ohe=(e)=>{try{return IG(e)}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")throw new ou(`PublicFormBranding base path not found: ${e}`,{cause:t});throw t}},ihe=(e,t)=>{if(e.trim().length===0)throw new ou("PublicFormBranding source must be a non-empty string");if(VN(e))throw new ou("PublicFormBranding source must be a relative org-local file");let r=wG(t??process.cwd()),n=wG(r,e),o=bG(r,n);if(o.length===0||o===".."||o.startsWith(`..${TG}`)||VN(o))throw new ou("PublicFormBranding source must be a relative org-local file");try{let i=ohe(r);if(!Zye(n).isFile())throw new ou(`PublicFormBranding source must be a file: ${e}`);let a=IG(n),c=bG(i,a);if(c.length===0||c===".."||c.startsWith(`..${TG}`)||VN(c))throw new ou("PublicFormBranding source must be a relative org-local file")}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")throw new ou(`PublicFormBranding source file not found: ${e}`,{cause:i});if(i instanceof ou)throw i;throw Error(`Failed to inspect PublicFormBranding source file: ${e}`,{cause:i})}return n},she=(e)=>{let t=Xye(e),r=Yye("sha256").update(t).digest("hex").slice(0,16),n=the(e),o=ehe(e,n);return`${nhe}${o}-${r}${n}`},ahe=(e)=>e.node.findAll().filter((t)=>t.isPublicFormBranding===!0),che=(e)=>{let t=ahe(e);if(t.length>1)throw Error("Organisation must declare at most one PublicFormBranding");return t[0]},lhe=(e)=>{let t=e.trim();return!(t.length===0||t.startsWith("#")||t.startsWith("/")||t.startsWith("//")||/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(t))},dhe=(e)=>{let t=e.search(/[?#]/);if(t===-1)return{path:e,decoration:""};return{path:e.slice(0,t),decoration:e.slice(t)}},AG=(e,t)=>e.replace(/\b(src|href)\s*=\s*("([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/gi,(r,n,o,i,s,a)=>{let c=i??s??a??"";if(!lhe(c))return r;let{path:l,decoration:d}=dhe(c),u=`${t(l)}${d}`;if(o.startsWith('"'))return`${n}="${u}"`;if(o.startsWith("'"))return`${n}='${u}'`;return`${n}=${u}`}),RG=(e,t)=>{let r=che(e);if(!r)return{branding:null,files:[]};let n=new Map,o=(i)=>{let s=ihe(i,t?.basePath),a=n.get(s);if(a!==void 0)return a.publicPath;let c=she(s),l={sourcePath:s,publicPath:c};return n.set(s,l),c};return{branding:{...r.headerHtml!==void 0?{headerHtml:AG(r.headerHtml,o)}:{},...r.footerHtml!==void 0?{footerHtml:AG(r.footerHtml,o)}:{}},files:[...n.values()]}},PG=(e,t)=>RG(e,t).branding,CG=(e,t)=>RG(e,t).files;class bg extends uhe.TaggedError("OrganisationFrontendManifestBuildError"){}var phe=(e)=>XI(e)&&typeof e._tag==="string",fhe=(e)=>(typeof e==="object"||typeof e==="function")&&e!==null&&phe(e.ast),mhe=(e)=>XI(e)&&e.isList===!0,yhe=(e)=>{let t=Pp(e,"FormComponentPluginType annotation");return{module:nu(t.module,"FormComponentPluginType annotation.module"),type:nu(t.type,"FormComponentPluginType annotation.type")}},xm=(e,t=e.annotations)=>{let r=[],o={...e.annotations,...t}[tK];if(o!==void 0)r.push(yhe(o));switch(e._tag){case"TypeLiteral":{for(let i of e.propertySignatures)r.push(...xm(i.type,i.annotations));return r}case"TupleType":{let i=e.rest[0];if(!i)return r;return r.push(...xm(i.type)),r}case"Refinement":return r.push(...xm(e.from,{...e.annotations,...t})),r;case"Transformation":return r.push(...xm(e.from,{...e.annotations,...t})),r;case"Union":{for(let i of e.types){if(i._tag==="Literal"&&i.literal===null)continue;if(i._tag==="UndefinedKeyword")continue;r.push(...xm(i,{...e.annotations,...t}))}return r}default:return r}},ZI=(e,t)=>{let r=e.get(t.type);if(r&&r.module!==t.module)throw Error(`Frontend plugin type "${t.type}" declares conflicting modules "${r.module}" and "${t.module}"`);e.set(t.type,t)},hhe=(e)=>{let t=new Map,r=(n)=>{let o=Pp(n,"list.formFields");for(let[i,s]of Object.entries(o)){if(!fhe(s))throw Error(`list.formFields.${i} must be an Effect schema`);for(let a of xm(s.ast))ZI(t,a)}};for(let n of e.node.findAll()){if(n.isForm===!0){let i=n;for(let s of xm(i.outputSchema.ast))ZI(t,s);continue}if(mhe(n)&&n.formFields!==void 0)r(n.formFields)}for(let n of HN(e)){if(n.frontendManifestPluginCategory!=="formComponents")continue;let{module:o,type:i}=WN(n);ZI(t,{module:o,type:i})}return Array.from(t.values()).sort((n,o)=>n.type.localeCompare(o.type))},ghe=(e)=>HN(e).filter((t)=>t.frontendManifestPluginCategory==="analytics").map((t)=>WN(t)).map(({module:t,type:r,config:n})=>({module:t,type:r,config:n})),She=(e)=>{let t=new Map;for(let r of e)ZI(t,r)},vhe=(e)=>e.node.findAll().filter(Gx).map((t)=>({processPath:To(t.node.path),documentationPath:t.props.documentationPath})).filter((t)=>t.documentationPath!==void 0).sort((t,r)=>t.processPath.localeCompare(r.processPath)),_G=(e,t)=>Eg.gen(function*(){let r=yield*SG(e),n=yield*Eg.try({try:()=>CK(e,{basePath:t?.basePath}),catch:(a)=>new bg({message:a instanceof Error?a.message:"Failed to build App Icons for frontend manifest",cause:a})}),o=yield*Eg.try({try:()=>ghe(e),catch:(a)=>new bg({message:a instanceof Error?a.message:"Failed to build analytics plugins for frontend manifest",cause:a})}),i=yield*Eg.try({try:()=>hhe(e),catch:(a)=>new bg({message:a instanceof Error?a.message:"Failed to collect form component plugins for frontend manifest",cause:a})});yield*Eg.try({try:()=>She([...o,...i]),catch:(a)=>new bg({message:a instanceof Error?a.message:"Conflicting frontend plugin module declarations",cause:a})});let s=yield*Eg.try({try:()=>PG(e,{basePath:t?.basePath}),catch:(a)=>new bg({message:a instanceof Error?a.message:"Failed to build Public Form Branding for frontend manifest",cause:a})});return{version:xg,organisation:{name:e.name,...e.acronym!==void 0?{acronym:e.acronym}:{}},appIcons:n,publicFormBranding:s,embed:{entries:r.entries},processes:{documentation:vhe(e)},plugins:{analytics:o,formComponents:i}}});import*as Em from"path";import{RUNTIME_ARTIFACT_FORMAT as xhe,RUNTIME_ARTIFACT_VERSION as Ehe,Runtime as kG,parseServerPluginRegistrations as bhe}from"@processfocus/runtime";import{Config as whe,Context as The,Data as Ahe,Effect as Ls,Either as h5e,Layer as Ihe}from"effect";class wg extends Ahe.TaggedError("processfocus:internal-tag/OrganisationLoadError"){}class eR extends The.Tag("processfocus:internal-tag/process/OrganisationProvider")(){}var Rhe=(e)=>Ls.gen(function*(){let t=yield*Bo,r=Em.resolve(process.cwd(),e),n=Em.join(r,"org.js"),o=Em.join(r,"src/index.ts"),s=(yield*t.exists(n))?n:o;if(!(yield*t.exists(s)))return yield*new wg({message:`Failed to load organisation from ${e}: Organisation file not found: ${s}`,orgPath:e});let c=yield*Ls.tryPromise({try:async()=>await import(s),catch:(g)=>new wg({message:`Failed to load organisation from ${e}: ${g instanceof Error?g.message:String(g)}`,orgPath:e,cause:g})}),l=yield*kG.loadArtifact(Ls.succeed({format:xhe,version:Ehe,organisation:c.org})).pipe(Ls.mapError((g)=>new wg({message:`Failed to load organisation from ${e}: ${g.message}`,orgPath:e}))),{CustomDbLayer:d,CustomGraphqlSchema:u,CustomJobLayer:p}=c,y=yield*bhe(c.ServerPlugins).pipe(Ls.mapError((g)=>new wg({message:`Failed to load organisation from ${e}: ${g.message}`,orgPath:e,cause:g})));return{org:l.organisation,resolvedPath:r,...d?{customDbLayer:d}:{},...u?{customGraphqlSchema:u}:{},...p?{customJobLayer:p}:{},serverPlugins:y}}),Phe=(e)=>kG.loadOrganisation({load:Rhe},e),Che=({org:e,orgPath:t,customDbLayer:r,customGraphqlSchema:n,customJobLayer:o,serverPlugins:i=[]})=>Ls.gen(function*(){let s=yield*Bo,a=Em.join(t,"dist/graphql/org.graphql"),c=Em.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 _he=({name:e,customDbLayer:t,customJobLayer:r,serverPlugins:n=[]})=>Ls.gen(function*(){if(yield*Ls.log(`Loaded organisation: ${e}`),t)yield*Ls.log("Loaded custom database layer from organisation");if(r)yield*Ls.log("Loaded custom job layer from organisation");if(n.length>0)yield*Ls.log(`Loaded ${n.length} server plugin registration(s) from organisation`)}),S5e=Ihe.effect(eR,Ls.gen(function*(){let e=yield*whe.string("PF_ORG").pipe(Ls.mapError(()=>new wg({message:"PF_ORG environment variable is not set",orgPath:"<env>"})));yield*Ls.log(`Loading organisation from: ${e}`);let{org:t,resolvedPath:r,customDbLayer:n,customGraphqlSchema:o,customJobLayer:i,serverPlugins:s}=yield*Phe(e);return yield*_he({name:t.name,customDbLayer:n,customJobLayer:i,serverPlugins:s}),yield*Che({org:t,orgPath:r,customDbLayer:n,customGraphqlSchema:o,customJobLayer:i,serverPlugins:s})}));var khe=so(wi(),1);var Dhe=so(wi(),1);import{Duration as w5e}from"effect";import{Context as Ohe,Data as tR,DateTime as R5e,Effect as P5e,Option as C5e,Schema as _5e,SchemaAST as k5e}from"effect";class Nhe extends tR.TaggedError("SourceStepNotFoundForScheduleError"){}class Fhe extends tR.TaggedError("EdgeNotFoundForScheduleError"){}class Uhe extends tR.TaggedError("ScheduleFunctionMissingError"){}class Mhe extends tR.TaggedError("ScheduleEvaluationError"){}class Lhe extends Ohe.Tag("processfocus:internal-tag/process/ScheduleEvaluator")(){}var Bhe=so(wi(),1);import{Context as zN,Data as sE,Effect as B5e,Option as $5e,Schema as q5e}from"effect";class $he extends sE.TaggedError("StepNotFoundError"){}class qhe extends sE.TaggedError("NotASystemStepError"){}class jhe extends sE.TaggedError("SystemStepExecutionError"){}class Hhe extends sE.TaggedError("OutputValidationError"){}class Whe extends sE.TaggedError("LongDurationDispatchError"){}class Vhe extends zN.Tag("processfocus:internal-tag/process/LongDurationDispatcher")(){}class zhe extends zN.Tag("processfocus:internal-tag/process/StepProcessStateReader")(){}class Khe extends zN.Tag("processfocus:internal-tag/process/SystemStepExecutor")(){}import{Context as Ghe,Data as Qhe}from"effect";class Jhe extends Qhe.TaggedError("UsageCostError"){}class Yhe extends Ghe.Tag("processfocus:internal-tag/process/UsageCostService")(){}var Xhe=so(wi(),1);var KN=(e)=>typeof e==="object"&&e!==null&&("isCustomEntitiesConfig"in e)&&e.isCustomEntitiesConfig===!0;var Zhe=so(wi(),1);var GN=(e)=>typeof e==="object"&&e!==null&&("isPoliciesConfig"in e)&&e.isPoliciesConfig===!0;class JN extends rge.TaggedError("CedarPoliciesDirNotFoundError"){get message(){return`CEDAR_PATH directory does not exist: ${this.path}`}}class rR extends tge.Tag("processfocus:internal-tag/auth-config/CedarPoliciesProvider")(){}var nR=(e)=>e.node.children.flatMap((t)=>GN(t)?[...t.policyFiles]:[]),oR=(e)=>e.node.children.flatMap((t)=>KN(t)?[...t.schemaFiles]:[]),nge=QN.effect(rR,DG.gen(function*(){let e=yield*Bo,t=yield*ege.string("CEDAR_PATH");if(!(yield*e.exists(t)))return yield*new JN({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)=>aE.join(t,c)),a=i.map((c)=>aE.join(t,c));return{policyPaths:s,schemaPaths:a}})).pipe(QN.provide(ele)),oge=QN.effect(rR,DG.gen(function*(){let e=yield*eR,r=nR(e.organisation).map((i)=>aE.join(e.orgPath,i)),o=oR(e.organisation).map((i)=>aE.join(e.orgPath,i));return{policyPaths:r,schemaPaths:o}}));import{Schema as ut}from"effect";var iR=ut.Struct({rpName:ut.String,rpID:ut.String,origin:ut.Union(ut.String,ut.Array(ut.String))}),sR=["google","github","microsoft","apple","discord","spotify","slack","linkedin","twitch","yahoo","x","keycloak","cognito","jumpcloud","facebook"],YN={google:["openid","email","profile"],github:["read:user","user:email"],microsoft:["openid","email","profile"],apple:["name","email"],discord:["identify","email"],spotify:["user-read-email"],slack:["openid","email","profile"],linkedin:["openid","email","profile"],twitch:["openid","user:read:email"],yahoo:["openid","email","profile"],x:["users.read","tweet.read","offline.access"],keycloak:["openid","email","profile"],cognito:["openid","email","profile"],jumpcloud:["openid","email","profile"],facebook:["email","public_profile"]},bm=ut.Struct({clientID:ut.String,clientSecret:ut.String,scopes:ut.Array(ut.String),pkce:ut.optional(ut.Boolean),query:ut.optional(ut.Record({key:ut.String,value:ut.String}))}),ige=bm.pipe(ut.extend(ut.Struct({responseMode:ut.optional(ut.Literal("query","form_post"))}))),sge=bm.pipe(ut.extend(ut.Struct({tenant:ut.String}))),age=bm.pipe(ut.extend(ut.Struct({team:ut.String}))),cge=bm.pipe(ut.extend(ut.Struct({baseUrl:ut.String,realm:ut.String}))),lge=bm.pipe(ut.extend(ut.Struct({domain:ut.String,region:ut.String,userPoolId:ut.String}))),dge=ut.Literal(...sR),OG=bm.pipe(ut.extend(ut.Struct({invitedOrgUnits:ut.optional(ut.Array(ut.String)),orgUnitAsRole:ut.optional(ut.Boolean),serviceAccountKey:ut.optional(ut.String),adminEmail:ut.optional(ut.String)}))),uge=ut.Struct({secret:ut.String,audience:ut.String});import{readFileSync as pge}from"fs";import{fileURLToPath as fge}from"url";import{Schema as wm}from"effect";var mge=wm.Struct({name:wm.String,version:wm.String,dependencies:wm.Record({key:wm.String,value:wm.String})}),yge=JSON.parse(pge(fge(new URL("../package.json",import.meta.url)),"utf8")),XN=wm.decodeUnknownSync(mge)(yge),cE=(e)=>{let t=XN.dependencies[e];if(t===void 0)throw Error(`Invalid @processfocus/cli package metadata: missing ${e}`);return t},{name:NG,version:aR}=XN,FG=cE("processfocus"),UG={"@cedar-policy/cedar-wasm":cE("@cedar-policy/cedar-wasm"),"@tursodatabase/database":cE("@tursodatabase/database"),"@tursodatabase/serverless":cE("@tursodatabase/serverless"),"@tursodatabase/sync":cE("@tursodatabase/sync")};var lE={name:NG,version:aR};import{Console as Ao,Data as cR,Effect as hge}from"effect";class MG extends cR.TaggedError("FlowValidationError"){}class gge extends cR.TaggedError("MissingElseBranchError"){}class Sge extends cR.TaggedError("MultipleElseBranchError"){}class LG extends cR.TaggedError("MultipleStartNodesError"){}var BG=(e)=>hge.gen(function*(){let t=e.validateAllFlows();if(t.length>0){yield*Ao.error(`
|
|
93
|
+
\u274C Flow Validation Error:`);for(let r of t){if(yield*Ao.error(` Process: ${r.processPath}`),r.unreachable.length>0){yield*Ao.error(" Unreachable steps (not connected to start):");for(let n of r.unreachable)yield*Ao.error(` - ${n}`)}if(r.dangling.length>0){yield*Ao.error(" Dangling steps (missing .end()):");for(let n of r.dangling)yield*Ao.error(` - ${n}`)}if(r.missingElse.length>0){yield*Ao.error(" Missing else branch (conditional flow without .else()):");for(let n of r.missingElse)yield*Ao.error(` - ${n}`)}if(r.multipleElse.length>0){yield*Ao.error(" Multiple else branches (only one allowed):");for(let n of r.multipleElse)yield*Ao.error(` - ${n}`)}if(r.orphanElse.length>0){yield*Ao.error(" Orphan else branch (else without conditional flow):");for(let n of r.orphanElse)yield*Ao.error(` - ${n}`)}}return yield*Ao.error(" Tip: Ensure all steps are connected via process.start() and call .end() on terminal steps"),yield*Ao.error(" Tip: Steps with conditional flows must have exactly one .else() or .elseEnd() branch"),yield*Ao.error(" Tip: An else branch requires at least one conditional flow from the same step"),yield*new MG({flowErrors:t})}for(let r of e.processes()){let n=r.startNodes();if(n.length>1){yield*Ao.error(`
|
|
94
|
+
\u274C Multiple Start Nodes Error:`),yield*Ao.error(` Process: ${r.node.path}`),yield*Ao.error(` Found ${n.length} start nodes, but only 1 is supported`),yield*Ao.error(" Start nodes:");for(let o of n)yield*Ao.error(` - ${o.node.path}`);return yield*new LG({processPath:r.node.path,startNodeCount:n.length})}}});var Pge=["@cedar-policy/cedar-wasm","@tursodatabase/database","@tursodatabase/sync"],Cge=["embed-manifest.json","frontend-plugin-manifest.json"],_ge="processfocus/org-bundle",kge="processfocus/graphql-schema",Dge="processfocus/cedar-policies",Oge="processfocus/frontend-manifest",Nge="processfocus/browser-plugin-bundle",Fge="processfocus/browser-plugin-preparation",dE="browser-plugins",$G=90000,qG=30000,Uge=["next/*","react","react/*","react-dom","react-dom/*"],Mge=(e)=>{if(typeof e!=="object"||e===null||!("__pfBuildDynamicSchema"in e)||typeof e.__pfBuildDynamicSchema!=="function")throw Error("Bundled organisation does not expose its GraphQL schema generator");let t=e.__pfBuildDynamicSchema;return async(r,n)=>{let o=await t(r,n);if(typeof o!=="string")throw Error("Bundled organisation GraphQL schema generator did not return a string");return o}},Cp=(e)=>jG("sha256").update(HG(e)).digest("hex"),Lge=(e)=>{let t;try{t=Bun.resolveSync(e.entrypoint,e.orgPath)}catch(c){throw Error(`browser plugin "${e.identity}" preparation entrypoint ${JSON.stringify(e.entrypoint)} cannot be resolved from the organisation`,{cause:c})}if(De.extname(t)!==".css")throw Error(`browser plugin "${e.identity}" stylesheet preparation entrypoint must resolve to a .css file`);let n=`${HG(t,"utf8").replaceAll(/@source\s+["'][^"']+["']\s*;/g,"").trimEnd()}
|
|
95
|
+
|
|
96
|
+
@source "./${De.basename(e.browserArtifactPath)}";
|
|
97
|
+
`,o=De.join(e.outputDir,dE,`.tmp-${eF()}.css`);wge(o,n);let i=Cp(o),s=`${dE}/${i}.css`,a=De.join(e.outputDir,s);if(lR(a))sc(o,{force:!0});else WG(o,a);return{kind:"stylesheet",path:s,sha256:i}},Bge=`
|
|
98
|
+
try {
|
|
99
|
+
const input = JSON.parse(await Bun.stdin.text())
|
|
100
|
+
const artifact = await import(input.artifactUrl)
|
|
101
|
+
if (typeof artifact.shouldActivate !== "function") {
|
|
102
|
+
throw new Error("artifact must export shouldActivate()")
|
|
103
|
+
}
|
|
104
|
+
if (!artifact.plugin || typeof artifact.plugin.activate !== "function") {
|
|
105
|
+
throw new Error("artifact must export plugin.activate()")
|
|
106
|
+
}
|
|
107
|
+
if (artifact.plugin.id !== input.identity) {
|
|
108
|
+
throw new Error("artifact plugin id must match its manifest identity")
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const analytics = []
|
|
112
|
+
const formRenderers = []
|
|
113
|
+
const executionMenuActions = []
|
|
114
|
+
const register = (registrations) => (registration) => {
|
|
115
|
+
registrations.push(registration)
|
|
116
|
+
return () => undefined
|
|
117
|
+
}
|
|
118
|
+
const host = {
|
|
119
|
+
kind: "organisation-plugin-host",
|
|
120
|
+
interfaceVersion: input.hostInterfaceVersion,
|
|
121
|
+
analytics: { register: register(analytics) },
|
|
122
|
+
formRenderers: { register: register(formRenderers) },
|
|
123
|
+
executionMenu: { register: register(executionMenuActions) },
|
|
124
|
+
graphql: { ClientConsumer: () => null },
|
|
125
|
+
}
|
|
126
|
+
if (!(await artifact.shouldActivate(input.config, "production"))) {
|
|
127
|
+
throw new Error("configured artifact declined production activation")
|
|
128
|
+
}
|
|
129
|
+
await artifact.plugin.activate(host)
|
|
130
|
+
|
|
131
|
+
if (input.category === "analytics") {
|
|
132
|
+
const registration = analytics.find(
|
|
133
|
+
(candidate) => candidate.type === input.identity,
|
|
134
|
+
)
|
|
135
|
+
if (!registration || typeof registration.render !== "function") {
|
|
136
|
+
throw new Error(
|
|
137
|
+
"artifact did not register its configured analytics render path",
|
|
138
|
+
)
|
|
139
|
+
}
|
|
140
|
+
registration.render(input.config)
|
|
141
|
+
} else {
|
|
142
|
+
const registration = formRenderers.find(
|
|
143
|
+
(candidate) => candidate.type === input.identity,
|
|
144
|
+
)
|
|
145
|
+
const menuAction = executionMenuActions.find(
|
|
146
|
+
(candidate) =>
|
|
147
|
+
typeof candidate.id === "string" &&
|
|
148
|
+
typeof candidate.label === "string" &&
|
|
149
|
+
typeof candidate.isVisible === "function" &&
|
|
150
|
+
typeof candidate.onSelect === "function",
|
|
151
|
+
)
|
|
152
|
+
if (!registration && !menuAction) {
|
|
153
|
+
throw new Error(
|
|
154
|
+
"artifact did not register a form renderer or execution-menu action",
|
|
155
|
+
)
|
|
156
|
+
}
|
|
157
|
+
if (registration) {
|
|
158
|
+
if (typeof registration.renderer !== "function") {
|
|
159
|
+
throw new Error(
|
|
160
|
+
"artifact registered an invalid form-component render path",
|
|
161
|
+
)
|
|
162
|
+
}
|
|
163
|
+
registration.renderer(
|
|
164
|
+
{ AppField: ({ children }) => children() },
|
|
165
|
+
{
|
|
166
|
+
_tag: "plugin",
|
|
167
|
+
field: "browserPluginValidation",
|
|
168
|
+
label: "Browser plugin validation",
|
|
169
|
+
pluginType: input.identity,
|
|
170
|
+
},
|
|
171
|
+
false,
|
|
172
|
+
)
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
} catch {
|
|
176
|
+
process.exitCode = 1
|
|
177
|
+
}
|
|
178
|
+
`,$ge=(e)=>{let t=["react","react-dom","next"].flatMap((i)=>{try{let s=Bun.resolveSync(`${i}/package.json`,De.dirname(e.entrypointPath));return[De.dirname(De.dirname(s))]}catch{return[]}}),r=[...new Set(t)].join(De.delimiter),n=new TextEncoder().encode(JSON.stringify({artifactUrl:VG(e.artifactPath).href,category:e.category,config:e.config,hostInterfaceVersion:e.hostInterfaceVersion,identity:e.identity})),o=Bun.spawnSync([process.execPath,"--no-install","-e",Bge],{cwd:e.orgPath,env:{NODE_ENV:"production",NODE_PATH:r},stdin:n,stderr:"ignore",stdout:"ignore",timeout:qG});if(o.exitedDueToTimeout)throw Error(`browser plugin "${e.identity}" production validation timed out after ${qG/1000}s`);if(o.exitCode!==0)throw Error(`browser plugin "${e.identity}" failed production render validation`)},qge=(e)=>{let t=new Map([...e.frontendManifest.plugins.analytics.map((a)=>({category:"analytics",config:a.config,identity:a.type})),...e.frontendManifest.plugins.formComponents.map((a)=>({category:"formComponents",config:void 0,identity:a.type}))].map((a)=>[a.identity,a])),r=xG(e.org).filter((a)=>a.frontendManifestPluginCategory!==void 0).map((a)=>({providerPath:a.node.path,input:EG(a)})),n=new Set,o=r.map(({providerPath:a,input:c})=>{if(n.has(c.identity))throw Error(`duplicate browser plugin identity "${c.identity}"`);n.add(c.identity);let l=t.get(c.identity);if(!l)throw Error(`browser plugin "${c.identity}" from ${a} has no active frontend manifest selection`);if(l.category!==c.category)throw Error(`browser plugin "${c.identity}" from ${a} declares category "${c.category}" but its frontend manifest selection is "${l.category}"`);return{input:c,selection:l}}),i=De.join(e.outputDir,dE);xge(i,{recursive:!0});let s=o.map(({input:a,selection:c})=>{let l;try{l=Bun.resolveSync(a.entrypoint,e.orgPath)}catch(S){throw Error(`browser plugin "${a.identity}" entrypoint ${JSON.stringify(a.entrypoint)} cannot be resolved from the organisation`,{cause:S})}let d=`.tmp-${eF()}.js`,u=De.join(i,d),p=Bun.spawnSync(["bun","build",l,"--outdir",i,"--entry-naming",d,"--target","browser","--format","esm","--production","--minify",...Uge.flatMap((S)=>["--external",S])],{cwd:e.orgPath,env:{...process.env,NODE_ENV:"production"},stderr:"pipe",stdout:"pipe",timeout:$G});if(p.exitedDueToTimeout)throw sc(u,{force:!0}),Error(`browser plugin "${a.identity}" bundle timed out after ${$G/1000}s`);if(p.exitCode!==0){sc(u,{force:!0});let S=new TextDecoder,x=S.decode(p.stderr).trim()||S.decode(p.stdout).trim();throw Error(`browser plugin "${a.identity}" bundle failed${x?`: ${x}`:""}`)}if(!lR(u))throw Error(`browser plugin "${a.identity}" bundle did not produce ${u}`);try{$ge({artifactPath:u,category:a.category,config:c.config,entrypointPath:l,hostInterfaceVersion:a.hostInterfaceVersion,identity:a.identity,orgPath:e.orgPath})}catch(S){throw sc(u,{force:!0}),S}let y=Cp(u),g=`${dE}/${y}.js`,E=De.join(e.outputDir,g);if(lR(E))sc(u,{force:!0});else WG(u,E);return{identity:a.identity,category:a.category,hostInterfaceVersion:a.hostInterfaceVersion,path:g,sha256:y,...a.preparation!==void 0&&{preparation:Lge({browserArtifactPath:g,entrypoint:a.preparation.entrypoint,identity:a.identity,orgPath:e.orgPath,outputDir:e.outputDir})}}});return{format:QI,version:JI,plugins:s}},Tg=(e,t="dist")=>En.gen(function*(){let r=yield*Bo,n=ZN(new URL("./bundled-db-import.mjs",import.meta.url)),o=ZN(new URL("./bundled-graphql-schema.mjs",import.meta.url)),i=De.resolve(process.cwd(),e),s=De.resolve(i,t);yield*Lr.log(`Building organisation from: ${i}`),yield*Lr.log(`Output directory: ${s}`),yield*Lr.log(`
|
|
179
|
+
[1/6] Preparing output directory...`),yield*r.makeDirectory(s,{recursive:!0}),yield*En.sync(()=>{for(let ge of Cge)sc(De.join(s,ge),{force:!0});sc(De.join(s,"_pf","app-icons"),{force:!0,recursive:!0}),sc(De.join(s,"_pf","public-form-branding"),{force:!0,recursive:!0}),sc(De.join(s,"docs"),{force:!0,recursive:!0}),sc(De.join(s,vg),{force:!0}),sc(De.join(s,dE),{force:!0,recursive:!0})}),yield*Lr.log(`
|
|
180
|
+
[2/6] Bundling organisation...`);let c=De.join(i,"src/index.ts"),l=De.join(s,"org.js"),d=De.join(Tge(),`.pfcli-build-${eF()}`);if(!(yield*r.exists(c)))return yield*new vn({message:`Source file not found: ${c}`});yield*r.makeDirectory(d,{recursive:!0});let p=De.join(d,"entry.ts"),y="createBundledDbImport",g=[`import * as OrgModule from ${globalThis.JSON.stringify(c)}`,`import { createBundledDbImport } from ${globalThis.JSON.stringify(n)}`,`import { buildBundledGraphqlSchema } from ${globalThis.JSON.stringify(o)}`,`export * from ${globalThis.JSON.stringify(c)}`,`export const dbImport = ${y}(OrgModule, ${globalThis.JSON.stringify(i)})`,"export const __pfBuildDynamicSchema = (orgPath, customGraphqlSchema) => buildBundledGraphqlSchema(OrgModule.org, orgPath, customGraphqlSchema)",""].join(`
|
|
181
|
+
`);yield*r.writeFileString(p,g).pipe(En.mapError((ge)=>new vn({message:"Failed to create temporary bundle entrypoint",cause:ge})));let E=["build",p,"--outdir",s,"--entry-naming","org.js","--minify","--target","node","--conditions","bun",...Pge.flatMap((ge)=>["--external",ge])],S=90000,x=yield*En.try({try:()=>Bun.spawnSync(["bun",...E],{cwd:i,stderr:"pipe",stdout:"pipe",timeout:S}),catch:(ge)=>new vn({message:"Failed to bundle organisation with bun build",cause:ge})}).pipe(En.ensuring(En.sync(()=>{try{sc(p,{force:!0})}catch{}try{bge(d)}catch{}})));if(x.exitedDueToTimeout)return yield*new vn({message:`bun build timed out after ${S/1000}s`});if(x.exitCode!==0){let ge=new TextDecoder,pr=ge.decode(x.stderr).trim(),mn=ge.decode(x.stdout).trim(),U=pr||mn;return yield*new vn({message:U?`bun build failed with exit code ${x.exitCode}: ${U}`:`bun build failed with exit code ${x.exitCode}`})}let w=yield*r.readFileString(l).pipe(En.mapError((ge)=>new vn({message:`Failed to read bundled organisation: ${l}`,cause:ge}))),_=jG("sha256").update(w).digest("hex");yield*Lr.log(`\u2705 Bundled: ${l}`),yield*Lr.log(`
|
|
182
|
+
[3/6] Generating deploy v${nE} manifest...`);let T=yield*En.tryPromise({try:async()=>import(c),catch:(ge)=>new vn({message:`Failed to import organisation: ${ge}`,cause:ge})});if(!T.org)return yield*new vn({message:`Module at ${c} must export an 'org' named export.`});if(!DK(T.org))return yield*new vn({message:`Export 'org' at ${c} must be an Organisation instance.`});let{org:b,CustomGraphqlSchema:I,CustomAwsRuntimeConfig:O}=T,L=De.join(i,"graphql");yield*BG(b).pipe(En.mapError((ge)=>new vn({message:"Process flow validation failed",cause:ge})));let Y=yield*En.try({try:()=>fG({org:b,orgBundleSha256:_,producer:lE,customAwsRuntimeConfig:O}),catch:(ge)=>new vn({message:"Failed to generate deploy manifest",cause:ge})}),Z=De.join(s,Sg),ee=`${Z}.tmp`,ae=JSON.stringify(Y,null,2);yield*r.writeFileString(ee,`${ae}
|
|
183
|
+
`),yield*r.rename(ee,Z),yield*Lr.log(`\u2705 Generated: ${Z}`),yield*Lr.log(`
|
|
184
|
+
[4/6] Generating frontend v${xg} manifest...`);let ne=yield*_G(b,{basePath:i}).pipe(En.mapError((ge)=>new vn({message:ge instanceof Error?ge.message:"Failed to generate frontend manifest",cause:ge}))),le=De.join(s,iE),ie=`${le}.tmp`,je=JSON.stringify(ne,null,2);yield*r.writeFileString(ie,`${je}
|
|
185
|
+
`),yield*r.rename(ie,le);let ft=yield*En.try({try:()=>_K(b,{basePath:i}),catch:(ge)=>new vn({message:ge instanceof Error?ge.message:"Failed to collect App Icons files",cause:ge})}),yt=yield*En.try({try:()=>qge({org:b,orgPath:i,outputDir:s,frontendManifest:ne}),catch:(ge)=>new vn({message:ge instanceof Error?ge.message:"Failed to build browser plugin artifacts",cause:ge})}),Ut=De.join(s,vg),_t=`${Ut}.tmp`;yield*r.writeFileString(_t,`${JSON.stringify(yt,null,2)}
|
|
186
|
+
`),yield*r.rename(_t,Ut);let nt=De.resolve(s,"_pf/app-icons");for(let ge of ft){let pr=De.resolve(s,ge.publicPath.replace(/^\//,""));if(!pr.startsWith(`${nt}${De.sep}`))return yield*new vn({message:`App Icons public path resolved outside ${nt}: ${ge.publicPath}`});yield*r.makeDirectory(De.dirname(pr),{recursive:!0}),yield*r.copyFile(ge.sourcePath,pr).pipe(En.mapError((mn)=>new vn({message:`Failed to copy App Icons file: ${ge.sourcePath}`,cause:mn})))}let be=yield*En.try({try:()=>CG(b,{basePath:i}),catch:(ge)=>new vn({message:ge instanceof Error?ge.message:"Failed to collect Public Form Branding files",cause:ge})}),Sr=De.resolve(s,"_pf/public-form-branding");for(let ge of be){let pr=De.resolve(s,ge.publicPath.replace(/^\//,""));if(!pr.startsWith(`${Sr}${De.sep}`))return yield*new vn({message:`Public Form Branding public path resolved outside ${Sr}: ${ge.publicPath}`});yield*r.makeDirectory(De.dirname(pr),{recursive:!0}),yield*r.copyFile(ge.sourcePath,pr).pipe(En.mapError((mn)=>new vn({message:`Failed to copy Public Form Branding file: ${ge.sourcePath}`,cause:mn})))}let no=De.join(i,"docs"),Xe=De.join(s,"docs");if(yield*r.exists(no))yield*En.sync(()=>{vge(no,Xe,{recursive:!0})}),yield*Lr.log(`\u2705 Copied docs: ${Xe}`);yield*Lr.log(`\u2705 Generated: ${le}`),yield*Lr.log(`\u2705 Generated: ${Ut}`),yield*Lr.log(`
|
|
187
|
+
[5/6] Generating GraphQL schema...`);let Mo=[];if(yield*r.exists(L)){let ge=(yield*r.readDirectory(L)).filter((pr)=>pr.endsWith(".graphql")).sort();if(ge.length>0)yield*Lr.log(`Found ${ge.length} custom GraphQL file(s) in organisation`);for(let pr of ge){let mn=De.join(L,pr),U=yield*r.readFileString(mn).pipe(En.mapError((V)=>new xp({message:`Failed to read custom GraphQL file: ${pr}`,cause:V})));Mo.push({fileName:pr,content:U})}}let Tr=I||Mo.length>0?{...I??{},...Mo.length>0?{typeDefs:[I?.typeDefs?.trim(),...Mo.map(({content:ge})=>ge.trim())].filter((ge)=>ge!==void 0).join(`
|
|
188
|
+
|
|
189
|
+
`)}:{}}:void 0,Qo=yield*En.tryPromise({try:async()=>import(`${VG(l).href}?sha256=${_}`),catch:(ge)=>new xp({message:"Failed to load bundled organisation schema generator",cause:ge})}),ur=yield*En.try({try:()=>Mge(Qo),catch:(ge)=>new xp({message:ge instanceof Error?ge.message:"Bundled organisation schema generator is invalid",cause:ge})}),Rr=yield*En.tryPromise({try:()=>ur(i,Tr),catch:(ge)=>new xp({message:"Failed to generate GraphQL schema",cause:ge})}),So=De.join(s,"graphql"),Ps=De.join(So,"org.graphql"),Nc=De.join(So,"org.graphql.tmp");yield*r.makeDirectory(So,{recursive:!0});for(let{fileName:ge,content:pr}of Mo){let mn=De.join(So,ge),U=De.join(So,`${ge}.tmp`);yield*r.writeFileString(U,pr),yield*r.rename(U,mn),yield*Lr.log(`\u2705 Copied custom GraphQL: ${ge}`)}yield*r.writeFileString(Nc,`${Rr}
|
|
190
|
+
`),yield*r.rename(Nc,Ps),yield*Lr.log(`\u2705 Generated: ${Ps}`),yield*Lr.log(`
|
|
191
|
+
[6/6] Copying Cedar policies...`);let gi=De.join(s,"cedar");yield*r.makeDirectory(gi,{recursive:!0});let Hu=ZN(new URL("./resources/cedar/",import.meta.url)),vo=De.join(Hu,"policies.cedar"),Zy=De.join(Hu,"schema.cedarschema");if(yield*r.exists(vo)){let ge=yield*r.readFileString(vo),pr=De.join(gi,"policies.cedar"),mn=De.join(gi,"policies.cedar.tmp");yield*r.writeFileString(mn,ge),yield*r.rename(mn,pr),yield*Lr.log("\u2705 Copied: policies.cedar")}else yield*Lr.warn(`\u26A0\uFE0F Default policies not found: ${vo}`);if(yield*r.exists(Zy)){let ge=yield*r.readFileString(Zy),pr=De.join(gi,"schema.cedarschema"),mn=De.join(gi,"schema.cedarschema.tmp");yield*r.writeFileString(mn,ge),yield*r.rename(mn,pr),yield*Lr.log("\u2705 Copied: schema.cedarschema")}else yield*Lr.warn(`\u26A0\uFE0F Default schema not found: ${Zy}`);let Bv=nR(b);if(Bv.length>0){yield*Lr.log(`Found ${Bv.length} custom policy file(s) in organisation`);for(let ge of Bv){let pr=De.join(i,ge);if(!(yield*r.exists(pr))){yield*Lr.warn(`\u26A0\uFE0F Custom policy file not found: ${pr}`);continue}let U=yield*r.readFileString(pr).pipe(En.mapError((Ze)=>new zh({message:`Failed to read custom policy file: ${ge}`,cause:Ze}))),V=De.basename(ge),re=De.join(gi,V),pe=De.join(gi,`${V}.tmp`);yield*r.writeFileString(pe,U),yield*r.rename(pe,re),yield*Lr.log(`\u2705 Copied custom policy: ${V}`)}}let $v=oR(b);if($v.length>0){yield*Lr.log(`Found ${$v.length} custom schema file(s) in organisation`);for(let ge of $v){let pr=De.join(i,ge);if(!(yield*r.exists(pr))){yield*Lr.warn(`\u26A0\uFE0F Custom schema file not found: ${pr}`);continue}let U=yield*r.readFileString(pr).pipe(En.mapError((Ze)=>new zh({message:`Failed to read custom schema file: ${ge}`,cause:Ze}))),V=De.basename(ge),re=De.join(gi,V),pe=De.join(gi,`${V}.tmp`);yield*r.writeFileString(pe,U),yield*r.rename(pe,re),yield*Lr.log(`\u2705 Copied custom schema: ${V}`)}}yield*Lr.log(`
|
|
192
|
+
Generating artifact inventory...`);let _k=yield*En.try({try:()=>{let ge=[{format:_ge,version:1,path:"org.js",sha256:Cp(De.join(s,"org.js"))},{format:gg,version:1,path:Sg,sha256:Cp(De.join(s,Sg))},{format:Oge,version:xg,path:iE,sha256:Cp(De.join(s,iE))},{format:QI,version:JI,path:vg,sha256:Cp(De.join(s,vg))},...yt.plugins.flatMap((U)=>[{format:Nge,version:U.hostInterfaceVersion,path:U.path,sha256:U.sha256},...U.preparation===void 0?[]:[{format:Fge,version:U.hostInterfaceVersion,path:U.preparation.path,sha256:U.preparation.sha256}]])],pr=De.join(s,"graphql/org.graphql");if(lR(pr))ge.push({format:kge,version:1,path:"graphql/org.graphql",sha256:Cp(pr)});let mn=De.join(s,"cedar");for(let U of Ege(mn).sort())if(U.endsWith(".cedar")||U.endsWith(".cedarschema"))ge.push({format:Dge,version:1,path:`cedar/${U}`,sha256:Cp(De.join(mn,U))});return ge},catch:(ge)=>new vn({message:"Failed to build artifact inventory",cause:ge})}),kk={format:Ige,version:Rge,producer:lE,entries:_k},Rd=De.join(s,Age),yT=`${Rd}.tmp`;yield*r.writeFileString(yT,`${JSON.stringify(kk,null,2)}
|
|
193
|
+
`),yield*r.rename(yT,Rd),yield*Lr.log(`\u2705 Generated: ${Rd}`),yield*Lr.log(`
|
|
194
|
+
\u2705 Build completed successfully!
|
|
195
|
+
Output: ${s}`)});import{Console as iu,Effect as Jge}from"effect";import{Effect as Tm}from"effect";var jge=`
|
|
196
|
+
query ListProjectStages($projectId: String!) {
|
|
197
|
+
listProjectStages(projectId: $projectId) {
|
|
198
|
+
items {
|
|
199
|
+
stageName
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
`,Hge=`
|
|
204
|
+
query ListProjectEnvironments($projectId: String!) {
|
|
205
|
+
listProjectEnvironments(projectId: $projectId) {
|
|
206
|
+
items {
|
|
207
|
+
environmentName
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
`,zG=1000,Wge=/^env-[0-9A-HJKMNP-TV-Z]{26}$/,Vge=(e)=>typeof e==="object"&&e!==null&&("listProjectStages"in e)&&Array.isArray(e.listProjectStages?.items),zge=(e)=>typeof e==="object"&&e!==null&&("listProjectEnvironments"in e)&&Array.isArray(e.listProjectEnvironments?.items),Kge=(e,t)=>{if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;let r=Array.from({length:t.length+1},(o,i)=>i),n=Array(t.length+1);for(let o=1;o<=e.length;o+=1){n[0]=o;for(let i=1;i<=t.length;i+=1){let s=e[o-1]===t[i-1]?0:1,a=(r[i]??i)+1,c=(n[i-1]??o)+1,l=(r[i-1]??i-1)+s;n[i]=Math.min(a,c,l)}for(let i=0;i<=t.length;i+=1)r[i]=n[i]??i}return r[t.length]??t.length},Gge=(e,t)=>{if(t.length===0)return{kind:"none"};let r=e.toLowerCase(),n=t.map((l)=>({value:l,score:Kge(r,l.toLowerCase())})).sort((l,d)=>l.score===d.score?l.value.localeCompare(d.value):l.score-d.score),o=n[0]?.score;if(o===void 0)return{kind:"none"};let i=n[0]?.value;if(i===void 0)return{kind:"none"};let s=Math.max(e.length,i.length),a=Math.max(1,Math.floor(s/3));if(o>a)return{kind:"none"};let c=n.filter((l)=>l.score===o).map((l)=>l.value);if(c.length===1){let[l]=c;if(l===void 0)return{kind:"none"};return{kind:"single",value:l}}return{kind:"multiple",values:c}},Qge=(e)=>{let t=Gge(e.value,e.knownValues),r=[`Unknown ${e.kind} "${e.value}" for project ${e.projectId}.`,""];if(t.kind==="single")r.push(`Did you mean "${t.value}"?`,"");else if(t.kind==="multiple")r.push(`Possible matches: ${t.values.join(", ")}`,"");return r.push(`Known ${e.kind}s:`,...e.knownValues.map((n)=>`- ${n}`)),r.join(`
|
|
212
|
+
`)},KG=(e)=>Tm.gen(function*(){if(e.knownValues.length===0)return;if(e.knownValues.includes(e.value))return;return yield*new ce({message:Qge(e)})}),Bs=(e,t)=>Tm.gen(function*(){let r=yield*Mr(jge,{projectId:e},{timeoutMs:zG}).pipe(Tm.catchTag("CliError",()=>Tm.void));if(!r)return;if(!Vge(r))return;let n=r.listProjectStages.items.map((o)=>o.stageName);for(let o of new Set(t))yield*KG({kind:"stage",projectId:e,value:o,knownValues:n})}),ai=(e,t)=>Tm.gen(function*(){if(Wge.test(t))return;let r=yield*Mr(Hge,{projectId:e},{timeoutMs:zG}).pipe(Tm.catchTag("CliError",()=>Tm.void));if(!r)return;if(!zge(r))return;let n=r.listProjectEnvironments.items.map((o)=>o.environmentName);yield*KG({kind:"environment",projectId:e,value:t,knownValues:n})});var Yge=`
|
|
213
|
+
mutation CopyNewConfigParameters($projectId: String!, $stageId: String!, $fromStageId: String!) {
|
|
214
|
+
copyNewConfigParameters(projectId: $projectId, stageId: $stageId, fromStageId: $fromStageId) {
|
|
215
|
+
copiedCount
|
|
216
|
+
copiedKeys
|
|
217
|
+
sameStage
|
|
218
|
+
skippedCount
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
`,GG=(e,t,r)=>Jge.gen(function*(){if(t===r){yield*iu.log(`Source and destination stage are both ${t}. Nothing copied.`);return}yield*Bs(e,[t,r]),yield*iu.log(`Copying new config parameters from stage ${r} to ${t} for project ${e}...`);let o=(yield*Mr(Yge,{projectId:e,stageId:t,fromStageId:r})).copyNewConfigParameters;if(o.sameStage){yield*iu.log("Source and destination stage resolve to the same stage. Nothing copied.");return}if(o.copiedCount===0){if(o.skippedCount===0){yield*iu.log(`No config parameters found in ${r}.`);return}yield*iu.log(`No new config parameters copied. ${o.skippedCount} key${o.skippedCount===1?"":"s"} already existed in ${t}.`);return}if(yield*iu.log(`Copied ${o.copiedCount} new config parameter${o.copiedCount===1?"":"s"} from ${r} to ${t}.`),o.skippedCount>0)yield*iu.log(`Skipped ${o.skippedCount} existing key${o.skippedCount===1?"":"s"}.`);yield*iu.log("");for(let i of o.copiedKeys)yield*iu.log(` ${i}`)});import{Console as QG,Effect as Xge}from"effect";var Zge=`
|
|
222
|
+
mutation DeleteConfigParameter($projectId: String!, $stageId: String!, $key: String!) {
|
|
223
|
+
deleteConfigParameter(projectId: $projectId, stageId: $stageId, key: $key)
|
|
224
|
+
}
|
|
225
|
+
`,JG=(e,t,r)=>Xge.gen(function*(){if(yield*Bs(e,[t]),yield*QG.log(`Deleting config parameter ${r} for project ${e}, stage ${t}...`),(yield*Mr(Zge,{projectId:e,stageId:t,key:r})).deleteConfigParameter)yield*QG.log(`Successfully deleted ${r}`);else return yield*new ce({message:"Failed to delete config parameter"})});import{Console as tF,Effect as eSe}from"effect";var tSe=`
|
|
226
|
+
query GetConfigParameter($projectId: String!, $stageId: String!, $key: String!) {
|
|
227
|
+
getConfigParameter(projectId: $projectId, stageId: $stageId, key: $key) {
|
|
228
|
+
name
|
|
229
|
+
value
|
|
230
|
+
isSecret
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
`,YG=(e,t,r)=>eSe.gen(function*(){yield*Bs(e,[t]),yield*tF.log(`Fetching config parameter ${r} for project ${e}, stage ${t}...`);let o=(yield*Mr(tSe,{projectId:e,stageId:t,key:r})).getConfigParameter;if(!o){yield*tF.log(`Parameter ${r} not found.`);return}let i=o.isSecret?"***":o.value??"(empty)";yield*tF.log(`${o.name}${o.isSecret?" (secret)":""}: ${i}`)});import{Console as dR,Effect as rSe}from"effect";var nSe=`
|
|
234
|
+
query ListConfigParameters($projectId: String!, $stageId: String!) {
|
|
235
|
+
listConfigParameters(projectId: $projectId, stageId: $stageId) {
|
|
236
|
+
items {
|
|
237
|
+
name
|
|
238
|
+
value
|
|
239
|
+
isSecret
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
`,XG=(e,t)=>rSe.gen(function*(){yield*Bs(e,[t]),yield*dR.log(`Fetching config parameters for project ${e}, stage ${t}...`);let r=yield*Mr(nSe,{projectId:e,stageId:t}),{items:n}=r.listConfigParameters;if(n.length===0){yield*dR.log("No config parameters found.");return}yield*dR.log(`
|
|
244
|
+
Config parameters (${n.length} total):
|
|
245
|
+
`);for(let o of n){let i=o.isSecret?"***":o.value??"(empty)";yield*dR.log(` ${o.name}${o.isSecret?" (secret)":""}: ${i}`)}});import{Console as ZG,Effect as eQ}from"effect";var oSe=`
|
|
246
|
+
mutation SetConfigParameter($projectId: String!, $stageId: String!, $key: String!, $value: String!, $isSecret: Boolean!) {
|
|
247
|
+
setConfigParameter(projectId: $projectId, stageId: $stageId, key: $key, value: $value, isSecret: $isSecret)
|
|
248
|
+
}
|
|
249
|
+
`,rF="Expected 'config set --project <project> --stage <stage> KEY', 'config set --project <project> --stage <stage> KEY=VALUE', or 'config set --project <project> --stage <stage> KEY VALUE'",iSe=(e,t=process.env)=>eQ.gen(function*(){if(e.length===1){let r=e[0];if(!r)return yield*new ce({message:rF});let n=r.indexOf("=");if(n===-1){let o=t[r];if(o===void 0)return yield*new ce({message:`Environment variable ${r} is unset`});return[r,o]}if(n===0)return yield*new ce({message:rF});return[r.slice(0,n),r.slice(n+1)]}if(e.length===2){let[r,n]=e;if(r&&n!==void 0)return[r,n]}return yield*new ce({message:rF})}),tQ=(e,t,r,n)=>eQ.gen(function*(){let[o,i]=yield*iSe(r);if(yield*Bs(e,[t]),yield*ZG.log(`Setting config parameter ${o}${n?" (secret)":""} for project ${e}, stage ${t}...`),(yield*Mr(oSe,{projectId:e,stageId:t,key:o,value:i,isSecret:n})).setConfigParameter)yield*ZG.log(`Successfully set ${o}`);else return yield*new ce({message:"Failed to set config parameter"})});import{Console as Li,Effect as uR}from"effect";var sSe=`
|
|
250
|
+
query GetDnsRecords($projectId: String!, $environmentId: String!) {
|
|
251
|
+
getDnsRecords(projectId: $projectId, environmentId: $environmentId) {
|
|
252
|
+
defaultDomain
|
|
253
|
+
frontendUrl
|
|
254
|
+
frontendUrlNote
|
|
255
|
+
customDomain
|
|
256
|
+
certificateStatus
|
|
257
|
+
warnings
|
|
258
|
+
validationRecords {
|
|
259
|
+
type
|
|
260
|
+
name
|
|
261
|
+
value
|
|
262
|
+
purpose
|
|
263
|
+
}
|
|
264
|
+
validationNote
|
|
265
|
+
siteAccessRecord {
|
|
266
|
+
type
|
|
267
|
+
name
|
|
268
|
+
value
|
|
269
|
+
purpose
|
|
270
|
+
}
|
|
271
|
+
siteAccessNote
|
|
272
|
+
postscriptNotes
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
`,rQ=(e)=>` ${e.type} ${e.name} -> ${e.value} (${e.purpose})`,nQ=(e,t)=>ai(e,t).pipe(uR.flatMap(()=>Mr(sSe,{projectId:e,environmentId:t})),uR.mapError((r)=>new dO({message:r.message,cause:r.cause})),uR.flatMap(({getDnsRecords:r})=>uR.gen(function*(){for(let n of r.warnings)yield*Li.log(n);if(r.warnings.length>0)yield*Li.log("");if(!r.customDomain){yield*Li.log(`No custom domain configured for ${e}/${t}.`),yield*Li.log(`Frontend URL: ${r.frontendUrl}`);return}if(yield*Li.log(`Custom domain: ${r.customDomain}`),r.certificateStatus)yield*Li.log(`Status: ${r.certificateStatus}`);if(yield*Li.log(`Frontend URL: ${r.frontendUrl}`),r.frontendUrlNote)yield*Li.log(`Note: ${r.frontendUrlNote}`);if(yield*Li.log(""),yield*Li.log("Required DNS records:"),r.validationRecords.length>0)for(let n of r.validationRecords)yield*Li.log(rQ(n));else if(r.validationNote)yield*Li.log(` (${r.validationNote})`);if(r.siteAccessRecord)yield*Li.log(rQ(r.siteAccessRecord));else if(r.siteAccessNote)yield*Li.log(` (${r.siteAccessNote})`);if(r.postscriptNotes.length>0){yield*Li.log("");for(let n of r.postscriptNotes)yield*Li.log(n)}})));import{existsSync as mQ,mkdirSync as HSe}from"fs";import{dirname as WSe,resolve as VSe}from"path";import{Console as sF,Duration as zSe,Effect as Bi}from"effect";import{chmod as iQ,mkdtemp as aSe,open as oF,readFile as cSe,rename as lSe,rm as dSe,stat as uSe}from"fs/promises";import{basename as pSe,dirname as fSe,join as nF}from"path";import{TURSO_LOGICAL_DUMP_PREFIX_INSPECT_BYTES as mSe,TURSO_LOGICAL_DUMP_SUFFIX_INSPECT_BYTES as ySe,filterTursoInternalStatements as hSe,httpsDumpUrlFromTursoLibsqlUrl as gSe,isPlausibleTursoSqlDumpPrefix as SSe,isPlausibleTursoSqlDumpSuffix as vSe}from"@processfocus/hosting-contract";import{Cause as sQ,Data as xSe,Duration as ESe,Effect as Ht,Exit as pR}from"effect";import{Database as aQ}from"bun:sqlite";var bSe=900000,oQ="__turso_internal_*";class cQ extends xSe.TaggedError("TursoDbDownloadFailure"){}var wSe=new Set(["EACCES","ECONNREFUSED","ECONNRESET","EDQUOT","EEXIST","EIO","ENOENT","ENOSPC","EPIPE","ETIMEDOUT","SQLITE_BUSY","SQLITE_CONSTRAINT","SQLITE_CORRUPT","SQLITE_ERROR","SQLITE_FULL","SQLITE_IOERR","SQLITE_LOCKED","SQLITE_NOTADB","SQLITE_READONLY","UND_ERR_CONNECT_TIMEOUT"]),TSe=(e)=>{if(typeof e!=="object"||e===null||!("code"in e))return;let t=e.code;if(typeof t==="number"&&Number.isSafeInteger(t))return t;if(typeof t==="string"&&wSe.has(t))return t;return},ASe=(e)=>{let t=e instanceof DOMException?"DOMException":e instanceof TypeError?"TypeError":e instanceof RangeError?"RangeError":e instanceof Error?"Error":typeof e==="object"&&e!==null?"NonErrorObject":"NonErrorPrimitive",r=TSe(e);return r===void 0?{_tag:"SanitizedBoundaryCause",errorType:t}:{_tag:"SanitizedBoundaryCause",errorType:t,code:r}},Ia=(e,t)=>new cQ(t===void 0?{message:e}:{message:e,cause:ASe(t)}),ys=(e)=>Ht.try({try:e.try,catch:(t)=>Ia(e.message,t)}),Ho=(e)=>Ht.tryPromise({try:e.try,catch:(t)=>Ia(e.message,t)}),ISe=(e)=>pR.isFailure(e)?Ht.failCause(e.cause):Ht.succeed(e.value),Am=(e,t,r)=>Ht.uninterruptibleMask((n)=>Ht.gen(function*(){let o=yield*e,i=yield*Ht.exit(n(t(o))),s=yield*Ht.exit(r(o,i));if(pR.isFailure(s)){if(pR.isFailure(i))return yield*Ht.failCause(sQ.sequential(i.cause,s.cause));return yield*Ht.failCause(s.cause)}return yield*ISe(i)})),RSe=(e)=>sQ.map(e,(t)=>new ce({message:t.message,cause:t})),PSe=(e)=>`"${e.replaceAll('"','""')}"`,CSe=(e)=>Ht.gen(function*(){let t=0;while(t<e.bytes.byteLength){let{bytesWritten:r}=yield*Ho({message:"Failed to write complete TursoDB dump response",try:(n)=>e.write(e.bytes,t,e.bytes.byteLength-t,n)});if(!Number.isSafeInteger(r)||r<1||r>e.bytes.byteLength-t)yield*Ht.fail(Ia("Failed to write complete TursoDB dump response"));t+=r}}),iF=(e,t)=>Ho({message:t,try:()=>e.close()}),_Se=(e)=>pR.isInterrupted(e.useExit)?ys({message:e.message,try:()=>{e.handle.close().catch(()=>{return})}}):iF(e.handle,e.message),kSe=(e)=>Ht.gen(function*(){let{size:t}=yield*Ho({message:"Failed to inspect TursoDB dump response",try:()=>uSe(e)}),r=Math.min(t,mSe),n=Math.min(t,ySe),o=new Uint8Array(r),i=new Uint8Array(n);return yield*Am(Ho({message:"Failed to inspect TursoDB dump response",try:()=>oF(e,"r")}),(s)=>Ht.gen(function*(){if(r>0)yield*Ho({message:"Failed to inspect TursoDB dump response",try:()=>s.read(o,0,r,0)}),yield*Ho({message:"Failed to inspect TursoDB dump response",try:()=>s.read(i,0,n,t-n)})}),(s)=>iF(s,"Failed to publish downloaded TursoDB snapshot")),{byteSize:t,firstBytes:o,lastBytes:i}}),DSe=(e)=>Ho({message:"TursoDB dump request failed",try:()=>e.cancel()}),OSe=(e)=>ys({message:"TursoDB dump request failed",try:()=>{e.cancel().catch(()=>{return})}}),NSe=(e)=>ys({message:"TursoDB dump request failed",try:()=>e.releaseLock()}),uE=(e,t)=>{e.addEventListener("abort",()=>t.abort(),{once:!0})},FSe=(e)=>{let t=new AbortController;return Ht.gen(function*(){let n=yield*ys({message:"Database Download session returned an invalid database URL",try:()=>gSe(e.sourceUrl)}),o=yield*Ho({message:"TursoDB dump request failed",try:(s)=>(uE(s,t),e.fetchImpl(n,{method:"GET",headers:{Authorization:`Bearer ${e.authToken}`},signal:t.signal}))});if(!o.ok){if(o.body!==null)yield*DSe(o.body).pipe(Ht.ignore);yield*Ht.fail(Ia(`TursoDB dump request failed with HTTP ${o.status}`))}let i=o.body;if(i===null)return yield*Ht.fail(Ia("TursoDB dump response was empty"));yield*Am(ys({message:"TursoDB dump request failed",try:()=>i.getReader()}),(s)=>Am(Ho({message:"TursoDB dump request failed",try:(a)=>(uE(a,t),e.openDumpFile(e.dumpPath))}),(a)=>Ht.gen(function*(){while(!0){let c=yield*Ho({message:"TursoDB dump request failed",try:(l)=>(uE(l,t),s.read())});if(c.done)break;if(c.value.byteLength>0)yield*CSe({bytes:c.value,write:(l,d,u,p)=>(uE(p,t),a.write(l,d,u,null))})}yield*Ho({message:"TursoDB dump request failed",try:(c)=>(uE(c,t),a.sync())})}),(a,c)=>_Se({handle:a,message:"TursoDB dump request failed",useExit:c})),(s)=>Ht.gen(function*(){yield*OSe(s).pipe(Ht.ignore),yield*NSe(s)}))}).pipe(Ht.ensuring(Ht.sync(()=>{t.abort()}))).pipe(Ht.timeoutFail({duration:ESe.millis(e.timeoutMs),onTimeout:()=>Ia("TursoDB dump request timed out")}))},USe=(e)=>Ht.gen(function*(){let t=yield*kSe(e);if(t.byteSize===0)yield*Ht.fail(Ia("TursoDB dump response was empty"));if(!SSe(t.firstBytes))yield*Ht.fail(Ia("TursoDB dump response was not valid logical SQL"));if(!vSe(t.lastBytes))yield*Ht.fail(Ia("TursoDB dump response was truncated or malformed"))}),MSe=(e)=>Ht.gen(function*(){let t=yield*ys({message:"Failed to materialize TursoDB logical dump as SQLite",try:()=>e.query(`SELECT type, name
|
|
276
|
+
FROM sqlite_schema
|
|
277
|
+
WHERE name GLOB '${oQ}'
|
|
278
|
+
ORDER BY CASE type
|
|
279
|
+
WHEN 'trigger' THEN 1
|
|
280
|
+
WHEN 'index' THEN 2
|
|
281
|
+
WHEN 'view' THEN 3
|
|
282
|
+
WHEN 'table' THEN 4
|
|
283
|
+
ELSE 5
|
|
284
|
+
END`).all()});for(let n of t){let o=PSe(n.name);yield*ys({message:"Failed to materialize TursoDB logical dump as SQLite",try:()=>{switch(n.type){case"trigger":e.exec(`DROP TRIGGER ${o}`);break;case"index":e.exec(`DROP INDEX ${o}`);break;case"view":e.exec(`DROP VIEW ${o}`);break;case"table":e.exec(`DROP TABLE ${o}`);break;default:{let i=n.type;throw Error(`Unexpected Turso schema object type: ${String(i)}`)}}}})}if((yield*ys({message:"Failed to materialize TursoDB logical dump as SQLite",try:()=>e.query(`SELECT name FROM sqlite_schema WHERE name GLOB '${oQ}'`).all()})).length>0)yield*Ht.fail(Ia("TursoDB internal objects remained after logical replay"))}),lQ=(e)=>Ht.gen(function*(){let t=yield*ys({message:"Downloaded TursoDB snapshot failed PRAGMA integrity_check",try:()=>e.query("PRAGMA integrity_check").all()});if(t.length!==1||t[0]?.integrity_check!=="ok")yield*Ht.fail(Ia("Downloaded TursoDB snapshot failed PRAGMA integrity_check"));if((yield*ys({message:"Downloaded TursoDB snapshot failed PRAGMA foreign_key_check",try:()=>e.query("PRAGMA foreign_key_check").all()})).length>0)yield*Ht.fail(Ia("Downloaded TursoDB snapshot failed PRAGMA foreign_key_check"))}),dQ=(e)=>ys({message:e.message,try:()=>e.database.close()}),LSe=(e)=>Am(ys({message:"Downloaded TursoDB snapshot failed PRAGMA integrity_check",try:()=>new aQ(e,{readonly:!0,strict:!0})}),lQ,(t)=>dQ({database:t,message:"Downloaded TursoDB snapshot failed validation"}));var BSe=(e)=>Ht.gen(function*(){let t=yield*Ho({message:"Failed to materialize TursoDB logical dump as SQLite",try:()=>cSe(e.dumpPath,"utf8")}),r=yield*ys({message:"Failed to materialize TursoDB logical dump as SQLite",try:()=>hSe(t)});yield*Am(ys({message:"Failed to create private TursoDB snapshot staging file",try:()=>new aQ(e.databasePath,{create:!0,strict:!0})}),(n)=>Ht.gen(function*(){yield*Ho({message:"Failed to create private TursoDB snapshot staging file",try:()=>iQ(e.databasePath,384)}),yield*ys({message:"Failed to materialize TursoDB logical dump as SQLite",try:()=>{n.exec("PRAGMA journal_mode = DELETE"),n.exec(r)}}),yield*MSe(n),yield*lQ(n)}),(n)=>dQ({database:n,message:"Failed to publish downloaded TursoDB snapshot"})),yield*LSe(e.databasePath)}),$Se=(e)=>Am(Ho({message:"Failed to publish downloaded TursoDB snapshot",try:()=>oF(e,"r")}),(t)=>Ho({message:"Failed to publish downloaded TursoDB snapshot",try:()=>t.sync()}),(t)=>iF(t,"Failed to publish downloaded TursoDB snapshot")),qSe=(e)=>Ho({message:"Failed to materialize TursoDB snapshot",try:()=>dSe(e,{recursive:!0,force:!0})}),jSe=(e)=>Ht.gen(function*(){let t=e.timeoutMs??bSe;if(!Number.isSafeInteger(t)||t<1)yield*Ht.fail(Ia("TursoDB download timeout must be a positive integer"));let r=fSe(e.outputPath);yield*Am(Ho({message:"Failed to publish downloaded TursoDB snapshot",try:()=>aSe(nF(r,`.${pSe(e.outputPath)}.download-`))}),(n)=>Ht.gen(function*(){let o=nF(n,"source.sql"),i=nF(n,"snapshot.sqlite");yield*Ho({message:"Failed to publish downloaded TursoDB snapshot",try:()=>iQ(n,448)}),yield*FSe({sourceUrl:e.sourceUrl,authToken:e.authToken,dumpPath:o,fetchImpl:e.fetch??fetch,openDumpFile:(s)=>oF(s,"wx",384),timeoutMs:t}),yield*USe(o),yield*BSe({dumpPath:o,databasePath:i}),yield*$Se(i),yield*Ho({message:"Failed to publish downloaded TursoDB snapshot",try:()=>lSe(i,e.outputPath)})}),qSe)}),uQ=(e)=>jSe(e).pipe(Ht.mapErrorCause(RSe));var KSe=`
|
|
285
|
+
mutation CreateDatabaseDownloadSession($projectId: String!, $environmentId: String!) {
|
|
286
|
+
createDatabaseDownloadSession(projectId: $projectId, environmentId: $environmentId) {
|
|
287
|
+
databaseUrl
|
|
288
|
+
authToken
|
|
289
|
+
databaseName
|
|
290
|
+
engine
|
|
291
|
+
target {
|
|
292
|
+
stageName
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
`,pQ=900000,fQ=(e)=>e.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"target",GSe=(e)=>e.toISOString().replace(/[:.]/g,"-"),QSe=(e,t,r=new Date)=>`pfcli-db-${fQ(e)}-${fQ(t)}-${GSe(r)}.sqlite`,JSe=(e)=>{let t=WSe(e);return Bi.try({try:()=>HSe(t,{recursive:!0}),catch:(r)=>new ce({message:`Failed to create output directory: ${t}`,cause:r})})},YSe=(e)=>Bi.tryPromise({try:()=>e.close(),catch:(t)=>new ce({message:"Failed to close local database sync state",cause:t})}).pipe(Bi.catchTag("CliError",(t)=>sF.error(`Warning: ${t.message}`))),XSe=(e)=>Bi.gen(function*(){let t=yield*Bi.tryPromise({try:()=>e.connectSyncDatabase({path:e.resolvedOutputPath,url:e.databaseUrl,authToken:e.authToken,clientName:"pfcli-db-download",fetch:e.fetchImpl}),catch:()=>new ce({message:"Failed to open local database sync state"})});return yield*Bi.tryPromise({try:()=>t.pull(),catch:()=>new ce({message:"Database sync pull failed"})}).pipe(Bi.timeoutFail({duration:zSe.millis(e.syncPullTimeoutMs),onTimeout:()=>new ce({message:"Database sync pull timed out"})}),Bi.ensuring(YSe(t)))}),ZSe=(e)=>Bi.sync(()=>mQ(e)).pipe(Bi.flatMap((t)=>t?Bi.void:Bi.fail(new ce({message:"Database sync completed without creating output file"})))),eve=()=>Bi.tryPromise({try:async()=>{let{connect:e}=await import("@tursodatabase/sync");return e},catch:(e)=>new ce({message:"Failed to load database sync support",cause:e})}),yQ=(e,t,r,n={})=>{let o=n.now??(()=>new Date),i=n.fetch??fetch,s=n.syncPullTimeoutMs??pQ,a=VSe(r??QSe(e,t,o()));return Bi.gen(function*(){yield*ai(e,t);let c=yield*ds(),l=oi(c.baseUrl);yield*JSe(a);let d=yield*Bi.sync(()=>mQ(a)),u=yield*Hr(l,c.accessToken,KSe,{projectId:e,environmentId:t}).pipe(Bi.map((y)=>y.createDatabaseDownloadSession)),p=u.engine==="tursodb"&&d?"Replacing local snapshot":d?"Updating local copy":"Downloading";if(yield*sF.log(`${p} ${u.databaseName} (${u.target.stageName})...`),u.engine==="libsql"){let y=n.connectSyncDatabase??(yield*eve());yield*XSe({databaseUrl:u.databaseUrl,authToken:u.authToken,resolvedOutputPath:a,fetchImpl:i,connectSyncDatabase:y,syncPullTimeoutMs:s})}else yield*(n.materializeTursoDbDownload??uQ)({sourceUrl:u.databaseUrl,authToken:u.authToken,outputPath:a,fetch:i,timeoutMs:n.tursoDbDownloadTimeoutMs??pQ});return yield*ZSe(a),yield*sF.log(`Saved to ${a}`),a})};import{Console as _Q,Effect as mE}from"effect";import{Effect as yR}from"effect";var fR="graphql-api",hQ=(e)=>{let t=e.split(".")[1];if(!t)return;try{let r=t.replace(/-/g,"+").replace(/_/g,"/"),n=r.padEnd(Math.ceil(r.length/4)*4,"=");return JSON.parse(Buffer.from(n,"base64").toString("utf8"))}catch{return}},gQ=(e)=>{let t=hQ(e);if(!t)return;if(typeof t.aud==="string")return t.aud;if(Array.isArray(t.aud)&&t.aud.every((r)=>typeof r==="string"))return t.aud;return},mR=(e)=>{let t=hQ(e);if(!t)return;let r=typeof t.properties==="object"&&t.properties!==null?t.properties:void 0;if(typeof r?.userId==="string")return r.userId;return typeof t.sub==="string"?t.sub:void 0};import{randomUUID as bQ}from"crypto";import{Clock as ive,Effect as EQ,Option as sve,Schema as Im}from"effect";var pE=(e)=>e.replace(/\/$/,"");var SQ=()=>process.env.FRONTEND_JWT_TOKEN,tve=(e)=>{let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Buffer.from(r,"base64").toString("utf8")},rve=(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(tve(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:pE(n.iss),audience:i}},vQ=()=>{let e=SQ();if(!e)return;return rve(e)};var Wl=()=>vQ()?.clientId??process.env.OAUTH_CLIENT_ID??"frontend",Ag=()=>vQ()?.audience??process.env.OAUTH_AUDIENCE??"graphql-api";var nve=(e)=>/^r3-[A-Za-z0-9]{43}$/.test(e),aF=async(e,t)=>{if(t===void 0||!Number.isSafeInteger(t)||t<=0)return;let r=[e.userId,[...new Set(e.roles??[])].sort(),e.orgUnitId??null,e.orgUnitPath??null,t],n="clientId"in e?["service",e.clientId,...r]:!e.delegation?["human",e.email,...r]:["delegation",e.email,e.delegation?.id,e.delegation?.generationId,e.delegation?.name,e.delegation?.expiresAt,e.delegationRoleSelection===void 0?null:[...new Set(e.delegationRoleSelection)].sort(),...r],o=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(JSON.stringify(["authority-recipient-v2",...n]))),i=0n;for(let c of new Uint8Array(o))i=i<<8n|BigInt(c);let s="";while(i>0n)s="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".charAt(Number(i%62n))+s,i/=62n;let a=`r3-${s.padStart(43,"0")}`;return nve(a)?a:void 0};import{Schema as Ot}from"effect";function cF(e){return{...e}}var ove=Ot.Struct({userId:Ot.String,clientId:Ot.String,roles:Ot.optional(Ot.Array(Ot.String)),orgUnitId:Ot.optional(Ot.String),orgUnitPath:Ot.optional(Ot.String)}),xQ=Ot.Struct({userId:Ot.String,email:Ot.String,picture:Ot.optional(Ot.String),orgUnitId:Ot.String,orgUnitPath:Ot.String,roles:Ot.Array(Ot.String),humanSession:Ot.optional(Ot.Literal(!0)),delegationRoleSelection:Ot.optional(Ot.Array(Ot.String)),delegation:Ot.optional(Ot.Struct({id:Ot.String,generationId:Ot.String,name:Ot.String,expiresAt:Ot.Number.pipe(Ot.int(),Ot.nonNegative())})),humanAuthentication:Ot.optional(Ot.Struct({providerUserId:Ot.String,authenticatedAt:Ot.Number.pipe(Ot.int(),Ot.nonNegative()),method:Ot.Literal("passkey")}))}),lF=xQ,_p=cF({user:Ot.standardSchemaV1(ove),providerUser:Ot.standardSchemaV1(xQ)});var wQ=1,TQ=["Waiting","Running","Completed","Failed","Abandoned"],ave=TQ,cve=new Set(TQ),lve=new Set(ave),dve=`
|
|
297
|
+
subscription PfcliExecutionStream {
|
|
298
|
+
streamExecution {
|
|
299
|
+
documents {
|
|
300
|
+
id
|
|
301
|
+
status
|
|
302
|
+
failureReason
|
|
303
|
+
abandonedReason
|
|
304
|
+
finishedAt
|
|
305
|
+
steps {
|
|
306
|
+
name
|
|
307
|
+
path
|
|
308
|
+
status
|
|
309
|
+
failureReason
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
`;class dF{items=[];waiters=[];closed=!1;failure=null;push(e){if(this.closed||this.failure)return;let t=this.waiters.shift();if(t){t.resolve({value:e,done:!1});return}this.items.push(e)}finish(){if(this.closed||this.failure)return;this.closed=!0;while(this.waiters.length>0)this.waiters.shift()?.resolve({value:void 0,done:!0})}fail(e){if(this.closed||this.failure)return;this.failure=e;while(this.waiters.length>0)this.waiters.shift()?.reject(e)}[Symbol.asyncIterator](){return{next:()=>{if(this.failure)return Promise.reject(this.failure);let e=this.items.shift();if(e)return Promise.resolve({value:e,done:!1});if(this.closed)return Promise.resolve({value:void 0,done:!0});return new Promise((t,r)=>{this.waiters.push({resolve:t,reject:r})})}}}}var AQ=(e)=>{if(typeof e==="string")return e;if(Buffer.isBuffer(e))return e.toString("utf8");if(Array.isArray(e))return Buffer.concat(e.filter((t)=>Buffer.isBuffer(t))).toString("utf8");if(e instanceof ArrayBuffer)return Buffer.from(e).toString("utf8");return String(e)},IQ=(e)=>{if(typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="number")return e.code;return},fE=(e)=>{if(e instanceof Error)return e;if(Array.isArray(e)){let t=e.map((r)=>typeof r==="object"&&r!==null&&("message"in r)?String(r.message):String(r)).join(", ");return Error(t)}if(typeof e==="object"&&e!==null){if("message"in e&&typeof e.message==="string")return Error(e.message);if("reason"in e&&typeof e.reason==="string")return Error(e.reason);return Error(JSON.stringify(e))}return Error(String(e))},uve=(e)=>typeof e==="string"&&cve.has(e),pve=(e)=>typeof e==="string"&&lve.has(e),RQ=(e)=>{if(typeof e!=="object"||e===null)return null;let t=e;if(typeof t.id!=="string"||!uve(t.status))return null;let n=(Array.isArray(t.steps)?t.steps:[]).map((o)=>{if(typeof o!=="object"||o===null)return null;let i=o;if(typeof i.name!=="string"||typeof i.path!=="string"||!pve(i.status))return null;return{name:i.name,path:i.path,status:i.status,failureReason:typeof i.failureReason==="string"?i.failureReason:null}}).filter((o)=>o!==null);return{id:t.id,status:t.status,failureReason:typeof t.failureReason==="string"?t.failureReason:null,abandonedReason:typeof t.abandonedReason==="string"?t.abandonedReason:null,finishedAt:typeof t.finishedAt==="string"?t.finishedAt:null,steps:n}},fve=(e)=>`header-${Buffer.from(JSON.stringify(e)).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`;class PQ{config;socket=null;subscriptionId=null;constructor(e){this.config=e}connect(){return new Promise((e,t)=>{if(typeof WebSocket>"u"){t(Error("WebSocket is not available in this runtime."));return}this.socket=new WebSocket(this.config.wsEndpoint,"graphql-transport-ws");let r=!1;this.socket.addEventListener("open",()=>{this.send({type:"connection_init",payload:{token:this.config.accessToken}})}),this.socket.addEventListener("message",(n)=>{let o=JSON.parse(AQ(n.data));switch(o.type){case"connection_ack":if(this.subscribe(),!r)r=!0,e();return;case"ping":this.send({type:"pong",payload:o.payload});return;case"pong":return;case"next":if(o.id!==this.subscriptionId)return;if(o.payload.errors&&o.payload.errors.length>0){this.config.onError(fE(o.payload.errors));return}for(let i of o.payload.data?.streamExecution?.documents??[]){let s=RQ(i);if(s)this.config.onExecution(s)}return;case"error":{let i=fE(o.payload);if(!r){r=!0,t(i);return}this.config.onError(i);return}case"complete":if(o.id===this.subscriptionId)this.config.onComplete();return}}),this.socket.addEventListener("error",(n)=>{let o=fE(n);if(!r){r=!0,t(o);return}this.config.onError(o)}),this.socket.addEventListener("close",(n)=>{let o=IQ(n);if(!r)r=!0,t(Error(`GraphQL subscription socket closed unexpectedly: code=${o??"unknown"}`));this.config.onClose()})})}disconnect(){this.socket?.close(),this.socket=null}subscribe(){this.subscriptionId=bQ(),this.send({id:this.subscriptionId,type:"subscribe",payload:{query:dve}})}send(e){if(this.socket?.readyState===wQ)this.socket.send(JSON.stringify(e))}}class CQ{config;socket=null;subscriptionId=null;constructor(e){this.config=e}connect(){return new Promise((e,t)=>{if(typeof WebSocket>"u"){t(Error("WebSocket is not available in this runtime."));return}let r={host:this.config.appSyncEventsHttpHost,authorization:this.config.accessToken},n=fve(r);this.socket=new WebSocket(this.config.realtimeUrl,["aws-appsync-event-ws",n]);let o=!1;this.socket.addEventListener("open",()=>{this.send({type:"connection_init"})}),this.socket.addEventListener("message",(i)=>{let s=JSON.parse(AQ(i.data));switch(s.type){case"connection_ack":this.subscribe();return;case"connection_error":{let a=s.errors[0],c=Error(a?`${a.errorType} (${a.errorCode}): ${a.message??"No message"}`:"AppSync connection failed");if(!o){o=!0,t(c);return}this.config.onError(c);return}case"subscribe_success":if(!o)o=!0,e();return;case"subscribe_error":{let a=s.errors[0],c=Error(a?`${a.errorType}: ${a.message}`:"AppSync subscription failed");if(!o){o=!0,t(c);return}this.config.onError(c);return}case"data":{let a=JSON.parse(s.event);for(let c of a.documents??[]){let l=RQ(c);if(l)this.config.onExecution(l)}return}case"ka":return;case"error":{let a=Error(s.errors[0]?.message??"AppSync stream failed");if(!o){o=!0,t(a);return}this.config.onError(a);return}}}),this.socket.addEventListener("error",(i)=>{let s=fE(i);if(!o){o=!0,t(s);return}this.config.onError(s)}),this.socket.addEventListener("close",(i)=>{let s=IQ(i);if(!o)o=!0,t(Error(`AppSync socket closed unexpectedly: code=${s??"unknown"}`));this.config.onClose()})})}disconnect(){this.socket?.close(),this.socket=null}subscribe(){this.subscriptionId=bQ(),this.send({type:"subscribe",id:this.subscriptionId,channel:`/rxdb/collection/execution/user/${this.config.recipientId}`,authorization:{host:this.config.appSyncEventsHttpHost,authorization:this.config.accessToken}})}send(e){if(this.socket?.readyState===wQ)this.socket.send(JSON.stringify(e))}}var mve=async(e)=>{let t=new dF,r=!1,n=new PQ({wsEndpoint:e.wsEndpoint,accessToken:e.accessToken,onExecution:(o)=>{t.push(o)},onError:(o)=>{if(r)return;t.fail(o)},onClose:()=>{if(r)return;t.fail(Error("GraphQL execution subscription disconnected"))},onComplete:()=>{if(r)return;t.finish()}});return await n.connect(),{[Symbol.asyncIterator]:()=>t[Symbol.asyncIterator](),close:async()=>{if(r)return;r=!0,n.disconnect(),t.finish()}}},yve=async(e,t)=>{let r=()=>Error("CLI access token has invalid provider-user session claims. Run 'pfcli auth login'."),n=e.accessToken.split(".");if(n.length!==3||!n[0]||!n[1]||!n[2])throw r();let o;try{o=JSON.parse(Buffer.from(n[1],"base64url").toString("utf8"))}catch{throw r()}let i=Im.decodeUnknownOption(Im.Struct({mode:Im.Literal("access"),type:Im.Literal("providerUser"),properties:lF,exp:Im.Number.pipe(Im.int(),Im.positive())}))(o);if(sve.isNone(i))throw r();if(t>=i.value.exp*1000)throw Error("CLI access token has expired. Run 'pfcli auth login'.");let s=await aF(i.value.properties,i.value.exp);if(!s)throw r();let a=new dF,c=!1,l=new CQ({realtimeUrl:e.realtimeUrl,appSyncEventsHttpHost:e.appSyncEventsHttpHost,accessToken:e.accessToken,recipientId:s,onExecution:(d)=>{a.push(d)},onError:(d)=>{if(c)return;a.fail(d)},onClose:()=>{if(c)return;a.fail(Error("AppSync execution subscription disconnected"))}});return await l.connect(),{[Symbol.asyncIterator]:()=>a[Symbol.asyncIterator](),close:async()=>{if(c)return;c=!0,l.disconnect(),a.finish()}}},$s=(e)=>EQ.flatMap(ive.currentTimeMillis,(t)=>EQ.tryPromise({try:()=>e.kind==="GRAPHQL_WS"?mve(e):yve(e,t),catch:(r)=>new ce({message:`Failed to subscribe to execution updates: ${fE(r).message}`,cause:r})}));var Ra=({credentials:e,subscriptionTransport:t,missingUserIdMessage:r,createExecutionEventSourceImpl:n=$s})=>t.kind==="APPSYNC_EVENTS"?yR.gen(function*(){let o=t.appSyncEventsHttpHost;if(!o)return yield*new ce({message:"GraphQL reported AppSync Events subscriptions but did not provide an AppSync host."});let i=mR(e.accessToken);if(!i)return yield*new ce({message:r});let s=e.baseUrl.replace(/^https?:\/\//,"");return yield*n({kind:"APPSYNC_EVENTS",realtimeUrl:`wss://${s}/event/realtime`,appSyncEventsHttpHost:o,accessToken:e.accessToken,userId:i})}):n({kind:"GRAPHQL_WS",wsEndpoint:y4(e.baseUrl),accessToken:e.accessToken}),Pa=(e,t)=>yR.tryPromise({try:()=>e.close(),catch:(r)=>new ce({message:t,cause:r})}).pipe(yR.catchAll(()=>yR.void));import{Effect as hve}from"effect";var gve=new Set(["Completed","Failed","Abandoned"]),Sve=new Set(["Waiting","Completed","Failed"]),vve=(e,t,r,n)=>{let o=Math.round(e/60000),i=o===1?"minute":"minutes",s=n?` for ${t} ${r}`:"";return`Timeout: No ${t} update received in the last ${o} ${i}${s}`},xve=(e,t)=>{let r=[];if(!e||e.status!==t.status)r.push(e?`Status: ${e.status} -> ${t.status}`:`Status: ${t.status}`);let n=new Map(e?.steps.map((o)=>[o.path,o.status])??[]);for(let o of t.steps){if(!Sve.has(o.status))continue;let i=n.get(o.path);if(!e){if(o.status==="Waiting"||o.status==="Failed")r.push(`Step ${o.name}: ${o.status}`);continue}if(i!==o.status)r.push(`Step ${o.name}: ${o.status}`)}return r},Eve=async(e,t,r)=>await new Promise((n,o)=>{let i=setTimeout(()=>{o(Error(r))},t);e.next().then((s)=>{clearTimeout(i),n(s)}).catch((s)=>{clearTimeout(i),o(s)})}),ac=(e,t,r)=>hve.tryPromise({try:async()=>{let n,o=Date.now(),i=r.hasPendingInitialLine,s=e[Symbol.asyncIterator](),a=vve(r.timeoutMs,r.executionLabel,t,r.includeExecutionIdInTimeout??!1),c=setInterval(()=>{process.stdout.write("."),i=!0},r.heartbeatMs);try{while(!0){let l=await Eve(s,r.timeoutMs,a);if(l.done)throw Error(`Execution update stream ended before ${r.executionLabel} finished: ${t}`);let d=l.value,u=Date.now();if(d.id!==t){if(u-o>r.timeoutMs)throw Error(a);continue}o=u;let p=xve(n,d);if(p.length>0){if(i)process.stdout.write(`
|
|
315
|
+
`),i=!1;for(let g=0;g<p.length-1;g++){let E=p[g];if(E)console.log(r.formatLogMessage(E,u))}let y=p[p.length-1];if(y)process.stdout.write(r.formatLogMessage(y,u)),i=!0}if(gve.has(d.status)){if(i)process.stdout.write(`
|
|
316
|
+
`);return d}n=d}}finally{clearInterval(c)}},catch:(n)=>new ce({message:`Failed while waiting for ${r.executionLabel} completion: ${n instanceof Error?n.message:String(n)}`,cause:n})}),cc=(e)=>e.steps.find((r)=>r.status==="Failed")?.failureReason??e.failureReason??e.abandonedReason??void 0;var qs=(e,t={})=>JSON.stringify({message:e,...t});var lc=`
|
|
317
|
+
query SubscriptionTransport {
|
|
318
|
+
subscriptionTransport {
|
|
319
|
+
kind
|
|
320
|
+
appSyncEventsHttpHost
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
`;var bve=`
|
|
324
|
+
mutation StartRollbackDb($projectId: String!, $environmentId: String!, $timestamp: String!) {
|
|
325
|
+
startOperationsRollbackDb(input: { projectId: $projectId, environmentId: $environmentId, timestamp: $timestamp }) {
|
|
326
|
+
executionId
|
|
327
|
+
processPath
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
`,wve=900000,Tve=1e4,Ave=(e=Date.now())=>{let t=new Date(e);return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}`},uF=(e,t=Date.now())=>`[${Ave(t)}] ${e}`,kQ=(e,t,r,n={},o={})=>{let i=o.createExecutionEventSource??$s,s=n.waitForCompletion??!0;return mE.gen(function*(){yield*ai(e,t);let a=yield*ds(),c=oi(a.baseUrl),l=()=>mE.gen(function*(){let y=yield*Hr(c,a.accessToken,bve,{projectId:e,environmentId:t,timestamp:r});return yield*_Q.log(qs("Rollback started",{executionId:y.startOperationsRollbackDb.executionId})),y.startOperationsRollbackDb});if(!s){yield*l();return}let d=yield*Hr(c,a.accessToken,lc,{}),u=yield*Ra({credentials:a,subscriptionTransport:d.subscriptionTransport,missingUserIdMessage:"CLI access token is missing userId/sub claims required for rollback subscriptions.",createExecutionEventSourceImpl:i}),p=Pa(u,"Failed to close rollback execution subscription.");return yield*mE.gen(function*(){let y=yield*l(),g=Date.now();yield*mE.sync(()=>process.stdout.write(uF("Waiting for rollback completion...",g)));let E=yield*ac(u,y.executionId,{executionLabel:"rollback",timeoutMs:wve,heartbeatMs:Tve,hasPendingInitialLine:!0,formatLogMessage:uF});if(E.status==="Completed"){yield*_Q.log(uF("Rollback completed."));return}return yield*new ce({message:cc(E)??`Rollback ${E.status.toLowerCase()}.`})}).pipe(mE.ensuring(p))})};import{accessSync as Ive,constants as Rve,statSync as Pve}from"fs";import{delimiter as Cve,join as _ve}from"path";import{httpsUrlFromTursoLibsqlUrl as kve}from"@processfocus/hosting-contract";import{Console as Dve,Effect as Rm}from"effect";var Ove=`
|
|
331
|
+
mutation CreateDatabaseShellSession($projectId: String!, $environmentId: String!, $ttlSeconds: Int) {
|
|
332
|
+
createDatabaseShellSession(projectId: $projectId, environmentId: $environmentId, ttlSeconds: $ttlSeconds) {
|
|
333
|
+
databaseUrl
|
|
334
|
+
authToken
|
|
335
|
+
expiresAt
|
|
336
|
+
databaseName
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
`,Nve=3600,Fve={s:1,sec:1,secs:1,second:1,seconds:1,m:60,min:60,mins:60,minute:60,minutes:60,h:3600,hr:3600,hrs:3600,hour:3600,hours:3600},Uve=(e)=>{try{if(!Pve(e).isFile())return!1;return Ive(e,Rve.X_OK),!0}catch{return!1}},Mve=(e,t)=>{if(process.platform!=="win32")return[e];let r=(t.PATHEXT??".EXE;.CMD;.BAT;.COM").split(";").filter((n)=>n.length>0);return[e,...r.map((n)=>`${e}${n}`)]},Lve=(e,t=process.env)=>{let r=t.PATH;if(!r)return;for(let n of r.split(Cve)){if(!n)continue;for(let o of Mve(e,t)){let i=_ve(n,o);if(Uve(i))return i}}return},Bve=(e)=>Rm.gen(function*(){if(e===void 0)return;let t=e.trim().toLowerCase(),r=/^(\d+)\s*([a-z]+)?$/.exec(t);if(!r)return yield*new ce({message:'Invalid Database Shell TTL. Use seconds or a duration like "900s", "15m", or "1h".'});let[,n,o="seconds"]=r,i=Fve[o];if(i===void 0)return yield*new ce({message:'Invalid Database Shell TTL unit. Use seconds, minutes, or hours, for example "900s", "15m", or "1h".'});let s=Number(n)*i;if(!Number.isSafeInteger(s)||s<=0)return yield*new ce({message:"Database Shell TTL must be a positive whole number of seconds."});if(s>Nve)return yield*new ce({message:"Database Shell TTL must be 1 hour or less."});return s}),$ve=(e)=>{let t=new Date(e);if(Number.isNaN(t.getTime()))return e;return t.toLocaleString()},qve=(e)=>Rm.gen(function*(){let t=e("turso");if(t!==void 0)return t;return yield*new ce({message:'The Turso CLI executable "turso" was not found on PATH. Install it from https://docs.turso.tech/cli/installation and rerun pfcli db shell.'})}),jve=(e,t)=>Rm.try({try:()=>{let r=new URL(kve(e));return r.searchParams.set("authToken",t),`${r.origin}?${r.searchParams.toString()}`},catch:(r)=>new ce({message:"Database Shell session returned an invalid database URL",cause:r})}),Hve=(e)=>Dve.error(["","WARNING: opening a live read-write Database Shell session.",`Project: ${e.projectId}`,`Environment: ${e.environmentId}`,`Database: ${e.databaseName}`,`Session expires: ${$ve(e.expiresAt)}`,"Changes made in this shell affect the active hosted environment database.","The Turso child process receives the session token in its argv; local process listings may expose it until the shell exits.",""].join(`
|
|
340
|
+
`)),Wve=(e,t)=>Bun.spawn([...e],t),DQ=(e,t,r,n={})=>{let o=n.findExecutable??Lve,i=n.spawn??Wve;return Rm.gen(function*(){let s=yield*Bve(r),a=yield*qve(o),c={projectId:e,environmentId:t};if(s!==void 0)c.ttlSeconds=s;let l=yield*Mr(Ove,c).pipe(Rm.map((y)=>y.createDatabaseShellSession));yield*Hve({projectId:e,environmentId:t,databaseName:l.databaseName,expiresAt:l.expiresAt});let d=yield*jve(l.databaseUrl,l.authToken),u={...process.env};delete u.LIBSQL_AUTH_TOKEN,delete u.TURSO_AUTH_TOKEN,delete u.TURSO_API_TOKEN;let p=yield*Rm.try({try:()=>i([a,"db","shell",d],{stdin:"inherit",stdout:"inherit",stderr:"inherit",env:u}),catch:(y)=>new ce({message:"Failed to launch Turso database shell",cause:y})});return yield*Rm.tryPromise({try:()=>p.exited,catch:(y)=>new ce({message:"Turso database shell failed before exiting cleanly",cause:y})})})};import{readFileSync as Vve,statSync as zve}from"fs";import{basename as Kve,resolve as Gve}from"path";import{Console as hR,Effect as Wo}from"effect";var Qve=`
|
|
341
|
+
mutation RequestDatabaseUploadUrl($project: String!, $env: String!, $contentType: String, $filename: String) {
|
|
342
|
+
requestDatabaseUploadUrl(project: $project, env: $env, contentType: $contentType, filename: $filename) {
|
|
343
|
+
operationId
|
|
344
|
+
fileId
|
|
345
|
+
documentStore
|
|
346
|
+
uploadUrl
|
|
347
|
+
expiresAt
|
|
348
|
+
status
|
|
349
|
+
target {
|
|
350
|
+
project
|
|
351
|
+
env
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
`,Jve=`
|
|
356
|
+
mutation StartUploadDb($projectId: String!, $environmentId: String!, $fileId: String!, $mode: String!) {
|
|
357
|
+
startOperationsUploadDb(input: { projectId: $projectId, environmentId: $environmentId, fileId: $fileId, mode: $mode }) {
|
|
358
|
+
executionId
|
|
359
|
+
processPath
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
`,Yve=`
|
|
363
|
+
mutation DeleteDatabaseUploadArtifact($fileId: ID!) {
|
|
364
|
+
deleteFile(fileId: $fileId) {
|
|
365
|
+
success
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
`,UQ="application/vnd.sqlite3",OQ=Buffer.from("SQLite format 3\x00","binary"),Xve=900000,Zve=1e4,exe=(e=Date.now())=>{let t=new Date(e);return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}`},NQ=(e,t=Date.now())=>`[${exe(t)}] ${e}`,txe=(e)=>Wo.gen(function*(){let t=Gve(e),r=yield*Wo.try({try:()=>zve(t),catch:(o)=>new ce({message:`Database upload input not found or unreadable: ${t}`,cause:o})});if(!r.isFile())return yield*new ce({message:`Database upload input must be a regular file: ${t}`});if(r.size===0)return yield*new ce({message:`Database upload input is empty: ${t}`});let n=yield*Wo.try({try:()=>Vve(t),catch:(o)=>new ce({message:`Failed to read database upload input: ${t}`,cause:o})});if(!n.subarray(0,OQ.length).equals(OQ))return yield*new ce({message:`Database upload input does not look like a SQLite database: ${t}`});return{bytes:n,filename:Kve(t)||"database.sqlite",inputPath:t}}),rxe=(e,t,r)=>Wo.gen(function*(){let n=yield*Wo.tryPromise({try:()=>r(e,{method:"PUT",headers:{"Content-Length":String(t.length),"Content-Type":UQ},body:t}),catch:(o)=>new ce({message:"Failed to upload database artifact",cause:o})});if(!n.ok)return yield*new ce({message:`Database artifact upload failed with ${n.status}`})}),FQ=(e,t,r)=>Hr(e,t,Yve,{fileId:r}).pipe(Wo.asVoid,Wo.catchTag("CliError",()=>hR.error(`Warning: database transfer artifact cleanup failed for file ${r}.`))),MQ=(e,t,r,n={})=>{let o=n.fetch??fetch,i=n.mode??"data-copy",s=n.createExecutionEventSource??$s;return Wo.gen(function*(){let a=yield*txe(r),c=yield*ds(),l=oi(c.baseUrl);yield*ai(e,t);let u=(yield*Hr(l,c.accessToken,Qve,{project:e,env:t,contentType:UQ,filename:a.filename})).requestDatabaseUploadUrl;yield*hR.log(qs("Database upload transfer ready",{operationId:u.operationId,fileId:u.fileId,documentStore:u.documentStore,inputPath:a.inputPath,byteSize:a.bytes.length,mode:i,status:u.status})),yield*rxe(u.uploadUrl,a.bytes,o).pipe(Wo.catchAll((y)=>FQ(l,c.accessToken,u.fileId).pipe(Wo.flatMap(()=>Wo.fail(y)))));let p=!1;return yield*Wo.gen(function*(){let y=yield*Hr(l,c.accessToken,lc,{}),g=yield*Ra({credentials:c,subscriptionTransport:y.subscriptionTransport,missingUserIdMessage:"CLI access token is missing userId/sub claims required for upload subscriptions.",createExecutionEventSourceImpl:s}),E=Pa(g,"Failed to close upload execution subscription.");return yield*Wo.gen(function*(){let S=yield*Hr(l,c.accessToken,Jve,{projectId:e,environmentId:t,fileId:u.fileId,mode:i});p=!0;let x=S.startOperationsUploadDb.executionId;yield*hR.log(qs("Database upload started",{executionId:x,operationId:u.operationId,fileId:u.fileId,inputPath:a.inputPath,mode:i}));let w=Date.now();yield*Wo.sync(()=>process.stdout.write(NQ("Waiting for database upload to apply...",w)));let _=yield*ac(g,x,{executionLabel:"database upload",timeoutMs:Xve,heartbeatMs:Zve,hasPendingInitialLine:!0,formatLogMessage:NQ});if(_.status!=="Completed")return yield*new ce({message:cc(_)??`Database upload ${_.status.toLowerCase()}.`});return yield*hR.log(qs("Database upload applied",{executionId:x,operationId:u.operationId,fileId:u.fileId,inputPath:a.inputPath,mode:i,status:"APPLIED"})),{operationId:u.operationId,executionId:x,fileId:u.fileId,mode:i,status:"APPLIED"}}).pipe(Wo.ensuring(E))}).pipe(Wo.catchAll((y)=>{if(p)return Wo.fail(y);return FQ(l,c.accessToken,u.fileId).pipe(Wo.flatMap(()=>Wo.fail(y)))}))})};import{randomUUID as bxe}from"crypto";import{readFileSync as wxe,rmSync as Txe,statSync as yF}from"fs";import{tmpdir as Axe}from"os";import*as yE from"path";import{Console as su,Effect as Ir}from"effect";import{spawnSync as nxe}from"child_process";import{cpSync as pF,existsSync as LQ,mkdtempSync as oxe,rmSync as ixe,writeFileSync as sxe}from"fs";import{tmpdir as axe}from"os";import*as js from"path";import{DEPLOY_ARTIFACT_FILENAME as BQ,DEPLOY_ARTIFACT_FORMAT as cxe,DEPLOY_ARTIFACT_VERSION as lxe}from"@processfocus/runtime";import{Effect as Ig}from"effect";var dxe=(e)=>{let t=js.relative(process.cwd(),js.resolve(e));return t&&!t.startsWith("..")?t:e},fF=(e,t)=>Ig.scoped(Ig.gen(function*(){let r=js.resolve(process.cwd(),e),n=yield*Ig.acquireRelease(Ig.sync(()=>oxe(js.join(axe(),"pfcli-deploy-stage-"))),(p)=>Ig.sync(()=>ixe(p,{recursive:!0,force:!0}))),o=js.join(n,"dist"),i=js.join(n,BQ),s=js.join(r,"drizzle.config.ts"),a=js.join(n,"drizzle.config.ts"),c=js.join(r,"drizzle"),l=js.join(n,"drizzle"),d=JSON.stringify({format:cxe,version:lxe,orgPath:dxe(e),producer:lE}),u=yield*Ig.try({try:()=>{pF(js.join(r,"dist"),o,{recursive:!0});let p=["dist",BQ];if(LQ(s))pF(s,a),p.push("drizzle.config.ts");if(LQ(c))pF(c,l,{recursive:!0}),p.push("drizzle");return sxe(i,`${d}
|
|
369
|
+
`),nxe("zip",["-r","-q",t,...p],{cwd:n,encoding:"utf8"})},catch:(p)=>new ce({message:"Failed to execute zip command",cause:p})});if(u.error)return yield*new ce({message:`Failed to create deployment zip: ${u.error.message}`,cause:u.error});if(u.status!==0)return yield*new ce({message:u.stderr?.trim()||`zip command failed with exit code ${String(u.status)}`})}));import{randomUUID as uxe}from"crypto";import{Effect as pxe}from"effect";var $Q=30000,mF="Lost the deploy progress connection",fxe=["progress","completed","failed"],mxe=new Set(fxe);class qQ{items=[];waiters=[];closed=!1;failure=null;push(e){if(this.closed||this.failure)return;let t=this.waiters.shift();if(t){t.resolve({value:e,done:!1});return}this.items.push(e)}finish(){if(this.closed||this.failure)return;this.closed=!0;while(this.waiters.length>0)this.waiters.shift()?.resolve({value:void 0,done:!0})}fail(e){if(this.closed||this.failure)return;this.failure=e;while(this.waiters.length>0)this.waiters.shift()?.reject(e)}[Symbol.asyncIterator](){return{next:()=>{if(this.failure)return Promise.reject(this.failure);let e=this.items.shift();if(e)return Promise.resolve({value:e,done:!1});if(this.closed)return Promise.resolve({value:void 0,done:!0});return new Promise((t,r)=>{this.waiters.push({resolve:t,reject:r})})}}}}var yxe=(e)=>{if(typeof e==="string")return e;if(Buffer.isBuffer(e))return e.toString("utf8");if(Array.isArray(e))return Buffer.concat(e.filter((t)=>Buffer.isBuffer(t))).toString("utf8");if(e instanceof ArrayBuffer)return Buffer.from(e).toString("utf8");return String(e)},hxe=(e)=>{if(typeof e==="object"&&e!==null){let t="code"in e&&typeof e.code==="number"?e.code:void 0,r="reason"in e&&typeof e.reason==="string"?e.reason:void 0;return{code:t,reason:r}}return{code:void 0,reason:void 0}},gR=(e)=>{if(e instanceof Error)return e;if(Array.isArray(e))return Error(e.map((t)=>String(t)).join(", "));if(typeof e==="object"&&e!==null){if("message"in e&&typeof e.message==="string")return Error(e.message);if("reason"in e&&typeof e.reason==="string")return Error(e.reason);return Error(JSON.stringify(e))}return Error(String(e))},gxe=(e)=>`header-${Buffer.from(JSON.stringify(e)).toString("base64url")}`,Sxe=(e)=>typeof e==="string"&&mxe.has(e),vxe=(e)=>{if(typeof e!=="object"||e===null)return null;let t=e;if(t.version!==1||typeof t.executionId!=="string"||typeof t.phase!=="string"||!Sxe(t.status)||typeof t.message!=="string"||typeof t.timestamp!=="string")return null;return{version:1,executionId:t.executionId,phase:t.phase,status:t.status,message:t.message,timestamp:t.timestamp}};class jQ{config;socket=null;subscriptionId=null;constructor(e){this.config=e}connect(){return new Promise((e,t)=>{if(typeof WebSocket>"u"){t(Error("WebSocket is not available in this runtime."));return}let r={host:this.config.appSyncEventsHttpHost,authorization:this.config.accessToken},n=gxe(r);this.socket=new WebSocket(this.config.realtimeUrl,["aws-appsync-event-ws",n]);let o=!1,i=setTimeout(()=>{let c=Error(`Timed out waiting for AppSync deploy progress connection after ${$Q/1000}s`);if(!o)o=!0,t(c),this.socket?.close()},$Q),s=()=>{if(!o)return o=!0,clearTimeout(i),e(),!0;return!1},a=(c)=>{if(!o)return o=!0,clearTimeout(i),t(c),!0;return!1};this.socket.addEventListener("open",()=>{this.send({type:"connection_init"})}),this.socket.addEventListener("message",(c)=>{let l;try{l=JSON.parse(yxe(c.data))}catch(d){let u=gR(d);if(!o){o=!0,clearTimeout(i),t(u);return}this.config.onError(u);return}switch(l.type){case"connection_ack":this.subscribe();return;case"connection_error":{let d=l.errors[0],u=Error(d?`${d.errorType} (${d.errorCode}): ${d.message??"No message"}`:"AppSync connection failed");if(a(u))return;this.config.onError(u);return}case"subscribe_success":if(s())return;return;case"subscribe_error":{let d=l.errors[0],u=Error(d?`${d.errorType}: ${d.message}`:"AppSync subscription failed");if(a(u))return;this.config.onError(u);return}case"data":{try{let d=vxe(JSON.parse(l.event));if(d)this.config.onEvent(d)}catch(d){this.config.onError(gR(d))}return}case"ka":return;case"error":{let d=Error(l.errors[0]?.message??"AppSync stream failed");if(!o){o=!0,t(d);return}this.config.onError(d);return}}}),this.socket.addEventListener("error",(c)=>{let l=gR(c);if(a(l))return;this.config.onError(l)}),this.socket.addEventListener("close",(c)=>{let{code:l,reason:d}=hxe(c);if(a(Error(`AppSync socket closed unexpectedly: code=${l??"unknown"}${d?` reason=${d}`:""}`)))return;this.config.onClose(l,d)})})}disconnect(){this.socket?.close(),this.socket=null}subscribe(){this.subscriptionId=uxe(),this.send({type:"subscribe",id:this.subscriptionId,channel:this.config.channel,authorization:{host:this.config.appSyncEventsHttpHost,authorization:this.config.accessToken}})}send(e){if(this.socket?.readyState===WebSocket.OPEN)this.socket.send(JSON.stringify(e))}}var xxe=async(e)=>{let t=new qQ,r=!1,n=new jQ({realtimeUrl:e.realtimeUrl,appSyncEventsHttpHost:e.appSyncEventsHttpHost,accessToken:e.accessToken,channel:e.channel,onEvent:(o)=>{t.push(o)},onError:(o)=>{if(r)return;t.fail(o)},onClose:(o,i)=>{if(r)return;let s=o!==void 0?` (close code ${o}${i?`: ${i}`:""})`:"";process.stderr.write(`
|
|
370
|
+
Deploy progress WebSocket closed${s}
|
|
371
|
+
`),t.fail(Error(`${mF}${s}. The deployment may still be running; check the Backend or deployment logs.`))}});return await n.connect(),{[Symbol.asyncIterator]:()=>t[Symbol.asyncIterator](),close:async()=>{if(r)return;r=!0,n.disconnect(),t.finish()}}},HQ=(e)=>pxe.tryPromise({try:()=>xxe(e),catch:(t)=>new ce({message:`Failed to subscribe to deployment progress: ${gR(t).message}`,cause:t})});var Exe=(e=Date.now())=>{let t=new Date(e);return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}`},Ai=(e,t=Date.now())=>`[${Exe(t)}] ${e}`;var Ixe=`
|
|
372
|
+
mutation RequestUploadUrl($stepPath: String!, $documentStore: String!, $contentType: String, $filename: String) {
|
|
373
|
+
requestUploadUrl(stepPath: $stepPath, documentStore: $documentStore, contentType: $contentType, filename: $filename) {
|
|
374
|
+
fileId
|
|
375
|
+
uploadUrl
|
|
376
|
+
expiresAt
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
`,Rxe=`
|
|
380
|
+
mutation StartDeploy($projectId: String!, $environmentId: String!, $fileId: String!) {
|
|
381
|
+
startOperationsDeploy(input: { projectId: $projectId, environmentId: $environmentId, fileId: $fileId }) {
|
|
382
|
+
executionId
|
|
383
|
+
processPath
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
`,Pxe=`
|
|
387
|
+
query DeployFrontendUrl($projectId: String!, $environmentId: String!) {
|
|
388
|
+
getDnsRecords(projectId: $projectId, environmentId: $environmentId) {
|
|
389
|
+
customDomain
|
|
390
|
+
frontendUrl
|
|
391
|
+
frontendUrlNote
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
`,Cxe="https://backend.processfocus.com",_xe="https://console.processfocus.com",kxe=(e)=>{let t=e.replace(/\/+$/,"");if(t===Cxe||t===_xe)return"Uploading artifact...";return`Uploading artifact to ${t}...`},SR=900000,WQ=1e4,Dxe=(e,t)=>`/cloud/deploy/${e}/${t}`,VQ="Deployment progress stream ended before deployment finished",zQ=(e,t)=>{let r=Math.round(e/60000),n=r===1?"minute":"minutes",o=t?` for deployment ${t}`:"";return`Timeout: No deployment update received in the last ${r} ${n}${o}`},Oxe=(e)=>{let t=e.message,r=e.cause instanceof Error?e.cause.message:String(e.cause??""),n=`${t}
|
|
395
|
+
${r}`;return n.includes(mF)||n.includes(VQ)},Nxe=async(e,t)=>await new Promise((r,n)=>{let o=setTimeout(()=>{n(Error(zQ(t)))},t);e.next().then((i)=>{clearTimeout(o),r(i)}).catch((i)=>{clearTimeout(o),n(i)})}),Fxe=(e,t,r)=>Ir.tryPromise({try:async()=>{let n=Date.now(),o=r,i,s=e[Symbol.asyncIterator](),a=setInterval(()=>{process.stdout.write("."),o=!0},WQ);try{while(!0){let c=await Nxe(s,SR);if(c.done)throw Error(`${VQ}: ${t}. The deployment may still be running; check the Backend or deployment logs.`);let l=c.value,d=Date.now();if(l.executionId!==t){if(d-n>SR)throw Error(zQ(SR,t));continue}if(n=d,l.status==="progress"){let u=`${l.phase}:${l.message}`;if(u!==i){if(o)process.stdout.write(`
|
|
396
|
+
`),o=!1;process.stdout.write(Ai(l.message,d)),o=!0,i=u}}if(l.status==="completed"||l.status==="failed"){if(o)process.stdout.write(`
|
|
397
|
+
`);return l}}}finally{clearInterval(a)}},catch:(n)=>new ce({message:`Failed while waiting for deployment progress: ${n instanceof Error?n.message:String(n)}`,cause:n})}),KQ=(e,t,r,n={},o={})=>{let i=yE.join(Axe(),`pfcli-deploy-${bxe()}.zip`),s=o.createExecutionEventSource??$s,a=o.createDeployProgressEventSource??HQ,c=o.buildOrg??((u)=>Tg(u)),l=o.prepareArtifact??fF,d=n.waitForCompletion??!0;return Ir.gen(function*(){yield*ai(t,r);let u=yield*ds(),p=gQ(u.accessToken);if(!(typeof p==="string"?p===fR:Array.isArray(p)?p.includes(fR):!0)){let ee=typeof p==="string"?p:Array.isArray(p)?p.join(","):"unknown";return yield*new ce({message:`CLI token audience is ${ee}, expected ${fR}. Run "pfcli auth login" after restarting local auth/runtime services.`})}let g=yE.resolve(process.cwd(),e);yield*Ir.try({try:()=>yF(g).isDirectory(),catch:()=>new ce({message:`Org directory not found at ${g}.`})}),yield*c(e).pipe(Ir.mapError((ee)=>new ce({message:`Failed to build organisation before deploy: ${ee instanceof Error?ee.message:String(ee)}`,cause:ee})));let E=yE.join(g,"dist");yield*Ir.try({try:()=>yF(E).isDirectory(),catch:()=>new ce({message:`Build completed but dist directory not found at ${E}. This may indicate a build configuration issue.`})});let S=oi(u.baseUrl);yield*su.log(`Creating artifact from ${E}`),yield*l(g,i),yield*Ir.try({try:()=>yF(i),catch:(ee)=>new ce({message:`Failed to create artifact zip at ${i}`,cause:ee})});let x=yield*Hr(S,u.accessToken,Ixe,{stepPath:"/operations/deploy/Upload artifact",documentStore:"/org-upload",contentType:"application/zip",filename:"org-dist.zip"});yield*su.log(kxe(u.baseUrl));let w=yield*Ir.try({try:()=>wxe(i),catch:(ee)=>new ce({message:"Failed to read artifact zip",cause:ee})}),_=yield*Ir.tryPromise({try:()=>fetch(x.requestUploadUrl.uploadUrl,{method:"PUT",headers:{"Content-Type":"application/zip"},body:w}),catch:(ee)=>new ce({message:"Failed to upload deployment artifact",cause:ee})});if(!_.ok){let ee=yield*Ir.tryPromise({try:async()=>{try{return await _.text()}catch{return""}},catch:(ae)=>new ce({message:"Failed to read upload error response body",cause:ae})});return yield*new ce({message:`Artifact upload failed with ${_.status}: ${ee}`})}let T=()=>Ir.gen(function*(){let ee=yield*Hr(S,u.accessToken,Rxe,{projectId:t,environmentId:r,fileId:x.requestUploadUrl.fileId});return yield*su.log(qs("Deployment started",{executionId:ee.startOperationsDeploy.executionId})),ee.startOperationsDeploy}),b=()=>Hr(S,u.accessToken,Pxe,{projectId:t,environmentId:r}).pipe(Ir.flatMap(({getDnsRecords:ee})=>Ir.gen(function*(){if(yield*su.log(`Frontend URL: ${ee.frontendUrl}`),ee.customDomain&&ee.frontendUrl!==`https://${ee.customDomain}`)yield*su.log(`Configured custom domain: https://${ee.customDomain}`);if(ee.frontendUrlNote)yield*su.log(`Note: ${ee.frontendUrlNote}`)})),Ir.catchAll(()=>Ir.void)),I=(ee,ae)=>Ir.gen(function*(){let ne=Date.now();yield*Ir.sync(()=>process.stdout.write(Ai("Waiting for deployment to start...",ne)));let le=yield*ac(ee,ae,{executionLabel:"deployment",timeoutMs:SR,heartbeatMs:WQ,hasPendingInitialLine:!0,formatLogMessage:Ai,includeExecutionIdInTimeout:!0});if(le.status==="Completed"){yield*su.log(Ai("Deployment completed.")),yield*b();return}return yield*new ce({message:cc(le)??`Deployment ${le.status.toLowerCase()}.`})}),O=(ee)=>Ir.gen(function*(){let ae=u.baseUrl.replace(/^https?:\/\//,""),ne=yield*a({realtimeUrl:`wss://${ae}/event/realtime`,appSyncEventsHttpHost:ee.appSyncEventsHttpHost,accessToken:u.accessToken,channel:Dxe(ee.userId,ee.executionId)}),le=Ir.tryPromise({try:()=>ne.close(),catch:(ie)=>new ce({message:"Failed to close deployment progress subscription.",cause:ie})}).pipe(Ir.catchAll(()=>Ir.void));return yield*Ir.gen(function*(){let ie=Date.now();yield*Ir.sync(()=>process.stdout.write(Ai("Waiting for deployment updates...",ie)));let je=yield*Fxe(ne,ee.executionId,!0);if(je.status==="completed"){yield*su.log(Ai("Deployment completed.")),yield*b();return}return yield*new ce({message:je.message??"Deployment failed."})}).pipe(Ir.ensuring(le))});if(!d){yield*T();return}let L=yield*Hr(S,u.accessToken,lc,{});if(L.subscriptionTransport.kind==="APPSYNC_EVENTS"){let ee=L.subscriptionTransport.appSyncEventsHttpHost;if(!ee)return yield*new ce({message:"GraphQL reported AppSync Events subscriptions but did not provide an AppSync host."});let ae=mR(u.accessToken);if(!ae)return yield*new ce({message:"CLI access token is missing userId/sub claims required for deploy progress subscriptions."});let ne=yield*T();return yield*O({executionId:ne.executionId,userId:ae,appSyncEventsHttpHost:ee}).pipe(Ir.catchAll((le)=>{if(!Oxe(le))return Ir.fail(le);return Ir.gen(function*(){yield*su.log(Ai("Deploy progress connection closed; waiting for deployment result..."));let ie=yield*Ra({credentials:u,subscriptionTransport:L.subscriptionTransport,missingUserIdMessage:"CLI access token is missing userId/sub claims required for execution subscriptions.",createExecutionEventSourceImpl:s}),je=Pa(ie,"Failed to close execution subscription.");return yield*I(ie,ne.executionId).pipe(Ir.ensuring(je))})}))}let Y=yield*Ra({credentials:u,subscriptionTransport:L.subscriptionTransport,missingUserIdMessage:"CLI access token is missing userId/sub claims required for execution subscriptions.",createExecutionEventSourceImpl:s}),Z=Pa(Y,"Failed to close execution subscription.");return yield*Ir.gen(function*(){let ee=yield*T();yield*I(Y,ee.executionId)}).pipe(Ir.ensuring(Z))}).pipe(Ir.ensuring(Ir.sync(()=>Txe(i,{force:!0}))))};import{Console as GQ,Effect as hE}from"effect";var Uxe=`
|
|
398
|
+
mutation StartDestroyEnvironment($projectId: String!, $environmentId: String!) {
|
|
399
|
+
startOperationsDestroyEnvironment(input: { projectId: $projectId, environmentId: $environmentId }) {
|
|
400
|
+
executionId
|
|
401
|
+
processPath
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
`,Mxe=2700000,Lxe=1e4,QQ=(e,t,r={},n={})=>{let o=n.createExecutionEventSource??$s,i=r.waitForCompletion??!0;return hE.gen(function*(){yield*ai(e,t);let s=yield*ds(),a=oi(s.baseUrl),c=()=>hE.gen(function*(){let p=yield*Hr(a,s.accessToken,Uxe,{projectId:e,environmentId:t});return yield*GQ.log(qs("Destroy started",{executionId:p.startOperationsDestroyEnvironment.executionId})),p.startOperationsDestroyEnvironment});if(!i){yield*c();return}let l=yield*Hr(a,s.accessToken,lc,{}),d=yield*Ra({credentials:s,subscriptionTransport:l.subscriptionTransport,missingUserIdMessage:"CLI access token is missing userId/sub claims required for destroy subscriptions.",createExecutionEventSourceImpl:o}),u=Pa(d,"Failed to close destroy execution subscription.");return yield*hE.gen(function*(){let p=yield*c(),y=Date.now();yield*hE.sync(()=>process.stdout.write(Ai("Waiting for environment destruction to complete...",y)));let g=yield*ac(d,p.executionId,{executionLabel:"environment destruction",timeoutMs:Mxe,heartbeatMs:Lxe,hasPendingInitialLine:!0,formatLogMessage:Ai,includeExecutionIdInTimeout:!0});if(g.status==="Completed"){yield*GQ.log(`Environment destroyed: ${t}`);return}return yield*new ce({message:cc(g)??`Environment destruction ${g.status.toLowerCase()}.`})}).pipe(hE.ensuring(u))})};import{Console as JQ,Effect as vR}from"effect";var Bxe=`
|
|
405
|
+
mutation StartAddEnvironment($projectId: String!, $stageId: String!, $environmentName: String!) {
|
|
406
|
+
startOperationsAddEnvironment(input: { projectId: $projectId, stageId: $stageId, environmentName: $environmentName }) {
|
|
407
|
+
executionId
|
|
408
|
+
processPath
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
`,$xe=900000,qxe=1e4,YQ=(e,t,r,n={})=>{let o=n.createExecutionEventSource??$s;return vR.gen(function*(){yield*Bs(e,[t]);let i=yield*ds(),s=oi(i.baseUrl),a=yield*Hr(s,i.accessToken,lc,{}),c=yield*Ra({credentials:i,subscriptionTransport:a.subscriptionTransport,missingUserIdMessage:"CLI access token is missing userId/sub claims required for env add subscriptions.",createExecutionEventSourceImpl:o}),l=Pa(c,"Failed to close env add execution subscription.");return yield*vR.gen(function*(){let d=yield*Hr(s,i.accessToken,Bxe,{projectId:e,stageId:t,environmentName:r});yield*JQ.log(qs("Environment add started",{executionId:d.startOperationsAddEnvironment.executionId}));let u=Date.now();yield*vR.sync(()=>process.stdout.write(Ai("Waiting for environment creation to complete...",u)));let p=yield*ac(c,d.startOperationsAddEnvironment.executionId,{executionLabel:"environment creation",timeoutMs:$xe,heartbeatMs:qxe,hasPendingInitialLine:!0,formatLogMessage:Ai,includeExecutionIdInTimeout:!0});if(p.status==="Completed"){yield*JQ.log(`Environment created: ${r}`);return}return yield*new ce({message:cc(p)??`Environment creation ${p.status.toLowerCase()}.`})}).pipe(vR.ensuring(l))})};import{Console as XQ,Effect as jxe}from"effect";var Hxe=`
|
|
412
|
+
query ListProjectEnvironments($projectId: String!, $stageId: String) {
|
|
413
|
+
listProjectEnvironments(projectId: $projectId, stageId: $stageId) {
|
|
414
|
+
items {
|
|
415
|
+
environmentName
|
|
416
|
+
stageName
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
`,ZQ=(e,t)=>jxe.gen(function*(){if(t)yield*Bs(e,[t]);let r=yield*Mr(Hxe,{projectId:e,stageId:t}),{items:n}=r.listProjectEnvironments;if(n.length===0){let o=t?` stage ${t}`:"";yield*XQ.log(`No environments found for project ${e}${o}.`);return}for(let o of n)yield*XQ.log(t?o.environmentName:`${o.environmentName} (${o.stageName})`)});import{Console as Jte,Data as c0e,Effect as V$}from"effect";import{Context as Wxe,Data as e5,Effect as t5}from"effect";class r5 extends e5.TaggedError("processfocus:internal-tag/auth-api/DatabaseQueryError"){}class n5 extends e5.TaggedError("processfocus:internal-tag/auth-api/DatabaseWriteError"){}var Cr=(e)=>(t)=>t.pipe(t5.mapError((r)=>new r5({message:e,cause:r}))),cn=(e)=>(t)=>t.pipe(t5.mapError((r)=>new n5({message:e,cause:r})));class Vo extends Wxe.Tag("processfocus:internal-tag/auth-api/AuthenticationDatabase")(){}Pg();import{Data as Fy,DateTime as L_t,Effect as Ny,Layer as B_t,Option as $_t,Runtime as q_t,Schema as Bt}from"effect";var Dp=new TextEncoder,Cg=new TextDecoder,OR=new TextDecoder("utf-8",{fatal:!0});function gs(...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 kF(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 DF(e){let t=Math.floor(e/4294967296),r=e%4294967296,n=new Uint8Array(8);return kF(n,t,0),kF(n,r,4),n}function NR(e){let t=new Uint8Array(4);return kF(t,e),t}var oEe=/[^\x00-\x7f]/;function Ss(e){if(typeof e=="string"&&e.length>=128){if(oEe.test(e))throw TypeError("non-ASCII string encountered in encode()");return Dp.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 FR(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 UR(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 j5(e,t){let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,t))}class zl 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 Op extends zl{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 MR extends zl{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 _g extends zl{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class Xr extends zl{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class LR extends zl{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",t){super(e,t)}}class ze extends zl{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"}class bn extends zl{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class Pm extends zl{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class OF extends zl{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}var iEe="The input to be decoded is not correctly encoded.";function EE(e){try{return UR(typeof e=="string"?e:Cg.decode(e),!0)}catch(t){throw TypeError(iEe,{cause:t})}}function uo(e){return FR(typeof e=="string"?Dp.encode(e):e,!0)}function cu(e,t){if(!(e instanceof Uint8Array))throw TypeError(`${t} must be an instance of Uint8Array`)}function _a(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 Np(...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 Cm(e,t){if(e!==void 0)throw TypeError(`${t} can only be called once`)}function Ws(e,t,r){try{return EE(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}function BR(e,t,r){try{return Ss(e)}catch{throw new r(`The ${t} is not a valid base64url string`)}}function $R(e,t,r){let n;try{n=JSON.parse(OR.decode(EE(e)))}catch{throw new t(r)}if(!_a(n))throw new t(r);return n}var qR={__proto__:null,b64:!0},jR={__proto__:null};function bE(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 HR(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 Fp(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 Xr(`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 WR(e,t){if(t.includes("b64")){let r=e.b64;if(typeof r!="boolean")throw new bn('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function _m(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(!_a(n))throw new e("JOSE Header is not a JSON object");return[n,r]}var sEe=(e)=>e[Symbol.toStringTag],aEe=(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 tl(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(_a(t)){if(s=uEe(t),typeof s.kty!="string")throw W5(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(aEe(e,s,r),s.kty==="oct")return EE(s.k);if(!Object.isFrozen(t)){let{key_ops:d}=t;Array.isArray(d)&&Object.freeze(d),Object.freeze(t)}}else{if(!lEe(t))throw W5(n,t,o);let d=o?"secret":i?"private":"public";if(t.type!==d&&(o||["secret","public","private"].includes(t.type)))throw TypeError(`${sEe(t)} instances must be of type "${d}" for the ${n} algorithm`);if(Kl(t))return t;if(a=t,a.type==="secret")return a.export()}NF||=new WeakMap;let c=t,l=NF.get(c);if(l?.[n])return l[n];if(l||NF.set(c,l={}),a&&typeof a.toCryptoKey=="function"){let d=a.type==="public",u=cEe[a.asymmetricKeyDetails?.namedCurve],p=e.resolve?.({crv:u,asymmetricKeyType:a.asymmetricKeyType})??e.subtle;return l[n]=a.toCryptoKey(p,d,e.usages[d?0:1])}return s??=a.export({format:"jwk"}),s.alg=n,l[n]=await MF(e,s)}var NF,cEe={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function zR(e){if(!Kl(e))throw Error("CryptoKey instance expected")}var Kl=(e)=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},wE=(e)=>e?.[Symbol.toStringTag]==="KeyObject",lEe=(e)=>Kl(e)||wE(e);function V5(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 Up=(e,...t)=>V5("Key must be ",e,...t);function W5(e,t,r){let n=["CryptoKey","KeyObject","JSON Web Key"];return r&&n.push("Uint8Array"),TypeError(V5(`Key for the ${e} algorithm must be `,t,...n))}var VR=(e,t="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function FF(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function kg(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 UF(e,t,r){let n=e.algorithm;if(n.name!==t.name)throw VR(t.name);if(t.hash&&n.hash?.name!==t.hash)throw VR(t.hash,"algorithm.hash");if(t.namedCurve&&n.namedCurve!==t.namedCurve)throw VR(t.namedCurve,"algorithm.namedCurve");if(t.length!==void 0&&n.length!==t.length)throw VR(t.length,"algorithm.length");FF(e,r)}function dEe(e){return{__proto__:null,...e}}function uEe(e){let t=dEe(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 KR(e){if(e!==void 0&&typeof e!="boolean")throw TypeError('"extractable" option must be a boolean');return e}async function MF(e,t,r){if(!e.kty.includes(t.kty))throw new Xr('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 rl(e,t,r,n=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey("raw",e,t,n,[r])),UF(e,t,r),e}var TE=(e)=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function GR(e,t){let r=e.byteLength<<3;if(r!==t)throw new ze(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)}var pEe=(e)=>crypto.getRandomValues(new Uint8Array(e.ivBits>>3));function z5(e,t){if(t.length<<3!==e.ivBits)throw new ze("Invalid Initialization Vector length")}async function K5(e,t,r){if(!(t instanceof Uint8Array))throw TypeError(Up(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 G5(e,t,r){return new Uint8Array((await crypto.subtle.sign("HMAC",e,t)).slice(0,r>>3))}async function fEe(e,t,r,n,o){let[i,s,a]=await K5(e,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:n,name:"AES-CBC"},i,t)),l=gs(o,n,c,DF(o.length*8)),d=await G5(s,l,a);return{ciphertext:c,tag:d,iv:n}}async function mEe(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 yEe(e,t,r,n,o,i){let[s,a,c]=await K5(e,t,"decrypt"),l=gs(i,n,r,DF(i.length*8)),d=await G5(a,l,c);try{if(await mEe(o,d))return new Uint8Array(await crypto.subtle.decrypt({iv:n,name:"AES-CBC"},s,r))}catch{}throw new LR}async function QR(e,t,r,n,o){if(!Kl(r)&&!(r instanceof Uint8Array))throw TypeError(Up(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(n?z5(e,n):n=pEe(e),r instanceof Uint8Array&&GR(r,e.cekBits),e.cbc)return fEe(e,t,r,n,o);let i=await rl(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 JR(e,t,r,n,o,i){if(!Kl(t)&&!(t instanceof Uint8Array))throw TypeError(Up(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!n)throw new ze("JWE Initialization Vector missing");if(!o)throw new ze("JWE Authentication Tag missing");if(!e.cbc&&o.length!==16)throw new ze("Invalid Authentication Tag length");if(z5(e,n),t instanceof Uint8Array&&GR(t,e.cekBits),e.cbc)return yEe(e,t,r,n,o,i);let s=await rl(t,e.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},s,gs(r,o)))}catch{throw new LR}}function AE(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}var hEe=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],gEe=[[],["deriveBits"]],ZR=[[],[]];function YR(e){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${e}`},usages:hEe,ops:["wrapKey","unwrapKey"]}}function XR(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 Xr('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:gEe,ops:[void 0,"deriveBits"]}}function Dg(e,t=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:t?"AES-GCM":"AES-KW",length:e},usages:ZR,ops:t?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function LF(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:ZR,ops:["deriveBits","deriveBits"]}}var km=AE({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:ZR,ops:["encrypt","decrypt"]},"RSA-OAEP":YR(1),"RSA-OAEP-256":YR(256),"RSA-OAEP-384":YR(384),"RSA-OAEP-512":YR(512),"ECDH-ES":XR("direct-key-agreement"),"ECDH-ES+A128KW":XR("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":XR("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":XR("key-agreement-with-key-wrapping"),A128KW:Dg(128),A192KW:Dg(192),A256KW:Dg(256),A128GCMKW:Dg(128,!0),A192GCMKW:Dg(192,!0),A256GCMKW:Dg(256,!0),"PBES2-HS256+A128KW":LF(),"PBES2-HS384+A192KW":LF(),"PBES2-HS512+A256KW":LF()}),SEe=["encrypt","decrypt"];function Og(e,t=!1){return{kty:["oct"],secret:!0,subtle:{name:t?"AES-CBC":"AES-GCM",length:e},usages:ZR,ops:SEe,cekBits:e,ivBits:t?128:96,cbc:t}}var vEe=AE({A128GCM:Og(128),A192GCM:Og(192),A256GCM:Og(256),"A128CBC-HS256":Og(256,!0),"A192CBC-HS384":Og(384,!0),"A256CBC-HS512":Og(512,!0)});function Q5(e,t){throw new Xr(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function lu(e){return(typeof e=="string"?km[e]:void 0)??Q5("alg","Algorithm")}function Dm(e){return e.mode==="key-wrapping"||e.mode==="key-encryption"||e.mode==="key-agreement-with-key-wrapping"}function Om(e){return(typeof e=="string"?vEe[e]:void 0)??Q5("enc","Encryption Algorithm")}function J5(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");FF(e,t)}async function xEe(e,t,r){let n=await rl(t,lu(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 EEe(e,t,r){let n=await rl(t,lu(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 X5(e,t,r){UF(t,lu(e).subtle,r),kg(e,t)}async function Z5(e,t,r,n){if(!(e instanceof Uint8Array)||e.length<8)throw new ze("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new ze("PBES2 Count Input must be a positive integer");let o=gs(Ss(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 rl(n,lu(t).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function BF(e){return gs(NR(e.length),e)}async function bEe(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 j5("sha256",gs(NR(a),e,r));s.set(c,(a-1)*32)}return s.slice(0,n)}async function eJ(e,t,r,n,o=new Uint8Array,i=new Uint8Array){J5(e),J5(t,"deriveBits");let s=gs(BF(Ss(r)),BF(o),BF(i),NR(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 bEe(a,n,s)}function tJ(e){zR(e);let t=e.algorithm.namedCurve;if(t!=="P-256"&&t!=="P-384"&&t!=="P-521"&&e.algorithm.name!=="X25519")throw new Xr("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function eP(e,t){let r=e[t];if(r!==void 0){if(typeof r!="string")throw new ze(`JOSE Header "${t}" (Agreement Party${t==="apu"?"U":"V"}Info) invalid`);return Ws(r,t,ze)}}function rJ(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 ze('JOSE Header "apu" and "apv" values must be distinct')}}function wEe(e){if(e===void 0)throw new ze("JWE Encrypted Key missing")}function Y5(e){if(e!==void 0)throw new ze("Encountered unexpected JWE Encrypted Key")}function TEe(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 nJ(e,t,r,n,o,i){let{alg:s}=e,a=e.mode;if(a==="direct-encryption")return Y5(n),r;let c=a==="direct-key-agreement";switch(c?Y5(n):wEe(n),e.subtle.name){case"ECDH":{let{epk:l}=o;if(!_a(l)||["d","k","p","q","dp","dq","qi","oth","priv"].some((g)=>Object.hasOwn(l,g)))throw new ze('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');tJ(r);let d=await MF(e,l),u=eP(o,"apu"),p=eP(o,"apv");rJ(u,p);let y=await eJ(d,r,c?t.alg:s,c?t.cekBits:parseInt(s.slice(-5,-2),10),u,p);if(c)return y;r=y;break}case"RSA-OAEP":return zR(r),X5(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,n));case"PBKDF2":{if(typeof o.p2c!="number")throw new ze('JOSE Header "p2c" (PBES2 Count) missing or invalid');TEe(i);let l=i??1e4;if(o.p2c>l)throw new ze('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof o.p2s!="string")throw new ze('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let d=Ws(o.p2s,"p2s",ze);r=await Z5(d,s,o.p2c,r);break}case"AES-GCM":{if(typeof o.iv!="string")throw new ze('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof o.tag!="string")throw new ze('JOSE Header "tag" (Authentication Tag) missing or invalid');let l=Ws(o.iv,"iv",ze),d=Ws(o.tag,"tag",ze);if(l.byteLength!==12)throw new ze("Invalid Initialization Vector length");if(d.byteLength!==16)throw new ze("Invalid Authentication Tag length");return JR(Om(s.slice(0,-2)),r,n,l,d,new Uint8Array)}}return EEe(s.slice(-6),r,n)}async function oJ(e,t,r,n,o,i={}){let{alg:s,mode:a}=e,c=Dm(e);if(o!==void 0&&!c)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let l=await tl(a==="direct-encryption"?t:e,r,"encrypt");if(a==="direct-encryption")return[l,void 0,void 0];let d=c?o??TE(t):void 0;d&&GR(d,t.cekBits);let u,p;switch(e.subtle.name){case"ECDH":{tJ(l);let{apu:y,apv:g}=i;y!==void 0&&cu(y,'"apu"'),g!==void 0&&cu(g,'"apv"');let E=y??eP(n,"apu"),S=g??eP(n,"apv");rJ(E,S);let x;i.epk!==void 0?x=await tl(e,i.epk,"decrypt"):x=(await crypto.subtle.generateKey(l.algorithm,!0,["deriveBits"])).privateKey;let w=crypto.subtle,_=x;if(!_.extractable){if(typeof w.getPublicKey!="function")throw TypeError('CryptoKey for "epk" must be extractable');_=await w.getPublicKey(x,[])}let{x:T,y:b,crv:I,kty:O}=await w.exportKey("jwk",_),L=a==="direct-key-agreement",Y=await eJ(l,x,L?t.alg:s,L?t.cekBits:parseInt(s.slice(-5,-2),10),E,S),Z={x:T,crv:I,kty:O};if(O==="EC"&&(Z.y=b),p={epk:Z},y!==void 0&&(p.apu=uo(y)),g!==void 0&&(p.apv=uo(g)),L)return[Y,void 0,p];l=Y;break}case"RSA-OAEP":{zR(l),X5(s,l,"encrypt"),u=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",l,d));break}case"PBKDF2":{let{p2c:y=2048,p2s:g=crypto.getRandomValues(new Uint8Array(16))}=i;l=await Z5(g,s,y,l),p={p2c:y,p2s:uo(g)};break}case"AES-GCM":{let y=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(y instanceof Uint8Array))throw TypeError('"iv" must be an instance of Uint8Array');let g=await QR(Om(s.slice(0,-2)),d,l,y,new Uint8Array);u=g.ciphertext,p={iv:uo(g.iv),tag:uo(g.tag)}}}if(u??=await xEe(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,p]}function tP(e,t){if(e.zip!==void 0&&e.zip!=="DEF")throw new Xr('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(e.zip!==void 0&&!t?.zip)throw new ze('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function iJ(e){if(typeof globalThis[e]>"u")throw new Xr(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function sJ(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 ze("Decompressed plaintext exceeded the configured limit")}return gs(...o)}async function aJ(e){return iJ("CompressionStream"),sJ(new CompressionStream("deflate-raw"),e)}async function cJ(e,t){return iJ("DecompressionStream"),sJ(new DecompressionStream("deflate-raw"),e,t)}function AEe(e){let{protected:t,ciphertext:r,iv:n,tag:o,aad:i}=e,s;return t!==void 0&&(s=$R(t,ze,"JWE Protected Header is invalid")),[s,Ws(r,"ciphertext",ze),n!==void 0?Ws(n,"iv",ze):void 0,o!==void 0?Ws(o,"tag",ze):void 0,BR((t??"")+(i!==void 0?`.${i}`:""),"aad",ze)]}function lJ(e){return[e&&bE("keyManagementAlgorithms",e.keyManagementAlgorithms),e&&bE("contentEncryptionAlgorithms",e.contentEncryptionAlgorithms),e?.crit,e?.maxPBES2Count,e?.maxDecompressedLength]}async function IEe(e,t,r,n=AEe(e)){let[o,i,s,a,c]=n,{header:l,unprotected:d,aad:u}=e,p;if(l!==void 0||d!==void 0){if(!Np(o,l,d))throw new ze("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");p={...o,...l,...d}}else p=o??{};let[y,g,E,S,x]=t,{encrypted_key:w}=e;Fp(ze,jR,E,o,p),tP(p,o);let{alg:_,enc:T}=p;if(typeof _!="string"||!_)throw new ze("missing JWE Algorithm (alg) in JWE Header");let b=km[_];if(w===""&&(!b||!Dm(b)))throw new ze("JWE Encrypted Key incorrect type");let I=b?.mode==="integrated-encryption";if(!I&&(typeof T!="string"||!T))throw new ze("missing JWE Encryption Algorithm (enc) in JWE Header");if(y&&!y.has(_)||!y&&_.startsWith("PBES2"))throw new _g('"alg" (Algorithm) Header Parameter value not allowed');let O;if(I){if(T!==void 0)throw new ze('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new ze("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new ze("JWE Authentication Tag must be empty for integrated encryption")}else{if(g&&!g.has(T))throw new _g('"enc" (Encryption Algorithm) Header Parameter value not allowed');O=Om(T)}let L;if(w!==void 0)try{L=Ws(w,"encrypted_key",ze)}catch(ne){if(!b||!Dm(b))throw ne;L=new Uint8Array}let Y=!1;typeof r=="function"&&(r=await r(o,e),Y=!0);let Z=b??lu(_);Dm(Z)&&L===void 0&&(L=new Uint8Array);let ee=await tl(Z.mode==="direct-encryption"?O:Z,r,"decrypt"),ae;if(Z.mode==="integrated-encryption")ae=await Z.decrypt(ee,L,i,c,o,p);else{let ne=O,le;try{le=await nJ(Z,ne,ee,L,p,S),Dm(Z)&&le instanceof Uint8Array&&le.byteLength<<3!==ne.cekBits&&(le=TE(ne))}catch(ie){if(ie instanceof TypeError||ie instanceof ze||ie instanceof Xr)throw ie;le=TE(ne)}ae=await JR(ne,le,i,s,a,c)}if(p.zip==="DEF"){let ne=x??250000;if(ne===0)throw new Xr('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(ne!==1/0&&(!Number.isSafeInteger(ne)||ne<1))throw TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");ae=await cJ(ae,ne).catch((le)=>{throw le instanceof ze?le:new ze("Failed to decompress plaintext",{cause:le})})}return{plaintext:ae,...o&&{protectedHeader:o},...u!==void 0&&{additionalAuthenticatedData:Ws(u,"aad",ze)},...d&&{sharedUnprotectedHeader:d},...l&&{unprotectedHeader:l},...Y&&{key:ee}}}async function dJ(e,t,r){if(e instanceof Uint8Array&&(e=Cg.decode(e)),typeof e!="string")throw new ze("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 ze("Invalid Compact JWE");return IEe({ciphertext:s,iv:i||void 0,protected:n,tag:a||void 0,encrypted_key:o||void 0},t,r)}async function $F(e,t,r){return dJ(e,lJ(r),t)}function uJ(e,t,r){if(!Np(e,t,r))throw new ze("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function REe(e,t,r=!1){if(!e[1]&&!e[2]&&!e[3])throw new ze("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&&cu(s,"JWE Additional Authenticated Data"),a!==void 0&&cu(a,"JWE Content Encryption Key"),c!==void 0&&cu(c,"JWE Initialization Vector"),!r&&n!==void 0&&(n=_m(ze,n)[0],e[1]=n),o!==void 0&&(o=_m(ze,o)[0],e[2]=o),!r&&i!==void 0&&(i=_m(ze,i)[0],e[3]=i),l!==void 0&&!_a(l))throw TypeError("JWE Key Management Parameters must be an object");uJ(n,o,i);let u={...n,...o,...i};HR(ze,n),Fp(ze,jR,d,n,u),tP(u,n);let{alg:p,enc:y}=u;if(typeof p!="string"||!p)throw new ze('JWE "alg" (Algorithm) Header Parameter missing or invalid');let g=km[p];if(g?.mode==="integrated-encryption"){if(y!==void 0)throw new ze('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 ${p}`);if(c!==void 0)throw TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${p}`);return[u,void 0,g]}if(typeof y!="string"||!y)throw new ze('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[u,Om(y),g]}async function PEe(e,t,r){let[n,o,i]=t,[s,a,c,l,d,u,p,y,,g]=e,E=a,S=c,x=i??lu(n.alg),w,_,T;x.mode==="integrated-encryption"?T=await tl(x,r,"encrypt"):[T,w,_]=await oJ(x,o,r,n,u,y),_&&(g?S=S?{...S,..._}:_:E=E?{...E,..._}:_,uJ(E,S,l));let b=E?uo(JSON.stringify(E)):"",I=d?.byteLength?uo(d):void 0,O=Ss(I?`${b}.${I}`:b),L=s;n.zip==="DEF"&&(L=await aJ(L).catch((ne)=>{throw new ze("Failed to compress plaintext",{cause:ne})}));let Y,Z,ee;x.mode==="integrated-encryption"?[w,Y]=await x.encrypt(T,L,O,E,n,y):{ciphertext:Y,tag:Z,iv:ee}=await QR(o,L,T,p,O);let ae={ciphertext:uo(Y)};return ee&&(ae.iv=uo(ee)),Z&&(ae.tag=uo(Z)),w?.byteLength&&(ae.encrypted_key=uo(w)),I&&(ae.aad=I),E&&(ae.protected=b),l&&(ae.unprotected=l),S&&(ae.header=S),ae}async function pJ(e,t,r){return PEe(e,REe(e,r),t)}function fJ(e){return[e.protected,e.encrypted_key,e.iv,e.ciphertext,e.tag].join(".")}var IE=[["verify"],["sign"]];function qF(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:IE}}function Ng(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:IE,minRsaBits:2048}}function jF(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:IE}}function mJ(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:IE}}function HF(e){let t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:IE}}var WF=AE({HS256:qF(256),HS384:qF(384),HS512:qF(512),RS256:Ng(256),RS384:Ng(384),RS512:Ng(512),PS256:Ng(256,32),PS384:Ng(384,48),PS512:Ng(512,64),ES256:jF("P-256",256),ES384:jF("P-384",384),ES512:jF("P-521",512),EdDSA:mJ(),Ed25519:mJ(),"ML-DSA-44":HF(44),"ML-DSA-65":HF(65),"ML-DSA-87":HF(87)});function rP(e){let t=typeof e=="string"?WF[e]:void 0;if(!t)throw new Xr(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function yJ(e){return[e&&bE("algorithms",e.algorithms),e?.crit]}function CEe(e){return e===void 0?{}:$R(e,bn,"JWS Protected Header is invalid")}function _Ee(e){try{return Ss(e)}catch{throw new bn("JWS Compact Serialization payload must use only ASCII characters")}}async function kEe(e,t,r,n,o){let{protected:i,header:s,payload:a}=e,c=o??CEe(i);if(!Np(c,s))throw new bn("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let l={...c,...s},d=WR(c,Fp(bn,qR,t[1],c,l)),{alg:u}=l;if(typeof u!="string"||!u)throw new bn('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(t[0]&&!t[0].has(u))throw new _g('"alg" (Algorithm) Header Parameter value not allowed');if(d){if(typeof a!="string")throw new bn("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new bn("JWS Payload must be a string or an Uint8Array instance");let p=d||typeof a!="string"?a:n(a),y=!1;typeof r=="function"&&(r=await r(c,e),y=!0);let g=rP(u),E=gs(i!==void 0?Ss(i):new Uint8Array,Ss("."),typeof p=="string"?t[2]??=BR(p,"payload",bn):p),S=Ws(e.signature,"signature",bn),x=await tl(g,r,"verify"),w=await rl(x,g.subtle,"verify");g.minRsaBits&&kg(g.alg,w);let _=!1;try{_=await crypto.subtle.verify(g.signing,w,S,E)}catch{}if(!_)throw new OF;let T={payload:typeof p=="string"?Ws(p,"payload",bn):p};return i!==void 0&&(T.protectedHeader=c),s!==void 0&&(T.unprotectedHeader=s),y?[{...T,key:x},d]:[T,d]}async function hJ(e,t,r){if(e instanceof Uint8Array&&(e=Cg.decode(e)),typeof e!="string")throw new bn("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:i,length:s}=e.split(".");if(s!==3)throw new bn("Invalid Compact JWS");return kEe({payload:o,protected:n,signature:i},t,r,_Ee)}var RE=(e)=>Math.floor(e.getTime()/1000),DEe={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},OEe=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Fg="check_failed";function VF(){throw TypeError("Invalid time period format")}function nP(e){typeof e!="string"&&VF();let t=OEe.exec(e);(!t||t[4]&&t[1])&&VF();let r=parseFloat(t[2]),n=Math.round(r*DEe[t[3][0].toLowerCase()]);return Number.isFinite(n)||VF(),t[1]==="-"||t[4]==="ago"?-n:n}function Ug(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function zF(e,t){if(typeof t!="string")throw TypeError(`"${e}" claim must be a string`)}function NEe(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 KF(e,t){return typeof e=="number"?Ug(t,e):e instanceof Date?Ug(t,RE(e)):RE(new Date)+nP(e)}var gJ=(e)=>{let t=e.toLowerCase();return e.includes("/")?t:`application/${t}`},FEe=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some((r)=>e.includes(r)):!1;function GF(e,t,r=!1){let n=e[t];if(!(n===void 0&&!r)){if(typeof n!="number")throw new Op(`"${t}" claim must be a number`,e,t,"invalid");return n}}function QF(e,t){throw new Op(`unexpected "${t}" claim value`,e,t,Fg)}function SJ(e,t,r={}){let n;try{n=JSON.parse(OR.decode(t))}catch{}if(!_a(n))throw new Pm("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o!==void 0&&(typeof e.typ!="string"||gJ(e.typ)!==gJ(o)))throw new Op('unexpected "typ" JWT header value',n,"typ",Fg);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 w of new Set(d.reverse()))if(!Object.hasOwn(n,w))throw new Op(`missing required "${w}" claim`,n,w,"missing");s!==void 0&&!(Array.isArray(s)?s:[s]).includes(n.iss)&&QF(n,"iss"),a!==void 0&&n.sub!==a&&QF(n,"sub"),c!==void 0&&!FEe(n.aud,typeof c=="string"?[c]:c)&&QF(n,"aud");let{clockTolerance:u}=r,p=0;if(typeof u=="string")p=nP(u);else if(u!==void 0){if(typeof u!="number")throw TypeError("Invalid clockTolerance option type");p=u}Ug("clockTolerance option",p);let{currentDate:y}=r,g=Ug("currentDate option",RE(y===void 0?new Date:y)),E=GF(n,"iat",l!==void 0),S=GF(n,"nbf");if(S!==void 0&&S>g+p)throw new Op('"nbf" claim timestamp check failed',n,"nbf",Fg);let x=GF(n,"exp");if(x!==void 0&&x<=g-p)throw new MR('"exp" claim timestamp check failed',n,"exp",Fg);if(l!==void 0){let w=g-E,_=Ug("maxTokenAge option",typeof l=="number"?l:nP(l));if(w-p>_)throw new MR('"iat" claim timestamp check failed (too far in the past)',n,"iat",Fg);if(w<-p)throw new Op('"iat" claim timestamp check failed (it should be in the past)',n,"iat",Fg)}return n}var vJ;function Mp(e){return vJ.get(e)}function xJ(e){let t=Mp(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 Dp.encode(JSON.stringify(t))}class JF{constructor(e={}){if(!_a(e))throw TypeError("JWT Claims Set MUST be an object");(vJ||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return zF("iss",e),Mp(this).iss=e,this}setSubject(e){return zF("sub",e),Mp(this).sub=e,this}setAudience(e){return NEe(e),Mp(this).aud=e,this}setJti(e){return zF("jti",e),Mp(this).jti=e,this}setNotBefore(e){return Mp(this).nbf=KF(e,"setNotBefore"),this}setExpirationTime(e){return Mp(this).exp=KF(e,"setExpirationTime"),this}setIssuedAt(e){let t=Mp(this);return e===void 0?t.iat=RE(new Date):typeof e=="string"?t.iat=Ug("setIssuedAt",RE(new Date)+nP(e)):t.iat=KF(e,"setIssuedAt"),this}}async function uc(e,t,r){let[n,o]=await hJ(e,yJ(r),t);if(!o)throw new Pm("JWTs MUST NOT use unencoded payload");let i=SJ(n.protectedHeader,n.payload,r);return{...n,payload:i}}class oP{#e;constructor(e){cu(e,"plaintext"),this.#e=[e]}setContentEncryptionKey(e){return Cm(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return Cm(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}setProtectedHeader(e){return Cm(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return Cm(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}async encrypt(e,t){return fJ(await pJ([...this.#e],e,t))}}async function UEe(e,t,r){let[n,o,i,s]=e,a="";if(o!==void 0){let x=_m(bn,o);o=x[0],a=uo(x[1])}if(i!==void 0&&(i=_m(bn,i)[0]),!o&&!i)throw new bn("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Np(o,i))throw new bn("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...o,...i};HR(bn,o);let l=WR(o,Fp(bn,qR,s,o,c));l||r?.();let{alg:d}=c;if(typeof d!="string"||!d)throw new bn('JWS "alg" (Algorithm) Header Parameter missing or invalid');let u=rP(d),p="",y=n,g;if(l){let x=e[4];x?(p=x[0]??=uo(n),y=x[1]??=Ss(p)):(p=uo(n),g=Dp.encode(`${a}.${p}`))}g??=gs(Ss(a),Ss("."),y);let E=await rl(await tl(u,t,"sign"),u.subtle,"sign");u.minRsaBits&&kg(u.alg,E);let S={signature:uo(new Uint8Array(await crypto.subtle.sign(u.signing,E,g))),payload:p};return o&&(S.protected=a),i&&(S.header=i),[S,l]}async function EJ(e,t,r,n,o){let[i]=await UEe([e,t,void 0,r],n,o);return`${i.protected}.${i.payload}.${i.signature}`}var MEe=JF;class Mg extends MEe{#e;setProtectedHeader(e){return Cm(this.#e,"setProtectedHeader"),this.#e=e,this}async sign(e,t){return EJ(xJ(this),this.#e,t?.crit,e,()=>{throw new Pm("JWTs MUST NOT use unencoded payload")})}}var Lg='"alg" (Algorithm)';function PE(e='JWK "alg" (Algorithm) Parameter'){throw new Xr(`Invalid or unsupported ${e} value`)}function iP(e,t){return(typeof e=="string"?WF[e]??km[e]:void 0)??PE(t)}var LEe=(e,t)=>{let r=(e.match(/.{1,64}/g)||[]).join(`
|
|
421
|
+
`);return`-----BEGIN ${t}-----
|
|
422
|
+
${r}
|
|
423
|
+
-----END ${t}-----`},bJ=async(e,t,r)=>{if(wE(r)){if(r.type!==e)throw TypeError(`key is not a ${e} key`);return r.export({format:"pem",type:t})}if(!Kl(r))throw TypeError(Up(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 LEe(FR(new Uint8Array(await crypto.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},wJ=(e)=>bJ("public","spki",e),TJ=(e)=>bJ("private","pkcs8",e),CE=(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},BEe=(e)=>({data:e,pos:0}),YF=(e)=>{let t=e.data[e.pos++];if(t===void 0)throw Error("Unexpected end of ASN.1 input");return t},_E=(e)=>{let t=YF(e);if(t&128){let r=t&127,n=0;for(let o=0;o<r;o++)n=n<<8|YF(e);return n}return t};var kE=(e,t,r)=>{if(YF(e)!==t)throw Error(r)},AJ=(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},$Ee=(e)=>{kE(e,6,"Expected algorithm OID");let t=_E(e);return AJ(e,t)};function qEe(e,t){if(kE(e,48,`Invalid ${t==="spki"?"SPKI":"PKCS#8"} structure`),_E(e),t==="pkcs8"){kE(e,2,"Expected version field");let r=_E(e);e.pos+=r}kE(e,48,"Expected algorithm identifier"),_E(e)}var jEe=(e)=>{let t=$Ee(e);if(CE(t,[43,101,110]))return"X25519";if(!CE(t,[42,134,72,206,61,2,1]))throw Error("Unsupported key algorithm");kE(e,6,"Expected curve OID");let r=_E(e),n=AJ(e,r);if(CE(n,[42,134,72,206,61,3,1,7]))return"P-256";if(CE(n,[43,129,4,0,34]))return"P-384";if(CE(n,[43,129,4,0,35]))return"P-521";throw Error("Unsupported named curve")},IJ=async(e,t,r,n)=>{let o=KR(n?.extractable),i=iP(r,Lg);i.secret&&PE(Lg);let s=e==="spki",a;if(i.resolve)try{let c=BEe(t);qEe(c,e),a=i.resolve({crv:jEe(c)})}catch{throw new Xr("Invalid or unsupported key format")}else a=i.subtle;return crypto.subtle.importKey(e,t,a,o??s,i.usages[s?0:1])},RJ=(e,t)=>UR(e.replace(t,"")),PJ=(e,t,r)=>{let n=RJ(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);return IJ("pkcs8",n,t,r)},CJ=(e,t,r)=>{let n=RJ(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g);return IJ("spki",n,t,r)};function sP(e){return wJ(e)}function aP(e){return TJ(e)}async function DE(e){if(wE(e))if(e.type==="secret")e=e.export();else return e.export({format:"jwk"});if(e instanceof Uint8Array)return{kty:"oct",k:uo(e)};if(!Kl(e))throw TypeError(Up(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 OE(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw TypeError('"spki" must be SPKI formatted string');return CJ(e,t,r)}async function NE(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw TypeError('"pkcs8" must be PKCS#8 formatted string');return PJ(e,t,r)}function HEe(e){let t=e?.modulusLength??2048;if(typeof t!="number"||!Number.isInteger(t)||t<2048)throw new Xr("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function cP(e,t){let r=KR(t?.extractable),n=iP(e,Lg);n.secret&&PE(Lg);let o;if(n.resolve){let i=t?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new Xr("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 Xr(`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:HEe(t)}:n.subtle}return crypto.subtle.generateKey(o,r??!1,[...n.usages[1],...n.usages[0]])}import{Effect as zo,Either as WJ}from"effect";import{Effect as ZF}from"effect";import{Data as pc}from"effect";class Nm extends pc.TaggedError("processfocus:internal-tag/openauth/OAuthEndpointError"){}class wn extends pc.TaggedError("processfocus:internal-tag/openauth/ClientAuthError"){}class _J extends pc.TaggedError("processfocus:internal-tag/openauth/MissingParameterError"){get description(){return`Missing parameter: ${this.parameter}`}}class kJ extends pc.TaggedError("processfocus:internal-tag/openauth/UnauthorizedClientError"){get description(){return`Client ${this.clientID} is not authorised to use this redirect_uri: ${this.redirectURI}`}}class DJ extends pc.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 OJ extends pc.TaggedError("processfocus:internal-tag/openauth/InvalidAuthorizationCodeError"){get description(){return"Authorization code has been used or expired"}}class NJ extends pc.TaggedError("processfocus:internal-tag/openauth/InvalidRefreshTokenError"){get description(){return"Refresh token has been used or expired"}}class FJ extends pc.TaggedError("processfocus:internal-tag/openauth/InvalidAccessTokenError"){get description(){return"Invalid access token"}}class UJ extends pc.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 lP extends pc.TaggedError("processfocus:internal-tag/openauth/MissingHostError"){get description(){return"Missing host or x-forwarded-host header in request"}}class XF extends pc.TaggedError("processfocus:internal-tag/openauth/JwtVerificationError"){}class Fm extends pc.TaggedError("processfocus:internal-tag/openauth/InvariantViolationError"){}var WEe=(e)=>e["x-forwarded-host"]??e.host,Bg=(e)=>{let t=e["cloudfront-forwarded-proto"]??e["x-forwarded-proto"]??"http";return t==="http"||t==="https"?t:void 0},ci=(e)=>{let t=WEe(e);if(!t)return ZF.fail(new lP);let r=Bg(e);if(!r)return ZF.fail(new Nm({error:"invalid_request",description:"Invalid forwarded protocol header",statusCode:400}));return ZF.succeed(`${r}://${t}`)};import{Effect as MJ}from"effect";var ka=(e,t)=>Rde(e,t).pipe(MJ.catchAll(()=>MJ.succeed(Xh("Internal Server Error",{status:500})))),Um=(e,t)=>ka(e,{...t,headers:{...t?.headers,"Cache-Control":"no-store",Pragma:"no-cache"}}),Qe=(e,t,r)=>ka({error:e,error_description:t},{status:r});import{Context as VEe,Data as zEe,Effect as l7e,Layer as d7e}from"effect";class eU extends zEe.TaggedError("processfocus:internal-tag/ClientRegistryError"){}class Ii extends VEe.Tag("processfocus:internal-tag/openauth/ClientRegistryService")(){}import{Context as JEe,Data as qJ,Effect as du,Layer as $J}from"effect";import{Effect as po,Stream as oU}from"effect";import{Context as KEe,Data as GEe,Effect as FE,Stream as QEe}from"effect";var tU=String.fromCharCode(31);function Mm(e){return e.join(tU)}function LJ(e){return e.split(tU)}function UE(e){return e.map((t)=>t.replaceAll(tU,""))}class nl extends GEe.TaggedError("processfocus:internal-tag/openauth/StorageError"){}class Zr extends KEe.Tag("processfocus:internal-tag/openauth/StorageService")(){}var wr;((i)=>(i.get=(s)=>FE.gen(function*(){return yield*(yield*Zr).get(UE(s))}),i.take=(s)=>FE.gen(function*(){return yield*(yield*Zr).take(UE(s))}),i.set=(s,a,c)=>FE.gen(function*(){return yield*(yield*Zr).set(UE(s),a,c)}),i.remove=(s)=>FE.gen(function*(){return yield*(yield*Zr).remove(UE(s))}),i.scan=(s)=>QEe.unwrap(FE.gen(function*(){return(yield*Zr).scan(UE(s))}))))(wr||={});var rU="ES256",nU="RSA-OAEP-512",BJ=po.gen(function*(){let t=[],r=(n)=>new nl({message:"Failed to import key",cause:n});return yield*wr.scan(["oauth:key"]).pipe(oU.runForEach(([n,o])=>po.gen(function*(){let i=yield*po.tryPromise({try:()=>OE(o.publicKey,"RS512",{extractable:!0}),catch:r}),s=yield*po.tryPromise({try:()=>NE(o.privateKey,"RS512"),catch:r}),a=yield*po.tryPromise({try:()=>DE(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}),iU=po.gen(function*(){let e=[],t=(o)=>new nl({message:"Failed to import key",cause:o});if(yield*wr.scan(["signing:key"]).pipe(oU.runForEach(([o,i])=>po.gen(function*(){let s=yield*po.tryPromise({try:()=>OE(i.publicKey,i.alg,{extractable:!0}),catch:t}),a=yield*po.tryPromise({try:()=>NE(i.privateKey,i.alg),catch:t}),c=yield*po.tryPromise({try:()=>DE(s),catch:t});c.kid=i.id,c.use="sig";let l={id:i.id,alg:rU,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*po.promise(()=>cP(rU,{extractable:!0})),n={id:crypto.randomUUID(),publicKey:yield*po.promise(()=>sP(r.publicKey)),privateKey:yield*po.promise(()=>aP(r.privateKey)),created:Date.now(),alg:rU};return yield*wr.set(["signing:key",n.id],n),yield*iU}),sU=po.gen(function*(){let e=[],t=(o)=>new nl({message:"Failed to import key",cause:o});if(yield*wr.scan(["encryption:key"]).pipe(oU.runForEach(([o,i])=>po.gen(function*(){let s=yield*po.tryPromise({try:()=>OE(i.publicKey,i.alg,{extractable:!0}),catch:t}),a=yield*po.tryPromise({try:()=>NE(i.privateKey,i.alg),catch:t}),c=yield*po.tryPromise({try:()=>DE(s),catch:t});c.kid=i.id;let l={id:i.id,alg:nU,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*po.promise(()=>cP(nU,{extractable:!0})),n={id:crypto.randomUUID(),publicKey:yield*po.promise(()=>sP(r.publicKey)),privateKey:yield*po.promise(()=>aP(r.privateKey)),created:Date.now(),alg:nU};return yield*wr.set(["encryption:key",n.id],n),yield*sU});class jJ extends qJ.TaggedError("processfocus:internal-tag/NoSigningKeysError"){}class HJ extends qJ.TaggedError("processfocus:internal-tag/NoEncryptionKeysError"){}class Ln extends JEe.Tag("processfocus:internal-tag/openauth/KeyManagementService")(){}var ME=$J.effect(Ln,du.gen(function*(){let e=yield*Zr,t=$J.succeed(Zr,e),r=yield*du.cached(du.gen(function*(){let[o,i]=yield*du.all([iU,BJ]).pipe(du.provide(t));return[...o,...i]})),n=yield*du.cached(sU.pipe(du.provide(t)));return{allSigningKeys:r,signingKey:du.gen(function*(){let i=(yield*r)[0];if(!i)return yield*new jJ({message:"No signing keys available"});return i}),encryptionKey:du.gen(function*(){let i=(yield*n)[0];if(!i)return yield*new HJ({message:"No encryption keys available"});return i})}}));var VJ=(e)=>e==="localhost"||e==="127.0.0.1"||e==="[::1]",zJ=(e)=>{let t=e.replace(/\/+$/,"");return t===""?"/":t},YEe=()=>!0,XEe=(e,t)=>{if(!YEe())return!1;if(typeof e!=="string")return!1;try{let r=new URL(e),n=new URL(t);return r.protocol===n.protocol&&VJ(r.hostname)&&VJ(n.hostname)&&r.hostname===n.hostname&&zJ(r.pathname)===zJ(n.pathname)}catch{return!1}};function ZEe(e){return e.replace(/["\r\n]/g,"")}function ebe(e){try{return{ok:!0,value:Buffer.from(e,"base64").toString("utf8")}}catch{return{ok:!1,error:new wn({description:"Authorization header is not valid base64"})}}}function tbe(e,t){try{return{ok:!0,clientId:decodeURIComponent(e),secret:decodeURIComponent(t)}}catch{return{ok:!1,error:new wn({description:"Authorization header contains invalid percent encoding"})}}}var rbe=(e)=>zo.gen(function*(){let t=yield*Ln,r=yield*on,n=yield*ci(r.headers).pipe(zo.mapError(()=>new wn({description:"Unable to determine token issuer from request headers"}))),o=yield*t.allSigningKeys.pipe(zo.mapError(()=>new wn({description:"Failed to load signing keys for client JWT verification"})));for(let i of o){let s=yield*zo.tryPromise(()=>uc(e,()=>Promise.resolve(i.public),{issuer:n})).pipe(zo.either),a=yield*WJ.match(s,{onLeft:()=>zo.succeed(void 0),onRight:(d)=>{let u=d.payload.properties?.clientId;if(typeof u!=="string"||u.length===0)return zo.fail(new wn({description:"Client JWT is missing properties.clientId claim"}));return zo.succeed(u)}});if(a!==void 0)return a;let c=yield*zo.tryPromise(()=>uc(e,()=>Promise.resolve(i.public))).pipe(zo.either),l=yield*WJ.match(c,{onLeft:()=>zo.succeed(void 0),onRight:(d)=>{if(!XEe(d.payload.iss,n))return zo.succeed(void 0);let u=d.payload.properties?.clientId;if(typeof u!=="string"||u.length===0)return zo.fail(new wn({description:"Client JWT is missing properties.clientId claim"}));return zo.succeed(u)}});if(l!==void 0)return l}return yield*new wn({description:"Invalid client JWT"})}),ol=(e)=>zo.gen(function*(){let t=yield*Ii,n=(yield*on).headers.authorization,o="none",i,s;if(n){let[l,d]=n.split(" "),u=l?.toLowerCase();if(!u||!d)return yield*new wn({description:"Authorization header is malformed"});if(u==="basic"){let p=ebe(d);if(!p.ok)return yield*p.error;let y=p.value,g=y.indexOf(":");if(g===-1)return yield*new wn({description:"Authorization header must contain client_id and client_secret"});let E=tbe(y.slice(0,g),y.slice(g+1));if(!E.ok)return yield*E.error;if(i=E.clientId,s=E.secret,o="client_secret_basic",e.has("client_id")||e.has("oauth_client_id"))return yield*new wn({description:"client_id must not be included in the body when Basic Authorization is used"})}else if(u==="bearer"){o="client_jwt",i=yield*rbe(d);let p=e.get("oauth_client_id")??e.get("client_id");if(p&&p!==i)return yield*new wn({description:"client_id in request body must match properties.clientId in client JWT"})}else return yield*new wn({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 wn({description:"Missing client_id"});let a=yield*t.getClient(i);if(!a)return yield*new wn({description:"Unknown client"});if(a.secretHash&&o!=="client_jwt"){if(!s)return yield*new wn({description:"Client authentication is required"});if(!(yield*zo.tryPromise({try:()=>Bun.password.verify(s,a.secretHash),catch:()=>new wn({description:"Failed to verify client credentials"})}).pipe(zo.withSpan("auth.verifyClientSecret"))))return yield*new wn({description:"Invalid client credentials"})}else if(s)return yield*new wn({description:"Public clients must not send client_secret"});if(a.isPublic&&o!=="none")return yield*new wn({description:"Public clients cannot use Authorization headers"});let c=a.enforcedAuthMethod;if(c&&o!==c)return yield*new wn({description:`Client must authenticate using ${c}`});if(!a.isPublic&&o==="none")return yield*new wn({description:"Confidential clients must authenticate using Basic, client_secret_post, or Bearer client JWT"});return{client:a,method:o}}).pipe(zo.withSpan("auth.authenticateClient")),Lm=(e)=>ka({error:"invalid_client",error_description:e},{status:401}).pipe(zo.map((t)=>lI(t,"WWW-Authenticate",`Basic realm="token", error="invalid_client", error_description="${ZEe(e)}"`)));import{Clock as nbe,Effect as LE}from"effect";var Gl=(e,t)=>LE.gen(function*(){let r=yield*Ln,n=yield*on,o=yield*nbe.currentTimeMillis;if(e.expiresAt!==void 0&&(!Number.isFinite(e.expiresAt)||e.expiresAt<=o))return yield*new Nm({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 Nm({error:"invalid_grant",description:"Credential expired",statusCode:400});let d=t?.generateRefreshToken??!0;if(e.nextToken!==void 0&&!d&&!t?.allowExistingRefreshToken)return yield*new Fm({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 S={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*wr.set(["oauth:refresh",e.subject,u],S,i)}let p=yield*r.signingKey.pipe(LE.withSpan("auth.getSigningKey")),y=yield*ci(n.headers),E={access:yield*LE.promise(()=>new Mg({mode:"access",type:e.type,properties:e.properties,aud:e.audience??e.clientID,iss:y,sub:e.subject}).setExpirationTime(c).setProtectedHeader({alg:p.alg,kid:p.id,typ:"JWT"}).sign(p.private)).pipe(LE.withSpan("auth.signAccessToken")),expiresIn:l};if(!u)return E;return{...E,refresh:[e.subject,u].join(":"),refreshExpiresIn:Math.floor(i)}}).pipe(LE.withSpan("auth.generateTokens"));import{Data as Pbe,Effect as Yt,Either as Cbe,Schema as att}from"effect";import{Effect as lU}from"effect";import{Context as obe,Duration as ibe,Effect as uP,Ref as dP}from"effect";var sbe=obe.GenericTag("processfocus:internal-tag/openauth/CookieService"),abe=()=>uP.gen(function*(){let t=(yield*on).headers.cookie??"",r=cde(t),n=yield*dP.make([]);return{get:(i)=>uP.succeed(r[i]),set:(i,s,a={})=>dP.update(n,(c)=>[...c,{name:i,value:s,options:a}]),delete:(i,s={})=>dP.update(n,(a)=>[...a,{name:i,value:"",options:{...s,maxAge:0,expires:new Date(0)}}]),getPending:()=>dP.get(n)}}),$g=(e,t,r={})=>{let n={maxAge:r.maxAge!==void 0?ibe.seconds(r.maxAge):void 0,expires:r.expires,path:r.path,domain:r.domain,secure:r.secure,httpOnly:r.httpOnly,sameSite:r.sameSite},o=sde(e,t,n);return ade(o)},q7e=DO((e)=>uP.gen(function*(){let t=yield*abe(),r=yield*e.pipe(uP.provideService(sbe,t)),n=yield*t.getPending();if(n.length===0)return r;let o=n.map(({name:i,value:s,options:a})=>$g(i,s,a));return Zh(r,{"Set-Cookie":o.join(", ")})}));function pP(e,t){let r=`${e}${t}`;return r.endsWith("/")?r.slice(0,-1):r}function aU(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 cU(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 fP(e,t){let r=aU(e);if(!r.ok)return!1;let n=new URL(r.value),o=pP(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=pP(s.origin,s.pathname),l=pP("http://localhost",n.pathname);return c===l}return pP(s.origin,s.pathname)===o})}import{Context as cbe,Data as lbe,Effect as V7e,Layer as z7e}from"effect";class mP extends lbe.TaggedError("processfocus:internal-tag/openauth/OnRefreshScopeError"){}class Ql extends cbe.Tag("processfocus:internal-tag/openauth/IssuerCallbacks")(){}import{Context as dbe,Data as ube,Effect as Bm,Layer as pbe,Schema as yP}from"effect";class hP extends ube.TaggedError("processfocus:internal-tag/openauth/DecryptionError"){}var KJ=yP.parseJson(yP.Unknown);class uu extends dbe.Tag("processfocus:internal-tag/openauth/EncryptionService")(){}var gP=pbe.effect(uu,Bm.gen(function*(){let e=yield*Ln;return{encrypt:(t)=>Bm.gen(function*(){let r=yield*e.encryptionKey,n=yield*yP.encode(KJ)(t).pipe(Bm.mapError((i)=>new nl({message:"Failed to encode value for encryption",cause:i})));return yield*Bm.promise(()=>new oP(new TextEncoder().encode(n)).setProtectedHeader({alg:"RSA-OAEP-512",enc:"A256GCM"}).encrypt(r.public))}),decrypt:(t)=>Bm.gen(function*(){let r=yield*e.encryptionKey,n=yield*Bm.tryPromise({try:()=>$F(t,r.private),catch:(i)=>new hP({message:"Failed to decrypt value",cause:i})}),o=new TextDecoder().decode(n.plaintext);return yield*yP.decodeUnknown(KJ)(o).pipe(Bm.mapError((i)=>new hP({message:"Failed to decode decrypted value",cause:i})))})}}));import{Context as fbe,Effect as eZe,Layer as tZe}from"effect";class fc extends fbe.Tag("processfocus:internal-tag/openauth/ProviderRegistryService")(){}function mbe(e,t){if(!fP(t,e.redirectUris))return{ok:!1};return{ok:!0,value:cU(t)}}var BE=(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 lU.succeed(cI(o.toString(),{status:302}))},dU=lU.gen(function*(){let e=yield*Ii,t=yield*uu,r=yield*fc,n=yield*Ql,o=yield*on,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,p=a.get("client_id")??void 0,y=a.get("audience")??void 0,g=a.get("code_challenge")??void 0,E=a.get("code_challenge_method")??void 0;if(!p)return yield*Qe("invalid_request","Missing parameter: client_id",400);if(!d)return yield*Qe("invalid_request","Missing parameter: redirect_uri",400);if(!l)return yield*Qe("invalid_request","Missing parameter: response_type",400);let S=p,x=d,w=e.staticClients.get(S);if(!w)return yield*Qe("unauthorized_client",`Unknown client: ${S}`,400);let _=mbe(w,x);if(!_.ok)return yield*Qe("unauthorized_client",`Invalid redirect_uri for client: ${S}`,400);let T=_.value;if(l!=="code")return yield*BE(T,"invalid_request","Only response_type=code is supported",u);if(g&&E!=="S256")return yield*BE(T,"invalid_request","code_challenge_method must be S256",u);if(w.isPublic&&(!g||E!=="S256"))return yield*BE(T,"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:S,redirectURI:T,audience:y},o)))return yield*Qe("unauthorized_client",`Client not allowed: ${S}`,400);let I={response_type:"code",redirect_uri:T,state:u,client_id:S,audience:y,pkce:g&&E?{challenge:g,method:"S256"}:void 0},O=[...r.staticProviders.keys()],L=O.includes("dummy"),Y=yield*r.listProviders,Z;if(c)if(O.includes(c))Z=`/oauth/${c}/authorize`;else if(Y.includes(c))Z=`/oauth/${c}/authorize`;else if(L)yield*lU.logWarning(`Provider '${c}' not found, falling back to dummy provider`),Z="/oauth/dummy/authorize";else return yield*BE(T,"invalid_request",`Provider '${c}' is not configured`,u);else if(O.length===1)Z=`/oauth/${O[0]}/authorize`;else return yield*BE(T,"invalid_request","Missing parameter: provider",u);let ee=yield*t.encrypt(I),ae=Bg(o.headers)==="https",ne=$g("authorization",ee,{maxAge:86400,httpOnly:!0,secure:ae,sameSite:ae?"none":"lax"});return cI(Z,{status:302}).pipe(lI("Set-Cookie",ne))});import{Effect as GJ}from"effect";var ybe={"Cache-Control":"public, max-age=3600, s-maxage=86400"},uU=GJ.gen(function*(){let e=yield*fc,t=yield*on,r=yield*ci(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*ka(i).pipe(GJ.map((s)=>Zh(s,ybe)))});import{Effect as QJ}from"effect";var hbe={"Cache-Control":"public, max-age=3600, s-maxage=86400"},pU=QJ.gen(function*(){let r={keys:(yield*(yield*Ln).allSigningKeys).map((n)=>({...n.jwk,alg:n.alg,exp:n.expired?Math.floor(n.expired.getTime()/1000):void 0}))};return yield*ka(r).pipe(QJ.map((n)=>Zh(n,hbe)))});import{Effect as JJ}from"effect";var fU=(e)=>JJ.gen(function*(){let t=e.get("token");if(!t)return yield*Qe("invalid_request","Missing token",400);let r=t.split(":"),n=r.pop(),o=r.join(":");if(o&&n)yield*wr.remove(["oauth:refresh",o,n]);else yield*JJ.logDebug("Token revocation: malformed token format");return yield*ka({success:!0})});import{Effect as bbe}from"effect";import{Effect as $E}from"effect";import{timingSafeEqual as gbe}from"crypto";function YJ(e,t){if(typeof e!=="string"||typeof t!=="string")return!1;if(e.length!==t.length)return!1;return gbe(Buffer.from(e),Buffer.from(t))}async function Sbe(e,t){if(t==="plain")return e;let n=new TextEncoder().encode(e),o=await crypto.subtle.digest("SHA-256",n);return uo(new Uint8Array(o))}async function XJ(e,t,r="S256"){let n=await Sbe(e,r);return YJ(n,t)}var SP=(e)=>$E.gen(function*(){let t=e.get("code");if(!t)return yield*Qe("invalid_request","Missing code",400);let r=e.get("redirect_uri");if(!r)return yield*Qe("invalid_request","Missing redirect_uri",400);let n=yield*ol(e).pipe($E.catchTag("processfocus:internal-tag/openauth/ClientAuthError",(y)=>$E.succeed({error:y})));if("error"in n)return yield*Lm(n.error.description);let{client:o}=n,i=aU(r);if(!i.ok)return yield*Qe("invalid_redirect_uri","Redirect URI mismatch",400);let s=i.value,a=["oauth:code",t],c=yield*wr.get(a);if(!c)return yield*Qe("invalid_grant","Authorization code has been used or expired",400);if(c.redirectURI!==s)return yield*Qe("invalid_redirect_uri","Redirect URI mismatch",400);let l=e.get("client_id");if(l&&l!==o.id)return yield*Qe("unauthorized_client","Client is not authorized to use this authorization code",403);if(c.clientID!==o.id)return yield*Qe("unauthorized_client","Client is not authorized to use this authorization code",403);if(o.isPublic&&!c.pkce)return yield*Qe("invalid_grant","PKCE is required for this client",400);if(c.pkce){let y=e.get("code_verifier");if(!y)return yield*Qe("invalid_grant","Missing code_verifier",400);if(!(yield*$E.promise(()=>XJ(y,c.pkce.challenge,c.pkce.method)).pipe($E.withSpan("auth.validatePKCE"))))return yield*Qe("invalid_grant","Code verifier does not match",400)}let d=yield*Gl({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*wr.remove(a);let{refresh:u,refreshExpiresIn:p}=d;if(!u||p===void 0)return yield*new Fm({message:"Invariant violation: authorization_code flow must issue a refresh token"});return yield*Um({access_token:d.access,expires_in:d.expiresIn,refresh_token:u,refresh_expires_in:p})});import{Effect as mU}from"effect";var vP=(e)=>mU.gen(function*(){let t=yield*fc,r=yield*ol(e).pipe(mU.catchTag("processfocus:internal-tag/openauth/ClientAuthError",(i)=>mU.succeed({error:i})));if("error"in r)return yield*Lm(r.error.description);let{client:n}=r;if(n.isPublic)return yield*Qe("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*Qe("invalid_request","Invalid provider parameter",400);return{needsUpstreamProvider:!0,provider:o,clientId:n.id,clientAudience:n.audience}});import{Clock as yU,Effect as Bp,Option as Ebe}from"effect";import{Context as ZJ,Layer as QZe}from"effect";class Lp extends ZJ.Tag("processfocus:internal-tag/openauth/TokenTtlConfig")(){}class qg extends ZJ.Tag("processfocus:internal-tag/openauth/SubjectsConfig")(){}import{Context as vbe,Effect as il,Layer as e6,Stream as xbe}from"effect";class pu extends vbe.Tag("processfocus:internal-tag/openauth/CookieAuthService")(){}var xP=e6.effect(pu,il.gen(function*(){let e=yield*uu,t=yield*Zr,r=e6.succeed(Zr,t);return{set:(n,o,i,s)=>il.gen(function*(){let a=yield*e.encrypt(i);return $g(n,a,{maxAge:o,httpOnly:!0,secure:s,sameSite:s?"none":"lax"})}),get:(n,o)=>il.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(il.tapError((a)=>il.logError("Failed to decrypt cookie").pipe(il.annotateLogs({key:o,error:a}))),il.orElseSucceed(()=>{return}))}),unset:(n)=>il.succeed($g(n,"",{maxAge:0,expires:new Date(0)})),invalidate:(n)=>il.gen(function*(){let o=[];yield*wr.scan(["oauth:refresh",n]).pipe(xbe.runForEach(([i])=>il.sync(()=>{o.push(i)})));for(let i of o)yield*wr.remove(i)}).pipe(il.provide(r))}}));var EP=(e)=>Bp.gen(function*(){let t=yield*Lp,r=yield*pu,n=yield*Ql,o=e.get("refresh_token");if(!o)return yield*Qe("invalid_request","Missing refresh_token",400);let i=yield*ol(e).pipe(Bp.catchTag("processfocus:internal-tag/openauth/ClientAuthError",(I)=>Bp.succeed({error:I})));if("error"in i)return yield*Lm(i.error.description);let{client:s}=i,a=o.split(":"),c=a.pop(),l=a.join(":"),d=["oauth:refresh",l,c],u=yield*wr.get(d);if(!u)return yield*Qe("invalid_grant","Refresh token has been used or expired",400);if(u.clientID!==s.id)return yield*Qe("unauthorized_client","Client is not authorized to use this refresh token",403);let p=yield*yU.currentTimeMillis;if(u.expiresAt!==void 0&&(!Number.isFinite(u.expiresAt)||p>=u.expiresAt))return yield*wr.remove(d),yield*Qe("invalid_grant","Credential expired",400);if(n.onRefresh){let I=yield*n.onRefresh({type:u.type,properties:u.properties,clientId:s.id,scope:e.get("scope")}).pipe(Bp.option);if(Ebe.isNone(I))return yield*Qe("invalid_grant","Session is no longer valid",400);u={...u,properties:I.value.properties}}let{refreshReuse:y,refreshRetention:g}=t,E=!u.timeUsed;if(y<=0)yield*wr.remove(d);else if(!u.timeUsed){let I=yield*yU.currentTimeMillis,O={...u,timeUsed:I};yield*wr.set(d,O,y+g)}else if((yield*yU.currentTimeMillis)>u.timeUsed+y*1000)return yield*r.invalidate(l),yield*Qe("invalid_grant","Refresh token has been used or expired",400);let S=e.get("scope"),x=u,w;if(S&&n.onRefreshScope){let I=u.properties.userId;if(!I)return yield*Qe("invalid_scope","Cannot determine user for scope validation",400);let O=yield*n.onRefreshScope({userId:I,clientId:s.id,scope:S,currentProperties:u.properties}).pipe(Bp.map((L)=>({success:!0,...L})),Bp.catchAll(()=>Bp.succeed({success:!1})));if(!O.success)return yield*Qe("invalid_scope","Failed to process scope request",400);x={...u,properties:O.properties},w=O.accessTokenTtl}let _=yield*Gl({type:x.type,properties:x.properties,subject:x.subject,clientID:x.clientID,audience:x.audience,ttl:x.ttl,expiresAt:x.expiresAt,accessTtlOverride:w,timeUsed:u.timeUsed,nextToken:u.nextToken},{generateRefreshToken:E,allowExistingRefreshToken:!E}),{refresh:T,refreshExpiresIn:b}=_;if(!T||b===void 0)return yield*new Fm({message:"Invariant violation: refresh_token flow must issue a refresh token"});return yield*Um({access_token:_.access,refresh_token:T,expires_in:_.expiresIn,refresh_expires_in:b})}).pipe(Bp.catchTag("processfocus:internal-tag/openauth/OAuthEndpointError",(t)=>Qe(t.error,t.description,t.statusCode)));var hU=(e)=>bbe.gen(function*(){let t=e.get("grant_type");if(t==="authorization_code")return yield*SP(e);if(t==="refresh_token")return yield*EP(e);if(t==="client_credentials"){let r=yield*vP(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*Qe("unsupported_grant_type","Invalid grant_type",400)});import{Effect as bP,Either as wbe}from"effect";var gU=bP.gen(function*(){let e=yield*Ln,t=yield*Ii,r=yield*qg,n=yield*on,o=n.headers.authorization;if(!o)return yield*Qe("invalid_request","Missing Authorization header",400);let[i,s]=o.split(" ");if(i!=="Bearer")return yield*Qe("invalid_request","Missing or invalid Authorization header",400);if(!s)return yield*Qe("invalid_request","Missing token",400);let a=[...t.configuredClientIds],c=yield*e.signingKey,l=yield*ci(n.headers),d=yield*bP.tryPromise({try:()=>uc(s,()=>Promise.resolve(c.public),{issuer:l,audience:a}),catch:(E)=>new XF({message:"Access token verification failed",cause:E})}).pipe(bP.either);if(wbe.isLeft(d))return yield*Qe("invalid_token","Invalid token",401);let u=d.right,p=r[u.payload.type];if(!p)return yield*Qe("invalid_token","Invalid token",401);let y=p["~standard"].validate(u.payload.properties),g=yield*bP.promise(async()=>y instanceof Promise?y:y);if(!g.issues&&u.payload.mode==="access")return yield*ka(g.value);return yield*Qe("invalid_token","Invalid token",401)});import{Effect as Tbe}from"effect";var t6=(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},qE=(e={})=>DO((t)=>Tbe.gen(function*(){let r=yield*on,n=r.headers.origin;if(r.method==="OPTIONS"){let s=t6(n,e);return aI({status:204}).pipe(Zh(s))}let o=yield*t,i=t6(n,e);return Zh(o,i)}));import{Effect as Abe}from"effect";var wP={"X-Content-Type-Options":"nosniff","Referrer-Policy":"no-referrer","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'; frame-ancestors 'none'; sandbox"},r6=DO((e)=>Abe.gen(function*(){let t=yield*e,r={},n=t.headers;if(!n["x-content-type-options"])r["X-Content-Type-Options"]=wP["X-Content-Type-Options"];if(!n["referrer-policy"])r["Referrer-Policy"]=wP["Referrer-Policy"];if(!n["x-frame-options"])r["X-Frame-Options"]=wP["X-Frame-Options"];if(!n["content-security-policy"])r["Content-Security-Policy"]=wP["Content-Security-Policy"];return Zh(t,r)}));import{Data as Ibe,Effect as Rbe}from"effect";class n6 extends Ibe.TaggedError("processfocus:internal-tag/openauth/ProviderCallbackError"){}var SU=(e,t)=>Rbe.tryPromise({try:t,catch:(r)=>new n6({message:e,cause:r})});class s6 extends Pbe.TaggedError("processfocus:internal-tag/openauth/ResolveIssuerClientsError"){}function _be(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 i6=(e,t,r,n,o)=>({name:e,invalidate:(i)=>r.invalidate(i),success:(i)=>Yt.gen(function*(){let s=yield*on,a=s.headers.cookie??"",c=yield*r.get(a,"authorization");if(!c)return yield*Qe("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(p,y,g){return Yt.gen(function*(){let E=g?.subject??(yield*t.resolveSubject(p,y)),S=n.staticClients.get(c.client_id);yield*wr.set(["oauth:code",l],{type:p,properties:y,clientID:c.client_id,redirectURI:c.redirect_uri,subject:E,audience:c.audience??S?.audience,ttl:{access:g?.ttl?.access??o.access,refresh:g?.ttl?.refresh??o.refresh},pkce:c.pkce},600);let x=new URL(c.redirect_uri);if(x.searchParams.set("code",l),c.state)x.searchParams.set("state",c.state);let w=yield*r.unset("authorization");return cI(x.toString(),{status:302}).pipe(lI("Set-Cookie",w))})},error(p,y){return Yt.gen(function*(){let g=new URL(c.redirect_uri);if(g.searchParams.set("error",p),g.searchParams.set("error_description",y),c.state)g.searchParams.set("state",c.state);let E=yield*r.unset("authorization");return cI(g.toString(),{status:302}).pipe(lI("Set-Cookie",E))})}},d,s)}),setCookie:(i,s,a)=>Yt.gen(function*(){let c=yield*on,l=Bg(c.headers)==="https";return yield*r.set(i,s,a,l)}),getCookie:(i)=>Yt.gen(function*(){let a=(yield*on).headers.cookie??"";return yield*r.get(a,i)}),deleteCookie:(i)=>r.unset(i)}),a6=Yt.gen(function*(){let e=yield*Ii,t=yield*pu,r=yield*fc,n=yield*Lp,o=yield*Ql,i=new Set;for(let x of e.staticClients.values())for(let w of x.corsOrigins)i.add(_be(w));let s=(x,w,_,T,b,I)=>Gl({type:_,properties:T,subject:b,clientID:x,audience:w,ttl:I,timeUsed:void 0,nextToken:void 0},{generateRefreshToken:!1}),a=rg("/.well-known/jwks.json",pU.pipe(qE({origin:"*",allowMethods:["GET"]}))),c=rg("/.well-known/oauth-authorization-server",uU.pipe(Yt.catchTag("processfocus:internal-tag/openauth/MissingHostError",(x)=>Qe("server_error",x.description,500)),qE({origin:"*",allowMethods:["GET"]}))),l=rg("/oauth/authorize",dU),d=tc("/oauth/token",Yt.gen(function*(){let x=yield*on;if(!(x.headers["content-type"]??"").includes("application/x-www-form-urlencoded"))return yield*Qe("invalid_request","Content-Type must be application/x-www-form-urlencoded",415);let _=yield*x.urlParamsBody,T=new Map;for(let[I,O]of _)T.set(I,O);let b=yield*hU(T);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(O,L,Y){return Yt.gen(function*(){let Z=Y?.subject??(yield*o.resolveSubject(O,L)),ee=yield*s(b.clientId,b.clientAudience,O,L,Z,{access:Y?.ttl?.access??n.access,refresh:Y?.ttl?.refresh??n.refresh});return yield*Um({access_token:ee.access,expires_in:ee.expiresIn})})},error(O,L){return Qe(O,L,400)}},{provider:"credentials",clientID:b.clientId,scope:b.scope},x);if(b.type==="client_credentials_upstream"){let I=yield*r.resolveProvider(b.provider);if(!I)return yield*Qe("invalid_request","Invalid provider parameter",400);if(!I.client)return yield*Qe("invalid_request","Provider does not support client_credentials",400);let O=T.get("provider_client_id")??T.get("client_id"),L=T.get("provider_client_secret")??T.get("client_secret");if(!O||!L)return yield*Qe("invalid_request","Missing client credentials for upstream provider",400);let Y=yield*SU("Provider client credentials callback failed",()=>I.client({clientID:O,clientSecret:L,params:Object.fromEntries(T)})).pipe(Yt.either);if(Cbe.isLeft(Y)){let ne=Y.left;return yield*Yt.logError("Provider client callback failed").pipe(Yt.annotateLogs({message:ne.message,cause:String(ne.cause)})),yield*Qe("server_error","Authentication provider callback failed",500)}let Z=Y.right,ee=typeof Z==="object"&&Z!==null?{provider:b.provider,...Z}:{provider:b.provider};return yield*o.success({subject(ne,le,ie){return Yt.gen(function*(){let je=ie?.subject??(yield*o.resolveSubject(ne,le)),ft=yield*s(b.clientId,b.clientAudience,ne,le,je,{access:ie?.ttl?.access??n.access,refresh:ie?.ttl?.refresh??n.refresh});return yield*Um({access_token:ft.access,expires_in:ft.expiresIn})})},error(ne,le){return Qe(ne,le,400)}},ee,x)}}return yield*Qe("server_error","Unknown token endpoint result",500)}).pipe(i.size>0?qE({origin:Array.from(i),allowHeaders:["Content-Type","Authorization"],allowMethods:["POST"]}):(x)=>x)),u=rg("/oauth/userinfo",gU.pipe(Yt.catchTag("processfocus:internal-tag/openauth/MissingHostError",(x)=>Qe("server_error",x.description,500)))),p=tc("/oauth/revoke",Yt.gen(function*(){let w=yield*(yield*on).urlParamsBody,_=new Map;for(let[T,b]of w)_.set(T,b);return yield*fU(_)}).pipe(qE({origin:"*",allowMethods:["POST"]}))),y=due.pipe(a,c,l,d,u,p);for(let[x,w]of r.staticProviders){let _=i6(x,o,t,e,n),T=w.init(_),b=`/oauth/${x}`,I=T.pipe(BO((O)=>Yt.gen(function*(){let L=yield*on,Y=new URL(L.url,"http://localhost").pathname,Z=`${b}${Y}`,ee=L.modify({headers:Jd({...L.headers,"x-original-path":Z})});return yield*O.pipe(Yt.provideService(on,ee),Yt.catchTag("processfocus:internal-tag/openauth/ProviderCallbackError",(ae)=>Yt.gen(function*(){return yield*Yt.logError("Provider callback failed").pipe(Yt.annotateLogs({providerName:x,message:ae.message,cause:String(ae.cause)})),yield*Qe("server_error","Authentication provider callback failed",500)})))})));y=y.pipe(uue(b,I))}let g=new Map,S=Yt.gen(function*(){let x=yield*on,w=yield*ci(x.headers),_=new URL(x.url,w),T=_.pathname.split("/").filter(Boolean);if(T.length<2||T[0]!=="oauth")return yield*Xh("Provider not found",{status:404});let b=T[1];if(!b)return yield*Xh("Provider not found",{status:404});if(r.hasProvider(b))return yield*Xh("Not found",{status:404});let I=g.get(b);if(!I){let le=yield*r.resolveProvider(b);if(!le)return yield*Xh(`Provider '${b}' not found`,{status:404});I=le,g.set(b,I)}let O=i6(b,o,t,e,n),L=I.init(O),Y=`/${T.slice(2).join("/")}`;yield*Yt.log("Dynamic provider handling").pipe(Yt.annotateLogs({providerName:b,subPath:Y,originalUrl:_.toString()}));let Z=new URL(Y,w);Z.search=_.search;let ee=Jd({...x.headers,"x-original-path":_.pathname}),ae=x.modify({url:Z.toString(),headers:ee}),ne=yield*L.pipe(Yt.provideService(on,ae),Yt.catchTag("processfocus:internal-tag/openauth/ProviderCallbackError",(le)=>Yt.gen(function*(){return yield*Yt.logError("Provider callback failed").pipe(Yt.annotateLogs({providerName:b,subPath:Y,message:le.message,cause:String(le.cause)})),yield*Qe("server_error","Authentication provider callback failed",500)})),Yt.catchAllCause((le)=>Yt.gen(function*(){return yield*Yt.logError("Dynamic provider handler error").pipe(Yt.annotateLogs({providerName:b,subPath:Y,cause:le.toString()})),Xh("Internal server error",{status:500})})));return yield*Yt.log("Dynamic provider response").pipe(Yt.annotateLogs({providerName:b,status:ne.status})),ne}).pipe(Yt.catchTag("processfocus:internal-tag/openauth/MissingHostError",(x)=>Qe("server_error",x.description,500)));return y=y.pipe(rg("/oauth/:provider/authorize",S),rg("/oauth/:provider/callback",S),tc("/oauth/:provider/callback",S),tc("/oauth/:provider/challenge",S),tc("/oauth/:provider/verify",S),tc("/oauth/:provider/register",S),tc("/oauth/:provider/register-options",S),tc("/oauth/:provider/register-verify",S),tc("/oauth/:provider/authenticate",S),tc("/oauth/:provider/auth-options",S),tc("/oauth/:provider/auth-verify",S),tc("/oauth/:provider/registration-session-exchange",S)),y.pipe(BO((x)=>Yt.gen(function*(){let w=yield*on;if(Bg(w.headers)===void 0)return yield*Qe("invalid_request","Invalid forwarded protocol header",400);return yield*x})),BO(r6))});import{Effect as btt}from"effect";import{Effect as Dtt}from"effect";var c6=(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},Obe=c6("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Nbe=c6("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Fbe=/^[-A-Za-z0-9\-_]*$/,Ube=/^[-A-Za-z0-9+/]*={0,3}$/,Jl={};Jl.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),p=t?Nbe:Obe;for(o=0;o<r;o+=4)s=p[e.charCodeAt(o)],a=p[e.charCodeAt(o+1)],c=p[e.charCodeAt(o+2)],l=p[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};Jl.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};Jl.toString=(e,t)=>new TextDecoder().decode(Jl.toArrayBuffer(e,t));Jl.fromString=(e,t)=>Jl.fromArrayBuffer(new TextEncoder().encode(e),t);Jl.validate=(e,t)=>{if(!(typeof e==="string"||e instanceof String))return!1;try{return t?Fbe.test(e):Ube.test(e)}catch(r){return!1}};Jl.base64=Jl;var qp=Jl;function jg(e,t="base64url"){let r=qp.toArrayBuffer(e,t==="base64url");return new Uint8Array(r)}function Yl(e,t="base64url"){let r=new Uint8Array(e);return qp.fromArrayBuffer(r.buffer,t==="base64url")}function Mbe(e){let t=qp.toArrayBuffer(e,!0);return qp.fromArrayBuffer(t)}function Hg(e){return qp.toString(e,!0)}function Lbe(e){return qp.validate(e,!1)}function l6(e){return e=d6(e),qp.validate(e,!0)}function d6(e){return e.replace(/=/g,"")}function Wg(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 TP=0,jE=1,RU=2,PU=3,CU=4,_U=5,kU=6,u6=7;function Xl(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==jE){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 IP{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 p6(e,t,r){return Wg(e,t,r)}function Bbe(e,t,r){let[n,o]=p6(e,t,r);return[-n-1,o]}function f6(e,t,r){let[n,o]=Wg(e,t,r),i=r+o;return[new Uint8Array(e.buffer.slice(i,i+n)),o+n]}var $be=new TextDecoder;function qbe(e,t,r){let[n,o]=f6(e,t,r);return[$be.decode(n),o]}function jbe(e,t,r){if(t===0)return[[],1];let[n,o]=Wg(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]=$m(e,r+i);s.push(l),i+=d}return[s,i]}var AP="Map is not supported or well formed";function Hbe(e,t,r){if(t===0)return[new Map,1];let[n,o]=Wg(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(AP);let[l,d]=$m(e,r+i);if(i+=d,c-=d,c<=0)throw Error(AP);if(typeof l!=="string"&&typeof l!=="number")throw Error(AP);if(s.has(l))throw Error(AP);let[u,p]=$m(e,r+i);i+=p,s.set(l,u)}return[s,i]}function Wbe(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 Vbe(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 zbe(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 Kbe(e,t,r){let[n,o]=Wg(e,t,r),[i,s]=$m(e,r+o);return[new IP(n,i),o+s]}function $m(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 TP:return p6(e,o,t);case jE:return Bbe(e,o,t);case RU:return f6(e,o,t);case PU:return qbe(e,o,t);case CU:return jbe(e,o,t);case _U:return Hbe(e,o,t);case kU:return Kbe(e,o,t);case u6: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 Wbe(e,t);case 26:return Vbe(e,t);case 27:return zbe(e,t)}}throw Error(`Unsupported or not well formed at ${t}`)}function Gbe(e){if(e===!0)return 245;else if(e===!1)return 244;else if(e===null)return 246;return 247}function Qbe(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 Jbe(e){if(typeof e=="number"){if(Number.isSafeInteger(e))if(e<0)return Xl(jE,Math.abs(e));else return Xl(TP,e);return[Qbe(e)]}else if(e<0n)return Xl(jE,e*-1n);else return Xl(TP,e)}var Ybe=new TextEncoder;function Xbe(e,t){t.push(...Xl(PU,e.length)),t.push(Ybe.encode(e))}function Zbe(e,t){t.push(...Xl(RU,e.length)),t.push(e)}function ewe(e,t){t.push(...Xl(CU,e.length));for(let r of e)HE(r,t)}function twe(e,t){t.push(new Uint8Array(Xl(_U,e.size)));for(let[r,n]of e.entries())HE(r,t),HE(n,t)}function rwe(e,t){t.push(...Xl(kU,e.tag)),HE(e.value,t)}function HE(e,t){if(typeof e=="boolean"||e===null||e==null){t.push(Gbe(e));return}if(typeof e=="number"||typeof e=="bigint"){t.push(...Jbe(e));return}if(typeof e=="string"){Xbe(e,t);return}if(e instanceof Uint8Array){Zbe(e,t);return}if(Array.isArray(e)){ewe(e,t);return}if(e instanceof Map){twe(e,t);return}if(e instanceof IP){rwe(e,t);return}throw Error("Not implemented")}function DU(e,t){if(e.byteLength===0||e.byteLength<=t||t<0)throw Error("No data");if(e instanceof Uint8Array)return $m(new DataView(e.buffer),t);else if(e instanceof ArrayBuffer)return $m(new DataView(e),t);return $m(e,t)}function OU(e){let t=[];HE(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 Vg(e){let t=new Uint8Array(e),r=DU(t,0),[n]=r;return n}function m6(e){return OU(e)}function y6(e){let t=e.get(ht.kty);return NU(t)&&t===Da.OKP}function jp(e){let t=e.get(ht.kty);return NU(t)&&t===Da.EC2}function Kg(e){let t=e.get(ht.kty);return NU(t)&&t===Da.RSA}var ht;(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"})(ht||(ht={}));var Da;(function(e){e[e.OKP=1]="OKP",e[e.EC2=2]="EC2",e[e.RSA=3]="RSA"})(Da||(Da={}));function NU(e){return Object.values(Da).indexOf(e)>=0}var $i;(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"})($i||($i={}));function h6(e){return Object.values($i).indexOf(e)>=0}var vt;(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"})(vt||(vt={}));function Zl(e){return Object.values(vt).indexOf(e)>=0}function Hp(e){if([vt.RS1].indexOf(e)>=0)return"SHA-1";else if([vt.ES256,vt.PS256,vt.RS256].indexOf(e)>=0)return"SHA-256";else if([vt.ES384,vt.PS384,vt.RS384].indexOf(e)>=0)return"SHA-384";else if([vt.ES512,vt.PS512,vt.RS512,vt.EdDSA].indexOf(e)>=0)return"SHA-512";throw Error(`Could not map COSE alg value of ${e} to a WebCrypto alg`)}var WE=void 0;function mc(){return new Promise((t,r)=>{if(WE)return t(WE);let n=iwe.stubThisGlobalThisCrypto();if(n)return WE=n,t(WE);return r(new g6)})}class g6 extends Error{constructor(){super("An instance of the Crypto API could not be located");this.name="MissingWebCrypto"}}var iwe={stubThisGlobalThisCrypto:()=>globalThis.crypto,setCachedCrypto:(e)=>{WE=e}};async function S6(e,t){let r=await mc(),n=Hp(t),o=await r.subtle.digest(n,e);return new Uint8Array(o)}async function FU(e){return(await mc()).getRandomValues(e),e}async function Gg(e){let t=await mc(),{keyData:r,algorithm:n}=e;return t.subtle.importKey("jwk",r,n,!1,["verify"])}async function RP(e){let{cosePublicKey:t,signature:r,data:n,shaHashOverride:o}=e,i=await mc(),s=t.get(ht.alg),a=t.get(ht.crv),c=t.get(ht.x),l=t.get(ht.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===$i.P256)d="P-256";else if(a===$i.P384)d="P-384";else if(a===$i.P521)d="P-521";else throw Error(`Unexpected COSE crv value of ${a} (EC2)`);let u={kty:"EC",crv:d,x:Yl(c),y:Yl(l),ext:!1},y=await Gg({keyData:u,algorithm:{name:"ECDSA",namedCurve:d}}),g=Hp(s);if(o)g=Hp(o);let E={name:"ECDSA",hash:{name:g}};return i.subtle.verify(E,y,r,n)}function UU(e){if([vt.EdDSA].indexOf(e)>=0)return"Ed25519";else if([vt.ES256,vt.ES384,vt.ES512,vt.ES256K].indexOf(e)>=0)return"ECDSA";else if([vt.RS256,vt.RS384,vt.RS512,vt.RS1].indexOf(e)>=0)return"RSASSA-PKCS1-v1_5";else if([vt.PS256,vt.PS384,vt.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 PP(e){let{cosePublicKey:t,signature:r,data:n,shaHashOverride:o}=e,i=await mc(),s=t.get(ht.alg),a=t.get(ht.n),c=t.get(ht.e);if(!s)throw Error("Public key was missing alg (RSA)");if(!Zl(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:Yl(a),e:Yl(c),ext:!1},d={name:UU(s),hash:{name:Hp(s)}},u={name:UU(s)};if(o)d.hash.name=Hp(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 y=0;if(d.hash.name==="SHA-256")l.alg="PS256",y=32;else if(d.hash.name==="SHA-384")l.alg="PS384",y=48;else if(d.hash.name==="SHA-512")l.alg="PS512",y=64;u.saltLength=y}else throw Error(`Unexpected RSA key algorithm ${s} (${d.name})`);let p=await Gg({keyData:l,algorithm:d});return i.subtle.verify(u,p,r,n)}function CP(e){let t=_P(e);return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20,32)].join("-")}function Ro(e){let t;if(typeof e==="string")if(l6(e))t=Mbe(e);else if(Lbe(e))t=e;else throw Error("Certificate is not a valid base64 or base64url string");else t=Yl(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)}
|
|
424
|
+
`}return r=`-----BEGIN CERTIFICATE-----
|
|
425
|
+
${r}-----END CERTIFICATE-----
|
|
426
|
+
`,r}function Qg(e){let t=Vg(e),r=Uint8Array.from([4]),n=t.get(ht.x),o=t.get(ht.y);if(!n)throw Error("COSE public key was missing x");if(o)return yc([r,n,o]);return yc([r,n])}function v6(e){return swe.stubThis(Vg(e))}var swe={stubThis:(e)=>e};function MU(e){let t=Hg(e),r=JSON.parse(t);return awe.stubThis(r)}var awe={stubThis:(e)=>e};function Wp(e){return cwe.stubThis(Vg(e))}var cwe={stubThis:(e)=>e};async function x6(){let e=new Uint8Array(32);return await FU(e),lwe.stubThis(e)}var lwe={stubThis:(e)=>e};var id={};cq(id,{Any:()=>yu,BaseBlock:()=>Po,BaseStringBlock:()=>MP,BitString:()=>od,BmpString:()=>tS,Boolean:()=>Yg,CharacterString:()=>dS,Choice:()=>YE,Constructed:()=>Ko,DATE:()=>qP,DEFAULT_MAX_CONTENT_LENGTH:()=>O6,DEFAULT_MAX_DEPTH:()=>k6,DEFAULT_MAX_NODES:()=>D6,DateTime:()=>HP,Duration:()=>WP,EndOfContent:()=>BP,Enumerated:()=>Xg,GeneralString:()=>lS,GeneralizedTime:()=>uS,GraphicString:()=>cS,HexBlock:()=>td,IA5String:()=>aS,Integer:()=>Gp,Null:()=>rd,NumericString:()=>nS,ObjectIdentifier:()=>Zg,OctetString:()=>nd,Primitive:()=>Kp,PrintableString:()=>oS,RawData:()=>d8,RelativeObjectIdentifier:()=>eS,Repeated:()=>Jg,Sequence:()=>vs,Set:()=>Qs,TIME:()=>VP,TeletexString:()=>iS,TimeOfDay:()=>jP,UTCTime:()=>Hm,UniversalString:()=>rS,Utf8String:()=>al,ValueBlock:()=>Ri,VideotexString:()=>sS,ViewWriter:()=>QE,VisibleString:()=>jm,compareSchema:()=>fu,fromBER:()=>gu,verifySchema:()=>Owe});/*!
|
|
427
|
+
* MIT License
|
|
428
|
+
*
|
|
429
|
+
* Copyright (c) 2017-2024 Peculiar Ventures, LLC
|
|
430
|
+
*
|
|
431
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
432
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
433
|
+
* in the Software without restriction, including without limitation the rights
|
|
434
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
435
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
436
|
+
* furnished to do so, subject to the following conditions:
|
|
437
|
+
*
|
|
438
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
439
|
+
* copies or substantial portions of the Software.
|
|
440
|
+
*
|
|
441
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
442
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
443
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
444
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
445
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
446
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
447
|
+
* SOFTWARE.
|
|
448
|
+
*
|
|
449
|
+
*/class Te{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=Te.toUint8Array(e),n=Te.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 LU="string",dwe=/^[0-9a-f\s]+$/i,uwe=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,pwe=/^[a-zA-Z0-9-_]+$/;class BU{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=Te.toUint8Array(e),r="";for(let o=0;o<t.length;o++)r+=String.fromCharCode(t[o]);return decodeURIComponent(escape(r))}}class sl{static toString(e,t=!1){let r=Te.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 Le{static isHex(e){return typeof e===LU&&dwe.test(e)}static isBase64(e){return typeof e===LU&&uwe.test(e)}static isBase64Url(e){return typeof e===LU&&pwe.test(e)}static ToString(e,t="utf8"){let r=Te.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 sl.toString(r,!0);case"utf16":case"utf16be":return sl.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 sl.fromString(e,!0);case"utf16":case"utf16be":return sl.fromString(e);default:throw Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Te.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(!Le.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(!Le.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=Le.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return BU.fromString(e);case"utf16":case"utf16be":return sl.fromString(e);case"utf16le":case"usc2":return sl.fromString(e,!0);default:throw Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=Le.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return BU.toString(e);case"utf16":case"utf16be":return sl.toString(e);case"utf16le":case"usc2":return sl.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=Te.toUint8Array(e),r="";for(let n=0;n<t.length;n++)r+=String.fromCharCode(t[n]);return r}static ToHex(e){let t=Te.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(!Le.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 sl.toString(e,t)}static FromUtf16String(e,t=!1){return sl.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,""))||""}}Le.DEFAULT_UTF8_ENCODING="utf8";function E6(...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 kP(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}/*!
|
|
450
|
+
Copyright (c) Peculiar Ventures, LLC
|
|
451
|
+
*/function qm(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 Vp(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 DP(...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 $U(){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=qm(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,qm(i,8)-n}function b6(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=Vp(s,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Vp(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 w6(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 Ks(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 Frt=Math.log(2);/*!
|
|
452
|
+
* Copyright (c) 2014, GMO GlobalSign
|
|
453
|
+
* Copyright (c) 2015-2022, Peculiar Ventures
|
|
454
|
+
* All rights reserved.
|
|
455
|
+
*
|
|
456
|
+
* Author 2014-2019, Yury Strozhevsky
|
|
457
|
+
*
|
|
458
|
+
* Redistribution and use in source and binary forms, with or without modification,
|
|
459
|
+
* are permitted provided that the following conditions are met:
|
|
460
|
+
*
|
|
461
|
+
* * Redistributions of source code must retain the above copyright notice, this
|
|
462
|
+
* list of conditions and the following disclaimer.
|
|
463
|
+
*
|
|
464
|
+
* * Redistributions in binary form must reproduce the above copyright notice, this
|
|
465
|
+
* list of conditions and the following disclaimer in the documentation and/or
|
|
466
|
+
* other materials provided with the distribution.
|
|
467
|
+
*
|
|
468
|
+
* * Neither the name of the copyright holder nor the names of its
|
|
469
|
+
* contributors may be used to endorse or promote products derived from
|
|
470
|
+
* this software without specific prior written permission.
|
|
471
|
+
*
|
|
472
|
+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
|
473
|
+
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
474
|
+
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
475
|
+
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
|
476
|
+
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
|
477
|
+
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
|
478
|
+
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
|
479
|
+
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
480
|
+
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
|
481
|
+
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
482
|
+
*
|
|
483
|
+
*/function OP(){if(typeof BigInt>"u")throw Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function jU(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 hu(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 QE{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return jU(this.items)}}var zE=[new Uint8Array([1])],T6="0123456789",qU="name",A6="valueHexView",ywe="isHexOnly",hwe="idBlock",gwe="tagClass",Swe="tagNumber",vwe="isConstructed",xwe="fromBER",Ewe="toBER",bwe="local",Gs="",ed=new ArrayBuffer(0),UP=new Uint8Array(0),GE="EndOfContent",R6="OCTET STRING",P6="BIT STRING";function td(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?Te.toUint8Array(i.valueHex):UP}fromBER(n,o,i,s){let a=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!hu(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",ed;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:Le.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}class zp{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=Gs,warnings:r=[],valueBeforeDecode:n=UP}={}){this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=Te.toUint8Array(n)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:Le.ToHex(this.valueBeforeDecodeView)}}}zp.NAME="baseBlock";class Ri extends zp{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'")}}Ri.NAME="valueBlock";class HU extends td(zp){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?Te.toUint8Array(e.valueHex):UP,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",ed}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=Vp(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=Te.toUint8Array(e);if(!hu(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=qm(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}}}HU.NAME="identificationBlock";class WU extends zp{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=Te.toUint8Array(e);if(!hu(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=qm(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=Vp(this.length,8);if(n.byteLength>127)return this.error="Too big length",ed;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}}}WU.NAME="lengthBlock";var Be={};class Po extends zp{constructor({name:e=Gs,optional:t=!1,primitiveSchema:r,...n}={},o){super(n);if(this.name=e,this.optional=t,r)this.primitiveSchema=r;this.idBlock=new HU(n),this.lenBlock=new WU(n),this.valueBlock=o?new o(n):new Ri(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 QE;if(!t)C6(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 ed}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 Le.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,t=Le.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 w6(t,r)}}Po.NAME="BaseBlock";function C6(e){var t;if(e instanceof Be.Constructed){for(let r of e.valueBlock.value)if(C6(r))e.lenBlock.isIndefiniteForm=!0}return!!((t=e.lenBlock)===null||t===void 0?void 0:t.isIndefiniteForm)}class MP extends Po{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=Gs,...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}'`}}MP.NAME="BaseStringBlock";class VU extends td(Ri){constructor({isHexOnly:e=!0,...t}={}){super(t);this.isHexOnly=e}}VU.NAME="PrimitiveValueBlock";var _6;class Kp extends Po{constructor(e={}){super(e,VU);this.idBlock.isConstructed=!1}}_6=Kp;(()=>{Be.Primitive=_6})();Kp.NAME="PRIMITIVE";var k6=100,D6=1e4,O6=16777216,wwe="Maximum ASN.1 nesting depth exceeded",Twe="Maximum ASN.1 node count exceeded",Awe="Maximum ASN.1 content length exceeded";function JE(e={}){var t,r,n;return{depth:0,maxDepth:(t=e.maxDepth)!==null&&t!==void 0?t:k6,nodesCount:0,maxNodes:(r=e.maxNodes)!==null&&r!==void 0?r:D6,maxContentLength:(n=e.maxContentLength)!==null&&n!==void 0?n:O6}}function Iwe(e){let t=new Po({},Ri);return t.error=e,{offset:-1,result:t}}function Rwe(e){if(e.nodesCount+=1,e.nodesCount>e.maxNodes)return Twe;return}function Pwe(e,t){if(e>t.maxContentLength)return Awe;return}function zU(e,t,r,n){let o=n.depth+1;if(o>n.maxDepth)return Iwe(wwe);n.depth=o;try{return LP(e,t,r,n)}finally{n.depth-=1}}function Cwe(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 LP(e,t=0,r=e.length,n=JE()){let o=t,i=new Po({},Ri),s=new zp;if(!hu(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=Rwe(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=Pwe(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 p=Po;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};p=Be.EndOfContent;break;case 1:p=Be.Boolean;break;case 2:p=Be.Integer;break;case 3:p=Be.BitString;break;case 4:p=Be.OctetString;break;case 5:p=Be.Null;break;case 6:p=Be.ObjectIdentifier;break;case 10:p=Be.Enumerated;break;case 12:p=Be.Utf8String;break;case 13:p=Be.RelativeObjectIdentifier;break;case 14:p=Be.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:p=Be.Sequence;break;case 17:p=Be.Set;break;case 18:p=Be.NumericString;break;case 19:p=Be.PrintableString;break;case 20:p=Be.TeletexString;break;case 21:p=Be.VideotexString;break;case 22:p=Be.IA5String;break;case 23:p=Be.UTCTime;break;case 24:p=Be.GeneralizedTime;break;case 25:p=Be.GraphicString;break;case 26:p=Be.VisibleString;break;case 27:p=Be.GeneralString;break;case 28:p=Be.UniversalString;break;case 29:p=Be.CharacterString;break;case 30:p=Be.BmpString;break;case 31:p=Be.DATE;break;case 32:p=Be.TimeOfDay;break;case 33:p=Be.DateTime;break;case 34:p=Be.Duration;break;default:{let y=i.idBlock.isConstructed?new Be.Constructed:new Be.Primitive;y.idBlock=i.idBlock,y.lenBlock=i.lenBlock,y.warnings=i.warnings,i=y}}break;case 2:case 3:case 4:default:p=i.idBlock.isConstructed?Be.Constructed:Be.Primitive}return i=Cwe(i,p),l=i.fromBER(e,t,d,n),i.valueBeforeDecodeView=e.subarray(o,o+i.blockLength),{offset:l,result:i}}function gu(e,t={}){if(!e.byteLength){let r=new Po({},Ri);return r.error="Input buffer has zero length",{offset:-1,result:r}}return LP(Te.toUint8Array(e).slice(),0,e.byteLength,JE(t))}function _we(e,t){if(e)return 1;return t}class mu extends Ri{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r);this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r,n){let o=Te.toUint8Array(e),i=n!==null&&n!==void 0?n:JE();if(!hu(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(_we(this.isIndefiniteForm,r)>0){let a=zU(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===GE)break}if(this.isIndefiniteForm)if(this.value[this.value.length-1].constructor.NAME===GE)this.value.pop();else this.warnings.push("No EndOfContent block encoded");return s}toBER(e,t){let r=t||new QE;for(let n=0;n<this.value.length;n++)this.value[n].toBER(e,r);if(!t)return r.final();return ed}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}}mu.NAME="ConstructedValueBlock";var N6;class Ko extends Po{constructor(e={}){super(e,mu);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(`
|
|
484
|
+
`).map((n)=>` ${n}`).join(`
|
|
485
|
+
`));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
|
|
486
|
+
${e.join(`
|
|
487
|
+
`)}`:`${t} :`}}N6=Ko;(()=>{Be.Constructed=N6})();Ko.NAME="CONSTRUCTED";class KU extends Ri{fromBER(e,t,r){return t}toBER(e){return ed}}KU.override="EndOfContentValueBlock";var F6;class BP extends Po{constructor(e={}){super(e,KU);this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}F6=BP;(()=>{Be.EndOfContent=F6})();BP.NAME=GE;var U6;class rd extends Po{constructor(e={}){super(e,Ri);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}`}}U6=rd;(()=>{Be.Null=U6})();rd.NAME="NULL";class GU extends td(Ri){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=Te.toUint8Array(t.valueHex);else this.valueHexView=new Uint8Array(1);if(e)this.value=e}fromBER(e,t,r){let n=Te.toUint8Array(e);if(!hu(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,$U.call(this),this.blockLength=r,t+r}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}GU.NAME="BooleanValueBlock";var M6;class Yg extends Po{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,GU);this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}}M6=Yg;(()=>{Be.Boolean=M6})();Yg.NAME="BOOLEAN";class QU extends td(mu){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=mu.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===GE)if(this.isIndefiniteForm)break;else return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1;if(s!==R6)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 mu.prototype.toBER.call(this,e,t);return e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}QU.NAME="OctetStringValueBlock";var JU;class nd extends Po{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},QU);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:JE(),a=zU(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 Ko.prototype.onAsciiEncoding.call(this);let e=this.constructor.NAME,t=Le.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 JU)e.push(t.valueBlock.valueHexView);return Te.concat(e)}}JU=nd;(()=>{Be.OctetString=JU})();nd.NAME=R6;class YU extends td(mu){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=mu.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===GE)if(this.isIndefiniteForm)break;else return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1;if(c!==P6)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=Te.toUint8Array(e);if(!hu(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:JE(),l=zU(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 mu.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}}}YU.NAME="BitStringValueBlock";var L6;class od extends Po{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},YU);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 Ko.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}`}}}L6=od;(()=>{Be.BitString=L6})();od.NAME=P6;var B6;function kwe(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 p=d;p>=0;p--,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=DP(new Uint8Array([l%10]),i);break;default:i[s-u]=l%10}}if(r[0]>0)i=DP(r,i);return i}function I6(e){if(e>=zE.length)for(let t=zE.length;t<=e;t++){let r=new Uint8Array([0]),n=zE[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=DP(r,n);zE.push(n)}return zE[e]}function Dwe(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 $P extends td(Ri){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=$U.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(b6(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=Dwe(I6(r),t),i="-";break;default:t=kwe(t,I6(r))}r++,n>>=1}}for(let a=0;a<t.length;a++){if(t[a])s=!0;if(s)i+=T6.charAt(t[a])}if(s===!1)i+=T6.charAt(0);return i}}B6=$P;$P.NAME="IntegerValueBlock";(()=>{Object.defineProperty(B6.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}})})();var KE;class Gp extends Po{constructor(e={}){super(e,$P);this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return OP(),BigInt(this.valueBlock.toString())}static fromBigInt(e){OP();let t=BigInt(e),r=new QE,n=t.toString(16).replace(/^-/,""),o=new Uint8Array(Le.FromHex(n));if(t<0){let s=new Uint8Array(o.length+(o[0]&128?1:0));s[0]|=128;let c=BigInt(`0x${Le.ToHex(s)}`)+t,l=Te.toUint8Array(Le.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 KE({valueHex:r.final()})}convertToDER(){let e=new KE({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new KE({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}KE=Gp;(()=>{Be.Integer=KE})();Gp.NAME="INTEGER";var $6;class Xg extends Gp{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}$6=Xg;(()=>{Be.Enumerated=$6})();Xg.NAME="ENUMERATED";class NP extends td(Ri){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=Te.toUint8Array(e);if(!hu(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=qm(this.valueHexView,7);else this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only");return t+this.blockLength}set valueBigInt(e){OP();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=Vp(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ed;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=Le.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}}}NP.NAME="sidBlock";class XU extends Ri{constructor({value:e=Gs,...t}={}){super(t);if(this.value=[],e)this.fromString(e)}fromBER(e,t,r){let n=t;while(r>0){let o=new NP;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,ed;t.push(n)}return jU(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 NP;if(n>Number.MAX_SAFE_INTEGER){OP();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}}XU.NAME="ObjectIdentifierValueBlock";var q6;class Zg extends Po{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,XU);this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}q6=Zg;(()=>{Be.ObjectIdentifier=q6})();Zg.NAME="OBJECT IDENTIFIER";class FP extends td(zp){constructor({valueDec:e=0,...t}={}){super(t);this.valueDec=e}fromBER(e,t,r){if(r===0)return t;let n=Te.toUint8Array(e);if(!hu(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=qm(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=Vp(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ed;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=Le.ToHex(this.valueHexView);else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}FP.NAME="relativeSidBlock";class ZU extends Ri{constructor({value:e=Gs,...t}={}){super(t);if(this.value=[],e)this.fromString(e)}fromBER(e,t,r){let n=t;while(r>0){let o=new FP;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,ed;r.push(o)}return jU(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 FP;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}}ZU.NAME="RelativeObjectIdentifierValueBlock";var j6;class eS extends Po{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,ZU);this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}j6=eS;(()=>{Be.RelativeObjectIdentifier=j6})();eS.NAME="RelativeObjectIdentifier";var H6;class vs extends Ko{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}H6=vs;(()=>{Be.Sequence=H6})();vs.NAME="SEQUENCE";var W6;class Qs extends Ko{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=17}}W6=Qs;(()=>{Be.Set=W6})();Qs.NAME="SET";class eM extends td(Ri){constructor({...e}={}){super(e);this.isHexOnly=!0,this.value=Gs}toJSON(){return{...super.toJSON(),value:this.value}}}eM.NAME="StringValueBlock";class tM extends eM{}tM.NAME="SimpleStringValueBlock";class Js extends MP{constructor({...e}={}){super(e,tM)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,Te.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}}Js.NAME="SIMPLE STRING";class rM extends Js{fromBuffer(e){this.valueBlock.valueHexView=Te.toUint8Array(e);try{this.valueBlock.value=Le.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=Le.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(Le.FromUtf8String(e)),this.valueBlock.value=e}}rM.NAME="Utf8StringValueBlock";var V6;class al extends rM{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}V6=al;(()=>{Be.Utf8String=V6})();al.NAME="UTF8String";class nM extends Js{fromBuffer(e){this.valueBlock.value=Le.ToUtf16String(e),this.valueBlock.valueHexView=Te.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(Le.FromUtf16String(e))}}nM.NAME="BmpStringValueBlock";var z6;class tS extends nM{constructor({...e}={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}z6=tS;(()=>{Be.BmpString=z6})();tS.NAME="BMPString";class oM extends Js{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=Vp(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}}oM.NAME="UniversalStringValueBlock";var K6;class rS extends oM{constructor({...e}={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}K6=rS;(()=>{Be.UniversalString=K6})();rS.NAME="UniversalString";var G6;class nS extends Js{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}G6=nS;(()=>{Be.NumericString=G6})();nS.NAME="NumericString";var Q6;class oS extends Js{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}Q6=oS;(()=>{Be.PrintableString=Q6})();oS.NAME="PrintableString";var J6;class iS extends Js{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}J6=iS;(()=>{Be.TeletexString=J6})();iS.NAME="TeletexString";var Y6;class sS extends Js{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}Y6=sS;(()=>{Be.VideotexString=Y6})();sS.NAME="VideotexString";var X6;class aS extends Js{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}X6=aS;(()=>{Be.IA5String=X6})();aS.NAME="IA5String";var Z6;class cS extends Js{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}Z6=cS;(()=>{Be.GraphicString=Z6})();cS.NAME="GraphicString";var e8;class jm extends Js{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}e8=jm;(()=>{Be.VisibleString=e8})();jm.NAME="VisibleString";var t8;class lS extends Js{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}t8=lS;(()=>{Be.GeneralString=t8})();lS.NAME="GeneralString";var r8;class dS extends Js{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}r8=dS;(()=>{Be.CharacterString=r8})();dS.NAME="CharacterString";var n8;class Hm extends jm{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,Te.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]=Ks(this.year<2000?this.year-1900:this.year-2000,2),t[1]=Ks(this.month,2),t[2]=Ks(this.day,2),t[3]=Ks(this.hour,2),t[4]=Ks(this.minute,2),t[5]=Ks(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}}}n8=Hm;(()=>{Be.UTCTime=n8})();Hm.NAME="UTCTime";var o8;class uS extends Hm{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("+"),p="";if(u===-1)u=r.indexOf("-"),d=-1;if(u!==-1){if(p=r.substring(u+1),r=r.substring(0,u),p.length!==2&&p.length!==4)throw Error("Wrong input string for conversion");let y=parseInt(p.substring(0,2),10);if(isNaN(y.valueOf()))throw Error("Wrong input string for conversion");if(s=d*y,p.length===4){if(y=parseInt(p.substring(2,4),10),isNaN(y.valueOf()))throw Error("Wrong input string for conversion");a=d*y}}}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(Ks(this.year,4)),t.push(Ks(this.month,2)),t.push(Ks(this.day,2)),t.push(Ks(this.hour,2)),t.push(Ks(this.minute,2)),t.push(Ks(this.second,2)),this.millisecond!==0)t.push("."),t.push(Ks(this.millisecond,3));return t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}o8=uS;(()=>{Be.GeneralizedTime=o8})();uS.NAME="GeneralizedTime";var i8;class qP extends al{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}i8=qP;(()=>{Be.DATE=i8})();qP.NAME="DATE";var s8;class jP extends al{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}s8=jP;(()=>{Be.TimeOfDay=s8})();jP.NAME="TimeOfDay";var a8;class HP extends al{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}a8=HP;(()=>{Be.DateTime=a8})();HP.NAME="DateTime";var c8;class WP extends al{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}c8=WP;(()=>{Be.Duration=c8})();WP.NAME="Duration";var l8;class VP extends al{constructor(e={}){super(e);this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}l8=VP;(()=>{Be.TIME=l8})();VP.NAME="TIME";class yu{constructor({name:e=Gs,optional:t=!1}={}){this.name=e,this.optional=t}}class YE extends yu{constructor({value:e=[],...t}={}){super(t);this.value=e}}class Jg extends yu{constructor({value:e=new yu,local:t=!1,...r}={}){super(r);this.value=e,this.local=t}}class d8{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=Te.toUint8Array(e)}constructor({data:e=UP}={}){this.dataView=Te.toUint8Array(e)}fromBER(e,t,r){let n=t+r;return this.dataView=Te.toUint8Array(e).subarray(t,n),n}toBER(e){return this.dataView.slice().buffer}}function fu(e,t,r){if(r instanceof YE){for(let i of r.value)if(fu(e,t,i).verified)return{verified:!0,result:e};{let i={verified:!1,result:{error:"Wrong values for Choice type"}};if(r.hasOwnProperty(qU))i.name=r.name;return i}}if(r instanceof yu){if(r.hasOwnProperty(qU))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(hwe in r===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(xwe in r.idBlock===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(Ewe 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(gwe)===!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(Swe)===!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(vwe)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!(ywe 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(A6 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,Gs),r.name)e[r.name]=t}if(r instanceof Be.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 Jg)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,Gs),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,Gs),r.name)delete e[r.name],l.name=r.name}return l}}else if(r.valueBlock.value[0]instanceof Jg){if(s=fu(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,Gs),r.name)delete e[r.name]}return s}if(qU in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){let l={};if(bwe 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=fu(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,Gs),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,Gs),r.name)delete e[r.name],c.name=r.name}return c}return{verified:!0,result:e}}if(r.primitiveSchema&&A6 in t.valueBlock){let i=LP(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,Gs),r.name)delete e[r.name],s.name=r.name}return s}return fu(e,i.result,r.primitiveSchema)}return{verified:!0,result:e}}function Owe(e,t){if(t instanceof Object===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};let r=LP(Te.toUint8Array(e));if(r.offset===-1)return{verified:!1,result:r.result};return fu(r.result,r.result,t)}function u8(e){return Object.prototype.toString.call(e)}function Nwe(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"&&KP(t.buffer)}function zP(e){return u8(e)==="[object ArrayBuffer]"}function p8(e){return typeof SharedArrayBuffer<"u"&&u8(e)==="[object SharedArrayBuffer]"}function KP(e){return zP(e)||p8(e)}function iM(e){return Nwe(e)}function sd(e){return KP(e)||iM(e)}function sM(e){if(!sd(e))throw TypeError("Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView")}function qi(e){if(sM(e),KP(e))return new Uint8Array(e);return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function _r(e){if(sM(e),zP(e))return e;let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(qi(e)),t}function XE(e,t,r={}){let n=qi(e),o=qi(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 GP(e){let t=qi(e),r="";for(let n of t)r+=String.fromCharCode(n);return r}function QP(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r)&255;return t}function Mwe(e){return typeof e==="string"}var Lwe=/^[0-9a-f]$/i,Bwe=[" ","\t",`
|
|
488
|
+
`,"\r",":","-","."];function $we(e){if(e.separators==="none")return[];if(!e.separators||e.separators==="common")return Bwe;return e.separators}function qwe(e){if(!e)throw TypeError("Hex separators must be non-empty strings")}function jwe(e,t,r){for(let n of r)if(e.startsWith(n,t))return n;return}function Hwe(e){let t=/[A-F]/.test(e),r=/[a-f]/.test(e);return t&&!r?"upper":"lower"}function Wwe(e){let t=/\r\n|\n/.exec(e);if(!t)return;return t[0]===`\r
|
|
489
|
+
`?`\r
|
|
490
|
+
`:`
|
|
491
|
+
`}function y8(e){return e.replace(/[^0-9a-f]/gi,"")}function Vwe(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 zwe(e){let t=e.trim(),r=/^0x/i.test(t)?"0x":"",n=r?t.slice(2):t,o=Wwe(n),i=n.split(/\r\n|\n/).filter((l)=>l.length>0),s=i[0]?.trim()??"",a=Vwe(s),c={case:Hwe(t),prefix:r};if(a)c.group=a;if(o&&i.length>1){let l=y8(i[0]??"").length/2;if(l>0&&i.slice(0,-1).every((d)=>y8(d).length/2===l))c.line={bytesPerLine:l,separator:o}}return c}function Kwe(e,t){let r=t.allowPrefix??!0,n=[...$we(t)].sort((a,c)=>c.length-a.length);for(let a of n)qwe(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(Lwe.test(c)){i+=c,s=!1,a+=1;continue}let l=jwe(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 h8(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 JP(e,t={}){return Kwe(e,t)}function g8(e,t={}){if(typeof e!=="string")return!1;try{return JP(e,t),!0}catch{return!1}}function ZE(e,t={}){let r=qi(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??`
|
|
492
|
+
`,c=[];for(let l=0;l<o.length;l+=s)c.push(h8(o.slice(l,l+s),t.group));i=c.join(a)}else i=h8(o,t.group);return`${t.prefix??""}${i}`}function YP(e,t={}){let r=JP(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 Gwe(e,t={}){let r=JP(e,t);return{bytes:YP(r),format:zwe(e),normalized:r}}function Qwe(e,t){return ZE(e,t)}var ant={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 S8(e){return new TextEncoder().encode(e)}function v8(e){return new TextDecoder("utf-8",{fatal:!1}).decode(qi(e))}function lM(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 dM(e,t={}){let r=_r(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 Jwe=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function x8(){return globalThis.Buffer}function tb(e){return e.replace(/[\n\r\t ]/g,"")}function Ywe(e){let t=e.length%4;return t?e+"=".repeat(4-t):e}function XP(e){if(typeof e!=="string")return!1;let t=tb(e);return t===""||Jwe.test(t)}function pM(e,t){let r=qi(e),n=x8();if(n)return n.from(r).toString("base64");return btoa(GP(r))}function fM(e,t){let r=tb(e);if(!XP(r))throw TypeError("Input is not valid Base64 text");let n=x8();if(n)return new Uint8Array(n.from(r,"base64"));return QP(atob(r))}var Wm={encode:pM,decode:fM,is:XP,normalize:tb,pad:Ywe};var Xwe=/^[A-Za-z0-9_-]*$/;function yM(e){return e.replace(/[\n\r\t ]/g,"")}function hM(e){return typeof e==="string"&&Xwe.test(yM(e))}function E8(e,t){return Wm.encode(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function b8(e,t){let r=yM(e);if(!hM(r))throw TypeError("Input is not valid Base64Url text");return Wm.decode(Wm.pad(r.replace(/-/g,"+").replace(/_/g,"/")))}var Zwe=/^[A-Z0-9][A-Z0-9 ._-]*[A-Z0-9]$/i,w8=/-----BEGIN ([^-]+)-----([\s\S]*?)-----END \1-----/g;function T8(e){if(!Zwe.test(e))throw TypeError(`Invalid PEM label '${e}'`)}function eTe(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}function tTe(e){let r=e.trim().replace(/\r\n/g,`
|
|
493
|
+
`).split(`
|
|
494
|
+
`).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 rTe(e){return/\r\n/.test(e)?`\r
|
|
495
|
+
`:`
|
|
496
|
+
`}function A8(e,t={}){let r=[],n=t.label,o;w8.lastIndex=0;while(o=w8.exec(e)){let i=o[1].trim();if(n&&i!==n)continue;T8(i);let s=tTe(o[2]);r.push({label:i,data:Wm.decode(s.base64Text),headers:s.headers,lineLength:s.base64Lines[0]?.length??64,newline:rTe(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 ZP(e,t,r={}){T8(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??`
|
|
497
|
+
`,i=[`-----BEGIN ${e}-----`];if(r.headers){for(let[s,a]of Object.entries(r.headers))i.push(`${s}: ${a}`);i.push("")}return i.push(...eTe(Wm.encode(t),n)),i.push(`-----END ${e}-----`),`${i.join(o)}${o}`}function I8(e,t={}){return A8(e,t).map(({lineLength:r,newline:n,...o})=>o)}function R8(e,t){let[r]=I8(e,{label:t,strict:!0});return r.data}function P8(e,t={}){let[r]=A8(e,{...t,strict:!0}),n={label:r.label,headers:r.headers,lineLength:r.lineLength,newline:r.newline};return{bytes:r.data,format:n,normalized:ZP(r.label,r.data,n)}}function C8(e,t){return ZP(t.label,e,t)}var rb={name:"pem",encode:(e,t)=>{if(!t?.label)throw TypeError("PEM label is required");return ZP(t.label,e,t)},decode:(e,t)=>R8(e,t?.label),format:C8,is:(e)=>typeof e==="string"&&/-----BEGIN [^-]+-----/.test(e),parse:P8};function ad(e){return e.trim().toLowerCase()}function nTe(e){return e instanceof Error?e:Error(String(e))}function _8(e,t,r){for(let n of[r.name,...r.aliases??[]])e.delete(ad(n));t.delete(ad(r.name))}function SM(e,t,r){let n=e[r];if(typeof n!=="function")throw Error(`Converter '${t}' does not support ${r}()`);return n}function oTe(e,t,r){let n=ad(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 vM(e=[]){let t=new Map,r=new Set,n={register(o,i={}){if(!o.name||!ad(o.name))throw TypeError("Converter name is required");let s=[...new Set([o.name,...o.aliases??[]].map(ad))],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)_8(t,r,c);for(let c of s)t.set(c,o);return r.add(ad(o.name)),this},unregister(o){let i=t.get(ad(o));if(!i)return!1;return _8(t,r,i),!0},has(o){return t.has(ad(o))},get(o){let i=t.get(ad(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:nTe(a)}}},normalize(o,i,s){let a=this.get(o);return SM(a,o,"normalize").call(a,i,s)},parse(o,i,s){let a=this.get(o);return SM(a,o,"parse").call(a,i,s)},format(o,i,s){let a=this.get(o);return SM(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(ad(c))),a=new Map;for(let c of s){let l=this.get(c),d=oTe(c,o,l);if(d<=0)continue;let u=l.name,p=a.get(u);if(!p||d>p.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 k8={name:"binary",aliases:["latin1"],encode:GP,decode:QP,is:Mwe},D8={name:"hex",encode:ZE,decode:YP,format:Qwe,is:g8,normalize:JP,parse:Gwe},O8={name:"base64",aliases:["b64"],encode:pM,decode:fM,is:XP,normalize:tb},N8={name:"base64url",aliases:["base64-url","b64url"],encode:E8,decode:b8,is:hM,normalize:yM},F8={name:"utf8",aliases:["utf-8"],encode:(e)=>v8(e),decode:(e)=>S8(e),is:(e)=>typeof e==="string"},U8={name:"utf16be",aliases:["utf16","utf-16","utf-16be"],encode:(e)=>dM(e),decode:(e)=>lM(e),is:(e)=>typeof e==="string"},M8={name:"utf16le",aliases:["utf-16le","ucs2","usc2"],encode:(e)=>dM(e,{littleEndian:!0}),decode:(e)=>lM(e,{littleEndian:!0}),is:(e)=>typeof e==="string"},L8=[k8,D8,O8,N8,F8,U8,M8,rb],cd=vM(L8);function xM(e,t,...r){return cd.encode(e,t,...r)}function EM(e,t,...r){return cd.decode(e,t,...r)}function iTe(e,t,...r){return cd.tryDecode(e,t,...r)}function sTe(e,t,...r){return cd.normalize(e,t,...r)}function aTe(e,t,...r){return cd.parse(e,t,...r)}function cTe(e,t,r){return cd.format(e,t,r)}function lTe(e,t){return cd.transcode(e,t)}function dTe(e,t){return cd.detect(e,t)}function uTe(e){return e.toLowerCase()}var B8={encode:xM,decode:EM,tryDecode:iTe,normalize:sTe,parse:aTe,format:cTe,transcode:lTe,detect:dTe,to(e,t,...r){return xM(e,t,...r)},from(e,t,...r){return EM(e,t,...r)},toString(e,t="utf8"){return xM(t,e)},fromString(e,t="utf8"){if(uTe(t)==="hex")return _r(YP(e,{allowOddLength:!0}));return _r(EM(t,e))},toBase64:pM,fromBase64:(e)=>_r(fM(e)),toBase64Url:E8,fromBase64Url:(e)=>_r(b8(e)),toHex:ZE,fromHex:(e)=>_r(YP(e,{allowOddLength:!0})),toBinary:GP,fromBinary:(e)=>_r(QP(e)),toUtf8String:v8,fromUtf8String:(e)=>_r(S8(e)),toUtf16String:(e,t=!1)=>dM(e,{littleEndian:t}),fromUtf16String:(e,t=!1)=>_r(lM(e,{littleEndian:t})),isHex:g8,isBase64:XP,isBase64Url:hM,formatString:tb};var B;(function(e){e[e.Sequence=0]="Sequence",e[e.Set=1]="Set",e[e.Choice=2]="Choice"})(B||(B={}));var A;(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"})(A||(A={}));class Su{unusedBits=0;value=new ArrayBuffer(0);constructor(e,t=0){if(e)if(typeof e==="number")this.fromNumber(e);else if(sd(e))this.unusedBits=t,this.value=_r(e);else throw TypeError("Unsupported type of 'params' argument for BitString")}fromASN(e){if(!(e instanceof od))throw TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=_r(e.valueBlock.valueHex),this}toASN(){return new od({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new od({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 he{buffer;get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){if(typeof e==="number")this.buffer=new ArrayBuffer(e);else if(sd(e))this.buffer=_r(e);else if(Array.isArray(e))this.buffer=new Uint8Array(e).buffer;else this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof nd))throw TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=_r(e.valueBlock.valueHex),this}toASN(){return new nd({valueHex:this.buffer})}toSchema(e){return new nd({name:e})}}var pTe={fromASN:(e)=>e instanceof rd?null:_r(e.valueBeforeDecodeView),toASN:(e)=>{if(e===null)return new rd;let t=gu(e);if(t.result.error)throw Error(t.result.error);return t.result}},fTe={fromASN:(e)=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:(e)=>new Gp({value:+e})},mTe={fromASN:(e)=>e.valueBlock.valueDec,toASN:(e)=>new Xg({value:e})},Kt={fromASN:(e)=>_r(e.valueBlock.valueHexView),toASN:(e)=>new Gp({valueHex:e})};var yTe={fromASN:(e)=>_r(e.valueBlock.valueHexView),toASN:(e)=>new od({valueHex:e})},hTe={fromASN:(e)=>e.valueBlock.toString(),toASN:(e)=>new Zg({value:e})},gTe={fromASN:(e)=>e.valueBlock.toString(),toASN:(e)=>new eS({value:e})},STe={fromASN:(e)=>e.valueBlock.value,toASN:(e)=>new Yg({value:e})},pS={fromASN:(e)=>_r(e.valueBlock.valueHexView),toASN:(e)=>new nd({valueHex:e})},$8={fromASN:(e)=>new he(e.getValue()),toASN:(e)=>e.toASN()};function hc(e){return{fromASN:(t)=>t.valueBlock.value,toASN:(t)=>new e({value:t})}}var bM=hc(al),vTe=hc(tS),xTe=hc(rS),ETe=hc(nS),bTe=hc(oS),wTe=hc(iS),TTe=hc(sS),ATe=hc(aS),ITe=hc(cS),RTe=hc(jm),PTe=hc(lS),CTe=hc(dS),_Te={fromASN:(e)=>e.toDate(),toASN:(e)=>new Hm({valueDate:e})},kTe={fromASN:(e)=>e.toDate(),toASN:(e)=>new uS({valueDate:e})},DTe={fromASN:()=>null,toASN:()=>new rd};function Qp(e){switch(e){case A.Any:return pTe;case A.BitString:return yTe;case A.BmpString:return vTe;case A.Boolean:return STe;case A.CharacterString:return CTe;case A.Enumerated:return mTe;case A.GeneralString:return PTe;case A.GeneralizedTime:return kTe;case A.GraphicString:return ITe;case A.IA5String:return ATe;case A.Integer:return fTe;case A.Null:return DTe;case A.NumericString:return ETe;case A.ObjectIdentifier:return hTe;case A.RelativeObjectIdentifier:return gTe;case A.OctetString:return pS;case A.PrintableString:return bTe;case A.TeletexString:return wTe;case A.UTCTime:return _Te;case A.UniversalString:return xTe;case A.Utf8String:return bM;case A.VideotexString:return TTe;case A.VisibleString:return RTe;default:return null}}function gc(e){if(typeof e==="function"&&e.prototype)if(e.prototype.toASN&&e.prototype.fromASN)return!0;else return gc(e.prototype);else return!!(e&&typeof e==="object"&&("toASN"in e)&&("fromASN"in e))}function TM(e){if(e){let t=Object.getPrototypeOf(e);if(t?.prototype?.constructor===Array)return!0;return TM(t)}return!1}function q8(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 AM{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:B.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=A[i.type],d=id[l];if(!d)throw Error(`Cannot get ASN1 class by name '${l}'`);a=new d({name:s})}else if(gc(i.type))a=new i.type().toSchema(s);else if(i.optional)if(this.get(i.type).type===B.Choice)a=new yu({name:s});else a=this.create(i.type,!1),a.name=s;else a=new yu({name:s});let c=!!i.optional||i.defaultValue!==void 0;if(i.repeated)a.name="",a=new(i.repeated==="set"?Qs:vs)({name:"",value:[new Jg({name:s,value:a})]});if(i.context!==null&&i.context!==void 0)if(i.implicit)if(typeof i.type==="number"||gc(i.type)){let l=i.repeated?Ko:Kp;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 Ko({name:!l?s:"",optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:d}))}else n.push(new Ko({optional:c,idBlock:{tagClass:3,tagNumber:i.context},value:[a]}));else a.optional=c,n.push(a)}switch(r.type){case B.Sequence:return new vs({value:n,name:""});case B.Set:return new Qs({value:n,name:""});case B.Choice:return new YE({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 Co=new AM;var z=(e)=>(t)=>{let r;if(!Co.has(t))r=Co.createDefault(t),Co.set(t,r);else r=Co.get(t);Object.assign(r,e)};var v=(e)=>(t,r)=>{let n;if(!Co.has(t.constructor))n=Co.createDefault(t.constructor),Co.set(t.constructor,n);else n=Co.get(t.constructor);let o=Object.assign({},e);if(typeof o.type==="number"&&!o.converter){let i=Qp(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 Vm extends Error{schemas=[]}class Tn{static parse(e,t,r){let n=gu(_r(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(gc(t))return new t().fromASN(e);let n=Co.get(t);Co.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(TM(t))return this.handleArrayTypes(e,n,t,r);return this.processSchemaItems(n,s,a,r),a}catch(n){if(n instanceof Vm)n.schemas.push(t.name);throw n}}static handleChoiceTypes(e,t,r,n,o){if(e.constructor===Ko&&t.type===B.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"&&Co.has(s.type)){let a=Co.get(s.type);if(a&&a.type===B.Sequence){let c=new vs;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===Ko&&t.type!==B.Choice){let i=new Ko({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===B.Sequence){let o=fu({},e,n);if(!o.verified)throw new Vm(`Data does not match to ${r.name} ASN1 schema.${o.result.error?` ${o.result.error}`:""}`);return o}else{let o=fu({},e,n);if(!o.verified)throw new Vm(`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=Qp(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=Qp(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"&&Co.has(e.type)&&Co.get(e.type).type===B.Choice}static processOptionalChoiceField(e,t){try{return{processed:!0,value:this.fromASN(e,t.type)}}catch(r){if(r instanceof Vm&&/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=Qp(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"||gc(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??(gc(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"?vs:Qs);i.valueBlock=e.valueBlock;let s=gu(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(gc(r))s=new r().toSchema("");else{let a=A[r],c=id[a];if(!c)throw Error(`Cannot get '${a}' class from asn1js module`);s=new c}s.valueBlock=i.valueBlock,i=gu(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 Vm&&/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=Co.get(r);if(n.type===B.Sequence){let o=new vs;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===B.Set){let o=new Qs;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 nb{static serialize(e){if(e instanceof Po)return e.toBER(!1);return this.toASN(e).toBER(!1)}static toASN(e){if(e&&typeof e==="object"&&gc(e))return e.toASN();if(!(e&&typeof e==="object"))throw TypeError("Parameter 1 should be type of Object.");let t=e.constructor,r=Co.get(t);Co.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=Qp(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"&&q8(this.serialize(s.defaultValue),this.serialize(a)))continue;let c=nb.toAsnItem(s,i,t,a);if(typeof s.context==="number")if(s.implicit)if(!s.repeated&&(typeof s.type==="number"||gc(s.type))){let l={};l.valueHex=c instanceof rd?_r(c.valueBeforeDecodeView):c.valueBlock.toBER(),n.push(new Kp({optional:s.optional,idBlock:{tagClass:3,tagNumber:s.context},...l}))}else n.push(new Ko({optional:s.optional,idBlock:{tagClass:3,tagNumber:s.context},value:c.valueBlock.value}));else n.push(new Ko({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 B.Sequence:o=new vs({value:n});break;case B.Set:o=new Qs({value:n});break;case B.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 ${A[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"?vs:Qs)({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"?vs:Qs)({value:i})}else o=this.toASN(n);return o}}class Ve extends Array{constructor(e=[]){if(typeof e==="number")super(e);else{super();for(let t of e)this.push(t)}}}class ue{static serialize(e){return nb.serialize(e)}static parse(e,t,r){return Tn.parse(e,t,r)}static toString(e,t){let r=sd(e)?_r(e):ue.serialize(e),n=gu(r,t?.berOptions);if(n.offset===-1)throw Error(`Cannot decode ASN.1 data. ${n.result.error}`);return n.result.toString()}}var g3=so(h3(),1),{__extends:rit,__assign:nit,__rest:oit,__decorate:h,__param:iit,__esDecorate:sit,__runInitializers:ait,__propKey:cit,__setFunctionName:lit,__metadata:dit,__awaiter:uit,__generator:pit,__exportStar:fit,__createBinding:mit,__values:yit,__read:hit,__spread:git,__spreadArrays:Sit,__spreadArray:vit,__await:xit,__asyncGenerator:Eit,__asyncDelegator:bit,__asyncValues:wit,__makeTemplateObject:Tit,__importStar:Ait,__importDefault:Iit,__classPrivateFieldGet:Ue,__classPrivateFieldSet:Wt,__classPrivateFieldIn:Rit,__addDisposableResource:Pit,__disposeResources:Cit,__rewriteRelativeImportExtension:_it}=g3.default;class nC{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(ZE(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 RM,PM,CM,_o=class{teletexString;printableString;universalString;utf8String;bmpString;constructor(t={}){Object.assign(this,t)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};h([v({type:A.TeletexString})],_o.prototype,"teletexString",void 0);h([v({type:A.PrintableString})],_o.prototype,"printableString",void 0);h([v({type:A.UniversalString})],_o.prototype,"universalString",void 0);h([v({type:A.Utf8String})],_o.prototype,"utf8String",void 0);h([v({type:A.BmpString})],_o.prototype,"bmpString",void 0);_o=h([z({type:B.Choice})],_o);var mS=class extends _o{ia5String;anyValue;constructor(t={}){super(t);Object.assign(this,t)}toString(){return this.ia5String||(this.anyValue?ZE(this.anyValue):super.toString())}};h([v({type:A.IA5String})],mS.prototype,"ia5String",void 0);h([v({type:A.Any})],mS.prototype,"anyValue",void 0);mS=h([z({type:B.Choice})],mS);class yS{type="";value=new mS;constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier})],yS.prototype,"type",void 0);h([v({type:mS})],yS.prototype,"value",void 0);var Jp=RM=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,RM.prototype)}};Jp=RM=h([z({type:B.Set,itemType:yS})],Jp);var _M=PM=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,PM.prototype)}};_M=PM=h([z({type:B.Sequence,itemType:Jp})],_M);var en=CM=class extends _M{constructor(t){super(t);Object.setPrototypeOf(this,CM.prototype)}};en=CM=h([z({type:B.Sequence})],en);var OTe={fromASN:(e)=>nC.toString(pS.fromASN(e)),toASN:(e)=>pS.toASN(nC.fromString(e))};class zm{typeId="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier})],zm.prototype,"typeId",void 0);h([v({type:A.Any,context:0})],zm.prototype,"value",void 0);class oC{nameAssigner;partyName=new _o;constructor(e={}){Object.assign(this,e)}}h([v({type:_o,optional:!0,context:0,implicit:!0})],oC.prototype,"nameAssigner",void 0);h([v({type:_o,context:1,implicit:!0})],oC.prototype,"partyName",void 0);var it=class{otherName;rfc822Name;dNSName;x400Address;directoryName;ediPartyName;uniformResourceIdentifier;iPAddress;registeredID;constructor(t={}){Object.assign(this,t)}};h([v({type:zm,context:0,implicit:!0})],it.prototype,"otherName",void 0);h([v({type:A.IA5String,context:1,implicit:!0})],it.prototype,"rfc822Name",void 0);h([v({type:A.IA5String,context:2,implicit:!0})],it.prototype,"dNSName",void 0);h([v({type:A.Any,context:3,implicit:!0})],it.prototype,"x400Address",void 0);h([v({type:en,context:4,implicit:!1})],it.prototype,"directoryName",void 0);h([v({type:oC,context:5})],it.prototype,"ediPartyName",void 0);h([v({type:A.IA5String,context:6,implicit:!0})],it.prototype,"uniformResourceIdentifier",void 0);h([v({type:A.OctetString,context:7,implicit:!0,converter:OTe})],it.prototype,"iPAddress",void 0);h([v({type:A.ObjectIdentifier,context:8,implicit:!0})],it.prototype,"registeredID",void 0);it=h([z({type:B.Choice})],it);var iC="1.3.6.1.5.5.7",Yp="1.3.6.1.5.5.7.1";var Km="1.3.6.1.5.5.7.3";var kM="1.3.6.1.5.5.7.48.1",DM="1.3.6.1.5.5.7.48.2",OM="1.3.6.1.5.5.7.48.3",NM="1.3.6.1.5.5.7.48.5",wt="2.5.29";var FM,sC=`${Yp}.1`;class Xp{accessMethod="";accessLocation=new it;constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier})],Xp.prototype,"accessMethod",void 0);h([v({type:it})],Xp.prototype,"accessLocation",void 0);var Gm=FM=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,FM.prototype)}};Gm=FM=h([z({type:B.Sequence,itemType:Xp})],Gm);var ob=`${wt}.35`;class hS extends he{}class vu{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){if(e)Object.assign(this,e)}}h([v({type:hS,context:0,optional:!0,implicit:!0})],vu.prototype,"keyIdentifier",void 0);h([v({type:it,context:1,optional:!0,implicit:!0,repeated:"sequence"})],vu.prototype,"authorityCertIssuer",void 0);h([v({type:A.Integer,context:2,optional:!0,implicit:!0,converter:Kt})],vu.prototype,"authorityCertSerialNumber",void 0);var gS=`${wt}.19`;class Zp{cA=!1;pathLenConstraint;constructor(e={}){Object.assign(this,e)}}h([v({type:A.Boolean,defaultValue:!1})],Zp.prototype,"cA",void 0);h([v({type:A.Integer,optional:!0})],Zp.prototype,"pathLenConstraint",void 0);var UM,ln=UM=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,UM.prototype)}};ln=UM=h([z({type:B.Sequence,itemType:it})],ln);var MM,NTe=`${wt}.29`,S3=MM=class extends ln{constructor(t){super(t);Object.setPrototypeOf(this,MM.prototype)}};S3=MM=h([z({type:B.Sequence})],S3);var LM,cC=`${wt}.32`,hst=`${cC}.0`,xu=class{ia5String;visibleString;bmpString;utf8String;constructor(t={}){Object.assign(this,t)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};h([v({type:A.IA5String})],xu.prototype,"ia5String",void 0);h([v({type:A.VisibleString})],xu.prototype,"visibleString",void 0);h([v({type:A.BmpString})],xu.prototype,"bmpString",void 0);h([v({type:A.Utf8String})],xu.prototype,"utf8String",void 0);xu=h([z({type:B.Choice})],xu);class lC{organization=new xu;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}}h([v({type:xu})],lC.prototype,"organization",void 0);h([v({type:A.Integer,repeated:"sequence"})],lC.prototype,"noticeNumbers",void 0);class dC{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}}h([v({type:lC,optional:!0})],dC.prototype,"noticeRef",void 0);h([v({type:xu,optional:!0})],dC.prototype,"explicitText",void 0);var aC=class{cPSuri;userNotice;constructor(t={}){Object.assign(this,t)}};h([v({type:A.IA5String})],aC.prototype,"cPSuri",void 0);h([v({type:dC})],aC.prototype,"userNotice",void 0);aC=h([z({type:B.Choice})],aC);class uC{policyQualifierId="";qualifier=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier})],uC.prototype,"policyQualifierId",void 0);h([v({type:A.Any})],uC.prototype,"qualifier",void 0);class SS{policyIdentifier="";policyQualifiers;constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier})],SS.prototype,"policyIdentifier",void 0);h([v({type:uC,repeated:"sequence",optional:!0})],SS.prototype,"policyQualifiers",void 0);var ib=LM=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,LM.prototype)}};ib=LM=h([z({type:B.Sequence,itemType:SS})],ib);var Est=`${wt}.20`,sb=class{value;constructor(t=0){this.value=t}};h([v({type:A.Integer})],sb.prototype,"value",void 0);sb=h([z({type:B.Choice})],sb);var Rst=`${wt}.27`,v3=class extends sb{};v3=h([z({type:B.Choice})],v3);var BM,pC=`${wt}.31`,cl;(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"})(cl||(cl={}));class fC extends Su{toJSON(){let e=[],t=this.toNumber();if(t&cl.aACompromise)e.push("aACompromise");if(t&cl.affiliationChanged)e.push("affiliationChanged");if(t&cl.cACompromise)e.push("cACompromise");if(t&cl.certificateHold)e.push("certificateHold");if(t&cl.cessationOfOperation)e.push("cessationOfOperation");if(t&cl.keyCompromise)e.push("keyCompromise");if(t&cl.privilegeWithdrawn)e.push("privilegeWithdrawn");if(t&cl.superseded)e.push("superseded");if(t&cl.unused)e.push("unused");return e}toString(){return`[${this.toJSON().join(", ")}]`}}var Eu=class{fullName;nameRelativeToCRLIssuer;constructor(t={}){Object.assign(this,t)}};h([v({type:it,context:0,repeated:"sequence",implicit:!0})],Eu.prototype,"fullName",void 0);h([v({type:Jp,context:1,implicit:!0})],Eu.prototype,"nameRelativeToCRLIssuer",void 0);Eu=h([z({type:B.Choice})],Eu);class bu{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}}h([v({type:Eu,context:0,optional:!0})],bu.prototype,"distributionPoint",void 0);h([v({type:fC,context:1,optional:!0,implicit:!0})],bu.prototype,"reasons",void 0);h([v({type:it,context:2,optional:!0,repeated:"sequence",implicit:!0})],bu.prototype,"cRLIssuer",void 0);var ef=BM=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,BM.prototype)}};ef=BM=h([z({type:B.Sequence,itemType:bu})],ef);var $M,Bst=`${wt}.46`,x3=$M=class extends ef{constructor(t){super(t);Object.setPrototypeOf(this,$M.prototype)}};x3=$M=h([z({type:B.Sequence,itemType:bu})],x3);var Vst=`${wt}.28`;class xs{static ONLY=!1;distributionPoint;onlyContainsUserCerts=xs.ONLY;onlyContainsCACerts=xs.ONLY;onlySomeReasons;indirectCRL=xs.ONLY;onlyContainsAttributeCerts=xs.ONLY;constructor(e={}){Object.assign(this,e)}}h([v({type:Eu,context:0,optional:!0})],xs.prototype,"distributionPoint",void 0);h([v({type:A.Boolean,context:1,defaultValue:xs.ONLY,implicit:!0})],xs.prototype,"onlyContainsUserCerts",void 0);h([v({type:A.Boolean,context:2,defaultValue:xs.ONLY,implicit:!0})],xs.prototype,"onlyContainsCACerts",void 0);h([v({type:fC,context:3,optional:!0,implicit:!0})],xs.prototype,"onlySomeReasons",void 0);h([v({type:A.Boolean,context:4,defaultValue:xs.ONLY,implicit:!0})],xs.prototype,"indirectCRL",void 0);h([v({type:A.Boolean,context:5,defaultValue:xs.ONLY,implicit:!0})],xs.prototype,"onlyContainsAttributeCerts",void 0);var qM=`${wt}.21`,ab;(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"})(ab||(ab={}));var vS=class{reason=ab.unspecified;constructor(t=ab.unspecified){this.reason=t}toJSON(){return ab[this.reason]}toString(){return this.toJSON()}};h([v({type:A.Enumerated})],vS.prototype,"reason",void 0);vS=h([z({type:B.Choice})],vS);var jM,xS=`${wt}.37`,Qm=jM=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,jM.prototype)}};Qm=jM=h([z({type:B.Sequence,itemType:A.ObjectIdentifier})],Qm);var eat=`${xS}.0`,E3=`${Km}.1`,b3=`${Km}.2`,w3=`${Km}.3`,T3=`${Km}.4`,A3=`${Km}.8`,I3=`${Km}.9`;var iat=`${wt}.54`,HM=class{value;constructor(t=new ArrayBuffer(0)){this.value=t}};h([v({type:A.Integer,converter:Kt})],HM.prototype,"value",void 0);HM=h([z({type:B.Choice})],HM);var WM=`${wt}.24`,ES=class{value=new Date;constructor(t){if(t)this.value=t}};h([v({type:A.GeneralizedTime})],ES.prototype,"value",void 0);ES=h([z({type:B.Choice})],ES);var VM,zM=`${wt}.18`,R3=VM=class extends ln{constructor(t){super(t);Object.setPrototypeOf(this,VM.prototype)}};R3=VM=h([z({type:B.Sequence})],R3);var mC=`${wt}.15`,ll;(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"})(ll||(ll={}));class cb extends Su{toJSON(){let e=this.toNumber(),t=[];if(e&ll.cRLSign)t.push("crlSign");if(e&ll.dataEncipherment)t.push("dataEncipherment");if(e&ll.decipherOnly)t.push("decipherOnly");if(e&ll.digitalSignature)t.push("digitalSignature");if(e&ll.encipherOnly)t.push("encipherOnly");if(e&ll.keyAgreement)t.push("keyAgreement");if(e&ll.keyCertSign)t.push("keyCertSign");if(e&ll.keyEncipherment)t.push("keyEncipherment");if(e&ll.nonRepudiation)t.push("nonRepudiation");return t}toString(){return`[${this.toJSON().join(", ")}]`}}var KM,wat=`${wt}.30`;class lb{base=new it;minimum=0;maximum;constructor(e={}){Object.assign(this,e)}}h([v({type:it})],lb.prototype,"base",void 0);h([v({type:A.Integer,context:0,defaultValue:0,implicit:!0})],lb.prototype,"minimum",void 0);h([v({type:A.Integer,context:1,optional:!0,implicit:!0})],lb.prototype,"maximum",void 0);var yC=KM=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,KM.prototype)}};yC=KM=h([z({type:B.Sequence,itemType:lb})],yC);class GM{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}}h([v({type:yC,context:0,optional:!0,implicit:!0})],GM.prototype,"permittedSubtrees",void 0);h([v({type:yC,context:1,optional:!0,implicit:!0})],GM.prototype,"excludedSubtrees",void 0);var Pat=`${wt}.36`;class QM{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}}h([v({type:A.Integer,context:0,implicit:!0,optional:!0,converter:Kt})],QM.prototype,"requireExplicitPolicy",void 0);h([v({type:A.Integer,context:1,implicit:!0,optional:!0,converter:Kt})],QM.prototype,"inhibitPolicyMapping",void 0);var JM,Oat=`${wt}.33`;class hC{issuerDomainPolicy="";subjectDomainPolicy="";constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier})],hC.prototype,"issuerDomainPolicy",void 0);h([v({type:A.ObjectIdentifier})],hC.prototype,"subjectDomainPolicy",void 0);var P3=JM=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,JM.prototype)}};P3=JM=h([z({type:B.Sequence,itemType:hC})],P3);var YM,wS=`${wt}.17`,bS=YM=class extends ln{constructor(t){super(t);Object.setPrototypeOf(this,YM.prototype)}};bS=YM=h([z({type:B.Sequence})],bS);class ji{type="";values=[];constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier})],ji.prototype,"type",void 0);h([v({type:A.Any,repeated:"set"})],ji.prototype,"values",void 0);var XM,Kat=`${wt}.9`,C3=XM=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,XM.prototype)}};C3=XM=h([z({type:B.Sequence,itemType:ji})],C3);var gC=`${wt}.14`;class Oa extends hS{}var tct=`${wt}.16`;class ZM{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}}h([v({type:A.GeneralizedTime,context:0,implicit:!0,optional:!0})],ZM.prototype,"notBefore",void 0);h([v({type:A.GeneralizedTime,context:1,implicit:!0,optional:!0})],ZM.prototype,"notAfter",void 0);var db;(function(e){e[e.keyUpdateAllowed=1]="keyUpdateAllowed",e[e.newExtensions=2]="newExtensions",e[e.pKIXCertificate=4]="pKIXCertificate"})(db||(db={}));class eL extends Su{toJSON(){let e=[],t=this.toNumber();if(t&db.pKIXCertificate)e.push("pKIXCertificate");if(t&db.newExtensions)e.push("newExtensions");if(t&db.keyUpdateAllowed)e.push("keyUpdateAllowed");return e}toString(){return`[${this.toJSON().join(", ")}]`}}class tL{entrustVers="";entrustInfoFlags=new eL;constructor(e={}){Object.assign(this,e)}}h([v({type:A.GeneralString})],tL.prototype,"entrustVers",void 0);h([v({type:eL})],tL.prototype,"entrustInfoFlags",void 0);var rL,dct=`${Yp}.11`,_3=rL=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,rL.prototype)}};_3=rL=h([z({type:B.Sequence,itemType:Xp})],_3);class me{algorithm="";parameters;constructor(e={}){Object.assign(this,e)}isEqual(e){return e instanceof me&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&XE(e.parameters,this.parameters)||e.parameters===this.parameters)}}h([v({type:A.ObjectIdentifier})],me.prototype,"algorithm",void 0);h([v({type:A.Any,optional:!0})],me.prototype,"parameters",void 0);class Es{algorithm=new me;subjectPublicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:me})],Es.prototype,"algorithm",void 0);h([v({type:A.BitString})],Es.prototype,"subjectPublicKey",void 0);var Bn=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}};h([v({type:A.UTCTime})],Bn.prototype,"utcTime",void 0);h([v({type:A.GeneralizedTime})],Bn.prototype,"generalTime",void 0);Bn=h([z({type:B.Choice})],Bn);class Jm{notBefore=new Bn(new Date);notAfter=new Bn(new Date);constructor(e){if(e)this.notBefore=new Bn(e.notBefore),this.notAfter=new Bn(e.notAfter)}}h([v({type:Bn})],Jm.prototype,"notBefore",void 0);h([v({type:Bn})],Jm.prototype,"notAfter",void 0);var nL;class bs{static CRITICAL=!1;extnID="";critical=bs.CRITICAL;extnValue=new he;constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier})],bs.prototype,"extnID",void 0);h([v({type:A.Boolean,defaultValue:bs.CRITICAL})],bs.prototype,"critical",void 0);h([v({type:he})],bs.prototype,"extnValue",void 0);var Sc=nL=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,nL.prototype)}};Sc=nL=h([z({type:B.Sequence,itemType:bs})],Sc);var wu;(function(e){e[e.v1=0]="v1",e[e.v2=1]="v2",e[e.v3=2]="v3"})(wu||(wu={}));class ws{version=wu.v1;serialNumber=new ArrayBuffer(0);signature=new me;issuer=new en;validity=new Jm;subject=new en;subjectPublicKeyInfo=new Es;issuerUniqueID;subjectUniqueID;extensions;constructor(e={}){Object.assign(this,e)}}h([v({type:A.Integer,context:0,defaultValue:wu.v1})],ws.prototype,"version",void 0);h([v({type:A.Integer,converter:Kt})],ws.prototype,"serialNumber",void 0);h([v({type:me})],ws.prototype,"signature",void 0);h([v({type:en})],ws.prototype,"issuer",void 0);h([v({type:Jm})],ws.prototype,"validity",void 0);h([v({type:en})],ws.prototype,"subject",void 0);h([v({type:Es})],ws.prototype,"subjectPublicKeyInfo",void 0);h([v({type:A.BitString,context:1,implicit:!0,optional:!0})],ws.prototype,"issuerUniqueID",void 0);h([v({type:A.BitString,context:2,implicit:!0,optional:!0})],ws.prototype,"subjectUniqueID",void 0);h([v({type:Sc,context:3,optional:!0})],ws.prototype,"extensions",void 0);class fo{tbsCertificate=new ws;tbsCertificateRaw;signatureAlgorithm=new me;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:ws,raw:!0})],fo.prototype,"tbsCertificate",void 0);h([v({type:me})],fo.prototype,"signatureAlgorithm",void 0);h([v({type:A.BitString})],fo.prototype,"signatureValue",void 0);class Tu{userCertificate=new ArrayBuffer(0);revocationDate=new Bn;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}}h([v({type:A.Integer,converter:Kt})],Tu.prototype,"userCertificate",void 0);h([v({type:Bn})],Tu.prototype,"revocationDate",void 0);h([v({type:bs,optional:!0,repeated:"sequence"})],Tu.prototype,"crlEntryExtensions",void 0);class vc{version;signature=new me;issuer=new en;thisUpdate=new Bn;nextUpdate;revokedCertificates;crlExtensions;constructor(e={}){Object.assign(this,e)}}h([v({type:A.Integer,optional:!0})],vc.prototype,"version",void 0);h([v({type:me})],vc.prototype,"signature",void 0);h([v({type:en})],vc.prototype,"issuer",void 0);h([v({type:Bn})],vc.prototype,"thisUpdate",void 0);h([v({type:Bn,optional:!0})],vc.prototype,"nextUpdate",void 0);h([v({type:Tu,repeated:"sequence",optional:!0})],vc.prototype,"revokedCertificates",void 0);h([v({type:bs,optional:!0,context:0,repeated:"sequence"})],vc.prototype,"crlExtensions",void 0);class Ym{tbsCertList=new vc;tbsCertListRaw;signatureAlgorithm=new me;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:vc,raw:!0})],Ym.prototype,"tbsCertList",void 0);h([v({type:me})],Ym.prototype,"signatureAlgorithm",void 0);h([v({type:A.BitString})],Ym.prototype,"signature",void 0);var D3={"2.5.4.6":"C","2.5.4.10":"O","2.5.4.11":"OU","2.5.4.3":"CN"};function TS(e){let t=Tn.parse(e,fo),r=t.tbsCertificate,n={combined:""};r.issuer.forEach(([s])=>{let a=D3[s.type];if(a)n[a]=s.value.toString()}),n.combined=O3(n);let o={combined:""};r.subject.forEach(([s])=>{let a=D3[s.type];if(a)o[a]=s.value.toString()}),o.combined=O3(o);let i=!1;if(r.extensions){for(let s of r.extensions)if(s.extnID===gS)i=Tn.parse(s.extnValue,Zp).cA}return{issuer:n,subject:o,version:r.version,basicConstraintsCA:i,notBefore:r.validity.notBefore.getTime(),notAfter:r.validity.notAfter.getTime(),parsedCertificate:t}}function O3(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 Hxt=so(F3());class ld{issuer=new en;serialNumber=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:en})],ld.prototype,"issuer",void 0);h([v({type:A.Integer,converter:Kt})],ld.prototype,"serialNumber",void 0);var Xm=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(t={}){Object.assign(this,t)}};h([v({type:Oa,context:0,implicit:!0})],Xm.prototype,"subjectKeyIdentifier",void 0);h([v({type:ld})],Xm.prototype,"issuerAndSerialNumber",void 0);Xm=h([z({type:B.Choice})],Xm);var li;(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"})(li||(li={}));var Zm=class extends me{};Zm=h([z({type:B.Sequence})],Zm);var ub=class extends me{};ub=h([z({type:B.Sequence})],ub);var Ys=class extends me{};Ys=h([z({type:B.Sequence})],Ys);var pb=class extends me{};pb=h([z({type:B.Sequence})],pb);var U3=class extends me{};U3=h([z({type:B.Sequence})],U3);var SC=class extends me{};SC=h([z({type:B.Sequence})],SC);class dd{attrType="";attrValues=[];constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier})],dd.prototype,"attrType",void 0);h([v({type:A.Any,repeated:"set"})],dd.prototype,"attrValues",void 0);var oL;class Na{version=li.v0;sid=new Xm;digestAlgorithm=new Zm;signedAttrs;signedAttrsRaw;signatureAlgorithm=new ub;signature=new he;unsignedAttrs;constructor(e={}){Object.assign(this,e)}}h([v({type:A.Integer})],Na.prototype,"version",void 0);h([v({type:Xm})],Na.prototype,"sid",void 0);h([v({type:Zm})],Na.prototype,"digestAlgorithm",void 0);h([v({type:dd,repeated:"set",context:0,implicit:!0,optional:!0,raw:!0})],Na.prototype,"signedAttrs",void 0);h([v({type:ub})],Na.prototype,"signatureAlgorithm",void 0);h([v({type:he})],Na.prototype,"signature",void 0);h([v({type:dd,repeated:"set",context:1,implicit:!0,optional:!0})],Na.prototype,"unsignedAttrs",void 0);var fb=oL=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,oL.prototype)}};fb=oL=h([z({type:B.Set,itemType:Na})],fb);var M3=class extends Na{};M3=h([z({type:B.Sequence})],M3);var L3=class extends Bn{};L3=h([z({type:B.Choice})],L3);class vC{acIssuer=new it;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}}h([v({type:it})],vC.prototype,"acIssuer",void 0);h([v({type:A.Integer})],vC.prototype,"acSerial",void 0);h([v({type:ji,repeated:"sequence"})],vC.prototype,"attrs",void 0);var iL,mb=iL=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,iL.prototype)}};mb=iL=h([z({type:B.Sequence,itemType:A.ObjectIdentifier})],mb);class yb{pathLenConstraint;permittedAttrs;excludedAttrs;permitUnSpecified=!0;constructor(e={}){Object.assign(this,e)}}h([v({type:A.Integer,optional:!0})],yb.prototype,"pathLenConstraint",void 0);h([v({type:mb,implicit:!0,context:0,optional:!0})],yb.prototype,"permittedAttrs",void 0);h([v({type:mb,implicit:!0,context:1,optional:!0})],yb.prototype,"excludedAttrs",void 0);h([v({type:A.Boolean,defaultValue:!0})],yb.prototype,"permitUnSpecified",void 0);class dl{issuer=new ln;serial=new ArrayBuffer(0);issuerUID=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:ln})],dl.prototype,"issuer",void 0);h([v({type:A.Integer,converter:Kt})],dl.prototype,"serial",void 0);h([v({type:A.BitString,optional:!0})],dl.prototype,"issuerUID",void 0);var sL;(function(e){e[e.publicKey=0]="publicKey",e[e.publicKeyCert=1]="publicKeyCert",e[e.otherObjectTypes=2]="otherObjectTypes"})(sL||(sL={}));class ul{digestedObjectType=sL.publicKey;otherObjectTypeID;digestAlgorithm=new me;objectDigest=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:A.Enumerated})],ul.prototype,"digestedObjectType",void 0);h([v({type:A.ObjectIdentifier,optional:!0})],ul.prototype,"otherObjectTypeID",void 0);h([v({type:me})],ul.prototype,"digestAlgorithm",void 0);h([v({type:A.BitString})],ul.prototype,"objectDigest",void 0);class AS{issuerName;baseCertificateID;objectDigestInfo;constructor(e={}){Object.assign(this,e)}}h([v({type:ln,optional:!0})],AS.prototype,"issuerName",void 0);h([v({type:dl,context:0,implicit:!0,optional:!0})],AS.prototype,"baseCertificateID",void 0);h([v({type:ul,context:1,implicit:!0,optional:!0})],AS.prototype,"objectDigestInfo",void 0);var ey=class{v1Form;v2Form;constructor(t={}){Object.assign(this,t)}};h([v({type:it,repeated:"sequence"})],ey.prototype,"v1Form",void 0);h([v({type:AS,context:0,implicit:!0})],ey.prototype,"v2Form",void 0);ey=h([z({type:B.Choice})],ey);class IS{notBeforeTime=new Date;notAfterTime=new Date;constructor(e={}){Object.assign(this,e)}}h([v({type:A.GeneralizedTime})],IS.prototype,"notBeforeTime",void 0);h([v({type:A.GeneralizedTime})],IS.prototype,"notAfterTime",void 0);class ty{baseCertificateID;entityName;objectDigestInfo;constructor(e={}){Object.assign(this,e)}}h([v({type:dl,implicit:!0,context:0,optional:!0})],ty.prototype,"baseCertificateID",void 0);h([v({type:ln,implicit:!0,context:1,optional:!0})],ty.prototype,"entityName",void 0);h([v({type:ul,implicit:!0,context:2,optional:!0})],ty.prototype,"objectDigestInfo",void 0);var aL;(function(e){e[e.v2=1]="v2"})(aL||(aL={}));class Fa{version=aL.v2;holder=new ty;issuer=new ey;signature=new me;serialNumber=new ArrayBuffer(0);attrCertValidityPeriod=new IS;attributes=[];issuerUniqueID;extensions;constructor(e={}){Object.assign(this,e)}}h([v({type:A.Integer})],Fa.prototype,"version",void 0);h([v({type:ty})],Fa.prototype,"holder",void 0);h([v({type:ey})],Fa.prototype,"issuer",void 0);h([v({type:me})],Fa.prototype,"signature",void 0);h([v({type:A.Integer,converter:Kt})],Fa.prototype,"serialNumber",void 0);h([v({type:IS})],Fa.prototype,"attrCertValidityPeriod",void 0);h([v({type:ji,repeated:"sequence"})],Fa.prototype,"attributes",void 0);h([v({type:A.BitString,optional:!0})],Fa.prototype,"issuerUniqueID",void 0);h([v({type:Sc,optional:!0})],Fa.prototype,"extensions",void 0);class RS{acinfo=new Fa;signatureAlgorithm=new me;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:Fa})],RS.prototype,"acinfo",void 0);h([v({type:me})],RS.prototype,"signatureAlgorithm",void 0);h([v({type:A.BitString})],RS.prototype,"signatureValue",void 0);var hb;(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"})(hb||(hb={}));class gb extends Su{}class Sb{type="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier,implicit:!0,context:0})],Sb.prototype,"type",void 0);h([v({type:A.Any,implicit:!0,context:1})],Sb.prototype,"value",void 0);class xC{policyId="";classList=new gb(hb.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier})],xC.prototype,"policyId",void 0);h([v({type:gb,defaultValue:new gb(hb.unclassified)})],xC.prototype,"classList",void 0);h([v({type:Sb,repeated:"set"})],xC.prototype,"securityCategories",void 0);class vb{cotets;oid;string;constructor(e={}){Object.assign(this,e)}}h([v({type:he})],vb.prototype,"cotets",void 0);h([v({type:A.ObjectIdentifier})],vb.prototype,"oid",void 0);h([v({type:A.Utf8String})],vb.prototype,"string",void 0);class cL{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}}h([v({type:ln,implicit:!0,context:0,optional:!0})],cL.prototype,"policyAuthority",void 0);h([v({type:vb,repeated:"sequence"})],cL.prototype,"values",void 0);var Wut=`${Yp}.4`,Vut=`${Yp}.6`,zut=`${Yp}.10`,Kut=`${wt}.55`,xb=`${iC}.10`,Gut=`${xb}.1`,Qut=`${xb}.2`,Jut=`${xb}.3`,Yut=`${xb}.4`,Xut=`${xb}.6`,lL="2.5.4",Zut=`${lL}.72`;var dL;class Eb{targetCertificate=new dl;targetName;certDigestInfo;constructor(e={}){Object.assign(this,e)}}h([v({type:dl})],Eb.prototype,"targetCertificate",void 0);h([v({type:it,optional:!0})],Eb.prototype,"targetName",void 0);h([v({type:ul,optional:!0})],Eb.prototype,"certDigestInfo",void 0);var PS=class{targetName;targetGroup;targetCert;constructor(t={}){Object.assign(this,t)}};h([v({type:it,context:0,implicit:!0})],PS.prototype,"targetName",void 0);h([v({type:it,context:1,implicit:!0})],PS.prototype,"targetGroup",void 0);h([v({type:Eb,context:2,implicit:!0})],PS.prototype,"targetCert",void 0);PS=h([z({type:B.Choice})],PS);var EC=dL=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,dL.prototype)}};EC=dL=h([z({type:B.Sequence,itemType:PS})],EC);var uL,B3=uL=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,uL.prototype)}};B3=uL=h([z({type:B.Sequence,itemType:EC})],B3);class pL{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}}h([v({type:ln,implicit:!0,context:0,optional:!0})],pL.prototype,"roleAuthority",void 0);h([v({type:it,implicit:!0,context:1})],pL.prototype,"roleName",void 0);class bC{service=new it;ident=new it;authInfo;constructor(e={}){Object.assign(this,e)}}h([v({type:it})],bC.prototype,"service",void 0);h([v({type:it})],bC.prototype,"ident",void 0);h([v({type:he,optional:!0})],bC.prototype,"authInfo",void 0);var fL;class wC{otherCertFormat="";otherCert=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier})],wC.prototype,"otherCertFormat",void 0);h([v({type:A.Any})],wC.prototype,"otherCert",void 0);var tf=class{certificate;v2AttrCert;other;constructor(t={}){Object.assign(this,t)}};h([v({type:fo})],tf.prototype,"certificate",void 0);h([v({type:RS,context:2,implicit:!0})],tf.prototype,"v2AttrCert",void 0);h([v({type:wC,context:3,implicit:!0})],tf.prototype,"other",void 0);tf=h([z({type:B.Choice})],tf);var rf=fL=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,fL.prototype)}};rf=fL=h([z({type:B.Set,itemType:tf})],rf);class Xs{contentType="";content=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier})],Xs.prototype,"contentType",void 0);h([v({type:A.Any,context:0})],Xs.prototype,"content",void 0);var ry=class{single;any;constructor(t={}){Object.assign(this,t)}};h([v({type:he})],ry.prototype,"single",void 0);h([v({type:A.Any})],ry.prototype,"any",void 0);ry=h([z({type:B.Choice})],ry);class CS{eContentType="";eContent;constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier})],CS.prototype,"eContentType",void 0);h([v({type:ry,context:0,optional:!0})],CS.prototype,"eContent",void 0);var bb=class{value;constructedValue;constructor(t={}){Object.assign(this,t)}};h([v({type:he,context:0,implicit:!0,optional:!0})],bb.prototype,"value",void 0);h([v({type:he,converter:$8,context:0,implicit:!0,optional:!0,repeated:"sequence"})],bb.prototype,"constructedValue",void 0);bb=h([z({type:B.Choice})],bb);class ny{contentType="";contentEncryptionAlgorithm=new pb;encryptedContent;constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier})],ny.prototype,"contentType",void 0);h([v({type:pb})],ny.prototype,"contentEncryptionAlgorithm",void 0);h([v({type:bb,optional:!0})],ny.prototype,"encryptedContent",void 0);class oy{keyAttrId="";keyAttr;constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier})],oy.prototype,"keyAttrId",void 0);h([v({type:A.Any,optional:!0})],oy.prototype,"keyAttr",void 0);var mL;class wb{subjectKeyIdentifier=new Oa;date;other;constructor(e={}){Object.assign(this,e)}}h([v({type:Oa})],wb.prototype,"subjectKeyIdentifier",void 0);h([v({type:A.GeneralizedTime,optional:!0})],wb.prototype,"date",void 0);h([v({type:oy,optional:!0})],wb.prototype,"other",void 0);var _S=class{rKeyId;issuerAndSerialNumber;constructor(t={}){Object.assign(this,t)}};h([v({type:wb,context:0,implicit:!0,optional:!0})],_S.prototype,"rKeyId",void 0);h([v({type:ld,optional:!0})],_S.prototype,"issuerAndSerialNumber",void 0);_S=h([z({type:B.Choice})],_S);class AC{rid=new _S;encryptedKey=new he;constructor(e={}){Object.assign(this,e)}}h([v({type:_S})],AC.prototype,"rid",void 0);h([v({type:he})],AC.prototype,"encryptedKey",void 0);var TC=mL=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,mL.prototype)}};TC=mL=h([z({type:B.Sequence,itemType:AC})],TC);class IC{algorithm=new me;publicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:me})],IC.prototype,"algorithm",void 0);h([v({type:A.BitString})],IC.prototype,"publicKey",void 0);var iy=class{subjectKeyIdentifier;originatorKey;issuerAndSerialNumber;constructor(t={}){Object.assign(this,t)}};h([v({type:Oa,context:0,implicit:!0,optional:!0})],iy.prototype,"subjectKeyIdentifier",void 0);h([v({type:IC,context:1,implicit:!0,optional:!0})],iy.prototype,"originatorKey",void 0);h([v({type:ld,optional:!0})],iy.prototype,"issuerAndSerialNumber",void 0);iy=h([z({type:B.Choice})],iy);class nf{version=li.v3;originator=new iy;ukm;keyEncryptionAlgorithm=new Ys;recipientEncryptedKeys=new TC;constructor(e={}){Object.assign(this,e)}}h([v({type:A.Integer})],nf.prototype,"version",void 0);h([v({type:iy,context:0})],nf.prototype,"originator",void 0);h([v({type:he,context:1,optional:!0})],nf.prototype,"ukm",void 0);h([v({type:Ys})],nf.prototype,"keyEncryptionAlgorithm",void 0);h([v({type:TC})],nf.prototype,"recipientEncryptedKeys",void 0);var kS=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(t={}){Object.assign(this,t)}};h([v({type:Oa,context:0,implicit:!0})],kS.prototype,"subjectKeyIdentifier",void 0);h([v({type:ld})],kS.prototype,"issuerAndSerialNumber",void 0);kS=h([z({type:B.Choice})],kS);class sy{version=li.v0;rid=new kS;keyEncryptionAlgorithm=new Ys;encryptedKey=new he;constructor(e={}){Object.assign(this,e)}}h([v({type:A.Integer})],sy.prototype,"version",void 0);h([v({type:kS})],sy.prototype,"rid",void 0);h([v({type:Ys})],sy.prototype,"keyEncryptionAlgorithm",void 0);h([v({type:he})],sy.prototype,"encryptedKey",void 0);class DS{keyIdentifier=new he;date;other;constructor(e={}){Object.assign(this,e)}}h([v({type:he})],DS.prototype,"keyIdentifier",void 0);h([v({type:A.GeneralizedTime,optional:!0})],DS.prototype,"date",void 0);h([v({type:oy,optional:!0})],DS.prototype,"other",void 0);class ay{version=li.v4;kekid=new DS;keyEncryptionAlgorithm=new Ys;encryptedKey=new he;constructor(e={}){Object.assign(this,e)}}h([v({type:A.Integer})],ay.prototype,"version",void 0);h([v({type:DS})],ay.prototype,"kekid",void 0);h([v({type:Ys})],ay.prototype,"keyEncryptionAlgorithm",void 0);h([v({type:he})],ay.prototype,"encryptedKey",void 0);class cy{version=li.v0;keyDerivationAlgorithm;keyEncryptionAlgorithm=new Ys;encryptedKey=new he;constructor(e={}){Object.assign(this,e)}}h([v({type:A.Integer})],cy.prototype,"version",void 0);h([v({type:SC,context:0,optional:!0})],cy.prototype,"keyDerivationAlgorithm",void 0);h([v({type:Ys})],cy.prototype,"keyEncryptionAlgorithm",void 0);h([v({type:he})],cy.prototype,"encryptedKey",void 0);class RC{oriType="";oriValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier})],RC.prototype,"oriType",void 0);h([v({type:A.Any})],RC.prototype,"oriValue",void 0);var Au=class{ktri;kari;kekri;pwri;ori;constructor(t={}){Object.assign(this,t)}};h([v({type:sy,optional:!0})],Au.prototype,"ktri",void 0);h([v({type:nf,context:1,implicit:!0,optional:!0})],Au.prototype,"kari",void 0);h([v({type:ay,context:2,implicit:!0,optional:!0})],Au.prototype,"kekri",void 0);h([v({type:cy,context:3,implicit:!0,optional:!0})],Au.prototype,"pwri",void 0);h([v({type:RC,context:4,implicit:!0,optional:!0})],Au.prototype,"ori",void 0);Au=h([z({type:B.Choice})],Au);var yL,Tb=yL=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,yL.prototype)}};Tb=yL=h([z({type:B.Set,itemType:Au})],Tb);var hL,$3=`${iC}.16`,Bft=`${$3}.2`,$ft=`${$3}.4`;class Ab{otherRevInfoFormat="";otherRevInfo=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier})],Ab.prototype,"otherRevInfoFormat",void 0);h([v({type:A.Any})],Ab.prototype,"otherRevInfo",void 0);var PC=class{other=new Ab;constructor(t={}){Object.assign(this,t)}};h([v({type:Ab,context:1,implicit:!0})],PC.prototype,"other",void 0);PC=h([z({type:B.Choice})],PC);var OS=hL=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,hL.prototype)}};OS=hL=h([z({type:B.Set,itemType:PC})],OS);class Ib{certs;crls;constructor(e={}){Object.assign(this,e)}}h([v({type:rf,context:0,implicit:!0,optional:!0})],Ib.prototype,"certs",void 0);h([v({type:OS,context:1,implicit:!0,optional:!0})],Ib.prototype,"crls",void 0);var gL,SL=gL=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,gL.prototype)}};SL=gL=h([z({type:B.Set,itemType:dd})],SL);class NS{version=li.v0;originatorInfo;recipientInfos=new Tb;encryptedContentInfo=new ny;unprotectedAttrs;constructor(e={}){Object.assign(this,e)}}h([v({type:A.Integer})],NS.prototype,"version",void 0);h([v({type:Ib,context:0,implicit:!0,optional:!0})],NS.prototype,"originatorInfo",void 0);h([v({type:Tb})],NS.prototype,"recipientInfos",void 0);h([v({type:ny})],NS.prototype,"encryptedContentInfo",void 0);h([v({type:SL,context:1,implicit:!0,optional:!0})],NS.prototype,"unprotectedAttrs",void 0);var q3="1.2.840.113549.1.7.1",CC="1.2.840.113549.1.7.2";var vL,_C=vL=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,vL.prototype)}};_C=vL=h([z({type:B.Set,itemType:Zm})],_C);class pl{version=li.v0;digestAlgorithms=new _C;encapContentInfo=new CS;certificates;crls;signerInfos=new fb;constructor(e={}){Object.assign(this,e)}}h([v({type:A.Integer})],pl.prototype,"version",void 0);h([v({type:_C})],pl.prototype,"digestAlgorithms",void 0);h([v({type:CS})],pl.prototype,"encapContentInfo",void 0);h([v({type:rf,context:0,implicit:!0,optional:!0})],pl.prototype,"certificates",void 0);h([v({type:OS,context:1,implicit:!0,optional:!0})],pl.prototype,"crls",void 0);h([v({type:fb})],pl.prototype,"signerInfos",void 0);var Iu="1.2.840.10045.2.1";var Rb="1.2.840.10045.4.1",kC="1.2.840.10045.4.3.1",Pb="1.2.840.10045.4.3.2",Cb="1.2.840.10045.4.3.3",_b="1.2.840.10045.4.3.4";var kb="1.2.840.10045.3.1.7";var Db="1.3.132.0.34";var xL="1.3.132.0.35";function Ob(e){return new me({algorithm:e})}var H3=Ob(Rb),Dmt=Ob(kC),W3=Ob(Pb),V3=Ob(Cb),z3=Ob(_b);var Nb=class{fieldType;parameters;constructor(t={}){Object.assign(this,t)}};h([v({type:A.ObjectIdentifier})],Nb.prototype,"fieldType",void 0);h([v({type:A.Any})],Nb.prototype,"parameters",void 0);Nb=h([z({type:B.Sequence})],Nb);class K3 extends he{}var FS=class{a;b;seed;constructor(t={}){Object.assign(this,t)}};h([v({type:A.OctetString})],FS.prototype,"a",void 0);h([v({type:A.OctetString})],FS.prototype,"b",void 0);h([v({type:A.BitString,optional:!0})],FS.prototype,"seed",void 0);FS=h([z({type:B.Sequence})],FS);var EL;(function(e){e[e.ecpVer1=1]="ecpVer1"})(EL||(EL={}));var ud=class{version=EL.ecpVer1;fieldID;curve;base;order;cofactor;constructor(t={}){Object.assign(this,t)}};h([v({type:A.Integer})],ud.prototype,"version",void 0);h([v({type:Nb})],ud.prototype,"fieldID",void 0);h([v({type:FS})],ud.prototype,"curve",void 0);h([v({type:K3})],ud.prototype,"base",void 0);h([v({type:A.Integer,converter:Kt})],ud.prototype,"order",void 0);h([v({type:A.Integer,optional:!0})],ud.prototype,"cofactor",void 0);ud=h([z({type:B.Sequence})],ud);var xc=class{namedCurve;implicitCurve;specifiedCurve;constructor(t={}){Object.assign(this,t)}};h([v({type:A.ObjectIdentifier})],xc.prototype,"namedCurve",void 0);h([v({type:A.Null})],xc.prototype,"implicitCurve",void 0);h([v({type:ud})],xc.prototype,"specifiedCurve",void 0);xc=h([z({type:B.Choice})],xc);class Fb{version=1;privateKey=new he;parameters;publicKey;constructor(e={}){Object.assign(this,e)}}h([v({type:A.Integer})],Fb.prototype,"version",void 0);h([v({type:he})],Fb.prototype,"privateKey",void 0);h([v({type:xc,context:0,optional:!0})],Fb.prototype,"parameters",void 0);h([v({type:A.BitString,context:1,optional:!0})],Fb.prototype,"publicKey",void 0);class of{r=new ArrayBuffer(0);s=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:A.Integer,converter:Kt})],of.prototype,"r",void 0);h([v({type:A.Integer,converter:Kt})],of.prototype,"s",void 0);var Ec="1.2.840.113549.1.1.1",G3="1.2.840.113549.1.1.7",Q3="1.2.840.113549.1.1.9",sf="1.2.840.113549.1.1.10",J3="1.2.840.113549.1.1.2",Y3="1.2.840.113549.1.1.4",US="1.2.840.113549.1.1.5",X3="1.2.840.113549.1.1.14";var DC="1.2.840.113549.1.1.11",MS="1.2.840.113549.1.1.12",LS="1.2.840.113549.1.1.13",bL="1.2.840.113549.1.1.15",wL="1.2.840.113549.1.1.16",ly="1.3.14.3.2.26",OC="2.16.840.1.101.3.4.2.4",dy="2.16.840.1.101.3.4.2.1",uy="2.16.840.1.101.3.4.2.2",py="2.16.840.1.101.3.4.2.3",Z3="2.16.840.1.101.3.4.2.5",eY="2.16.840.1.101.3.4.2.6",tY="1.2.840.113549.2.2",rY="1.2.840.113549.2.5",af="1.2.840.113549.1.1.8";function Go(e){return new me({algorithm:e,parameters:null})}var ryt=Go(tY),nyt=Go(rY),Ru=Go(ly),oyt=Go(OC),iyt=Go(dy),syt=Go(uy),ayt=Go(py),cyt=Go(Z3),lyt=Go(eY),NC=new me({algorithm:af,parameters:ue.serialize(Ru)}),TL=new me({algorithm:Q3,parameters:ue.serialize(pS.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))}),dyt=Go(Ec),uyt=Go(J3),pyt=Go(Y3),fyt=Go(US),myt=Go(bL),yyt=Go(wL),hyt=Go(MS),gyt=Go(LS),Syt=Go(bL),vyt=Go(wL);class Ub{hashAlgorithm=new me(Ru);maskGenAlgorithm=new me({algorithm:af,parameters:ue.serialize(Ru)});pSourceAlgorithm=new me(TL);constructor(e={}){Object.assign(this,e)}}h([v({type:me,context:0,defaultValue:Ru})],Ub.prototype,"hashAlgorithm",void 0);h([v({type:me,context:1,defaultValue:NC})],Ub.prototype,"maskGenAlgorithm",void 0);h([v({type:me,context:2,defaultValue:TL})],Ub.prototype,"pSourceAlgorithm",void 0);var Iyt=new me({algorithm:G3,parameters:ue.serialize(new Ub)});class Pu{hashAlgorithm=new me(Ru);maskGenAlgorithm=new me({algorithm:af,parameters:ue.serialize(Ru)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}}h([v({type:me,context:0,defaultValue:Ru})],Pu.prototype,"hashAlgorithm",void 0);h([v({type:me,context:1,defaultValue:NC})],Pu.prototype,"maskGenAlgorithm",void 0);h([v({type:A.Integer,context:2,defaultValue:20})],Pu.prototype,"saltLength",void 0);h([v({type:A.Integer,context:3,defaultValue:1})],Pu.prototype,"trailerField",void 0);var Oyt=new me({algorithm:sf,parameters:ue.serialize(new Pu)});class BS{digestAlgorithm=new me;digest=new he;constructor(e={}){Object.assign(this,e)}}h([v({type:me})],BS.prototype,"digestAlgorithm",void 0);h([v({type:he})],BS.prototype,"digest",void 0);var AL;class Mb{prime=new ArrayBuffer(0);exponent=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:A.Integer,converter:Kt})],Mb.prototype,"prime",void 0);h([v({type:A.Integer,converter:Kt})],Mb.prototype,"exponent",void 0);h([v({type:A.Integer,converter:Kt})],Mb.prototype,"coefficient",void 0);var FC=AL=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,AL.prototype)}};FC=AL=h([z({type:B.Sequence,itemType:Mb})],FC);class fl{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)}}h([v({type:A.Integer})],fl.prototype,"version",void 0);h([v({type:A.Integer,converter:Kt})],fl.prototype,"modulus",void 0);h([v({type:A.Integer,converter:Kt})],fl.prototype,"publicExponent",void 0);h([v({type:A.Integer,converter:Kt})],fl.prototype,"privateExponent",void 0);h([v({type:A.Integer,converter:Kt})],fl.prototype,"prime1",void 0);h([v({type:A.Integer,converter:Kt})],fl.prototype,"prime2",void 0);h([v({type:A.Integer,converter:Kt})],fl.prototype,"exponent1",void 0);h([v({type:A.Integer,converter:Kt})],fl.prototype,"exponent2",void 0);h([v({type:A.Integer,converter:Kt})],fl.prototype,"coefficient",void 0);h([v({type:FC,optional:!0})],fl.prototype,"otherPrimeInfos",void 0);class fy{modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:A.Integer,converter:Kt})],fy.prototype,"modulus",void 0);h([v({type:A.Integer,converter:Kt})],fy.prototype,"publicExponent",void 0);var IL;(function(e){e[e.Transient=0]="Transient",e[e.Singleton=1]="Singleton",e[e.ResolutionScoped=2]="ResolutionScoped",e[e.ContainerScoped=3]="ContainerScoped"})(IL||(IL={}));var Pi=IL;var TY=so(wY(),1),{__extends:Lb,__assign:lht,__rest:dht,__decorate:uht,__param:pht,__metadata:fht,__awaiter:AY,__generator:IY,__exportStar:mht,__createBinding:yht,__values:Bb,__read:qS,__spread:pd,__spreadArrays:hht,__await:ght,__asyncGenerator:Sht,__asyncDelegator:vht,__asyncValues:xht,__makeTemplateObject:Eht,__importStar:bht,__importDefault:wht,__classPrivateFieldGet:Tht,__classPrivateFieldSet:Aht}=TY.default;var $Te="injectionTokens";function PL(e){var t=Reflect.getMetadata("design:paramtypes",e)||[],r=Reflect.getOwnMetadata($Te,e)||{};return Object.keys(r).forEach(function(n){t[+n]=r[n]}),t}function $b(e){return!!e.useClass}function jS(e){return!!e.useFactory}var LC=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,pd(i))}};return this.reflectMethods.forEach(n),r},e}();function cf(e){return typeof e==="string"||typeof e==="symbol"}function CL(e){return typeof e==="object"&&"token"in e&&"multiple"in e}function BC(e){return typeof e==="object"&&"token"in e&&"transform"in e}function RY(e){return typeof e==="function"||e instanceof LC}function my(e){return!!e.useToken}function yy(e){return e.useValue!=null}function PY(e){return $b(e)||yy(e)||my(e)||jS(e)}var qTe=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}(),qb=qTe;var jTe=function(e){Lb(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(qb),CY=jTe;var HTe=function(){function e(){this.scopedResolutions=new Map}return e}(),jb=HTe;function WTe(e,t){if(e===null)return"at position #"+t;var r=e.split(",")[t].trim();return'"'+r+'" at position #'+t}function VTe(e,t,r){if(r===void 0)r=" ";return pd([e],t.message.split(`
|
|
498
|
+
`).map(function(n){return r+n})).join(`
|
|
499
|
+
`)}function _L(e,t,r){var n=qS(e.toString().match(/constructor\(([\w, ]+)\)/)||[],2),o=n[1],i=o===void 0?null:o,s=WTe(i,t);return VTe("Cannot inject the dependency "+s+' of "'+e.name+'" constructor. Reason:',r)}function _Y(e){if(typeof e.dispose!=="function")return!1;var t=e.dispose;if(t.length>0)return!1;return!0}var zTe=function(e){Lb(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(qb);var KTe=function(e){Lb(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(qb);var GTe=function(){function e(){this.preResolution=new zTe,this.postResolution=new KTe}return e}(),kY=GTe;var kL=new Map,QTe=function(){function e(t){this.parent=t,this._registry=new CY,this.interceptors=new kY,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(t,r,n){if(n===void 0)n={lifecycle:Pi.Transient};this.ensureNotDisposed();var o;if(!PY(r))o={useClass:r};else o=r;if(my(o)){var i=[t],s=o;while(s!=null){var a=s.useToken;if(i.includes(a))throw Error("Token registration cycle detected! "+pd(i,[a]).join(" -> "));i.push(a);var c=this._registry.get(a);if(c&&my(c.provider))s=c.provider;else s=null}}if(n.lifecycle===Pi.Singleton||n.lifecycle==Pi.ContainerScoped||n.lifecycle==Pi.ResolutionScoped){if(yy(o)||jS(o))throw Error('Cannot use lifecycle "'+Pi[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(),cf(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(),cf(t)){if(cf(r))return this.register(t,{useToken:r},{lifecycle:Pi.Singleton});else if(r)return this.register(t,{useClass:r},{lifecycle:Pi.Singleton});throw Error('Cannot register a type name as a singleton without a "to" token')}var n=t;if(r&&!cf(r))n=r;return this.register(t,{useClass:n},{lifecycle:Pi.Singleton})},e.prototype.resolve=function(t,r,n){if(r===void 0)r=new jb;if(n===void 0)n=!1;this.ensureNotDisposed();var o=this.getRegistration(t);if(!o&&cf(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(RY(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=Bb(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=Bb(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===Pi.ResolutionScoped&&r.scopedResolutions.has(t))return r.scopedResolutions.get(t);var n=t.options.lifecycle===Pi.Singleton,o=t.options.lifecycle===Pi.ContainerScoped,i=n||o,s;if(yy(t.provider))s=t.provider.useValue;else if(my(t.provider))s=i?t.instance||(t.instance=this.resolve(t.provider.useToken,r)):this.resolve(t.provider.useToken,r);else if($b(t.provider))s=i?t.instance||(t.instance=this.construct(t.provider.useClass,r)):this.construct(t.provider.useClass,r);else if(jS(t.provider))s=t.provider.useFactory(this);else s=this.construct(t.provider,r);if(t.options.lifecycle===Pi.ResolutionScoped)r.scopedResolutions.set(t,s);return s},e.prototype.resolveAll=function(t,r,n){var o=this;if(r===void 0)r=new jb;if(n===void 0)n=!1;this.ensureNotDisposed();var i=this.getAllRegistrations(t);if(!i&&cf(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=Bb(this._registry.entries()),o=n.next();!o.done;o=n.next()){var i=qS(o.value,2),s=i[0],a=i[1];this._registry.setAll(s,a.filter(function(c){return!yy(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=Bb(this._registry.entries()),i=o.next();!i.done;i=o.next()){var s=qS(i.value,2),a=s[0],c=s[1];if(c.some(function(l){var d=l.options;return d.lifecycle===Pi.ContainerScoped}))n._registry.setAll(a,c.map(function(l){if(l.options.lifecycle===Pi.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 AY(this,void 0,void 0,function(){var t;return IY(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 LC)return t.createProxy(function(i){return n.resolve(i,r)});var o=function(){var i=kL.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,pd([void 0],s)))}();if(_Y(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(CL(o))if(BC(o))return o.multiple?(s=n.resolve(o.transform)).transform.apply(s,pd([n.resolveAll(o.token,new jb,o.isOptional)],o.transformArgs)):(a=n.resolve(o.transform)).transform.apply(a,pd([n.resolve(o.token,t,o.isOptional)],o.transformArgs));else return o.multiple?n.resolveAll(o.token,new jb,o.isOptional):n.resolve(o.token,t,o.isOptional);else if(BC(o))return(c=n.resolve(o.transform,t)).transform.apply(c,pd([n.resolve(o.token,t)],o.transformArgs));return n.resolve(o,t)}catch(l){throw Error(_L(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}(),tn=new QTe;function JTe(e){return function(t){if(kL.set(t,PL(t)),e&&e.token)if(!Array.isArray(e.token))tn.register(e.token,t);else e.token.forEach(function(r){tn.register(r,t)})}}var lf=JTe;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 OL;class HS{attrId="";attrValues=[];constructor(e={}){Object.assign(e)}}h([v({type:A.ObjectIdentifier})],HS.prototype,"attrId",void 0);h([v({type:A.Any,repeated:"set"})],HS.prototype,"attrValues",void 0);var DY=OL=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,OL.prototype)}};DY=OL=h([z({type:B.Sequence,itemType:HS})],DY);var NL,OY=NL=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,NL.prototype)}};OY=NL=h([z({type:B.Sequence,itemType:Xs})],OY);var hy="1.2.840.113549.1.12.10.1";var DSt=`${hy}.1`,OSt=`${hy}.2`,NSt=`${hy}.3`,FSt=`${hy}.4`,USt=`${hy}.5`,MSt=`${hy}.6`,$C="1.2.840.113549.1.9";class FL{certId="";certValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier})],FL.prototype,"certId",void 0);h([v({type:A.Any,context:0})],FL.prototype,"certValue",void 0);var NY=`${$C}.22`,jSt=`${NY}.1`,HSt=`${NY}.2`;class UL{crlId="";crltValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier})],UL.prototype,"crlId",void 0);h([v({type:A.Any,context:0})],UL.prototype,"crltValue",void 0);var YTe=`${$C}.23`,GSt=`${YTe}.1`;class ML extends he{}class gy{encryptionAlgorithm=new me;encryptedData=new ML;constructor(e={}){Object.assign(this,e)}}h([v({type:me})],gy.prototype,"encryptionAlgorithm",void 0);h([v({type:ML})],gy.prototype,"encryptedData",void 0);var LL,BL;(function(e){e[e.v1=0]="v1"})(BL||(BL={}));class qL extends he{}var $L=LL=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,LL.prototype)}};$L=LL=h([z({type:B.Sequence,itemType:ji})],$L);class Sy{version=BL.v1;privateKeyAlgorithm=new me;privateKey=new qL;attributes;constructor(e={}){Object.assign(this,e)}}h([v({type:A.Integer})],Sy.prototype,"version",void 0);h([v({type:me})],Sy.prototype,"privateKeyAlgorithm",void 0);h([v({type:qL})],Sy.prototype,"privateKey",void 0);h([v({type:$L,implicit:!0,context:0,optional:!0})],Sy.prototype,"attributes",void 0);var FY=class extends Sy{};FY=h([z({type:B.Sequence})],FY);var UY=class extends gy{};UY=h([z({type:B.Sequence})],UY);class jL{secretTypeId="";secretValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier})],jL.prototype,"secretTypeId",void 0);h([v({type:A.Any,context:0})],jL.prototype,"secretValue",void 0);class vy{mac=new BS;macSalt=new he;iterations=1;constructor(e={}){Object.assign(this,e)}}h([v({type:BS})],vy.prototype,"mac",void 0);h([v({type:he})],vy.prototype,"macSalt",void 0);h([v({type:A.Integer,defaultValue:1})],vy.prototype,"iterations",void 0);class WS{version=3;authSafe=new Xs;macData=new vy;constructor(e={}){Object.assign(this,e)}}h([v({type:A.Integer})],WS.prototype,"version",void 0);h([v({type:Xs})],WS.prototype,"authSafe",void 0);h([v({type:vy,optional:!0})],WS.prototype,"macData",void 0);var HL;class Hb{bagId="";bagValue=new ArrayBuffer(0);bagAttributes;constructor(e={}){Object.assign(this,e)}}h([v({type:A.ObjectIdentifier})],Hb.prototype,"bagId",void 0);h([v({type:A.Any,context:0})],Hb.prototype,"bagValue",void 0);h([v({type:HS,repeated:"set",optional:!0})],Hb.prototype,"bagAttributes",void 0);var MY=HL=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,HL.prototype)}};MY=HL=h([z({type:B.Sequence,itemType:Hb})],MY);var WL,VL,zL,Qn="1.2.840.113549.1.9",zvt=`${Qn}.0`,YY=`${Qn}.24`,Vb=`${Qn}.25`,XY=`${Qn}.26`,ZY=`${Qn}.27`,Kvt=`${YY}.1`,Gvt=`${YY}.2`,Qvt=`${Qn}.1`,Jvt=`${Qn}.2`,Yvt=`${Qn}.3`,Xvt=`${Qn}.4`,Zvt=`${Qn}.5`,ext=`${Qn}.6`,eB=`${Qn}.7`,txt=`${Qn}.8`,rxt=`${Qn}.9`,nxt=`${Qn}.13`,zb=`${Qn}.14`,oxt=`${Qn}.15`,ixt=`${Qn}.20`,sxt=`${Qn}.21`;var axt=`${Vb}.1`,cxt=`${Vb}.2`,lxt=`${Vb}.3`,dxt=`${Vb}.4`,uxt=`${Vb}.5`,Kb="1.3.6.1.5.5.7.9",pxt=`${Kb}.1`,fxt=`${Kb}.2`,mxt=`${Kb}.3`,yxt=`${Kb}.4`,hxt=`${Kb}.5`,gxt=`${XY}.1`,Sxt=`${XY}.2`,vxt=`${ZY}.1`,xxt=`${ZY}.2`,Ext=`${Qn}.16`,bxt=`${Qn}.22`,wxt=`${Qn}.23`,Txt=`${lL}.65`,qC=class extends _o{ia5String;constructor(t={}){super(t)}toString(){return{}.toString(),this.ia5String||super.toString()}};h([v({type:A.IA5String})],qC.prototype,"ia5String",void 0);qC=h([z({type:B.Choice})],qC);var LY=class extends Xs{};LY=h([z({type:B.Sequence})],LY);var BY=class extends WS{};BY=h([z({type:B.Sequence})],BY);var $Y=class extends gy{};$Y=h([z({type:B.Sequence})],$Y);var KL=class{value;constructor(t=""){this.value=t}toString(){return this.value}};h([v({type:A.IA5String})],KL.prototype,"value",void 0);KL=h([z({type:B.Choice})],KL);var qY=class extends qC{};qY=h([z({type:B.Choice})],qY);var jY=class extends _o{};jY=h([z({type:B.Choice})],jY);var GL=class{value;constructor(t=new Date){this.value=t}};h([v({type:A.GeneralizedTime})],GL.prototype,"value",void 0);GL=h([z({type:B.Choice})],GL);var HY=class extends _o{};HY=h([z({type:B.Choice})],HY);var QL=class{value;constructor(t="M"){this.value=t}toString(){return this.value}};h([v({type:A.PrintableString})],QL.prototype,"value",void 0);QL=h([z({type:B.Choice})],QL);var jC=class{value;constructor(t=""){this.value=t}toString(){return this.value}};h([v({type:A.PrintableString})],jC.prototype,"value",void 0);jC=h([z({type:B.Choice})],jC);var WY=class extends jC{};WY=h([z({type:B.Choice})],WY);var VY=class extends _o{};VY=h([z({type:B.Choice})],VY);var JL=class{value;constructor(t=""){this.value=t}toString(){return this.value}};h([v({type:A.ObjectIdentifier})],JL.prototype,"value",void 0);JL=h([z({type:B.Choice})],JL);var zY=class extends Bn{};zY=h([z({type:B.Choice})],zY);var YL=class{value;constructor(t=0){this.value=t}toString(){return this.value.toString()}};h([v({type:A.Integer})],YL.prototype,"value",void 0);YL=h([z({type:B.Choice})],YL);var KY=class extends Na{};KY=h([z({type:B.Sequence})],KY);var Wb=class extends _o{};Wb=h([z({type:B.Choice})],Wb);var GY=WL=class extends Sc{constructor(t){super(t);Object.setPrototypeOf(this,WL.prototype)}};GY=WL=h([z({type:B.Sequence})],GY);var QY=VL=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,VL.prototype)}};QY=VL=h([z({type:B.Set,itemType:dd})],QY);var XL=class{value;constructor(t=""){this.value=t}toString(){return this.value}};h([v({type:A.BmpString})],XL.prototype,"value",void 0);XL=h([z({type:B.Choice})],XL);var ZL=class extends me{};ZL=h([z({type:B.Sequence})],ZL);var JY=zL=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,zL.prototype)}};JY=zL=h([z({type:B.Sequence,itemType:ZL})],JY);var tB,Gb=tB=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,tB.prototype)}};Gb=tB=h([z({type:B.Sequence,itemType:ji})],Gb);class Cu{version=0;subject=new en;subjectPKInfo=new Es;attributes=new Gb;constructor(e={}){Object.assign(this,e)}}h([v({type:A.Integer})],Cu.prototype,"version",void 0);h([v({type:en})],Cu.prototype,"subject",void 0);h([v({type:Es})],Cu.prototype,"subjectPKInfo",void 0);h([v({type:Gb,implicit:!0,context:0,optional:!0})],Cu.prototype,"attributes",void 0);class xy{certificationRequestInfo=new Cu;certificationRequestInfoRaw;signatureAlgorithm=new me;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}h([v({type:Cu,raw:!0})],xy.prototype,"certificationRequestInfo",void 0);h([v({type:me})],xy.prototype,"signatureAlgorithm",void 0);h([v({type:A.BitString})],xy.prototype,"signature",void 0);/*!
|
|
500
|
+
* MIT License
|
|
501
|
+
*
|
|
502
|
+
* Copyright (c) Peculiar Ventures. All rights reserved.
|
|
503
|
+
*
|
|
504
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
505
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
506
|
+
* in the Software without restriction, including without limitation the rights
|
|
507
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
508
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
509
|
+
* furnished to do so, subject to the following conditions:
|
|
510
|
+
*
|
|
511
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
512
|
+
* copies or substantial portions of the Software.
|
|
513
|
+
*
|
|
514
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
515
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
516
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
517
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
518
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
519
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
520
|
+
* SOFTWARE.
|
|
521
|
+
*
|
|
522
|
+
*/var Tw="crypto.algorithm";class L9{getAlgorithms(){return tn.resolveAll(Tw)}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 me({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 Ey="crypto.algorithmProvider";tn.registerSingleton(Ey,L9);var zC,ea="1.3.36.3.3.2.8.1.1",e9=`${ea}.1`,t9=`${ea}.2`,r9=`${ea}.3`,n9=`${ea}.4`,o9=`${ea}.5`,i9=`${ea}.6`,s9=`${ea}.7`,a9=`${ea}.8`,c9=`${ea}.9`,l9=`${ea}.10`,d9=`${ea}.11`,u9=`${ea}.12`,p9=`${ea}.13`,f9=`${ea}.14`,m9="brainpoolP160r1",y9="brainpoolP160t1",h9="brainpoolP192r1",g9="brainpoolP192t1",S9="brainpoolP224r1",v9="brainpoolP224t1",x9="brainpoolP256r1",E9="brainpoolP256t1",b9="brainpoolP320r1",w9="brainpoolP320t1",T9="brainpoolP384r1",A9="brainpoolP384t1",I9="brainpoolP512r1",R9="brainpoolP512t1",$n="ECDSA",bw=zC=class{toAsnAlgorithm(t){switch(t.name.toLowerCase()){case $n.toLowerCase():if("hash"in t)switch((typeof t.hash==="string"?t.hash:t.hash.name).toLowerCase()){case"sha-1":return H3;case"sha-256":return W3;case"sha-384":return V3;case"sha-512":return z3}else if("namedCurve"in t){let r="";switch(t.namedCurve){case"P-256":r=kb;break;case"K-256":r=zC.SECP256K1;break;case"P-384":r=Db;break;case"P-521":r=xL;break;case m9:r=e9;break;case y9:r=t9;break;case h9:r=r9;break;case g9:r=n9;break;case S9:r=o9;break;case v9:r=i9;break;case x9:r=s9;break;case E9:r=a9;break;case b9:r=c9;break;case w9:r=l9;break;case T9:r=d9;break;case A9:r=u9;break;case I9:r=p9;break;case R9:r=f9;break}if(r)return new me({algorithm:Iu,parameters:ue.serialize(new xc({namedCurve:r}))})}}return null}toWebAlgorithm(t){switch(t.algorithm){case Rb:return{name:$n,hash:{name:"SHA-1"}};case Pb:return{name:$n,hash:{name:"SHA-256"}};case Cb:return{name:$n,hash:{name:"SHA-384"}};case _b:return{name:$n,hash:{name:"SHA-512"}};case Iu:{if(!t.parameters)throw TypeError("Cannot get required parameters from EC algorithm");switch(ue.parse(t.parameters,xc).namedCurve){case kb:return{name:$n,namedCurve:"P-256"};case zC.SECP256K1:return{name:$n,namedCurve:"K-256"};case Db:return{name:$n,namedCurve:"P-384"};case xL:return{name:$n,namedCurve:"P-521"};case e9:return{name:$n,namedCurve:m9};case t9:return{name:$n,namedCurve:y9};case r9:return{name:$n,namedCurve:h9};case n9:return{name:$n,namedCurve:g9};case o9:return{name:$n,namedCurve:S9};case i9:return{name:$n,namedCurve:v9};case s9:return{name:$n,namedCurve:x9};case a9:return{name:$n,namedCurve:E9};case c9:return{name:$n,namedCurve:b9};case l9:return{name:$n,namedCurve:w9};case d9:return{name:$n,namedCurve:T9};case u9:return{name:$n,namedCurve:A9};case p9:return{name:$n,namedCurve:I9};case f9:return{name:$n,namedCurve:R9}}}}return null}};bw.SECP256K1="1.3.132.0.10";bw=zC=h([lf()],bw);tn.registerSingleton(Tw,bw);var B9=Symbol("name"),$9=Symbol("value");class nr{constructor(e,t={},r=""){this[B9]=e,this[$9]=r;for(let n in t)this[n]=t[n]}}nr.NAME=B9;nr.VALUE=$9;class q9{static toTextObject(e){let t=new nr("Algorithm Identifier",{},fd.toString(e.algorithm));if(e.parameters)switch(e.algorithm){case Iu:{let r=new bw().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 fd{static toString(e){let t=this.items[e];if(t)return t;return e}}fd.items={[ly]:"sha1",[OC]:"sha224",[dy]:"sha256",[uy]:"sha384",[py]:"sha512",[Ec]:"rsaEncryption",[US]:"sha1WithRSAEncryption",[X3]:"sha224WithRSAEncryption",[DC]:"sha256WithRSAEncryption",[MS]:"sha384WithRSAEncryption",[LS]:"sha512WithRSAEncryption",[Iu]:"ecPublicKey",[Rb]:"ecdsaWithSHA1",[kC]:"ecdsaWithSHA224",[Pb]:"ecdsaWithSHA256",[Cb]:"ecdsaWithSHA384",[_b]:"ecdsaWithSHA512",[E3]:"TLS WWW server authentication",[b3]:"TLS WWW client authentication",[w3]:"Code Signing",[T3]:"E-mail Protection",[A3]:"Time Stamping",[I3]:"OCSP Signing",[CC]:"Signed Data"};class ku{static serialize(e){return this.serializeObj(e).join(`
|
|
523
|
+
`)}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,t=0){let r=[],n=this.pad(t++),o="",i=e[nr.VALUE];if(i)o=` ${i}`;r.push(`${n}${e[nr.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[nr.NAME]=s,r.push(...this.serializeObj(l,t));else if(a instanceof nr)a[nr.NAME]=s,r.push(...this.serializeObj(a,t));else if(Te.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[nr.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=Te.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)}}ku.oidSerializer=fd;ku.algorithmSerializer=q9;var VS;class Du{get rawData(){if(!Ue(this,VS,"f"))Wt(this,VS,ue.serialize(this.asn),"f");return Ue(this,VS,"f")}constructor(...e){if(VS.set(this,void 0),Te.isBufferSource(e[0]))this.asn=ue.parse(e[0],e[1]),Wt(this,VS,Te.toArrayBuffer(e[0]),"f"),this.onInit(this.asn);else this.asn=e[0],this.onInit(this.asn)}equal(e){if(e instanceof Du)return kP(e.rawData,this.rawData);return!1}toString(e="text"){switch(e){case"asn":return ue.toString(this.rawData);case"text":return ku.serialize(this.toTextObject());case"hex":return Le.ToHex(this.rawData);case"base64":return Le.ToBase64(this.rawData);case"base64url":return Le.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 nr(this.getTextName(),{},e)}}VS=new WeakMap;Du.NAME="ASN";class Ma extends Du{constructor(...e){let t;if(Te.isBufferSource(e[0]))t=Te.toArrayBuffer(e[0]);else t=ue.serialize(new bs({extnID:e[0],critical:e[1],extnValue:new he(Te.toArrayBuffer(e[2]))}));super(t,bs)}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[nr.NAME]===Ma.NAME)e[nr.NAME]=fd.toString(this.type);return e}}var j9;class df{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[j9]="CryptoProvider",typeof self<"u"&&typeof crypto<"u")this.set(df.DEFAULT,crypto);else if(typeof global<"u"&&global.crypto&&global.crypto.subtle)this.set(df.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=df.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(df.DEFAULT,e);return this}}j9=Symbol.toStringTag;df.DEFAULT="default";var ko=new df,tAe=/^[0-2](?:\.[1-9][0-9]*)+$/;function rAe(e){return new RegExp(tAe).test(e)}class yB{constructor(e={}){this.items={};for(let t in e)this.register(t,e[t])}get(e){return this.items[e]||null}findId(e){if(!rAe(e))return this.get(e);return e}register(e,t){this.items[e]=t,this.items[t]=e}}var Zs=new yB;Zs.register("CN","2.5.4.3");Zs.register("L","2.5.4.7");Zs.register("ST","2.5.4.8");Zs.register("O","2.5.4.10");Zs.register("OU","2.5.4.11");Zs.register("C","2.5.4.6");Zs.register("DC","0.9.2342.19200300.100.1.25");Zs.register("E","1.2.840.113549.1.9.1");Zs.register("G","2.5.4.42");Zs.register("I","2.5.4.43");Zs.register("SN","2.5.4.4");Zs.register("T","2.5.4.12");function nAe(e,t){return`\\${Le.ToHex(Le.FromUtf8String(t)).toUpperCase()}`}function oAe(e){return e.replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,nAe)}class uf{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 yB,this.asn=new en;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 en)this.asn=e;else if(Te.isBufferSource(e))this.asn=ue.parse(e,en);else this.asn=this.fromJSON(e)}getField(e){let t=this.extraNames.findId(e)||Zs.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)||Zs.get(e)}toString(){return this.asn.map((e)=>e.map((t)=>{let r=this.getName(t.type)||t.type,n=t.value.anyValue?`#${Le.ToHex(t.value.anyValue)}`:oAe(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?`#${Le.ToHex(o.value.anyValue)}`:o.value.toString())}t.push(n)}return t}fromString(e){let t=new en,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 Jp([l]));o=c}return t}fromJSON(e){let t=new en;for(let r of e){let n=new Jp;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 yS({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=Le.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(uf.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,`
|
|
524
|
+
`).replace(/\\0d/ig,"\r").replace(/\\0g/ig,"\t").replace(/\\(.)/g,"$1")}toArrayBuffer(){return ue.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]||ko.get();else r=e[0]||ko.get();return await r.subtle.digest(n,this.toArrayBuffer())}}var H9="Cannot initialize GeneralName from ASN.1 data.",P9=`${H9} Unsupported string format in use.`,iAe=`${H9} Value doesn't match to GUID regular expression.`,C9=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,_9="1.3.6.1.4.1.311.25.1",k9="1.3.6.1.4.1.311.20.2.3",rB="dns",nB="dn",oB="email",iB="ip",sB="url",aB="guid",cB="upn",HC="id";class _u extends Du{constructor(...e){let t;if(e.length===2)switch(e[0]){case nB:{let r=new uf(e[1]).toArrayBuffer(),n=ue.parse(r,en);t=new it({directoryName:n});break}case rB:t=new it({dNSName:e[1]});break;case oB:t=new it({rfc822Name:e[1]});break;case aB:{let r=new RegExp(C9,"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 Le.ToHex(new Uint8Array(Le.FromHex(o)).reverse());return o}).join("");t=new it({otherName:new zm({typeId:_9,value:ue.serialize(new he(Le.FromHex(n)))})});break}case iB:t=new it({iPAddress:e[1]});break;case HC:t=new it({registeredID:e[1]});break;case cB:{t=new it({otherName:new zm({typeId:k9,value:ue.serialize(bM.toASN(e[1]))})});break}case sB:t=new it({uniformResourceIdentifier:e[1]});break;default:throw Error("Cannot create GeneralName. Unsupported type of the name")}else if(Te.isBufferSource(e[0]))t=ue.parse(e[0],it);else t=e[0];super(t)}onInit(e){if(e.dNSName!=null)this.type=rB,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=oB,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=iB,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=sB,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=HC,this.value=e.registeredID;else if(e.directoryName!=null)this.type=nB,this.value=new uf(e.directoryName).toString();else if(e.otherName!=null)if(e.otherName.typeId===_9){this.type=aB;let t=ue.parse(e.otherName.value,he),r=new RegExp(C9,"i").exec(Le.ToHex(t));if(!r)throw Error(iAe);this.value=r.slice(1).map((n,o)=>{if(o<3)return Le.ToHex(new Uint8Array(Le.FromHex(n)).reverse());return n}).join("-")}else if(e.otherName.typeId===k9)this.type=cB,this.value=ue.parse(e.otherName.value,_o).toString();else throw Error(P9);else throw Error(P9)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case nB:case rB:case aB:case iB:case HC:case cB:case sB:e=this.type.toUpperCase();break;case oB:e="Email";break;default:throw Error("Unsupported GeneralName type")}let t=this.value;if(this.type===HC)t=fd.toString(t);return new nr(e,void 0,t)}}class pf extends Du{constructor(e){let t;if(e instanceof ln)t=e;else if(Array.isArray(e)){let r=[];for(let n of e)if(n instanceof it)r.push(n);else{let o=ue.parse(new _u(n.type,n.value).rawData,it);r.push(o)}t=new ln(r)}else if(Te.isBufferSource(e))t=ue.parse(e,ln);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 _u(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[nr.NAME]];if(!Array.isArray(n))n=[],e[r[nr.NAME]]=n;n.push(r)}return e}}pf.NAME="GeneralNames";var Ew="-{5}",ww="\\n",sAe=`[^${ww}]+`,aAe=`${Ew}BEGIN (${sAe}(?=${Ew}))${Ew}`,cAe=`${Ew}END \\1${Ew}`,XS="\\n",lAe=`[^:${ww}]+`,dAe=`(?:[^${ww}]+${XS}(?: +[^${ww}]+${XS})*)`,uAe="[a-zA-Z0-9=+/]+",pAe=`(?:${uAe}${XS})+`,D9=`${aAe}${XS}(?:((?:${lAe}: ${dAe})+))?${XS}?(${pAe})${cAe}`;class Hi{static isPem(e){return typeof e==="string"&&new RegExp(D9,"g").test(e.replace(/\r/g,""))}static decodeWithHeaders(e){e=e.replace(/\r/g,"");let t=new RegExp(D9,"g"),r=[],n=null;while(n=t.exec(e)){let o=n[3].replace(new RegExp(`[${ww}]+`,"g"),""),i={type:n[1],headers:[],rawData:Le.FromBase64(o)},s=n[2];if(s){let a=s.split(new RegExp(XS,"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(!Te.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:Te.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(`
|
|
525
|
+
`)}else{if(!t)throw Error("Required argument 'tag' is missed");return this.encodeStruct({type:t,rawData:Te.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=Le.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(`
|
|
526
|
+
`)}}Hi.CertificateTag="CERTIFICATE";Hi.CrlTag="CRL";Hi.CertificateRequestTag="CERTIFICATE REQUEST";Hi.PublicKeyTag="PUBLIC KEY";Hi.PrivateKeyTag="PRIVATE KEY";class Ua extends Du{static isAsnEncoded(e){return Te.isBufferSource(e)||typeof e==="string"}static toArrayBuffer(e){if(typeof e==="string")if(Hi.isPem(e))return Hi.decode(e)[0];else if(Le.isHex(e))return Le.FromHex(e);else if(Le.isBase64(e))return Le.FromBase64(e);else if(Le.isBase64Url(e))return Le.FromBase64Url(e);else throw TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url");else{let t=Te.toUint8Array(e);if(t.length>0&&t[0]===48)return Te.toArrayBuffer(e);let r=Le.ToBinary(e);if(Hi.isPem(r))return Hi.decode(r)[0];else if(Le.isHex(r))return Le.FromHex(r);else if(Le.isBase64(r))return Le.FromBase64(r);else if(Le.isBase64Url(r))return Le.FromBase64Url(r);throw TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}}constructor(...e){if(Ua.isAsnEncoded(e[0]))super(Ua.toArrayBuffer(e[0]),e[1]);else super(e[0])}toString(e="pem"){switch(e){case"pem":return Hi.encode(this.rawData,this.tag);default:return super.toString(e)}}}class ml extends Ua{static async create(e,t=ko.get()){if(e instanceof ml)return e;else if(df.isCryptoKey(e)){if(e.type!=="public")throw TypeError("Public key is required");let r=await t.subtle.exportKey("spki",e);return new ml(r)}else if(e.publicKey)return e.publicKey;else if(Te.isBufferSource(e))return new ml(e);else throw TypeError("Unsupported PublicKeyType")}constructor(e){if(Ua.isAsnEncoded(e))super(e,Es);else super(e);this.tag=Hi.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]||ko.get();else t=e[0]||ko.get();let o=this.rawData,i=ue.parse(this.rawData,Es);if(i.algorithm.algorithm===sf)o=fAe(i,o);return t.subtle.importKey("spki",o,n,!0,r)}onInit(e){let t=tn.resolve(Ey),r=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case Ec:{let n=ue.parse(e.subjectPublicKey,fy),o=Te.toUint8Array(n.modulus);r.publicExponent=Te.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]||ko.get();else r=e[0]||ko.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=ko.get();else t=e[0];else if(e.length===2)r=e[0],t=e[1];else t=ko.get();let n=ue.parse(this.rawData,Es);return await t.subtle.digest(r,n.subjectPublicKey)}toTextObject(){let e=this.toTextObjectEmpty(),t=ue.parse(this.rawData,Es);switch(e.Algorithm=ku.serializeAlgorithm(t.algorithm),t.algorithm.algorithm){case Iu:e["EC Point"]=t.subjectPublicKey;break;case Ec:default:e["Raw Data"]=t.subjectPublicKey}return e}}function fAe(e,t){return e.algorithm=new me({algorithm:Ec,parameters:null}),t=ue.serialize(e),t}class by extends Ma{static async create(e,t=!1,r=ko.get()){if("name"in e&&"serialNumber"in e)return new by(e,t);let o=await(await ml.create(e,r)).getKeyIdentifier(r);return new by(Le.ToHex(o),t)}constructor(...e){if(Te.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]==="string"){let t=new vu({keyIdentifier:new hS(Le.FromHex(e[0]))});super(ob,e[1],ue.serialize(t))}else{let t=e[0],r=t.name instanceof pf?ue.parse(t.name.rawData,ln):t.name,n=new vu({authorityCertIssuer:r,authorityCertSerialNumber:Le.FromHex(t.serialNumber)});super(ob,e[1],ue.serialize(n))}}onInit(e){super.onInit(e);let t=ue.parse(e.extnValue,vu);if(t.keyIdentifier)this.keyId=Le.ToHex(t.keyIdentifier);if(t.authorityCertIssuer||t.authorityCertSerialNumber)this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?Le.ToHex(t.authorityCertSerialNumber):""}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=ue.parse(this.value,vu);if(t.authorityCertIssuer)e["Authority Issuer"]=new pf(t.authorityCertIssuer).toTextObject();if(t.authorityCertSerialNumber)e["Authority Serial Number"]=t.authorityCertSerialNumber;if(t.keyIdentifier)e[""]=t.keyIdentifier;return e}}by.NAME="Authority Key Identifier";class hB extends Ma{constructor(...e){if(Te.isBufferSource(e[0])){super(e[0]);let t=ue.parse(this.value,Zp);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{let t=new Zp({cA:e[0],pathLenConstraint:e[1]});super(gS,e[2],ue.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}}hB.NAME="Basic Constraints";var O9;(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"})(O9||(O9={}));class gB extends Ma{constructor(...e){if(Te.isBufferSource(e[0])){super(e[0]);let t=ue.parse(this.value,Qm);this.usages=t.map((r)=>r)}else{let t=new Qm(e[0]);super(xS,e[1],ue.serialize(t));this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[""]=this.usages.map((t)=>fd.toString(t)).join(", "),e}}gB.NAME="Extended Key Usages";var N9;(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"})(N9||(N9={}));class SB extends Ma{constructor(...e){if(Te.isBufferSource(e[0])){super(e[0]);let t=ue.parse(this.value,cb);this.usages=t.toNumber()}else{let t=new cb(e[0]);super(mC,e[1],ue.serialize(t));this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=ue.parse(this.value,cb);return e[""]=t.toJSON().join(", "),e}}SB.NAME="Key Usages";class ZS extends Ma{static async create(e,t=!1,r=ko.get()){let o=await(await ml.create(e,r)).getKeyIdentifier(r);return new ZS(Le.ToHex(o),t)}constructor(...e){if(Te.isBufferSource(e[0])){super(e[0]);let t=ue.parse(this.value,Oa);this.keyId=Le.ToHex(t)}else{let t=typeof e[0]==="string"?Le.FromHex(e[0]):e[0],r=new Oa(t);super(gC,e[1],ue.serialize(r));this.keyId=Le.ToHex(t)}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=ue.parse(this.value,Oa);return e[""]=t,e}}ZS.NAME="Subject Key Identifier";class vB extends Ma{constructor(...e){if(Te.isBufferSource(e[0]))super(e[0]);else super(wS,e[1],new pf(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=ue.parse(e.extnValue,bS);this.names=new pf(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let r in t)e[r]=t[r];return e}}vB.NAME="Subject Alternative Name";class Wi{static register(e,t){this.items.set(e,t)}static create(e){let t=new Ma(e),r=this.items.get(t.type);if(r)return new r(e);return t}}Wi.items=new Map;class xB extends Ma{constructor(...e){var t;if(Te.isBufferSource(e[0])){super(e[0]);let r=ue.parse(this.value,ib);this.policies=r.map((n)=>n.policyIdentifier)}else{let r=e[0],n=(t=e[1])!==null&&t!==void 0?t:!1,o=new ib(r.map((i)=>new SS({policyIdentifier:i})));super(cC,n,ue.serialize(o));this.policies=r}}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map((t)=>new nr("",{},fd.toString(t))),e}}xB.NAME="Certificate Policies";Wi.register(cC,xB);class Aw extends Ma{constructor(...e){var t;if(Te.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&typeof e[0][0]==="string"){let n=e[0].map((i)=>new bu({distributionPoint:new Eu({fullName:[new it({uniformResourceIdentifier:i})]})})),o=new ef(n);super(pC,e[1],ue.serialize(o))}else{let r=new ef(e[0]);super(pC,e[1],ue.serialize(r))}(t=this.distributionPoints)!==null&&t!==void 0||(this.distributionPoints=[])}onInit(e){super.onInit(e);let t=ue.parse(e.extnValue,ef);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 _u(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}}Aw.NAME="CRL Distribution Points";class EB extends Ma{constructor(...e){var t,r,n,o;if(Te.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof Gm){let i=new Gm(e[0]);super(sC,e[1],ue.serialize(i))}else{let i=e[0],s=new Gm;VC(s,i,kM,"ocsp"),VC(s,i,DM,"caIssuers"),VC(s,i,OM,"timeStamping"),VC(s,i,NM,"caRepository");super(sC,e[1],ue.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=[],ue.parse(e.extnValue,Gm).forEach((r)=>{switch(r.accessMethod){case kM:this.ocsp.push(new _u(r.accessLocation));break;case DM:this.caIssuers.push(new _u(r.accessLocation));break;case OM:this.timeStamping.push(new _u(r.accessLocation));break;case NM:this.caRepository.push(new _u(r.accessLocation));break}})}toTextObject(){let e=this.toTextObjectWithoutValue();if(this.ocsp.length)WC(e,"OCSP",this.ocsp);if(this.caIssuers.length)WC(e,"CA Issuers",this.caIssuers);if(this.timeStamping.length)WC(e,"Time Stamping",this.timeStamping);if(this.caRepository.length)WC(e,"CA Repository",this.caRepository);return e}}EB.NAME="Authority Info Access";function WC(e,t,r){if(r.length===1)e[t]=r[0].toTextObject();else{let n=new nr("");r.forEach((o,i)=>{let s=o.toTextObject(),a=`${s[nr.NAME]} ${i+1}`,c=n[a];if(!Array.isArray(c))c=[],n[a]=c;c.push(s)}),e[t]=n}}function VC(e,t,r,n){let o=t[n];if(o)(Array.isArray(o)?o:[o]).forEach((s)=>{if(typeof s==="string")s=new _u("url",s);e.push(new Xp({accessMethod:r,accessLocation:ue.parse(s.rawData,it)}))})}class bB extends Ma{constructor(...e){if(Te.isBufferSource(e[0]))super(e[0]);else super(zM,e[1],new pf(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=ue.parse(e.extnValue,ln);this.names=new pf(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let r in t)e[r]=t[r];return e}}bB.NAME="Issuer Alternative Name";class ev extends Du{constructor(...e){let t;if(Te.isBufferSource(e[0]))t=Te.toArrayBuffer(e[0]);else{let r=e[0],n=Array.isArray(e[1])?e[1].map((o)=>Te.toArrayBuffer(o)):[];t=ue.serialize(new ji({type:r,values:n}))}super(t,ji)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Value=this.values.map((t)=>new nr("",{"":t})),e}toTextObjectWithoutValue(){let e=this.toTextObjectEmpty();if(e[nr.NAME]===ev.NAME)e[nr.NAME]=fd.toString(this.type);return e}}ev.NAME="Attribute";class wB extends ev{constructor(...e){var t;if(Te.isBufferSource(e[0]))super(e[0]);else{let r=new Wb({printableString:e[0]});super(eB,[ue.serialize(r)])}(t=this.password)!==null&&t!==void 0||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){let t=ue.parse(this.values[0],Wb);this.password=t.toString()}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[nr.VALUE]=this.password,e}}wB.NAME="Challenge Password";class GC extends ev{constructor(...e){var t;if(Te.isBufferSource(e[0]))super(e[0]);else{let r=e[0],n=new Sc;for(let o of r)n.push(ue.parse(o.rawData,bs));super(zb,[ue.serialize(n)])}(t=this.items)!==null&&t!==void 0||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){let t=ue.parse(this.values[0],Sc);this.items=t.map((r)=>Wi.create(ue.serialize(r)))}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.items.map((r)=>r.toTextObject());for(let r of t)e[r[nr.NAME]]=r;return e}}GC.NAME="Extensions";class Iw{static register(e,t){this.items.set(e,t)}static create(e){let t=new ev(e),r=this.items.get(t.type);if(r)return new r(e);return t}}Iw.items=new Map;var Rw="crypto.signatureFormatter";class W9{toAsnSignature(e,t){return Te.toArrayBuffer(t)}toWebSignature(e,t){return Te.toArrayBuffer(t)}}var KC,uB=KC=class{static createPssParams(t,r){let n=KC.getHashAlgorithm(t);if(!n)return null;return new Pu({hashAlgorithm:n,maskGenAlgorithm:new me({algorithm:af,parameters:ue.serialize(n)}),saltLength:r})}static getHashAlgorithm(t){let r=tn.resolve(Ey);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 me({algorithm:US,parameters:null});case"sha-256":return new me({algorithm:DC,parameters:null});case"sha-384":return new me({algorithm:MS,parameters:null});case"sha-512":return new me({algorithm:LS,parameters:null})}}else return new me({algorithm:Ec,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=KC.createPssParams(t.hash,t.saltLength);if(!r)throw Error("Cannot create PSS parameters");return new me({algorithm:sf,parameters:ue.serialize(r)})}else return new me({algorithm:sf,parameters:null})}return null}toWebAlgorithm(t){switch(t.algorithm){case Ec:return{name:"RSASSA-PKCS1-v1_5"};case US:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case DC:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case MS:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case LS:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case sf:if(t.parameters){let r=ue.parse(t.parameters,Pu);return{name:"RSA-PSS",hash:tn.resolve(Ey).toWebAlgorithm(r.hashAlgorithm),saltLength:r.saltLength}}else return{name:"RSA-PSS"}}return null}};uB=KC=h([lf()],uB);tn.registerSingleton(Tw,uB);var pB=class{toAsnAlgorithm(t){switch(t.name.toLowerCase()){case"sha-1":return new me({algorithm:ly});case"sha-256":return new me({algorithm:dy});case"sha-384":return new me({algorithm:uy});case"sha-512":return new me({algorithm:py})}return null}toWebAlgorithm(t){switch(t.algorithm){case ly:return{name:"SHA-1"};case dy:return{name:"SHA-256"};case uy:return{name:"SHA-384"};case py:return{name:"SHA-512"}}return null}};pB=h([lf()],pB);tn.registerSingleton(Tw,pB);class bc{addPadding(e,t){let r=Te.toUint8Array(t),n=new Uint8Array(e);return n.set(r,e-r.length),n.buffer}removePadding(e,t=!1){let r=Te.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=bc.namedCurveSize.get(r)||bc.defaultNamedCurveSize,o=new of,i=Te.toUint8Array(t);return o.r=this.removePadding(i.slice(0,n),!0),o.s=this.removePadding(i.slice(n,n+n),!0),ue.serialize(o)}return null}toWebSignature(e,t){if(e.name==="ECDSA"){let r=ue.parse(t,of),n=e.namedCurve,o=bc.namedCurveSize.get(n)||bc.defaultNamedCurveSize,i=this.addPadding(o,this.removePadding(r.r)),s=this.addPadding(o,this.removePadding(r.s));return E6(i,s)}return null}}bc.namedCurveSize=new Map;bc.defaultNamedCurveSize=32;var lB="1.3.101.110",F9="1.3.101.111",dB="1.3.101.112",U9="1.3.101.113",fB=class{toAsnAlgorithm(t){let r=null;switch(t.name.toLowerCase()){case"ed25519":r=dB;break;case"x25519":r=lB;break;case"eddsa":switch(t.namedCurve.toLowerCase()){case"ed25519":r=dB;break;case"ed448":r=U9;break}break;case"ecdh-es":switch(t.namedCurve.toLowerCase()){case"x25519":r=lB;break;case"x448":r=F9;break}}if(r)return new me({algorithm:r});return null}toWebAlgorithm(t){switch(t.algorithm){case dB:return{name:"Ed25519"};case U9:return{name:"EdDSA",namedCurve:"Ed448"};case lB:return{name:"X25519"};case F9:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};fB=h([lf()],fB);tn.registerSingleton(Tw,fB);var Qb,Jb,Yb,Xb,Zb,ew,tw,zS;class V9 extends Ua{get subjectName(){if(!Ue(this,Jb,"f"))Wt(this,Jb,new uf(this.asn.certificationRequestInfo.subject),"f");return Ue(this,Jb,"f")}get subject(){if(!Ue(this,Yb,"f"))Wt(this,Yb,this.subjectName.toString(),"f");return Ue(this,Yb,"f")}get signatureAlgorithm(){if(!Ue(this,Xb,"f")){let e=tn.resolve(Ey);Wt(this,Xb,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return Ue(this,Xb,"f")}get signature(){if(!Ue(this,Zb,"f"))Wt(this,Zb,this.asn.signature,"f");return Ue(this,Zb,"f")}get publicKey(){if(!Ue(this,ew,"f"))Wt(this,ew,new ml(this.asn.certificationRequestInfo.subjectPKInfo),"f");return Ue(this,ew,"f")}get attributes(){if(!Ue(this,tw,"f"))Wt(this,tw,this.asn.certificationRequestInfo.attributes.map((e)=>Iw.create(ue.serialize(e))),"f");return Ue(this,tw,"f")}get extensions(){if(!Ue(this,zS,"f")){Wt(this,zS,[],"f");let e=this.getAttribute(zb);if(e instanceof GC)Wt(this,zS,e.items,"f")}return Ue(this,zS,"f")}get tbs(){if(!Ue(this,Qb,"f"))Wt(this,Qb,this.asn.certificationRequestInfoRaw||ue.serialize(this.asn.certificationRequestInfo),"f");return Ue(this,Qb,"f")}constructor(e){let t=Ua.isAsnEncoded(e)?[e,xy]:[e];super(t[0],t[1]);Qb.set(this,void 0),Jb.set(this,void 0),Yb.set(this,void 0),Xb.set(this,void 0),Zb.set(this,void 0),ew.set(this,void 0),tw.set(this,void 0),zS.set(this,void 0),this.tag=Hi.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=ko.get()){let t={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(t,["verify"],e),n=tn.resolveAll(Rw).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=ue.parse(this.rawData,xy),r=t.certificationRequestInfo,n=new nr("",{Version:`${wu[r.version]} (${r.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){let o=new nr("");for(let i of this.attributes){let s=i.toTextObject();o[s[nr.NAME]]=s}n.Attributes=o}return e.Data=n,e.Signature=new nr("",{Algorithm:ku.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}}Qb=new WeakMap,Jb=new WeakMap,Yb=new WeakMap,Xb=new WeakMap,Zb=new WeakMap,ew=new WeakMap,tw=new WeakMap,zS=new WeakMap;V9.NAME="PKCS#10 Certificate Request";var rw,nw,ow,iw,sw,aw,cw,lw,dw,uw,KS,pw;class ff extends Ua{get publicKey(){if(!Ue(this,pw,"f"))Wt(this,pw,new ml(this.asn.tbsCertificate.subjectPublicKeyInfo),"f");return Ue(this,pw,"f")}get serialNumber(){if(!Ue(this,nw,"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);Wt(this,nw,Le.ToHex(t),"f")}return Ue(this,nw,"f")}get subjectName(){if(!Ue(this,ow,"f"))Wt(this,ow,new uf(this.asn.tbsCertificate.subject),"f");return Ue(this,ow,"f")}get subject(){if(!Ue(this,iw,"f"))Wt(this,iw,this.subjectName.toString(),"f");return Ue(this,iw,"f")}get issuerName(){if(!Ue(this,sw,"f"))Wt(this,sw,new uf(this.asn.tbsCertificate.issuer),"f");return Ue(this,sw,"f")}get issuer(){if(!Ue(this,aw,"f"))Wt(this,aw,this.issuerName.toString(),"f");return Ue(this,aw,"f")}get notBefore(){if(!Ue(this,cw,"f")){let e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw Error("Cannot get 'notBefore' value");Wt(this,cw,e,"f")}return Ue(this,cw,"f")}get notAfter(){if(!Ue(this,lw,"f")){let e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw Error("Cannot get 'notAfter' value");Wt(this,lw,e,"f")}return Ue(this,lw,"f")}get signatureAlgorithm(){if(!Ue(this,dw,"f")){let e=tn.resolve(Ey);Wt(this,dw,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return Ue(this,dw,"f")}get signature(){if(!Ue(this,uw,"f"))Wt(this,uw,this.asn.signatureValue,"f");return Ue(this,uw,"f")}get extensions(){if(!Ue(this,KS,"f")){if(Wt(this,KS,[],"f"),this.asn.tbsCertificate.extensions)Wt(this,KS,this.asn.tbsCertificate.extensions.map((e)=>Wi.create(ue.serialize(e))),"f")}return Ue(this,KS,"f")}get tbs(){if(!Ue(this,rw,"f"))Wt(this,rw,this.asn.tbsCertificateRaw||ue.serialize(this.asn.tbsCertificate),"f");return Ue(this,rw,"f")}constructor(e){let t=Ua.isAsnEncoded(e)?[e,fo]:[e];super(t[0],t[1]);rw.set(this,void 0),nw.set(this,void 0),ow.set(this,void 0),iw.set(this,void 0),sw.set(this,void 0),aw.set(this,void 0),cw.set(this,void 0),lw.set(this,void 0),dw.set(this,void 0),uw.set(this,void 0),KS.set(this,void 0),pw.set(this,void 0),this.tag=Hi.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=ko.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 ml)r={...o.algorithm,...this.signatureAlgorithm},n=await o.export(r,["verify"],t);else if(Te.isBufferSource(o)){let c=new ml(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=tn.resolveAll(Rw).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=ko.get()),await t.subtle.digest(r,this.rawData)}async isSelfSigned(e=ko.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){let e=this.toTextObjectEmpty(),t=ue.parse(this.rawData,fo),r=t.tbsCertificate,n=new nr("",{Version:`${wu[r.version]} (${r.version})`,"Serial Number":r.serialNumber,"Signature Algorithm":ku.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new nr("",{"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 nr("");for(let i of this.extensions){let s=i.toTextObject();o[s[nr.NAME]]=s}n.Extensions=o}return e.Data=n,e.Signature=new nr("",{Algorithm:ku.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}}rw=new WeakMap,nw=new WeakMap,ow=new WeakMap,iw=new WeakMap,sw=new WeakMap,aw=new WeakMap,cw=new WeakMap,lw=new WeakMap,dw=new WeakMap,uw=new WeakMap,KS=new WeakMap,pw=new WeakMap;ff.NAME="Certificate";class z9 extends Array{constructor(e){super();if(Ua.isAsnEncoded(e))this.import(e);else if(e instanceof ff)this.push(e);else if(Array.isArray(e))for(let t of e)this.push(t)}export(e){let t=new pl;t.version=1,t.encapContentInfo.eContentType=q3,t.encapContentInfo.eContent=new ry({single:new he}),t.certificates=new rf(this.map((o)=>new tf({certificate:ue.parse(o.rawData,fo)})));let r=new Xs({contentType:CC,content:ue.serialize(t)}),n=ue.serialize(r);if(e==="raw")return n;return this.toString(e)}import(e){let t=Ua.toArrayBuffer(e),r=ue.parse(t,Xs);if(r.contentType!==CC)throw TypeError("Cannot parse CMS package. Incoming data is not a SignedData object.");let n=ue.parse(r.content,pl);this.clear();for(let o of n.certificates||[])if(o.certificate)this.push(new ff(o.certificate))}clear(){while(this.pop());}toString(e="pem"){let t=this.export("raw");switch(e){case"pem":return Hi.encode(t,"CMS");case"pem-chain":return this.map((r)=>r.toString("pem")).join(`
|
|
527
|
+
`);case"asn":return ue.toString(t);case"hex":return Le.ToHex(t);case"base64":return Le.ToBase64(t);case"base64url":return Le.ToBase64Url(t);case"text":return ku.serialize(this.toTextObject());default:throw TypeError("Argument 'format' is unsupported value")}}toTextObject(){let e=ue.parse(this.export("raw"),Xs),t=ue.parse(e.content,pl);return new nr("X509Certificates",{"Content Type":fd.toString(e.contentType),Content:new nr("",{Version:`${li[t.version]} (${t.version})`,Certificates:new nr("",{Certificate:this.map((n)=>n.toTextObject())})})})}}class TB{constructor(e={}){if(this.certificates=[],e.certificates)this.certificates=e.certificates}async build(e,t=ko.get()){let r=new z9(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(kP(o,s))throw Error("Cannot build a certificate chain. Circular dependency.")}r.push(n)}return r}async findIssuer(e,t=ko.get()){if(!await e.isSelfSigned(t)){let r=e.getExtension(ob);for(let n of this.certificates){if(n.subject!==e.issuer)continue;if(r){if(r.keyId){let o=n.getExtension(gC);if(o&&o.keyId!==r.keyId)continue}else if(r.certId){let o=n.getExtension(wS);if(o&&!(r.certId.serialNumber===n.serialNumber&&kP(ue.serialize(r.certId.name),ue.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 K9(e,t=ko.get()){let r=Te.toUint8Array(Le.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 fw,mw,GS,QS,JS,M9;(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"})(M9||(M9={}));class mB extends Du{get serialNumber(){if(!Ue(this,fw,"f"))Wt(this,fw,Le.ToHex(this.asn.userCertificate),"f");return Ue(this,fw,"f")}get revocationDate(){if(!Ue(this,mw,"f"))Wt(this,mw,this.asn.revocationDate.getTime(),"f");return Ue(this,mw,"f")}get reason(){if(Ue(this,GS,"f")===void 0)this.extensions;return Ue(this,GS,"f")}get invalidity(){if(Ue(this,QS,"f")===void 0)this.extensions;return Ue(this,QS,"f")}get extensions(){if(!Ue(this,JS,"f")){if(Wt(this,JS,[],"f"),this.asn.crlEntryExtensions)Wt(this,JS,this.asn.crlEntryExtensions.map((e)=>{let t=Wi.create(ue.serialize(e));switch(t.type){case qM:if(Ue(this,GS,"f")===void 0)Wt(this,GS,ue.parse(t.value,vS).reason,"f");break;case WM:if(Ue(this,QS,"f")===void 0)Wt(this,QS,ue.parse(t.value,ES).value,"f");break}return t}),"f")}return Ue(this,JS,"f")}constructor(...e){let t;if(Te.isBufferSource(e[0]))t=Te.toArrayBuffer(e[0]);else if(typeof e[0]==="string")t=ue.serialize(new Tu({userCertificate:K9(e[0]),revocationDate:new Bn(e[1]),crlEntryExtensions:e[2]}));else if(e[0]instanceof Tu)t=e[0];if(!t)throw TypeError("Cannot create X509CrlEntry instance. Wrong constructor arguments.");super(t,Tu);fw.set(this,void 0),mw.set(this,void 0),GS.set(this,void 0),QS.set(this,void 0),JS.set(this,void 0)}onInit(e){}}fw=new WeakMap,mw=new WeakMap,GS=new WeakMap,QS=new WeakMap,JS=new WeakMap;var yw,hw,gw,Sw,vw,xw,YS;class AB extends Ua{get version(){return this.asn.tbsCertList.version}get signatureAlgorithm(){if(!Ue(this,hw,"f")){let e=tn.resolve(Ey);Wt(this,hw,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return Ue(this,hw,"f")}get signature(){return this.asn.signature}get issuer(){return this.issuerName.toString()}get issuerName(){if(!Ue(this,gw,"f"))Wt(this,gw,new uf(this.asn.tbsCertList.issuer),"f");return Ue(this,gw,"f")}get thisUpdate(){if(!Ue(this,Sw,"f")){let e=this.asn.tbsCertList.thisUpdate.getTime();if(!e)throw Error("Cannot get 'thisUpdate' value");Wt(this,Sw,e,"f")}return Ue(this,Sw,"f")}get nextUpdate(){var e;if(Ue(this,vw,"f")===void 0)Wt(this,vw,((e=this.asn.tbsCertList.nextUpdate)===null||e===void 0?void 0:e.getTime())||void 0,"f");return Ue(this,vw,"f")}get entries(){var e;if(!Ue(this,xw,"f"))Wt(this,xw,((e=this.asn.tbsCertList.revokedCertificates)===null||e===void 0?void 0:e.map((t)=>new mB(t)))||[],"f");return Ue(this,xw,"f")}get extensions(){if(!Ue(this,YS,"f")){if(Wt(this,YS,[],"f"),this.asn.tbsCertList.crlExtensions)Wt(this,YS,this.asn.tbsCertList.crlExtensions.map((e)=>Wi.create(ue.serialize(e))),"f")}return Ue(this,YS,"f")}get tbs(){if(!Ue(this,yw,"f"))Wt(this,yw,this.asn.tbsCertListRaw||ue.serialize(this.asn.tbsCertList),"f");return Ue(this,yw,"f")}get tbsCertListSignatureAlgorithm(){return this.asn.tbsCertList.signature}get certListSignatureAlgorithm(){return this.asn.signatureAlgorithm}constructor(e){super(e,Ua.isAsnEncoded(e)?Ym:void 0);this.tag=Hi.CrlTag,yw.set(this,void 0),hw.set(this,void 0),gw.set(this,void 0),Sw.set(this,void 0),vw.set(this,void 0),xw.set(this,void 0),YS.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=ko.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 ff)r={...o.publicKey.algorithm,...o.signatureAlgorithm},n=await o.publicKey.export(r,["verify"]);else if(o instanceof ml)r={...o.algorithm,...this.signatureAlgorithm},n=await o.export(r,["verify"]);else r={...o.algorithm,...this.signatureAlgorithm},n=o}catch{return!1}let i=tn.resolveAll(Rw).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=ko.get()),await t.subtle.digest(r,this.rawData)}findRevoked(e){let t=typeof e==="string"?e:e.serialNumber,r=K9(t);for(let n of this.asn.tbsCertList.revokedCertificates||[])if(Te.isEqual(n.userCertificate,r))return new mB(ue.serialize(n));return null}}yw=new WeakMap,hw=new WeakMap,gw=new WeakMap,Sw=new WeakMap,vw=new WeakMap,xw=new WeakMap,YS=new WeakMap;Wi.register(gS,hB);Wi.register(xS,gB);Wi.register(mC,SB);Wi.register(gC,ZS);Wi.register(ob,by);Wi.register(wS,vB);Wi.register(pC,Aw);Wi.register(sC,EB);Wi.register(zM,bB);Iw.register(eB,wB);Iw.register(zb,GC);tn.registerSingleton(Rw,W9);tn.registerSingleton(Rw,bc);bc.namedCurveSize.set("P-256",32);bc.namedCurveSize.set("K-256",32);bc.namedCurveSize.set("P-384",48);bc.namedCurveSize.set("P-521",66);function QC(e){return mAe.stubThis(e)}var mAe={stubThis:(e)=>globalThis.fetch(e)};var G9={};async function Q9(e){let{extensions:t}=e;if(!t)return!1;let r,n,o;t.forEach((u)=>{if(u instanceof by)r=u;else if(u instanceof ZS)n=u;else if(u instanceof Aw)o=u});let i=void 0;if(r&&r.keyId)i=r.keyId;else if(n)i=n.keyId;if(i){let u=G9[i];if(u){let p=new Date;if(!u.nextUpdate||u.nextUpdate>p)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 QC(s)).arrayBuffer()}catch(u){return!1}let c;try{c=new AB(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 p=u.serialNumber;l.revokedCerts.push(p)}if(i)G9[i]=l;return l.revokedCerts.indexOf(e.serialNumber)>=0}return!1}function J9(e){let t;try{t=Vg(e)}catch(r){throw Error(`Error decoding authenticator extensions: ${r.message}`)}return Y9(t)}function Y9(e){let t={};for(let[r,n]of e)if(n instanceof Map)t[r]=Y9(n);else t[r]=n;return t}function IB(e){if(e.byteLength<37)throw Error(`Authenticator data was ${e.byteLength} bytes, expected at least 37 bytes`);let t=0,r=JC(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 g=r.getUint16(t);t+=2,d=e.slice(t,t+=g);let E=hAe("a301634f4b500327206745643235353139"),S=e.slice(t,t+E.byteLength),x=!1;if(yl(E,S))x=!0,e[t]=164;let w=Vg(e.slice(t)),_=Uint8Array.from(m6(w));if(x)e[t]=163;u=_,t+=_.byteLength}let p=void 0,y=void 0;if(s.ed){let g=Vg(e.slice(t));y=Uint8Array.from(m6(g)),p=J9(y),t+=y.byteLength}if(e.byteLength>t)throw Error("Leftover bytes detected while parsing authenticator data");return yAe.stubThis({rpIdHash:n,flagsBuf:o,flags:s,counter:c,counterBuf:a,aaguid:l,credentialID:d,credentialPublicKey:u,extensionsData:p,extensionsDataBuffer:y})}var yAe={stubThis:(e)=>e};function wc(e,t=-7){if(typeof e==="string")e=YC(e);return S6(e,t)}async function Vi(e,t=[]){if(t.length===0)return!0;let r=e.map((s)=>new ff(s));for(let s=0;s<r.length;s++){let a=r[s],c=e[s];try{await X9(a)}catch(l){throw Error(`Found revoked certificate in x5c:
|
|
528
|
+
${c}`)}try{Z9(a.notBefore,a.notAfter)}catch(l){throw Error(`Found certificate out of validity period in x5c:
|
|
529
|
+
${c}`)}}let n=t.map((s)=>{try{return new ff(s)}catch(a){let c=a;throw Error(`Could not parse trust anchor certificate:
|
|
530
|
+
${s}`,{cause:c})}}),o=[];for(let s=0;s<n.length;s++){let a=n[s];try{await X9(a)}catch(c){continue}try{Z9(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((y)=>y.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 p=await new TB({certificates:[...d,s]}).build(l);if(p.length<c)continue;if(p[p.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 eX;return!0}async function X9(e){if(await Q9(e))throw Error("Found revoked certificate in certificate path")}function Z9(e,t){let r=new Date(Date.now());if(e>r||t<r)throw Error("Certificate is not yet valid or expired")}class eX extends Error{constructor(){super("x5c could not be chained to any specified trust anchor");this.name="InvalidX5CChain"}}function RB(e){let t;if(e==="1.2.840.10045.4.3.2")t=vt.ES256;else if(e==="1.2.840.10045.4.3.3")t=vt.ES384;else if(e==="1.2.840.10045.4.3.4")t=vt.ES512;else if(e==="1.2.840.113549.1.1.11")t=vt.RS256;else if(e==="1.2.840.113549.1.1.12")t=vt.RS384;else if(e==="1.2.840.113549.1.1.13")t=vt.RS512;else if(e==="1.2.840.113549.1.1.5")t=vt.RS1;else throw Error(`Unable to map X.509 signature algorithm ${e} to a COSE algorithm`);return t}function XC(e){let t=new Map,r=Tn.parse(e,fo),{tbsCertificate:n}=r,{subjectPublicKeyInfo:o,signature:i}=n,s=i.algorithm,a=o.algorithm.algorithm;if(a===Iu){if(!o.algorithm.parameters)throw Error("Certificate public key was missing parameters (EC2)");let c=Tn.parse(new Uint8Array(o.algorithm.parameters),xc),l=-999,{namedCurve:d}=c;if(d===kb)l=$i.P256;else if(d===Db)l=$i.P384;else throw Error(`Certificate public key contained unexpected namedCurve ${d} (EC2)`);let u=new Uint8Array(o.subjectPublicKey),p,y;if(u[0]===4){let E=1,S=(u.length-1)/2;p=u.slice(E,E+=S),y=u.slice(E)}else throw Error('TODO: Figure out how to handle public keys in "compressed form"');let g=new Map;g.set(ht.kty,Da.EC2),g.set(ht.alg,RB(s)),g.set(ht.crv,l),g.set(ht.x,p),g.set(ht.y,y),t=g}else if(a===Ec){let c=Tn.parse(o.subjectPublicKey,fy),l=new Map;l.set(ht.kty,Da.RSA),l.set(ht.alg,RB(s)),l.set(ht.n,new Uint8Array(c.modulus)),l.set(ht.e,new Uint8Array(c.publicExponent)),t=l}else throw Error(`Certificate public key contained unexpected algorithm ID ${a}`);return t}function Tc(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=Wp(n);else if(o)s=XC(o);return gAe.stubThis(tX({cosePublicKey:s,signature:t,data:r,shaHashOverride:i}))}var gAe={stubThis:(e)=>e};function rX(e){let t=e.split(".");return[JSON.parse(Hg(t[0])),JSON.parse(Hg(t[1])),t[2]]}function nX(e){let t;if(e==="ES256")t=vt.ES256;else if(e==="ES384")t=vt.ES384;else if(e==="ES512")t=vt.ES512;else if(e==="RS256")t=vt.RS256;else if(e==="RS384")t=vt.RS384;else if(e==="RS512")t=vt.RS512;else throw Error(`Unable to map JWS algorithm "${e}" to a COSE algorithm`);return t}function oX(e,t){let[r,n,o]=e.split("."),i=XC(t),s=YC(`${r}.${n}`),a=jg(o),c=JSON.parse(Hg(r)),l=nX(c.alg);if(jp(i))return RP({data:s,signature:a,cosePublicKey:i,shaHashOverride:l});else if(Kg(i))return PP({data:s,signature:a,cosePublicKey:i,shaHashOverride:l});let d=i.get(ht.kty);throw Error(`JWT verification with public key of kty ${d} is not supported by this method`)}function iX(e){let t=e.replace("-----BEGIN CERTIFICATE-----","").replace("-----END CERTIFICATE-----","").replace(/[\n ]/g,"");return jg(t,"base64")}var sX=`-----BEGIN CERTIFICATE-----
|
|
531
|
+
MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG
|
|
532
|
+
A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv
|
|
533
|
+
b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw
|
|
534
|
+
MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i
|
|
535
|
+
YWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxT
|
|
536
|
+
aWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZ
|
|
537
|
+
jc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavp
|
|
538
|
+
xy0Sy6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp
|
|
539
|
+
1Wrjsok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdG
|
|
540
|
+
snUOhugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJ
|
|
541
|
+
U26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N8
|
|
542
|
+
9iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E
|
|
543
|
+
BTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0B
|
|
544
|
+
AQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOz
|
|
545
|
+
yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE
|
|
546
|
+
38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP
|
|
547
|
+
AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad
|
|
548
|
+
DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME
|
|
549
|
+
HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==
|
|
550
|
+
-----END CERTIFICATE-----
|
|
551
|
+
`;var aX=`-----BEGIN CERTIFICATE-----
|
|
552
|
+
MIIFYDCCA0igAwIBAgIJAOj6GWMU0voYMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV
|
|
553
|
+
BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMTYwNTI2MTYyODUyWhcNMjYwNTI0MTYy
|
|
554
|
+
ODUyWjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B
|
|
555
|
+
AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS
|
|
556
|
+
Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7
|
|
557
|
+
tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj
|
|
558
|
+
nar86461qO0rOs2cXjp3kOG1FEJ5MVmFmBGtnrKpa73XpXyTqRxB/M0n1n/W9nGq
|
|
559
|
+
C4FSYa04T6N5RIZGBN2z2MT5IKGbFlbC8UrW0DxW7AYImQQcHtGl/m00QLVWutHQ
|
|
560
|
+
oVJYnFPlXTcHYvASLu+RhhsbDmxMgJJ0mcDpvsC4PjvB+TxywElgS70vE0XmLD+O
|
|
561
|
+
JtvsBslHZvPBKCOdT0MS+tgSOIfga+z1Z1g7+DVagf7quvmag8jfPioyKvxnK/Eg
|
|
562
|
+
sTUVi2ghzq8wm27ud/mIM7AY2qEORR8Go3TVB4HzWQgpZrt3i5MIlCaY504LzSRi
|
|
563
|
+
igHCzAPlHws+W0rB5N+er5/2pJKnfBSDiCiFAVtCLOZ7gLiMm0jhO2B6tUXHI/+M
|
|
564
|
+
RPjy02i59lINMRRev56GKtcd9qO/0kUJWdZTdA2XoS82ixPvZtXQpUpuL12ab+9E
|
|
565
|
+
aDK8Z4RHJYYfCT3Q5vNAXaiWQ+8PTWm2QgBR/bkwSWc+NpUFgNPN9PvQi8WEg5Um
|
|
566
|
+
AGMCAwEAAaOBpjCBozAdBgNVHQ4EFgQUNmHhAHyIBQlRi0RsR/8aTMnqTxIwHwYD
|
|
567
|
+
VR0jBBgwFoAUNmHhAHyIBQlRi0RsR/8aTMnqTxIwDwYDVR0TAQH/BAUwAwEB/zAO
|
|
568
|
+
BgNVHQ8BAf8EBAMCAYYwQAYDVR0fBDkwNzA1oDOgMYYvaHR0cHM6Ly9hbmRyb2lk
|
|
569
|
+
Lmdvb2dsZWFwaXMuY29tL2F0dGVzdGF0aW9uL2NybC8wDQYJKoZIhvcNAQELBQAD
|
|
570
|
+
ggIBACDIw41L3KlXG0aMiS//cqrG+EShHUGo8HNsw30W1kJtjn6UBwRM6jnmiwfB
|
|
571
|
+
Pb8VA91chb2vssAtX2zbTvqBJ9+LBPGCdw/E53Rbf86qhxKaiAHOjpvAy5Y3m00m
|
|
572
|
+
qC0w/Zwvju1twb4vhLaJ5NkUJYsUS7rmJKHHBnETLi8GFqiEsqTWpG/6ibYCv7rY
|
|
573
|
+
DBJDcR9W62BW9jfIoBQcxUCUJouMPH25lLNcDc1ssqvC2v7iUgI9LeoM1sNovqPm
|
|
574
|
+
QUiG9rHli1vXxzCyaMTjwftkJLkf6724DFhuKug2jITV0QkXvaJWF4nUaHOTNA4u
|
|
575
|
+
JU9WDvZLI1j83A+/xnAJUucIv/zGJ1AMH2boHqF8CY16LpsYgBt6tKxxWH00XcyD
|
|
576
|
+
CdW2KlBCeqbQPcsFmWyWugxdcekhYsAWyoSf818NUsZdBWBaR/OukXrNLfkQ79Iy
|
|
577
|
+
ZohZbvabO/X+MVT3rriAoKc8oE2Uws6DF+60PV7/WIPjNvXySdqspImSN78mflxD
|
|
578
|
+
qwLqRBYkA3I75qppLGG9rp7UCdRjxMl8ZDBld+7yvHVgt1cVzJx9xnyGCC23Uaic
|
|
579
|
+
MDSXYrB4I4WHXPGjxhZuCuPBLTdOLU8YRvMYdEvYebWHMpvwGCF6bAx3JBpIeOQ1
|
|
580
|
+
wDB5y0USicV3YgYGmi+NZfhA4URSh77Yd6uuJOJENRaNVTzk
|
|
581
|
+
-----END CERTIFICATE-----
|
|
582
|
+
`,cX=`-----BEGIN CERTIFICATE-----
|
|
583
|
+
MIIFHDCCAwSgAwIBAgIJANUP8luj8tazMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV
|
|
584
|
+
BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMTkxMTIyMjAzNzU4WhcNMzQxMTE4MjAz
|
|
585
|
+
NzU4WjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B
|
|
586
|
+
AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS
|
|
587
|
+
Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7
|
|
588
|
+
tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj
|
|
589
|
+
nar86461qO0rOs2cXjp3kOG1FEJ5MVmFmBGtnrKpa73XpXyTqRxB/M0n1n/W9nGq
|
|
590
|
+
C4FSYa04T6N5RIZGBN2z2MT5IKGbFlbC8UrW0DxW7AYImQQcHtGl/m00QLVWutHQ
|
|
591
|
+
oVJYnFPlXTcHYvASLu+RhhsbDmxMgJJ0mcDpvsC4PjvB+TxywElgS70vE0XmLD+O
|
|
592
|
+
JtvsBslHZvPBKCOdT0MS+tgSOIfga+z1Z1g7+DVagf7quvmag8jfPioyKvxnK/Eg
|
|
593
|
+
sTUVi2ghzq8wm27ud/mIM7AY2qEORR8Go3TVB4HzWQgpZrt3i5MIlCaY504LzSRi
|
|
594
|
+
igHCzAPlHws+W0rB5N+er5/2pJKnfBSDiCiFAVtCLOZ7gLiMm0jhO2B6tUXHI/+M
|
|
595
|
+
RPjy02i59lINMRRev56GKtcd9qO/0kUJWdZTdA2XoS82ixPvZtXQpUpuL12ab+9E
|
|
596
|
+
aDK8Z4RHJYYfCT3Q5vNAXaiWQ+8PTWm2QgBR/bkwSWc+NpUFgNPN9PvQi8WEg5Um
|
|
597
|
+
AGMCAwEAAaNjMGEwHQYDVR0OBBYEFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMB8GA1Ud
|
|
598
|
+
IwQYMBaAFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMA8GA1UdEwEB/wQFMAMBAf8wDgYD
|
|
599
|
+
VR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4ICAQBOMaBc8oumXb2voc7XCWnu
|
|
600
|
+
XKhBBK3e2KMGz39t7lA3XXRe2ZLLAkLM5y3J7tURkf5a1SutfdOyXAmeE6SRo83U
|
|
601
|
+
h6WszodmMkxK5GM4JGrnt4pBisu5igXEydaW7qq2CdC6DOGjG+mEkN8/TA6p3cno
|
|
602
|
+
L/sPyz6evdjLlSeJ8rFBH6xWyIZCbrcpYEJzXaUOEaxxXxgYz5/cTiVKN2M1G2ok
|
|
603
|
+
QBUIYSY6bjEL4aUN5cfo7ogP3UvliEo3Eo0YgwuzR2v0KR6C1cZqZJSTnghIC/vA
|
|
604
|
+
D32KdNQ+c3N+vl2OTsUVMC1GiWkngNx1OO1+kXW+YTnnTUOtOIswUP/Vqd5SYgAI
|
|
605
|
+
mMAfY8U9/iIgkQj6T2W6FsScy94IN9fFhE1UtzmLoBIuUFsVXJMTz+Jucth+IqoW
|
|
606
|
+
Fua9v1R93/k98p41pjtFX+H8DslVgfP097vju4KDlqN64xV1grw3ZLl4CiOe/A91
|
|
607
|
+
oeLm2UHOq6wn3esB4r2EIQKb6jTVGu5sYCcdWpXr0AUVqcABPdgL+H7qJguBw09o
|
|
608
|
+
jm6xNIrw2OocrDKsudk/okr/AwqEyPKw9WnMlQgLIKw1rODG2NvU9oR3GVGdMkUB
|
|
609
|
+
ZutL8VuFkERQGt6vQ2OCw0sV47VMkuYbacK/xyZFiRcrPJPb41zgbQj9XAEyLKCH
|
|
610
|
+
ex0SdDrx+tWUDqG8At2JHA==
|
|
611
|
+
-----END CERTIFICATE-----
|
|
612
|
+
`,lX=`
|
|
613
|
+
-----BEGIN CERTIFICATE-----
|
|
614
|
+
MIIFHDCCAwSgAwIBAgIJAMNrfES5rhgxMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV
|
|
615
|
+
BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMjExMTE3MjMxMDQyWhcNMzYxMTEzMjMx
|
|
616
|
+
MDQyWjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B
|
|
617
|
+
AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS
|
|
618
|
+
Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7
|
|
619
|
+
tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj
|
|
620
|
+
nar86461qO0rOs2cXjp3kOG1FEJ5MVmFmBGtnrKpa73XpXyTqRxB/M0n1n/W9nGq
|
|
621
|
+
C4FSYa04T6N5RIZGBN2z2MT5IKGbFlbC8UrW0DxW7AYImQQcHtGl/m00QLVWutHQ
|
|
622
|
+
oVJYnFPlXTcHYvASLu+RhhsbDmxMgJJ0mcDpvsC4PjvB+TxywElgS70vE0XmLD+O
|
|
623
|
+
JtvsBslHZvPBKCOdT0MS+tgSOIfga+z1Z1g7+DVagf7quvmag8jfPioyKvxnK/Eg
|
|
624
|
+
sTUVi2ghzq8wm27ud/mIM7AY2qEORR8Go3TVB4HzWQgpZrt3i5MIlCaY504LzSRi
|
|
625
|
+
igHCzAPlHws+W0rB5N+er5/2pJKnfBSDiCiFAVtCLOZ7gLiMm0jhO2B6tUXHI/+M
|
|
626
|
+
RPjy02i59lINMRRev56GKtcd9qO/0kUJWdZTdA2XoS82ixPvZtXQpUpuL12ab+9E
|
|
627
|
+
aDK8Z4RHJYYfCT3Q5vNAXaiWQ+8PTWm2QgBR/bkwSWc+NpUFgNPN9PvQi8WEg5Um
|
|
628
|
+
AGMCAwEAAaNjMGEwHQYDVR0OBBYEFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMB8GA1Ud
|
|
629
|
+
IwQYMBaAFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMA8GA1UdEwEB/wQFMAMBAf8wDgYD
|
|
630
|
+
VR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4ICAQBTNNZe5cuf8oiq+jV0itTG
|
|
631
|
+
zWVhSTjOBEk2FQvh11J3o3lna0o7rd8RFHnN00q4hi6TapFhh4qaw/iG6Xg+xOan
|
|
632
|
+
63niLWIC5GOPFgPeYXM9+nBb3zZzC8ABypYuCusWCmt6Tn3+Pjbz3MTVhRGXuT/T
|
|
633
|
+
QH4KGFY4PhvzAyXwdjTOCXID+aHud4RLcSySr0Fq/L+R8TWalvM1wJJPhyRjqRCJ
|
|
634
|
+
erGtfBagiALzvhnmY7U1qFcS0NCnKjoO7oFedKdWlZz0YAfu3aGCJd4KHT0MsGiL
|
|
635
|
+
Zez9WP81xYSrKMNEsDK+zK5fVzw6jA7cxmpXcARTnmAuGUeI7VVDhDzKeVOctf3a
|
|
636
|
+
0qQLwC+d0+xrETZ4r2fRGNw2YEs2W8Qj6oDcfPvq9JySe7pJ6wcHnl5EZ0lwc4xH
|
|
637
|
+
7Y4Dx9RA1JlfooLMw3tOdJZH0enxPXaydfAD3YifeZpFaUzicHeLzVJLt9dvGB0b
|
|
638
|
+
HQLE4+EqKFgOZv2EoP686DQqbVS1u+9k0p2xbMA105TBIk7npraa8VM0fnrRKi7w
|
|
639
|
+
lZKwdH+aNAyhbXRW9xsnODJ+g8eF452zvbiKKngEKirK5LGieoXBX7tZ9D1GNBH2
|
|
640
|
+
Ob3bKOwwIWdEFle/YF/h6zWgdeoaNGDqVBrLr2+0DtWoiB1aDEjLWl9FmyIUyUm7
|
|
641
|
+
mD/vFDkzF+wm7cyWpQpCVQ==
|
|
642
|
+
-----END CERTIFICATE-----
|
|
643
|
+
`,dX=`
|
|
644
|
+
-----BEGIN CERTIFICATE-----
|
|
645
|
+
MIIFHDCCAwSgAwIBAgIJAPHBcqaZ6vUdMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV
|
|
646
|
+
BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMjIwMzIwMTgwNzQ4WhcNNDIwMzE1MTgw
|
|
647
|
+
NzQ4WjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B
|
|
648
|
+
AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS
|
|
649
|
+
Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7
|
|
650
|
+
tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj
|
|
651
|
+
nar86461qO0rOs2cXjp3kOG1FEJ5MVmFmBGtnrKpa73XpXyTqRxB/M0n1n/W9nGq
|
|
652
|
+
C4FSYa04T6N5RIZGBN2z2MT5IKGbFlbC8UrW0DxW7AYImQQcHtGl/m00QLVWutHQ
|
|
653
|
+
oVJYnFPlXTcHYvASLu+RhhsbDmxMgJJ0mcDpvsC4PjvB+TxywElgS70vE0XmLD+O
|
|
654
|
+
JtvsBslHZvPBKCOdT0MS+tgSOIfga+z1Z1g7+DVagf7quvmag8jfPioyKvxnK/Eg
|
|
655
|
+
sTUVi2ghzq8wm27ud/mIM7AY2qEORR8Go3TVB4HzWQgpZrt3i5MIlCaY504LzSRi
|
|
656
|
+
igHCzAPlHws+W0rB5N+er5/2pJKnfBSDiCiFAVtCLOZ7gLiMm0jhO2B6tUXHI/+M
|
|
657
|
+
RPjy02i59lINMRRev56GKtcd9qO/0kUJWdZTdA2XoS82ixPvZtXQpUpuL12ab+9E
|
|
658
|
+
aDK8Z4RHJYYfCT3Q5vNAXaiWQ+8PTWm2QgBR/bkwSWc+NpUFgNPN9PvQi8WEg5Um
|
|
659
|
+
AGMCAwEAAaNjMGEwHQYDVR0OBBYEFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMB8GA1Ud
|
|
660
|
+
IwQYMBaAFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMA8GA1UdEwEB/wQFMAMBAf8wDgYD
|
|
661
|
+
VR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4ICAQB8cMqTllHc8U+qCrOlg3H7
|
|
662
|
+
174lmaCsbo/bJ0C17JEgMLb4kvrqsXZs01U3mB/qABg/1t5Pd5AORHARs1hhqGIC
|
|
663
|
+
W/nKMav574f9rZN4PC2ZlufGXb7sIdJpGiO9ctRhiLuYuly10JccUZGEHpHSYM2G
|
|
664
|
+
tkgYbZba6lsCPYAAP83cyDV+1aOkTf1RCp/lM0PKvmxYN10RYsK631jrleGdcdkx
|
|
665
|
+
oSK//mSQbgcWnmAEZrzHoF1/0gso1HZgIn0YLzVhLSA/iXCX4QT2h3J5z3znluKG
|
|
666
|
+
1nv8NQdxei2DIIhASWfu804CA96cQKTTlaae2fweqXjdN1/v2nqOhngNyz1361mF
|
|
667
|
+
mr4XmaKH/ItTwOe72NI9ZcwS1lVaCvsIkTDCEXdm9rCNPAY10iTunIHFXRh+7KPz
|
|
668
|
+
lHGewCq/8TOohBRn0/NNfh7uRslOSZ/xKbN9tMBtw37Z8d2vvnXq/YWdsm1+JLVw
|
|
669
|
+
n6yYD/yacNJBlwpddla8eaVMjsF6nBnIgQOf9zKSe06nSTqvgwUHosgOECZJZ1Eu
|
|
670
|
+
zbH4yswbt02tKtKEFhx+v+OTge/06V+jGsqTWLsfrOCNLuA8H++z+pUENmpqnnHo
|
|
671
|
+
vaI47gC+TNpkgYGkkBT6B/m/U01BuOBBTzhIlMEZq9qkDWuM2cA5kW5V3FJUcfHn
|
|
672
|
+
w1IdYIg2Wxg7yHcQZemFQg==
|
|
673
|
+
-----END CERTIFICATE-----
|
|
674
|
+
`;var uX=`-----BEGIN CERTIFICATE-----
|
|
675
|
+
MIICEjCCAZmgAwIBAgIQaB0BbHo84wIlpQGUKEdXcTAKBggqhkjOPQQDAzBLMR8w
|
|
676
|
+
HQYDVQQDDBZBcHBsZSBXZWJBdXRobiBSb290IENBMRMwEQYDVQQKDApBcHBsZSBJ
|
|
677
|
+
bmMuMRMwEQYDVQQIDApDYWxpZm9ybmlhMB4XDTIwMDMxODE4MjEzMloXDTQ1MDMx
|
|
678
|
+
NTAwMDAwMFowSzEfMB0GA1UEAwwWQXBwbGUgV2ViQXV0aG4gUm9vdCBDQTETMBEG
|
|
679
|
+
A1UECgwKQXBwbGUgSW5jLjETMBEGA1UECAwKQ2FsaWZvcm5pYTB2MBAGByqGSM49
|
|
680
|
+
AgEGBSuBBAAiA2IABCJCQ2pTVhzjl4Wo6IhHtMSAzO2cv+H9DQKev3//fG59G11k
|
|
681
|
+
xu9eI0/7o6V5uShBpe1u6l6mS19S1FEh6yGljnZAJ+2GNP1mi/YK2kSXIuTHjxA/
|
|
682
|
+
pcoRf7XkOtO4o1qlcaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUJtdk
|
|
683
|
+
2cV4wlpn0afeaxLQG2PxxtcwDgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2cA
|
|
684
|
+
MGQCMFrZ+9DsJ1PW9hfNdBywZDsWDbWFp28it1d/5w2RPkRX3Bbn/UbDTNLx7Jr3
|
|
685
|
+
jAGGiQIwHFj+dJZYUJR786osByBelJYsVZd2GbHQu209b5RCmGQ21gpSAk9QZW4B
|
|
686
|
+
1bWeT0vT
|
|
687
|
+
-----END CERTIFICATE-----
|
|
688
|
+
`;var pX=`-----BEGIN CERTIFICATE-----
|
|
689
|
+
MIIDXzCCAkegAwIBAgILBAAAAAABIVhTCKIwDQYJKoZIhvcNAQELBQAwTDEgMB4G
|
|
690
|
+
A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkdsb2JhbFNp
|
|
691
|
+
Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDkwMzE4MTAwMDAwWhcNMjkwMzE4
|
|
692
|
+
MTAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMzETMBEG
|
|
693
|
+
A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI
|
|
694
|
+
hvcNAQEBBQADggEPADCCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWtiHL8
|
|
695
|
+
RgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsT
|
|
696
|
+
gHeMCOFJ0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmm
|
|
697
|
+
KPZpO/bLyCiR5Z2KYVc3rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zd
|
|
698
|
+
QQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjlOCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZ
|
|
699
|
+
XriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2xmmFghcCAwEAAaNCMEAw
|
|
700
|
+
DgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI/wS3+o
|
|
701
|
+
LkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZU
|
|
702
|
+
RUm7lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMp
|
|
703
|
+
jjM5RcOO5LlXbKr8EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK
|
|
704
|
+
6fBdRoyV3XpYKBovHd7NADdBj+1EbddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQX
|
|
705
|
+
mcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18YIvDQVETI53O9zJrlAGomecs
|
|
706
|
+
Mx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7rkpeDMdmztcpH
|
|
707
|
+
WD9f
|
|
708
|
+
-----END CERTIFICATE-----
|
|
709
|
+
`,fX=`-----BEGIN CERTIFICATE-----
|
|
710
|
+
MIIFWjCCA0KgAwIBAgISEdK7udcjGJ5AXwqdLdDfJWfRMA0GCSqGSIb3DQEBDAUA
|
|
711
|
+
MEYxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRwwGgYD
|
|
712
|
+
VQQDExNHbG9iYWxTaWduIFJvb3QgUjQ2MB4XDTE5MDMyMDAwMDAwMFoXDTQ2MDMy
|
|
713
|
+
MDAwMDAwMFowRjELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYt
|
|
714
|
+
c2ExHDAaBgNVBAMTE0dsb2JhbFNpZ24gUm9vdCBSNDYwggIiMA0GCSqGSIb3DQEB
|
|
715
|
+
AQUAA4ICDwAwggIKAoICAQCsrHQy6LNl5brtQyYdpokNRbopiLKkHWPd08EsCVeJ
|
|
716
|
+
OaFV6Wc0dwxu5FUdUiXSE2te4R2pt32JMl8Nnp8semNgQB+msLZ4j5lUlghYruQG
|
|
717
|
+
vGIFAha/r6gjA7aUD7xubMLL1aa7DOn2wQL7Id5m3RerdELv8HQvJfTqa1VbkNud
|
|
718
|
+
316HCkD7rRlr+/fKYIje2sGP1q7Vf9Q8g+7XFkyDRTNrJ9CG0Bwta/OrffGFqfUo
|
|
719
|
+
0q3v84RLHIf8E6M6cqJaESvWJ3En7YEtbWaBkoe0G1h6zD8K+kZPTXhc+CtI4wSE
|
|
720
|
+
y132tGqzZfxCnlEmIyDLPRT5ge1lFgBPGmSXZgjPjHvjK8Cd+RTyG/FWaha/LIWF
|
|
721
|
+
zXg4mutCagI0GIMXTpRW+LaCtfOW3T3zvn8gdz57GSNrLNRyc0NXfeD412lPFzYE
|
|
722
|
+
+cCQYDdF3uYM2HSNrpyibXRdQr4G9dlkbgIQrImwTDsHTUB+JMWKmIJ5jqSngiCN
|
|
723
|
+
I/onccnfxkF0oE32kRbcRoxfKWMxWXEM2G/CtjJ9++ZdU6Z+Ffy7dXxd7Pj2Fxzs
|
|
724
|
+
x2sZy/N78CsHpdlseVR2bJ0cpm4O6XkMqCNqo98bMDGfsVR7/mrLZqrcZdCinkqa
|
|
725
|
+
ByFrgY/bxFn63iLABJzjqls2k+g9vXqhnQt2sQvHnf3PmKgGwvgqo6GDoLclcqUC
|
|
726
|
+
4wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNV
|
|
727
|
+
HQ4EFgQUA1yrc4GHqMywptWU4jaWSf8FmSwwDQYJKoZIhvcNAQEMBQADggIBAHx4
|
|
728
|
+
7PYCLLtbfpIrXTncvtgdokIzTfnvpCo7RGkerNlFo048p9gkUbJUHJNOxO97k4Vg
|
|
729
|
+
JuoJSOD1u8fpaNK7ajFxzHmuEajwmf3lH7wvqMxX63bEIaZHU1VNaL8FpO7XJqti
|
|
730
|
+
2kM3S+LGteWygxk6x9PbTZ4IevPuzz5i+6zoYMzRx6Fcg0XERczzF2sUyQQCPtIk
|
|
731
|
+
pnnpHs6i58FZFZ8d4kuaPp92CC1r2LpXFNqD6v6MVenQTqnMdzGxRBF6XLE+0xRF
|
|
732
|
+
FRhiJBPSy03OXIPBNvIQtQ6IbbjhVp+J3pZmOUdkLG5NrmJ7v2B0GbhWrJKsFjLt
|
|
733
|
+
rWhV/pi60zTe9Mlhww6G9kuEYO4Ne7UyWHmRVSyBQ7N0H3qqJZ4d16GLuc1CLgSk
|
|
734
|
+
ZoNNiTW2bKg2SnkheCLQQrzRQDGQob4Ez8pn7fXwgNNgyYMqIgXQBztSvwyeqiv5
|
|
735
|
+
u+YfjyW6hY0XHgL+XVAEV8/+LbzvXMAaq7afJMbfc2hIkCwU9D9SGuTSyxTDYWnP
|
|
736
|
+
4vkYxboznxSjBF25cfe1lNj2M8FawTSLfJvdkzrnE6JwYZ+vj+vYxXX4M2bUdGc6
|
|
737
|
+
N3ec592kD3ZDZopD8p/7DEJ4Y9HiD2971KE9dJeFt0g5QdYg/NA6s/rob8SKunE3
|
|
738
|
+
vouXsXgxT7PntgMTzlSdriVZzH81Xwj3QEUxeCp6
|
|
739
|
+
-----END CERTIFICATE-----
|
|
740
|
+
`;class mX{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(Ro(o));else n.push(o);this.pemCertificates.set(t,n)}getRootCertificates(e){let{identifier:t}=e;return this.pemCertificates.get(t)??[]}}var mf=new mX;mf.setRootCertificates({identifier:"android-key",certificates:[aX,cX,lX,dX]});mf.setRootCertificates({identifier:"android-safetynet",certificates:[sX]});mf.setRootCertificates({identifier:"apple",certificates:[uX]});mf.setRootCertificates({identifier:"mds",certificates:[pX,fX]});async function yX(e){let t=rX(e),r=t[0],n=t[1],o=r.x5c.map(Ro);try{let p=mf.getRootCertificates({identifier:"mds"});await Vi(o,p)}catch(p){throw Error("BLOB certificate path could not be validated",{cause:p})}let i=o[0];if(!await oX(e,iX(i)))throw Error("BLOB signature could not be verified");let a=[];for(let p of n.entries)if(p.aaguid&&p.metadataStatement)a.push(p.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 hX(e){let{cosePublicKey:t,signature:r,data:n}=e,o=await mc(),i=t.get(ht.alg),s=t.get(ht.crv),a=t.get(ht.x);if(!i)throw Error("Public key was missing alg (OKP)");if(!Zl(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===$i.ED25519)c="Ed25519";else throw Error(`Unexpected COSE crv value of ${s} (OKP)`);let l={kty:"OKP",crv:c,alg:"EdDSA",x:Yl(a),ext:!1},u=await Gg({keyData:l,algorithm:{name:c,namedCurve:c}}),p={name:c};return o.subtle.verify(p,u,r,n)}function SX(e,t){let r=Tn.parse(e,of),n=new Uint8Array(r.r),o=new Uint8Array(r.s),i=SAe(t),s=gX(n,i),a=gX(o,i);return yc([s,a])}function SAe(e){switch(e){case $i.P256:return 32;case $i.P384:return 48;case $i.P521:return 66;default:throw Error(`Unexpected COSE crv value of ${e} (EC2)`)}}function gX(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 tX(e){let{cosePublicKey:t,signature:r,data:n,shaHashOverride:o}=e;if(jp(t)){let s=t.get(ht.crv);if(!h6(s))throw Error(`unknown COSE curve ${s}`);let a=SX(r,s);return RP({cosePublicKey:t,signature:a,data:n,shaHashOverride:o})}else if(Kg(t))return PP({cosePublicKey:t,signature:r,data:n,shaHashOverride:o});else if(y6(t))return hX({cosePublicKey:t,signature:r,data:n});let i=t.get(ht.kty);throw Error(`Signature verification with public key of kty ${i} is not supported by this method`)}function yl(e,t){if(e.length!=t.length)return!1;return e.every((r,n)=>r===t[n])}function _P(e){return Array.from(e,(r)=>r.toString(16).padStart(2,"0")).join("")}function hAe(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 yc(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 vAe(e){return new globalThis.TextDecoder("utf-8").decode(e)}function YC(e){return new globalThis.TextEncoder().encode(e)}function xAe(e){return Uint8Array.from(e.split("").map((t)=>t.charCodeAt(0)))}function JC(e){return new DataView(e.buffer,e.byteOffset,e.length)}async function PB(){let e=new Uint8Array(32);return await FU(e),EAe.stubThis(e)}var EAe={stubThis:(e)=>e};var vX=[-8,-7,-36,-37,-38,-39,-257,-258,-259,-65535],bAe={residentKey:"preferred",userVerification:"preferred"},wAe=[-8,-7,-257];async function xX(e){let{rpName:t,rpID:r,userName:n,userID:o,challenge:i=await PB(),userDisplayName:s="",timeout:a=60000,attestationType:c="none",excludeCredentials:l=[],authenticatorSelection:d=bAe,extensions:u,supportedAlgorithmIDs:p=wAe,preferredAuthenticatorType:y}=e,g=p.map((w)=>({alg:w,type:"public-key"}));if(d.residentKey===void 0){if(d.requireResidentKey)d.residentKey="required"}else d.requireResidentKey=d.residentKey==="required";let E=i;if(typeof E==="string")E=YC(E);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 S=o;if(!S)S=await x6();let x=[];if(y){if(y==="securityKey")x.push("security-key"),d.authenticatorAttachment="cross-platform";else if(y==="localDevice")x.push("client-device"),d.authenticatorAttachment="platform";else if(y==="remoteDevice")x.push("hybrid"),d.authenticatorAttachment="cross-platform"}return{challenge:Yl(E),rp:{name:t,id:r},user:{id:Yl(S),name:n,displayName:s},pubKeyCredParams:g,timeout:a,attestation:c,excludeCredentials:l.map((w)=>{if(!l6(w.id))throw Error(`excludeCredential id "${w.id}" is not a valid base64url string`);return{...w,id:d6(w.id),type:"public-key"}}),authenticatorSelection:d,extensions:{...u,credProps:!0},hints:x}}function CB({be:e,bs:t}){let r=t,n="singleDevice";if(e)n="multiDevice";if(n==="singleDevice"&&r)throw new EX("Single-device credential indicated that it was backed up, which should be impossible.");return{credentialDeviceType:n,credentialBackedUp:r}}class EX extends Error{constructor(e){super(e);this.name="InvalidBackupFlags"}}async function _B(e,t){try{return await Promise.any(t.map((n)=>new Promise((o,i)=>{wc(xAe(n)).then((s)=>{if(yl(e,s))o(n);else i()})})))}catch(r){if(r.name==="AggregateError")throw new bX;throw r}}class bX extends Error{constructor(){super("Unexpected RP ID hash");this.name="UnexpectedRPIDHash"}}async function wX(e){let{attStmt:t,clientDataHash:r,rpIdHash:n,credentialID:o,credentialPublicKey:i,aaguid:s,rootCertificates:a}=e,c=Uint8Array.from([0]),l=Qg(i),d=yc([c,n,r,o,l]),u=t.get("sig"),p=t.get("x5c");if(!p)throw Error("No attestation certificate provided in attestation statement (FIDOU2F)");if(!u)throw Error("No attestation signature provided in attestation statement (FIDOU2F)");let y=Number.parseInt(_P(s),16);if(y!==0)throw Error(`AAGUID "${y}" was not expected value`);try{await Vi(p.map(Ro),a)}catch(g){throw Error(`${g.message} (FIDOU2F)`)}return Tc({signature:u,data:d,x509Certificate:p[0],hashAlgorithm:vt.ES256})}var TX="1.3.6.1.4.1.45724.1.1.4";function ZC(e,t){if(!e)return!0;let r=e.find((s)=>s.extnID===TX);if(!r)return!0;let n=Tn.parse(r.extnValue,he),o=new Uint8Array(n.buffer);if(!yl(t,o)){let s=_P(o),a=_P(t);throw Error(`Certificate extension id-fido-gen-ce-aaguid (${TX}) value of "${s}" was present but not equal to attestation statement AAGUID value of "${a}"`)}return!0}function AX(e){return(t,...r)=>{}}var TAe={url:"",no:0,nextUpdate:new Date(0)},AAe="https://mds.fidoalliance.org/",La;(function(e){e[e.DISABLED=0]="DISABLED",e[e.REFRESHING=1]="REFRESHING",e[e.READY=2]="READY"})(La||(La={}));var wy=AX("MetadataService");class IX{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:La.DISABLED}),Object.defineProperty(this,"verificationMode",{enumerable:!0,configurable:!0,writable:!0,value:"strict"})}async initialize(e={}){this.statementCache={};let{mdsServers:t=[AAe],statements:r,verificationMode:n}=e;if(this.setState(La.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:TAe.url},o+=1}),wy(`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){wy(`Could not download BLOB from ${c}:`,l),i-=1}let a=Object.keys(this.statementCache).length-o;wy(`Cached ${a} statements from ${i} metadata server(s)`)}if(n)this.verificationMode=n;this.setState(La.READY)}async getStatement(e){if(this.state===La.DISABLED)return;if(!e)return;if(e instanceof Uint8Array)e=CP(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(La.REFRESHING);let i=await this.downloadBlob(n);await this.verifyBlob(i,n)}finally{this.setState(La.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 QC(t)).text()}async verifyBlob(e,t){let{url:r,no:n}=t,{payload:o,parsedNextUpdate:i}=await yX(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)wy(`\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===La.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===La.READY)clearInterval(s),t();i-=1},100)})}setState(e){if(this.state=e,e===La.DISABLED)wy("MetadataService is DISABLED");else if(e===La.REFRESHING)wy("MetadataService is REFRESHING");else if(e===La.READY)wy("MetadataService is READY")}}var yf=new IX;async function hf({statement:e,credentialPublicKey:t,x5c:r,attestationStatementAlg:n}){let{authenticationAlgorithms:o,authenticatorGetInfo:i,attestationRootCertificates:s}=e,a=new Set;o.forEach((S)=>{let x=RX[S];if(x)a.add(x)});let c=Wp(t),l=c.get(ht.kty),d=c.get(ht.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(jp(c)){let S=c.get(ht.crv);u.crv=S}let p=!1;for(let S of a){if(S.alg===u.alg&&S.kty===u.kty)if((S.kty===Da.EC2||S.kty===Da.OKP)&&S.crv===u.crv)p=!0;else p=!0;if(p)break}if(!p){let S=o.map((_)=>`'${_}' (COSE info: ${PX(RX[_])})`),x=JSON.stringify(S,null,2).replace(/"/g,""),w=PX(u);throw Error(`Public key parameters ${w} did not match any of the following metadata algorithms:
|
|
741
|
+
${x}`)}if(n!==void 0&&i?.algorithms!==void 0){let S=i.algorithms.map((x)=>x.alg);if(S.indexOf(n)<0)throw Error(`Attestation statement alg ${n} did not match one of ${S}`)}let y=r.map(Ro),g=s.map(Ro),E=!1;if(y.length===1&&g.indexOf(y[0])>=0)E=!0;if(!E)try{await Vi(y,g)}catch(S){throw Error(`Could not validate certificate path with any metadata root certificates: ${S.message}`)}return!0}var RX={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 PX(e){let{kty:t,alg:r,crv:n}=e,o="";if(t!==Da.RSA)o=`{ kty: ${t}, alg: ${r}, crv: ${n} }`;else o=`{ kty: ${t}, alg: ${r} }`;return o}async function CX(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(!Zl(l))throw Error(`Attestation statement contained invalid alg ${l} (Packed)`);let d=yc([n,r]),u=!1;if(c){let{subject:p,basicConstraintsCA:y,version:g,notBefore:E,notAfter:S,parsedCertificate:x}=TS(c[0]),{OU:w,CN:_,O:T,C:b}=p;if(w!=="Authenticator Attestation")throw Error('Certificate OU was not "Authenticator Attestation" (Packed|Full)');if(!_)throw Error("Certificate CN was empty (Packed|Full)");if(!T)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(y)throw Error("Certificate basic constraints CA was not `false` (Packed|Full)");if(g!==2)throw Error("Certificate version was not `3` (ASN.1 value of 2) (Packed|Full)");let I=new Date;if(E>I)throw Error(`Certificate not good before "${E.toString()}" (Packed|Full)`);if(I=new Date,S<I)throw Error(`Certificate not good after "${S.toString()}" (Packed|Full)`);try{await ZC(x.tbsCertificate.extensions,i)}catch(L){throw Error(`${L.message} (Packed|Full)`)}let O=await yf.getStatement(i);if(O){if(O.attestationTypes.indexOf("basic_full")<0)throw Error("Metadata does not indicate support for full attestations (Packed|Full)");try{await hf({statement:O,credentialPublicKey:o,x5c:c,attestationStatementAlg:l})}catch(L){throw Error(`${L.message} (Packed|Full)`)}}else try{await Vi(c.map(Ro),s)}catch(L){throw Error(`${L.message} (Packed|Full)`)}u=await Tc({signature:a,data:d,x509Certificate:c[0],hashAlgorithm:l})}else u=await Tc({signature:a,data:d,credentialPublicKey:o,hashAlgorithm:l});return u}async function _X(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 y=vAe(d).split("."),g=JSON.parse(Hg(y[0])),E=JSON.parse(Hg(y[1])),S=y[2],{nonce:x,ctsProfileMatch:w,timestampMs:_}=E;if(s){let le=Date.now();if(_>Date.now())throw Error(`Payload timestamp "${_}" was later than "${le}" (SafetyNet)`);let ie=_+60000;if(le=Date.now(),ie<le)throw Error(`Payload timestamp "${ie}" has expired (SafetyNet)`)}let T=yc([n,r]),b=await wc(T),I=Yl(b,"base64");if(x!==I)throw Error("Could not verify payload nonce (SafetyNet)");if(c&&!w)throw Error("Could not verify device integrity (SafetyNet)");let O=jg(g.x5c[0],"base64"),L=TS(O),{subject:Y}=L;if(Y.CN!=="attest.android.com")throw Error('Certificate common name was not "attest.android.com" (SafetyNet)');let Z=await yf.getStatement(o);if(Z)try{await hf({statement:Z,credentialPublicKey:a,x5c:g.x5c,attestationStatementAlg:l})}catch(le){throw Error(`${le.message} (SafetyNet)`)}else try{await Vi(g.x5c.map(Ro),i)}catch(le){throw Error(`${le.message} (SafetyNet)`)}let ee=YC(`${y[0]}.${y[1]}`),ae=jg(S);return await Tc({signature:ae,data:ee,x509Certificate:O,hashAlgorithm:l})}var kX={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"},md={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"},DX={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"},OX={"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"}},NX={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 FX(e){let t=0,r=JC(e),n=r.getUint32(t);t+=4;let o=r.getUint16(t);t+=2;let i=kX[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 p=r.getUint32(t);t+=4;let y=!!e.slice(t,t+=1),g={clock:d,resetCount:u,restartCount:p,safe:y},E=e.slice(t,t+=8),S=r.getUint16(t);t+=2;let x=e.slice(t,t+=S),w=JC(x),_=r.getUint16(t);t+=2;let T=e.slice(t,t+=_),b={nameAlg:md[w.getUint16(0)],nameAlgBuffer:x.slice(0,2),name:x,qualifiedName:T};return{magic:n,type:i,qualifiedSigner:a,extraData:l,clockInfo:g,firmwareVersion:E,attested:b}}function UX(e){let t=0,r=JC(e),n=md[r.getUint16(t)];t+=2;let o=md[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=md[r.getUint16(t)];t+=2;let p=md[r.getUint16(t)];t+=2;let y=r.getUint16(t);t+=2;let g=r.getUint32(t);t+=4,l.rsa={symmetric:u,scheme:p,keyBits:y,exponent:g};let E=r.getUint16(t);t+=2,d=e.slice(t,t+=E)}else if(n==="TPM_ALG_ECC"){let u=md[r.getUint16(t)];t+=2;let p=md[r.getUint16(t)];t+=2;let y=DX[r.getUint16(t)];t+=2;let g=md[r.getUint16(t)];t+=2,l.ecc={symmetric:u,scheme:p,curveID:y,kdf:g};let E=r.getUint16(t);t+=2;let S=e.slice(t,t+=E),x=r.getUint16(t);t+=2;let w=e.slice(t,t+=x);d=yc([S,w])}else throw Error(`Unexpected type "${n}" (TPM)`);return{type:n,nameAlg:o,objectAttributes:s,authPolicy:c,parameters:l,unique:d}}async function MX(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"),p=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(!Zl(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(!p)throw Error("Attestation statement did not contain certInfo (TPM)");let y=UX(u),{unique:g,type:E,parameters:S}=y,x=Wp(o);if(E==="TPM_ALG_RSA"){if(!Kg(x))throw Error(`Credential public key with kty ${x.get(ht.kty)} did not match ${E}`);let Xe=x.get(ht.n),_n=x.get(ht.e);if(!Xe)throw Error("COSE public key missing n (TPM|RSA)");if(!_n)throw Error("COSE public key missing e (TPM|RSA)");if(!yl(g,Xe))throw Error("PubArea unique is not same as credentialPublicKey (TPM|RSA)");if(!S.rsa)throw Error("Parsed pubArea type is RSA, but missing parameters.rsa (TPM|RSA)");let Mo=_n,Ni=S.rsa.exponent||65537,Tr=Mo[0]+(Mo[1]<<8)+(Mo[2]<<16);if(Ni!==Tr)throw Error(`Unexpected public key exp ${Tr}, expected ${Ni} (TPM|RSA)`)}else if(E==="TPM_ALG_ECC"){if(!jp(x))throw Error(`Credential public key with kty ${x.get(ht.kty)} did not match ${E}`);let Xe=x.get(ht.crv),_n=x.get(ht.x),Mo=x.get(ht.y);if(!Xe)throw Error("COSE public key missing crv (TPM|ECC)");if(!_n)throw Error("COSE public key missing x (TPM|ECC)");if(!Mo)throw Error("COSE public key missing y (TPM|ECC)");if(!yl(g,yc([_n,Mo])))throw Error("PubArea unique is not same as public key x and y (TPM|ECC)");if(!S.ecc)throw Error("Parsed pubArea type is ECC, but missing parameters.ecc (TPM|ECC)");let Ni=S.ecc.curveID,Tr=NX[Ni];if(Tr!==Xe)throw Error(`Public area key curve ID "${Ni}" mapped to "${Tr}" which did not match public key crv of "${Xe}" (TPM|ECC)`)}else throw Error(`Unsupported pubArea.type "${E}"`);let w=FX(p),{magic:_,type:T,attested:b,extraData:I}=w;if(_!==4283712327)throw Error(`Unexpected magic value "${_}", expected "0xff544347" (TPM)`);if(T!=="TPM_ST_ATTEST_CERTIFY")throw Error(`Unexpected type "${T}", expected "TPM_ST_ATTEST_CERTIFY" (TPM)`);let O=await wc(u,RAe(b.nameAlg)),L=yc([b.nameAlgBuffer,O]);if(!yl(b.name,L))throw Error("Attested name comparison failed (TPM)");let Y=yc([n,i]),Z=await wc(Y,l);if(!yl(I,Z))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 ee=TS(d[0]),{basicConstraintsCA:ae,version:ne,subject:le,notAfter:ie,notBefore:je}=ee;if(ae)throw Error("Certificate basic constraints CA was not `false` (TPM)");if(ne!==2)throw Error("Certificate version was not `3` (ASN.1 value of 2) (TPM)");if(le.combined.length>0)throw Error("Certificate subject was not empty (TPM)");let ft=new Date;if(je>ft)throw Error(`Certificate not good before "${je.toString()}" (TPM)`);if(ft=new Date,ie<ft)throw Error(`Certificate not good after "${ie.toString()}" (TPM)`);let yt=Tn.parse(d[0],fo);if(!yt.tbsCertificate.extensions)throw Error("Certificate was missing extensions (TPM)");let Ut,_t;if(yt.tbsCertificate.extensions.forEach((Xe)=>{if(Xe.extnID===wS)Ut=Tn.parse(Xe.extnValue,bS);else if(Xe.extnID===xS)_t=Tn.parse(Xe.extnValue,Qm)}),!Ut)throw Error("Certificate did not contain subjectAltName extension (TPM)");if(!Ut[0].directoryName?.[0].length)throw Error("Certificate subjectAltName extension directoryName was empty (TPM)");let{tcgAtTpmManufacturer:nt,tcgAtTpmModel:be,tcgAtTpmVersion:Sr}=IAe(Ut[0].directoryName);if(!nt||!be||!Sr)throw Error("Certificate contained incomplete subjectAltName data (TPM)");if(!_t)throw Error("Certificate did not contain ExtendedKeyUsage extension (TPM)");if(!OX[nt])throw Error(`Could not match TPM manufacturer "${nt}" (TPM)`);if(_t[0]!=="2.23.133.8.3")throw Error(`Unexpected extKeyUsage "${_t[0]}", expected "2.23.133.8.3" (TPM)`);try{await ZC(yt.tbsCertificate.extensions,t)}catch(Xe){throw Error(`${Xe.message} (TPM)`)}let no=await yf.getStatement(t);if(no)try{await hf({statement:no,credentialPublicKey:o,x5c:d,attestationStatementAlg:l})}catch(Xe){throw Error(`${Xe.message} (TPM)`)}else try{await Vi(d.map(Ro),s)}catch(Xe){throw Error(`${Xe.message} (TPM)`)}return Tc({signature:c,data:p,x509Certificate:d[0],hashAlgorithm:l})}function IAe(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 RAe(e){if(e==="TPM_ALG_SHA256")return vt.ES256;else if(e==="TPM_ALG_SHA384")return vt.ES384;else if(e==="TPM_ALG_SHA512")return vt.ES512;throw Error(`Unexpected TPM attested name alg ${e}`)}var kB,LX="1.3.6.1.4.1.11129.2.1.17",DB;(function(e){e[e.verified=0]="verified",e[e.selfSigned=1]="selfSigned",e[e.unverified=2]="unverified",e[e.failed=3]="failed"})(DB||(DB={}));class nv{verifiedBootKey=new he;deviceLocked=!1;verifiedBootState=DB.verified;verifiedBootHash;constructor(e={}){Object.assign(this,e)}}h([v({type:he})],nv.prototype,"verifiedBootKey",void 0);h([v({type:A.Boolean})],nv.prototype,"deviceLocked",void 0);h([v({type:A.Enumerated})],nv.prototype,"verifiedBootState",void 0);h([v({type:he,optional:!0})],nv.prototype,"verifiedBootHash",void 0);var tv=kB=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,kB.prototype)}};tv=kB=h([z({type:B.Set,itemType:A.Integer})],tv);class st{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)}}h([v({context:1,type:tv,optional:!0})],st.prototype,"purpose",void 0);h([v({context:2,type:A.Integer,optional:!0})],st.prototype,"algorithm",void 0);h([v({context:3,type:A.Integer,optional:!0})],st.prototype,"keySize",void 0);h([v({context:5,type:tv,optional:!0})],st.prototype,"digest",void 0);h([v({context:6,type:tv,optional:!0})],st.prototype,"padding",void 0);h([v({context:10,type:A.Integer,optional:!0})],st.prototype,"ecCurve",void 0);h([v({context:200,type:A.Integer,optional:!0})],st.prototype,"rsaPublicExponent",void 0);h([v({context:203,type:tv,optional:!0})],st.prototype,"mgfDigest",void 0);h([v({context:303,type:A.Null,optional:!0})],st.prototype,"rollbackResistance",void 0);h([v({context:305,type:A.Null,optional:!0})],st.prototype,"earlyBootOnly",void 0);h([v({context:400,type:A.Integer,optional:!0})],st.prototype,"activeDateTime",void 0);h([v({context:401,type:A.Integer,optional:!0})],st.prototype,"originationExpireDateTime",void 0);h([v({context:402,type:A.Integer,optional:!0})],st.prototype,"usageExpireDateTime",void 0);h([v({context:405,type:A.Integer,optional:!0})],st.prototype,"usageCountLimit",void 0);h([v({context:503,type:A.Null,optional:!0})],st.prototype,"noAuthRequired",void 0);h([v({context:504,type:A.Integer,optional:!0})],st.prototype,"userAuthType",void 0);h([v({context:505,type:A.Integer,optional:!0})],st.prototype,"authTimeout",void 0);h([v({context:506,type:A.Null,optional:!0})],st.prototype,"allowWhileOnBody",void 0);h([v({context:507,type:A.Null,optional:!0})],st.prototype,"trustedUserPresenceRequired",void 0);h([v({context:508,type:A.Null,optional:!0})],st.prototype,"trustedConfirmationRequired",void 0);h([v({context:509,type:A.Null,optional:!0})],st.prototype,"unlockedDeviceRequired",void 0);h([v({context:600,type:A.Null,optional:!0})],st.prototype,"allApplications",void 0);h([v({context:601,type:he,optional:!0})],st.prototype,"applicationId",void 0);h([v({context:701,type:A.Integer,optional:!0})],st.prototype,"creationDateTime",void 0);h([v({context:702,type:A.Integer,optional:!0})],st.prototype,"origin",void 0);h([v({context:703,type:A.Null,optional:!0})],st.prototype,"rollbackResistant",void 0);h([v({context:704,type:nv,optional:!0})],st.prototype,"rootOfTrust",void 0);h([v({context:705,type:A.Integer,optional:!0})],st.prototype,"osVersion",void 0);h([v({context:706,type:A.Integer,optional:!0})],st.prototype,"osPatchLevel",void 0);h([v({context:709,type:he,optional:!0})],st.prototype,"attestationApplicationId",void 0);h([v({context:710,type:he,optional:!0})],st.prototype,"attestationIdBrand",void 0);h([v({context:711,type:he,optional:!0})],st.prototype,"attestationIdDevice",void 0);h([v({context:712,type:he,optional:!0})],st.prototype,"attestationIdProduct",void 0);h([v({context:713,type:he,optional:!0})],st.prototype,"attestationIdSerial",void 0);h([v({context:714,type:he,optional:!0})],st.prototype,"attestationIdImei",void 0);h([v({context:715,type:he,optional:!0})],st.prototype,"attestationIdMeid",void 0);h([v({context:716,type:he,optional:!0})],st.prototype,"attestationIdManufacturer",void 0);h([v({context:717,type:he,optional:!0})],st.prototype,"attestationIdModel",void 0);h([v({context:718,type:A.Integer,optional:!0})],st.prototype,"vendorPatchLevel",void 0);h([v({context:719,type:A.Integer,optional:!0})],st.prototype,"bootPatchLevel",void 0);h([v({context:720,type:A.Null,optional:!0})],st.prototype,"deviceUniqueAttestation",void 0);h([v({context:723,type:he,optional:!0})],st.prototype,"attestationIdSecondImei",void 0);h([v({context:724,type:he,optional:!0})],st.prototype,"moduleHash",void 0);var Ou;(function(e){e[e.software=0]="software",e[e.trustedEnvironment=1]="trustedEnvironment",e[e.strongBox=2]="strongBox"})(Ou||(Ou={}));var rv;(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"})(rv||(rv={}));class Ac{attestationVersion=rv.KM4;attestationSecurityLevel=Ou.software;keymasterVersion=0;keymasterSecurityLevel=Ou.software;attestationChallenge=new he;uniqueId=new he;softwareEnforced=new st;teeEnforced=new st;constructor(e={}){Object.assign(this,e)}}h([v({type:A.Integer})],Ac.prototype,"attestationVersion",void 0);h([v({type:A.Enumerated})],Ac.prototype,"attestationSecurityLevel",void 0);h([v({type:A.Integer})],Ac.prototype,"keymasterVersion",void 0);h([v({type:A.Enumerated})],Ac.prototype,"keymasterSecurityLevel",void 0);h([v({type:he})],Ac.prototype,"attestationChallenge",void 0);h([v({type:he})],Ac.prototype,"uniqueId",void 0);h([v({type:st})],Ac.prototype,"softwareEnforced",void 0);h([v({type:st})],Ac.prototype,"teeEnforced",void 0);class yd{attestationVersion=rv.keyMint4;attestationSecurityLevel=Ou.software;keyMintVersion=0;keyMintSecurityLevel=Ou.software;attestationChallenge=new he;uniqueId=new he;softwareEnforced=new st;hardwareEnforced=new st;constructor(e={}){Object.assign(this,e)}toLegacyKeyDescription(){return new Ac({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 yd({attestationVersion:e.attestationVersion,attestationSecurityLevel:e.attestationSecurityLevel,keyMintVersion:e.keymasterVersion,keyMintSecurityLevel:e.keymasterSecurityLevel,attestationChallenge:e.attestationChallenge,uniqueId:e.uniqueId,softwareEnforced:e.softwareEnforced,hardwareEnforced:e.teeEnforced})}}h([v({type:A.Integer})],yd.prototype,"attestationVersion",void 0);h([v({type:A.Enumerated})],yd.prototype,"attestationSecurityLevel",void 0);h([v({type:A.Integer})],yd.prototype,"keyMintVersion",void 0);h([v({type:A.Enumerated})],yd.prototype,"keyMintSecurityLevel",void 0);h([v({type:he})],yd.prototype,"attestationChallenge",void 0);h([v({type:he})],yd.prototype,"uniqueId",void 0);h([v({type:st})],yd.prototype,"softwareEnforced",void 0);h([v({type:st})],yd.prototype,"hardwareEnforced",void 0);var OB,NB=class extends st{};NB=h([z({type:B.Choice})],NB);var ov=OB=class extends Ve{constructor(t){super(t);Object.setPrototypeOf(this,OB.prototype)}findProperty(t){let r=this.find((n)=>n[t]!==void 0);if(r)return r[t];return}};ov=OB=h([z({type:B.Sequence,itemType:NB})],ov);class hd{attestationVersion=rv.KM4;attestationSecurityLevel=Ou.software;keymasterVersion=0;keymasterSecurityLevel=Ou.software;attestationChallenge=new he;uniqueId=new he;softwareEnforced=new ov;teeEnforced=new ov;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)}}h([v({type:A.Integer})],hd.prototype,"attestationVersion",void 0);h([v({type:A.Enumerated})],hd.prototype,"attestationSecurityLevel",void 0);h([v({type:A.Integer})],hd.prototype,"keymasterVersion",void 0);h([v({type:A.Enumerated})],hd.prototype,"keymasterSecurityLevel",void 0);h([v({type:he})],hd.prototype,"attestationChallenge",void 0);h([v({type:he})],hd.prototype,"uniqueId",void 0);h([v({type:ov})],hd.prototype,"softwareEnforced",void 0);h([v({type:ov})],hd.prototype,"teeEnforced",void 0);var BX=class extends hd{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)}};BX=h([z({type:B.Sequence})],BX);class e_{packageName;version;constructor(e={}){Object.assign(this,e)}}h([v({type:A.OctetString})],e_.prototype,"packageName",void 0);h([v({type:A.Integer})],e_.prototype,"version",void 0);class FB{packageInfos;signatureDigests;constructor(e={}){Object.assign(this,e)}}h([v({type:e_,repeated:"set"})],FB.prototype,"packageInfos",void 0);h([v({type:A.OctetString,repeated:"set"})],FB.prototype,"signatureDigests",void 0);async function $X(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(!Zl(l))throw Error(`Attestation statement contained invalid alg ${l} (Android Key)`);let d=Tn.parse(a[0],fo),u=new Uint8Array(d.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey),p=Qg(o);if(!yl(p,u))throw Error("Credential public key does not equal leaf cert public key (Android Key)");let y=d.tbsCertificate.extensions?.find((T)=>T.extnID===LX);if(!y)throw Error("Certificate did not contain extKeyStore (Android Key)");let g=Tn.parse(y.extnValue,Ac),{attestationChallenge:E,teeEnforced:S,softwareEnforced:x}=g;if(!yl(new Uint8Array(E.buffer),r))throw Error("Attestation challenge was not equal to client data hash (Android Key)");if(S.allApplications!==void 0)throw Error('teeEnforced contained "allApplications [600]" tag (Android Key)');if(x.allApplications!==void 0)throw Error('teeEnforced contained "allApplications [600]" tag (Android Key)');let w=await yf.getStatement(i);if(w)try{await hf({statement:w,credentialPublicKey:o,x5c:a,attestationStatementAlg:l})}catch(T){let b=T;throw Error(`${b.message} (Android Key)`,{cause:b})}else{let T=a.slice(0,-1).map(Ro),b=a.slice(-1).map(Ro);try{await Vi(T,b)}catch(I){let O=I;throw Error(`${O.message} (Android Key)`,{cause:O})}if(s.length>0&&s.indexOf(b[0])<0)throw Error("x5c root certificate was not a known root certificate (Android Key)")}let _=yc([t,r]);return Tc({signature:c,data:_,x509Certificate:a[0],hashAlgorithm:l})}async function qX(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 Vi(s.map(Ro),i)}catch(S){throw Error(`${S.message} (Apple)`)}let a=Tn.parse(s[0],fo),{extensions:c,subjectPublicKeyInfo:l}=a.tbsCertificate;if(!c)throw Error("credCert missing extensions (Apple)");let d=c.find((S)=>S.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=yc([r,n]),p=await wc(u),y=new Uint8Array(d.extnValue.buffer).slice(6);if(!yl(p,y))throw Error("credCert nonce was not expected value (Apple)");let g=Qg(o),E=new Uint8Array(l.subjectPublicKey);if(!yl(g,E))throw Error("Credential public key does not equal credCert public key (Apple)");return!0}async function jX(e){let{response:t,expectedChallenge:r,expectedOrigin:n,expectedRPID:o,expectedType:i,requireUserPresence:s=!0,requireUserVerification:a=!0,supportedAlgorithmIDs:c=vX,attestationSafetyNetEnforceCTSCheck:l=!0}=e,{id:d,rawId:u,type:p,response:y}=t;if(!d)throw Error("Missing credential ID");if(d!==u)throw Error("Credential ID was not base64url-encoded");if(p!=="public-key")throw Error(`Unexpected credential type ${p}, expected "public-key"`);let g=MU(y.clientDataJSON),{type:E,origin:S,challenge:x,tokenBinding:w}=g;if(Array.isArray(i)){if(!i.includes(E)){let Xe=i.join(", ");throw Error(`Unexpected registration response type "${E}", expected one of: ${Xe}`)}}else if(i){if(E!==i)throw Error(`Unexpected registration response type "${E}", expected "${i}"`)}else if(E!=="webauthn.create")throw Error(`Unexpected registration response type: ${E}`);if(typeof r==="function"){if(!await r(x))throw Error(`Custom challenge verifier returned false for registration response challenge "${x}"`)}else if(x!==r)throw Error(`Unexpected registration response challenge "${x}", expected "${r}"`);if(Array.isArray(n)){if(!n.includes(S))throw Error(`Unexpected registration response origin "${S}", expected one of: ${n.join(", ")}`)}else if(S!==n)throw Error(`Unexpected registration response origin "${S}", expected "${n}"`);if(w){if(typeof w!=="object")throw Error(`Unexpected value for TokenBinding "${w}"`);if(["present","supported","not-supported"].indexOf(w.status)<0)throw Error(`Unexpected tokenBinding.status value of "${w.status}"`)}let _=jg(y.attestationObject),T=v6(_),b=T.get("fmt"),I=T.get("authData"),O=T.get("attStmt"),L=IB(I),{aaguid:Y,rpIdHash:Z,flags:ee,credentialID:ae,counter:ne,credentialPublicKey:le,extensionsData:ie}=L,je;if(o){let Xe=[];if(typeof o==="string")Xe=[o];else Xe=o;je=await _B(Z,Xe)}if(s&&!ee.up)throw Error("User presence was required, but user was not present");if(a&&!ee.uv)throw Error("User verification was required, but user could not be verified");if(!ae)throw Error("No credential ID was provided by authenticator");if(!le)throw Error("No public key was provided by authenticator");if(!Y)throw Error("No AAGUID was present during registration");let yt=Wp(le).get(ht.alg);if(typeof yt!=="number")throw Error("Credential public key was missing numeric alg");if(!c.includes(yt)){let Xe=c.join(", ");throw Error(`Unexpected public key alg "${yt}", expected one of "${Xe}"`)}let Ut=await wc(jg(y.clientDataJSON)),_t=mf.getRootCertificates({identifier:b}),nt={aaguid:Y,attStmt:O,authData:I,clientDataHash:Ut,credentialID:ae,credentialPublicKey:le,rootCertificates:_t,rpIdHash:Z,attestationSafetyNetEnforceCTSCheck:l},be=!1;if(b==="fido-u2f")be=await wX(nt);else if(b==="packed")be=await CX(nt);else if(b==="android-safetynet")be=await _X(nt);else if(b==="android-key")be=await $X(nt);else if(b==="tpm")be=await MX(nt);else if(b==="apple")be=await qX(nt);else if(b==="none"){if(O.size>0)throw Error("None attestation had unexpected attestation statement");be=!0}else throw Error(`Unsupported Attestation Format: ${b}`);if(!be)return{verified:!1};let{credentialDeviceType:Sr,credentialBackedUp:no}=CB(ee);return{verified:!0,registrationInfo:{fmt:b,aaguid:CP(Y),credentialType:p,credential:{id:Yl(ae),publicKey:le,counter:ne,transports:t.response.transports},attestationObject:_,userVerified:ee.uv,credentialDeviceType:Sr,credentialBackedUp:no,origin:g.origin,rpID:je,authenticatorExtensionResults:ie}}}import{Data as PAe,Effect as Ty,Either as CAt,Schema as xr}from"effect";class HX extends PAe.TaggedError("processfocus:internal-tag/openauth/PasskeyVerificationError"){}var WX=xr.Struct({id:xr.String,rawId:xr.String,type:xr.Literal("public-key"),clientExtensionResults:xr.Record({key:xr.String,value:xr.Unknown}),response:xr.Struct({clientDataJSON:xr.String,attestationObject:xr.String,transports:xr.optional(xr.Array(xr.String))})}),CAe=(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()}}}),_Ae=xr.Struct({id:xr.String,rawId:xr.String,type:xr.Literal("public-key"),clientExtensionResults:xr.Record({key:xr.String,value:xr.Unknown}),response:xr.Struct({clientDataJSON:xr.String,authenticatorData:xr.String,signature:xr.String,userHandle:xr.String})});var OAt=xr.Struct({challengeId:xr.String,response:WX,sessionBearer:xr.optional(xr.String)}),NAt=xr.Struct({challengeId:xr.String,response:_Ae}),FAt=xr.Struct({token:xr.String});var kAe=(e)=>Buffer.from(e).toString("base64url"),DAe=(e)=>{let t=Buffer.from(e,"base64url");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)},UB=WX,OAe=(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()}}))},NAe=(e,t,r,n)=>{let o=OAe(n);return Ty.promise(()=>xX({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 MB=(e)=>NAe({rpName:e.rpName,rpID:e.rpID},e.email,DAe(e.userHandle),e.excludeCredentials),LB=(e)=>Ty.tryPromise({try:()=>jX({response:CAe(e.response),expectedChallenge:e.expectedChallenge,expectedOrigin:typeof e.origin==="string"?e.origin:[...e.origin],expectedRPID:e.rpID,requireUserVerification:!0}),catch:(t)=>new HX({message:"Passkey registration verification failed",cause:t})}).pipe(Ty.tapError((t)=>Ty.logError("Registration verification failed").pipe(Ty.annotateLogs({error:t}))),Ty.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:kAe(t.registrationInfo.credential.publicKey),counter:t.registrationInfo.credential.counter,...r&&{transports:r}}}}),Ty.orElseSucceed(()=>({verified:!1})));import{Clock as HAt,Effect as WAt,Layer as VAt,Schema as VX,Stream as zAt}from"effect";var QAt=VX.parseJson(VX.Unknown);import{Clock as t_,Effect as Pw,Layer as FAe,Stream as UAe}from"effect";var BB=FAe.sync(Zr,()=>{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)=>Pw.gen(function*(){let n=t(Mm(r));if(!n.found)return;let o=e[n.index][1];if(o.expiry){if((yield*t_.currentTimeMillis)>=o.expiry){e.splice(n.index,1);return}}return o.value}),take:(r)=>Pw.gen(function*(){let n=t(Mm(r));if(!n.found)return;let o=e[n.index][1];if(e.splice(n.index,1),o.expiry){if((yield*t_.currentTimeMillis)>=o.expiry)return}return o.value}),set:(r,n,o)=>Pw.gen(function*(){let i=Mm(r),s=t(i),a={value:n};if(o){let l=yield*t_.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)=>Pw.sync(()=>{let n=Mm(r),o=t(n);if(o.found)e.splice(o.index,1)}),scan:(r)=>UAe.fromIterableEffect(Pw.gen(function*(){let n=yield*t_.currentTimeMillis,o=Mm(r),i=[];for(let[s,a]of e){if(!s.startsWith(o))continue;if(a.expiry&&n>=a.expiry)continue;i.push([LJ(s),a.value])}return i}))}});import{Runtime as tIt}from"effect";import{Clock as nIe,DateTime as KX,Effect as Ts,Option as cv,Schema as Nu}from"effect";import{Context as $Ae}from"effect";class gd extends $Ae.Tag("processfocus:internal-tag/auth-api/DelegationDatabase")(){}import{createHash as ZAe}from"crypto";import{Context as eIe,Data as tIe,DateTime as gf,Effect as Iy,FiberRef as zX,Layer as rIe,Option as sv}from"effect";import{Context as qAe}from"effect";class Cw extends qAe.Tag("processfocus:internal-tag/auth-policy/AuthorizationService")(){}import{Context as jAe,Effect as AIt,FiberRef as IIt}from"effect";class HAe extends jAe.Tag("processfocus:internal-tag/auth-policy/CurrentPrincipal")(){}import{Data as iv}from"effect";class WAe extends iv.TaggedError("PolicyLoadError"){}class VAe extends iv.TaggedError("SchemaLoadError"){}class zAe extends iv.TaggedError("PolicyParseError"){}class KAe extends iv.TaggedError("SchemaParseError"){}class GAe extends iv.TaggedError("AuthorizationError"){}class QAe extends iv.TaggedError("AuthorizationDeniedError"){}class Ay{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 r_{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}}}import{Context as JAe,Effect as YAe,FiberRef as XAe}from"effect";class Ic extends JAe.Tag("processfocus:internal-tag/request-time/RequestTime")(){}var Ie=()=>YAe.flatMap(Ic,XAe.get);class zi extends tIe.TaggedError("InvalidDelegationSession"){}class av extends eIe.Tag("processfocus:internal-tag/auth-api/DelegationSessionService")(){}var $B=({db:e,authDb:t,auth:r})=>(n)=>Iy.gen(function*(){let o=yield*gf.now,i=n.delegation;if(!i||n.humanAuthentication!==void 0)return yield*new zi;let s=yield*e.findGeneration({generationId:i.generationId});if(sv.isNone(s))return yield*new zi;let a=s.value,c=gf.toEpochMillis(a.expiresAt);if(a.id!==i.id||a.userId!==n.userId||a.revokedAt!==null||a.generationRevokedAt!==null||i.expiresAt!==c||gf.toEpochMillis(o)>=c)return yield*new zi;let l=yield*t.findProviderUserByUserId(a.userId);if(sv.isNone(l)||l.value.email!==n.email)return yield*new zi;let d=yield*t.findProviderUserRoles(a.userId),u=n.delegationRoleSelection===void 0?d:d.filter((S)=>n.delegationRoleSelection?.includes(S)),p=new Ay(a.id,{owner:l.value.email,name:a.name,roles:u,orgUnitId:l.value.orgUnitPath});if(!(yield*r.canLogin(p,{uid:{type:"PF::Application",id:"frontend"}}).pipe(Iy.provideService(Ic,zX.unsafeMake(o)))))return yield*new zi;let y=new Set([a.generationId]),g=new Set([a.id]),E=a;while(E.parentGenerationId!==null){if(y.has(E.parentGenerationId))return yield*new zi;let S=yield*e.findGeneration({generationId:E.parentGenerationId});if(sv.isNone(S))return yield*new zi;let x=S.value,w=gf.toEpochMillis(x.expiresAt);if(g.has(x.id)||x.revokedAt!==null||x.generationRevokedAt!==null||gf.toEpochMillis(o)>=w||gf.toEpochMillis(E.expiresAt)>w)return yield*new zi;y.add(x.generationId),g.add(x.id);let _=yield*t.findProviderUserByUserId(x.userId);if(sv.isNone(_))return yield*new zi;let T=yield*t.findProviderUserRoles(x.userId);if(!(yield*r.canLogin(new Ay(x.id,{owner:_.value.email,name:x.name,roles:T,orgUnitId:_.value.orgUnitPath}),{uid:{type:"PF::Application",id:"frontend"}}).pipe(Iy.provideService(Ic,zX.unsafeMake(o)))))return yield*new zi;E=x}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(Iy.mapError(()=>new zi)),KIt=rIe.effect(av,Iy.gen(function*(){let e=yield*gd,t=yield*Vo,r=yield*Cw,n=yield*Hs,o=$B({db:e,authDb:t,auth:r});return av.of({check:o,exchange:(i)=>n.withTransaction(Iy.gen(function*(){if(!/^pfds_[A-Za-z0-9_-]{43}$/.test(i))return yield*new zi;let s=ZAe("sha256").update(i).digest("base64url"),a=yield*e.findGeneration({verifier:s});if(sv.isNone(a))return yield*new zi;let c=a.value,l=yield*t.findProviderUserByUserId(c.userId);if(sv.isNone(l))return yield*new zi;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:gf.toEpochMillis(c.expiresAt)}});return yield*e.recordLogin({delegationId:c.id,generationId:c.generationId,ownerId:c.ownerId,loggedInAt:yield*gf.now}),d})).pipe(Iy.mapError(()=>new zi))})}));var oIe=Nu.Struct({secret:Nu.String.pipe(Nu.maxLength(48))}),iIe=Nu.Struct({accessToken:Nu.String.pipe(Nu.minLength(1),Nu.maxLength(16384))}),Ci=(e,t=200)=>IO(e,{status:t,headers:{"cache-control":"no-store",pragma:"no-cache","x-content-type-options":"nosniff"}}),sIe=Ts.gen(function*(){let e=Wl(),t=yield*Ts.serviceOption(av),r=yield*Ts.serviceOption(gd),n=yield*Ln,o=0,i=0,s=yield*Ts.context();return Ts.gen(function*(){let a=yield*on,c=new URL(a.url,"https://localhost");if(c.pathname==="/oauth/delegation/availability"){if(a.method!=="GET")return Ci({error:"method_not_allowed"},405);let x=new URL(yield*ci(a.headers));if(c.search||x.protocol!=="https:"&&!["localhost","127.0.0.1","[::1]"].includes(x.hostname))return Ci({error:"invalid_request"},400);let{client:w,method:_}=yield*ol(new Map);if(w.id!==e||_!=="client_jwt")return Ci({error:"invalid_client"},401);let T=cv.isSome(r)&&(yield*r.value.isSecretLoginEnabled().pipe(Ts.orElseSucceed(()=>!1)));return Ci({secretLoginEnabled:T})}if(cv.isNone(t))return Ci({error:"delegated_access_unavailable"},403);if(a.method!=="POST")return Ci({error:"method_not_allowed"},405);let l=new URL(a.url,"https://localhost").pathname==="/oauth/delegation/session",d=new URL(yield*ci(a.headers));if(d.protocol!=="https:"&&!["localhost","127.0.0.1","[::1]"].includes(d.hostname))return Ci({error:"invalid_request"},400);if(new URL(a.url,"https://localhost").search||a.headers["content-type"]?.split(";")[0]!=="application/json")return Ci({error:"invalid_request"},400);let u=yield*nIe.currentTimeMillis;if(u>=o+60000)o=u,i=0;if(!l&&++i>30)return Ci({error:"rate_limited"},429);let{client:p,method:y}=yield*ol(new Map);if(p.id!==e||y!=="client_jwt")return Ci({error:"invalid_client"},401);if(l){let x=yield*a.json.pipe(ez(cv.some(20480)),Ts.flatMap(Nu.decodeUnknown(iIe,{onExcessProperty:"error"}))),w=yield*n.allSigningKeys,_=yield*KX.now,T=yield*Ts.tryPromise(()=>uc(x.accessToken,async(Y)=>{let Z=w.find((ee)=>ee.id===Y.kid&&ee.alg===Y.alg);if(!Z)throw Error("Unknown signing key");return Z.public},{issuer:d.toString().replace(/\/$/,""),audience:p.audience,requiredClaims:["exp","sub"],currentDate:KX.toDateUtc(_)})).pipe(Ts.option);if(cv.isNone(T))return Ci({error:"invalid_token"},401);let b=T.value.payload,I=b.properties;if(b.mode!=="access"||b.type!=="providerUser"||typeof I!=="object"||I===null||!("delegation"in I))return Ci({error:"invalid_token"},401);let O=yield*Ts.promise(async()=>_p.providerUser["~standard"].validate(I));if(O.issues||!O.value.delegation||b.exp===void 0||b.exp*1000>O.value.delegation.expiresAt)return Ci({error:"invalid_token"},401);let L=yield*t.value.check(O.value).pipe(Ts.option);if(cv.isNone(L))return Ci({error:"invalid_token"},401);return Ci({session:L.value})}let g=yield*a.json.pipe(ez(cv.some(1024)),Ts.flatMap(Nu.decodeUnknown(oIe,{onExcessProperty:"error"}))),E=yield*t.value.exchange(g.secret),S=yield*Gl({type:"providerUser",properties:E,subject:`delegation:${E.delegation.id}:${E.delegation.generationId}`,clientID:p.id,audience:p.audience,ttl:{access:600,refresh:7776000},expiresAt:E.delegation.expiresAt,timeUsed:void 0,nextToken:void 0});return Ci({access_token:S.access,refresh_token:S.refresh,expires_in:S.expiresIn,refresh_expires_in:S.refreshExpiresIn})}).pipe(Ts.provide(s),Ts.catchAll(()=>Ts.succeed(Ci({error:"invalid_grant"},400))))});import{createHash as GX,randomBytes as QX,randomUUID as qB}from"crypto";import{Data as aIe,DateTime as dn,Effect as kr,FiberRef as lv,Option as hl,Schema as Do}from"effect";class qn extends aIe.TaggedError("DelegationRequestError"){}var _w=Do.Struct({requestId:Do.optional(Do.UUID),name:Do.String.pipe(Do.minLength(1),Do.maxLength(128)),lifetimeDays:Do.Literal(1,7,14)}),jB={id:Do.String.pipe(Do.minLength(1)),generationId:Do.String.pipe(Do.minLength(1)),expectedName:_w.fields.name},cIe=Do.Union(Do.Struct({operation:Do.Literal("rename"),...jB,name:_w.fields.name}),Do.Struct({operation:Do.Literal("replace"),...jB,name:_w.fields.name,lifetimeDays:_w.fields.lifetimeDays}),Do.Struct({operation:Do.Literal("revoke"),...jB})),lIe=(e,t)=>({id:e.id,name:e.name,generationId:e.generationId,createdAt:dn.formatIso(e.createdAt),expiresAt:dn.formatIso(e.expiresAt),revokedAt:e.revokedAt===null?null:dn.formatIso(e.revokedAt),status:e.revokedAt!==null?"revoked":dn.lessThanOrEqualTo(e.expiresAt,t)?"expired":"active",lastUsedAt:e.lastUsedAt===null?null:dn.formatIso(e.lastUsedAt)}),_i=(e,t=200)=>IO(e,{status:t,headers:{"cache-control":"no-store",pragma:"no-cache","x-content-type-options":"nosniff"}}),dIe=kr.gen(function*(){let e=yield*kr.serviceOption(gd),t=yield*kr.serviceOption(Cw),r=yield*Vo,n=hl.isSome(e)&&hl.isSome(t)?$B({db:e.value,authDb:r,auth:t.value}):void 0,o=yield*Hs,i=yield*Ln,s=yield*Ii;return kr.gen(function*(){let c=yield*on;if(c.method!=="GET"&&c.method!=="POST"&&c.method!=="PATCH")return _i({error:"method_not_allowed"},405);let l=c.headers.authorization?.match(/^Bearer ([^ ]+)$/)?.[1];if(!l)return _i({error:"invalid_token"},401);let d=yield*i.allSigningKeys,u=yield*ci(c.headers).pipe(kr.mapError(()=>new qn({status:401,error:"invalid_token"}))),p=yield*dn.now,y=yield*kr.tryPromise({try:()=>uc(l,async(ie)=>{let je=d.find((ft)=>ft.id===ie.kid&&ft.alg===ie.alg);if(!je)throw Error("Unknown signing key");return je.public},{issuer:u,audience:[...s.staticClients.values()].map((ie)=>ie.audience),requiredClaims:["exp","sub"],currentDate:dn.toDateUtc(p)}),catch:()=>new qn({status:401,error:"invalid_token"})}),g=y.payload.exp;if(typeof g!=="number"||y.payload.mode!=="access"||y.payload.type!=="providerUser")return _i({error:"invalid_token"},401);let E=yield*kr.promise(async()=>_p.providerUser["~standard"].validate(y.payload.properties));if(E.issues)return _i({error:"invalid_token"},401);let S=E.value;if(S.delegation!==void 0&&n===void 0)return _i({error:"invalid_token"},401);if(hl.isNone(e))return _i({error:"delegation_unavailable"},403);let x=e.value,w=c.method==="PATCH"?yield*c.json.pipe(kr.flatMap(Do.decodeUnknown(cIe,{onExcessProperty:"error"})),kr.mapError(()=>new qn({status:400,error:"invalid_request"}))):void 0,_=new URL(c.url,"https://auth.invalid").searchParams.getAll("ownerUserId");if(_.length>1||_[0]==="")return _i({error:"invalid_request"},400);let T=_[0]??S.userId,b=S,I=kr.gen(function*(){if(dn.toEpochMillis(yield*dn.now)>=g*1000)return yield*new qn({status:401,error:"invalid_token"});let ie=b.delegation!==void 0&&n!==void 0?yield*n(b).pipe(kr.mapError(()=>new qn({status:401,error:"invalid_token"}))):b,je=new Set,ft=new Set,yt=ie.delegation?.generationId??null;while(yt!==null){if(ft.has(yt))return yield*new qn({status:401,error:"invalid_token"});ft.add(yt);let Rr=yield*x.findGeneration({generationId:yt});if(hl.isNone(Rr))return yield*new qn({status:401,error:"invalid_token"});je.add(Rr.value.id),yt=Rr.value.parentGenerationId}let Ut=(Rr,So)=>dn.unsafeMake(Math.min(dn.toEpochMillis(dn.add(Rr,{days:So})),ie.delegation?.expiresAt??Number.POSITIVE_INFINITY)),_t=yield*x.findOwnerId(ie.userId),nt=yield*r.findProviderUserByUserId(ie.userId);if(hl.isNone(_t)||hl.isNone(nt))return yield*new qn({status:401,error:"invalid_token"});let be=yield*x.findOwnerId(T),Sr=yield*r.findProviderUserByUserId(T);if(hl.isNone(be)||hl.isNone(Sr))return yield*new qn({status:403,error:c.method==="PATCH"?"operation_denied":"issuance_denied"});if(hl.isNone(t))return yield*new qn({status:403,error:c.method==="PATCH"?"operation_denied":"issuance_denied"});let no=t.value,Xe=ie.delegation===void 0?yield*r.findProviderUserRoles(ie.userId):ie.roles,_n=ie.delegation===void 0?new r_(nt.value.email,{roles:Xe,orgUnitId:nt.value.orgUnitPath}):new Ay(ie.delegation.id,{owner:nt.value.email,name:ie.delegation.name,roles:Xe,orgUnitId:nt.value.orgUnitPath}),Mo=yield*r.findProviderUserRoles(T),Ni=new r_(Sr.value.email,{roles:Mo,orgUnitId:Sr.value.orgUnitPath}),Tr=(Rr)=>new Ay(Rr.id,{owner:Sr.value.email,name:Rr.name,roles:Mo,orgUnitId:Sr.value.orgUnitPath}),Qo=(Rr)=>kr.gen(function*(){let So=(Nc)=>no.canIssueDelegationSecret(_n,Ni,{ownerProviderUserId:T,humanSession:ie.delegation===void 0&&ie.humanSession===!0,humanAuthentication:Nc}).pipe(kr.provideService(Ic,lv.unsafeMake(Rr)));if(yield*So(ie.humanAuthentication))return"allowed";if(ie.delegation!==void 0||ie.userId!==T)return"issuance_denied";if(!(yield*So({providerUserId:ie.userId,authenticatedAt:dn.toEpochMillis(Rr),method:"passkey"})))return"issuance_denied";let Ps=yield*r.findOAuthProviderByName("passkey");return nt.value.provider==="passkey"&&hl.isSome(Ps)?"verification_required":"unsupported_authentication"}),ur=(Rr,So)=>kr.gen(function*(){let Ps=yield*kr.all({rename:no.canManageDelegation(_n,Tr(Rr),"rename"),replace:no.canManageDelegation(_n,Tr(Rr),"replace"),revoke:no.canManageDelegation(_n,Tr(Rr),"revoke")}).pipe(kr.provideService(Ic,lv.unsafeMake(So)));return{...lIe(Rr,So),allowedActions:{rename:Rr.revokedAt===null&&Ps.rename,replace:!je.has(Rr.id)&&Rr.revokedAt===null&&Ps.replace&&(yield*Qo(So))!=="issuance_denied",revoke:Rr.revokedAt===null&&Ps.revoke}}});return{session:ie,ancestorIds:je,issuanceExpiry:Ut,actorId:_t.value,ownerId:be.value,owner:Sr.value,principal:_n,ownerPrincipal:Ni,resource:Tr,withActions:ur,issuanceDecision:Qo,auth:no}});if(c.method==="GET"){let{session:ie,ownerId:je,owner:ft,principal:yt,ownerPrincipal:Ut,withActions:_t,issuanceDecision:nt,auth:be}=yield*I,Sr=lv.unsafeMake(p);if(!(yield*be.canListDelegationTokens(yt,Ut).pipe(kr.provideService(Ic,Sr))))return _i({error:"issuance_denied"},403);let Xe=yield*x.list(je);return _i({owner:{userId:T,email:ft.email},issuanceDeadline:ie.delegation===void 0?null:dn.formatIso(dn.unsafeMake(ie.delegation.expiresAt)),canIssue:(yield*nt(p))!=="issuance_denied",delegations:yield*kr.forEach(Xe,(_n)=>_t(_n,p))})}let O=yield*x.findOwnerId(T);if(hl.isNone(O)){if(T===S.userId)return _i({error:"invalid_token"},401);return _i({error:c.method==="PATCH"?"operation_denied":"issuance_denied"},403)}if(w!==void 0){let ie=w,je=ie.operation==="revoke"?ie.expectedName:ie.name.trim();if(!je)return _i({error:"invalid_request"},400);let ft=yield*o.withTransaction(kr.gen(function*(){yield*x.releaseExpiredNames(O.value,p);let{session:yt,ancestorIds:Ut,issuanceExpiry:_t,actorId:nt,ownerId:be,principal:Sr,ownerPrincipal:no,resource:Xe,withActions:_n,issuanceDecision:Mo,auth:Ni}=yield*I,Tr=yield*dn.now;yield*x.releaseExpiredNames(be,Tr);let Qo=yield*x.list(be),ur=Qo.find((vo)=>vo.id===ie.id);if(!ur)return yield*new qn({status:403,error:"operation_denied"});if(!(yield*Ni.canManageDelegation(Sr,Xe(ur),ie.operation).pipe(kr.provideService(Ic,lv.unsafeMake(Tr))))||ur.revokedAt!==null)return yield*new qn({status:403,error:"operation_denied"});if(ie.operation==="replace"&&Ut.has(ur.id))return yield*new qn({status:403,error:"operation_denied"});if(ie.operation==="replace"&&T!==yt.userId&&!(yield*Ni.canIssueDelegationSecret(Sr,no,{ownerProviderUserId:T,humanSession:yt.delegation===void 0&&yt.humanSession===!0,humanAuthentication:yt.humanAuthentication}).pipe(kr.provideService(Ic,lv.unsafeMake(Tr)))))return yield*new qn({status:403,error:"operation_denied"});if(ur.generationId!==ie.generationId||ur.name!==ie.expectedName)return yield*new qn({status:409,error:"stale_delegation"});if(ie.operation==="replace"&&je!==ur.name&&!(yield*Ni.canManageDelegation(Sr,Xe(ur),"rename").pipe(kr.provideService(Ic,lv.unsafeMake(Tr)))))return yield*new qn({status:403,error:"operation_denied"});if(ie.operation==="replace"){let vo=yield*Mo(Tr);if(vo!=="allowed")return yield*new qn({status:403,error:vo})}let So=ie.operation==="replace"||dn.greaterThan(ur.expiresAt,Tr);if(ie.operation!=="revoke"&&So&&Qo.some((vo)=>vo.id!==ur.id&&vo.name===je&&vo.revokedAt===null&&dn.greaterThan(vo.expiresAt,Tr)))return yield*new qn({status:409,error:"name_conflict"});if(ie.operation==="revoke"){let vo=dn.unsafeMake(Math.floor(dn.toEpochMillis(Tr)/1000)*1000);return yield*x.revoke({id:ur.id,revokedAt:vo}),yield*x.revokeGeneration({generationId:ur.generationId,revokedAt:vo}),yield*x.recordChange({delegationId:ur.id,generationId:ur.generationId,actorId:nt,actorDelegation:yt.delegation,event:"revoked",occurredAt:Tr}),yield*_n({...ur,revokedAt:vo},Tr)}if(yield*x.updateName({id:ur.id,name:je,activeName:So?je:null}),je!==ur.name)yield*x.recordChange({delegationId:ur.id,generationId:ur.generationId,actorId:nt,actorDelegation:yt.delegation,event:"renamed",oldName:ur.name,newName:je,occurredAt:Tr});if(ie.operation==="rename")return yield*_n({...ur,name:je},Tr);let Ps=`dsg-${qB()}`,Nc=`pfds_${QX(32).toString("base64url")}`,gi=dn.unsafeMake(Math.floor(dn.toEpochMillis(Tr)/1000)*1000),Hu=_t(gi,ie.lifetimeDays);return yield*x.revokeGeneration({generationId:ur.generationId,revokedAt:Tr}),yield*x.recordChange({delegationId:ur.id,generationId:ur.generationId,actorId:nt,actorDelegation:yt.delegation,event:"replaced",occurredAt:Tr}),yield*x.insertGeneration({id:Ps,parentGenerationId:yt.delegation?.generationId??null,delegationId:ur.id,verifier:GX("sha256").update(Nc).digest("base64url"),issuedAt:gi,expiresAt:Hu}),yield*x.recordIssuance({delegationId:ur.id,generationId:Ps,actorId:nt,actorDelegation:yt.delegation,issuedAt:gi}),{...yield*_n({...ur,name:je,generationId:Ps,createdAt:gi,expiresAt:Hu,lastUsedAt:null},Tr),secret:Nc}}));return _i(ft)}let L=yield*c.json.pipe(kr.flatMap(Do.decodeUnknown(_w,{onExcessProperty:"error"})),kr.mapError(()=>new qn({status:400,error:"invalid_request"}))),Y=L.name.trim();if(Y.length===0)return _i({error:"invalid_request"},400);let Z=`dlg-${qB()}`,ee=`dsg-${L.requestId??qB()}`,ae=`pfds_${QX(32).toString("base64url")}`,ne=GX("sha256").update(ae).digest("base64url"),le=yield*o.withTransaction(kr.gen(function*(){yield*x.releaseExpiredNames(O.value,p);let{session:ie,issuanceExpiry:je,actorId:ft,ownerId:yt,withActions:Ut,issuanceDecision:_t}=yield*I,nt=yield*dn.now,be=yield*_t(nt);if(be!=="allowed")return yield*new qn({status:403,error:be});if(yield*x.hasGeneration(ee))return yield*new qn({status:409,error:"submission_replayed"});let Sr=dn.unsafeMake(Math.floor(dn.toEpochMillis(nt)/1000)*1000),no=je(Sr,L.lifetimeDays);if(yield*x.releaseExpiredNames(yt,nt),!(yield*x.claimName({id:Z,ownerId:yt,name:Y})))return yield*new qn({status:409,error:"name_conflict"});return yield*x.insertGeneration({id:ee,parentGenerationId:ie.delegation?.generationId??null,delegationId:Z,verifier:ne,issuedAt:Sr,expiresAt:no}),yield*x.recordIssuance({delegationId:Z,generationId:ee,actorId:ft,actorDelegation:ie.delegation,issuedAt:Sr}),{...yield*Ut({id:Z,name:Y,generationId:ee,createdAt:Sr,expiresAt:no,revokedAt:null,lastUsedAt:null},nt),secret:ae}}));return _i(le,201)}).pipe(kr.catchTag("DelegationRequestError",({status:c,error:l})=>kr.succeed(_i({error:l},c))),kr.catchAll(()=>kr.logError("Unexpected delegation management failure").pipe(kr.as(_i({error:"internal_error"},500)))))});import{Data as uIe}from"effect";class HB extends uIe.TaggedError("InvariantViolationError"){}import{Data as kIe,DateTime as c_,Effect as un,Either as o1,Option as s_,Schema as jn}from"effect";Ki();import{Data as Dy,DateTime as rPt,Effect as ZB,Option as e1}from"effect";import{Effect as FRt,Either as URt,Option as MRt,Schema as QB}from"effect";var BRt=QB.Struct({inviteOnly:QB.optional(QB.Boolean)});import{Effect as jRt,Schedule as o7}from"effect";var HRt=o7.addDelay(o7.recurs(1),()=>100);import{createHash as vIe,randomBytes as xIe,randomUUID as EIe}from"crypto";import{DateTime as i_,Effect as i7,Option as JB,Schema as ky}from"effect";var _y=(e)=>e.provider==="passkey"?e.sub:Buffer.from(e.userId).toString("base64url");var YB=86400;var XRt=ky.Struct({recoveryId:ky.String,userId:ky.String,userHandle:ky.String,email:ky.String,invitationId:ky.String,actor:ky.String});var XB=(e)=>vIe("sha256").update(e).digest("base64url"),bIe=(e)=>["passkey-recovery-current",e];var s7=(e)=>i7.gen(function*(){let t=yield*Vo,r=yield*Zr;return yield*(yield*Hs).withTransaction(i7.gen(function*(){let o=e.email.trim().toLowerCase(),i=yield*t.findProviderUserByEmail(o),s={ok:!1,error:"Cannot recover this account. An active account with current roles and a closed, non-deleted invitation is required."};if(JB.isNone(i))return s;let a=yield*t.findRecoveryInvitation(i.value.id,o);if(JB.isNone(a)||(yield*t.hasPendingInvitation(o)))return s;if(JB.isNone(yield*t.findOAuthProviderByName("passkey")))return s;if((yield*t.findProviderUserRoles(i.value.id)).length===0)return s;let c=yield*i_.now,l={recoveryId:EIe(),userId:i.value.id,email:o,userHandle:_y({...i.value,userId:i.value.id}),invitationId:a.value,actor:e.actor},d=`pfr_${xIe(32).toString("base64url")}`;return yield*r.set(bIe(l.userId),l.recoveryId,YB),yield*r.set(["passkey-recovery-link",XB(d)],l,YB),yield*r.set(["passkey-recovery-audit",l.recoveryId,"issued"],{...l,at:i_.formatIso(c)}),{ok:!0,email:o,registrationLinkUrl:`${e.frontendOrigin.replace(/\/$/,"")}/register/passkey#token=${d}`,expiresAt:i_.toDateUtc(i_.add(c,{seconds:YB}))}}))});class AIe extends Dy.TaggedError("processfocus:internal-tag/RootOrgUnitNotFoundError"){}var c7=10;class l7 extends Dy.TaggedError("processfocus:internal-tag/PasskeyOpenRegistrationDeniedError"){}class IIe extends Dy.TaggedError("processfocus:internal-tag/PasskeyInvitationRegistrationDeniedError"){}class n1 extends Dy.TaggedError("processfocus:internal-tag/PasskeyIdentityNotFoundError"){}class RIe extends Dy.TaggedError("processfocus:internal-tag/PasskeyCounterError"){}class t1 extends Dy.TaggedError("processfocus:internal-tag/PasskeyCredentialAlreadyOwnedError"){}class r1 extends Dy.TaggedError("processfocus:internal-tag/PasskeyManagementDeniedError"){}var PIe=(e,t)=>Sd(e,(r)=>/unique/i.test(r)&&t.some((n)=>n.test(r)));var CIe=(e)=>PIe(e,[/passkey_credential_id/i,/pf_passkey_credential/i]),_Ie=ZB.fn("passkey.withRoles")(function*(e){let t=yield*Vo,r=yield*t.findProviderUserRoles(e),n=yield*t.findProviderUserByUserId(e);if(e1.isNone(n))return yield*new n1({userHandle:e});return{...n.value,roles:r}});var d7=(e)=>ZB.gen(function*(){let t=yield*Vo,r=yield*t.findProviderUserByUserId(e.userId);if(e1.isNone(r))return yield*new n1({userHandle:e.userHandle});if(_y({...r.value,userId:r.value.id})!==e.userHandle)return yield*new r1({reason:"user_handle_mismatch"});if((yield*t.listPasskeyCredentialsForUser(e.userId)).length===0)return yield*new r1({reason:"no_existing_passkey"});let o=yield*t.findPasskeyCredentialById(e.credential.id);if(e1.isSome(o))return yield*new t1({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(ZB.mapError((i)=>CIe(i)?new t1({credentialId:e.credential.id}):i)),yield*_Ie(e.userId)});class fv extends kIe.TaggedError("PasskeyManagementRequestError"){}var s1=jn.Trim.pipe(jn.minLength(1),jn.maxLength(128)),p7=jn.String.pipe(jn.minLength(1)),DIe=jn.Struct({id:p7,name:s1}),OIe=jn.Struct({id:p7}),NIe=jn.Struct({name:s1}),FIe=jn.Struct({challengeId:jn.String.pipe(jn.minLength(1)),response:UB}),UIe=jn.Struct({type:jn.Literal("management"),challenge:jn.String,userId:jn.String,userHandle:jn.String,name:s1}),MIe=300,An=(e,t=200)=>IO(e,{status:t,headers:{"cache-control":"no-store",pragma:"no-cache","x-content-type-options":"nosniff"}}),LIe=(e)=>e.delegation===void 0&&(e.humanSession===!0||e.humanAuthentication?.method==="passkey"&&e.humanAuthentication.providerUserId===e.userId),a_=(e,t,r)=>({organisation:{name:e},account:t,credentials:r.map((n)=>({id:n.id,name:n.name,createdAt:c_.formatIso(n.createdAt),lastUsedAt:n.lastUsedAt===null?null:c_.formatIso(n.lastUsedAt)}))}),u7=(e)=>["passkey","management",e],i1=()=>new fv({status:400,error:"invalid_request"}),BIe=un.gen(function*(){let e=yield*Vo,t=yield*Ln,r=yield*Ii,n=yield*Hs,o=yield*Zr,i=(c)=>c.pipe(un.provideService(Vo,e)),s=(c)=>c.pipe(un.provideService(Zr,o));return un.gen(function*(){let c=yield*on;if(c.method!=="GET"&&c.method!=="PATCH"&&c.method!=="POST"&&c.method!=="DELETE")return An({error:"method_not_allowed"},405);let l=c.headers.authorization?.match(/^Bearer ([^ ]+)$/)?.[1];if(!l)return An({error:"invalid_token"},401);let d=yield*t.allSigningKeys,u=yield*ci(c.headers).pipe(un.mapError(()=>new fv({status:401,error:"invalid_token"}))),p=yield*c_.now,y=yield*un.tryPromise({try:()=>uc(l,async(ft)=>{let yt=d.find((Ut)=>Ut.id===ft.kid&&Ut.alg===ft.alg);if(!yt)throw Error("Unknown signing key");return yt.public},{issuer:u,audience:[...r.staticClients.values()].map((ft)=>ft.audience),requiredClaims:["exp","sub"],currentDate:c_.toDateUtc(p)}),catch:()=>new fv({status:401,error:"invalid_token"})});if(typeof y.payload.exp!=="number"||y.payload.mode!=="access"||y.payload.type!=="providerUser")return An({error:"invalid_token"},401);let g=yield*un.promise(async()=>_p.providerUser["~standard"].validate(y.payload.properties));if(g.issues)return An({error:"invalid_token"},401);let E=g.value;if(!LIe(E))return An({error:"management_denied"},403);if(new URL(c.url,"https://auth.invalid").searchParams.getAll("ownerUserId").length>0)return An({error:"invalid_request"},400);let x=yield*e.findOAuthProviderByName("passkey");if(s_.isNone(x))return An({error:"management_denied"},403);let w=yield*e.findProviderUserByUserId(E.userId);if(s_.isNone(w))return An({error:"invalid_token"},401);let _=yield*e.listPasskeyCredentialsForUser(E.userId);if(_.length===0)return An({error:"management_denied"},403);let T=yield*e.findRootOrgUnit(),b=s_.match(T,{onNone:()=>"Organisation",onSome:(ft)=>ft.name}),I=a_(b,{userId:w.value.id,email:w.value.email},_);if(c.method==="GET")return An(I);if(c.method==="DELETE"){let ft=yield*c.json.pipe(un.flatMap(jn.decodeUnknown(OIe,{onExcessProperty:"error"})),un.mapError(()=>i1())),yt=yield*e.removePasskeyCredential({userId:E.userId,id:ft.id});if(yt==="last_credential")return An({error:"last_credential"},409);if(yt==="not_found")return An({error:"management_denied"},403);let Ut=yield*e.listPasskeyCredentialsForUser(E.userId);return An(a_(b,{userId:w.value.id,email:w.value.email},Ut))}if(c.method==="PATCH"){let ft=yield*c.json.pipe(un.flatMap(jn.decodeUnknown(DIe,{onExcessProperty:"error"})),un.mapError(()=>i1()));if(!(yield*e.renamePasskeyCredential({userId:E.userId,id:ft.id,name:ft.name})))return An({error:"management_denied"},403);let Ut=yield*e.listPasskeyCredentialsForUser(E.userId);return An(a_(b,{userId:w.value.id,email:w.value.email},Ut))}let O=yield*c.json.pipe(un.mapError(()=>i1())),L=jn.decodeUnknownEither(NIe,{onExcessProperty:"error"})(O),Y=jn.decodeUnknownEither(FIe)(O);if(o1.isRight(L)&&o1.isLeft(Y)){let ft=yield*jn.decodeUnknown(iR)(x.value.config).pipe(un.mapError(()=>new fv({status:500,error:"internal_error"}))),yt=_y({...w.value,userId:w.value.id}),Ut=yield*MB({rpName:ft.rpName,rpID:ft.rpID,email:w.value.email,userHandle:yt,excludeCredentials:_.map((nt)=>({id:nt.credentialId,...nt.transports&&{transports:nt.transports}}))}),_t=crypto.randomUUID();return yield*s(wr.set(u7(_t),{type:"management",challenge:Ut.challenge,userId:E.userId,userHandle:yt,name:L.right.name},MIe)),An({challengeId:_t,options:Ut})}if(o1.isLeft(Y))return An({error:"invalid_request"},400);let Z=Y.right,ee=yield*s(wr.take(u7(Z.challengeId))),ae=jn.decodeUnknownOption(UIe)(ee);if(s_.isNone(ae)||ae.value.userId!==E.userId)return An({error:"invalid_request"},400);let ne=yield*jn.decodeUnknown(iR)(x.value.config).pipe(un.mapError(()=>new fv({status:500,error:"internal_error"}))),le=yield*LB({origin:ne.origin,rpID:ne.rpID,expectedChallenge:ae.value.challenge,response:Z.response});if(!le.verified)return An({error:"verification_failed"},400);let ie=yield*n.withTransaction(i(d7({userId:E.userId,userHandle:ae.value.userHandle,name:ae.value.name,credential:le.credential}))).pipe(un.catchTag("processfocus:internal-tag/PasskeyCredentialAlreadyOwnedError",(ft)=>un.succeed("already_registered")),un.catchTag("processfocus:internal-tag/PasskeyManagementDeniedError",(ft)=>un.succeed("management_denied")),un.catchTag("processfocus:internal-tag/PasskeyIdentityNotFoundError",(ft)=>un.succeed("management_denied")));if(ie==="already_registered")return An({error:"already_registered"},409);if(ie==="management_denied")return An({error:"management_denied"},403);let je=yield*e.listPasskeyCredentialsForUser(E.userId);return An(a_(b,{userId:w.value.id,email:w.value.email},je))}).pipe(un.catchTag("PasskeyManagementRequestError",({status:c,error:l})=>un.succeed(An({error:l},c))),un.catchAll(()=>un.logError("Unexpected passkey management failure").pipe(un.as(An({error:"internal_error"},500)))))});import{DateTime as bCt,Duration as wCt,Effect as TCt,Option as ACt}from"effect";import{Effect as t_t}from"effect";import{Data as kw,DateTime as BCt,Effect as $Ct,Either as qCt,Option as jCt,Schema as Gi}from"effect";import{Data as $Ie,Effect as DCt,Schema as xf}from"effect";class qIe extends $Ie.TaggedError("processfocus:internal-tag/GoogleDirectoryError"){}var OCt=xf.Struct({client_email:xf.String,private_key:xf.String}),NCt=xf.Struct({access_token:xf.String}),FCt=xf.Struct({orgUnitPath:xf.optionalWith(xf.String,{exact:!0})});class jIe extends kw.TaggedError("processfocus:internal-tag/RootOrgUnitNotFoundError"){}class HIe extends kw.TaggedError("processfocus:internal-tag/InviteRequiredError"){}class WIe extends kw.TaggedError("processfocus:internal-tag/DummyProviderUserNotFoundError"){}class m7 extends kw.TaggedError("processfocus:internal-tag/VerifiedEmailRequiredError"){}class VIe extends kw.TaggedError("processfocus:internal-tag/ProviderUserEmailAlreadyOwnedError"){}var GCt=Gi.Struct({sub:Gi.String,email:Gi.String,name:Gi.String,given_name:Gi.optionalWith(Gi.String,{exact:!0}),family_name:Gi.optionalWith(Gi.String,{exact:!0}),picture:Gi.optionalWith(Gi.String,{exact:!0}),locale:Gi.optionalWith(Gi.String,{exact:!0}),email_verified:Gi.optionalWith(Gi.Boolean,{exact:!0})}),QCt=Gi.Struct({sub:Gi.String});import{Clock as c_t,Effect as l_t}from"effect";var zIe=315360000;class a1 extends Fy.TaggedError("ClientJwtMintError"){}class l_ extends Fy.TaggedError("FrontendJwtCreateError"){}var KIe=(e,t,r,n)=>Ny.gen(function*(){let i=yield*(yield*Ln).signingKey;return yield*Ny.tryPromise({try:()=>new Mg({mode:"access",type:"user",properties:{userId:`frontend:${e}`,clientId:e,roles:[]}}).setProtectedHeader({alg:i.alg,kid:i.id}).setIssuer(t).setAudience(r).setSubject(`frontend:${e}`).setIssuedAt(n).setExpirationTime(n+zIe).sign(i.private),catch:(a)=>new l_({message:"Failed to create frontend JWT",cause:a})})}).pipe(Ny.mapError((o)=>o instanceof l_?o:new l_({message:"Failed to create frontend JWT",cause:o})));class GIe extends Fy.TaggedError("ProviderUserAuthenticationError"){}class QIe extends Fy.TaggedError("UnsupportedProviderError"){}class JIe extends Fy.TaggedError("ProviderConfigurationError"){}class YIe extends Fy.TaggedError("InvalidProviderConfigError"){}class XIe extends Fy.TaggedError("InvalidRoleScopeError"){}var Ekt=Bt.Struct({clientID:Bt.String,clientSecret:Bt.String,scopes:Bt.mutable(Bt.Array(Bt.String)),pkce:Bt.optional(Bt.Boolean),query:Bt.optional(Bt.Record({key:Bt.String,value:Bt.String})),responseMode:Bt.optional(Bt.Literal("query","form_post")),tenant:Bt.optional(Bt.String),team:Bt.optional(Bt.String),baseUrl:Bt.optional(Bt.String),realm:Bt.optional(Bt.String),domain:Bt.optional(Bt.String),region:Bt.optional(Bt.String),userPoolId:Bt.optional(Bt.String)}).pipe(Bt.extend(Bt.Record({key:Bt.String,value:Bt.Unknown})));var bkt=Bt.Struct({rpName:Bt.String,rpID:Bt.String,origin:Bt.Union(Bt.String,Bt.mutable(Bt.Array(Bt.String)))});var d_=(e)=>Ny.gen(function*(){if(e.clientId.trim().length===0)return yield*new a1({message:"clientId must not be empty"});let t=pE(e.issuerUrl);return yield*Ny.try({try:()=>new URL(t),catch:()=>new a1({message:`Invalid issuer URL: ${e.issuerUrl}`})}),yield*KIe(e.clientId,t,e.audience,e.issuedAtUnixSeconds??Math.floor(Date.now()/1000)).pipe(Ny.provide(ME))}),u_=(e,t)=>wr.set(["frontend-jwt",e],{token:t}),p_=(e)=>wr.get(["frontend-jwt",e]).pipe(Ny.map((t)=>t?.token));Ki();Ki();import{Layer as W$}from"effect";var R=Symbol.for("drizzle:entityKind");function H(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,R))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(R in r&&r[R]===t[R])return!0;r=Object.getPrototypeOf(r)}return!1}var Oo=class{static[R]="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 pn=class{static[R]="Subquery";constructor(e,t,r,n=!1,o=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:n,usedTables:o}}},f_=class extends pn{static[R]="WithSubquery"};var Dw=Symbol.for("drizzle:OriginalColumn");var c1=(e)=>e;c1.isNoop=!0;var Pt=class{static[R]="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=c1;mapToDriverValue=c1;postBuild(){return this}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}[Dw](){return this}};var ta=Symbol.for("drizzle:Name");var Uu=Symbol.for("drizzle:Schema"),ra=Symbol.for("drizzle:Columns"),y7=Symbol.for("drizzle:ExtraConfigColumns"),Uy=Symbol.for("drizzle:OriginalName"),l1=Symbol.for("drizzle:BaseName"),Ef=Symbol.for("drizzle:IsAlias"),h7=Symbol.for("drizzle:ExtraConfigBuilder"),ZIe=Symbol.for("drizzle:IsDrizzleTable"),xe=class{static[R]="Table";static Symbol={Name:ta,Schema:Uu,OriginalName:Uy,Columns:ra,ExtraConfigColumns:y7,BaseName:l1,IsAlias:Ef,ExtraConfigBuilder:h7};[ta];[Uy];[Uu];[ra];[y7];[l1];[Ef]=!1;[ZIe]=!0;[h7]=void 0;constructor(e,t,r){this[ta]=this[Uy]=e,this[Uu]=t,this[l1]=r}};function Mu(e){return e[ta]}function My(e){return`${e[Uu]??"public"}.${e[ta]}`}function g7(e,...t){return e(...t)}var S7={startActiveSpan(e,t){return t()}};var dr=Symbol.for("drizzle:ViewBaseConfig");function Lu(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function eRe(e){let t={sql:"",params:[]};for(let r of e)t.sql+=r.sql,t.params.push(...r.params);return t}function tRe(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 No=class{static[R]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new Ae([this])}},Ae=class e{static[R]="SQL";decoder=bf;shouldInlineParams=!1;usedTables=[];constructor(t){this.queryChunks=t;for(let r of t)if(H(r,xe)){let n=r[xe.Symbol.Schema];this.usedTables.push(n===void 0?r[xe.Symbol.Name]:n+"."+r[xe.Symbol.Name])}}append(t){return this.queryChunks.push(...t.queryChunks),this}toQuery(t){return S7.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(H(u,No))return{sql:u.value.join(""),params:[]};if(H(u,Ow))return{sql:o(u.value),params:[]};if(u===void 0)return{sql:"",params:[]};if(Array.isArray(u)){let p=[new No("(")];for(let[y,g]of u.entries())if(p.push(g),y<u.length-1)p.push(new No(", "));return p.push(new No(")")),this.buildQueryFromSourceParams(p,n)}if(H(u,e))return this.buildQueryFromSourceParams(u.queryChunks,{...n,inlineParams:a||u.shouldInlineParams});if(H(u,xe)){let p=u[xe.Symbol.Schema],y=u[xe.Symbol.Name];if(l==="mssql-view-with-schemabinding")return{sql:(p===void 0?o("dbo"):o(p))+"."+o(y),params:[]};return{sql:p===void 0||u[Ef]?o(y):o(p)+"."+o(y),params:[]}}if(H(u,Pt)){let p=u.name;if(r.invokeSource==="indexes")return{sql:o(p),params:[]};let y=l==="mssql-check"?void 0:u.table[xe.Symbol.Schema];return{sql:u.isAlias?o(u.name):u.table[Ef]||y===void 0?o(u.table[xe.Symbol.Name])+"."+o(p):o(y)+"."+o(u.table[xe.Symbol.Name])+"."+o(p),params:[]}}if(H(u,Jn)){let p=u[dr].schema,y=u[dr].name;return{sql:p===void 0||u[dr].isAlias?o(y):o(p)+"."+o(y),params:[]}}if(H(u,ki)){if(H(u.value,e))return this.buildQueryFromSourceParams([u.value],n);let p=s&&H(u.encoder,Pt);if(H(u.value,gl)){let E=i(c.value++,u);return u.codec=p?(S)=>s.apply(u.encoder,"normalizeParam",S):void 0,{sql:p?s.apply(u.encoder,"castParam",E):E,params:[u]}}let y;if(u.value===null)y=u.value;else{if(y=u.encoder.mapToDriverValue.isNoop?u.value:u.encoder.mapToDriverValue(u.value),H(y,e))return this.buildQueryFromSourceParams([y],n);if(p)y=s.apply(u.encoder,"normalizeParam",y)}if(a)return{sql:this.mapInlineParam(y,n),params:[]};let g=i(c.value++,y);return{sql:p?s.apply(u.encoder,"castParam",g):g,params:[y]}}if(H(u,gl))return{sql:i(c.value++,u),params:[u]};if(H(u,e.Aliased)&&u.fieldAlias!==void 0)return{sql:(u.origin!==void 0?o(u.origin)+".":"")+o(u.fieldAlias),params:[]};if(H(u,pn)){if(u._.isWith)return{sql:o(u._.alias),params:[]};return this.buildQueryFromSourceParams([new No("("),u._.sql,new No(") "),new Ow(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(Lu(u)){if(u.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([u.getSQL()],n);return this.buildQueryFromSourceParams([new No("("),u.getSQL(),new No(")")],n)}if(a)return{sql:this.mapInlineParam(u,n),params:[]};return{sql:i(c.value++,u),params:[u]}});if(r.tagged)return tRe(d);return eRe(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}},Ow=class{static[R]="Name";brand;constructor(e){this.value=e}getSQL(){return new Ae([this])}};function m_(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}var bf={mapFromDriverValue:(e)=>e};bf.mapFromDriverValue.isNoop=!0;var Nw={mapToDriverValue:(e)=>e};Nw.mapToDriverValue.isNoop=!0;var v7={...bf,...Nw},ki=class{static[R]="Param";brand;constructor(e,t=Nw,r){this.value=e,this.encoder=t,this.codec=r}getSQL(){return new Ae([this])}};function m(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new No(e[0]));for(let[n,o]of t.entries())r.push(o,new No(e[n+1]));return new Ae(r)}(function(e){function t(){return new Ae([])}e.empty=t;function r(l){return new Ae(l)}e.fromList=r;function n(l){return new Ae([new No(l)])}e.raw=n;function o(l,d){let u=[];for(let[p,y]of l.entries()){if(p>0&&d!==void 0)u.push(d);u.push(y)}return new Ae(u)}e.join=o;function i(l){return new Ow(l)}e.identifier=i;function s(l){return new gl(l)}e.placeholder=s;function a(l,d){return new ki(l,d)}e.param=a;function c(l){let d=yv(l);if(!d.length)return;return m.raw(d)}e.comment=c})(m||(m={}));function yv(e){let t=yv.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})(yv||(yv={}));(function(e){class t{static[R]="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})(Ae||(Ae={}));var gl=class{static[R]="Placeholder";constructor(e){this.name=e}getSQL(){return new Ae([this])}};function Bu(e,t){return e.map((r)=>{if(H(r,gl)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(H(r,ki)&&H(r.value,gl)){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 rRe=Symbol.for("drizzle:IsDrizzleView"),Jn=class{static[R]="View";[dr];[rRe]=!0;get[ta](){return this[dr].name}get[Uu](){return this[dr].schema}get[Ef](){return this[dr].isAlias}get[Uy](){return this[dr].originalName}get[ra](){return this[dr].selectedFields}constructor({name:e,schema:t,selectedFields:r,query:n}){this[dr]={name:e,originalName:e,schema:t,selectedFields:r,query:n,isExisting:!n,isAlias:!1}}};Pt.prototype.getSQL=function(){return new Ae([this])};pn.prototype.getSQL=function(){return new Ae([this])};var Ly=class{static[R]="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]}},d1=class{static[R]="ViewSelectionAliasProxyHandler";constructor(e,t,r){this.view=e,this.selection=t,this.ignoreColumnAlias=r}get(e,t){let r=e[t];if(H(r,Pt))return new Proxy(r,new Ly(this.view,this.ignoreColumnAlias));if(H(r,pn)||H(r,Ae)||H(r,Ae.Aliased)||Lu(r)||typeof r!=="object"||r===null)return r;return new Proxy(r,this)}},By=class{static[R]="TableAliasProxyHandler";constructor(e,t,r){this.alias=e,this.replaceOriginalName=t,this.ignoreColumnAlias=r}get(e,t){if(t===xe.Symbol.IsAlias)return!0;if(t===xe.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===xe.Symbol.OriginalName)return this.alias;if(t===dr)return{...e[dr],name:this.alias,isAlias:!0,selectedFields:new Proxy(e[dr].selectedFields,new d1(new Proxy(e,this),e[dr].selectedFields,this.ignoreColumnAlias))};if(t===xe.Symbol.Columns){let n=e[xe.Symbol.Columns];if(!n)return n;if(H(e,Jn))return new Proxy(e[xe.Symbol.Columns],new d1(new Proxy(e,this),e[xe.Symbol.Columns],this.ignoreColumnAlias));let o={};return Object.keys(n).map((i)=>{o[i]=new Proxy(n[i],new Ly(new Proxy(e,this),this.ignoreColumnAlias))}),o}let r=e[t];if(H(r,Pt))return new Proxy(r,new Ly(new Proxy(e,this),this.ignoreColumnAlias));return r}},x7=class{static[R]="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===Dw)return()=>e;return e[t]}};function Di(e,t){return new Proxy(e,new By(t,!1,!1))}function E7(e,t){return new Proxy(e,new x7(t))}function Sl(e,t){return new Proxy(e,new Ly(new Proxy(e.table,new By(t,!1,!1)),!1))}function y_(e,t){return new Ae.Aliased(hv(e.sql,t),e.fieldAlias)}function hv(e,t){return m.join(e.queryChunks.map((r)=>{if(H(r,Pt))return Sl(r,t);if(H(r,Ae))return hv(r,t);if(H(r,Ae.Aliased))return y_(r,t);return r}))}Pt.prototype.as=function(e){return E7(this,e)};function gv(e){return e[Dw]()}function vd(e,t){return new Proxy(e,new By(t,!1))}var b7=class{static[R]="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 w7=class{static[R]="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 nRe(e,this)}},nRe=class{static[R]="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[ta],...n,r[0].table[ta],...o];return e??`${i.join("_")}_fk`}isNameExplicit(){return!!this.reference().name}};var di=class extends b7{static[R]="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 w7(()=>{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))}},Yn=class extends Pt{static[R]="SQLiteColumn";table;constructor(e,t){super(e,t);this.table=e}};function u1(e,t,r){let n={},o=e.reduce((i,{path:s,field:a,codec:c,arrayDimensions:l},d)=>{let u;if(H(a,Pt))u=a;else if(H(a,Ae))u=a.decoder;else if(H(a,pn))u=a._.sql.decoder;else u=a.sql.decoder;let p=i;for(let[y,g]of s.entries())if(y<s.length-1){if(!(g in p))p[g]={};p=p[g]}else{let E=t[d],S=p[g]=E===null?null:u.mapFromDriverValue(c?c(E,l):E);if(r&&H(a,Pt)&&s.length===2){let x=s[0];if(!(x in n))n[x]=S===null?Mu(a.table):!1;else if(typeof n[x]==="string"&&n[x]!==Mu(a.table))n[x]=!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 g_=Object.getPrototypeOf(()=>null).constructor;function oRe(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:p}=e[c],y,g,E,S=!1;if(H(l,Pt))S=!0,y=l,E=`field: decoder${c}`;else if(H(l,Ae))y=l.decoder,E=`field: { decoder: decoder${c} }`;else if(H(l,pn))y=l._.sql.decoder,E=`field: { _: { sql: { decoder: decoder${c} } } }`;else y=l.sql.decoder,E=`field: { sql: { decoder: decoder${c} } }`;if(g=`decoder${c}.mapFromDriverValue`,y.mapFromDriverValue.isNoop)g="";if(g)r.push(`const { ${E}${u?`, codec: codec${c}`:""} } = columns[${c}];`);else if(u)r.push(`const { codec: codec${c} } = columns[${c}];`);let x=`c${c}`,w=x;if(u)w=`codec${c}(${w}, ${p})`;if(g)w=`${g}(${w})`;if(s[c]=x===w?`${x}`:`${x} === null ? ${x} : ${w}`,d.length!==2||!S)continue;if(i[d[0]]===void 0)i[d[0]]=[`c${c}`];else i[d[0]]?.push(`c${c}`);let[_]=d,T=Mu(l.table);o[_]=t[T]?!1:typeof o[_]==="string"?o[_]===T?T:!1:T}n.push("mapped[i] = {");let a=[];for(let c=0;c<e.length;++c){let{path:l}=e[c],d=l.map((g)=>JSON.stringify(g)),u=s[c],p=l.slice(0,-1),y=0;while(y<a.length&&y<p.length&&a[y]===p[y])y++;for(let g=a.length-1;g>=y;--g)n.push(`${"\t".repeat(g+1)}},`);for(let g=y;g<p.length;++g)n.push(`${"\t".repeat(g+1)}${d[g]}: ${g===0&&p.length===1&&typeof o[l[0]]==="string"?`${i[l[0]]?.map((E)=>`${E} === null`).join(" && ")} ? null : {`:"{"}`);a=p,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(`
|
|
742
|
+
`)}
|
|
743
|
+
`:""}for (let i = 0; i < length; ++i) {
|
|
744
|
+
${n.join(`
|
|
745
|
+
`)}
|
|
746
|
+
}`}function p1(e,t){let r=` "use strict";
|
|
747
|
+
const { columns } = this;
|
|
748
|
+
const { length } = rows;
|
|
749
|
+
const mapped = Array.from({ length });
|
|
750
|
+
${oRe(e,t)}
|
|
751
|
+
return mapped;
|
|
752
|
+
//# sourceURL=drizzle:jit-query-mapper`;return Object.assign(new g_("rows",r).bind({columns:e}),{body:`function jitQueryMapper (rows) {
|
|
753
|
+
${r}
|
|
754
|
+
}`})}function T7(e){if(!e)return!1;try{let t=new g_("input",'"use strict"; return input;')(!0);if(t!==!0)console.warn(`Unable to use jit mappers due to incompatibility: corrupted jit function output.
|
|
755
|
+
Falling back to premade mappers.
|
|
756
|
+
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.
|
|
757
|
+
Falling back to premade mappers.
|
|
758
|
+
Error details:`),console.error(t),!1}}function Rc(e,t,r){return Object.entries(e).reduce((n,[o,i])=>{if(typeof o!=="string")return n;let s=t?[...t,o]:[o];if(H(i,Pt))n.push({path:s,field:i,codec:r?.get(i,"normalize"),arrayDimensions:i.dimensions});else if(H(i,Ae)||H(i,Ae.Aliased)){let a=h_(i);n.push(a?{path:s,field:i,codec:r?.get(a,"normalize"),arrayDimensions:a.dimensions}:{path:s,field:i})}else if(H(i,pn)){let a=h_(i._.sql);n.push(a?{path:s,field:i,codec:r?.get(a,"normalize"),arrayDimensions:a.dimensions}:{path:s,field:i})}else if(H(i,xe))n.push(...Rc(i[xe.Symbol.Columns],s,r));else n.push(...Rc(i,s,r));return n},[])}function h_(e){let t=e.getSQL();if(H(t.decoder,Pt))return t.decoder}function Fw(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 S_(e,t){let r=Object.entries(t).filter(([,n])=>n!==void 0).map(([n,o])=>{if(H(o,Ae)||H(o,Pt))return[n,o];else return[n,new ki(o,e[xe.Symbol.Columns][n])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function v_(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 x_(e){return e[xe.Symbol.Columns]}function Uw(e){return H(e,pn)?e._.alias:H(e,Jn)?e[dr].name:H(e,Ae)?void 0:e[xe.Symbol.IsAlias]?e[xe.Symbol.Name]:e[xe.Symbol.BaseName]}function Tt(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}var f1=typeof TextDecoder>"u"?null:new TextDecoder;var t0t={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 A7=class extends di{static[R]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new I7(e,this.config)}},I7=class extends Yn{static[R]="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 $y(e){return(t,r)=>{let{name:n,config:o}=Tt(t,r);return new A7(n,o,e)}}var E_=class extends di{static[R]="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()}},b_=class extends Yn{static[R]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}},R7=class extends E_{static[R]="SQLiteIntegerBuilder";constructor(e){super(e,"number int53","SQLiteInteger")}build(e){return new P7(e,this.config)}},P7=class extends b_{static[R]="SQLiteInteger"},C7=class extends E_{static[R]="SQLiteTimestampBuilder";constructor(e,t){super(e,"object date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(m`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new _7(e,this.config)}},_7=class extends b_{static[R]="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}},k7=class extends E_{static[R]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new D7(e,this.config)}},D7=class extends b_{static[R]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue=(e)=>Number(e)===1;mapToDriverValue=(e)=>e?1:0};function Re(e,t){let{name:r,config:n}=Tt(e,t);if(n?.mode==="timestamp"||n?.mode==="timestamp_ms")return new C7(r,n.mode);if(n?.mode==="boolean")return new k7(r,n.mode);return new R7(r)}var O7=class extends di{static[R]="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 N7(e,this.config)}},N7=class extends Yn{static[R]="SQLiteText";enumValues=this.config.enumValues;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}},F7=class extends di{static[R]="SQLiteTextJsonBuilder";constructor(e){super(e,"object json","SQLiteTextJson")}build(e){return new U7(e,this.config)}},U7=class extends Yn{static[R]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue=(e)=>JSON.parse(e);mapToDriverValue=(e)=>JSON.stringify(e)};function P(e,t={}){let{name:r,config:n}=Tt(e,t);if(n.mode==="json")return new F7(r);return new O7(r,n)}function M7(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 iRe=class extends di{static[R]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint int64","SQLiteBigInt")}build(e){return new sRe(e,this.config)}},sRe=class extends Yn{static[R]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue=(e)=>{if(typeof e==="string")return BigInt(M7(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(f1.decode(e))};mapToDriverValue=(e)=>Buffer.from(e.toString())},aRe=class extends di{static[R]="SQLiteBlobJsonBuilder";constructor(e){super(e,"object json","SQLiteBlobJson")}build(e){return new cRe(e,this.config)}},cRe=class extends Yn{static[R]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue=(e)=>{if(typeof e==="string")return JSON.parse(M7(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(f1.decode(e))};mapToDriverValue=(e)=>Buffer.from(JSON.stringify(e))},lRe=class extends di{static[R]="SQLiteBlobBufferBuilder";constructor(e){super(e,"object buffer","SQLiteBlobBuffer")}build(e){return new dRe(e,this.config)}},dRe=class extends Yn{static[R]="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 L7(e,t){let{name:r,config:n}=Tt(e,t);if(n?.mode==="json")return new aRe(r);if(n?.mode==="bigint")return new iRe(r);return new lRe(r)}var uRe=class extends di{static[R]="SQLiteNumericBuilder";constructor(e){super(e,"string numeric","SQLiteNumeric")}build(e){return new pRe(e,this.config)}},pRe=class extends Yn{static[R]="SQLiteNumeric";mapFromDriverValue=(e)=>{if(typeof e==="string")return e;return String(e)};getSQLType(){return"numeric"}},fRe=class extends di{static[R]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new mRe(e,this.config)}},mRe=class extends Yn{static[R]="SQLiteNumericNumber";mapFromDriverValue=(e)=>{if(typeof e==="number")return e;return Number(e)};mapToDriverValue=String;getSQLType(){return"numeric"}},yRe=class extends di{static[R]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint int64","SQLiteNumericBigInt")}build(e){return new hRe(e,this.config)}},hRe=class extends Yn{static[R]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}};function B7(e,t){let{name:r,config:n}=Tt(e,t),o=n?.mode;return o==="number"?new fRe(r):o==="bigint"?new yRe(r):new uRe(r)}var gRe=class extends di{static[R]="SQLiteRealBuilder";constructor(e){super(e,"number double","SQLiteReal")}build(e){return new SRe(e,this.config)}},SRe=class extends Yn{static[R]="SQLiteReal";getSQLType(){return"real"}};function $7(e){return new gRe(e??"")}function q7(){return{blob:L7,customType:$y,integer:Re,numeric:B7,real:$7,text:P}}function vRe(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((t)=>t.toLowerCase()).join("_")}function xRe(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 w_(e){if(e==="snake_case")return vRe;if(e==="camelCase")return xRe;return(t)=>t}var T_=Symbol.for("drizzle:SQLiteInlineForeignKeys"),ui=class extends xe{static[R]="SQLiteTable";static Symbol=Object.assign({},xe.Symbol,{InlineForeignKeys:T_});[xe.Symbol.Columns];[T_]=[];[xe.Symbol.ExtraConfigBuilder]=void 0};function A_(e,t,r,n,o,i=e){let s=w_(o),a=new ui(e,n,i),c=typeof t==="function"?t(q7()):t,l=Object.fromEntries(Object.entries(c).map(([u,p])=>{let y=p;y.setName(u,s);let g=y.build(a).postBuild();return a[T_].push(...y.buildForeignKeys(g,a)),[u,g]})),d=Object.assign(a,l);if(d[xe.Symbol.Columns]=l,d[xe.Symbol.ExtraConfigColumns]=l,r)d[ui.Symbol.ExtraConfigBuilder]=r;return d}function j7(e){return(t,r,n)=>A_(t,r,n,void 0,e)}var Dt=j7(void 0);var H7=class{static[R]="SQLiteCheckBuilder";brand;constructor(e,t){this.name=e,this.value=t}build(e){return new W7(e,this)}},W7=class{static[R]="SQLiteCheck";name;value;constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}};function Qi(e,t){return new H7(e,t)}var m1=class{static[R]="SQLiteIndexBuilderOn";constructor(e,t){this.name=e,this.unique=t}on(...e){return new V7(this.name,e,this.unique)}},V7=class{static[R]="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 z7(this.config,e)}},z7=class{static[R]="SQLiteIndex";config;isNameExplicit;constructor(e,t){this.config={...e,table:t},this.isNameExplicit=!!e.name}};function gt(e){return new m1(e,!1)}function Xt(e){return new m1(e,!0)}function vl(e){if(H(e,ui))return[`${e[xe.Symbol.BaseName]}`];if(H(e,pn))return e._.usedTables??[];if(H(e,Ae))return e.usedTables??[];return[]}var wf=class extends Jn{static[R]="SQLiteViewBase"};var Xn=class e{static[R]="SelectionProxyHandler";config;constructor(t){this.config={...t}}get(t,r){if(r==="_")return{...t._,selectedFields:new Proxy(t._.selectedFields,this)};if(r===dr)return{...t[dr],selectedFields:new Proxy(t[dr].selectedFields,this)};if(typeof r==="symbol")return t[r];let n=(H(t,pn)?t._.selectedFields:H(t,Jn)?t[dr].selectedFields:t)[r];if(H(n,Ae.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(H(n,Ae)){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(H(n,Pt)){if(this.config.alias)return new Proxy(n,new Ly(new Proxy(n.table,new By(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 K7=class{static[R]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}withoutSelectionCastCodecs(){return this}};var Pc=class{static[R]="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(H(e,pn))r=Object.fromEntries(Object.keys(e._.selectedFields).map((n)=>[n,e[n]]));else if(H(e,wf))r=e[dr].selectedFields;else if(H(e,Ae))r={};else r=x_(e);return new Sv({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}},y1=class extends K7{static[R]="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=Uw(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of vl(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let n=this.tableName,o=Uw(t);for(let i of vl(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"&&!H(t,Ae)){let i=H(t,pn)?t._.selectedFields:H(t,Jn)?t[dr].selectedFields:t[xe.Symbol.Columns];this.config.fields[o]=i}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new Xn({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(ERe()):r;if(!Fw(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 Xn({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new Xn({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 Xn({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 Xn({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(...vl(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...vl(r.table));return new Proxy(new pn(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new Xn({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new Xn({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}withoutSelectionCastCodecs(){return this}$dynamic(){return this}},Sv=class extends y1{static[R]="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=Rc(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()}};v_(Sv,[Oo]);function I_(e,t){return(r,n,...o)=>{let i=[n,...o].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of i)if(!Fw(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 ERe=()=>({union:h1,unionAll:g1,intersect:S1,except:v1}),h1=I_("union",!1),g1=I_("union",!0),S1=I_("intersect",!1),v1=I_("except",!1);function Zn(e,t){if(m_(t)&&!Lu(e)&&!H(e,ki)&&!H(e,gl)&&!H(e,Pt)&&!H(e,xe)&&!H(e,Jn))return new ki(e,t);return e}var f=(e,t)=>m`${e} = ${Zn(t,e)}`,Tf=(e,t)=>m`${e} <> ${Zn(t,e)}`;function k(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Ae(t);return new Ae([new No("("),m.join(t.map((r)=>m`(${r})`),new No(" and ")),new No(")")])}function Zt(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Ae(t);return new Ae([new No("("),m.join(t.map((r)=>m`(${r})`),new No(" or ")),new No(")")])}function na(e){return H(e,Ae)?m`not (${e})`:m`not ${e}`}var Vr=(e,t)=>m`${e} > ${Zn(t,e)}`,Af=(e,t)=>m`${e} >= ${Zn(t,e)}`,xd=(e,t)=>m`${e} < ${Zn(t,e)}`,Fo=(e,t)=>m`${e} <= ${Zn(t,e)}`;function Ye(e,t){if(Array.isArray(t)){if(t.length===0)return m`false`;return m`${e} in ${t.map((r)=>Zn(r,e))}`}return m`${e} in ${Zn(t,e)}`}function Uo(e,t){if(Array.isArray(t)){if(t.length===0)return m`true`;return m`${e} not in ${t.map((r)=>Zn(r,e))}`}return m`${e} not in ${Zn(t,e)}`}function Pe(e){return m`(${e} is null)`}function mr(e){return m`(${e} is not null)`}function qy(e){return m`exists ${e}`}function jy(e){return m`not exists ${e}`}function vv(e,t,r){return m`${e} between ${Zn(t,e)} and ${Zn(r,e)}`}function xv(e,t,r){return m`${e} not between ${Zn(t,e)} and ${Zn(r,e)}`}function If(e,t){return m`${e} like ${t}`}function Ev(e,t){return m`${e} not like ${t}`}function bv(e,t){return m`${e} ilike ${t}`}function wv(e,t){return m`${e} not ilike ${t}`}function R_(e,t){if(Array.isArray(t)){if(t.length===0)throw Error("arrayContains requires at least one value");let r=Zn(t,e);return m`${e} @> ${m`${Array.isArray(r)?new ki(r):r}`}`}return m`${e} @> ${Zn(t,e)}`}function P_(e,t){if(Array.isArray(t)){if(t.length===0)throw Error("arrayContained requires at least one value");let r=Zn(t,e);return m`${e} <@ ${m`${Array.isArray(r)?new ki(r):r}`}`}return m`${e} <@ ${Zn(t,e)}`}function C_(e,t){if(Array.isArray(t)){if(t.length===0)throw Error("arrayOverlaps requires at least one value");let r=Zn(t,e);return m`${e} && ${m`${Array.isArray(r)?new ki(r):r}`}`}return m`${e} && ${Zn(t,e)}`}function oa(e){return m`${e} asc`}function eo(e){return m`${e} desc`}var G7=class{static[R]="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 bRe(e,this)}},bRe=class{static[R]="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[ta],...n,r[0].table[ta],...o];return e??`${i.join("_")}_fk`}isNameExplicit(){return!!this.reference().name}};var Ke=class{static[R]="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})=>g7((o,i)=>{let s=new G7(()=>{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 wRe(e,{...this.config,dimensions:this.config.dimensions??0})}},Ce=class extends Pt{static[R]="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)}},wRe=class extends Ce{static[R]="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 Rf=class extends Ke{static[R]="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 TRe=class extends Rf{static[R]="PgBigInt53Builder";constructor(e){super(e,"number int53","PgBigInt53")}build(e){return new ARe(e,this.config)}},ARe=class extends Ce{static[R]="PgBigInt53";codec="bigint:number";getSQLType(){return"bigint"}},IRe=class extends Rf{static[R]="PgBigInt64Builder";constructor(e){super(e,"bigint int64","PgBigInt64")}build(e){return new RRe(e,this.config)}},RRe=class extends Ce{static[R]="PgBigInt64";codec="bigint";getSQLType(){return"bigint"}},PRe=class extends Rf{static[R]="PgBigIntStringBuilder";constructor(e){super(e,"string int64","PgBigIntString")}build(e){return new CRe(e,this.config)}},CRe=class extends Ce{static[R]="PgBigIntString";codec="bigint:string";getSQLType(){return"bigint"}};function Q7(e,t){let{name:r,config:n}=Tt(e,t);if(n.mode==="number")return new TRe(r);if(n.mode==="string")return new PRe(r);return new IRe(r)}var _Re=class extends Ke{static[R]="PgBigSerial53Builder";constructor(e){super(e,"number int53","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new kRe(e,this.config)}},kRe=class extends Ce{static[R]="PgBigSerial53";codec="bigserial:number";getSQLType(){return"bigserial"}},DRe=class extends Ke{static[R]="PgBigSerial64Builder";constructor(e){super(e,"bigint int64","PgBigSerial64");this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new ORe(e,this.config)}},ORe=class extends Ce{static[R]="PgBigSerial64";codec="bigserial";getSQLType(){return"bigserial"}};function J7(e,t){let{name:r,config:n}=Tt(e,t);if(n.mode==="number")return new _Re(r);return new DRe(r)}var NRe=class extends Ke{static[R]="PgBooleanBuilder";constructor(e){super(e,"boolean","PgBoolean")}build(e){return new FRe(e,this.config)}},FRe=class extends Ce{static[R]="PgBoolean";codec="bool";getSQLType(){return"boolean"}};function Y7(e){return new NRe(e??"")}var URe=class extends Ke{static[R]="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 MRe(e,this.config)}},MRe=class extends Ce{static[R]="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 X7(e,t={}){let{name:r,config:n}=Tt(e,t);return new URe(r,n)}var LRe=class extends Ke{static[R]="PgCidrBuilder";constructor(e){super(e,"string cidr","PgCidr")}build(e){return new BRe(e,this.config)}},BRe=class extends Ce{static[R]="PgCidr";codec="cidr";getSQLType(){return"cidr"}};function Z7(e){return new LRe(e??"")}function eZ(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 tZ(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]=eZ(e,n+1,!0);r.push(c),n=l;continue}if(i==="}")return[r,n+1];if(i==="{"){let[c,l]=tZ(e,n+1);r.push(c),n=l;continue}let[s,a]=eZ(e,n,!1);r.push(s),n=a}return[r,n]}function __(e){let[t]=tZ(e,1);return t}function k_(e){return`{${e.map((t)=>{if(Array.isArray(t))return k_(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}function $Re(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 rZ(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 x1(e){let t=$Re(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=rZ(t,r);r+=8;let c=rZ(t,r);return r+=8,{srid:s,point:[a,c]}}throw Error("Unsupported geometry type")}var qRe={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 sZ(e){return qRe[e]??e}var pi=(e)=>m`${e}::text`,Hn=(e,t)=>m`${e}::text${m.raw("[]".repeat(t))}`,jRe=(e)=>(t,r)=>{if(!r)return e(t);let n=[];for(let s=0;s<r;s++)n.push(m.identifier(`s${s}`));let o=t;for(let s of n)o=m`${o}[${s}]`;let i=m`array(\
|
|
759
|
+
select ${e(o)} \
|
|
760
|
+
from generate_subscripts(${t}, ${m.raw(r.toString())}) ${n[r-1]} \
|
|
761
|
+
order by ${n[r-1]})`;for(let s=r-1;s>0;s--)i=m`array(\
|
|
762
|
+
select ${i} \
|
|
763
|
+
from generate_subscripts(${t}, ${m.raw(s.toString())}) ${n[s-1]} \
|
|
764
|
+
order by ${n[s-1]})`;return m`case when ${t} is null then null else ${i} end`},Dr=(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},nZ=(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)=>k_(r(n,o)):r},oZ=(e)=>{let t=Dr(e);return(r,n)=>t(__(r),n)},D_=(e)=>{let[t,r,n]=e.slice(1,-1).split(",");return[Number.parseFloat(t),Number.parseFloat(r),Number.parseFloat(n)]},O_=(e)=>{let[t,r,n]=e.slice(1,-1).split(",");return{a:Number.parseFloat(t),b:Number.parseFloat(r),c:Number.parseFloat(n)}},N_=(e)=>{let[t,r]=e.slice(1,-1).split(",");return[Number.parseFloat(t),Number.parseFloat(r)]},F_=(e)=>{let[t,r]=e.slice(1,-1).split(",");return{x:Number.parseFloat(t),y:Number.parseFloat(r)}},U_=(e)=>x1(e).point,M_=(e)=>{let t=x1(e);return{x:t.point[0],y:t.point[1]}},L_=(e)=>new Date(e),iZ=(e)=>new Date(e+"+0000"),Pf=(e)=>{let t=e.slice(1,-1);if(t.length===0)return[];return t.split(",").map(Number.parseFloat)},yFt={bytea:{castInJson:(e)=>m`encode(${e}, 'base64')`,castArrayInJson:jRe((e)=>m`encode(${e}, 'base64')`),normalizeInJson:(e)=>Buffer.from(e,"base64"),normalizeArrayInJson:Dr((e)=>Buffer.from(e,"base64"))},bigint:{castInJson:pi,castArrayInJson:Hn,normalizeInJson:BigInt,normalizeArrayInJson:Dr(BigInt)},"bigint:number":{castInJson:pi,castArrayInJson:Hn,normalize:Number,normalizeArray:Dr(Number),normalizeInJson:Number,normalizeArrayInJson:Dr(Number)},"bigint:string":{castInJson:pi,castArrayInJson:Hn},bigserial:{castInJson:pi,castArrayInJson:Hn,normalizeInJson:BigInt,normalizeArrayInJson:Dr(BigInt),normalize:BigInt,normalizeArray:Dr(BigInt)},"bigserial:number":{castInJson:pi,castArrayInJson:Hn,normalize:Number,normalizeArray:Dr(Number),normalizeInJson:Number,normalizeArrayInJson:Dr(Number)},date:{normalizeInJson:L_,normalizeArrayInJson:Dr(L_)},"date:string":{},enum:{castArray:Hn,normalizeParamArray:k_},"geometry(point)":{castInJson:pi,castArrayInJson:Hn,normalize:M_,normalizeArray:Dr(M_),normalizeInJson:M_,normalizeArrayInJson:Dr(M_)},"geometry(point):tuple":{castInJson:pi,castArrayInJson:Hn,normalize:U_,normalizeArray:Dr(U_),normalizeInJson:U_,normalizeArrayInJson:Dr(U_)},interval:{castArrayInJson:Hn},json:{normalizeParamArray:nZ((e)=>JSON.stringify(e),!0)},jsonb:{normalizeParamArray:nZ((e)=>JSON.stringify(e),!0)},line:{castInJson:pi,castArrayInJson:Hn,normalize:O_,normalizeArray:Dr(O_),normalizeInJson:O_,normalizeArrayInJson:Dr(O_)},"line:tuple":{castInJson:pi,castArrayInJson:Hn,normalize:D_,normalizeArray:Dr(D_),normalizeInJson:D_,normalizeArrayInJson:Dr(D_)},numeric:{castInJson:pi,castArrayInJson:Hn,castArray:Hn},"numeric:number":{castInJson:pi,castArrayInJson:Hn,castArray:Hn,normalize:Number,normalizeArray:Dr(Number),normalizeInJson:Number,normalizeArrayInJson:Dr(Number)},"numeric:bigint":{castInJson:pi,castArrayInJson:Hn,castArray:Hn,normalize:BigInt,normalizeArray:Dr(BigInt),normalizeInJson:BigInt,normalizeArrayInJson:Dr(BigInt)},point:{castInJson:pi,castArrayInJson:Hn,normalize:F_,normalizeArray:Dr(F_),normalizeInJson:F_,normalizeArrayInJson:Dr(F_)},"point:tuple":{castInJson:pi,castArrayInJson:Hn,normalize:N_,normalizeArray:Dr(N_),normalizeInJson:N_,normalizeArrayInJson:Dr(N_)},timestamp:{castInJson:pi,castArrayInJson:Hn,normalizeInJson:iZ,normalizeArrayInJson:Dr(iZ)},timestamptz:{castInJson:pi,castArrayInJson:Hn,normalizeInJson:L_,normalizeArrayInJson:Dr(L_)},"timestamp:string":{castInJson:pi,castArrayInJson:Hn},"timestamptz:string":{castInJson:pi,castArrayInJson:Hn},halfvec:{normalize:Pf,normalizeArray:oZ(Pf),normalizeInJson:Pf,normalizeArrayInJson:Dr(Pf)},vector:{normalize:Pf,normalizeArray:oZ(Pf),normalizeInJson:Pf,normalizeArrayInJson:Dr(Pf)}};var HRe=class extends Ke{static[R]="PgCustomColumnBuilder";constructor(e,t,r){super(e,"custom","PgCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new WRe(e,this.config)}},WRe=class extends Ce{static[R]="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"?sZ(r):void 0,this.dimensions&&t.customTypeParams.fromJson)this.mapFromJsonValue=(n)=>{if(n===null)return n;let o=typeof n==="string"?__(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 aZ(e){return(t,r)=>{let{name:n,config:o}=Tt(t,r);return new HRe(n,o,e)}}var Cf=class extends Ke{static[R]="PgDateColumnBaseBuilder";defaultNow(){return this.default(m`now()`)}};var VRe=class extends Cf{static[R]="PgDateBuilder";constructor(e){super(e,"object date","PgDate")}build(e){return new zRe(e,this.config)}},zRe=class extends Ce{static[R]="PgDate";codec="date";getSQLType(){return"date"}mapToDriverValue=function(e){if(typeof e==="string")return e;return e.toISOString()}},KRe=class extends Cf{static[R]="PgDateStringBuilder";constructor(e){super(e,"string date","PgDateString")}build(e){return new GRe(e,this.config)}},GRe=class extends Ce{static[R]="PgDateString";codec="date:string";getSQLType(){return"date"}mapToDriverValue=(e)=>{if(typeof e==="string")return e;return e.toISOString()}};function cZ(e,t){let{name:r,config:n}=Tt(e,t);if(n?.mode==="date")return new VRe(r);return new KRe(r)}var QRe=class extends Ke{static[R]="PgDoublePrecisionBuilder";constructor(e){super(e,"number double","PgDoublePrecision")}build(e){return new JRe(e,this.config)}},JRe=class extends Ce{static[R]="PgDoublePrecision";codec="float8";getSQLType(){return"double precision"}};function lZ(e){return new QRe(e??"")}var YRe=class extends Ke{static[R]="PgInetBuilder";constructor(e){super(e,"string inet","PgInet")}build(e){return new XRe(e,this.config)}},XRe=class extends Ce{static[R]="PgInet";codec="inet";getSQLType(){return"inet"}};function dZ(e){return new YRe(e??"")}var ZRe=class extends Rf{static[R]="PgIntegerBuilder";constructor(e){super(e,"number int32","PgInteger")}build(e){return new ePe(e,this.config)}},ePe=class extends Ce{static[R]="PgInteger";codec="int";getSQLType(){return"integer"}};function uZ(e){return new ZRe(e??"")}var tPe=class extends Ke{static[R]="PgIntervalBuilder";constructor(e,t){super(e,"string interval","PgInterval");this.config.intervalConfig=t}build(e){return new rPe(e,this.config)}},rPe=class extends Ce{static[R]="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 pZ(e,t={}){let{name:r,config:n}=Tt(e,t);return new tPe(r,n)}var nPe=class extends Ke{static[R]="PgJsonBuilder";constructor(e){super(e,"object json","PgJson")}build(e){return new oPe(e,this.config)}},oPe=class extends Ce{static[R]="PgJson";codec="json";constructor(e,t){super(e,t)}getSQLType(){return"json"}};function fZ(e){return new nPe(e??"")}var iPe=class extends Ke{static[R]="PgJsonbBuilder";constructor(e){super(e,"object json","PgJsonb")}build(e){return new sPe(e,this.config)}},sPe=class extends Ce{static[R]="PgJsonb";codec="jsonb";constructor(e,t){super(e,t)}getSQLType(){return"jsonb"}};function mZ(e){return new iPe(e??"")}var aPe=class extends Ke{static[R]="PgLineBuilder";constructor(e){super(e,"array line","PgLine")}build(e){return new cPe(e,this.config)}},cPe=class extends Ce{static[R]="PgLine";codec="line:tuple";mode="tuple";getSQLType(){return"line"}mapToDriverValue=(e)=>`{${e[0]},${e[1]},${e[2]}}`},lPe=class extends Ke{static[R]="PgLineABCBuilder";constructor(e){super(e,"object line","PgLineABC")}build(e){return new dPe(e,this.config)}},dPe=class extends Ce{static[R]="PgLineABC";codec="line";mode="abc";getSQLType(){return"line"}mapToDriverValue=(e)=>`{${e.a},${e.b},${e.c}}`};function yZ(e,t){let{name:r,config:n}=Tt(e,t);if(!n?.mode||n.mode==="tuple")return new aPe(r);return new lPe(r)}var uPe=class extends Ke{static[R]="PgMacaddrBuilder";constructor(e){super(e,"string macaddr","PgMacaddr")}build(e){return new pPe(e,this.config)}},pPe=class extends Ce{static[R]="PgMacaddr";codec="macaddr";getSQLType(){return"macaddr"}};function hZ(e){return new uPe(e??"")}var fPe=class extends Ke{static[R]="PgMacaddr8Builder";constructor(e){super(e,"string macaddr8","PgMacaddr8")}build(e){return new mPe(e,this.config)}},mPe=class extends Ce{static[R]="PgMacaddr8";codec="macaddr8";getSQLType(){return"macaddr8"}};function gZ(e){return new fPe(e??"")}var yPe=class extends Ke{static[R]="PgNumericBuilder";constructor(e,t,r){super(e,"string numeric","PgNumeric");this.config.precision=t,this.config.scale=r}build(e){return new hPe(e,this.config)}},hPe=class extends Ce{static[R]="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})`}},gPe=class extends Ke{static[R]="PgNumericNumberBuilder";constructor(e,t,r){super(e,"number","PgNumericNumber");this.config.precision=t,this.config.scale=r}build(e){return new SPe(e,this.config)}},SPe=class extends Ce{static[R]="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})`}},vPe=class extends Ke{static[R]="PgNumericBigIntBuilder";constructor(e,t,r){super(e,"bigint int64","PgNumericBigInt");this.config.precision=t,this.config.scale=r}build(e){return new xPe(e,this.config)}},xPe=class extends Ce{static[R]="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 SZ(e,t){let{name:r,config:n}=Tt(e,t),o=n?.mode;return o==="number"?new gPe(r,n?.precision,n?.scale):o==="bigint"?new vPe(r,n?.precision,n?.scale):new yPe(r,n?.precision,n?.scale)}var EPe=class extends Ke{static[R]="PgPointTupleBuilder";constructor(e){super(e,"array point","PgPointTuple")}build(e){return new bPe(e,this.config)}},bPe=class extends Ce{static[R]="PgPointTuple";codec="point:tuple";mode="tuple";getSQLType(){return"point"}mapToDriverValue=(e)=>`(${e[0]},${e[1]})`},wPe=class extends Ke{static[R]="PgPointObjectBuilder";constructor(e){super(e,"object point","PgPointObject")}build(e){return new TPe(e,this.config)}},TPe=class extends Ce{static[R]="PgPointObject";codec="point";mode="xy";getSQLType(){return"point"}mapToDriverValue=(e)=>`(${e.x},${e.y})`};function vZ(e,t){let{name:r,config:n}=Tt(e,t);if(!n?.mode||n.mode==="tuple")return new EPe(r);return new wPe(r)}var APe=class extends Ke{static[R]="PgGeometryBuilder";constructor(e,t){super(e,"array geometry","PgGeometry");this.config.srid=t}build(e){return new IPe(e,this.config)}},IPe=class extends Ce{static[R]="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]})`},RPe=class extends Ke{static[R]="PgGeometryObjectBuilder";constructor(e,t){super(e,"object geometry","PgGeometryObject");this.config.srid=t}build(e){return new PPe(e,this.config)}},PPe=class extends Ce{static[R]="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 xZ(e,t){let{name:r,config:n}=Tt(e,t);if(!n?.mode||n.mode==="tuple")return new APe(r,n?.srid);return new RPe(r,n?.srid)}var CPe=class extends Ke{static[R]="PgRealBuilder";constructor(e,t){super(e,"number float","PgReal");this.config.length=t}build(e){return new _Pe(e,this.config)}},_Pe=class extends Ce{static[R]="PgReal";codec="float4";constructor(e,t){super(e,t)}getSQLType(){return"real"}};function EZ(e){return new CPe(e??"")}var kPe=class extends Ke{static[R]="PgSerialBuilder";constructor(e){super(e,"number int32","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new DPe(e,this.config)}},DPe=class extends Ce{static[R]="PgSerial";codec="serial";getSQLType(){return"serial"}};function bZ(e){return new kPe(e??"")}var OPe=class extends Rf{static[R]="PgSmallIntBuilder";constructor(e){super(e,"number int16","PgSmallInt")}build(e){return new NPe(e,this.config)}},NPe=class extends Ce{static[R]="PgSmallInt";codec="smallint";getSQLType(){return"smallint"}};function wZ(e){return new OPe(e??"")}var FPe=class extends Ke{static[R]="PgSmallSerialBuilder";constructor(e){super(e,"number int16","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new UPe(e,this.config)}},UPe=class extends Ce{static[R]="PgSmallSerial";codec="smallserial";getSQLType(){return"smallserial"}};function TZ(e){return new FPe(e??"")}var MPe=class extends Ke{static[R]="PgTextBuilder";constructor(e,t){super(e,t.enum?.length?"string enum":"string","PgText");this.config.enumValues=t.enum}build(e){return new LPe(e,this.config,this.config.enumValues)}},LPe=class extends Ce{static[R]="PgText";enumValues;codec="text";constructor(e,t,r){super(e,t);this.enumValues=r}getSQLType(){return"text"}};function AZ(e,t={}){let{name:r,config:n}=Tt(e,t);return new MPe(r,n)}var BPe=class extends Cf{static[R]="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 $Pe(e,this.config)}},$Pe=class extends Ce{static[R]="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 IZ(e,t={}){let{name:r,config:n}=Tt(e,t);return new BPe(r,n.withTimezone??!1,n.precision)}var qPe=class extends Cf{static[R]="PgTimestampBuilder";constructor(e,t,r){super(e,"object date","PgTimestamp");this.config.withTimezone=t,this.config.precision=r}build(e){return new jPe(e,this.config)}},jPe=class extends Ce{static[R]="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()}},HPe=class extends Cf{static[R]="PgTimestampStringBuilder";constructor(e,t,r){super(e,"string timestamp","PgTimestampString");this.config.withTimezone=t,this.config.precision=r}build(e){return new WPe(e,this.config)}},WPe=class extends Ce{static[R]="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 RZ(e,t={}){let{name:r,config:n}=Tt(e,t);if(n?.mode==="string")return new HPe(r,n.withTimezone??!1,n.precision);return new qPe(r,n?.withTimezone??!1,n?.precision)}var VPe=class extends Ke{static[R]="PgUUIDBuilder";constructor(e){super(e,"string uuid","PgUUID")}defaultRandom(){return this.default(m`gen_random_uuid()`)}build(e){return new zPe(e,this.config)}},zPe=class extends Ce{static[R]="PgUUID";codec="uuid";getSQLType(){return"uuid"}};function PZ(e){return new VPe(e??"")}var KPe=class extends Ke{static[R]="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 GPe(e,this.config)}},GPe=class extends Ce{static[R]="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 CZ(e,t={}){let{name:r,config:n}=Tt(e,t);return new KPe(r,n)}var QPe=class extends Ke{static[R]="PgBinaryVectorBuilder";constructor(e,t){super(e,"string binary","PgBinaryVector");this.config.length=t.dimensions,this.config.isLengthExact=!0}build(e){return new JPe(e,this.config)}},JPe=class extends Ce{static[R]="PgBinaryVector";codec="bit";getSQLType(){return`bit(${this.length})`}};function _Z(e,t){let{name:r,config:n}=Tt(e,t);return new QPe(r,n)}var YPe=class extends Ke{static[R]="PgHalfVectorBuilder";constructor(e,t){super(e,"array halfvector","PgHalfVector");this.config.length=t.dimensions,this.config.isLengthExact=!0}build(e){return new XPe(e,this.config)}},XPe=class extends Ce{static[R]="PgHalfVector";codec="halfvec";getSQLType(){return`halfvec(${this.length})`}mapToDriverValue=(e)=>JSON.stringify(e)};function kZ(e,t){let{name:r,config:n}=Tt(e,t);return new YPe(r,n)}var ZPe=class extends Ke{static[R]="PgSparseVectorBuilder";constructor(e,t){super(e,"string sparsevec","PgSparseVector");this.config.vectorDimensions=t.dimensions}build(e){return new eCe(e,this.config)}},eCe=class extends Ce{static[R]="PgSparseVector";codec="sparsevec";vectorDimensions=this.config.vectorDimensions;getSQLType(){return`sparsevec(${this.vectorDimensions})`}};function DZ(e,t){let{name:r,config:n}=Tt(e,t);return new ZPe(r,n)}var tCe=class extends Ke{static[R]="PgVectorBuilder";constructor(e,t){super(e,"array vector","PgVector");this.config.length=t.dimensions,this.config.isLengthExact=!0}build(e){return new rCe(e,this.config)}},rCe=class extends Ce{static[R]="PgVector";codec="vector";getSQLType(){return`vector(${this.length})`}mapToDriverValue=(e)=>JSON.stringify(e)};function OZ(e,t){let{name:r,config:n}=Tt(e,t);return new tCe(r,n)}function NZ(){return{bigint:Q7,bigserial:J7,boolean:Y7,char:X7,cidr:Z7,customType:aZ,date:cZ,doublePrecision:lZ,inet:dZ,integer:uZ,interval:pZ,json:fZ,jsonb:mZ,line:yZ,macaddr:hZ,macaddr8:gZ,numeric:SZ,point:vZ,geometry:xZ,real:EZ,serial:bZ,smallint:wZ,smallserial:TZ,text:AZ,time:IZ,timestamp:RZ,uuid:PZ,varchar:CZ,bit:_Z,halfvec:kZ,sparsevec:DZ,vector:OZ}}var E1=Symbol.for("drizzle:PgInlineForeignKeys"),b1=Symbol.for("drizzle:EnableRLS"),Mw=class extends xe{static[R]="PgTable";static Symbol=Object.assign({},xe.Symbol,{InlineForeignKeys:E1,EnableRLS:b1});[E1]=[];[b1]=!1;[xe.Symbol.ExtraConfigBuilder]=void 0;[xe.Symbol.ExtraConfigColumns]={}};function FZ(e,t,r,n,o,i=e){let s=w_(o),a=new Mw(e,n,i),c=typeof t==="function"?t(NZ()):t,l=Object.fromEntries(Object.entries(c).map(([p,y])=>{let g=y;g.setName(p,s);let E=g.build(a).postBuild();return a[E1].push(...g.buildForeignKeys(E,a)),[p,E]})),d=Object.fromEntries(Object.entries(c).map(([p,y])=>{let g=y;return g.setName(p,s),[p,g.buildExtraConfigColumn(a)]})),u=Object.assign(a,l);if(u[xe.Symbol.Columns]=l,u[xe.Symbol.ExtraConfigColumns]=d,r)u[Mw.Symbol.ExtraConfigBuilder]=r;return Object.assign(u,{enableRLS:()=>(u[Mw.Symbol.EnableRLS]=!0,u)})}function nCe(e){return Object.assign((n,o,i)=>FZ(n,o,i,void 0,e),{withRLS:(n,o,i)=>{let s=FZ(n,o,i,void 0,e);return s[b1]=!0,s}})}var yBt=nCe(void 0);var UZ=class{static[R]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new oCe(e,this.columns,this.name)}},oCe=class{static[R]="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[Mw.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}};var MZ=class{static[R]="Relation";referencedTableName;fieldName;constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[xe.Symbol.Name]}},LZ=class{static[R]="Relations";constructor(e,t){this.table=e,this.config=t}},Tv=class e extends MZ{static[R]="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}},w1=class e extends MZ{static[R]="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 BZ(){return{and:k,between:vv,eq:f,exists:qy,gt:Vr,gte:Af,ilike:bv,inArray:Ye,isNull:Pe,isNotNull:mr,like:If,lt:xd,lte:Fo,ne:Tf,not:na,notBetween:xv,notExists:jy,notLike:Ev,notIlike:wv,notInArray:Uo,or:Zt,sql:m}}function $Z(){return{sql:m,asc:oa,desc:eo}}function qZ(e,t){if(Object.keys(e).length===1&&"default"in e&&!H(e.default,xe))e=e.default;let r={},n={},o={};for(let[i,s]of Object.entries(e))if(H(s,xe)){let a=My(s),c=n[a];r[a]=i,o[i]={tsName:i,dbName:s[xe.Symbol.Name],schema:s[xe.Symbol.Schema],columns:s[xe.Symbol.Columns],relations:c?.relations??{},primaryKey:c?.primaryKey??[]};for(let d of Object.values(s[xe.Symbol.Columns]))if(d.primary)o[i].primaryKey.push(d);let l=s[xe.Symbol.ExtraConfigBuilder]?.(s[xe.Symbol.ExtraConfigColumns]);if(l){for(let d of Object.values(l))if(H(d,UZ))o[i].primaryKey.push(...d.columns)}}else if(H(s,LZ)){let a=My(s.table),c=r[a],l=s.config(t(s.table));for(let[d,u]of Object.entries(l))if(c){let p=o[c];p.relations[d]=u}else{if(!(a in n))n[a]={relations:{}};n[a].relations[d]=u}}return{tables:o,tableNamesMap:r}}function er(e,t){return new LZ(e,(r)=>Object.fromEntries(Object.entries(t(r)).map(([n,o])=>[n,o.withFieldName(n)])))}function iCe(e){return function(r,n){return new Tv(e,r,n,n?.fields.reduce((o,i)=>o&&i.notNull,!0)??!1)}}function sCe(e){return function(r,n){return new w1(e,r,n)}}function jZ(e,t,r){if(H(r,Tv)&&r.config)return{fields:r.config.fields,references:r.config.references};let n=t[My(r.referencedTable)];if(!n)throw Error(`Table "${r.referencedTable[xe.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[My(i)];if(!s)throw Error(`Table "${i[xe.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[xe.Symbol.Name]}". Please specify relation name`);if(a[0]&&H(a[0],Tv)&&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 HZ(e){return{one:iCe(e),many:sCe(e)}}function B_(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]=H(c,Tv)?d&&B_(e,e[a.relationTableTsKey],d,a.selection,o):d.map((u)=>B_(e,e[a.relationTableTsKey],u,a.selection,o))}else{let c=o(r[s]),l=a.field,d;if(H(l,Pt))d=l;else if(H(l,Ae))d=l.decoder;else d=l.sql.decoder;i[a.tsKey]=c===null?null:d.mapFromDriverValue(c)}return i}var $u=class extends Error{static[R]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}},Hy=class e extends Error{static[R]="DrizzleQueryError";constructor(t,r,n){super(`Failed query: ${t}
|
|
765
|
+
params: ${r}`);if(this.query=t,this.params=r,this.cause=n,this.name="DrizzleQueryError",Error.captureStackTrace(this,e),n)this.cause=n}},WZ=class extends $u{static[R]="TransactionRollbackError";constructor(){super({message:"Rollback"});this.name="TransactionRollbackError"}};function VZ(e,t){for(let r of Object.values(e))for(let[n,o]of Object.entries(r.relations)){if(!H(o,Wy))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(!H(i,Wy))continue;let s,{targetTableName:a,alias:c,sourceColumns:l,targetColumns:d,throughTable:u,sourceTable:p,through:y,where:g,sourceColumnTableNames:E,targetColumnTableNames:S}=i,x=`relations -> ${n.name}: { ${o}: r.${H(i,Lw)?"one":"many"}.${a}(...) }`;if(o in n.table[ra])throw Error(`${x}: relation name collides with column "${o}" of table "${n.name}"`);if(typeof c==="string"&&!c)throw Error(`${x}: "alias" cannot be an empty string - omit it if you don't need it`);if(l?.length===0)throw Error(`${x}: "from" cannot be empty`);if(d?.length===0)throw Error(`${x}: "to" cannot be empty`);if(l&&d){if(l.length!==d.length&&!u)throw Error(`${x}: "from" and "to" fields without "through" must have the same length`);for(let _ of E)if(_!==r)throw Error(`${x}: all "from" columns must belong to table "${r}", found column of table "${_}"`);for(let _ of S)if(_!==a)throw Error(`${x}: all "to" columns must belong to table "${a}", found column of table "${_}"`);if(y){if(y.source.length!==l.length||y.target.length!==d.length)throw Error(`${x}: ".through(column)" must be used either on all columns in "from" and "to" or not defined on any of them`);for(let _ of y.source)if(t[_._.tableName]!==u)throw Error(`${x}: ".through(column)" must be used on the same table by all columns of the relation`);for(let _ of y.target)if(t[_._.tableName]!==u)throw Error(`${x}: ".through(column)" must be used on the same table by all columns of the relation`)}continue}if(l||d)throw Error(`${x}: relation must have either both "from" and "to" defined, or none of them`);let w=e[a];if(!w)throw Error(`${x}: 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 _=Object.values(w.relations).filter((T)=>H(T,Wy)&&T.alias===c&&T!==i);if(_.length>1)throw Error(`${x}: not enough data provided to build the relation - "from"/"to" are not defined, and multiple relations with alias "${c}" found in table "${a}": ${_.map((T)=>`"${T.fieldName}"`).join(", ")}`);if(s=_[0],!s)throw Error(`${x}: 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 _=Object.values(w.relations).filter((T)=>H(T,Wy)&&T.targetTable===p&&!T.alias&&T!==i);if(_.length>1)throw Error(`${x}: not enough data provided to build the relation - "from"/"to" are not defined, and multiple relations between "${a}" and "${r}" were found.
|
|
766
|
+
Hint: you can specify "alias" on both sides of the relation with the same value`);if(s=_[0],!s)throw Error(`${x}: 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(`${x}: 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=!g,i.where=g??s.where}return e}function zZ(e,t){let r={};for(let[n,o]of Object.entries(e))r[n]={table:o,name:n,relations:t[n]??{}};return VZ(r,e)}var Wy=class{static[R]="RelationV2";fieldName;sourceColumns;targetColumns;alias;where;sourceTable;targetTable;through;throughTable;isReversed;sourceColumnTableNames=[];targetColumnTableNames=[];constructor(e,t){this.targetTableName=t,this.targetTable=e}},Lw=class extends Wy{static[R]="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}},KZ=class extends Wy{static[R]="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)}}},GZ=class{static[R]="AggregatedField";table;onTable(e){return this.table=e,this}},QZ=class extends GZ{static[R]="AggregatedFieldCount";query;getSQL(){if(!this.query){if(!this.table)throw Error("Table must be set before building aggregate field");this.query=m`select count(*) as ${m.identifier("r")} from ${_f(this.table)}`.mapWith(Number)}return this.query}},Vy={and:k,between:vv,eq:f,exists:qy,gt:Vr,gte:Af,ilike:bv,inArray:Ye,arrayContains:R_,arrayContained:P_,arrayOverlaps:C_,isNull:Pe,isNotNull:mr,like:If,lt:xd,lte:Fo,ne:Tf,not:na,notBetween:xv,notExists:jy,notLike:Ev,notIlike:wv,notInArray:Uo,or:Zt,sql:m},JZ={sql:m,asc:oa,desc:eo};function Av(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 p;if(H(l,Pt))p=l;else if(H(l,Ae))p=l.decoder;else if(H(l,Ae.Aliased))p=l.sql.decoder;else if(H(l,xe)||H(l,Jn))p=bf;else p=l.getSQL().decoder;if(s&&l.mapFromJsonValue)return(y)=>l.mapFromJsonValue(y);return p.mapFromDriverValue.isNoop?d?(y)=>d(y,u):void 0:d?(y)=>p.mapFromDriverValue(d(y,u)):(y)=>p.mapFromDriverValue(y)});for(let l=0;l<a;++l){let d=t?e:e[l];for(let u=0;u<r.length;++u){let p=r[u];if(p.selection){if(d[p.key]===null)continue;if(o){if(d[p.key]=JSON.parse(d[p.key]),d[p.key]===null)continue}else if(i&&typeof d[p.key]==="string")d[p.key]=JSON.parse(d[p.key]);if(p.isArray){Av(d[p.key],!1,p.selection,n,!1,i);continue}Av(d[p.key],!0,p.selection,n,!1,i);continue}if(n)d[p.key]=n(d[p.key]);if(d[p.key]===null)continue;let y=c[u];if(!y)continue;d[p.key]=y(d[p.key])}}return e}function YZ(e,t,r,n,o=!1,i=!1){let s=t?1:e.length,a=r.map(({field:l,codec:d,arrayDimensions:u})=>{let p;if(H(l,Pt))p=l;else if(H(l,Ae))p=l.decoder;else if(H(l,Ae.Aliased))p=l.sql.decoder;else if(H(l,xe)||H(l,Jn))p=bf;else p=l.getSQL().decoder;return p.mapFromDriverValue.isNoop?d?(y)=>d(y,u):void 0:d?(y)=>p.mapFromDriverValue(d(y,u)):(y)=>p.mapFromDriverValue(y)}),c=Array.from({length:s});for(let l=0;l<s;++l){let d=t?e:e[l],u={};for(let p=0;p<r.length;++p){let y=r[p],g=d[p];if(y.selection){if(g===null){u[y.key]=null;continue}if(o){if(g=JSON.parse(g),g===null){u[y.key]=null;continue}}else if(i&&typeof g==="string")g=JSON.parse(g);if(y.isArray)Av(g,!1,y.selection,n,!1,i);else Av(g,!0,y.selection,n,!1,i);u[y.key]=g;continue}if(n)g=n(g);if(g===null){u[y.key]=null;continue}let E=a[p];u[y.key]=E?E(g):g}c[l]=u}return t?c[0]:c}function I1({selection:e,isFirst:t,parseJson:r,parseJsonIfString:n,rootJsonMappers:o,arrayModeRoot:i},s){return(a)=>{if(t&&!a[0])return a[0];return i?YZ(t?a[0]:a,t,e,s,r,n):Av(t?a[0]:a,t,e,s,r,n,o)}}function A1(e,t,r,n,o,i,s,a,c,l){let d=[],u=[],p=!1,y=e.map(()=>`c${c.n++}`),g=e.map((E,S)=>l?y[S]:`${JSON.stringify(E.key)}: ${y[S]}`);d.push(l?`let [ ${g.join(", ")} ] = ${t};`:`let { ${g.join(", ")} } = ${t};`);for(let[E,{field:S,key:x,codec:w,isArray:_,selection:T,arrayDimensions:b}]of e.entries()){let I=`${r}[${E}]`,O=JSON.stringify(x),L=y[E];if(T){if(o)d.push(`if (${L} !== null) ${L} = JSON.parse(${L});`),p=!0;else if(i)d.push(`if (typeof ${L} === 'string') ${L} = JSON.parse(${L});`),p=!0;let ne=`s${c.n++}`,le=a.length;if(a.push(`const { selection: ${ne} } = ${I};`),_){let ie=`j${c.n++}`,je=A1(T,`${L}[${ie}]`,ne,n,!1,i,!0,a,c,!1);if(je.hasWork){p=!0,d.push(`if (${L} !== null) {`),d.push(` for (let ${ie} = 0; ${ie} < ${L}.length; ++${ie}) {`);for(let ft of je.bodyStmts)d.push(` ${ft}`);d.push(` ${L}[${ie}] = ${je.literal};`),d.push("\t}"),d.push("}")}else a.splice(le,1)}else{let ie=A1(T,L,ne,n,!1,i,!0,a,c,!1);if(ie.hasWork){p=!0,d.push(`if (${L} !== null) {`);for(let je of ie.bodyStmts)d.push(` ${je}`);d.push(` ${L} = ${ie.literal};`),d.push("}")}else a.splice(le,1)}u.push(`${O}: ${L}`);continue}let Y="",Z="",ee=!1;if(H(S,Pt)){if(s&&S.mapFromJsonValue){ee=!0;let ne=c.n++;Z=`field: dec${ne}`,Y=`dec${ne}.mapFromJsonValue`}else if(!S.mapFromDriverValue.isNoop){let ne=c.n++;Z=`field: dec${ne}`,Y=`dec${ne}.mapFromDriverValue`}}else if(H(S,Ae)){if(s&&S.decoder.mapFromJsonValue){ee=!0;let ne=c.n++;Z=`field: { decoder: dec${ne} }`,Y=`dec${ne}.mapFromJsonValue`}else if(!S.decoder.mapFromDriverValue.isNoop){let ne=c.n++;Z=`field: { decoder: dec${ne} }`,Y=`dec${ne}.mapFromDriverValue`}}else if(H(S,Ae.Aliased)){if(s&&S.sql.decoder.mapFromJsonValue){ee=!0;let ne=c.n++;Z=`field: { sql: { decoder: dec${ne} } }`,Y=`dec${ne}.mapFromJsonValue`}else if(!S.sql.decoder.mapFromDriverValue.isNoop){let ne=c.n++;Z=`field: { sql: { decoder: dec${ne} } }`,Y=`dec${ne}.mapFromDriverValue`}}else if(H(S,xe)||H(S,Jn));else{let ne=S.getSQL();if(s&&ne.decoder.mapFromJsonValue){ee=!0;let le=c.n++;a.push(`const dec${le} = ${I}.field.getSQL().decoder;`),Y=`dec${le}.mapFromJsonValue`}else if(!ne.decoder.mapFromDriverValue.isNoop){let le=c.n++;a.push(`const dec${le} = ${I}.field.getSQL().decoder;`),Y=`dec${le}.mapFromDriverValue`}}let ae="";if(!ee&&w)ae=`codec${c.n++}`;if(Z||ae){let ne=[];if(Z)ne.push(Z);if(ae)ne.push(`codec: ${ae}`);a.push(`const { ${ne.join(", ")} } = ${I};`)}if(n){if(p=!0,d.push(`${L} = mapColumnValue(${L});`),Y||ae){let ne=L;if(ae)ne=`${ae}(${ne}, ${b})`;if(Y)ne=`${Y}(${ne})`;d.push(`if (${L} !== null) ${L} = ${ne};`)}u.push(`${O}: ${L}`)}else if(Y||ae){p=!0;let ne=L;if(ae)ne=`${ae}(${ne}, ${b})`;if(Y)ne=`${Y}(${ne})`;u.push(`${O}: ${L} === null ? null : ${ne}`)}else u.push(`${O}: ${L}`)}return{bodyStmts:d,literal:`{ ${u.join(", ")} }`,hasWork:p}}function q_({selection:e,isFirst:t,parseJson:r,parseJsonIfString:n,rootJsonMappers:o,arrayModeRoot:i},s){let a=[],c=A1(e,"row","selection",s,r,n,i?!1:o,a,{n:0},!!i),l=[];l.push(` "use strict";
|
|
767
|
+
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(`
|
|
768
|
+
`);return Object.assign(new g_("rows",d).bind({selection:e,mapColumnValue:s}),{body:`function jitRqbMapper (rows) {
|
|
769
|
+
${d}
|
|
770
|
+
}`})}var XZ=class{static[R]="RelationsBuilderTable";_;constructor(e,t){this._={name:t,table:e}}},ZZ=class{static[R]="RelationsBuilderColumn";_;constructor(e,t,r){this._={tableName:t,column:e,key:r}}through(e){return new eee(this._.column,this._.tableName,this._.key,e)}},eee=class{static[R]="RelationsBuilderColumn";_;constructor(e,t,r,n){this._={tableName:t,column:e,through:n,key:r}}},tee=class{static[R]="RelationsHelperStatic";_;constructor(e){this._={tables:e};let t={},r={};for(let[n,o]of Object.entries(e))t[n]=(i)=>new Lw(e,o,n,i),r[n]=(i)=>new KZ(e,o,n,i);this.one=t,this.many=r}one;many;aggs={count(){return new QZ}}};function ree(e){let t=new tee(e),r=Object.entries(e).reduce((n,[o,i])=>{let s=new XZ(i,o),a=Object.entries(i[ra]).reduce((c,[l,d])=>(c[l]=new ZZ(d,o,l),c),{});return n[o]=Object.assign(s,a),n},{});return Object.assign(t,r)}function nee(e){return Object.fromEntries(Object.entries(e).filter(([t,r])=>H(r,xe)||H(r,Jn)))}function R1(e,t){let r=nee(e);return zZ(r,t?t(ree(r)):{})}function P1(e,t){let r=e[ra][t];return r?H(r,Pt)?r:H(r,Ae.Aliased)?m`${e}.${m.identifier(r.fieldAlias)}`:m`${e}.${m.identifier(t)}`:m`${e}.${m.identifier(t)}`}function $_(e,t){if(typeof t!=="object"||H(t,gl))return f(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=$_(e,i);if(!s)continue;n.push(na(s));continue}case"OR":if(!i.length)continue;n.push(Zt(...i.map((s)=>$_(e,s))));continue;case"AND":if(!i.length)continue;n.push(k(...i.map((s)=>$_(e,s))));continue;case"isNotNull":case"isNull":if(!i)continue;n.push(Vy[o](e));continue;case"in":n.push(Vy.inArray(e,i));continue;case"notIn":n.push(Vy.notInArray(e,i));continue;default:n.push(Vy[o](e,i));continue}}if(!n.length)return;return k(...n)}function Ed(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,Vy):c.getSQL();s.push(l);continue}case"OR":if(!c?.length)continue;s.push(Zt(...c.map((l)=>Ed(e,l,r,n,o))));continue;case"AND":if(!c?.length)continue;s.push(k(...c.map((l)=>Ed(e,l,r,n,o))));continue;case"NOT":{if(c===void 0)continue;let l=Ed(e,c,r,n,o);if(!l)continue;s.push(na(l));continue}default:{if(e[ra][a]){let x=$_(P1(e,a),c);if(x)s.push(x);continue}let l=r[a];if(!l)throw new $u({message:`Unknown relational filter field: "${a}"`});let d=Di(l.targetTable,`f${o}`),u=l.throughTable?Di(l.throughTable,`ft${o}`):void 0,p=n[l.targetTableName],{filter:y,joinCondition:g}=j_(l,e,d,u),E=k(y,typeof c==="boolean"?void 0:Ed(d,c,p.relations,n,o+1)),S=u?m`(select * from ${_f(d)} inner join ${_f(u)} on ${g}${m` where ${E}`.if(E)} limit 1)`:m`(select * from ${_f(d)}${m` where ${E}`.if(E)} limit 1)`;if(E)s.push((c?qy:jy)(S))}}}return k(...s)}function C1(e,t){if(typeof t==="function"){let n=t(e,JZ);return H(n,Ae)?n:Array.isArray(n)?n.length?m.join(n.map((o)=>H(o,Ae)?o:oa(o)),m`, `):void 0:H(n,Pt)?oa(n):void 0}let r=Object.entries(t).filter(([n,o])=>o);if(!r.length)return;return m.join(r.map(([n,o])=>(o==="asc"?oa:eo)(P1(e,n))),m`, `)}function _1(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:Vy.sql}):a).getSQL(),l=r?h_(c):void 0,d=l&&(!n||!l.jsonSelectIdentifier)?m`${r.apply(l,n?"castInJson":"cast",m`(${c})`)} as ${m.identifier(s)}`:m`(${c}) as ${m.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?m.join(o,m`, `):void 0,selection:i}}function j_(e,t,r,n){if(e.through){let o=e.sourceColumns.map((s,a)=>{let c=e.through.source[a];return f(m`${t}.${m.identifier(s.name)}`,m`${n}.${m.identifier(H(c._.column,Pt)?c._.column.name:c._.key)}`)}),i=e.targetColumns.map((s,a)=>{let c=e.through.target[a];return f(m`${n}.${m.identifier(H(c._.column,Pt)?c._.column.name:c._.key)}`,m`${r}.${m.identifier(s.name)}`)});return{filter:k(e.where?Ed(e.isReversed?t:r,e.where):void 0,...o),joinCondition:k(...i)}}return{filter:k(...e.sourceColumns.map((o,i)=>{let s=e.targetColumns[i];return f(m`${t}.${m.identifier(o.name)}`,m`${r}.${m.identifier(s.name)}`)}),e.where?Ed(e.isReversed?t:r,e.where):void 0)}}function _f(e){return m`${e[Ef]?m`${m`${m.identifier(e[Uu]??"")}.`.if(e[Uu])}${m.identifier(e[Uy])} as ${e}`:e}`}function oee(e){let t=parseInt(e.slice(0,4),10),r=parseInt(e.slice(4,6),10)-1,n=parseInt(e.slice(6,8),10),o=parseInt(e.slice(8,10),10),i=parseInt(e.slice(10,12),10),s=parseInt(e.slice(12,14),10);return Date.UTC(t,r,n,o,i,s)}function Bw(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 k1={sqlite:1,pg:1,effect:1,mysql:1,mssql:1,cockroach:1,singlestore:1},D1={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 iee(e,t,r){if(t.all(m`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${e}`).length===0)return{newDb:!0};let n=t.all(m`SELECT name as column_name FROM pragma_table_info(${e})`),o=D1.sqlite(n.map((i)=>i.column_name));for(let i=o;i<k1.sqlite;i++){let s=mCe[i];if(!s)throw Error(`No upgrade path from migration table version ${i} to ${i+1}`);s(e,t,r)}return{newDb:!1}}var mCe={0:(e,t,r)=>{let n=m`${m.identifier(e)}`,o=t.all(m`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"),p=i.get(u),y,g=null;if(p&&p.length===1)y=p[0],g="millis";else if(p&&p.length>1){if(y=p.find((E)=>E.hash&&l.hash&&E.hash===l.hash),y)g="hash"}else if(y=s.get(l.hash),y)g="hash";if(y)a.push({id:l.id,name:y.name,hash:l.hash,created_at:d,matchedBy:l.id?"id":g});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(m`ALTER TABLE ${n} ADD COLUMN ${m.identifier("name")} text`),l.run(m`ALTER TABLE ${n} ADD COLUMN ${m.identifier("applied_at")} TEXT`);for(let d of a){let u=m`UPDATE ${n} SET ${m.identifier("name")} = ${d.name}, ${m.identifier("applied_at")} = NULL WHERE`;if(d.id)u.append(m` ${m.identifier("id")} = ${d.id}`);else if(d.matchedBy==="millis")u.append(m` ${m.identifier("created_at")} = ${d.created_at}`);else u.append(m` ${m.identifier("hash")} = ${d.hash}`);l.run(u)}})}};async function see(e,t,r){if((await t.session.all(m`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${e}`)).length===0)return{newDb:!0};let n=await t.session.all(m`SELECT name as column_name FROM pragma_table_info(${e})`),o=D1.sqlite(n.map((i)=>i.column_name));for(let i=o;i<k1.sqlite;i++){let s=yCe[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 yCe={0:async(e,t,r)=>{let n=m`${m.identifier(e)}`,o=await t.session.all(m`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),p=Number(u.substring(0,u.length-3)+"000"),y=i.get(p),g,E=null;if(y&&y.length===1)g=y[0],E="millis";else if(y&&y.length>1){if(g=y.find((S)=>S.hash&&d.hash&&S.hash===d.hash),g)E="hash"}else if(g=s.get(d.hash),g)E="hash";if(g)a.push({id:d.id,name:g.name,hash:d.hash,created_at:u,matchedBy:d.id?"id":E});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=[m`ALTER TABLE ${n} ADD COLUMN ${m.identifier("name")} text`,m`ALTER TABLE ${n} ADD COLUMN ${m.identifier("applied_at")} TEXT`];for(let d of a){let u=m`UPDATE ${n} SET ${m.identifier("name")} = ${d.name}, ${m.identifier("applied_at")} = NULL WHERE`;if(d.id)u.append(m` ${m.identifier("id")} = ${d.id}`);else if(d.matchedBy==="millis")u.append(m` ${m.identifier("created_at")} = ${d.created_at}`);else u.append(m` ${m.identifier("hash")} = ${d.hash}`);l.push(u)}await t.transaction(async(d)=>{for(let u of l)await d.run(u)})}};var $w=class{static[R]="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=[m`with `];for(let[r,n]of e.entries())if(t.push(m`${m.identifier(n._.alias)} as (${n._.sql})`),r<e.length-1)t.push(m`, `);return t.push(m` `),m.join(t)}buildDeleteQuery({table:e,where:t,returning:r,withList:n,limit:o,orderBy:i}){let s=this.buildWithCTE(n),a=r?m` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0;return m`${s}delete from ${e}${t?m` where ${t}`:void 0}${a}${this.buildOrderBy(i)}${this.buildLimit(o)}`}buildUpdateSet(e,t){let r=e[xe.Symbol.Columns],n=Object.keys(r).filter((i)=>t[i]!==void 0||r[i]?.onUpdateFn!==void 0),o=n.length;return m.join(n.flatMap((i,s)=>{let a=r[i],c=a.onUpdateFn?.(),l=t[i]??(H(c,Ae)?c:m.param(c,a)),d=m`${m.identifier(a.name)} = ${l}`;if(s<o-1)return[d,m.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&&m.join([m.raw(" from "),this.buildFromTable(s)]),p=this.buildJoins(i),y=n?m` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0;return m`${l}update ${e} set ${d}${u}${p}${r?m` where ${r}`:void 0}${y}${this.buildOrderBy(c)}${this.buildLimit(a)}`}buildSelection(e,{isSingleTable:t=!1}={}){let r=e.length,n=e.flatMap(({field:o},i)=>{let s=[];if(H(o,Ae.Aliased)&&o.isSelectionField){if(!t&&o.origin!==void 0)s.push(m.identifier(o.origin),m.raw("."));s.push(m.identifier(o.fieldAlias))}else if(H(o,Ae.Aliased)||H(o,Ae)){let a=H(o,Ae.Aliased)?o.sql:o;if(t){let c=new Ae(a.queryChunks.map((l)=>{if(H(l,Pt))return m.identifier(l.name);return l}));s.push(a.shouldInlineParams?c.inlineParams():c)}else s.push(a);if(H(o,Ae.Aliased))s.push(m` as ${m.identifier(o.fieldAlias)}`)}else if(H(o,Pt))if(o.columnType==="SQLiteNumericBigInt")if(t)s.push(o.isAlias?m`cast(${m.identifier(gv(o).name)} as text) as ${o}`:m`cast(${m.identifier(o.name)} as text)`);else s.push(o.isAlias?m`cast(${gv(o)} as text) as ${o}`:m`cast(${o} as text)`);else if(t)s.push(o.isAlias?m`${m.identifier(gv(o).name)} as ${o}`:m.identifier(o.name));else s.push(o.isAlias?m`${gv(o)} as ${o}`:o);else if(H(o,pn)){let a=Object.entries(o._.selectedFields);if(a.length===1){let c=a[0][1],l=H(c,Ae)?c.decoder:H(c,Pt)?{mapFromDriverValue:(d)=>c.mapFromDriverValue(d)}:c.sql.decoder;if(l)o._.sql.decoder=l}s.push(o)}if(i<r-1)s.push(m`, `);return s});return m.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(m` `);let o=n.table,i=n.on?m` on ${n.on}`:void 0;if(H(o,ui)){let s=o[ui.Symbol.Name],a=o[ui.Symbol.Schema],c=o[ui.Symbol.OriginalName],l=s===c?void 0:n.alias;t.push(m`${m.raw(n.joinType)} join ${a?m`${m.identifier(a)}.`:void 0}${m.identifier(c)}${l&&m` ${m.identifier(l)}`}${i}`)}else t.push(m`${m.raw(n.joinType)} join ${o}${i}`);if(r<e.length-1)t.push(m` `)}return m.join(t)}buildLimit(e){return typeof e==="object"||typeof e==="number"&&e>=0?m` 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(m`, `)}return t.length>0?m` order by ${m.join(t)}`:void 0}buildFromTable(e){if(H(e,xe)&&e[xe.Symbol.IsAlias])return m`${m`${m.identifier(e[xe.Symbol.Schema]??"")}.`.if(e[xe.Symbol.Schema])}${m.identifier(e[xe.Symbol.OriginalName])} ${m.identifier(e[xe.Symbol.Name])}`;if(H(e,Jn)&&e[dr].isAlias){let t=m`${m.identifier(e[dr].originalName)}`;if(e[dr].schema)t=m`${m.identifier(e[dr].schema)}.${t}`;return m`${t} ${m.identifier(e[dr].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:p}){let y=r??Rc(t);for(let L of y)if(H(L.field,Pt)&&Mu(L.field.table)!==(H(i,pn)?i._.alias:H(i,wf)?i[dr].name:H(i,Ae)?void 0:Mu(i))&&!((Y)=>s?.some(({alias:Z})=>Z===(Y[xe.Symbol.IsAlias]?Mu(Y):Y[xe.Symbol.BaseName])))(L.field.table)){let Y=Mu(L.field.table);throw Error(`Your "${L.path.join("->")}" field references a column "${Y}"."${L.field.name}", but the table "${Y}" is not part of the query! Did you forget to join it?`)}let g=!s||s.length===0,E=this.buildWithCTE(e),S=u?m` distinct`:void 0,x=this.buildSelection(y,{isSingleTable:g}),w=this.buildFromTable(i),_=this.buildJoins(s),T=n?m` where ${n}`:void 0,b=o?m` having ${o}`:void 0,I=[];if(c){for(let[L,Y]of c.entries())if(I.push(Y),L<c.length-1)I.push(m`, `)}let O=m`${E}select${S} ${x} from ${w}${_}${T}${I.length>0?m` group by ${m.join(I)}`:void 0}${b}${this.buildOrderBy(a)}${this.buildLimit(l)}${d?m` offset ${d}`:void 0}`;if(p.length>0)return this.buildSetOperations(O,p);return O}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=m`${e.getSQL()} `,c=m`${n.getSQL()}`,l;if(i&&i.length>0){let y=[];for(let g of i)if(H(g,Yn))y.push(m.identifier(g.name));else if(H(g,Ae)){for(let E=0;E<g.queryChunks.length;E++){let S=g.queryChunks[E];if(H(S,Yn))g.queryChunks[E]=m.identifier(S.name)}y.push(m`${g}`)}else y.push(m`${g}`);l=m` order by ${m.join(y,m`, `)}`}let d=typeof o==="object"||typeof o==="number"&&o>=0?m` limit ${o}`:void 0,u=m.raw(`${t} ${r?"all ":""}`),p=s?m` offset ${s}`:void 0;return m`${a}${u}${c}${l}${d}${p}`}buildInsertQuery({table:e,values:t,onConflict:r,returning:n,withList:o,select:i}){let s=[],a=e[xe.Symbol.Columns],c=Object.entries(a).filter(([y,g])=>!g.shouldDisableInsert()),l=c.map(([,y])=>m.identifier(y.name));if(i){let y=t;if(H(y,Ae))s.push(y);else s.push(y.getSQL())}else{let y=t;s.push(m.raw("values "));for(let[g,E]of y.entries()){let S=[];for(let[x,w]of c){let _=E[x];if(_===void 0||H(_,ki)&&_.value===void 0){let T;if(w.default!==null&&w.default!==void 0)T=H(w.default,Ae)?w.default:m.param(w.default,w);else if(w.defaultFn!==void 0){let b=w.defaultFn();T=H(b,Ae)?b:m.param(b,w)}else if(!w.default&&w.onUpdateFn!==void 0){let b=w.onUpdateFn();T=H(b,Ae)?b:m.param(b,w)}else T=m`null`;S.push(T)}else S.push(_)}if(s.push(S),g<y.length-1)s.push(m`, `)}}let d=this.buildWithCTE(o),u=m.join(s),p=n?m` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0;return m`${d}insert into ${e} ${l} ${u}${r?.length?m.join(r):void 0}${p}`}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,p=[],y,g=[];if(i===!0)l=Object.entries(o.columns).map(([S,x])=>({dbKey:x.name,tsKey:S,field:Sl(x,s),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let S=Object.fromEntries(Object.entries(o.columns).map(([I,O])=>[I,Sl(O,s)]));if(i.where){let I=typeof i.where==="function"?i.where(S,BZ()):i.where;y=I&&hv(I,s)}let x=[],w=[];if(i.columns){let I=!1;for(let[O,L]of Object.entries(i.columns)){if(L===void 0)continue;if(O in o.columns){if(!I&&L===!0)I=!0;w.push(O)}}if(w.length>0)w=I?w.filter((O)=>i.columns?.[O]===!0):Object.keys(o.columns).filter((O)=>!w.includes(O))}else w=Object.keys(o.columns);for(let I of w){let O=o.columns[I];x.push({tsKey:I,value:O})}let _=[];if(i.with)_=Object.entries(i.with).filter((I)=>!!I[1]).map(([I,O])=>({tsKey:I,queryConfig:O,relation:o.relations[I]}));let T;if(i.extras){T=typeof i.extras==="function"?i.extras(S,{sql:m}):i.extras;for(let[I,O]of Object.entries(T))x.push({tsKey:I,value:y_(O,s)})}for(let{tsKey:I,value:O}of x)l.push({dbKey:H(O,Ae.Aliased)?O.fieldAlias:o.columns[I].name,tsKey:I,field:H(O,Pt)?Sl(O,s):O,relationTableTsKey:void 0,isJson:!1,selection:[]});let b=typeof i.orderBy==="function"?i.orderBy(S,$Z()):i.orderBy??[];if(!Array.isArray(b))b=[b];p=b.map((I)=>{if(H(I,Pt))return Sl(I,s);return hv(I,s)}),d=i.limit,u=i.offset;for(let{tsKey:I,queryConfig:O,relation:L}of _){let Y=jZ(t,r,L),Z=r[My(L.referencedTable)],ee=`${s}_${I}`,ae=k(...Y.fields.map((ie,je)=>f(Sl(Y.references[je],ee),Sl(ie,s)))),ne=this._buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:e[Z],tableConfig:t[Z],queryConfig:H(L,Tv)?O===!0?{limit:1}:{...O,limit:1}:O,tableAlias:ee,joinOn:ae,nestedQueryRelation:L}),le=m`(${ne.sql})`.as(I);l.push({dbKey:I,tsKey:I,field:le,relationTableTsKey:Z,isJson:!0,selection:ne.selection})}}if(l.length===0)throw new $u({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 E;if(y=k(c,y),a){let S=m`json_array(${m.join(l.map(({field:w})=>H(w,Yn)?m.identifier(w.name):H(w,Ae.Aliased)?w.sql:w),m`, `)})`;if(H(a,w1))S=m`coalesce(json_group_array(${S}), json_array())`;let x=[{dbKey:"data",tsKey:"data",field:S.as("data"),isJson:!0,relationTableTsKey:o.tsName,selection:l}];if(d!==void 0||u!==void 0||p.length>0)E=this.buildSelectQuery({table:Di(n,s),fields:{},fieldsFlat:[{path:[],field:m.raw("*")}],where:y,limit:d,offset:u,orderBy:p,setOperators:[]}),y=void 0,d=void 0,u=void 0,p=void 0;else E=Di(n,s);E=this.buildSelectQuery({table:H(E,ui)?E:new pn(E,{},s),fields:{},fieldsFlat:x.map(({field:w})=>({path:[],field:H(w,Pt)?Sl(w,s):w})),joins:g,where:y,limit:d,offset:u,orderBy:p,setOperators:[]})}else E=this.buildSelectQuery({table:Di(n,s),fields:{},fieldsFlat:l.map(({field:S})=>({path:[],field:H(S,Pt)?Sl(S,s):S})),joins:g,where:y,limit:d,offset:u,orderBy:p,setOperators:[]});return{tableTsKey:o.tsName,sql:E,selection:l}}nestedSelectionerror(){throw new $u({message:"Views with nested selections are not supported by the relational query builder"})}buildRqbColumn(e,t,r){if(H(t,Pt)){let n=m`${e}.${m.identifier(t.name)}`;switch(t.columnType){case"SQLiteBigInt":case"SQLiteBlobJson":case"SQLiteBlobBuffer":return m`hex(${n}) as ${m.identifier(r)}`;case"SQLiteNumeric":case"SQLiteNumericNumber":case"SQLiteNumericBigInt":return m`cast(${n} as text) as ${m.identifier(r)}`;case"SQLiteCustomColumn":return m`${t.jsonSelectIdentifier(n,m)} as ${m.identifier(r)}`;default:return m`${n} as ${m.identifier(r)}`}}return m`${e}.${H(t,Ae.Aliased)?m.identifier(t.fieldAlias):Lu(t)?m.identifier(r):this.nestedSelectionerror()} as ${m.identifier(r)}`}unwrapAllColumns=(e,t)=>m.join(Object.entries(e[ra]).map(([r,n])=>(t.push({key:r,field:n}),this.buildRqbColumn(e,n,r))),m`, `);getSelectedTableColumns=(e,t)=>{let r=[],n=e[ra],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?m.join(n,m`, `):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=[],p=i==="first",y=n===!0?void 0:n,g=a??"",E=c??0;if(!E)t=Di(t,`d${E}`);let S=p?1:y?.limit,x=y?.offset,w=this.buildColumns(t,u,y),_=y?.where&&o?k(Ed(t,y.where,r.relations,e),o):y?.where?Ed(t,y.where,r.relations,e):o,T=y?.orderBy?C1(t,y.orderBy):void 0,b=y?.extras?_1(t,y.extras):void 0;if(b)u.push(...b.selection);let I=y?(()=>{let{with:L}=y;if(!L)return;let Y=Object.entries(L).filter(([Z,ee])=>ee);if(!Y.length)return;return m.join(Y.map(([Z,ee])=>{let ae=r.relations[Z],ne=H(ae,Lw),le=Di(ae.targetTable,`d${E+1}`),ie=ae.throughTable?Di(ae.throughTable,`tr${E}`):void 0,{filter:je,joinCondition:ft}=j_(ae,t,le,ie),yt=ie?m` inner join ${_f(ie)} on ${ft}`:void 0,Ut=this.buildRelationalQuery({table:le,mode:ne?"first":"many",schema:e,queryConfig:ee,tableConfig:e[ae.targetTableName],relationWhere:je,isNested:!0,errorPath:`${g.length?`${g}.`:""}${Z}`,depth:E+1,throughJoin:yt,jsonb:d});u.push({field:le,key:Z,selection:Ut.selection,isArray:!ne,isOptional:(ae.optional??!1)||ee!==!0&&!!ee.where});let _t=m.join(Ut.selection.map((be)=>m`${m.raw(this.escapeString(be.key))}, ${be.selection?m`${d}(${m.identifier(be.key)})`:m.identifier(be.key)}`),m`, `),nt=s?d:m`json`;return ne?m`(select ${nt}_object(${_t}) as ${m.identifier("r")} from (${Ut.sql}) as ${m.identifier("t")}) as ${m.identifier(Z)}`:m`coalesce((select ${nt}_group_array(json_object(${_t})) as ${m.identifier("r")} from (${Ut.sql}) as ${m.identifier("t")}), ${d}_array()) as ${m.identifier(Z)}`}),m`, `)})():void 0,O=[w,b?.sql,I].filter((L)=>L!==void 0);if(!O.length)throw new $u({message:`No fields selected for table "${r.name}"${g?` ("${g}")`:""}`});return{sql:m`select ${m.join(O,m`, `)} from ${_f(t)}${l}${m` where ${_}`.if(_)}${m` order by ${T}`.if(T)}${m` limit ${S}`.if(S!==void 0)}${m` offset ${x}`.if(x!==void 0)}`,selection:u}}},aee=class extends $w{static[R]="SQLiteSyncDialect";migrate(e,t,r){let n=r===void 0?"__drizzle_migrations":typeof r==="string"?"__drizzle_migrations":r.migrationsTable??"__drizzle_migrations",{newDb:o}=iee(n,t,e);if(o){let a=m`
|
|
771
|
+
CREATE TABLE IF NOT EXISTS ${m.identifier(n)} (
|
|
772
|
+
id INTEGER PRIMARY KEY,
|
|
773
|
+
hash text NOT NULL,
|
|
774
|
+
created_at numeric,
|
|
775
|
+
name text,
|
|
776
|
+
applied_at TEXT
|
|
777
|
+
)`;t.run(a)}let i=t.all(m`SELECT id, hash, created_at, name FROM ${m.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(m`insert into ${m.identifier(n)} ("hash", "created_at", "name", "applied_at") values(${a.hash}, ${a.folderMillis}, ${a.name}, ${new Date().toISOString()})`);return}let s=Bw({localMigrations:e,dbMigrations:i});t.run(m`BEGIN`);try{for(let a of s){for(let c of a.sql)t.run(m.raw(c));t.run(m`INSERT INTO ${m.identifier(n)} ("hash", "created_at", "name", "applied_at") values(${a.hash}, ${a.folderMillis}, ${a.name}, ${new Date().toISOString()})`)}t.run(m`COMMIT`)}catch(a){throw t.run(m`ROLLBACK`),a}}},cee=class extends $w{static[R]="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 see(n,t,e);if(o){let a=m`
|
|
778
|
+
CREATE TABLE IF NOT EXISTS ${m.identifier(n)} (
|
|
779
|
+
id INTEGER PRIMARY KEY,
|
|
780
|
+
hash text NOT NULL,
|
|
781
|
+
created_at numeric,
|
|
782
|
+
name text,
|
|
783
|
+
applied_at TEXT
|
|
784
|
+
)
|
|
785
|
+
`;await t.session.run(a)}let i=await t.session.all(m`SELECT id, hash, created_at, name FROM ${m.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(m`insert into ${m.identifier(n)} ("hash", "created_at", "name", "applied_at") values(${a.hash}, ${a.folderMillis}, ${a.name}, ${new Date().toISOString()})`);return}let s=Bw({localMigrations:e,dbMigrations:i});await t.session.transaction(async(a)=>{for(let c of s){for(let l of c.sql)await a.run(m.raw(l));await a.run(m`insert into ${m.identifier(n)} ("hash", "created_at", "name", "applied_at") values(${c.hash}, ${c.folderMillis}, ${c.name}, ${new Date().toISOString()})`)}})}};var zy=class{static[R]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=H(e,$w)?e:void 0,this.dialectConfig=H(e,$w)?void 0:e}$with=(e,t)=>{let r=this;return{as:(o)=>{if(typeof o==="function")o=o(r);return new Proxy(new f_(o.getSQL(),t??("getSelectedFields"in o?o.getSelectedFields()??{}:{}),e,!0),new Xn({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(o){return new Pc({fields:o??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function n(o){return new Pc({fields:o??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:n}}select(e){return new Pc({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Pc({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new aee(this.dialectConfig);return this.dialect}};var O1=class{static[R]="SQLiteViewBuilderCore";constructor(e){this.name=e}config={}},lee=class extends O1{static[R]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new zy);let t=new Xn({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new H_({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}},dee=class extends O1{static[R]="SQLiteManualViewBuilder";columns;constructor(e,t,r){super(e);this.columns=x_(A_(e,t,void 0,void 0,r))}existing(){return new Proxy(new H_({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new Xn({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new H_({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new Xn({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}},H_=class extends wf{static[R]="SQLiteView";constructor({config:e}){super(e)}};function uee(e){return(t,r)=>{if(r)return new dee(t,r,e);return new lee(t)}}var Ky=uee(void 0);var fee=class{static[R]="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 pee(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new N1(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new pee(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new N1(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}},N1=class extends Oo{static[R]="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)=>B_(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()}},pee=class extends N1{static[R]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}};var W_=class e extends Ae{static[R]="SQLiteCountBuilder";dialect;session;static buildCount(t,r,n){let o=m`select count(*) from ${t}${m` where ${r}`.if(r)}`;return n?m`(${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)}},mee=class extends W_{static[R]="SQLiteSyncCountBuilder";sync(e){return this.executeRaw(e)}};v_(W_,[Oo]);var hee=class{static[R]="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 yee(this.schema,this.table,this.tableConfig,this.dialect,this.session,e??!0,"many",this.rowMode,this.forbidJsonb):new F1(this.schema,this.table,this.tableConfig,this.dialect,this.session,e??!0,"many",this.rowMode,this.forbidJsonb)}findFirst(e){return this.mode==="sync"?new yee(this.schema,this.table,this.tableConfig,this.dialect,this.session,e??!0,"first",this.rowMode,this.forbidJsonb):new F1(this.schema,this.table,this.tableConfig,this.dialect,this.session,e??!0,"first",this.rowMode,this.forbidJsonb)}},F1=class extends Oo{static[R]="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?m`json`:m`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",I1({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?m`json`:m`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=m`select json_object(${m.join(t.selection.map((r)=>m`${m.raw(this.dialect.escapeString(r.key))}, ${r.selection?m`${e}(${m.identifier(r.key)})`:m.identifier(r.key)}`),m`, `)}) as ${m.identifier("r")} from (${t.sql}) as ${m.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()}},yee=class extends F1{static[R]="SQLiteSyncRelationalQueryV2";sync(){return this.executeRaw()}};var qw=class extends Oo{static[R]="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 V_=class extends Oo{static[R]="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[xe.Symbol.Columns],new Xn({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[ui.Symbol.Columns]){return this.config.returning=Rc(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:vl(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 z_=class{static[R]="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[xe.Symbol.Columns];for(let i of Object.keys(r)){let s=r[i];n[i]=H(s,Ae)?s:new ki(s,o[i])}return n});return new U1(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new zy):e;if(!H(t,Ae)&&!Fw(this.table[ra],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 U1(this.table,t,this.session,this.dialect,this.withList,!0)}},U1=class extends Oo{static[R]="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[ui.Symbol.Columns]){return this.config.returning=Rc(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(m` on conflict do nothing`);else{let t=Array.isArray(e.target)?m`${e.target}`:m`${[e.target]}`,r=e.where?m` where ${e.where}`:m``;this.config.onConflict.push(m` 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?m` where ${e.where}`:void 0,r=e.targetWhere?m` where ${e.targetWhere}`:void 0,n=e.setWhere?m` where ${e.setWhere}`:void 0,o=Array.isArray(e.target)?m`${e.target}`:m`${[e.target]}`,i=this.dialect.buildUpdateSet(this.config.table,S_(this.config.table,e.set));return this.config.onConflict.push(m` 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:vl(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 K_=class{static[R]="SQLiteUpdateBuilder";constructor(e,t,r,n){this.table=e,this.session=t,this.dialect=r,this.withList=n}set(e){return new gee(this.table,S_(this.table,e),this.session,this.dialect,this.withList)}},gee=class extends Oo{static[R]="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=Uw(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?H(t,ui)?t[xe.Symbol.Columns]:H(t,pn)?t._.selectedFields:H(t,wf)?t[dr].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[xe.Symbol.Columns],new Xn({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),o&&new Proxy(o,new Xn({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[xe.Symbol.Columns],new Xn({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[ui.Symbol.Columns]){return this.config.returning=Rc(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:vl(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 G_=class{static[R]="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 fee(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 hee(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 zy(r.dialect));return new Proxy(new f_(o.getSQL(),t??("getSelectedFields"in o?o.getSelectedFields()??{}:{}),e,!0),new Xn({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return this.resultKind==="async"?new W_({source:e,filters:t,session:this.session,dialect:this.dialect}):new mee({source:e,filters:t,session:this.session,dialect:this.dialect})}with(...e){let t=this;function r(a){return new Pc({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function n(a){return new Pc({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function o(a){return new K_(a,t.session,t.dialect,e)}function i(a){return new z_(a,t.session,t.dialect,e)}function s(a){return new V_(a,t.session,t.dialect,e)}return{select:r,selectDistinct:n,update:o,insert:i,delete:s}}select(e){return new Pc({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Pc({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new K_(e,this.session,this.dialect)}$cache;insert(e){return new z_(e,this.session,this.dialect)}delete(e){return new V_(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?m.raw(e):e.getSQL();if(this.resultKind==="async")return new qw(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"?m.raw(e):e.getSQL();if(this.resultKind==="async")return new qw(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"?m.raw(e):e.getSQL();if(this.resultKind==="async")return new qw(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"?m.raw(e):e.getSQL();if(this.resultKind==="async")return new qw(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 See=class{static[R]="Cache"},jw=class extends See{static[R]="NoopCache";strategy(){return"all"}async get(e){}async put(e,t,r,n){}async onMutate(e){}};async function Q_(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 vee=class extends Oo{static[R]="ExecuteResultSync";constructor(e){super();this.resultCb=e}async execute(){return this.resultCb()}sync(){return this.resultCb()}},M1=class{static[R]="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||H(this.cache,jw)||this.queryMetadata===void 0)try{return await r()}catch(n){throw new Hy(e,t,n)}if(this.cacheConfig&&!this.cacheConfig.enabled)try{return await r()}catch(n){throw new Hy(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 Hy(e,t,n)}if(!this.cacheConfig)try{return await r()}catch(n){throw new Hy(e,t,n)}if(this.queryMetadata.type==="select"){let n=await this.cache.get(this.cacheConfig.tag??await Q_(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 Hy(e,t,i)}return await this.cache.put(this.cacheConfig.tag??await Q_(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 Hy(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 vee(()=>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)}}},L1=class{static[R]="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 $u({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")}},B1=class extends G_{static[R]="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 WZ}};var hCe=class{static[R]="ConsoleLogWriter";write(e){console.log(e)}},xee=class{static[R]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new hCe}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}`)}},Eee=class{static[R]="NoopLogger";logQuery(){}};var wee=class extends L1{static[R]="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 Eee,this.cache=i.cache??new jw}prepareQuery(e,t,r,n,o,i){return new bee(this.client,e,this.logger,this.cache,o,i,t,r,this.options.useJitMappers,n)}prepareRelationalQuery(e,t,r,n,o){return new bee(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 gCe("async",this.dialect,this,this.relations,this.schema,void 0,!0);await this.run(m.raw(`begin${t?.behavior?" "+t.behavior:""}`));try{let n=await e(r);return await this.run(m`commit`),n}catch(n){throw await this.run(m`rollback`),n}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}},gCe=class e extends B1{static[R]="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(m.raw(`savepoint ${r}`));try{let o=await t(n);return await this.session.run(m.raw(`release savepoint ${r}`)),o}catch(o){throw await this.session.run(m.raw(`rollback to savepoint ${r}`)),o}}},bee=class extends M1{static[R]="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=Bu(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??q_(this.rqbConfig))(e):this.customResultMapper(e)}if(this.customResultMapper)return this.customResultMapper(e);return this.useJitMappers?(this.jitMapper=this.jitMapper??p1(this.fields,this.joinsNotNullableMap))(e):e.map((r)=>u1(this.fields,r,this.joinsNotNullableMap))}async all(e){if(this.isRqbV2Query)return this.allRqbV2(e);let{query:t,logger:r,client:n}=this,o=Bu(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=Bu(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=Bu(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=Bu(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??q_(this.rqbConfig))([JSON.parse(r)]):this.customResultMapper([JSON.parse(r)]);if(this.customResultMapper)return this.customResultMapper([e]);return this.useJitMappers?(this.jitMapper=this.jitMapper??p1(this.fields,this.joinsNotNullableMap))([r])[0]:u1(this.fields,r,this.joinsNotNullableMap)}async values(e){let t=Bu(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 Tee=class extends G_{static[R]="SqliteRemoteDatabase";async batch(e){return this.session.batch(e)}};function $1(e,t,r){let n=new cee,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 xee;else if(a.logger!==!1)o=a.logger,i=a.cache}let c;if(a.schema){let u=qZ(a.schema,HZ);c={fullSchema:a.schema,schema:u.tables,tableNamesMap:u.tableNamesMap}}let l=a.relations??{},d=new Tee("async",n,new wee(e,n,l,c,s,{logger:o,cache:i,useJitMappers:T7(a.jit)}),l,c,!0);if(d.$cache=i,d.$cache)d.$cache.invalidate=i?.onMutate;return d}import*as xCe from"effect/Context";import*as Pee from"effect/Effect";import*as Cee from"effect/Layer";Pg();Hw();import*as fi from"effect/Effect";import*as Aee from"effect/Effectable";import*as Iee from"effect/Runtime";var Ww=void 0,vCe={...Aee.CommitPrototype,commit(){return fi.runtime().pipe(fi.flatMap((e)=>fi.tryPromise({try:()=>{let t=Ww;Ww=e;let r=this.execute();return Ww=t,r},catch:(t)=>new ia({cause:t,message:"Failed to execute QueryPromise"})})))}},q1=(e)=>{if(fi.EffectTypeId in e)return;Object.assign(e,vCe)},Ree=fi.gen(function*(){let e=yield*Hs,t=yield*fi.runtime();return(r,n,o)=>{let i=Iee.runPromise(Ww?Ww:t),s=e.unsafe(r,n);if(o==="execute")return i(fi.either(fi.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=fi.map(a,(c)=>c[0]??[]);return i(fi.either(fi.map(a,(c)=>({rows:c})))).then((c)=>{if(c._tag==="Left")throw c.left.cause;return c.right})}});var _ee=(e)=>Pee.gen(function*(){return $1(yield*Ree,e)});q1(Oo.prototype);q1(Sv.prototype);function j1(e){return m`count(${e||m.raw("*")})`.mapWith(Number)}import{Context as y_e,Effect as h_e,Layer as g_e}from"effect";var zr={};cq(zr,{calendarPeriod:()=>sa,calendarPeriodRelations:()=>l_e,completedJob:()=>aa,dateException:()=>xl,dateExceptionRelations:()=>d_e,delegation:()=>$t,delegationHistory:()=>Oi,delegationHistoryRelations:()=>XCe,delegationRelations:()=>JCe,documentStore:()=>Gt,documentStoreRelations:()=>p_e,externalParticipant:()=>yi,externalParticipantRelations:()=>qCe,file:()=>Vn,fileRelations:()=>f_e,flow:()=>J,flowRelations:()=>$Ce,holidayInstance:()=>Wn,holidayInstanceRelations:()=>u_e,invitation:()=>D,invitationRelations:()=>o_e,invitationRole:()=>Je,invitationRoleRelations:()=>s_e,jobQueue:()=>lt,oauthClient:()=>yr,oauthClientRelations:()=>a_e,oauthProvider:()=>Ft,oauthStorage:()=>Pn,orgUnit:()=>G,orgUnitRelations:()=>OCe,passkeyCredential:()=>St,passkeyCredentialRelations:()=>GCe,permittedClientEmail:()=>Rs,permittedClientEmailRelations:()=>n_e,permittedClientRole:()=>Ji,permittedClientRoleRelations:()=>r_e,permittedRole:()=>mi,permittedRoleRelations:()=>t_e,phase:()=>mo,phaseRelations:()=>UCe,process:()=>te,processExecution:()=>K,processExecutionRelations:()=>HCe,processItsActiveProcesses:()=>Df,processItsNoDrafts:()=>DCe,processItsStartStep:()=>kf,processRelations:()=>NCe,processState:()=>q,processStateItsIsDraft:()=>ca,processStateRelations:()=>jCe,providerUser:()=>N,providerUserRelations:()=>QCe,providerUserRole:()=>xt,providerUserRoleRelations:()=>ZCe,publicCompletionInvitationAttempt:()=>Et,publicCompletionInvitationAttemptRelations:()=>VCe,registrationSession:()=>yo,registrationSessionRelations:()=>i_e,role:()=>F,roleRelations:()=>FCe,roleResponsibility:()=>fn,roleResponsibilityRelations:()=>MCe,scheduledFlow:()=>ot,scheduledFlowRelations:()=>zCe,secretGeneration:()=>ct,secretGenerationRelations:()=>YCe,step:()=>M,stepDocumentStore:()=>to,stepDocumentStoreRelations:()=>m_e,stepItsCanStartProcess:()=>_c,stepRelations:()=>LCe,stepSupportingRole:()=>Rn,stepSupportingRoleRelations:()=>BCe,toDo:()=>C,toDoRelations:()=>WCe,user:()=>oe,userRelations:()=>KCe,userSettings:()=>Er,userSettingsRelations:()=>e_e,weeklySchedule:()=>ho,weeklyScheduleRelations:()=>c_e});import{DateTime as Nee}from"effect";import J_ from"crypto";function Vw(e){if(!Iv(e))throw Error("Parameter was not an error")}function Iv(e){return!!e&&typeof e==="object"&&bCe(e)==="[object Error]"||e instanceof Error}function bCe(e){return Object.prototype.toString.call(e)}var wCe="Layerr";function H1(){return wCe}function kee(e){let t,r="";if(e.length===0)t={};else if(Iv(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 Cc extends Error{constructor(e,t){let r=[...arguments],{options:n,shortMessage:o}=kee(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=H1();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(Vw(e),!e._cause)return null;return Iv(e._cause)?e._cause:null}static fullStack(e){Vw(e);let t=Cc.cause(e);if(t)return`${e.stack}
|
|
786
|
+
caused by: ${Cc.fullStack(t)}`;return e.stack??""}static info(e){Vw(e);let t={},r=Cc.cause(e);if(r)Object.assign(t,Cc.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 Oee="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Kw=32,Dee=281474976710655,TCe=10,ACe=16,zw=Object.freeze({source:"ulid"});function ICe(e){let t=e||RCe(),r=t&&(t.crypto||t.msCrypto)||(typeof J_<"u"?J_: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(J_?.randomBytes)return()=>J_.randomBytes(1).readUInt8()/255;throw new Cc({info:{code:"PRNG_DETECT",...zw}},"Failed to find a reliable PRNG")}function RCe(){if(_Ce())return self;if(typeof window<"u")return window;if(typeof global<"u")return global;if(typeof globalThis<"u")return globalThis;return null}function PCe(e,t){let r="";for(;e>0;e--)r=kCe(t)+r;return r}function CCe(e,t){if(isNaN(e))throw new Cc({info:{code:"ENC_TIME_NAN",...zw}},`Time must be a number: ${e}`);else if(e>Dee)throw new Cc({info:{code:"ENC_TIME_SIZE_EXCEED",...zw}},`Cannot encode a time larger than ${Dee}: ${e}`);else if(e<0)throw new Cc({info:{code:"ENC_TIME_NEG",...zw}},`Time must be positive: ${e}`);else if(Number.isInteger(e)===!1)throw new Cc({info:{code:"ENC_TIME_TYPE",...zw}},`Time must be an integer: ${e}`);let r,n="";for(let o=t;o>0;o--)r=e%Kw,n=Oee.charAt(r)+n,e=(e-r)/Kw;return n}function _Ce(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function kCe(e){let t=Math.floor(e()*Kw);if(t===Kw)t=Kw-1;return Oee.charAt(t)}function Nt(e,t){let r=t||ICe(),n=isNaN(e)?Date.now():e;return CCe(n,TCe)+PCe(ACe,r)}var In=$y({dataType(){return"text collate nocase"}}),Ba=$y({dataType(){return"text"},toDriver(e){return JSON.stringify(e)},fromDriver(e){return e==null?{}:JSON.parse(e)}}),se=$y({dataType(){return"real"},toDriver(e){return Nee.toEpochMillis(e)/86400000+2440587.5},fromDriver(e){let t=(e-2440587.5)*86400000;return Nee.unsafeMake(t)}}),G=Dt("pf_org_unit",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`ou-${Nt()}`),name:In("name").notNull(),orgUnitLevel:P("org_unit_level",{length:64}).notNull(),parentOrgUnitId:P("parent_org_unit",{length:41}).references(()=>G.id),path:P("path",{length:2048}).notNull(),acronym:In("acronym"),timezone:P("timezone",{length:64}).notNull().default("UTC"),startDayOfWeek:Re("start_day_of_week").default(0),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({pathidxIdx:Xt("pf_org_unit_pathidx_idx").on(e.path).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_org_unit_updated_at_id_idx").on(e.updatedAt,e.id),nameLengthCheck:Qi("name_length_check",m.raw('length("pf_org_unit"."name") <= 1024')),acronymLengthCheck:Qi("acronym_length_check",m.raw('length("pf_org_unit"."acronym") <= 64'))})),te=Dt("pf_process",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`prc-${Nt()}`),orgUnitId:P("org_unit_id",{length:41}).notNull().references(()=>G.id),name:In("name").notNull(),path:P("path",{length:2048}).notNull(),purpose:In("purpose").notNull(),slaValue:Re("sla_value"),slaUnit:P("sla_unit",{length:16}),slaWarning:Re("sla_warning"),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({pathidxIdx:Xt("pf_process_pathidx_idx").on(e.path).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_process_updated_at_id_idx").on(e.updatedAt,e.id),nameLengthCheck:Qi("name_length_check",m.raw('length("pf_process"."name") <= 1024'))})),F=Dt("pf_role",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`role-${Nt()}`),orgUnitId:P("org_unit_id",{length:41}).notNull().references(()=>G.id),name:In("name").notNull(),path:P("path",{length:2048}).notNull(),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({pathidxIdx:Xt("pf_role_pathidx_idx").on(e.path).where(m`_deleted = 0`),orgunitunameidxIdx:Xt("pf_role_orgunitunameidx_idx").on(e.orgUnitId,e.name).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_role_updated_at_id_idx").on(e.updatedAt,e.id),nameLengthCheck:Qi("name_length_check",m.raw('length("pf_role"."name") <= 1024'))})),mo=Dt("pf_phase",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`ph-${Nt()}`),processId:P("process_id",{length:41}).notNull().references(()=>te.id),name:In("name").notNull(),path:P("path",{length:2048}).notNull(),phaseOrder:Re("phase_order").notNull(),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({pathidxIdx:Xt("pf_phase_pathidx_idx").on(e.path).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_phase_updated_at_id_idx").on(e.updatedAt,e.id),nameLengthCheck:Qi("name_length_check",m.raw('length("pf_phase"."name") <= 1024'))})),fn=Dt("pf_role_responsibility",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`rr-${Nt()}`),processId:P("process_id",{length:41}).notNull().references(()=>te.id),roleId:P("role_id",{length:41}).notNull().references(()=>F.id),responsibility:In("responsibility").notNull(),responsibilityOrder:Re("responsibility_order").notNull(),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({processroleidxIdx:Xt("pf_role_responsibility_processroleidx_idx").on(e.processId,e.roleId).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_role_responsibility_updated_at_id_idx").on(e.updatedAt,e.id)})),M=Dt("pf_step",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`step-${Nt()}`),name:In("name").notNull(),path:P("path",{length:2048}).notNull(),purpose:In("purpose").notNull(),processId:P("process_id",{length:41}).notNull().references(()=>te.id),roleId:P("role_id",{length:41}).references(()=>F.id),formFields:Re("form_fields"),phaseId:P("phase_id",{length:41}).references(()=>mo.id),slaValue:Re("sla_value"),slaUnit:P("sla_unit",{length:16}),slaWarning:Re("sla_warning"),hasForEach:Re("has_for_each",{mode:"boolean"}).notNull().default(!1),embedded:Re("embedded",{mode:"boolean"}).notNull().default(!1),retryLimit:Re("retry_limit"),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({pathidxIdx:Xt("pf_step_pathidx_idx").on(e.path).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_step_updated_at_id_idx").on(e.updatedAt,e.id),nameLengthCheck:Qi("name_length_check",m.raw('length("pf_step"."name") <= 1024'))})),Rn=Dt("pf_step_supporting_role",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`ssr-${Nt()}`),stepId:P("step_id",{length:41}).notNull().references(()=>M.id),roleId:P("role_id",{length:41}).notNull().references(()=>F.id),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({steproleidxIdx:Xt("pf_step_supporting_role_steproleidx_idx").on(e.stepId,e.roleId).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_step_supporting_role_updated_at_id_idx").on(e.updatedAt,e.id)})),J=Dt("pf_flow",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`flow-${Nt()}`),flowKey:P("flow_key",{length:128}).notNull(),sourceStepId:P("source_step",{length:41}).notNull().references(()=>M.id),targetStepId:P("target_step",{length:41}).notNull().references(()=>M.id),condition:In("condition"),schedule:In("schedule"),fallbackBranch:Re("fallback_branch",{mode:"boolean"}).notNull().default(!1),errorBranch:Re("error_branch",{mode:"boolean"}).notNull().default(!1),errorTags:Ba("error_tags"),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({sourcetargetidxIdx:gt("pf_flow_sourcetargetidx_idx").on(e.sourceStepId,e.targetStepId).where(m`_deleted = 0`),flowkeyidxIdx:Xt("pf_flow_flowkeyidx_idx").on(e.flowKey).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_flow_updated_at_id_idx").on(e.updatedAt,e.id)})),yi=Dt("pf_external_participant",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`xp-${Nt()}`),email:P("email",{length:320}).notNull(),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({emailidxIdx:Xt("pf_external_participant_emailidx_idx").on(e.email).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_external_participant_updated_at_id_idx").on(e.updatedAt,e.id)})),q=Dt("pf_process_state",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`pst-${Nt()}`),processId:P("process_id",{length:41}).notNull().references(()=>te.id),startStepId:P("start_step",{length:41}).notNull().references(()=>M.id),state:Ba("state").notNull(),startedByUserId:P("started_by_user",{length:41}).references(()=>oe.id),startedByExternalParticipantId:P("started_by_external_participant",{length:41}).references(()=>yi.id),startedByRoleId:P("started_by_role",{length:41}).references(()=>F.id),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({updatedAtIdIdx:gt("pf_process_state_updated_at_id_idx").on(e.updatedAt,e.id),singleStarterCheck:Qi("single_starter_check",m`${e.startedByUserId} is null or ${e.startedByExternalParticipantId} is null`)})),K=Dt("pf_process_execution",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`pex-${Nt()}`),withoutWaiting:Re("without_waiting",{mode:"boolean"}).notNull().default(!1),processStateId:P("process_state_id",{length:41}).notNull().references(()=>q.id),finishedAt:se("finished_at"),businessDuration:Re("business_duration"),abandonedAt:se("abandoned_at"),abandonedReason:In("abandoned_reason"),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({updatedAtIdIdx:gt("pf_process_execution_updated_at_id_idx").on(e.updatedAt,e.id)})),C=Dt("pf_to_do",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`todo-${Nt()}`),processExecutionId:P("process_execution_id",{length:41}).notNull().references(()=>K.id),flowId:P("flow_id",{length:41}).notNull().references(()=>J.id),completedByUserId:P("completed_by_user",{length:41}).references(()=>oe.id),completedByExternalParticipantId:P("completed_by_external_participant",{length:41}).references(()=>yi.id),assignedToProviderUserId:P("assigned_to_provider_user",{length:41}).references(()=>N.id),businessDuration:Re("business_duration"),slaTargetAt:se("sla_target_at"),slaWarningAt:se("sla_warning_at"),failureReason:In("failure_reason"),correctionRequiredAt:se("correction_required_at"),correctionFailureReason:In("correction_failure_reason"),correctionInvitationAttemptId:P("correction_invitation_attempt_id",{length:41}),itemData:Ba("item_data"),barrierScheduledFlowId:P("barrier_scheduled_flow_id",{length:41}),completedByRoleId:P("completed_by_role",{length:41}).references(()=>F.id),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({updatedAtIdIdx:gt("pf_to_do_updated_at_id_idx").on(e.updatedAt,e.id),singleCompleterCheck:Qi("single_completer_check",m`${e.completedByUserId} is null or ${e.completedByExternalParticipantId} is null`)})),Et=Dt("pf_public_completion_invitation_attempt",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`pcia-${Nt()}`),toDoId:P("to_do_id",{length:41}).notNull().references(()=>C.id),email:P("email",{length:320}).notNull(),providerMessageId:P("provider_message_id",{length:256}),providerSentTo:In("provider_sent_to"),deliveryStatus:P("delivery_status",{length:32}),deliveryEventId:P("delivery_event_id",{length:256}),deliveryFailureKind:P("delivery_failure_kind",{length:64}),deliveryFailureReason:In("delivery_failure_reason"),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({todoidxIdx:gt("pf_public_completion_invitation_attempt_todoidx_idx").on(e.toDoId).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_public_completion_invitation_attempt_updated_at_id_idx").on(e.updatedAt,e.id)})),ot=Dt("pf_scheduled_flow",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`sf-${Nt()}`),processExecutionId:P("process_execution_id",{length:41}).notNull().references(()=>K.id),sourceStepId:P("source_step",{length:41}).notNull().references(()=>M.id),targetStepId:P("target_step",{length:41}).references(()=>M.id),scheduledAt:se("scheduled_at"),forEachBarrier:Re("for_each_barrier",{mode:"boolean"}).notNull().default(!1),completedByRoleId:P("completed_by_role",{length:41}).references(()=>F.id),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({updatedAtIdIdx:gt("pf_scheduled_flow_updated_at_id_idx").on(e.updatedAt,e.id)})),oe=Dt("pf_user",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`usr-${Nt()}`),provider:P("provider",{length:128}).notNull(),sub:P("sub",{length:256}).notNull(),lastLoggedIn:se("last_logged_in").notNull(),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({uniquesubIdx:Xt("pf_user_uniquesub_idx").on(e.provider,e.sub).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_user_updated_at_id_idx").on(e.updatedAt,e.id)})),St=Dt("pf_passkey_credential",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`pkc-${Nt()}`),userId:P("user_id",{length:41}).notNull().references(()=>oe.id),passkeyCredentialId:P("passkey_credential_id",{length:2048}).notNull(),passkeyPublicKey:P("passkey_public_key",{length:2048}).notNull(),signatureCounter:P("signature_counter",{length:16}).notNull(),passkeyTransports:Ba("passkey_transports"),passkeyName:P("passkey_name",{length:128}),passkeyLastUsedAt:se("passkey_last_used_at"),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({credentialidxIdx:Xt("pf_passkey_credential_credentialidx_idx").on(e.passkeyCredentialId).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_passkey_credential_updated_at_id_idx").on(e.updatedAt,e.id)})),N=Dt("pf_provider_user",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`pu-${Nt()}`),userId:P("user_id",{length:41}).notNull().references(()=>oe.id),email:P("email",{length:320}).notNull(),name:In("name").notNull(),firstName:In("first_name").notNull(),lastName:In("last_name").notNull(),picture:P("picture",{length:1024}).notNull(),locale:P("locale",{length:35}).notNull(),orgUnitId:P("org_unit_id",{length:41}).notNull().references(()=>G.id),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({emailidxIdx:Xt("pf_provider_user_emailidx_idx").on(e.email).where(m`_deleted = 0`),userUniqueIdx:Xt("pf_provider_user_user_unique_idx").on(e.userId).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_provider_user_updated_at_id_idx").on(e.updatedAt,e.id),nameLengthCheck:Qi("name_length_check",m.raw('length("pf_provider_user"."name") <= 1024')),firstNameLengthCheck:Qi("first_name_length_check",m.raw('length("pf_provider_user"."first_name") <= 128')),lastNameLengthCheck:Qi("last_name_length_check",m.raw('length("pf_provider_user"."last_name") <= 128'))})),$t=Dt("pf_delegation",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`dlg-${Nt()}`),ownerProviderUserId:P("owner_provider_user",{length:41}).notNull().references(()=>N.id),delegationName:P("delegation_name",{length:128}).notNull(),activeDelegationName:P("active_delegation_name",{length:128}),secretRevokedAt:se("secret_revoked_at"),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({ownernameidxIdx:Xt("pf_delegation_ownernameidx_idx").on(e.ownerProviderUserId,e.activeDelegationName).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_delegation_updated_at_id_idx").on(e.updatedAt,e.id)})),ct=Dt("pf_secret_generation",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`dsg-${Nt()}`),delegationId:P("delegation_id",{length:41}).notNull().references(()=>$t.id),secretVerifier:P("secret_verifier",{length:64}).notNull(),secretIssuedAt:se("secret_issued_at").notNull(),secretExpiresAt:se("secret_expires_at").notNull(),secretRevokedAt:se("secret_revoked_at"),secretLastUsedAt:se("secret_last_used_at"),parentSecretGenerationId:P("parent_secret_generation",{length:41}).references(()=>ct.id),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({delegationidxIdx:gt("pf_secret_generation_delegationidx_idx").on(e.delegationId).where(m`_deleted = 0`),verifieridxIdx:Xt("pf_secret_generation_verifieridx_idx").on(e.secretVerifier).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_secret_generation_updated_at_id_idx").on(e.updatedAt,e.id)})),Oi=Dt("pf_delegation_history",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`dgh-${Nt()}`),delegationId:P("delegation_id",{length:41}).notNull().references(()=>$t.id),secretGenerationId:P("secret_generation_id",{length:41}).notNull().references(()=>ct.id),actorProviderUserId:P("actor_provider_user",{length:41}).notNull().references(()=>N.id),delegationEvent:P("delegation_event",{length:32}).notNull(),secretIssuedAt:se("secret_issued_at").notNull(),oldDelegationName:P("old_delegation_name",{length:128}),newDelegationName:P("new_delegation_name",{length:128}),actorDelegationId:P("actor_delegation",{length:41}).references(()=>$t.id),actorSecretGenerationId:P("actor_secret_generation",{length:41}).references(()=>ct.id),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({updatedAtIdIdx:gt("pf_delegation_history_updated_at_id_idx").on(e.updatedAt,e.id)})),xt=Dt("pf_provider_user_role",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`pur-${Nt()}`),providerUserId:P("provider_user_id",{length:41}).notNull().references(()=>N.id),roleId:P("role_id",{length:41}).notNull().references(()=>F.id),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({provideruserroleidxIdx:Xt("pf_provider_user_role_provideruserroleidx_idx").on(e.providerUserId,e.roleId).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_provider_user_role_updated_at_id_idx").on(e.updatedAt,e.id)})),Er=Dt("pf_user_settings",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`us-${Nt()}`),userId:P("user_id",{length:41}).notNull().references(()=>oe.id),notificationPreference:Ba("notification_preference").notNull(),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({userUniqueIdx:Xt("pf_user_settings_user_unique_idx").on(e.userId).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_user_settings_updated_at_id_idx").on(e.updatedAt,e.id)})),mi=Dt("pf_permitted_role",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`pr-${Nt()}`),providerUserId:P("provider_user_id",{length:41}).notNull().references(()=>N.id),roleId:P("role_id",{length:41}).notNull().references(()=>F.id),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({provideruserroleidxIdx:Xt("pf_permitted_role_provideruserroleidx_idx").on(e.providerUserId,e.roleId).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_permitted_role_updated_at_id_idx").on(e.updatedAt,e.id)})),Ji=Dt("pf_permitted_client_role",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`pcr-${Nt()}`),oauthClientId:P("oauth_client_id",{length:41}).notNull().references(()=>yr.id),roleId:P("role_id",{length:41}).notNull().references(()=>F.id),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({oauthclientroleidxIdx:Xt("pf_permitted_client_role_oauthclientroleidx_idx").on(e.oauthClientId,e.roleId).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_permitted_client_role_updated_at_id_idx").on(e.updatedAt,e.id)})),Rs=Dt("pf_permitted_client_email",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`pce-${Nt()}`),oauthClientId:P("oauth_client_id",{length:41}).notNull().references(()=>yr.id),email:P("email",{length:320}).notNull(),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({oauthclientemailidxIdx:Xt("pf_permitted_client_email_oauthclientemailidx_idx").on(e.oauthClientId,e.email).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_permitted_client_email_updated_at_id_idx").on(e.updatedAt,e.id)})),D=Dt("pf_invitation",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`inv-${Nt()}`),invitationId:P("invitation_id",{length:128}).notNull(),email:P("email",{length:320}).notNull(),invitationStatus:P("invitation_status",{length:32}).notNull().default("pending"),invitationSource:P("invitation_source",{length:32}).notNull().default("legacy"),invitationPendingEmail:P("invitation_pending_email",{length:320}),invitationAcceptedAt:se("invitation_accepted_at"),invitationAcceptedByProvider:P("invitation_accepted_by_provider",{length:64}),invitationAcceptedBySubject:P("invitation_accepted_by_subject",{length:256}),acceptedByProviderUserId:P("accepted_by_provider_user",{length:41}).references(()=>N.id),invitationLegacyClosedAt:se("invitation_legacy_closed_at"),invitationLegacyClosureReason:P("invitation_legacy_closure_reason",{length:128}),registrationTokenHash:P("registration_token_hash",{length:64}),registrationEncryptionVersion:Re("registration_encryption_version"),registrationEncryptionNonce:P("registration_encryption_nonce",{length:24}),registrationAuthenticationTag:P("registration_authentication_tag",{length:32}),registrationEncryptedToken:In("registration_encrypted_token"),registrationLinkExpiresAt:se("registration_link_expires_at"),registrationLinkGeneratedAt:se("registration_link_generated_at"),registrationLinkGeneratedBy:P("registration_link_generated_by",{length:256}),registrationLinkRevealedAt:se("registration_link_revealed_at"),registrationLinkRevealedBy:P("registration_link_revealed_by",{length:256}),registrationLinkRevokedAt:se("registration_link_revoked_at"),registrationLinkRevokedBy:P("registration_link_revoked_by",{length:256}),registrationLinkGeneration:Re("registration_link_generation"),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({emailidxIdx:gt("pf_invitation_emailidx_idx").on(e.email).where(m`_deleted = 0`),statusidxIdx:gt("pf_invitation_statusidx_idx").on(e.invitationStatus).where(m`_deleted = 0`),invitationididxIdx:Xt("pf_invitation_invitationididx_idx").on(e.invitationId).where(m`_deleted = 0`),pendingemailidxIdx:Xt("pf_invitation_pendingemailidx_idx").on(e.invitationPendingEmail).where(m`_deleted = 0`),registrationtokenhashidxIdx:Xt("pf_invitation_registrationtokenhashidx_idx").on(e.registrationTokenHash).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_invitation_updated_at_id_idx").on(e.updatedAt,e.id)})),yo=Dt("pf_registration_session",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`rgs-${Nt()}`),registrationSessionTokenHash:P("registration_session_token_hash",{length:64}).notNull(),invitationId:P("invitation_id",{length:41}).notNull().references(()=>D.id),registrationLinkGeneration:Re("registration_link_generation").notNull(),registrationSessionExpiresAt:se("registration_session_expires_at").notNull(),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({invitationidxIdx:gt("pf_registration_session_invitationidx_idx").on(e.invitationId).where(m`_deleted = 0`),tokenhashidxIdx:Xt("pf_registration_session_tokenhashidx_idx").on(e.registrationSessionTokenHash).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_registration_session_updated_at_id_idx").on(e.updatedAt,e.id)})),Je=Dt("pf_invitation_role",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`ir-${Nt()}`),invitationId:P("invitation_id",{length:41}).notNull().references(()=>D.id),roleId:P("role_id",{length:41}).notNull().references(()=>F.id),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({invitationroleidxIdx:Xt("pf_invitation_role_invitationroleidx_idx").on(e.invitationId,e.roleId).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_invitation_role_updated_at_id_idx").on(e.updatedAt,e.id)})),Pn=Dt("pf_oauth_storage",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`oas-${Nt()}`),oauthKey:P("oauth_key",{length:2048}).notNull(),keyKind:P("key_kind",{length:64}).notNull(),keyValue:Ba("key_value").notNull(),keyExpiry:se("key_expiry"),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({keyidxIdx:Xt("pf_oauth_storage_keyidx_idx").on(e.oauthKey),updatedAtIdIdx:gt("pf_oauth_storage_updated_at_id_idx").on(e.updatedAt,e.id)})),Ft=Dt("pf_oauth_provider",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`opr-${Nt()}`),providerName:P("provider_name",{length:64}).notNull(),providerConfig:Ba("provider_config").notNull(),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({nameidxIdx:Xt("pf_oauth_provider_nameidx_idx").on(e.providerName).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_oauth_provider_updated_at_id_idx").on(e.updatedAt,e.id)})),yr=Dt("pf_oauth_client",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`ocl-${Nt()}`),clientId:P("client_id",{length:128}).notNull(),clientSecretHash:P("client_secret_hash",{length:256}).notNull(),audience:P("audience",{length:128}).notNull(),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({clientididxIdx:Xt("pf_oauth_client_clientididx_idx").on(e.clientId).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_oauth_client_updated_at_id_idx").on(e.updatedAt,e.id)})),lt=Dt("pf_job_queue",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`qjob-${Nt()}`),queue:P("queue",{length:512}).notNull(),jobPayload:Ba("job_payload").notNull(),jobAttempts:Re("job_attempts").notNull().default(0),jobRetryLimit:Re("job_retry_limit").notNull().default(5),availableAt:se("available_at").notNull().default(m`(julianday('now'))`),lockedUntil:se("locked_until"),claimReceipt:P("claim_receipt",{length:64}),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({readyIdxIdx:gt("pf_job_queue_ready_idx_idx").on(e.queue,e.lockedUntil,e.jobAttempts,e.availableAt).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_job_queue_updated_at_id_idx").on(e.updatedAt,e.id)})),aa=Dt("pf_completed_job",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`cj-${Nt()}`),queue:P("queue",{length:512}).notNull(),jobId:P("job_id",{length:1024}).notNull(),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({jobIdIxIdx:Xt("pf_completed_job_job_id_ix_idx").on(e.queue,e.jobId).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_completed_job_updated_at_id_idx").on(e.updatedAt,e.id)})),ho=Dt("pf_weekly_schedule",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`ws-${Nt()}`),orgUnitId:P("org_unit_id",{length:41}).notNull().references(()=>G.id),dayOfWeek:Re("day_of_week").notNull(),timeRanges:Ba("time_ranges").notNull(),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({orgunitdayidxIdx:Xt("pf_weekly_schedule_orgunitdayidx_idx").on(e.orgUnitId,e.dayOfWeek).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_weekly_schedule_updated_at_id_idx").on(e.updatedAt,e.id)})),sa=Dt("pf_calendar_period",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`calp-${Nt()}`),orgUnitId:P("org_unit_id",{length:41}).notNull().references(()=>G.id),periodKind:P("period_kind",{length:64}).notNull(),periodTitle:In("period_title").notNull(),periodStart:se("period_start").notNull(),periodEnd:se("period_end").notNull(),periodActive:Re("period_active",{mode:"boolean"}).notNull(),periodSchedule:Ba("period_schedule"),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({kinddateidxIdx:gt("pf_calendar_period_kinddateidx_idx").on(e.periodKind,e.periodStart,e.periodEnd).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_calendar_period_updated_at_id_idx").on(e.updatedAt,e.id),periodTitleLengthCheck:Qi("period_title_length_check",m.raw('length("pf_calendar_period"."period_title") <= 256'))})),xl=Dt("pf_date_exception",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`dex-${Nt()}`),orgUnitId:P("org_unit_id",{length:41}).notNull().references(()=>G.id),exceptionDate:se("exception_date").notNull(),exceptionSlots:Ba("exception_slots").notNull(),exceptionNote:In("exception_note"),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({orgunitdateidxIdx:Xt("pf_date_exception_orgunitdateidx_idx").on(e.orgUnitId,e.exceptionDate).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_date_exception_updated_at_id_idx").on(e.updatedAt,e.id)})),Wn=Dt("pf_holiday_instance",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`hol-${Nt()}`),orgUnitId:P("org_unit_id",{length:41}).notNull().references(()=>G.id),holidayTitle:In("holiday_title").notNull(),holidayRule:Ba("holiday_rule").notNull(),holidayDate:se("holiday_date"),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({orgunittitleidxIdx:Xt("pf_holiday_instance_orgunittitleidx_idx").on(e.orgUnitId,e.holidayTitle).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_holiday_instance_updated_at_id_idx").on(e.updatedAt,e.id),holidayTitleLengthCheck:Qi("holiday_title_length_check",m.raw('length("pf_holiday_instance"."holiday_title") <= 256'))})),Gt=Dt("pf_document_store",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`dstr-${Nt()}`),orgUnitId:P("org_unit_id",{length:41}).notNull().references(()=>G.id),name:In("name").notNull(),path:P("path",{length:2048}).notNull(),acceptedTypes:Ba("accepted_types"),sizeLimit:Re("size_limit"),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({pathidxIdx:Xt("pf_document_store_pathidx_idx").on(e.path).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_document_store_updated_at_id_idx").on(e.updatedAt,e.id),nameLengthCheck:Qi("name_length_check",m.raw('length("pf_document_store"."name") <= 1024'))})),Vn=Dt("pf_file",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`file-${Nt()}`),documentStoreId:P("document_store_id",{length:41}).notNull().references(()=>Gt.id),fileSize:Re("file_size"),mediaKind:P("media_kind",{length:256}),uploadPending:Re("upload_pending",{mode:"boolean"}).notNull().default(!0),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({updatedAtIdIdx:gt("pf_file_updated_at_id_idx").on(e.updatedAt,e.id)})),to=Dt("pf_step_document_store",{id:P("id",{length:41}).primaryKey().$defaultFn(()=>`sds-${Nt()}`),stepId:P("step_id",{length:41}).notNull().references(()=>M.id),documentStoreId:P("document_store_id",{length:41}).notNull().references(()=>Gt.id),createdAt:se("created_at").notNull().default(m`(julianday('now'))`),updatedAt:se("updated_at").notNull().default(m`(julianday('now'))`),createdBy:P("created_by",{length:256}).notNull().default("SYSTEM"),updatedBy:P("updated_by",{length:256}).notNull().default("SYSTEM"),_deleted:Re("_deleted",{mode:"boolean"}).notNull().default(!1)},(e)=>({stepdocstoreidxIdx:Xt("pf_step_document_store_stepdocstoreidx_idx").on(e.stepId,e.documentStoreId).where(m`_deleted = 0`),updatedAtIdIdx:gt("pf_step_document_store_updated_at_id_idx").on(e.updatedAt,e.id)})),DCe=Ky("pf_process_its_no_drafts",{id:P("id",{length:41}).notNull(),noDrafts:Re("no_drafts",{mode:"boolean"}).notNull()}).as(m`
|
|
787
|
+
select
|
|
788
|
+
id,
|
|
789
|
+
not exists (select 1 from pf_process_execution
|
|
790
|
+
join pf_process_state on pf_process_execution.process_state_id = pf_process_state.id and pf_process_state._deleted = false
|
|
791
|
+
where pf_process_state.process_id = pf_process.id and pf_process_execution._deleted = false) as no_drafts
|
|
792
|
+
from pf_process
|
|
793
|
+
`),kf=Ky("pf_process_its_start_step",{id:P("id",{length:41}).notNull(),startStep:P("start_step",{length:41})}).as(m`
|
|
794
|
+
select
|
|
795
|
+
id,
|
|
796
|
+
(select pf_step.id from pf_step
|
|
797
|
+
join pf_step_its_can_start_process on pf_step.id = pf_step_its_can_start_process.id
|
|
798
|
+
where pf_step.process_id = pf_process.id
|
|
799
|
+
and pf_step_its_can_start_process.can_start_process = 1
|
|
800
|
+
and pf_step._deleted = false
|
|
801
|
+
limit 1) as start_step
|
|
802
|
+
from pf_process
|
|
803
|
+
`),Df=Ky("pf_process_its_active_processes",{id:P("id",{length:41}).notNull(),activeProcesses:Re("active_processes").notNull()}).as(m`
|
|
804
|
+
select
|
|
805
|
+
pf_process.id,
|
|
806
|
+
count(distinct pf_to_do.id) as active_processes
|
|
807
|
+
from pf_process
|
|
808
|
+
left outer join pf_process_state on pf_process_state.process_id = pf_process.id and pf_process_state._deleted = false
|
|
809
|
+
left outer join pf_process_execution on pf_process_execution.process_state_id = pf_process_state.id and pf_process_execution._deleted = false
|
|
810
|
+
left outer join pf_to_do on pf_to_do.process_execution_id = pf_process_execution.id and pf_to_do._deleted = false
|
|
811
|
+
group by
|
|
812
|
+
pf_process.id
|
|
813
|
+
`),_c=Ky("pf_step_its_can_start_process",{id:P("id",{length:41}).notNull(),canStartProcess:Re("can_start_process",{mode:"boolean"}).notNull()}).as(m`
|
|
814
|
+
select
|
|
815
|
+
id,
|
|
816
|
+
not exists (select 1 from pf_flow where pf_flow.target_step = pf_step.id and pf_flow._deleted = false) as can_start_process
|
|
817
|
+
from pf_step
|
|
818
|
+
`),ca=Ky("pf_process_state_its_is_draft",{id:P("id",{length:41}).notNull(),isDraft:Re("is_draft",{mode:"boolean"}).notNull()}).as(m`
|
|
819
|
+
select
|
|
820
|
+
id,
|
|
821
|
+
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
|
|
822
|
+
from pf_process_state
|
|
823
|
+
`),OCe=er(G,({one:e,many:t})=>({parentOrgUnit:e(G,{fields:[G.parentOrgUnitId],references:[G.id]}),processes:t(te),roles:t(F),providerUsers:t(N),weeklySchedules:t(ho),calendarPeriods:t(sa),dateExceptions:t(xl),holidayInstances:t(Wn),documentStores:t(Gt),children:t(G)})),NCe=er(te,({one:e,many:t})=>({orgUnit:e(G,{fields:[te.orgUnitId],references:[G.id]}),phases:t(mo),roleResponsibilities:t(fn),steps:t(M),processStates:t(q)})),FCe=er(F,({one:e,many:t})=>({orgUnit:e(G,{fields:[F.orgUnitId],references:[G.id]}),roleResponsibilities:t(fn),steps:t(M),stepSupportingRoles:t(Rn),processStates:t(q),toDos:t(C),scheduledFlows:t(ot),providerUserRoles:t(xt),permittedRoles:t(mi),permittedClientRoles:t(Ji),invitationRoles:t(Je)})),UCe=er(mo,({one:e,many:t})=>({process:e(te,{fields:[mo.processId],references:[te.id]}),steps:t(M)})),MCe=er(fn,({one:e})=>({process:e(te,{fields:[fn.processId],references:[te.id]}),role:e(F,{fields:[fn.roleId],references:[F.id]})})),LCe=er(M,({one:e,many:t})=>({process:e(te,{fields:[M.processId],references:[te.id]}),role:e(F,{fields:[M.roleId],references:[F.id]}),phase:e(mo,{fields:[M.phaseId],references:[mo.id]}),stepSupportingRoles:t(Rn),flows:t(J,{relationName:"flow_sourceStep"}),processStates:t(q),scheduledFlows:t(ot,{relationName:"scheduledFlow_sourceStep"}),stepDocumentStores:t(to)})),BCe=er(Rn,({one:e})=>({step:e(M,{fields:[Rn.stepId],references:[M.id]}),role:e(F,{fields:[Rn.roleId],references:[F.id]})})),$Ce=er(J,({one:e,many:t})=>({sourceStep:e(M,{relationName:"flow_sourceStep",fields:[J.sourceStepId],references:[M.id]}),targetStep:e(M,{relationName:"flow_targetStep",fields:[J.targetStepId],references:[M.id]}),toDos:t(C)})),qCe=er(yi,({many:e})=>({processStates:e(q),toDos:e(C)})),jCe=er(q,({one:e,many:t})=>({process:e(te,{fields:[q.processId],references:[te.id]}),startStep:e(M,{fields:[q.startStepId],references:[M.id]}),startedByUser:e(oe,{fields:[q.startedByUserId],references:[oe.id]}),startedByExternalParticipant:e(yi,{fields:[q.startedByExternalParticipantId],references:[yi.id]}),startedByRole:e(F,{fields:[q.startedByRoleId],references:[F.id]}),processExecutions:t(K)})),HCe=er(K,({one:e,many:t})=>({processState:e(q,{fields:[K.processStateId],references:[q.id]}),toDos:t(C),scheduledFlows:t(ot)})),WCe=er(C,({one:e,many:t})=>({processExecution:e(K,{fields:[C.processExecutionId],references:[K.id]}),flow:e(J,{fields:[C.flowId],references:[J.id]}),completedByUser:e(oe,{fields:[C.completedByUserId],references:[oe.id]}),completedByExternalParticipant:e(yi,{fields:[C.completedByExternalParticipantId],references:[yi.id]}),assignedToProviderUser:e(N,{fields:[C.assignedToProviderUserId],references:[N.id]}),completedByRole:e(F,{fields:[C.completedByRoleId],references:[F.id]}),publicCompletionInvitationAttempts:t(Et)})),VCe=er(Et,({one:e})=>({toDo:e(C,{fields:[Et.toDoId],references:[C.id]})})),zCe=er(ot,({one:e})=>({processExecution:e(K,{fields:[ot.processExecutionId],references:[K.id]}),sourceStep:e(M,{relationName:"scheduledFlow_sourceStep",fields:[ot.sourceStepId],references:[M.id]}),targetStep:e(M,{relationName:"scheduledFlow_targetStep",fields:[ot.targetStepId],references:[M.id]}),completedByRole:e(F,{fields:[ot.completedByRoleId],references:[F.id]})})),KCe=er(oe,({one:e,many:t})=>({processStates:t(q),toDos:t(C),passkeyCredentials:t(St),providerUser:e(N,{fields:[oe.id],references:[N.userId]}),userSettings:e(Er,{fields:[oe.id],references:[Er.userId]})})),GCe=er(St,({one:e})=>({user:e(oe,{fields:[St.userId],references:[oe.id]})})),QCe=er(N,({one:e,many:t})=>({user:e(oe,{fields:[N.userId],references:[oe.id]}),orgUnit:e(G,{fields:[N.orgUnitId],references:[G.id]}),toDos:t(C),delegations:t($t),delegationHistories:t(Oi),providerUserRoles:t(xt),permittedRoles:t(mi),invitations:t(D)})),JCe=er($t,({one:e,many:t})=>({ownerProviderUser:e(N,{fields:[$t.ownerProviderUserId],references:[N.id]}),secretGenerations:t(ct),delegationHistories:t(Oi,{relationName:"delegationHistory_delegation"})})),YCe=er(ct,({one:e,many:t})=>({delegation:e($t,{fields:[ct.delegationId],references:[$t.id]}),parentSecretGeneration:e(ct,{fields:[ct.parentSecretGenerationId],references:[ct.id]}),delegationHistories:t(Oi,{relationName:"delegationHistory_secretGeneration"}),children:t(ct)})),XCe=er(Oi,({one:e})=>({delegation:e($t,{relationName:"delegationHistory_delegation",fields:[Oi.delegationId],references:[$t.id]}),secretGeneration:e(ct,{relationName:"delegationHistory_secretGeneration",fields:[Oi.secretGenerationId],references:[ct.id]}),actorProviderUser:e(N,{fields:[Oi.actorProviderUserId],references:[N.id]}),actorDelegation:e($t,{relationName:"delegationHistory_actorDelegation",fields:[Oi.actorDelegationId],references:[$t.id]}),actorSecretGeneration:e(ct,{relationName:"delegationHistory_actorSecretGeneration",fields:[Oi.actorSecretGenerationId],references:[ct.id]})})),ZCe=er(xt,({one:e})=>({providerUser:e(N,{fields:[xt.providerUserId],references:[N.id]}),role:e(F,{fields:[xt.roleId],references:[F.id]})})),e_e=er(Er,({one:e})=>({user:e(oe,{fields:[Er.userId],references:[oe.id]})})),t_e=er(mi,({one:e})=>({providerUser:e(N,{fields:[mi.providerUserId],references:[N.id]}),role:e(F,{fields:[mi.roleId],references:[F.id]})})),r_e=er(Ji,({one:e})=>({oauthClient:e(yr,{fields:[Ji.oauthClientId],references:[yr.id]}),role:e(F,{fields:[Ji.roleId],references:[F.id]})})),n_e=er(Rs,({one:e})=>({oauthClient:e(yr,{fields:[Rs.oauthClientId],references:[yr.id]})})),o_e=er(D,({one:e,many:t})=>({acceptedByProviderUser:e(N,{fields:[D.acceptedByProviderUserId],references:[N.id]}),registrationSessions:t(yo),invitationRoles:t(Je)})),i_e=er(yo,({one:e})=>({invitation:e(D,{fields:[yo.invitationId],references:[D.id]})})),s_e=er(Je,({one:e})=>({invitation:e(D,{fields:[Je.invitationId],references:[D.id]}),role:e(F,{fields:[Je.roleId],references:[F.id]})})),a_e=er(yr,({many:e})=>({permittedClientRoles:e(Ji),permittedClientEmails:e(Rs)})),c_e=er(ho,({one:e})=>({orgUnit:e(G,{fields:[ho.orgUnitId],references:[G.id]})})),l_e=er(sa,({one:e})=>({orgUnit:e(G,{fields:[sa.orgUnitId],references:[G.id]})})),d_e=er(xl,({one:e})=>({orgUnit:e(G,{fields:[xl.orgUnitId],references:[G.id]})})),u_e=er(Wn,({one:e})=>({orgUnit:e(G,{fields:[Wn.orgUnitId],references:[G.id]})})),p_e=er(Gt,({one:e,many:t})=>({orgUnit:e(G,{fields:[Gt.orgUnitId],references:[G.id]}),files:t(Vn),stepDocumentStores:t(to)})),f_e=er(Vn,({one:e})=>({documentStore:e(Gt,{fields:[Vn.documentStoreId],references:[Gt.id]})})),m_e=er(to,({one:e})=>({step:e(M,{fields:[to.stepId],references:[M.id]}),documentStore:e(Gt,{fields:[to.documentStoreId],references:[Gt.id]})}));var S_e=R1(zr,(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})}})),v_e={schema:zr,relations:S_e};class Ee extends y_e.Tag("processfocus:internal-tag/service-drizzle-sqlite/TypedSqliteDrizzle")(){}var Rv=g_e.effect(Ee,_ee(v_e).pipe(h_e.map((e)=>e)));import{createHash as ite,randomBytes as zke}from"crypto";import{Data as ste,DateTime as $a,Effect as pt,Either as Kke,Layer as w$,Option as hr,Stream as rte}from"effect";import{Data as Yi}from"effect";class kc extends Yi.TaggedError("UpdateDeletedDocumentError"){}class Fee extends Yi.TaggedError("NoProviderUserID"){}class Uee extends Yi.TaggedError("ProviderUserNotFound"){}class x_e extends Yi.TaggedError("NotAuthorized"){}class E_e extends Yi.TaggedError("ProcessStateNotFound"){}class b_e extends Yi.TaggedError("PublicCompletionInvitationNotFound"){}class w_e extends Yi.TaggedError("MissingGeneratedSchemaError"){}class T_e extends Yi.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:
|
|
824
|
+
- ${this.errors.map((t)=>t.field?`'${t.field}': ${t.message}`:t.message).join(`
|
|
825
|
+
- `)}`}}class A_e extends Yi.TaggedError("ExecutionIdConflictError"){get message(){return`executionId is already used for a different process start: ${this.executionId}`}}class I_e extends Yi.TaggedError("StepCompletionConflictError"){get message(){return"The process changed while completing this step. Refresh and try again."}}class R_e extends Yi.TaggedError("UpdateProviderUserError"){}class P_e extends Yi.TaggedError("DocumentStoreNotFoundError"){get message(){return`Document store not found: ${this.path}`}}class C_e extends Yi.TaggedError("ListNotFoundError"){get message(){return`List not found: ${this.listPath}`}}class __e extends Yi.TaggedError("ExportRowLimitError"){get message(){return`Export for list "${this.listPath}" matched ${this.rowCount} rows, exceeding the limit of ${this.maxRows}`}}class k_e extends Yi.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 D_e extends Yi.TaggedError("AuthorizedPageTimeoutError"){}import{Data as O_e,Effect as n4t,Schema as bd}from"effect";var N_e="graphql-api",F_e=`${N_e}:public-todo`,o4t=bd.Struct({v:bd.Literal(1),tid:bd.String,externalParticipantEmail:bd.optional(bd.String),publicCompletionInvitationAttemptId:bd.optional(bd.String),iat:bd.Number,exp:bd.Number,aud:bd.Literal(F_e)});class U_e extends O_e.TaggedError("PublicTodoTokenError"){}import{createCipheriv as M_e,createDecipheriv as a4t,createHash as V1,randomBytes as Mee,timingSafeEqual as c4t}from"crypto";import{Data as L_e,Effect as W1}from"effect";var Lee=1,Bee=7,B_e=32;class z1 extends L_e.TaggedError("RegistrationLinkCryptoError"){}var $_e="process-focus:invitation-registration:v1\x00",Y_="dev-invitation-registration-secret",q_e=()=>{let e=process.env.INVITATION_REGISTRATION_ENCRYPTION_KEY;if(e)return e;let t="development";if(t==="development"||t==="test")return Y_;return},j_e=(e)=>{if(/^[0-9a-f]{64}$/i.test(e))return Buffer.from(e,"hex");try{let t=Buffer.from(e,"base64");if(t.length===32)return t}catch{}return V1("sha256").update(e).digest()},H_e=(e=q_e())=>W1.try({try:()=>{if(!e)throw Error("INVITATION_REGISTRATION_ENCRYPTION_KEY is not configured");let t=j_e(e);return V1("sha256").update($_e).update(t).digest()},catch:(t)=>new z1({message:t instanceof Error?t.message:"Invitation registration encryption is not configured correctly"})});var W_e=(e)=>Buffer.from(JSON.stringify([Lee,e.organisationScope,e.invitationId,e.tokenHash,e.expiresAtUnixMs]),"utf8"),$ee=(e)=>W1.gen(function*(){let t=yield*H_e(e.secret),r=Mee(B_e),n=r.toString("base64url"),o=V1("sha256").update(r).digest("base64url"),i=yield*W1.try({try:()=>{let s=Mee(12),a=M_e("aes-256-gcm",t,s);a.setAAD(W_e({organisationScope:e.organisationScope,invitationId:e.invitationId,tokenHash:o,expiresAtUnixMs:e.expiresAtUnixMs}));let c=Buffer.concat([a.update(r),a.final()]);return{encryptionVersion:Lee,nonce:s.toString("base64url"),authenticationTag:a.getAuthTag().toString("base64url"),ciphertext:c.toString("base64url")}},catch:()=>new z1({message:"Failed to encrypt registration link token"})});return{rawToken:n,tokenHash:o,envelope:i}});var qee=(e,t)=>`${e.replace(/\/$/,"")}/register/passkey#token=${t}`;import{Context as V_e}from"effect";class K1 extends V_e.Tag("processfocus:internal-tag/graphql-db-operations/BusinessCalendarQueries")(){}import{Data as z_e,DateTime as v4t,Effect as x4t}from"effect";class K_e extends z_e.TaggedError("processfocus:internal-tag/InvalidCalendarDataError"){}import{Context as G_e}from"effect";class G1 extends G_e.Tag("processfocus:internal-tag/graphql-db-operations/CleanupOperations")(){}import{Context as Q_e}from"effect";class Q1 extends Q_e.Tag("processfocus:internal-tag/graphql-db-operations/CompletedJobOperations")(){}import{Context as J_e}from"effect";class J1 extends J_e.Tag("processfocus:internal-tag/graphql-db-operations/DraftProcessExecutionQueries")(){}import{Context as Y_e}from"effect";class Y1 extends Y_e.Tag("processfocus:internal-tag/graphql-db-operations/ExecutionDurationQueries")(){}import{Context as X_e}from"effect";class X1 extends X_e.Tag("processfocus:internal-tag/graphql-db-operations/ExecutionQueries")(){}import{Context as Z_e,Data as eke}from"effect";class Z1 extends eke.TaggedError("InvalidExternalParticipantEmail"){}var jee=(e)=>{let t=e.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t))return null;return t};class e$ extends Z_e.Tag("processfocus:internal-tag/graphql-db-operations/ExternalParticipantOperations")(){}import{Context as tke}from"effect";class t$ extends tke.Tag("processfocus:internal-tag/graphql-db-operations/FileOperations")(){}import{Context as nke}from"effect";import{Context as rke}from"effect";var Gw={notifications:{todoAssignment:{email:!1},executionFailure:{email:!1}}},Gy=(e)=>{if(!e||typeof e!=="object")return Gw;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}}}},r$=(e)=>({notifications:{todoAssignment:{email:e.notifications.todoAssignment.email},executionFailure:{email:e.notifications.executionFailure.email}}}),Jr={Pending:"pending",Accepted:"accepted",LegacyClosed:"legacy_closed"},Of={Model:"model",Dashboard:"dashboard",Process:"process",Legacy:"legacy"},wd={NotGenerated:"not_generated",Active:"active",Expired:"expired",Revoked:"revoked"};class Nf extends rke.Tag("processfocus:internal-tag/graphql-db-operations/SettingsQueries")(){}var Qw=(e)=>Array.isArray(e)&&e.every((t)=>typeof t==="string")?e:null,X_=(e)=>({providerUserId:e.providerUserId,userId:e.userId,email:e.email,name:e.name,firstName:e.firstName,lastName:e.lastName,todoAssignmentEmailEnabled:Gy(e.notificationPreference).notifications.todoAssignment.email,executionFailureEmailEnabled:Gy(e.notificationPreference).notifications.executionFailure.email});class n$ extends nke.Tag("processfocus:internal-tag/graphql-db-operations/FlowExecutionOperations")(){}function Z_(e){if(e===null||e<=5)return"Simple";if(e<=15)return"Medium";return"Complex"}import{Effect as oke}from"effect";var ek="provider user not found",Hee="role not found",ike="PROVIDER_USER_NOT_FOUND",ske="ROLE_NOT_FOUND",ake=(e)=>e.startsWith("/")?e:`/${e}`,cke=(e)=>e.trim().toLowerCase();var lke=(e)=>{if(e===ike)return ek;if(e===ske)return Hee;return null};var Wee=(e)=>({...e,error:lke(e.error)}),Vee=(e)=>oke.gen(function*(){let t=yield*Nf,r=cke(e.email),n=ake(e.rolePath),o=yield*t.queryProviderUserByEmail(r);if(!o)return{success:!1,email:r,rolePath:n,alreadyHadRole:!1,error:ek};let i=yield*t.queryRoleByPath(n);if(!i)return{success:!1,email:r,rolePath:n,alreadyHadRole:!1,error:Hee};let s=yield*t.grantProviderUserRole(o.id,i.id,e.grantedBy);return{success:!0,email:r,rolePath:n,alreadyHadRole:s.alreadyHadRole,error:null}});import{Context as dke,Data as uke}from"effect";class Jw extends uke.TaggedError("StepNotFoundError"){}class o$ extends dke.Tag("processfocus:internal-tag/graphql-db-operations/ProcessExecutionOperations")(){}import{Context as pke}from"effect";class i$ extends pke.Tag("processfocus:internal-tag/graphql-db-operations/FlowQueries")(){}import{Context as fke}from"effect";class s$ extends fke.Tag("processfocus:internal-tag/graphql-db-operations/OAuthClientQueries")(){}import{Context as mke}from"effect";class a$ extends mke.Tag("processfocus:internal-tag/graphql-db-operations/OrgQueries")(){}import{Context as zee}from"effect";class c$ extends zee.Tag("processfocus:internal-tag/graphql-db-operations/ProcessQueries")(){}class l$ extends zee.Tag("processfocus:internal-tag/graphql-db-operations/ProcessCollectionQueries")(){}import{Context as yke}from"effect";class d$ extends yke.Tag("processfocus:internal-tag/graphql-db-operations/ProviderUserQueries")(){}import{Context as hke,Data as gke}from"effect";class u$ extends gke.TaggedError("ProcessNotFoundError"){}class p$ extends hke.Tag("processfocus:internal-tag/graphql-db-operations/WorkflowQueries")(){}import{DateTime as Cv,Effect as Pv,Either as Ske}from"effect";var Kee="Invitation not found",f$="This invitation can no longer be changed. Create a new invitation if you need to grant roles again.",Gee="Assign at least one role before generating a registration link.",vke="Registration links are unavailable while the passkey provider is disabled.",m$="An active registration link already exists. Reveal or rotate it instead.",Qee="An active registration link already exists. Pass --rotate to replace it.",xke="There is no active registration link.",Jee="Could not update the registration link. Refresh and try again.",Eke="Trusted frontend origin is not configured.",bke="Registration link encryption is not configured correctly.",wke="Registration link could not be processed. Refresh and try again.",Tke=(e)=>{let t=e.message;if(t.includes("INVITATION_REGISTRATION_ENCRYPTION_KEY")||t.includes("not configured"))return bke;return wke},Ake=(e)=>{let t=Cv.toDateUtc(Cv.add(e,{days:Bee}));return new Date(Math.round(t.getTime()/1000)*1000)},Dc=(e)=>({ok:!1,error:e}),Ike=(e,t,r,n)=>Pv.gen(function*(){let o=yield*e.queryInvitationDetail(t);if(!o)return Dc(Kee);if(o.roles.length===0)return yield*e.revokeRegistrationLink(t,r,n),Dc(Gee);let i=yield*Cv.now,s=yield*e.queryLiveRegistrationLink(t,Cv.toDateUtc(i));if(!s||s.tokenHash!==n.tokenHash||s.generation!==n.generation)return Dc(Jee);return{ok:!0,invitation:o}}),Rke=(e)=>Pv.gen(function*(){let t=yield*Nf,r=e.invitation;if(r.status!==Jr.Pending)return Dc(f$);if(r.roles.length===0)return Dc(Gee);if(!e.rotate&&r.registrationLinkStatus===wd.Active)return Dc(m$);if(!(yield*t.isPasskeyProviderEnabled()))return Dc(vke);let o=yield*Cv.now,i=r.registrationLinkGeneration;if(e.rotate){let l=yield*t.queryLiveRegistrationLink(r.id,Cv.toDateUtc(o));if(!l&&r.registrationLinkStatus!==wd.Expired)return Dc(xke);i=l?.generation??i}let s=e.frontendOrigin.replace(/\/$/,"");if(!s)return Dc(Eke);let a=Ake(o),c=yield*$ee({organisationScope:e.organisationScope,invitationId:r.id,expiresAtUnixMs:a.getTime(),...e.secret===void 0?{}:{secret:e.secret}}).pipe(Pv.either);return yield*Ske.match(c,{onLeft:(l)=>Pv.succeed(Dc(Tke(l))),onRight:(l)=>Pv.gen(function*(){let d=i+1;if(!(yield*t.storeRegistrationLink(r.id,{tokenHash:l.tokenHash,encryptionVersion:l.envelope.encryptionVersion,nonce:l.envelope.nonce,authenticationTag:l.envelope.authenticationTag,ciphertext:l.envelope.ciphertext,expiresAt:a,generation:d,expectedPreviousGeneration:i,requireActiveLink:e.rotate&&r.registrationLinkStatus===wd.Active,actor:e.actor})))return Dc(Jee);let p=yield*Ike(t,r.id,e.actor,{tokenHash:l.tokenHash,generation:d});if(!p.ok)return p;return{ok:!0,invitation:p.invitation,email:p.invitation.email,registrationLinkUrl:qee(s,l.rawToken),expiresAt:a}})})}),Yee=(e)=>Pv.gen(function*(){let t=yield*Nf,r=e.email.trim().toLowerCase(),n=yield*t.queryInvitationByNormalizedEmail(r);if(!n)return Dc(Kee);return yield*Rke({invitation:n,rotate:e.rotate,actor:e.actor,organisationScope:e.organisationScope,frontendOrigin:e.frontendOrigin,...e.secret===void 0?{}:{secret:e.secret}})});import{Effect as Xee}from"effect";var Or=(e)=>{let t=e[0];return t===void 0?Xee.dieMessage("Database write returned no row"):Xee.succeed(t)};import{Context as Pke}from"effect";class y$ extends Pke.Tag("processfocus:internal-tag/graphql-db-operations/ScheduledFlowOperations")(){}import{Context as Cke,Data as Zee}from"effect";class _ke extends Zee.TaggedError("TodoNotFoundError"){}class tk extends Zee.TaggedError("InvalidProcessStateError"){}class h$ extends Cke.Tag("processfocus:internal-tag/graphql-db-operations/StepCompletionOperations")(){}import{Context as kke}from"effect";class g$ extends kke.Tag("processfocus:internal-tag/graphql-db-operations/StepRoleQueries")(){}import{Context as Dke}from"effect";class S$ extends Dke.Tag("processfocus:internal-tag/graphql-db-operations/SystemUserOperations")(){}import{Context as Oke}from"effect";class v$ extends Oke.Tag("processfocus:internal-tag/graphql-db-operations/TodoQueries")(){}import{Context as Nke,Effect as Fke,FiberRef as Uke,Option as Tzt,Schema as Qy}from"effect";var Azt=Qy.Struct({version:Qy.Literal(1),ownerUserId:Qy.String,ownerEmail:Qy.String,delegationId:Qy.String,generationId:Qy.String,name:Qy.String});class ete extends Nke.Tag("processfocus:internal-tag/graphql-db-operations/UserDetails")(){}var It=()=>Fke.flatMap(ete,Uke.get);import{DateTime as qu,Effect as Xi,Layer as Mke,Option as x$}from"effect";var E$=Mke.effect(gd,Xi.gen(function*(){let e=yield*Ee,t=e.select({id:Oi.secretGenerationId}).from(Oi).where(f(Oi.delegationEvent,"replaced"));return gd.of({hasGeneration:(r)=>e.select({id:ct.id}).from(ct).where(f(ct.id,r)).limit(1).pipe(Xi.map((n)=>n.length>0),Cr("Failed to check Secret Generation")),findGeneration:(r)=>e.select({id:$t.id,name:$t.delegationName,generationId:ct.id,parentGenerationId:ct.parentSecretGenerationId,ownerId:N.id,userId:N.userId,createdAt:ct.secretIssuedAt,expiresAt:ct.secretExpiresAt,revokedAt:$t.secretRevokedAt,generationRevokedAt:ct.secretRevokedAt,lastUsedAt:ct.secretLastUsedAt}).from(ct).innerJoin($t,f($t.id,ct.delegationId)).innerJoin(N,f(N.id,$t.ownerProviderUserId)).innerJoin(oe,f(oe.id,N.userId)).where(k("verifier"in r?f(ct.secretVerifier,r.verifier):f(ct.id,r.generationId),f(ct._deleted,!1),Uo(ct.id,t),f($t._deleted,!1),f(N._deleted,!1),f(oe._deleted,!1))).pipe(Xi.map((n)=>x$.fromNullable(n[0]).pipe(x$.map((o)=>({...o,expiresAt:qu.unsafeMake(Math.round(qu.toEpochMillis(o.expiresAt)/1000)*1000)})))),Cr("Failed to resolve Secret Generation")),recordUse:({generationId:r,usedAt:n})=>e.update(ct).set({secretLastUsedAt:n}).where(k(f(ct.id,r),Zt(Pe(ct.secretLastUsedAt),Fo(ct.secretLastUsedAt,qu.subtract(n,{seconds:30}))))).pipe(Xi.asVoid,cn("Failed to record delegated use")),recordLogin:({delegationId:r,generationId:n,ownerId:o,loggedInAt:i})=>e.insert(Oi).values({delegationId:r,secretGenerationId:n,actorProviderUserId:o,actorDelegationId:r,actorSecretGenerationId:n,delegationEvent:"login",secretIssuedAt:i}).pipe(Xi.asVoid,cn("Failed to record delegated login")),isSecretLoginEnabled:()=>e.select({config:Ft.providerConfig}).from(Ft).where(f(Ft._deleted,!1)).pipe(Xi.map((r)=>r.some(({config:n})=>typeof n==="object"&&n!==null&&("delegatedAccess"in n)&&n.delegatedAccess===!0)),Cr("Failed to read secret-login presentation configuration")),findOwnerId:(r)=>e.select({id:N.id}).from(N).innerJoin(oe,f(oe.id,N.userId)).where(k(f(N.userId,r),f(N._deleted,!1),f(oe._deleted,!1))).pipe(Xi.map((n)=>x$.fromNullable(n[0]?.id)),Cr("Failed to resolve Delegation owner")),list:(r)=>e.select({id:$t.id,name:$t.delegationName,generationId:ct.id,createdAt:ct.secretIssuedAt,expiresAt:ct.secretExpiresAt,revokedAt:$t.secretRevokedAt,lastUsedAt:ct.secretLastUsedAt}).from($t).innerJoin(ct,f(ct.delegationId,$t.id)).where(k(f($t.ownerProviderUserId,r),f($t._deleted,!1),f(ct._deleted,!1),Uo(ct.id,t))).orderBy(ct.secretIssuedAt,$t.id).pipe(Xi.map((n)=>n.map((o)=>({...o,createdAt:qu.unsafeMake(Math.round(qu.toEpochMillis(o.createdAt)/1000)*1000),expiresAt:qu.unsafeMake(Math.round(qu.toEpochMillis(o.expiresAt)/1000)*1000),revokedAt:o.revokedAt===null?null:qu.unsafeMake(Math.round(qu.toEpochMillis(o.revokedAt)/1000)*1000)}))),Cr("Failed to list Delegations")),releaseExpiredNames:(r,n)=>e.update($t).set({activeDelegationName:null}).where(k(f($t.ownerProviderUserId,r),Zt(mr($t.secretRevokedAt),Ye($t.id,e.select({id:ct.delegationId}).from(ct).where(k(f(ct._deleted,!1),Uo(ct.id,t),Fo(ct.secretExpiresAt,n))))))).pipe(Xi.asVoid,cn("Failed to release expired Delegation names")),claimName:({id:r,ownerId:n,name:o})=>e.insert($t).values({id:r,ownerProviderUserId:n,delegationName:o,activeDelegationName:o}).onConflictDoNothing().returning({id:$t.id}).pipe(Xi.map((i)=>i.length===1),cn("Failed to claim Delegation name")),updateName:({id:r,name:n,activeName:o})=>e.update($t).set({delegationName:n,activeDelegationName:o}).where(f($t.id,r)).pipe(Xi.asVoid,cn("Failed to rename Delegation")),revokeGeneration:({generationId:r,revokedAt:n})=>e.update(ct).set({secretRevokedAt:n}).where(k(f(ct.id,r),Pe(ct.secretRevokedAt))).pipe(Xi.asVoid,cn("Failed to revoke Secret Generation")),revoke:({id:r,revokedAt:n})=>e.update($t).set({secretRevokedAt:n,activeDelegationName:null}).where(k(f($t.id,r),Pe($t.secretRevokedAt))).pipe(Xi.asVoid,cn("Failed to revoke Delegation")),recordChange:(r)=>e.insert(Oi).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(Xi.asVoid,cn("Failed to record Delegation change")),insertGeneration:({id:r,delegationId:n,parentGenerationId:o,verifier:i,issuedAt:s,expiresAt:a})=>e.insert(ct).values({id:r,delegationId:n,parentSecretGenerationId:o??null,secretVerifier:i,secretIssuedAt:s,secretExpiresAt:a}).pipe(Xi.asVoid,cn("Failed to store Secret Generation")),recordIssuance:({delegationId:r,generationId:n,actorId:o,actorDelegation:i,issuedAt:s})=>e.insert(Oi).values({delegationId:r,secretGenerationId:n,actorProviderUserId:o,actorDelegationId:i?.id,actorSecretGenerationId:i?.generationId,delegationEvent:"issued",secretIssuedAt:s}).pipe(Xi.asVoid,cn("Failed to record Delegation issuance"))})}));Ki();import{Duration as Lke,Effect as Bke,Schedule as tte}from"effect";var $ke=["socket connection was closed unexpectedly"],qke=["ECONNRESET"],jke=(e,t)=>t.some((r)=>e.includes(r)),Hke=(e,t)=>t.some((r)=>e===r);var Yw=(e)=>Cy(e)||Sd(e,(t)=>jke(t,$ke),{codePredicate:(t)=>Hke(t,qke)}),Wke=tte.addDelay(tte.recurs(3),()=>Lke.millis(100)),ju=(e)=>e.pipe(Bke.retry({schedule:Wke,while:Yw}));var Gke=32,nte=(e)=>ite("sha256").update(Buffer.from(e,"base64url")).digest("base64url"),Qke=()=>{let e=zke(Gke);return{rawBearer:e.toString("base64url"),tokenHash:ite("sha256").update(e).digest("base64url")}};class b$ extends ste.TaggedError("ProviderUserNotFoundError"){}class ate extends ste.TaggedError("OrgUnitNotFoundError"){}var cte=String.fromCharCode(31),Jke=String.fromCharCode(65535),Xw=(e)=>e.join(cte),Yke=(e)=>`${e}${Jke}`,Xke=(e)=>e.split(cte),Zke=pt.gen(function*(){let e=yield*Ee,t=yield*$a.now;return(yield*e.delete(Pn).where(k(na(Pe(Pn.keyExpiry)),Fo(Pn.keyExpiry,t))).returning({id:Pn.id})).length}),eDe=(e)=>e[0]??"unknown",ote=(e)=>({id:e.id,name:e.name,orgUnitLevel:e.orgUnitLevel,path:e.path,parentOrgUnitId:e.parentOrgUnitId}),Zw=(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}),tDe=w$.effect(Vo,pt.gen(function*(){let e=yield*Ee;return{findRecoveryInvitation:(t,r)=>pt.gen(function*(){let n=yield*e.select({id:D.id}).from(D).innerJoin(N,f(D.acceptedByProviderUserId,N.id)).where(k(f(N.userId,t),f(N.email,r),f(N._deleted,!1),f(D.email,r),Ye(D.invitationStatus,[Jr.Accepted,Jr.LegacyClosed]),f(D._deleted,!1))).limit(1);return hr.fromNullable(n[0]?.id)}).pipe(Cr("Failed to find recovery invitation")),findRootOrgUnit:()=>pt.gen(function*(){let r=(yield*e.select().from(G).where(k(Pe(G.parentOrgUnitId),f(G._deleted,!1))).limit(1))[0];if(!r)return hr.none();return hr.some(ote(r))}).pipe(Cr("Failed to find root organization unit")),findProviderUserByProviderSub:(t,r)=>pt.gen(function*(){let o=(yield*e.select().from(N).innerJoin(oe,f(N.userId,oe.id)).innerJoin(G,f(N.orgUnitId,G.id)).where(k(f(oe.provider,t),f(oe.sub,r),f(N._deleted,!1),f(oe._deleted,!1),f(G._deleted,!1))).limit(1))[0];if(!o)return hr.none();return hr.some(Zw({providerUser:o.pf_provider_user,user:o.pf_user,orgUnit:o.pf_org_unit}))}).pipe(Cr("Failed to find provider user by provider subject")),findProviderUserByEmail:(t)=>pt.gen(function*(){let n=(yield*e.select().from(N).innerJoin(oe,f(N.userId,oe.id)).innerJoin(G,f(N.orgUnitId,G.id)).where(k(m`lower(${N.email}) = ${t.toLowerCase()}`,f(N._deleted,!1),f(oe._deleted,!1),f(G._deleted,!1))).limit(1))[0];if(!n)return hr.none();return hr.some(Zw({providerUser:n.pf_provider_user,user:n.pf_user,orgUnit:n.pf_org_unit}))}).pipe(Cr("Failed to find provider user by email")),findProviderUserById:(t)=>pt.gen(function*(){let n=(yield*e.select().from(N).innerJoin(oe,f(N.userId,oe.id)).innerJoin(G,f(N.orgUnitId,G.id)).where(k(f(N.id,t),f(N._deleted,!1),f(oe._deleted,!1),f(G._deleted,!1))).limit(1))[0];if(!n)return hr.none();return hr.some(Zw({providerUser:n.pf_provider_user,user:n.pf_user,orgUnit:n.pf_org_unit}))}).pipe(Cr("Failed to find provider user by id")),findProviderUserByUserId:(t)=>pt.gen(function*(){let n=(yield*e.select().from(N).innerJoin(oe,f(N.userId,oe.id)).innerJoin(G,f(N.orgUnitId,G.id)).where(k(f(N.userId,t),f(N._deleted,!1),f(oe._deleted,!1),f(G._deleted,!1))).limit(1))[0];if(!n)return hr.none();return hr.some(Zw({providerUser:n.pf_provider_user,user:n.pf_user,orgUnit:n.pf_org_unit}))}).pipe(Cr("Failed to find provider user by user id")),createProviderUser:(t)=>pt.gen(function*(){let r=yield*$a.now,n=yield*e.insert(oe).values({provider:t.provider,sub:t.sub,lastLoggedIn:r}).returning(),o=yield*Or(n),i=yield*e.insert(N).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*Or(i),c=(yield*e.select({path:G.path}).from(G).where(f(G.id,t.orgUnitId)).limit(1))[0];if(!c)return yield*new ate({orgUnitId:t.orgUnitId});return Zw({providerUser:s,user:o,orgUnit:c})}).pipe(cn("Failed to create provider user")),findPasskeyCredentialById:(t)=>pt.gen(function*(){let n=(yield*e.select({userId:St.userId,email:N.email,sub:oe.sub,provider:oe.provider,credentialId:St.passkeyCredentialId,publicKey:St.passkeyPublicKey,counter:St.signatureCounter,transports:St.passkeyTransports}).from(St).innerJoin(oe,f(St.userId,oe.id)).innerJoin(N,f(N.userId,oe.id)).where(k(f(St.passkeyCredentialId,t),f(St._deleted,!1),f(oe._deleted,!1),f(N._deleted,!1))).limit(1))[0];if(!n)return hr.none();let o=Array.isArray(n.transports)?n.transports.filter((i)=>typeof i==="string"):void 0;return hr.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(Cr("Failed to find passkey credential")),createPasskeyCredential:(t)=>e.insert(St).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(cn("Failed to create passkey credential"),pt.asVoid),listPasskeyCredentialsForUser:(t)=>e.select({id:St.id,name:St.passkeyName,createdAt:St.createdAt,lastUsedAt:St.passkeyLastUsedAt,credentialId:St.passkeyCredentialId,transports:St.passkeyTransports}).from(St).where(k(f(St.userId,t),f(St._deleted,!1))).orderBy(oa(St.createdAt),oa(St.id)).pipe(pt.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}}})),Cr("Failed to list passkey credentials")),renamePasskeyCredential:(t)=>e.update(St).set({passkeyName:t.name}).where(k(f(St.id,t.id),f(St.userId,t.userId),f(St._deleted,!1))).returning({id:St.id}).pipe(pt.map((r)=>r.length===1)).pipe(cn("Failed to rename passkey credential")),removePasskeyCredential:(t)=>pt.gen(function*(){let r=yield*$a.now;if((yield*e.update(St).set({_deleted:!0,updatedAt:r,updatedBy:"SYSTEM"}).where(k(f(St.id,t.id),f(St.userId,t.userId),f(St._deleted,!1),Vr(e.select({count:j1()}).from(e.select({id:St.id}).from(St).where(k(f(St.userId,t.userId),f(St._deleted,!1))).as("remaining")),1))).returning({id:St.id}).pipe(cn("Failed to remove passkey credential"))).length===1)return"removed";return(yield*e.select({id:St.id}).from(St).where(k(f(St.id,t.id),f(St.userId,t.userId),f(St._deleted,!1))).limit(1).pipe(cn("Failed to remove passkey credential"))).length===1?"last_credential":"not_found"}),advancePasskeyCredentialCounter:(t,r,n,o)=>e.update(St).set({signatureCounter:String(n),...o!==void 0&&{passkeyLastUsedAt:o}}).where(k(f(St.passkeyCredentialId,t),f(St.signatureCounter,String(r)),f(St._deleted,!1))).returning({id:St.id}).pipe(pt.map((i)=>i.length===1)).pipe(cn("Failed to advance passkey credential counter")),updateLastLoggedIn:(t,r)=>e.update(oe).set({lastLoggedIn:r}).where(f(oe.id,t)).pipe(cn("Failed to update last logged in"),pt.asVoid),updateProviderUserProfilePicture:(t,r)=>e.update(N).set({picture:r}).where(f(N.userId,t)).pipe(cn("Failed to update provider user profile picture"),pt.asVoid),findAllOAuthProviders:()=>pt.gen(function*(){return(yield*e.select({name:Ft.providerName,config:Ft.providerConfig}).from(Ft).where(f(Ft._deleted,!1))).map((r)=>({name:r.name,config:r.config}))}).pipe(Cr("Failed to list OAuth providers")),findOAuthProviderByName:(t)=>pt.gen(function*(){let n=(yield*e.select({name:Ft.providerName,config:Ft.providerConfig}).from(Ft).where(k(f(Ft.providerName,t),f(Ft._deleted,!1))).limit(1))[0];return n?hr.some({name:n.name,config:n.config}):hr.none()}).pipe(Cr("Failed to find OAuth provider")),findProviderUserRoles:(t)=>pt.gen(function*(){return(yield*e.select({path:F.path}).from(xt).innerJoin(N,f(xt.providerUserId,N.id)).innerJoin(F,f(xt.roleId,F.id)).where(k(f(N.userId,t),f(xt._deleted,!1),f(N._deleted,!1),f(F._deleted,!1)))).map((n)=>n.path)}).pipe(Cr("Failed to find provider user roles")),findInvitationRoleIds:(t)=>pt.gen(function*(){let r=t.toLowerCase();return(yield*e.select({roleId:Je.roleId}).from(D).innerJoin(Je,f(Je.invitationId,D.id)).innerJoin(F,f(F.id,Je.roleId)).where(k(f(D.invitationPendingEmail,r),f(D.invitationStatus,"pending"),f(D._deleted,!1),f(Je._deleted,!1),f(F._deleted,!1)))).map((o)=>o.roleId)}).pipe(Cr("Failed to find invitation role ids")),hasPendingInvitation:(t)=>pt.gen(function*(){let r=t.toLowerCase();return(yield*e.select({id:D.id}).from(D).where(k(f(D.invitationPendingEmail,r),f(D.invitationStatus,"pending"),f(D._deleted,!1))).limit(1)).length>0}).pipe(Cr("Failed to check pending invitation")),acceptPendingInvitationForUser:(t)=>pt.gen(function*(){let r=t.email.toLowerCase(),o=(yield*e.select({id:N.id}).from(N).where(k(f(N.userId,t.userId),f(N._deleted,!1))).limit(1))[0];if(!o)return yield*new b$({userId:t.userId});let i=t.invitationPin?[f(D.id,t.invitationPin.invitationId),m`coalesce(${D.registrationLinkGeneration}, 0) = ${t.invitationPin.linkGeneration}`]:[],s=yield*e.update(D).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:m`coalesce(${D.registrationLinkGeneration}, 0) + 1`,updatedAt:t.acceptedAt,updatedBy:"SYSTEM"}).where(k(f(D.invitationPendingEmail,r),f(D.invitationStatus,"pending"),f(D._deleted,!1),...i)).returning({id:D.id}),a=s[0];if(a)yield*e.update(yo).set({_deleted:!0,updatedAt:t.acceptedAt,updatedBy:"SYSTEM"}).where(k(f(yo.invitationId,a.id),f(yo._deleted,!1)));return s.length>0}).pipe(cn("Failed to accept pending invitation")),exchangeRegistrationLink:(t)=>pt.gen(function*(){let r=nte(t),n=yield*$a.now;if((yield*e.select({id:Ft.id}).from(Ft).where(k(f(Ft.providerName,"passkey"),f(Ft._deleted,!1))).limit(1)).length===0)return hr.none();let s=(yield*e.select({id:D.id,email:D.email,generation:D.registrationLinkGeneration,expiresAt:D.registrationLinkExpiresAt,pendingEmail:D.invitationPendingEmail}).from(D).where(k(f(D.registrationTokenHash,r),f(D.invitationStatus,"pending"),f(D._deleted,!1))).limit(1))[0];if(!s||s.generation===null||!s.expiresAt||!s.pendingEmail)return hr.none();if($a.lessThanOrEqualTo(s.expiresAt,n))return hr.none();if((yield*e.select({roleId:Je.roleId}).from(Je).innerJoin(F,f(F.id,Je.roleId)).where(k(f(Je.invitationId,s.id),f(Je._deleted,!1),f(F._deleted,!1))).limit(1)).length===0)return hr.none();if((yield*e.select({id:N.id}).from(N).where(k(f(N.email,s.pendingEmail),f(N._deleted,!1))).limit(1)).length>0)return hr.none();let{rawBearer:l,tokenHash:d}=Qke(),u=$a.add(n,{minutes:c7});return yield*e.insert(yo).values({registrationSessionTokenHash:d,invitationId:s.id,registrationLinkGeneration:s.generation,registrationSessionExpiresAt:u,createdAt:n,updatedAt:n,createdBy:"SYSTEM",updatedBy:"SYSTEM"}),hr.some({email:s.pendingEmail,sessionBearer:l,expiresAt:u,invitationId:s.id,linkGeneration:s.generation})}).pipe(cn("Failed to exchange registration link")),resolveInvitationRegistrationSession:(t)=>pt.gen(function*(){let r=nte(t),n=yield*$a.now;if((yield*e.select({id:Ft.id}).from(Ft).where(k(f(Ft.providerName,"passkey"),f(Ft._deleted,!1))).limit(1)).length===0)return hr.none();let s=(yield*e.select({sessionId:yo.id,sessionHash:yo.registrationSessionTokenHash,sessionGeneration:yo.registrationLinkGeneration,sessionExpiresAt:yo.registrationSessionExpiresAt,invitationId:D.id,pendingEmail:D.invitationPendingEmail,invitationStatus:D.invitationStatus,invitationDeleted:D._deleted,linkGeneration:D.registrationLinkGeneration}).from(yo).innerJoin(D,f(D.id,yo.invitationId)).where(k(f(yo.registrationSessionTokenHash,r),f(yo._deleted,!1),Vr(yo.registrationSessionExpiresAt,n))).limit(1))[0];if(!s||s.invitationDeleted||s.invitationStatus!=="pending"||!s.pendingEmail||s.linkGeneration===null||s.sessionGeneration!==s.linkGeneration)return hr.none();if((yield*e.select({roleId:Je.roleId}).from(Je).innerJoin(F,f(F.id,Je.roleId)).where(k(f(Je.invitationId,s.invitationId),f(Je._deleted,!1),f(F._deleted,!1))).limit(1)).length===0)return hr.none();if((yield*e.select({id:N.id}).from(N).where(k(f(N.email,s.pendingEmail),f(N._deleted,!1))).limit(1)).length>0)return hr.none();return hr.some({email:s.pendingEmail,invitationId:s.invitationId,linkGeneration:s.linkGeneration,sessionTokenHash:s.sessionHash,sessionId:s.sessionId})}).pipe(Cr("Failed to resolve registration session")),deleteRegistrationSessionsForInvitation:(t)=>pt.gen(function*(){let r=yield*$a.now;yield*e.update(yo).set({_deleted:!0,updatedAt:r,updatedBy:"SYSTEM"}).where(k(f(yo.invitationId,t),f(yo._deleted,!1)))}).pipe(cn("Failed to delete registration sessions")),findRoleIdsByPaths:(t)=>pt.gen(function*(){if(t.length===0)return[];return(yield*e.select({id:F.id}).from(F).where(k(Ye(F.path,t),f(F._deleted,!1)))).map((n)=>n.id)}).pipe(Cr("Failed to find role ids by paths")),assignProviderUserRoles:(t,r)=>pt.gen(function*(){if(r.length===0)return;let o=(yield*e.select({id:N.id}).from(N).where(k(f(N.userId,t),f(N._deleted,!1))).limit(1))[0];if(!o)return yield*new b$({userId:t});let i=yield*$a.now;yield*e.insert(xt).values(r.map((s)=>({providerUserId:o.id,roleId:s,createdAt:i,updatedAt:i})))}).pipe(cn("Failed to assign provider user roles")),findAllOAuthClients:()=>pt.gen(function*(){return yield*e.select({clientId:yr.clientId,secretHash:yr.clientSecretHash,audience:yr.audience}).from(yr).where(f(yr._deleted,!1))}).pipe(Cr("Failed to list OAuth clients")),findOAuthClientById:(t)=>pt.gen(function*(){let n=(yield*e.select({clientId:yr.clientId,secretHash:yr.clientSecretHash,audience:yr.audience}).from(yr).where(k(f(yr.clientId,t),f(yr._deleted,!1))).limit(1))[0];return n?hr.some(n):hr.none()}).pipe(Cr("Failed to find OAuth client")),validateRolePaths:(t)=>pt.gen(function*(){if(t.length===0)return[];return(yield*e.select({path:F.path}).from(F).where(k(Ye(F.path,t),f(F._deleted,!1)))).map((n)=>n.path)}).pipe(Cr("Failed to validate role paths")),upsertM2MUser:(t,r,n)=>pt.gen(function*(){let i=n?.updateLastLoggedIn!==!1,s=k(f(oe.provider,"client_credentials"),f(oe.sub,t),f(oe._deleted,!1)),a=()=>e.select({id:oe.id}).from(oe).where(s).limit(1);if(i){let p=yield*e.update(oe).set({lastLoggedIn:r,updatedAt:r}).where(s).returning({id:oe.id}).pipe(ju,pt.catchAll((y)=>Yw(y)?pt.logWarning("Non-critical last_logged_in update failed, continuing authentication").pipe(pt.annotateLogs({error:y,clientId:t}),pt.as([])):pt.fail(y)));if(p[0])return p[0].id}let c=yield*a();if(c[0])return c[0].id;let l=e.insert(oe).values({provider:"client_credentials",sub:t,lastLoggedIn:r,createdAt:r,updatedAt:r,createdBy:"SYSTEM",updatedBy:"SYSTEM"}),d=i?yield*l.onConflictDoUpdate({target:[oe.provider,oe.sub],targetWhere:m`_deleted = 0`,set:{lastLoggedIn:r,updatedAt:r}}).returning({id:oe.id}).pipe(ju,pt.either):yield*l.returning({id:oe.id}).pipe(ju,pt.either);if(Kke.isLeft(d)){let p=yield*a();if(p[0])return p[0].id;return yield*pt.fail(d.left)}return(yield*Or(d.right)).id}).pipe(cn("Failed to upsert M2M user")),findPermittedRolesWithOrgUnit:(t)=>pt.gen(function*(){return yield*e.select({rolePath:F.path,orgUnitId:F.orgUnitId,orgUnitPath:G.path}).from(mi).innerJoin(N,f(mi.providerUserId,N.id)).innerJoin(F,f(mi.roleId,F.id)).innerJoin(G,f(F.orgUnitId,G.id)).where(k(f(N.userId,t),f(mi._deleted,!1),f(N._deleted,!1),f(F._deleted,!1),f(G._deleted,!1)))}).pipe(Cr("Failed to find permitted roles")),findOrgUnitByPath:(t)=>pt.gen(function*(){let n=(yield*e.select().from(G).where(f(G.path,t)).limit(1))[0];if(!n)return hr.none();return hr.some(ote(n))}).pipe(Cr("Failed to find organization unit by path")),validateRolePathsWithOrgUnit:(t)=>pt.gen(function*(){if(t.length===0)return[];return yield*e.select({rolePath:F.path,orgUnitId:F.orgUnitId,orgUnitPath:G.path}).from(F).innerJoin(G,f(F.orgUnitId,G.id)).where(k(Ye(F.path,t),f(F._deleted,!1),f(G._deleted,!1)))}).pipe(Cr("Failed to validate role paths with org unit")),findPermittedClientRole:(t,r)=>pt.gen(function*(){let o=(yield*e.select({rolePath:F.path,orgUnitId:F.orgUnitId,orgUnitPath:G.path,updatedAt:Ji.updatedAt}).from(yr).innerJoin(Ji,f(Ji.oauthClientId,yr.id)).innerJoin(F,f(Ji.roleId,F.id)).innerJoin(G,f(F.orgUnitId,G.id)).where(k(f(yr.clientId,t),f(F.path,r),f(yr._deleted,!1),f(Ji._deleted,!1),f(F._deleted,!1),f(G._deleted,!1))).limit(1))[0];if(!o)return hr.none();return hr.some({rolePath:o.rolePath,orgUnitId:o.orgUnitId,orgUnitPath:o.orgUnitPath,updatedAt:o.updatedAt})}).pipe(Cr("Failed to find permitted client role")),findPermittedClientEmail:(t,r)=>pt.gen(function*(){let o=(yield*e.select({email:Rs.email,updatedAt:Rs.updatedAt}).from(yr).innerJoin(Rs,f(Rs.oauthClientId,yr.id)).where(k(f(yr.clientId,t),f(Rs.email,r),f(yr._deleted,!1),f(Rs._deleted,!1))).limit(1))[0];if(!o)return hr.none();return hr.some({email:o.email,updatedAt:o.updatedAt})}).pipe(Cr("Failed to find permitted client email"))}})),eT=(e)=>e.pipe(ju,pt.mapError((t)=>new nl({message:t.message,cause:t}))),T$=w$.merge(tDe,E$),tT=w$.effect(Zr,pt.gen(function*(){let e=yield*Ee;return{get:(t)=>eT(pt.gen(function*(){let r=Xw(t),n=yield*$a.now,o=yield*e.select().from(Pn).where(k(f(Pn.oauthKey,r),Zt(Pe(Pn.keyExpiry),Vr(Pn.keyExpiry,n)))).limit(1);if(o.length===0)return;let i=o[0];if(!i)return;return i.keyValue})),take:(t)=>eT(pt.gen(function*(){let r=Xw(t),n=yield*$a.now;return(yield*e.delete(Pn).where(k(f(Pn.oauthKey,r),Zt(Pe(Pn.keyExpiry),Vr(Pn.keyExpiry,n)))).returning({value:Pn.keyValue}))[0]?.value})),set:(t,r,n)=>eT(pt.gen(function*(){let o=Xw(t),i=eDe(t),s=n===void 0?void 0:$a.unsafeMake(Date.now()+n*1000);yield*e.insert(Pn).values({oauthKey:o,keyKind:i,keyValue:r,keyExpiry:s}).onConflictDoUpdate({target:Pn.oauthKey,set:{keyValue:r,keyKind:i,keyExpiry:s}})})),remove:(t)=>eT(pt.gen(function*(){let r=Xw(t);yield*e.delete(Pn).where(f(Pn.oauthKey,r))})),scan:(t)=>rte.unwrap(eT(pt.gen(function*(){let r=Xw(t),n=Yke(r),o=yield*$a.now,i=yield*e.select().from(Pn).where(k(Af(Pn.oauthKey,r),xd(Pn.oauthKey,n),Zt(Pe(Pn.keyExpiry),Vr(Pn.keyExpiry,o))));return rte.fromIterable(i.map((s)=>[Xke(s.oauthKey),s.keyValue]))})))}}));import{Effect as rk,Layer as rDe}from"effect";var A$=rDe.effect(K1,rk.gen(function*(){let e=yield*Ee;return{getCalendarData:(t)=>rk.gen(function*(){if(t.length===0)return new Map;let[r,n,o,i,s]=yield*rk.all([e.select({id:G.id,timezone:G.timezone}).from(G).where(Ye(G.id,t)),e.select({orgUnitId:ho.orgUnitId,dayOfWeek:ho.dayOfWeek,timeRanges:ho.timeRanges}).from(ho).where(Ye(ho.orgUnitId,t)),e.select({orgUnitId:xl.orgUnitId,exceptionDate:m`(${xl.exceptionDate} - 2440587.5) * 86400000`.as("exception_date_ms"),exceptionSlots:xl.exceptionSlots,exceptionNote:xl.exceptionNote}).from(xl).where(Ye(xl.orgUnitId,t)),e.select({orgUnitId:Wn.orgUnitId,holidayTitle:Wn.holidayTitle,holidayRule:Wn.holidayRule,holidayDate:m`CASE WHEN ${Wn.holidayDate} IS NOT NULL THEN (${Wn.holidayDate} - 2440587.5) * 86400000 ELSE NULL END`.as("holiday_date_ms")}).from(Wn).where(Ye(Wn.orgUnitId,t)),e.select({orgUnitId:sa.orgUnitId,periodKind:sa.periodKind,periodTitle:sa.periodTitle,periodStart:m`(${sa.periodStart} - 2440587.5) * 86400000`.as("period_start_ms"),periodEnd:m`(${sa.periodEnd} - 2440587.5) * 86400000`.as("period_end_ms"),periodActive:sa.periodActive,periodSchedule:sa.periodSchedule}).from(sa).where(Ye(sa.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:()=>rk.gen(function*(){return(yield*e.select({id:G.id}).from(G).where(Pe(G.parentOrgUnitId)).limit(1))[0]?.id??null})}}));import{Effect as I$,Layer as nDe}from"effect";var oDe=nDe.effect(Q1,I$.gen(function*(){let e=yield*Ee;return{isJobCompleted:(t,r)=>I$.gen(function*(){return(yield*e.select({id:aa.id}).from(aa).where(k(f(aa.queue,t),f(aa.jobId,r),f(aa._deleted,!1))).limit(1)).length>0}),markJobCompleted:(t,r)=>e.insert(aa).values({queue:t,jobId:r}),clearJobCompleted:(t,r)=>I$.gen(function*(){let n=yield*Ie(),o=yield*It();yield*e.update(aa).set({_deleted:!0,updatedAt:n,updatedBy:o.by}).where(k(f(aa.queue,t),f(aa.jobId,r),f(aa._deleted,!1)))})}}));import{Effect as lte,Layer as iDe}from"effect";var R$=iDe.effect(Y1,lte.gen(function*(){let e=yield*Ee;return{getExecutionTimestamps:(t,r)=>lte.gen(function*(){if(t.length===0)return[];let n=e.$with("ranked_executions").as(e.select({processId:q.processId,orgUnitId:te.orgUnitId,createdAt:m`(${K.createdAt} - 2440587.5) * 86400000`.as("created_at_ms"),finishedAt:m`(${K.finishedAt} - 2440587.5) * 86400000`.as("finished_at_ms"),rowNum:m`ROW_NUMBER() OVER (PARTITION BY ${q.processId} ORDER BY ${K.finishedAt} DESC)`.as("row_num")}).from(K).innerJoin(q,f(K.processStateId,q.id)).innerJoin(te,f(q.processId,te.id)).where(k(mr(K.finishedAt),f(K._deleted,!1),f(q._deleted,!1),f(te._deleted,!1),Ye(q.processId,t))));return(yield*e.with(n).select({processId:n.processId,orgUnitId:n.orgUnitId,createdAt:n.createdAt,finishedAt:n.finishedAt}).from(n).where(Fo(n.rowNum,r))).map((i)=>({processId:i.processId,orgUnitId:i.orgUnitId,createdAt:i.createdAt,finishedAt:i.finishedAt}))})}}));import{Effect as rT,Layer as sDe}from"effect";var P$=sDe.effect(X1,rT.gen(function*(){let e=yield*Ee,t=vd(G,"role_org_unit"),r=vd(F,"completing_role"),n=vd(N,"assigned_provider_user"),o=(g)=>rT.gen(function*(){if(g.length===0)return[];return(yield*e.select({executionId:C.processExecutionId,updatedBy:C.updatedBy,todoId:C.id,stepId:M.id,stepName:M.name,stepPath:M.path,completed:C._deleted,failureReason:C.failureReason,correctionRequiredAt:m`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:N.id,providerUserFirstName:N.firstName,providerUserLastName:N.lastName,providerUserEmail:N.email,providerUserPicture:N.picture,providerUserOrgUnit:G.name,assignedProviderUserEmail:n.email,externalParticipantId:yi.id,externalParticipantEmail:yi.email,roleId:F.id,roleName:F.name,roleOrgUnitPath:t.path,completingRoleId:r.id,completingRoleName:r.name,completingRolePath:r.path,itemData:C.itemData,createdAt:m`(${C.createdAt} - 2440587.5) * 86400000`.as("created_at_millis"),updatedAt:m`(${C.updatedAt} - 2440587.5) * 86400000`.as("updated_at_millis")}).from(C).innerJoin(J,f(C.flowId,J.id)).innerJoin(M,f(J.targetStepId,M.id)).leftJoin(F,f(M.roleId,F.id)).leftJoin(t,f(F.orgUnitId,t.id)).leftJoin(r,f(C.completedByRoleId,r.id)).leftJoin(oe,f(C.completedByUserId,oe.id)).leftJoin(N,k(f(oe.id,N.userId),f(N._deleted,!1))).leftJoin(G,f(N.orgUnitId,G.id)).leftJoin(n,f(C.assignedToProviderUserId,n.id)).leftJoin(yi,f(C.completedByExternalParticipantId,yi.id)).where(Ye(C.processExecutionId,g)).orderBy(C.updatedAt)).map((S)=>({executionId:S.executionId,updatedBy:S.updatedBy,todoId:S.todoId,stepId:S.stepId,stepName:S.stepName,stepPath:S.stepPath,completed:S.completed,failureReason:S.failureReason,correctionRequiredAt:S.correctionRequiredAt,correctionFailureReason:S.correctionFailureReason,completedByUserId:S.completedByUserId,providerUserId:S.providerUserId,providerUserFirstName:S.providerUserFirstName,providerUserLastName:S.providerUserLastName,providerUserEmail:S.providerUserEmail,providerUserPicture:S.providerUserPicture,providerUserOrgUnit:S.providerUserOrgUnit,assignedProviderUserEmail:S.assignedProviderUserEmail,externalParticipantId:S.externalParticipantId,externalParticipantEmail:S.externalParticipantEmail,roleId:S.roleId,roleName:S.roleName,roleOrgUnitPath:S.roleOrgUnitPath,completingRoleId:S.completingRoleId,completingRoleName:S.completingRoleName,completingRolePath:S.completingRolePath,itemData:S.itemData,createdAt:S.createdAt,updatedAt:S.updatedAt}))}),i=vd(M,"start_step"),s=vd(F,"start_step_role"),a=vd(G,"start_step_role_org_unit"),c=vd(F,"started_by_role"),l=vd(yi,"start_external_participant"),d=(g)=>rT.gen(function*(){let E=e.$with("duration_stats").as(e.select({processId:q.processId,minDurationMs:m`MIN(${K.businessDuration})`.as("min_duration_ms"),maxDurationMs:m`MAX(${K.businessDuration})`.as("max_duration_ms")}).from(K).innerJoin(q,f(K.processStateId,q.id)).where(k(mr(K.finishedAt),mr(K.businessDuration),f(K._deleted,!1),f(q._deleted,!1))).groupBy(q.processId)),S=e.with(E).select({id:K.id,processStateId:K.processStateId,withoutWaiting:K.withoutWaiting,processName:te.name,processPath:te.path,finishedAt:m`CASE WHEN ${K.finishedAt} IS NULL THEN NULL ELSE strftime('%Y-%m-%dT%H:%M:%SZ', ${K.finishedAt}) END`.as("finished_at_iso"),abandonedAt:m`CASE WHEN ${K.abandonedAt} IS NULL THEN NULL ELSE strftime('%Y-%m-%dT%H:%M:%SZ', ${K.abandonedAt}) END`.as("abandoned_at_iso"),abandonedReason:K.abandonedReason,startedAt:m`strftime('%Y-%m-%dT%H:%M:%SZ', ${K.createdAt})`.as("started_at_iso"),updatedAt:m`CAST(ROUND((${K.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`.as("updated_at_millis"),deleted:K._deleted,startedAtMs:m`(${K.createdAt} - 2440587.5) * 86400000`.as("started_at_millis"),finishedAtMs:m`CASE WHEN ${K.finishedAt} IS NULL THEN NULL ELSE (${K.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:m`strftime('%Y-%m-%dT%H:%M:%SZ', ${q.createdAt})`.as("process_state_created_at_iso"),startedByEmail:N.email,createdBy:K.createdBy,startedById:N.id,startedByFirstName:N.firstName,startedByLastName:N.lastName,startedByPicture:N.picture,startedByOrgUnit:G.name,processSlaValue:te.slaValue,processSlaUnit:te.slaUnit,processSlaWarning:te.slaWarning,typicalDurationMinMs:E.minDurationMs,typicalDurationMaxMs:E.maxDurationMs,processOrgUnitId:te.orgUnitId}).from(K).innerJoin(q,f(K.processStateId,q.id)).innerJoin(te,f(q.processId,te.id)).innerJoin(i,f(q.startStepId,i.id)).leftJoin(s,f(i.roleId,s.id)).leftJoin(a,f(s.orgUnitId,a.id)).leftJoin(c,f(q.startedByRoleId,c.id)).leftJoin(oe,f(q.startedByUserId,oe.id)).leftJoin(N,k(f(oe.id,N.userId),f(N._deleted,!1))).leftJoin(G,f(N.orgUnitId,G.id)).leftJoin(l,f(q.startedByExternalParticipantId,l.id)).leftJoin(E,f(q.processId,E.processId)).where(g.whereClause),x=g.newestFirst?S.orderBy(eo(K.createdAt),K.id):S.orderBy(K.updatedAt,K.id),w=g.limit!==void 0?x.limit(g.limit):x;return(yield*g.offset!==void 0?w.offset(g.offset):w).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=(g)=>{if(!g)return;let E=m`CAST(ROUND((${K.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`;return Zt(Vr(E,g.updatedAt),k(f(E,g.updatedAt),Vr(K.id,g.id)))},p=(g)=>rT.gen(function*(){let S=(yield*e.select({state:q.state}).from(K).innerJoin(q,f(K.processStateId,q.id)).where(f(K.id,g)).limit(1))[0];if(!S)return null;return S.state}),y=k(Pe(K.finishedAt),Pe(K.abandonedAt),Pe(K.abandonedReason));return{pullExecution:(g,E,S=!1,x)=>d({whereClause:k(x===void 0?void 0:Zt(u({id:"",updatedAt:x}),y),S&&g?Zt(u(g),y):u(g)),limit:E}),getExecutions:(g)=>g.length===0?rT.succeed([]):d({whereClause:Ye(K.id,g)}),listExecutions:(g)=>d({whereClause:k(f(K._deleted,!1),g.processPath!=null?f(te.path,g.processPath):void 0),limit:g.limit,offset:g.offset,newestFirst:!0}),getTodosForExecutions:o,getProcessStateByExecutionId:p}}));import{Effect as dte,Layer as aDe}from"effect";var C$=aDe.effect(e$,dte.gen(function*(){let e=yield*Ee;return{upsertByEmail:(t)=>dte.gen(function*(){let r=jee(t);if(r===null)return yield*new Z1({email:t,message:"External participant email must be a valid email address"});let n=yield*Ie(),o=yield*It(),i=yield*e.insert(yi).values({email:r,createdAt:n,updatedAt:n,createdBy:o.by,updatedBy:o.by}).onConflictDoUpdate({target:yi.email,targetWhere:m`_deleted = 0`,set:{updatedAt:n,updatedBy:o.by}}).returning({id:yi.id});return(yield*Or(i)).id})}}));import{Effect as Ff,Layer as cDe}from"effect";var lDe=cDe.effect(t$,Ff.gen(function*(){let e=yield*Ee;return{createFile:(t,r,n)=>Ff.gen(function*(){let o=yield*Ie(),i=yield*e.insert(Vn).values({documentStoreId:t,mediaKind:r??null,uploadPending:!0,createdBy:n,createdAt:o,updatedAt:o}).returning({id:Vn.id});return(yield*Or(i)).id}),getFileWithStore:(t)=>Ff.gen(function*(){let n=(yield*e.select({id:Vn.id,documentStoreId:Vn.documentStoreId,fileSize:Vn.fileSize,uploadPending:Vn.uploadPending,storeName:Gt.name,acceptedTypes:Gt.acceptedTypes,sizeLimit:Gt.sizeLimit}).from(Vn).innerJoin(Gt,f(Vn.documentStoreId,Gt.id)).where(f(Vn.id,t)).limit(1))[0];if(!n)return null;return{...n,acceptedTypes:n.acceptedTypes??null}}),markFileUploaded:(t,r,n)=>Ff.gen(function*(){let i={uploadPending:!1,updatedAt:yield*Ie()};if(r!==void 0)i.fileSize=r;if(n!==void 0)i.mediaKind=n;yield*e.update(Vn).set(i).where(f(Vn.id,t))}),getDocumentStoreByPath:(t)=>Ff.gen(function*(){return(yield*e.select({id:Gt.id,name:Gt.name}).from(Gt).where(f(Gt.path,t)).limit(1))[0]??null}),isStepLinkedToDocumentStore:(t,r)=>Ff.gen(function*(){return((yield*e.select({count:m`count(*)`}).from(to).innerJoin(M,f(to.stepId,M.id)).innerJoin(Gt,f(to.documentStoreId,Gt.id)).where(k(f(M.path,t),f(Gt.path,r),f(to._deleted,!1))).limit(1))[0]?.count??0)>0}),getFileOwnerInfo:(t)=>Ff.gen(function*(){let n=(yield*e.select({createdBy:Vn.createdBy,orgUnitPath:G.path,documentStorePath:Gt.path}).from(Vn).innerJoin(Gt,f(Vn.documentStoreId,Gt.id)).innerJoin(G,f(Gt.orgUnitId,G.id)).where(f(Vn.id,t)).limit(1))[0];if(!n?.createdBy)return null;return{createdBy:n.createdBy,orgUnitPath:n.orgUnitPath,documentStorePath:n.documentStorePath}}),deleteFile:(t)=>Ff.gen(function*(){return(yield*e.delete(Vn).where(f(Vn.id,t)).returning({id:Vn.id})).length>0})}}));import{Effect as Br,Layer as dDe}from"effect";var uDe=dDe.effect(n$,Br.gen(function*(){let e=yield*Ee,t=Di(M,"source_step"),r=Di(M,"target_step");return{queryFlowById:(n)=>Br.gen(function*(){let i=(yield*e.select({id:J.id,condition:J.condition,schedule:J.schedule,sourceStepPath:t.path,targetStepId:r.id,targetStepPath:r.path,fallbackBranch:J.fallbackBranch,isOnError:J.errorBranch,taggedErrors:J.errorTags}).from(J).innerJoin(t,f(J.sourceStepId,t.id)).innerJoin(r,f(J.targetStepId,r.id)).where(k(f(J.id,n),f(J._deleted,!1))).limit(1))[0];if(!i)return null;return{...i,taggedErrors:Qw(i.taggedErrors)}}),getProcessStateByExecutionId:(n)=>Br.gen(function*(){let o=yield*e.select({processStateId:q.id,withoutWaiting:K.withoutWaiting,createdBy:K.createdBy,state:q.state}).from(K).innerJoin(q,f(K.processStateId,q.id)).where(f(K.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)=>Br.gen(function*(){return(yield*e.select({id:K.id}).from(K).where(k(f(K.id,n),Pe(K.finishedAt),Pe(K.abandonedAt))).limit(1)).length>0}),queryTodoNotificationInfo:(n)=>Br.gen(function*(){if(n.length===0)return[];return yield*e.select({todoId:C.id,processExecutionId:C.processExecutionId,assignedToProviderUserId:C.assignedToProviderUserId,roleId:M.roleId,stepPath:M.path,processName:te.name,stepName:M.name,itemData:C.itemData}).from(C).innerJoin(J,f(C.flowId,J.id)).innerJoin(M,f(J.targetStepId,M.id)).innerJoin(te,f(M.processId,te.id)).where(k(Ye(C.id,n),f(C._deleted,!1),f(J._deleted,!1),f(M._deleted,!1),f(te._deleted,!1)))}),insertToDo:({processExecutionId:n,flowId:o,assignedToProviderUserId:i,slaTargetAt:s,slaWarningAt:a,itemData:c,barrierScheduledFlowId:l})=>Br.gen(function*(){let d=yield*Ie(),u=yield*It(),p=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*Or(p)).id}),insertToDos:({processExecutionId:n,flowId:o,items:i,slaTargetAt:s,slaWarningAt:a,barrierScheduledFlowId:c})=>Br.gen(function*(){let l=yield*Ie(),d=yield*It();return(yield*e.insert(C).values(i.map((p)=>({processExecutionId:n,flowId:o,slaTargetAt:s??null,slaWarningAt:a??null,itemData:p,barrierScheduledFlowId:c??null,createdAt:l,updatedAt:l,createdBy:d.by,updatedBy:d.by}))).returning({id:C.id})).map((p)=>p.id)}),queryFlowsBySourceStepId:(n)=>Br.gen(function*(){return(yield*e.select({id:J.id,condition:J.condition,schedule:J.schedule,sourceStepPath:t.path,targetStepId:r.id,targetStepPath:r.path,fallbackBranch:J.fallbackBranch,isOnError:J.errorBranch,taggedErrors:J.errorTags}).from(J).innerJoin(t,f(J.sourceStepId,t.id)).innerJoin(r,f(J.targetStepId,r.id)).where(k(f(J.sourceStepId,n),f(J._deleted,!1)))).map((i)=>({...i,taggedErrors:Qw(i.taggedErrors)}))}),countActiveTodos:(n)=>Br.gen(function*(){let o=yield*e.select({count:m`COUNT(*)`.as("count")}).from(C).where(k(f(C.processExecutionId,n),f(C._deleted,!1)));return Number(o[0]?.count??0)}),countPendingFlowJobs:(n,o)=>Br.gen(function*(){let i=yield*e.select({count:m`COUNT(*)`.as("count")}).from(lt).where(k(f(lt.queue,o),f(lt._deleted,!1),m`(
|
|
826
|
+
(
|
|
827
|
+
json_extract(${lt.jobPayload}, '$.sourceScheduledFlowId') IS NULL
|
|
828
|
+
AND json_extract(${lt.jobPayload}, '$.processExecutionId') = ${n}
|
|
829
|
+
)
|
|
830
|
+
OR
|
|
831
|
+
(
|
|
832
|
+
json_extract(${lt.jobPayload}, '$.sourceScheduledFlowId') IS NOT NULL
|
|
833
|
+
AND json_extract(${lt.jobPayload}, '$.processExecutionId') = ${n}
|
|
834
|
+
AND EXISTS (
|
|
835
|
+
SELECT 1 FROM ${ot}
|
|
836
|
+
WHERE ${ot.id} = json_extract(${lt.jobPayload}, '$.payload.scheduledFlowId')
|
|
837
|
+
AND ${ot._deleted} = false
|
|
838
|
+
)
|
|
839
|
+
)
|
|
840
|
+
)`));return Number(i[0]?.count??0)}),insertFlowDispatchJobs:(n)=>Br.gen(function*(){if(n.length===0)return;let o=yield*Ie(),i=yield*It();yield*e.insert(lt).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)=>Br.gen(function*(){return(yield*e.select({id:lt.id,payload:lt.jobPayload}).from(lt).where(k(f(lt._deleted,!1),m`json_extract(${lt.jobPayload}, '$.sourceScheduledFlowId') = ${n}`))).map(({id:i,payload:s})=>({id:i,...s})).sort((i,s)=>i.sequence-s.sequence)}),queryFlowDispatchIdsByStorageQueue:(n,o,i)=>Br.gen(function*(){let s=m`json_extract(${lt.jobPayload}, '$.sourceScheduledFlowId')`;return(yield*e.select({sourceScheduledFlowId:s}).from(lt).where(k(f(lt._deleted,!1),f(lt.queue,n),Zt(Pe(lt.lockedUntil),Fo(lt.lockedUntil,o)))).groupBy(s).orderBy(m`MIN(${lt.createdAt})`,s).limit(i)).map((c)=>c.sourceScheduledFlowId)}),claimFlowDispatchJobs:(n,o,i,s)=>Br.gen(function*(){return(yield*e.update(lt).set({lockedUntil:i,claimReceipt:s}).where(k(f(lt._deleted,!1),m`json_extract(${lt.jobPayload}, '$.sourceScheduledFlowId') = ${n}`,Zt(Pe(lt.lockedUntil),Fo(lt.lockedUntil,o)))).returning({id:lt.id,payload:lt.jobPayload})).map(({id:c,payload:l})=>({id:c,...l})).sort((c,l)=>c.sequence-l.sequence)}),releaseFlowDispatchJobs:(n,o)=>e.update(lt).set({lockedUntil:null,claimReceipt:null}).where(k(f(lt._deleted,!1),f(lt.claimReceipt,o),m`json_extract(${lt.jobPayload}, '$.sourceScheduledFlowId') = ${n}`)),extendFlowDispatchClaim:(n,o,i)=>Br.gen(function*(){return(yield*e.update(lt).set({lockedUntil:i}).where(k(f(lt._deleted,!1),f(lt.claimReceipt,o),m`json_extract(${lt.jobPayload}, '$.sourceScheduledFlowId') = ${n}`)).returning({id:lt.id})).length>0}),deleteFlowDispatchJob:(n,o)=>Br.gen(function*(){return(yield*e.delete(lt).where(o===void 0?f(lt.id,n):k(f(lt.id,n),f(lt.claimReceipt,o))).returning({id:lt.id})).length>0}),setProcessExecutionFinished:(n,o)=>Br.gen(function*(){let i=yield*Ie(),s=yield*It();yield*e.update(K).set({finishedAt:i,businessDuration:o,updatedAt:i,updatedBy:s.by}).where(f(K.id,n))}),setProcessExecutionFailed:(n,o)=>Br.gen(function*(){let i=yield*Ie(),s=yield*It();yield*e.update(K).set({finishedAt:i,abandonedReason:o,updatedAt:i,updatedBy:s.by}).where(k(f(K.id,n),Pe(K.finishedAt),Pe(K.abandonedAt)))}),getProcessIdForExecution:(n)=>Br.gen(function*(){return(yield*e.select({processId:q.processId}).from(K).innerJoin(q,f(K.processStateId,q.id)).where(f(K.id,n)).limit(1))[0]?.processId??null}),getExecutionDetailsForCompletion:(n)=>Br.gen(function*(){return(yield*e.select({createdAtMs:m`(${K.createdAt} - 2440587.5) * 86400000`.as("created_at_ms"),orgUnitId:te.orgUnitId}).from(K).innerJoin(q,f(K.processStateId,q.id)).innerJoin(te,f(q.processId,te.id)).where(f(K.id,n)).limit(1))[0]??null}),getTargetStepSlaInfo:(n)=>Br.gen(function*(){return(yield*e.select({slaValue:r.slaValue,slaUnit:r.slaUnit,slaWarning:r.slaWarning,orgUnitId:te.orgUnitId}).from(J).innerJoin(r,f(J.targetStepId,r.id)).innerJoin(te,f(r.processId,te.id)).where(k(f(J.id,n),f(J._deleted,!1))).limit(1))[0]??null}),targetStepHasRole:(n)=>Br.gen(function*(){let o=yield*e.select({roleId:r.roleId}).from(J).innerJoin(r,f(J.targetStepId,r.id)).where(k(f(J.id,n),f(J._deleted,!1))).limit(1);if(!o[0])return null;return o[0].roleId!==null}),targetStepHasForEach:(n)=>Br.gen(function*(){let o=yield*e.select({hasForEach:r.hasForEach}).from(J).innerJoin(r,f(J.targetStepId,r.id)).where(k(f(J.id,n),f(J._deleted,!1))).limit(1);if(!o[0])return null;return o[0].hasForEach}),countActiveTodosForStep:(n,o)=>Br.gen(function*(){let i=yield*e.select({count:m`COUNT(*)`.as("count")}).from(C).innerJoin(J,f(C.flowId,J.id)).where(k(f(C.processExecutionId,n),f(J.targetStepId,o),f(C._deleted,!1)));return Number(i[0]?.count??0)}),getStepRetryLimitByPath:(n)=>Br.gen(function*(){let o=yield*e.select({retryLimit:M.retryLimit}).from(M).where(k(f(M.path,n),f(M._deleted,!1))).limit(1);if(!o[0])return yield*Br.logWarning("getStepRetryLimitByPath: step not found",{stepPath:n}),null;return o[0].retryLimit}),queryNotificationRecipientByProviderUserId:(n)=>Br.gen(function*(){let i=(yield*e.select({providerUserId:N.id,userId:N.userId,email:N.email,name:N.name,firstName:N.firstName,lastName:N.lastName,notificationPreference:Er.notificationPreference}).from(N).leftJoin(Er,k(f(Er.userId,N.userId),f(Er._deleted,!1))).where(k(f(N.id,n),f(N._deleted,!1))).limit(1))[0];return i?X_(i):null}),queryNotificationRecipientsByRoleId:(n)=>Br.gen(function*(){return(yield*e.select({providerUserId:N.id,userId:N.userId,email:N.email,name:N.name,firstName:N.firstName,lastName:N.lastName,notificationPreference:Er.notificationPreference}).from(xt).innerJoin(N,f(xt.providerUserId,N.id)).leftJoin(Er,k(f(Er.userId,N.userId),f(Er._deleted,!1))).where(k(f(xt.roleId,n),f(xt._deleted,!1),f(N._deleted,!1)))).map(X_)}),queryNotificationRecipientsByRolePath:(n)=>Br.gen(function*(){return(yield*e.select({providerUserId:N.id,userId:N.userId,email:N.email,name:N.name,firstName:N.firstName,lastName:N.lastName,notificationPreference:Er.notificationPreference}).from(xt).innerJoin(N,f(xt.providerUserId,N.id)).innerJoin(F,f(xt.roleId,F.id)).leftJoin(Er,k(f(Er.userId,N.userId),f(Er._deleted,!1))).where(k(f(F.path,n),f(xt._deleted,!1),f(N._deleted,!1),f(F._deleted,!1)))).map(X_)})}}));import{Layer as CDe}from"effect";import{Effect as nk,Layer as pDe}from"effect";var ute=pDe.effect(G1,nk.gen(function*(){let e=yield*Ee;return{cleanupExecutions:()=>nk.gen(function*(){yield*e.delete(Et);let r=(yield*e.select({id:C.id}).from(C)).length;yield*e.delete(C);let o=(yield*e.select({id:ot.id}).from(ot)).length;yield*e.delete(ot);let s=(yield*e.select({id:lt.id}).from(lt)).length;yield*e.delete(lt),yield*e.delete(aa);let c=(yield*e.select({id:K.id}).from(K)).length;yield*e.delete(K);let d=(yield*e.select({id:q.id}).from(q)).length;return yield*e.delete(q),yield*nk.log("Cleanup completed").pipe(nk.annotateLogs({todosDeleted:r,scheduledFlowsDeleted:o,executionsDeleted:c,statesDeleted:d,jobsDeleted:s})),{todosDeleted:r,scheduledFlowsDeleted:o,executionsDeleted:c,statesDeleted:d,jobsDeleted:s}})}}));import{Effect as _v,Layer as fDe}from"effect";var pte=fDe.effect(J1,_v.gen(function*(){let e=yield*Ee;return{pullDraftProcessExecution:(t,r)=>_v.gen(function*(){let n=yield*It();if(!n.id)return[];let o=[f(ca.isDraft,!0),f(q.startedByUserId,n.id)];if(t){let s=m`CAST(ROUND((${q.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`,a=Zt(Vr(s,t.updatedAt),k(f(s,t.updatedAt),Vr(q.id,t.id)));if(a)o.push(a)}return(yield*e.select({id:q.id,processId:q.processId,startStepId:q.startStepId,startedByUserId:q.startedByUserId,startedByEmail:N.email,name:te.name,startStepPath:M.path,state:q.state,lastSaved:q.updatedAt,updatedAt:m`CAST(ROUND((${q.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`.as("updated_at_millis"),deleted:q._deleted}).from(q).innerJoin(te,f(q.processId,te.id)).innerJoin(M,f(q.startStepId,M.id)).innerJoin(ca,f(q.id,ca.id)).leftJoin(N,k(f(q.startedByUserId,N.userId),f(N._deleted,!1))).where(k(...o)).orderBy(q.updatedAt,q.id).limit(r)).map((s)=>({...s,state:s.state}))}),insertProcessState:(t,r,n,o)=>_v.gen(function*(){let i=yield*Ie(),s=yield*It(),c=(yield*e.select({id:M.id}).from(M).where(k(f(M.path,n),f(M.processId,r),f(M._deleted,!1))).limit(1))[0];if(!c)return yield*new Jw({path:n,message:`Step not found for path: ${n}`});if((yield*e.insert(q).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:q.id}).returning({id:q.id})).length===0)return yield*new kc({processStateId:t,message:`Draft process execution already exists: ${t}`});return t}),updateProcessState:(t,r,n)=>_v.gen(function*(){let o=yield*Ie(),i=yield*It();if(n.id!==t)return yield*new kc({processStateId:t,message:"Assumed master state targets a different document"});let s=i.id;if(!s)return yield*new kc({processStateId:t,message:"Draft process execution requires a persisted user owner"});if(n.deleted)return yield*new kc({processStateId:t,message:`Cannot update deleted process execution state: ${t}`});let a=m`CAST(ROUND((${q.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`,c=JSON.stringify(n.state),l=m`
|
|
841
|
+
NOT EXISTS (
|
|
842
|
+
SELECT fullkey, atom, type FROM json_tree(${q.state})
|
|
843
|
+
EXCEPT
|
|
844
|
+
SELECT fullkey, atom, type FROM json_tree(${c})
|
|
845
|
+
)
|
|
846
|
+
AND NOT EXISTS (
|
|
847
|
+
SELECT fullkey, atom, type FROM json_tree(${c})
|
|
848
|
+
EXCEPT
|
|
849
|
+
SELECT fullkey, atom, type FROM json_tree(${q.state})
|
|
850
|
+
)
|
|
851
|
+
`;if((yield*e.update(q).set({state:r,updatedAt:o,updatedBy:i.by,_deleted:!1}).where(k(f(q.id,t),f(q.processId,n.processId),l,f(q._deleted,!1),f(a,Math.round(n.updatedAt)),f(q.startedByUserId,s),Ye(q.id,e.select({id:ca.id}).from(ca).where(f(ca.isDraft,!0))))).returning({id:q.id})).length===0)return yield*new kc({processStateId:t,message:`Cannot update deleted process execution state: ${t}`});return t}),deleteProcessState:(t,r)=>_v.gen(function*(){let n=yield*Ie(),o=yield*It();if(r.id!==t)return yield*new kc({processStateId:t,message:"Assumed master state targets a different document"});let i=o.id;if(!i)return yield*new kc({processStateId:t,message:"Draft process execution requires a persisted user owner"});if(r.deleted)return yield*new kc({processStateId:t,message:`Cannot delete from a deleted assumed master state: ${t}`});let s=m`CAST(ROUND((${q.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`,a=JSON.stringify(r.state),c=m`
|
|
852
|
+
NOT EXISTS (
|
|
853
|
+
SELECT fullkey, atom, type FROM json_tree(${q.state})
|
|
854
|
+
EXCEPT
|
|
855
|
+
SELECT fullkey, atom, type FROM json_tree(${a})
|
|
856
|
+
)
|
|
857
|
+
AND NOT EXISTS (
|
|
858
|
+
SELECT fullkey, atom, type FROM json_tree(${a})
|
|
859
|
+
EXCEPT
|
|
860
|
+
SELECT fullkey, atom, type FROM json_tree(${q.state})
|
|
861
|
+
)
|
|
862
|
+
`;if((yield*e.update(q).set({_deleted:!0,updatedAt:n,updatedBy:o.by}).where(k(f(q.id,t),f(q.processId,r.processId),c,f(q._deleted,!1),f(s,Math.round(r.updatedAt)),f(q.startedByUserId,i),Ye(q.id,e.select({id:ca.id}).from(ca).where(f(ca.isDraft,!0))))).returning({id:q.id})).length===0)return yield*new kc({processStateId:t,message:`Cannot delete inaccessible, changed, or non-draft process execution state: ${t}`});return t}),getProcessStates:(t)=>_v.gen(function*(){let r=yield*It();if(!r.id||t.length===0)return[];return(yield*e.select({id:q.id,processId:q.processId,startStepId:q.startStepId,startedByUserId:q.startedByUserId,startedByEmail:N.email,name:te.name,startStepPath:M.path,state:q.state,lastSaved:q.updatedAt,updatedAt:m`CAST(ROUND((${q.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`.as("updated_at_millis"),deleted:q._deleted}).from(q).innerJoin(te,f(q.processId,te.id)).innerJoin(M,f(q.startStepId,M.id)).innerJoin(ca,f(q.id,ca.id)).leftJoin(N,k(f(q.startedByUserId,N.userId),f(N._deleted,!1))).where(k(Ye(q.id,t),f(ca.isDraft,!0),f(q.startedByUserId,r.id))).orderBy(q.updatedAt,q.id)).map((o)=>({...o,state:o.state}))})}}));import{Effect as ok,Layer as mDe}from"effect";var fte=mDe.effect(o$,ok.gen(function*(){let e=yield*Ee;return{insertProcessState:(t,r,n,o,i)=>ok.gen(function*(){let s=yield*Ie(),a=yield*It(),l=(yield*e.select({id:M.id}).from(M).where(k(f(M.path,r),f(M._deleted,!1))).limit(1))[0];if(!l)return yield*new Jw({path:r,message:`Step not found for path: ${r}`});let d=yield*e.insert(q).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:q.id});return{processStateId:(yield*Or(d)).id,stepId:l.id}}),insertProcessExecution:(t,r,n=!1)=>ok.gen(function*(){let o=yield*Ie(),i=yield*It(),s=yield*e.insert(K).values({...r!==void 0?{id:r}:{},processStateId:t,withoutWaiting:n,createdAt:o,updatedAt:o,createdBy:i.by,updatedBy:i.by}).returning({id:K.id});return(yield*Or(s)).id}),getProcessExecutionStartInfo:(t)=>ok.gen(function*(){let n=(yield*e.select({executionId:K.id,withoutWaiting:K.withoutWaiting,processId:q.processId,stepId:M.id,startStepPath:M.path,state:q.state}).from(K).innerJoin(q,k(f(K.processStateId,q.id),f(q._deleted,!1))).innerJoin(M,k(f(q.startStepId,M.id),f(M._deleted,!1))).where(k(f(K.id,t),f(K._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 yDe,Layer as hDe}from"effect";var _$=hDe.effect(i$,yDe.gen(function*(){let e=yield*Ee;return{queryFlowsBySourceStepId:(t)=>e.select({id:J.id,sourceStepId:J.sourceStepId,targetStepId:J.targetStepId}).from(J).where(k(f(J.sourceStepId,t),f(J._deleted,!1)))}}));import{Effect as mte,Layer as gDe,Option as yte}from"effect";var k$=gDe.effect(s$,mte.gen(function*(){let e=yield*Ee;return{queryOAuthClientByClientId:(t)=>mte.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 yte.some(o)}return yte.none()}),addPermittedClientRole:(t,r)=>e.insert(Ji).values({oauthClientId:t,roleId:r}).onConflictDoUpdate({target:[Ji.oauthClientId,Ji.roleId],targetWhere:m`_deleted = 0`,set:{updatedAt:m`julianday('now')`}}),addPermittedClientEmail:(t,r)=>e.insert(Rs).values({oauthClientId:t,email:r}).onConflictDoUpdate({target:[Rs.oauthClientId,Rs.email],targetWhere:m`_deleted = 0`,set:{updatedAt:m`julianday('now')`}})}}));import{Effect as D$,Layer as SDe}from"effect";var vDe=(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)},hte=SDe.effect(a$,D$.gen(function*(){let e=yield*Ee;return{queryRoot:D$.gen(function*(){return(yield*e.select().from(G).where(k(Pe(G.parentOrgUnitId),na(G._deleted))).limit(1))[0]??null}),queryChildren:(t)=>e.select().from(G).where(k(f(G.parentOrgUnitId,t),na(G._deleted))),queryProcesses:(t)=>e.select().from(te).where(k(f(te.orgUnitId,t),f(te._deleted,!1))),queryRoles:(t)=>e.select().from(F).where(k(f(F.orgUnitId,t),f(F._deleted,!1))),queryOrgLevels:D$.gen(function*(){let t=yield*e.select({id:G.id,parentOrgUnitId:G.parentOrgUnitId,orgUnitLevel:G.orgUnitLevel}).from(G).where(na(G._deleted));return vDe(t)})}}));import{Effect as kv,Layer as gte}from"effect";var Ste=gte.effect(c$,kv.gen(function*(){let e=yield*Ee;return{queryAllProcesses:kv.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(ju)}),listProcesses:(t)=>kv.gen(function*(){let r=[f(te._deleted,!1)];if(t.processPath!=null)r.push(f(te.path,t.processPath));return(yield*e.select({id:te.id,path:te.path,name:te.name,category:G.name,purpose:te.purpose,startStepPath:M.path,activeInstances:Df.activeProcesses}).from(te).innerJoin(G,f(te.orgUnitId,G.id)).innerJoin(kf,f(te.id,kf.id)).innerJoin(M,f(kf.startStep,M.id)).leftJoin(Df,f(te.id,Df.id)).where(k(...r)).orderBy(te.path,te.id).limit(t.limit).offset(t.offset)).map((o)=>({...o,activeInstances:o.activeInstances??0}))}).pipe(ju)}})),vte=gte.effect(l$,kv.gen(function*(){let e=yield*Ee,t=(n,o)=>kv.gen(function*(){let i=e.$with("duration_stats").as(e.select({processId:q.processId,minDurationMs:m`MIN((${K.finishedAt} - ${K.createdAt}) * 86400000)`.as("min_duration_ms"),maxDurationMs:m`MAX((${K.finishedAt} - ${K.createdAt}) * 86400000)`.as("max_duration_ms")}).from(K).innerJoin(q,f(K.processStateId,q.id)).where(k(mr(K.finishedAt),f(K._deleted,!1),f(q._deleted,!1))).groupBy(q.processId)),s=e.with(i).select({id:te.id,name:te.name,path:te.path,purpose:te.purpose,updatedAt:m`CAST(ROUND((${te.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`.as("updated_at_millis"),deleted:te._deleted,orgUnitId:G.id,orgUnitName:G.name,orgUnitLevel:G.orgUnitLevel,startStepPath:M.path,formFieldCount:M.formFields,activeInstances:Df.activeProcesses,minDurationMs:i.minDurationMs,maxDurationMs:i.maxDurationMs}).from(te).innerJoin(G,f(te.orgUnitId,G.id)).innerJoin(kf,f(te.id,kf.id)).innerJoin(M,f(kf.startStep,M.id)).leftJoin(Df,f(te.id,Df.id)).leftJoin(i,f(te.id,i.processId)).where(n).orderBy(te.updatedAt,te.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=m`CAST(ROUND((${te.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`;return Zt(Vr(o,n.updatedAt),k(f(o,n.updatedAt),Vr(te.id,n.id)))};return{pullProcess:(n,o)=>t(r(n),o),getProcesses:(n)=>n.length===0?kv.succeed([]):t(Ye(te.id,n))}}));import{DateTime as sk,Effect as Zi,Layer as xDe,Option as Td}from"effect";var ik=(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:sk.toDateUtc(e.createdAt),updatedAt:sk.toDateUtc(e.updatedAt),createdBy:e.createdBy,updatedBy:e.updatedBy}),xte=(e)=>e.replace(/[\\%_]/g,"\\$&"),Ete=xDe.effect(d$,Zi.gen(function*(){let e=yield*Ee;return{queryProviderUserByUserId:(t)=>Zi.gen(function*(){let r=yield*e.query.providerUser.findMany({with:{user:!0,orgUnit:!0},where:{userId:t}});if(r.length&&r[0])return Td.some(ik(r[0]));else return Td.none()}),queryProviderUserByProviderUserId:(t)=>Zi.gen(function*(){let r=yield*e.query.providerUser.findMany({with:{user:!0,orgUnit:!0},where:{id:t}});if(r.length&&r[0])return Td.some(ik(r[0]));else return Td.none()}),queryProviderUserByEmail:(t)=>Zi.gen(function*(){let r=t.trim().toLowerCase(),o=(yield*e.select({providerUser:N,user:oe,orgUnit:G}).from(N).innerJoin(oe,f(N.userId,oe.id)).innerJoin(G,f(N.orgUnitId,G.id)).where(k(m`lower(${N.email}) = ${r}`,f(N._deleted,!1),f(oe._deleted,!1),f(G._deleted,!1))).limit(1))[0];if(!o)return Td.none();return Td.some(ik({...o.providerUser,user:o.user,orgUnit:o.orgUnit}))}),queryProviderUsers:(t,r)=>Zi.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)=>m`${i.name} like ${`%${xte(n)}%`} escape ${"\\"}`},{RAW:(i)=>m`${i.email} like ${`%${xte(n)}%`} escape ${"\\"}`}]},orderBy:{name:"asc",email:"asc"},limit:r.limit,offset:r.offset})).map(ik)}),queryAllRoles:()=>Zi.gen(function*(){return(yield*e.query.role.findMany({where:{_deleted:!1}})).map((r)=>({id:r.id,name:r.name,path:r.path}))}),queryProviderUserRoleIds:(t)=>Zi.gen(function*(){return(yield*e.query.providerUserRole.findMany({where:{providerUserId:t,_deleted:!1}})).map((n)=>n.roleId)}),queryProviderUserRolePaths:(t)=>Zi.gen(function*(){return(yield*e.query.providerUserRole.findMany({with:{role:!0},where:{providerUserId:t,_deleted:!1}})).map((n)=>n.role.path)}),queryProviderUserRolePathsByProviderUserIds:(t)=>Zi.gen(function*(){if(t.length===0)return new Map;let r=yield*e.query.providerUserRole.findMany({with:{role:!0},where:{RAW:(o)=>k(Ye(o.providerUserId,[...t]),f(o._deleted,!1))??m`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)=>Zi.gen(function*(){if(yield*e.delete(mi).where(f(mi.providerUserId,t)),r.length>0)yield*e.insert(mi).values(r.map((n)=>({providerUserId:t,roleId:n})))}),queryRoleByPath:(t)=>Zi.gen(function*(){let r=yield*e.query.role.findMany({where:{path:t,_deleted:!1}});if(r.length&&r[0]){let n=r[0];return Td.some({id:n.id,name:n.name,path:n.path})}return Td.none()}),addPermittedRole:(t,r)=>e.insert(mi).values({providerUserId:t,roleId:r}).onConflictDoUpdate({target:[mi.providerUserId,mi.roleId],targetWhere:m`_deleted = 0`,set:{updatedAt:m`julianday('now')`}}),findInvitationRoleIds:(t)=>Zi.gen(function*(){let r=t.toLowerCase();return(yield*e.select({roleId:Je.roleId}).from(D).innerJoin(Je,f(Je.invitationId,D.id)).innerJoin(F,f(F.id,Je.roleId)).where(k(f(D.invitationPendingEmail,r),f(D.invitationStatus,"pending"),f(D._deleted,!1),f(Je._deleted,!1),f(F._deleted,!1)))).map((o)=>o.roleId)}),findRootOrgUnit:()=>Zi.gen(function*(){let r=(yield*e.select({id:G.id,path:G.path}).from(G).where(k(Pe(G.parentOrgUnitId),f(G._deleted,!1))).limit(1))[0];return r?Td.some({id:r.id,path:r.path}):Td.none()}),createProviderUserFromInvitation:(t)=>Zi.gen(function*(){let r=yield*sk.now,n=t.email.toLowerCase(),o=yield*e.insert(oe).values({provider:"m2m",sub:`m2m:${n}`,lastLoggedIn:r}).returning(),i=yield*Or(o),s=yield*e.insert(N).values({userId:i.id,email:n,name:n.split("@")[0]??n,firstName:"",lastName:"",picture:"",locale:"",orgUnitId:t.orgUnitId}).returning(),a=yield*Or(s);return{userId:i.id,providerUserId:a.id}}),acceptPendingInvitationForProviderUser:(t)=>Zi.gen(function*(){let r=yield*sk.now,n=t.email.toLowerCase();return(yield*e.update(D).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:m`coalesce(${D.registrationLinkGeneration}, 0) + 1`,updatedAt:r,updatedBy:"SYSTEM"}).where(k(f(D.invitationPendingEmail,n),f(D.invitationStatus,"pending"),f(D._deleted,!1))).returning({id:D.id})).length>0}),assignProviderUserRoles:(t,r)=>Zi.gen(function*(){if(r.length===0)return;yield*e.insert(xt).values(r.map((n)=>({providerUserId:t,roleId:n})))})}}));import{Effect as bte,Layer as EDe}from"effect";var O$=EDe.effect(p$,bte.gen(function*(){let e=yield*Ee;return{queryWorkflowByProcessPath:(t)=>bte.gen(function*(){let n=(yield*e.select({id:te.id,name:te.name,path:te.path,purpose:te.purpose}).from(te).where(k(f(te.path,t),f(te._deleted,!1))).limit(1))[0];if(!n)return yield*new u$({path:t,message:`Process not found: ${t}`});let o=yield*e.select({id:M.id,name:M.name,path:M.path,purpose:M.purpose,processId:M.processId,roleId:M.roleId,roleName:F.name,rolePath:F.path,phaseId:mo.id,phaseName:mo.name,phasePath:mo.path,phaseOrder:mo.phaseOrder,isStartStep:_c.canStartProcess,isEmbedded:M.embedded}).from(M).leftJoin(F,f(M.roleId,F.id)).leftJoin(mo,f(M.phaseId,mo.id)).innerJoin(_c,f(M.id,_c.id)).where(k(f(M.processId,n.id),f(M._deleted,!1),Zt(Pe(M.roleId),f(F._deleted,!1)))),i=o.map((l)=>l.id),s=i.length>0?yield*e.select({id:J.id,sourceStepId:J.sourceStepId,targetStepId:J.targetStepId,condition:J.condition,fallbackBranch:J.fallbackBranch,errorBranch:J.errorBranch,errorTags:J.errorTags,schedule:J.schedule}).from(J).where(k(f(J._deleted,!1),Zt(Ye(J.sourceStepId,i),Ye(J.targetStepId,i)))):[],a=yield*e.select({roleId:fn.roleId,roleName:F.name,rolePath:F.path,responsibility:fn.responsibility,order:fn.responsibilityOrder}).from(fn).innerJoin(F,f(fn.roleId,F.id)).where(k(f(fn.processId,n.id),f(fn._deleted,!1),f(F._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:Qw(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 Cn,Effect as gr,Layer as bDe}from"effect";var wDe=(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")},Jy=bDe.effect(Nf,gr.gen(function*(){let e=yield*Ee,t=(l)=>gr.gen(function*(){return yield*e.select({id:F.id,name:F.name,path:F.path}).from(Je).innerJoin(F,f(F.id,Je.roleId)).where(k(f(Je.invitationId,l),f(Je._deleted,!1),f(F._deleted,!1))).orderBy(F.path)}),r=(l)=>{if(l===Jr.Accepted)return Jr.Accepted;if(l===Jr.LegacyClosed)return Jr.LegacyClosed;return Jr.Pending},n=(l)=>{if(l===Of.Model)return Of.Model;if(l===Of.Dashboard)return Of.Dashboard;if(l===Of.Process)return Of.Process;return Of.Legacy},o=(l)=>l?Cn.toDateUtc(l):null,i=(l)=>{if(l.lifecycleStatus!==Jr.Pending)return wd.NotGenerated;if(l.tokenHash){if(l.expiresAt&&Cn.toEpochMillis(l.expiresAt)<=Cn.toEpochMillis(l.now))return wd.Expired;return wd.Active}if(l.revokedAt)return wd.Revoked;return wd.NotGenerated},s={registrationTokenHash:null,registrationEncryptionVersion:null,registrationEncryptionNonce:null,registrationAuthenticationTag:null,registrationEncryptedToken:null,registrationLinkExpiresAt:null,registrationLinkGeneration:m`coalesce(${D.registrationLinkGeneration}, 0) + 1`},a=(l,d)=>gr.gen(function*(){let u=yield*t(l.id),p=r(l.invitationStatus);return{id:l.id,email:l.email,status:p,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:p,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:D.id,email:D.email,invitationStatus:D.invitationStatus,invitationSource:D.invitationSource,invitationAcceptedAt:D.invitationAcceptedAt,invitationAcceptedByProvider:D.invitationAcceptedByProvider,invitationAcceptedBySubject:D.invitationAcceptedBySubject,acceptedByProviderUserId:D.acceptedByProviderUserId,invitationLegacyClosedAt:D.invitationLegacyClosedAt,invitationLegacyClosureReason:D.invitationLegacyClosureReason,registrationTokenHash:D.registrationTokenHash,registrationLinkExpiresAt:D.registrationLinkExpiresAt,registrationLinkGeneratedAt:D.registrationLinkGeneratedAt,registrationLinkGeneratedBy:D.registrationLinkGeneratedBy,registrationLinkRevealedAt:D.registrationLinkRevealedAt,registrationLinkRevealedBy:D.registrationLinkRevealedBy,registrationLinkRevokedAt:D.registrationLinkRevokedAt,registrationLinkRevokedBy:D.registrationLinkRevokedBy,registrationLinkGeneration:D.registrationLinkGeneration};return{queryAllUsers:(l,d)=>gr.gen(function*(){let u=(l-1)*d,y=(yield*e.select({count:m`count(*)`}).from(oe).where(f(oe._deleted,!1)))[0]?.count??0;return{items:(yield*e.select({id:oe.id,provider:oe.provider,sub:oe.sub,lastLoggedIn:oe.lastLoggedIn,providerUserId:N.id,providerUserName:N.name,providerUserEmail:N.email}).from(oe).leftJoin(N,k(f(N.userId,oe.id),f(N._deleted,!1))).where(f(oe._deleted,!1)).orderBy(eo(oe.lastLoggedIn),oe.id).limit(d).offset(u)).map((S)=>({id:S.id,provider:S.provider,sub:S.sub,lastLoggedIn:Cn.toDateUtc(S.lastLoggedIn),isProviderUser:S.providerUserId!==null,providerUserName:S.providerUserName,providerUserEmail:S.providerUserEmail})),totalCount:y}}),queryAllOAuthProviders:(l,d)=>gr.gen(function*(){let u=(l-1)*d,y=(yield*e.select({count:m`count(*)`}).from(Ft).where(f(Ft._deleted,!1)))[0]?.count??0;return{items:(yield*e.select({id:Ft.id,providerName:Ft.providerName}).from(Ft).where(f(Ft._deleted,!1)).orderBy(Ft.providerName).limit(d).offset(u)).map((S)=>({id:S.id,providerName:S.providerName})),totalCount:y}}),queryAllInvitations:(l,d,u=Jr.Pending)=>gr.gen(function*(){let p=(l-1)*d,y=k(f(D._deleted,!1),f(D.invitationStatus,u)),E=(yield*e.select({count:m`count(*)`}).from(D).where(y))[0]?.count??0,S=yield*e.select(c).from(D).where(y).orderBy(D.email).limit(d).offset(p),x=yield*Cn.now,w=[];for(let _ of S)w.push(yield*a(_,x));return{items:w,totalCount:E}}),queryInvitationDetail:(l)=>gr.gen(function*(){let u=(yield*e.select(c).from(D).where(k(f(D.id,l),f(D._deleted,!1))).limit(1))[0];if(!u)return null;return yield*a(u,yield*Cn.now)}),queryPendingInvitationByEmail:(l)=>gr.gen(function*(){let u=(yield*e.select(c).from(D).where(k(f(D.invitationPendingEmail,l),f(D.invitationStatus,Jr.Pending),f(D._deleted,!1))).limit(1))[0];if(!u)return null;return yield*a(u,yield*Cn.now)}),queryInvitationByNormalizedEmail:(l)=>gr.gen(function*(){let u=(yield*e.select(c).from(D).where(k(f(D.invitationPendingEmail,l),f(D.invitationStatus,Jr.Pending),f(D._deleted,!1))).limit(1))[0];if(u)return yield*a(u,yield*Cn.now);let y=(yield*e.select(c).from(D).where(k(f(D.email,l),f(D._deleted,!1))).orderBy(eo(D.createdAt)).limit(1))[0];if(!y)return null;return yield*a(y,yield*Cn.now)}),queryUserDetail:(l)=>gr.gen(function*(){let u=(yield*e.select({id:oe.id,provider:oe.provider,sub:oe.sub,lastLoggedIn:oe.lastLoggedIn,providerUserId:N.id,providerUserEmail:N.email,providerUserName:N.name,providerUserFirstName:N.firstName,providerUserLastName:N.lastName,notificationPreference:Er.notificationPreference}).from(oe).leftJoin(N,k(f(N.userId,oe.id),f(N._deleted,!1))).leftJoin(Er,k(f(Er.userId,oe.id),f(Er._deleted,!1))).where(k(f(oe.id,l),f(oe._deleted,!1))).limit(1))[0];if(!u)return null;let p=[];if(u.providerUserId)p=(yield*e.select({roleId:F.id}).from(xt).innerJoin(F,k(f(xt.roleId,F.id),f(F._deleted,!1))).where(k(f(xt.providerUserId,u.providerUserId),f(xt._deleted,!1)))).map((E)=>E.roleId);let y=u.notificationPreference?Gy(u.notificationPreference):Gw;return{id:u.id,provider:u.provider,sub:u.sub,lastLoggedIn:Cn.toDateUtc(u.lastLoggedIn),providerUser:u.providerUserId?{id:u.providerUserId,email:u.providerUserEmail??"",name:u.providerUserName??"",firstName:u.providerUserFirstName??"",lastName:u.providerUserLastName??"",roleIds:p,notificationPreferences:y}:null}}),queryProviderUserDetail:(l)=>gr.gen(function*(){let u=(yield*e.select({id:N.id,email:N.email,name:N.name,firstName:N.firstName,lastName:N.lastName,notificationPreference:Er.notificationPreference}).from(N).leftJoin(Er,k(f(Er.userId,N.userId),f(Er._deleted,!1))).where(k(f(N.id,l),f(N._deleted,!1))).limit(1))[0];if(!u)return null;let p=yield*e.select({roleId:F.id}).from(xt).innerJoin(F,k(f(xt.roleId,F.id),f(F._deleted,!1))).where(k(f(xt.providerUserId,l),f(xt._deleted,!1))),y=u.notificationPreference?Gy(u.notificationPreference):Gw;return{id:u.id,email:u.email??"",name:u.name??"",firstName:u.firstName??"",lastName:u.lastName??"",roleIds:p.map((g)=>g.roleId),notificationPreferences:y}}),queryAllRoles:()=>gr.gen(function*(){return yield*e.select({id:F.id,name:F.name,path:F.path}).from(F).where(f(F._deleted,!1)).orderBy(F.path)}),queryRolesByIds:(l)=>gr.gen(function*(){if(l.length===0)return[];return yield*e.select({id:F.id,name:F.name,path:F.path}).from(F).where(k(Ye(F.id,[...l]),f(F._deleted,!1)))}),queryPaginatedRoles:(l,d)=>gr.gen(function*(){let u=(l-1)*d,y=(yield*e.select({count:m`count(*)`}).from(F).where(f(F._deleted,!1)))[0]?.count??0;return{items:yield*e.select({id:F.id,name:F.name,path:F.path}).from(F).where(f(F._deleted,!1)).orderBy(F.path).limit(d).offset(u),totalCount:y}}),queryProviderUserRoleIds:(l)=>gr.gen(function*(){return(yield*e.select({roleId:F.id}).from(xt).innerJoin(F,k(f(xt.roleId,F.id),f(F._deleted,!1))).where(k(f(xt.providerUserId,l),f(xt._deleted,!1)))).map((u)=>u.roleId)}),replaceProviderUserRoles:(l,d)=>gr.gen(function*(){if(yield*e.delete(xt).where(f(xt.providerUserId,l)),d.length>0){let u=yield*Cn.now,p=d.map((y)=>({providerUserId:l,roleId:y,createdAt:u,updatedAt:u,createdBy:"SYSTEM",updatedBy:"SYSTEM",_deleted:!1}));yield*e.insert(xt).values(p)}}),createInvitation:(l)=>gr.gen(function*(){let d=yield*Cn.now,u=yield*e.insert(D).values({invitationId:l.invitationId,email:l.email,invitationStatus:Jr.Pending,invitationSource:l.source,invitationPendingEmail:l.email,createdAt:d,updatedAt:d,createdBy:l.createdBy,updatedBy:l.updatedBy,_deleted:!1}).returning({id:D.id});return(yield*Or(u)).id}),updateInvitationDetails:(l,d)=>gr.gen(function*(){let u=yield*Cn.now,y=(yield*e.select({id:D.id,email:D.email}).from(D).where(k(f(D.id,l),f(D.invitationStatus,Jr.Pending),f(D._deleted,!1))).limit(1))[0];if(!y)return!1;let g=y.email!==d.email;if((yield*e.update(D).set({email:d.email,invitationPendingEmail:d.email,updatedAt:u,updatedBy:d.updatedBy}).where(k(f(D.id,l),f(D.invitationStatus,Jr.Pending),f(D._deleted,!1))).returning({id:D.id})).length===0)return!1;if(g)yield*e.update(D).set({...s,registrationLinkRevokedAt:u,registrationLinkRevokedBy:d.updatedBy,updatedAt:u,updatedBy:d.updatedBy}).where(k(f(D.id,l),f(D.invitationStatus,Jr.Pending),f(D._deleted,!1),mr(D.registrationTokenHash)));return!0}),replaceInvitationRoles:(l,d,u)=>gr.gen(function*(){let p=yield*Cn.now;if((yield*e.select({id:D.id}).from(D).where(k(f(D.id,l),f(D.invitationStatus,Jr.Pending),f(D._deleted,!1))).limit(1)).length===0)return;let g=yield*e.select({id:Je.id,roleId:Je.roleId,deleted:Je._deleted}).from(Je).where(f(Je.invitationId,l)),E=new Map(g.map((I)=>[I.roleId,I])),S=new Set(d),x=new Set(g.filter((I)=>!I.deleted).map((I)=>I.roleId)),w=d.some((I)=>!x.has(I))||[...x].some((I)=>!S.has(I)),_=g.filter((I)=>!I.deleted&&!S.has(I.roleId)).map((I)=>I.id);if(_.length>0)yield*e.update(Je).set({_deleted:!0,updatedAt:p,updatedBy:u}).where(Ye(Je.id,_));if(d.length===0){if(w)yield*e.update(D).set({...s,registrationLinkRevokedAt:p,registrationLinkRevokedBy:u,updatedAt:p,updatedBy:u}).where(k(f(D.id,l),f(D.invitationStatus,Jr.Pending),f(D._deleted,!1),mr(D.registrationTokenHash)));return}let T=d.flatMap((I)=>{let O=E.get(I);return O?.deleted?[O.id]:[]});if(T.length>0)yield*e.update(Je).set({_deleted:!1,updatedAt:p,updatedBy:u}).where(Ye(Je.id,T));let b=d.filter((I)=>!E.has(I));if(b.length>0)yield*e.insert(Je).values(b.map((I)=>({invitationId:l,roleId:I,createdAt:p,updatedAt:p,createdBy:u,updatedBy:u,_deleted:!1})));if(w)yield*e.update(D).set({...s,registrationLinkRevokedAt:p,registrationLinkRevokedBy:u,updatedAt:p,updatedBy:u}).where(k(f(D.id,l),f(D.invitationStatus,Jr.Pending),f(D._deleted,!1),mr(D.registrationTokenHash)))}),deleteInvitation:(l,d)=>gr.gen(function*(){let u=yield*Cn.now;if((yield*e.update(D).set({_deleted:!0,invitationPendingEmail:null,...s,registrationLinkRevokedAt:u,registrationLinkRevokedBy:d,updatedAt:u,updatedBy:d}).where(k(f(D.id,l),f(D.invitationStatus,Jr.Pending),f(D._deleted,!1))).returning({id:D.id})).length===0)return!1;return yield*e.update(Je).set({_deleted:!0,updatedAt:u,updatedBy:d}).where(k(f(Je.invitationId,l),f(Je._deleted,!1))),!0}),storeRegistrationLink:(l,d)=>gr.gen(function*(){let u=yield*Cn.now,p=Cn.unsafeMake(d.expiresAt),y=d.requireActiveLink?k(mr(D.registrationTokenHash),Vr(D.registrationLinkExpiresAt,u)):Zt(Pe(D.registrationTokenHash),Fo(D.registrationLinkExpiresAt,u));return(yield*e.update(D).set({registrationTokenHash:d.tokenHash,registrationEncryptionVersion:d.encryptionVersion,registrationEncryptionNonce:d.nonce,registrationAuthenticationTag:d.authenticationTag,registrationEncryptedToken:d.ciphertext,registrationLinkExpiresAt:p,registrationLinkGeneratedAt:u,registrationLinkGeneratedBy:d.actor,registrationLinkRevealedAt:null,registrationLinkRevealedBy:null,registrationLinkRevokedAt:null,registrationLinkRevokedBy:null,registrationLinkGeneration:d.generation,updatedAt:u,updatedBy:d.actor}).where(k(f(D.id,l),f(D.invitationStatus,Jr.Pending),f(D._deleted,!1),m`coalesce(${D.registrationLinkGeneration}, 0) = ${d.expectedPreviousGeneration}`,y)).returning({id:D.id})).length>0}),recordRegistrationLinkReveal:(l,d,u)=>gr.gen(function*(){let p=yield*Cn.now;return(yield*e.update(D).set({registrationLinkRevealedAt:p,registrationLinkRevealedBy:d,updatedAt:p,updatedBy:d}).where(k(f(D.id,l),f(D.invitationStatus,Jr.Pending),f(D._deleted,!1),f(D.registrationTokenHash,u.tokenHash),m`coalesce(${D.registrationLinkGeneration}, 0) = ${u.generation}`,Vr(D.registrationLinkExpiresAt,p))).returning({id:D.id})).length>0}),queryLiveRegistrationLink:(l,d)=>gr.gen(function*(){let u=Cn.unsafeMake(d),y=(yield*e.select({invitationId:D.id,tokenHash:D.registrationTokenHash,encryptionVersion:D.registrationEncryptionVersion,nonce:D.registrationEncryptionNonce,authenticationTag:D.registrationAuthenticationTag,ciphertext:D.registrationEncryptedToken,expiresAt:D.registrationLinkExpiresAt,generation:D.registrationLinkGeneration}).from(D).where(k(f(D.id,l),f(D.invitationStatus,Jr.Pending),f(D._deleted,!1),mr(D.registrationTokenHash),Vr(D.registrationLinkExpiresAt,u))).limit(1))[0];if(!y?.tokenHash||y.encryptionVersion===null||!y.nonce||!y.authenticationTag||!y.ciphertext||!y.expiresAt||y.generation===null)return null;return{invitationId:y.invitationId,tokenHash:y.tokenHash,encryptionVersion:y.encryptionVersion,nonce:y.nonce,authenticationTag:y.authenticationTag,ciphertext:y.ciphertext,expiresAt:Cn.toDateUtc(y.expiresAt),generation:y.generation}}),revokeRegistrationLink:(l,d,u)=>gr.gen(function*(){let p=yield*Cn.now,y=u?[f(D.registrationTokenHash,u.tokenHash),m`coalesce(${D.registrationLinkGeneration}, 0) = ${u.generation}`]:[mr(D.registrationTokenHash)];return(yield*e.update(D).set({...s,registrationLinkRevokedAt:p,registrationLinkRevokedBy:d,updatedAt:p,updatedBy:d}).where(k(f(D.id,l),f(D.invitationStatus,Jr.Pending),f(D._deleted,!1),...y)).returning({id:D.id})).length>0}),clearRegistrationLink:(l,d)=>gr.gen(function*(){let u=yield*Cn.now;yield*e.update(D).set({...s,registrationLinkRevokedAt:u,registrationLinkRevokedBy:d,updatedAt:u,updatedBy:d}).where(k(f(D.id,l),f(D._deleted,!1),mr(D.registrationTokenHash)))}),isPasskeyProviderEnabled:()=>gr.gen(function*(){return(yield*e.select({id:Ft.id}).from(Ft).where(k(f(Ft.providerName,"passkey"),f(Ft._deleted,!1))).limit(1)).length>0}),queryNotificationPreferences:(l)=>gr.gen(function*(){let u=(yield*e.select({notificationPreference:Er.notificationPreference}).from(Er).where(k(f(Er.userId,l),f(Er._deleted,!1))).limit(1))[0];if(!u?.notificationPreference)return Gw;return Gy(u.notificationPreference)}),updateNotificationPreferences:(l,d,u)=>gr.gen(function*(){let p=yield*Cn.now;yield*e.insert(Er).values({userId:l,notificationPreference:r$(d),createdAt:p,updatedAt:p,updatedBy:u}).onConflictDoUpdate({target:Er.userId,targetWhere:m`_deleted = 0`,set:{notificationPreference:r$(d),updatedAt:p,updatedBy:u}})}),queryProviderUserByEmail:(l)=>gr.gen(function*(){let d=l.trim().toLowerCase();return(yield*e.select({id:N.id,email:N.email}).from(N).where(k(m`lower(${N.email}) = ${d}`,f(N._deleted,!1))).limit(1))[0]??null}),queryRoleByPath:(l)=>gr.gen(function*(){return(yield*e.select({id:F.id,path:F.path}).from(F).where(k(f(F.path,l),f(F._deleted,!1))).limit(1))[0]??null}),grantProviderUserRole:(l,d,u)=>gr.gen(function*(){let y=(yield*e.select({id:xt.id,deleted:xt._deleted}).from(xt).where(k(f(xt.providerUserId,l),f(xt.roleId,d))).limit(1))[0];if(y&&!y.deleted)return{alreadyHadRole:!0};let g=yield*Cn.now;if(y?.deleted)return yield*e.update(xt).set({_deleted:!1,updatedAt:g,updatedBy:u}).where(f(xt.id,y.id)),{alreadyHadRole:!1};return{alreadyHadRole:(yield*e.insert(xt).values({providerUserId:l,roleId:d,createdAt:g,updatedAt:g,createdBy:u,updatedBy:u,_deleted:!1}).returning({id:xt.id}).pipe(gr.catchAll((S)=>wDe(S)?gr.succeed([]):gr.fail(S)))).length===0}})}}));import{strict as TDe}from"assert";import{DateTime as la,Effect as br,Layer as ADe,Schema as Uf}from"effect";var wte=ADe.effect(h$,br.gen(function*(){let e=yield*Ee,t=(r,n)=>br.gen(function*(){return(yield*e.select({id:C.id,createdBy:C.createdBy,processExecutionId:C.processExecutionId,processStateId:K.processStateId,startedByUserId:q.startedByUserId,targetStepId:M.id,targetStepPath:M.path,processPath:te.path,orgUnitPath:G.path,assignedToProviderUserId:C.assignedToProviderUserId,assignedToProviderUserEmail:N.email,correctionRequiredAt:C.correctionRequiredAt,createdAtMs:m`(${C.createdAt} - 2440587.5) * 86400000`.as("created_at_ms"),orgUnitId:te.orgUnitId,itemData:C.itemData,hasForEach:M.hasForEach,barrierScheduledFlowId:C.barrierScheduledFlowId,completed:C._deleted}).from(C).innerJoin(K,f(C.processExecutionId,K.id)).innerJoin(q,f(K.processStateId,q.id)).innerJoin(te,f(q.processId,te.id)).innerJoin(G,f(te.orgUnitId,G.id)).innerJoin(J,f(C.flowId,J.id)).innerJoin(M,f(J.targetStepId,M.id)).leftJoin(N,f(C.assignedToProviderUserId,N.id)).where(n?f(C.id,r):k(f(C.id,r),f(C._deleted,!1))).limit(1))[0]??null});return{queryTodoById:(r)=>t(r,!1),queryTodoForCompletionById:(r)=>t(r,!0),queryPublicTodoInfo:(r)=>br.gen(function*(){let o=(yield*e.select({todoId:C.id,deleted:C._deleted,failureReason:C.failureReason,correctionRequiredAt:C.correctionRequiredAt,abandonedAt:K.abandonedAt,stepPath:M.path,itemData:C.itemData}).from(C).innerJoin(K,f(C.processExecutionId,K.id)).innerJoin(J,f(C.flowId,J.id)).innerJoin(M,f(J.targetStepId,M.id)).where(f(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:Et.email}).from(Et).where(k(f(Et.toDoId,r),f(Et._deleted,!1))).orderBy(eo(Et.createdAt),eo(Et.id)).limit(1):[];return{todoId:o.todoId,status:i,stepPath:o.stepPath,latestPublicCompletionInvitationRecipientEmail:s[0]?.email??null,itemData:o.itemData}}),queryLatestPublicCompletionInvitationAttempt:(r)=>br.gen(function*(){return(yield*e.select({id:Et.id,email:Et.email}).from(Et).where(k(f(Et.toDoId,r),f(Et._deleted,!1))).orderBy(eo(Et.createdAt),eo(Et.id)).limit(1))[0]??null}),createPublicCompletionInvitationAttempt:({todoId:r,recipientEmail:n})=>br.gen(function*(){let o=yield*Ie(),i=yield*It(),s=yield*e.insert(Et).values({toDoId:r,email:n,createdAt:o,updatedAt:o,createdBy:i.by,updatedBy:i.by}).returning({id:Et.id});return(yield*Or(s)).id}),recordPublicCompletionInvitationAttemptReceipt:(r,n)=>br.gen(function*(){let o=yield*Ie(),i=yield*It();return(yield*e.update(Et).set({providerMessageId:n.providerMessageId,providerSentTo:n.providerSentTo,updatedAt:o,updatedBy:i.by}).where(k(f(Et.id,r),f(Et._deleted,!1))).returning({id:Et.id})).length>0}),queryPublicCompletionInvitationAttemptCallbackTarget:(r,n)=>br.gen(function*(){if((yield*e.select({id:Et.id}).from(Et).where(k(f(Et.toDoId,r),f(Et._deleted,!1))).orderBy(eo(Et.createdAt),eo(Et.id)).limit(1))[0]?.id!==n)return null;return(yield*e.select({attemptId:Et.id,todoId:C.id,providerMessageId:Et.providerMessageId,providerSentTo:Et.providerSentTo,processExecutionId:C.processExecutionId,assignedToProviderUserId:C.assignedToProviderUserId,roleId:M.roleId,stepPath:M.path,stepName:M.name,processName:te.name}).from(Et).innerJoin(C,f(Et.toDoId,C.id)).innerJoin(J,f(C.flowId,J.id)).innerJoin(M,f(J.targetStepId,M.id)).innerJoin(te,f(M.processId,te.id)).where(k(f(Et.id,n),f(Et.toDoId,r),f(Et._deleted,!1),f(C._deleted,!1),Pe(C.completedByUserId),Pe(C.completedByExternalParticipantId),Pe(C.completedByRoleId),Pe(C.failureReason),Pe(C.correctionRequiredAt),f(J._deleted,!1),f(M._deleted,!1),f(te._deleted,!1))).limit(1))[0]??null}),recordPublicCompletionInvitationAttemptDeliveryEvent:(r,n)=>br.gen(function*(){let o=yield*Ie(),i=yield*It();return(yield*e.update(Et).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(k(f(Et.id,r),f(Et._deleted,!1))).returning({id:Et.id})).length>0}),enterPublicCompletionCorrectionRequired:(r)=>br.gen(function*(){let n=yield*Ie(),o=yield*It(),s=(yield*e.update(C).set({correctionRequiredAt:n,correctionFailureReason:r.failureReason,correctionInvitationAttemptId:r.invitationAttemptId,updatedAt:n,updatedBy:o.by}).where(k(f(C.id,r.todoId),f(C._deleted,!1),Pe(C.completedByUserId),Pe(C.completedByExternalParticipantId),Pe(C.completedByRoleId),Pe(C.failureReason),Pe(C.correctionRequiredAt))).returning({id:C.id,processExecutionId:C.processExecutionId}))[0];if(!s)return!1;return yield*e.update(K).set({updatedAt:n,updatedBy:o.by}).where(f(K.id,s.processExecutionId)),!0}),queryPublicCompletionCorrectionRecipient:(r)=>br.gen(function*(){return(yield*e.select({recipientEmail:Et.email,failureReason:C.correctionFailureReason}).from(C).innerJoin(Et,f(C.correctionInvitationAttemptId,Et.id)).where(k(f(C.id,r),f(C._deleted,!1),Pe(C.completedByUserId),Pe(C.completedByExternalParticipantId),Pe(C.completedByRoleId),Pe(C.failureReason),mr(C.correctionRequiredAt),f(Et._deleted,!1))).limit(1))[0]??null}),clearPublicCompletionCorrectionRequired:(r)=>br.gen(function*(){let n=yield*Ie(),o=yield*It(),s=(yield*e.update(C).set({correctionRequiredAt:null,correctionFailureReason:null,correctionInvitationAttemptId:null,updatedAt:n,updatedBy:o.by}).where(k(f(C.id,r),f(C._deleted,!1),Pe(C.completedByUserId),Pe(C.completedByExternalParticipantId),Pe(C.completedByRoleId),Pe(C.failureReason),mr(C.correctionRequiredAt))).returning({id:C.id,processExecutionId:C.processExecutionId}))[0];if(!s)return!1;return yield*e.update(K).set({updatedAt:n,updatedBy:o.by}).where(f(K.id,s.processExecutionId)),!0}),updateProcessState:(r,n)=>br.gen(function*(){let o=yield*Ie(),i=yield*It();yield*e.update(q).set({state:m`json_patch(${q.state}, ${globalThis.JSON.stringify(n)})`,updatedAt:o,updatedBy:i.by}).where(f(q.id,r))}),updateProcessStateIfUnchanged:(r,n,o)=>br.gen(function*(){let i=yield*Ie(),s=yield*It(),a=la.toEpochMillis(i)>la.toEpochMillis(n)?i:la.add(n,{millis:1}),l=(yield*e.update(q).set({state:m`json_patch(${q.state}, ${globalThis.JSON.stringify(o)})`,updatedAt:a,updatedBy:s.by}).where(k(f(q.id,r),m`ROUND((${q.updatedAt} - 2440587.5) * 86400000) = ${Math.round(la.toEpochMillis(n))}`)).returning({updatedAtMs:m`ROUND((${q.updatedAt} - 2440587.5) * 86400000)`}))[0];return l?{kind:"updated",updatedAt:la.unsafeMake(l.updatedAtMs)}:{kind:"conflict"}}),appendProcessStateArrayItem:(r,n,o)=>br.gen(function*(){let i=yield*Ie(),s=yield*It(),a=`$.${n}`,c=globalThis.JSON.stringify(o);yield*e.update(q).set({state:m`json_set(COALESCE(${q.state}, json('{}')), ${a}, json_insert(COALESCE(json_extract(${q.state}, ${a}), json('[]')), '$[#]', json(${c})))`,updatedAt:i,updatedBy:s.by}).where(f(q.id,r))}),appendProcessStateArrayItemIfUnchanged:(r,n,o,i)=>br.gen(function*(){let s=yield*Ie(),a=yield*It(),c=la.toEpochMillis(s)>la.toEpochMillis(n)?s:la.add(n,{millis:1}),l=`$.${o}`,d=globalThis.JSON.stringify(i),p=(yield*e.update(q).set({state:m`json_set(COALESCE(${q.state}, json('{}')), ${l}, json_insert(COALESCE(json_extract(${q.state}, ${l}), json('[]')), '$[#]', json(${d})))`,updatedAt:c,updatedBy:a.by}).where(k(f(q.id,r),m`ROUND((${q.updatedAt} - 2440587.5) * 86400000) = ${Math.round(la.toEpochMillis(n))}`)).returning({updatedAtMs:m`ROUND((${q.updatedAt} - 2440587.5) * 86400000)`}))[0];return p?{kind:"updated",updatedAt:la.unsafeMake(p.updatedAtMs)}:{kind:"conflict"}}),completeToDo:(r,n,o,i,s)=>br.gen(function*(){let a=yield*Ie(),c=yield*It();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(f(C.id,r));let l=yield*e.select({id:C.id,processExecutionId:C.processExecutionId,flowId:C.flowId,processName:te.name,processPath:te.path,processOrgUnitPath:G.path,stepName:M.name,stepPath:M.path,rolePath:F.path,assignedToProviderUserId:C.assignedToProviderUserId,assignedToProviderUserEmail:N.email,role:F.name,description:M.purpose,formFields:M.formFields,updatedAt:m`(${C.updatedAt} - 2440587.5) * 86400000`.as("updated_at_millis"),createdAt:m`strftime('%Y-%m-%dT%H:%M:%fZ', (${C.createdAt} - 2440587.5) * 86400, 'unixepoch')`.as("created_at_iso"),slaTargetAt:m`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:m`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(K,f(C.processExecutionId,K.id)).innerJoin(q,f(K.processStateId,q.id)).innerJoin(te,f(q.processId,te.id)).innerJoin(G,f(te.orgUnitId,G.id)).innerJoin(J,f(C.flowId,J.id)).innerJoin(M,f(J.targetStepId,M.id)).leftJoin(F,f(M.roleId,F.id)).leftJoin(N,f(C.assignedToProviderUserId,N.id)).where(f(C.id,r)).limit(1);TDe(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:Z_(d.formFields),updatedAt:d.updatedAt,deleted:d.deleted,summary:[]}}),completeToDoIfOpen:(r)=>br.gen(function*(){let n=yield*Ie(),o=yield*It();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(k(f(C.id,r.todoId),f(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(f(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)=>br.gen(function*(){let s=yield*Ie(),a=yield*It();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(k(f(C.id,r),f(C._deleted,!1))).returning({id:C.id})).length>0}),failToDo:(r,n)=>br.gen(function*(){let o=yield*Ie(),i=yield*It();yield*e.update(C).set({failureReason:n,correctionRequiredAt:null,correctionFailureReason:null,correctionInvitationAttemptId:null,completedByUserId:null,_deleted:!1,updatedAt:o,updatedBy:i.by}).where(k(f(C.id,r),f(C._deleted,!1)))}),failAsyncToDo:(r,n)=>br.gen(function*(){let o=yield*Ie(),i=yield*It();return(yield*e.update(C).set({failureReason:n,updatedAt:o,updatedBy:i.by}).where(k(f(C.id,r),f(C._deleted,!1),Pe(C.failureReason),Pe(C.correctionRequiredAt))).returning({id:C.id})).length>0}),getProcessStateByTodoId:(r)=>br.gen(function*(){let n=yield*e.select({processExecutionId:K.id,processStateId:q.id,state:q.state,updatedAtMs:m`ROUND((${q.updatedAt} - 2440587.5) * 86400000)`,processStartedAt:m`(${K.createdAt} - 2440587.5) * 86400000`.as("process_started_at_millis")}).from(C).innerJoin(K,f(C.processExecutionId,K.id)).innerJoin(q,f(K.processStateId,q.id)).where(k(f(C.id,r),f(C._deleted,!1))).limit(1);if(!n[0])return null;let o=Uf.Record({key:Uf.String,value:Uf.Unknown}),i=Uf.decodeUnknownEither(o)(n[0].state??{});if(i._tag==="Left")return yield*new tk({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:la.unsafeMake(n[0].updatedAtMs),processStartedAt:la.unsafeFromDate(new Date(n[0].processStartedAt))}}),countActiveTodos:(r)=>br.gen(function*(){let n=yield*e.select({count:m`COUNT(*)`.as("count")}).from(C).where(k(f(C.processExecutionId,r),f(C._deleted,!1)));return Number(n[0]?.count??0)}),countPendingFlowJobs:(r,n)=>br.gen(function*(){let o=yield*e.select({count:m`COUNT(*)`.as("count")}).from(lt).where(k(f(lt.queue,n),f(lt._deleted,!1),m`json_extract(${lt.jobPayload}, '$.processExecutionId') = ${r}`));return Number(o[0]?.count??0)}),setProcessExecutionFinished:(r,n)=>br.gen(function*(){let o=yield*Ie(),i=yield*It();yield*e.update(K).set({finishedAt:o,businessDuration:n,updatedAt:o,updatedBy:i.by}).where(f(K.id,r))}),getProcessStatesByTodoIds:(r)=>br.gen(function*(){if(r.length===0)return[];let n=yield*e.select({todoId:C.id,processExecutionId:K.id,processStateId:q.id,state:q.state,stepPath:M.path,itemData:C.itemData,processStartedAt:m`(${K.createdAt} - 2440587.5) * 86400000`.as("process_started_at_millis")}).from(C).innerJoin(K,f(C.processExecutionId,K.id)).innerJoin(q,f(K.processStateId,q.id)).innerJoin(J,f(C.flowId,J.id)).innerJoin(M,f(J.targetStepId,M.id)).where(Ye(C.id,r)),o=Uf.Record({key:Uf.String,value:Uf.Unknown}),i=[];for(let s of n){let a=Uf.decodeUnknownEither(o)(s.state??{});if(a._tag==="Left")return yield*new tk({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:la.unsafeFromDate(new Date(s.processStartedAt)),itemData:s.itemData})}return i}),getCompletedStepsForExecution:(r)=>br.gen(function*(){let n=yield*e.select({stepPath:M.path,userId:oe.id,userSub:oe.sub,providerUserId:m`COALESCE(${N.id}, ${oe.id})`.as("assigned_to_provider_user_id"),providerUserName:m`COALESCE(${N.name}, ${oe.sub})`.as("provider_user_name"),providerUserFirstName:m`COALESCE(${N.firstName}, ${oe.sub})`.as("provider_user_first_name"),providerUserLastName:m`COALESCE(${N.lastName}, '')`.as("provider_user_last_name"),providerUserEmail:m`COALESCE(${N.email}, ${oe.sub})`.as("provider_user_email"),providerUserPicture:m`COALESCE(${N.picture}, '')`.as("provider_user_picture"),completedAt:m`(${K.createdAt} - 2440587.5) * 86400000`.as("completed_at_millis")}).from(K).innerJoin(q,f(K.processStateId,q.id)).innerJoin(M,f(q.startStepId,M.id)).innerJoin(oe,f(q.startedByUserId,oe.id)).leftJoin(N,f(oe.id,N.userId)).where(f(K.id,r)),o=yield*e.select({stepPath:M.path,userId:oe.id,userSub:oe.sub,providerUserId:m`COALESCE(${N.id}, ${oe.id})`.as("assigned_to_provider_user_id"),providerUserName:m`COALESCE(${N.name}, ${oe.sub})`.as("provider_user_name"),providerUserFirstName:m`COALESCE(${N.firstName}, ${oe.sub})`.as("provider_user_first_name"),providerUserLastName:m`COALESCE(${N.lastName}, '')`.as("provider_user_last_name"),providerUserEmail:m`COALESCE(${N.email}, ${oe.sub})`.as("provider_user_email"),providerUserPicture:m`COALESCE(${N.picture}, '')`.as("provider_user_picture"),completedAt:m`(${C.updatedAt} - 2440587.5) * 86400000`.as("completed_at_millis")}).from(C).innerJoin(J,f(C.flowId,J.id)).innerJoin(M,f(J.targetStepId,M.id)).innerJoin(oe,f(C.completedByUserId,oe.id)).leftJoin(N,f(oe.id,N.userId)).where(k(f(C.processExecutionId,r),f(C._deleted,!0),mr(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:la.unsafeFromDate(new Date(s.completedAt))}))}),queryFailedTodosForExecution:(r)=>br.gen(function*(){return(yield*e.select({todoId:C.id,stepPath:M.path,isSystemStep:m`CASE WHEN ${M.roleId} IS NULL THEN 1 ELSE 0 END`.as("is_system_step")}).from(C).innerJoin(J,f(C.flowId,J.id)).innerJoin(M,f(J.targetStepId,M.id)).where(k(f(C.processExecutionId,r),f(C._deleted,!1),mr(C.failureReason)))).map((o)=>({todoId:o.todoId,stepPath:o.stepPath,isSystemStep:o.isSystemStep}))}),clearTodoFailures:(r)=>br.gen(function*(){if(r.length===0)return;let n=yield*Ie(),o=yield*It();yield*e.update(C).set({failureReason:null,updatedAt:n,updatedBy:o.by}).where(Ye(C.id,r))}),clearProcessExecutionFinished:(r)=>br.gen(function*(){let n=yield*Ie(),o=yield*It();yield*e.update(K).set({finishedAt:null,businessDuration:null,abandonedReason:null,updatedAt:n,updatedBy:o.by}).where(f(K.id,r))}),reopenFailedSystemStartExecution:(r)=>br.gen(function*(){let n=yield*Ie(),o=yield*It();return(yield*e.update(K).set({finishedAt:null,businessDuration:null,abandonedReason:null,updatedAt:n,updatedBy:o.by}).where(k(f(K.id,r),mr(K.finishedAt),Pe(K.abandonedAt),mr(K.abandonedReason))).returning({id:K.id})).length>0}),queryActiveTodoStepPaths:(r)=>br.gen(function*(){return(yield*e.selectDistinct({stepPath:M.path}).from(C).innerJoin(J,f(C.flowId,J.id)).innerJoin(M,f(J.targetStepId,M.id)).where(k(f(C.processExecutionId,r),f(C._deleted,!1),Pe(C.failureReason)))).map((o)=>o.stepPath)}),setProcessExecutionAbandoned:(r,n)=>br.gen(function*(){let o=yield*Ie(),i=yield*It();yield*e.update(K).set({finishedAt:o,abandonedAt:o,updatedAt:o,updatedBy:i.by,...n===void 0?{}:{abandonedReason:n}}).where(f(K.id,r))}),softDeleteActiveTodosForExecution:(r)=>br.gen(function*(){let n=yield*Ie(),o=yield*It();return(yield*e.update(C).set({_deleted:!0,failureReason:"Execution abandoned",updatedAt:n,updatedBy:o.by}).where(k(f(C.processExecutionId,r),f(C._deleted,!1))).returning({id:C.id})).map((s)=>s.id)})}}));import{Effect as nT,Layer as IDe}from"effect";var N$=IDe.effect(g$,nT.gen(function*(){let e=yield*Ee,t=(n)=>nT.gen(function*(){return(yield*e.select({path:F.path}).from(Rn).innerJoin(F,f(Rn.roleId,F.id)).innerJoin(M,f(Rn.stepId,M.id)).where(k(f(M.path,n),f(Rn._deleted,!1),f(F._deleted,!1))).orderBy(oa(Rn.createdAt))).map((i)=>i.path)}),r={rolePath:null,supportingRolePaths:[],startsProcess:!1,embedded:!1};return{queryRolePathsByStepPath:(n)=>nT.gen(function*(){let i=(yield*e.select({rolePath:F.path,canStartProcess:_c.canStartProcess,embedded:M.embedded}).from(M).leftJoin(F,f(M.roleId,F.id)).innerJoin(_c,f(M.id,_c.id)).where(k(f(M.path,n),f(M._deleted,!1),Zt(Pe(F.id),f(F._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)=>nT.gen(function*(){if(n.length===0)return new Map;let o=yield*e.select({stepId:M.id,stepPath:M.path,rolePath:F.path,canStartProcess:_c.canStartProcess,embedded:M.embedded}).from(M).leftJoin(F,f(M.roleId,F.id)).innerJoin(_c,f(M.id,_c.id)).where(k(Ye(M.path,n),f(M._deleted,!1),Zt(Pe(F.id),f(F._deleted,!1)))),i=o.map((l)=>l.stepId),s=i.length>0?yield*e.select({stepPath:M.path,rolePath:F.path}).from(Rn).innerJoin(F,f(Rn.roleId,F.id)).innerJoin(M,f(Rn.stepId,M.id)).where(k(Ye(M.id,i),f(Rn._deleted,!1),f(F._deleted,!1))).orderBy(oa(Rn.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)=>nT.gen(function*(){return(yield*e.select({id:F.id}).from(F).where(k(f(F.path,n),f(F._deleted,!1))).limit(1))[0]?.id})}}));import{Effect as Tte,Layer as RDe}from"effect";var F$=RDe.effect(S$,Tte.gen(function*(){let e=yield*Ee;return{registerInvitation:(t)=>Tte.gen(function*(){let r=yield*Ie(),n=yield*It(),o=t.email.trim().toLowerCase();yield*e.insert(D).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 oT,Layer as PDe}from"effect";var Mf=m`CAST(ROUND((${C.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`,U$=(e)=>e.select({id:C.id,processExecutionId:C.processExecutionId,flowId:C.flowId,processName:te.name,processPath:te.path,processOrgUnitPath:G.path,stepName:M.name,stepPath:M.path,rolePath:F.path,assignedToProviderUserId:C.assignedToProviderUserId,assignedToProviderUserEmail:N.email,role:F.name,description:M.purpose,formFields:M.formFields,correctionRequiredAt:C.correctionRequiredAt,updatedAt:Mf.as("updated_at_millis"),createdAt:m`strftime('%Y-%m-%dT%H:%M:%fZ', (${C.createdAt} - 2440587.5) * 86400, 'unixepoch')`.as("created_at_iso"),slaTargetAt:m`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:m`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(K,f(C.processExecutionId,K.id)).innerJoin(q,f(K.processStateId,q.id)).innerJoin(te,f(q.processId,te.id)).innerJoin(G,f(te.orgUnitId,G.id)).innerJoin(J,f(C.flowId,J.id)).innerJoin(M,f(J.targetStepId,M.id)).innerJoin(F,f(M.roleId,F.id)).leftJoin(N,f(C.assignedToProviderUserId,N.id)),M$=(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:Z_(e.formFields),updatedAt:e.updatedAt,deleted:e.deleted,summary:[]}),L$=PDe.effect(v$,oT.gen(function*(){let e=yield*Ee;return{pullTodo:(t,r,n)=>oT.gen(function*(){if(n.kind==="live-backfill"&&n.head===null)return[];let o=[];if(n.kind==="live-backfill")o.push(f(C._deleted,!1));if(n.kind==="live-backfill"&&n.head){let a=Zt(xd(Mf,n.head.updatedAt),k(f(Mf,n.head.updatedAt),Fo(C.id,n.head.id)));if(a)o.push(a)}if(t){let a=Zt(Vr(Mf,t.updatedAt),k(f(Mf,t.updatedAt),Vr(C.id,t.id)));if(a)o.push(a)}return(yield*U$(e).where(o.length>0?k(...o):void 0).orderBy(Mf,C.id).limit(r)).map(M$)}),getTodoReplicationHead:()=>oT.gen(function*(){return(yield*e.select({id:C.id,updatedAt:Mf}).from(C).orderBy(eo(Mf),eo(C.id)).limit(1))[0]??null}),getTodos:(t)=>oT.gen(function*(){if(t.length===0)return[];return(yield*U$(e).where(Ye(C.id,t)).orderBy(C.updatedAt,C.id)).map(M$)}),listTodos:(t)=>oT.gen(function*(){let r=[];if(t.processPath!=null)r.push(f(te.path,t.processPath));if(t.state)switch(t.state.kind){case"correction-required":r.push(mr(C.correctionRequiredAt));break;case"correction-free":r.push(Pe(C.correctionRequiredAt),f(C._deleted,t.state.deleted));break}return(yield*U$(e).where(r.length>0?k(...r):void 0).orderBy(eo(C.createdAt),C.id).limit(t.limit).offset(t.offset)).map(M$)})}}));var YQt=CDe.mergeAll(A$,ute,hte,Ste,vte,Ete,k$,fte,pte,R$,P$,C$,_$,Jy,F$,L$,wte,N$,O$);import{strict as iT}from"assert";import{Effect as Kr,Layer as DDe}from"effect";import{Context as _De,Data as kDe}from"effect";class B$ extends kDe.TaggedError("FlowCrossProcessError"){}class $$ extends _De.Tag("processfocus:internal-tag/org-to-db/DbOperations")(){}var c5t=DDe.succeed($$,{upsertOrgUnit:(e,t)=>Kr.gen(function*(){let r=yield*Ee,n=yield*Ie(),o=yield*r.insert(G).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:G.path,targetWhere:m`_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:G.id});return(yield*Or(o)).id}),upsertProcess:(e,t)=>Kr.gen(function*(){let r=yield*Ee,n=yield*Ie(),o=e.sla?.value??null,i=e.sla?.unit??null,s=e.sla?.warningAt??null,a=yield*r.insert(te).values({orgUnitId:t,name:e.name,path:e.path,purpose:e.purpose,slaValue:o,slaUnit:i,slaWarning:s,createdAt:n,updatedAt:n}).onConflictDoUpdate({target:te.path,targetWhere:m`_deleted = 0`,set:{name:e.name,purpose:e.purpose,orgUnitId:t,slaValue:o,slaUnit:i,slaWarning:s,updatedAt:n}}).returning({id:te.id});return(yield*Or(a)).id}),upsertRole:(e,t)=>Kr.gen(function*(){let r=yield*Ee,n=yield*Ie(),o=yield*r.insert(F).values({orgUnitId:t,name:e.name,path:e.path,createdAt:n,updatedAt:n}).onConflictDoUpdate({target:F.path,targetWhere:m`_deleted = 0`,set:{name:e.name,orgUnitId:t,_deleted:!1,updatedAt:n}}).returning({id:F.id});return(yield*Or(o)).id}),upsertPhase:(e,t)=>Kr.gen(function*(){let r=yield*Ee,n=yield*Ie(),o=yield*r.insert(mo).values({processId:t,name:e.name,path:e.path,phaseOrder:e.order,createdAt:n,updatedAt:n}).onConflictDoUpdate({target:mo.path,targetWhere:m`_deleted = 0`,set:{name:e.name,processId:t,phaseOrder:e.order,_deleted:!1,updatedAt:n}}).returning({id:mo.id});return(yield*Or(o)).id}),upsertStep:(e,t,r)=>Kr.gen(function*(){let n=yield*Ee,o=yield*Ie(),i=null;if(e.rolePath){let E=yield*n.select({id:F.id}).from(F).where(f(F.path,e.rolePath)).limit(1);iT(E[0],`Role not found for path: ${e.rolePath}`),i=E[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,p=e.retryLimit??null,y=yield*n.insert(M).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:p,createdAt:o,updatedAt:o}).onConflictDoUpdate({target:M.path,targetWhere:m`_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:p,_deleted:!1,updatedAt:o}}).returning({id:M.id}),g=(yield*Or(y)).id;if(e.supportingRolePaths!==void 0){yield*n.update(Rn).set({_deleted:!0,updatedAt:o}).where(k(f(Rn.stepId,g),f(Rn._deleted,!1)));for(let E of e.supportingRolePaths){let S=yield*n.select({id:F.id}).from(F).where(f(F.path,E)).limit(1);iT(S[0],`Supporting role not found for path: ${E}`),yield*n.insert(Rn).values({stepId:g,roleId:S[0].id,createdAt:o,updatedAt:o}).onConflictDoUpdate({target:[Rn.stepId,Rn.roleId],targetWhere:m`_deleted = 0`,set:{_deleted:!1,updatedAt:o}})}}return g}),upsertRoleResponsibility:(e,t,r)=>Kr.gen(function*(){let n=yield*Ee,o=yield*Ie();yield*n.insert(fn).values({processId:t,roleId:r,responsibility:e.responsibility,responsibilityOrder:e.order,createdAt:o,updatedAt:o}).onConflictDoUpdate({target:[fn.processId,fn.roleId],targetWhere:m`_deleted = 0`,set:{responsibility:e.responsibility,responsibilityOrder:e.order,_deleted:!1,updatedAt:o}})}),upsertFlow:(e,t,r,n)=>Kr.gen(function*(){let o=yield*Ee,i=yield*Ie(),s=t.taggedErrors?[...t.taggedErrors].sort():null,a=yield*o.select({id:M.id,processId:M.processId}).from(M).where(Ye(M.id,[r,n])),c=a.find((p)=>p.id===r),l=a.find((p)=>p.id===n);if(iT(c,`Source step not found: ${r}`),iT(l,`Target step not found: ${n}`),c.processId!==l.processId)return yield*new B$({sourceStepId:r,targetStepId:n,sourceProcessId:c.processId,targetProcessId:l.processId});let u=(yield*o.select({id:J.id}).from(J).where(k(f(J.flowKey,e),f(J._deleted,!1))).limit(1))[0]??(yield*o.select({id:J.id}).from(J).where(k(f(J.sourceStepId,r),f(J.targetStepId,n),t.condition===void 0?Pe(J.condition):f(J.condition,t.condition),t.schedule===void 0?Pe(J.schedule):f(J.schedule,t.schedule),f(J.fallbackBranch,t.isElse),f(J.errorBranch,t.isOnError??!1),s===null?Pe(J.errorTags):f(J.errorTags,s),f(J._deleted,!1),If(J.flowKey,"legacy:%"))).limit(1))[0];if(u){yield*o.update(J).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(f(J.id,u.id));return}yield*o.insert(J).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)=>Kr.gen(function*(){let t=yield*Ee,r=yield*Ie();if(e.length===0){yield*t.update(J).set({_deleted:!0,updatedAt:r});return}let o=(yield*t.select({id:J.id,flowKey:J.flowKey}).from(J)).filter((i)=>!e.includes(i.flowKey)).map((i)=>i.id);if(o.length>0)yield*t.update(J).set({_deleted:!0,updatedAt:r}).where(Ye(J.id,o))}),deleteOrphanedSteps:(e)=>Kr.gen(function*(){let t=yield*Ee,r=yield*Ie();if(e.length===0)yield*t.update(M).set({_deleted:!0,updatedAt:r});else yield*t.update(M).set({_deleted:!0,updatedAt:r}).where(Uo(M.path,e))}),deleteOrphanedRoles:(e)=>Kr.gen(function*(){let t=yield*Ee,r=yield*Ie();if(e.length===0)yield*t.update(F).set({_deleted:!0,updatedAt:r});else yield*t.update(F).set({_deleted:!0,updatedAt:r}).where(Uo(F.path,e))}),deleteOrphanedProcesses:(e)=>Kr.gen(function*(){let t=yield*Ee,r=yield*Ie();if(e.length===0)yield*t.update(te).set({_deleted:!0,updatedAt:r});else yield*t.update(te).set({_deleted:!0,updatedAt:r}).where(Uo(te.path,e))}),deleteOrphanedOrgUnits:(e)=>Kr.gen(function*(){let t=yield*Ee,r=yield*Ie();if(e.length===0)yield*t.update(G).set({_deleted:!0,updatedAt:r});else yield*t.update(G).set({_deleted:!0,updatedAt:r}).where(Uo(G.path,e))}),deleteOrphanedPhases:(e)=>Kr.gen(function*(){let t=yield*Ee,r=yield*Ie();if(e.length===0)yield*t.update(mo).set({_deleted:!0,updatedAt:r});else yield*t.update(mo).set({_deleted:!0,updatedAt:r}).where(Uo(mo.path,e))}),deleteOrphanedRoleResponsibilities:(e)=>Kr.gen(function*(){let t=yield*Ee,r=yield*Ie();if(e.length===0){yield*t.update(fn).set({_deleted:!0,updatedAt:r});return}let n=new Map,o=yield*t.select({id:te.id,path:te.path}).from(te).where(f(te._deleted,!1));for(let d of o)n.set(d.path,d.id);let i=new Map,s=yield*t.select({id:F.id,path:F.path}).from(F).where(f(F._deleted,!1));for(let d of s)i.set(d.path,d.id);let a=e.map(({processPath:d,rolePath:u})=>{let p=n.get(d),y=i.get(u);return p&&y?{processId:p,roleId:y}:null}).filter((d)=>d!==null),l=(yield*t.select({id:fn.id,processId:fn.processId,roleId:fn.roleId}).from(fn)).filter((d)=>!a.some((u)=>u.processId===d.processId&&u.roleId===d.roleId)).map((d)=>d.id);if(l.length>0)yield*t.update(fn).set({_deleted:!0,updatedAt:r}).where(Ye(fn.id,l))}),upsertOAuthProvider:(e,t)=>Kr.gen(function*(){let r=yield*Ee,n=yield*Ie();yield*r.insert(Ft).values({providerName:e,providerConfig:t,createdAt:n,updatedAt:n}).onConflictDoUpdate({target:Ft.providerName,targetWhere:m`_deleted = 0`,set:{providerConfig:t,updatedAt:n}})}),deleteOrphanedOAuthProviders:(e)=>Kr.gen(function*(){let t=yield*Ee,r=yield*Ie();if(e.length===0)yield*t.update(Ft).set({_deleted:!0,updatedAt:r});else yield*t.update(Ft).set({_deleted:!0,updatedAt:r}).where(Uo(Ft.providerName,e))}),upsertInvitation:(e,t)=>Kr.gen(function*(){let r=yield*Ee,n=yield*Ie(),o=e.email.toLowerCase(),s=(yield*r.select({id:D.id,email:D.email,invitationStatus:D.invitationStatus}).from(D).where(k(f(D.invitationId,e.id),f(D._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:m`coalesce(${D.registrationLinkGeneration}, 0) + 1`,registrationLinkRevokedAt:n,registrationLinkRevokedBy:"SYSTEM"};yield*r.update(D).set({_deleted:!0,invitationPendingEmail:null,...a,updatedAt:n}).where(k(f(D.invitationPendingEmail,o),Tf(D.invitationId,e.id),f(D.invitationStatus,"pending"),f(D._deleted,!1))),yield*r.insert(D).values({invitationId:e.id,email:o,invitationStatus:"pending",invitationSource:"model",invitationPendingEmail:o,createdAt:n,updatedAt:n}).onConflictDoUpdate({target:D.invitationId,targetWhere:m`_deleted = 0`,set:{email:o,invitationSource:"model",invitationPendingEmail:o,_deleted:!1,updatedAt:n},setWhere:f(D.invitationStatus,"pending")});let l=(yield*r.select({id:D.id,email:D.email,invitationStatus:D.invitationStatus}).from(D).where(k(f(D.invitationId,e.id),f(D._deleted,!1))).limit(1))[0];if(iT(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(D).set({updatedAt:n}).where(k(f(D.id,d),f(D.invitationStatus,"pending"),f(D._deleted,!1))).returning({id:D.id})).length===0)return d;let y=yield*r.select({id:Je.id,roleId:Je.roleId,deleted:Je._deleted}).from(Je).where(f(Je.invitationId,d)),g=new Set(y.map((b)=>b.roleId)),E=new Set(y.filter((b)=>!b.deleted).map((b)=>b.roleId)),S=new Set(t),x=t.filter((b)=>!g.has(b)),w=y.filter((b)=>!b.deleted&&!S.has(b.roleId)).map((b)=>b.id),_=t.some((b)=>!E.has(b))||[...E].some((b)=>!S.has(b));if(u||_)yield*r.update(D).set({...a,updatedAt:n}).where(k(f(D.id,d),f(D.invitationStatus,"pending"),f(D._deleted,!1),mr(D.registrationTokenHash)));if(x.length>0)yield*r.insert(Je).values(x.map((b)=>({invitationId:d,roleId:b,createdAt:n,updatedAt:n})));if(w.length>0)yield*r.update(Je).set({_deleted:!0,updatedAt:n}).where(Ye(Je.id,w));let T=t.filter((b)=>g.has(b));if(T.length>0){let b=y.filter((I)=>T.includes(I.roleId)).map((I)=>I.id);if(b.length>0)yield*r.update(Je).set({_deleted:!1,updatedAt:n}).where(Ye(Je.id,b))}return d}),deleteOrphanedInvitations:(e)=>Kr.gen(function*(){let t=yield*Ee,r=yield*Ie(),n=e.length===0?k(f(D.invitationSource,"model"),f(D.invitationStatus,"pending"),f(D._deleted,!1)):k(f(D.invitationSource,"model"),f(D.invitationStatus,"pending"),f(D._deleted,!1),Uo(D.invitationId,e)),o=yield*t.update(D).set({_deleted:!0,invitationPendingEmail:null,updatedAt:r}).where(n).returning({id:D.id});if(o.length>0)yield*t.update(Je).set({_deleted:!0,updatedAt:r}).where(k(Ye(Je.invitationId,o.map((i)=>i.id)),f(Je._deleted,!1)))}),upsertOAuthClient:(e,t,r)=>Kr.gen(function*(){let n=yield*Ee,o=yield*Ie();yield*n.insert(yr).values({clientId:e,clientSecretHash:t,audience:r,createdAt:o,updatedAt:o}).onConflictDoUpdate({target:yr.clientId,targetWhere:m`_deleted = 0`,set:{clientSecretHash:t,audience:r,_deleted:!1,updatedAt:o}})}),deleteOrphanedOAuthClients:(e)=>Kr.gen(function*(){let t=yield*Ee,r=yield*Ie();if(e.length===0)yield*t.update(yr).set({_deleted:!0,updatedAt:r});else yield*t.update(yr).set({_deleted:!0,updatedAt:r}).where(Uo(yr.clientId,e))}),upsertWeeklySchedule:(e,t)=>Kr.gen(function*(){let r=yield*Ee,n=yield*Ie();yield*r.insert(ho).values({orgUnitId:t,dayOfWeek:e.dayOfWeek,timeRanges:e.timeRanges,createdAt:n,updatedAt:n}).onConflictDoUpdate({target:[ho.orgUnitId,ho.dayOfWeek],targetWhere:m`_deleted = 0`,set:{timeRanges:e.timeRanges,_deleted:!1,updatedAt:n}})}),deleteOrphanedWeeklySchedules:(e)=>Kr.gen(function*(){let t=yield*Ee,r=yield*Ie();if(e.length===0){yield*t.update(ho).set({_deleted:!0,updatedAt:r});return}let n=new Map,o=yield*t.select({id:G.id,path:G.path}).from(G).where(f(G._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:ho.id,orgUnitId:ho.orgUnitId,dayOfWeek:ho.dayOfWeek}).from(ho)).filter((c)=>!i.some((l)=>l.orgUnitId===c.orgUnitId&&l.dayOfWeek===c.dayOfWeek)).map((c)=>c.id);if(a.length>0)yield*t.update(ho).set({_deleted:!0,updatedAt:r}).where(Ye(ho.id,a))}),upsertHolidayRule:(e,t)=>Kr.gen(function*(){let r=yield*Ee,n=yield*Ie();yield*r.insert(Wn).values({orgUnitId:t,holidayTitle:e.name,holidayRule:e.rule,createdAt:n,updatedAt:n}).onConflictDoUpdate({target:[Wn.orgUnitId,Wn.holidayTitle],targetWhere:m`_deleted = 0`,set:{holidayRule:e.rule,_deleted:!1,updatedAt:n}})}),deleteOrphanedHolidayRules:(e)=>Kr.gen(function*(){let t=yield*Ee,r=yield*Ie();if(e.length===0){yield*t.update(Wn).set({_deleted:!0,updatedAt:r});return}let n=new Map,o=yield*t.select({id:G.id,path:G.path}).from(G).where(f(G._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:Wn.id,orgUnitId:Wn.orgUnitId,holidayTitle:Wn.holidayTitle}).from(Wn)).filter((c)=>!i.some((l)=>l.orgUnitId===c.orgUnitId&&l.holidayTitle===c.holidayTitle)).map((c)=>c.id);if(a.length>0)yield*t.update(Wn).set({_deleted:!0,updatedAt:r}).where(Ye(Wn.id,a))}),upsertDocumentStore:(e,t)=>Kr.gen(function*(){let r=yield*Ee,n=yield*Ie(),o=yield*r.insert(Gt).values({orgUnitId:t,name:e.name,path:e.path,acceptedTypes:e.acceptedTypes??null,sizeLimit:e.maxFileSize??null,createdAt:n,updatedAt:n}).onConflictDoUpdate({target:Gt.path,targetWhere:m`_deleted = 0`,set:{name:e.name,orgUnitId:t,acceptedTypes:e.acceptedTypes??null,sizeLimit:e.maxFileSize??null,updatedAt:n}}).returning({id:Gt.id});return(yield*Or(o)).id}),deleteOrphanedDocumentStores:(e)=>Kr.gen(function*(){let t=yield*Ee,r=yield*Ie();if(e.length===0)yield*t.update(Gt).set({_deleted:!0,updatedAt:r});else yield*t.update(Gt).set({_deleted:!0,updatedAt:r}).where(Uo(Gt.path,e))}),upsertStepDocumentStore:(e,t)=>Kr.gen(function*(){let r=yield*Ee,n=yield*Ie();yield*r.insert(to).values({stepId:e,documentStoreId:t,createdAt:n,updatedAt:n}).onConflictDoUpdate({target:[to.stepId,to.documentStoreId],targetWhere:m`_deleted = 0`,set:{_deleted:!1,updatedAt:n}})}),deleteOrphanedStepDocumentStores:(e)=>Kr.gen(function*(){let t=yield*Ee,r=yield*Ie();if(e.length===0){yield*t.update(to).set({_deleted:!0,updatedAt:r});return}let n=new Map,o=yield*t.select({id:M.id,path:M.path}).from(M).where(f(M._deleted,!1));for(let d of o)n.set(d.path,d.id);let i=new Map,s=yield*t.select({id:Gt.id,path:Gt.path}).from(Gt).where(f(Gt._deleted,!1));for(let d of s)i.set(d.path,d.id);let a=e.map(({stepPath:d,documentStorePath:u})=>{let p=n.get(d),y=i.get(u);return p&&y?{stepId:p,documentStoreId:y}:null}).filter((d)=>d!==null),l=(yield*t.select({id:to.id,stepId:to.stepId,documentStoreId:to.documentStoreId}).from(to)).filter((d)=>!a.some((u)=>u.stepId===d.stepId&&u.documentStoreId===d.documentStoreId)).map((d)=>d.id);if(l.length>0)yield*t.update(to).set({_deleted:!0,updatedAt:r}).where(Ye(to.id,l))})});import{Effect as Ad,Layer as ODe,Option as Ate}from"effect";var NDe=ODe.effect(y$,Ad.gen(function*(){let e=yield*Ee,t=Di(M,"source_step"),r=Di(M,"target_step");return{insertScheduledFlow:(n,o,i)=>Ad.gen(function*(){let s=yield*Ie(),a=yield*It(),c=yield*e.insert(ot).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:ot.id});return(yield*Or(c)).id}),insertOrGetScheduledFlow:(n,o,i,s)=>Ad.gen(function*(){let a=yield*Ie(),c=yield*It(),l=yield*e.insert(ot).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:ot.id}).returning({id:ot.id});if(l[0])return l[0].id;let d=yield*e.select({id:ot.id}).from(ot).where(f(ot.id,n)).limit(1);return(yield*Or(d)).id}),getScheduledFlow:(n)=>Ad.gen(function*(){let o=yield*e.select({processExecutionId:ot.processExecutionId,createdBy:ot.createdBy,sourceStepId:ot.sourceStepId,targetStepId:ot.targetStepId,scheduledAt:ot.scheduledAt,forEachBarrier:ot.forEachBarrier,completedByRoleId:ot.completedByRoleId}).from(ot).where(f(ot.id,n)).limit(1);if(!o[0])return Ate.none();return Ate.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)=>Ad.gen(function*(){return(yield*e.delete(ot).where(f(ot.id,n)).returning({id:ot.id})).length>0}),hasPendingScheduledFlows:(n)=>Ad.gen(function*(){if((yield*e.select({id:ot.id}).from(ot).where(f(ot.processExecutionId,n)).limit(1)).length>0)return!0;return(yield*e.select({id:C.id}).from(C).innerJoin(J,f(C.flowId,J.id)).innerJoin(M,f(J.targetStepId,M.id)).where(k(f(C.processExecutionId,n),Pe(C.businessDuration),Pe(C.failureReason),f(C._deleted,!1),Pe(M.roleId))).limit(1)).length>0}),getPendingStartScheduledFlowId:(n,o)=>Ad.gen(function*(){return(yield*e.select({id:ot.id}).from(ot).where(k(f(ot.processExecutionId,n),f(ot.sourceStepId,o),Pe(ot.targetStepId),Pe(ot.scheduledAt),f(ot.forEachBarrier,!1))).limit(1))[0]?.id??null}),queryPendingAbandonStepPaths:(n)=>Ad.gen(function*(){let o=yield*e.select({sourceStepPath:t.path,targetStepPath:r.path}).from(ot).innerJoin(t,k(f(ot.sourceStepId,t.id),f(t._deleted,!1))).leftJoin(r,k(f(ot.targetStepId,r.id),f(r._deleted,!1))).where(k(f(ot.processExecutionId,n),f(ot._deleted,!1)));return[...new Set(o.map((i)=>i.targetStepPath??i.sourceStepPath))]}),deleteScheduledFlowsForExecution:(n)=>Ad.gen(function*(){yield*e.delete(ot).where(f(ot.processExecutionId,n))}),wasBarrierScheduledFlow:(n)=>Ad.gen(function*(){return(yield*e.select({id:C.id}).from(C).where(f(C.barrierScheduledFlowId,n)).limit(1)).length>0})}}));Hw();Ki();import{Effect as n0e,Layer as o0e}from"effect";var Qte=(e,t)=>o0e.unwrapEffect(n0e.tryPromise({try:e,catch:(r)=>new ia({cause:r,message:t})})),i0e={local:async()=>{await Promise.resolve().then(() => Ute());return j$({busy_timeout:KB})},cloud:async()=>{await Promise.resolve().then(() => Gte());return zte}},s0e=(e)=>Qte(e.local,"Failed to load local Turso database layer"),a0e=(e)=>Qte(e.cloud,"Failed to load Turso Cloud database layer"),jf=(e,t=i0e)=>vf(e)?s0e(t):a0e(t);var Fv=(e)=>{let t=jf(e);return tT.pipe(W$.provideMerge(Rv),W$.provideMerge(t),W$.provide(Fu(e)))};class z$ extends c0e.TaggedError("FrontendJwtNotFoundError"){}var Yte=(e)=>V$.gen(function*(){let t=As(e);if(!t)return yield*Jte.error(Is),yield*new z$({message:"Database path not configured"});let r=Fv(t),n=yield*p_(Wl()).pipe(V$.provide(r));if(!n)return yield*Jte.error("No frontend JWT found. Run 'pfcli import' or 'pfcli refresh-frontend-jwt' to create one."),yield*new z$({message:"No frontend JWT found"});yield*V$.sync(()=>process.stdout.write(n))});Ki();import{Console as Yy,Data as Xte,Effect as hi,Layer as K$}from"effect";class Zte extends Xte.TaggedError("GrantRoleDbPathError"){}class G$ extends Xte.TaggedError("GrantRoleModeError"){}var l0e=30000,d0e=`
|
|
863
|
+
mutation GrantProjectUserRole($projectId: String!, $environmentId: String!, $rolePath: String!, $email: String!) {
|
|
864
|
+
grantProjectUserRole(projectId: $projectId, environmentId: $environmentId, rolePath: $rolePath, email: $email) {
|
|
865
|
+
success
|
|
866
|
+
email
|
|
867
|
+
rolePath
|
|
868
|
+
alreadyHadRole
|
|
869
|
+
error
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
`,ere=(e)=>hi.gen(function*(){if(!e.success){let t=e.error===ek?e.email:e.rolePath;yield*Yy.error(`\u274C ${e.error}: ${t}`),yield*hi.sync(()=>{process.exitCode=1});return}if(e.alreadyHadRole){yield*Yy.log(`already had role: ${e.email} already has ${e.rolePath}`);return}yield*Yy.log(`granted role: ${e.email} granted ${e.rolePath}`)}),u0e=(e)=>hi.gen(function*(){let t=As(e.orgPath);if(!t)return yield*new Zte({message:Is});let r=jf(t),n=Jy.pipe(K$.provideMerge(Rv),K$.provideMerge(r),K$.provide(Fu(t))),o=yield*Vee({rolePath:e.rolePath,email:e.email,grantedBy:"SYSTEM"}).pipe(hi.provide(n));yield*ere(o)}),p0e=(e)=>hi.gen(function*(){let t=yield*Mr(d0e,{projectId:e.projectId,environmentId:e.environmentId,rolePath:e.rolePath,email:e.email},{timeoutMs:l0e});yield*ere(Wee(t.grantProjectUserRole))}),f0e=(e)=>hi.gen(function*(){let{projectId:t,environmentId:r}=e;if(Boolean(t)!==Boolean(r))return yield*new G$({message:"Remote mode requires both --project and --env together."});else if(t&&r){if(e.orgPath)return yield*new G$({message:"Remote mode does not accept positional org-path. Remove org-path when using --project/--env."});return yield*ai(t,r),yield*p0e({projectId:t,environmentId:r,rolePath:e.rolePath,email:e.email})}return yield*u0e(e)}),tre=(e)=>f0e(e).pipe(hi.catchTag("GrantRoleModeError",(t)=>hi.gen(function*(){yield*Yy.error(`
|
|
873
|
+
\u274C ${t.message}`),yield*hi.sync(()=>{process.exitCode=1})})),hi.catchTag("GrantRoleDbPathError",(t)=>hi.gen(function*(){yield*Yy.error(`
|
|
874
|
+
\u274C ${t.message}`),yield*hi.sync(()=>{process.exitCode=1})})),hi.catchTag("CliError",(t)=>hi.gen(function*(){yield*Yy.error(`
|
|
875
|
+
\u274C ${t.message}`),yield*hi.sync(()=>{process.exitCode=1})})),hi.catchAll((t)=>hi.gen(function*(){yield*Yy.error(`
|
|
876
|
+
\u274C Grant role failed: ${String(t)}`),yield*hi.sync(()=>{process.exitCode=1})})));import{spawn as _0e}from"child_process";import{createHash as k0e}from"crypto";import{existsSync as Sk,readFileSync as pre,readdirSync as D0e,statSync as O0e,watch as N0e}from"fs";import{basename as F0e,dirname as U0e,join as Id,resolve as Z$}from"path";import{fileURLToPath as cre}from"url";import{inspect as M0e}from"util";import{Console as ro,Data as L0e,Effect as or,Schema as gk}from"effect";Ki();var uk=()=>{let e=process.env.OAUTH_ISSUER_URL;if(e)return e;let r=`http://localhost:${lO()}`;return console.warn(`\u26A0\uFE0F OAUTH_ISSUER_URL not set \u2014 falling back to ${r} (local dev only)`),r};import*as sre from"path";import{fileURLToPath as are}from"url";Ki();import{Console as Y$,Effect as cT}from"effect";Pg();import m0e from"crypto";import rre,{existsSync as y0e,readdirSync as h0e}from"fs";import{join as g0e}from"path";function nre(e){if(rre.existsSync(`${e.migrationsFolder}/meta/_journal.json`))throw Error('We detected that you have old drizzle-kit migration folders. You must upgrade drizzle-kit and run "drizzle-kit up"');let t=e.migrationsFolder,r=[],n=h0e(t).map((o)=>({path:g0e(t,o,"migration.sql"),name:o})).filter((o)=>y0e(o.path));n.sort((o,i)=>o.name.localeCompare(i.name));for(let o of n){let i=o.path,s=o.name.slice(0,14),a=rre.readFileSync(i).toString(),c=a.split("--> statement-breakpoint").map((d)=>d),l=oee(s);r.push({sql:c,bps:!0,folderMillis:l,hash:m0e.createHash("sha256").update(a).digest("hex"),name:o.name})}return r}Ki();import{Effect as Lv,Either as S0e,Layer as v0e}from"effect";var x0e=(e)=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(e),Uv=(e)=>`'${e.replaceAll("'","''")}'`,Q$=(e)=>`"${e.replaceAll('"','""')}"`,ore=(e)=>{let t=[],r=new Set,n=e;while(n&&!r.has(n)){if(r.add(n),n instanceof Error){t.push(n.message),n=n.cause;continue}if(typeof n==="object"){let i=n;if(typeof i.message==="string")t.push(i.message);n=i.cause;continue}if(typeof n==="string")t.push(n);break}return t.filter((i,s)=>i&&t.indexOf(i)===s).join(" -> ")||"Unknown migration error"},E0e=(e)=>{let t="",r,n=!1,o=!1;for(let i=0;i<e.length;i+=1){let s=e[i],a=e[i+1];if(s===void 0)break;if(n){if(s===`
|
|
877
|
+
`)t+=s,n=!1;continue}if(o){if(s==="*"&&a==="/")i+=1,o=!1;continue}if(r){if(t+=" ",s===r)if(a===r)t+=" ",i+=1;else r=void 0;continue}if(s==="-"&&a==="-"){i+=1,n=!0;continue}if(s==="/"&&a==="*"){i+=1,o=!0;continue}if(s==="'"||s==='"'||s==="`")r=s;t+=s}return t},b0e=(e)=>{let t=E0e(e).trim(),r=(n)=>t.match(n)?.length??0;if(!/^CREATE\s+(?:TEMP(?:ORARY)?\s+)?TRIGGER\b/i.test(t))return!1;return r(/\bBEGIN\b/gi)+r(/\bCASE\b/gi)>r(/\bEND\b/gi)},w0e=(e)=>{let t=[],r="",n,o=!1,i=!1;for(let a=0;a<e.length;a+=1){let c=e[a],l=e[a+1];if(c===void 0)break;if(o){if(r+=c,c===`
|
|
878
|
+
`)o=!1;continue}if(i){if(r+=c,c==="*"&&l==="/")r+=l,a+=1,i=!1;continue}if(n){if(r+=c,c===n)if(l===n)r+=l,a+=1;else n=void 0;continue}if(c==="-"&&l==="-"){r+=c,r+=l,a+=1,o=!0;continue}if(c==="/"&&l==="*"){r+=c,r+=l,a+=1,i=!0;continue}if(c==="'"||c==='"'||c==="`"){r+=c,n=c;continue}if(c===";"){let d=r.trim();if(b0e(d)){r+=c;continue}if(d.length>0)t.push(d);r="";continue}r+=c}let s=r.trim();if(s.length>0)t.push(s);return t},T0e=(e)=>{let t=!1,r=!1;for(let n=0;n<e.length;n+=1){let o=e[n],i=e[n+1];if(o===void 0)break;if(t){if(o===`
|
|
879
|
+
`)t=!1;continue}if(r){if(o==="*"&&i==="/")n+=1,r=!1;continue}if(o==="-"&&i==="-"){n+=1,t=!0;continue}if(o==="/"&&i==="*"){n+=1,r=!0;continue}if(!/\s/.test(o))return!0}return!1},Mv=(e)=>Lv.gen(function*(){let t=yield*Hs;for(let r of e){let n=w0e(r);for(let o of n){if(!T0e(o))continue;let i=Object.assign([o],{raw:[o]}),s=yield*Lv.either(t(i));if(S0e.isLeft(s))return yield*new Yc({reason:ore(s.left),statement:o.substring(0,200),cause:s.left})}}}),pk=(e)=>jf(e).pipe(v0e.provide(Fu(e))),A0e=(e)=>Lv.gen(function*(){if(!x0e(e))return yield*new Yc({reason:`Invalid migrations table name: ${e}`,cause:void 0});let t=yield*Hs,r=Q$(e);yield*Mv([`CREATE TABLE IF NOT EXISTS ${r} (
|
|
880
|
+
id INTEGER PRIMARY KEY,
|
|
881
|
+
hash text NOT NULL,
|
|
882
|
+
created_at numeric,
|
|
883
|
+
name text,
|
|
884
|
+
applied_at TEXT
|
|
885
|
+
)`]);let n=yield*t.unsafe(`PRAGMA table_info(${e})`),o=new Set(n.map((i)=>String(i.name??"")));if(!o.has("name"))yield*Mv([`ALTER TABLE ${r} ADD COLUMN name text`]);if(!o.has("applied_at"))yield*Mv([`ALTER TABLE ${r} ADD COLUMN applied_at TEXT`])}),I0e=(e,t,r)=>Lv.gen(function*(){if(!r.some((l)=>l.name==null))return;let o=new Map,i=new Map;for(let l of t){let d=o.get(l.folderMillis)??[];d.push(l),o.set(l.folderMillis,d),i.set(l.hash,l)}let s=[],a=[];for(let l of r){if(l.name!=null)continue;let d=String(l.created_at??""),u=Number(d.length>=3?`${d.slice(0,d.length-3)}000`:d),p=Number.isFinite(u)?o.get(u):void 0,y;if(p?.length===1)y=p[0];else if(p&&p.length>1)y=p.find((g)=>g.hash===l.hash);else y=i.get(l.hash);if(!y?.name){s.push(l);continue}a.push({id:l.id,hash:l.hash,name:y.name})}if(s.length>0)return yield*new Yc({reason:`While upgrading migrations table ${e} found ${s.length} database migration(s) that do not match any local migration (${s.map((l)=>`[id: ${String(l.id)}, created_at: ${String(l.created_at)}]`).join(", ")})`,cause:void 0});let c=Q$(e);for(let l of a)if(l.id!=null)yield*Mv([`UPDATE ${c} SET name = ${Uv(l.name)} WHERE id = ${l.id}`]);else yield*Mv([`UPDATE ${c} SET name = ${Uv(l.name)} WHERE hash = ${Uv(l.hash)}`])}),fk=(e)=>Lv.gen(function*(){let t=yield*Hs,r=yield*Lv.try({try:()=>nre(e),catch:(u)=>new Yc({reason:ore(u),cause:u})});yield*A0e(e.migrationsTable);let n=Q$(e.migrationsTable),i=(yield*t.unsafe(`SELECT id, hash, created_at, name FROM ${n}`)).map((u)=>{let p=u;return{id:typeof p.id==="number"?p.id:p.id==null?null:Number(p.id),hash:String(p.hash??""),created_at:typeof p.created_at==="string"||typeof p.created_at==="number"?p.created_at:p.created_at==null?null:String(p.created_at),name:typeof p.name==="string"?p.name:p.name==null?null:String(p.name)}});yield*I0e(e.migrationsTable,r,i);let a=(yield*t.unsafe(`SELECT id, hash, created_at, name FROM ${n}`)).map((u,p)=>{let y=u,g=typeof y.id==="number"?y.id:y.id==null?p+1:Number(y.id);return{id:Number.isFinite(g)?g:p+1,hash:String(y.hash??""),created_at:String(y.created_at??""),name:typeof y.name==="string"?y.name:y.name==null?null:String(y.name)}}),c=Bw({localMigrations:r,dbMigrations:a});if(c.length===0)return;let l=new Date().toISOString(),d=["PRAGMA foreign_keys=ON"];for(let u of c)d.push(...u.sql),d.push(`INSERT INTO ${n} ("hash", "created_at", "name", "applied_at") VALUES (${Uv(u.hash)}, ${u.folderMillis}, ${Uv(u.name)}, ${Uv(l)})`);yield*Mv(d)});import*as aT from"path";Ki();import{Console as mk,Data as R0e,Effect as J$}from"effect";var P0e="drizzle.config.ts",C0e="drizzle";class ire extends R0e.TaggedError("NoDrizzleConfigError"){}var yk=(e)=>J$.gen(function*(){let t=yield*Bo,r=As(e);if(!r)return yield*new Yc({reason:Is,cause:void 0});let n=aT.resolve(process.cwd(),e),o=aT.join(n,P0e);if(!(yield*t.exists(o)))return yield*new ire({orgPath:n});let s=aT.join(n,C0e);if(!(yield*t.exists(s))){yield*mk.log(`Migrations folder not found: ${s}. Run 'bunx drizzle-kit generate' first.`);return}yield*mk.log(`Running custom migrations from: ${s}`),yield*mk.log(`Database: ${r}`);let c=pk(r);yield*fk({migrationsFolder:s,migrationsTable:"__drizzle_migrations_org"}).pipe(J$.tap(()=>mk.log("\u2705 Custom schema migrations completed")),J$.provide(c))});var X$=are(new URL("./resources/system-migrations/",import.meta.url)),hk=(e)=>cT.gen(function*(){let t=As(e);if(!t)return yield*new Yc({reason:Is,cause:void 0});let r=yield*Bo;if(vf(t)){let i=t.startsWith("file:")?are(new URL(t)):t;yield*r.makeDirectory(sre.dirname(i),{recursive:!0})}if(!(yield*r.exists(X$)))return yield*new Yc({reason:`System migrations folder not found: ${X$}`,cause:void 0});yield*Y$.log("Running system migrations..."),yield*Y$.log(`Database: ${t}`);let o=pk(t);yield*fk({migrationsFolder:X$,migrationsTable:"__drizzle_migrations_pf"}).pipe(cT.tap(()=>Y$.log("\u2705 System migrations completed")),cT.provide(o)),yield*yk(e).pipe(cT.catchTag("NoDrizzleConfigError",()=>cT.void))});class Xy extends L0e.TaggedError("NotifyError"){}var fre=gk.parseJson(gk.Unknown),lre=(e)=>e.replace(/\/+$/,""),B0e=(e,t,r)=>{try{let[,n]=e.split(".");if(!n)return!1;let o=JSON.parse(Buffer.from(n,"base64url").toString("utf8")),i=typeof o.iss==="string"&&lre(o.iss)===lre(t),s=o.aud===r||Array.isArray(o.aud)&&o.aud.includes(r);return i&&s}catch{return!1}},$0e=(e)=>or.gen(function*(){let t=process.env.GRAPHQL_SERVER_URL??`http://localhost:${Ux()}`,r=process.env.INTERNAL_API_SECRET,n={"Content-Type":"application/json"};if(r)n["x-callback-secret"]=r;let o=yield*gk.encode(fre)({processPaths:e}).pipe(or.mapError((s)=>new Xy({cause:s}))),i=yield*or.tryPromise({try:()=>fetch(`${t}/internal/import-completed`,{method:"POST",headers:n,body:o}),catch:(s)=>new Xy({cause:s})});if(!i.ok){let s=yield*or.tryPromise({try:()=>i.text(),catch:(a)=>new Xy({cause:a})});return yield*new Xy({cause:`Server returned ${i.status}: ${s}`})}yield*ro.log("Frontend notified of changes")}).pipe(or.catchAll((t)=>ro.warn(`\u26A0\uFE0F Could not notify frontend: ${eq(t)}`))),q0e=(e)=>or.gen(function*(){let t=yield*gk.encode(fre)({processPaths:e}).pipe(or.mapError((n)=>new Xy({cause:n}))),r=c4();yield*or.tryPromise({try:()=>fetch(`${r}/api/dev/import-completed`,{method:"POST",headers:{"Content-Type":"application/json"},body:t}),catch:(n)=>new Xy({cause:n})})}).pipe(or.catchAll((t)=>ro.warn(`\u26A0\uFE0F Could not notify frontend dev event stream: ${eq(t)}`))),j0e="deploy-artifact",dre=300,H0e=()=>process.env.PF_IMPORT_MODE===j0e,eq=(e)=>e instanceof Error?e.message:String(e),W0e=(e)=>e instanceof Error?e.stack??e.message:M0e(e,{breakLength:120,depth:4}),V0e=(e,t,r={runMigrations:!0,ensureFrontendJwt:!0})=>{let n=cre(new URL("../main.ts",import.meta.url)),o=Sk(n)?n:cre(new URL("./main.mjs",import.meta.url)),i={...process.env,...r.runMigrations?{}:{PF_IMPORT_SKIP_MIGRATIONS:"1"},...r.ensureFrontendJwt?{}:{PF_IMPORT_SKIP_FRONTEND_JWT:"1"}};return new Promise((s,a)=>{let c=_0e(process.execPath,["run",o,"import",e],{cwd:process.cwd(),env:i,stdio:"inherit"}),l=()=>c.kill("SIGTERM");if(t?.aborted)l();else t?.addEventListener("abort",l,{once:!0});c.on("error",(d)=>{t?.removeEventListener("abort",l),a(d)}),c.on("exit",(d,u)=>{if(t?.removeEventListener("abort",l),d===0){s();return}a(Error(u?`pfcli import exited with signal ${u}`:`pfcli import exited with code ${d??"unknown"}`))})})},z0e=()=>{let e=process.env.PF_IMPORT_WATCH_DEBOUNCE_MS;if(!e)return dre;let t=Number(e);return Number.isFinite(t)&&t>=0?t:dre},ure=(e)=>`${Math.round(e)}ms`,K0e=(e)=>{let t=F0e(e);return t.startsWith(".#")||t.startsWith("#")&&t.endsWith("#")||t.endsWith("~")||t.endsWith(".swp")||t.endsWith(".swo")||t.endsWith(".swx")},G0e=(e)=>{let t=e.replaceAll("\\","/");return t.endsWith("/drizzle.config.ts")||t.includes("/drizzle/")},Q0e=(e)=>{let t=Z$(process.cwd(),e),r=[Id(t,"src"),Id(t,"cedar"),Id(t,"drizzle"),Id(t,"drizzle.config.ts")],n=new Set,o=(i)=>{if(!Sk(i))return;if(n.add(i),!O0e(i).isDirectory())return;for(let a of D0e(i,{withFileTypes:!0})){if(a.name==="node_modules"||a.name==="dist")continue;if(a.isDirectory())o(Id(i,a.name))}};for(let i of r)o(i);return[...n]},J0e=(e,t)=>{let r=Q0e(e),n=[];for(let o of r){let i=N0e(o,(s,a)=>{t({eventType:s,path:a?Id(o,a.toString()):o})});n.push(i)}return n.map((o)=>({close:()=>o.close()}))},Y0e=async(e,t={})=>{let r=t.debounceMs??z0e(),n=t.skipInitialImport??!1,o=t.signal,i=t.runImportOnce??((w,_,T)=>V0e(w,_,T)),s=t.createWatchers??J0e,a,c=!1,l=!1,d=!1,u=!1,p=0,y=[],g=()=>{if(!a)return;clearTimeout(a),a=void 0},E=()=>{g();for(let w of y)w.close();y=[]},S=async(w,_)=>{if(o?.aborted)return;if(c){l=!0,d||=_;return}c=!0,l=!1,d=!1,p+=1;let T=p,b=performance.now(),I={runMigrations:_,ensureFrontendJwt:_};console.log(`
|
|
886
|
+
[import:watch] cycle ${T} started (${w}${_?", full":", fast"})`);try{await i(e,o,I),console.log(`[import:watch] cycle ${T} completed in ${ure(performance.now()-b)}`)}catch(O){if(o?.aborted)return;console.error(`[import:watch] cycle ${T} failed in ${ure(performance.now()-b)}: ${O instanceof Error?O.message:String(O)}`)}finally{c=!1}if(l&&!o?.aborted)x("changes during previous cycle",d)},x=(w,_)=>{u||=_,g(),a=setTimeout(()=>{a=void 0;let T=u;u=!1,S(w,T)},r)};if(console.log(`[import:watch] watching ${Z$(process.cwd(),e)} (debounce ${r}ms)`),y=s(e,(w)=>{if(K0e(w.path))return;console.log(`[import:watch] change detected: ${w.path}`),x(`${w.eventType} ${w.path}`,G0e(w.path))}),y.length===0)console.warn(n?"[import:watch] no existing source paths to watch; skip-initial mode assumes a separate bootstrap import has already completed. Later saves will not be observed until watch mode is restarted":"[import:watch] no existing source paths to watch yet; initial import will still run");if(o?.addEventListener("abort",E,{once:!0}),n)console.log("[import:watch] initial import skipped; using completed bootstrap");else await S("initial",!0);await new Promise((w)=>{if(o?.aborted){w();return}o?.addEventListener("abort",()=>w(),{once:!0})})},mre=(e)=>typeof e==="object"&&e!==null,X0e=(e)=>{if(!mre(e))return{};let t={};if(typeof e.query==="string")t.query=e.query;if(Array.isArray(e.params))t.params=e.params;return t},Z0e=(e)=>{let t=e;while(mre(t)){if("cause"in t){t=t.cause;continue}if(typeof t.message==="string")return t.message;break}return},eOe=(e)=>or.gen(function*(){if(!vf(e))return;let t=yield*Bo,r=U0e(e);if(!(yield*t.exists(r)))yield*t.makeDirectory(r,{recursive:!0}),yield*ro.log(`Created database directory: ${r}`)}),tOe=(e,t)=>or.acquireUseRelease(or.sync(()=>{let r=process.env.SQLITE_DATABASE_PATH;return process.env.SQLITE_DATABASE_PATH=e,r}),()=>t,(r)=>or.sync(()=>{if(r===void 0){delete process.env.SQLITE_DATABASE_PATH;return}process.env.SQLITE_DATABASE_PATH=r})),rOe=(e)=>{if(!Sk(e))throw Error(`Organisation deploy manifest not found: ${e}. Re-run deploy with a freshly built artifact.`);let t;try{t=JSON.parse(pre(e,"utf8"))}catch(r){throw Error(`Organisation deploy manifest at ${e} is not valid JSON. Re-run deploy with a freshly built artifact.`,{cause:r})}try{return pG(t)}catch(r){throw Error(`Organisation deploy manifest at ${e} is invalid: ${r instanceof Error?r.message:String(r)}. Re-run deploy with a freshly built artifact.`,{cause:r})}},nOe=(e)=>or.gen(function*(){let t=yield*Bo,r=H0e(),n=Z$(process.cwd(),e),o=Id(n,"src","index.ts"),i=Id(n,"dist","org.js"),s=Id(n,"org.js"),a=Id(n,"dist",Sg);if(r)yield*or.try({try:()=>{if(!Sk(i))throw Error(`Deploy artifact bundle not found: ${i}. Re-run deploy with a freshly built artifact.`);let u=rOe(a);if(k0e("sha256").update(pre(i)).digest("hex")!==u.orgBundleSha256)throw Error(`Organisation bundle hash mismatch for ${i}. Re-run deploy with a freshly built artifact.`)},catch:(u)=>new Hl({path:e,cause:u})});else if(yield*t.exists(o))yield*Tg(e);let c=yield*t.exists(i),l=r?i:c?i:(yield*t.exists(s))?s:void 0;if(!l)return yield*new Hl({path:e,cause:Error(`Built organisation bundle not found. Checked ${i} and ${s}`)});let d=yield*or.tryPromise({try:async()=>await import(l),catch:(u)=>new Hl({path:e,cause:u})});if(!d.dbImport||!or.isEffect(d.dbImport))return yield*new Hl({path:e,cause:Error(`Built organisation bundle at ${l} must export a 'dbImport' Effect.`)});return{bundlePath:l,dbImport:d.dbImport}}),vk=(e,t={})=>or.gen(function*(){let r=t.runMigrations??process.env.PF_IMPORT_SKIP_MIGRATIONS!=="1",n=t.ensureFrontendJwt??process.env.PF_IMPORT_SKIP_FRONTEND_JWT!=="1",o=As(e);if(!o)return yield*new Hl({path:e,cause:Is});yield*eOe(o);let{bundlePath:i,dbImport:s}=yield*nOe(e);if(yield*ro.log(`Using built organisation bundle: ${i}`),r)yield*hk(e).pipe(or.catchTag("MigrationError",(c)=>or.gen(function*(){if(yield*ro.error(`
|
|
887
|
+
\u274C Migration failed: ${c.reason}`),c.statement)yield*ro.error(` Statement: ${c.statement}`);return yield*c})));else yield*ro.log("Skipping migrations for import watch fast path");yield*ro.log(`Importing to database: ${o}`);let a=Fv(o);yield*tOe(o,s.pipe(or.tap(({orgName:c})=>ro.log(`Loaded organisation: ${c}`)),or.tap(()=>ro.log(`\u2705 Database import completed: ${o}`)),or.tap(()=>n?or.gen(function*(){let c=uk(),l=Wl(),d=Ag(),u=yield*p_(l);if(u&&B0e(u,c,d)){yield*ro.log("Frontend JWT already exists, skipping creation (run 'pfcli refresh-frontend-jwt' to regenerate)");return}if(u)yield*ro.log("Frontend JWT issuer or audience changed, refreshing token");let p=yield*d_({clientId:l,issuerUrl:c,audience:d});yield*u_(l,p),yield*ro.log("Frontend JWT stored in database")}).pipe(or.provide(a),or.catchAll((c)=>ro.warn(`\u26A0\uFE0F Could not create frontend JWT: ${eq(c)}`))):ro.log("Skipping frontend JWT check for import watch fast path")),or.tap(({processPaths:c})=>or.all([$0e(c),q0e(c)],{concurrency:"unbounded"})),or.catchTags({SqlError:(c)=>or.gen(function*(){yield*ro.error(`
|
|
888
|
+
\u274C SQL Error:`);let{cause:l}=c,d=X0e(l);if(d.query)yield*ro.error(` Query: ${d.query}`);if(d.params)yield*ro.error(` Params: ${globalThis.JSON.stringify(d.params)}`);let u=Z0e(l)??c.message;if(u)yield*ro.error(` Error: ${u}`);return yield*c})}),or.tapDefect((c)=>or.gen(function*(){yield*ro.error(`
|
|
889
|
+
\u274C Unexpected error occurred:`),yield*ro.error(W0e(c))}))))}),yre=(e,t={})=>or.acquireUseRelease(or.sync(()=>{let r=new AbortController,n=()=>r.abort();if(t.signal?.aborted)n();else t.signal?.addEventListener("abort",n,{once:!0});return{abort:n,controller:r}}),({controller:r})=>or.tryPromise({try:()=>Y0e(e,{...t,signal:r.signal}),catch:(n)=>new Hl({path:e,cause:n})}),({abort:r,controller:n})=>or.sync(()=>{t.signal?.removeEventListener("abort",r),n.abort()}));import{readFileSync as oOe,writeFileSync as hre}from"fs";import*as da from"path";import{Console as Oc,Effect as Ek,Schema as xk}from"effect";var lT=sR,iOe=`export * from "./org"
|
|
890
|
+
`,sOe="^3.19.13",aOe="^1.0.0-rc.4-ca0f029",cOe=xk.Record({key:xk.String,value:xk.Unknown}),Hf=(e)=>JSON.stringify(e),gre=(e,t)=>`${e.replace(/[^a-z0-9]/gi,"_").toUpperCase()}_${t}`,lOe=(e)=>e.split(/[-_]/).map((t)=>t.charAt(0).toUpperCase()+t.slice(1)).join(" "),dOe=(e)=>`{
|
|
891
|
+
${e.map((r)=>` ${r}: {
|
|
892
|
+
clientID: process.env[${Hf(gre(r,"CLIENT_ID"))}] ?? "",
|
|
893
|
+
clientSecret: process.env[${Hf(gre(r,"CLIENT_SECRET"))}] ?? "",
|
|
894
|
+
scopes: [${YN[r].map(Hf).join(", ")}],
|
|
895
|
+
},`).join(`
|
|
896
|
+
`)}
|
|
897
|
+
}`,uOe=(e)=>{if(e.length===1){let t=e[0];if(t===void 0)return`/*
|
|
898
|
+
* Identity providers handle how people prove who they are when logging in.
|
|
899
|
+
*
|
|
900
|
+
* In this example, the configured identity providers confirm who each person
|
|
901
|
+
* is and share basic profile information such as their email address.
|
|
902
|
+
*/`;return`/*
|
|
903
|
+
* Identity providers handle how people prove who they are when logging in.
|
|
904
|
+
*
|
|
905
|
+
* In this example, ${lOe(t)} is the identity provider.
|
|
906
|
+
* It confirms who the person is and shares basic profile information such as
|
|
907
|
+
* their email address.
|
|
908
|
+
*/`}return`/*
|
|
909
|
+
* Identity providers handle how people prove who they are when logging in.
|
|
910
|
+
*
|
|
911
|
+
* In this example, the configured identity providers confirm who each person
|
|
912
|
+
* is and share basic profile information such as their email address.
|
|
913
|
+
*/`},pOe=(e)=>`${JSON.stringify({name:e,version:"0.0.1",private:!0,type:"module",dependencies:{...UG,effect:sOe,processfocus:FG},devDependencies:{"drizzle-kit":aOe}},null,2)}
|
|
914
|
+
`,fOe=`import { Schema as ES } from "effect"
|
|
915
|
+
import { Form, type OrgUnit, Process, type Role } from "processfocus"
|
|
916
|
+
import { FormLabel } from "processfocus/forms"
|
|
917
|
+
|
|
918
|
+
export class Todo extends Process {
|
|
919
|
+
constructor(
|
|
920
|
+
scope: OrgUnit,
|
|
921
|
+
id: string,
|
|
922
|
+
employeeRole: Role,
|
|
923
|
+
managerRole: Role,
|
|
924
|
+
) {
|
|
925
|
+
super(scope, id, {
|
|
926
|
+
name: "Todo",
|
|
927
|
+
purpose: "Simple task management process",
|
|
928
|
+
})
|
|
929
|
+
|
|
930
|
+
/*
|
|
931
|
+
* This process flow has two steps.
|
|
932
|
+
*
|
|
933
|
+
* First, an employee creates a todo. Then a manager completes and
|
|
934
|
+
* acknowledges it. The final line below wires those steps into a simple
|
|
935
|
+
* start-to-end flow.
|
|
936
|
+
*/
|
|
937
|
+
const create_todo = new Form(this, "Create todo", {
|
|
938
|
+
name: "Create new todo",
|
|
939
|
+
form: () => ({
|
|
940
|
+
title: ES.String.annotations({ [FormLabel]: "Title" }),
|
|
941
|
+
description: ES.String.annotations({ [FormLabel]: "Description" }),
|
|
942
|
+
}),
|
|
943
|
+
role: employeeRole,
|
|
944
|
+
})
|
|
945
|
+
|
|
946
|
+
const complete_todo = new Form(this, "Complete todo", {
|
|
947
|
+
name: "Complete and acknowledge",
|
|
948
|
+
form: () => ({}),
|
|
949
|
+
role: managerRole,
|
|
950
|
+
})
|
|
951
|
+
|
|
952
|
+
this.start(create_todo).end(complete_todo)
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
`,mOe=(e,t,r,n,o)=>`import {
|
|
956
|
+
AuthenticationConfig,
|
|
957
|
+
type AuthenticationConfigProps,
|
|
958
|
+
PoliciesConfig,
|
|
959
|
+
} from "processfocus/auth"
|
|
960
|
+
import {
|
|
961
|
+
type BusinessCalendarConfig,
|
|
962
|
+
NZ_HOLIDAYS,
|
|
963
|
+
Saturday,
|
|
964
|
+
Sunday,
|
|
965
|
+
Weekdays,
|
|
966
|
+
} from "processfocus/calendar"
|
|
967
|
+
import { Invitation, OrgUnit, Organisation, Role } from "processfocus"
|
|
968
|
+
import { Todo } from "./todo"
|
|
969
|
+
|
|
970
|
+
const weekdaySchedule = Weekdays.map((day) => ({
|
|
971
|
+
day,
|
|
972
|
+
ranges: [{ open: { hour: 8, minute: 30 }, close: { hour: 17, minute: 0 } }],
|
|
973
|
+
}))
|
|
974
|
+
|
|
975
|
+
/*
|
|
976
|
+
* The business calendar defines when your organisation is considered to be
|
|
977
|
+
* working.
|
|
978
|
+
*
|
|
979
|
+
* Process Focus uses it for due dates, scheduling, and other time-based
|
|
980
|
+
* calculations. That means weekends, holidays, and working hours are handled
|
|
981
|
+
* consistently everywhere.
|
|
982
|
+
*
|
|
983
|
+
* For example, if you schedule something 2 days from now, that means
|
|
984
|
+
* 2 business days according to this business calendar.
|
|
985
|
+
*/
|
|
986
|
+
const businessCalendar: BusinessCalendarConfig = {
|
|
987
|
+
weeklySchedule: weekdaySchedule,
|
|
988
|
+
holidays: NZ_HOLIDAYS,
|
|
989
|
+
exceptions: [],
|
|
990
|
+
nonWorkingDays: [Saturday, Sunday],
|
|
991
|
+
periods: [],
|
|
992
|
+
startDayOfWeek: Sunday,
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
export const org = new Organisation({
|
|
996
|
+
name: ${Hf(e)},
|
|
997
|
+
acronym: ${Hf(t)},
|
|
998
|
+
timeZone: ${Hf(r)},
|
|
999
|
+
businessCalendar,
|
|
1000
|
+
})
|
|
1001
|
+
|
|
1002
|
+
/*
|
|
1003
|
+
* Roles describe the responsibilities people can have in your organisation.
|
|
1004
|
+
*
|
|
1005
|
+
* People are assigned roles, and processes use those roles to decide who can
|
|
1006
|
+
* start work, review work, approve work, or administer the system.
|
|
1007
|
+
*/
|
|
1008
|
+
export const employee = new Role(org, "Employee", { name: "Employee" })
|
|
1009
|
+
export const administrator = new Role(org, "Administrator", {
|
|
1010
|
+
name: "Administrator",
|
|
1011
|
+
})
|
|
1012
|
+
|
|
1013
|
+
/*
|
|
1014
|
+
* Org units model the structure of your organisation.
|
|
1015
|
+
*
|
|
1016
|
+
* They can represent departments, teams, regions, or other parts of the
|
|
1017
|
+
* business. Roles and processes can then be attached to the right part of the
|
|
1018
|
+
* organisation.
|
|
1019
|
+
*/
|
|
1020
|
+
const operations = new OrgUnit(org, "operations", {
|
|
1021
|
+
name: "Operations",
|
|
1022
|
+
type: "department",
|
|
1023
|
+
})
|
|
1024
|
+
const operations_manager = new Role(operations, "Manager", {
|
|
1025
|
+
name: "Manager",
|
|
1026
|
+
})
|
|
1027
|
+
|
|
1028
|
+
/*
|
|
1029
|
+
* This creates your first process in the Operations department.
|
|
1030
|
+
*
|
|
1031
|
+
* A process models a repeatable piece of business work. In this example, the
|
|
1032
|
+
* process is a simple todo flow with one person creating work and another
|
|
1033
|
+
* person completing it.
|
|
1034
|
+
*/
|
|
1035
|
+
new Todo(operations, "todo", employee, operations_manager)
|
|
1036
|
+
|
|
1037
|
+
${uOe(n)}
|
|
1038
|
+
const identityProviders: AuthenticationConfigProps["identityProviders"] = ${dOe(n)}
|
|
1039
|
+
|
|
1040
|
+
new AuthenticationConfig(org, "auth", {
|
|
1041
|
+
inviteOnly: true,
|
|
1042
|
+
identityProviders,
|
|
1043
|
+
secretClients: {},
|
|
1044
|
+
})
|
|
1045
|
+
|
|
1046
|
+
/*
|
|
1047
|
+
* Policies control authorisation: what people are allowed to do after they
|
|
1048
|
+
* have logged in.
|
|
1049
|
+
*
|
|
1050
|
+
* These policy files let you customise access rules for your organisation,
|
|
1051
|
+
* such as who may view, manage, or approve different kinds of work.
|
|
1052
|
+
*/
|
|
1053
|
+
new PoliciesConfig(org, "policies", {
|
|
1054
|
+
policyFiles: ["cedar/custom.cedar"],
|
|
1055
|
+
})
|
|
1056
|
+
|
|
1057
|
+
/*
|
|
1058
|
+
* An invitation allows the person with this email address to log in.
|
|
1059
|
+
*
|
|
1060
|
+
* Their identity is validated by the identity provider. Process Focus relies
|
|
1061
|
+
* on that identity provider and does not validate identities itself.
|
|
1062
|
+
*
|
|
1063
|
+
* When this person logs in for the first time, Process Focus assigns them the
|
|
1064
|
+
* Employee and Administrator roles.
|
|
1065
|
+
*/
|
|
1066
|
+
new Invitation(org, "admin", {
|
|
1067
|
+
email: ${Hf(o)},
|
|
1068
|
+
roles: [employee, administrator],
|
|
1069
|
+
})
|
|
1070
|
+
`,yOe=`import { pathToFileURL } from "node:url"
|
|
1071
|
+
import { defineConfig } from "drizzle-kit"
|
|
1072
|
+
|
|
1073
|
+
const dbPath = process.env.SQLITE_DATABASE_PATH
|
|
1074
|
+
if (!dbPath) {
|
|
1075
|
+
throw new Error(
|
|
1076
|
+
"SQLITE_DATABASE_PATH environment variable is required.\\n" +
|
|
1077
|
+
"Please set it to the path of your SQLite database file.\\n" +
|
|
1078
|
+
"Example: export SQLITE_DATABASE_PATH=/path/to/database.db",
|
|
1079
|
+
)
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
// Parse the URL to determine protocol
|
|
1083
|
+
// If no protocol, treat as file path
|
|
1084
|
+
let parsedUrl: URL
|
|
1085
|
+
try {
|
|
1086
|
+
parsedUrl = new URL(dbPath)
|
|
1087
|
+
} catch {
|
|
1088
|
+
// Not a valid URL, treat as file path
|
|
1089
|
+
parsedUrl = pathToFileURL(dbPath)
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
const dbUrl = parsedUrl.href
|
|
1093
|
+
|
|
1094
|
+
// Use "turso" dialect for remote Turso databases (libsql://),
|
|
1095
|
+
// "sqlite" for local files (file://)
|
|
1096
|
+
const isRemote = parsedUrl.protocol === "libsql:"
|
|
1097
|
+
const dialect = isRemote ? "turso" : "sqlite"
|
|
1098
|
+
let authToken: string | undefined
|
|
1099
|
+
if (isRemote) {
|
|
1100
|
+
authToken = process.env.TURSO_AUTH_TOKEN
|
|
1101
|
+
if (!authToken) {
|
|
1102
|
+
throw new Error("TURSO_AUTH_TOKEN is required for remote Turso databases")
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
export default defineConfig({
|
|
1107
|
+
schema: "./src/schema/schema.ts",
|
|
1108
|
+
out: "./drizzle",
|
|
1109
|
+
dialect,
|
|
1110
|
+
// Use separate table to avoid collisions with core schema migrations
|
|
1111
|
+
migrations: { table: "__drizzle_migrations_org" },
|
|
1112
|
+
dbCredentials: {
|
|
1113
|
+
url: dbUrl,
|
|
1114
|
+
...(authToken && { authToken }),
|
|
1115
|
+
},
|
|
1116
|
+
})
|
|
1117
|
+
`,hOe=(e)=>`// ${e} can request the Administrator role
|
|
1118
|
+
permit (
|
|
1119
|
+
principal == PF::ProviderUser::${Hf(e)},
|
|
1120
|
+
action == PF::Action::"requestRole",
|
|
1121
|
+
resource == PF::Role::"/Administrator"
|
|
1122
|
+
);
|
|
1123
|
+
|
|
1124
|
+
// Administrators can complete any step
|
|
1125
|
+
permit (
|
|
1126
|
+
principal in PF::Role::"/Administrator",
|
|
1127
|
+
action == PF::Action::"complete",
|
|
1128
|
+
resource is PF::Step
|
|
1129
|
+
);
|
|
1130
|
+
|
|
1131
|
+
// Administrators can administer users
|
|
1132
|
+
permit (
|
|
1133
|
+
principal in PF::Role::"/Administrator",
|
|
1134
|
+
action == PF::Action::"administerUsers",
|
|
1135
|
+
resource is PF::Application
|
|
1136
|
+
);
|
|
1137
|
+
|
|
1138
|
+
// Administrators can administer OAuth providers
|
|
1139
|
+
permit (
|
|
1140
|
+
principal in PF::Role::"/Administrator",
|
|
1141
|
+
action == PF::Action::"administerOAuthProviders",
|
|
1142
|
+
resource is PF::Application
|
|
1143
|
+
);
|
|
1144
|
+
|
|
1145
|
+
// Administrators can view process state (debugging feature)
|
|
1146
|
+
permit (
|
|
1147
|
+
principal in PF::Role::"/Administrator",
|
|
1148
|
+
action == PF::Action::"showProcessState",
|
|
1149
|
+
resource is PF::Application
|
|
1150
|
+
);
|
|
1151
|
+
|
|
1152
|
+
// Administrators can view combined authorisation policies and schema.
|
|
1153
|
+
permit (
|
|
1154
|
+
principal in PF::Role::"/Administrator",
|
|
1155
|
+
action == PF::Action::"viewAuthorization",
|
|
1156
|
+
resource is PF::Application
|
|
1157
|
+
);
|
|
1158
|
+
|
|
1159
|
+
// Administrators can restart any execution
|
|
1160
|
+
permit (
|
|
1161
|
+
principal in PF::Role::"/Administrator",
|
|
1162
|
+
action == PF::Action::"restart",
|
|
1163
|
+
resource is PF::Execution
|
|
1164
|
+
);
|
|
1165
|
+
`,gOe=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}},SOe=(e)=>Ek.gen(function*(){let t=da.join(e,"package.json"),r=oOe(t,"utf8"),n=process.env.PFCLI_INIT_SDK_OVERRIDE,o=process.env.PFCLI_INIT_RUNTIME_OVERRIDE,i=n!==void 0||o!==void 0,s=yield*Ek.try({try:()=>{try{if(i){let c={...xk.decodeUnknownSync(cOe)(JSON.parse(r)),overrides:{...n===void 0?{}:{processfocus:n},...o===void 0?{}:{"@processfocus/runtime":o}}};hre(t,`${JSON.stringify(c,null,2)}
|
|
1166
|
+
`)}return Bun.spawnSync(["bun","install"],{cwd:e,stderr:"pipe",stdout:"pipe"})}finally{if(i)hre(t,r)}},catch:(a)=>new Qd({message:`Failed to install dependencies in ${e}`,cause:a})});if(s.exitCode!==0){let a=new TextDecoder,c=a.decode(s.stderr).trim(),l=a.decode(s.stdout).trim();return yield*new Qd({message:c||l?`bun install failed in ${e}: ${c||l}`:`bun install failed in ${e} with exit code ${s.exitCode}`})}}),Sre=(e,t,r)=>Ek.gen(function*(){let n=yield*Bo;if(t.length===0)return yield*new Qd({message:`At least one --identity-provider must be supplied. Available providers: ${lT.join(", ")}`});if(!r.includes("@")||r.trim().length===0)return yield*new Qd({message:"A valid --email address is required."});let o=t.filter((y)=>!lT.includes(y));if(o.length>0)return yield*new Qd({message:`Unsupported provider(s): ${o.join(", ")}`});let i=t,s=da.resolve(process.cwd(),e),a=da.basename(s),c=a.toLowerCase().replace(/[^a-z0-9-_]/g,"-"),l=a.split("-").map((y)=>y.charAt(0).toUpperCase()+y.slice(1)).join(" "),d=a.split("-").map((y)=>y.charAt(0).toUpperCase()).join(""),u=gOe();if(yield*Oc.log(`Initialising organisation at: ${s}`),yield*n.exists(s)){if((yield*n.readDirectory(s).pipe(Ek.mapError((g)=>new Qd({message:`Failed to read directory: ${s}`,cause:g})))).length>0)return yield*new Qd({message:`Directory is not empty: ${s}`})}yield*Oc.log(`
|
|
1167
|
+
[1/3] Creating directory structure...`),yield*n.makeDirectory(s,{recursive:!0}),yield*n.makeDirectory(da.join(s,"src"),{recursive:!0}),yield*n.makeDirectory(da.join(s,"cedar"),{recursive:!0}),yield*Oc.log("[2/3] Writing template files..."),yield*n.writeFileString(da.join(s,"src","index.ts"),iOe),yield*Oc.log(" \u2705 src/index.ts"),yield*n.writeFileString(da.join(s,"src","todo.ts"),fOe),yield*Oc.log(" \u2705 src/todo.ts"),yield*n.writeFileString(da.join(s,"src","org.ts"),mOe(l,d,u,i,r)),yield*Oc.log(" \u2705 src/org.ts"),yield*n.writeFileString(da.join(s,"cedar","custom.cedar"),hOe(r)),yield*Oc.log(" \u2705 cedar/custom.cedar"),yield*n.writeFileString(da.join(s,"drizzle.config.ts"),yOe),yield*Oc.log(" \u2705 drizzle.config.ts"),yield*n.writeFileString(da.join(s,"package.json"),pOe(c)),yield*Oc.log(" \u2705 package.json"),yield*Oc.log("[3/3] Importing organisation..."),yield*Oc.log("Installing dependencies with bun..."),yield*SOe(s),yield*vk(s),yield*Oc.log(`
|
|
1168
|
+
\u2705 Organisation initialised successfully!
|
|
1169
|
+
Path: ${s}`)});import{Console as dT,Data as tq,Effect as es,Layer as bk}from"effect";Ki();class xre extends tq.TaggedError("InvitationRegistrationLinkDbPathError"){}class Ere extends tq.TaggedError("InvitationRegistrationLinkDatabaseError"){constructor(e){let t=typeof e==="object"&&e!==null&&"_tag"in e&&e._tag==="SqlError"?"SQL operation failed":"database client initialization failed";super({message:`Could not access the local database. Check SQLITE_DATABASE_PATH or org-path and try again. Failure category: ${t}.`,cause:e})}}class Tk extends tq.TaggedError("InvitationRegistrationLinkModeError"){}var vOe=30000,xOe=`
|
|
1170
|
+
mutation GenerateProjectRegistrationLink($projectId: String!, $environmentId: String!, $email: String!, $rotate: Boolean) {
|
|
1171
|
+
generateProjectRegistrationLink(projectId: $projectId, environmentId: $environmentId, email: $email, rotate: $rotate) {
|
|
1172
|
+
__typename
|
|
1173
|
+
... on ProjectRegistrationLinkSuccess {
|
|
1174
|
+
email
|
|
1175
|
+
registrationLinkUrl
|
|
1176
|
+
expiresAt
|
|
1177
|
+
}
|
|
1178
|
+
... on ProjectRegistrationLinkFailure {
|
|
1179
|
+
error
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
`,bre=(e)=>es.gen(function*(){if(!e.ok){yield*dT.error(`\u274C ${e.error}`),yield*es.sync(()=>{process.exitCode=1});return}yield*dT.log(e.registrationLinkUrl),yield*dT.log(`expires at: ${e.expiresAt}`)}),EOe=(e,t)=>!t&&e===m$?Qee:e,bOe=(e)=>process.env.PF_SCOPE??process.env.PF_ORG??e??"local",vre=()=>((process.env.FRONTEND_BASE_URL??process.env.BASE_URL??process.env.NEXT_PUBLIC_FRONTEND_URL)||"http://localhost:3000").replace(/\/$/,""),wOe=()=>{let e=process.env.INVITATION_REGISTRATION_ENCRYPTION_KEY;if(e)return e;let t="development";return t===void 0||t==="development"||t==="test"?Y_:void 0},TOe=(e)=>es.gen(function*(){let t=As(e.orgPath);if(!t)return yield*new xre({message:Is});let r=jf(t),n=bk.mergeAll(Jy,T$,tT).pipe(bk.provideMerge(Rv),bk.provideMerge(r),bk.provide(Fu(t))),o=wOe(),i=yield*Yee({email:e.email,rotate:e.rotate,actor:"SYSTEM",organisationScope:bOe(e.orgPath),frontendOrigin:vre(),...o===void 0?{}:{secret:o}}).pipe(es.flatMap((s)=>!s.ok&&e.rotate&&s.error===f$?s7({email:e.email,actor:"SYSTEM",frontendOrigin:vre()}):es.succeed(s)),es.provide(n),es.mapError((s)=>new Ere(s)));yield*bre(i.ok?{ok:!0,registrationLinkUrl:i.registrationLinkUrl,expiresAt:i.expiresAt.toISOString()}:{ok:!1,error:EOe(i.error,e.rotate)})}),AOe=(e)=>es.gen(function*(){let r=(yield*Mr(xOe,{projectId:e.projectId,environmentId:e.environmentId,email:e.email,rotate:e.rotate},{timeoutMs:vOe})).generateProjectRegistrationLink;yield*bre(r.__typename==="ProjectRegistrationLinkSuccess"?{ok:!0,registrationLinkUrl:r.registrationLinkUrl,expiresAt:r.expiresAt}:{ok:!1,error:r.error})}),IOe=(e)=>es.gen(function*(){let{projectId:t,environmentId:r}=e;if(Boolean(t)!==Boolean(r))return yield*new Tk({message:"Remote mode requires both --project and --env together."});if(t&&r){if(e.orgPath)return yield*new Tk({message:"Remote mode does not accept positional org-path. Remove org-path when using --project/--env."})}if(!e.email)return yield*new Tk({message:`Missing required option: --email.
|
|
1184
|
+
Local example: pfcli invitation registration-link [org-path] --email <invited-email>
|
|
1185
|
+
Remote example: pfcli invitation registration-link --project <project-number> --env <environment-name> --email <invited-email>`});if(t&&r)return{kind:"remote",projectId:t,environmentId:r,email:e.email,rotate:e.rotate};return{kind:"local",orgPath:e.orgPath,email:e.email,rotate:e.rotate}}),ROe=(e)=>es.gen(function*(){let t=yield*IOe(e);if(t.kind==="local")return yield*TOe(t);return yield*ai(t.projectId,t.environmentId),yield*AOe({projectId:t.projectId,environmentId:t.environmentId,email:t.email,rotate:t.rotate})}),wk=(e)=>es.gen(function*(){yield*dT.error(`
|
|
1186
|
+
\u274C ${e.message}`),yield*es.sync(()=>{process.exitCode=1})}),wre=(e)=>ROe(e).pipe(es.catchTags({InvitationRegistrationLinkModeError:wk,InvitationRegistrationLinkDbPathError:wk,InvitationRegistrationLinkDatabaseError:wk,CliError:wk}),es.catchAll(()=>es.gen(function*(){yield*dT.error(`
|
|
1187
|
+
\u274C Registration link failed unexpectedly.`),yield*es.sync(()=>{process.exitCode=1})})));import{Console as rq,Effect as Ak}from"effect";var POe=`
|
|
1188
|
+
query GetRuntimeLogs($projectId: String!, $environmentId: String!, $target: RuntimeLogTarget!, $limit: Int) {
|
|
1189
|
+
getRuntimeLogs(projectId: $projectId, environmentId: $environmentId, target: $target, limit: $limit) {
|
|
1190
|
+
events {
|
|
1191
|
+
timestamp
|
|
1192
|
+
message
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
`,COe=100,Tre=(e,t,r)=>ai(e,t).pipe(Ak.flatMap(()=>Mr(POe,{projectId:e,environmentId:t,target:r,limit:COe})),Ak.mapError((n)=>new ce({message:n.message,cause:n.cause})),Ak.flatMap(({getRuntimeLogs:n})=>Ak.gen(function*(){let o=r.toLowerCase();if(yield*rq.log(`Showing recent ${o} logs.`),n.events.length===0){yield*rq.log(`No recent ${o} logs found.`);return}for(let i of n.events)yield*rq.log(`${i.timestamp} ${i.message}`)}))),Are=(e,t)=>Tre(e,t,"PRIMARY"),Ire=(e,t)=>Tre(e,t,"CANARY");import{Console as Rre,Effect as _Oe}from"effect";var kOe=100,DOe=`
|
|
1197
|
+
query ListProjects($page: Int!, $limit: Int!) {
|
|
1198
|
+
listProjects(page: $page, limit: $limit) {
|
|
1199
|
+
items {
|
|
1200
|
+
projectNumber
|
|
1201
|
+
projectName
|
|
1202
|
+
}
|
|
1203
|
+
totalCount
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
`,Pre=()=>_Oe.gen(function*(){let e=1,t=0,r;while(r===void 0||t<r){let n=yield*Mr(DOe,{page:e,limit:kOe}),{items:o}=n.listProjects;if(r=n.listProjects.totalCount,o.length===0)break;for(let i of o)yield*Rre.log(`${i.projectNumber} ${i.projectName}`);t+=o.length,e+=1}if(t===0)yield*Rre.log("No projects found.")});import{Console as OOe,Effect as nq}from"effect";Ki();var Cre=(e,t={})=>nq.gen(function*(){let r=As(e);if(!r)return yield*new Hl({path:e,cause:Is});let n=Fv(r),o=uk(),i=Wl(),s=Ag();yield*d_({clientId:i,issuerUrl:o,audience:s,...t.issuedAtUnixSeconds?{issuedAtUnixSeconds:t.issuedAtUnixSeconds()}:{}}).pipe(nq.flatMap((a)=>u_(i,a)),nq.provide(n)),yield*OOe.log(`Frontend JWT refreshed (issuer: ${o}, audience: ${s})`)});import{Console as _re,Effect as kre}from"effect";var NOe=`# pfcli agent skill
|
|
1207
|
+
|
|
1208
|
+
Use this guide when operating the Process Focus CLI from an agent.
|
|
1209
|
+
|
|
1210
|
+
## Start here
|
|
1211
|
+
|
|
1212
|
+
- Prefer the workspace command while developing in this repository: \`bun cli/pfcli/src/main.ts <command>\`.
|
|
1213
|
+
- Prefer the installed command outside the monorepo: \`pfcli <command>\`.
|
|
1214
|
+
- Use \`pfcli --help\` or \`pfcli <command> --help\` for structural command help.
|
|
1215
|
+
- Do not print, persist, or quote access tokens, signed URLs, Turso tokens, SSM parameter values, AWS credentials, or raw secrets.
|
|
1216
|
+
- If a command says to run \`pfcli auth login\`, authenticate before retrying remote commands.
|
|
1217
|
+
|
|
1218
|
+
## Common workflows
|
|
1219
|
+
|
|
1220
|
+
### Scaffold an organisation
|
|
1221
|
+
|
|
1222
|
+
\`\`\`bash
|
|
1223
|
+
pfcli init <org-path> --email <admin-email> --identity-provider <provider>
|
|
1224
|
+
\`\`\`
|
|
1225
|
+
|
|
1226
|
+
- Repeat \`--identity-provider\` for multiple providers.
|
|
1227
|
+
- \`org-path\` may come from \`PF_ORG\`.
|
|
1228
|
+
- The command creates the org template, installs released dependencies, imports the org, and creates the local frontend JWT.
|
|
1229
|
+
|
|
1230
|
+
### Build an organisation artifact
|
|
1231
|
+
|
|
1232
|
+
\`\`\`bash
|
|
1233
|
+
pfcli build <org-path> [--output dist]
|
|
1234
|
+
\`\`\`
|
|
1235
|
+
|
|
1236
|
+
- Produces \`dist/org.js\`, \`dist/graphql/org.graphql\`, and \`dist/cedar/\`.
|
|
1237
|
+
- Use this before inspecting deployable org output.
|
|
1238
|
+
|
|
1239
|
+
### Import an organisation locally
|
|
1240
|
+
|
|
1241
|
+
\`\`\`bash
|
|
1242
|
+
pfcli import <org-path>
|
|
1243
|
+
\`\`\`
|
|
1244
|
+
|
|
1245
|
+
- Uses \`SQLITE_DATABASE_PATH\` or \`<org-path>/db/pf.db\`.
|
|
1246
|
+
- Builds first when source is present, runs migrations, then imports the bundled model.
|
|
1247
|
+
|
|
1248
|
+
### Deploy a project environment
|
|
1249
|
+
|
|
1250
|
+
\`\`\`bash
|
|
1251
|
+
pfcli deploy <org-path> --project <project-number> --env <environment-name>
|
|
1252
|
+
pfcli deploy <org-path> --project <project-number> --env <environment-name> --no-wait
|
|
1253
|
+
\`\`\`
|
|
1254
|
+
|
|
1255
|
+
- Requires \`pfcli auth login\` credentials.
|
|
1256
|
+
- Builds the org, uploads the dist artifact, starts the backend deploy process, and waits by default.
|
|
1257
|
+
- Project numbers and internal IDs are accepted. Prefer project numbers in user-facing examples.
|
|
1258
|
+
|
|
1259
|
+
### Mint a first-admin Registration Link
|
|
1260
|
+
|
|
1261
|
+
\`\`\`bash
|
|
1262
|
+
# Local database
|
|
1263
|
+
pfcli invitation registration-link [org-path] --email <invited-email>
|
|
1264
|
+
pfcli invitation registration-link [org-path] --email <invited-email> --rotate
|
|
1265
|
+
|
|
1266
|
+
# Remote customer environment
|
|
1267
|
+
pfcli invitation registration-link --project <project-number> --env <environment-name> --email <invited-email>
|
|
1268
|
+
pfcli invitation registration-link --project <project-number> --env <environment-name> --email <invited-email> --rotate
|
|
1269
|
+
\`\`\`
|
|
1270
|
+
|
|
1271
|
+
- Local mode resolves its database from \`SQLITE_DATABASE_PATH\`, \`org-path\`, or \`PF_ORG\`; remote mode requires \`--project\` and \`--env\` together plus \`pfcli auth login\` against Console.
|
|
1272
|
+
- Local URLs use \`FRONTEND_BASE_URL\`, \`BASE_URL\`, or \`NEXT_PUBLIC_FRONTEND_URL\`. Local mode is a developer workflow, so it intentionally falls back to \`http://localhost:3000\` even when \`NODE_ENV\` is unset; configure an origin when the local frontend uses another address.
|
|
1273
|
+
- Prints the Registration Link URL once to stdout. Do not copy that URL into logs, skill examples, or summaries; use a placeholder such as \`https://<env>.<project-number>.app.processfocus.com/register/passkey#token=<token>\`.
|
|
1274
|
+
- A second generate without \`--rotate\` fails; pass \`--rotate\` to replace an active or expired pending link. Revoked pending links are refused.
|
|
1275
|
+
- For an existing active account associated with an accepted or legacy-closed Invitation, \`--rotate\` issues a separate, single-use Passkey Recovery Link. It preserves current roles, existing passkeys, and Invitation history. Recovery requires current roles and an enabled passkey provider.
|
|
1276
|
+
- Remote recovery additionally requires the explicit \`recoverProviderUser\` permission, initially granted only to Cloud Backend Administrators. Recovery links expire after 24 hours; rotation invalidates older links and sessions.
|
|
1277
|
+
- Automated coverage verifies local token issuance and exchange at the authentication boundary. Completing passkey registration and signing in through the browser remains a manual acceptance step.
|
|
1278
|
+
|
|
1279
|
+
### Destroy a project environment
|
|
1280
|
+
|
|
1281
|
+
\`\`\`bash
|
|
1282
|
+
pfcli destroy --project <project-number> --env <environment-name> --yes
|
|
1283
|
+
pfcli destroy --project <project-number> --env <environment-name> --yes --no-wait
|
|
1284
|
+
\`\`\`
|
|
1285
|
+
|
|
1286
|
+
- Requires \`pfcli auth login\` credentials.
|
|
1287
|
+
- Project numbers and internal IDs are accepted. Prefer project numbers in user-facing examples.
|
|
1288
|
+
- This is destructive: it deletes the environment's AWS stacks and environment record through the existing Backend process.
|
|
1289
|
+
- \`--yes\` is mandatory and there is no interactive prompt.
|
|
1290
|
+
- Waits for completion by default. \`--no-wait\` returns after the execution starts.
|
|
1291
|
+
|
|
1292
|
+
### List remote inventory
|
|
1293
|
+
|
|
1294
|
+
\`\`\`bash
|
|
1295
|
+
pfcli projects
|
|
1296
|
+
pfcli stage list --project <project-number>
|
|
1297
|
+
pfcli env list --project <project-number> [--stage <stage-name>]
|
|
1298
|
+
\`\`\`
|
|
1299
|
+
|
|
1300
|
+
### Manage stage configuration
|
|
1301
|
+
|
|
1302
|
+
\`\`\`bash
|
|
1303
|
+
pfcli config list --project <project-number> --stage <stage-name>
|
|
1304
|
+
pfcli config get --project <project-number> --stage <stage-name> <key>
|
|
1305
|
+
pfcli config set --project <project-number> --stage <stage-name> KEY
|
|
1306
|
+
pfcli config set --project <project-number> --stage <stage-name> KEY=VALUE
|
|
1307
|
+
pfcli config set --project <project-number> --stage <stage-name> KEY VALUE
|
|
1308
|
+
pfcli config set --project <project-number> --stage <stage-name> --secret KEY
|
|
1309
|
+
pfcli config delete --project <project-number> --stage <stage-name> <key>
|
|
1310
|
+
pfcli config copy-new --project <project-number> --stage <target-stage> --from-stage <source-stage>
|
|
1311
|
+
\`\`\`
|
|
1312
|
+
|
|
1313
|
+
- The bare \`KEY\` form copies the exported environment variable of the same name and fails if it is unset. Use \`KEY=\` to explicitly set an empty value.
|
|
1314
|
+
- Use \`--secret\` for values that must be stored as secure parameters.
|
|
1315
|
+
- Never paste secret values into summaries or logs.
|
|
1316
|
+
|
|
1317
|
+
### Inspect runtime logs
|
|
1318
|
+
|
|
1319
|
+
\`\`\`bash
|
|
1320
|
+
pfcli logs --project <project-number> --env <environment-name>
|
|
1321
|
+
pfcli canary-logs --project <project-number> --env <environment-name>
|
|
1322
|
+
\`\`\`
|
|
1323
|
+
|
|
1324
|
+
- Output is raw timestamped log messages from the cloud API.
|
|
1325
|
+
- Do not promise streaming or a precise time window unless the CLI help says so.
|
|
1326
|
+
|
|
1327
|
+
## Database workflows
|
|
1328
|
+
|
|
1329
|
+
### Download a hosted database
|
|
1330
|
+
|
|
1331
|
+
\`\`\`bash
|
|
1332
|
+
pfcli db download --project <project-number> --env <environment-name> [--output ./backup.sqlite]
|
|
1333
|
+
\`\`\`
|
|
1334
|
+
|
|
1335
|
+
- Uses an authoritative engine value and short-lived read-only session from GraphQL.
|
|
1336
|
+
- SQLite-engine downloads use Turso Sync; treat \`--output\` as reusable sync state and expect possible sidecars.
|
|
1337
|
+
- TursoDB downloads stream and validate a logical dump into an ordinary SQLite file. Existing output is atomically replaced by a complete snapshot, not incrementally updated.
|
|
1338
|
+
- A failed TursoDB download leaves existing output untouched and removes private temporary files.
|
|
1339
|
+
- The first version is pull-only. Do not describe it as restore, backup verification, a backend snapshot artifact, or a document-store transfer.
|
|
1340
|
+
|
|
1341
|
+
### Upload a local database
|
|
1342
|
+
|
|
1343
|
+
\`\`\`bash
|
|
1344
|
+
pfcli db upload --project <project-number> --env <environment-name> [--mode data-copy|exact-restore] <sqlite-file>
|
|
1345
|
+
\`\`\`
|
|
1346
|
+
|
|
1347
|
+
- Uploads a local SQLite database through a signed document-store URL and waits for backend apply completion.
|
|
1348
|
+
- This is destructive from the environment's point of view. Expect the backend to create a recovery snapshot before cutover.
|
|
1349
|
+
- The default \`data-copy\` mode preserves the destination's cryptographic identity and stored frontend JWT, and discards imported OpenAuth sessions. Use \`exact-restore\` only when all uploaded state, including authentication keys and sessions, must replace destination state.
|
|
1350
|
+
- SQLite-engine targets require a WAL artifact and use Turso file seeding. TursoDB targets use logical dump replay, accept the delete-journal artifacts produced by TursoDB downloads, filter Turso-owned objects, and preserve AUTOINCREMENT continuity.
|
|
1351
|
+
- Do not print signed URLs or raw operation credentials.
|
|
1352
|
+
|
|
1353
|
+
### Open a live database shell
|
|
1354
|
+
|
|
1355
|
+
\`\`\`bash
|
|
1356
|
+
pfcli db shell --project <project-number> --env <environment-name> [--ttl 15m]
|
|
1357
|
+
\`\`\`
|
|
1358
|
+
|
|
1359
|
+
- Requires the external \`turso\` CLI on \`PATH\`.
|
|
1360
|
+
- Opens a live read-write shell for the Active Environment Database.
|
|
1361
|
+
- This is for investigation and emergency repair, not transfer, local SQLite access, restore, rollback, or backup workflows.
|
|
1362
|
+
|
|
1363
|
+
### Prepare a database rollback
|
|
1364
|
+
|
|
1365
|
+
\`\`\`bash
|
|
1366
|
+
pfcli db rollback --project <project-number> --env <environment-name> --timestamp <iso-timestamp>
|
|
1367
|
+
pfcli db rollback --project <project-number> --env <environment-name> --timestamp 2026-04-01T00:00:00Z --no-wait
|
|
1368
|
+
\`\`\`
|
|
1369
|
+
|
|
1370
|
+
- Accepts RFC3339 / ISO-8601 timestamps. If no timezone is supplied, local terminal timezone is used.
|
|
1371
|
+
|
|
1372
|
+
## Authentication
|
|
1373
|
+
|
|
1374
|
+
\`\`\`bash
|
|
1375
|
+
pfcli auth login
|
|
1376
|
+
\`\`\`
|
|
1377
|
+
|
|
1378
|
+
- Uses \`BASE_URL\` when set, otherwise defaults to \`https://console.processfocus.com\`.
|
|
1379
|
+
- The Console host is the canonical CLI auth endpoint for customer sessions.
|
|
1380
|
+
- Stores CLI credentials under the Process Focus config directory.
|
|
1381
|
+
- Remote commands use these credentials; do not edit credential files manually.
|
|
1382
|
+
|
|
1383
|
+
## Local runtime helpers
|
|
1384
|
+
|
|
1385
|
+
\`\`\`bash
|
|
1386
|
+
pfcli get-frontend-jwt [org-path]
|
|
1387
|
+
pfcli refresh-frontend-jwt [org-path]
|
|
1388
|
+
\`\`\`
|
|
1389
|
+
|
|
1390
|
+
- \`org-path\` may come from \`PF_ORG\`.
|
|
1391
|
+
- Use refresh when local auth/runtime issuer keys or URLs changed.
|
|
1392
|
+
|
|
1393
|
+
## Agent operating rules
|
|
1394
|
+
|
|
1395
|
+
- Ask for missing project, environment, stage, or org path values before taking remote action.
|
|
1396
|
+
- Prefer read-only commands first when diagnosing: \`projects\`, \`stage list\`, \`env list\`, \`config list\`, \`logs\`, \`canary-logs\`.
|
|
1397
|
+
- Treat \`destroy\`, \`db shell\`, \`db upload\`, \`db rollback\`, \`config set\`, \`config delete\`, \`stage add\`, \`env add\`, \`grant role\`, \`invitation registration-link\`, and \`deploy\` as state-changing.
|
|
1398
|
+
- For state-changing production actions, confirm target project/environment/stage unless the user already specified them clearly.
|
|
1399
|
+
- If command output is JSON status lines, preserve important IDs and final status, but redact secrets.
|
|
1400
|
+
- Re-run \`pfcli skills get core\` after upgrading \`pfcli\` instead of relying on cached guidance.`,oq=[{name:"core",description:"Core pfcli workflows, safety rules, and command guidance",content:NOe}],Dre=()=>kre.gen(function*(){for(let e of oq)yield*_re.log(`${e.name} ${e.description}`)}),Ore=(e)=>kre.gen(function*(){let t=oq.find((r)=>r.name===e);if(t===void 0)yield*new ce({message:`Unknown pfcli skill "${e}". Available skills: ${oq.map((r)=>r.name).join(", ")}`});else yield*_re.log(t.content)});import{Console as Nre,Effect as Ik}from"effect";var FOe=`
|
|
1401
|
+
mutation StartAddStage($projectId: String!, $stageName: String!) {
|
|
1402
|
+
startOperationsAddStage(input: { projectId: $projectId, stageName: $stageName }) {
|
|
1403
|
+
executionId
|
|
1404
|
+
processPath
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
`,UOe=900000,MOe=1e4,LOe=(e,t)=>{let r=`Stage "${t}" already exists in this project.`;return e.includes(r)?r:e},Fre=(e,t,r={})=>{let n=r.createExecutionEventSource??$s;return Ik.gen(function*(){let o=yield*ds(),i=oi(o.baseUrl),s=yield*Hr(i,o.accessToken,lc,{}),a=yield*Ra({credentials:o,subscriptionTransport:s.subscriptionTransport,missingUserIdMessage:"CLI access token is missing userId/sub claims required for stage add subscriptions.",createExecutionEventSourceImpl:n}),c=Pa(a,"Failed to close stage add execution subscription.");return yield*Ik.gen(function*(){let l=yield*Hr(i,o.accessToken,FOe,{projectId:e,stageName:t});yield*Nre.log(qs("Stage add started",{executionId:l.startOperationsAddStage.executionId}));let d=Date.now();yield*Ik.sync(()=>process.stdout.write(Ai("Waiting for stage creation to complete...",d)));let u=yield*ac(a,l.startOperationsAddStage.executionId,{executionLabel:"stage creation",timeoutMs:UOe,heartbeatMs:MOe,hasPendingInitialLine:!0,formatLogMessage:Ai,includeExecutionIdInTimeout:!0});if(u.status==="Completed"){yield*Nre.log(`Stage created: ${t}`);return}let p=cc(u)??`Stage creation ${u.status.toLowerCase()}.`;return yield*new ce({message:LOe(p,t)})}).pipe(Ik.ensuring(c))})};import{Console as Ure,Effect as BOe}from"effect";var $Oe=`
|
|
1408
|
+
query ListProjectStages($projectId: String!) {
|
|
1409
|
+
listProjectStages(projectId: $projectId) {
|
|
1410
|
+
items {
|
|
1411
|
+
stageName
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
`,Mre=(e)=>BOe.gen(function*(){let t=yield*Mr($Oe,{projectId:e}),{items:r}=t.listProjectStages;if(r.length===0){yield*Ure.log(`No stages found for project ${e}.`);return}for(let n of r)yield*Ure.log(n.stageName)});var iq="PFCLI_CI_PROVIDER_USER";var Lre=(e)=>{let t=[],r;for(let n=0;n<e.length;n++){let o=e[n];if(o===void 0)continue;if(o==="--ci-provider-user"){if(r!==void 0)return{argv:t,error:"--ci-provider-user must only be provided once"};let i=e[n+1];if(!i||i.startsWith("-"))return{argv:t,error:"--ci-provider-user requires an email address"};r=i,n++;continue}if(o.startsWith("--ci-provider-user=")){if(r!==void 0)return{argv:t,error:"--ci-provider-user must only be provided once"};r=o.slice(19);continue}t.push(o)}if(r!==void 0){let n=t.slice(2);if(n[0]!=="auth"||n[1]!=="login")return{argv:t,error:"--ci-provider-user is only supported by auth login"}}return r===void 0?{argv:t}:{argv:t,providerUser:r}};var Bre=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,qOe=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?$/,jOe=(e)=>e.toISOString().replace(".000Z","Z"),$re=(e)=>{if(Bre.test(e)&&e.endsWith("Z"))return e;if(!Bre.test(e)&&!qOe.test(e))return e;let t=new Date(e);if(Number.isNaN(t.getTime()))return e;return jOe(t)};var Rk=C2({name:"org-path",exists:"either"}).pipe(Nl("Path to the organisation directory")),Pk=C2({name:"org-path",exists:"either"}).pipe(Nl("Path to the organisation directory to initialise"),Nse(uT.string("PF_ORG"))),WOe=Gse("output",{exists:"either"}).pipe(Jse("o"),Ll("dist"),At("Output directory for build artifacts")),VOe=fr("project").pipe(Un,At("Project number (or internal ID) to deploy")),zOe=fr("env").pipe(Un,At("Environment name to deploy to")),KOe=fr("project").pipe(Un,At("Project number (or internal ID) whose runtime logs to read")),GOe=fr("env").pipe(Un,At("Environment name whose runtime logs to read")),QOe=mp("no-wait").pipe(Ll(!1),At("Return after starting the deployment without waiting")),JOe=mp("watch").pipe(Ll(!1),At("Run an experimental watched import loop with debounce, timing and recovery")),YOe=mp("watch-skip-initial").pipe(Ll(!1),At("Start watch mode without its initial import after a separate bootstrap import has completed")),XOe=fr("project").pipe(At("Project number or internal ID")),ZOe=fr("env").pipe(At("Environment name")),eNe=fr("project").pipe(Un,At("Project number (or internal ID) to roll back")),tNe=fr("env").pipe(Un,At("Environment name to roll back")),rNe=fr("timestamp").pipe(Un,At("RFC3339 / ISO-8601 rollback timestamp; if no timezone is supplied, the local terminal timezone is used (for example 2026-04-16T18:00:00)")),nNe=mp("no-wait").pipe(Ll(!1),At("Return after starting the rollback without waiting")),oNe=fr("project").pipe(Un,At("Project number (or internal ID) to destroy from")),iNe=fr("env").pipe(Un,At("Environment name (or internal ID) to destroy")),sNe=mp("yes").pipe(Ll(!1),At("Confirm deletion of the environment's AWS stacks and environment record")),aNe=mp("no-wait").pipe(Ll(!1),At("Return after starting destruction without waiting")),cNe=fr("project").pipe(Un,At("Project number (or internal ID) to download from")),lNe=fr("env").pipe(Un,At("Environment name to download from")),dNe=fr("output").pipe(Un,At("Output SQLite file path")),uNe=fr("project").pipe(Un,At("Project number (or internal ID) to open a database shell for")),pNe=fr("env").pipe(Un,At("Environment name to open a database shell for")),fNe=fr("ttl").pipe(Un,At('Database Shell session TTL; bare numbers are seconds, for example "900", "15m", or "1h"')),mNe=fr("project").pipe(Un,At("Project number (or internal ID) to upload to")),yNe=fr("env").pipe(Un,At("Environment name to upload to")),hNe=X2("mode",[...HOe]).pipe(Ll("data-copy"),At("Upload mode: preserve destination authentication identity (data-copy) or restore all database state (exact-restore)")),gNe=ap({name:"sqlite-file"}).pipe(l0,Nl("Local SQLite database file to upload")),SNe=X2("identity-provider",[...lT]).pipe(Qse,At(`Identity provider to scaffold (repeatable: ${lT.join(", ")})`)),vNe=fr("email").pipe(At("Admin email used for the scaffolded invitation and Cedar policy")),xNe=ap({name:"name"}).pipe(Nl("Skill name to print")),ENe=qt("import",{orgPath:Pk,watch:JOe,watchSkipInitial:YOe},({orgPath:e,watch:t,watchSkipInitial:r})=>t?yre(e,{skipInitialImport:r}):Fe.gen(function*(){if(r)yield*go.warn("--watch-skip-initial is ignored unless --watch is also set");return yield*vk(e)})).pipe(jt("Import organisation to SQLite database (uses PF_ORG, SQLITE_DATABASE_PATH, or $org-path/db/pf.db)")),bNe=qt("build",{orgPath:Rk,outputDir:WOe},({orgPath:e,outputDir:t})=>Tg(e,t).pipe(Fe.catchIf((r)=>r instanceof vn||r instanceof xp||r instanceof zh,(r)=>Fe.gen(function*(){yield*go.error(`
|
|
1416
|
+
\u274C ${r.message}`),yield*Fe.sync(()=>{process.exitCode=1})})))).pipe(jt("Build organisation artifacts (bundled JS, GraphQL schema, Cedar policies)")),wNe=qt("projects",{},()=>Pre().pipe(Fe.catchTag("CliError",(e)=>Fe.gen(function*(){yield*go.error(`
|
|
1417
|
+
\u274C ${e.message}`),yield*Fe.sync(()=>{process.exitCode=1})})))).pipe(jt("List projects in the Backend environment (tab-separated: number, name)")),TNe=qt("deploy",{orgPath:Rk,projectId:VOe,environmentId:zOe,noWait:QOe},({orgPath:e,projectId:t,environmentId:r,noWait:n})=>Fe.gen(function*(){let o=[];if(kt.isNone(t))o.push("--project");if(kt.isNone(r))o.push("--env");if(o.length>0)return yield*new ce({message:`Missing required deploy option(s): ${o.join(", ")}.
|
|
1418
|
+
Example: pfcli deploy ${e} --project <project-number> --env <environment-name>`});let i=kt.match(t,{onNone:()=>"",onSome:(a)=>a}),s=kt.match(r,{onNone:()=>"",onSome:(a)=>a});return yield*KQ(e,i,s,{waitForCompletion:!n})}).pipe(Fe.catchTag("CliError",(o)=>Fe.gen(function*(){yield*go.error(`
|
|
1419
|
+
\u274C ${o.message}`),yield*Fe.sync(()=>{process.exitCode=1})})))).pipe(jt("Build org, upload dist artifact, start deploy process, and wait for completion by default")),ANe=qt("destroy",{projectId:oNe,environmentId:iNe,confirmed:sNe,noWait:aNe},({projectId:e,environmentId:t,confirmed:r,noWait:n})=>Fe.gen(function*(){let o=[];if(kt.isNone(e))o.push("--project");if(kt.isNone(t))o.push("--env");if(o.length>0)return yield*new ce({message:`Missing required destroy option(s): ${o.join(", ")}.
|
|
1420
|
+
Example: pfcli destroy --project <project-number> --env <environment-name> --yes`});let i=kt.getOrThrow(e),s=kt.getOrThrow(t);if(!r)return yield*new ce({message:`Confirmation required to destroy project ${i}, environment ${s}. This command deletes the environment's AWS stacks and environment record. Re-run with --yes.`});return yield*QQ(i,s,{waitForCompletion:!n})}).pipe(Fe.catchTag("CliError",(o)=>Fe.gen(function*(){yield*go.error(`
|
|
1421
|
+
\u274C ${o.message}`),yield*Fe.sync(()=>{process.exitCode=1})})))).pipe(jt("Destroy a hosted project environment and wait for completion by default")),INe=qt("rollback",{projectId:eNe,environmentId:tNe,timestamp:rNe,noWait:nNe},({projectId:e,environmentId:t,timestamp:r,noWait:n})=>Fe.gen(function*(){let o=[];if(kt.isNone(e))o.push("--project");if(kt.isNone(t))o.push("--env");if(kt.isNone(r))o.push("--timestamp");if(o.length>0)return yield*new ce({message:`Missing required rollback option(s): ${o.join(", ")}.
|
|
1422
|
+
Example: pfcli db rollback --project <project-number> --env <environment-name> --timestamp 2026-04-01T00:00:00Z
|
|
1423
|
+
Local timezone also supported: --timestamp 2026-04-16T18:00:00`});let i=kt.getOrThrow(e),s=kt.getOrThrow(t),a=$re(kt.getOrThrow(r));return yield*kQ(i,s,a,{waitForCompletion:!n})}).pipe(Fe.catchTag("CliError",(o)=>Fe.gen(function*(){yield*go.error(`
|
|
1424
|
+
\u274C ${o.message}`),yield*Fe.sync(()=>{process.exitCode=1})})))).pipe(jt("Start a database rollback preparation process and wait for completion by default")),RNe=qt("download",{projectId:cNe,environmentId:lNe,outputPath:dNe},({projectId:e,environmentId:t,outputPath:r})=>Fe.gen(function*(){let n=[];if(kt.isNone(e))n.push("--project");if(kt.isNone(t))n.push("--env");if(n.length>0)return yield*new ce({message:`Missing required download option(s): ${n.join(", ")}.
|
|
1425
|
+
Example: pfcli db download --project <project-number> --env <environment-name> [--output ./backup.sqlite]`});return yield*yQ(kt.getOrThrow(e),kt.getOrThrow(t),kt.getOrUndefined(r))}).pipe(Fe.catchTag("CliError",(n)=>Fe.gen(function*(){yield*go.error(`
|
|
1426
|
+
\u274C ${n.message}`),yield*Fe.sync(()=>{process.exitCode=1})})))).pipe(jt("Download a hosted environment database to a local path")),PNe=qt("upload",{projectId:mNe,environmentId:yNe,mode:hNe,sqliteFile:gNe},({projectId:e,environmentId:t,mode:r,sqliteFile:n})=>Fe.gen(function*(){let o=[];if(kt.isNone(e))o.push("--project");if(kt.isNone(t))o.push("--env");if(kt.isNone(n))o.push("<sqlite-file>");if(o.length>0)return yield*new ce({message:`Missing required upload option(s): ${o.join(", ")}.
|
|
1427
|
+
Example: pfcli db upload --project <project-number> --env <environment-name> <sqlite-file>`});return yield*MQ(kt.getOrThrow(e),kt.getOrThrow(t),kt.getOrThrow(n),{mode:r})}).pipe(Fe.catchTag("CliError",(o)=>Fe.gen(function*(){yield*go.error(`
|
|
1428
|
+
\u274C ${o.message}`),yield*Fe.sync(()=>{process.exitCode=1})})))).pipe(jt("Upload and apply a local SQLite database through a signed document-store URL")),CNe=qt("shell",{projectId:uNe,environmentId:pNe,ttl:fNe},({projectId:e,environmentId:t,ttl:r})=>Fe.gen(function*(){let n=[];if(kt.isNone(e))n.push("--project");if(kt.isNone(t))n.push("--env");if(n.length>0)return yield*new ce({message:`Missing required database shell option(s): ${n.join(", ")}.
|
|
1429
|
+
Example: pfcli db shell --project <project-number> --env <environment-name> [--ttl 15m]`});let o=yield*DQ(kt.getOrThrow(e),kt.getOrThrow(t),kt.getOrUndefined(r));yield*Fe.sync(()=>{process.exitCode=o})}).pipe(Fe.catchTag("CliError",(n)=>Fe.gen(function*(){yield*go.error(`
|
|
1430
|
+
\u274C ${n.message}`),yield*Fe.sync(()=>{process.exitCode=1})})))).pipe(jt("Open an interactive Turso shell for a hosted environment database")),_Ne=qt("db",{}).pipe(jt("Database commands"),Wd([INe,RNe,PNe,CNe])),kNe=qt("custom-domain",{projectId:XOe,environmentId:ZOe},({projectId:e,environmentId:t})=>nQ(e,t).pipe(Fe.catchTag("CustomDomainError",(r)=>Fe.gen(function*(){yield*go.error(`
|
|
1431
|
+
\u274C ${r.message}`),yield*Fe.sync(()=>{process.exitCode=1})})))).pipe(jt("Show custom-domain certificate status and required DNS records")),jre=(e,t,r)=>qt(e,{projectId:KOe,environmentId:GOe},({projectId:n,environmentId:o})=>Fe.gen(function*(){let i=[];if(kt.isNone(n))i.push("--project");if(kt.isNone(o))i.push("--env");if(i.length>0)return yield*new ce({message:`Missing required ${e} option(s): ${i.join(", ")}.
|
|
1432
|
+
Example: pfcli ${e} --project <project-number> --env <environment-name>`});return yield*r(kt.getOrThrow(n),kt.getOrThrow(o))}).pipe(Fe.catchTag("CliError",(i)=>Fe.gen(function*(){yield*go.error(`
|
|
1433
|
+
\u274C ${i.message}`),yield*Fe.sync(()=>{process.exitCode=1})})))).pipe(jt(t)),DNe=jre("logs","Show recent primary runtime logs",Are),ONe=jre("canary-logs","Show recent canary runtime logs",Ire),NNe=qt("migrate",{orgPath:Rk},({orgPath:e})=>hk(e).pipe(Fe.catchTag("MigrationError",(t)=>Fe.gen(function*(){if(yield*go.error(`
|
|
1434
|
+
\u274C Migration failed: ${t.reason}`),t.statement)yield*go.error(` Statement: ${t.statement}`);return yield*t})))).pipe(jt("Run system and org schema migrations (uses SQLITE_DATABASE_PATH or $org-path/db/pf.db)")),FNe=qt("migrate-custom",{orgPath:Rk},({orgPath:e})=>yk(e)).pipe(jt("Run custom schema migrations for organisation (uses SQLITE_DATABASE_PATH or $org-path/db/pf.db)")),UNe=qt("init",{orgPath:Pk,providers:SNe,email:vNe},({orgPath:e,providers:t,email:r})=>Sre(e,t,r)).pipe(jt("Initialise a new organisation directory with template files and auth scaffolding")),MNe=qt("get-frontend-jwt",{orgPath:Pk},({orgPath:e})=>Yte(e)).pipe(jt("Output the stored frontend JWT token (created during import)")),LNe=qt("refresh-frontend-jwt",{orgPath:Pk},({orgPath:e})=>Cre(e)).pipe(jt("Regenerate the frontend JWT token with the current issuer URL and signing keys")),pT=fr("project").pipe(At("Project number (or internal ID)")),fT=fr("stage").pipe(At("Stage name")),Hre=ap({name:"key"}).pipe(Nl("Configuration parameter name")),BNe=Ose(ap({name:"assignment"})).pipe(Nl("One of KEY, KEY=VALUE, or KEY VALUE")),$Ne=mp("secret").pipe(Ll(!1),At("Store as a secret (SecureString in SSM)")),qNe=fr("from-stage").pipe(At("Source stage name")),Wre=fr("project").pipe(At("Project number (or internal ID)")),Vre=fr("project").pipe(At("Project number (or internal ID)")),jNe=fr("stage").pipe(At("Stage name")),HNe=fr("stage").pipe(Un,At("Stage name")),WNe=ap({name:"stage-name"}).pipe(Nl("Stage name to create")),VNe=ap({name:"env-name"}).pipe(Nl("Environment name to create")),zNe=qt("list",{projectId:pT,stageId:fT},({projectId:e,stageId:t})=>XG(e,t)).pipe(jt("List all config parameters for a project and stage")),KNe=qt("get",{projectId:pT,stageId:fT,key:Hre},({projectId:e,stageId:t,key:r})=>YG(e,t,r)).pipe(jt("Get a config parameter value")),GNe=qt("set",{projectId:pT,stageId:fT,args:BNe,isSecret:$Ne},({projectId:e,stageId:t,args:r,isSecret:n})=>tQ(e,t,r,n)).pipe(jt("Set a config parameter value")),QNe=qt("delete",{projectId:pT,stageId:fT,key:Hre},({projectId:e,stageId:t,key:r})=>JG(e,t,r)).pipe(jt("Delete a config parameter")),JNe=qt("copy-new",{projectId:pT,stageId:fT,fromStageId:qNe},({projectId:e,stageId:t,fromStageId:r})=>GG(e,t,r)).pipe(jt("Copy only missing config parameters from another stage")),YNe=qt("config",{}).pipe(jt("Manage SSM configuration parameters"),Wd([zNe,KNe,GNe,QNe,JNe])),XNe=qt("add",{projectId:Wre,stageName:WNe},({projectId:e,stageName:t})=>Fre(e,t).pipe(Fe.catchTag("CliError",(r)=>Fe.gen(function*(){yield*go.error(`
|
|
1435
|
+
\u274C ${r.message}`),yield*Fe.sync(()=>{process.exitCode=1})})))).pipe(jt("Add a stage to a project")),ZNe=qt("list",{projectId:Wre},({projectId:e})=>Mre(e).pipe(Fe.catchTag("CliError",(t)=>Fe.gen(function*(){yield*go.error(`
|
|
1436
|
+
\u274C ${t.message}`),yield*Fe.sync(()=>{process.exitCode=1})})))).pipe(jt("List stages in a project")),eFe=qt("stage",{}).pipe(jt("Manage project stages"),Wd([ZNe,XNe])),tFe=qt("add",{projectId:Vre,stageId:jNe,environmentName:VNe},({projectId:e,stageId:t,environmentName:r})=>YQ(e,t,r).pipe(Fe.catchTag("CliError",(n)=>Fe.gen(function*(){yield*go.error(`
|
|
1437
|
+
\u274C ${n.message}`),yield*Fe.sync(()=>{process.exitCode=1})})))).pipe(jt("Add an environment to a stage")),rFe=qt("list",{projectId:Vre,stageId:HNe},({projectId:e,stageId:t})=>ZQ(e,kt.getOrUndefined(t)).pipe(Fe.catchTag("CliError",(r)=>Fe.gen(function*(){yield*go.error(`
|
|
1438
|
+
\u274C ${r.message}`),yield*Fe.sync(()=>{process.exitCode=1})})))).pipe(jt("List environments in a project")),nFe=qt("env",{}).pipe(jt("Manage project environments"),Wd([rFe,tFe])),oFe=qt("login",{},()=>Fe.gen(function*(){let e=yield*uT.string("BASE_URL").pipe(uT.withDefault("https://console.processfocus.com")),t=yield*uT.option(uT.string(iq)),r=kt.getOrUndefined(t);yield*x4(e,r===void 0?{}:{ciProviderUser:r})}).pipe(Fe.catchTag("AuthLoginError",(e)=>Fe.gen(function*(){yield*go.error(`
|
|
1439
|
+
\u274C Login failed: ${e.message}`),yield*Fe.sync(()=>{process.exitCode=1})})))).pipe(jt("Login via browser-based OAuth (uses BASE_URL env var, defaults to https://console.processfocus.com)")),iFe=qt("auth",{}).pipe(jt("Authentication commands"),Wd([oFe])),sFe=qt("list",{},()=>Dre()).pipe(jt("List agent skills served by this pfcli version")),aFe=qt("get",{name:xNe},({name:e})=>Ore(e).pipe(Fe.catchTag("CliError",(t)=>Fe.gen(function*(){yield*go.error(`
|
|
1440
|
+
\u274C ${t.message}`),yield*Fe.sync(()=>{process.exitCode=1})})))).pipe(jt("Print an agent skill for this pfcli version")),cFe=qt("skills",{}).pipe(jt("Agent-oriented runtime skill guidance"),Wd([sFe,aFe])),lFe=fr("role").pipe(At("Role path to grant (e.g. /Administrator)")),dFe=fr("user").pipe(At("Email address of the provider user")),uFe=fr("project").pipe(Un,At("Project number or internal ID (remote mode)")),pFe=fr("env").pipe(Un,At("Environment name (remote mode)")),fFe=ap({name:"org-path"}).pipe(l0,Nl("Path to the organisation directory (local mode only)")),mFe=qt("role",{role:lFe,user:dFe,projectId:uFe,environmentId:pFe,orgPath:fFe},({role:e,user:t,projectId:r,environmentId:n,orgPath:o})=>{let i={orgPath:kt.getOrUndefined(o),rolePath:e,email:t,projectId:kt.getOrUndefined(r),environmentId:kt.getOrUndefined(n)};return tre(i)}).pipe(jt("Grant a role to a provider user locally or in a remote customer environment")),yFe=qt("grant",{}).pipe(jt("Grant operations"),Wd([mFe])),zre="project",Kre="env",Gre="email",hFe=fr(zre).pipe(Un,At("Project number or internal ID (remote mode)")),gFe=fr(Kre).pipe(Un,At("Environment name (remote mode)")),SFe=fr(Gre).pipe(Un,At("Normalized Email of the Invitation or existing account")),vFe=mp("rotate").pipe(Ll(!1),At("Replace an active or expired Registration Link, or issue an existing account's Passkey Recovery Link")),xFe=ap({name:"org-path"}).pipe(l0,Nl("Path to the organisation directory (local mode only)")),EFe=qt("registration-link",{projectId:hFe,environmentId:gFe,email:SFe,rotate:vFe,orgPath:xFe},({projectId:e,environmentId:t,email:r,rotate:n,orgPath:o})=>wre({orgPath:kt.getOrUndefined(o),projectId:kt.getOrUndefined(e),environmentId:kt.getOrUndefined(t),email:kt.getOrUndefined(r),rotate:n})).pipe(jt("Issue a Registration Link or, with --rotate, recover an existing account locally or remotely")),bFe=qt("invitation",{}).pipe(jt("Invitation operations"),Wd([EFe])),wFe=qt("pfcli",{}).pipe(jt("Process Focus CLI Tool"),Wd([UNe,ENe,bNe,wNe,TNe,ANe,DNe,ONe,_Ne,kNe,NNe,FNe,MNe,LNe,YNe,eFe,nFe,iFe,cFe,yFe,bFe])),TFe=Fae(wFe,{name:"pfcli",version:aR}),qre=(e)=>{if(typeof e!=="string"||!e.includes("COMMANDS"))return e;let t=!1;return e.split(`
|
|
1441
|
+
`).map((r)=>{if(r.includes("COMMANDS"))return t=!0,r;if(t)return r.replace(/^(\s*)- /,"$1");return r}).join(`
|
|
1442
|
+
`)},AFe=()=>{let{log:e,error:t}=console;return console.log=(...r)=>e(...r.map((n)=>qre(n))),console.error=(...r)=>t(...r.map((n)=>qre(n))),()=>{console.log=e,console.error=t}},IFe=(e)=>{let t=e.slice(2);if(t[0]!=="config")return;let r=t[1];if(r!==void 0&&!r.startsWith("-"))return;console.error("Missing config subcommand. Use one of: list, get, set, delete, copy-new"),console.error("Examples:"),console.error(' pfcli config list --project 0000-0000-0002 --stage "Development"'),console.error(' pfcli config set --project 0000-0000-0002 --stage "Development" GOOGLE_CLIENT_ID="$GOOGLE_CLIENT_ID"'),console.error(' pfcli config copy-new --project 0000-0000-0002 --stage "Production" --from-stage "Development"')},Qre=[`--${zre}`,`--${Kre}`,`--${Gre}`],RFe=(e)=>{for(let t=0;t<e.length;t++){let r=e[t];if(r!==void 0&&Qre.includes(r)){let n=e[t+1];if(n===void 0||n.startsWith("-"))return r;t++}}return},PFe=(e)=>{for(let t=0;t<e.length;t++){let r=e[t];if(r===void 0)continue;if(Qre.includes(r)){t++;continue}if(!r.startsWith("-"))return t}return},CFe=(e)=>{if(e[2]!=="invitation"||e[3]!=="registration-link")return{ok:!0,argv:[...e]};let n=e.slice(4),o=RFe(n);if(o!==void 0)return{ok:!1,error:`${o} requires a value.`};let i=PFe(n);if(i===void 0)return{ok:!0,argv:[...e]};let s=n[i];if(s===void 0)return{ok:!0,argv:[...e]};return{ok:!0,argv:[...e.slice(0,4),...n.slice(0,i),...n.slice(i+1),s]}},_Fe=(e)=>Fe.scoped(Fe.acquireRelease(Fe.sync(AFe),(t)=>Fe.sync(t)).pipe(Fe.flatMap(()=>Fe.gen(function*(){let t=Lre(e);if(t.error){yield*go.error(`
|
|
1443
|
+
\u274C ${t.error}`),yield*Fe.sync(()=>{process.exitCode=1});return}if(t.providerUser!==void 0)process.env[iq]=t.providerUser;let r=CFe(t.argv);if(!r.ok){yield*go.error(`
|
|
1444
|
+
\u274C ${r.error}`),yield*Fe.sync(()=>{process.exitCode=1});return}yield*TFe(r.argv)}).pipe(Fe.catchIf(yae,(t)=>Fe.sync(()=>{if(!mW(t))IFe(e);process.exitCode=mW(t)?0:1}))))));if(import.meta.main)_Fe(process.argv).pipe(Fe.provide(Zce),sle);export{_Fe as runPfcliCommand};
|