@powerhousedao/connect 5.1.0-dev.9 → 5.1.0-staging.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/dist/assets/{AddDriveModal-sL0hSfwK.js → AddDriveModal-CGnuKCkz.js} +1 -1
- package/dist/assets/ClearStorageModal-tHn6sdVv.js +1 -0
- package/dist/assets/{CookiesPolicyModal-8Ea1bpuS.js → CookiesPolicyModal-D5y1O9wD.js} +1 -1
- package/dist/assets/CreateDocumentModal-DU4C2Y6P.js +1 -0
- package/dist/assets/{DebugSettingsModal-BN0vka2j.js → DebugSettingsModal-BLV4d9N1.js} +1 -1
- package/dist/assets/{DeleteDriveModal-BkMiD-at.js → DeleteDriveModal-CQq-0aWd.js} +1 -1
- package/dist/assets/DeleteItemModal-JV0AvuwF.js +1 -0
- package/dist/assets/DisclaimerModal-DQZyl_zf.js +1 -0
- package/dist/assets/DriveSettingsModal-yXsOiCLy.js +1 -0
- package/dist/assets/{ExportDocumentWithErrorsModal--MRX9RA5.js → ExportDocumentWithErrorsModal-CPfizBgB.js} +1 -1
- package/dist/assets/SettingsModal-GeNqOEFN.js +1 -0
- package/dist/assets/{UpgradeDriveModal-RsikHBVp.js → UpgradeDriveModal-BCRmp5F4.js} +1 -1
- package/dist/assets/{design_system-BtrDHANm.js → design_system-pnKFY6jM.js} +1 -1
- package/dist/assets/design_system_connect-BrlN-7x3.js +104 -0
- package/dist/assets/{design_system_ui-CXZVaXzt.js → design_system_ui-Cz-kMJRJ.js} +1 -1
- package/dist/assets/{document_drive-N2jFG7-p.js → document_drive-CVkeqJ3l.js} +1 -1
- package/dist/assets/{document_engineering-CZ8g9riq.js → document_engineering-BAszqzBd.js} +1 -1
- package/dist/assets/{document_model_editor-C2QDzIWG.js → document_model_editor-D5oPro82.js} +4 -4
- package/dist/assets/{drive_explorer-DHMI_z5h.js → drive_explorer-C6clT2Df.js} +2 -2
- package/dist/assets/{graphql-editor-B_sLuXTF.js → graphql-editor-C6f63OmN.js} +1 -1
- package/dist/assets/{hooks-CrcQ2Zxj.js → hooks-BySGfjQp.js} +1 -1
- package/dist/assets/index-BYfBva47.js +20 -0
- package/dist/assets/index-XUlAOLkX.css +1 -0
- package/dist/assets/{json-editor-xWjFAcl1.js → json-editor-D27WLv4C.js} +1 -1
- package/dist/assets/nodefs-AYr2EwM_.js +1 -0
- package/dist/assets/opfs-ahp-rEGVoJkP.js +3 -0
- package/dist/assets/reactor_browser-D4maXKS-.js +25 -0
- package/dist/assets/state-schemas-DGMOULa-.js +2 -0
- package/dist/index.html +9 -9
- package/lib/package.copy.json +1 -1
- package/lib/src/feature-flags.d.ts +17 -3
- package/lib/src/feature-flags.d.ts.map +1 -1
- package/lib/src/feature-flags.js +32 -3
- package/lib/src/feature-flags.js.map +1 -1
- package/lib/src/store/reactor.d.ts.map +1 -1
- package/lib/src/store/reactor.js +5 -5
- package/lib/src/store/reactor.js.map +1 -1
- package/lib/tsconfig.tsbuildinfo +1 -1
- package/nginx.conf +7 -0
- package/package.copy.json +1 -1
- package/package.json +10 -10
- package/dist/assets/ClearStorageModal-taO2ME0w.js +0 -1
- package/dist/assets/CreateDocumentModal-CSVg8ZHf.js +0 -1
- package/dist/assets/DeleteItemModal-DYfBVcdK.js +0 -1
- package/dist/assets/DisclaimerModal-orJjo4Cr.js +0 -1
- package/dist/assets/DriveSettingsModal-DghD5DLg.js +0 -1
- package/dist/assets/SettingsModal-DyKVA0Ca.js +0 -1
- package/dist/assets/design_system_connect-CDNGzuLc.js +0 -45
- package/dist/assets/index-Br7E7qjt.css +0 -1
- package/dist/assets/index-DCLcMalw.js +0 -78
- package/dist/assets/nodefs-DTI9wPNC.js +0 -1
- package/dist/assets/opfs-ahp-gTaseGJ8.js +0 -3
- package/dist/assets/reactor_browser-h6aSTneX.js +0 -25
- package/dist/assets/state-schemas-DRj4Gqo5.js +0 -2
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import{l as ie,d as Xl,a as eh,i as Ti,b as th,c as nh,g as rh,h as ih,e as sh,m as oh,u as ah,s as ch,f as dh,j as uh,r as lh,P as hh,k as fh,S as ph,D as mh,n as bh}from"./document_drive-N2jFG7-p.js";import{Y as wh,Z as yh,d as gh,_ as Nh,g as kt,k as Ii,w as xh,e as vh,$ as Eh,a0 as Dh,a1 as kh,a2 as Sh,j as Ah,h as Oh}from"./document_model-LXEZCDPq.js";import"./document_model_editor-C2QDzIWG.js";import{r as jt}from"./sentry_react-cODD7zWc.js";import{g as Zs,a as Ri}from"./react-DQSxOgtG.js";async function Je(t,e){if(!e){ie.error("No actions found");return}const n=Array.isArray(e)?e:[e];if(n.length===0){ie.error("No actions found");return}const r=window.ph?.legacyReactor;if(!r)return;if(!t){ie.error("No document found");return}const i=await r.queueActions(t.header.id,n);return i.status!=="SUCCESS"&&ie.error(i.error),i.document}async function Kc(t,e){if(!e){ie.error("No operations found");return}const n=Array.isArray(e)?e:[e],r=window.ph?.legacyReactor;if(!r)return;const i=await r.queueOperations(t,n);return i.status!=="SUCCESS"&&ie.error(i.error),i.document}async function zc(t,e,n,r){const i=r?.operationsLimit||50,s=r?.onProgress;ie.verbose(`uploadDocumentOperations(documentId:${t}, ops: ${Object.keys(e).join(",")}, limit:${i})`);const o=Object.values(e).filter(u=>u!==void 0),a=o.reduce((u,h)=>u+h.length,0);let c=0;for(const u of o)for(let h=0;h<u.length;h+=i){ie.verbose(`uploadDocumentOperations:for(i:${h}, ops:${u.length}, limit:${i}): START`);const f=u.slice(h,h+i),l=f.at(-1);if(!l)break;const m=l.action.scope;if(await n(t,f),c+=f.length,s){const p=Math.round(c/a*100);s({stage:"uploading",progress:p,totalOperations:a,uploadedOperations:c})}ie.verbose(`uploadDocumentOperations:for:waitForUpdate(${t}:${m} rev ${l.index}): NEXT`)}ie.verbose(`uploadDocumentOperations:for:waitForUpdate(${t}): END`)}async function Ch(t,e){const n=window.ph?.legacyReactor;if(!n)return t;const i=n.getDocumentModelModules().find(h=>h.documentModel.global.id===e.header.documentType);if(!i)return ie.error(`Document model '${e.header.documentType}' not found`),t;const s=i.reducer,o=window.ph?.user,a=window.ph?.connectCrypto;if(!o||!a||!t.context?.signer)return t;const c=t.context.signer;return await wh(t,s,e,c,a.sign)}function Th(t){const e=window.ph?.user,n=window.ph?.did;return e?{context:{signer:{app:{name:"Connect",key:n||""},user:{address:e.address,networkId:e.networkId,chainId:e.chainId},signatures:[]}},...t}:t}async function Ih(t,e){if(!t){ie.error("No action found");return}if(!e){ie.error("No document found");return}const n=await Ch(t,e);return Th(n)}async function Rh(t,e){if(!t){ie.error("No actions found");return}const n=Array.isArray(t)?t:[t];return(await Promise.all(n.map(i=>Ih(i,e)))).filter(i=>i!==void 0)}async function Wh(t){try{return await window.ph?.legacyReactor?.getDocument(t)}catch(e){ie.debug(`Failed to get document with id ${t}:`,e);return}}async function Mh(t,e){const n=typeof e=="string"?await Wh(e):e;if(!n){ie.error(`Document with id ${JSON.stringify(e)} not found`);return}const r=await Rh(t,n);if(!r){ie.error("No signed actions with context found");return}return await Je(n,r)}class na extends Error{constructor(e){super(`Document type ${e} is not supported`),this.name="UnsupportedDocumentTypeError"}}class Ph extends Error{constructor(e,n,r){super(`Document ${e} is not of type ${n}. Actual type: ${r}`)}}class $h extends Error{constructor(){super("There is no selected document. Call 'setSelectedNode' to select a document.")}}function Lh(t,e){return e?.length?e.some(n=>{if(n.endsWith("/*")){const r=n.slice(0,-2);return t.startsWith(r+"/")}if(n.endsWith("*")&&!n.endsWith("/*")){const r=n.slice(0,-1);return t.startsWith(r)}return n===t}):!0}function qe(){const t=window.ph?.user,e=window.ph?.allowList;return e?{isAllowedToCreateDocuments:e.includes(t?.address??""),isAllowedToEditDocuments:e.includes(t?.address??"")}:{isAllowedToCreateDocuments:!0,isAllowedToEditDocuments:!0}}async function Bh(t,e,n){const r=window.ph?.legacyReactor;if(!r)return{isDuplicate:!1};try{const i=await r.getDrive(e),s=i.state.global.nodes.find(a=>a.id===t.header.id);if(s&&s.parentFolder===(n??null))return{isDuplicate:!0,duplicateType:"id",nodeId:s.id};const o=i.state.global.nodes.find(a=>Ti(a)&&a.name===t.header.name&&a.documentType===t.header.documentType&&a.parentFolder===(n??null));return o?{isDuplicate:!0,duplicateType:"name",nodeId:o.id}:{isDuplicate:!1}}catch{return{isDuplicate:!1}}}function Uh(t){switch(t.header.documentType){case"powerhouse/document-model":return"document-model";case"powerhouse/app":return"app";case"powerhouse/document-editor":return"editor";case"powerhouse/subgraph":return"subgraph";case"powerhouse/package":return"package";case"powerhouse/processor":{const r=t.state.global?.type;return r==="analytics"?"analytics-processor":r==="relational"?"relational-processor":r==="codegen"?"codegen-processor":void 0}default:return}}function qh(t,e){Nh(t).generateAsync({type:"blob"}).then(r=>{const i=window.document.createElement("a");i.style.display="none",i.href=URL.createObjectURL(r),i.download=e,window.document.body.appendChild(i),i.click(),window.document.body.removeChild(i)}).catch(ie.error)}async function Fh(t,e){if(!window.ph?.legacyReactor)return;let r="";if(t.header.documentType===yh){const o=t.state.global.extension.replace(/^\.+|\.+$/g,"");r=o!==""?`.${o}`:""}const i=`${t.header.name||"Untitled"}${r}.phd`;if(!window.showSaveFilePicker)return qh(t,i);try{const s=await window.showSaveFilePicker({suggestedName:i});return await gh(t,s),s}catch(s){if(!(s instanceof DOMException&&s.name==="AbortError"))throw s}}async function Jc(t){const e=window.ph?.legacyReactor;if(!e)return;const n=e.getDocumentModelModules(),r=await vh(t,s=>s,{checkHashes:!0}),i=n.find(s=>s.documentModel.global.id===r.header.documentType);if(!i)throw new Error(`Document "${r.header.documentType}" is not supported`);return i.utils.loadFromInput(t)}async function Gc(t,e,n,r,i,s,o){const a=window.ph?.legacyReactor;if(!a)return;const{isAllowedToCreateDocuments:c}=qe();if(!c)throw new Error("User is not allowed to create documents");const u=await a.getDrive(t),h=s??kt(),l=a.getDocumentModelModules().find(g=>g.documentModel.global.id===n);if(!l)throw new Error(`Document model module for type ${n} not found`);const m=l.utils.createDocument({...i?.state});m.header=Ii(h,n),m.header.name=e;const p=o?{preferredEditor:o}:void 0;await a.addDocument(m,p);const b=eh({id:h,name:e,documentType:n,parentFolder:r??null}),w=(await Je(u,b)).state.global.nodes.find(g=>g.id===h);if(!w||!Ti(w))throw new Error("There was an error adding document");return w}async function Vh(t,e,n,r){ie.verbose(`addFile(drive: ${e}, name: ${n}, folder: ${r})`);const i=window.ph?.legacyReactor;if(!i)return;const{isAllowedToCreateDocuments:s}=qe();if(!s)throw new Error("User is not allowed to create files");const o=await Jc(t);if(!o)throw new Error("No document loaded");if(!i.getDocumentModelModules().find(m=>m.documentModel.global.id===o.header.documentType))throw new Error(`Document model module for type ${o.header.documentType} not found`);let c=!1;try{await i.getDocument(o.header.id),c=!0}catch{}const u=c?kt():o.header.id,h=Ii(u,o.header.documentType);h.lastModifiedAtUtcIso=o.header.createdAtUtcIso,h.meta=o.header.meta,h.name=n||o.header.name;const f={...o,state:o.initialState,operations:Object.keys(o.operations).reduce((m,p)=>(m[p]=[],m),{})};if(!await Gc(e,n||o.header.name,o.header.documentType,r,f,u,o.header.meta?.preferredEditor))throw new Error("There was an error adding file");zc(u,o.operations,Kc).catch(m=>{throw m})}async function _h(t,e,n,r,i,s,o){ie.verbose(`addFileWithProgress(drive: ${e}, name: ${n}, folder: ${r})`);const a=window.ph?.legacyReactor;if(!a)return;const{isAllowedToCreateDocuments:c}=qe();if(!c)throw new Error("User is not allowed to create files");try{i?.({stage:"loading",progress:0});const u=await Jc(t);if(!u)throw new Error("No document loaded");const h=await Bh(u,e,r);if(h.isDuplicate&&!o){i?.({stage:"conflict",progress:0,duplicateType:h.duplicateType});return}h.isDuplicate&&o==="replace"&&h.nodeId&&await Hh(e,h.nodeId);const f=Uh(u);if(i?.(f?{stage:"loading",progress:10,documentType:f}:{stage:"loading",progress:10}),!Lh(u.header.documentType,s))throw i?.({stage:"unsupported-document-type",progress:100,error:`Document type ${u.header.documentType} is not supported`}),new na(u.header.documentType);if(!a.getDocumentModelModules().find(g=>g.documentModel.global.id===u.header.documentType))throw new Error(`Document model module for type ${u.header.documentType} not found`);i?.({stage:"initializing",progress:10});let m=!1;try{await a.getDocument(u.header.id),m=!0}catch{}const p=m?kt():u.header.id,b=Ii(p,u.header.documentType);b.lastModifiedAtUtcIso=u.header.createdAtUtcIso,b.meta=u.header.meta,b.name=n||u.header.name;const v={...u,header:b,state:u.initialState,operations:Object.keys(u.operations).reduce((g,y)=>(g[y]=[],g),{})},w=await Gc(e,n||u.header.name,u.header.documentType,r,v,p,u.header.meta?.preferredEditor);if(!w)throw new Error("There was an error adding file");return i?.({stage:"initializing",progress:20}),await zc(p,u.operations,Kc,{onProgress:g=>{if(g.totalOperations&&g.uploadedOperations!==void 0){const y=g.totalOperations>0?g.uploadedOperations/g.totalOperations:0,k=20+Math.round(y*80);i?.({stage:"uploading",progress:k,totalOperations:g.totalOperations,uploadedOperations:g.uploadedOperations})}}}),i?.({stage:"complete",progress:100}),w}catch(u){if(!(u instanceof na)){const h=u instanceof Error?u.message:"Unknown error occurred";i?.({stage:"failed",progress:100,error:h})}throw u}}async function jh(t,e,n){const r=window.ph?.legacyReactor;if(!r)return;const{isAllowedToCreateDocuments:i}=qe();if(!i)throw new Error("User is not allowed to create folders");const s=kt(),o=await r.getDrive(t),c=(await Je(o,th({id:s,name:e,parentFolder:n}))).state.global.nodes.find(u=>u.id===s);if(!c||!nh(c))throw new Error("There was an error adding folder");return c}async function Hh(t,e){const n=window.ph?.legacyReactor;if(!n)return;const{isAllowedToCreateDocuments:r}=qe();if(!r)throw new Error("User is not allowed to delete documents");const i=await n.getDrive(t);await Je(i,Xl({id:e}))}async function Kh(t,e,n){const r=window.ph?.legacyReactor;if(!r)return;const{isAllowedToCreateDocuments:i}=qe();if(!i)throw new Error("User is not allowed to rename documents");const s=await r.getDrive(t),a=(await Je(s,ah({id:e,name:n}))).state.global.nodes.find(c=>c.id===e);if(!a)throw new Error("There was an error renaming node");return a}async function zh(t,e,n){const r=window.ph?.legacyReactor;if(!r)return;const{isAllowedToCreateDocuments:i}=qe();if(!i)throw new Error("User is not allowed to move documents");const s=await r.getDrive(t);return await Je(s,oh({srcFolder:e.id,targetParentFolder:n?.id}))}function Jh(t,e,n=kt()){const r=t.getDocumentModelModules().find(i=>i.documentModel.global.id===e.header.documentType);if(!r)throw new Error(`Document model module for type ${e.header.documentType} not found`);return xh(e.initialState,e.operations,r.reducer,void 0,Ii(n,e.header.documentType))}async function ra(t,e,n){const r=window.ph?.legacyReactor;if(!r)return;const{isAllowedToCreateDocuments:i}=qe();if(!i)throw new Error("User is not allowed to copy documents");const s=await r.getDrive(t),o=rh({srcId:e.id,targetParentFolder:n?.id,targetName:e.name},()=>kt(),s.state.global.nodes),a=new Map;for(const h of o){const f=s.state.global.nodes.find(l=>l.id===h.srcId);if(f){const l=ih({nodes:s.state.global.nodes,srcName:h.targetName||f.name,targetParentFolder:h.targetParentFolder||null});a.set(h.targetId,l)}}const c=o.filter(h=>{const f=s.state.global.nodes.find(l=>l.id===h.srcId);return f!==void 0&&Ti(f)});for(const h of c)try{const f=await r.getDocument(h.srcId),l=Jh(r,f,h.targetId),m=a.get(h.targetId);m&&(l.header.name=m),await r.addDocument(l)}catch(f){ie.error(`Error copying document ${h.srcId}: ${String(f)}`)}const u=o.map(h=>sh(h));return await Je(s,u)}async function p1(t,e){const n=window.ph?.legacyReactor;if(!n)return;const{isAllowedToCreateDocuments:r}=qe();if(!r)throw new Error("User is not allowed to create drives");const i=kt();return await n.addDrive({global:t.global,local:t.local,id:i},e)}async function m1(t,e){const n=window.ph?.legacyReactor;return n?await n.addRemoteDrive(t,e):void 0}async function b1(t){const e=window.ph?.legacyReactor;if(!e)return;const{isAllowedToCreateDocuments:n}=qe();if(!n)throw new Error("User is not allowed to delete drives");await e.deleteDrive(t)}async function w1(t,e){const n=window.ph?.legacyReactor;if(!n)return;const{isAllowedToCreateDocuments:r}=qe();if(!r)throw new Error("User is not allowed to rename drives");const i=await n.getDrive(t);return await Je(i,uh({name:e}))}async function y1(t,e){const n=window.ph?.legacyReactor;if(!n)return;const{isAllowedToCreateDocuments:r}=qe();if(!r)throw new Error("User is not allowed to change drive availability");const i=await n.getDrive(t);return await Je(i,dh({availableOffline:e}))}async function g1(t,e){const n=window.ph?.legacyReactor;if(!n)return;const{isAllowedToCreateDocuments:r}=qe();if(!r)throw new Error("User is not allowed to change drive availability");const i=await n.getDrive(t);return await Je(i,ch({type:e}))}async function N1(t,e){const n=window.ph?.legacyReactor;if(!n)return;const r=await n.getDrive(t);if((await Je(r,lh({triggerId:e}))).state.local.triggers.find(o=>o.id===e))throw new Error(`There was an error removing trigger ${e}`)}async function x1(t,e,n){const r=window.ph?.legacyReactor;if(!r)return;const i=kt(),s={driveId:t,listenerId:i,block:!1,filter:{branch:n.pullFilter?.branch??[],documentId:n.pullFilter?.documentId??[],documentType:n.pullFilter?.documentType??[],scope:n.pullFilter?.scope??[]},system:!1,label:`Pullresponder #${i}`,callInfo:{data:"",name:"PullResponder",transmitterType:"PullResponder"}},o=r.listeners;s.transmitter=new hh(s,o);try{await o.setListener(t,s)}catch(a){throw new Error(`Listener couldn't be registered: ${a}`)}return{driveId:t,filter:s.filter,data:{interval:`${n.pullInterval}`||"1000",listenerId:i,url:e},id:i,type:"PullResponder"}}async function v1(t,e){const n=window.ph?.legacyReactor;if(!n)return;const r=await n.getDrive(t);if(!(await Je(r,fh({trigger:e}))).state.local.triggers.find(o=>o.id===o.id))throw new Error(`There was an error adding the trigger ${e.id}`)}const Gh="powerhouse/generic-drive-explorer",E1="powerhouse/common";function R(t){const e=`ph:set${Eh(t)}`,n=`ph:${t}Updated`;function r(h){const f=new CustomEvent(e,{detail:{[t]:h}});window.dispatchEvent(f)}function i(){const h=new CustomEvent(n);window.dispatchEvent(h)}function s(h){const f=h.detail[t];if(!window.ph)throw new Error("ph global store is not defined");window.ph[t]=f,i()}function o(){window.addEventListener(e,s)}function a(h){return window.addEventListener(n,h),()=>{window.removeEventListener(n,h)}}function c(){if(!window.ph)throw new Error("ph global store is not defined");return window.ph[t]}function u(){return jt.useSyncExternalStore(a,c)}return{useValue:u,setValue:r,addEventHandler:o}}const Zc=R("isExternalControlsEnabled"),Zh=Zc.setValue,Yh=Zc.addEventHandler,Ys=R("isDragAndDropEnabled"),Qh=Ys.setValue,D1=Ys.useValue,Xh=Ys.addEventHandler,Qs=R("allowedDocumentTypes"),ef=Qs.setValue;function tf(){return Qs.useValue()}const nf=Qs.addEventHandler,rf={allowedDocumentTypes:ef,isDragAndDropEnabled:Qh},sf={isExternalControlsEnabled:Zh},Xs=R("vetraPackages"),eo=Xs.useValue,of=Xs.addEventHandler;function k1(t){Xs.setValue(t);const e=t?.flatMap(n=>n.modules.documentModelModules).filter(n=>n!==void 0);window.ph?.legacyReactor?.setDocumentModelModules(e)}function Yc(){return eo()?.flatMap(e=>e.modules.documentModelModules||[])}function af(t){return Yc()?.find(n=>n.id===t)}function ia(t){return t.toSorted((e,n)=>e.name.localeCompare(n.name))}function S1(t){return t?t.kind.toUpperCase()==="FILE":!1}function Qc(t){return t?t.kind.toUpperCase()==="FOLDER":!1}function to(t){function e(n){Mh(n,t).catch(ie.error)}return[t,e]}function no(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Xc(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?no(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function ed(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const n=Xc(e);let r=0;for(const i of t)n.set(i,r),r+=i.length;return no(n)}const cf=Object.freeze(Object.defineProperty({__proto__:null,concat:ed},Symbol.toStringTag,{value:"Module"}));function df(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var b=0,v=0,w=0,g=p.length;w!==g&&p[w]===0;)w++,b++;for(var y=(g-w)*h+1>>>0,k=new Uint8Array(y);w!==g;){for(var x=p[w],N=0,A=y-1;(x!==0||N<v)&&A!==-1;A--,N++)x+=256*k[A]>>>0,k[A]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");v=N,w++}for(var S=y-v;S!==y&&k[S]===0;)S++;for(var O=c.repeat(b);S<y;++S)O+=t.charAt(k[S]);return O}function l(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var b=0;if(p[b]!==" "){for(var v=0,w=0;p[b]===c;)v++,b++;for(var g=(p.length-b)*u+1>>>0,y=new Uint8Array(g);p[b];){var k=n[p.charCodeAt(b)];if(k===255)return;for(var x=0,N=g-1;(k!==0||x<w)&&N!==-1;N--,x++)k+=a*y[N]>>>0,y[N]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");w=x,b++}if(p[b]!==" "){for(var A=g-w;A!==g&&y[A]===0;)A++;for(var S=new Uint8Array(v+(g-A)),O=v;A!==g;)S[O++]=y[A++];return S}}}function m(p){var b=l(p);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:l,decode:m}}var uf=df,lf=uf;const td=new Uint8Array(0),hf=t=>t.reduce((e,n)=>e+n.toString(16).padStart(2,"0"),""),ff=t=>{const e=t.match(/../g);return e?new Uint8Array(e.map(n=>parseInt(n,16))):td},nd=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let n=0;n<t.byteLength;n++)if(t[n]!==e[n])return!1;return!0},hn=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},pf=t=>t instanceof ArrayBuffer||ArrayBuffer.isView(t),rd=t=>new TextEncoder().encode(t),id=t=>new TextDecoder().decode(t),mf=Object.freeze(Object.defineProperty({__proto__:null,coerce:hn,empty:td,equals:nd,fromHex:ff,fromString:rd,isBinary:pf,toHex:hf,toString:id},Symbol.toStringTag,{value:"Module"}));let bf=class{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},wf=class{constructor(e,n,r){if(this.name=e,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return sd(this,e)}},yf=class{constructor(e){this.decoders=e}or(e){return sd(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const sd=(t,e)=>new yf({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});let gf=class{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new bf(e,n,r),this.decoder=new wf(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const Wi=({name:t,prefix:e,encode:n,decode:r})=>new gf(t,e,n,r),Sr=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=lf(n,e);return Wi({prefix:t,name:e,encode:r,decode:s=>hn(i(s))})},Nf=(t,e,n,r)=>{const i={};for(let h=0;h<e.length;++h)i[e[h]]=h;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,u=0;for(let h=0;h<s;++h){const f=i[t[h]];if(f===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|f,a+=n,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},xf=(t,e,n)=>{const r=e[e.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,s+=e[i&a>>o];if(o&&(s+=e[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},ge=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>Wi({prefix:e,name:t,encode(i){return xf(i,r,n)},decode(i){return Nf(i,r,n,t)}}),vf=Wi({prefix:"\0",name:"identity",encode:t=>id(t),decode:t=>rd(t)}),Ef=Object.freeze(Object.defineProperty({__proto__:null,identity:vf},Symbol.toStringTag,{value:"Module"})),Df=ge({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),kf=Object.freeze(Object.defineProperty({__proto__:null,base2:Df},Symbol.toStringTag,{value:"Module"})),Sf=ge({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Af=Object.freeze(Object.defineProperty({__proto__:null,base8:Sf},Symbol.toStringTag,{value:"Module"})),Of=Sr({prefix:"9",name:"base10",alphabet:"0123456789"}),Cf=Object.freeze(Object.defineProperty({__proto__:null,base10:Of},Symbol.toStringTag,{value:"Module"})),Tf=ge({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),If=ge({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Rf=Object.freeze(Object.defineProperty({__proto__:null,base16:Tf,base16upper:If},Symbol.toStringTag,{value:"Module"})),Zn=ge({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Wf=ge({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Mf=ge({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Pf=ge({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),$f=ge({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Lf=ge({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Bf=ge({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Uf=ge({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),qf=ge({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Ff=Object.freeze(Object.defineProperty({__proto__:null,base32:Zn,base32hex:$f,base32hexpad:Bf,base32hexpadupper:Uf,base32hexupper:Lf,base32pad:Mf,base32padupper:Pf,base32upper:Wf,base32z:qf},Symbol.toStringTag,{value:"Module"})),Vf=Sr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),_f=Sr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),jf=Object.freeze(Object.defineProperty({__proto__:null,base36:Vf,base36upper:_f},Symbol.toStringTag,{value:"Module"})),tt=Sr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Hf=Sr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Kf=Object.freeze(Object.defineProperty({__proto__:null,base58btc:tt,base58flickr:Hf},Symbol.toStringTag,{value:"Module"})),zf=ge({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Jf=ge({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Gf=ge({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Zf=ge({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Yf=Object.freeze(Object.defineProperty({__proto__:null,base64:zf,base64pad:Jf,base64url:Gf,base64urlpad:Zf},Symbol.toStringTag,{value:"Module"})),od=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Qf=od.reduce((t,e,n)=>(t[n]=e,t),[]),Xf=od.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function ep(t){return t.reduce((e,n)=>(e+=Qf[n],e),"")}function tp(t){const e=[];for(const n of t){const r=Xf[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const np=Wi({prefix:"🚀",name:"base256emoji",encode:ep,decode:tp}),rp=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:np},Symbol.toStringTag,{value:"Module"}));var ip=ad,sa=128,sp=-128,op=Math.pow(2,31);function ad(t,e,n){e=e||[],n=n||0;for(var r=n;t>=op;)e[n++]=t&255|sa,t/=128;for(;t&sp;)e[n++]=t&255|sa,t>>>=7;return e[n]=t|0,ad.bytes=n-r+1,e}var ap=Is,cp=128,oa=127;function Is(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw Is.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&oa)<<i:(o&oa)*Math.pow(2,i),i+=7}while(o>=cp);return Is.bytes=s-r,n}var dp=Math.pow(2,7),up=Math.pow(2,14),lp=Math.pow(2,21),hp=Math.pow(2,28),fp=Math.pow(2,35),pp=Math.pow(2,42),mp=Math.pow(2,49),bp=Math.pow(2,56),wp=Math.pow(2,63),yp=function(t){return t<dp?1:t<up?2:t<lp?3:t<hp?4:t<fp?5:t<pp?6:t<mp?7:t<bp?8:t<wp?9:10},gp={encode:ip,decode:ap,encodingLength:yp},ci=gp;const ur=(t,e=0)=>[ci.decode(t,e),ci.decode.bytes],lr=(t,e,n=0)=>(ci.encode(t,e,n),e),hr=t=>ci.encodingLength(t),Np=Object.freeze(Object.defineProperty({__proto__:null,decode:ur,encodeTo:lr,encodingLength:hr},Symbol.toStringTag,{value:"Module"})),fr=(t,e)=>{const n=e.byteLength,r=hr(t),i=r+hr(n),s=new Uint8Array(i+n);return lr(t,s,0),lr(n,s,r),s.set(e,i),new Mi(t,n,e,s)},cd=t=>{const e=hn(t),[n,r]=ur(e),[i,s]=ur(e.subarray(r)),o=e.subarray(r+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new Mi(n,i,o,e)},dd=(t,e)=>t===e?!0:t.code===e.code&&t.size===e.size&&nd(t.bytes,e.bytes);class Mi{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const xp=Object.freeze(Object.defineProperty({__proto__:null,Digest:Mi,create:fr,decode:cd,equals:dd},Symbol.toStringTag,{value:"Module"})),ro=({name:t,code:e,encode:n})=>new ud(t,e,n);class ud{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?fr(this.code,n):n.then(r=>fr(this.code,r))}else throw Error("Unknown type, must be binary type")}}const vp=Object.freeze(Object.defineProperty({__proto__:null,Hasher:ud,from:ro},Symbol.toStringTag,{value:"Module"})),ld=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Ep=ro({name:"sha2-256",code:18,encode:ld("SHA-256")}),Dp=ro({name:"sha2-512",code:19,encode:ld("SHA-512")}),kp=Object.freeze(Object.defineProperty({__proto__:null,sha256:Ep,sha512:Dp},Symbol.toStringTag,{value:"Module"})),hd=0,Sp="identity",fd=hn,Ap=t=>fr(hd,fd(t)),Op={code:hd,name:Sp,encode:fd,digest:Ap},Cp=Object.freeze(Object.defineProperty({__proto__:null,identity:Op},Symbol.toStringTag,{value:"Module"})),Tp="raw",Ip=85,Rp=t=>hn(t),Wp=t=>hn(t),Mp=Object.freeze(Object.defineProperty({__proto__:null,code:Ip,decode:Wp,encode:Rp,name:Tp},Symbol.toStringTag,{value:"Module"})),Pp=new TextEncoder,$p=new TextDecoder,Lp="json",Bp=512,Up=t=>Pp.encode(JSON.stringify(t)),qp=t=>JSON.parse($p.decode(t)),Fp=Object.freeze(Object.defineProperty({__proto__:null,code:Bp,decode:qp,encode:Up,name:Lp},Symbol.toStringTag,{value:"Module"}));class De{constructor(e,n,r,i){this.code=n,this.version=e,this.multihash=r,this.bytes=i,this.byteOffset=i.byteOffset,this.byteLength=i.byteLength,this.asCID=this,this._baseCache=new Map,Object.defineProperties(this,{byteOffset:Ur,byteLength:Ur,code:Br,version:Br,multihash:Br,bytes:Br,_baseCache:Ur,asCID:Ur})}toV0(){switch(this.version){case 0:return this;default:{const{code:e,multihash:n}=this;if(e!==Vn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(n.code!==Hp)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return De.createV0(n)}}}toV1(){switch(this.version){case 0:{const{code:e,digest:n}=this.multihash,r=fr(e,n);return De.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}equals(e){return e&&this.code===e.code&&this.version===e.version&&dd(this.multihash,e.multihash)}toString(e){const{bytes:n,version:r,_baseCache:i}=this;switch(r){case 0:return _p(n,i,e||tt.encoder);default:return jp(n,i,e||Zn.encoder)}}toJSON(){return{code:this.code,version:this.version,hash:this.multihash.bytes}}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return"CID("+this.toString()+")"}static isCID(e){return zp(/^0\.0/,Jp),!!(e&&(e[ca]||e.asCID===e))}get toBaseEncodedString(){throw new Error("Deprecated, use .toString()")}get codec(){throw new Error('"codec" property is deprecated, use integer "code" property instead')}get buffer(){throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead")}get multibaseName(){throw new Error('"multibaseName" property is deprecated')}get prefix(){throw new Error('"prefix" property is deprecated')}static asCID(e){if(e instanceof De)return e;if(e!=null&&e.asCID===e){const{version:n,code:r,multihash:i,bytes:s}=e;return new De(n,r,i,s||aa(n,r,i.bytes))}else if(e!=null&&e[ca]===!0){const{version:n,multihash:r,code:i}=e,s=cd(r);return De.create(n,i,s)}else return null}static create(e,n,r){if(typeof n!="number")throw new Error("String codecs are no longer supported");switch(e){case 0:{if(n!==Vn)throw new Error(`Version 0 CID must use dag-pb (code: ${Vn}) block encoding`);return new De(e,n,r,r.bytes)}case 1:{const i=aa(e,n,r.bytes);return new De(e,n,r,i)}default:throw new Error("Invalid version")}}static createV0(e){return De.create(0,Vn,e)}static createV1(e,n){return De.create(1,e,n)}static decode(e){const[n,r]=De.decodeFirst(e);if(r.length)throw new Error("Incorrect length");return n}static decodeFirst(e){const n=De.inspectBytes(e),r=n.size-n.multihashSize,i=hn(e.subarray(r,r+n.multihashSize));if(i.byteLength!==n.multihashSize)throw new Error("Incorrect length");const s=i.subarray(n.multihashSize-n.digestSize),o=new Mi(n.multihashCode,n.digestSize,s,i);return[n.version===0?De.createV0(o):De.createV1(n.codec,o),e.subarray(n.size)]}static inspectBytes(e){let n=0;const r=()=>{const[f,l]=ur(e.subarray(n));return n+=l,f};let i=r(),s=Vn;if(i===18?(i=0,n=0):i===1&&(s=r()),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);const o=n,a=r(),c=r(),u=n+c,h=u-o;return{version:i,codec:s,multihashCode:a,digestSize:c,multihashSize:h,size:u}}static parse(e,n){const[r,i]=Vp(e,n),s=De.decode(i);return s._baseCache.set(r,e),s}}const Vp=(t,e)=>{switch(t[0]){case"Q":{const n=e||tt;return[tt.prefix,n.decode(`${tt.prefix}${t}`)]}case tt.prefix:{const n=e||tt;return[tt.prefix,n.decode(t)]}case Zn.prefix:{const n=e||Zn;return[Zn.prefix,n.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},_p=(t,e,n)=>{const{prefix:r}=n;if(r!==tt.prefix)throw Error(`Cannot string encode V0 in ${n.name} encoding`);const i=e.get(r);if(i==null){const s=n.encode(t).slice(1);return e.set(r,s),s}else return i},jp=(t,e,n)=>{const{prefix:r}=n,i=e.get(r);if(i==null){const s=n.encode(t);return e.set(r,s),s}else return i},Vn=112,Hp=18,aa=(t,e,n)=>{const r=hr(t),i=r+hr(e),s=new Uint8Array(i+n.byteLength);return lr(t,s,0),lr(e,s,r),s.set(n,i),s},ca=Symbol.for("@ipld/js-cid/CID"),Br={writable:!1,configurable:!1,enumerable:!0},Ur={writable:!1,enumerable:!1,configurable:!1},Kp="0.0.0-dev",zp=(t,e)=>{if(t.test(Kp))console.warn(e);else throw new Error(e)},Jp=`CID.isCID(v) is deprecated and will be removed in the next major release.
|
|
2
|
-
Following code pattern:
|
|
3
|
-
|
|
4
|
-
if (CID.isCID(value)) {
|
|
5
|
-
doSomethingWithCID(value)
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
Is replaced with:
|
|
9
|
-
|
|
10
|
-
const cid = CID.asCID(value)
|
|
11
|
-
if (cid) {
|
|
12
|
-
// Make sure to use cid instead of value
|
|
13
|
-
doSomethingWithCID(cid)
|
|
14
|
-
}
|
|
15
|
-
`,Rs={...Ef,...kf,...Af,...Cf,...Rf,...Ff,...jf,...Kf,...Yf,...rp},Gp={...kp,...Cp},Zp={raw:Mp,json:Fp},Yp=Object.freeze(Object.defineProperty({__proto__:null,CID:De,bases:Rs,bytes:mf,codecs:Zp,digest:xp,hasher:vp,hashes:Gp,varint:Np},Symbol.toStringTag,{value:"Module"}));function pd(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const da=pd("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Ji=pd("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=Xc(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),md={utf8:da,"utf-8":da,hex:Rs.base16,latin1:Ji,ascii:Ji,binary:Ji,...Rs};function Pi(t,e="utf8"){const n=md[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?no(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}const Qp=Object.freeze(Object.defineProperty({__proto__:null,fromString:Pi},Symbol.toStringTag,{value:"Module"}));function io(t,e="utf8"){const n=md[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):n.encoder.encode(t).substring(1)}const Xp=Object.freeze(Object.defineProperty({__proto__:null,toString:io},Symbol.toStringTag,{value:"Module"})),mn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Ar(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function pr(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function xt(t,...e){if(!Ar(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function bd(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");pr(t.outputLen),pr(t.blockLen)}function Rn(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function wd(t,e){xt(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function em(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function st(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Gi(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Xe(t,e){return t<<32-e|t>>>e}function qr(t,e){return t<<e|t>>>32-e>>>0}const tm=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function nm(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function rm(t){for(let e=0;e<t.length;e++)t[e]=nm(t[e]);return t}const ua=tm?t=>t:rm,yd=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",im=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function sn(t){if(xt(t),yd)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=im[t[n]];return e}const dt={_0:48,_9:57,A:65,F:70,a:97,f:102};function la(t){if(t>=dt._0&&t<=dt._9)return t-dt._0;if(t>=dt.A&&t<=dt.F)return t-(dt.A-10);if(t>=dt.a&&t<=dt.f)return t-(dt.a-10)}function mr(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(yd)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=la(t.charCodeAt(s)),a=la(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[i]=o*16+a}return r}function sm(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function $i(t){return typeof t=="string"&&(t=sm(t)),xt(t),t}function nt(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];xt(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}class so{}function Or(t){const e=r=>t().update($i(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function oo(t=32){if(mn&&typeof mn.getRandomValues=="function")return mn.getRandomValues(new Uint8Array(t));if(mn&&typeof mn.randomBytes=="function")return Uint8Array.from(mn.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function om(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}function am(t,e,n){return t&e^~t&n}function cm(t,e,n){return t&e^t&n^e&n}class ao extends so{constructor(e,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=Gi(this.buffer)}update(e){Rn(this),e=$i(e),xt(e);const{view:n,buffer:r,blockLen:i}=this,s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=Gi(e);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Rn(this),wd(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,st(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let f=o;f<i;f++)n[f]=0;om(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=Gi(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,h=this.get();if(u>h.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,h[f],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const At=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ve=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Ee=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Fr=BigInt(2**32-1),ha=BigInt(32);function dm(t,e=!1){return e?{h:Number(t&Fr),l:Number(t>>ha&Fr)}:{h:Number(t>>ha&Fr)|0,l:Number(t&Fr)|0}}function gd(t,e=!1){const n=t.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:o,l:a}=dm(t[s],e);[r[s],i[s]]=[o,a]}return[r,i]}const fa=(t,e,n)=>t>>>n,pa=(t,e,n)=>t<<32-n|e>>>n,bn=(t,e,n)=>t>>>n|e<<32-n,wn=(t,e,n)=>t<<32-n|e>>>n,Vr=(t,e,n)=>t<<64-n|e>>>n-32,_r=(t,e,n)=>t>>>n-32|e<<64-n,um=(t,e,n)=>t<<n|e>>>32-n,lm=(t,e,n)=>e<<n|t>>>32-n,hm=(t,e,n)=>e<<n-32|t>>>64-n,fm=(t,e,n)=>t<<n-32|e>>>64-n;function ut(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:i|0}}const pm=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),mm=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,bm=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),wm=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,ym=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),gm=(t,e,n,r,i,s)=>e+n+r+i+s+(t/2**32|0)|0,Nm=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ot=new Uint32Array(64);class xm extends ao{constructor(e=32){super(64,e,8,!1),this.A=At[0]|0,this.B=At[1]|0,this.C=At[2]|0,this.D=At[3]|0,this.E=At[4]|0,this.F=At[5]|0,this.G=At[6]|0,this.H=At[7]|0}get(){const{A:e,B:n,C:r,D:i,E:s,F:o,G:a,H:c}=this;return[e,n,r,i,s,o,a,c]}set(e,n,r,i,s,o,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,n){for(let f=0;f<16;f++,n+=4)Ot[f]=e.getUint32(n,!1);for(let f=16;f<64;f++){const l=Ot[f-15],m=Ot[f-2],p=Xe(l,7)^Xe(l,18)^l>>>3,b=Xe(m,17)^Xe(m,19)^m>>>10;Ot[f]=b+Ot[f-7]+p+Ot[f-16]|0}let{A:r,B:i,C:s,D:o,E:a,F:c,G:u,H:h}=this;for(let f=0;f<64;f++){const l=Xe(a,6)^Xe(a,11)^Xe(a,25),m=h+l+am(a,c,u)+Nm[f]+Ot[f]|0,b=(Xe(r,2)^Xe(r,13)^Xe(r,22))+cm(r,i,s)|0;h=u,u=c,c=a,a=o+m|0,o=s,s=i,i=r,r=m+b|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,h=h+this.H|0,this.set(r,i,s,o,a,c,u,h)}roundClean(){st(Ot)}destroy(){this.set(0,0,0,0,0,0,0,0),st(this.buffer)}}const Nd=gd(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),vm=Nd[0],Em=Nd[1],Ct=new Uint32Array(80),Tt=new Uint32Array(80);class xd extends ao{constructor(e=64){super(128,e,16,!1),this.Ah=Ee[0]|0,this.Al=Ee[1]|0,this.Bh=Ee[2]|0,this.Bl=Ee[3]|0,this.Ch=Ee[4]|0,this.Cl=Ee[5]|0,this.Dh=Ee[6]|0,this.Dl=Ee[7]|0,this.Eh=Ee[8]|0,this.El=Ee[9]|0,this.Fh=Ee[10]|0,this.Fl=Ee[11]|0,this.Gh=Ee[12]|0,this.Gl=Ee[13]|0,this.Hh=Ee[14]|0,this.Hl=Ee[15]|0}get(){const{Ah:e,Al:n,Bh:r,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:u,El:h,Fh:f,Fl:l,Gh:m,Gl:p,Hh:b,Hl:v}=this;return[e,n,r,i,s,o,a,c,u,h,f,l,m,p,b,v]}set(e,n,r,i,s,o,a,c,u,h,f,l,m,p,b,v){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=h|0,this.Fh=f|0,this.Fl=l|0,this.Gh=m|0,this.Gl=p|0,this.Hh=b|0,this.Hl=v|0}process(e,n){for(let y=0;y<16;y++,n+=4)Ct[y]=e.getUint32(n),Tt[y]=e.getUint32(n+=4);for(let y=16;y<80;y++){const k=Ct[y-15]|0,x=Tt[y-15]|0,N=bn(k,x,1)^bn(k,x,8)^fa(k,x,7),A=wn(k,x,1)^wn(k,x,8)^pa(k,x,7),S=Ct[y-2]|0,O=Tt[y-2]|0,$=bn(S,O,19)^Vr(S,O,61)^fa(S,O,6),q=wn(S,O,19)^_r(S,O,61)^pa(S,O,6),L=bm(A,q,Tt[y-7],Tt[y-16]),C=wm(L,N,$,Ct[y-7],Ct[y-16]);Ct[y]=C|0,Tt[y]=L|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:h,Eh:f,El:l,Fh:m,Fl:p,Gh:b,Gl:v,Hh:w,Hl:g}=this;for(let y=0;y<80;y++){const k=bn(f,l,14)^bn(f,l,18)^Vr(f,l,41),x=wn(f,l,14)^wn(f,l,18)^_r(f,l,41),N=f&m^~f&b,A=l&p^~l&v,S=ym(g,x,A,Em[y],Tt[y]),O=gm(S,w,k,N,vm[y],Ct[y]),$=S|0,q=bn(r,i,28)^Vr(r,i,34)^Vr(r,i,39),L=wn(r,i,28)^_r(r,i,34)^_r(r,i,39),C=r&s^r&a^s&a,E=i&o^i&c^o&c;w=b|0,g=v|0,b=m|0,v=p|0,m=f|0,p=l|0,{h:f,l}=ut(u|0,h|0,O|0,$|0),u=a|0,h=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const D=pm($,L,E);r=mm(D,O,q,C),i=D|0}({h:r,l:i}=ut(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=ut(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=ut(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:h}=ut(this.Dh|0,this.Dl|0,u|0,h|0),{h:f,l}=ut(this.Eh|0,this.El|0,f|0,l|0),{h:m,l:p}=ut(this.Fh|0,this.Fl|0,m|0,p|0),{h:b,l:v}=ut(this.Gh|0,this.Gl|0,b|0,v|0),{h:w,l:g}=ut(this.Hh|0,this.Hl|0,w|0,g|0),this.set(r,i,s,o,a,c,u,h,f,l,m,p,b,v,w,g)}roundClean(){st(Ct,Tt)}destroy(){st(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class Dm extends xd{constructor(){super(48),this.Ah=ve[0]|0,this.Al=ve[1]|0,this.Bh=ve[2]|0,this.Bl=ve[3]|0,this.Ch=ve[4]|0,this.Cl=ve[5]|0,this.Dh=ve[6]|0,this.Dl=ve[7]|0,this.Eh=ve[8]|0,this.El=ve[9]|0,this.Fh=ve[10]|0,this.Fl=ve[11]|0,this.Gh=ve[12]|0,this.Gl=ve[13]|0,this.Hh=ve[14]|0,this.Hl=ve[15]|0}}const co=Or(()=>new xm),vd=Or(()=>new xd),km=Or(()=>new Dm);const uo=BigInt(0),Ws=BigInt(1);function cn(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function Qe(t,e,n=""){const r=Ar(t),i=t?.length,s=e!==void 0;if(!r||s&&i!==e){const o=n&&`"${n}" `,a=s?` of length ${e}`:"",c=r?`length=${i}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function Jn(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Ed(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?uo:BigInt("0x"+t)}function Li(t){return Ed(sn(t))}function br(t){return xt(t),Ed(sn(Uint8Array.from(t).reverse()))}function lo(t,e){return mr(t.toString(16).padStart(e*2,"0"))}function Dd(t,e){return lo(t,e).reverse()}function Sm(t){return mr(Jn(t))}function re(t,e,n){let r;if(typeof e=="string")try{r=mr(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Ar(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(t+" of length "+n+" expected, got "+i);return r}function ma(t){return Uint8Array.from(t)}const Zi=t=>typeof t=="bigint"&&uo<=t;function Am(t,e,n){return Zi(t)&&Zi(e)&&Zi(n)&&e<=t&&t<n}function Ms(t,e,n,r){if(!Am(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function kd(t){let e;for(e=0;t>uo;t>>=Ws,e+=1);return e}const Cr=t=>(Ws<<BigInt(t))-Ws;function Om(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");const r=m=>new Uint8Array(m),i=m=>Uint8Array.of(m);let s=r(t),o=r(t),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},u=(...m)=>n(o,s,...m),h=(m=r(0))=>{o=u(i(0),m),s=u(),m.length!==0&&(o=u(i(1),m),s=u())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let m=0;const p=[];for(;m<e;){s=u();const b=s.slice();p.push(b),m+=s.length}return nt(...p)};return(m,p)=>{c(),h(m);let b;for(;!(b=p(f()));)h();return c(),b}}function Tr(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(i,s,o){const a=t[i];if(o&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([i,s])=>r(i,s,!1)),Object.entries(n).forEach(([i,s])=>r(i,s,!0))}function di(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t(n,...r);return e.set(n,s),s}}const Re=BigInt(0),we=BigInt(1),Qt=BigInt(2),Sd=BigInt(3),Ad=BigInt(4),Od=BigInt(5),Cm=BigInt(7),Cd=BigInt(8),Tm=BigInt(9),Td=BigInt(16);function he(t,e){const n=t%e;return n>=Re?n:e+n}function ce(t,e,n){let r=t;for(;e-- >Re;)r*=r,r%=n;return r}function ba(t,e){if(t===Re)throw new Error("invert: expected non-zero number");if(e<=Re)throw new Error("invert: expected positive modulus, got "+e);let n=he(t,e),r=e,i=Re,s=we;for(;n!==Re;){const a=r/n,c=r%n,u=i-s*a;r=n,n=c,i=s,s=u}if(r!==we)throw new Error("invert: does not exist");return he(i,e)}function ho(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Id(t,e){const n=(t.ORDER+we)/Ad,r=t.pow(e,n);return ho(t,r,e),r}function Im(t,e){const n=(t.ORDER-Od)/Cd,r=t.mul(e,Qt),i=t.pow(r,n),s=t.mul(e,i),o=t.mul(t.mul(s,Qt),i),a=t.mul(s,t.sub(o,t.ONE));return ho(t,a,e),a}function Rm(t){const e=ct(t),n=Rd(t),r=n(e,e.neg(e.ONE)),i=n(e,r),s=n(e,e.neg(r)),o=(t+Cm)/Td;return(a,c)=>{let u=a.pow(c,o),h=a.mul(u,r);const f=a.mul(u,i),l=a.mul(u,s),m=a.eql(a.sqr(h),c),p=a.eql(a.sqr(f),c);u=a.cmov(u,h,m),h=a.cmov(l,f,p);const b=a.eql(a.sqr(h),c),v=a.cmov(u,h,b);return ho(a,v,c),v}}function Rd(t){if(t<Sd)throw new Error("sqrt is not defined for small field");let e=t-we,n=0;for(;e%Qt===Re;)e/=Qt,n++;let r=Qt;const i=ct(t);for(;wa(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Id;let s=i.pow(r,e);const o=(e+we)/Qt;return function(c,u){if(c.is0(u))return u;if(wa(c,u)!==1)throw new Error("Cannot find square root");let h=n,f=c.mul(c.ONE,s),l=c.pow(u,e),m=c.pow(u,o);for(;!c.eql(l,c.ONE);){if(c.is0(l))return c.ZERO;let p=1,b=c.sqr(l);for(;!c.eql(b,c.ONE);)if(p++,b=c.sqr(b),p===h)throw new Error("Cannot find square root");const v=we<<BigInt(h-p-1),w=c.pow(f,v);h=p,f=c.sqr(w),l=c.mul(l,f),m=c.mul(m,w)}return m}}function Wm(t){return t%Ad===Sd?Id:t%Cd===Od?Im:t%Td===Tm?Rm(t):Rd(t)}const Mm=(t,e)=>(he(t,e)&we)===we,Pm=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function $m(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=Pm.reduce((r,i)=>(r[i]="function",r),e);return Tr(t,n),t}function Lm(t,e,n){if(n<Re)throw new Error("invalid exponent, negatives unsupported");if(n===Re)return t.ONE;if(n===we)return e;let r=t.ONE,i=e;for(;n>Re;)n&we&&(r=t.mul(r,i)),i=t.sqr(i),n>>=we;return r}function Wd(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),i=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),s=t.inv(i);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),s),r}function wa(t,e){const n=(t.ORDER-we)/Qt,r=t.pow(e,n),i=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function Md(t,e){e!==void 0&&pr(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function ct(t,e,n=!1,r={}){if(t<=Re)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,s,o=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const l=e;l.BITS&&(i=l.BITS),l.sqrt&&(s=l.sqrt),typeof l.isLE=="boolean"&&(n=l.isLE),typeof l.modFromBytes=="boolean"&&(o=l.modFromBytes),a=l.allowedLengths}else typeof e=="number"&&(i=e),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:u}=Md(t,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let h;const f=Object.freeze({ORDER:t,isLE:n,BITS:c,BYTES:u,MASK:Cr(c),ZERO:Re,ONE:we,allowedLengths:a,create:l=>he(l,t),isValid:l=>{if(typeof l!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof l);return Re<=l&&l<t},is0:l=>l===Re,isValidNot0:l=>!f.is0(l)&&f.isValid(l),isOdd:l=>(l&we)===we,neg:l=>he(-l,t),eql:(l,m)=>l===m,sqr:l=>he(l*l,t),add:(l,m)=>he(l+m,t),sub:(l,m)=>he(l-m,t),mul:(l,m)=>he(l*m,t),pow:(l,m)=>Lm(f,l,m),div:(l,m)=>he(l*ba(m,t),t),sqrN:l=>l*l,addN:(l,m)=>l+m,subN:(l,m)=>l-m,mulN:(l,m)=>l*m,inv:l=>ba(l,t),sqrt:s||(l=>(h||(h=Wm(t)),h(f,l))),toBytes:l=>n?Dd(l,u):lo(l,u),fromBytes:(l,m=!0)=>{if(a){if(!a.includes(l.length)||l.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+l.length);const b=new Uint8Array(u);b.set(l,n?0:b.length-l.length),l=b}if(l.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+l.length);let p=n?br(l):Li(l);if(o&&(p=he(p,t)),!m&&!f.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:l=>Wd(f,l),cmov:(l,m,p)=>p?m:l});return Object.freeze(f)}function Pd(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function $d(t){const e=Pd(t);return e+Math.ceil(e/2)}function Bm(t,e,n=!1){const r=t.length,i=Pd(e),s=$d(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?br(t):Li(t),a=he(o,e-we)+we;return n?Dd(a,i):lo(a,i)}const Wn=BigInt(0),Xt=BigInt(1);function ui(t,e){const n=e.negate();return t?n:e}function en(t,e){const n=Wd(t.Fp,e.map(r=>r.Z));return e.map((r,i)=>t.fromAffine(r.toAffine(n[i])))}function Ld(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Yi(t,e){Ld(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),i=2**t,s=Cr(t),o=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function ya(t,e,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(t&i),c=t>>o;a>r&&(a-=s,c+=Xt);const u=e*r,h=u+Math.abs(a)-1,f=a===0,l=a<0,m=e%2!==0;return{nextN:c,offset:h,isZero:f,isNeg:l,isNegF:m,offsetF:u}}function Um(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function qm(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const Qi=new WeakMap,Bd=new WeakMap;function Xi(t){return Bd.get(t)||1}function ga(t){if(t!==Wn)throw new Error("invalid wNAF")}class Ud{constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let i=e;for(;n>Wn;)n&Xt&&(r=r.add(i)),i=i.double(),n>>=Xt;return r}precomputeWindow(e,n){const{windows:r,windowSize:i}=Yi(n,this.bits),s=[];let o=e,a=o;for(let c=0;c<r;c++){a=o,s.push(a);for(let u=1;u<i;u++)a=a.add(o),s.push(a);o=a.double()}return s}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let i=this.ZERO,s=this.BASE;const o=Yi(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:u,isZero:h,isNeg:f,isNegF:l,offsetF:m}=ya(r,a,o);r=c,h?s=s.add(ui(l,n[m])):i=i.add(ui(f,n[u]))}return ga(r),{p:i,f:s}}wNAFUnsafe(e,n,r,i=this.ZERO){const s=Yi(e,this.bits);for(let o=0;o<s.windows&&r!==Wn;o++){const{nextN:a,offset:c,isZero:u,isNeg:h}=ya(r,o,s);if(r=a,!u){const f=n[c];i=i.add(h?f.negate():f)}}return ga(r),i}getPrecomputes(e,n,r){let i=Qi.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(i=r(i)),Qi.set(n,i))),i}cached(e,n,r){const i=Xi(e);return this.wNAF(i,this.getPrecomputes(i,e,r),n)}unsafe(e,n,r,i){const s=Xi(e);return s===1?this._unsafeLadder(e,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,i)}createCache(e,n){Ld(n,this.bits),Bd.set(e,n),Qi.delete(e)}hasCache(e){return Xi(e)!==1}}function Fm(t,e,n,r){let i=e,s=t.ZERO,o=t.ZERO;for(;n>Wn||r>Wn;)n&Xt&&(s=s.add(i)),r&Xt&&(o=o.add(i)),i=i.double(),n>>=Xt,r>>=Xt;return{p1:s,p2:o}}function qd(t,e,n,r){Um(n,t),qm(r,e);const i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=kd(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=Cr(c),h=new Array(Number(u)+1).fill(o),f=Math.floor((e.BITS-1)/c)*c;let l=o;for(let m=f;m>=0;m-=c){h.fill(o);for(let b=0;b<s;b++){const v=r[b],w=Number(v>>BigInt(m)&u);h[w]=h[w].add(n[b])}let p=o;for(let b=h.length-1,v=o;b>0;b--)v=v.add(h[b]),p=p.add(v);if(l=l.add(p),m!==0)for(let b=0;b<c;b++)l=l.double()}return l}function Na(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return $m(e),e}else return ct(t,{isLE:n})}function Fd(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const c of["p","n","h"]){const u=e[c];if(!(typeof u=="bigint"&&u>Wn))throw new Error(`CURVE.${c} must be positive bigint`)}const i=Na(e.p,n.Fp,r),s=Na(e.n,n.Fn,r),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const c of a)if(!i.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:s}}const It=BigInt(0),me=BigInt(1),es=BigInt(2),Vm=BigInt(8);function _m(t,e,n,r){const i=t.sqr(n),s=t.sqr(r),o=t.add(t.mul(e.a,i),s),a=t.add(t.ONE,t.mul(e.d,t.mul(i,s)));return t.eql(o,a)}function jm(t,e={}){const n=Fd("edwards",t,e,e.FpFnLE),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o}=s;Tr(e,{},{uvRatio:"function"});const a=es<<BigInt(i.BYTES*8)-me,c=v=>r.create(v),u=e.uvRatio||((v,w)=>{try{return{isValid:!0,value:r.sqrt(r.div(v,w))}}catch{return{isValid:!1,value:It}}});if(!_m(r,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function h(v,w,g=!1){const y=g?me:It;return Ms("coordinate "+v,w,y,a),w}function f(v){if(!(v instanceof p))throw new Error("ExtendedPoint expected")}const l=di((v,w)=>{const{X:g,Y:y,Z:k}=v,x=v.is0();w==null&&(w=x?Vm:r.inv(k));const N=c(g*w),A=c(y*w),S=r.mul(k,w);if(x)return{x:It,y:me};if(S!==me)throw new Error("invZ was invalid");return{x:N,y:A}}),m=di(v=>{const{a:w,d:g}=s;if(v.is0())throw new Error("bad point: ZERO");const{X:y,Y:k,Z:x,T:N}=v,A=c(y*y),S=c(k*k),O=c(x*x),$=c(O*O),q=c(A*w),L=c(O*c(q+S)),C=c($+c(g*c(A*S)));if(L!==C)throw new Error("bad point: equation left != right (1)");const E=c(y*k),D=c(x*N);if(E!==D)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(w,g,y,k){this.X=h("x",w),this.Y=h("y",g),this.Z=h("z",y,!0),this.T=h("t",k),Object.freeze(this)}static CURVE(){return s}static fromAffine(w){if(w instanceof p)throw new Error("extended point not allowed");const{x:g,y}=w||{};return h("x",g),h("y",y),new p(g,y,me,c(g*y))}static fromBytes(w,g=!1){const y=r.BYTES,{a:k,d:x}=s;w=ma(Qe(w,y,"point")),cn(g,"zip215");const N=ma(w),A=w[y-1];N[y-1]=A&-129;const S=br(N),O=g?a:r.ORDER;Ms("point.y",S,It,O);const $=c(S*S),q=c($-me),L=c(x*$-k);let{isValid:C,value:E}=u(q,L);if(!C)throw new Error("bad point: invalid y coordinate");const D=(E&me)===me,T=(A&128)!==0;if(!g&&E===It&&T)throw new Error("bad point: x=0 and x_0=1");return T!==D&&(E=c(-E)),p.fromAffine({x:E,y:S})}static fromHex(w,g=!1){return p.fromBytes(re("point",w),g)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,g=!0){return b.createCache(this,w),g||this.multiply(es),this}assertValidity(){m(this)}equals(w){f(w);const{X:g,Y:y,Z:k}=this,{X:x,Y:N,Z:A}=w,S=c(g*A),O=c(x*k),$=c(y*A),q=c(N*k);return S===O&&$===q}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:w}=s,{X:g,Y:y,Z:k}=this,x=c(g*g),N=c(y*y),A=c(es*c(k*k)),S=c(w*x),O=g+y,$=c(c(O*O)-x-N),q=S+N,L=q-A,C=S-N,E=c($*L),D=c(q*C),T=c($*C),W=c(L*q);return new p(E,D,W,T)}add(w){f(w);const{a:g,d:y}=s,{X:k,Y:x,Z:N,T:A}=this,{X:S,Y:O,Z:$,T:q}=w,L=c(k*S),C=c(x*O),E=c(A*y*q),D=c(N*$),T=c((k+x)*(S+O)-L-C),W=D-E,B=D+E,M=c(C-g*L),P=c(T*W),U=c(B*M),V=c(T*M),se=c(W*B);return new p(P,U,se,V)}subtract(w){return this.add(w.negate())}multiply(w){if(!i.isValidNot0(w))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:g,f:y}=b.cached(this,w,k=>en(p,k));return en(p,[g,y])[0]}multiplyUnsafe(w,g=p.ZERO){if(!i.isValid(w))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return w===It?p.ZERO:this.is0()||w===me?this:b.unsafe(this,w,y=>en(p,y),g)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return b.unsafe(this,s.n).is0()}toAffine(w){return l(this,w)}clearCofactor(){return o===me?this:this.multiplyUnsafe(o)}toBytes(){const{x:w,y:g}=this.toAffine(),y=r.toBytes(g);return y[y.length-1]|=w&me?128:0,y}toHex(){return sn(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(w){return en(p,w)}static msm(w,g){return qd(p,i,w,g)}_setWindowSize(w){this.precompute(w)}toRawBytes(){return this.toBytes()}}p.BASE=new p(s.Gx,s.Gy,me,c(s.Gx*s.Gy)),p.ZERO=new p(It,me,me,It),p.Fp=r,p.Fn=i;const b=new Ud(p,i.BITS);return p.BASE.precompute(8),p}function Hm(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is required');Tr(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:i,Fp:s,Fn:o}=t,a=n.randomBytes||oo,c=n.adjustScalarBytes||(O=>O),u=n.domain||((O,$,q)=>{if(cn(q,"phflag"),$.length||q)throw new Error("Contexts/pre-hash are not supported");return O});function h(O){return o.create(br(O))}function f(O){const $=y.secretKey;O=re("private key",O,$);const q=re("hashed private key",e(O),2*$),L=c(q.slice(0,$)),C=q.slice($,2*$),E=h(L);return{head:L,prefix:C,scalar:E}}function l(O){const{head:$,prefix:q,scalar:L}=f(O),C=i.multiply(L),E=C.toBytes();return{head:$,prefix:q,scalar:L,point:C,pointBytes:E}}function m(O){return l(O).pointBytes}function p(O=Uint8Array.of(),...$){const q=nt(...$);return h(e(u(q,re("context",O),!!r)))}function b(O,$,q={}){O=re("message",O),r&&(O=r(O));const{prefix:L,scalar:C,pointBytes:E}=l($),D=p(q.context,L,O),T=i.multiply(D).toBytes(),W=p(q.context,T,E,O),B=o.create(D+W*C);if(!o.isValid(B))throw new Error("sign failed: invalid s");const M=nt(T,o.toBytes(B));return Qe(M,y.signature,"result")}const v={zip215:!0};function w(O,$,q,L=v){const{context:C,zip215:E}=L,D=y.signature;O=re("signature",O,D),$=re("message",$),q=re("publicKey",q,y.publicKey),E!==void 0&&cn(E,"zip215"),r&&($=r($));const T=D/2,W=O.subarray(0,T),B=br(O.subarray(T,D));let M,P,U;try{M=t.fromBytes(q,E),P=t.fromBytes(W,E),U=i.multiplyUnsafe(B)}catch{return!1}if(!E&&M.isSmallOrder())return!1;const V=p(C,P.toBytes(),M.toBytes(),$);return P.add(M.multiplyUnsafe(V)).subtract(U).clearCofactor().is0()}const g=s.BYTES,y={secretKey:g,publicKey:g,signature:2*g,seed:g};function k(O=a(y.seed)){return Qe(O,y.seed,"seed")}function x(O){const $=S.randomSecretKey(O);return{secretKey:$,publicKey:m($)}}function N(O){return Ar(O)&&O.length===o.BYTES}function A(O,$){try{return!!t.fromBytes(O,$)}catch{return!1}}const S={getExtendedPublicKey:l,randomSecretKey:k,isValidSecretKey:N,isValidPublicKey:A,toMontgomery(O){const{y:$}=t.fromBytes(O),q=y.publicKey,L=q===32;if(!L&&q!==57)throw new Error("only defined for 25519 and 448");const C=L?s.div(me+$,me-$):s.div($-me,$+me);return s.toBytes(C)},toMontgomerySecret(O){const $=y.secretKey;Qe(O,$);const q=e(O.subarray(0,$));return c(q).subarray(0,$)},randomPrivateKey:k,precompute(O=8,$=t.BASE){return $.precompute(O,!1)}};return Object.freeze({keygen:x,getPublicKey:m,sign:b,verify:w,utils:S,Point:t,lengths:y})}function Km(t){const e={a:t.a,d:t.d,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp,r=ct(e.n,t.nBitLength,!0),i={Fp:n,Fn:r,uvRatio:t.uvRatio},s={randomBytes:t.randomBytes,adjustScalarBytes:t.adjustScalarBytes,domain:t.domain,prehash:t.prehash,mapToCurve:t.mapToCurve};return{CURVE:e,curveOpts:i,hash:t.hash,eddsaOpts:s}}function zm(t,e){const n=e.Point;return Object.assign({},e,{ExtendedPoint:n,CURVE:t,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function Jm(t){const{CURVE:e,curveOpts:n,hash:r,eddsaOpts:i}=Km(t),s=jm(e,n),o=Hm(s,r,i);return zm(t,o)}const Gm=BigInt(1),xa=BigInt(2);BigInt(3);const Zm=BigInt(5),Ym=BigInt(8),fo=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Vd={p:fo,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ym,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Qm(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=fo,a=t*t%s*t%s,c=ce(a,xa,s)*a%s,u=ce(c,Gm,s)*t%s,h=ce(u,Zm,s)*u%s,f=ce(h,e,s)*h%s,l=ce(f,n,s)*f%s,m=ce(l,r,s)*l%s,p=ce(m,i,s)*m%s,b=ce(p,i,s)*m%s,v=ce(b,e,s)*h%s;return{pow_p_5_8:ce(v,xa,s)*t%s,b2:a}}function Xm(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const va=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function eb(t,e){const n=fo,r=he(e*e*e,n),i=he(r*r*e,n),s=Qm(t*i).pow_p_5_8;let o=he(t*r*s,n);const a=he(e*o*o,n),c=o,u=he(o*va,n),h=a===t,f=a===he(-t,n),l=a===he(-t*va,n);return h&&(o=c),(f||l)&&(o=u),Mm(o,n)&&(o=he(-o,n)),{isValid:h||f,value:o}}const tb=ct(Vd.p,{isLE:!0}),nb={...Vd,Fp:tb,hash:vd,adjustScalarBytes:Xm,uvRatio:eb},_d=Jm(nb);function rb(t){return _d.utils.toMontgomery(re("pub",t))}var jr={exports:{}},ts,Ea;function ib(){if(Ea)return ts;Ea=1;function t(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<e.length;i++){var s=e.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=e.length,c=e.charAt(0),u=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var b=0,v=0,w=0,g=p.length;w!==g&&p[w]===0;)w++,b++;for(var y=(g-w)*h+1>>>0,k=new Uint8Array(y);w!==g;){for(var x=p[w],N=0,A=y-1;(x!==0||N<v)&&A!==-1;A--,N++)x+=256*k[A]>>>0,k[A]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");v=N,w++}for(var S=y-v;S!==y&&k[S]===0;)S++;for(var O=c.repeat(b);S<y;++S)O+=e.charAt(k[S]);return O}function l(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var b=0;if(p[b]!==" "){for(var v=0,w=0;p[b]===c;)v++,b++;for(var g=(p.length-b)*u+1>>>0,y=new Uint8Array(g);p[b];){var k=n[p.charCodeAt(b)];if(k===255)return;for(var x=0,N=g-1;(k!==0||x<w)&&N!==-1;N--,x++)k+=a*y[N]>>>0,y[N]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");w=x,b++}if(p[b]!==" "){for(var A=g-w;A!==g&&y[A]===0;)A++;for(var S=new Uint8Array(v+(g-A)),O=v;A!==g;)S[O++]=y[A++];return S}}}function m(p){var b=l(p);if(b)return b;throw new Error("Non-base"+a+" character")}return{encode:f,decodeUnsafe:l,decode:m}}return ts=t,ts}var ns,Da;function po(){if(Da)return ns;Da=1;const t=new TextDecoder,e=s=>t.decode(s),n=new TextEncoder,r=s=>n.encode(s);function i(s,o){const a=new Uint8Array(o);let c=0;for(const u of s)a.set(u,c),c+=u.length;return a}return ns={decodeText:e,encodeText:r,concat:i},ns}var rs,ka;function sb(){if(ka)return rs;ka=1;const{encodeText:t}=po();class e{constructor(r,i,s,o){this.name=r,this.code=i,this.codeBuf=t(this.code),this.alphabet=o,this.codec=s(o)}encode(r){return this.codec.encode(r)}decode(r){for(const i of r)if(this.alphabet&&this.alphabet.indexOf(i)<0)throw new Error(`invalid character '${i}' in '${r}'`);return this.codec.decode(r)}}return rs=e,rs}var is,Sa;function ob(){if(Sa)return is;Sa=1;const t=(r,i,s)=>{const o={};for(let l=0;l<i.length;++l)o[i[l]]=l;let a=r.length;for(;r[a-1]==="=";)--a;const c=new Uint8Array(a*s/8|0);let u=0,h=0,f=0;for(let l=0;l<a;++l){const m=o[r[l]];if(m===void 0)throw new SyntaxError("Invalid character "+r[l]);h=h<<s|m,u+=s,u>=8&&(u-=8,c[f++]=255&h>>u)}if(u>=s||255&h<<8-u)throw new SyntaxError("Unexpected end of data");return c},e=(r,i,s)=>{const o=i[i.length-1]==="=",a=(1<<s)-1;let c="",u=0,h=0;for(let f=0;f<r.length;++f)for(h=h<<8|r[f],u+=8;u>s;)u-=s,c+=i[a&h>>u];if(u&&(c+=i[a&h<<s-u]),o)for(;c.length*s&7;)c+="=";return c};return is={rfc4648:r=>i=>({encode(s){return e(s,i,r)},decode(s){return t(s,i,r)}})},is}var ss,Aa;function ab(){if(Aa)return ss;Aa=1;const t=ib(),e=sb(),{rfc4648:n}=ob(),{decodeText:r,encodeText:i}=po(),o=[["identity","\0",()=>({encode:r,decode:i}),""],["base2","0",n(1),"01"],["base8","7",n(3),"01234567"],["base10","9",t,"0123456789"],["base16","f",n(4),"0123456789abcdef"],["base16upper","F",n(4),"0123456789ABCDEF"],["base32hex","v",n(5),"0123456789abcdefghijklmnopqrstuv"],["base32hexupper","V",n(5),"0123456789ABCDEFGHIJKLMNOPQRSTUV"],["base32hexpad","t",n(5),"0123456789abcdefghijklmnopqrstuv="],["base32hexpadupper","T",n(5),"0123456789ABCDEFGHIJKLMNOPQRSTUV="],["base32","b",n(5),"abcdefghijklmnopqrstuvwxyz234567"],["base32upper","B",n(5),"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"],["base32pad","c",n(5),"abcdefghijklmnopqrstuvwxyz234567="],["base32padupper","C",n(5),"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567="],["base32z","h",n(5),"ybndrfg8ejkmcpqxot1uwisza345h769"],["base36","k",t,"0123456789abcdefghijklmnopqrstuvwxyz"],["base36upper","K",t,"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"],["base58btc","z",t,"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"],["base58flickr","Z",t,"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"],["base64","m",n(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"],["base64pad","M",n(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="],["base64url","u",n(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"],["base64urlpad","U",n(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_="]],a=o.reduce((u,h)=>(u[h[0]]=new e(h[0],h[1],h[2],h[3]),u),{}),c=o.reduce((u,h)=>(u[h[1]]=a[h[0]],u),{});return ss={names:a,codes:c},ss}var Oa;function cb(){return Oa||(Oa=1,(function(t,e){const n=ab(),{encodeText:r,decodeText:i,concat:s}=po();function o(b,v){if(!v)throw new Error("requires an encoded Uint8Array");const{name:w,codeBuf:g}=f(b);return h(w,v),s([g,v],g.length+v.length)}function a(b,v){const w=f(b),g=r(w.encode(v));return s([w.codeBuf,g],w.codeBuf.length+g.length)}function c(b){b instanceof Uint8Array&&(b=i(b));const v=b[0];return["f","F","v","V","t","T","b","B","c","C","h","k","K"].includes(v)&&(b=b.toLowerCase()),f(b[0]).decode(b.substring(1))}function u(b){if(b instanceof Uint8Array&&(b=i(b)),Object.prototype.toString.call(b)!=="[object String]")return!1;try{return f(b[0]).name}catch{return!1}}function h(b,v){f(b).decode(i(v))}function f(b){if(Object.prototype.hasOwnProperty.call(n.names,b))return n.names[b];if(Object.prototype.hasOwnProperty.call(n.codes,b))return n.codes[b];throw new Error(`Unsupported encoding: ${b}`)}function l(b){return b instanceof Uint8Array&&(b=i(b)),f(b[0])}e=t.exports=o,e.encode=a,e.decode=c,e.isEncoded=u,e.encoding=f,e.encodingFromData=l;const m=Object.freeze(n.names),p=Object.freeze(n.codes);e.names=m,e.codes=p})(jr,jr.exports)),jr.exports}var db=cb();class jd extends so{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,bd(e);const r=$i(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?e.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),st(s)}update(e){return Rn(this),this.iHash.update(e),this}digestInto(e){Rn(this),xt(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Hd=(t,e,n)=>new jd(t,e).update(n).digest();Hd.create=(t,e)=>new jd(t,e);const Ca=(t,e)=>(t+(t>=0?e:-e)/Kd)/e;function ub(t,e,n){const[[r,i],[s,o]]=e,a=Ca(o*t,n),c=Ca(-i*t,n);let u=t-a*r-c*s,h=-a*i-c*o;const f=u<yt,l=h<yt;f&&(u=-u),l&&(h=-h);const m=Cr(Math.ceil(kd(n)/2))+An;if(u<yt||u>=m||h<yt||h>=m)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:l,k2:h}}function Ps(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function os(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return cn(n.lowS,"lowS"),cn(n.prehash,"prehash"),n.format!==void 0&&Ps(n.format),n}class lb extends Error{constructor(e=""){super(e)}}const mt={Err:lb,_tlv:{encode:(t,e)=>{const{Err:n}=mt;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,i=Jn(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Jn(i.length/2|128):"";return Jn(t)+s+i+e},decode(t,e){const{Err:n}=mt;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const i=e[r++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const u=e.subarray(r,r+c);if(u.length!==c)throw new n("tlv.decode: length bytes not complete");if(u[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const h of u)o=o<<8|h;if(r+=c,o<128)throw new n("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=mt;if(t<yt)throw new e("integer: negative integers are not allowed");let n=Jn(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){const{Err:e}=mt;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Li(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=mt,i=re("signature",t),{v:s,l:o}=r.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:u,l:h}=r.decode(2,c);if(h.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(u)}},hexFromSig(t){const{_tlv:e,_int:n}=mt,r=e.encode(2,n.encode(t.r)),i=e.encode(2,n.encode(t.s)),s=r+i;return e.encode(48,s)}},yt=BigInt(0),An=BigInt(1),Kd=BigInt(2),Hr=BigInt(3),hb=BigInt(4);function En(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let i=re("private key",e);try{r=t.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof e}`)}}if(!t.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function fb(t,e={}){const n=Fd("weierstrass",t,e),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:a}=s;Tr(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!r.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=Jd(r,i);function h(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(L,C,E){const{x:D,y:T}=C.toAffine(),W=r.toBytes(D);if(cn(E,"isCompressed"),E){h();const B=!r.isOdd(T);return nt(zd(B),W)}else return nt(Uint8Array.of(4),W,r.toBytes(T))}function l(L){Qe(L,void 0,"Point");const{publicKey:C,publicKeyUncompressed:E}=u,D=L.length,T=L[0],W=L.subarray(1);if(D===C&&(T===2||T===3)){const B=r.fromBytes(W);if(!r.isValid(B))throw new Error("bad point: is not on curve, wrong x");const M=b(B);let P;try{P=r.sqrt(M)}catch(se){const Y=se instanceof Error?": "+se.message:"";throw new Error("bad point: is not on curve, sqrt error"+Y)}h();const U=r.isOdd(P);return(T&1)===1!==U&&(P=r.neg(P)),{x:B,y:P}}else if(D===E&&T===4){const B=r.BYTES,M=r.fromBytes(W.subarray(0,B)),P=r.fromBytes(W.subarray(B,B*2));if(!v(M,P))throw new Error("bad point: is not on curve");return{x:M,y:P}}else throw new Error(`bad point: got length ${D}, expected compressed=${C} or uncompressed=${E}`)}const m=e.toBytes||f,p=e.fromBytes||l;function b(L){const C=r.sqr(L),E=r.mul(C,L);return r.add(r.add(E,r.mul(L,s.a)),s.b)}function v(L,C){const E=r.sqr(C),D=b(L);return r.eql(E,D)}if(!v(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const w=r.mul(r.pow(s.a,Hr),hb),g=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(w,g)))throw new Error("bad curve params: a or b");function y(L,C,E=!1){if(!r.isValid(C)||E&&r.is0(C))throw new Error(`bad point coordinate ${L}`);return C}function k(L){if(!(L instanceof O))throw new Error("ProjectivePoint expected")}function x(L){if(!c||!c.basises)throw new Error("no endo");return ub(L,c.basises,i.ORDER)}const N=di((L,C)=>{const{X:E,Y:D,Z:T}=L;if(r.eql(T,r.ONE))return{x:E,y:D};const W=L.is0();C==null&&(C=W?r.ONE:r.inv(T));const B=r.mul(E,C),M=r.mul(D,C),P=r.mul(T,C);if(W)return{x:r.ZERO,y:r.ZERO};if(!r.eql(P,r.ONE))throw new Error("invZ was invalid");return{x:B,y:M}}),A=di(L=>{if(L.is0()){if(e.allowInfinityPoint&&!r.is0(L.Y))return;throw new Error("bad point: ZERO")}const{x:C,y:E}=L.toAffine();if(!r.isValid(C)||!r.isValid(E))throw new Error("bad point: x or y not field elements");if(!v(C,E))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function S(L,C,E,D,T){return E=new O(r.mul(E.X,L),E.Y,E.Z),C=ui(D,C),E=ui(T,E),C.add(E)}class O{constructor(C,E,D){this.X=y("x",C),this.Y=y("y",E,!0),this.Z=y("z",D),Object.freeze(this)}static CURVE(){return s}static fromAffine(C){const{x:E,y:D}=C||{};if(!C||!r.isValid(E)||!r.isValid(D))throw new Error("invalid affine point");if(C instanceof O)throw new Error("projective point not allowed");return r.is0(E)&&r.is0(D)?O.ZERO:new O(E,D,r.ONE)}static fromBytes(C){const E=O.fromAffine(p(Qe(C,void 0,"point")));return E.assertValidity(),E}static fromHex(C){return O.fromBytes(re("pointHex",C))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(C=8,E=!0){return q.createCache(this,C),E||this.multiply(Hr),this}assertValidity(){A(this)}hasEvenY(){const{y:C}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(C)}equals(C){k(C);const{X:E,Y:D,Z:T}=this,{X:W,Y:B,Z:M}=C,P=r.eql(r.mul(E,M),r.mul(W,T)),U=r.eql(r.mul(D,M),r.mul(B,T));return P&&U}negate(){return new O(this.X,r.neg(this.Y),this.Z)}double(){const{a:C,b:E}=s,D=r.mul(E,Hr),{X:T,Y:W,Z:B}=this;let M=r.ZERO,P=r.ZERO,U=r.ZERO,V=r.mul(T,T),se=r.mul(W,W),Y=r.mul(B,B),_=r.mul(T,W);return _=r.add(_,_),U=r.mul(T,B),U=r.add(U,U),M=r.mul(C,U),P=r.mul(D,Y),P=r.add(M,P),M=r.sub(se,P),P=r.add(se,P),P=r.mul(M,P),M=r.mul(_,M),U=r.mul(D,U),Y=r.mul(C,Y),_=r.sub(V,Y),_=r.mul(C,_),_=r.add(_,U),U=r.add(V,V),V=r.add(U,V),V=r.add(V,Y),V=r.mul(V,_),P=r.add(P,V),Y=r.mul(W,B),Y=r.add(Y,Y),V=r.mul(Y,_),M=r.sub(M,V),U=r.mul(Y,se),U=r.add(U,U),U=r.add(U,U),new O(M,P,U)}add(C){k(C);const{X:E,Y:D,Z:T}=this,{X:W,Y:B,Z:M}=C;let P=r.ZERO,U=r.ZERO,V=r.ZERO;const se=s.a,Y=r.mul(s.b,Hr);let _=r.mul(E,W),oe=r.mul(D,B),pe=r.mul(T,M),Ce=r.add(E,D),ae=r.add(W,B);Ce=r.mul(Ce,ae),ae=r.add(_,oe),Ce=r.sub(Ce,ae),ae=r.add(E,T);let xe=r.add(W,M);return ae=r.mul(ae,xe),xe=r.add(_,pe),ae=r.sub(ae,xe),xe=r.add(D,T),P=r.add(B,M),xe=r.mul(xe,P),P=r.add(oe,pe),xe=r.sub(xe,P),V=r.mul(se,ae),P=r.mul(Y,pe),V=r.add(P,V),P=r.sub(oe,V),V=r.add(oe,V),U=r.mul(P,V),oe=r.add(_,_),oe=r.add(oe,_),pe=r.mul(se,pe),ae=r.mul(Y,ae),oe=r.add(oe,pe),pe=r.sub(_,pe),pe=r.mul(se,pe),ae=r.add(ae,pe),_=r.mul(oe,ae),U=r.add(U,_),_=r.mul(xe,ae),P=r.mul(Ce,P),P=r.sub(P,_),_=r.mul(Ce,oe),V=r.mul(xe,V),V=r.add(V,_),new O(P,U,V)}subtract(C){return this.add(C.negate())}is0(){return this.equals(O.ZERO)}multiply(C){const{endo:E}=e;if(!i.isValidNot0(C))throw new Error("invalid scalar: out of range");let D,T;const W=B=>q.cached(this,B,M=>en(O,M));if(E){const{k1neg:B,k1:M,k2neg:P,k2:U}=x(C),{p:V,f:se}=W(M),{p:Y,f:_}=W(U);T=se.add(_),D=S(E.beta,V,Y,B,P)}else{const{p:B,f:M}=W(C);D=B,T=M}return en(O,[D,T])[0]}multiplyUnsafe(C){const{endo:E}=e,D=this;if(!i.isValid(C))throw new Error("invalid scalar: out of range");if(C===yt||D.is0())return O.ZERO;if(C===An)return D;if(q.hasCache(this))return this.multiply(C);if(E){const{k1neg:T,k1:W,k2neg:B,k2:M}=x(C),{p1:P,p2:U}=Fm(O,D,W,M);return S(E.beta,P,U,T,B)}else return q.unsafe(D,C)}multiplyAndAddUnsafe(C,E,D){const T=this.multiplyUnsafe(E).add(C.multiplyUnsafe(D));return T.is0()?void 0:T}toAffine(C){return N(this,C)}isTorsionFree(){const{isTorsionFree:C}=e;return o===An?!0:C?C(O,this):q.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:C}=e;return o===An?this:C?C(O,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(C=!0){return cn(C,"isCompressed"),this.assertValidity(),m(O,this,C)}toHex(C=!0){return sn(this.toBytes(C))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(C=!0){return this.toBytes(C)}_setWindowSize(C){this.precompute(C)}static normalizeZ(C){return en(O,C)}static msm(C,E){return qd(O,i,C,E)}static fromPrivateKey(C){return O.BASE.multiply(En(i,C))}}O.BASE=new O(s.Gx,s.Gy,r.ONE),O.ZERO=new O(r.ZERO,r.ONE,r.ZERO),O.Fp=r,O.Fn=i;const $=i.BITS,q=new Ud(O,e.endo?Math.ceil($/2):$);return O.BASE.precompute(8),O}function zd(t){return Uint8Array.of(t?2:3)}function Jd(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function pb(t,e={}){const{Fn:n}=t,r=e.randomBytes||oo,i=Object.assign(Jd(t.Fp,n),{seed:$d(n.ORDER)});function s(m){try{return!!En(n,m)}catch{return!1}}function o(m,p){const{publicKey:b,publicKeyUncompressed:v}=i;try{const w=m.length;return p===!0&&w!==b||p===!1&&w!==v?!1:!!t.fromBytes(m)}catch{return!1}}function a(m=r(i.seed)){return Bm(Qe(m,i.seed,"seed"),n.ORDER)}function c(m,p=!0){return t.BASE.multiply(En(n,m)).toBytes(p)}function u(m){const p=a(m);return{secretKey:p,publicKey:c(p)}}function h(m){if(typeof m=="bigint")return!1;if(m instanceof t)return!0;const{secretKey:p,publicKey:b,publicKeyUncompressed:v}=i;if(n.allowedLengths||p===b)return;const w=re("key",m).length;return w===b||w===v}function f(m,p,b=!0){if(h(m)===!0)throw new Error("first arg must be private key");if(h(p)===!1)throw new Error("second arg must be public key");const v=En(n,m);return t.fromHex(p).multiply(v).toBytes(b)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:u,Point:t,utils:{isValidSecretKey:s,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:m=>En(n,m),precompute(m=8,p=t.BASE){return p.precompute(m,!1)}},lengths:i})}function mb(t,e,n={}){bd(e),Tr(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||oo,i=n.hmac||((E,...D)=>Hd(e,E,nt(...D))),{Fp:s,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:u,getPublicKey:h,getSharedSecret:f,utils:l,lengths:m}=pb(t,n),p={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},b="compact";function v(E){const D=a>>An;return E>D}function w(E,D){if(!o.isValidNot0(D))throw new Error(`invalid signature ${E}: out of range 1..Point.Fn.ORDER`);return D}function g(E,D){Ps(D);const T=m.signature,W=D==="compact"?T:D==="recovered"?T+1:void 0;return Qe(E,W,`${D} signature`)}class y{constructor(D,T,W){this.r=w("r",D),this.s=w("s",T),W!=null&&(this.recovery=W),Object.freeze(this)}static fromBytes(D,T=b){g(D,T);let W;if(T==="der"){const{r:U,s:V}=mt.toSig(Qe(D));return new y(U,V)}T==="recovered"&&(W=D[0],T="compact",D=D.subarray(1));const B=o.BYTES,M=D.subarray(0,B),P=D.subarray(B,B*2);return new y(o.fromBytes(M),o.fromBytes(P),W)}static fromHex(D,T){return this.fromBytes(mr(D),T)}addRecoveryBit(D){return new y(this.r,this.s,D)}recoverPublicKey(D){const T=s.ORDER,{r:W,s:B,recovery:M}=this;if(M==null||![0,1,2,3].includes(M))throw new Error("recovery id invalid");if(a*Kd<T&&M>1)throw new Error("recovery id is ambiguous for h>1 curve");const U=M===2||M===3?W+a:W;if(!s.isValid(U))throw new Error("recovery id 2 or 3 invalid");const V=s.toBytes(U),se=t.fromBytes(nt(zd((M&1)===0),V)),Y=o.inv(U),_=x(re("msgHash",D)),oe=o.create(-_*Y),pe=o.create(B*Y),Ce=t.BASE.multiplyUnsafe(oe).add(se.multiplyUnsafe(pe));if(Ce.is0())throw new Error("point at infinify");return Ce.assertValidity(),Ce}hasHighS(){return v(this.s)}toBytes(D=b){if(Ps(D),D==="der")return mr(mt.hexFromSig(this));const T=o.toBytes(this.r),W=o.toBytes(this.s);if(D==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return nt(Uint8Array.of(this.recovery),T,W)}return nt(T,W)}toHex(D){return sn(this.toBytes(D))}assertValidity(){}static fromCompact(D){return y.fromBytes(re("sig",D),"compact")}static fromDER(D){return y.fromBytes(re("sig",D),"der")}normalizeS(){return this.hasHighS()?new y(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return sn(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return sn(this.toBytes("compact"))}}const k=n.bits2int||function(D){if(D.length>8192)throw new Error("input is too large");const T=Li(D),W=D.length*8-c;return W>0?T>>BigInt(W):T},x=n.bits2int_modN||function(D){return o.create(k(D))},N=Cr(c);function A(E){return Ms("num < 2^"+c,E,yt,N),o.toBytes(E)}function S(E,D){return Qe(E,void 0,"message"),D?Qe(e(E),void 0,"prehashed message"):E}function O(E,D,T){if(["recovered","canonical"].some(oe=>oe in T))throw new Error("sign() legacy options not supported");const{lowS:W,prehash:B,extraEntropy:M}=os(T,p);E=S(E,B);const P=x(E),U=En(o,D),V=[A(U),A(P)];if(M!=null&&M!==!1){const oe=M===!0?r(m.secretKey):M;V.push(re("extraEntropy",oe))}const se=nt(...V),Y=P;function _(oe){const pe=k(oe);if(!o.isValidNot0(pe))return;const Ce=o.inv(pe),ae=t.BASE.multiply(pe).toAffine(),xe=o.create(ae.x);if(xe===yt)return;const Lr=o.create(Ce*o.create(Y+xe*U));if(Lr===yt)return;let ea=(ae.x===xe?0:2)|Number(ae.y&An),ta=Lr;return W&&v(Lr)&&(ta=o.neg(Lr),ea^=1),new y(xe,ta,ea)}return{seed:se,k2sig:_}}function $(E,D,T={}){E=re("message",E);const{seed:W,k2sig:B}=O(E,D,T);return Om(e.outputLen,o.BYTES,i)(W,B)}function q(E){let D;const T=typeof E=="string"||Ar(E),W=!T&&E!==null&&typeof E=="object"&&typeof E.r=="bigint"&&typeof E.s=="bigint";if(!T&&!W)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(W)D=new y(E.r,E.s);else if(T){try{D=y.fromBytes(re("sig",E),"der")}catch(B){if(!(B instanceof mt.Err))throw B}if(!D)try{D=y.fromBytes(re("sig",E),"compact")}catch{return!1}}return D||!1}function L(E,D,T,W={}){const{lowS:B,prehash:M,format:P}=os(W,p);if(T=re("publicKey",T),D=S(re("message",D),M),"strict"in W)throw new Error("options.strict was renamed to lowS");const U=P===void 0?q(E):y.fromBytes(re("sig",E),P);if(U===!1)return!1;try{const V=t.fromBytes(T);if(B&&U.hasHighS())return!1;const{r:se,s:Y}=U,_=x(D),oe=o.inv(Y),pe=o.create(_*oe),Ce=o.create(se*oe),ae=t.BASE.multiplyUnsafe(pe).add(V.multiplyUnsafe(Ce));return ae.is0()?!1:o.create(ae.x)===se}catch{return!1}}function C(E,D,T={}){const{prehash:W}=os(T,p);return D=S(D,W),y.fromBytes(E,"recovered").recoverPublicKey(D).toBytes()}return Object.freeze({keygen:u,getPublicKey:h,getSharedSecret:f,utils:l,lengths:m,Point:t,sign:$,verify:L,recoverPublicKey:C,Signature:y,hash:e})}function bb(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp;let r=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const i=ct(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),s={Fp:n,Fn:i,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function wb(t){const{CURVE:e,curveOpts:n}=bb(t),r={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:n,hash:t.hash,ecdsaOpts:r}}function yb(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,Md(n.Fn.ORDER,n.Fn.BITS))})}function gb(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:i}=wb(t),s=fb(e,n),o=mb(s,r,i);return yb(t,o)}function Bi(t,e){const n=r=>gb({...t,hash:r});return{...n(e),create:n}}const mo={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Nb={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Ta=BigInt(2);function xb(t){const e=mo.p,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),u=t*t*t%e,h=u*u*t%e,f=ce(h,n,e)*h%e,l=ce(f,n,e)*h%e,m=ce(l,Ta,e)*u%e,p=ce(m,i,e)*m%e,b=ce(p,s,e)*p%e,v=ce(b,a,e)*b%e,w=ce(v,c,e)*v%e,g=ce(w,a,e)*b%e,y=ce(g,n,e)*h%e,k=ce(y,o,e)*p%e,x=ce(k,r,e)*u%e,N=ce(x,Ta,e);if(!$s.eql($s.sqr(N),t))throw new Error("Cannot find square root");return N}const $s=ct(mo.p,{sqrt:xb}),wr=Bi({...mo,Fp:$s,lowS:!0,endo:Nb},co);const Gd={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},Zd={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},Yd={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},vb=ct(Gd.p),Eb=ct(Zd.p),Db=ct(Yd.p),kb=Bi({...Gd,Fp:vb,lowS:!1},co),Sb=Bi({...Zd,Fp:Eb,lowS:!1},km),Ab=Bi({...Yd,Fp:Db,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},vd);const li=kb,Ob=co,Cb=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Qd=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),Tb=Qd.map(t=>(9*t+5)%16),Xd=(()=>{const n=[[Qd],[Tb]];for(let r=0;r<4;r++)for(let i of n)i.push(i[r].map(s=>Cb[s]));return n})(),eu=Xd[0],tu=Xd[1],nu=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(t=>Uint8Array.from(t)),Ib=eu.map((t,e)=>t.map(n=>nu[e][n])),Rb=tu.map((t,e)=>t.map(n=>nu[e][n])),Wb=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Mb=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function Ia(t,e,n,r){return t===0?e^n^r:t===1?e&n|~e&r:t===2?(e|~n)^r:t===3?e&r|n&~r:e^(n|~r)}const Kr=new Uint32Array(16);class Pb extends ao{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:e,h1:n,h2:r,h3:i,h4:s}=this;return[e,n,r,i,s]}set(e,n,r,i,s){this.h0=e|0,this.h1=n|0,this.h2=r|0,this.h3=i|0,this.h4=s|0}process(e,n){for(let m=0;m<16;m++,n+=4)Kr[m]=e.getUint32(n,!0);let r=this.h0|0,i=r,s=this.h1|0,o=s,a=this.h2|0,c=a,u=this.h3|0,h=u,f=this.h4|0,l=f;for(let m=0;m<5;m++){const p=4-m,b=Wb[m],v=Mb[m],w=eu[m],g=tu[m],y=Ib[m],k=Rb[m];for(let x=0;x<16;x++){const N=qr(r+Ia(m,s,a,u)+Kr[w[x]]+b,y[x])+f|0;r=f,f=u,u=qr(a,10)|0,a=s,s=N}for(let x=0;x<16;x++){const N=qr(i+Ia(p,o,c,h)+Kr[g[x]]+v,k[x])+l|0;i=l,l=h,h=qr(c,10)|0,c=o,o=N}}this.set(this.h1+a+h|0,this.h2+u+l|0,this.h3+f+i|0,this.h4+r+o|0,this.h0+s+c|0)}roundClean(){st(Kr)}destroy(){this.destroyed=!0,st(this.buffer),this.set(0,0,0,0,0)}}const $b=Or(()=>new Pb),ru=$b,Lb=BigInt(0),_n=BigInt(1),Bb=BigInt(2),Ub=BigInt(7),qb=BigInt(256),Fb=BigInt(113),iu=[],su=[],ou=[];for(let t=0,e=_n,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],iu.push(2*(5*r+n)),su.push((t+1)*(t+2)/2%64);let i=Lb;for(let s=0;s<7;s++)e=(e<<_n^(e>>Ub)*Fb)%qb,e&Bb&&(i^=_n<<(_n<<BigInt(s))-_n);ou.push(i)}const au=gd(ou,!0),Vb=au[0],_b=au[1],Ra=(t,e,n)=>n>32?hm(t,e,n):um(t,e,n),Wa=(t,e,n)=>n>32?fm(t,e,n):lm(t,e,n);function jb(t,e=24){const n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)n[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=n[c],h=n[c+1],f=Ra(u,h,1)^n[a],l=Wa(u,h,1)^n[a+1];for(let m=0;m<50;m+=10)t[o+m]^=f,t[o+m+1]^=l}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=su[o],c=Ra(i,s,a),u=Wa(i,s,a),h=iu[o];i=t[h],s=t[h+1],t[h]=c,t[h+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)n[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~n[(a+2)%10]&n[(a+4)%10]}t[0]^=Vb[r],t[1]^=_b[r]}st(n)}class bo extends so{constructor(e,n,r,i=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=i,this.rounds=s,pr(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=em(this.state)}clone(){return this._cloneInto()}keccak(){ua(this.state32),jb(this.state32,this.rounds),ua(this.state32),this.posOut=0,this.pos=0}update(e){Rn(this),e=$i(e),xt(e);const{blockLen:n,state:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);for(let a=0;a<o;a++)r[this.pos++]^=e[s++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:n,pos:r,blockLen:i}=this;e[r]^=n,(n&128)!==0&&r===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){Rn(this,!1),xt(e),this.finish();const n=this.state,{blockLen:r}=this;for(let i=0,s=e.length;i<s;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,s-i);e.set(n.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return pr(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(wd(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,st(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new bo(n,r,i,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=r,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Hb=(t,e,n)=>Or(()=>new bo(e,t,n)),Kb=Hb(1,136,256/8);var as,Ma;function zb(){return Ma||(Ma=1,as=function t(e){if(typeof e=="number"&&isNaN(e))throw new Error("NaN is not allowed");if(typeof e=="number"&&!isFinite(e))throw new Error("Infinity is not allowed");return e===null||typeof e!="object"?JSON.stringify(e):e.toJSON instanceof Function?t(e.toJSON()):Array.isArray(e)?`[${e.reduce((i,s,o)=>`${i}${o===0?"":","}${t(s===void 0||typeof s=="symbol"?null:s)}`,"")}]`:`{${Object.keys(e).sort().reduce((r,i)=>{if(e[i]===void 0||typeof e[i]=="symbol")return r;const s=r.length===0?"":",";return`${r}${s}${t(i)}:${t(e[i])}`},"")}}`}),as}var Jb=zb();const Gb=Zs(Jb);function Zb(t,e){try{var n=t()}catch(r){return e(r)}return n&&n.then?n.then(void 0,e):n}function Yb(){const t=new Map;return function(e,n){try{let i=function(o){if(r)return o;const a=t.get(e.didUrl);return a!==void 0?a:Promise.resolve(n()).then(function(c){var u;return((u=c.didResolutionMetadata)==null?void 0:u.error)!=="notFound"&&t.set(e.didUrl,c),c})},r;const s=(function(){if(e.params&&e.params["no-cache"]==="true")return Promise.resolve(n()).then(function(o){return r=1,o})})();return Promise.resolve(s&&s.then?s.then(i):i(s))}catch(r){return Promise.reject(r)}}}function Qb(t,e){return e()}const Xb="(?:%[0-9a-fA-F]{2})",Pa=`(?:[a-zA-Z0-9._-]|${Xb})`,ew="([a-z0-9]+)",tw=`((?:${Pa}*:)*(${Pa}+))`,$a="[a-zA-Z0-9_.:%-]",nw=`;${$a}+=${$a}*`,rw=`((${nw})*)`,iw="(/[^#?]*)?",sw="([?][^#]*)?",ow="(#.*)?",aw=new RegExp(`^did:${ew}:${tw}${rw}${iw}${sw}${ow}$`);function cu(t){if(t===""||!t)return null;const e=t.match(aw);if(e){const n={did:`did:${e[1]}:${e[2]}`,method:e[1],id:e[2],didUrl:t};if(e[4]){const r=e[4].slice(1).split(";");n.params={};for(const i of r){const s=i.split("=");n.params[s[0]]=s[1]}}return e[6]&&(n.path=e[6]),e[7]&&(n.query=e[7].slice(1)),e[8]&&(n.fragment=e[8].slice(1)),n}return null}const hi={didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}};function cw(t){return function(e,n,r){try{return Promise.resolve(Zb(function(){return Promise.resolve(t(e,n,r)).then(function(i){return{...hi,didResolutionMetadata:{contentType:"application/did+ld+json"},didDocument:i}})},function(i){return{...hi,didResolutionMetadata:{error:"notFound",message:i.toString()}}}))}catch(i){return Promise.reject(i)}}}class dw{constructor(e={},n={}){this.registry=void 0,this.cache=void 0,this.registry=e,this.cache=n.cache===!0?Yb():n.cache||Qb,n.legacyResolvers&&Object.keys(n.legacyResolvers).map(r=>{this.registry[r]||(this.registry[r]=cw(n.legacyResolvers[r]))})}resolve(e,n={}){try{const r=this,i=cu(e);if(i===null)return Promise.resolve({...hi,didResolutionMetadata:{error:"invalidDid"}});const s=r.registry[i.method];return s?Promise.resolve(r.cache(i,()=>s(i.did,i,r,n))):Promise.resolve({...hi,didResolutionMetadata:{error:"unsupportedDidMethod"}})}catch(r){return Promise.reject(r)}}}function du(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function uu(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(n=>typeof n=="string"):e.every(n=>Number.isSafeInteger(n)):!1}function uw(t){if(typeof t!="function")throw new Error("function expected");return!0}function yr(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function lu(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Ls(t){if(!Array.isArray(t))throw new Error("array expected")}function hu(t,e){if(!uu(!0,e))throw new Error(`${t}: array of strings expected`)}function fu(t,e){if(!uu(!1,e))throw new Error(`${t}: array of numbers expected`)}function lw(...t){const e=s=>s,n=(s,o)=>a=>s(o(a)),r=t.map(s=>s.encode).reduceRight(n,e),i=t.map(s=>s.decode).reduce(n,e);return{encode:r,decode:i}}function hw(t){const e=typeof t=="string"?t.split(""):t,n=e.length;hu("alphabet",e);const r=new Map(e.map((i,s)=>[i,s]));return{encode:i=>(Ls(i),i.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${t}`);return e[s]})),decode:i=>(Ls(i),i.map(s=>{yr("alphabet.decode",s);const o=r.get(s);if(o===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${t}`);return o}))}}function fw(t=""){return yr("join",t),{encode:e=>(hu("join.decode",e),e.join(t)),decode:e=>(yr("join.decode",e),e.split(t))}}const pu=(t,e)=>e===0?t:pu(e,t%e),fi=(t,e)=>t+(e-pu(t,e)),Xr=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Bs(t,e,n,r){if(Ls(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(fi(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${fi(e,n)}`);let i=0,s=0;const o=Xr[e],a=Xr[n]-1,c=[];for(const u of t){if(lu(u),u>=o)throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);if(i=i<<e|u,s+e>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${e}`);for(s+=e;s>=n;s-=n)c.push((i>>s-n&a)>>>0);const h=Xr[s];if(h===void 0)throw new Error("invalid carry");i&=h-1}if(i=i<<n-s&a,!r&&s>=e)throw new Error("Excess padding");if(!r&&i>0)throw new Error(`Non-zero padding: ${i}`);return r&&s>0&&c.push(i>>>0),c}function pw(t,e=!1){if(lu(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(fi(8,t)>32||fi(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!du(n))throw new Error("radix2.encode input should be Uint8Array");return Bs(Array.from(n),8,t,!e)},decode:n=>(fu("radix2.decode",n),Uint8Array.from(Bs(n,t,8,e)))}}function La(t){return uw(t),function(...e){try{return t.apply(null,e)}catch{}}}const Us=lw(hw("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),fw("")),Ba=[996825010,642813549,513874426,1027748829,705979059];function jn(t){const e=t>>25;let n=(t&33554431)<<5;for(let r=0;r<Ba.length;r++)(e>>r&1)===1&&(n^=Ba[r]);return n}function Ua(t,e,n=1){const r=t.length;let i=1;for(let s=0;s<r;s++){const o=t.charCodeAt(s);if(o<33||o>126)throw new Error(`Invalid prefix (${t})`);i=jn(i)^o>>5}i=jn(i);for(let s=0;s<r;s++)i=jn(i)^t.charCodeAt(s)&31;for(let s of e)i=jn(i)^s;for(let s=0;s<6;s++)i=jn(i);return i^=n,Us.encode(Bs([i%Xr[30]],30,5,!1))}function mw(t){const e=t==="bech32"?1:734539939,n=pw(5),r=n.decode,i=n.encode,s=La(r);function o(f,l,m=90){yr("bech32.encode prefix",f),du(l)&&(l=Array.from(l)),fu("bech32.encode",l);const p=f.length;if(p===0)throw new TypeError(`Invalid prefix length ${p}`);const b=p+7+l.length;if(m!==!1&&b>m)throw new TypeError(`Length ${b} exceeds limit ${m}`);const v=f.toLowerCase(),w=Ua(v,l,e);return`${v}1${Us.encode(l)}${w}`}function a(f,l=90){yr("bech32.decode input",f);const m=f.length;if(m<8||l!==!1&&m>l)throw new TypeError(`invalid string length: ${m} (${f}). Expected (8..${l})`);const p=f.toLowerCase();if(f!==p&&f!==f.toUpperCase())throw new Error("String must be lowercase or uppercase");const b=p.lastIndexOf("1");if(b===0||b===-1)throw new Error('Letter "1" must be present between prefix and data only');const v=p.slice(0,b),w=p.slice(b+1);if(w.length<6)throw new Error("Data must be at least 6 characters long");const g=Us.decode(w).slice(0,-6),y=Ua(v,g,e);if(!w.endsWith(y))throw new Error(`Invalid checksum in ${f}: expected "${y}"`);return{prefix:v,words:g}}const c=La(a);function u(f){const{prefix:l,words:m}=a(f,!1);return{prefix:l,words:m,bytes:r(m)}}function h(f,l){return o(f,i(l))}return{encode:o,decode:a,encodeFromBytes:h,decodeToBytes:u,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:s,toWords:i}}const qa=mw("bech32"),He={toString:io,fromString:Pi,concat:ed};function wo(t){return He.toString(t,"base64url")}function Ve(t){const e=t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return He.fromString(e,"base64url")}function mu(t){return He.fromString(t,"base58btc")}function bw(t){return He.toString(t,"base58btc")}const ww={ES256:["JsonWebKey2020","Multikey","EcdsaSecp256r1VerificationKey2019"],ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","JsonWebKey2020","Multikey"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","ConditionalProof2022","JsonWebKey2020","Multikey"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018","Ed25519VerificationKey2020","JsonWebKey2020","Multikey"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018","Ed25519VerificationKey2020","JsonWebKey2020","Multikey"]},zr={Secp256k1SignatureVerificationKey2018:"Secp256k1",Secp256k1VerificationKey2018:"Secp256k1",EcdsaSecp256k1VerificationKey2019:"Secp256k1",EcdsaPublicKeySecp256k1:"Secp256k1",EcdsaSecp256k1RecoveryMethod2020:"Secp256k1",EcdsaSecp256r1VerificationKey2019:"P-256",Ed25519VerificationKey2018:"Ed25519",Ed25519VerificationKey2020:"Ed25519",ED25519SignatureVerification:"Ed25519",X25519KeyAgreementKey2019:"X25519",X25519KeyAgreementKey2020:"X25519",ConditionalProof2022:void 0,JsonWebKey2020:void 0,Multikey:void 0},yw={"ed25519-pub":237,"x25519-pub":236,"secp256k1-pub":231,"bls12_381-g1-pub":234,"bls12_381-g2-pub":235,"p256-pub":4608},gw={"bls12_381-g1-pub":"Bls12381G1","bls12_381-g2-pub":"Bls12381G2","ed25519-pub":"Ed25519","p256-pub":"P-256","secp256k1-pub":"Secp256k1","x25519-pub":"X25519"};function Ui(t){if(t.publicKeyBase58)return{keyBytes:mu(t.publicKeyBase58),keyType:zr[t.type]};if(t.publicKeyBase64)return{keyBytes:Ve(t.publicKeyBase64),keyType:zr[t.type]};if(t.publicKeyHex)return{keyBytes:ei(t.publicKeyHex),keyType:zr[t.type]};if(t.publicKeyJwk&&t.publicKeyJwk.crv==="secp256k1"&&t.publicKeyJwk.x&&t.publicKeyJwk.y)return{keyBytes:wr.ProjectivePoint.fromAffine({x:Jr(Ve(t.publicKeyJwk.x)),y:Jr(Ve(t.publicKeyJwk.y))}).toRawBytes(!1),keyType:"Secp256k1"};if(t.publicKeyJwk&&t.publicKeyJwk.crv==="P-256"&&t.publicKeyJwk.x&&t.publicKeyJwk.y)return{keyBytes:li.ProjectivePoint.fromAffine({x:Jr(Ve(t.publicKeyJwk.x)),y:Jr(Ve(t.publicKeyJwk.y))}).toRawBytes(!1),keyType:"P-256"};if(t.publicKeyJwk&&t.publicKeyJwk.kty==="OKP"&&["Ed25519","X25519"].includes(t.publicKeyJwk.crv??"")&&t.publicKeyJwk.x)return{keyBytes:Ve(t.publicKeyJwk.x),keyType:t.publicKeyJwk.crv};if(t.publicKeyMultibase){const{keyBytes:e,keyType:n}=Nw(t.publicKeyMultibase);return{keyBytes:e,keyType:n??zr[t.type]}}return{keyBytes:new Uint8Array}}function Nw(t){const e=db.decode(t);if([32,33,48,64,65,96].includes(e.length))return{keyBytes:e};try{const[n,r]=ur(e),i=Object.entries(yw).filter(([,s])=>s===n)?.[0][0]??"";return{keyBytes:e.slice(r),keyType:gw[i]}}catch{return{keyBytes:e}}}function ei(t,e){let n=t.startsWith("0x")?t.substring(2):t;return n.length%2!==0&&(n=`0${n}`),He.fromString(n.toLowerCase(),"base16")}function Fa(t){return wo(He.fromString(t))}function bu(t){return He.toString(Ve(t))}function Vt(t){return He.toString(t,"base16")}function Jr(t){return BigInt("0x"+He.toString(t,"base16"))}function xw(t){return He.fromString(t,"utf-8")}function wu({r:t,s:e,recoveryParam:n},r){const i=new Uint8Array(r?65:64);if(i.set(He.fromString(t,"base16"),0),i.set(He.fromString(e,"base16"),32),r){if(typeof n>"u")throw new Error("Signer did not return a recoveryParam");i[64]=n}return wo(i)}function vw(t){const e=Ve(t);if(e.length<64||e.length>65)throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${e.length}`);const n=Vt(e.slice(0,32)),r=Vt(e.slice(32,64)),i=e.length===65?e[64]:void 0;return{r:n,s:r,recoveryParam:i}}function on(t){const e=typeof t=="string"?Pi(t):t;return Ob(e)}const Ew=Kb;function yu(t){const e=Pi(t.slice(2),"base16");return`0x${io(Ew(e).slice(-20),"base16")}`}function yo(t){return typeof t=="object"&&"r"in t&&"s"in t}function Dw(){return function(e,n){try{return Promise.resolve(n(e)).then(function(r){return yo(r)?wu(r):r})}catch(r){return Promise.reject(r)}}}function Va(t){return function(n,r){try{return Promise.resolve(r(n)).then(function(i){if(yo(i))return wu(i,t);if(t&&typeof vw(i).recoveryParam>"u")throw new Error("not_supported: ES256K-R not supported when signer doesn't provide a recovery param");return i})}catch(i){return Promise.reject(i)}}}function _a(){return function(e,n){try{return Promise.resolve(n(e)).then(function(r){if(yo(r))throw new Error("invalid_config: expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}const kw={ES256:Dw(),ES256K:Va(),"ES256K-R":Va(!0),Ed25519:_a(),EdDSA:_a()};function Sw(t){const e=kw[t];if(!e)throw new Error(`not_supported: Unsupported algorithm ${t}`);return e}function Aw(t,e){const n=Vt(mu(e).slice(0,1)),r=ei(t),i=ru(on(r)),s=n+Vt(i),o=on(ei(s)),a=on(o),c=Vt(a).substring(0,8),u=s+c;return bw(ei(u))}function Ow(t,e){const n=wr.ProjectivePoint.fromHex(t).toRawBytes(),r=ru(on(n)),i=qa.toWords(r);return qa.encode(e,i).replace(e,"")}function Cw(t,e){if(e){const n=e.split(":");switch(n[0]){case"bip122":n[n.length-1]=Aw(t,n[n.length-1]);break;case"cosmos":n[n.length-1]=Ow(t,n[1]);break;case"eip155":n[n.length-1]=yu(t);break;default:return!1}return n.join(":").toLowerCase()===e.toLowerCase()}return!1}function Tw(t,e=!1){const n=Ve(t);if(n.length!==(e?65:64))throw new Error("wrong signature length");const r=Vt(n.slice(0,32)),i=Vt(n.slice(32,64)),s={r,s:i};return e&&(s.recoveryParam=n[64]),s}function qs(t,e=!1){const n=Ve(t);if(n.length!==(e?65:64))throw new Error("wrong signature length");return{compact:n.slice(0,64),recovery:n[64]}}function Iw(t,e,n){const r=on(t),i=li.Signature.fromCompact(qs(e).compact),o=n.filter(a=>!a.ethereumAddress&&!a.blockchainAccountId).find(a=>{try{const{keyBytes:c}=Ui(a);return li.verify(i,r,c)}catch{return!1}});if(!o)throw new Error("invalid_signature: Signature invalid for JWT");return o}function Rw(t,e,n){const r=on(t),i=wr.Signature.fromCompact(Ve(e)).normalizeS(),s=n.filter(c=>!c.ethereumAddress&&!c.blockchainAccountId),o=n.filter(c=>c.ethereumAddress||c.blockchainAccountId);let a=s.find(c=>{try{const{keyBytes:u}=Ui(c);return wr.verify(i,r,u)}catch{return!1}});if(!a&&o.length>0&&(a=gu(t,e,o)),!a)throw new Error("invalid_signature: Signature invalid for JWT");return a}function gu(t,e,n){const r=[];if(e.length>86)r.push(qs(e,!0));else{const o=qs(e,!1);r.push({...o,recovery:0}),r.push({...o,recovery:1})}const i=on(t),s=o=>{const c=wr.Signature.fromCompact(o.compact).addRecoveryBit(o.recovery||0).recoverPublicKey(i),u=yu(c.toHex(!1)).toLowerCase(),h=c.toHex(!1),f=c.toHex(!0);return n.find(l=>{const{keyBytes:m}=Ui(l),p=Vt(m);return p===h||p===f||l.ethereumAddress?.toLowerCase()===u||l.blockchainAccountId?.split("@eip155")?.[0].toLowerCase()===u||Cw(h,l.blockchainAccountId)})};for(const o of r){const a=s(o);if(a)return a}throw new Error("invalid_signature: Signature invalid for JWT")}function ja(t,e,n){const r=xw(t),i=Ve(e),s=n.find(o=>{const{keyBytes:a,keyType:c}=Ui(o);return c==="Ed25519"?_d.verify(i,r,a):!1});if(!s)throw new Error("invalid_signature: Signature invalid for JWT");return s}const Ww={ES256:Iw,ES256K:Rw,"ES256K-R":gu,Ed25519:ja,EdDSA:ja};function Nu(t){const e=Ww[t];if(!e)throw new Error(`not_supported: Unsupported algorithm ${t}`);return e}Nu.toSignatureObject=Tw;const J={INVALID_JWT:"invalid_jwt",INVALID_AUDIENCE:"invalid_config",INVALID_SIGNATURE:"invalid_signature",NO_SUITABLE_KEYS:"no_suitable_keys",NOT_SUPPORTED:"not_supported",RESOLVER_ERROR:"resolver_error"};function Mw(t,e){try{var n=t()}catch(r){return e(r)}return n&&n.then?n.then(void 0,e):n}const Pw=function(t,{header:e,payload:n,data:r,signature:i},s,o){try{if(!s.conditionDelegated)throw new Error("Expected conditionDelegated");if(!o.resolver)throw new Error("Expected resolver");let a;const c=s.conditionDelegated;return Promise.resolve(vu(o.resolver,e.alg,c,o.proofPurpose)).then(function(u){let h;function f(b){if(a)return s;throw new Error(`${J.INVALID_SIGNATURE}: condition for authenticator ${s.id} is not met.`)}const l=u.didResolutionResult;if(!l?.didDocument)throw new Error(`${J.RESOLVER_ERROR}: Could not resolve delegated DID ${c}.`);const m=u.authenticators.find(b=>b.id===c);if(!m)throw new Error(`${J.NO_SUITABLE_KEYS}: Could not find delegated authenticator ${c} in it's DID Document`);const p=(function(){if(m.type===go)return Promise.resolve(No(t,{...o,didAuthenticator:{didResolutionResult:l,authenticators:[m],issuer:m.id}})).then(function({verified:b}){b&&(a=m)});try{a=xo({header:e,payload:n,data:r,signature:i},m)}catch(b){if(!b.message.startsWith("invalid_signature:"))throw b}})();return p&&p.then?p.then(f):f(p)})}catch(a){return Promise.reject(a)}},Ha=typeof Symbol<"u"?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function Se(t,e,n){if(!t.s){if(n instanceof Mn)if(n.s)e&1&&(e=n.s),n=n.v;else{n.o=Se.bind(null,t,e);return}if(n&&n.then){n.then(Se.bind(null,t,e),Se.bind(null,t,2));return}t.s=e,t.v=n;const r=t.o;r&&r(t)}}const Mn=(function(){function t(){}return t.prototype.then=function(e,n){const r=new t,i=this.s;if(i){const s=i&1?e:n;if(s){try{Se(r,1,s(this.v))}catch(o){Se(r,2,o)}return r}else return this}return this.o=function(s){try{const o=s.v;s.s&1?Se(r,1,e?e(o):o):n?Se(r,1,n(o)):Se(r,2,o)}catch(o){Se(r,2,o)}},r},t})();function xu(t){return t instanceof Mn&&t.s&1}function $w(t,e,n){var r=-1,i,s;function o(a){try{for(;++r<t.length&&(!n||!n());)if(a=e(r),a&&a.then)if(xu(a))a=a.v;else{a.then(o,s||(s=Se.bind(null,i=new Mn,2)));return}i?Se(i,1,a):i=a}catch(c){Se(i||(i=new Mn),2,c)}}return o(),i}const Lw=function(t,{header:e,payload:n,data:r,signature:i},s,o){try{let a=function(m){if(c)return m;throw new Error(`${J.INVALID_SIGNATURE}: condition for authenticator ${s.id} is not met.`)},c;if(!s.conditionWeightedThreshold||!s.threshold)throw new Error("Expected conditionWeightedThreshold and threshold");const u=[],h=s.threshold;let f=0;const l=Bw(s.conditionWeightedThreshold,function(m){function p(g){if(c)return g;if(v&&!u.includes(v.id)&&(u.push(v.id),f+=m.weight,f>=h))return c=1,s}const b=m.condition;let v;const w=Mw(function(){if(b.type===go){if(!o.didAuthenticator)throw new Error("Expected didAuthenticator");const g={...o,didAuthenticator:{didResolutionResult:o.didAuthenticator?.didResolutionResult,authenticators:[b],issuer:b.id}};return Promise.resolve(No(t,g)).then(function({verified:y}){y&&(v=b)})}else return Promise.resolve(xo({header:e,payload:n,data:r,signature:i},b)).then(function(g){v=g})},function(g){if(!g.message.startsWith(J.INVALID_SIGNATURE))throw g});return w&&w.then?w.then(p):p(w)},function(){return c});return Promise.resolve(l&&l.then?l.then(a):a(l))}catch(a){return Promise.reject(a)}};function Bw(t,e,n){if(typeof t[Ha]=="function"){let h=function(f){try{for(;!(i=r.next()).done&&(!n||!n());)if(f=e(i.value),f&&f.then)if(xu(f))f=f.v;else{f.then(h,o||(o=Se.bind(null,s=new Mn,2)));return}s?Se(s,1,f):s=f}catch(l){Se(s||(s=new Mn),2,l)}};var r=t[Ha](),i,s,o;if(h(),r.return){var a=function(f){try{i.done||r.return()}catch{}return f};if(s&&s.then)return s.then(a,function(f){throw a(f)});a()}return s}if(!("length"in t))throw new TypeError("Object is not iterable");for(var c=[],u=0;u<t.length;u++)c.push(t[u]);return $w(c,function(h){return e(c[h])},n)}const Uw=function(t,{header:e,payload:n,signature:r,data:i},s,o){try{if(s.conditionWeightedThreshold)return Lw(t,{header:e,payload:n,data:i,signature:r},s,o);if(s.conditionDelegated)return Pw(t,{header:e,payload:n,data:i,signature:r},s,o);throw new Error(`${J.INVALID_JWT}: conditional proof type did not find condition for authenticator ${s.id}.`)}catch(a){return Promise.reject(a)}},Ka=function(t,{header:e,payload:n,signature:r,data:i},s,o){try{return s.type===go?Uw(t,{payload:n,header:e,signature:r,data:i},s,o):Promise.resolve(xo({header:e,payload:n,data:i,signature:r},[s]))}catch(a){return Promise.reject(a)}},go="ConditionalProof2022";function ke(t,e,n){if(!t.s){if(n instanceof gr)if(n.s)e&1&&(e=n.s),n=n.v;else{n.o=ke.bind(null,t,e);return}if(n&&n.then){n.then(ke.bind(null,t,e),ke.bind(null,t,2));return}t.s=e,t.v=n;const r=t.o;r&&r(t)}}const gr=(function(){function t(){}return t.prototype.then=function(e,n){const r=new t,i=this.s;if(i){const s=i&1?e:n;if(s){try{ke(r,1,s(this.v))}catch(o){ke(r,2,o)}return r}else return this}return this.o=function(s){try{const o=s.v;s.s&1?ke(r,1,e?e(o):o):n?ke(r,1,n(o)):ke(r,2,o)}catch(o){ke(r,2,o)}},r},t})();function Gn(t){return t instanceof gr&&t.s&1}function qw(t,e,n){var r=-1,i,s;function o(a){try{for(;++r<t.length&&(!n||!n());)if(a=e(r),a&&a.then)if(Gn(a))a=a.v;else{a.then(o,s||(s=ke.bind(null,i=new gr,2)));return}i?ke(i,1,a):i=a}catch(c){ke(i||(i=new gr),2,c)}}return o(),i}function Fw(t,e){try{var n=t()}catch(r){return e(r)}return n&&n.then?n.then(void 0,e):n}function Vw(t,e,n){for(var r;;){var i=t();if(Gn(i)&&(i=i.v),!i)return s;if(i.then){r=0;break}var s=n();if(s&&s.then)if(Gn(s))s=s.s;else{r=1;break}var o}var a=new gr,c=ke.bind(null,a,2);return(r===0?i.then(h):r===1?s.then(u):o.then(f)).then(void 0,c),a;function u(l){s=l;do{if(i=t(),!i||Gn(i)&&!i.v){ke(a,1,s);return}if(i.then){i.then(h).then(void 0,c);return}s=n(),Gn(s)&&(s=s.v)}while(!s||!s.then);s.then(u).then(void 0,c)}function h(l){l?(s=n(),s&&s.then?s.then(u).then(void 0,c):u(s)):ke(a,1,s)}function f(){(i=t())?i.then?i.then(h).then(void 0,c):h(i):ke(a,1,s)}}const vu=function(t,e,n,r){try{const i=ww[e];if(!i||i.length===0)throw new Error(`${J.NOT_SUPPORTED}: No supported signature types for algorithm ${e}`);let s;return Promise.resolve(t.resolve(n,{accept:za})).then(function(o){if(Object.getOwnPropertyNames(o).indexOf("didDocument")===-1?s={didDocument:o,didDocumentMetadata:{},didResolutionMetadata:{contentType:za}}:s=o,s.didResolutionMetadata?.error||s.didDocument==null){const{error:h,message:f}=s.didResolutionMetadata;throw new Error(`${J.RESOLVER_ERROR}: Unable to resolve DID document for ${n}: ${h}, ${f||""}`)}const a=(h,f)=>{const l=h.filter(({id:m})=>f===m);return l.length>0?l[0]:null};let c=[...s?.didDocument?.verificationMethod||[],...s?.didDocument?.publicKey||[]];typeof r=="string"&&(r.startsWith("assertion")&&!Object.getOwnPropertyNames(s?.didDocument).includes("assertionMethod")&&(s.didDocument={...s.didDocument},s.didDocument.assertionMethod=[...c.map(h=>h.id)]),c=(s.didDocument[r]||[]).map(h=>typeof h=="string"?a(c,h):typeof h.publicKey=="string"?a(c,h.publicKey):h).filter(h=>h!=null));const u=c.filter(({type:h})=>i.find(f=>f===h));if(typeof r=="string"&&(!u||u.length===0))throw new Error(`${J.NO_SUITABLE_KEYS}: DID document for ${n} does not have public keys suitable for ${e} with ${r} purpose`);if(!u||u.length===0)throw new Error(`${J.NO_SUITABLE_KEYS}: DID document for ${n} does not have public keys for ${e}`);return{authenticators:u,issuer:n,didResolutionResult:s}})}catch(i){return Promise.reject(i)}},No=function(t,e={resolver:void 0,auth:void 0,audience:void 0,callbackUrl:void 0,skewTime:void 0,proofPurpose:void 0,policies:{},didAuthenticator:void 0}){try{let n=function(){let m;function p(g){if(v){const y=typeof e.policies?.now=="number"?e.policies.now:Math.floor(Date.now()/1e3),k=typeof e.skewTime<"u"&&e.skewTime>=0?e.skewTime:Gw,x=y+k;if(e.policies?.nbf!==!1&&r.nbf){if(r.nbf>x)throw new Error(`${J.INVALID_JWT}: JWT not valid before nbf: ${r.nbf}`)}else if(e.policies?.iat!==!1&&r.iat&&r.iat>x)throw new Error(`${J.INVALID_JWT}: JWT not valid yet (issued in the future) iat: ${r.iat}`);if(e.policies?.exp!==!1&&r.exp&&r.exp<=y-k)throw new Error(`${J.INVALID_JWT}: JWT has expired: exp: ${r.exp} < now: ${y}`);if(e.policies?.aud!==!1&&r.aud){if(!e.audience&&!e.callbackUrl)throw new Error(`${J.INVALID_AUDIENCE}: JWT audience is required but your app address has not been configured`);if(typeof(Array.isArray(r.aud)?r.aud:[r.aud]).find(S=>e.audience===S||e.callbackUrl===S)>"u")throw new Error(`${J.INVALID_AUDIENCE}: JWT audience does not match your DID or callback url`)}return{verified:!0,payload:r,didResolutionResult:f,issuer:h,signer:v,jwt:t,policies:e.policies}}throw new Error(`${J.INVALID_SIGNATURE}: JWT not valid. issuer DID document does not contain a verificationMethod that matches the signature.`)}const{did:b}=cu(c);let v=null;const w=(function(){if(b!==c){const g=u.find(y=>y.id===c);if(!g)throw new Error(`${J.INVALID_JWT}: No authenticator found for did URL ${c}`);return Promise.resolve(Ka(t,{payload:r,header:i,signature:s,data:o},g,e)).then(function(y){v=y})}else{let g=0;return Vw(function(){return!m&&!v&&g<u.length},void 0,function(){function y(N){g++}const k=u[g],x=Fw(function(){return Promise.resolve(Ka(t,{payload:r,header:i,signature:s,data:o},k,e)).then(function(N){v=N})},function(N){if(!N.message.includes(J.INVALID_SIGNATURE)||g===u.length-1)throw N});return x&&x.then?x.then(y):y(x)})}})();return w&&w.then?w.then(p):p(w)};if(!e.resolver)throw new Error("missing_resolver: No DID resolver has been configured");const{payload:r,header:i,signature:s,data:o}=qi(t,!1),a=Object.prototype.hasOwnProperty.call(e,"auth")?e.auth?"authentication":void 0:e.proofPurpose;let c;if(!r.iss&&!r.client_id)throw new Error(`${J.INVALID_JWT}: JWT iss or client_id are required`);if(e.didAuthenticator)c=e.didAuthenticator.issuer;else if(r.iss===Hw||r.iss===Kw){if(!r.sub)throw new Error(`${J.INVALID_JWT}: JWT sub is required`);typeof r.sub_jwk>"u"?c=r.sub:c=(i.kid||"").split("#")[0]}else if(r.iss===zw){if(!r.did)throw new Error(`${J.INVALID_JWT}: JWT did is required`);c=r.did}else if(!r.iss&&r.scope==="openid"&&r.redirect_uri){if(!r.client_id)throw new Error(`${J.INVALID_JWT}: JWT client_id is required`);c=r.client_id}else c=r.iss;if(!c)throw new Error(`${J.INVALID_JWT}: No DID has been found in the JWT`);let u,h,f;const l=(function(){if(e.didAuthenticator)({didResolutionResult:f,authenticators:u,issuer:h}=e.didAuthenticator);else return Promise.resolve(vu(e.resolver,i.alg,c,a)).then(function(m){({didResolutionResult:f,authenticators:u,issuer:h}=m),e.didAuthenticator={didResolutionResult:f,authenticators:u,issuer:h}})})();return Promise.resolve(l&&l.then?l.then(n):n(l))}catch(n){return Promise.reject(n)}},_w=function(t,{expiresIn:e,canonicalize:n},r){try{if(r.length===0)throw new Error("invalid_argument: must provide one or more issuers");let i=t,s="";const o=qw(r,function(a){const c=r[a],u={typ:"JWT",alg:c.alg};return a!==0&&(u.cty="JWT"),Promise.resolve(Eu(i,{...c,canonicalize:n,expiresIn:e},u)).then(function(h){s=h,i={jwt:s}})});return Promise.resolve(o&&o.then?o.then(function(){return s}):s)}catch(i){return Promise.reject(i)}},Eu=function(t,{issuer:e,signer:n,alg:r,expiresIn:i,canonicalize:s},o={}){try{if(!n)throw new Error("missing_signer: No Signer functionality has been configured");if(!e)throw new Error("missing_issuer: No issuing DID has been configured");o.typ||(o.typ="JWT"),o.alg||(o.alg=r);const a={iat:Math.floor(Date.now()/1e3),exp:void 0};if(i)if(typeof i=="number")a.exp=(t.nbf||a.iat)+Math.floor(i);else throw new Error("invalid_argument: JWT expiresIn is not a number");const c={...a,...t,iss:e};return jw(c,n,o,{canonicalize:s})}catch(a){return Promise.reject(a)}},jw=function(t,e,n={},r={}){try{n.alg||(n.alg=Jw);const i=typeof t=="string"?t:Ja(t,r.canonicalize),s=[Ja(n,r.canonicalize),i].join("."),o=Sw(n.alg);return Promise.resolve(o(s,e)).then(function(a){return[s,a].join(".")})}catch(i){return Promise.reject(i)}},Hw="https://self-issued.me/v2",Kw="https://self-issued.me/v2/openid-vc",zw="https://self-issued.me",Jw="ES256K",za="application/did+json";function Ja(t,e=!1){return Fa(e?Gb(t):JSON.stringify(t))}const Gw=300;function Zw(t){const e=t.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(bu(e[1])),payload:e[2],signature:e[3],data:`${e[1]}.${e[2]}`};throw new Error("invalid_argument: Incorrect format JWS")}function qi(t,e=!0){if(!t)throw new Error("invalid_argument: no JWT passed into decodeJWT");try{const n=Zw(t),r=Object.assign(n,{payload:JSON.parse(bu(n.payload))}),i=r.payload.iss;if(r.header.cty==="JWT"&&e){const s=qi(r.payload.jwt);if(s.payload.iss!==i)throw new Error(`${J.INVALID_JWT}: multiple issuers`);return s}return r}catch(n){throw new Error(`invalid_argument: ${J.INVALID_JWT}: ${n}`)}}function xo({header:t,payload:e,data:n,signature:r},i){Array.isArray(i)||(i=[i]);const s=e.iss;let o=!0;do{if(s!==e.iss)throw new Error(`${J.INVALID_JWT}: multiple issuers`);try{return Nu(t.alg)(n,r,i)}catch(a){if(!a.message.startsWith(J.INVALID_SIGNATURE))throw a}t.cty!=="JWT"?o=!1:{payload:e,header:t,signature:r,data:n}=qi(e.jwt,!1)}while(o);throw new Error(`${J.INVALID_SIGNATURE}: no matching public key found`)}typeof Symbol<"u"&&(Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")));var cs,Ga;function Yw(){if(Ga)return cs;Ga=1;function t(e,n){for(let r=0;r<e.byteLength;r++){if(e[r]<n[r])return-1;if(e[r]>n[r])return 1}return e.byteLength>n.byteLength?1:e.byteLength<n.byteLength?-1:0}return cs=t,cs}var ds,Za;function Qw(){if(Za)return ds;Za=1;function t(e,n){n||(n=e.reduce((s,o)=>s+o.length,0));const r=new Uint8Array(n);let i=0;for(const s of e)r.set(s,i),i+=s.length;return r}return ds=t,ds}var us,Ya;function Xw(){if(Ya)return us;Ya=1;function t(e,n){if(e===n)return!0;if(e.byteLength!==n.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==n[r])return!1;return!0}return us=t,us}const e0=Ri(Yp);var ls,Qa;function Du(){if(Qa)return ls;Qa=1;const{bases:t}=e0;function e(s,o,a,c){return{name:s,prefix:o,encoder:{name:s,prefix:o,encode:a},decoder:{decode:c}}}const n=e("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),r=e("ascii","a",s=>{let o="a";for(let a=0;a<s.length;a++)o+=String.fromCharCode(s[a]);return o},s=>{s=s.substring(1);const o=new Uint8Array(s.length);for(let a=0;a<s.length;a++)o[a]=s.charCodeAt(a);return o});return ls={utf8:n,"utf-8":n,hex:t.base16,latin1:r,ascii:r,binary:r,...t},ls}var hs,Xa;function t0(){if(Xa)return hs;Xa=1;const t=Du();function e(n,r="utf8"){const i=t[r];if(!i)throw new Error(`Unsupported encoding "${r}"`);return i.decoder.decode(`${i.prefix}${n}`)}return hs=e,hs}var fs,ec;function n0(){if(ec)return fs;ec=1;const t=Du();function e(n,r="utf8"){const i=t[r];if(!i)throw new Error(`Unsupported encoding "${r}"`);return i.encoder.encode(n).substring(1)}return fs=e,fs}var ps,tc;function r0(){if(tc)return ps;tc=1;function t(e,n){if(e.length!==n.length)throw new Error("Inputs should have the same length");const r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^n[i];return r}return ps=t,ps}var ms,nc;function i0(){if(nc)return ms;nc=1;const t=Yw(),e=Qw(),n=Xw(),r=t0(),i=n0(),s=r0();return ms={compare:t,concat:e,equals:n,fromString:r,toString:i,xor:s},ms}var ti=i0(),bs,rc;function s0(){if(rc)return bs;rc=1,bs=r;var t=128,e=-128,n=Math.pow(2,31);function r(i,s,o){if(Number.MAX_SAFE_INTEGER&&i>Number.MAX_SAFE_INTEGER)throw r.bytes=0,new RangeError("Could not encode varint");s=s||[],o=o||0;for(var a=o;i>=n;)s[o++]=i&255|t,i/=128;for(;i&e;)s[o++]=i&255|t,i>>>=7;return s[o]=i|0,r.bytes=o-a+1,s}return bs}var ws,ic;function o0(){if(ic)return ws;ic=1,ws=n;var t=128,e=127;function n(r,o){var s=0,o=o||0,a=0,c=o,u,h=r.length;do{if(c>=h||a>49)throw n.bytes=0,new RangeError("Could not decode varint");u=r[c++],s+=a<28?(u&e)<<a:(u&e)*Math.pow(2,a),a+=7}while(u>=t);return n.bytes=c-o,s}return ws}var ys,sc;function a0(){if(sc)return ys;sc=1;var t=Math.pow(2,7),e=Math.pow(2,14),n=Math.pow(2,21),r=Math.pow(2,28),i=Math.pow(2,35),s=Math.pow(2,42),o=Math.pow(2,49),a=Math.pow(2,56),c=Math.pow(2,63);return ys=function(u){return u<t?1:u<e?2:u<n?3:u<r?4:u<i?5:u<s?6:u<o?7:u<a?8:u<c?9:10},ys}var gs,oc;function vo(){return oc||(oc=1,gs={encode:s0(),decode:o0(),encodingLength:a0()}),gs}const c0=Ri(cf),d0=Ri(Xp),u0=Ri(Qp);var Ns,ac;function ku(){if(ac)return Ns;ac=1;const t=vo(),{toString:e}=d0,{fromString:n}=u0;Ns={numberToUint8Array:i,uint8ArrayToNumber:r,varintUint8ArrayEncode:s,varintEncode:o};function r(a){return parseInt(e(a,"base16"),16)}function i(a){let c=a.toString(16);return c.length%2===1&&(c="0"+c),n(c,"base16")}function s(a){return Uint8Array.from(t.encode(r(a)))}function o(a){return Uint8Array.from(t.encode(a))}return Ns}var xs,cc;function l0(){return cc||(cc=1,xs={baseTable:Object.freeze({identity:0,cidv1:1,cidv2:2,cidv3:3,ip4:4,tcp:6,sha1:17,"sha2-256":18,"sha2-512":19,"sha3-512":20,"sha3-384":21,"sha3-256":22,"sha3-224":23,"shake-128":24,"shake-256":25,"keccak-224":26,"keccak-256":27,"keccak-384":28,"keccak-512":29,blake3:30,dccp:33,"murmur3-128":34,"murmur3-32":35,ip6:41,ip6zone:42,path:47,multicodec:48,multihash:49,multiaddr:50,multibase:51,dns:53,dns4:54,dns6:55,dnsaddr:56,protobuf:80,cbor:81,raw:85,"dbl-sha2-256":86,rlp:96,bencode:99,"dag-pb":112,"dag-cbor":113,"libp2p-key":114,"git-raw":120,"torrent-info":123,"torrent-file":124,"leofcoin-block":129,"leofcoin-tx":130,"leofcoin-pr":131,sctp:132,"dag-jose":133,"dag-cose":134,"eth-block":144,"eth-block-list":145,"eth-tx-trie":146,"eth-tx":147,"eth-tx-receipt-trie":148,"eth-tx-receipt":149,"eth-state-trie":150,"eth-account-snapshot":151,"eth-storage-trie":152,"eth-receipt-log-trie":153,"eth-reciept-log":154,"bitcoin-block":176,"bitcoin-tx":177,"bitcoin-witness-commitment":178,"zcash-block":192,"zcash-tx":193,"caip-50":202,streamid:206,"stellar-block":208,"stellar-tx":209,md4:212,md5:213,bmt:214,"decred-block":224,"decred-tx":225,"ipld-ns":226,"ipfs-ns":227,"swarm-ns":228,"ipns-ns":229,zeronet:230,"secp256k1-pub":231,"bls12_381-g1-pub":234,"bls12_381-g2-pub":235,"x25519-pub":236,"ed25519-pub":237,"bls12_381-g1g2-pub":238,"dash-block":240,"dash-tx":241,"swarm-manifest":250,"swarm-feed":251,udp:273,"p2p-webrtc-star":275,"p2p-webrtc-direct":276,"p2p-stardust":277,"p2p-circuit":290,"dag-json":297,udt:301,utp:302,unix:400,thread:406,p2p:421,ipfs:421,https:443,onion:444,onion3:445,garlic64:446,garlic32:447,tls:448,noise:454,quic:460,ws:477,wss:478,"p2p-websocket-star":479,http:480,"swhid-1-snp":496,json:512,messagepack:513,"libp2p-peer-record":769,"libp2p-relay-rsvp":770,"car-index-sorted":1024,"sha2-256-trunc254-padded":4114,"ripemd-128":4178,"ripemd-160":4179,"ripemd-256":4180,"ripemd-320":4181,x11:4352,"p256-pub":4608,"p384-pub":4609,"p521-pub":4610,"ed448-pub":4611,"x448-pub":4612,"ed25519-priv":4864,"secp256k1-priv":4865,"x25519-priv":4866,kangarootwelve:7425,"sm3-256":21325,"blake2b-8":45569,"blake2b-16":45570,"blake2b-24":45571,"blake2b-32":45572,"blake2b-40":45573,"blake2b-48":45574,"blake2b-56":45575,"blake2b-64":45576,"blake2b-72":45577,"blake2b-80":45578,"blake2b-88":45579,"blake2b-96":45580,"blake2b-104":45581,"blake2b-112":45582,"blake2b-120":45583,"blake2b-128":45584,"blake2b-136":45585,"blake2b-144":45586,"blake2b-152":45587,"blake2b-160":45588,"blake2b-168":45589,"blake2b-176":45590,"blake2b-184":45591,"blake2b-192":45592,"blake2b-200":45593,"blake2b-208":45594,"blake2b-216":45595,"blake2b-224":45596,"blake2b-232":45597,"blake2b-240":45598,"blake2b-248":45599,"blake2b-256":45600,"blake2b-264":45601,"blake2b-272":45602,"blake2b-280":45603,"blake2b-288":45604,"blake2b-296":45605,"blake2b-304":45606,"blake2b-312":45607,"blake2b-320":45608,"blake2b-328":45609,"blake2b-336":45610,"blake2b-344":45611,"blake2b-352":45612,"blake2b-360":45613,"blake2b-368":45614,"blake2b-376":45615,"blake2b-384":45616,"blake2b-392":45617,"blake2b-400":45618,"blake2b-408":45619,"blake2b-416":45620,"blake2b-424":45621,"blake2b-432":45622,"blake2b-440":45623,"blake2b-448":45624,"blake2b-456":45625,"blake2b-464":45626,"blake2b-472":45627,"blake2b-480":45628,"blake2b-488":45629,"blake2b-496":45630,"blake2b-504":45631,"blake2b-512":45632,"blake2s-8":45633,"blake2s-16":45634,"blake2s-24":45635,"blake2s-32":45636,"blake2s-40":45637,"blake2s-48":45638,"blake2s-56":45639,"blake2s-64":45640,"blake2s-72":45641,"blake2s-80":45642,"blake2s-88":45643,"blake2s-96":45644,"blake2s-104":45645,"blake2s-112":45646,"blake2s-120":45647,"blake2s-128":45648,"blake2s-136":45649,"blake2s-144":45650,"blake2s-152":45651,"blake2s-160":45652,"blake2s-168":45653,"blake2s-176":45654,"blake2s-184":45655,"blake2s-192":45656,"blake2s-200":45657,"blake2s-208":45658,"blake2s-216":45659,"blake2s-224":45660,"blake2s-232":45661,"blake2s-240":45662,"blake2s-248":45663,"blake2s-256":45664,"skein256-8":45825,"skein256-16":45826,"skein256-24":45827,"skein256-32":45828,"skein256-40":45829,"skein256-48":45830,"skein256-56":45831,"skein256-64":45832,"skein256-72":45833,"skein256-80":45834,"skein256-88":45835,"skein256-96":45836,"skein256-104":45837,"skein256-112":45838,"skein256-120":45839,"skein256-128":45840,"skein256-136":45841,"skein256-144":45842,"skein256-152":45843,"skein256-160":45844,"skein256-168":45845,"skein256-176":45846,"skein256-184":45847,"skein256-192":45848,"skein256-200":45849,"skein256-208":45850,"skein256-216":45851,"skein256-224":45852,"skein256-232":45853,"skein256-240":45854,"skein256-248":45855,"skein256-256":45856,"skein512-8":45857,"skein512-16":45858,"skein512-24":45859,"skein512-32":45860,"skein512-40":45861,"skein512-48":45862,"skein512-56":45863,"skein512-64":45864,"skein512-72":45865,"skein512-80":45866,"skein512-88":45867,"skein512-96":45868,"skein512-104":45869,"skein512-112":45870,"skein512-120":45871,"skein512-128":45872,"skein512-136":45873,"skein512-144":45874,"skein512-152":45875,"skein512-160":45876,"skein512-168":45877,"skein512-176":45878,"skein512-184":45879,"skein512-192":45880,"skein512-200":45881,"skein512-208":45882,"skein512-216":45883,"skein512-224":45884,"skein512-232":45885,"skein512-240":45886,"skein512-248":45887,"skein512-256":45888,"skein512-264":45889,"skein512-272":45890,"skein512-280":45891,"skein512-288":45892,"skein512-296":45893,"skein512-304":45894,"skein512-312":45895,"skein512-320":45896,"skein512-328":45897,"skein512-336":45898,"skein512-344":45899,"skein512-352":45900,"skein512-360":45901,"skein512-368":45902,"skein512-376":45903,"skein512-384":45904,"skein512-392":45905,"skein512-400":45906,"skein512-408":45907,"skein512-416":45908,"skein512-424":45909,"skein512-432":45910,"skein512-440":45911,"skein512-448":45912,"skein512-456":45913,"skein512-464":45914,"skein512-472":45915,"skein512-480":45916,"skein512-488":45917,"skein512-496":45918,"skein512-504":45919,"skein512-512":45920,"skein1024-8":45921,"skein1024-16":45922,"skein1024-24":45923,"skein1024-32":45924,"skein1024-40":45925,"skein1024-48":45926,"skein1024-56":45927,"skein1024-64":45928,"skein1024-72":45929,"skein1024-80":45930,"skein1024-88":45931,"skein1024-96":45932,"skein1024-104":45933,"skein1024-112":45934,"skein1024-120":45935,"skein1024-128":45936,"skein1024-136":45937,"skein1024-144":45938,"skein1024-152":45939,"skein1024-160":45940,"skein1024-168":45941,"skein1024-176":45942,"skein1024-184":45943,"skein1024-192":45944,"skein1024-200":45945,"skein1024-208":45946,"skein1024-216":45947,"skein1024-224":45948,"skein1024-232":45949,"skein1024-240":45950,"skein1024-248":45951,"skein1024-256":45952,"skein1024-264":45953,"skein1024-272":45954,"skein1024-280":45955,"skein1024-288":45956,"skein1024-296":45957,"skein1024-304":45958,"skein1024-312":45959,"skein1024-320":45960,"skein1024-328":45961,"skein1024-336":45962,"skein1024-344":45963,"skein1024-352":45964,"skein1024-360":45965,"skein1024-368":45966,"skein1024-376":45967,"skein1024-384":45968,"skein1024-392":45969,"skein1024-400":45970,"skein1024-408":45971,"skein1024-416":45972,"skein1024-424":45973,"skein1024-432":45974,"skein1024-440":45975,"skein1024-448":45976,"skein1024-456":45977,"skein1024-464":45978,"skein1024-472":45979,"skein1024-480":45980,"skein1024-488":45981,"skein1024-496":45982,"skein1024-504":45983,"skein1024-512":45984,"skein1024-520":45985,"skein1024-528":45986,"skein1024-536":45987,"skein1024-544":45988,"skein1024-552":45989,"skein1024-560":45990,"skein1024-568":45991,"skein1024-576":45992,"skein1024-584":45993,"skein1024-592":45994,"skein1024-600":45995,"skein1024-608":45996,"skein1024-616":45997,"skein1024-624":45998,"skein1024-632":45999,"skein1024-640":46e3,"skein1024-648":46001,"skein1024-656":46002,"skein1024-664":46003,"skein1024-672":46004,"skein1024-680":46005,"skein1024-688":46006,"skein1024-696":46007,"skein1024-704":46008,"skein1024-712":46009,"skein1024-720":46010,"skein1024-728":46011,"skein1024-736":46012,"skein1024-744":46013,"skein1024-752":46014,"skein1024-760":46015,"skein1024-768":46016,"skein1024-776":46017,"skein1024-784":46018,"skein1024-792":46019,"skein1024-800":46020,"skein1024-808":46021,"skein1024-816":46022,"skein1024-824":46023,"skein1024-832":46024,"skein1024-840":46025,"skein1024-848":46026,"skein1024-856":46027,"skein1024-864":46028,"skein1024-872":46029,"skein1024-880":46030,"skein1024-888":46031,"skein1024-896":46032,"skein1024-904":46033,"skein1024-912":46034,"skein1024-920":46035,"skein1024-928":46036,"skein1024-936":46037,"skein1024-944":46038,"skein1024-952":46039,"skein1024-960":46040,"skein1024-968":46041,"skein1024-976":46042,"skein1024-984":46043,"skein1024-992":46044,"skein1024-1000":46045,"skein1024-1008":46046,"skein1024-1016":46047,"skein1024-1024":46048,"poseidon-bls12_381-a2-fc1":46081,"poseidon-bls12_381-a2-fc1-sc":46082,"zeroxcert-imprint-256":52753,"fil-commitment-unsealed":61697,"fil-commitment-sealed":61698,"holochain-adr-v0":8417572,"holochain-adr-v1":8483108,"holochain-key-v0":9728292,"holochain-key-v1":9793828,"holochain-sig-v0":10645796,"holochain-sig-v1":10711332,"skynet-ns":11639056,"arweave-ns":11704592})}),xs}var vs,dc;function h0(){if(dc)return vs;dc=1;const{baseTable:t}=l0(),e=ku().varintEncode,n={},r={},i={};for(const o in t){const a=o,c=t[a];n[a]=e(c);const u=a.toUpperCase().replace(/-/g,"_");r[u]=c,i[c]||(i[c]=a)}Object.freeze(n),Object.freeze(r),Object.freeze(i);const s=Object.freeze(t);return vs={nameToVarint:n,constantToCode:r,nameToCode:s,codeToName:i},vs}var Es,uc;function f0(){if(uc)return Es;uc=1;const t=vo(),{concat:e}=c0,n=ku(),{nameToVarint:r,constantToCode:i,nameToCode:s,codeToName:o}=h0();function a(x,N){let A;if(x instanceof Uint8Array)A=n.varintUint8ArrayEncode(x);else if(r[x])A=r[x];else throw new Error("multicodec not recognized");return e([A,N],A.length+N.length)}function c(x){return t.decode(x),x.slice(t.decode.bytes)}function u(x){const N=t.decode(x),A=o[N];if(A===void 0)throw new Error(`Code "${N}" not found`);return A}function h(x){return o[x]}function f(x){const N=s[x];if(N===void 0)throw new Error(`Codec "${x}" not found`);return N}function l(x){return t.decode(x)}function m(x){const N=r[x];if(N===void 0)throw new Error(`Codec "${x}" not found`);return N}function p(x){return n.varintEncode(x)}function b(x){return u(x)}function v(x){return h(x)}function w(x){return f(x)}function g(x){return l(x)}function y(x){return m(x)}function k(x){return Array.from(p(x))}return Es={addPrefix:a,rmPrefix:c,getNameFromData:u,getNameFromCode:h,getCodeFromName:f,getCodeFromData:l,getVarintFromName:m,getVarintFromCode:p,getCodec:b,getName:v,getNumber:w,getCode:g,getCodeVarint:y,getVarint:k,...i,nameToVarint:r,nameToCode:s,codeToName:o},Es}var p0=f0();const m0=Zs(p0);function b0(t,e){const n=new Uint8Array(t.length+1);return n[0]=2+(e[e.length-1]&1),n.set(t,1),n}function w0(t){const e=t.slice(0,t.length/2),n=t.slice(t.length/2,t.length),r=ti.fromString(e,"base16"),i=ti.fromString(n,"base16"),s=b0(r,i);return ti.toString(s,"base16")}function y0(t){return t.slice(2)}function g0(t,e){const n=ti.fromString(e,"base16");return N0(t,n)}function N0(t,e){const n=m0.addPrefix(t,e);return`did:key:${tt.encode(n)}`}function Su(t=0){return new Uint8Array(t)}function Au(t,e){e==null&&(e=t.reduce((i,s)=>i+s.length,0));const n=Su(e);let r=0;for(const i of t)n.set(i,r),r+=i.length;return n}function x0(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function v0(t){return new TextEncoder().encode(t)}function E0(t){return new TextDecoder().decode(t)}function D0(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var b=0,v=0,w=0,g=p.length;w!==g&&p[w]===0;)w++,b++;for(var y=(g-w)*h+1>>>0,k=new Uint8Array(y);w!==g;){for(var x=p[w],N=0,A=y-1;(x!==0||N<v)&&A!==-1;A--,N++)x+=256*k[A]>>>0,k[A]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");v=N,w++}for(var S=y-v;S!==y&&k[S]===0;)S++;for(var O=c.repeat(b);S<y;++S)O+=t.charAt(k[S]);return O}function l(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var b=0;if(p[b]!==" "){for(var v=0,w=0;p[b]===c;)v++,b++;for(var g=(p.length-b)*u+1>>>0,y=new Uint8Array(g);p[b];){var k=n[p.charCodeAt(b)];if(k===255)return;for(var x=0,N=g-1;(k!==0||x<w)&&N!==-1;N--,x++)k+=a*y[N]>>>0,y[N]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");w=x,b++}if(p[b]!==" "){for(var A=g-w;A!==g&&y[A]===0;)A++;for(var S=new Uint8Array(v+(g-A)),O=v;A!==g;)S[O++]=y[A++];return S}}}function m(p){var b=l(p);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:l,decode:m}}var k0=D0,S0=k0;class A0{name;prefix;baseEncode;constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class O0{name;prefix;baseDecode;prefixCodePoint;constructor(e,n,r){this.name=e,this.prefix=n;const i=n.codePointAt(0);if(i===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i,this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Ou(this,e)}}class C0{decoders;constructor(e){this.decoders=e}or(e){return Ou(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r!=null)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function Ou(t,e){return new C0({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}class T0{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new A0(e,n,r),this.decoder=new O0(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function Fi({name:t,prefix:e,encode:n,decode:r}){return new T0(t,e,n,r)}function Ir({name:t,prefix:e,alphabet:n}){const{encode:r,decode:i}=S0(n,t);return Fi({prefix:e,name:t,encode:r,decode:s=>x0(i(s))})}function I0(t,e,n,r){let i=t.length;for(;t[i-1]==="=";)--i;const s=new Uint8Array(i*n/8|0);let o=0,a=0,c=0;for(let u=0;u<i;++u){const h=e[t[u]];if(h===void 0)throw new SyntaxError(`Non-${r} character`);a=a<<n|h,o+=n,o>=8&&(o-=8,s[c++]=255&a>>o)}if(o>=n||(255&a<<8-o)!==0)throw new SyntaxError("Unexpected end of data");return s}function R0(t,e,n){const r=e[e.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,s+=e[i&a>>o];if(o!==0&&(s+=e[i&a<<n-o]),r)for(;(s.length*n&7)!==0;)s+="=";return s}function W0(t){const e={};for(let n=0;n<t.length;++n)e[t[n]]=n;return e}function Ne({name:t,prefix:e,bitsPerChar:n,alphabet:r}){const i=W0(r);return Fi({prefix:e,name:t,encode(s){return R0(s,r,n)},decode(s){return I0(s,i,n,t)}})}const M0=Ir({prefix:"9",name:"base10",alphabet:"0123456789"}),P0=Object.freeze(Object.defineProperty({__proto__:null,base10:M0},Symbol.toStringTag,{value:"Module"})),$0=Ne({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),L0=Ne({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),B0=Object.freeze(Object.defineProperty({__proto__:null,base16:$0,base16upper:L0},Symbol.toStringTag,{value:"Module"})),U0=Ne({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),q0=Object.freeze(Object.defineProperty({__proto__:null,base2:U0},Symbol.toStringTag,{value:"Module"})),Cu=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),F0=Cu.reduce((t,e,n)=>(t[n]=e,t),[]),V0=Cu.reduce((t,e,n)=>{const r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return t[r]=n,t},[]);function _0(t){return t.reduce((e,n)=>(e+=F0[n],e),"")}function j0(t){const e=[];for(const n of t){const r=n.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${n}`);const i=V0[r];if(i==null)throw new Error(`Non-base256emoji character: ${n}`);e.push(i)}return new Uint8Array(e)}const H0=Fi({prefix:"🚀",name:"base256emoji",encode:_0,decode:j0}),K0=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:H0},Symbol.toStringTag,{value:"Module"})),z0=Ne({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),J0=Ne({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),G0=Ne({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Z0=Ne({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Y0=Ne({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Q0=Ne({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),X0=Ne({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ey=Ne({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ty=Ne({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),ny=Object.freeze(Object.defineProperty({__proto__:null,base32:z0,base32hex:Y0,base32hexpad:X0,base32hexpadupper:ey,base32hexupper:Q0,base32pad:G0,base32padupper:Z0,base32upper:J0,base32z:ty},Symbol.toStringTag,{value:"Module"})),ry=Ir({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),iy=Ir({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),sy=Object.freeze(Object.defineProperty({__proto__:null,base36:ry,base36upper:iy},Symbol.toStringTag,{value:"Module"})),Tu=Ir({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),oy=Ir({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),ay=Object.freeze(Object.defineProperty({__proto__:null,base58btc:Tu,base58flickr:oy},Symbol.toStringTag,{value:"Module"})),cy=Ne({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),dy=Ne({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),uy=Ne({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ly=Ne({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),hy=Object.freeze(Object.defineProperty({__proto__:null,base64:cy,base64pad:dy,base64url:uy,base64urlpad:ly},Symbol.toStringTag,{value:"Module"})),fy=Ne({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),py=Object.freeze(Object.defineProperty({__proto__:null,base8:fy},Symbol.toStringTag,{value:"Module"})),my=Fi({prefix:"\0",name:"identity",encode:t=>E0(t),decode:t=>v0(t)}),by=Object.freeze(Object.defineProperty({__proto__:null,identity:my},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const lc={...by,...q0,...py,...P0,...B0,...ny,...sy,...ay,...hy,...K0};function Iu(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const hc=Iu("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Ds=Iu("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=Su(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),Ru={utf8:hc,"utf-8":hc,hex:lc.base16,latin1:Ds,ascii:Ds,binary:Ds,...lc};function wy(t,e="utf8"){const n=Ru[e];if(n==null)throw new Error(`Unsupported encoding "${e}"`);return n.decoder.decode(`${n.prefix}${t}`)}function ot(t,e="utf8"){const n=Ru[e];if(n==null)throw new Error(`Unsupported encoding "${e}"`);return n.encoder.encode(t).substring(1)}const yy={},I1=Object.freeze(Object.defineProperty({__proto__:null,default:yy},Symbol.toStringTag,{value:"Module"}));var gy=vo();const fc=Zs(gy);function Ny(t,e){const n=`did:key:${e}`,r=`${n}#${e}`;return{id:n,verificationMethod:[{id:r,type:"Secp256k1VerificationKey2018",controller:n,publicKeyBase58:ot(t,"base58btc")}],authentication:[r],assertionMethod:[r],capabilityDelegation:[r],capabilityInvocation:[r]}}const xy=Object.freeze(Object.defineProperty({__proto__:null,keyToDidDoc:Ny},Symbol.toStringTag,{value:"Module"}));function vy(t){const e=new Uint8Array(t.length+2);return e[0]=236,e[1]=1,e.set(t,2),`z${ot(e,"base58btc")}`}function Ey(t,e){const n=`did:key:${e}`,r=`${n}#${e}`,i=rb(t),s=`${n}#${vy(i)}`;return{id:n,verificationMethod:[{id:r,type:"Ed25519VerificationKey2018",controller:n,publicKeyBase58:ot(t,"base58btc")}],authentication:[r],assertionMethod:[r],capabilityDelegation:[r],capabilityInvocation:[r],keyAgreement:[{id:s,type:"X25519KeyAgreementKey2019",controller:n,publicKeyBase58:ot(i,"base58btc")}]}}const Dy=Object.freeze(Object.defineProperty({__proto__:null,keyToDidDoc:Ey},Symbol.toStringTag,{value:"Module"})),Pn=Sm;function ky(t,e){const n=`did:key:${e}`,r=`${n}#${e}`,i=li.ProjectivePoint.fromHex(Sy(t));return{id:n,verificationMethod:[{id:r,type:"JsonWebKey2020",controller:n,publicKeyJwk:{kty:"EC",crv:"P-256",x:ot(Pn(i.x),"base64url"),y:ot(Pn(i.y),"base64url")}}],authentication:[r],assertionMethod:[r],capabilityDelegation:[r],capabilityInvocation:[r]}}function Sy(t){return t.length===64?Au([new Uint8Array([4]),t]):t}const Ay=Object.freeze(Object.defineProperty({__proto__:null,keyToDidDoc:ky},Symbol.toStringTag,{value:"Module"}));const Oy=Sb;function Cy(t,e){const n=`did:key:${e}`,r=`${n}#${e}`,i=Oy.ProjectivePoint.fromHex(Ty(t));return{id:n,verificationMethod:[{id:r,type:"JsonWebKey2020",controller:n,publicKeyJwk:{kty:"EC",crv:"P-384",x:ot(Pn(i.x),"base64url"),y:ot(Pn(i.y),"base64url")}}],authentication:[r],assertionMethod:[r],capabilityDelegation:[r],capabilityInvocation:[r]}}function Ty(t){return t.length===96?Au([new Uint8Array([4]),t]):t}const Iy=Object.freeze(Object.defineProperty({__proto__:null,keyToDidDoc:Cy},Symbol.toStringTag,{value:"Module"}));const Ry=Ab;function Wy(t,e){const n=`did:key:${e}`,r=`${n}#${e}`,i=Ry.ProjectivePoint.fromHex(t);return{id:n,verificationMethod:[{id:r,type:"JsonWebKey2020",controller:n,publicKeyJwk:{kty:"EC",crv:"P-521",x:ot(Pn(i.x),"base64url"),y:ot(Pn(i.y),"base64url")}}],authentication:[r],assertionMethod:[r],capabilityDelegation:[r],capabilityInvocation:[r]}}const My=Object.freeze(Object.defineProperty({__proto__:null,keyToDidDoc:Wy},Symbol.toStringTag,{value:"Module"})),Py="application/did+ld+json",pc="application/did+json",$y={231:xy,237:Dy,4608:Ay,4609:Iy,4610:My};function Ly(){return{key:async(t,e,n,r)=>{const i=r.accept||pc,s={didResolutionMetadata:{contentType:i},didDocument:null,didDocumentMetadata:{}};try{const o=Tu.decode(e.id),a=fc.decode(o),c=o.slice(fc.decode.bytes),u=await $y[a].keyToDidDoc(c,e.id);i===Py?(u["@context"]="https://w3id.org/did/v1",s.didDocument=u):i===pc?s.didDocument=u:(delete s.didResolutionMetadata.contentType,s.didResolutionMetadata.error="representationNotSupported")}catch(o){s.didResolutionMetadata.error="invalidDid",s.didResolutionMetadata.message=o.toString()}return s}}}const mc="ES256K",By=/^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/,Fs="https://www.w3.org/2018/credentials/v1",Vs="VerifiableCredential",Uy="JwtProof2020",Wu=["evidence","termsOfUse","refreshService","credentialSchema","credentialStatus"];function _e(t){return Array.isArray(t)?t:[t]}function Nr(t){return Array.isArray(t)?t.map(e=>Nr(e)):t instanceof Date?new Date(t.getTime()):t&&typeof t=="object"?Object.getOwnPropertyNames(t).reduce((e,n)=>(Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n)),e[n]=Nr(t[n]),e),Object.create(Object.getPrototypeOf(t))):t}function pi(t){return t!=null}function qy(t){if(typeof t!="object"||t===null)return t;const e={...t};return Object.keys(e).forEach(n=>e[n]===void 0&&delete e[n]),e}function Fy(t){return typeof t=="object"&&t.sub&&t.iss&&t.claim&&t.iat}function Vy(t){const{iat:e,nbf:n,claim:r,vc:i,...s}=t,o={...s,nbf:n||e,vc:{"@context":[Fs],type:[Vs],credentialSubject:r}};return i&&(t.issVc=i),o}function Mu(t,e=!0){let n=Nr(t);Fy(t)&&(n=Vy(t)),n.credentialSubject={...t.credentialSubject,...t.vc?.credentialSubject},t.sub&&!t.credentialSubject?.id&&n.credentialSubject&&(n.credentialSubject.id=t.sub,e&&delete n.sub),e&&delete n.vc?.credentialSubject,(typeof t.issuer>"u"||typeof t.issuer=="object")&&(n.issuer=qy({id:t.iss,...t.issuer}),e&&!t.issuer?.id&&delete n.iss),!t.id&&t.jti&&(n.id=n.id||n.jti,e&&delete n.jti);const r=[..._e(n.type),..._e(n.vc?.type)].filter(pi);n.type=[...new Set(r)],e&&delete n.vc?.type;for(const s of Wu)t.vc&&t.vc[s]&&(n[s]||(n[s]=t.vc[s]),e&&delete n.vc[s]);const i=[..._e(t.context),..._e(t["@context"]),..._e(t.vc?.["@context"])].filter(pi);return n["@context"]=[...new Set(i)],e&&(delete n.context,delete n.vc?.["@context"]),!t.issuanceDate&&(t.iat||t.nbf)&&(n.issuanceDate=new Date((t.nbf||t.iat)*1e3).toISOString(),e&&(t.nbf?delete n.nbf:delete n.iat)),!t.expirationDate&&t.exp&&(n.expirationDate=new Date(t.exp*1e3).toISOString(),e&&delete n.exp),e&&n.vc&&Object.keys(n.vc).length===0&&delete n.vc,n}function bc(t,e=!0){let n;try{n=qi(t)}catch{throw new TypeError("unknown credential format")}return{...Mu(n.payload,e),proof:{type:Uy,jwt:t}}}function Pu(t,e=!0){if(typeof t=="string"){if(By.test(t))return bc(t,e);{let n;try{n=JSON.parse(t)}catch{throw new TypeError("unknown credential format")}return Pu(n,e)}}else return t.proof?.jwt?Nr({...bc(t.proof.jwt,e),proof:t.proof}):{proof:{},...Mu(t,e)}}function _y(t,e=!0){if(Array.isArray(t.credentialSubject))throw Error("credentialSubject of type array not supported");const n=Nr({vc:{...t.vc},...t});n.vc=n.vc;const r={...t.credentialSubject,...t.vc?.credentialSubject};t.sub||(n.sub=t.credentialSubject?.id,e&&delete r.id);const i=[..._e(t.context),..._e(t["@context"]),..._e(t.vc?.["@context"])].filter(pi);n.vc["@context"]=[...new Set(i)],e&&(delete n.context,delete n["@context"]);const s=[..._e(t.type),..._e(t.vc?.type)].filter(pi);if(n.vc.type=[...new Set(s)],e&&delete n.type,t.id&&Object.getOwnPropertyNames(t).indexOf("jti")===-1&&(n.jti=t.id,e&&delete n.id),t.issuanceDate&&Object.getOwnPropertyNames(t).indexOf("nbf")===-1){const o=Date.parse(t.issuanceDate);isNaN(o)||(n.nbf=Math.floor(o/1e3),e&&delete n.issuanceDate)}if(t.expirationDate&&Object.getOwnPropertyNames(t).indexOf("exp")===-1){const o=Date.parse(t.expirationDate);isNaN(o)||(n.exp=Math.floor(o/1e3),e&&delete n.expirationDate)}t.issuer&&Object.getOwnPropertyNames(t).indexOf("iss")===-1&&(typeof t.issuer=="object"?(n.iss=t.issuer?.id,e&&(delete n.issuer.id,Object.keys(n.issuer).length===0&&delete n.issuer)):typeof t.issuer=="string"&&(n.iss=t.iss||""+t.issuer,e&&delete n.issuer)),n.vc.credentialSubject=r,e&&delete n.credentialSubject;for(const o of Wu)t[o]&&(n.vc[o]||(n.vc[o]=t[o]),e&&delete n[o]);return n}const xr={SCHEMA_ERROR:"schema_error"};function jy(t){return t&&!isNaN(t)&&Object.prototype.toString.call(t)==="[object Date]"}function vr(t){if(typeof t=="number"){if(!(Number.isInteger(t)&&t<1e11))throw new TypeError(`${xr.SCHEMA_ERROR}: "${t}" is not a unix timestamp in seconds`)}else if(typeof t=="string")vr(Math.floor(new Date(t).valueOf()/1e3));else if(!jy(t))throw new TypeError(`${xr.SCHEMA_ERROR}: "${t}" is not a valid time`)}function $u(t){const e=_e(t);if(e.length<1||e.indexOf(Fs)===-1)throw new TypeError(`${xr.SCHEMA_ERROR}: @context is missing default context "${Fs}"`)}function Lu(t){const e=_e(t);if(e.length<1||e.indexOf(Vs)===-1)throw new TypeError(`${xr.SCHEMA_ERROR}: type is missing default "${Vs}"`)}function Bu(t){if(Object.keys(t).length===0)throw new TypeError(`${xr.SCHEMA_ERROR}: credentialSubject must not be empty`)}const Hy=function(t,e,n={}){try{const r=n?.policies?.issuanceDate===!1?!1:void 0,i=n?.policies?.expirationDate===!1?!1:void 0;return n={...n,policies:{...n?.policies,nbf:r,exp:i,iat:r}},Promise.resolve(No(t,{resolver:e,...n})).then(function(s){return s.verifiableCredential=Pu(s.jwt,n?.removeOriginalFields),n?.policies?.format!==!1&&Jy(s.verifiableCredential),s})}catch(r){return Promise.reject(r)}},Ky=function(t,e,n={}){try{const r={iat:void 0,..._y(t,n.removeOriginalFields)};if(zy(r),Array.isArray(e)){const i=e[0].did,s=[];for(const o of e){if(o.did!==i)throw new Error("All issuers must be the same did to comply with the Verifiable Conditions spec");s.push({issuer:o.did||r.iss||"",signer:o.signer,alg:o.alg||n.header?.alg||mc})}return Promise.resolve(_w(r,{...n},s))}else return Promise.resolve(Eu(r,{...n,issuer:e.did||r.iss||"",signer:e.signer},{...n.header,alg:e.alg||n.header?.alg||mc}))}catch(r){return Promise.reject(r)}};function zy(t){$u(t.vc["@context"]),Lu(t.vc.type),Bu(t.vc.credentialSubject),t.nbf&&vr(t.nbf),t.exp&&vr(t.exp)}function Jy(t){$u(t["@context"]),Lu(t.type),Bu(t.credentialSubject),t.issuanceDate&&vr(t.issuanceDate),t.expirationDate&&vr(t.expirationDate)}function Gy(t){const e=t.split(":");if(!t.startsWith("did:pkh:")||e.length!==5)throw new Error("Invalid pkh did");const[,,n,r,i]=e;if(!i.startsWith("0x"))throw new Error(`Invalid address: ${i}`);const s=Number(r);if(isNaN(s))throw new Error(`Invalid chain id: ${r}`);return{chainId:s,networkId:n,address:i}}async function Zy(t){try{const e=parseInt(String(Date.now()/1e3)),n=await Hy(t,Yy(),{policies:{now:parseInt(String(Date.now()/1e3)),expirationDate:!0,issuanceDate:!0}});return n.payload.exp&&n.payload.exp<e?!1:n}catch(e){return console.error(e),!1}}async function Uu(t,e,n,r,i){const s={sub:r.did,vc:{"@context":["https://www.w3.org/2018/credentials/v1"],type:["VerifiableCredential"],credentialSubject:{chainId:t,networkId:e,address:n}},aud:i?.aud};return await Ky(s,r,{expiresIn:i?.expiresIn})}const Yy=()=>{const t=Ly();if(!t)throw new Error("Failed to get key resolver");return new dw(t)};class Ge{static#e="browserKeyDB";static#t="keyPairs";static#n="keyPair";#r;constructor(){this.#r=this.#i()}#i(){return new Promise((e,n)=>{const r=indexedDB.open(Ge.#e);r.onupgradeneeded=this.#c,r.onsuccess=()=>this.#s(r.result,e,n),r.onerror=()=>n(r.error)})}#c=e=>{const n=e.target.result;this.#o(n)};#s=(e,n,r)=>{if(e.objectStoreNames.contains(Ge.#t))n(e);else{const i=e.version;e.close();const s=indexedDB.open(Ge.#e,i+1);s.onupgradeneeded=this.#c,s.onsuccess=()=>n(s.result),s.onerror=()=>r(s.error)}};#o(e){e.objectStoreNames.contains(Ge.#t)||e.createObjectStore(Ge.#t)}async#a(e="readwrite"){return(await this.#r).transaction(Ge.#t,e).objectStore(Ge.#t)}async saveKeyPair(e){const r=(await this.#a()).put(e,Ge.#n);return new Promise((i,s)=>{r.onsuccess=()=>{i()},r.onerror=()=>{s(new Error("Failed to save key pair"))}})}async loadKeyPair(){const n=(await this.#a("readonly")).get(Ge.#n);return new Promise((r,i)=>{n.onsuccess=()=>{const s=n.result;r(s)},n.onerror=()=>{i(new Error("Failed to load key pair"))}})}}const Qy="eip155",Xy=1;function eg(t){return Array.prototype.map.call(new Uint8Array(t),e=>("00"+e.toString(16)).slice(-2)).join("")}class Dn{#e;#t;#n;#r;#i;static algorithm={name:"ECDSA",namedCurve:"P-256"};static signAlgorithm={name:"ECDSA",namedCurve:"P-256",hash:"SHA-256"};constructor(e,n=globalThis.crypto.subtle){this.#n=e,this.#e=n,this.#r=this.#c()}async#c(){const e=await this.#n.loadKeyPair();return e?this.#t=await this.#d(e):(this.#t=await this.#o(),await this.#n.saveKeyPair(await this.#a())),await this.#s()}async getBearerToken(e,n,r=!1,i){const s=await this.getIssuer();if((r||!this.#i)&&(this.#i=await Uu(Number(Xy),Qy,n||await this.#r,s,i)),!this.#i)throw new Error("Could not create bearer token");return this.#i}did(){return this.#r}async regenerateDid(){this.#t=await this.#o(),await this.#n.saveKeyPair(await this.#a())}async#s(){if(!this.#t)throw new Error("No key pair available");const e=await this.#e.exportKey("raw",this.#t.publicKey),n="p256-pub",r=y0(eg(e)),i=w0(r);return g0(n,i)}async#o(){return await this.#e.generateKey(Dn.algorithm,!0,["sign","verify"])}async#a(){if(!this.#t)throw new Error("No key pair available");return{publicKey:await this.#e.exportKey("jwk",this.#t.publicKey),privateKey:await this.#e.exportKey("jwk",this.#t.privateKey)}}async#d(e){return{publicKey:await this.#e.importKey("jwk",e.publicKey,Dn.algorithm,!0,["verify"]),privateKey:await this.#e.importKey("jwk",e.privateKey,Dn.algorithm,!0,["sign"])}}#u=async(...e)=>await this.#e.sign(...e);#p=async(...e)=>await this.#e.verify(...e);#h(e){return wy(e,"utf-8")}async sign(e){if(this.#t?.privateKey){const n=typeof e=="string"?this.#h(e):e,r=await this.#e.sign(Dn.signAlgorithm,this.#t.privateKey,n.buffer);return new Uint8Array(r)}else throw new Error("No private key available")}async getIssuer(){if(!this.#t?.privateKey)throw new Error("No private key available");return{did:await this.#r,signer:async e=>{const n=await this.sign(typeof e=="string"?new TextEncoder().encode(e):e);return wo(n)},alg:"ES256"}}}const tg="https://www.renown.id";class ng{#e;#t;#n;#r;constructor(e,n,r,i=tg){this.#t=e,this.#r=n,this.#n=r,this.#e=i,this.user&&this.login(this.user.did).catch(()=>{})}get user(){return this.#t.get("user")}#i(e){e?this.#t.set("user",e):this.#t.delete("user"),this.#r.emit("user",e)}set connectId(e){this.#n=e;const n=this.user;this.#i(void 0),n&&this.login(n.did).catch(r=>{console.log("User no longer authenticated:",r)})}async login(e){try{const n=Gy(e),r=await this.#c(n.address,n.chainId,this.#n);if(!r)throw this.#i(void 0),new Error("Credential not found");const i={...n,did:e,credential:r};return this.#i(i),i}catch(n){throw this.#i(void 0),n}}logout(){return this.#i(void 0),Promise.resolve()}on(e,n){return this.#r.on(e,n)}async#c(e,n,r){if(!this.#e)throw new Error("RENOWN_URL is not set");const i=new URL(`/api/auth/credential?address=${encodeURIComponent(e)}&chainId=${encodeURIComponent(n)}&connectId=${encodeURIComponent(r)}`,this.#e),s=await fetch(i,{method:"GET"});if(s.ok)return(await s.json()).credential;throw new Error("Failed to get credential")}async verifyBearerToken(e){return Zy(e)}async createBearerToken(e,n,r,i){if(!this.user)throw new Error("User not found");return Uu(n,this.#n,e,r,i)}}class wc extends CustomEvent{constructor(e,n){super(e,{detail:n})}}class rg{#e=new EventTarget;on(e,n){const r=i=>{i instanceof wc&&n(i.detail)};return this.#e.addEventListener(e.toString(),r),()=>{this.#e.removeEventListener(e.toString(),r)}}emit(e,n){const r=new wc(e.toString(),n);this.#e.dispatchEvent(r)}}class ig{namespace;constructor(e){this.namespace=e}}class sg extends ig{constructor(e,n){super(`${n}:${e}`)}#e(e){return`${this.namespace}:${e.toString()}`}get(e){const n=localStorage.getItem(this.#e(e));if(n)return JSON.parse(n)}set(e,n){return n?localStorage.setItem(this.#e(e),JSON.stringify(n)):localStorage.removeItem(this.#e(e))}delete(e){return localStorage.removeItem(this.#e(e))}}function R1(t,e,n){return new ng(new sg("renown",e),new rg,t,n)}const Eo=R("drives"),qu=Eo.useValue,og=Eo.setValue,ag=Eo.addEventHandler;function cg(t){return t.reduce((e,n)=>(n.status==="fulfilled"?e.push(n.value):console.warn(n.reason),e),[])}function W1(t){if(!t)return"PUBLIC";const e="readContext"in t,{sharingType:n}=e?{sharingType:"PUBLIC"}:t.state.local,r=n?.toUpperCase();return r==="PRIVATE"?"LOCAL":r}function M1(t){if(!t)return!1;const e="readContext"in t,{availableOffline:n}=e?{availableOffline:!1}:t.state.local;return n??!1}async function dg(t){if(!t)return[];const e=await t.getDrives(),n=await Promise.allSettled(e.map(r=>t.getDrive(r)));return cg(n)}function P1(t,e){if(e==="LOCAL")return;const n=window.ph?.legacyReactor;if(n)try{const r=n.getSyncStatus(t);return r instanceof ph?"INITIAL_SYNC":r}catch(r){return console.error(r),"ERROR"}}function ug(t){return t?.state.local.triggers.find(e=>e.type==="PullResponder")}function Fu(t){return ug(t)?.data?.url}function Vu(t){if(!t)return;const e=Fu(t);if("remoteUrl"in t.state.global){const n=t.state.global.remoteUrl;if(typeof n=="string")return n}return e}function lg(t){const e=Vu(t),n=Fu(t);return e!==void 0||n!==void 0}const $1=(t={})=>{const e=t.defaultDrivesUrl||[];return{defaultDrives:{remoteDrives:e.map(r=>({url:r,options:{sharingType:"PUBLIC",availableOffline:!0,listeners:[{block:!0,callInfo:{data:r,name:"switchboard-push",transmitterType:"SwitchboardPush"},filter:{branch:["main"],documentId:["*"],documentType:["*"],scope:["global"]},label:"Switchboard Sync",listenerId:"1",system:!0}],triggers:[]}})),removeOldRemoteDrives:e.length>0?{strategy:"preserve-by-url-and-detach",urls:e}:{strategy:"preserve-all"}}}},hg=200,fg=1e3;async function yc(t){if(!t)return;const e=await dg(t);og(e)}function pg(t=hg,e=fg){let n=null,r=0;return(i,s=!1)=>{const o=Date.now(),a=o-r;return n!==null&&clearTimeout(n),s||a>=e?(r=o,yc(i)):new Promise(c=>{n=setTimeout(()=>{r=Date.now(),yc(i).then(c)},t)})}}const L1=pg();async function B1(t,e,n){await mg(t,e,n);const i=(await t.initialize())?.at(0);if(i)throw i}async function mg(t,e,n){let r=e?.user;r instanceof Function&&(r=await r()),!(!n||!r)&&t.setGenerateJwtHandler(async i=>n.getBearerToken(i,r.address,!0,{expiresIn:10}))}async function U1(){const t=new Dn(new Ge);return await t.did(),t}function _u(t){switch(t.status){case"pending":return{status:"pending"};case"fulfilled":return{status:"fulfilled",value:t.value};case"rejected":return{status:"rejected",reason:t.reason};default:return t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e}),t.catch(e=>{t.status="rejected",t.reason=e}),_u(t)}}function q1(t){const e=new Map;return t.on("documentDeleted",n=>{e.delete(n)}),{get(n,r){const i=e.get(n);if(i&&(_u(i).status==="pending"||!r))return i;const s=t.getDocument(n);return e.set(n,s),s},subscribe(n,r){const i=Array.isArray(n)?n:[n];return t.on("operationsAdded",s=>{i.includes(s)&&this.get(s,!0).then(()=>r()).catch(()=>{console.warn("Failed to refetch document",s)})})}}}const Do=R("documentCache"),bg=Do.useValue,F1=Do.setValue,wg=Do.addEventHandler;function yg(t){const e=bg(),n=jt.useSyncExternalStore(r=>t&&e?e.subscribe(t,r):()=>{},()=>t?e?.get(t):void 0);return n?jt.use(n):void 0}function ju(t){const e=yg(t),[,n]=to(e);return[e,n]}let ni;typeof window<"u"?window.btoa?ni=function(t){return btoa(unescape(encodeURIComponent(t)))}:ni=function(t){const e=unescape(encodeURIComponent(t+""));let n="";for(let r,i,s=0,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";e.charAt(s|0)||(o="=",s%1);n+=o.charAt(63&r>>8-s%1*8)){if(i=e.charCodeAt(s+=3/4),i>255)throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");r=r<<8|i}return n}:ni=function(t){return Buffer.from(t).toString("base64")};function Z(t,e){let n=gc(t,e);return(e&&e.fallback!==void 0?e.fallback:Z.defaults.fallback)===!0&&n===""&&(n=gc(ni(t),e)),n}const Hu={bg:{Й:"Y",й:"y",X:"H",x:"h",Ц:"Ts",ц:"ts",Щ:"Sht",щ:"sht",Ъ:"A",ъ:"a",Ь:"Y",ь:"y"},de:{Ä:"AE",ä:"ae",Ö:"OE",ö:"oe",Ü:"UE",ü:"ue"},sr:{đ:"dj",Đ:"DJ"},uk:{И:"Y",и:"y",Й:"Y",й:"y",Ц:"Ts",ц:"ts",Х:"Kh",х:"kh",Щ:"Shch",щ:"shch",Г:"H",г:"h"}};let ko={};function gc(t,e){if(typeof t!="string")throw new Error("slug() requires a string argument, received "+typeof t);if(!t.isWellFormed())throw new Error("slug() received a malformed string with lone surrogates");typeof e=="string"&&(e={replacement:e}),e=e?Object.assign({},e):{},e.mode=e.mode||Z.defaults.mode;const n=Z.defaults.modes[e.mode],r=["replacement","multicharmap","charmap","remove","lower","trim"];for(let c,u=0,h=r.length;u<h;u++)c=r[u],e[c]=c in e?e[c]:n[c];const i=Hu[e.locale]||ko;let s=[];for(const c in e.multicharmap){if(!Object.prototype.hasOwnProperty.call(e.multicharmap,c))continue;const u=c.length;s.indexOf(u)===-1&&s.push(u)}s=s.sort(function(c,u){return u-c});const o=e.mode==="rfc3986"?/[^\w\s\-.~]/:/[^A-Za-z0-9\s]/;let a="";for(let c,u=0,h=t.length;u<h;u++){c=t[u];let f=!1;for(let l=0;l<s.length;l++){const m=s[l],p=t.substr(u,m);if(e.multicharmap[p]){u+=m-1,c=e.multicharmap[p],f=!0;break}}f||(i[c]?c=i[c]:e.charmap[c]?c=e.charmap[c].replace(e.replacement," "):c.includes(e.replacement)?c=c.replace(e.replacement," "):c=c.replace(o,"")),a+=c}return e.remove&&(a=a.replace(e.remove,"")),e.trim&&(a=a.trim()),a=a.replace(/\s+/g,e.replacement),e.lower&&(a=a.toLowerCase()),a}const Ku={फ़:"Fi",ग़:"Ghi",ख़:"Khi",क़:"Qi",ड़:"ugDha",ढ़:"ugDhha",य़:"Yi",ज़:"Za",בִי:"i",בֵ:"e",בֵי:"e",בֶ:"e",בַ:"a",בָ:"a",בֹ:"o",וֹ:"o",בֻ:"u",וּ:"u",בּ:"b",כּ:"k",ךּ:"k",פּ:"p",שׁ:"sh",שׂ:"s",בְ:"e",חֱ:"e",חֲ:"a",חֳ:"o",בִ:"i"},zu={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",Æ:"AE",Ç:"C",È:"E",É:"E",Ê:"E",Ë:"E",Ì:"I",Í:"I",Î:"I",Ï:"I",Ð:"D",Ñ:"N",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ő:"O",Ø:"O",Ō:"O",Ù:"U",Ú:"U",Û:"U",Ü:"U",Ű:"U",Ý:"Y",Þ:"TH",ß:"ss",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",æ:"ae",ç:"c",è:"e",é:"e",ê:"e",ë:"e",ì:"i",í:"i",î:"i",ï:"i",ð:"d",ñ:"n",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ő:"o",ø:"o",ō:"o",Œ:"OE",œ:"oe",ù:"u",ú:"u",û:"u",ü:"u",ű:"u",ý:"y",þ:"th",ÿ:"y","ẞ":"SS",α:"a",β:"b",γ:"g",δ:"d",ε:"e",ζ:"z",η:"h",θ:"th",ι:"i",κ:"k",λ:"l",μ:"m",ν:"n",ξ:"3",ο:"o",π:"p",ρ:"r",σ:"s",τ:"t",υ:"y",φ:"f",χ:"x",ψ:"ps",ω:"w",ά:"a",έ:"e",ί:"i",ό:"o",ύ:"y",ή:"h",ώ:"w",ς:"s",ϊ:"i",ΰ:"y",ϋ:"y",ΐ:"i",Α:"A",Β:"B",Γ:"G",Δ:"D",Ε:"E",Ζ:"Z",Η:"H",Θ:"Th",Ι:"I",Κ:"K",Λ:"L",Μ:"M",Ν:"N",Ξ:"3",Ο:"O",Π:"P",Ρ:"R",Σ:"S",Τ:"T",Υ:"Y",Φ:"F",Χ:"X",Ψ:"PS",Ω:"W",Ά:"A",Έ:"E",Ί:"I",Ό:"O",Ύ:"Y",Ή:"H",Ώ:"W",Ϊ:"I",Ϋ:"Y",ş:"s",Ş:"S",ı:"i",İ:"I",ğ:"g",Ğ:"G",а:"a",б:"b",в:"v",г:"g",д:"d",е:"e",ё:"yo",ж:"zh",з:"z",и:"i",й:"j",к:"k",л:"l",м:"m",н:"n",о:"o",п:"p",р:"r",с:"s",т:"t",у:"u",ф:"f",х:"h",ц:"c",ч:"ch",ш:"sh",щ:"sh",ъ:"u",ы:"y",ь:"",э:"e",ю:"yu",я:"ya",А:"A",Б:"B",В:"V",Г:"G",Д:"D",Е:"E",Ё:"Yo",Ж:"Zh",З:"Z",И:"I",Й:"J",К:"K",Л:"L",М:"M",Н:"N",О:"O",П:"P",Р:"R",С:"S",Т:"T",У:"U",Ф:"F",Х:"H",Ц:"C",Ч:"Ch",Ш:"Sh",Щ:"Sh",Ъ:"U",Ы:"Y",Ь:"",Э:"E",Ю:"Yu",Я:"Ya",Є:"Ye",І:"I",Ї:"Yi",Ґ:"G",є:"ye",і:"i",ї:"yi",ґ:"g",č:"c",ď:"d",ě:"e",ň:"n",ř:"r",š:"s",ť:"t",ů:"u",ž:"z",Č:"C",Ď:"D",Ě:"E",Ň:"N",Ř:"R",Š:"S",Ť:"T",Ů:"U",Ž:"Z",ľ:"l",ĺ:"l",ŕ:"r",Ľ:"L",Ĺ:"L",Ŕ:"R",ą:"a",ć:"c",ę:"e",ł:"l",ń:"n",ś:"s",ź:"z",ż:"z",Ą:"A",Ć:"C",Ę:"E",Ł:"L",Ń:"N",Ś:"S",Ź:"Z",Ż:"Z",ā:"a",ē:"e",ģ:"g",ī:"i",ķ:"k",ļ:"l",ņ:"n",ū:"u",Ā:"A",Ē:"E",Ģ:"G",Ī:"I",Ķ:"K",Ļ:"L",Ņ:"N",Ū:"U",أ:"a",إ:"i",ب:"b",ت:"t",ث:"th",ج:"g",ح:"h",خ:"kh",د:"d",ذ:"th",ر:"r",ز:"z",س:"s",ش:"sh",ص:"s",ض:"d",ط:"t",ظ:"th",ع:"aa",غ:"gh",ف:"f",ق:"k",ك:"k",ل:"l",م:"m",ن:"n",ه:"h",و:"o",ي:"y",ء:"aa",ة:"a",آ:"a",ا:"a",پ:"p",ژ:"zh",گ:"g",چ:"ch",ک:"k",ی:"i",ė:"e",į:"i",ų:"u",Ė:"E",Į:"I",Ų:"U",ț:"t",Ț:"T",ţ:"t",Ţ:"T",ș:"s",Ș:"S",ă:"a",Ă:"A",Ạ:"A",Ả:"A",Ầ:"A",Ấ:"A",Ậ:"A",Ẩ:"A",Ẫ:"A",Ằ:"A",Ắ:"A",Ặ:"A",Ẳ:"A",Ẵ:"A",Ẹ:"E",Ẻ:"E",Ẽ:"E",Ề:"E",Ế:"E",Ệ:"E",Ể:"E",Ễ:"E",Ị:"I",Ỉ:"I",Ĩ:"I",Ọ:"O",Ỏ:"O",Ồ:"O",Ố:"O",Ộ:"O",Ổ:"O",Ỗ:"O",Ơ:"O",Ờ:"O",Ớ:"O",Ợ:"O",Ở:"O",Ỡ:"O",Ụ:"U",Ủ:"U",Ũ:"U",Ư:"U",Ừ:"U",Ứ:"U",Ự:"U",Ử:"U",Ữ:"U",Ỳ:"Y",Ỵ:"Y",Ỷ:"Y",Ỹ:"Y",Đ:"D",ạ:"a",ả:"a",ầ:"a",ấ:"a",ậ:"a",ẩ:"a",ẫ:"a",ằ:"a",ắ:"a",ặ:"a",ẳ:"a",ẵ:"a",ẹ:"e",ẻ:"e",ẽ:"e",ề:"e",ế:"e",ệ:"e",ể:"e",ễ:"e",ị:"i",ỉ:"i",ĩ:"i",ọ:"o",ỏ:"o",ồ:"o",ố:"o",ộ:"o",ổ:"o",ỗ:"o",ơ:"o",ờ:"o",ớ:"o",ợ:"o",ở:"o",ỡ:"o",ụ:"u",ủ:"u",ũ:"u",ư:"u",ừ:"u",ứ:"u",ự:"u",ử:"u",ữ:"u",ỳ:"y",ỵ:"y",ỷ:"y",ỹ:"y",đ:"d",Ә:"AE",ә:"ae",Ғ:"GH",ғ:"gh",Қ:"KH",қ:"kh",Ң:"NG",ң:"ng",Ү:"UE",ү:"ue",Ұ:"U",ұ:"u",Һ:"H",һ:"h",Ө:"OE",ө:"oe",ђ:"dj",ј:"j",љ:"lj",њ:"nj",ћ:"c",џ:"dz",Ђ:"Dj",Ј:"j",Љ:"Lj",Њ:"Nj",Ћ:"C",Џ:"Dz",nj:"nj",lj:"lj",Nj:"NJ",Lj:"LJ",अ:"a",आ:"aa",ए:"e",ई:"ii",ऍ:"ei",ऎ:"ae",ऐ:"ai",इ:"i",ओ:"o",ऑ:"oi",ऒ:"oii",ऊ:"uu",औ:"ou",उ:"u",ब:"B",भ:"Bha",च:"Ca",छ:"Chha",ड:"Da",ढ:"Dha",फ:"Fa",ग:"Ga",घ:"Gha",ग़:"Ghi",ह:"Ha",ज:"Ja",झ:"Jha",क:"Ka",ख:"Kha",ख़:"Khi",ल:"L",ळ:"Li",ऌ:"Li",ऴ:"Lii",ॡ:"Lii",म:"Ma",न:"Na",ङ:"Na",ञ:"Nia",ण:"Nae",ऩ:"Ni",ॐ:"oms",प:"Pa",क़:"Qi",र:"Ra",ऋ:"Ri",ॠ:"Ri",ऱ:"Ri",स:"Sa",श:"Sha",ष:"Shha",ट:"Ta",त:"Ta",ठ:"Tha",द:"Tha",थ:"Tha",ध:"Thha",ड़:"ugDha",ढ़:"ugDhha",व:"Va",य:"Ya",य़:"Yi",ज़:"Za",ə:"e",Ə:"E",ა:"a",ბ:"b",გ:"g",დ:"d",ე:"e",ვ:"v",ზ:"z",თ:"t",ი:"i",კ:"k",ლ:"l",მ:"m",ნ:"n",ო:"o",პ:"p",ჟ:"zh",რ:"r",ს:"s",ტ:"t",უ:"u",ფ:"p",ქ:"k",ღ:"gh",ყ:"q",შ:"sh",ჩ:"ch",ც:"ts",ძ:"dz",წ:"ts",ჭ:"ch",ხ:"kh",ჯ:"j",ჰ:"h",ב:"v",גּ:"g",ג:"g",ד:"d",דּ:"d",ה:"h",ו:"v",ז:"z",ח:"h",ט:"t",י:"y",כ:"kh",ך:"kh",ל:"l",מ:"m",ם:"m",נ:"n",ן:"n",ס:"s",פ:"f",ף:"f",ץ:"ts",צ:"ts",ק:"k",ר:"r",תּ:"t",ת:"t"};Z.charmap=Object.assign({},zu);Z.multicharmap=Object.assign({},Ku);Z.defaults={charmap:Z.charmap,mode:"pretty",modes:{rfc3986:{replacement:"-",remove:null,lower:!0,charmap:Z.charmap,multicharmap:Z.multicharmap,trim:!0},pretty:{replacement:"-",remove:null,lower:!0,charmap:Z.charmap,multicharmap:Z.multicharmap,trim:!0}},multicharmap:Z.multicharmap,fallback:!0};Z.reset=function(){Z.defaults.modes.rfc3986.charmap=Z.defaults.modes.pretty.charmap=Z.charmap=Z.defaults.charmap=Object.assign({},zu),Z.defaults.modes.rfc3986.multicharmap=Z.defaults.modes.pretty.multicharmap=Z.multicharmap=Z.defaults.multicharmap=Object.assign({},Ku),ko=""};Z.extend=function(t){const e=Object.keys(t),n={},r={};for(let i=0;i<e.length;i++)e[i].length>1?n[e[i]]=t[e[i]]:r[e[i]]=t[e[i]];Object.assign(Z.charmap,r),Object.assign(Z.multicharmap,n)};Z.setLocale=function(t){ko=Hu[t]||{}};function mi(t){return new URL(t.replace(/^\/+/,""),window.location.origin+(window.ph?.basePath??"/")).pathname}function Ju(t){const e=window.ph?.basePath??"/";return t.replace(e,e.endsWith("/")?"/":"")}function gg(t){if(!t)return"";const e=t.name;return Z(e?`${e}-${t.id}`:t.id)}function Ng(t){const e=Ju(t);return/^\/d\/[^/]+\/([^/]+)$/.exec(e)?.[1]}function Gu(t){return t?/\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/.exec(t)?.[0]:void 0}function xg(t){return Gu(t)}function Zu(t){const e=Ju(t);return/^\/d\/([^/]+)/.exec(e)?.[1]??""}function vg(t){return Gu(t)}function Eg(t){const e=Zu(t);return vg(e)}const So=R("selectedDriveId"),Yu=So.useValue,Dg=So.setValue,kg=So.addEventHandler;function Sg(){const t=Ao();if(!t[0])throw new Error("There is no drive selected. Did you mean to call 'useSelectedDriveSafe'?");return t}function Ao(){const t=Yu(),n=qu()?.find(s=>s.header.id===t),[r,i]=to(n);return n?[r,i]:[void 0,void 0]}function Ag(t){const e=typeof t=="string"?t:t?.header.slug,r=window.ph?.drives?.find(s=>s.header.slug===e)?.header.id;if(Dg(r),!r){const s=mi("/");if(s===window.location.pathname)return;window.history.pushState(null,"",s);return}const i=mi(`/d/${e}`);i!==window.location.pathname&&window.history.pushState(null,"",i)}function Og(){window.addEventListener("popstate",()=>{const t=window.location.pathname,e=Eg(t),n=window.ph?.selectedDriveId;e!==n&&Ag(e)})}function Rr(){const[t]=Ao();return t?.state.global.nodes}function Cg(){return Rr()?.filter(e=>Qc(e))}const Oo=R("selectedNodeId"),Tg=Oo.useValue,Qu=Oo.setValue,Ig=Oo.addEventHandler;function Wr(){const t=Tg();return Rr()?.find(n=>n.id===t)}function Xu(t){const e=typeof t=="string"?t:gg(t),n=xg(e);Qu(n);const r=Zu(window.location.pathname);if(!r)return;if(!e){const s=mi(`/d/${r}`);if(s===window.location.pathname)return;window.history.pushState(null,"",s);return}const i=mi(`/d/${r}/${e}`);i!==window.location.pathname&&window.history.pushState(null,"",i)}function Rg(){window.addEventListener("ph:selectedDriveIdUpdated",()=>{Qu(void 0)})}function Wg(){window.addEventListener("popstate",()=>{const t=window.location.pathname,e=Ng(t),n=window.ph?.selectedNodeId;e!==n&&Xu(e)})}function Co(){const t=Wr();if(Qc(t))return t}function V1(){const t=Rr(),n=Co()?.id;return t?ia(n?t.filter(r=>r.parentFolder===n):t.filter(r=>!r.parentFolder)):[]}const{setValue:Mg,addEventHandler:Pg}=R("routerBasename"),{setValue:$g,addEventHandler:Lg}=R("version"),{setValue:Bg,addEventHandler:Ug}=R("requiresHardRefresh"),{setValue:qg,addEventHandler:Fg}=R("warnOutdatedApp"),{setValue:Vg,addEventHandler:_g}=R("studioMode"),{setValue:jg,addEventHandler:Hg}=R("basePath"),{setValue:Kg,addEventHandler:zg}=R("versionCheckInterval"),{setValue:Jg,addEventHandler:Gg}=R("cliVersion"),{setValue:Zg,addEventHandler:Yg}=R("fileUploadOperationsChunkSize"),{setValue:Qg,addEventHandler:Xg}=R("isDocumentModelSelectionSettingsEnabled"),{setValue:eN,addEventHandler:tN}=R("gaTrackingId"),{setValue:nN,addEventHandler:rN}=R("defaultDrivesUrl"),{setValue:iN,addEventHandler:sN}=R("drivesPreserveStrategy"),{setValue:oN,addEventHandler:aN}=R("isLocalDrivesEnabled"),{setValue:cN,addEventHandler:dN}=R("isAddDriveEnabled"),{setValue:uN,addEventHandler:lN}=R("isPublicDrivesEnabled"),{setValue:hN,addEventHandler:fN}=R("isAddPublicDrivesEnabled"),{setValue:pN,addEventHandler:mN}=R("isDeletePublicDrivesEnabled"),{setValue:bN,addEventHandler:wN}=R("isCloudDrivesEnabled"),{setValue:yN,addEventHandler:gN}=R("isAddCloudDrivesEnabled"),{setValue:NN,addEventHandler:xN}=R("isDeleteCloudDrivesEnabled");R("isLocalDrivesEnabled");const{setValue:vN,addEventHandler:EN}=R("isAddLocalDrivesEnabled"),{setValue:DN,addEventHandler:kN}=R("isDeleteLocalDrivesEnabled"),{setValue:SN,addEventHandler:AN}=R("isEditorDebugModeEnabled"),{setValue:ON,addEventHandler:CN}=R("isEditorReadModeEnabled"),{setValue:TN,addEventHandler:IN}=R("isAnalyticsDatabaseWorkerEnabled"),{setValue:RN,addEventHandler:WN}=R("isDiffAnalyticsEnabled"),{setValue:MN,addEventHandler:PN}=R("isDriveAnalyticsEnabled"),{setValue:$N,addEventHandler:LN}=R("renownUrl"),{setValue:BN,addEventHandler:UN}=R("renownNetworkId"),{setValue:qN,addEventHandler:FN}=R("renownChainId"),{setValue:VN,addEventHandler:_N}=R("sentryRelease"),{setValue:jN,addEventHandler:HN}=R("sentryDsn"),{setValue:KN,addEventHandler:zN}=R("sentryEnv"),{setValue:JN,addEventHandler:GN}=R("isSentryTracingEnabled"),{setValue:ZN,addEventHandler:YN}=R("isExternalProcessorsEnabled"),{setValue:QN,addEventHandler:XN}=R("isExternalPackagesEnabled"),el=R("enabledEditors"),e2=el.setValue,t2=el.addEventHandler,tl=R("disabledEditors"),n2=tl.setValue,r2=tl.addEventHandler,nl=R("isRelationalProcessorsEnabled"),i2=nl.setValue,s2=nl.addEventHandler,rl=R("isExternalRelationalProcessorsEnabled"),o2=rl.setValue,a2=rl.addEventHandler,il=R("isAnalyticsEnabled"),c2=il.setValue,d2=il.addEventHandler,sl=R("isAnalyticsExternalProcessorsEnabled"),u2=sl.setValue,l2=sl.addEventHandler,ol=R("analyticsDatabaseName"),h2=ol.setValue,f2=ol.addEventHandler,al=R("logLevel"),p2=al.setValue,m2=al.addEventHandler,To=R("allowList"),b2=To.setValue,w2=To.useValue,y2=To.addEventHandler,g2={routerBasename:Mg,version:$g,requiresHardRefresh:Bg,warnOutdatedApp:qg,studioMode:Vg,basePath:jg,versionCheckInterval:Kg,cliVersion:Jg,fileUploadOperationsChunkSize:Zg,isDocumentModelSelectionSettingsEnabled:Qg,gaTrackingId:eN,defaultDrivesUrl:nN,drivesPreserveStrategy:iN,isLocalDrivesEnabled:oN,isAddDriveEnabled:cN,isPublicDrivesEnabled:uN,isAddPublicDrivesEnabled:hN,isDeletePublicDrivesEnabled:pN,isCloudDrivesEnabled:bN,isAddCloudDrivesEnabled:yN,isDeleteCloudDrivesEnabled:NN,isAddLocalDrivesEnabled:vN,isDeleteLocalDrivesEnabled:DN,isEditorDebugModeEnabled:SN,isEditorReadModeEnabled:ON,isRelationalProcessorsEnabled:i2,isExternalRelationalProcessorsEnabled:o2,isAnalyticsEnabled:c2,analyticsDatabaseName:h2,isAnalyticsExternalProcessorsEnabled:u2,isAnalyticsDatabaseWorkerEnabled:TN,isDiffAnalyticsEnabled:RN,isDriveAnalyticsEnabled:MN,renownUrl:$N,renownNetworkId:BN,renownChainId:qN,sentryRelease:VN,sentryDsn:jN,sentryEnv:KN,isSentryTracingEnabled:JN,isExternalProcessorsEnabled:ZN,isExternalPackagesEnabled:QN,allowList:b2,logLevel:p2,disabledEditors:n2,enabledEditors:e2},N2={...rf,...sf,...g2};function Io(t,e){const n=N2[t];n(e)}function _1(t){for(const e of Object.keys(t))Io(e,t[e])}function x2(t){for(const e of Object.keys(t))Io(e,t[e])}function v2(t){for(const e of Object.keys(t))Io(e,t[e])}function j1(t){const[e,n]=jt.useState(!1);jt.useEffect(()=>{e||(x2(t),n(!0))},[t,e])}function H1(t){const[e,n]=jt.useState(!1);jt.useEffect(()=>{e||(v2(t),n(!0))},[t,e])}function E2(t,e){const[n,r]=ju(t),i=af(e);if(!t||!e)return[];if(!n)throw new mh(t);if(!i)throw new bh(e);if(n.header.documentType!==e)throw new Ph(t,e,n.header.documentType);return[n,r]}function D2(){return Yc()?.map(e=>e.documentModel.global.id)}function k2(){const t=tf(),e=D2();return t??e}function K1(t){const n=qu()?.find(s=>s.header.id===t),[r,i]=to(n);if(!n)throw new Error(`Drive with id ${t} not found`);return[r,i]}function cl(){return eo()?.flatMap(e=>e.modules.editorModules||[]).filter(e=>!e.documentTypes.includes("powerhouse/document-drive"))}function S2(){return eo()?.flatMap(e=>e.modules.editorModules||[]).filter(e=>e.documentTypes.includes("powerhouse/document-drive"))}function z1(t){const e=cl();return!t||e?.length===0?void 0:e?.filter(r=>r.documentTypes.includes(t))?.[0]}function A2(t){return S2()?.find(n=>n.id===t)}function J1(){return A2(Gh)}function G1(t){return cl()?.find(n=>n.id===t)}function dl(t){return Cg()?.find(n=>n.id===t)}const Ro=R("modal"),Z1=Ro.useValue,Vi=Ro.setValue,O2=Ro.addEventHandler;function C2(t){Vi(t)}function Y1(){Vi(void 0)}function Q1(t){Vi({type:"createDocument",documentType:t})}function X1(t){const e=typeof t=="string"?t:t.id;Vi({type:"deleteItem",id:e})}function et(t,e){return e?.id!==t?e:void 0}function eE(){const[t]=Ao(),e=Co(),n=Wr(),r=dl(n?.parentFolder),i=t?.header.id;async function s(l,m){if(!i)return;const p=l.name.replace(/\..+/gim,"");return Vh(l,i,p,et(i,m)?.id)}async function o(l,m){if(i)return jh(i,l,et(i,m)?.id)}async function a(l,m){if(!i)return;if(!et(i,m)){console.error(`Node ${m.id} not found`);return}return await Kh(i,m.id,l)}async function c(l,m){if(!i)return;const p=et(i,l);if(!p){console.error(`Node ${l.id} not found`);return}const b=et(i,m);await ra(i,p,b)}async function u(l,m){if(!i)return;const p=et(i,l);if(!p){console.error(`Node ${l.id} not found`);return}const b=et(i,m);!b?.id&&!l.parentFolder||b?.id===l.parentFolder||await zh(i,p,b)}async function h(l){if(!i)return;const m=et(i,l);if(!m){console.error(`Node ${l.id} not found`);return}const p=et(i,e??r);await ra(i,m,p)}async function f(l){if(!l||!i)return;const m=et(i,e??r);if(!m)return;const p=await o(l,m);p&&Xu(p)}return{onAddFile:s,onAddFolder:o,onRenameNode:a,onCopyNode:c,onMoveNode:u,onDuplicateNode:h,onAddAndSelectNewFolder:f}}function T2(t){return Rr()?.find(n=>n.id===t)}function I2(t){const e=Rr();if(!e)return[];const n=[];let r=e.find(i=>i.id===t);for(;r&&(n.push(r),!!r.parentFolder);)r=e.find(i=>i.id===r?.parentFolder);return n.reverse()}function tE(){const t=Wr();return I2(t?.id)}function R2(t){const e=T2(t);return dl(e?.parentFolder)}function nE(){const t=Wr();return R2(t?.id)}const Wo=R("revisionHistoryVisible"),rE=Wo.useValue,W2=Wo.setValue,M2=Wo.addEventHandler;function iE(){W2(!0)}function ul(){const t=Wr();return t&&Ti(t)?t.id:void 0}function sE(){const t=ul();return ju(t)}function oE(t){const e=ul();if(!e)throw new $h;return E2(e,t)}const Mo=R("selectedTimelineItem"),aE=Mo.useValue,cE=Mo.setValue,P2=Mo.addEventHandler,$2=R("selectedTimelineRevision"),L2=$2.addEventHandler,B2=t=>{const e=[];if(t.header.documentType!=="powerhouse/document-model")return e;const n=t,r=n.state.global.specifications[0],i=Object.keys(r.state).reduce((a,c)=>{const u=c;return[...a,...Dh(r.state[u].initialValue,u!=="global").map(h=>({...h,message:`${h.message}. Scope: ${u}`,details:{...h.details,scope:u}}))]},[]),s=Object.keys(r.state).reduce((a,c)=>{const u=c,h=u==="global";return[...a,...kh(r.state[u].schema,n.state.global?.name||n.header.name||"",h?"":u,!h).map(f=>({...f,message:`${f.message}. Scope: ${u}`,details:{...f.details,scope:u}}))]},[]),o=Sh(r.modules);return[...i,...s,...o]},dE=t=>{if(!t)return;if(B2(t).length)C2({type:"exportDocumentWithErrors",documentId:t.header.id});else return Fh(t)},uE=(t,e,n=[])=>{if(!t||!e)return 0;const r=n.find(i=>{const s=new Date(i.timestampUtcMs);return s>=t&&s<=e});return r?r.index:0};var ks={exports:{}},Nc;function U2(){return Nc||(Nc=1,(function(t){var e=(function(){var n=String.fromCharCode,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",s={};function o(c,u){if(!s[c]){s[c]={};for(var h=0;h<c.length;h++)s[c][c.charAt(h)]=h}return s[c][u]}var a={compressToBase64:function(c){if(c==null)return"";var u=a._compress(c,6,function(h){return r.charAt(h)});switch(u.length%4){default:case 0:return u;case 1:return u+"===";case 2:return u+"==";case 3:return u+"="}},decompressFromBase64:function(c){return c==null?"":c==""?null:a._decompress(c.length,32,function(u){return o(r,c.charAt(u))})},compressToUTF16:function(c){return c==null?"":a._compress(c,15,function(u){return n(u+32)})+" "},decompressFromUTF16:function(c){return c==null?"":c==""?null:a._decompress(c.length,16384,function(u){return c.charCodeAt(u)-32})},compressToUint8Array:function(c){for(var u=a.compress(c),h=new Uint8Array(u.length*2),f=0,l=u.length;f<l;f++){var m=u.charCodeAt(f);h[f*2]=m>>>8,h[f*2+1]=m%256}return h},decompressFromUint8Array:function(c){if(c==null)return a.decompress(c);for(var u=new Array(c.length/2),h=0,f=u.length;h<f;h++)u[h]=c[h*2]*256+c[h*2+1];var l=[];return u.forEach(function(m){l.push(n(m))}),a.decompress(l.join(""))},compressToEncodedURIComponent:function(c){return c==null?"":a._compress(c,6,function(u){return i.charAt(u)})},decompressFromEncodedURIComponent:function(c){return c==null?"":c==""?null:(c=c.replace(/ /g,"+"),a._decompress(c.length,32,function(u){return o(i,c.charAt(u))}))},compress:function(c){return a._compress(c,16,function(u){return n(u)})},_compress:function(c,u,h){if(c==null)return"";var f,l,m={},p={},b="",v="",w="",g=2,y=3,k=2,x=[],N=0,A=0,S;for(S=0;S<c.length;S+=1)if(b=c.charAt(S),Object.prototype.hasOwnProperty.call(m,b)||(m[b]=y++,p[b]=!0),v=w+b,Object.prototype.hasOwnProperty.call(m,v))w=v;else{if(Object.prototype.hasOwnProperty.call(p,w)){if(w.charCodeAt(0)<256){for(f=0;f<k;f++)N=N<<1,A==u-1?(A=0,x.push(h(N)),N=0):A++;for(l=w.charCodeAt(0),f=0;f<8;f++)N=N<<1|l&1,A==u-1?(A=0,x.push(h(N)),N=0):A++,l=l>>1}else{for(l=1,f=0;f<k;f++)N=N<<1|l,A==u-1?(A=0,x.push(h(N)),N=0):A++,l=0;for(l=w.charCodeAt(0),f=0;f<16;f++)N=N<<1|l&1,A==u-1?(A=0,x.push(h(N)),N=0):A++,l=l>>1}g--,g==0&&(g=Math.pow(2,k),k++),delete p[w]}else for(l=m[w],f=0;f<k;f++)N=N<<1|l&1,A==u-1?(A=0,x.push(h(N)),N=0):A++,l=l>>1;g--,g==0&&(g=Math.pow(2,k),k++),m[v]=y++,w=String(b)}if(w!==""){if(Object.prototype.hasOwnProperty.call(p,w)){if(w.charCodeAt(0)<256){for(f=0;f<k;f++)N=N<<1,A==u-1?(A=0,x.push(h(N)),N=0):A++;for(l=w.charCodeAt(0),f=0;f<8;f++)N=N<<1|l&1,A==u-1?(A=0,x.push(h(N)),N=0):A++,l=l>>1}else{for(l=1,f=0;f<k;f++)N=N<<1|l,A==u-1?(A=0,x.push(h(N)),N=0):A++,l=0;for(l=w.charCodeAt(0),f=0;f<16;f++)N=N<<1|l&1,A==u-1?(A=0,x.push(h(N)),N=0):A++,l=l>>1}g--,g==0&&(g=Math.pow(2,k),k++),delete p[w]}else for(l=m[w],f=0;f<k;f++)N=N<<1|l&1,A==u-1?(A=0,x.push(h(N)),N=0):A++,l=l>>1;g--,g==0&&(g=Math.pow(2,k),k++)}for(l=2,f=0;f<k;f++)N=N<<1|l&1,A==u-1?(A=0,x.push(h(N)),N=0):A++,l=l>>1;for(;;)if(N=N<<1,A==u-1){x.push(h(N));break}else A++;return x.join("")},decompress:function(c){return c==null?"":c==""?null:a._decompress(c.length,32768,function(u){return c.charCodeAt(u)})},_decompress:function(c,u,h){var f=[],l=4,m=4,p=3,b="",v=[],w,g,y,k,x,N,A,S={val:h(0),position:u,index:1};for(w=0;w<3;w+=1)f[w]=w;for(y=0,x=Math.pow(2,2),N=1;N!=x;)k=S.val&S.position,S.position>>=1,S.position==0&&(S.position=u,S.val=h(S.index++)),y|=(k>0?1:0)*N,N<<=1;switch(y){case 0:for(y=0,x=Math.pow(2,8),N=1;N!=x;)k=S.val&S.position,S.position>>=1,S.position==0&&(S.position=u,S.val=h(S.index++)),y|=(k>0?1:0)*N,N<<=1;A=n(y);break;case 1:for(y=0,x=Math.pow(2,16),N=1;N!=x;)k=S.val&S.position,S.position>>=1,S.position==0&&(S.position=u,S.val=h(S.index++)),y|=(k>0?1:0)*N,N<<=1;A=n(y);break;case 2:return""}for(f[3]=A,g=A,v.push(A);;){if(S.index>c)return"";for(y=0,x=Math.pow(2,p),N=1;N!=x;)k=S.val&S.position,S.position>>=1,S.position==0&&(S.position=u,S.val=h(S.index++)),y|=(k>0?1:0)*N,N<<=1;switch(A=y){case 0:for(y=0,x=Math.pow(2,8),N=1;N!=x;)k=S.val&S.position,S.position>>=1,S.position==0&&(S.position=u,S.val=h(S.index++)),y|=(k>0?1:0)*N,N<<=1;f[m++]=n(y),A=m-1,l--;break;case 1:for(y=0,x=Math.pow(2,16),N=1;N!=x;)k=S.val&S.position,S.position>>=1,S.position==0&&(S.position=u,S.val=h(S.index++)),y|=(k>0?1:0)*N,N<<=1;f[m++]=n(y),A=m-1,l--;break;case 2:return v.join("")}if(l==0&&(l=Math.pow(2,p),p++),f[A])b=f[A];else if(A===m)b=g+g.charAt(0);else return null;v.push(b),f[m++]=g+b.charAt(0),l--,g=b,l==0&&(l=Math.pow(2,p),p++)}}};return a})();t!=null?t.exports=e:typeof angular<"u"&&angular!=null&&angular.module("LZString",[]).factory("LZString",function(){return e})})(ks)),ks.exports}var q2=U2();function F2(t){return t.split("/").pop()}function V2(){return`query getDocument($documentId: String!) {
|
|
16
|
-
document(id: $documentId) {
|
|
17
|
-
id
|
|
18
|
-
documentType
|
|
19
|
-
createdAtUtcIso
|
|
20
|
-
lastModifiedAtUtcIso
|
|
21
|
-
name
|
|
22
|
-
revision
|
|
23
|
-
stateJSON
|
|
24
|
-
}
|
|
25
|
-
}`}function _2(t,e,n){const r=F2(t),i=V2(),s={documentId:e,driveId:r},o=n?{Authorization:`Bearer ${n}`}:void 0,a={document:i.trim(),variables:JSON.stringify(s,null,2)};return o&&(a.headers=JSON.stringify(o)),q2.compressToEncodedURIComponent(JSON.stringify(a))}function j2(t,e,n){const r=_2(t,e,n);return`${t}?explorerURLState=${r}`}function lE(t){return{id:kt(),name:t.manifest.name,description:t.manifest.description,category:t.manifest.category,author:{name:"Powerhouse",website:"https://powerhousedao.com"},modules:{documentModelModules:t.documentModels.map(H2),editorModules:t.editors.map(r=>K2(r,t.manifest))}}}function H2(t){const e=t.documentModel.global,n=e.name,r=e.id,i=r,s=e.extension,o=e.specifications,a=t.reducer,c=t.actions,u=t.utils;return{id:i,name:n,documentType:r,extension:s,documentModel:Ah(Oh(),e),specifications:o,reducer:a,actions:c,utils:u}}function K2(t,e){const n=e?.apps?.find(u=>u.driveEditor===t.config.id)?.name,r=t.config.id,i=r.split("-").map(u=>u.charAt(0).toUpperCase()+u.slice(1)).join(" "),s=n||t.config.name||i,o=t.documentTypes,a=t.Component;return{id:r,name:s,documentTypes:o,Component:a}}function hE(t){const{id:e,name:n,description:r,category:i,author:s,modules:o}=t;return{id:e,name:n,description:r,category:i,author:s,modules:z2(o)}}function z2(t){return Object.entries(t).reduce((e,[n,r])=>(e[n]=r.map(i=>({id:i.id,name:i.name})),e),{})}const Po=R("connectCrypto"),J2=Po.useValue,fE=Po.setValue,G2=Po.addEventHandler,{setValue:pE,addEventHandler:Z2}=R("did"),{addEventHandler:Y2}=R("loading"),{setValue:xn,addEventHandler:Q2}=R("loginStatus"),ll=R("processorManager"),mE=ll.setValue,X2=ll.addEventHandler,$o=R("legacyReactor"),hl=R("reactorClient"),fl=R("sync"),bE=$o.useValue,wE=$o.setValue,ex=$o.addEventHandler,yE=hl.setValue,tx=hl.addEventHandler,gE=fl.setValue,nx=fl.addEventHandler,pl=R("renown"),NE=pl.setValue,rx=pl.addEventHandler,Lo=R("user"),ml=Lo.useValue,xc=Lo.setValue,ix=Lo.addEventHandler,sx={loading:Y2,legacyReactor:ex,reactorClient:tx,sync:nx,modal:O2,connectCrypto:G2,did:Z2,renown:rx,loginStatus:Q2,user:ix,processorManager:X2,drives:ag,documentCache:wg,selectedDriveId:()=>{kg(),Og(),Rg()},selectedNodeId:()=>{Ig(),Wg()},vetraPackages:of,selectedTimelineRevision:L2,revisionHistoryVisible:M2,selectedTimelineItem:P2,routerBasename:Pg,version:Lg,logLevel:m2,requiresHardRefresh:Ug,warnOutdatedApp:Fg,studioMode:_g,basePath:Hg,versionCheckInterval:zg,cliVersion:Gg,fileUploadOperationsChunkSize:Yg,isDocumentModelSelectionSettingsEnabled:Xg,gaTrackingId:tN,allowList:y2,defaultDrivesUrl:rN,drivesPreserveStrategy:sN,allowedDocumentTypes:nf,enabledEditors:t2,disabledEditors:r2,isAddDriveEnabled:dN,isLocalDrivesEnabled:aN,isPublicDrivesEnabled:lN,isAddPublicDrivesEnabled:fN,isDeletePublicDrivesEnabled:mN,isCloudDrivesEnabled:wN,isAddCloudDrivesEnabled:gN,isDeleteCloudDrivesEnabled:xN,isAddLocalDrivesEnabled:EN,isDeleteLocalDrivesEnabled:kN,isDragAndDropEnabled:Xh,isExternalControlsEnabled:Yh,isEditorDebugModeEnabled:AN,isEditorReadModeEnabled:CN,isRelationalProcessorsEnabled:s2,isExternalRelationalProcessorsEnabled:a2,isAnalyticsEnabled:d2,isAnalyticsExternalProcessorsEnabled:l2,analyticsDatabaseName:f2,isAnalyticsDatabaseWorkerEnabled:IN,isDiffAnalyticsEnabled:WN,isDriveAnalyticsEnabled:PN,renownUrl:LN,renownNetworkId:UN,renownChainId:FN,sentryRelease:_N,sentryDsn:HN,sentryEnv:zN,isSentryTracingEnabled:GN,isExternalProcessorsEnabled:YN,isExternalPackagesEnabled:XN};function xE(){for(const t of Object.values(sx))t()}function vE(t){const[e]=Sg(),n=lg(e),r=Vu(e),i=J2(),s=ml();return jt.useMemo(()=>!n||!t?.header.id||!r?null:async()=>{const o=s?.address?await i?.getBearerToken(r,s.address,!1,{expiresIn:600}):void 0;return j2(r,t.header.id,o)},[n,r,t,s,i])}const EE=t=>{const e=Yu(),n=Co(),r=k2();return async(s,o,a)=>{if(!e){console.warn("No selected drive - upload skipped");return}const c=s.name.replace(/\..+/gim,""),u=n?.id;return await _h(s,e,c,u,o,r,a)}};function DE(){const t=ml(),e=w2();return e?{isAllowedToCreateDocuments:e.includes(t?.address??""),isAllowedToEditDocuments:e.includes(t?.address??"")}:{isAllowedToCreateDocuments:!0,isAllowedToEditDocuments:!0}}function _t(t){return typeof t>"u"||t===void 0}function Ae(t){return typeof t=="string"}function _i(t){return typeof t=="number"}function bi(t){return typeof t=="boolean"}function Bo(t){return t===null}function ox(t){return t instanceof Date}function Uo(t){return typeof t=="bigint"}function Fe(t){return typeof t=="function"}function je(t){return typeof t=="object"&&t!==null}function ax(t){return t[t.length-1]}function d(t){return Object.freeze(t)}function Gr(t){return vt(t)?t:[t]}function vt(t){return Array.isArray(t)}function Le(t){return t}const H=d({is(t){return t.kind==="AlterTableNode"},create(t){return d({kind:"AlterTableNode",table:t})},cloneWithTableProps(t,e){return d({...t,...e})},cloneWithColumnAlteration(t,e){return d({...t,columnAlterations:t.columnAlterations?[...t.columnAlterations,e]:[e]})}}),G=d({is(t){return t.kind==="IdentifierNode"},create(t){return d({kind:"IdentifierNode",name:t})}}),ht=d({is(t){return t.kind==="CreateIndexNode"},create(t){return d({kind:"CreateIndexNode",name:G.create(t)})},cloneWith(t,e){return d({...t,...e})},cloneWithColumns(t,e){return d({...t,columns:[...t.columns||[],...e]})}}),bl=d({is(t){return t.kind==="CreateSchemaNode"},create(t,e){return d({kind:"CreateSchemaNode",schema:G.create(t),...e})},cloneWith(t,e){return d({...t,...e})}}),cx=["preserve rows","delete rows","drop"],We=d({is(t){return t.kind==="CreateTableNode"},create(t){return d({kind:"CreateTableNode",table:t,columns:d([])})},cloneWithColumn(t,e){return d({...t,columns:d([...t.columns,e])})},cloneWithConstraint(t,e){return d({...t,constraints:t.constraints?d([...t.constraints,e]):d([e])})},cloneWithFrontModifier(t,e){return d({...t,frontModifiers:t.frontModifiers?d([...t.frontModifiers,e]):d([e])})},cloneWithEndModifier(t,e){return d({...t,endModifiers:t.endModifiers?d([...t.endModifiers,e]):d([e])})},cloneWith(t,e){return d({...t,...e})}}),Et=d({is(t){return t.kind==="SchemableIdentifierNode"},create(t){return d({kind:"SchemableIdentifierNode",identifier:G.create(t)})},createWithSchema(t,e){return d({kind:"SchemableIdentifierNode",schema:G.create(t),identifier:G.create(e)})}}),Yn=d({is(t){return t.kind==="DropIndexNode"},create(t,e){return d({kind:"DropIndexNode",name:Et.create(t),...e})},cloneWith(t,e){return d({...t,...e})}}),_s=d({is(t){return t.kind==="DropSchemaNode"},create(t,e){return d({kind:"DropSchemaNode",schema:G.create(t),...e})},cloneWith(t,e){return d({...t,...e})}}),js=d({is(t){return t.kind==="DropTableNode"},create(t,e){return d({kind:"DropTableNode",table:t,...e})},cloneWith(t,e){return d({...t,...e})}}),St=d({is(t){return t.kind==="AliasNode"},create(t,e){return d({kind:"AliasNode",node:t,alias:e})}}),gt=d({is(t){return t.kind==="TableNode"},create(t){return d({kind:"TableNode",table:Et.create(t)})},createWithSchema(t,e){return d({kind:"TableNode",table:Et.createWithSchema(t,e)})}});function Oe(t){return je(t)&&Fe(t.toOperationNode)}function wl(t){return je(t)&&"expressionType"in t&&Oe(t)}function dx(t){return je(t)&&"expression"in t&&Ae(t.alias)&&Oe(t)}const lt=d({is(t){return t.kind==="SelectModifierNode"},create(t,e){return d({kind:"SelectModifierNode",modifier:t,of:e})},createWithExpression(t){return d({kind:"SelectModifierNode",rawModifier:t})}}),Ht=d({is(t){return t.kind==="AndNode"},create(t,e){return d({kind:"AndNode",left:t,right:e})}}),Bn=d({is(t){return t.kind==="OrNode"},create(t,e){return d({kind:"OrNode",left:t,right:e})}}),Ss=d({is(t){return t.kind==="OnNode"},create(t){return d({kind:"OnNode",on:t})},cloneWithOperation(t,e,n){return d({...t,on:e==="And"?Ht.create(t.on,n):Bn.create(t.on,n)})}}),an=d({is(t){return t.kind==="JoinNode"},create(t,e){return d({kind:"JoinNode",joinType:t,table:e,on:void 0})},createWithOn(t,e,n){return d({kind:"JoinNode",joinType:t,table:e,on:Ss.create(n)})},cloneWithOn(t,e){return d({...t,on:t.on?Ss.cloneWithOperation(t.on,"And",e):Ss.create(e)})}}),$n=d({is(t){return t.kind==="BinaryOperationNode"},create(t,e,n){return d({kind:"BinaryOperationNode",leftOperand:t,operator:e,rightOperand:n})}}),ux=["=","==","!=","<>",">",">=","<","<=","in","not in","is","is not","like","not like","match","ilike","not ilike","@>","<@","^@","&&","?","?&","?|","!<","!>","<=>","!~","~","~*","!~*","@@","@@@","!!","<->","regexp","is distinct from","is not distinct from"],lx=["+","-","*","/","%","^","&","|","#","<<",">>"],yl=["->","->>"],hx=[...ux,...lx,"&&","||"],fx=["exists","not exists"],px=["not","-",...fx],mx=[...hx,...yl,...px,"between","between symmetric"],Kt=d({is(t){return t.kind==="OperatorNode"},create(t){return d({kind:"OperatorNode",operator:t})}});function vc(t){return Ae(t)&&yl.includes(t)}const le=d({is(t){return t.kind==="ColumnNode"},create(t){return d({kind:"ColumnNode",column:G.create(t)})}}),qo=d({is(t){return t.kind==="SelectAllNode"},create(){return d({kind:"SelectAllNode"})}}),ji=d({is(t){return t.kind==="ReferenceNode"},create(t,e){return d({kind:"ReferenceNode",table:e,column:t})},createSelectAll(t){return d({kind:"ReferenceNode",table:t,column:qo.create()})}});class bx{#e;get dynamicReference(){return this.#e}get refType(){}constructor(e){this.#e=e}toOperationNode(){return El(this.#e)}}function gl(t){return je(t)&&Oe(t)&&Ae(t.dynamicReference)}const wt=d({is(t){return t.kind==="OrderByItemNode"},create(t,e){return d({kind:"OrderByItemNode",orderBy:t,direction:e})},cloneWith(t,e){return d({...t,...e})}}),de=d({is(t){return t.kind==="RawNode"},create(t,e){return d({kind:"RawNode",sqlFragments:d(t),parameters:d(e)})},createWithSql(t){return de.create([t],[])},createWithChild(t){return de.create(["",""],[t])},createWithChildren(t){return de.create(new Array(t.length+1).fill(""),t)}}),wx={is(t){return t.kind==="CollateNode"},create(t){return d({kind:"CollateNode",collation:G.create(t)})}};class zt{#e;constructor(e){this.#e=d(e)}desc(){return new zt({node:wt.cloneWith(this.#e.node,{direction:de.createWithSql("desc")})})}asc(){return new zt({node:wt.cloneWith(this.#e.node,{direction:de.createWithSql("asc")})})}nullsLast(){return new zt({node:wt.cloneWith(this.#e.node,{nulls:"last"})})}nullsFirst(){return new zt({node:wt.cloneWith(this.#e.node,{nulls:"first"})})}collate(e){return new zt({node:wt.cloneWith(this.#e.node,{collation:wx.create(e)})})}toOperationNode(){return this.#e.node}}const Ec=new Set;function Un(t){Ec.has(t)||(Ec.add(t),console.log(t))}function Nl(t){return t==="asc"||t==="desc"}function dn(t){if(t.length===2)return[As(t[0],t[1])];if(t.length===1){const[e]=t;return Array.isArray(e)?(Un("orderBy(array) is deprecated, use multiple orderBy calls instead."),e.map(n=>As(n))):[As(e)]}throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${t.length}`)}function As(t,e){const n=yx(t);if(wt.is(n)){if(e)throw new Error("Cannot specify direction twice!");return n}return xl(n,e)}function yx(t){if($r(t))return pn(t);if(gl(t))return t.toOperationNode();const[e,n]=t.split(" ");return n?(Un("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),xl(Dt(e),n)):Dt(t)}function xl(t,e){if(typeof e=="string"){if(!Nl(e))throw new Error(`Invalid order by direction: ${e}`);return wt.create(t,de.createWithSql(e))}if(wl(e))return Un("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),wt.create(t,e.toOperationNode());const n=wt.create(t);return e?e(new zt({node:n})).toOperationNode():n}const wi=d({is(t){return t.kind==="JSONReferenceNode"},create(t,e){return d({kind:"JSONReferenceNode",reference:t,traversal:e})},cloneWithTraversal(t,e){return d({...t,traversal:e})}}),vl=d({is(t){return t.kind==="JSONOperatorChainNode"},create(t){return d({kind:"JSONOperatorChainNode",operator:t,values:d([])})},cloneWithValue(t,e){return d({...t,values:d([...t.values,e])})}}),Qn=d({is(t){return t.kind==="JSONPathNode"},create(t){return d({kind:"JSONPathNode",inOperator:t,pathLegs:d([])})},cloneWithLeg(t,e){return d({...t,pathLegs:d([...t.pathLegs,e])})}});function El(t){return Ae(t)?Dt(t):t.toOperationNode()}function Er(t){return vt(t)?t.map(e=>Be(e)):[Be(t)]}function Be(t){return $r(t)?pn(t):El(t)}function gx(t,e){const n=Dt(t);if(vc(e))return wi.create(n,vl.create(Kt.create(e)));const r=e.slice(0,-1);if(vc(r))return wi.create(n,Qn.create(Kt.create(r)));throw new Error(`Invalid JSON operator: ${e}`)}function Dt(t){if(!t.includes("."))return ji.create(le.create(t));const n=t.split(".").map(Fo);if(n.length===3)return xx(n);if(n.length===2)return vx(n);throw new Error(`invalid column reference ${t}`)}function Nx(t){const e=" as ";if(t.includes(e)){const[n,r]=t.split(e).map(Fo);return St.create(Dt(n),G.create(r))}else return Dt(t)}function Dl(t){return le.create(t)}function yi(t){if(t.includes(" ")){const[n,r]=t.split(" ").map(Fo);if(!Nl(r))throw new Error(`invalid order direction "${r}" next to "${n}"`);return dn([n,r])[0]}else return Dl(t)}function xx(t){const[e,n,r]=t;return ji.create(le.create(r),gt.createWithSchema(e,n))}function vx(t){const[e,n]=t;return ji.create(le.create(n),gt.create(e))}function Fo(t){return t.trim()}const kl=d({is(t){return t.kind==="PrimitiveValueListNode"},create(t){return d({kind:"PrimitiveValueListNode",values:d([...t])})}}),Hi=d({is(t){return t.kind==="ValueListNode"},create(t){return d({kind:"ValueListNode",values:d(t)})}}),Ke=d({is(t){return t.kind==="ValueNode"},create(t){return d({kind:"ValueNode",value:t})},createImmediate(t){return d({kind:"ValueNode",value:t,immediate:!0})}});function Ex(t){return vt(t)?Dx(t):fe(t)}function fe(t){return $r(t)?pn(t):Ke.create(t)}function Vo(t){return _i(t)||bi(t)||Bo(t)}function _o(t){if(!Vo(t))throw new Error(`unsafe immediate value ${JSON.stringify(t)}`);return Ke.createImmediate(t)}function Dx(t){return t.some($r)?Hi.create(t.map(e=>fe(e))):kl.create(t)}const Nt=d({is(t){return t.kind==="ParensNode"},create(t){return d({kind:"ParensNode",node:t})}});function ye(t){if(t.length===3)return jo(t[0],t[1],t[2]);if(t.length===1)return fe(t[0]);throw new Error(`invalid arguments: ${JSON.stringify(t)}`)}function jo(t,e,n){return kx(e)&&Sl(n)?$n.create(Be(t),Hs(e),Ke.createImmediate(n)):$n.create(Be(t),Hs(e),Ex(n))}function at(t,e,n){return $n.create(Be(t),Hs(e),Be(n))}function Dc(t,e){return gi(Object.entries(t).filter(([,n])=>!_t(n)).map(([n,r])=>jo(n,Sl(r)?"is":"=",r)),e)}function gi(t,e,n=!0){const r=e==="and"?Ht.create:Bn.create;if(t.length===0)return $n.create(Ke.createImmediate(1),Kt.create("="),Ke.createImmediate(e==="and"?1:0));let i=kc(t[0]);for(let s=1;s<t.length;++s)i=r(i,kc(t[s]));return t.length>1&&n?Nt.create(i):i}function kx(t){return t==="is"||t==="is not"}function Sl(t){return Bo(t)||bi(t)}function Hs(t){if(Ae(t)&&mx.includes(t))return Kt.create(t);if(Oe(t))return t.toOperationNode();throw new Error(`invalid operator ${JSON.stringify(t)}`)}function kc(t){return Oe(t)?t.toOperationNode():t}const Ln=d({is(t){return t.kind==="OrderByNode"},create(t){return d({kind:"OrderByNode",items:d([...t])})},cloneWithItems(t,e){return d({...t,items:d([...t.items,...e])})}}),Sc=d({is(t){return t.kind==="PartitionByNode"},create(t){return d({kind:"PartitionByNode",items:d(t)})},cloneWithItems(t,e){return d({...t,items:d([...t.items,...e])})}}),Ks=d({is(t){return t.kind==="OverNode"},create(){return d({kind:"OverNode"})},cloneWithOrderByItems(t,e){return d({...t,orderBy:t.orderBy?Ln.cloneWithItems(t.orderBy,e):Ln.create(e)})},cloneWithPartitionByItems(t,e){return d({...t,partitionBy:t.partitionBy?Sc.cloneWithItems(t.partitionBy,e):Sc.create(e)})}}),Ni=d({is(t){return t.kind==="FromNode"},create(t){return d({kind:"FromNode",froms:d(t)})},cloneWithFroms(t,e){return d({...t,froms:d([...t.froms,...e])})}}),Ac=d({is(t){return t.kind==="GroupByNode"},create(t){return d({kind:"GroupByNode",items:d(t)})},cloneWithItems(t,e){return d({...t,items:d([...t.items,...e])})}}),Oc=d({is(t){return t.kind==="HavingNode"},create(t){return d({kind:"HavingNode",having:t})},cloneWithOperation(t,e,n){return d({...t,having:e==="And"?Ht.create(t.having,n):Bn.create(t.having,n)})}}),be=d({is(t){return t.kind==="InsertQueryNode"},create(t,e,n){return d({kind:"InsertQueryNode",into:t,...e&&{with:e},replace:n})},createWithoutInto(){return d({kind:"InsertQueryNode"})},cloneWith(t,e){return d({...t,...e})}}),Al=d({is(t){return t.kind==="ListNode"},create(t){return d({kind:"ListNode",items:d(t)})}}),On=d({is(t){return t.kind==="UpdateQueryNode"},create(t,e){return d({kind:"UpdateQueryNode",table:t.length===1?t[0]:Al.create(t),...e&&{with:e}})},createWithoutTable(){return d({kind:"UpdateQueryNode"})},cloneWithFromItems(t,e){return d({...t,from:t.from?Ni.cloneWithFroms(t.from,e):Ni.create(e)})},cloneWithUpdates(t,e){return d({...t,updates:t.updates?d([...t.updates,...e]):e})},cloneWithLimit(t,e){return d({...t,limit:e})}}),Cc=d({is(t){return t.kind==="UsingNode"},create(t){return d({kind:"UsingNode",tables:d(t)})},cloneWithTables(t,e){return d({...t,tables:d([...t.tables,...e])})}}),Xn=d({is(t){return t.kind==="DeleteQueryNode"},create(t,e){return d({kind:"DeleteQueryNode",from:Ni.create(t),...e&&{with:e}})},cloneWithOrderByItems:(t,e)=>I.cloneWithOrderByItems(t,e),cloneWithoutOrderBy:t=>I.cloneWithoutOrderBy(t),cloneWithLimit(t,e){return d({...t,limit:e})},cloneWithoutLimit(t){return d({...t,limit:void 0})},cloneWithUsing(t,e){return d({...t,using:t.using!==void 0?Cc.cloneWithTables(t.using,e):Cc.create(e)})}}),Te=d({is(t){return t.kind==="WhereNode"},create(t){return d({kind:"WhereNode",where:t})},cloneWithOperation(t,e,n){return d({...t,where:e==="And"?Ht.create(t.where,n):Bn.create(t.where,n)})}}),Tc=d({is(t){return t.kind==="ReturningNode"},create(t){return d({kind:"ReturningNode",selections:d(t)})},cloneWithSelections(t,e){return d({...t,selections:t.selections?d([...t.selections,...e]):d(e)})}}),Sx=d({is(t){return t.kind==="ExplainNode"},create(t,e){return d({kind:"ExplainNode",format:t,options:e})}}),un=d({is(t){return t.kind==="WhenNode"},create(t){return d({kind:"WhenNode",condition:t})},cloneWithResult(t,e){return d({...t,result:e})}}),it=d({is(t){return t.kind==="MergeQueryNode"},create(t,e){return d({kind:"MergeQueryNode",into:t,...e&&{with:e}})},cloneWithUsing(t,e){return d({...t,using:e})},cloneWithWhen(t,e){return d({...t,whens:t.whens?d([...t.whens,e]):d([e])})},cloneWithThen(t,e){return d({...t,whens:t.whens?d([...t.whens.slice(0,-1),un.cloneWithResult(t.whens[t.whens.length-1],e)]):void 0})}}),Ic=d({is(t){return t.kind==="OutputNode"},create(t){return d({kind:"OutputNode",selections:d(t)})},cloneWithSelections(t,e){return d({...t,selections:t.selections?d([...t.selections,...e]):d(e)})}}),I=d({is(t){return Q.is(t)||be.is(t)||On.is(t)||Xn.is(t)||it.is(t)},cloneWithEndModifier(t,e){return d({...t,endModifiers:t.endModifiers?d([...t.endModifiers,e]):d([e])})},cloneWithWhere(t,e){return d({...t,where:t.where?Te.cloneWithOperation(t.where,"And",e):Te.create(e)})},cloneWithJoin(t,e){return d({...t,joins:t.joins?d([...t.joins,e]):d([e])})},cloneWithReturning(t,e){return d({...t,returning:t.returning?Tc.cloneWithSelections(t.returning,e):Tc.create(e)})},cloneWithoutReturning(t){return d({...t,returning:void 0})},cloneWithoutWhere(t){return d({...t,where:void 0})},cloneWithExplain(t,e,n){return d({...t,explain:Sx.create(e,n?.toOperationNode())})},cloneWithTop(t,e){return d({...t,top:e})},cloneWithOutput(t,e){return d({...t,output:t.output?Ic.cloneWithSelections(t.output,e):Ic.create(e)})},cloneWithOrderByItems(t,e){return d({...t,orderBy:t.orderBy?Ln.cloneWithItems(t.orderBy,e):Ln.create(e)})},cloneWithoutOrderBy(t){return d({...t,orderBy:void 0})}}),Q=d({is(t){return t.kind==="SelectQueryNode"},create(t){return d({kind:"SelectQueryNode",...t&&{with:t}})},createFrom(t,e){return d({kind:"SelectQueryNode",from:Ni.create(t),...e&&{with:e}})},cloneWithSelections(t,e){return d({...t,selections:t.selections?d([...t.selections,...e]):d(e)})},cloneWithDistinctOn(t,e){return d({...t,distinctOn:t.distinctOn?d([...t.distinctOn,...e]):d(e)})},cloneWithFrontModifier(t,e){return d({...t,frontModifiers:t.frontModifiers?d([...t.frontModifiers,e]):d([e])})},cloneWithOrderByItems:(t,e)=>I.cloneWithOrderByItems(t,e),cloneWithGroupByItems(t,e){return d({...t,groupBy:t.groupBy?Ac.cloneWithItems(t.groupBy,e):Ac.create(e)})},cloneWithLimit(t,e){return d({...t,limit:e})},cloneWithOffset(t,e){return d({...t,offset:e})},cloneWithFetch(t,e){return d({...t,fetch:e})},cloneWithHaving(t,e){return d({...t,having:t.having?Oc.cloneWithOperation(t.having,"And",e):Oc.create(e)})},cloneWithSetOperations(t,e){return d({...t,setOperations:t.setOperations?d([...t.setOperations,...e]):d([...e])})},cloneWithoutSelections(t){return d({...t,selections:[]})},cloneWithoutLimit(t){return d({...t,limit:void 0})},cloneWithoutOffset(t){return d({...t,offset:void 0})},cloneWithoutOrderBy:t=>I.cloneWithoutOrderBy(t),cloneWithoutGroupBy(t){return d({...t,groupBy:void 0})}});class er{#e;constructor(e){this.#e=d(e)}on(...e){return new er({...this.#e,joinNode:an.cloneWithOn(this.#e.joinNode,ye(e))})}onRef(e,n,r){return new er({...this.#e,joinNode:an.cloneWithOn(this.#e.joinNode,at(e,n,r))})}onTrue(){return new er({...this.#e,joinNode:an.cloneWithOn(this.#e.joinNode,de.createWithSql("true"))})}$call(e){return e(this)}toOperationNode(){return this.#e.joinNode}}const Ax=d({is(t){return t.kind==="PartitionByItemNode"},create(t){return d({kind:"PartitionByItemNode",partitionBy:t})}});function Ox(t){return Er(t).map(Ax.create)}class tr{#e;constructor(e){this.#e=d(e)}orderBy(...e){return new tr({overNode:Ks.cloneWithOrderByItems(this.#e.overNode,dn(e))})}clearOrderBy(){return new tr({overNode:I.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(e){return new tr({overNode:Ks.cloneWithPartitionByItems(this.#e.overNode,Ox(e))})}$call(e){return e(this)}toOperationNode(){return this.#e.overNode}}const nr=d({is(t){return t.kind==="SelectionNode"},create(t){return d({kind:"SelectionNode",selection:t})},createSelectAll(){return d({kind:"SelectionNode",selection:qo.create()})},createSelectAllFromTable(t){return d({kind:"SelectionNode",selection:ji.createSelectAll(t)})}});function Ue(t){return Fe(t)?Ue(t(Fn())):vt(t)?t.map(e=>Rc(e)):[Rc(t)]}function Rc(t){return Ae(t)?nr.create(Nx(t)):gl(t)?nr.create(t.toOperationNode()):nr.create(Bl(t))}function ze(t){return t?Array.isArray(t)?t.map(Wc):[Wc(t)]:[nr.createSelectAll()]}function Wc(t){if(Ae(t))return nr.createSelectAllFromTable(ue(t));throw new Error(`invalid value selectAll expression: ${JSON.stringify(t)}`)}const Cx=d({is(t){return t.kind==="ValuesNode"},create(t){return d({kind:"ValuesNode",values:d(t)})}}),Tx=d({is(t){return t.kind==="DefaultInsertValueNode"},create(){return d({kind:"DefaultInsertValueNode"})}});function Ol(t){const e=Fe(t)?t(Fn()):t,n=vt(e)?e:d([e]);return Ix(n)}function Ix(t){const e=Rx(t);return[d([...e.keys()].map(le.create)),Cx.create(t.map(n=>Wx(n,e)))]}function Rx(t){const e=new Map;for(const n of t){const r=Object.keys(n);for(const i of r)!e.has(i)&&n[i]!==void 0&&e.set(i,e.size)}return e}function Wx(t,e){const n=Object.keys(t),r=Array.from({length:e.size});let i=!1,s=n.length;for(const a of n){const c=e.get(a);if(_t(c)){s--;continue}const u=t[a];(_t(u)||$r(u))&&(i=!0),r[c]=u}if(s<e.size||i){const a=Tx.create();return Hi.create(r.map(c=>_t(c)?a:fe(c)))}return kl.create(r)}const Cl=d({is(t){return t.kind==="ColumnUpdateNode"},create(t,e){return d({kind:"ColumnUpdateNode",column:t,value:e})}});function Mx(...t){return t.length===2?[Cl.create(Be(t[0]),fe(t[1]))]:Ho(t[0])}function Ho(t){const e=Fe(t)?t(Fn()):t;return Object.entries(e).filter(([n,r])=>r!==void 0).map(([n,r])=>Cl.create(le.create(n),fe(r)))}const Px=d({is(t){return t.kind==="OnDuplicateKeyNode"},create(t){return d({kind:"OnDuplicateKeyNode",updates:t})}});class $x{insertId;numInsertedOrUpdatedRows;constructor(e,n){this.insertId=e,this.numInsertedOrUpdatedRows=n}}class Mr extends Error{node;constructor(e){super("no result"),this.node=e}}function Pr(t){return Object.prototype.hasOwnProperty.call(t,"prototype")}const Pe=d({is(t){return t.kind==="OnConflictNode"},create(){return d({kind:"OnConflictNode"})},cloneWith(t,e){return d({...t,...e})},cloneWithIndexWhere(t,e){return d({...t,indexWhere:t.indexWhere?Te.cloneWithOperation(t.indexWhere,"And",e):Te.create(e)})},cloneWithIndexOrWhere(t,e){return d({...t,indexWhere:t.indexWhere?Te.cloneWithOperation(t.indexWhere,"Or",e):Te.create(e)})},cloneWithUpdateWhere(t,e){return d({...t,updateWhere:t.updateWhere?Te.cloneWithOperation(t.updateWhere,"And",e):Te.create(e)})},cloneWithUpdateOrWhere(t,e){return d({...t,updateWhere:t.updateWhere?Te.cloneWithOperation(t.updateWhere,"Or",e):Te.create(e)})},cloneWithoutIndexWhere(t){return d({...t,indexWhere:void 0})},cloneWithoutUpdateWhere(t){return d({...t,updateWhere:void 0})}});class ft{#e;constructor(e){this.#e=d(e)}column(e){const n=le.create(e);return new ft({...this.#e,onConflictNode:Pe.cloneWith(this.#e.onConflictNode,{columns:this.#e.onConflictNode.columns?d([...this.#e.onConflictNode.columns,n]):d([n])})})}columns(e){const n=e.map(le.create);return new ft({...this.#e,onConflictNode:Pe.cloneWith(this.#e.onConflictNode,{columns:this.#e.onConflictNode.columns?d([...this.#e.onConflictNode.columns,...n]):d(n)})})}constraint(e){return new ft({...this.#e,onConflictNode:Pe.cloneWith(this.#e.onConflictNode,{constraint:G.create(e)})})}expression(e){return new ft({...this.#e,onConflictNode:Pe.cloneWith(this.#e.onConflictNode,{indexExpression:e.toOperationNode()})})}where(...e){return new ft({...this.#e,onConflictNode:Pe.cloneWithIndexWhere(this.#e.onConflictNode,ye(e))})}whereRef(e,n,r){return new ft({...this.#e,onConflictNode:Pe.cloneWithIndexWhere(this.#e.onConflictNode,at(e,n,r))})}clearWhere(){return new ft({...this.#e,onConflictNode:Pe.cloneWithoutIndexWhere(this.#e.onConflictNode)})}doNothing(){return new Lx({...this.#e,onConflictNode:Pe.cloneWith(this.#e.onConflictNode,{doNothing:!0})})}doUpdateSet(e){return new rr({...this.#e,onConflictNode:Pe.cloneWith(this.#e.onConflictNode,{updates:Ho(e)})})}$call(e){return e(this)}}class Lx{#e;constructor(e){this.#e=d(e)}toOperationNode(){return this.#e.onConflictNode}}class rr{#e;constructor(e){this.#e=d(e)}where(...e){return new rr({...this.#e,onConflictNode:Pe.cloneWithUpdateWhere(this.#e.onConflictNode,ye(e))})}whereRef(e,n,r){return new rr({...this.#e,onConflictNode:Pe.cloneWithUpdateWhere(this.#e.onConflictNode,at(e,n,r))})}clearWhere(){return new rr({...this.#e,onConflictNode:Pe.cloneWithoutUpdateWhere(this.#e.onConflictNode)})}$call(e){return e(this)}toOperationNode(){return this.#e.onConflictNode}}const Bx=d({is(t){return t.kind==="TopNode"},create(t,e){return d({kind:"TopNode",expression:t,modifiers:e})}});function qn(t,e){if(!_i(t)&&!Uo(t))throw new Error(`Invalid top expression: ${t}`);if(!_t(e)&&!Ux(e))throw new Error(`Invalid top modifiers: ${e}`);return Bx.create(t,e)}function Ux(t){return t==="percent"||t==="with ties"||t==="percent with ties"}const yn=d({is(t){return t.kind==="OrActionNode"},create(t){return d({kind:"OrActionNode",action:t})}});class K{#e;constructor(e){this.#e=d(e)}values(e){const[n,r]=Ol(e);return new K({...this.#e,queryNode:be.cloneWith(this.#e.queryNode,{columns:n,values:r})})}columns(e){return new K({...this.#e,queryNode:be.cloneWith(this.#e.queryNode,{columns:d(e.map(le.create))})})}expression(e){return new K({...this.#e,queryNode:be.cloneWith(this.#e.queryNode,{values:pn(e)})})}defaultValues(){return new K({...this.#e,queryNode:be.cloneWith(this.#e.queryNode,{defaultValues:!0})})}modifyEnd(e){return new K({...this.#e,queryNode:I.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}ignore(){return new K({...this.#e,queryNode:be.cloneWith(this.#e.queryNode,{orAction:yn.create("ignore")})})}orIgnore(){return new K({...this.#e,queryNode:be.cloneWith(this.#e.queryNode,{orAction:yn.create("ignore")})})}orAbort(){return new K({...this.#e,queryNode:be.cloneWith(this.#e.queryNode,{orAction:yn.create("abort")})})}orFail(){return new K({...this.#e,queryNode:be.cloneWith(this.#e.queryNode,{orAction:yn.create("fail")})})}orReplace(){return new K({...this.#e,queryNode:be.cloneWith(this.#e.queryNode,{orAction:yn.create("replace")})})}orRollback(){return new K({...this.#e,queryNode:be.cloneWith(this.#e.queryNode,{orAction:yn.create("rollback")})})}top(e,n){return new K({...this.#e,queryNode:I.cloneWithTop(this.#e.queryNode,qn(e,n))})}onConflict(e){return new K({...this.#e,queryNode:be.cloneWith(this.#e.queryNode,{onConflict:e(new ft({onConflictNode:Pe.create()})).toOperationNode()})})}onDuplicateKeyUpdate(e){return new K({...this.#e,queryNode:be.cloneWith(this.#e.queryNode,{onDuplicateKey:Px.create(Ho(e))})})}returning(e){return new K({...this.#e,queryNode:I.cloneWithReturning(this.#e.queryNode,Ue(e))})}returningAll(){return new K({...this.#e,queryNode:I.cloneWithReturning(this.#e.queryNode,ze())})}output(e){return new K({...this.#e,queryNode:I.cloneWithOutput(this.#e.queryNode,Ue(e))})}outputAll(e){return new K({...this.#e,queryNode:I.cloneWithOutput(this.#e.queryNode,ze(e))})}clearReturning(){return new K({...this.#e,queryNode:I.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(e,n){return e?n(this):new K({...this.#e})}$castTo(){return new K(this.#e)}$narrowType(){return new K(this.#e)}$assertType(){return new K(this.#e)}withPlugin(e){return new K({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){const e=this.compile(),n=await this.#e.executor.executeQuery(e),{adapter:r}=this.#e.executor,i=e.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new $x(n.insertId,n.numAffectedRows??BigInt(0))]}async executeTakeFirst(){const[e]=await this.execute();return e}async executeTakeFirstOrThrow(e=Mr){const n=await this.executeTakeFirst();if(n===void 0)throw Pr(e)?new e(this.toOperationNode()):e(this.toOperationNode());return n}async*stream(e=100){const n=this.compile(),r=this.#e.executor.stream(n,e);for await(const i of r)yield*i.rows}async explain(e,n){return await new K({...this.#e,queryNode:I.cloneWithExplain(this.#e.queryNode,e,n)}).execute()}}class qx{numDeletedRows;constructor(e){this.numDeletedRows=e}}const Ko=d({is(t){return t.kind==="LimitNode"},create(t){return d({kind:"LimitNode",limit:t})}});class te{#e;constructor(e){this.#e=d(e)}where(...e){return new te({...this.#e,queryNode:I.cloneWithWhere(this.#e.queryNode,ye(e))})}whereRef(e,n,r){return new te({...this.#e,queryNode:I.cloneWithWhere(this.#e.queryNode,at(e,n,r))})}clearWhere(){return new te({...this.#e,queryNode:I.cloneWithoutWhere(this.#e.queryNode)})}top(e,n){return new te({...this.#e,queryNode:I.cloneWithTop(this.#e.queryNode,qn(e,n))})}using(e){return new te({...this.#e,queryNode:Xn.cloneWithUsing(this.#e.queryNode,Cn(e))})}innerJoin(...e){return this.#t("InnerJoin",e)}leftJoin(...e){return this.#t("LeftJoin",e)}rightJoin(...e){return this.#t("RightJoin",e)}fullJoin(...e){return this.#t("FullJoin",e)}#t(e,n){return new te({...this.#e,queryNode:I.cloneWithJoin(this.#e.queryNode,zi(e,n))})}returning(e){return new te({...this.#e,queryNode:I.cloneWithReturning(this.#e.queryNode,Ue(e))})}returningAll(e){return new te({...this.#e,queryNode:I.cloneWithReturning(this.#e.queryNode,ze(e))})}output(e){return new te({...this.#e,queryNode:I.cloneWithOutput(this.#e.queryNode,Ue(e))})}outputAll(e){return new te({...this.#e,queryNode:I.cloneWithOutput(this.#e.queryNode,ze(e))})}clearReturning(){return new te({...this.#e,queryNode:I.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new te({...this.#e,queryNode:Xn.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...e){return new te({...this.#e,queryNode:I.cloneWithOrderByItems(this.#e.queryNode,dn(e))})}clearOrderBy(){return new te({...this.#e,queryNode:I.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new te({...this.#e,queryNode:Xn.cloneWithLimit(this.#e.queryNode,Ko.create(fe(e)))})}modifyEnd(e){return new te({...this.#e,queryNode:I.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}$call(e){return e(this)}$if(e,n){return e?n(this):new te({...this.#e})}$castTo(){return new te(this.#e)}$narrowType(){return new te(this.#e)}$assertType(){return new te(this.#e)}withPlugin(e){return new te({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){const e=this.compile(),n=await this.#e.executor.executeQuery(e),{adapter:r}=this.#e.executor,i=e.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new qx(n.numAffectedRows??BigInt(0))]}async executeTakeFirst(){const[e]=await this.execute();return e}async executeTakeFirstOrThrow(e=Mr){const n=await this.executeTakeFirst();if(n===void 0)throw Pr(e)?new e(this.toOperationNode()):e(this.toOperationNode());return n}async*stream(e=100){const n=this.compile(),r=this.#e.executor.stream(n,e);for await(const i of r)yield*i.rows}async explain(e,n){return await new te({...this.#e,queryNode:I.cloneWithExplain(this.#e.queryNode,e,n)}).execute()}}class Fx{numUpdatedRows;numChangedRows;constructor(e,n){this.numUpdatedRows=e,this.numChangedRows=n}}class X{#e;constructor(e){this.#e=d(e)}where(...e){return new X({...this.#e,queryNode:I.cloneWithWhere(this.#e.queryNode,ye(e))})}whereRef(e,n,r){return new X({...this.#e,queryNode:I.cloneWithWhere(this.#e.queryNode,at(e,n,r))})}clearWhere(){return new X({...this.#e,queryNode:I.cloneWithoutWhere(this.#e.queryNode)})}top(e,n){return new X({...this.#e,queryNode:I.cloneWithTop(this.#e.queryNode,qn(e,n))})}from(e){return new X({...this.#e,queryNode:On.cloneWithFromItems(this.#e.queryNode,Cn(e))})}innerJoin(...e){return this.#t("InnerJoin",e)}leftJoin(...e){return this.#t("LeftJoin",e)}rightJoin(...e){return this.#t("RightJoin",e)}fullJoin(...e){return this.#t("FullJoin",e)}#t(e,n){return new X({...this.#e,queryNode:I.cloneWithJoin(this.#e.queryNode,zi(e,n))})}orderBy(...e){return new X({...this.#e,queryNode:I.cloneWithOrderByItems(this.#e.queryNode,dn(e))})}clearOrderBy(){return new X({...this.#e,queryNode:I.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new X({...this.#e,queryNode:On.cloneWithLimit(this.#e.queryNode,Ko.create(fe(e)))})}set(...e){return new X({...this.#e,queryNode:On.cloneWithUpdates(this.#e.queryNode,Mx(...e))})}returning(e){return new X({...this.#e,queryNode:I.cloneWithReturning(this.#e.queryNode,Ue(e))})}returningAll(e){return new X({...this.#e,queryNode:I.cloneWithReturning(this.#e.queryNode,ze(e))})}output(e){return new X({...this.#e,queryNode:I.cloneWithOutput(this.#e.queryNode,Ue(e))})}outputAll(e){return new X({...this.#e,queryNode:I.cloneWithOutput(this.#e.queryNode,ze(e))})}modifyEnd(e){return new X({...this.#e,queryNode:I.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}clearReturning(){return new X({...this.#e,queryNode:I.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(e,n){return e?n(this):new X({...this.#e})}$castTo(){return new X(this.#e)}$narrowType(){return new X(this.#e)}$assertType(){return new X(this.#e)}withPlugin(e){return new X({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){const e=this.compile(),n=await this.#e.executor.executeQuery(e),{adapter:r}=this.#e.executor,i=e.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new Fx(n.numAffectedRows??BigInt(0),n.numChangedRows)]}async executeTakeFirst(){const[e]=await this.execute();return e}async executeTakeFirstOrThrow(e=Mr){const n=await this.executeTakeFirst();if(n===void 0)throw Pr(e)?new e(this.toOperationNode()):e(this.toOperationNode());return n}async*stream(e=100){const n=this.compile(),r=this.#e.executor.stream(n,e);for await(const i of r)yield*i.rows}async explain(e,n){return await new X({...this.#e,queryNode:I.cloneWithExplain(this.#e.queryNode,e,n)}).execute()}}const Mc=d({is(t){return t.kind==="CommonTableExpressionNameNode"},create(t,e){return d({kind:"CommonTableExpressionNameNode",table:gt.create(t),columns:e?d(e.map(le.create)):void 0})}}),xi=d({is(t){return t.kind==="CommonTableExpressionNode"},create(t,e){return d({kind:"CommonTableExpressionNode",name:t,expression:e})},cloneWith(t,e){return d({...t,...e})}});class vi{#e;constructor(e){this.#e=d(e)}materialized(){return new vi({...this.#e,node:xi.cloneWith(this.#e.node,{materialized:!0})})}notMaterialized(){return new vi({...this.#e,node:xi.cloneWith(this.#e.node,{materialized:!1})})}toOperationNode(){return this.#e.node}}function Pc(t,e){const n=e(Xx()).toOperationNode();return Fe(t)?t(Vx(n)).toOperationNode():xi.create(Tl(t),n)}function Vx(t){return e=>new vi({node:xi.create(Tl(e),t)})}function Tl(t){if(t.includes("(")){const e=t.split(/[\(\)]/),n=e[0],r=e[1].split(",").map(i=>i.trim());return Mc.create(n,r)}else return Mc.create(t)}const Zr=d({is(t){return t.kind==="WithNode"},create(t,e){return d({kind:"WithNode",expressions:d([t]),...e})},cloneWithExpression(t,e){return d({...t,expressions:d([...t.expressions,e])})}}),$c=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"];function _x(t){let e="";for(let n=0;n<t;++n)e+=jx();return e}function jx(){return $c[~~(Math.random()*$c.length)]}function j(){return new Hx}class Hx{#e;get queryId(){return this.#e===void 0&&(this.#e=_x(8)),this.#e}}class Il{nodeStack=[];#e=d({AliasNode:this.transformAlias.bind(this),ColumnNode:this.transformColumn.bind(this),IdentifierNode:this.transformIdentifier.bind(this),SchemableIdentifierNode:this.transformSchemableIdentifier.bind(this),RawNode:this.transformRaw.bind(this),ReferenceNode:this.transformReference.bind(this),SelectQueryNode:this.transformSelectQuery.bind(this),SelectionNode:this.transformSelection.bind(this),TableNode:this.transformTable.bind(this),FromNode:this.transformFrom.bind(this),SelectAllNode:this.transformSelectAll.bind(this),AndNode:this.transformAnd.bind(this),OrNode:this.transformOr.bind(this),ValueNode:this.transformValue.bind(this),ValueListNode:this.transformValueList.bind(this),PrimitiveValueListNode:this.transformPrimitiveValueList.bind(this),ParensNode:this.transformParens.bind(this),JoinNode:this.transformJoin.bind(this),OperatorNode:this.transformOperator.bind(this),WhereNode:this.transformWhere.bind(this),InsertQueryNode:this.transformInsertQuery.bind(this),DeleteQueryNode:this.transformDeleteQuery.bind(this),ReturningNode:this.transformReturning.bind(this),CreateTableNode:this.transformCreateTable.bind(this),AddColumnNode:this.transformAddColumn.bind(this),ColumnDefinitionNode:this.transformColumnDefinition.bind(this),DropTableNode:this.transformDropTable.bind(this),DataTypeNode:this.transformDataType.bind(this),OrderByNode:this.transformOrderBy.bind(this),OrderByItemNode:this.transformOrderByItem.bind(this),GroupByNode:this.transformGroupBy.bind(this),GroupByItemNode:this.transformGroupByItem.bind(this),UpdateQueryNode:this.transformUpdateQuery.bind(this),ColumnUpdateNode:this.transformColumnUpdate.bind(this),LimitNode:this.transformLimit.bind(this),OffsetNode:this.transformOffset.bind(this),OnConflictNode:this.transformOnConflict.bind(this),OnDuplicateKeyNode:this.transformOnDuplicateKey.bind(this),CreateIndexNode:this.transformCreateIndex.bind(this),DropIndexNode:this.transformDropIndex.bind(this),ListNode:this.transformList.bind(this),PrimaryKeyConstraintNode:this.transformPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.transformUniqueConstraint.bind(this),ReferencesNode:this.transformReferences.bind(this),CheckConstraintNode:this.transformCheckConstraint.bind(this),WithNode:this.transformWith.bind(this),CommonTableExpressionNode:this.transformCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.transformCommonTableExpressionName.bind(this),HavingNode:this.transformHaving.bind(this),CreateSchemaNode:this.transformCreateSchema.bind(this),DropSchemaNode:this.transformDropSchema.bind(this),AlterTableNode:this.transformAlterTable.bind(this),DropColumnNode:this.transformDropColumn.bind(this),RenameColumnNode:this.transformRenameColumn.bind(this),AlterColumnNode:this.transformAlterColumn.bind(this),ModifyColumnNode:this.transformModifyColumn.bind(this),AddConstraintNode:this.transformAddConstraint.bind(this),DropConstraintNode:this.transformDropConstraint.bind(this),RenameConstraintNode:this.transformRenameConstraint.bind(this),ForeignKeyConstraintNode:this.transformForeignKeyConstraint.bind(this),CreateViewNode:this.transformCreateView.bind(this),RefreshMaterializedViewNode:this.transformRefreshMaterializedView.bind(this),DropViewNode:this.transformDropView.bind(this),GeneratedNode:this.transformGenerated.bind(this),DefaultValueNode:this.transformDefaultValue.bind(this),OnNode:this.transformOn.bind(this),ValuesNode:this.transformValues.bind(this),SelectModifierNode:this.transformSelectModifier.bind(this),CreateTypeNode:this.transformCreateType.bind(this),DropTypeNode:this.transformDropType.bind(this),ExplainNode:this.transformExplain.bind(this),DefaultInsertValueNode:this.transformDefaultInsertValue.bind(this),AggregateFunctionNode:this.transformAggregateFunction.bind(this),OverNode:this.transformOver.bind(this),PartitionByNode:this.transformPartitionBy.bind(this),PartitionByItemNode:this.transformPartitionByItem.bind(this),SetOperationNode:this.transformSetOperation.bind(this),BinaryOperationNode:this.transformBinaryOperation.bind(this),UnaryOperationNode:this.transformUnaryOperation.bind(this),UsingNode:this.transformUsing.bind(this),FunctionNode:this.transformFunction.bind(this),CaseNode:this.transformCase.bind(this),WhenNode:this.transformWhen.bind(this),JSONReferenceNode:this.transformJSONReference.bind(this),JSONPathNode:this.transformJSONPath.bind(this),JSONPathLegNode:this.transformJSONPathLeg.bind(this),JSONOperatorChainNode:this.transformJSONOperatorChain.bind(this),TupleNode:this.transformTuple.bind(this),MergeQueryNode:this.transformMergeQuery.bind(this),MatchedNode:this.transformMatched.bind(this),AddIndexNode:this.transformAddIndex.bind(this),CastNode:this.transformCast.bind(this),FetchNode:this.transformFetch.bind(this),TopNode:this.transformTop.bind(this),OutputNode:this.transformOutput.bind(this),OrActionNode:this.transformOrAction.bind(this),CollateNode:this.transformCollate.bind(this)});transformNode(e,n){if(!e)return e;this.nodeStack.push(e);const r=this.transformNodeImpl(e,n);return this.nodeStack.pop(),d(r)}transformNodeImpl(e,n){return this.#e[e.kind](e,n)}transformNodeList(e,n){return e&&d(e.map(r=>this.transformNode(r,n)))}transformSelectQuery(e,n){return{kind:"SelectQueryNode",from:this.transformNode(e.from,n),selections:this.transformNodeList(e.selections,n),distinctOn:this.transformNodeList(e.distinctOn,n),joins:this.transformNodeList(e.joins,n),groupBy:this.transformNode(e.groupBy,n),orderBy:this.transformNode(e.orderBy,n),where:this.transformNode(e.where,n),frontModifiers:this.transformNodeList(e.frontModifiers,n),endModifiers:this.transformNodeList(e.endModifiers,n),limit:this.transformNode(e.limit,n),offset:this.transformNode(e.offset,n),with:this.transformNode(e.with,n),having:this.transformNode(e.having,n),explain:this.transformNode(e.explain,n),setOperations:this.transformNodeList(e.setOperations,n),fetch:this.transformNode(e.fetch,n),top:this.transformNode(e.top,n)}}transformSelection(e,n){return{kind:"SelectionNode",selection:this.transformNode(e.selection,n)}}transformColumn(e,n){return{kind:"ColumnNode",column:this.transformNode(e.column,n)}}transformAlias(e,n){return{kind:"AliasNode",node:this.transformNode(e.node,n),alias:this.transformNode(e.alias,n)}}transformTable(e,n){return{kind:"TableNode",table:this.transformNode(e.table,n)}}transformFrom(e,n){return{kind:"FromNode",froms:this.transformNodeList(e.froms,n)}}transformReference(e,n){return{kind:"ReferenceNode",column:this.transformNode(e.column,n),table:this.transformNode(e.table,n)}}transformAnd(e,n){return{kind:"AndNode",left:this.transformNode(e.left,n),right:this.transformNode(e.right,n)}}transformOr(e,n){return{kind:"OrNode",left:this.transformNode(e.left,n),right:this.transformNode(e.right,n)}}transformValueList(e,n){return{kind:"ValueListNode",values:this.transformNodeList(e.values,n)}}transformParens(e,n){return{kind:"ParensNode",node:this.transformNode(e.node,n)}}transformJoin(e,n){return{kind:"JoinNode",joinType:e.joinType,table:this.transformNode(e.table,n),on:this.transformNode(e.on,n)}}transformRaw(e,n){return{kind:"RawNode",sqlFragments:d([...e.sqlFragments]),parameters:this.transformNodeList(e.parameters,n)}}transformWhere(e,n){return{kind:"WhereNode",where:this.transformNode(e.where,n)}}transformInsertQuery(e,n){return{kind:"InsertQueryNode",into:this.transformNode(e.into,n),columns:this.transformNodeList(e.columns,n),values:this.transformNode(e.values,n),returning:this.transformNode(e.returning,n),onConflict:this.transformNode(e.onConflict,n),onDuplicateKey:this.transformNode(e.onDuplicateKey,n),endModifiers:this.transformNodeList(e.endModifiers,n),with:this.transformNode(e.with,n),ignore:e.ignore,orAction:this.transformNode(e.orAction,n),replace:e.replace,explain:this.transformNode(e.explain,n),defaultValues:e.defaultValues,top:this.transformNode(e.top,n),output:this.transformNode(e.output,n)}}transformValues(e,n){return{kind:"ValuesNode",values:this.transformNodeList(e.values,n)}}transformDeleteQuery(e,n){return{kind:"DeleteQueryNode",from:this.transformNode(e.from,n),using:this.transformNode(e.using,n),joins:this.transformNodeList(e.joins,n),where:this.transformNode(e.where,n),returning:this.transformNode(e.returning,n),endModifiers:this.transformNodeList(e.endModifiers,n),with:this.transformNode(e.with,n),orderBy:this.transformNode(e.orderBy,n),limit:this.transformNode(e.limit,n),explain:this.transformNode(e.explain,n),top:this.transformNode(e.top,n),output:this.transformNode(e.output,n)}}transformReturning(e,n){return{kind:"ReturningNode",selections:this.transformNodeList(e.selections,n)}}transformCreateTable(e,n){return{kind:"CreateTableNode",table:this.transformNode(e.table,n),columns:this.transformNodeList(e.columns,n),constraints:this.transformNodeList(e.constraints,n),temporary:e.temporary,ifNotExists:e.ifNotExists,onCommit:e.onCommit,frontModifiers:this.transformNodeList(e.frontModifiers,n),endModifiers:this.transformNodeList(e.endModifiers,n),selectQuery:this.transformNode(e.selectQuery,n)}}transformColumnDefinition(e,n){return{kind:"ColumnDefinitionNode",column:this.transformNode(e.column,n),dataType:this.transformNode(e.dataType,n),references:this.transformNode(e.references,n),primaryKey:e.primaryKey,autoIncrement:e.autoIncrement,unique:e.unique,notNull:e.notNull,unsigned:e.unsigned,defaultTo:this.transformNode(e.defaultTo,n),check:this.transformNode(e.check,n),generated:this.transformNode(e.generated,n),frontModifiers:this.transformNodeList(e.frontModifiers,n),endModifiers:this.transformNodeList(e.endModifiers,n),nullsNotDistinct:e.nullsNotDistinct,identity:e.identity,ifNotExists:e.ifNotExists}}transformAddColumn(e,n){return{kind:"AddColumnNode",column:this.transformNode(e.column,n)}}transformDropTable(e,n){return{kind:"DropTableNode",table:this.transformNode(e.table,n),ifExists:e.ifExists,cascade:e.cascade}}transformOrderBy(e,n){return{kind:"OrderByNode",items:this.transformNodeList(e.items,n)}}transformOrderByItem(e,n){return{kind:"OrderByItemNode",orderBy:this.transformNode(e.orderBy,n),direction:this.transformNode(e.direction,n),collation:this.transformNode(e.collation,n),nulls:e.nulls}}transformGroupBy(e,n){return{kind:"GroupByNode",items:this.transformNodeList(e.items,n)}}transformGroupByItem(e,n){return{kind:"GroupByItemNode",groupBy:this.transformNode(e.groupBy,n)}}transformUpdateQuery(e,n){return{kind:"UpdateQueryNode",table:this.transformNode(e.table,n),from:this.transformNode(e.from,n),joins:this.transformNodeList(e.joins,n),where:this.transformNode(e.where,n),updates:this.transformNodeList(e.updates,n),returning:this.transformNode(e.returning,n),endModifiers:this.transformNodeList(e.endModifiers,n),with:this.transformNode(e.with,n),explain:this.transformNode(e.explain,n),limit:this.transformNode(e.limit,n),top:this.transformNode(e.top,n),output:this.transformNode(e.output,n),orderBy:this.transformNode(e.orderBy,n)}}transformColumnUpdate(e,n){return{kind:"ColumnUpdateNode",column:this.transformNode(e.column,n),value:this.transformNode(e.value,n)}}transformLimit(e,n){return{kind:"LimitNode",limit:this.transformNode(e.limit,n)}}transformOffset(e,n){return{kind:"OffsetNode",offset:this.transformNode(e.offset,n)}}transformOnConflict(e,n){return{kind:"OnConflictNode",columns:this.transformNodeList(e.columns,n),constraint:this.transformNode(e.constraint,n),indexExpression:this.transformNode(e.indexExpression,n),indexWhere:this.transformNode(e.indexWhere,n),updates:this.transformNodeList(e.updates,n),updateWhere:this.transformNode(e.updateWhere,n),doNothing:e.doNothing}}transformOnDuplicateKey(e,n){return{kind:"OnDuplicateKeyNode",updates:this.transformNodeList(e.updates,n)}}transformCreateIndex(e,n){return{kind:"CreateIndexNode",name:this.transformNode(e.name,n),table:this.transformNode(e.table,n),columns:this.transformNodeList(e.columns,n),unique:e.unique,using:this.transformNode(e.using,n),ifNotExists:e.ifNotExists,where:this.transformNode(e.where,n),nullsNotDistinct:e.nullsNotDistinct}}transformList(e,n){return{kind:"ListNode",items:this.transformNodeList(e.items,n)}}transformDropIndex(e,n){return{kind:"DropIndexNode",name:this.transformNode(e.name,n),table:this.transformNode(e.table,n),ifExists:e.ifExists,cascade:e.cascade}}transformPrimaryKeyConstraint(e,n){return{kind:"PrimaryKeyConstraintNode",columns:this.transformNodeList(e.columns,n),name:this.transformNode(e.name,n),deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred}}transformUniqueConstraint(e,n){return{kind:"UniqueConstraintNode",columns:this.transformNodeList(e.columns,n),name:this.transformNode(e.name,n),nullsNotDistinct:e.nullsNotDistinct,deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred}}transformForeignKeyConstraint(e,n){return{kind:"ForeignKeyConstraintNode",columns:this.transformNodeList(e.columns,n),references:this.transformNode(e.references,n),name:this.transformNode(e.name,n),onDelete:e.onDelete,onUpdate:e.onUpdate,deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred}}transformSetOperation(e,n){return{kind:"SetOperationNode",operator:e.operator,expression:this.transformNode(e.expression,n),all:e.all}}transformReferences(e,n){return{kind:"ReferencesNode",table:this.transformNode(e.table,n),columns:this.transformNodeList(e.columns,n),onDelete:e.onDelete,onUpdate:e.onUpdate}}transformCheckConstraint(e,n){return{kind:"CheckConstraintNode",expression:this.transformNode(e.expression,n),name:this.transformNode(e.name,n)}}transformWith(e,n){return{kind:"WithNode",expressions:this.transformNodeList(e.expressions,n),recursive:e.recursive}}transformCommonTableExpression(e,n){return{kind:"CommonTableExpressionNode",name:this.transformNode(e.name,n),materialized:e.materialized,expression:this.transformNode(e.expression,n)}}transformCommonTableExpressionName(e,n){return{kind:"CommonTableExpressionNameNode",table:this.transformNode(e.table,n),columns:this.transformNodeList(e.columns,n)}}transformHaving(e,n){return{kind:"HavingNode",having:this.transformNode(e.having,n)}}transformCreateSchema(e,n){return{kind:"CreateSchemaNode",schema:this.transformNode(e.schema,n),ifNotExists:e.ifNotExists}}transformDropSchema(e,n){return{kind:"DropSchemaNode",schema:this.transformNode(e.schema,n),ifExists:e.ifExists,cascade:e.cascade}}transformAlterTable(e,n){return{kind:"AlterTableNode",table:this.transformNode(e.table,n),renameTo:this.transformNode(e.renameTo,n),setSchema:this.transformNode(e.setSchema,n),columnAlterations:this.transformNodeList(e.columnAlterations,n),addConstraint:this.transformNode(e.addConstraint,n),dropConstraint:this.transformNode(e.dropConstraint,n),renameConstraint:this.transformNode(e.renameConstraint,n),addIndex:this.transformNode(e.addIndex,n),dropIndex:this.transformNode(e.dropIndex,n)}}transformDropColumn(e,n){return{kind:"DropColumnNode",column:this.transformNode(e.column,n)}}transformRenameColumn(e,n){return{kind:"RenameColumnNode",column:this.transformNode(e.column,n),renameTo:this.transformNode(e.renameTo,n)}}transformAlterColumn(e,n){return{kind:"AlterColumnNode",column:this.transformNode(e.column,n),dataType:this.transformNode(e.dataType,n),dataTypeExpression:this.transformNode(e.dataTypeExpression,n),setDefault:this.transformNode(e.setDefault,n),dropDefault:e.dropDefault,setNotNull:e.setNotNull,dropNotNull:e.dropNotNull}}transformModifyColumn(e,n){return{kind:"ModifyColumnNode",column:this.transformNode(e.column,n)}}transformAddConstraint(e,n){return{kind:"AddConstraintNode",constraint:this.transformNode(e.constraint,n)}}transformDropConstraint(e,n){return{kind:"DropConstraintNode",constraintName:this.transformNode(e.constraintName,n),ifExists:e.ifExists,modifier:e.modifier}}transformRenameConstraint(e,n){return{kind:"RenameConstraintNode",oldName:this.transformNode(e.oldName,n),newName:this.transformNode(e.newName,n)}}transformCreateView(e,n){return{kind:"CreateViewNode",name:this.transformNode(e.name,n),temporary:e.temporary,orReplace:e.orReplace,ifNotExists:e.ifNotExists,materialized:e.materialized,columns:this.transformNodeList(e.columns,n),as:this.transformNode(e.as,n)}}transformRefreshMaterializedView(e,n){return{kind:"RefreshMaterializedViewNode",name:this.transformNode(e.name,n),concurrently:e.concurrently,withNoData:e.withNoData}}transformDropView(e,n){return{kind:"DropViewNode",name:this.transformNode(e.name,n),ifExists:e.ifExists,materialized:e.materialized,cascade:e.cascade}}transformGenerated(e,n){return{kind:"GeneratedNode",byDefault:e.byDefault,always:e.always,identity:e.identity,stored:e.stored,expression:this.transformNode(e.expression,n)}}transformDefaultValue(e,n){return{kind:"DefaultValueNode",defaultValue:this.transformNode(e.defaultValue,n)}}transformOn(e,n){return{kind:"OnNode",on:this.transformNode(e.on,n)}}transformSelectModifier(e,n){return{kind:"SelectModifierNode",modifier:e.modifier,rawModifier:this.transformNode(e.rawModifier,n),of:this.transformNodeList(e.of,n)}}transformCreateType(e,n){return{kind:"CreateTypeNode",name:this.transformNode(e.name,n),enum:this.transformNode(e.enum,n)}}transformDropType(e,n){return{kind:"DropTypeNode",name:this.transformNode(e.name,n),ifExists:e.ifExists}}transformExplain(e,n){return{kind:"ExplainNode",format:e.format,options:this.transformNode(e.options,n)}}transformSchemableIdentifier(e,n){return{kind:"SchemableIdentifierNode",schema:this.transformNode(e.schema,n),identifier:this.transformNode(e.identifier,n)}}transformAggregateFunction(e,n){return{kind:"AggregateFunctionNode",func:e.func,aggregated:this.transformNodeList(e.aggregated,n),distinct:e.distinct,orderBy:this.transformNode(e.orderBy,n),withinGroup:this.transformNode(e.withinGroup,n),filter:this.transformNode(e.filter,n),over:this.transformNode(e.over,n)}}transformOver(e,n){return{kind:"OverNode",orderBy:this.transformNode(e.orderBy,n),partitionBy:this.transformNode(e.partitionBy,n)}}transformPartitionBy(e,n){return{kind:"PartitionByNode",items:this.transformNodeList(e.items,n)}}transformPartitionByItem(e,n){return{kind:"PartitionByItemNode",partitionBy:this.transformNode(e.partitionBy,n)}}transformBinaryOperation(e,n){return{kind:"BinaryOperationNode",leftOperand:this.transformNode(e.leftOperand,n),operator:this.transformNode(e.operator,n),rightOperand:this.transformNode(e.rightOperand,n)}}transformUnaryOperation(e,n){return{kind:"UnaryOperationNode",operator:this.transformNode(e.operator,n),operand:this.transformNode(e.operand,n)}}transformUsing(e,n){return{kind:"UsingNode",tables:this.transformNodeList(e.tables,n)}}transformFunction(e,n){return{kind:"FunctionNode",func:e.func,arguments:this.transformNodeList(e.arguments,n)}}transformCase(e,n){return{kind:"CaseNode",value:this.transformNode(e.value,n),when:this.transformNodeList(e.when,n),else:this.transformNode(e.else,n),isStatement:e.isStatement}}transformWhen(e,n){return{kind:"WhenNode",condition:this.transformNode(e.condition,n),result:this.transformNode(e.result,n)}}transformJSONReference(e,n){return{kind:"JSONReferenceNode",reference:this.transformNode(e.reference,n),traversal:this.transformNode(e.traversal,n)}}transformJSONPath(e,n){return{kind:"JSONPathNode",inOperator:this.transformNode(e.inOperator,n),pathLegs:this.transformNodeList(e.pathLegs,n)}}transformJSONPathLeg(e,n){return{kind:"JSONPathLegNode",type:e.type,value:e.value}}transformJSONOperatorChain(e,n){return{kind:"JSONOperatorChainNode",operator:this.transformNode(e.operator,n),values:this.transformNodeList(e.values,n)}}transformTuple(e,n){return{kind:"TupleNode",values:this.transformNodeList(e.values,n)}}transformMergeQuery(e,n){return{kind:"MergeQueryNode",into:this.transformNode(e.into,n),using:this.transformNode(e.using,n),whens:this.transformNodeList(e.whens,n),with:this.transformNode(e.with,n),top:this.transformNode(e.top,n),endModifiers:this.transformNodeList(e.endModifiers,n),output:this.transformNode(e.output,n),returning:this.transformNode(e.returning,n)}}transformMatched(e,n){return{kind:"MatchedNode",not:e.not,bySource:e.bySource}}transformAddIndex(e,n){return{kind:"AddIndexNode",name:this.transformNode(e.name,n),columns:this.transformNodeList(e.columns,n),unique:e.unique,using:this.transformNode(e.using,n),ifNotExists:e.ifNotExists}}transformCast(e,n){return{kind:"CastNode",expression:this.transformNode(e.expression,n),dataType:this.transformNode(e.dataType,n)}}transformFetch(e,n){return{kind:"FetchNode",rowCount:this.transformNode(e.rowCount,n),modifier:e.modifier}}transformTop(e,n){return{kind:"TopNode",expression:e.expression,modifiers:e.modifiers}}transformOutput(e,n){return{kind:"OutputNode",selections:this.transformNodeList(e.selections,n)}}transformDataType(e,n){return e}transformSelectAll(e,n){return e}transformIdentifier(e,n){return e}transformValue(e,n){return e}transformPrimitiveValueList(e,n){return e}transformOperator(e,n){return e}transformDefaultInsertValue(e,n){return e}transformOrAction(e,n){return e}transformCollate(e,n){return e}}const Kx=d({AlterTableNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,RefreshMaterializedViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0}),zx={json_agg:!0,to_json:!0};class Jx extends Il{#e;#t=new Set;#n=new Set;constructor(e){super(),this.#e=e}transformNodeImpl(e,n){if(!this.#i(e))return super.transformNodeImpl(e,n);const r=this.#s(e);for(const o of r)this.#n.add(o);const i=this.#c(e);for(const o of i)this.#t.add(o);const s=super.transformNodeImpl(e,n);for(const o of i)this.#t.delete(o);for(const o of r)this.#n.delete(o);return s}transformSchemableIdentifier(e,n){const r=super.transformSchemableIdentifier(e,n);return r.schema||!this.#t.has(e.identifier.name)?r:{...r,schema:G.create(this.#e)}}transformReferences(e,n){const r=super.transformReferences(e,n);return r.table.table.schema?r:{...r,table:gt.createWithSchema(this.#e,r.table.table.identifier.name)}}transformAggregateFunction(e,n){return{...super.transformAggregateFunction({...e,aggregated:[]},n),aggregated:this.#r(e,n,"aggregated")}}transformFunction(e,n){return{...super.transformFunction({...e,arguments:[]},n),arguments:this.#r(e,n,"arguments")}}#r(e,n,r){return zx[e.func]?e[r].map(i=>!gt.is(i)||i.table.schema?this.transformNode(i,n):{...i,table:this.transformIdentifier(i.table.identifier,n)}):this.transformNodeList(e[r],n)}#i(e){return e.kind in Kx}#c(e){const n=new Set;if("name"in e&&e.name&&Et.is(e.name)&&this.#a(e.name,n),"from"in e&&e.from)for(const r of e.from.froms)this.#o(r,n);if("into"in e&&e.into&&this.#o(e.into,n),"table"in e&&e.table&&this.#o(e.table,n),"joins"in e&&e.joins)for(const r of e.joins)this.#o(r.table,n);return"using"in e&&e.using&&(an.is(e.using)?this.#o(e.using.table,n):this.#o(e.using,n)),n}#s(e){const n=new Set;return"with"in e&&e.with&&this.#d(e.with,n),n}#o(e,n){if(gt.is(e))this.#a(e.table,n);else if(St.is(e)&>.is(e.node))this.#a(e.node.table,n);else if(Al.is(e))for(const r of e.items)this.#o(r,n)}#a(e,n){const r=e.identifier.name;!this.#t.has(r)&&!this.#n.has(r)&&n.add(r)}#d(e,n){for(const r of e.expressions){const i=r.name.table.table.identifier.name;this.#n.has(i)||n.add(i)}}}class fn{#e;constructor(e){this.#e=new Jx(e)}transformQuery(e){return this.#e.transformNode(e.node,e.queryId)}async transformResult(e){return e.result}}const Gx=d({is(t){return t.kind==="MatchedNode"},create(t,e=!1){return d({kind:"MatchedNode",not:t,bySource:e})}});function Lc(t,e,n){return un.create(gi([Gx.create(!t.isMatched,t.bySource),...e&&e.length>0?[e.length===3&&n?at(e[0],e[1],e[2]):ye(e)]:[]],"and",!1))}function ir(t){return Ae(t)?de.create([t],[]):Oe(t)?t.toOperationNode():t}class Bc{#e;#t;#n;constructor(){this.#e=new Promise((e,n)=>{this.#n=n,this.#t=e})}get promise(){return this.#e}resolve=e=>{this.#t&&this.#t(e)};reject=e=>{this.#n&&this.#n(e)}}async function Rl(t){const e=new Bc,n=new Bc;return t.provideConnection(async r=>(e.resolve(r),await n.promise)).catch(r=>e.reject(r)),d({connection:await e.promise,release:n.resolve})}const Zx=d([]);class Wl{#e;constructor(e=Zx){this.#e=e}get plugins(){return this.#e}transformQuery(e,n){for(const r of this.#e){const i=r.transformQuery({node:e,queryId:n});if(i.kind===e.kind)e=i;else throw new Error(["KyselyPlugin.transformQuery must return a node","of the same kind that was given to it.",`The plugin was given a ${e.kind}`,`but it returned a ${i.kind}`].join(" "))}return e}async executeQuery(e){return await this.provideConnection(async n=>{const r=await n.executeQuery(e);return"numUpdatedOrDeletedRows"in r&&Un("kysely:warning: outdated driver/plugin detected! `QueryResult.numUpdatedOrDeletedRows` has been replaced with `QueryResult.numAffectedRows`."),await this.#t(r,e.queryId)})}async*stream(e,n){const{connection:r,release:i}=await Rl(this);try{for await(const s of r.streamQuery(e,n))yield await this.#t(s,e.queryId)}finally{i()}}async#t(e,n){for(const r of this.#e)e=await r.transformResult({result:e,queryId:n});return e}}class kn extends Wl{get adapter(){throw new Error("this query cannot be compiled to SQL")}compileQuery(){throw new Error("this query cannot be compiled to SQL")}provideConnection(){throw new Error("this query cannot be executed")}withConnectionProvider(){throw new Error("this query cannot have a connection provider")}withPlugin(e){return new kn([...this.plugins,e])}withPlugins(e){return new kn([...this.plugins,...e])}withPluginAtFront(e){return new kn([e,...this.plugins])}withoutPlugins(){return new kn([])}}const Ki=new kn;class Yx{numChangedRows;constructor(e){this.numChangedRows=e}}class Wt{#e;constructor(e){this.#e=d(e)}modifyEnd(e){return new Wt({...this.#e,queryNode:I.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,n){return new Wt({...this.#e,queryNode:I.cloneWithTop(this.#e.queryNode,qn(e,n))})}using(...e){return new Ie({...this.#e,queryNode:it.cloneWithUsing(this.#e.queryNode,zi("Using",e))})}returning(e){return new Wt({...this.#e,queryNode:I.cloneWithReturning(this.#e.queryNode,Ue(e))})}returningAll(e){return new Wt({...this.#e,queryNode:I.cloneWithReturning(this.#e.queryNode,ze(e))})}output(e){return new Wt({...this.#e,queryNode:I.cloneWithOutput(this.#e.queryNode,Ue(e))})}outputAll(e){return new Wt({...this.#e,queryNode:I.cloneWithOutput(this.#e.queryNode,ze(e))})}}class Ie{#e;constructor(e){this.#e=d(e)}modifyEnd(e){return new Ie({...this.#e,queryNode:I.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,n){return new Ie({...this.#e,queryNode:I.cloneWithTop(this.#e.queryNode,qn(e,n))})}whenMatched(){return this.#t([])}whenMatchedAnd(...e){return this.#t(e)}whenMatchedAndRef(e,n,r){return this.#t([e,n,r],!0)}#t(e,n){return new Uc({...this.#e,queryNode:it.cloneWithWhen(this.#e.queryNode,Lc({isMatched:!0},e,n))})}whenNotMatched(){return this.#n([])}whenNotMatchedAnd(...e){return this.#n(e)}whenNotMatchedAndRef(e,n,r){return this.#n([e,n,r],!0)}whenNotMatchedBySource(){return this.#n([],!1,!0)}whenNotMatchedBySourceAnd(...e){return this.#n(e,!1,!0)}whenNotMatchedBySourceAndRef(e,n,r){return this.#n([e,n,r],!0,!0)}returning(e){return new Ie({...this.#e,queryNode:I.cloneWithReturning(this.#e.queryNode,Ue(e))})}returningAll(e){return new Ie({...this.#e,queryNode:I.cloneWithReturning(this.#e.queryNode,ze(e))})}output(e){return new Ie({...this.#e,queryNode:I.cloneWithOutput(this.#e.queryNode,Ue(e))})}outputAll(e){return new Ie({...this.#e,queryNode:I.cloneWithOutput(this.#e.queryNode,ze(e))})}#n(e,n=!1,r=!1){const i={...this.#e,queryNode:it.cloneWithWhen(this.#e.queryNode,Lc({isMatched:!1,bySource:r},e,n))},s=r?Uc:Qx;return new s(i)}$call(e){return e(this)}$if(e,n){return e?n(this):new Ie({...this.#e})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){const e=this.compile(),n=await this.#e.executor.executeQuery(e),{adapter:r}=this.#e.executor,i=e.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new Yx(n.numAffectedRows)]}async executeTakeFirst(){const[e]=await this.execute();return e}async executeTakeFirstOrThrow(e=Mr){const n=await this.executeTakeFirst();if(n===void 0)throw Pr(e)?new e(this.toOperationNode()):e(this.toOperationNode());return n}}class Uc{#e;constructor(e){this.#e=d(e)}thenDelete(){return new Ie({...this.#e,queryNode:it.cloneWithThen(this.#e.queryNode,ir("delete"))})}thenDoNothing(){return new Ie({...this.#e,queryNode:it.cloneWithThen(this.#e.queryNode,ir("do nothing"))})}thenUpdate(e){return new Ie({...this.#e,queryNode:it.cloneWithThen(this.#e.queryNode,ir(e(new X({queryId:this.#e.queryId,executor:Ki,queryNode:On.createWithoutTable()}))))})}thenUpdateSet(...e){return this.thenUpdate(n=>n.set(...e))}}class Qx{#e;constructor(e){this.#e=d(e)}thenDoNothing(){return new Ie({...this.#e,queryNode:it.cloneWithThen(this.#e.queryNode,ir("do nothing"))})}thenInsertValues(e){const[n,r]=Ol(e);return new Ie({...this.#e,queryNode:it.cloneWithThen(this.#e.queryNode,ir(be.cloneWith(be.createWithoutInto(),{columns:n,values:r})))})}}class Ut{#e;constructor(e){this.#e=d(e)}selectFrom(e){return zs({queryId:j(),executor:this.#e.executor,queryNode:Q.createFrom(Cn(e),this.#e.withNode)})}selectNoFrom(e){return zs({queryId:j(),executor:this.#e.executor,queryNode:Q.cloneWithSelections(Q.create(this.#e.withNode),Ue(e))})}insertInto(e){return new K({queryId:j(),executor:this.#e.executor,queryNode:be.create(ue(e),this.#e.withNode)})}replaceInto(e){return new K({queryId:j(),executor:this.#e.executor,queryNode:be.create(ue(e),this.#e.withNode,!0)})}deleteFrom(e){return new te({queryId:j(),executor:this.#e.executor,queryNode:Xn.create(Cn(e),this.#e.withNode)})}updateTable(e){return new X({queryId:j(),executor:this.#e.executor,queryNode:On.create(Cn(e),this.#e.withNode)})}mergeInto(e){return new Wt({queryId:j(),executor:this.#e.executor,queryNode:it.create(Ul(e),this.#e.withNode)})}with(e,n){const r=Pc(e,n);return new Ut({...this.#e,withNode:this.#e.withNode?Zr.cloneWithExpression(this.#e.withNode,r):Zr.create(r)})}withRecursive(e,n){const r=Pc(e,n);return new Ut({...this.#e,withNode:this.#e.withNode?Zr.cloneWithExpression(this.#e.withNode,r):Zr.create(r,{recursive:!0})})}withPlugin(e){return new Ut({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new Ut({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new Ut({...this.#e,executor:this.#e.executor.withPluginAtFront(new fn(e))})}}function Xx(){return new Ut({executor:Ki})}function ev(t,e){return new er({joinNode:an.create(t,kr(e))})}function tv(){return new tr({overNode:Ks.create()})}function zi(t,e){if(e.length===3)return rv(t,e[0],e[1],e[2]);if(e.length===2)return nv(t,e[0],e[1]);if(e.length===1)return iv(t,e[0]);throw new Error("not implemented")}function nv(t,e,n){return n(ev(t,e)).toOperationNode()}function rv(t,e,n,r){return an.createWithOn(t,kr(e),at(n,"=",r))}function iv(t,e){return an.create(t,kr(e))}const sv=d({is(t){return t.kind==="OffsetNode"},create(t){return d({kind:"OffsetNode",offset:t})}}),ov=d({is(t){return t.kind==="GroupByItemNode"},create(t){return d({kind:"GroupByItemNode",groupBy:t})}});function av(t){return t=Fe(t)?t(Fn()):t,Er(t).map(ov.create)}const Ml=d({is(t){return t.kind==="SetOperationNode"},create(t,e,n){return d({kind:"SetOperationNode",operator:t,expression:e,all:n})}});function gn(t,e,n){return Fe(e)&&(e=e(Jo())),vt(e)||(e=[e]),e.map(r=>Ml.create(t,pn(r),n))}class z{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new zo(this,e)}or(...e){return new Ei(Bn.create(this.#e,ye(e)))}and(...e){return new Di(Ht.create(this.#e,ye(e)))}$castTo(){return new z(this.#e)}$notNull(){return new z(this.#e)}toOperationNode(){return this.#e}}class zo{#e;#t;constructor(e,n){this.#e=e,this.#t=n}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return St.create(this.#e.toOperationNode(),Oe(this.#t)?this.#t.toOperationNode():G.create(this.#t))}}class Ei{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new zo(this,e)}or(...e){return new Ei(Bn.create(this.#e,ye(e)))}$castTo(){return new Ei(this.#e)}toOperationNode(){return Nt.create(this.#e)}}class Di{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new zo(this,e)}and(...e){return new Di(Ht.create(this.#e,ye(e)))}$castTo(){return new Di(this.#e)}toOperationNode(){return Nt.create(this.#e)}}const cv={is(t){return t.kind==="FetchNode"},create(t,e){return{kind:"FetchNode",rowCount:Ke.create(t),modifier:e}}};function dv(t,e){if(!_i(t)&&!Uo(t))throw new Error(`Invalid fetch row count: ${t}`);if(!uv(e))throw new Error(`Invalid fetch modifier: ${e}`);return cv.create(t,e)}function uv(t){return t==="only"||t==="with ties"}class F{#e;constructor(e){this.#e=d(e)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...e){return new F({...this.#e,queryNode:I.cloneWithWhere(this.#e.queryNode,ye(e))})}whereRef(e,n,r){return new F({...this.#e,queryNode:I.cloneWithWhere(this.#e.queryNode,at(e,n,r))})}having(...e){return new F({...this.#e,queryNode:Q.cloneWithHaving(this.#e.queryNode,ye(e))})}havingRef(e,n,r){return new F({...this.#e,queryNode:Q.cloneWithHaving(this.#e.queryNode,at(e,n,r))})}select(e){return new F({...this.#e,queryNode:Q.cloneWithSelections(this.#e.queryNode,Ue(e))})}distinctOn(e){return new F({...this.#e,queryNode:Q.cloneWithDistinctOn(this.#e.queryNode,Er(e))})}modifyFront(e){return new F({...this.#e,queryNode:Q.cloneWithFrontModifier(this.#e.queryNode,lt.createWithExpression(e.toOperationNode()))})}modifyEnd(e){return new F({...this.#e,queryNode:I.cloneWithEndModifier(this.#e.queryNode,lt.createWithExpression(e.toOperationNode()))})}distinct(){return new F({...this.#e,queryNode:Q.cloneWithFrontModifier(this.#e.queryNode,lt.create("Distinct"))})}forUpdate(e){return new F({...this.#e,queryNode:I.cloneWithEndModifier(this.#e.queryNode,lt.create("ForUpdate",e?Gr(e).map(ue):void 0))})}forShare(e){return new F({...this.#e,queryNode:I.cloneWithEndModifier(this.#e.queryNode,lt.create("ForShare",e?Gr(e).map(ue):void 0))})}forKeyShare(e){return new F({...this.#e,queryNode:I.cloneWithEndModifier(this.#e.queryNode,lt.create("ForKeyShare",e?Gr(e).map(ue):void 0))})}forNoKeyUpdate(e){return new F({...this.#e,queryNode:I.cloneWithEndModifier(this.#e.queryNode,lt.create("ForNoKeyUpdate",e?Gr(e).map(ue):void 0))})}skipLocked(){return new F({...this.#e,queryNode:I.cloneWithEndModifier(this.#e.queryNode,lt.create("SkipLocked"))})}noWait(){return new F({...this.#e,queryNode:I.cloneWithEndModifier(this.#e.queryNode,lt.create("NoWait"))})}selectAll(e){return new F({...this.#e,queryNode:Q.cloneWithSelections(this.#e.queryNode,ze(e))})}innerJoin(...e){return this.#t("InnerJoin",e)}leftJoin(...e){return this.#t("LeftJoin",e)}rightJoin(...e){return this.#t("RightJoin",e)}fullJoin(...e){return this.#t("FullJoin",e)}crossJoin(...e){return this.#t("CrossJoin",e)}innerJoinLateral(...e){return this.#t("LateralInnerJoin",e)}leftJoinLateral(...e){return this.#t("LateralLeftJoin",e)}crossJoinLateral(...e){return this.#t("LateralCrossJoin",e)}crossApply(...e){return this.#t("CrossApply",e)}outerApply(...e){return this.#t("OuterApply",e)}#t(e,n){return new F({...this.#e,queryNode:I.cloneWithJoin(this.#e.queryNode,zi(e,n))})}orderBy(...e){return new F({...this.#e,queryNode:I.cloneWithOrderByItems(this.#e.queryNode,dn(e))})}groupBy(e){return new F({...this.#e,queryNode:Q.cloneWithGroupByItems(this.#e.queryNode,av(e))})}limit(e){return new F({...this.#e,queryNode:Q.cloneWithLimit(this.#e.queryNode,Ko.create(fe(e)))})}offset(e){return new F({...this.#e,queryNode:Q.cloneWithOffset(this.#e.queryNode,sv.create(fe(e)))})}fetch(e,n="only"){return new F({...this.#e,queryNode:Q.cloneWithFetch(this.#e.queryNode,dv(e,n))})}top(e,n){return new F({...this.#e,queryNode:I.cloneWithTop(this.#e.queryNode,qn(e,n))})}union(e){return new F({...this.#e,queryNode:Q.cloneWithSetOperations(this.#e.queryNode,gn("union",e,!1))})}unionAll(e){return new F({...this.#e,queryNode:Q.cloneWithSetOperations(this.#e.queryNode,gn("union",e,!0))})}intersect(e){return new F({...this.#e,queryNode:Q.cloneWithSetOperations(this.#e.queryNode,gn("intersect",e,!1))})}intersectAll(e){return new F({...this.#e,queryNode:Q.cloneWithSetOperations(this.#e.queryNode,gn("intersect",e,!0))})}except(e){return new F({...this.#e,queryNode:Q.cloneWithSetOperations(this.#e.queryNode,gn("except",e,!1))})}exceptAll(e){return new F({...this.#e,queryNode:Q.cloneWithSetOperations(this.#e.queryNode,gn("except",e,!0))})}as(e){return new lv(this,e)}clearSelect(){return new F({...this.#e,queryNode:Q.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new F({...this.#e,queryNode:I.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new F({...this.#e,queryNode:Q.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new F({...this.#e,queryNode:Q.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new F({...this.#e,queryNode:I.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new F({...this.#e,queryNode:Q.cloneWithoutGroupBy(this.#e.queryNode)})}$call(e){return e(this)}$if(e,n){return e?n(this):new F({...this.#e})}$castTo(){return new F(this.#e)}$narrowType(){return new F(this.#e)}$assertType(){return new F(this.#e)}$asTuple(){return new z(this.toOperationNode())}$asScalar(){return new z(this.toOperationNode())}withPlugin(e){return new F({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){const e=this.compile();return(await this.#e.executor.executeQuery(e)).rows}async executeTakeFirst(){const[e]=await this.execute();return e}async executeTakeFirstOrThrow(e=Mr){const n=await this.executeTakeFirst();if(n===void 0)throw Pr(e)?new e(this.toOperationNode()):e(this.toOperationNode());return n}async*stream(e=100){const n=this.compile(),r=this.#e.executor.stream(n,e);for await(const i of r)yield*i.rows}async explain(e,n){return await new F({...this.#e,queryNode:I.cloneWithExplain(this.#e.queryNode,e,n)}).execute()}}function zs(t){return new F(t)}class lv{#e;#t;constructor(e,n){this.#e=e,this.#t=n}get expression(){return this.#e}get alias(){return this.#t}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return St.create(this.#e.toOperationNode(),G.create(this.#t))}}const qt=d({is(t){return t.kind==="AggregateFunctionNode"},create(t,e=[]){return d({kind:"AggregateFunctionNode",func:t,aggregated:e})},cloneWithDistinct(t){return d({...t,distinct:!0})},cloneWithOrderBy(t,e,n=!1){const r=n?"withinGroup":"orderBy";return d({...t,[r]:t[r]?Ln.cloneWithItems(t[r],e):Ln.create(e)})},cloneWithFilter(t,e){return d({...t,filter:t.filter?Te.cloneWithOperation(t.filter,"And",e):Te.create(e)})},cloneWithOrFilter(t,e){return d({...t,filter:t.filter?Te.cloneWithOperation(t.filter,"Or",e):Te.create(e)})},cloneWithOver(t,e){return d({...t,over:e})}}),qc=d({is(t){return t.kind==="FunctionNode"},create(t,e){return d({kind:"FunctionNode",func:t,arguments:e})}});class $e{#e;constructor(e){this.#e=d(e)}get expressionType(){}as(e){return new hv(this,e)}distinct(){return new $e({...this.#e,aggregateFunctionNode:qt.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...e){return new $e({...this.#e,aggregateFunctionNode:I.cloneWithOrderByItems(this.#e.aggregateFunctionNode,dn(e))})}clearOrderBy(){return new $e({...this.#e,aggregateFunctionNode:I.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...e){return new $e({...this.#e,aggregateFunctionNode:qt.cloneWithOrderBy(this.#e.aggregateFunctionNode,dn(e),!0)})}filterWhere(...e){return new $e({...this.#e,aggregateFunctionNode:qt.cloneWithFilter(this.#e.aggregateFunctionNode,ye(e))})}filterWhereRef(e,n,r){return new $e({...this.#e,aggregateFunctionNode:qt.cloneWithFilter(this.#e.aggregateFunctionNode,at(e,n,r))})}over(e){const n=tv();return new $e({...this.#e,aggregateFunctionNode:qt.cloneWithOver(this.#e.aggregateFunctionNode,(e?e(n):n).toOperationNode())})}$call(e){return e(this)}$castTo(){return new $e(this.#e)}$notNull(){return new $e(this.#e)}toOperationNode(){return this.#e.aggregateFunctionNode}}class hv{#e;#t;constructor(e,n){this.#e=e,this.#t=n}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return St.create(this.#e.toOperationNode(),G.create(this.#t))}}function Pl(){const t=(n,r)=>new z(qc.create(n,Er(r??[]))),e=(n,r)=>new $e({aggregateFunctionNode:qt.create(n,r?Er(r):void 0)});return Object.assign(t,{agg:e,avg(n){return e("avg",[n])},coalesce(...n){return t("coalesce",n)},count(n){return e("count",[n])},countAll(n){return new $e({aggregateFunctionNode:qt.create("count",ze(n))})},max(n){return e("max",[n])},min(n){return e("min",[n])},sum(n){return e("sum",[n])},any(n){return t("any",[n])},jsonAgg(n){return new $e({aggregateFunctionNode:qt.create("json_agg",[Ae(n)?ue(n):n.toOperationNode()])})},toJson(n){return new z(qc.create("to_json",[Ae(n)?ue(n):n.toOperationNode()]))}})}const fv=d({is(t){return t.kind==="UnaryOperationNode"},create(t,e){return d({kind:"UnaryOperationNode",operator:t,operand:e})}});function pv(t,e){return fv.create(Kt.create(t),Be(e))}const rt=d({is(t){return t.kind==="CaseNode"},create(t){return d({kind:"CaseNode",value:t})},cloneWithWhen(t,e){return d({...t,when:d(t.when?[...t.when,e]:[e])})},cloneWithThen(t,e){return d({...t,when:t.when?d([...t.when.slice(0,-1),un.cloneWithResult(t.when[t.when.length-1],e)]):void 0})},cloneWith(t,e){return d({...t,...e})}});class $l{#e;constructor(e){this.#e=d(e)}when(...e){return new Ll({...this.#e,node:rt.cloneWithWhen(this.#e.node,un.create(ye(e)))})}}class Ll{#e;constructor(e){this.#e=d(e)}then(e){return new mv({...this.#e,node:rt.cloneWithThen(this.#e.node,Vo(e)?_o(e):fe(e))})}}class mv{#e;constructor(e){this.#e=d(e)}when(...e){return new Ll({...this.#e,node:rt.cloneWithWhen(this.#e.node,un.create(ye(e)))})}else(e){return new bv({...this.#e,node:rt.cloneWith(this.#e.node,{else:Vo(e)?_o(e):fe(e)})})}end(){return new z(rt.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new z(rt.cloneWith(this.#e.node,{isStatement:!0}))}}class bv{#e;constructor(e){this.#e=d(e)}end(){return new z(rt.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new z(rt.cloneWith(this.#e.node,{isStatement:!0}))}}const Fc=d({is(t){return t.kind==="JSONPathLegNode"},create(t,e){return d({kind:"JSONPathLegNode",type:t,value:e})}});class Js{#e;constructor(e){this.#e=e}at(e){return this.#t("ArrayLocation",e)}key(e){return this.#t("Member",e)}#t(e,n){return wi.is(this.#e)?new Dr(wi.cloneWithTraversal(this.#e,Qn.is(this.#e.traversal)?Qn.cloneWithLeg(this.#e.traversal,Fc.create(e,n)):vl.cloneWithValue(this.#e.traversal,Ke.createImmediate(n)))):new Dr(Qn.cloneWithLeg(this.#e,Fc.create(e,n)))}}class Dr extends Js{#e;constructor(e){super(e),this.#e=e}get expressionType(){}as(e){return new wv(this,e)}$castTo(){return new Dr(this.#e)}$notNull(){return new Dr(this.#e)}toOperationNode(){return this.#e}}class wv{#e;#t;constructor(e,n){this.#e=e,this.#t=n}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return St.create(this.#e.toOperationNode(),Oe(this.#t)?this.#t.toOperationNode():G.create(this.#t))}}const Vc=d({is(t){return t.kind==="TupleNode"},create(t){return d({kind:"TupleNode",values:d(t)})}}),yv=["varchar","char","text","integer","int2","int4","int8","smallint","bigint","boolean","real","double precision","float4","float8","decimal","numeric","binary","bytea","date","datetime","time","timetz","timestamp","timestamptz","serial","bigserial","uuid","json","jsonb","blob","varbinary","int4range","int4multirange","int8range","int8multirange","numrange","nummultirange","tsrange","tsmultirange","tstzrange","tstzmultirange","daterange","datemultirange"],gv=[/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^varbinary\(\d+\)$/],Nv=d({is(t){return t.kind==="DataTypeNode"},create(t){return d({kind:"DataTypeNode",dataType:t})}});function xv(t){return!!(yv.includes(t)||gv.some(e=>e.test(t)))}function ln(t){if(Oe(t))return t.toOperationNode();if(xv(t))return Nv.create(t);throw new Error(`invalid column data type ${JSON.stringify(t)}`)}const vv=d({is(t){return t.kind==="CastNode"},create(t,e){return d({kind:"CastNode",expression:t,dataType:e})}});function Jo(t=Ki){function e(i,s,o){return new z(jo(i,s,o))}function n(i,s){return new z(pv(i,s))}const r=Object.assign(e,{fn:void 0,eb:void 0,selectFrom(i){return zs({queryId:j(),executor:t,queryNode:Q.createFrom(Cn(i))})},case(i){return new $l({node:rt.create(_t(i)?void 0:Be(i))})},ref(i,s){return _t(s)?new z(Dt(i)):new Js(gx(i,s))},jsonPath(){return new Js(Qn.create())},table(i){return new z(ue(i))},val(i){return new z(fe(i))},refTuple(...i){return new z(Vc.create(i.map(Be)))},tuple(...i){return new z(Vc.create(i.map(fe)))},lit(i){return new z(_o(i))},unary:n,not(i){return n("not",i)},exists(i){return n("exists",i)},neg(i){return n("-",i)},between(i,s,o){return new z($n.create(Be(i),Kt.create("between"),Ht.create(fe(s),fe(o))))},betweenSymmetric(i,s,o){return new z($n.create(Be(i),Kt.create("between symmetric"),Ht.create(fe(s),fe(o))))},and(i){return vt(i)?new z(gi(i,"and")):new z(Dc(i,"and"))},or(i){return vt(i)?new z(gi(i,"or")):new z(Dc(i,"or"))},parens(...i){const s=ye(i);return Nt.is(s)?new z(s):new z(Nt.create(s))},cast(i,s){return new z(vv.create(Be(i),ln(s)))},withSchema(i){return Jo(t.withPluginAtFront(new fn(i)))}});return r.fn=Pl(),r.eb=r,r}function Fn(t){return Jo()}function pn(t){if(Oe(t))return t.toOperationNode();if(Fe(t))return t(Fn()).toOperationNode();throw new Error(`invalid expression: ${JSON.stringify(t)}`)}function Bl(t){if(Oe(t))return t.toOperationNode();if(Fe(t))return t(Fn()).toOperationNode();throw new Error(`invalid aliased expression: ${JSON.stringify(t)}`)}function $r(t){return wl(t)||dx(t)||Fe(t)}class Ev{#e;get table(){return this.#e}constructor(e){this.#e=e}as(e){return new Dv(this.#e,e)}}class Dv{#e;#t;get table(){return this.#e}get alias(){return this.#t}constructor(e,n){this.#e=e,this.#t=n}toOperationNode(){return St.create(ue(this.#e),G.create(this.#t))}}function kv(t){return je(t)&&Oe(t)&&Ae(t.table)&&Ae(t.alias)}function Cn(t){return vt(t)?t.map(e=>kr(e)):[kr(t)]}function kr(t){return Ae(t)?Ul(t):kv(t)?t.toOperationNode():Bl(t)}function Ul(t){const e=" as ";if(t.includes(e)){const[n,r]=t.split(e).map(ql);return St.create(ue(n),G.create(r))}else return ue(t)}function ue(t){if(t.includes(".")){const[n,r]=t.split(".").map(ql);return gt.createWithSchema(n,r)}else return gt.create(t)}function ql(t){return t.trim()}const Fl=d({is(t){return t.kind==="AddColumnNode"},create(t){return d({kind:"AddColumnNode",column:t})}}),ne=d({is(t){return t.kind==="ColumnDefinitionNode"},create(t,e){return d({kind:"ColumnDefinitionNode",column:le.create(t),dataType:e})},cloneWithFrontModifier(t,e){return d({...t,frontModifiers:t.frontModifiers?d([...t.frontModifiers,e]):[e]})},cloneWithEndModifier(t,e){return d({...t,endModifiers:t.endModifiers?d([...t.endModifiers,e]):[e]})},cloneWith(t,e){return d({...t,...e})}}),Vl=d({is(t){return t.kind==="DropColumnNode"},create(t){return d({kind:"DropColumnNode",column:le.create(t)})}}),_l=d({is(t){return t.kind==="RenameColumnNode"},create(t,e){return d({kind:"RenameColumnNode",column:le.create(t),renameTo:le.create(e)})}}),Go=d({is(t){return t.kind==="CheckConstraintNode"},create(t,e){return d({kind:"CheckConstraintNode",expression:t,name:e?G.create(e):void 0})}}),Sv=["no action","restrict","cascade","set null","set default"],ri=d({is(t){return t.kind==="ReferencesNode"},create(t,e){return d({kind:"ReferencesNode",table:t,columns:d([...e])})},cloneWithOnDelete(t,e){return d({...t,onDelete:e})},cloneWithOnUpdate(t,e){return d({...t,onUpdate:e})}});function jl(t){return Oe(t)?t.toOperationNode():Ke.createImmediate(t)}const Yr=d({is(t){return t.kind==="GeneratedNode"},create(t){return d({kind:"GeneratedNode",...t})},createWithExpression(t){return d({kind:"GeneratedNode",always:!0,expression:t})},cloneWith(t,e){return d({...t,...e})}}),Av=d({is(t){return t.kind==="DefaultValueNode"},create(t){return d({kind:"DefaultValueNode",defaultValue:t})}});function ki(t){if(Sv.includes(t))return t;throw new Error(`invalid OnModifyForeignAction ${t}`)}class ee{#e;constructor(e){this.#e=e}autoIncrement(){return new ee(ne.cloneWith(this.#e,{autoIncrement:!0}))}identity(){return new ee(ne.cloneWith(this.#e,{identity:!0}))}primaryKey(){return new ee(ne.cloneWith(this.#e,{primaryKey:!0}))}references(e){const n=Dt(e);if(!n.table||qo.is(n.column))throw new Error(`invalid call references('${e}'). The reference must have format table.column or schema.table.column`);return new ee(ne.cloneWith(this.#e,{references:ri.create(n.table,[n.column])}))}onDelete(e){if(!this.#e.references)throw new Error("on delete constraint can only be added for foreign keys");return new ee(ne.cloneWith(this.#e,{references:ri.cloneWithOnDelete(this.#e.references,ki(e))}))}onUpdate(e){if(!this.#e.references)throw new Error("on update constraint can only be added for foreign keys");return new ee(ne.cloneWith(this.#e,{references:ri.cloneWithOnUpdate(this.#e.references,ki(e))}))}unique(){return new ee(ne.cloneWith(this.#e,{unique:!0}))}notNull(){return new ee(ne.cloneWith(this.#e,{notNull:!0}))}unsigned(){return new ee(ne.cloneWith(this.#e,{unsigned:!0}))}defaultTo(e){return new ee(ne.cloneWith(this.#e,{defaultTo:Av.create(jl(e))}))}check(e){return new ee(ne.cloneWith(this.#e,{check:Go.create(e.toOperationNode())}))}generatedAlwaysAs(e){return new ee(ne.cloneWith(this.#e,{generated:Yr.createWithExpression(e.toOperationNode())}))}generatedAlwaysAsIdentity(){return new ee(ne.cloneWith(this.#e,{generated:Yr.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new ee(ne.cloneWith(this.#e,{generated:Yr.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#e.generated)throw new Error("stored() can only be called after generatedAlwaysAs");return new ee(ne.cloneWith(this.#e,{generated:Yr.cloneWith(this.#e.generated,{stored:!0})}))}modifyFront(e){return new ee(ne.cloneWithFrontModifier(this.#e,e.toOperationNode()))}nullsNotDistinct(){return new ee(ne.cloneWith(this.#e,{nullsNotDistinct:!0}))}ifNotExists(){return new ee(ne.cloneWith(this.#e,{ifNotExists:!0}))}modifyEnd(e){return new ee(ne.cloneWithEndModifier(this.#e,e.toOperationNode()))}$call(e){return e(this)}toOperationNode(){return this.#e}}const Hl=d({is(t){return t.kind==="ModifyColumnNode"},create(t){return d({kind:"ModifyColumnNode",column:t})}}),Mt=d({is(t){return t.kind==="ForeignKeyConstraintNode"},create(t,e,n,r){return d({kind:"ForeignKeyConstraintNode",columns:t,references:ri.create(e,n),name:r?G.create(r):void 0})},cloneWith(t,e){return d({...t,...e})}});class bt{#e;constructor(e){this.#e=e}onDelete(e){return new bt(Mt.cloneWith(this.#e,{onDelete:ki(e)}))}onUpdate(e){return new bt(Mt.cloneWith(this.#e,{onUpdate:ki(e)}))}deferrable(){return new bt(Mt.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new bt(Mt.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new bt(Mt.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new bt(Mt.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}}const ii=d({is(t){return t.kind==="AddConstraintNode"},create(t){return d({kind:"AddConstraintNode",constraint:t})}}),Jt=d({is(t){return t.kind==="UniqueConstraintNode"},create(t,e,n){return d({kind:"UniqueConstraintNode",columns:d(t.map(le.create)),name:e?G.create(e):void 0,nullsNotDistinct:n})},cloneWith(t,e){return d({...t,...e})}}),si=d({is(t){return t.kind==="DropConstraintNode"},create(t){return d({kind:"DropConstraintNode",constraintName:G.create(t)})},cloneWith(t,e){return d({...t,...e})}}),Hn=d({is(t){return t.kind==="AlterColumnNode"},create(t,e,n){return d({kind:"AlterColumnNode",column:le.create(t),[e]:n})}});class Kl{#e;constructor(e){this.#e=e}setDataType(e){return new Kn(Hn.create(this.#e,"dataType",ln(e)))}setDefault(e){return new Kn(Hn.create(this.#e,"setDefault",jl(e)))}dropDefault(){return new Kn(Hn.create(this.#e,"dropDefault",!0))}setNotNull(){return new Kn(Hn.create(this.#e,"setNotNull",!0))}dropNotNull(){return new Kn(Hn.create(this.#e,"dropNotNull",!0))}$call(e){return e(this)}}class Kn{#e;constructor(e){this.#e=e}toOperationNode(){return this.#e}}class Nn{#e;constructor(e){this.#e=d(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class Pt{#e;constructor(e){this.#e=d(e)}onDelete(e){return new Pt({...this.#e,constraintBuilder:this.#e.constraintBuilder.onDelete(e)})}onUpdate(e){return new Pt({...this.#e,constraintBuilder:this.#e.constraintBuilder.onUpdate(e)})}deferrable(){return new Pt({...this.#e,constraintBuilder:this.#e.constraintBuilder.deferrable()})}notDeferrable(){return new Pt({...this.#e,constraintBuilder:this.#e.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new Pt({...this.#e,constraintBuilder:this.#e.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new Pt({...this.#e,constraintBuilder:this.#e.constraintBuilder.initiallyImmediate()})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(H.cloneWithTableProps(this.#e.node,{addConstraint:ii.create(this.#e.constraintBuilder.toOperationNode())}),this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class Tn{#e;constructor(e){this.#e=d(e)}ifExists(){return new Tn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{dropConstraint:si.cloneWith(this.#e.node.dropConstraint,{ifExists:!0})})})}cascade(){return new Tn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{dropConstraint:si.cloneWith(this.#e.node.dropConstraint,{modifier:"cascade"})})})}restrict(){return new Tn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{dropConstraint:si.cloneWith(this.#e.node.dropConstraint,{modifier:"restrict"})})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}const Sn=d({is(t){return t.kind==="PrimaryKeyConstraintNode"},create(t,e){return d({kind:"PrimaryKeyConstraintNode",columns:d(t.map(le.create)),name:e?G.create(e):void 0})},cloneWith(t,e){return d({...t,...e})}}),vn=d({is(t){return t.kind==="AddIndexNode"},create(t){return d({kind:"AddIndexNode",name:G.create(t)})},cloneWith(t,e){return d({...t,...e})},cloneWithColumns(t,e){return d({...t,columns:[...t.columns||[],...e]})}});class Gt{#e;constructor(e){this.#e=d(e)}unique(){return new Gt({...this.#e,node:H.cloneWithTableProps(this.#e.node,{addIndex:vn.cloneWith(this.#e.node.addIndex,{unique:!0})})})}column(e){return new Gt({...this.#e,node:H.cloneWithTableProps(this.#e.node,{addIndex:vn.cloneWithColumns(this.#e.node.addIndex,[yi(e)])})})}columns(e){return new Gt({...this.#e,node:H.cloneWithTableProps(this.#e.node,{addIndex:vn.cloneWithColumns(this.#e.node.addIndex,e.map(yi))})})}expression(e){return new Gt({...this.#e,node:H.cloneWithTableProps(this.#e.node,{addIndex:vn.cloneWithColumns(this.#e.node.addIndex,[e.toOperationNode()])})})}using(e){return new Gt({...this.#e,node:H.cloneWithTableProps(this.#e.node,{addIndex:vn.cloneWith(this.#e.node.addIndex,{using:de.createWithSql(e)})})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class Ft{#e;constructor(e){this.#e=e}nullsNotDistinct(){return new Ft(Jt.cloneWith(this.#e,{nullsNotDistinct:!0}))}deferrable(){return new Ft(Jt.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new Ft(Jt.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new Ft(Jt.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new Ft(Jt.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}}class tn{#e;constructor(e){this.#e=e}deferrable(){return new tn(Sn.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new tn(Sn.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new tn(Sn.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new tn(Sn.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}}class zl{#e;constructor(e){this.#e=e}$call(e){return e(this)}toOperationNode(){return this.#e}}const Ov=d({is(t){return t.kind==="RenameConstraintNode"},create(t,e){return d({kind:"RenameConstraintNode",oldName:G.create(t),newName:G.create(e)})}});class Cv{#e;constructor(e){this.#e=d(e)}renameTo(e){return new Nn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{renameTo:ue(e)})})}setSchema(e){return new Nn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{setSchema:G.create(e)})})}alterColumn(e,n){const r=n(new Kl(e));return new Ye({...this.#e,node:H.cloneWithColumnAlteration(this.#e.node,r.toOperationNode())})}dropColumn(e){return new Ye({...this.#e,node:H.cloneWithColumnAlteration(this.#e.node,Vl.create(e))})}renameColumn(e,n){return new Ye({...this.#e,node:H.cloneWithColumnAlteration(this.#e.node,_l.create(e,n))})}addColumn(e,n,r=Le){const i=r(new ee(ne.create(e,ln(n))));return new Ye({...this.#e,node:H.cloneWithColumnAlteration(this.#e.node,Fl.create(i.toOperationNode()))})}modifyColumn(e,n,r=Le){const i=r(new ee(ne.create(e,ln(n))));return new Ye({...this.#e,node:H.cloneWithColumnAlteration(this.#e.node,Hl.create(i.toOperationNode()))})}addUniqueConstraint(e,n,r=Le){const i=r(new Ft(Jt.create(n,e)));return new Nn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{addConstraint:ii.create(i.toOperationNode())})})}addCheckConstraint(e,n,r=Le){const i=r(new zl(Go.create(n.toOperationNode(),e)));return new Nn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{addConstraint:ii.create(i.toOperationNode())})})}addForeignKeyConstraint(e,n,r,i,s=Le){const o=s(new bt(Mt.create(n.map(le.create),ue(r),i.map(le.create),e)));return new Pt({...this.#e,constraintBuilder:o})}addPrimaryKeyConstraint(e,n,r=Le){const i=r(new tn(Sn.create(n,e)));return new Nn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{addConstraint:ii.create(i.toOperationNode())})})}dropConstraint(e){return new Tn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{dropConstraint:si.create(e)})})}renameConstraint(e,n){return new Tn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{renameConstraint:Ov.create(e,n)})})}addIndex(e){return new Gt({...this.#e,node:H.cloneWithTableProps(this.#e.node,{addIndex:vn.create(e)})})}dropIndex(e){return new Nn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{dropIndex:Yn.create(e)})})}$call(e){return e(this)}}class Ye{#e;constructor(e){this.#e=d(e)}alterColumn(e,n){const r=n(new Kl(e));return new Ye({...this.#e,node:H.cloneWithColumnAlteration(this.#e.node,r.toOperationNode())})}dropColumn(e){return new Ye({...this.#e,node:H.cloneWithColumnAlteration(this.#e.node,Vl.create(e))})}renameColumn(e,n){return new Ye({...this.#e,node:H.cloneWithColumnAlteration(this.#e.node,_l.create(e,n))})}addColumn(e,n,r=Le){const i=r(new ee(ne.create(e,ln(n))));return new Ye({...this.#e,node:H.cloneWithColumnAlteration(this.#e.node,Fl.create(i.toOperationNode()))})}modifyColumn(e,n,r=Le){const i=r(new ee(ne.create(e,ln(n))));return new Ye({...this.#e,node:H.cloneWithColumnAlteration(this.#e.node,Hl.create(i.toOperationNode()))})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class Jl extends Il{transformPrimitiveValueList(e){return Hi.create(e.values.map(Ke.createImmediate))}transformValue(e){return Ke.createImmediate(e.value)}}class Ze{#e;constructor(e){this.#e=d(e)}ifNotExists(){return new Ze({...this.#e,node:ht.cloneWith(this.#e.node,{ifNotExists:!0})})}unique(){return new Ze({...this.#e,node:ht.cloneWith(this.#e.node,{unique:!0})})}nullsNotDistinct(){return new Ze({...this.#e,node:ht.cloneWith(this.#e.node,{nullsNotDistinct:!0})})}on(e){return new Ze({...this.#e,node:ht.cloneWith(this.#e.node,{table:ue(e)})})}column(e){return new Ze({...this.#e,node:ht.cloneWithColumns(this.#e.node,[yi(e)])})}columns(e){return new Ze({...this.#e,node:ht.cloneWithColumns(this.#e.node,e.map(yi))})}expression(e){return new Ze({...this.#e,node:ht.cloneWithColumns(this.#e.node,[e.toOperationNode()])})}using(e){return new Ze({...this.#e,node:ht.cloneWith(this.#e.node,{using:de.createWithSql(e)})})}where(...e){const n=new Jl;return new Ze({...this.#e,node:I.cloneWithWhere(this.#e.node,n.transformNode(ye(e),this.#e.queryId))})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class Zo{#e;constructor(e){this.#e=d(e)}ifNotExists(){return new Zo({...this.#e,node:bl.cloneWith(this.#e.node,{ifNotExists:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}function Tv(t){if(cx.includes(t))return t;throw new Error(`invalid OnCommitAction ${t}`)}class Me{#e;constructor(e){this.#e=d(e)}temporary(){return new Me({...this.#e,node:We.cloneWith(this.#e.node,{temporary:!0})})}onCommit(e){return new Me({...this.#e,node:We.cloneWith(this.#e.node,{onCommit:Tv(e)})})}ifNotExists(){return new Me({...this.#e,node:We.cloneWith(this.#e.node,{ifNotExists:!0})})}addColumn(e,n,r=Le){const i=r(new ee(ne.create(e,ln(n))));return new Me({...this.#e,node:We.cloneWithColumn(this.#e.node,i.toOperationNode())})}addPrimaryKeyConstraint(e,n,r=Le){const i=r(new tn(Sn.create(n,e)));return new Me({...this.#e,node:We.cloneWithConstraint(this.#e.node,i.toOperationNode())})}addUniqueConstraint(e,n,r=Le){const i=r(new Ft(Jt.create(n,e)));return new Me({...this.#e,node:We.cloneWithConstraint(this.#e.node,i.toOperationNode())})}addCheckConstraint(e,n,r=Le){const i=r(new zl(Go.create(n.toOperationNode(),e)));return new Me({...this.#e,node:We.cloneWithConstraint(this.#e.node,i.toOperationNode())})}addForeignKeyConstraint(e,n,r,i,s=Le){const o=s(new bt(Mt.create(n.map(le.create),ue(r),i.map(le.create),e)));return new Me({...this.#e,node:We.cloneWithConstraint(this.#e.node,o.toOperationNode())})}modifyFront(e){return new Me({...this.#e,node:We.cloneWithFrontModifier(this.#e.node,e.toOperationNode())})}modifyEnd(e){return new Me({...this.#e,node:We.cloneWithEndModifier(this.#e.node,e.toOperationNode())})}as(e){return new Me({...this.#e,node:We.cloneWith(this.#e.node,{selectQuery:pn(e)})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class sr{#e;constructor(e){this.#e=d(e)}on(e){return new sr({...this.#e,node:Yn.cloneWith(this.#e.node,{table:ue(e)})})}ifExists(){return new sr({...this.#e,node:Yn.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new sr({...this.#e,node:Yn.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class Si{#e;constructor(e){this.#e=d(e)}ifExists(){return new Si({...this.#e,node:_s.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new Si({...this.#e,node:_s.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class Ai{#e;constructor(e){this.#e=d(e)}ifExists(){return new Ai({...this.#e,node:js.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new Ai({...this.#e,node:js.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}const $t=d({is(t){return t.kind==="CreateViewNode"},create(t){return d({kind:"CreateViewNode",name:Et.create(t)})},cloneWith(t,e){return d({...t,...e})}});class Iv{#e=new Jl;transformQuery(e){return this.#e.transformNode(e.node,e.queryId)}transformResult(e){return Promise.resolve(e.result)}}class Lt{#e;constructor(e){this.#e=d(e)}temporary(){return new Lt({...this.#e,node:$t.cloneWith(this.#e.node,{temporary:!0})})}materialized(){return new Lt({...this.#e,node:$t.cloneWith(this.#e.node,{materialized:!0})})}ifNotExists(){return new Lt({...this.#e,node:$t.cloneWith(this.#e.node,{ifNotExists:!0})})}orReplace(){return new Lt({...this.#e,node:$t.cloneWith(this.#e.node,{orReplace:!0})})}columns(e){return new Lt({...this.#e,node:$t.cloneWith(this.#e.node,{columns:e.map(Dl)})})}as(e){const n=e.withPlugin(new Iv).toOperationNode();return new Lt({...this.#e,node:$t.cloneWith(this.#e.node,{as:n})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}const oi=d({is(t){return t.kind==="DropViewNode"},create(t){return d({kind:"DropViewNode",name:Et.create(t)})},cloneWith(t,e){return d({...t,...e})}});class or{#e;constructor(e){this.#e=d(e)}materialized(){return new or({...this.#e,node:oi.cloneWith(this.#e.node,{materialized:!0})})}ifExists(){return new or({...this.#e,node:oi.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new or({...this.#e,node:oi.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}const Gl=d({is(t){return t.kind==="CreateTypeNode"},create(t){return d({kind:"CreateTypeNode",name:t})},cloneWithEnum(t,e){return d({...t,enum:Hi.create(e.map(Ke.createImmediate))})}});class Yo{#e;constructor(e){this.#e=d(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}asEnum(e){return new Yo({...this.#e,node:Gl.cloneWithEnum(this.#e.node,e)})}$call(e){return e(this)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}const Zl=d({is(t){return t.kind==="DropTypeNode"},create(t){return d({kind:"DropTypeNode",name:t})},cloneWith(t,e){return d({...t,...e})}});class Qo{#e;constructor(e){this.#e=d(e)}ifExists(){return new Qo({...this.#e,node:Zl.cloneWith(this.#e.node,{ifExists:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}function _c(t){if(t.includes(".")){const n=t.split(".").map(Rv);if(n.length===2)return Et.createWithSchema(n[0],n[1]);throw new Error(`invalid schemable identifier ${t}`)}else return Et.create(t)}function Rv(t){return t.trim()}const ai=d({is(t){return t.kind==="RefreshMaterializedViewNode"},create(t){return d({kind:"RefreshMaterializedViewNode",name:Et.create(t)})},cloneWith(t,e){return d({...t,...e})}});class ar{#e;constructor(e){this.#e=d(e)}concurrently(){return new ar({...this.#e,node:ai.cloneWith(this.#e.node,{concurrently:!0,withNoData:!1})})}withData(){return new ar({...this.#e,node:ai.cloneWith(this.#e.node,{withNoData:!1})})}withNoData(){return new ar({...this.#e,node:ai.cloneWith(this.#e.node,{withNoData:!0,concurrently:!1})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class cr{#e;constructor(e){this.#e=e}createTable(e){return new Me({queryId:j(),executor:this.#e,node:We.create(ue(e))})}dropTable(e){return new Ai({queryId:j(),executor:this.#e,node:js.create(ue(e))})}createIndex(e){return new Ze({queryId:j(),executor:this.#e,node:ht.create(e)})}dropIndex(e){return new sr({queryId:j(),executor:this.#e,node:Yn.create(e)})}createSchema(e){return new Zo({queryId:j(),executor:this.#e,node:bl.create(e)})}dropSchema(e){return new Si({queryId:j(),executor:this.#e,node:_s.create(e)})}alterTable(e){return new Cv({queryId:j(),executor:this.#e,node:H.create(ue(e))})}createView(e){return new Lt({queryId:j(),executor:this.#e,node:$t.create(e)})}refreshMaterializedView(e){return new ar({queryId:j(),executor:this.#e,node:ai.create(e)})}dropView(e){return new or({queryId:j(),executor:this.#e,node:oi.create(e)})}createType(e){return new Yo({queryId:j(),executor:this.#e,node:Gl.create(_c(e))})}dropType(e){return new Qo({queryId:j(),executor:this.#e,node:Zl.create(_c(e))})}withPlugin(e){return new cr(this.#e.withPlugin(e))}withoutPlugins(){return new cr(this.#e.withoutPlugins())}withSchema(e){return new cr(this.#e.withPluginAtFront(new fn(e)))}}class Wv{ref(e){return new bx(e)}table(e){return new Ev(e)}}class Mv{#e;constructor(e){this.#e=e}async provideConnection(e){const n=await this.#e.acquireConnection();try{return await e(n)}finally{await this.#e.releaseConnection(n)}}}class Zt extends Wl{#e;#t;#n;constructor(e,n,r,i=[]){super(i),this.#e=e,this.#t=n,this.#n=r}get adapter(){return this.#t}compileQuery(e,n){return this.#e.compileQuery(e,n)}provideConnection(e){return this.#n.provideConnection(e)}withPlugins(e){return new Zt(this.#e,this.#t,this.#n,[...this.plugins,...e])}withPlugin(e){return new Zt(this.#e,this.#t,this.#n,[...this.plugins,e])}withPluginAtFront(e){return new Zt(this.#e,this.#t,this.#n,[e,...this.plugins])}withConnectionProvider(e){return new Zt(this.#e,this.#t,e,[...this.plugins])}withoutPlugins(){return new Zt(this.#e,this.#t,this.#n,[])}}function Os(){return typeof performance<"u"&&Fe(performance.now)?performance.now():Date.now()}class Pv{#e;#t;#n;#r;#i;#c=new WeakSet;constructor(e,n){this.#r=!1,this.#e=e,this.#t=n}async init(){if(this.#i)throw new Error("driver has already been destroyed");this.#n||(this.#n=this.#e.init().then(()=>{this.#r=!0}).catch(e=>(this.#n=void 0,Promise.reject(e)))),await this.#n}async acquireConnection(){if(this.#i)throw new Error("driver has already been destroyed");this.#r||await this.init();const e=await this.#e.acquireConnection();return this.#c.has(e)||(this.#s()&&this.#o(e),this.#c.add(e)),e}async releaseConnection(e){await this.#e.releaseConnection(e)}beginTransaction(e,n){return this.#e.beginTransaction(e,n)}commitTransaction(e){return this.#e.commitTransaction(e)}rollbackTransaction(e){return this.#e.rollbackTransaction(e)}savepoint(e,n,r){if(this.#e.savepoint)return this.#e.savepoint(e,n,r);throw new Error("The `savepoint` method is not supported by this driver")}rollbackToSavepoint(e,n,r){if(this.#e.rollbackToSavepoint)return this.#e.rollbackToSavepoint(e,n,r);throw new Error("The `rollbackToSavepoint` method is not supported by this driver")}releaseSavepoint(e,n,r){if(this.#e.releaseSavepoint)return this.#e.releaseSavepoint(e,n,r);throw new Error("The `releaseSavepoint` method is not supported by this driver")}async destroy(){this.#n&&(await this.#n,this.#i||(this.#i=this.#e.destroy().catch(e=>(this.#i=void 0,Promise.reject(e)))),await this.#i)}#s(){return this.#t.isLevelEnabled("query")||this.#t.isLevelEnabled("error")}#o(e){const n=e.executeQuery,r=e.streamQuery,i=this;e.executeQuery=async s=>{let o;const a=Os();try{return await n.call(e,s)}catch(c){throw o=c,await i.#a(c,s,a),c}finally{o||await i.#d(s,a)}},e.streamQuery=async function*(s,o){let a;const c=Os();try{for await(const u of r.call(e,s,o))yield u}catch(u){throw a=u,await i.#a(u,s,c),u}finally{a||await i.#d(s,c,!0)}}}async#a(e,n,r){await this.#t.error(()=>({level:"error",error:e,query:n,queryDurationMillis:this.#u(r)}))}async#d(e,n,r=!1){await this.#t.query(()=>({level:"query",isStream:r,query:e,queryDurationMillis:this.#u(n)}))}#u(e){return Os()-e}}const $v=()=>{};class Xo{#e;#t;constructor(e){this.#e=e}async provideConnection(e){for(;this.#t;)await this.#t.catch($v);return this.#t=this.#n(e).finally(()=>{this.#t=void 0}),this.#t}async#n(e){return await e(this.#e)}}const Lv=["read only","read write"],Bv=["read uncommitted","read committed","repeatable read","serializable","snapshot"];function Yl(t){if(t.accessMode&&!Lv.includes(t.accessMode))throw new Error(`invalid transaction access mode ${t.accessMode}`);if(t.isolationLevel&&!Bv.includes(t.isolationLevel))throw new Error(`invalid transaction isolation level ${t.isolationLevel}`)}d(["query","error"]);class Uv{#e;#t;constructor(e){Fe(e)?(this.#t=e,this.#e=d({query:!0,error:!0})):(this.#t=qv,this.#e=d({query:e.includes("query"),error:e.includes("error")}))}isLevelEnabled(e){return this.#e[e]}async query(e){this.#e.query&&await this.#t(e())}async error(e){this.#e.error&&await this.#t(e())}}function qv(t){if(t.level==="query"){const e=`kysely:query:${t.isStream?"stream:":""}`;console.log(`${e} ${t.query.sql}`),console.log(`${e} duration: ${t.queryDurationMillis.toFixed(1)}ms`)}else t.level==="error"&&(t.error instanceof Error?console.error(`kysely:error: ${t.error.stack??t.error.message}`):console.error(`kysely:error: ${JSON.stringify({error:t.error,query:t.query.sql,queryDurationMillis:t.queryDurationMillis})}`))}function Fv(t){return je(t)&&Fe(t.compile)}Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");class nn extends Ut{#e;constructor(e){let n,r;if(Vv(e))n={executor:e.executor},r={...e};else{const i=e.dialect,s=i.createDriver(),o=i.createQueryCompiler(),a=i.createAdapter(),c=new Uv(e.log??[]),u=new Pv(s,c),h=new Mv(u),f=new Zt(o,a,h,e.plugins??[]);n={executor:f},r={config:e,executor:f,dialect:i,driver:u}}super(n),this.#e=d(r)}get schema(){return new cr(this.#e.executor)}get dynamic(){return new Wv}get introspection(){return this.#e.dialect.createIntrospector(this.withoutPlugins())}case(e){return new $l({node:rt.create(_t(e)?void 0:pn(e))})}get fn(){return Pl()}transaction(){return new Oi({...this.#e})}startTransaction(){return new Ci({...this.#e})}connection(){return new _v({...this.#e})}withPlugin(e){return new nn({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new nn({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new nn({...this.#e,executor:this.#e.executor.withPluginAtFront(new fn(e))})}withTables(){return new nn({...this.#e})}async destroy(){await this.#e.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#e.executor}executeQuery(e,n){n!==void 0&&Un("Passing `queryId` in `db.executeQuery` is deprecated and will result in a compile-time error in the future.");const r=Fv(e)?e.compile():e;return this.getExecutor().executeQuery(r)}async[Symbol.asyncDispose](){await this.destroy()}}class rn extends nn{#e;constructor(e){super(e),this.#e=e}get isTransaction(){return!0}transaction(){throw new Error("calling the transaction method for a Transaction is not supported")}connection(){throw new Error("calling the connection method for a Transaction is not supported")}async destroy(){throw new Error("calling the destroy method for a Transaction is not supported")}withPlugin(e){return new rn({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new rn({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new rn({...this.#e,executor:this.#e.executor.withPluginAtFront(new fn(e))})}withTables(){return new rn({...this.#e})}}function Vv(t){return je(t)&&je(t.config)&&je(t.driver)&&je(t.executor)&&je(t.dialect)}class _v{#e;constructor(e){this.#e=d(e)}async execute(e){return this.#e.executor.provideConnection(async n=>{const r=this.#e.executor.withConnectionProvider(new Xo(n)),i=new nn({...this.#e,executor:r});return await e(i)})}}class Oi{#e;constructor(e){this.#e=d(e)}setAccessMode(e){return new Oi({...this.#e,accessMode:e})}setIsolationLevel(e){return new Oi({...this.#e,isolationLevel:e})}async execute(e){const{isolationLevel:n,accessMode:r,...i}=this.#e,s={isolationLevel:n,accessMode:r};return Yl(s),this.#e.executor.provideConnection(async o=>{const a=this.#e.executor.withConnectionProvider(new Xo(o)),c=new rn({...i,executor:a});let u=!1;try{await this.#e.driver.beginTransaction(o,s),u=!0;const h=await e(c);return await this.#e.driver.commitTransaction(o),h}catch(h){throw u&&await this.#e.driver.rollbackTransaction(o),h}})}}class Ci{#e;constructor(e){this.#e=d(e)}setAccessMode(e){return new Ci({...this.#e,accessMode:e})}setIsolationLevel(e){return new Ci({...this.#e,isolationLevel:e})}async execute(){const{isolationLevel:e,accessMode:n,...r}=this.#e,i={isolationLevel:e,accessMode:n};Yl(i);const s=await Rl(this.#e.executor);return await this.#e.driver.beginTransaction(s.connection,i),new pt({...r,connection:s,executor:this.#e.executor.withConnectionProvider(new Xo(s.connection))})}}class pt extends rn{#e;#t;#n;constructor(e){const n={isCommitted:!1,isRolledBack:!1};e={...e,executor:new Bt(e.executor,n)};const{connection:r,...i}=e;super(i),this.#e=d(e),this.#n=n;const s=j();this.#t=o=>e.executor.compileQuery(o,s)}get isCommitted(){return this.#n.isCommitted}get isRolledBack(){return this.#n.isRolledBack}commit(){return Yt(this.#n),new zn(async()=>{await this.#e.driver.commitTransaction(this.#e.connection.connection),this.#n.isCommitted=!0,this.#e.connection.release()})}rollback(){return Yt(this.#n),new zn(async()=>{await this.#e.driver.rollbackTransaction(this.#e.connection.connection),this.#n.isRolledBack=!0,this.#e.connection.release()})}savepoint(e){return Yt(this.#n),new zn(async()=>(await this.#e.driver.savepoint?.(this.#e.connection.connection,e,this.#t),new pt({...this.#e})))}rollbackToSavepoint(e){return Yt(this.#n),new zn(async()=>(await this.#e.driver.rollbackToSavepoint?.(this.#e.connection.connection,e,this.#t),new pt({...this.#e})))}releaseSavepoint(e){return Yt(this.#n),new zn(async()=>(await this.#e.driver.releaseSavepoint?.(this.#e.connection.connection,e,this.#t),new pt({...this.#e})))}withPlugin(e){return new pt({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new pt({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new pt({...this.#e,executor:this.#e.executor.withPluginAtFront(new fn(e))})}withTables(){return new pt({...this.#e})}}class zn{#e;constructor(e){this.#e=e}async execute(){return await this.#e()}}function Yt(t){if(t.isCommitted)throw new Error("Transaction is already committed");if(t.isRolledBack)throw new Error("Transaction is already rolled back")}class Bt{#e;#t;constructor(e,n){e instanceof Bt?this.#e=e.#e:this.#e=e,this.#t=n}get adapter(){return this.#e.adapter}get plugins(){return this.#e.plugins}transformQuery(e,n){return this.#e.transformQuery(e,n)}compileQuery(e,n){return this.#e.compileQuery(e,n)}provideConnection(e){return this.#e.provideConnection(e)}executeQuery(e){return Yt(this.#t),this.#e.executeQuery(e)}stream(e,n){return Yt(this.#t),this.#e.stream(e,n)}withConnectionProvider(e){return new Bt(this.#e.withConnectionProvider(e),this.#t)}withPlugin(e){return new Bt(this.#e.withPlugin(e),this.#t)}withPlugins(e){return new Bt(this.#e.withPlugins(e),this.#t)}withPluginAtFront(e){return new Bt(this.#e.withPluginAtFront(e),this.#t)}withoutPlugins(){return new Bt(this.#e.withoutPlugins(),this.#t)}}class dr{#e;constructor(e){this.#e=d(e)}get expressionType(){}get isRawBuilder(){return!0}as(e){return new jv(this,e)}$castTo(){return new dr({...this.#e})}$notNull(){return new dr(this.#e)}withPlugin(e){return new dr({...this.#e,plugins:this.#e.plugins!==void 0?d([...this.#e.plugins,e]):d([e])})}toOperationNode(){return this.#n(this.#t())}compile(e){return this.#r(this.#t(e))}async execute(e){const n=this.#t(e);return n.executeQuery(this.#r(n))}#t(e){const n=e!==void 0?e.getExecutor():Ki;return this.#e.plugins!==void 0?n.withPlugins(this.#e.plugins):n}#n(e){return e.transformQuery(this.#e.rawNode,this.#e.queryId)}#r(e){return e.compileQuery(this.#n(e),this.#e.queryId)}}function Rt(t){return new dr(t)}class jv{#e;#t;constructor(e,n){this.#e=e,this.#t=n}get expression(){return this.#e}get alias(){return this.#t}get rawBuilder(){return this.#e}toOperationNode(){return St.create(this.#e.toOperationNode(),Oe(this.#t)?this.#t.toOperationNode():G.create(this.#t))}}const In=Object.assign((t,...e)=>Rt({queryId:j(),rawNode:de.create(t,e?.map(jc)??[])}),{ref(t){return Rt({queryId:j(),rawNode:de.createWithChild(Dt(t))})},val(t){return Rt({queryId:j(),rawNode:de.createWithChild(fe(t))})},value(t){return this.val(t)},table(t){return Rt({queryId:j(),rawNode:de.createWithChild(ue(t))})},id(...t){const e=new Array(t.length+1).fill(".");return e[0]="",e[e.length-1]="",Rt({queryId:j(),rawNode:de.create(e,t.map(G.create))})},lit(t){return Rt({queryId:j(),rawNode:de.createWithChild(Ke.createImmediate(t))})},literal(t){return this.lit(t)},raw(t){return Rt({queryId:j(),rawNode:de.createWithSql(t)})},join(t,e=In`, `){const n=new Array(Math.max(2*t.length-1,0)),r=e.toOperationNode();for(let i=0;i<t.length;++i)n[2*i]=jc(t[i]),i!==t.length-1&&(n[2*i+1]=r);return Rt({queryId:j(),rawNode:de.createWithChildren(n)})}});function jc(t){return Oe(t)?t.toOperationNode():fe(t)}class Hv{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#e=d({AliasNode:this.visitAlias.bind(this),ColumnNode:this.visitColumn.bind(this),IdentifierNode:this.visitIdentifier.bind(this),SchemableIdentifierNode:this.visitSchemableIdentifier.bind(this),RawNode:this.visitRaw.bind(this),ReferenceNode:this.visitReference.bind(this),SelectQueryNode:this.visitSelectQuery.bind(this),SelectionNode:this.visitSelection.bind(this),TableNode:this.visitTable.bind(this),FromNode:this.visitFrom.bind(this),SelectAllNode:this.visitSelectAll.bind(this),AndNode:this.visitAnd.bind(this),OrNode:this.visitOr.bind(this),ValueNode:this.visitValue.bind(this),ValueListNode:this.visitValueList.bind(this),PrimitiveValueListNode:this.visitPrimitiveValueList.bind(this),ParensNode:this.visitParens.bind(this),JoinNode:this.visitJoin.bind(this),OperatorNode:this.visitOperator.bind(this),WhereNode:this.visitWhere.bind(this),InsertQueryNode:this.visitInsertQuery.bind(this),DeleteQueryNode:this.visitDeleteQuery.bind(this),ReturningNode:this.visitReturning.bind(this),CreateTableNode:this.visitCreateTable.bind(this),AddColumnNode:this.visitAddColumn.bind(this),ColumnDefinitionNode:this.visitColumnDefinition.bind(this),DropTableNode:this.visitDropTable.bind(this),DataTypeNode:this.visitDataType.bind(this),OrderByNode:this.visitOrderBy.bind(this),OrderByItemNode:this.visitOrderByItem.bind(this),GroupByNode:this.visitGroupBy.bind(this),GroupByItemNode:this.visitGroupByItem.bind(this),UpdateQueryNode:this.visitUpdateQuery.bind(this),ColumnUpdateNode:this.visitColumnUpdate.bind(this),LimitNode:this.visitLimit.bind(this),OffsetNode:this.visitOffset.bind(this),OnConflictNode:this.visitOnConflict.bind(this),OnDuplicateKeyNode:this.visitOnDuplicateKey.bind(this),CreateIndexNode:this.visitCreateIndex.bind(this),DropIndexNode:this.visitDropIndex.bind(this),ListNode:this.visitList.bind(this),PrimaryKeyConstraintNode:this.visitPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.visitUniqueConstraint.bind(this),ReferencesNode:this.visitReferences.bind(this),CheckConstraintNode:this.visitCheckConstraint.bind(this),WithNode:this.visitWith.bind(this),CommonTableExpressionNode:this.visitCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.visitCommonTableExpressionName.bind(this),HavingNode:this.visitHaving.bind(this),CreateSchemaNode:this.visitCreateSchema.bind(this),DropSchemaNode:this.visitDropSchema.bind(this),AlterTableNode:this.visitAlterTable.bind(this),DropColumnNode:this.visitDropColumn.bind(this),RenameColumnNode:this.visitRenameColumn.bind(this),AlterColumnNode:this.visitAlterColumn.bind(this),ModifyColumnNode:this.visitModifyColumn.bind(this),AddConstraintNode:this.visitAddConstraint.bind(this),DropConstraintNode:this.visitDropConstraint.bind(this),RenameConstraintNode:this.visitRenameConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),RefreshMaterializedViewNode:this.visitRefreshMaterializedView.bind(this),DropViewNode:this.visitDropView.bind(this),GeneratedNode:this.visitGenerated.bind(this),DefaultValueNode:this.visitDefaultValue.bind(this),OnNode:this.visitOn.bind(this),ValuesNode:this.visitValues.bind(this),SelectModifierNode:this.visitSelectModifier.bind(this),CreateTypeNode:this.visitCreateType.bind(this),DropTypeNode:this.visitDropType.bind(this),ExplainNode:this.visitExplain.bind(this),DefaultInsertValueNode:this.visitDefaultInsertValue.bind(this),AggregateFunctionNode:this.visitAggregateFunction.bind(this),OverNode:this.visitOver.bind(this),PartitionByNode:this.visitPartitionBy.bind(this),PartitionByItemNode:this.visitPartitionByItem.bind(this),SetOperationNode:this.visitSetOperation.bind(this),BinaryOperationNode:this.visitBinaryOperation.bind(this),UnaryOperationNode:this.visitUnaryOperation.bind(this),UsingNode:this.visitUsing.bind(this),FunctionNode:this.visitFunction.bind(this),CaseNode:this.visitCase.bind(this),WhenNode:this.visitWhen.bind(this),JSONReferenceNode:this.visitJSONReference.bind(this),JSONPathNode:this.visitJSONPath.bind(this),JSONPathLegNode:this.visitJSONPathLeg.bind(this),JSONOperatorChainNode:this.visitJSONOperatorChain.bind(this),TupleNode:this.visitTuple.bind(this),MergeQueryNode:this.visitMergeQuery.bind(this),MatchedNode:this.visitMatched.bind(this),AddIndexNode:this.visitAddIndex.bind(this),CastNode:this.visitCast.bind(this),FetchNode:this.visitFetch.bind(this),TopNode:this.visitTop.bind(this),OutputNode:this.visitOutput.bind(this),OrActionNode:this.visitOrAction.bind(this),CollateNode:this.visitCollate.bind(this)});visitNode=e=>{this.nodeStack.push(e),this.#e[e.kind](e),this.nodeStack.pop()}}const Kv=/'/g;class zv extends Hv{#e="";#t=[];get numParameters(){return this.#t.length}compileQuery(e,n){return this.#e="",this.#t=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode(e),d({query:e,queryId:n,sql:this.getSql(),parameters:[...this.#t]})}getSql(){return this.#e}visitSelectQuery(e){const n=this.parentNode!==void 0&&!Nt.is(this.parentNode)&&!be.is(this.parentNode)&&!We.is(this.parentNode)&&!$t.is(this.parentNode)&&!Ml.is(this.parentNode);this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(" ")),n&&this.append("("),e.with&&(this.visitNode(e.with),this.append(" ")),this.append("select"),e.distinctOn&&(this.append(" "),this.compileDistinctOn(e.distinctOn)),e.frontModifiers?.length&&(this.append(" "),this.compileList(e.frontModifiers," ")),e.top&&(this.append(" "),this.visitNode(e.top)),e.selections&&(this.append(" "),this.compileList(e.selections)),e.from&&(this.append(" "),this.visitNode(e.from)),e.joins&&(this.append(" "),this.compileList(e.joins," ")),e.where&&(this.append(" "),this.visitNode(e.where)),e.groupBy&&(this.append(" "),this.visitNode(e.groupBy)),e.having&&(this.append(" "),this.visitNode(e.having)),e.setOperations&&(this.append(" "),this.compileList(e.setOperations," ")),e.orderBy&&(this.append(" "),this.visitNode(e.orderBy)),e.limit&&(this.append(" "),this.visitNode(e.limit)),e.offset&&(this.append(" "),this.visitNode(e.offset)),e.fetch&&(this.append(" "),this.visitNode(e.fetch)),e.endModifiers?.length&&(this.append(" "),this.compileList(this.sortSelectModifiers([...e.endModifiers])," ")),n&&this.append(")")}visitFrom(e){this.append("from "),this.compileList(e.froms)}visitSelection(e){this.visitNode(e.selection)}visitColumn(e){this.visitNode(e.column)}compileDistinctOn(e){this.append("distinct on ("),this.compileList(e),this.append(")")}compileList(e,n=", "){const r=e.length-1;for(let i=0;i<=r;i++)this.visitNode(e[i]),i<r&&this.append(n)}visitWhere(e){this.append("where "),this.visitNode(e.where)}visitHaving(e){this.append("having "),this.visitNode(e.having)}visitInsertQuery(e){const n=this.parentNode!==void 0&&!Nt.is(this.parentNode)&&!de.is(this.parentNode)&&!un.is(this.parentNode);this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(" ")),n&&this.append("("),e.with&&(this.visitNode(e.with),this.append(" ")),this.append(e.replace?"replace":"insert"),e.ignore&&(Un("`InsertQueryNode.ignore` is deprecated. Use `InsertQueryNode.orAction` instead."),this.append(" ignore")),e.orAction&&(this.append(" "),this.visitNode(e.orAction)),e.top&&(this.append(" "),this.visitNode(e.top)),e.into&&(this.append(" into "),this.visitNode(e.into)),e.columns&&(this.append(" ("),this.compileList(e.columns),this.append(")")),e.output&&(this.append(" "),this.visitNode(e.output)),e.values&&(this.append(" "),this.visitNode(e.values)),e.defaultValues&&(this.append(" "),this.append("default values")),e.onConflict&&(this.append(" "),this.visitNode(e.onConflict)),e.onDuplicateKey&&(this.append(" "),this.visitNode(e.onDuplicateKey)),e.returning&&(this.append(" "),this.visitNode(e.returning)),n&&this.append(")"),e.endModifiers?.length&&(this.append(" "),this.compileList(e.endModifiers," "))}visitValues(e){this.append("values "),this.compileList(e.values)}visitDeleteQuery(e){const n=this.parentNode!==void 0&&!Nt.is(this.parentNode)&&!de.is(this.parentNode);this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(" ")),n&&this.append("("),e.with&&(this.visitNode(e.with),this.append(" ")),this.append("delete "),e.top&&(this.visitNode(e.top),this.append(" ")),this.visitNode(e.from),e.output&&(this.append(" "),this.visitNode(e.output)),e.using&&(this.append(" "),this.visitNode(e.using)),e.joins&&(this.append(" "),this.compileList(e.joins," ")),e.where&&(this.append(" "),this.visitNode(e.where)),e.orderBy&&(this.append(" "),this.visitNode(e.orderBy)),e.limit&&(this.append(" "),this.visitNode(e.limit)),e.returning&&(this.append(" "),this.visitNode(e.returning)),n&&this.append(")"),e.endModifiers?.length&&(this.append(" "),this.compileList(e.endModifiers," "))}visitReturning(e){this.append("returning "),this.compileList(e.selections)}visitAlias(e){this.visitNode(e.node),this.append(" as "),this.visitNode(e.alias)}visitReference(e){e.table&&(this.visitNode(e.table),this.append(".")),this.visitNode(e.column)}visitSelectAll(e){this.append("*")}visitIdentifier(e){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier(e),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier(e){if(!Ae(e.name))throw new Error("a non-string identifier was passed to compileUnwrappedIdentifier.");this.append(this.sanitizeIdentifier(e.name))}visitAnd(e){this.visitNode(e.left),this.append(" and "),this.visitNode(e.right)}visitOr(e){this.visitNode(e.left),this.append(" or "),this.visitNode(e.right)}visitValue(e){e.immediate?this.appendImmediateValue(e.value):this.appendValue(e.value)}visitValueList(e){this.append("("),this.compileList(e.values),this.append(")")}visitTuple(e){this.append("("),this.compileList(e.values),this.append(")")}visitPrimitiveValueList(e){this.append("(");const{values:n}=e;for(let r=0;r<n.length;++r)this.appendValue(n[r]),r!==n.length-1&&this.append(", ");this.append(")")}visitParens(e){this.append("("),this.visitNode(e.node),this.append(")")}visitJoin(e){this.append(Gv[e.joinType]),this.append(" "),this.visitNode(e.table),e.on&&(this.append(" "),this.visitNode(e.on))}visitOn(e){this.append("on "),this.visitNode(e.on)}visitRaw(e){const{sqlFragments:n,parameters:r}=e;for(let i=0;i<n.length;++i)this.append(n[i]),r.length>i&&this.visitNode(r[i])}visitOperator(e){this.append(e.operator)}visitTable(e){this.visitNode(e.table)}visitSchemableIdentifier(e){e.schema&&(this.visitNode(e.schema),this.append(".")),this.visitNode(e.identifier)}visitCreateTable(e){this.append("create "),e.frontModifiers&&e.frontModifiers.length>0&&(this.compileList(e.frontModifiers," "),this.append(" ")),e.temporary&&this.append("temporary "),this.append("table "),e.ifNotExists&&this.append("if not exists "),this.visitNode(e.table),e.selectQuery?(this.append(" as "),this.visitNode(e.selectQuery)):(this.append(" ("),this.compileList([...e.columns,...e.constraints??[]]),this.append(")"),e.onCommit&&(this.append(" on commit "),this.append(e.onCommit)),e.endModifiers&&e.endModifiers.length>0&&(this.append(" "),this.compileList(e.endModifiers," ")))}visitColumnDefinition(e){e.ifNotExists&&this.append("if not exists "),this.visitNode(e.column),this.append(" "),this.visitNode(e.dataType),e.unsigned&&this.append(" unsigned"),e.frontModifiers&&e.frontModifiers.length>0&&(this.append(" "),this.compileList(e.frontModifiers," ")),e.generated&&(this.append(" "),this.visitNode(e.generated)),e.identity&&this.append(" identity"),e.defaultTo&&(this.append(" "),this.visitNode(e.defaultTo)),e.notNull&&this.append(" not null"),e.unique&&this.append(" unique"),e.nullsNotDistinct&&this.append(" nulls not distinct"),e.primaryKey&&this.append(" primary key"),e.autoIncrement&&(this.append(" "),this.append(this.getAutoIncrement())),e.references&&(this.append(" "),this.visitNode(e.references)),e.check&&(this.append(" "),this.visitNode(e.check)),e.endModifiers&&e.endModifiers.length>0&&(this.append(" "),this.compileList(e.endModifiers," "))}getAutoIncrement(){return"auto_increment"}visitReferences(e){this.append("references "),this.visitNode(e.table),this.append(" ("),this.compileList(e.columns),this.append(")"),e.onDelete&&(this.append(" on delete "),this.append(e.onDelete)),e.onUpdate&&(this.append(" on update "),this.append(e.onUpdate))}visitDropTable(e){this.append("drop table "),e.ifExists&&this.append("if exists "),this.visitNode(e.table),e.cascade&&this.append(" cascade")}visitDataType(e){this.append(e.dataType)}visitOrderBy(e){this.append("order by "),this.compileList(e.items)}visitOrderByItem(e){this.visitNode(e.orderBy),e.collation&&(this.append(" "),this.visitNode(e.collation)),e.direction&&(this.append(" "),this.visitNode(e.direction)),e.nulls&&(this.append(" nulls "),this.append(e.nulls))}visitGroupBy(e){this.append("group by "),this.compileList(e.items)}visitGroupByItem(e){this.visitNode(e.groupBy)}visitUpdateQuery(e){const n=this.parentNode!==void 0&&!Nt.is(this.parentNode)&&!de.is(this.parentNode)&&!un.is(this.parentNode);if(this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(" ")),n&&this.append("("),e.with&&(this.visitNode(e.with),this.append(" ")),this.append("update "),e.top&&(this.visitNode(e.top),this.append(" ")),e.table&&(this.visitNode(e.table),this.append(" ")),this.append("set "),e.updates&&this.compileList(e.updates),e.output&&(this.append(" "),this.visitNode(e.output)),e.from&&(this.append(" "),this.visitNode(e.from)),e.joins){if(!e.from)throw new Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins");this.append(" "),this.compileList(e.joins," ")}e.where&&(this.append(" "),this.visitNode(e.where)),e.orderBy&&(this.append(" "),this.visitNode(e.orderBy)),e.limit&&(this.append(" "),this.visitNode(e.limit)),e.returning&&(this.append(" "),this.visitNode(e.returning)),n&&this.append(")"),e.endModifiers?.length&&(this.append(" "),this.compileList(e.endModifiers," "))}visitColumnUpdate(e){this.visitNode(e.column),this.append(" = "),this.visitNode(e.value)}visitLimit(e){this.append("limit "),this.visitNode(e.limit)}visitOffset(e){this.append("offset "),this.visitNode(e.offset)}visitOnConflict(e){this.append("on conflict"),e.columns?(this.append(" ("),this.compileList(e.columns),this.append(")")):e.constraint?(this.append(" on constraint "),this.visitNode(e.constraint)):e.indexExpression&&(this.append(" ("),this.visitNode(e.indexExpression),this.append(")")),e.indexWhere&&(this.append(" "),this.visitNode(e.indexWhere)),e.doNothing===!0?this.append(" do nothing"):e.updates&&(this.append(" do update set "),this.compileList(e.updates),e.updateWhere&&(this.append(" "),this.visitNode(e.updateWhere)))}visitOnDuplicateKey(e){this.append("on duplicate key update "),this.compileList(e.updates)}visitCreateIndex(e){this.append("create "),e.unique&&this.append("unique "),this.append("index "),e.ifNotExists&&this.append("if not exists "),this.visitNode(e.name),e.table&&(this.append(" on "),this.visitNode(e.table)),e.using&&(this.append(" using "),this.visitNode(e.using)),e.columns&&(this.append(" ("),this.compileList(e.columns),this.append(")")),e.nullsNotDistinct&&this.append(" nulls not distinct"),e.where&&(this.append(" "),this.visitNode(e.where))}visitDropIndex(e){this.append("drop index "),e.ifExists&&this.append("if exists "),this.visitNode(e.name),e.table&&(this.append(" on "),this.visitNode(e.table)),e.cascade&&this.append(" cascade")}visitCreateSchema(e){this.append("create schema "),e.ifNotExists&&this.append("if not exists "),this.visitNode(e.schema)}visitDropSchema(e){this.append("drop schema "),e.ifExists&&this.append("if exists "),this.visitNode(e.schema),e.cascade&&this.append(" cascade")}visitPrimaryKeyConstraint(e){e.name&&(this.append("constraint "),this.visitNode(e.name),this.append(" ")),this.append("primary key ("),this.compileList(e.columns),this.append(")"),this.buildDeferrable(e)}buildDeferrable(e){e.deferrable!==void 0&&(e.deferrable?this.append(" deferrable"):this.append(" not deferrable")),e.initiallyDeferred!==void 0&&(e.initiallyDeferred?this.append(" initially deferred"):this.append(" initially immediate"))}visitUniqueConstraint(e){e.name&&(this.append("constraint "),this.visitNode(e.name),this.append(" ")),this.append("unique"),e.nullsNotDistinct&&this.append(" nulls not distinct"),this.append(" ("),this.compileList(e.columns),this.append(")"),this.buildDeferrable(e)}visitCheckConstraint(e){e.name&&(this.append("constraint "),this.visitNode(e.name),this.append(" ")),this.append("check ("),this.visitNode(e.expression),this.append(")")}visitForeignKeyConstraint(e){e.name&&(this.append("constraint "),this.visitNode(e.name),this.append(" ")),this.append("foreign key ("),this.compileList(e.columns),this.append(") "),this.visitNode(e.references),e.onDelete&&(this.append(" on delete "),this.append(e.onDelete)),e.onUpdate&&(this.append(" on update "),this.append(e.onUpdate)),this.buildDeferrable(e)}visitList(e){this.compileList(e.items)}visitWith(e){this.append("with "),e.recursive&&this.append("recursive "),this.compileList(e.expressions)}visitCommonTableExpression(e){this.visitNode(e.name),this.append(" as "),bi(e.materialized)&&(e.materialized||this.append("not "),this.append("materialized ")),this.visitNode(e.expression)}visitCommonTableExpressionName(e){this.visitNode(e.table),e.columns&&(this.append("("),this.compileList(e.columns),this.append(")"))}visitAlterTable(e){this.append("alter table "),this.visitNode(e.table),this.append(" "),e.renameTo&&(this.append("rename to "),this.visitNode(e.renameTo)),e.setSchema&&(this.append("set schema "),this.visitNode(e.setSchema)),e.addConstraint&&this.visitNode(e.addConstraint),e.dropConstraint&&this.visitNode(e.dropConstraint),e.renameConstraint&&this.visitNode(e.renameConstraint),e.columnAlterations&&this.compileColumnAlterations(e.columnAlterations),e.addIndex&&this.visitNode(e.addIndex),e.dropIndex&&this.visitNode(e.dropIndex)}visitAddColumn(e){this.append("add column "),this.visitNode(e.column)}visitRenameColumn(e){this.append("rename column "),this.visitNode(e.column),this.append(" to "),this.visitNode(e.renameTo)}visitDropColumn(e){this.append("drop column "),this.visitNode(e.column)}visitAlterColumn(e){this.append("alter column "),this.visitNode(e.column),this.append(" "),e.dataType&&(this.announcesNewColumnDataType()&&this.append("type "),this.visitNode(e.dataType),e.dataTypeExpression&&(this.append("using "),this.visitNode(e.dataTypeExpression))),e.setDefault&&(this.append("set default "),this.visitNode(e.setDefault)),e.dropDefault&&this.append("drop default"),e.setNotNull&&this.append("set not null"),e.dropNotNull&&this.append("drop not null")}visitModifyColumn(e){this.append("modify column "),this.visitNode(e.column)}visitAddConstraint(e){this.append("add "),this.visitNode(e.constraint)}visitDropConstraint(e){this.append("drop constraint "),e.ifExists&&this.append("if exists "),this.visitNode(e.constraintName),e.modifier==="cascade"?this.append(" cascade"):e.modifier==="restrict"&&this.append(" restrict")}visitRenameConstraint(e){this.append("rename constraint "),this.visitNode(e.oldName),this.append(" to "),this.visitNode(e.newName)}visitSetOperation(e){this.append(e.operator),this.append(" "),e.all&&this.append("all "),this.visitNode(e.expression)}visitCreateView(e){this.append("create "),e.orReplace&&this.append("or replace "),e.materialized&&this.append("materialized "),e.temporary&&this.append("temporary "),this.append("view "),e.ifNotExists&&this.append("if not exists "),this.visitNode(e.name),this.append(" "),e.columns&&(this.append("("),this.compileList(e.columns),this.append(") ")),e.as&&(this.append("as "),this.visitNode(e.as))}visitRefreshMaterializedView(e){this.append("refresh materialized view "),e.concurrently&&this.append("concurrently "),this.visitNode(e.name),e.withNoData?this.append(" with no data"):this.append(" with data")}visitDropView(e){this.append("drop "),e.materialized&&this.append("materialized "),this.append("view "),e.ifExists&&this.append("if exists "),this.visitNode(e.name),e.cascade&&this.append(" cascade")}visitGenerated(e){this.append("generated "),e.always&&this.append("always "),e.byDefault&&this.append("by default "),this.append("as "),e.identity&&this.append("identity"),e.expression&&(this.append("("),this.visitNode(e.expression),this.append(")")),e.stored&&this.append(" stored")}visitDefaultValue(e){this.append("default "),this.visitNode(e.defaultValue)}visitSelectModifier(e){e.rawModifier?this.visitNode(e.rawModifier):this.append(Jv[e.modifier]),e.of&&(this.append(" of "),this.compileList(e.of,", "))}visitCreateType(e){this.append("create type "),this.visitNode(e.name),e.enum&&(this.append(" as enum "),this.visitNode(e.enum))}visitDropType(e){this.append("drop type "),e.ifExists&&this.append("if exists "),this.visitNode(e.name)}visitExplain(e){this.append("explain"),(e.options||e.format)&&(this.append(" "),this.append(this.getLeftExplainOptionsWrapper()),e.options&&(this.visitNode(e.options),e.format&&this.append(this.getExplainOptionsDelimiter())),e.format&&(this.append("format"),this.append(this.getExplainOptionAssignment()),this.append(e.format)),this.append(this.getRightExplainOptionsWrapper()))}visitDefaultInsertValue(e){this.append("default")}visitAggregateFunction(e){this.append(e.func),this.append("("),e.distinct&&this.append("distinct "),this.compileList(e.aggregated),e.orderBy&&(this.append(" "),this.visitNode(e.orderBy)),this.append(")"),e.withinGroup&&(this.append(" within group ("),this.visitNode(e.withinGroup),this.append(")")),e.filter&&(this.append(" filter("),this.visitNode(e.filter),this.append(")")),e.over&&(this.append(" "),this.visitNode(e.over))}visitOver(e){this.append("over("),e.partitionBy&&(this.visitNode(e.partitionBy),e.orderBy&&this.append(" ")),e.orderBy&&this.visitNode(e.orderBy),this.append(")")}visitPartitionBy(e){this.append("partition by "),this.compileList(e.items)}visitPartitionByItem(e){this.visitNode(e.partitionBy)}visitBinaryOperation(e){this.visitNode(e.leftOperand),this.append(" "),this.visitNode(e.operator),this.append(" "),this.visitNode(e.rightOperand)}visitUnaryOperation(e){this.visitNode(e.operator),this.isMinusOperator(e.operator)||this.append(" "),this.visitNode(e.operand)}isMinusOperator(e){return Kt.is(e)&&e.operator==="-"}visitUsing(e){this.append("using "),this.compileList(e.tables)}visitFunction(e){this.append(e.func),this.append("("),this.compileList(e.arguments),this.append(")")}visitCase(e){this.append("case"),e.value&&(this.append(" "),this.visitNode(e.value)),e.when&&(this.append(" "),this.compileList(e.when," ")),e.else&&(this.append(" else "),this.visitNode(e.else)),this.append(" end"),e.isStatement&&this.append(" case")}visitWhen(e){this.append("when "),this.visitNode(e.condition),e.result&&(this.append(" then "),this.visitNode(e.result))}visitJSONReference(e){this.visitNode(e.reference),this.visitNode(e.traversal)}visitJSONPath(e){e.inOperator&&this.visitNode(e.inOperator),this.append("'$");for(const n of e.pathLegs)this.visitNode(n);this.append("'")}visitJSONPathLeg(e){const n=e.type==="ArrayLocation";this.append(n?"[":"."),this.append(String(e.value)),n&&this.append("]")}visitJSONOperatorChain(e){for(let n=0,r=e.values.length;n<r;n++)n===r-1?this.visitNode(e.operator):this.append("->"),this.visitNode(e.values[n])}visitMergeQuery(e){e.with&&(this.visitNode(e.with),this.append(" ")),this.append("merge "),e.top&&(this.visitNode(e.top),this.append(" ")),this.append("into "),this.visitNode(e.into),e.using&&(this.append(" "),this.visitNode(e.using)),e.whens&&(this.append(" "),this.compileList(e.whens," ")),e.returning&&(this.append(" "),this.visitNode(e.returning)),e.output&&(this.append(" "),this.visitNode(e.output)),e.endModifiers?.length&&(this.append(" "),this.compileList(e.endModifiers," "))}visitMatched(e){e.not&&this.append("not "),this.append("matched"),e.bySource&&this.append(" by source")}visitAddIndex(e){this.append("add "),e.unique&&this.append("unique "),this.append("index "),this.visitNode(e.name),e.columns&&(this.append(" ("),this.compileList(e.columns),this.append(")")),e.using&&(this.append(" using "),this.visitNode(e.using))}visitCast(e){this.append("cast("),this.visitNode(e.expression),this.append(" as "),this.visitNode(e.dataType),this.append(")")}visitFetch(e){this.append("fetch next "),this.visitNode(e.rowCount),this.append(` rows ${e.modifier}`)}visitOutput(e){this.append("output "),this.compileList(e.selections)}visitTop(e){this.append(`top(${e.expression})`),e.modifiers&&this.append(` ${e.modifiers}`)}visitOrAction(e){this.append(e.action)}visitCollate(e){this.append("collate "),this.visitNode(e.collation)}append(e){this.#e+=e}appendValue(e){this.addParameter(e),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getCurrentParameterPlaceholder(){return"$"+this.numParameters}getLeftExplainOptionsWrapper(){return"("}getExplainOptionAssignment(){return" "}getExplainOptionsDelimiter(){return", "}getRightExplainOptionsWrapper(){return")"}sanitizeIdentifier(e){const n=this.getLeftIdentifierWrapper(),r=this.getRightIdentifierWrapper();let i="";for(const s of e)i+=s,s===n?i+=n:s===r&&(i+=r);return i}sanitizeStringLiteral(e){return e.replace(Kv,"''")}addParameter(e){this.#t.push(e)}appendImmediateValue(e){if(Ae(e))this.appendStringLiteral(e);else if(_i(e)||bi(e)||Uo(e))this.append(e.toString());else if(Bo(e))this.append("null");else if(ox(e))this.appendImmediateValue(e.toISOString());else throw new Error(`invalid immediate value ${e}`)}appendStringLiteral(e){this.append("'"),this.append(this.sanitizeStringLiteral(e)),this.append("'")}sortSelectModifiers(e){return e.sort((n,r)=>n.modifier&&r.modifier?Hc[n.modifier]-Hc[r.modifier]:1),d(e)}compileColumnAlterations(e){this.compileList(e)}announcesNewColumnDataType(){return!0}}const Jv=d({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),Hc=d({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),Gv=d({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"}),Qr=d({raw(t,e=[]){return d({sql:t,query:de.createWithSql(t),parameters:d(e),queryId:j()})}});class Zv{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}}class Yv{transformQuery(e){return e.node}async transformResult(e){return e.result}}const Ql="kysely_migration",Gs="kysely_migration_lock",Qv=!1,Cs="migration_lock";d({__noMigrations__:!0});class kE{#e;constructor(e){this.#e=d(e)}async getMigrations(){const e=await this.#l(this.#r)?await this.#e.db.withPlugin(this.#s).selectFrom(this.#r).select(["name","timestamp"]).$narrowType().execute():[];return(await this.#b()).map(({name:r,...i})=>{const s=e.find(o=>o.name===r);return{name:r,migration:i,executedAt:s?new Date(s.timestamp):void 0}})}async migrateToLatest(){return this.#t(()=>({direction:"Up",step:1/0}))}async migrateTo(e){return this.#t(({migrations:n,executedMigrations:r,pendingMigrations:i})=>{if(je(e)&&e.__noMigrations__===!0)return{direction:"Down",step:1/0};if(!n.find(a=>a.name===e))throw new Error(`migration "${e}" doesn't exist`);const s=r.indexOf(e),o=i.findIndex(a=>a.name===e);if(s!==-1)return{direction:"Down",step:r.length-s-1};if(o!==-1)return{direction:"Up",step:o+1};throw new Error(`migration "${e}" isn't executed or pending`)})}async migrateUp(){return this.#t(()=>({direction:"Up",step:1}))}async migrateDown(){return this.#t(()=>({direction:"Down",step:1}))}async#t(e){try{return await this.#o(),await this.#w(e)}catch(n){return n instanceof Ts?n.resultSet:{error:n}}}get#n(){return this.#e.migrationTableSchema}get#r(){return this.#e.migrationTableName??Ql}get#i(){return this.#e.migrationLockTableName??Gs}get#c(){return this.#e.allowUnorderedMigrations??Qv}get#s(){return this.#n?new fn(this.#n):new Yv}async#o(){await this.#a(),await this.#d(),await this.#u(),await this.#p()}async#a(){if(this.#n&&!await this.#h())try{await this.#f(this.#e.db.schema.createSchema(this.#n))}catch(e){if(!await this.#h())throw e}}async#d(){if(!await this.#l(this.#r))try{this.#n&&await this.#f(this.#e.db.schema.createSchema(this.#n)),await this.#f(this.#e.db.schema.withPlugin(this.#s).createTable(this.#r).addColumn("name","varchar(255)",e=>e.notNull().primaryKey()).addColumn("timestamp","varchar(255)",e=>e.notNull()))}catch(e){if(!await this.#l(this.#r))throw e}}async#u(){if(!await this.#l(this.#i))try{await this.#f(this.#e.db.schema.withPlugin(this.#s).createTable(this.#i).addColumn("id","varchar(255)",e=>e.notNull().primaryKey()).addColumn("is_locked","integer",e=>e.notNull().defaultTo(0)))}catch(e){if(!await this.#l(this.#i))throw e}}async#p(){if(!await this.#m())try{await this.#e.db.withPlugin(this.#s).insertInto(this.#i).values({id:Cs,is_locked:0}).execute()}catch(e){if(!await this.#m())throw e}}async#h(){return(await this.#e.db.introspection.getSchemas()).some(n=>n.name===this.#n)}async#l(e){const n=this.#n;return(await this.#e.db.introspection.getTables({withInternalKyselyTables:!0})).some(i=>i.name===e&&(!n||i.schema===n))}async#m(){return!!await this.#e.db.withPlugin(this.#s).selectFrom(this.#i).where("id","=",Cs).select("id").executeTakeFirst()}async#w(e){const n=this.#e.db.getExecutor().adapter,r=d({lockTable:this.#e.migrationLockTableName??Gs,lockRowId:Cs,lockTableSchema:this.#e.migrationTableSchema}),i=async s=>{try{await n.acquireMigrationLock(s,r);const o=await this.#y(s);if(o.migrations.length===0)return{results:[]};const{direction:a,step:c}=e(o);return c<=0?{results:[]}:a==="Down"?await this.#E(s,o,c):a==="Up"?await this.#D(s,o,c):{results:[]}}finally{await n.releaseMigrationLock(s,r)}};return n.supportsTransactionalDdl&&!this.#e.disableTransactions?this.#e.db.transaction().execute(i):this.#e.db.connection().execute(i)}async#y(e){const n=await this.#b(),r=await this.#N(e);this.#x(n,r),this.#c||this.#v(n,r);const i=this.#g(n,r);return d({migrations:n,executedMigrations:r,lastMigration:ax(r),pendingMigrations:i})}#g(e,n){return e.filter(r=>!n.includes(r.name))}async#b(){const e=await this.#e.provider.getMigrations();return Object.keys(e).sort().map(n=>({...e[n],name:n}))}async#N(e){const n=await e.withPlugin(this.#s).selectFrom(this.#r).select(["name","timestamp"]).$narrowType().execute(),r=this.#e.nameComparator||((i,s)=>i.localeCompare(s));return n.sort((i,s)=>i.timestamp===s.timestamp?r(i.name,s.name):new Date(i.timestamp).getTime()-new Date(s.timestamp).getTime()).map(i=>i.name)}#x(e,n){for(const r of n)if(!e.some(i=>i.name===r))throw new Error(`corrupted migrations: previously executed migration ${r} is missing`)}#v(e,n){for(let r=0;r<n.length;++r)if(e[r].name!==n[r])throw new Error(`corrupted migrations: expected previously executed migration ${n[r]} to be at index ${r} but ${e[r].name} was found in its place. New migrations must always have a name that comes alphabetically after the last executed migration.`)}async#E(e,n,r){const i=n.executedMigrations.slice().reverse().slice(0,r).map(o=>n.migrations.find(a=>a.name===o)),s=i.map(o=>({migrationName:o.name,direction:"Down",status:"NotExecuted"}));for(let o=0;o<s.length;++o){const a=i[o];try{a.down&&(await a.down(e),await e.withPlugin(this.#s).deleteFrom(this.#r).where("name","=",a.name).execute(),s[o]={migrationName:a.name,direction:"Down",status:"Success"})}catch(c){throw s[o]={migrationName:a.name,direction:"Down",status:"Error"},new Ts({error:c,results:s})}}return{results:s}}async#D(e,n,r){const s=n.pendingMigrations.slice(0,r).map(o=>({migrationName:o.name,direction:"Up",status:"NotExecuted"}));for(let o=0;o<s.length;o++){const a=n.pendingMigrations[o];try{await a.up(e),await e.withPlugin(this.#s).insertInto(this.#r).values({name:a.name,timestamp:new Date().toISOString()}).execute(),s[o]={migrationName:a.name,direction:"Up",status:"Success"}}catch(c){throw s[o]={migrationName:a.name,direction:"Up",status:"Error"},new Ts({error:c,results:s})}}return{results:s}}async#f(e){this.#e.db.getExecutor().adapter.supportsCreateIfNotExists&&(e=e.ifNotExists()),await e.execute()}}class Ts extends Error{#e;constructor(e){super(),this.#e=e}get resultSet(){return this.#e}}const Xv=/"/g;class e1 extends zv{sanitizeIdentifier(e){return e.replace(Xv,'""')}}class t1{#e;constructor(e){this.#e=e}async getSchemas(){return(await this.#e.selectFrom("pg_catalog.pg_namespace").select("nspname").$castTo().execute()).map(n=>({name:n.nspname}))}async getTables(e={withInternalKyselyTables:!1}){let n=this.#e.selectFrom("pg_catalog.pg_attribute as a").innerJoin("pg_catalog.pg_class as c","a.attrelid","c.oid").innerJoin("pg_catalog.pg_namespace as ns","c.relnamespace","ns.oid").innerJoin("pg_catalog.pg_type as typ","a.atttypid","typ.oid").innerJoin("pg_catalog.pg_namespace as dtns","typ.typnamespace","dtns.oid").select(["a.attname as column","a.attnotnull as not_null","a.atthasdef as has_default","c.relname as table","c.relkind as table_type","ns.nspname as schema","typ.typname as type","dtns.nspname as type_schema",In`col_description(a.attrelid, a.attnum)`.as("column_description"),In`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as("auto_incrementing")]).where("c.relkind","in",["r","v","p"]).where("ns.nspname","!~","^pg_").where("ns.nspname","!=","information_schema").where("ns.nspname","!=","crdb_internal").where(In`has_schema_privilege(ns.nspname, 'USAGE')`).where("a.attnum",">=",0).where("a.attisdropped","!=",!0).orderBy("ns.nspname").orderBy("c.relname").orderBy("a.attnum").$castTo();e.withInternalKyselyTables||(n=n.where("c.relname","!=",Ql).where("c.relname","!=",Gs));const r=await n.execute();return this.#t(r)}async getMetadata(e){return{tables:await this.getTables(e)}}#t(e){return e.reduce((n,r)=>{let i=n.find(s=>s.name===r.table&&s.schema===r.schema);return i||(i=d({name:r.table,isView:r.table_type==="v",schema:r.schema,columns:[]}),n.push(i)),i.columns.push(d({name:r.column,dataType:r.type,dataTypeSchema:r.type_schema,isNullable:!r.not_null,isAutoIncrementing:r.auto_incrementing!==null,hasDefaultValue:r.has_default,comment:r.column_description??void 0})),n},[])}}const n1=BigInt("3853314791062309107");class r1 extends Zv{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(e,n){await In`select pg_advisory_xact_lock(${In.lit(n1)})`.execute(e)}async releaseMigrationLock(e,n){}}var i1=class{client;constructor(t){this.client=t}async executeQuery(t){const e=await this.client.query(t.sql,[...t.parameters]);return e.affectedRows?{numAffectedRows:BigInt(e.affectedRows),rows:e.rows}:{rows:e.rows}}async*streamQuery(t,e){if(!Number.isInteger(e)||e<=0)throw new Error("chunkSize must be a positive integer");const n=await this.client.query(t.sql,[...t.parameters]);for(let r=0;r<n.rows.length;r=r+e)yield{rows:n.rows.slice(r,r+e)}}},SE=class{constructor(t){this.pgLite=t}createAdapter(){return new r1}createDriver(){return new s1(this.pgLite)}createQueryCompiler(){return new e1}createIntrospector(t){return new t1(t)}},s1=class{client;connection;queue=[];constructor(t){this.client=t}async init(){}async acquireConnection(){if(this.client===void 0)throw new Error("PGLite not initialized");return this.connection!==void 0?new Promise(t=>{this.queue.push(t)}):(this.connection=new i1(this.client),this.connection)}async releaseConnection(t){if(t!==this.connection)throw new Error("Invalid connection");const n=this.queue.splice(0,1)[0];if(n===void 0){this.connection=void 0;return}n(this.connection)}async beginTransaction(t,e){e.isolationLevel?await t.executeQuery(Qr.raw(`start transaction isolation level ${e.isolationLevel}`)):await t.executeQuery(Qr.raw("begin"))}async commitTransaction(t){await t.executeQuery(Qr.raw("commit"))}async rollbackTransaction(t){await t.executeQuery(Qr.raw("rollback"))}async destroy(){this.client=void 0}};const o1="https://www.renown.id",a1="eip155",c1="1";function AE(){const t=new URL(o1);t.searchParams.set("connect",window.ph?.did??""),t.searchParams.set("network",a1),t.searchParams.set("chain",c1);const e=new URL(window.location.pathname,window.location.origin);t.searchParams.set("returnUrl",e.toJSON()),window.open(t,"_self")?.focus()}async function OE(t,e,n,r){if(!(!n||!r||!e))try{xn("checking");let i=n.user instanceof Function?n.user():n.user;if(i=i instanceof Promise?await i:i,i?.did&&(i.did===t||!t))return xn("authorized"),xc(i),e.setGenerateJwtHandler(async o=>r.getBearerToken(o,i.address,!0,{expiresIn:10})),i;if(!t)return;const s=await n.login(t??"");s?(xn("authorized"),xc(s),e.setGenerateJwtHandler(async o=>r.getBearerToken(o,s.address,!0,{expiresIn:10}))):xn("not-authorized")}catch(i){xn("not-authorized"),ie.error(i)}}async function CE(){const t=window.ph?.renown,e=window.ph?.legacyReactor;xn("initial"),await t?.logout(),e?.removeJwtHandler()}export{Qc as $,Sg as A,lg as B,Vu as C,J2 as D,ml as E,j2 as F,B2 as G,Fh as H,A2 as I,J1 as J,nn as K,W1 as L,kE as M,aE as N,rE as O,SE as P,af as Q,G1 as R,z1 as S,W2 as T,uE as U,Z1 as V,Yc as W,Q1 as X,V1 as Y,S1 as Z,Co as _,H1 as a,j1 as a0,Gh as a1,E1 as a2,xE as a3,U1 as a4,R1 as a5,$1 as a6,B1 as a7,q1 as a8,dg as a9,N1 as aA,x1 as aB,v1 as aC,K1 as aD,b1 as aE,T2 as aF,Hh as aG,M1 as aH,g1 as aI,y1 as aJ,w1 as aK,eo as aL,hE as aM,I1 as aN,Zu as aa,Ng as ab,OE as ac,_1 as ad,wE as ae,yE as af,gE as ag,F1 as ah,fE as ai,pE as aj,NE as ak,mE as al,og as am,L1 as an,v2 as ao,x2 as ap,qu as aq,bE as ar,m1 as as,CE as at,AE as au,S2 as av,Y1 as aw,p1 as ax,nE as ay,Gc as az,DE as b,Ao as c,Yu as d,tE as e,Xu as f,jh as g,ju as h,sE as i,R2 as j,vE as k,iE as l,cE as m,dE as n,eE as o,D1 as p,EE as q,Kb as r,Ag as s,P1 as t,oE as u,X1 as v,C2 as w,lE as x,k1 as y,In as z};
|