@powerhousedao/connect 5.1.0-dev.13 → 5.1.0-dev.15

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.
Files changed (49) hide show
  1. package/dist/assets/{AddDriveModal-CJ-bVy3_.js → AddDriveModal-CFiZUwbG.js} +1 -1
  2. package/dist/assets/{ClearStorageModal-D3RZAgrW.js → ClearStorageModal-B08dxM9Q.js} +1 -1
  3. package/dist/assets/{CookiesPolicyModal-BIve839u.js → CookiesPolicyModal-1L0r5OwI.js} +1 -1
  4. package/dist/assets/CreateDocumentModal-D56YVF3R.js +1 -0
  5. package/dist/assets/{DebugSettingsModal-BXk4_2QI.js → DebugSettingsModal-FF8F5iL9.js} +1 -1
  6. package/dist/assets/{DeleteDriveModal-D1nliv0t.js → DeleteDriveModal-BX2F5ijO.js} +1 -1
  7. package/dist/assets/DeleteItemModal-Dp0yI59L.js +1 -0
  8. package/dist/assets/DisclaimerModal-lDeplIo2.js +1 -0
  9. package/dist/assets/DriveSettingsModal-DOebf6uN.js +1 -0
  10. package/dist/assets/{ExportDocumentWithErrorsModal-T6DgSPPe.js → ExportDocumentWithErrorsModal-CU2IqI_V.js} +1 -1
  11. package/dist/assets/{SettingsModal-uUVQnlan.js → SettingsModal-C51lS85m.js} +1 -1
  12. package/dist/assets/UpgradeDriveModal-DcIAJzVB.js +1 -0
  13. package/dist/assets/{design_system-CXWL2el7.js → design_system-UWj0AhHV.js} +1 -1
  14. package/dist/assets/{design_system_connect-BziKm0Dg.js → design_system_connect-lcd2b25T.js} +4 -4
  15. package/dist/assets/{design_system_ui-Dxl4iPBf.js → design_system_ui-CErGSL3p.js} +1 -1
  16. package/dist/assets/{document_drive-CVkeqJ3l.js → document_drive-DZ6mXkbS.js} +1 -1
  17. package/dist/assets/{document_engineering-DBRB-fgc.js → document_engineering-BXuZzkFN.js} +1 -1
  18. package/dist/assets/{document_model-LXEZCDPq.js → document_model-D4RwF66T.js} +1 -1
  19. package/dist/assets/{document_model_editor-z5olAhx3.js → document_model_editor-D_BY44WX.js} +4 -4
  20. package/dist/assets/{drive_explorer-DWgA9K4r.js → drive_explorer-DQY98xjB.js} +2 -2
  21. package/dist/assets/{graphql-editor-D886web_.js → graphql-editor-DmoLtFTg.js} +1 -1
  22. package/dist/assets/{hooks-e_ii3Esl.js → hooks-CYkOxZbe.js} +1 -1
  23. package/dist/assets/index-BtQu1SOl.js +20 -0
  24. package/dist/assets/{json-editor-CHuyzVLs.js → json-editor-VziZWCXO.js} +1 -1
  25. package/dist/assets/{nodefs-B7lQTpJ4.js → nodefs-BrkZxu2e.js} +1 -1
  26. package/dist/assets/{opfs-ahp-CusaWQGU.js → opfs-ahp-DivB1_J8.js} +1 -1
  27. package/dist/assets/reactor_browser-BWiRZG4C.js +25 -0
  28. package/dist/assets/{state-schemas-BO2eMHcE.js → state-schemas-DTWL4CA4.js} +2 -2
  29. package/dist/index.html +9 -9
  30. package/lib/package.copy.json +1 -1
  31. package/lib/src/feature-flags.js +4 -4
  32. package/lib/src/feature-flags.js.map +1 -1
  33. package/lib/src/hooks/useClientErrorHandler.d.ts.map +1 -1
  34. package/lib/src/hooks/useClientErrorHandler.js +13 -2
  35. package/lib/src/hooks/useClientErrorHandler.js.map +1 -1
  36. package/lib/src/store/reactor.d.ts.map +1 -1
  37. package/lib/src/store/reactor.js +67 -28
  38. package/lib/src/store/reactor.js.map +1 -1
  39. package/lib/tsconfig.tsbuildinfo +1 -1
  40. package/nginx.conf +7 -0
  41. package/package.copy.json +1 -1
  42. package/package.json +10 -10
  43. package/dist/assets/CreateDocumentModal-BmIO-7Pc.js +0 -1
  44. package/dist/assets/DeleteItemModal-CbszPdS6.js +0 -1
  45. package/dist/assets/DisclaimerModal-BKVNrbUc.js +0 -1
  46. package/dist/assets/DriveSettingsModal-Doz_7CYW.js +0 -1
  47. package/dist/assets/UpgradeDriveModal-dK4Ihal5.js +0 -1
  48. package/dist/assets/index-DcOzw2lF.js +0 -20
  49. package/dist/assets/reactor_browser-CwsD6kpc.js +0 -25
@@ -0,0 +1,25 @@
1
+ import{l as pe,d as lh,a as hh,i as lr,b as oa,c as sa,g as fh,h as ph,e as mh,m as wh,u as bh,s as aa,f as ca,j as yh,r as gh,P as Nh,k as xh,S as vh,D as Eh,n as Dh}from"./document_drive-DZ6mXkbS.js";import{Y as kh,Z as Sh,_ as Ch,d as Ah,$ as Oh,g as et,k as Ii,w as Th,e as Rh,a0 as Ih,a1 as Wh,a2 as Mh,j as Lh,h as Ph}from"./document_model-D4RwF66T.js";import"./document_model_editor-D_BY44WX.js";import{r as Ht}from"./sentry_react-cODD7zWc.js";import{g as Xo,a as Wi}from"./react-DQSxOgtG.js";function I(t){const e=`ph:set${kh(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 o(h){const f=h.detail[t];if(!window.ph)throw new Error("ph global store is not defined");window.ph[t]=f,i()}function s(){window.addEventListener(e,o)}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 Ht.useSyncExternalStore(a,c)}return{useValue:u,setValue:r,addEventHandler:s}}const ed=I("features"),x1=ed.setValue,$h=ed.addEventHandler;function Mi(){return window.ph?.features?.get("FEATURE_LEGACY_READ_ENABLED")??!0}function We(){return window.ph?.features?.get("FEATURE_LEGACY_WRITE_ENABLED")??!0}function es(){return window.ph?.features?.get("FEATURE_CHANNEL_SYNC_ENABLED")??!1}async function Ge(t,e){if(!t)throw new Error("No document provided");if(!e)throw new Error("No actions provided");const n=Array.isArray(e)?e:[e];if(n.length===0)throw new Error("No actions provided");if(We()){const i=window.ph?.legacyReactor;if(!i)throw new Error("Legacy reactor not initialized");const o=await i.queueActions(t.header.id,n);return o.status!=="SUCCESS"&&pe.error(o.error),o.document}else{const i=window.ph?.reactorClient;if(!i)throw new Error("ReactorClient not initialized");return await i.execute(t.header.id,"main",n)}}async function td(t,e){if(!t)throw new Error("No documentId provided");if(!e)throw new Error("No operations provided");const n=Array.isArray(e)?e:[e];if(n.length===0)throw new Error("No operations provided");if(We()){const i=window.ph?.legacyReactor;if(!i)throw new Error("Legacy reactor not initialized");const o=await i.queueOperations(t,n);return o.status!=="SUCCESS"&&pe.error(o.error),o.document}else{const i=window.ph?.reactorClient;if(!i)throw new Error("ReactorClient not initialized");const o=n.map(s=>s.action);return await i.execute(t,"main",o)}}async function nd(t,e,n,r){const i=r?.operationsLimit||50,o=r?.onProgress;pe.verbose(`uploadDocumentOperations(documentId:${t}, ops: ${Object.keys(e).join(",")}, limit:${i})`);const s=Object.values(e).filter(u=>u!==void 0),a=s.reduce((u,h)=>u+h.length,0);let c=0;for(const u of s)for(let h=0;h<u.length;h+=i){pe.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,o){const p=Math.round(c/a*100);o({stage:"uploading",progress:p,totalOperations:a,uploadedOperations:c})}pe.verbose(`uploadDocumentOperations:for:waitForUpdate(${t}:${m} rev ${l.index}): NEXT`)}pe.verbose(`uploadDocumentOperations:for:waitForUpdate(${t}): END`)}async function Bh(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 pe.error(`Document model '${e.header.documentType}' not found`),t;const o=i.reducer,s=window.ph?.user,a=window.ph?.connectCrypto;if(!s||!a||!t.context?.signer)return t;const c=t.context.signer;return await Sh(t,o,e,c,a.sign)}function Uh(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 qh(t,e){if(!t){pe.error("No action found");return}if(!e){pe.error("No document found");return}const n=await Bh(t,e);return Uh(n)}async function Fh(t,e){if(!t){pe.error("No actions found");return}const n=Array.isArray(t)?t:[t];return(await Promise.all(n.map(i=>qh(i,e)))).filter(i=>i!==void 0)}async function Vh(t){try{return await window.ph?.legacyReactor?.getDocument(t)}catch(e){pe.debug(`Failed to get document with id ${t}:`,e);return}}async function _h(t,e){const n=typeof e=="string"?await Vh(e):e;if(!n){pe.error(`Document with id ${JSON.stringify(e)} not found`);return}const r=await Fh(t,n);if(!r){pe.error("No signed actions with context found");return}return await Ge(n,r)}class da extends Error{constructor(e){super(`Document type ${e} is not supported`),this.name="UnsupportedDocumentTypeError"}}class jh extends Error{constructor(e,n,r){super(`Document ${e} is not of type ${n}. Actual type: ${r}`)}}class Hh extends Error{constructor(){super("There is no selected document. Call 'setSelectedNode' to select a document.")}}function zh(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 Fe(){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 Kh(t,e,n){const r=Mi();try{if(r){const i=window.ph?.legacyReactor;if(!i)throw new Error("Legacy reactor not initialized");const o=await i.getDrive(e),s=o.state.global.nodes.find(c=>c.id===t.header.id);if(s&&s.parentFolder===(n??null))return{isDuplicate:!0,duplicateType:"id",nodeId:s.id};const a=o.state.global.nodes.find(c=>lr(c)&&c.name===t.header.name&&c.documentType===t.header.documentType&&c.parentFolder===(n??null));return a?{isDuplicate:!0,duplicateType:"name",nodeId:a.id}:{isDuplicate:!1}}else{const i=window.ph?.reactorClient;if(!i)throw new Error("ReactorClient not initialized");const{document:o}=await i.get(e),s=o.state.global.nodes.find(c=>c.id===t.header.id);if(s&&s.parentFolder===(n??null))return{isDuplicate:!0,duplicateType:"id",nodeId:s.id};const a=o.state.global.nodes.find(c=>lr(c)&&c.name===t.header.name&&c.documentType===t.header.documentType&&c.parentFolder===(n??null));return a?{isDuplicate:!0,duplicateType:"name",nodeId:a.id}:{isDuplicate:!1}}}catch{return{isDuplicate:!1}}}function Jh(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 Gh(t,e){Oh(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(pe.error)}async function Zh(t,e){if(Mi()){if(!window.ph?.legacyReactor)throw new Error("Legacy reactor not initialized")}else if(!window.ph?.reactorClient)throw new Error("ReactorClient not initialized");let r="";if(t.header.documentType===Ch){const s=t.state.global.extension.replace(/^\.+|\.+$/g,"");r=s!==""?`.${s}`:""}const i=`${t.header.name||"Untitled"}${r}.phd`;if(!window.showSaveFilePicker)return Gh(t,i);try{const o=await window.showSaveFilePicker({suggestedName:i});return await Ah(t,o),o}catch(o){if(!(o instanceof DOMException&&o.name==="AbortError"))throw o}}async function rd(t){const e=Mi(),n=await Rh(t,r=>r,{checkHashes:!0});if(e){const r=window.ph?.legacyReactor;if(!r)throw new Error("Legacy reactor not initialized");const o=r.getDocumentModelModules().find(s=>s.documentModel.global.id===n.header.documentType);if(!o)throw new Error(`Document "${n.header.documentType}" is not supported`);return o.utils.loadFromInput(t)}else{const r=window.ph?.reactorClient;if(!r)throw new Error("ReactorClient not initialized");const{results:i}=await r.getDocumentModels(),o=i.find(s=>s.documentModel.global.id===n.header.documentType);if(!o)throw new Error(`Document "${n.header.documentType}" is not supported`);return o.utils.loadFromInput(t)}}async function id(t,e,n,r,i,o,s){const{isAllowedToCreateDocuments:a}=Fe();if(!a)throw new Error("User is not allowed to create documents");if(We()){const u=window.ph?.legacyReactor;if(!u)throw new Error("Legacy reactor not initialized");const h=await u.getDrive(t),f=o??et(),m=u.getDocumentModelModules().find(y=>y.documentModel.global.id===n);if(!m)throw new Error(`Document model module for type ${n} not found`);const p=m.utils.createDocument({...i?.state});p.header=Ii(f,n),p.header.name=e;const w=s?{preferredEditor:s}:void 0;await u.addDocument(p,w);const v=hh({id:f,name:e,documentType:n,parentFolder:r??null}),g=(await Ge(h,v)).state.global.nodes.find(y=>y.id===f);if(!g||!lr(g))throw new Error("There was an error adding document");return g}else{const u=window.ph?.reactorClient;if(!u)throw new Error("ReactorClient not initialized");const h=await u.createEmpty(n,t);return e&&await u.rename(h.header.id,e),r&&await u.moveChildren(t,r,[h.header.id]),{id:h.header.id,name:e||h.header.name,documentType:n,parentFolder:r??null,kind:"file"}}}async function Yh(t,e,n,r){pe.verbose(`addFile(drive: ${e}, name: ${n}, folder: ${r})`);const{isAllowedToCreateDocuments:i}=Fe();if(!i)throw new Error("User is not allowed to create files");const o=We(),s=await rd(t);if(!s)throw new Error("No document loaded");let a=!1;if(o){const l=window.ph?.legacyReactor;if(!l)throw new Error("Legacy reactor not initialized");if(!l.getDocumentModelModules().find(p=>p.documentModel.global.id===s.header.documentType))throw new Error(`Document model module for type ${s.header.documentType} not found`);try{await l.getDocument(s.header.id),a=!0}catch{}}else{const l=window.ph?.reactorClient;if(!l)throw new Error("ReactorClient not initialized");const{results:m}=await l.getDocumentModels();if(!m.find(w=>w.documentModel.global.id===s.header.documentType))throw new Error(`Document model module for type ${s.header.documentType} not found`);try{await l.get(s.header.id),a=!0}catch{}}const c=a?et():s.header.id,u=Ii(c,s.header.documentType);u.lastModifiedAtUtcIso=s.header.createdAtUtcIso,u.meta=s.header.meta,u.name=n||s.header.name;const h={...s,state:s.initialState,operations:Object.keys(s.operations).reduce((l,m)=>(l[m]=[],l),{})};if(!await id(e,n||s.header.name,s.header.documentType,r,h,c,s.header.meta?.preferredEditor))throw new Error("There was an error adding file");nd(c,s.operations,td).catch(l=>{throw l})}async function Qh(t,e,n,r,i,o,s){pe.verbose(`addFileWithProgress(drive: ${e}, name: ${n}, folder: ${r})`);const a=window.ph?.legacyReactor;if(!a)return;const{isAllowedToCreateDocuments:c}=Fe();if(!c)throw new Error("User is not allowed to create files");try{i?.({stage:"loading",progress:0});const u=await rd(t);if(!u)throw new Error("No document loaded");const h=await Kh(u,e,r);if(h.isDuplicate&&!s){i?.({stage:"conflict",progress:0,duplicateType:h.duplicateType});return}h.isDuplicate&&s==="replace"&&h.nodeId&&await ef(e,h.nodeId);const f=Jh(u);if(i?.(f?{stage:"loading",progress:10,documentType:f}:{stage:"loading",progress:10}),!zh(u.header.documentType,o))throw i?.({stage:"unsupported-document-type",progress:100,error:`Document type ${u.header.documentType} is not supported`}),new da(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?et():u.header.id,w=Ii(p,u.header.documentType);w.lastModifiedAtUtcIso=u.header.createdAtUtcIso,w.meta=u.header.meta,w.name=n||u.header.name;const v={...u,header:w,state:u.initialState,operations:Object.keys(u.operations).reduce((g,y)=>(g[y]=[],g),{})},b=await id(e,n||u.header.name,u.header.documentType,r,v,p,u.header.meta?.preferredEditor);if(!b)throw new Error("There was an error adding file");return i?.({stage:"initializing",progress:20}),await nd(p,u.operations,td,{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}),b}catch(u){if(!(u instanceof da)){const h=u instanceof Error?u.message:"Unknown error occurred";i?.({stage:"failed",progress:100,error:h})}throw u}}async function Xh(t,e,n){const{isAllowedToCreateDocuments:r}=Fe();if(!r)throw new Error("User is not allowed to create folders");if(We()){const o=window.ph?.legacyReactor;if(!o)throw new Error("Legacy reactor not initialized");const s=et(),a=await o.getDrive(t),u=(await Ge(a,oa({id:s,name:e,parentFolder:n}))).state.global.nodes.find(h=>h.id===s);if(!u||!sa(u))throw new Error("There was an error adding folder");return u}else{const o=window.ph?.reactorClient;if(!o)throw new Error("ReactorClient not initialized");const{document:s}=await o.get(t),a=et(),u=(await o.execute(t,"main",[oa({id:a,name:e,parentFolder:n})])).state.global.nodes.find(h=>h.id===a);if(!u||!sa(u))throw new Error("There was an error adding folder");return u}}async function ef(t,e){const{isAllowedToCreateDocuments:n}=Fe();if(!n)throw new Error("User is not allowed to delete documents");if(We()){const i=window.ph?.legacyReactor;if(!i)throw new Error("Legacy reactor not initialized");const o=await i.getDrive(t);await Ge(o,lh({id:e}))}else{const i=window.ph?.reactorClient;if(!i)throw new Error("ReactorClient not initialized");await i.deleteDocument(e)}}async function tf(t,e,n){const{isAllowedToCreateDocuments:r}=Fe();if(!r)throw new Error("User is not allowed to rename documents");if(We()){const o=window.ph?.legacyReactor;if(!o)throw new Error("Legacy reactor not initialized");const s=await o.getDrive(t),c=(await Ge(s,bh({id:e,name:n}))).state.global.nodes.find(u=>u.id===e);if(!c)throw new Error("There was an error renaming node");return c}else{const o=window.ph?.reactorClient;if(!o)throw new Error("ReactorClient not initialized");await o.rename(e,n);const{document:s}=await o.get(t),a=s.state.global.nodes.find(c=>c.id===e);if(!a)throw new Error("There was an error renaming node");return a}}async function nf(t,e,n){const{isAllowedToCreateDocuments:r}=Fe();if(!r)throw new Error("User is not allowed to move documents");if(We()){const o=window.ph?.legacyReactor;if(!o)throw new Error("Legacy reactor not initialized");const s=await o.getDrive(t);return await Ge(s,wh({srcFolder:e.id,targetParentFolder:n?.id}))}else{const o=window.ph?.reactorClient;if(!o)throw new Error("ReactorClient not initialized");const s=e.parentFolder??t,a=n?.id??t;return await o.moveChildren(s,a,[e.id])}}function rf(t,e,n=et()){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 Th(e.initialState,e.operations,r.reducer,void 0,Ii(n,e.header.documentType))}async function ua(t,e,n){const r=window.ph?.legacyReactor;if(!r)return;const{isAllowedToCreateDocuments:i}=Fe();if(!i)throw new Error("User is not allowed to copy documents");const o=await r.getDrive(t),s=fh({srcId:e.id,targetParentFolder:n?.id,targetName:e.name},()=>et(),o.state.global.nodes),a=new Map;for(const h of s){const f=o.state.global.nodes.find(l=>l.id===h.srcId);if(f){const l=ph({nodes:o.state.global.nodes,srcName:h.targetName||f.name,targetParentFolder:h.targetParentFolder||null});a.set(h.targetId,l)}}const c=s.filter(h=>{const f=o.state.global.nodes.find(l=>l.id===h.srcId);return f!==void 0&&lr(f)});for(const h of c)try{const f=await r.getDocument(h.srcId),l=rf(r,f,h.targetId),m=a.get(h.targetId);m&&(l.header.name=m),await r.addDocument(l)}catch(f){pe.error(`Error copying document ${h.srcId}: ${String(f)}`)}const u=s.map(h=>mh(h));return await Ge(o,u)}async function v1(t,e){const{isAllowedToCreateDocuments:n}=Fe();if(!n)throw new Error("User is not allowed to create drives");if(We()){const i=window.ph?.legacyReactor;if(!i)throw new Error("Legacy reactor not initialized");const o=et();return await i.addDrive({global:t.global,local:t.local,id:o},e)}else{const i=window.ph?.reactorClient;if(!i)throw new Error("ReactorClient not initialized");return et(),await i.createEmpty("powerhouse/document-drive")}}async function E1(t,e){if(We()){const r=window.ph?.legacyReactor;if(!r)throw new Error("Legacy reactor not initialized");return await r.addRemoteDrive(t,e)}else throw window.ph?.reactorClient?new Error("addRemoteDrive not yet implemented for ReactorClient"):new Error("ReactorClient not initialized")}async function D1(t){const{isAllowedToCreateDocuments:e}=Fe();if(!e)throw new Error("User is not allowed to delete drives");if(We()){const r=window.ph?.legacyReactor;if(!r)throw new Error("Legacy reactor not initialized");await r.deleteDrive(t)}else{const r=window.ph?.reactorClient;if(!r)throw new Error("ReactorClient not initialized");await r.deleteDocument(t)}}async function k1(t,e){const{isAllowedToCreateDocuments:n}=Fe();if(!n)throw new Error("User is not allowed to rename drives");if(We()){const i=window.ph?.legacyReactor;if(!i)throw new Error("Legacy reactor not initialized");const o=await i.getDrive(t);return await Ge(o,yh({name:e}))}else{const i=window.ph?.reactorClient;if(!i)throw new Error("ReactorClient not initialized");return await i.rename(t,e)}}async function S1(t,e){const{isAllowedToCreateDocuments:n}=Fe();if(!n)throw new Error("User is not allowed to change drive availability");if(We()){const i=window.ph?.legacyReactor;if(!i)throw new Error("Legacy reactor not initialized");const o=await i.getDrive(t);return await Ge(o,ca({availableOffline:e}))}else{const i=window.ph?.reactorClient;if(!i)throw new Error("ReactorClient not initialized");const{document:o}=await i.get(t);return await i.execute(t,"main",[ca({availableOffline:e})])}}async function C1(t,e){const{isAllowedToCreateDocuments:n}=Fe();if(!n)throw new Error("User is not allowed to change drive sharing type");if(We()){const i=window.ph?.legacyReactor;if(!i)throw new Error("Legacy reactor not initialized");const o=await i.getDrive(t);return await Ge(o,aa({type:e}))}else{const i=window.ph?.reactorClient;if(!i)throw new Error("ReactorClient not initialized");return await i.execute(t,"main",[aa({type:e})])}}async function A1(t,e){if(es())return;const r=window.ph?.legacyReactor;if(!r)throw new Error("Legacy reactor not initialized");const i=await r.getDrive(t);if((await Ge(i,gh({triggerId:e}))).state.local.triggers.find(a=>a.id===e))throw new Error(`There was an error removing trigger ${e}`)}async function O1(t,e,n){if(es())return;const i=window.ph?.legacyReactor;if(!i)throw new Error("Legacy reactor not initialized");const o=et(),s={driveId:t,listenerId:o,block:!1,filter:{branch:n.pullFilter?.branch??[],documentId:n.pullFilter?.documentId??[],documentType:n.pullFilter?.documentType??[],scope:n.pullFilter?.scope??[]},system:!1,label:`Pullresponder #${o}`,callInfo:{data:"",name:"PullResponder",transmitterType:"PullResponder"}},a=i.listeners;s.transmitter=new Nh(s,a);try{await a.setListener(t,s)}catch(c){throw new Error(`Listener couldn't be registered: ${c}`)}return{driveId:t,filter:s.filter,data:{interval:`${n.pullInterval}`||"1000",listenerId:o,url:e},id:o,type:"PullResponder"}}async function T1(t,e){if(es())return;const r=window.ph?.legacyReactor;if(!r)throw new Error("Legacy reactor not initialized");const i=await r.getDrive(t);if(!(await Ge(i,xh({trigger:e}))).state.local.triggers.find(a=>a.id===e.id))throw new Error(`There was an error adding the trigger ${e.id}`)}const of="powerhouse/generic-drive-explorer",R1="powerhouse/common",od=I("isExternalControlsEnabled"),sf=od.setValue,af=od.addEventHandler,ts=I("isDragAndDropEnabled"),cf=ts.setValue,I1=ts.useValue,df=ts.addEventHandler,ns=I("allowedDocumentTypes"),uf=ns.setValue;function lf(){return ns.useValue()}const hf=ns.addEventHandler,ff={allowedDocumentTypes:uf,isDragAndDropEnabled:cf},pf={isExternalControlsEnabled:sf},rs=I("vetraPackages"),is=rs.useValue,mf=rs.addEventHandler;function W1(t){rs.setValue(t);const e=t?.flatMap(n=>n.modules.documentModelModules).filter(n=>n!==void 0);window.ph?.legacyReactor?.setDocumentModelModules(e)}function sd(){return is()?.flatMap(e=>e.modules.documentModelModules||[])}function wf(t){return sd()?.find(n=>n.id===t)}function la(t){return t.toSorted((e,n)=>e.name.localeCompare(n.name))}function M1(t){return t?t.kind.toUpperCase()==="FILE":!1}function ad(t){return t?t.kind.toUpperCase()==="FOLDER":!1}function os(t){function e(n){_h(n,t).catch(pe.error)}return[t,e]}function ss(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function cd(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?ss(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function dd(t,e){e||(e=t.reduce((i,o)=>i+o.length,0));const n=cd(e);let r=0;for(const i of t)n.set(i,r),r+=i.length;return ss(n)}const bf=Object.freeze(Object.defineProperty({__proto__:null,concat:dd},Symbol.toStringTag,{value:"Module"}));function yf(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 o=t.charAt(i),s=o.charCodeAt(0);if(n[s]!==255)throw new TypeError(o+" is ambiguous");n[s]=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 w=0,v=0,b=0,g=p.length;b!==g&&p[b]===0;)b++,w++;for(var y=(g-b)*h+1>>>0,k=new Uint8Array(y);b!==g;){for(var x=p[b],N=0,C=y-1;(x!==0||N<v)&&C!==-1;C--,N++)x+=256*k[C]>>>0,k[C]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");v=N,b++}for(var S=y-v;S!==y&&k[S]===0;)S++;for(var A=c.repeat(w);S<y;++S)A+=t.charAt(k[S]);return A}function l(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var w=0;if(p[w]!==" "){for(var v=0,b=0;p[w]===c;)v++,w++;for(var g=(p.length-w)*u+1>>>0,y=new Uint8Array(g);p[w];){var k=n[p.charCodeAt(w)];if(k===255)return;for(var x=0,N=g-1;(k!==0||x<b)&&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");b=x,w++}if(p[w]!==" "){for(var C=g-b;C!==g&&y[C]===0;)C++;for(var S=new Uint8Array(v+(g-C)),A=v;C!==g;)S[A++]=y[C++];return S}}}function m(p){var w=l(p);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:l,decode:m}}var gf=yf,Nf=gf;const ud=new Uint8Array(0),xf=t=>t.reduce((e,n)=>e+n.toString(16).padStart(2,"0"),""),vf=t=>{const e=t.match(/../g);return e?new Uint8Array(e.map(n=>parseInt(n,16))):ud},ld=(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},fn=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")},Ef=t=>t instanceof ArrayBuffer||ArrayBuffer.isView(t),hd=t=>new TextEncoder().encode(t),fd=t=>new TextDecoder().decode(t),Df=Object.freeze(Object.defineProperty({__proto__:null,coerce:fn,empty:ud,equals:ld,fromHex:vf,fromString:hd,isBinary:Ef,toHex:xf,toString:fd},Symbol.toStringTag,{value:"Module"}));let kf=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")}},Sf=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 pd(this,e)}},Cf=class{constructor(e){this.decoders=e}or(e){return pd(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 pd=(t,e)=>new Cf({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});let Af=class{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new kf(e,n,r),this.decoder=new Sf(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const Li=({name:t,prefix:e,encode:n,decode:r})=>new Af(t,e,n,r),Ar=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=Nf(n,e);return Li({prefix:t,name:e,encode:r,decode:o=>fn(i(o))})},Of=(t,e,n,r)=>{const i={};for(let h=0;h<e.length;++h)i[e[h]]=h;let o=t.length;for(;t[o-1]==="=";)--o;const s=new Uint8Array(o*n/8|0);let a=0,c=0,u=0;for(let h=0;h<o;++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,s[u++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s},Tf=(t,e,n)=>{const r=e[e.length-1]==="=",i=(1<<n)-1;let o="",s=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],s+=8;s>n;)s-=n,o+=e[i&a>>s];if(s&&(o+=e[i&a<<n-s]),r)for(;o.length*n&7;)o+="=";return o},ge=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>Li({prefix:e,name:t,encode(i){return Tf(i,r,n)},decode(i){return Of(i,r,n,t)}}),Rf=Li({prefix:"\0",name:"identity",encode:t=>fd(t),decode:t=>hd(t)}),If=Object.freeze(Object.defineProperty({__proto__:null,identity:Rf},Symbol.toStringTag,{value:"Module"})),Wf=ge({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Mf=Object.freeze(Object.defineProperty({__proto__:null,base2:Wf},Symbol.toStringTag,{value:"Module"})),Lf=ge({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Pf=Object.freeze(Object.defineProperty({__proto__:null,base8:Lf},Symbol.toStringTag,{value:"Module"})),$f=Ar({prefix:"9",name:"base10",alphabet:"0123456789"}),Bf=Object.freeze(Object.defineProperty({__proto__:null,base10:$f},Symbol.toStringTag,{value:"Module"})),Uf=ge({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),qf=ge({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Ff=Object.freeze(Object.defineProperty({__proto__:null,base16:Uf,base16upper:qf},Symbol.toStringTag,{value:"Module"})),Yn=ge({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Vf=ge({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),_f=ge({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),jf=ge({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Hf=ge({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),zf=ge({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Kf=ge({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Jf=ge({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Gf=ge({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Zf=Object.freeze(Object.defineProperty({__proto__:null,base32:Yn,base32hex:Hf,base32hexpad:Kf,base32hexpadupper:Jf,base32hexupper:zf,base32pad:_f,base32padupper:jf,base32upper:Vf,base32z:Gf},Symbol.toStringTag,{value:"Module"})),Yf=Ar({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Qf=Ar({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Xf=Object.freeze(Object.defineProperty({__proto__:null,base36:Yf,base36upper:Qf},Symbol.toStringTag,{value:"Module"})),rt=Ar({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ep=Ar({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),tp=Object.freeze(Object.defineProperty({__proto__:null,base58btc:rt,base58flickr:ep},Symbol.toStringTag,{value:"Module"})),np=ge({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),rp=ge({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ip=ge({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),op=ge({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),sp=Object.freeze(Object.defineProperty({__proto__:null,base64:np,base64pad:rp,base64url:ip,base64urlpad:op},Symbol.toStringTag,{value:"Module"})),md=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),ap=md.reduce((t,e,n)=>(t[n]=e,t),[]),cp=md.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function dp(t){return t.reduce((e,n)=>(e+=ap[n],e),"")}function up(t){const e=[];for(const n of t){const r=cp[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const lp=Li({prefix:"🚀",name:"base256emoji",encode:dp,decode:up}),hp=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:lp},Symbol.toStringTag,{value:"Module"}));var fp=wd,ha=128,pp=-128,mp=Math.pow(2,31);function wd(t,e,n){e=e||[],n=n||0;for(var r=n;t>=mp;)e[n++]=t&255|ha,t/=128;for(;t&pp;)e[n++]=t&255|ha,t>>>=7;return e[n]=t|0,wd.bytes=n-r+1,e}var wp=Mo,bp=128,fa=127;function Mo(t,r){var n=0,r=r||0,i=0,o=r,s,a=t.length;do{if(o>=a)throw Mo.bytes=0,new RangeError("Could not decode varint");s=t[o++],n+=i<28?(s&fa)<<i:(s&fa)*Math.pow(2,i),i+=7}while(s>=bp);return Mo.bytes=o-r,n}var yp=Math.pow(2,7),gp=Math.pow(2,14),Np=Math.pow(2,21),xp=Math.pow(2,28),vp=Math.pow(2,35),Ep=Math.pow(2,42),Dp=Math.pow(2,49),kp=Math.pow(2,56),Sp=Math.pow(2,63),Cp=function(t){return t<yp?1:t<gp?2:t<Np?3:t<xp?4:t<vp?5:t<Ep?6:t<Dp?7:t<kp?8:t<Sp?9:10},Ap={encode:fp,decode:wp,encodingLength:Cp},ui=Ap;const hr=(t,e=0)=>[ui.decode(t,e),ui.decode.bytes],fr=(t,e,n=0)=>(ui.encode(t,e,n),e),pr=t=>ui.encodingLength(t),Op=Object.freeze(Object.defineProperty({__proto__:null,decode:hr,encodeTo:fr,encodingLength:pr},Symbol.toStringTag,{value:"Module"})),mr=(t,e)=>{const n=e.byteLength,r=pr(t),i=r+pr(n),o=new Uint8Array(i+n);return fr(t,o,0),fr(n,o,r),o.set(e,i),new Pi(t,n,e,o)},bd=t=>{const e=fn(t),[n,r]=hr(e),[i,o]=hr(e.subarray(r)),s=e.subarray(r+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new Pi(n,i,s,e)},yd=(t,e)=>t===e?!0:t.code===e.code&&t.size===e.size&&ld(t.bytes,e.bytes);class Pi{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const Tp=Object.freeze(Object.defineProperty({__proto__:null,Digest:Pi,create:mr,decode:bd,equals:yd},Symbol.toStringTag,{value:"Module"})),as=({name:t,code:e,encode:n})=>new gd(t,e,n);class gd{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?mr(this.code,n):n.then(r=>mr(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Rp=Object.freeze(Object.defineProperty({__proto__:null,Hasher:gd,from:as},Symbol.toStringTag,{value:"Module"})),Nd=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Ip=as({name:"sha2-256",code:18,encode:Nd("SHA-256")}),Wp=as({name:"sha2-512",code:19,encode:Nd("SHA-512")}),Mp=Object.freeze(Object.defineProperty({__proto__:null,sha256:Ip,sha512:Wp},Symbol.toStringTag,{value:"Module"})),xd=0,Lp="identity",vd=fn,Pp=t=>mr(xd,vd(t)),$p={code:xd,name:Lp,encode:vd,digest:Pp},Bp=Object.freeze(Object.defineProperty({__proto__:null,identity:$p},Symbol.toStringTag,{value:"Module"})),Up="raw",qp=85,Fp=t=>fn(t),Vp=t=>fn(t),_p=Object.freeze(Object.defineProperty({__proto__:null,code:qp,decode:Vp,encode:Fp,name:Up},Symbol.toStringTag,{value:"Module"})),jp=new TextEncoder,Hp=new TextDecoder,zp="json",Kp=512,Jp=t=>jp.encode(JSON.stringify(t)),Gp=t=>JSON.parse(Hp.decode(t)),Zp=Object.freeze(Object.defineProperty({__proto__:null,code:Kp,decode:Gp,encode:Jp,name:zp},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:Fr,byteLength:Fr,code:qr,version:qr,multihash:qr,bytes:qr,_baseCache:Fr,asCID:Fr})}toV0(){switch(this.version){case 0:return this;default:{const{code:e,multihash:n}=this;if(e!==_n)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(n.code!==em)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=mr(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&&yd(this.multihash,e.multihash)}toString(e){const{bytes:n,version:r,_baseCache:i}=this;switch(r){case 0:return Qp(n,i,e||rt.encoder);default:return Xp(n,i,e||Yn.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 nm(/^0\.0/,rm),!!(e&&(e[ma]||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:o}=e;return new De(n,r,i,o||pa(n,r,i.bytes))}else if(e!=null&&e[ma]===!0){const{version:n,multihash:r,code:i}=e,o=bd(r);return De.create(n,i,o)}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!==_n)throw new Error(`Version 0 CID must use dag-pb (code: ${_n}) block encoding`);return new De(e,n,r,r.bytes)}case 1:{const i=pa(e,n,r.bytes);return new De(e,n,r,i)}default:throw new Error("Invalid version")}}static createV0(e){return De.create(0,_n,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=fn(e.subarray(r,r+n.multihashSize));if(i.byteLength!==n.multihashSize)throw new Error("Incorrect length");const o=i.subarray(n.multihashSize-n.digestSize),s=new Pi(n.multihashCode,n.digestSize,o,i);return[n.version===0?De.createV0(s):De.createV1(n.codec,s),e.subarray(n.size)]}static inspectBytes(e){let n=0;const r=()=>{const[f,l]=hr(e.subarray(n));return n+=l,f};let i=r(),o=_n;if(i===18?(i=0,n=0):i===1&&(o=r()),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);const s=n,a=r(),c=r(),u=n+c,h=u-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:h,size:u}}static parse(e,n){const[r,i]=Yp(e,n),o=De.decode(i);return o._baseCache.set(r,e),o}}const Yp=(t,e)=>{switch(t[0]){case"Q":{const n=e||rt;return[rt.prefix,n.decode(`${rt.prefix}${t}`)]}case rt.prefix:{const n=e||rt;return[rt.prefix,n.decode(t)]}case Yn.prefix:{const n=e||Yn;return[Yn.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)]}}},Qp=(t,e,n)=>{const{prefix:r}=n;if(r!==rt.prefix)throw Error(`Cannot string encode V0 in ${n.name} encoding`);const i=e.get(r);if(i==null){const o=n.encode(t).slice(1);return e.set(r,o),o}else return i},Xp=(t,e,n)=>{const{prefix:r}=n,i=e.get(r);if(i==null){const o=n.encode(t);return e.set(r,o),o}else return i},_n=112,em=18,pa=(t,e,n)=>{const r=pr(t),i=r+pr(e),o=new Uint8Array(i+n.byteLength);return fr(t,o,0),fr(e,o,r),o.set(n,i),o},ma=Symbol.for("@ipld/js-cid/CID"),qr={writable:!1,configurable:!1,enumerable:!0},Fr={writable:!1,enumerable:!1,configurable:!1},tm="0.0.0-dev",nm=(t,e)=>{if(t.test(tm))console.warn(e);else throw new Error(e)},rm=`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
+ `,Lo={...If,...Mf,...Pf,...Bf,...Ff,...Zf,...Xf,...tp,...sp,...hp},im={...Mp,...Bp},om={raw:_p,json:Zp},sm=Object.freeze(Object.defineProperty({__proto__:null,CID:De,bases:Lo,bytes:Df,codecs:om,digest:Tp,hasher:Rp,hashes:im,varint:Op},Symbol.toStringTag,{value:"Module"}));function Ed(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const wa=Ed("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Zi=Ed("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=cd(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),Dd={utf8:wa,"utf-8":wa,hex:Lo.base16,latin1:Zi,ascii:Zi,binary:Zi,...Lo};function $i(t,e="utf8"){const n=Dd[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?ss(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}const am=Object.freeze(Object.defineProperty({__proto__:null,fromString:$i},Symbol.toStringTag,{value:"Module"}));function cs(t,e="utf8"){const n=Dd[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 cm=Object.freeze(Object.defineProperty({__proto__:null,toString:cs},Symbol.toStringTag,{value:"Module"})),wn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Or(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function wr(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Et(t,...e){if(!Or(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 kd(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");wr(t.outputLen),wr(t.blockLen)}function Wn(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 Sd(t,e){Et(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function dm(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function at(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Yi(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function tt(t,e){return t<<32-e|t>>>e}function Vr(t,e){return t<<e|t>>>32-e>>>0}const um=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function lm(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function hm(t){for(let e=0;e<t.length;e++)t[e]=lm(t[e]);return t}const ba=um?t=>t:hm,Cd=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",fm=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function sn(t){if(Et(t),Cd)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=fm[t[n]];return e}const lt={_0:48,_9:57,A:65,F:70,a:97,f:102};function ya(t){if(t>=lt._0&&t<=lt._9)return t-lt._0;if(t>=lt.A&&t<=lt.F)return t-(lt.A-10);if(t>=lt.a&&t<=lt.f)return t-(lt.a-10)}function br(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Cd)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,o=0;i<n;i++,o+=2){const s=ya(t.charCodeAt(o)),a=ya(t.charCodeAt(o+1));if(s===void 0||a===void 0){const c=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}r[i]=s*16+a}return r}function pm(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Bi(t){return typeof t=="string"&&(t=pm(t)),Et(t),t}function it(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Et(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const o=t[r];n.set(o,i),i+=o.length}return n}class ds{}function Tr(t){const e=r=>t().update(Bi(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function us(t=32){if(wn&&typeof wn.getRandomValues=="function")return wn.getRandomValues(new Uint8Array(t));if(wn&&typeof wn.randomBytes=="function")return Uint8Array.from(wn.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function mm(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),o=BigInt(4294967295),s=Number(n>>i&o),a=Number(n&o),c=r?4:0,u=r?0:4;t.setUint32(e+c,s,r),t.setUint32(e+u,a,r)}function wm(t,e,n){return t&e^~t&n}function bm(t,e,n){return t&e^t&n^e&n}class ls extends ds{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=Yi(this.buffer)}update(e){Wn(this),e=Bi(e),Et(e);const{view:n,buffer:r,blockLen:i}=this,o=e.length;for(let s=0;s<o;){const a=Math.min(i-this.pos,o-s);if(a===i){const c=Yi(e);for(;i<=o-s;s+=i)this.process(c,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Wn(this),Sd(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:o}=this;let{pos:s}=this;n[s++]=128,at(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(r,0),s=0);for(let f=s;f<i;f++)n[f]=0;mm(r,i-8,BigInt(this.length*8),o),this.process(r,0);const a=Yi(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],o)}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:o,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=o,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]),_r=BigInt(2**32-1),ga=BigInt(32);function ym(t,e=!1){return e?{h:Number(t&_r),l:Number(t>>ga&_r)}:{h:Number(t>>ga&_r)|0,l:Number(t&_r)|0}}function Ad(t,e=!1){const n=t.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let o=0;o<n;o++){const{h:s,l:a}=ym(t[o],e);[r[o],i[o]]=[s,a]}return[r,i]}const Na=(t,e,n)=>t>>>n,xa=(t,e,n)=>t<<32-n|e>>>n,bn=(t,e,n)=>t>>>n|e<<32-n,yn=(t,e,n)=>t<<32-n|e>>>n,jr=(t,e,n)=>t<<64-n|e>>>n-32,Hr=(t,e,n)=>t>>>n-32|e<<64-n,gm=(t,e,n)=>t<<n|e>>>32-n,Nm=(t,e,n)=>e<<n|t>>>32-n,xm=(t,e,n)=>e<<n-32|t>>>64-n,vm=(t,e,n)=>t<<n-32|e>>>64-n;function ht(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:i|0}}const Em=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Dm=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,km=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Sm=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,Cm=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),Am=(t,e,n,r,i,o)=>e+n+r+i+o+(t/2**32|0)|0,Om=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 Tm extends ls{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:o,F:s,G:a,H:c}=this;return[e,n,r,i,o,s,a,c]}set(e,n,r,i,o,s,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=o|0,this.F=s|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=tt(l,7)^tt(l,18)^l>>>3,w=tt(m,17)^tt(m,19)^m>>>10;Ot[f]=w+Ot[f-7]+p+Ot[f-16]|0}let{A:r,B:i,C:o,D:s,E:a,F:c,G:u,H:h}=this;for(let f=0;f<64;f++){const l=tt(a,6)^tt(a,11)^tt(a,25),m=h+l+wm(a,c,u)+Om[f]+Ot[f]|0,w=(tt(r,2)^tt(r,13)^tt(r,22))+bm(r,i,o)|0;h=u,u=c,c=a,a=s+m|0,s=o,o=i,i=r,r=m+w|0}r=r+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+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,o,s,a,c,u,h)}roundClean(){at(Ot)}destroy(){this.set(0,0,0,0,0,0,0,0),at(this.buffer)}}const Od=Ad(["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))),Rm=Od[0],Im=Od[1],Tt=new Uint32Array(80),Rt=new Uint32Array(80);class Td extends ls{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:o,Cl:s,Dh:a,Dl:c,Eh:u,El:h,Fh:f,Fl:l,Gh:m,Gl:p,Hh:w,Hl:v}=this;return[e,n,r,i,o,s,a,c,u,h,f,l,m,p,w,v]}set(e,n,r,i,o,s,a,c,u,h,f,l,m,p,w,v){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=i|0,this.Ch=o|0,this.Cl=s|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=w|0,this.Hl=v|0}process(e,n){for(let y=0;y<16;y++,n+=4)Tt[y]=e.getUint32(n),Rt[y]=e.getUint32(n+=4);for(let y=16;y<80;y++){const k=Tt[y-15]|0,x=Rt[y-15]|0,N=bn(k,x,1)^bn(k,x,8)^Na(k,x,7),C=yn(k,x,1)^yn(k,x,8)^xa(k,x,7),S=Tt[y-2]|0,A=Rt[y-2]|0,P=bn(S,A,19)^jr(S,A,61)^Na(S,A,6),q=yn(S,A,19)^Hr(S,A,61)^xa(S,A,6),$=km(C,q,Rt[y-7],Rt[y-16]),O=Sm($,N,P,Tt[y-7],Tt[y-16]);Tt[y]=O|0,Rt[y]=$|0}let{Ah:r,Al:i,Bh:o,Bl:s,Ch:a,Cl:c,Dh:u,Dl:h,Eh:f,El:l,Fh:m,Fl:p,Gh:w,Gl:v,Hh:b,Hl:g}=this;for(let y=0;y<80;y++){const k=bn(f,l,14)^bn(f,l,18)^jr(f,l,41),x=yn(f,l,14)^yn(f,l,18)^Hr(f,l,41),N=f&m^~f&w,C=l&p^~l&v,S=Cm(g,x,C,Im[y],Rt[y]),A=Am(S,b,k,N,Rm[y],Tt[y]),P=S|0,q=bn(r,i,28)^jr(r,i,34)^jr(r,i,39),$=yn(r,i,28)^Hr(r,i,34)^Hr(r,i,39),O=r&o^r&a^o&a,E=i&s^i&c^s&c;b=w|0,g=v|0,w=m|0,v=p|0,m=f|0,p=l|0,{h:f,l}=ht(u|0,h|0,A|0,P|0),u=a|0,h=c|0,a=o|0,c=s|0,o=r|0,s=i|0;const D=Em(P,$,E);r=Dm(D,A,q,O),i=D|0}({h:r,l:i}=ht(this.Ah|0,this.Al|0,r|0,i|0)),{h:o,l:s}=ht(this.Bh|0,this.Bl|0,o|0,s|0),{h:a,l:c}=ht(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:h}=ht(this.Dh|0,this.Dl|0,u|0,h|0),{h:f,l}=ht(this.Eh|0,this.El|0,f|0,l|0),{h:m,l:p}=ht(this.Fh|0,this.Fl|0,m|0,p|0),{h:w,l:v}=ht(this.Gh|0,this.Gl|0,w|0,v|0),{h:b,l:g}=ht(this.Hh|0,this.Hl|0,b|0,g|0),this.set(r,i,o,s,a,c,u,h,f,l,m,p,w,v,b,g)}roundClean(){at(Tt,Rt)}destroy(){at(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class Wm extends Td{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 hs=Tr(()=>new Tm),Rd=Tr(()=>new Td),Mm=Tr(()=>new Wm);const fs=BigInt(0),Po=BigInt(1);function dn(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function Xe(t,e,n=""){const r=Or(t),i=t?.length,o=e!==void 0;if(!r||o&&i!==e){const s=n&&`"${n}" `,a=o?` of length ${e}`:"",c=r?`length=${i}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return t}function Gn(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Id(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?fs:BigInt("0x"+t)}function Ui(t){return Id(sn(t))}function yr(t){return Et(t),Id(sn(Uint8Array.from(t).reverse()))}function ps(t,e){return br(t.toString(16).padStart(e*2,"0"))}function Wd(t,e){return ps(t,e).reverse()}function Lm(t){return br(Gn(t))}function re(t,e,n){let r;if(typeof e=="string")try{r=br(e)}catch(o){throw new Error(t+" must be hex string or Uint8Array, cause: "+o)}else if(Or(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 va(t){return Uint8Array.from(t)}const Qi=t=>typeof t=="bigint"&&fs<=t;function Pm(t,e,n){return Qi(t)&&Qi(e)&&Qi(n)&&e<=t&&t<n}function $o(t,e,n,r){if(!Pm(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Md(t){let e;for(e=0;t>fs;t>>=Po,e+=1);return e}const Rr=t=>(Po<<BigInt(t))-Po;function $m(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 o=r(t),s=r(t),a=0;const c=()=>{o.fill(1),s.fill(0),a=0},u=(...m)=>n(s,o,...m),h=(m=r(0))=>{s=u(i(0),m),o=u(),m.length!==0&&(s=u(i(1),m),o=u())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let m=0;const p=[];for(;m<e;){o=u();const w=o.slice();p.push(w),m+=o.length}return it(...p)};return(m,p)=>{c(),h(m);let w;for(;!(w=p(f()));)h();return c(),w}}function Ir(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(i,o,s){const a=t[i];if(s&&a===void 0)return;const c=typeof a;if(c!==o||a===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${c}`)}Object.entries(e).forEach(([i,o])=>r(i,o,!1)),Object.entries(n).forEach(([i,o])=>r(i,o,!0))}function li(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(i!==void 0)return i;const o=t(n,...r);return e.set(n,o),o}}const Ie=BigInt(0),be=BigInt(1),Xt=BigInt(2),Ld=BigInt(3),Pd=BigInt(4),$d=BigInt(5),Bm=BigInt(7),Bd=BigInt(8),Um=BigInt(9),Ud=BigInt(16);function le(t,e){const n=t%e;return n>=Ie?n:e+n}function ae(t,e,n){let r=t;for(;e-- >Ie;)r*=r,r%=n;return r}function Ea(t,e){if(t===Ie)throw new Error("invert: expected non-zero number");if(e<=Ie)throw new Error("invert: expected positive modulus, got "+e);let n=le(t,e),r=e,i=Ie,o=be;for(;n!==Ie;){const a=r/n,c=r%n,u=i-o*a;r=n,n=c,i=o,o=u}if(r!==be)throw new Error("invert: does not exist");return le(i,e)}function ms(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function qd(t,e){const n=(t.ORDER+be)/Pd,r=t.pow(e,n);return ms(t,r,e),r}function qm(t,e){const n=(t.ORDER-$d)/Bd,r=t.mul(e,Xt),i=t.pow(r,n),o=t.mul(e,i),s=t.mul(t.mul(o,Xt),i),a=t.mul(o,t.sub(s,t.ONE));return ms(t,a,e),a}function Fm(t){const e=ut(t),n=Fd(t),r=n(e,e.neg(e.ONE)),i=n(e,r),o=n(e,e.neg(r)),s=(t+Bm)/Ud;return(a,c)=>{let u=a.pow(c,s),h=a.mul(u,r);const f=a.mul(u,i),l=a.mul(u,o),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 w=a.eql(a.sqr(h),c),v=a.cmov(u,h,w);return ms(a,v,c),v}}function Fd(t){if(t<Ld)throw new Error("sqrt is not defined for small field");let e=t-be,n=0;for(;e%Xt===Ie;)e/=Xt,n++;let r=Xt;const i=ut(t);for(;Da(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return qd;let o=i.pow(r,e);const s=(e+be)/Xt;return function(c,u){if(c.is0(u))return u;if(Da(c,u)!==1)throw new Error("Cannot find square root");let h=n,f=c.mul(c.ONE,o),l=c.pow(u,e),m=c.pow(u,s);for(;!c.eql(l,c.ONE);){if(c.is0(l))return c.ZERO;let p=1,w=c.sqr(l);for(;!c.eql(w,c.ONE);)if(p++,w=c.sqr(w),p===h)throw new Error("Cannot find square root");const v=be<<BigInt(h-p-1),b=c.pow(f,v);h=p,f=c.sqr(b),l=c.mul(l,f),m=c.mul(m,b)}return m}}function Vm(t){return t%Pd===Ld?qd:t%Bd===$d?qm:t%Ud===Um?Fm(t):Fd(t)}const _m=(t,e)=>(le(t,e)&be)===be,jm=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Hm(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=jm.reduce((r,i)=>(r[i]="function",r),e);return Ir(t,n),t}function zm(t,e,n){if(n<Ie)throw new Error("invalid exponent, negatives unsupported");if(n===Ie)return t.ONE;if(n===be)return e;let r=t.ONE,i=e;for(;n>Ie;)n&be&&(r=t.mul(r,i)),i=t.sqr(i),n>>=be;return r}function Vd(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),i=e.reduce((s,a,c)=>t.is0(a)?s:(r[c]=s,t.mul(s,a)),t.ONE),o=t.inv(i);return e.reduceRight((s,a,c)=>t.is0(a)?s:(r[c]=t.mul(s,r[c]),t.mul(s,a)),o),r}function Da(t,e){const n=(t.ORDER-be)/Xt,r=t.pow(e,n),i=t.eql(r,t.ONE),o=t.eql(r,t.ZERO),s=t.eql(r,t.neg(t.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function _d(t,e){e!==void 0&&wr(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function ut(t,e,n=!1,r={}){if(t<=Ie)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,o,s=!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&&(o=l.sqrt),typeof l.isLE=="boolean"&&(n=l.isLE),typeof l.modFromBytes=="boolean"&&(s=l.modFromBytes),a=l.allowedLengths}else typeof e=="number"&&(i=e),r.sqrt&&(o=r.sqrt);const{nBitLength:c,nByteLength:u}=_d(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:Rr(c),ZERO:Ie,ONE:be,allowedLengths:a,create:l=>le(l,t),isValid:l=>{if(typeof l!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof l);return Ie<=l&&l<t},is0:l=>l===Ie,isValidNot0:l=>!f.is0(l)&&f.isValid(l),isOdd:l=>(l&be)===be,neg:l=>le(-l,t),eql:(l,m)=>l===m,sqr:l=>le(l*l,t),add:(l,m)=>le(l+m,t),sub:(l,m)=>le(l-m,t),mul:(l,m)=>le(l*m,t),pow:(l,m)=>zm(f,l,m),div:(l,m)=>le(l*Ea(m,t),t),sqrN:l=>l*l,addN:(l,m)=>l+m,subN:(l,m)=>l-m,mulN:(l,m)=>l*m,inv:l=>Ea(l,t),sqrt:o||(l=>(h||(h=Vm(t)),h(f,l))),toBytes:l=>n?Wd(l,u):ps(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 w=new Uint8Array(u);w.set(l,n?0:w.length-l.length),l=w}if(l.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+l.length);let p=n?yr(l):Ui(l);if(s&&(p=le(p,t)),!m&&!f.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:l=>Vd(f,l),cmov:(l,m,p)=>p?m:l});return Object.freeze(f)}function jd(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 Hd(t){const e=jd(t);return e+Math.ceil(e/2)}function Km(t,e,n=!1){const r=t.length,i=jd(e),o=Hd(e);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);const s=n?yr(t):Ui(t),a=le(s,e-be)+be;return n?Wd(a,i):ps(a,i)}const Mn=BigInt(0),en=BigInt(1);function hi(t,e){const n=e.negate();return t?n:e}function tn(t,e){const n=Vd(t.Fp,e.map(r=>r.Z));return e.map((r,i)=>t.fromAffine(r.toAffine(n[i])))}function zd(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Xi(t,e){zd(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),i=2**t,o=Rr(t),s=BigInt(t);return{windows:n,windowSize:r,mask:o,maxNumber:i,shiftBy:s}}function ka(t,e,n){const{windowSize:r,mask:i,maxNumber:o,shiftBy:s}=n;let a=Number(t&i),c=t>>s;a>r&&(a-=o,c+=en);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 Jm(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 Gm(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 eo=new WeakMap,Kd=new WeakMap;function to(t){return Kd.get(t)||1}function Sa(t){if(t!==Mn)throw new Error("invalid wNAF")}class Jd{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>Mn;)n&en&&(r=r.add(i)),i=i.double(),n>>=en;return r}precomputeWindow(e,n){const{windows:r,windowSize:i}=Xi(n,this.bits),o=[];let s=e,a=s;for(let c=0;c<r;c++){a=s,o.push(a);for(let u=1;u<i;u++)a=a.add(s),o.push(a);s=a.double()}return o}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let i=this.ZERO,o=this.BASE;const s=Xi(e,this.bits);for(let a=0;a<s.windows;a++){const{nextN:c,offset:u,isZero:h,isNeg:f,isNegF:l,offsetF:m}=ka(r,a,s);r=c,h?o=o.add(hi(l,n[m])):i=i.add(hi(f,n[u]))}return Sa(r),{p:i,f:o}}wNAFUnsafe(e,n,r,i=this.ZERO){const o=Xi(e,this.bits);for(let s=0;s<o.windows&&r!==Mn;s++){const{nextN:a,offset:c,isZero:u,isNeg:h}=ka(r,s,o);if(r=a,!u){const f=n[c];i=i.add(h?f.negate():f)}}return Sa(r),i}getPrecomputes(e,n,r){let i=eo.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(i=r(i)),eo.set(n,i))),i}cached(e,n,r){const i=to(e);return this.wNAF(i,this.getPrecomputes(i,e,r),n)}unsafe(e,n,r,i){const o=to(e);return o===1?this._unsafeLadder(e,n,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),n,i)}createCache(e,n){zd(n,this.bits),Kd.set(e,n),eo.delete(e)}hasCache(e){return to(e)!==1}}function Zm(t,e,n,r){let i=e,o=t.ZERO,s=t.ZERO;for(;n>Mn||r>Mn;)n&en&&(o=o.add(i)),r&en&&(s=s.add(i)),i=i.double(),n>>=en,r>>=en;return{p1:o,p2:s}}function Gd(t,e,n,r){Jm(n,t),Gm(r,e);const i=n.length,o=r.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");const s=t.ZERO,a=Md(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=Rr(c),h=new Array(Number(u)+1).fill(s),f=Math.floor((e.BITS-1)/c)*c;let l=s;for(let m=f;m>=0;m-=c){h.fill(s);for(let w=0;w<o;w++){const v=r[w],b=Number(v>>BigInt(m)&u);h[b]=h[b].add(n[w])}let p=s;for(let w=h.length-1,v=s;w>0;w--)v=v.add(h[w]),p=p.add(v);if(l=l.add(p),m!==0)for(let w=0;w<c;w++)l=l.double()}return l}function Ca(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Hm(e),e}else return ut(t,{isLE:n})}function Zd(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>Mn))throw new Error(`CURVE.${c} must be positive bigint`)}const i=Ca(e.p,n.Fp,r),o=Ca(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:o}}const It=BigInt(0),me=BigInt(1),no=BigInt(2),Ym=BigInt(8);function Qm(t,e,n,r){const i=t.sqr(n),o=t.sqr(r),s=t.add(t.mul(e.a,i),o),a=t.add(t.ONE,t.mul(e.d,t.mul(i,o)));return t.eql(s,a)}function Xm(t,e={}){const n=Zd("edwards",t,e,e.FpFnLE),{Fp:r,Fn:i}=n;let o=n.CURVE;const{h:s}=o;Ir(e,{},{uvRatio:"function"});const a=no<<BigInt(i.BYTES*8)-me,c=v=>r.create(v),u=e.uvRatio||((v,b)=>{try{return{isValid:!0,value:r.sqrt(r.div(v,b))}}catch{return{isValid:!1,value:It}}});if(!Qm(r,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function h(v,b,g=!1){const y=g?me:It;return $o("coordinate "+v,b,y,a),b}function f(v){if(!(v instanceof p))throw new Error("ExtendedPoint expected")}const l=li((v,b)=>{const{X:g,Y:y,Z:k}=v,x=v.is0();b==null&&(b=x?Ym:r.inv(k));const N=c(g*b),C=c(y*b),S=r.mul(k,b);if(x)return{x:It,y:me};if(S!==me)throw new Error("invZ was invalid");return{x:N,y:C}}),m=li(v=>{const{a:b,d:g}=o;if(v.is0())throw new Error("bad point: ZERO");const{X:y,Y:k,Z:x,T:N}=v,C=c(y*y),S=c(k*k),A=c(x*x),P=c(A*A),q=c(C*b),$=c(A*c(q+S)),O=c(P+c(g*c(C*S)));if($!==O)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(b,g,y,k){this.X=h("x",b),this.Y=h("y",g),this.Z=h("z",y,!0),this.T=h("t",k),Object.freeze(this)}static CURVE(){return o}static fromAffine(b){if(b instanceof p)throw new Error("extended point not allowed");const{x:g,y}=b||{};return h("x",g),h("y",y),new p(g,y,me,c(g*y))}static fromBytes(b,g=!1){const y=r.BYTES,{a:k,d:x}=o;b=va(Xe(b,y,"point")),dn(g,"zip215");const N=va(b),C=b[y-1];N[y-1]=C&-129;const S=yr(N),A=g?a:r.ORDER;$o("point.y",S,It,A);const P=c(S*S),q=c(P-me),$=c(x*P-k);let{isValid:O,value:E}=u(q,$);if(!O)throw new Error("bad point: invalid y coordinate");const D=(E&me)===me,T=(C&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(b,g=!1){return p.fromBytes(re("point",b),g)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,g=!0){return w.createCache(this,b),g||this.multiply(no),this}assertValidity(){m(this)}equals(b){f(b);const{X:g,Y:y,Z:k}=this,{X:x,Y:N,Z:C}=b,S=c(g*C),A=c(x*k),P=c(y*C),q=c(N*k);return S===A&&P===q}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:b}=o,{X:g,Y:y,Z:k}=this,x=c(g*g),N=c(y*y),C=c(no*c(k*k)),S=c(b*x),A=g+y,P=c(c(A*A)-x-N),q=S+N,$=q-C,O=S-N,E=c(P*$),D=c(q*O),T=c(P*O),W=c($*q);return new p(E,D,W,T)}add(b){f(b);const{a:g,d:y}=o,{X:k,Y:x,Z:N,T:C}=this,{X:S,Y:A,Z:P,T:q}=b,$=c(k*S),O=c(x*A),E=c(C*y*q),D=c(N*P),T=c((k+x)*(S+A)-$-O),W=D-E,B=D+E,M=c(O-g*$),L=c(T*W),U=c(B*M),V=c(T*M),ie=c(W*B);return new p(L,U,ie,V)}subtract(b){return this.add(b.negate())}multiply(b){if(!i.isValidNot0(b))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:g,f:y}=w.cached(this,b,k=>tn(p,k));return tn(p,[g,y])[0]}multiplyUnsafe(b,g=p.ZERO){if(!i.isValid(b))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return b===It?p.ZERO:this.is0()||b===me?this:w.unsafe(this,b,y=>tn(p,y),g)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return w.unsafe(this,o.n).is0()}toAffine(b){return l(this,b)}clearCofactor(){return s===me?this:this.multiplyUnsafe(s)}toBytes(){const{x:b,y:g}=this.toAffine(),y=r.toBytes(g);return y[y.length-1]|=b&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(b){return tn(p,b)}static msm(b,g){return Gd(p,i,b,g)}_setWindowSize(b){this.precompute(b)}toRawBytes(){return this.toBytes()}}p.BASE=new p(o.Gx,o.Gy,me,c(o.Gx*o.Gy)),p.ZERO=new p(It,me,me,It),p.Fp=r,p.Fn=i;const w=new Jd(p,i.BITS);return p.BASE.precompute(8),p}function ew(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is required');Ir(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:i,Fp:o,Fn:s}=t,a=n.randomBytes||us,c=n.adjustScalarBytes||(A=>A),u=n.domain||((A,P,q)=>{if(dn(q,"phflag"),P.length||q)throw new Error("Contexts/pre-hash are not supported");return A});function h(A){return s.create(yr(A))}function f(A){const P=y.secretKey;A=re("private key",A,P);const q=re("hashed private key",e(A),2*P),$=c(q.slice(0,P)),O=q.slice(P,2*P),E=h($);return{head:$,prefix:O,scalar:E}}function l(A){const{head:P,prefix:q,scalar:$}=f(A),O=i.multiply($),E=O.toBytes();return{head:P,prefix:q,scalar:$,point:O,pointBytes:E}}function m(A){return l(A).pointBytes}function p(A=Uint8Array.of(),...P){const q=it(...P);return h(e(u(q,re("context",A),!!r)))}function w(A,P,q={}){A=re("message",A),r&&(A=r(A));const{prefix:$,scalar:O,pointBytes:E}=l(P),D=p(q.context,$,A),T=i.multiply(D).toBytes(),W=p(q.context,T,E,A),B=s.create(D+W*O);if(!s.isValid(B))throw new Error("sign failed: invalid s");const M=it(T,s.toBytes(B));return Xe(M,y.signature,"result")}const v={zip215:!0};function b(A,P,q,$=v){const{context:O,zip215:E}=$,D=y.signature;A=re("signature",A,D),P=re("message",P),q=re("publicKey",q,y.publicKey),E!==void 0&&dn(E,"zip215"),r&&(P=r(P));const T=D/2,W=A.subarray(0,T),B=yr(A.subarray(T,D));let M,L,U;try{M=t.fromBytes(q,E),L=t.fromBytes(W,E),U=i.multiplyUnsafe(B)}catch{return!1}if(!E&&M.isSmallOrder())return!1;const V=p(O,L.toBytes(),M.toBytes(),P);return L.add(M.multiplyUnsafe(V)).subtract(U).clearCofactor().is0()}const g=o.BYTES,y={secretKey:g,publicKey:g,signature:2*g,seed:g};function k(A=a(y.seed)){return Xe(A,y.seed,"seed")}function x(A){const P=S.randomSecretKey(A);return{secretKey:P,publicKey:m(P)}}function N(A){return Or(A)&&A.length===s.BYTES}function C(A,P){try{return!!t.fromBytes(A,P)}catch{return!1}}const S={getExtendedPublicKey:l,randomSecretKey:k,isValidSecretKey:N,isValidPublicKey:C,toMontgomery(A){const{y:P}=t.fromBytes(A),q=y.publicKey,$=q===32;if(!$&&q!==57)throw new Error("only defined for 25519 and 448");const O=$?o.div(me+P,me-P):o.div(P-me,P+me);return o.toBytes(O)},toMontgomerySecret(A){const P=y.secretKey;Xe(A,P);const q=e(A.subarray(0,P));return c(q).subarray(0,P)},randomPrivateKey:k,precompute(A=8,P=t.BASE){return P.precompute(A,!1)}};return Object.freeze({keygen:x,getPublicKey:m,sign:w,verify:b,utils:S,Point:t,lengths:y})}function tw(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=ut(e.n,t.nBitLength,!0),i={Fp:n,Fn:r,uvRatio:t.uvRatio},o={randomBytes:t.randomBytes,adjustScalarBytes:t.adjustScalarBytes,domain:t.domain,prehash:t.prehash,mapToCurve:t.mapToCurve};return{CURVE:e,curveOpts:i,hash:t.hash,eddsaOpts:o}}function nw(t,e){const n=e.Point;return Object.assign({},e,{ExtendedPoint:n,CURVE:t,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function rw(t){const{CURVE:e,curveOpts:n,hash:r,eddsaOpts:i}=tw(t),o=Xm(e,n),s=ew(o,r,i);return nw(t,s)}const iw=BigInt(1),Aa=BigInt(2);BigInt(3);const ow=BigInt(5),sw=BigInt(8),ws=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Yd={p:ws,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:sw,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function aw(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),o=ws,a=t*t%o*t%o,c=ae(a,Aa,o)*a%o,u=ae(c,iw,o)*t%o,h=ae(u,ow,o)*u%o,f=ae(h,e,o)*h%o,l=ae(f,n,o)*f%o,m=ae(l,r,o)*l%o,p=ae(m,i,o)*m%o,w=ae(p,i,o)*m%o,v=ae(w,e,o)*h%o;return{pow_p_5_8:ae(v,Aa,o)*t%o,b2:a}}function cw(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Oa=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function dw(t,e){const n=ws,r=le(e*e*e,n),i=le(r*r*e,n),o=aw(t*i).pow_p_5_8;let s=le(t*r*o,n);const a=le(e*s*s,n),c=s,u=le(s*Oa,n),h=a===t,f=a===le(-t,n),l=a===le(-t*Oa,n);return h&&(s=c),(f||l)&&(s=u),_m(s,n)&&(s=le(-s,n)),{isValid:h||f,value:s}}const uw=ut(Yd.p,{isLE:!0}),lw={...Yd,Fp:uw,hash:Rd,adjustScalarBytes:cw,uvRatio:dw},Qd=rw(lw);function hw(t){return Qd.utils.toMontgomery(re("pub",t))}var zr={exports:{}},ro,Ta;function fw(){if(Ta)return ro;Ta=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 o=e.charAt(i),s=o.charCodeAt(0);if(n[s]!==255)throw new TypeError(o+" is ambiguous");n[s]=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 w=0,v=0,b=0,g=p.length;b!==g&&p[b]===0;)b++,w++;for(var y=(g-b)*h+1>>>0,k=new Uint8Array(y);b!==g;){for(var x=p[b],N=0,C=y-1;(x!==0||N<v)&&C!==-1;C--,N++)x+=256*k[C]>>>0,k[C]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");v=N,b++}for(var S=y-v;S!==y&&k[S]===0;)S++;for(var A=c.repeat(w);S<y;++S)A+=e.charAt(k[S]);return A}function l(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var w=0;if(p[w]!==" "){for(var v=0,b=0;p[w]===c;)v++,w++;for(var g=(p.length-w)*u+1>>>0,y=new Uint8Array(g);p[w];){var k=n[p.charCodeAt(w)];if(k===255)return;for(var x=0,N=g-1;(k!==0||x<b)&&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");b=x,w++}if(p[w]!==" "){for(var C=g-b;C!==g&&y[C]===0;)C++;for(var S=new Uint8Array(v+(g-C)),A=v;C!==g;)S[A++]=y[C++];return S}}}function m(p){var w=l(p);if(w)return w;throw new Error("Non-base"+a+" character")}return{encode:f,decodeUnsafe:l,decode:m}}return ro=t,ro}var io,Ra;function bs(){if(Ra)return io;Ra=1;const t=new TextDecoder,e=o=>t.decode(o),n=new TextEncoder,r=o=>n.encode(o);function i(o,s){const a=new Uint8Array(s);let c=0;for(const u of o)a.set(u,c),c+=u.length;return a}return io={decodeText:e,encodeText:r,concat:i},io}var oo,Ia;function pw(){if(Ia)return oo;Ia=1;const{encodeText:t}=bs();class e{constructor(r,i,o,s){this.name=r,this.code=i,this.codeBuf=t(this.code),this.alphabet=s,this.codec=o(s)}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 oo=e,oo}var so,Wa;function mw(){if(Wa)return so;Wa=1;const t=(r,i,o)=>{const s={};for(let l=0;l<i.length;++l)s[i[l]]=l;let a=r.length;for(;r[a-1]==="=";)--a;const c=new Uint8Array(a*o/8|0);let u=0,h=0,f=0;for(let l=0;l<a;++l){const m=s[r[l]];if(m===void 0)throw new SyntaxError("Invalid character "+r[l]);h=h<<o|m,u+=o,u>=8&&(u-=8,c[f++]=255&h>>u)}if(u>=o||255&h<<8-u)throw new SyntaxError("Unexpected end of data");return c},e=(r,i,o)=>{const s=i[i.length-1]==="=",a=(1<<o)-1;let c="",u=0,h=0;for(let f=0;f<r.length;++f)for(h=h<<8|r[f],u+=8;u>o;)u-=o,c+=i[a&h>>u];if(u&&(c+=i[a&h<<o-u]),s)for(;c.length*o&7;)c+="=";return c};return so={rfc4648:r=>i=>({encode(o){return e(o,i,r)},decode(o){return t(o,i,r)}})},so}var ao,Ma;function ww(){if(Ma)return ao;Ma=1;const t=fw(),e=pw(),{rfc4648:n}=mw(),{decodeText:r,encodeText:i}=bs(),s=[["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=s.reduce((u,h)=>(u[h[0]]=new e(h[0],h[1],h[2],h[3]),u),{}),c=s.reduce((u,h)=>(u[h[1]]=a[h[0]],u),{});return ao={names:a,codes:c},ao}var La;function bw(){return La||(La=1,(function(t,e){const n=ww(),{encodeText:r,decodeText:i,concat:o}=bs();function s(w,v){if(!v)throw new Error("requires an encoded Uint8Array");const{name:b,codeBuf:g}=f(w);return h(b,v),o([g,v],g.length+v.length)}function a(w,v){const b=f(w),g=r(b.encode(v));return o([b.codeBuf,g],b.codeBuf.length+g.length)}function c(w){w instanceof Uint8Array&&(w=i(w));const v=w[0];return["f","F","v","V","t","T","b","B","c","C","h","k","K"].includes(v)&&(w=w.toLowerCase()),f(w[0]).decode(w.substring(1))}function u(w){if(w instanceof Uint8Array&&(w=i(w)),Object.prototype.toString.call(w)!=="[object String]")return!1;try{return f(w[0]).name}catch{return!1}}function h(w,v){f(w).decode(i(v))}function f(w){if(Object.prototype.hasOwnProperty.call(n.names,w))return n.names[w];if(Object.prototype.hasOwnProperty.call(n.codes,w))return n.codes[w];throw new Error(`Unsupported encoding: ${w}`)}function l(w){return w instanceof Uint8Array&&(w=i(w)),f(w[0])}e=t.exports=s,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})(zr,zr.exports)),zr.exports}var yw=bw();class Xd extends ds{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,kd(e);const r=Bi(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,o=new Uint8Array(i);o.set(r.length>i?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),at(o)}update(e){return Wn(this),this.iHash.update(e),this}digestInto(e){Wn(this),Et(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:o,blockLen:s,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,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 eu=(t,e,n)=>new Xd(t,e).update(n).digest();eu.create=(t,e)=>new Xd(t,e);const Pa=(t,e)=>(t+(t>=0?e:-e)/tu)/e;function gw(t,e,n){const[[r,i],[o,s]]=e,a=Pa(s*t,n),c=Pa(-i*t,n);let u=t-a*r-c*o,h=-a*i-c*s;const f=u<Nt,l=h<Nt;f&&(u=-u),l&&(h=-h);const m=Rr(Math.ceil(Md(n)/2))+An;if(u<Nt||u>=m||h<Nt||h>=m)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:l,k2:h}}function Bo(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function co(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return dn(n.lowS,"lowS"),dn(n.prehash,"prehash"),n.format!==void 0&&Bo(n.format),n}class Nw extends Error{constructor(e=""){super(e)}}const bt={Err:Nw,_tlv:{encode:(t,e)=>{const{Err:n}=bt;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=Gn(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const o=r>127?Gn(i.length/2|128):"";return Gn(t)+o+i+e},decode(t,e){const{Err:n}=bt;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++],o=!!(i&128);let s=0;if(!o)s=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)s=s<<8|h;if(r+=c,s<128)throw new n("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+s);if(a.length!==s)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+s)}}},_int:{encode(t){const{Err:e}=bt;if(t<Nt)throw new e("integer: negative integers are not allowed");let n=Gn(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}=bt;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 Ui(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=bt,i=re("signature",t),{v:o,l:s}=r.decode(48,i);if(s.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,o),{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}=bt,r=e.encode(2,n.encode(t.r)),i=e.encode(2,n.encode(t.s)),o=r+i;return e.encode(48,o)}},Nt=BigInt(0),An=BigInt(1),tu=BigInt(2),Kr=BigInt(3),xw=BigInt(4);function Dn(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 vw(t,e={}){const n=Zd("weierstrass",t,e),{Fp:r,Fn:i}=n;let o=n.CURVE;const{h:s,n:a}=o;Ir(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!r.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=ru(r,i);function h(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f($,O,E){const{x:D,y:T}=O.toAffine(),W=r.toBytes(D);if(dn(E,"isCompressed"),E){h();const B=!r.isOdd(T);return it(nu(B),W)}else return it(Uint8Array.of(4),W,r.toBytes(T))}function l($){Xe($,void 0,"Point");const{publicKey:O,publicKeyUncompressed:E}=u,D=$.length,T=$[0],W=$.subarray(1);if(D===O&&(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=w(B);let L;try{L=r.sqrt(M)}catch(ie){const Y=ie instanceof Error?": "+ie.message:"";throw new Error("bad point: is not on curve, sqrt error"+Y)}h();const U=r.isOdd(L);return(T&1)===1!==U&&(L=r.neg(L)),{x:B,y:L}}else if(D===E&&T===4){const B=r.BYTES,M=r.fromBytes(W.subarray(0,B)),L=r.fromBytes(W.subarray(B,B*2));if(!v(M,L))throw new Error("bad point: is not on curve");return{x:M,y:L}}else throw new Error(`bad point: got length ${D}, expected compressed=${O} or uncompressed=${E}`)}const m=e.toBytes||f,p=e.fromBytes||l;function w($){const O=r.sqr($),E=r.mul(O,$);return r.add(r.add(E,r.mul($,o.a)),o.b)}function v($,O){const E=r.sqr(O),D=w($);return r.eql(E,D)}if(!v(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const b=r.mul(r.pow(o.a,Kr),xw),g=r.mul(r.sqr(o.b),BigInt(27));if(r.is0(r.add(b,g)))throw new Error("bad curve params: a or b");function y($,O,E=!1){if(!r.isValid(O)||E&&r.is0(O))throw new Error(`bad point coordinate ${$}`);return O}function k($){if(!($ instanceof A))throw new Error("ProjectivePoint expected")}function x($){if(!c||!c.basises)throw new Error("no endo");return gw($,c.basises,i.ORDER)}const N=li(($,O)=>{const{X:E,Y:D,Z:T}=$;if(r.eql(T,r.ONE))return{x:E,y:D};const W=$.is0();O==null&&(O=W?r.ONE:r.inv(T));const B=r.mul(E,O),M=r.mul(D,O),L=r.mul(T,O);if(W)return{x:r.ZERO,y:r.ZERO};if(!r.eql(L,r.ONE))throw new Error("invZ was invalid");return{x:B,y:M}}),C=li($=>{if($.is0()){if(e.allowInfinityPoint&&!r.is0($.Y))return;throw new Error("bad point: ZERO")}const{x:O,y:E}=$.toAffine();if(!r.isValid(O)||!r.isValid(E))throw new Error("bad point: x or y not field elements");if(!v(O,E))throw new Error("bad point: equation left != right");if(!$.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function S($,O,E,D,T){return E=new A(r.mul(E.X,$),E.Y,E.Z),O=hi(D,O),E=hi(T,E),O.add(E)}class A{constructor(O,E,D){this.X=y("x",O),this.Y=y("y",E,!0),this.Z=y("z",D),Object.freeze(this)}static CURVE(){return o}static fromAffine(O){const{x:E,y:D}=O||{};if(!O||!r.isValid(E)||!r.isValid(D))throw new Error("invalid affine point");if(O instanceof A)throw new Error("projective point not allowed");return r.is0(E)&&r.is0(D)?A.ZERO:new A(E,D,r.ONE)}static fromBytes(O){const E=A.fromAffine(p(Xe(O,void 0,"point")));return E.assertValidity(),E}static fromHex(O){return A.fromBytes(re("pointHex",O))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(O=8,E=!0){return q.createCache(this,O),E||this.multiply(Kr),this}assertValidity(){C(this)}hasEvenY(){const{y:O}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(O)}equals(O){k(O);const{X:E,Y:D,Z:T}=this,{X:W,Y:B,Z:M}=O,L=r.eql(r.mul(E,M),r.mul(W,T)),U=r.eql(r.mul(D,M),r.mul(B,T));return L&&U}negate(){return new A(this.X,r.neg(this.Y),this.Z)}double(){const{a:O,b:E}=o,D=r.mul(E,Kr),{X:T,Y:W,Z:B}=this;let M=r.ZERO,L=r.ZERO,U=r.ZERO,V=r.mul(T,T),ie=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(O,U),L=r.mul(D,Y),L=r.add(M,L),M=r.sub(ie,L),L=r.add(ie,L),L=r.mul(M,L),M=r.mul(_,M),U=r.mul(D,U),Y=r.mul(O,Y),_=r.sub(V,Y),_=r.mul(O,_),_=r.add(_,U),U=r.add(V,V),V=r.add(U,V),V=r.add(V,Y),V=r.mul(V,_),L=r.add(L,V),Y=r.mul(W,B),Y=r.add(Y,Y),V=r.mul(Y,_),M=r.sub(M,V),U=r.mul(Y,ie),U=r.add(U,U),U=r.add(U,U),new A(M,L,U)}add(O){k(O);const{X:E,Y:D,Z:T}=this,{X:W,Y:B,Z:M}=O;let L=r.ZERO,U=r.ZERO,V=r.ZERO;const ie=o.a,Y=r.mul(o.b,Kr);let _=r.mul(E,W),oe=r.mul(D,B),fe=r.mul(T,M),Oe=r.add(E,D),se=r.add(W,B);Oe=r.mul(Oe,se),se=r.add(_,oe),Oe=r.sub(Oe,se),se=r.add(E,T);let xe=r.add(W,M);return se=r.mul(se,xe),xe=r.add(_,fe),se=r.sub(se,xe),xe=r.add(D,T),L=r.add(B,M),xe=r.mul(xe,L),L=r.add(oe,fe),xe=r.sub(xe,L),V=r.mul(ie,se),L=r.mul(Y,fe),V=r.add(L,V),L=r.sub(oe,V),V=r.add(oe,V),U=r.mul(L,V),oe=r.add(_,_),oe=r.add(oe,_),fe=r.mul(ie,fe),se=r.mul(Y,se),oe=r.add(oe,fe),fe=r.sub(_,fe),fe=r.mul(ie,fe),se=r.add(se,fe),_=r.mul(oe,se),U=r.add(U,_),_=r.mul(xe,se),L=r.mul(Oe,L),L=r.sub(L,_),_=r.mul(Oe,oe),V=r.mul(xe,V),V=r.add(V,_),new A(L,U,V)}subtract(O){return this.add(O.negate())}is0(){return this.equals(A.ZERO)}multiply(O){const{endo:E}=e;if(!i.isValidNot0(O))throw new Error("invalid scalar: out of range");let D,T;const W=B=>q.cached(this,B,M=>tn(A,M));if(E){const{k1neg:B,k1:M,k2neg:L,k2:U}=x(O),{p:V,f:ie}=W(M),{p:Y,f:_}=W(U);T=ie.add(_),D=S(E.beta,V,Y,B,L)}else{const{p:B,f:M}=W(O);D=B,T=M}return tn(A,[D,T])[0]}multiplyUnsafe(O){const{endo:E}=e,D=this;if(!i.isValid(O))throw new Error("invalid scalar: out of range");if(O===Nt||D.is0())return A.ZERO;if(O===An)return D;if(q.hasCache(this))return this.multiply(O);if(E){const{k1neg:T,k1:W,k2neg:B,k2:M}=x(O),{p1:L,p2:U}=Zm(A,D,W,M);return S(E.beta,L,U,T,B)}else return q.unsafe(D,O)}multiplyAndAddUnsafe(O,E,D){const T=this.multiplyUnsafe(E).add(O.multiplyUnsafe(D));return T.is0()?void 0:T}toAffine(O){return N(this,O)}isTorsionFree(){const{isTorsionFree:O}=e;return s===An?!0:O?O(A,this):q.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:O}=e;return s===An?this:O?O(A,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(O=!0){return dn(O,"isCompressed"),this.assertValidity(),m(A,this,O)}toHex(O=!0){return sn(this.toBytes(O))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(O=!0){return this.toBytes(O)}_setWindowSize(O){this.precompute(O)}static normalizeZ(O){return tn(A,O)}static msm(O,E){return Gd(A,i,O,E)}static fromPrivateKey(O){return A.BASE.multiply(Dn(i,O))}}A.BASE=new A(o.Gx,o.Gy,r.ONE),A.ZERO=new A(r.ZERO,r.ONE,r.ZERO),A.Fp=r,A.Fn=i;const P=i.BITS,q=new Jd(A,e.endo?Math.ceil(P/2):P);return A.BASE.precompute(8),A}function nu(t){return Uint8Array.of(t?2:3)}function ru(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Ew(t,e={}){const{Fn:n}=t,r=e.randomBytes||us,i=Object.assign(ru(t.Fp,n),{seed:Hd(n.ORDER)});function o(m){try{return!!Dn(n,m)}catch{return!1}}function s(m,p){const{publicKey:w,publicKeyUncompressed:v}=i;try{const b=m.length;return p===!0&&b!==w||p===!1&&b!==v?!1:!!t.fromBytes(m)}catch{return!1}}function a(m=r(i.seed)){return Km(Xe(m,i.seed,"seed"),n.ORDER)}function c(m,p=!0){return t.BASE.multiply(Dn(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:w,publicKeyUncompressed:v}=i;if(n.allowedLengths||p===w)return;const b=re("key",m).length;return b===w||b===v}function f(m,p,w=!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=Dn(n,m);return t.fromHex(p).multiply(v).toBytes(w)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:u,Point:t,utils:{isValidSecretKey:o,isValidPublicKey:s,randomSecretKey:a,isValidPrivateKey:o,randomPrivateKey:a,normPrivateKeyToScalar:m=>Dn(n,m),precompute(m=8,p=t.BASE){return p.precompute(m,!1)}},lengths:i})}function Dw(t,e,n={}){kd(e),Ir(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||us,i=n.hmac||((E,...D)=>eu(e,E,it(...D))),{Fp:o,Fn:s}=t,{ORDER:a,BITS:c}=s,{keygen:u,getPublicKey:h,getSharedSecret:f,utils:l,lengths:m}=Ew(t,n),p={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},w="compact";function v(E){const D=a>>An;return E>D}function b(E,D){if(!s.isValidNot0(D))throw new Error(`invalid signature ${E}: out of range 1..Point.Fn.ORDER`);return D}function g(E,D){Bo(D);const T=m.signature,W=D==="compact"?T:D==="recovered"?T+1:void 0;return Xe(E,W,`${D} signature`)}class y{constructor(D,T,W){this.r=b("r",D),this.s=b("s",T),W!=null&&(this.recovery=W),Object.freeze(this)}static fromBytes(D,T=w){g(D,T);let W;if(T==="der"){const{r:U,s:V}=bt.toSig(Xe(D));return new y(U,V)}T==="recovered"&&(W=D[0],T="compact",D=D.subarray(1));const B=s.BYTES,M=D.subarray(0,B),L=D.subarray(B,B*2);return new y(s.fromBytes(M),s.fromBytes(L),W)}static fromHex(D,T){return this.fromBytes(br(D),T)}addRecoveryBit(D){return new y(this.r,this.s,D)}recoverPublicKey(D){const T=o.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*tu<T&&M>1)throw new Error("recovery id is ambiguous for h>1 curve");const U=M===2||M===3?W+a:W;if(!o.isValid(U))throw new Error("recovery id 2 or 3 invalid");const V=o.toBytes(U),ie=t.fromBytes(it(nu((M&1)===0),V)),Y=s.inv(U),_=x(re("msgHash",D)),oe=s.create(-_*Y),fe=s.create(B*Y),Oe=t.BASE.multiplyUnsafe(oe).add(ie.multiplyUnsafe(fe));if(Oe.is0())throw new Error("point at infinify");return Oe.assertValidity(),Oe}hasHighS(){return v(this.s)}toBytes(D=w){if(Bo(D),D==="der")return br(bt.hexFromSig(this));const T=s.toBytes(this.r),W=s.toBytes(this.s);if(D==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return it(Uint8Array.of(this.recovery),T,W)}return it(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,s.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=Ui(D),W=D.length*8-c;return W>0?T>>BigInt(W):T},x=n.bits2int_modN||function(D){return s.create(k(D))},N=Rr(c);function C(E){return $o("num < 2^"+c,E,Nt,N),s.toBytes(E)}function S(E,D){return Xe(E,void 0,"message"),D?Xe(e(E),void 0,"prehashed message"):E}function A(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}=co(T,p);E=S(E,B);const L=x(E),U=Dn(s,D),V=[C(U),C(L)];if(M!=null&&M!==!1){const oe=M===!0?r(m.secretKey):M;V.push(re("extraEntropy",oe))}const ie=it(...V),Y=L;function _(oe){const fe=k(oe);if(!s.isValidNot0(fe))return;const Oe=s.inv(fe),se=t.BASE.multiply(fe).toAffine(),xe=s.create(se.x);if(xe===Nt)return;const Ur=s.create(Oe*s.create(Y+xe*U));if(Ur===Nt)return;let ra=(se.x===xe?0:2)|Number(se.y&An),ia=Ur;return W&&v(Ur)&&(ia=s.neg(Ur),ra^=1),new y(xe,ia,ra)}return{seed:ie,k2sig:_}}function P(E,D,T={}){E=re("message",E);const{seed:W,k2sig:B}=A(E,D,T);return $m(e.outputLen,s.BYTES,i)(W,B)}function q(E){let D;const T=typeof E=="string"||Or(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 bt.Err))throw B}if(!D)try{D=y.fromBytes(re("sig",E),"compact")}catch{return!1}}return D||!1}function $(E,D,T,W={}){const{lowS:B,prehash:M,format:L}=co(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=L===void 0?q(E):y.fromBytes(re("sig",E),L);if(U===!1)return!1;try{const V=t.fromBytes(T);if(B&&U.hasHighS())return!1;const{r:ie,s:Y}=U,_=x(D),oe=s.inv(Y),fe=s.create(_*oe),Oe=s.create(ie*oe),se=t.BASE.multiplyUnsafe(fe).add(V.multiplyUnsafe(Oe));return se.is0()?!1:s.create(se.x)===ie}catch{return!1}}function O(E,D,T={}){const{prehash:W}=co(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:P,verify:$,recoverPublicKey:O,Signature:y,hash:e})}function kw(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(s=>Math.ceil(s/2)))):void 0;const i=ut(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),o={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:o}}function Sw(t){const{CURVE:e,curveOpts:n}=kw(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 Cw(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,_d(n.Fn.ORDER,n.Fn.BITS))})}function Aw(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:i}=Sw(t),o=vw(e,n),s=Dw(o,r,i);return Cw(t,s)}function qi(t,e){const n=r=>Aw({...t,hash:r});return{...n(e),create:n}}const ys={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Ow={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},$a=BigInt(2);function Tw(t){const e=ys.p,n=BigInt(3),r=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),u=t*t*t%e,h=u*u*t%e,f=ae(h,n,e)*h%e,l=ae(f,n,e)*h%e,m=ae(l,$a,e)*u%e,p=ae(m,i,e)*m%e,w=ae(p,o,e)*p%e,v=ae(w,a,e)*w%e,b=ae(v,c,e)*v%e,g=ae(b,a,e)*w%e,y=ae(g,n,e)*h%e,k=ae(y,s,e)*p%e,x=ae(k,r,e)*u%e,N=ae(x,$a,e);if(!Uo.eql(Uo.sqr(N),t))throw new Error("Cannot find square root");return N}const Uo=ut(ys.p,{sqrt:Tw}),gr=qi({...ys,Fp:Uo,lowS:!0,endo:Ow},hs);const iu={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},ou={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},su={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},Rw=ut(iu.p),Iw=ut(ou.p),Ww=ut(su.p),Mw=qi({...iu,Fp:Rw,lowS:!1},hs),Lw=qi({...ou,Fp:Iw,lowS:!1},Mm),Pw=qi({...su,Fp:Ww,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},Rd);const fi=Mw,$w=hs,Bw=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),au=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),Uw=au.map(t=>(9*t+5)%16),cu=(()=>{const n=[[au],[Uw]];for(let r=0;r<4;r++)for(let i of n)i.push(i[r].map(o=>Bw[o]));return n})(),du=cu[0],uu=cu[1],lu=[[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)),qw=du.map((t,e)=>t.map(n=>lu[e][n])),Fw=uu.map((t,e)=>t.map(n=>lu[e][n])),Vw=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),_w=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function Ba(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 Jr=new Uint32Array(16);class jw extends ls{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:o}=this;return[e,n,r,i,o]}set(e,n,r,i,o){this.h0=e|0,this.h1=n|0,this.h2=r|0,this.h3=i|0,this.h4=o|0}process(e,n){for(let m=0;m<16;m++,n+=4)Jr[m]=e.getUint32(n,!0);let r=this.h0|0,i=r,o=this.h1|0,s=o,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,w=Vw[m],v=_w[m],b=du[m],g=uu[m],y=qw[m],k=Fw[m];for(let x=0;x<16;x++){const N=Vr(r+Ba(m,o,a,u)+Jr[b[x]]+w,y[x])+f|0;r=f,f=u,u=Vr(a,10)|0,a=o,o=N}for(let x=0;x<16;x++){const N=Vr(i+Ba(p,s,c,h)+Jr[g[x]]+v,k[x])+l|0;i=l,l=h,h=Vr(c,10)|0,c=s,s=N}}this.set(this.h1+a+h|0,this.h2+u+l|0,this.h3+f+i|0,this.h4+r+s|0,this.h0+o+c|0)}roundClean(){at(Jr)}destroy(){this.destroyed=!0,at(this.buffer),this.set(0,0,0,0,0)}}const Hw=Tr(()=>new jw),hu=Hw,zw=BigInt(0),jn=BigInt(1),Kw=BigInt(2),Jw=BigInt(7),Gw=BigInt(256),Zw=BigInt(113),fu=[],pu=[],mu=[];for(let t=0,e=jn,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],fu.push(2*(5*r+n)),pu.push((t+1)*(t+2)/2%64);let i=zw;for(let o=0;o<7;o++)e=(e<<jn^(e>>Jw)*Zw)%Gw,e&Kw&&(i^=jn<<(jn<<BigInt(o))-jn);mu.push(i)}const wu=Ad(mu,!0),Yw=wu[0],Qw=wu[1],Ua=(t,e,n)=>n>32?xm(t,e,n):gm(t,e,n),qa=(t,e,n)=>n>32?vm(t,e,n):Nm(t,e,n);function Xw(t,e=24){const n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let s=0;s<10;s++)n[s]=t[s]^t[s+10]^t[s+20]^t[s+30]^t[s+40];for(let s=0;s<10;s+=2){const a=(s+8)%10,c=(s+2)%10,u=n[c],h=n[c+1],f=Ua(u,h,1)^n[a],l=qa(u,h,1)^n[a+1];for(let m=0;m<50;m+=10)t[s+m]^=f,t[s+m+1]^=l}let i=t[2],o=t[3];for(let s=0;s<24;s++){const a=pu[s],c=Ua(i,o,a),u=qa(i,o,a),h=fu[s];i=t[h],o=t[h+1],t[h]=c,t[h+1]=u}for(let s=0;s<50;s+=10){for(let a=0;a<10;a++)n[a]=t[s+a];for(let a=0;a<10;a++)t[s+a]^=~n[(a+2)%10]&n[(a+4)%10]}t[0]^=Yw[r],t[1]^=Qw[r]}at(n)}class gs extends ds{constructor(e,n,r,i=!1,o=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=o,wr(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=dm(this.state)}clone(){return this._cloneInto()}keccak(){ba(this.state32),Xw(this.state32,this.rounds),ba(this.state32),this.posOut=0,this.pos=0}update(e){Wn(this),e=Bi(e),Et(e);const{blockLen:n,state:r}=this,i=e.length;for(let o=0;o<i;){const s=Math.min(n-this.pos,i-o);for(let a=0;a<s;a++)r[this.pos++]^=e[o++];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){Wn(this,!1),Et(e),this.finish();const n=this.state,{blockLen:r}=this;for(let i=0,o=e.length;i<o;){this.posOut>=r&&this.keccak();const s=Math.min(r-this.posOut,o-i);e.set(n.subarray(this.posOut,this.posOut+s),i),this.posOut+=s,i+=s}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return wr(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Sd(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,at(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:i,rounds:o,enableXOF:s}=this;return e||(e=new gs(n,r,i,s,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=i,e.enableXOF=s,e.destroyed=this.destroyed,e}}const eb=(t,e,n)=>Tr(()=>new gs(e,t,n)),tb=eb(1,136,256/8);var uo,Fa;function nb(){return Fa||(Fa=1,uo=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,o,s)=>`${i}${s===0?"":","}${t(o===void 0||typeof o=="symbol"?null:o)}`,"")}]`:`{${Object.keys(e).sort().reduce((r,i)=>{if(e[i]===void 0||typeof e[i]=="symbol")return r;const o=r.length===0?"":",";return`${r}${o}${t(i)}:${t(e[i])}`},"")}}`}),uo}var rb=nb();const ib=Xo(rb);function ob(t,e){try{var n=t()}catch(r){return e(r)}return n&&n.then?n.then(void 0,e):n}function sb(){const t=new Map;return function(e,n){try{let i=function(s){if(r)return s;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 o=(function(){if(e.params&&e.params["no-cache"]==="true")return Promise.resolve(n()).then(function(s){return r=1,s})})();return Promise.resolve(o&&o.then?o.then(i):i(o))}catch(r){return Promise.reject(r)}}}function ab(t,e){return e()}const cb="(?:%[0-9a-fA-F]{2})",Va=`(?:[a-zA-Z0-9._-]|${cb})`,db="([a-z0-9]+)",ub=`((?:${Va}*:)*(${Va}+))`,_a="[a-zA-Z0-9_.:%-]",lb=`;${_a}+=${_a}*`,hb=`((${lb})*)`,fb="(/[^#?]*)?",pb="([?][^#]*)?",mb="(#.*)?",wb=new RegExp(`^did:${db}:${ub}${hb}${fb}${pb}${mb}$`);function bu(t){if(t===""||!t)return null;const e=t.match(wb);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 o=i.split("=");n.params[o[0]]=o[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 pi={didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}};function bb(t){return function(e,n,r){try{return Promise.resolve(ob(function(){return Promise.resolve(t(e,n,r)).then(function(i){return{...pi,didResolutionMetadata:{contentType:"application/did+ld+json"},didDocument:i}})},function(i){return{...pi,didResolutionMetadata:{error:"notFound",message:i.toString()}}}))}catch(i){return Promise.reject(i)}}}class yb{constructor(e={},n={}){this.registry=void 0,this.cache=void 0,this.registry=e,this.cache=n.cache===!0?sb():n.cache||ab,n.legacyResolvers&&Object.keys(n.legacyResolvers).map(r=>{this.registry[r]||(this.registry[r]=bb(n.legacyResolvers[r]))})}resolve(e,n={}){try{const r=this,i=bu(e);if(i===null)return Promise.resolve({...pi,didResolutionMetadata:{error:"invalidDid"}});const o=r.registry[i.method];return o?Promise.resolve(r.cache(i,()=>o(i.did,i,r,n))):Promise.resolve({...pi,didResolutionMetadata:{error:"unsupportedDidMethod"}})}catch(r){return Promise.reject(r)}}}function yu(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function gu(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 gb(t){if(typeof t!="function")throw new Error("function expected");return!0}function Nr(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function Nu(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function qo(t){if(!Array.isArray(t))throw new Error("array expected")}function xu(t,e){if(!gu(!0,e))throw new Error(`${t}: array of strings expected`)}function vu(t,e){if(!gu(!1,e))throw new Error(`${t}: array of numbers expected`)}function Nb(...t){const e=o=>o,n=(o,s)=>a=>o(s(a)),r=t.map(o=>o.encode).reduceRight(n,e),i=t.map(o=>o.decode).reduce(n,e);return{encode:r,decode:i}}function xb(t){const e=typeof t=="string"?t.split(""):t,n=e.length;xu("alphabet",e);const r=new Map(e.map((i,o)=>[i,o]));return{encode:i=>(qo(i),i.map(o=>{if(!Number.isSafeInteger(o)||o<0||o>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${o}". Allowed: ${t}`);return e[o]})),decode:i=>(qo(i),i.map(o=>{Nr("alphabet.decode",o);const s=r.get(o);if(s===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${t}`);return s}))}}function vb(t=""){return Nr("join",t),{encode:e=>(xu("join.decode",e),e.join(t)),decode:e=>(Nr("join.decode",e),e.split(t))}}const Eu=(t,e)=>e===0?t:Eu(e,t%e),mi=(t,e)=>t+(e-Eu(t,e)),ti=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Fo(t,e,n,r){if(qo(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(mi(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${mi(e,n)}`);let i=0,o=0;const s=ti[e],a=ti[n]-1,c=[];for(const u of t){if(Nu(u),u>=s)throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);if(i=i<<e|u,o+e>32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${e}`);for(o+=e;o>=n;o-=n)c.push((i>>o-n&a)>>>0);const h=ti[o];if(h===void 0)throw new Error("invalid carry");i&=h-1}if(i=i<<n-o&a,!r&&o>=e)throw new Error("Excess padding");if(!r&&i>0)throw new Error(`Non-zero padding: ${i}`);return r&&o>0&&c.push(i>>>0),c}function Eb(t,e=!1){if(Nu(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(mi(8,t)>32||mi(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!yu(n))throw new Error("radix2.encode input should be Uint8Array");return Fo(Array.from(n),8,t,!e)},decode:n=>(vu("radix2.decode",n),Uint8Array.from(Fo(n,t,8,e)))}}function ja(t){return gb(t),function(...e){try{return t.apply(null,e)}catch{}}}const Vo=Nb(xb("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),vb("")),Ha=[996825010,642813549,513874426,1027748829,705979059];function Hn(t){const e=t>>25;let n=(t&33554431)<<5;for(let r=0;r<Ha.length;r++)(e>>r&1)===1&&(n^=Ha[r]);return n}function za(t,e,n=1){const r=t.length;let i=1;for(let o=0;o<r;o++){const s=t.charCodeAt(o);if(s<33||s>126)throw new Error(`Invalid prefix (${t})`);i=Hn(i)^s>>5}i=Hn(i);for(let o=0;o<r;o++)i=Hn(i)^t.charCodeAt(o)&31;for(let o of e)i=Hn(i)^o;for(let o=0;o<6;o++)i=Hn(i);return i^=n,Vo.encode(Fo([i%ti[30]],30,5,!1))}function Db(t){const e=t==="bech32"?1:734539939,n=Eb(5),r=n.decode,i=n.encode,o=ja(r);function s(f,l,m=90){Nr("bech32.encode prefix",f),yu(l)&&(l=Array.from(l)),vu("bech32.encode",l);const p=f.length;if(p===0)throw new TypeError(`Invalid prefix length ${p}`);const w=p+7+l.length;if(m!==!1&&w>m)throw new TypeError(`Length ${w} exceeds limit ${m}`);const v=f.toLowerCase(),b=za(v,l,e);return`${v}1${Vo.encode(l)}${b}`}function a(f,l=90){Nr("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 w=p.lastIndexOf("1");if(w===0||w===-1)throw new Error('Letter "1" must be present between prefix and data only');const v=p.slice(0,w),b=p.slice(w+1);if(b.length<6)throw new Error("Data must be at least 6 characters long");const g=Vo.decode(b).slice(0,-6),y=za(v,g,e);if(!b.endsWith(y))throw new Error(`Invalid checksum in ${f}: expected "${y}"`);return{prefix:v,words:g}}const c=ja(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 s(f,i(l))}return{encode:s,decode:a,encodeFromBytes:h,decodeToBytes:u,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:o,toWords:i}}const Ka=Db("bech32"),ze={toString:cs,fromString:$i,concat:dd};function Ns(t){return ze.toString(t,"base64url")}function _e(t){const e=t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return ze.fromString(e,"base64url")}function Du(t){return ze.fromString(t,"base58btc")}function kb(t){return ze.toString(t,"base58btc")}const Sb={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"]},Gr={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},Cb={"ed25519-pub":237,"x25519-pub":236,"secp256k1-pub":231,"bls12_381-g1-pub":234,"bls12_381-g2-pub":235,"p256-pub":4608},Ab={"bls12_381-g1-pub":"Bls12381G1","bls12_381-g2-pub":"Bls12381G2","ed25519-pub":"Ed25519","p256-pub":"P-256","secp256k1-pub":"Secp256k1","x25519-pub":"X25519"};function Fi(t){if(t.publicKeyBase58)return{keyBytes:Du(t.publicKeyBase58),keyType:Gr[t.type]};if(t.publicKeyBase64)return{keyBytes:_e(t.publicKeyBase64),keyType:Gr[t.type]};if(t.publicKeyHex)return{keyBytes:ni(t.publicKeyHex),keyType:Gr[t.type]};if(t.publicKeyJwk&&t.publicKeyJwk.crv==="secp256k1"&&t.publicKeyJwk.x&&t.publicKeyJwk.y)return{keyBytes:gr.ProjectivePoint.fromAffine({x:Zr(_e(t.publicKeyJwk.x)),y:Zr(_e(t.publicKeyJwk.y))}).toRawBytes(!1),keyType:"Secp256k1"};if(t.publicKeyJwk&&t.publicKeyJwk.crv==="P-256"&&t.publicKeyJwk.x&&t.publicKeyJwk.y)return{keyBytes:fi.ProjectivePoint.fromAffine({x:Zr(_e(t.publicKeyJwk.x)),y:Zr(_e(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:_e(t.publicKeyJwk.x),keyType:t.publicKeyJwk.crv};if(t.publicKeyMultibase){const{keyBytes:e,keyType:n}=Ob(t.publicKeyMultibase);return{keyBytes:e,keyType:n??Gr[t.type]}}return{keyBytes:new Uint8Array}}function Ob(t){const e=yw.decode(t);if([32,33,48,64,65,96].includes(e.length))return{keyBytes:e};try{const[n,r]=hr(e),i=Object.entries(Cb).filter(([,o])=>o===n)?.[0][0]??"";return{keyBytes:e.slice(r),keyType:Ab[i]}}catch{return{keyBytes:e}}}function ni(t,e){let n=t.startsWith("0x")?t.substring(2):t;return n.length%2!==0&&(n=`0${n}`),ze.fromString(n.toLowerCase(),"base16")}function Ja(t){return Ns(ze.fromString(t))}function ku(t){return ze.toString(_e(t))}function _t(t){return ze.toString(t,"base16")}function Zr(t){return BigInt("0x"+ze.toString(t,"base16"))}function Tb(t){return ze.fromString(t,"utf-8")}function Su({r:t,s:e,recoveryParam:n},r){const i=new Uint8Array(r?65:64);if(i.set(ze.fromString(t,"base16"),0),i.set(ze.fromString(e,"base16"),32),r){if(typeof n>"u")throw new Error("Signer did not return a recoveryParam");i[64]=n}return Ns(i)}function Rb(t){const e=_e(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=_t(e.slice(0,32)),r=_t(e.slice(32,64)),i=e.length===65?e[64]:void 0;return{r:n,s:r,recoveryParam:i}}function an(t){const e=typeof t=="string"?$i(t):t;return $w(e)}const Ib=tb;function Cu(t){const e=$i(t.slice(2),"base16");return`0x${cs(Ib(e).slice(-20),"base16")}`}function xs(t){return typeof t=="object"&&"r"in t&&"s"in t}function Wb(){return function(e,n){try{return Promise.resolve(n(e)).then(function(r){return xs(r)?Su(r):r})}catch(r){return Promise.reject(r)}}}function Ga(t){return function(n,r){try{return Promise.resolve(r(n)).then(function(i){if(xs(i))return Su(i,t);if(t&&typeof Rb(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 Za(){return function(e,n){try{return Promise.resolve(n(e)).then(function(r){if(xs(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 Mb={ES256:Wb(),ES256K:Ga(),"ES256K-R":Ga(!0),Ed25519:Za(),EdDSA:Za()};function Lb(t){const e=Mb[t];if(!e)throw new Error(`not_supported: Unsupported algorithm ${t}`);return e}function Pb(t,e){const n=_t(Du(e).slice(0,1)),r=ni(t),i=hu(an(r)),o=n+_t(i),s=an(ni(o)),a=an(s),c=_t(a).substring(0,8),u=o+c;return kb(ni(u))}function $b(t,e){const n=gr.ProjectivePoint.fromHex(t).toRawBytes(),r=hu(an(n)),i=Ka.toWords(r);return Ka.encode(e,i).replace(e,"")}function Bb(t,e){if(e){const n=e.split(":");switch(n[0]){case"bip122":n[n.length-1]=Pb(t,n[n.length-1]);break;case"cosmos":n[n.length-1]=$b(t,n[1]);break;case"eip155":n[n.length-1]=Cu(t);break;default:return!1}return n.join(":").toLowerCase()===e.toLowerCase()}return!1}function Ub(t,e=!1){const n=_e(t);if(n.length!==(e?65:64))throw new Error("wrong signature length");const r=_t(n.slice(0,32)),i=_t(n.slice(32,64)),o={r,s:i};return e&&(o.recoveryParam=n[64]),o}function _o(t,e=!1){const n=_e(t);if(n.length!==(e?65:64))throw new Error("wrong signature length");return{compact:n.slice(0,64),recovery:n[64]}}function qb(t,e,n){const r=an(t),i=fi.Signature.fromCompact(_o(e).compact),s=n.filter(a=>!a.ethereumAddress&&!a.blockchainAccountId).find(a=>{try{const{keyBytes:c}=Fi(a);return fi.verify(i,r,c)}catch{return!1}});if(!s)throw new Error("invalid_signature: Signature invalid for JWT");return s}function Fb(t,e,n){const r=an(t),i=gr.Signature.fromCompact(_e(e)).normalizeS(),o=n.filter(c=>!c.ethereumAddress&&!c.blockchainAccountId),s=n.filter(c=>c.ethereumAddress||c.blockchainAccountId);let a=o.find(c=>{try{const{keyBytes:u}=Fi(c);return gr.verify(i,r,u)}catch{return!1}});if(!a&&s.length>0&&(a=Au(t,e,s)),!a)throw new Error("invalid_signature: Signature invalid for JWT");return a}function Au(t,e,n){const r=[];if(e.length>86)r.push(_o(e,!0));else{const s=_o(e,!1);r.push({...s,recovery:0}),r.push({...s,recovery:1})}const i=an(t),o=s=>{const c=gr.Signature.fromCompact(s.compact).addRecoveryBit(s.recovery||0).recoverPublicKey(i),u=Cu(c.toHex(!1)).toLowerCase(),h=c.toHex(!1),f=c.toHex(!0);return n.find(l=>{const{keyBytes:m}=Fi(l),p=_t(m);return p===h||p===f||l.ethereumAddress?.toLowerCase()===u||l.blockchainAccountId?.split("@eip155")?.[0].toLowerCase()===u||Bb(h,l.blockchainAccountId)})};for(const s of r){const a=o(s);if(a)return a}throw new Error("invalid_signature: Signature invalid for JWT")}function Ya(t,e,n){const r=Tb(t),i=_e(e),o=n.find(s=>{const{keyBytes:a,keyType:c}=Fi(s);return c==="Ed25519"?Qd.verify(i,r,a):!1});if(!o)throw new Error("invalid_signature: Signature invalid for JWT");return o}const Vb={ES256:qb,ES256K:Fb,"ES256K-R":Au,Ed25519:Ya,EdDSA:Ya};function Ou(t){const e=Vb[t];if(!e)throw new Error(`not_supported: Unsupported algorithm ${t}`);return e}Ou.toSignatureObject=Ub;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 _b(t,e){try{var n=t()}catch(r){return e(r)}return n&&n.then?n.then(void 0,e):n}const jb=function(t,{header:e,payload:n,data:r,signature:i},o,s){try{if(!o.conditionDelegated)throw new Error("Expected conditionDelegated");if(!s.resolver)throw new Error("Expected resolver");let a;const c=o.conditionDelegated;return Promise.resolve(Ru(s.resolver,e.alg,c,s.proofPurpose)).then(function(u){let h;function f(w){if(a)return o;throw new Error(`${J.INVALID_SIGNATURE}: condition for authenticator ${o.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(w=>w.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===vs)return Promise.resolve(Es(t,{...s,didAuthenticator:{didResolutionResult:l,authenticators:[m],issuer:m.id}})).then(function({verified:w}){w&&(a=m)});try{a=Ds({header:e,payload:n,data:r,signature:i},m)}catch(w){if(!w.message.startsWith("invalid_signature:"))throw w}})();return p&&p.then?p.then(f):f(p)})}catch(a){return Promise.reject(a)}},Qa=typeof Symbol<"u"?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function Se(t,e,n){if(!t.s){if(n instanceof Ln)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 Ln=(function(){function t(){}return t.prototype.then=function(e,n){const r=new t,i=this.s;if(i){const o=i&1?e:n;if(o){try{Se(r,1,o(this.v))}catch(s){Se(r,2,s)}return r}else return this}return this.o=function(o){try{const s=o.v;o.s&1?Se(r,1,e?e(s):s):n?Se(r,1,n(s)):Se(r,2,s)}catch(s){Se(r,2,s)}},r},t})();function Tu(t){return t instanceof Ln&&t.s&1}function Hb(t,e,n){var r=-1,i,o;function s(a){try{for(;++r<t.length&&(!n||!n());)if(a=e(r),a&&a.then)if(Tu(a))a=a.v;else{a.then(s,o||(o=Se.bind(null,i=new Ln,2)));return}i?Se(i,1,a):i=a}catch(c){Se(i||(i=new Ln),2,c)}}return s(),i}const zb=function(t,{header:e,payload:n,data:r,signature:i},o,s){try{let a=function(m){if(c)return m;throw new Error(`${J.INVALID_SIGNATURE}: condition for authenticator ${o.id} is not met.`)},c;if(!o.conditionWeightedThreshold||!o.threshold)throw new Error("Expected conditionWeightedThreshold and threshold");const u=[],h=o.threshold;let f=0;const l=Kb(o.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,o}const w=m.condition;let v;const b=_b(function(){if(w.type===vs){if(!s.didAuthenticator)throw new Error("Expected didAuthenticator");const g={...s,didAuthenticator:{didResolutionResult:s.didAuthenticator?.didResolutionResult,authenticators:[w],issuer:w.id}};return Promise.resolve(Es(t,g)).then(function({verified:y}){y&&(v=w)})}else return Promise.resolve(Ds({header:e,payload:n,data:r,signature:i},w)).then(function(g){v=g})},function(g){if(!g.message.startsWith(J.INVALID_SIGNATURE))throw g});return b&&b.then?b.then(p):p(b)},function(){return c});return Promise.resolve(l&&l.then?l.then(a):a(l))}catch(a){return Promise.reject(a)}};function Kb(t,e,n){if(typeof t[Qa]=="function"){let h=function(f){try{for(;!(i=r.next()).done&&(!n||!n());)if(f=e(i.value),f&&f.then)if(Tu(f))f=f.v;else{f.then(h,s||(s=Se.bind(null,o=new Ln,2)));return}o?Se(o,1,f):o=f}catch(l){Se(o||(o=new Ln),2,l)}};var r=t[Qa](),i,o,s;if(h(),r.return){var a=function(f){try{i.done||r.return()}catch{}return f};if(o&&o.then)return o.then(a,function(f){throw a(f)});a()}return o}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 Hb(c,function(h){return e(c[h])},n)}const Jb=function(t,{header:e,payload:n,signature:r,data:i},o,s){try{if(o.conditionWeightedThreshold)return zb(t,{header:e,payload:n,data:i,signature:r},o,s);if(o.conditionDelegated)return jb(t,{header:e,payload:n,data:i,signature:r},o,s);throw new Error(`${J.INVALID_JWT}: conditional proof type did not find condition for authenticator ${o.id}.`)}catch(a){return Promise.reject(a)}},Xa=function(t,{header:e,payload:n,signature:r,data:i},o,s){try{return o.type===vs?Jb(t,{payload:n,header:e,signature:r,data:i},o,s):Promise.resolve(Ds({header:e,payload:n,data:i,signature:r},[o]))}catch(a){return Promise.reject(a)}},vs="ConditionalProof2022";function ke(t,e,n){if(!t.s){if(n instanceof xr)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 xr=(function(){function t(){}return t.prototype.then=function(e,n){const r=new t,i=this.s;if(i){const o=i&1?e:n;if(o){try{ke(r,1,o(this.v))}catch(s){ke(r,2,s)}return r}else return this}return this.o=function(o){try{const s=o.v;o.s&1?ke(r,1,e?e(s):s):n?ke(r,1,n(s)):ke(r,2,s)}catch(s){ke(r,2,s)}},r},t})();function Zn(t){return t instanceof xr&&t.s&1}function Gb(t,e,n){var r=-1,i,o;function s(a){try{for(;++r<t.length&&(!n||!n());)if(a=e(r),a&&a.then)if(Zn(a))a=a.v;else{a.then(s,o||(o=ke.bind(null,i=new xr,2)));return}i?ke(i,1,a):i=a}catch(c){ke(i||(i=new xr),2,c)}}return s(),i}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(t,e,n){for(var r;;){var i=t();if(Zn(i)&&(i=i.v),!i)return o;if(i.then){r=0;break}var o=n();if(o&&o.then)if(Zn(o))o=o.s;else{r=1;break}var s}var a=new xr,c=ke.bind(null,a,2);return(r===0?i.then(h):r===1?o.then(u):s.then(f)).then(void 0,c),a;function u(l){o=l;do{if(i=t(),!i||Zn(i)&&!i.v){ke(a,1,o);return}if(i.then){i.then(h).then(void 0,c);return}o=n(),Zn(o)&&(o=o.v)}while(!o||!o.then);o.then(u).then(void 0,c)}function h(l){l?(o=n(),o&&o.then?o.then(u).then(void 0,c):u(o)):ke(a,1,o)}function f(){(i=t())?i.then?i.then(h).then(void 0,c):h(i):ke(a,1,o)}}const Ru=function(t,e,n,r){try{const i=Sb[e];if(!i||i.length===0)throw new Error(`${J.NOT_SUPPORTED}: No supported signature types for algorithm ${e}`);let o;return Promise.resolve(t.resolve(n,{accept:ec})).then(function(s){if(Object.getOwnPropertyNames(s).indexOf("didDocument")===-1?o={didDocument:s,didDocumentMetadata:{},didResolutionMetadata:{contentType:ec}}:o=s,o.didResolutionMetadata?.error||o.didDocument==null){const{error:h,message:f}=o.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=[...o?.didDocument?.verificationMethod||[],...o?.didDocument?.publicKey||[]];typeof r=="string"&&(r.startsWith("assertion")&&!Object.getOwnPropertyNames(o?.didDocument).includes("assertionMethod")&&(o.didDocument={...o.didDocument},o.didDocument.assertionMethod=[...c.map(h=>h.id)]),c=(o.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:o}})}catch(i){return Promise.reject(i)}},Es=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:iy,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:w}=bu(c);let v=null;const b=(function(){if(w!==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(Xa(t,{payload:r,header:i,signature:o,data:s},g,e)).then(function(y){v=y})}else{let g=0;return Yb(function(){return!m&&!v&&g<u.length},void 0,function(){function y(N){g++}const k=u[g],x=Zb(function(){return Promise.resolve(Xa(t,{payload:r,header:i,signature:o,data:s},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 b&&b.then?b.then(p):p(b)};if(!e.resolver)throw new Error("missing_resolver: No DID resolver has been configured");const{payload:r,header:i,signature:o,data:s}=Vi(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===ey||r.iss===ty){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===ny){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(Ru(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)}},Qb=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,o="";const s=Gb(r,function(a){const c=r[a],u={typ:"JWT",alg:c.alg};return a!==0&&(u.cty="JWT"),Promise.resolve(Iu(i,{...c,canonicalize:n,expiresIn:e},u)).then(function(h){o=h,i={jwt:o}})});return Promise.resolve(s&&s.then?s.then(function(){return o}):o)}catch(i){return Promise.reject(i)}},Iu=function(t,{issuer:e,signer:n,alg:r,expiresIn:i,canonicalize:o},s={}){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");s.typ||(s.typ="JWT"),s.alg||(s.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 Xb(c,n,s,{canonicalize:o})}catch(a){return Promise.reject(a)}},Xb=function(t,e,n={},r={}){try{n.alg||(n.alg=ry);const i=typeof t=="string"?t:tc(t,r.canonicalize),o=[tc(n,r.canonicalize),i].join("."),s=Lb(n.alg);return Promise.resolve(s(o,e)).then(function(a){return[o,a].join(".")})}catch(i){return Promise.reject(i)}},ey="https://self-issued.me/v2",ty="https://self-issued.me/v2/openid-vc",ny="https://self-issued.me",ry="ES256K",ec="application/did+json";function tc(t,e=!1){return Ja(e?ib(t):JSON.stringify(t))}const iy=300;function oy(t){const e=t.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(ku(e[1])),payload:e[2],signature:e[3],data:`${e[1]}.${e[2]}`};throw new Error("invalid_argument: Incorrect format JWS")}function Vi(t,e=!0){if(!t)throw new Error("invalid_argument: no JWT passed into decodeJWT");try{const n=oy(t),r=Object.assign(n,{payload:JSON.parse(ku(n.payload))}),i=r.payload.iss;if(r.header.cty==="JWT"&&e){const o=Vi(r.payload.jwt);if(o.payload.iss!==i)throw new Error(`${J.INVALID_JWT}: multiple issuers`);return o}return r}catch(n){throw new Error(`invalid_argument: ${J.INVALID_JWT}: ${n}`)}}function Ds({header:t,payload:e,data:n,signature:r},i){Array.isArray(i)||(i=[i]);const o=e.iss;let s=!0;do{if(o!==e.iss)throw new Error(`${J.INVALID_JWT}: multiple issuers`);try{return Ou(t.alg)(n,r,i)}catch(a){if(!a.message.startsWith(J.INVALID_SIGNATURE))throw a}t.cty!=="JWT"?s=!1:{payload:e,header:t,signature:r,data:n}=Vi(e.jwt,!1)}while(s);throw new Error(`${J.INVALID_SIGNATURE}: no matching public key found`)}typeof Symbol<"u"&&(Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")));var lo,nc;function sy(){if(nc)return lo;nc=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 lo=t,lo}var ho,rc;function ay(){if(rc)return ho;rc=1;function t(e,n){n||(n=e.reduce((o,s)=>o+s.length,0));const r=new Uint8Array(n);let i=0;for(const o of e)r.set(o,i),i+=o.length;return r}return ho=t,ho}var fo,ic;function cy(){if(ic)return fo;ic=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 fo=t,fo}const dy=Wi(sm);var po,oc;function Wu(){if(oc)return po;oc=1;const{bases:t}=dy;function e(o,s,a,c){return{name:o,prefix:s,encoder:{name:o,prefix:s,encode:a},decoder:{decode:c}}}const n=e("utf8","u",o=>"u"+new TextDecoder("utf8").decode(o),o=>new TextEncoder().encode(o.substring(1))),r=e("ascii","a",o=>{let s="a";for(let a=0;a<o.length;a++)s+=String.fromCharCode(o[a]);return s},o=>{o=o.substring(1);const s=new Uint8Array(o.length);for(let a=0;a<o.length;a++)s[a]=o.charCodeAt(a);return s});return po={utf8:n,"utf-8":n,hex:t.base16,latin1:r,ascii:r,binary:r,...t},po}var mo,sc;function uy(){if(sc)return mo;sc=1;const t=Wu();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 mo=e,mo}var wo,ac;function ly(){if(ac)return wo;ac=1;const t=Wu();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 wo=e,wo}var bo,cc;function hy(){if(cc)return bo;cc=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 bo=t,bo}var yo,dc;function fy(){if(dc)return yo;dc=1;const t=sy(),e=ay(),n=cy(),r=uy(),i=ly(),o=hy();return yo={compare:t,concat:e,equals:n,fromString:r,toString:i,xor:o},yo}var ri=fy(),go,uc;function py(){if(uc)return go;uc=1,go=r;var t=128,e=-128,n=Math.pow(2,31);function r(i,o,s){if(Number.MAX_SAFE_INTEGER&&i>Number.MAX_SAFE_INTEGER)throw r.bytes=0,new RangeError("Could not encode varint");o=o||[],s=s||0;for(var a=s;i>=n;)o[s++]=i&255|t,i/=128;for(;i&e;)o[s++]=i&255|t,i>>>=7;return o[s]=i|0,r.bytes=s-a+1,o}return go}var No,lc;function my(){if(lc)return No;lc=1,No=n;var t=128,e=127;function n(r,s){var o=0,s=s||0,a=0,c=s,u,h=r.length;do{if(c>=h||a>49)throw n.bytes=0,new RangeError("Could not decode varint");u=r[c++],o+=a<28?(u&e)<<a:(u&e)*Math.pow(2,a),a+=7}while(u>=t);return n.bytes=c-s,o}return No}var xo,hc;function wy(){if(hc)return xo;hc=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),o=Math.pow(2,42),s=Math.pow(2,49),a=Math.pow(2,56),c=Math.pow(2,63);return xo=function(u){return u<t?1:u<e?2:u<n?3:u<r?4:u<i?5:u<o?6:u<s?7:u<a?8:u<c?9:10},xo}var vo,fc;function ks(){return fc||(fc=1,vo={encode:py(),decode:my(),encodingLength:wy()}),vo}const by=Wi(bf),yy=Wi(cm),gy=Wi(am);var Eo,pc;function Mu(){if(pc)return Eo;pc=1;const t=ks(),{toString:e}=yy,{fromString:n}=gy;Eo={numberToUint8Array:i,uint8ArrayToNumber:r,varintUint8ArrayEncode:o,varintEncode:s};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 o(a){return Uint8Array.from(t.encode(r(a)))}function s(a){return Uint8Array.from(t.encode(a))}return Eo}var Do,mc;function Ny(){return mc||(mc=1,Do={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})}),Do}var ko,wc;function xy(){if(wc)return ko;wc=1;const{baseTable:t}=Ny(),e=Mu().varintEncode,n={},r={},i={};for(const s in t){const a=s,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 o=Object.freeze(t);return ko={nameToVarint:n,constantToCode:r,nameToCode:o,codeToName:i},ko}var So,bc;function vy(){if(bc)return So;bc=1;const t=ks(),{concat:e}=by,n=Mu(),{nameToVarint:r,constantToCode:i,nameToCode:o,codeToName:s}=xy();function a(x,N){let C;if(x instanceof Uint8Array)C=n.varintUint8ArrayEncode(x);else if(r[x])C=r[x];else throw new Error("multicodec not recognized");return e([C,N],C.length+N.length)}function c(x){return t.decode(x),x.slice(t.decode.bytes)}function u(x){const N=t.decode(x),C=s[N];if(C===void 0)throw new Error(`Code "${N}" not found`);return C}function h(x){return s[x]}function f(x){const N=o[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 w(x){return u(x)}function v(x){return h(x)}function b(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 So={addPrefix:a,rmPrefix:c,getNameFromData:u,getNameFromCode:h,getCodeFromName:f,getCodeFromData:l,getVarintFromName:m,getVarintFromCode:p,getCodec:w,getName:v,getNumber:b,getCode:g,getCodeVarint:y,getVarint:k,...i,nameToVarint:r,nameToCode:o,codeToName:s},So}var Ey=vy();const Dy=Xo(Ey);function ky(t,e){const n=new Uint8Array(t.length+1);return n[0]=2+(e[e.length-1]&1),n.set(t,1),n}function Sy(t){const e=t.slice(0,t.length/2),n=t.slice(t.length/2,t.length),r=ri.fromString(e,"base16"),i=ri.fromString(n,"base16"),o=ky(r,i);return ri.toString(o,"base16")}function Cy(t){return t.slice(2)}function Ay(t,e){const n=ri.fromString(e,"base16");return Oy(t,n)}function Oy(t,e){const n=Dy.addPrefix(t,e);return`did:key:${rt.encode(n)}`}function Lu(t=0){return new Uint8Array(t)}function Pu(t,e){e==null&&(e=t.reduce((i,o)=>i+o.length,0));const n=Lu(e);let r=0;for(const i of t)n.set(i,r),r+=i.length;return n}function Ty(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 Ry(t){return new TextEncoder().encode(t)}function Iy(t){return new TextDecoder().decode(t)}function Wy(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 o=t.charAt(i),s=o.charCodeAt(0);if(n[s]!==255)throw new TypeError(o+" is ambiguous");n[s]=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 w=0,v=0,b=0,g=p.length;b!==g&&p[b]===0;)b++,w++;for(var y=(g-b)*h+1>>>0,k=new Uint8Array(y);b!==g;){for(var x=p[b],N=0,C=y-1;(x!==0||N<v)&&C!==-1;C--,N++)x+=256*k[C]>>>0,k[C]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");v=N,b++}for(var S=y-v;S!==y&&k[S]===0;)S++;for(var A=c.repeat(w);S<y;++S)A+=t.charAt(k[S]);return A}function l(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var w=0;if(p[w]!==" "){for(var v=0,b=0;p[w]===c;)v++,w++;for(var g=(p.length-w)*u+1>>>0,y=new Uint8Array(g);p[w];){var k=n[p.charCodeAt(w)];if(k===255)return;for(var x=0,N=g-1;(k!==0||x<b)&&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");b=x,w++}if(p[w]!==" "){for(var C=g-b;C!==g&&y[C]===0;)C++;for(var S=new Uint8Array(v+(g-C)),A=v;C!==g;)S[A++]=y[C++];return S}}}function m(p){var w=l(p);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:l,decode:m}}var My=Wy,Ly=My;class Py{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 $y{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 $u(this,e)}}class By{decoders;constructor(e){this.decoders=e}or(e){return $u(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 $u(t,e){return new By({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}class Uy{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 Py(e,n,r),this.decoder=new $y(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function _i({name:t,prefix:e,encode:n,decode:r}){return new Uy(t,e,n,r)}function Wr({name:t,prefix:e,alphabet:n}){const{encode:r,decode:i}=Ly(n,t);return _i({prefix:e,name:t,encode:r,decode:o=>Ty(i(o))})}function qy(t,e,n,r){let i=t.length;for(;t[i-1]==="=";)--i;const o=new Uint8Array(i*n/8|0);let s=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,s+=n,s>=8&&(s-=8,o[c++]=255&a>>s)}if(s>=n||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return o}function Fy(t,e,n){const r=e[e.length-1]==="=",i=(1<<n)-1;let o="",s=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],s+=8;s>n;)s-=n,o+=e[i&a>>s];if(s!==0&&(o+=e[i&a<<n-s]),r)for(;(o.length*n&7)!==0;)o+="=";return o}function Vy(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=Vy(r);return _i({prefix:e,name:t,encode(o){return Fy(o,r,n)},decode(o){return qy(o,i,n,t)}})}const _y=Wr({prefix:"9",name:"base10",alphabet:"0123456789"}),jy=Object.freeze(Object.defineProperty({__proto__:null,base10:_y},Symbol.toStringTag,{value:"Module"})),Hy=Ne({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),zy=Ne({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Ky=Object.freeze(Object.defineProperty({__proto__:null,base16:Hy,base16upper:zy},Symbol.toStringTag,{value:"Module"})),Jy=Ne({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Gy=Object.freeze(Object.defineProperty({__proto__:null,base2:Jy},Symbol.toStringTag,{value:"Module"})),Bu=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Zy=Bu.reduce((t,e,n)=>(t[n]=e,t),[]),Yy=Bu.reduce((t,e,n)=>{const r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return t[r]=n,t},[]);function Qy(t){return t.reduce((e,n)=>(e+=Zy[n],e),"")}function Xy(t){const e=[];for(const n of t){const r=n.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${n}`);const i=Yy[r];if(i==null)throw new Error(`Non-base256emoji character: ${n}`);e.push(i)}return new Uint8Array(e)}const e0=_i({prefix:"🚀",name:"base256emoji",encode:Qy,decode:Xy}),t0=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:e0},Symbol.toStringTag,{value:"Module"})),n0=Ne({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),r0=Ne({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),i0=Ne({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),o0=Ne({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),s0=Ne({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),a0=Ne({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),c0=Ne({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),d0=Ne({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),u0=Ne({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),l0=Object.freeze(Object.defineProperty({__proto__:null,base32:n0,base32hex:s0,base32hexpad:c0,base32hexpadupper:d0,base32hexupper:a0,base32pad:i0,base32padupper:o0,base32upper:r0,base32z:u0},Symbol.toStringTag,{value:"Module"})),h0=Wr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),f0=Wr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),p0=Object.freeze(Object.defineProperty({__proto__:null,base36:h0,base36upper:f0},Symbol.toStringTag,{value:"Module"})),Uu=Wr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),m0=Wr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),w0=Object.freeze(Object.defineProperty({__proto__:null,base58btc:Uu,base58flickr:m0},Symbol.toStringTag,{value:"Module"})),b0=Ne({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),y0=Ne({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),g0=Ne({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),N0=Ne({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),x0=Object.freeze(Object.defineProperty({__proto__:null,base64:b0,base64pad:y0,base64url:g0,base64urlpad:N0},Symbol.toStringTag,{value:"Module"})),v0=Ne({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),E0=Object.freeze(Object.defineProperty({__proto__:null,base8:v0},Symbol.toStringTag,{value:"Module"})),D0=_i({prefix:"\0",name:"identity",encode:t=>Iy(t),decode:t=>Ry(t)}),k0=Object.freeze(Object.defineProperty({__proto__:null,identity:D0},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const yc={...k0,...Gy,...E0,...jy,...Ky,...l0,...p0,...w0,...x0,...t0};function qu(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const gc=qu("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Co=qu("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=Lu(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),Fu={utf8:gc,"utf-8":gc,hex:yc.base16,latin1:Co,ascii:Co,binary:Co,...yc};function S0(t,e="utf8"){const n=Fu[e];if(n==null)throw new Error(`Unsupported encoding "${e}"`);return n.decoder.decode(`${n.prefix}${t}`)}function ct(t,e="utf8"){const n=Fu[e];if(n==null)throw new Error(`Unsupported encoding "${e}"`);return n.encoder.encode(t).substring(1)}const C0={},U1=Object.freeze(Object.defineProperty({__proto__:null,default:C0},Symbol.toStringTag,{value:"Module"}));var A0=ks();const Nc=Xo(A0);function O0(t,e){const n=`did:key:${e}`,r=`${n}#${e}`;return{id:n,verificationMethod:[{id:r,type:"Secp256k1VerificationKey2018",controller:n,publicKeyBase58:ct(t,"base58btc")}],authentication:[r],assertionMethod:[r],capabilityDelegation:[r],capabilityInvocation:[r]}}const T0=Object.freeze(Object.defineProperty({__proto__:null,keyToDidDoc:O0},Symbol.toStringTag,{value:"Module"}));function R0(t){const e=new Uint8Array(t.length+2);return e[0]=236,e[1]=1,e.set(t,2),`z${ct(e,"base58btc")}`}function I0(t,e){const n=`did:key:${e}`,r=`${n}#${e}`,i=hw(t),o=`${n}#${R0(i)}`;return{id:n,verificationMethod:[{id:r,type:"Ed25519VerificationKey2018",controller:n,publicKeyBase58:ct(t,"base58btc")}],authentication:[r],assertionMethod:[r],capabilityDelegation:[r],capabilityInvocation:[r],keyAgreement:[{id:o,type:"X25519KeyAgreementKey2019",controller:n,publicKeyBase58:ct(i,"base58btc")}]}}const W0=Object.freeze(Object.defineProperty({__proto__:null,keyToDidDoc:I0},Symbol.toStringTag,{value:"Module"})),Pn=Lm;function M0(t,e){const n=`did:key:${e}`,r=`${n}#${e}`,i=fi.ProjectivePoint.fromHex(L0(t));return{id:n,verificationMethod:[{id:r,type:"JsonWebKey2020",controller:n,publicKeyJwk:{kty:"EC",crv:"P-256",x:ct(Pn(i.x),"base64url"),y:ct(Pn(i.y),"base64url")}}],authentication:[r],assertionMethod:[r],capabilityDelegation:[r],capabilityInvocation:[r]}}function L0(t){return t.length===64?Pu([new Uint8Array([4]),t]):t}const P0=Object.freeze(Object.defineProperty({__proto__:null,keyToDidDoc:M0},Symbol.toStringTag,{value:"Module"}));const $0=Lw;function B0(t,e){const n=`did:key:${e}`,r=`${n}#${e}`,i=$0.ProjectivePoint.fromHex(U0(t));return{id:n,verificationMethod:[{id:r,type:"JsonWebKey2020",controller:n,publicKeyJwk:{kty:"EC",crv:"P-384",x:ct(Pn(i.x),"base64url"),y:ct(Pn(i.y),"base64url")}}],authentication:[r],assertionMethod:[r],capabilityDelegation:[r],capabilityInvocation:[r]}}function U0(t){return t.length===96?Pu([new Uint8Array([4]),t]):t}const q0=Object.freeze(Object.defineProperty({__proto__:null,keyToDidDoc:B0},Symbol.toStringTag,{value:"Module"}));const F0=Pw;function V0(t,e){const n=`did:key:${e}`,r=`${n}#${e}`,i=F0.ProjectivePoint.fromHex(t);return{id:n,verificationMethod:[{id:r,type:"JsonWebKey2020",controller:n,publicKeyJwk:{kty:"EC",crv:"P-521",x:ct(Pn(i.x),"base64url"),y:ct(Pn(i.y),"base64url")}}],authentication:[r],assertionMethod:[r],capabilityDelegation:[r],capabilityInvocation:[r]}}const _0=Object.freeze(Object.defineProperty({__proto__:null,keyToDidDoc:V0},Symbol.toStringTag,{value:"Module"})),j0="application/did+ld+json",xc="application/did+json",H0={231:T0,237:W0,4608:P0,4609:q0,4610:_0};function z0(){return{key:async(t,e,n,r)=>{const i=r.accept||xc,o={didResolutionMetadata:{contentType:i},didDocument:null,didDocumentMetadata:{}};try{const s=Uu.decode(e.id),a=Nc.decode(s),c=s.slice(Nc.decode.bytes),u=await H0[a].keyToDidDoc(c,e.id);i===j0?(u["@context"]="https://w3id.org/did/v1",o.didDocument=u):i===xc?o.didDocument=u:(delete o.didResolutionMetadata.contentType,o.didResolutionMetadata.error="representationNotSupported")}catch(s){o.didResolutionMetadata.error="invalidDid",o.didResolutionMetadata.message=s.toString()}return o}}}const vc="ES256K",K0=/^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/,jo="https://www.w3.org/2018/credentials/v1",Ho="VerifiableCredential",J0="JwtProof2020",Vu=["evidence","termsOfUse","refreshService","credentialSchema","credentialStatus"];function je(t){return Array.isArray(t)?t:[t]}function vr(t){return Array.isArray(t)?t.map(e=>vr(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]=vr(t[n]),e),Object.create(Object.getPrototypeOf(t))):t}function wi(t){return t!=null}function G0(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 Z0(t){return typeof t=="object"&&t.sub&&t.iss&&t.claim&&t.iat}function Y0(t){const{iat:e,nbf:n,claim:r,vc:i,...o}=t,s={...o,nbf:n||e,vc:{"@context":[jo],type:[Ho],credentialSubject:r}};return i&&(t.issVc=i),s}function _u(t,e=!0){let n=vr(t);Z0(t)&&(n=Y0(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=G0({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=[...je(n.type),...je(n.vc?.type)].filter(wi);n.type=[...new Set(r)],e&&delete n.vc?.type;for(const o of Vu)t.vc&&t.vc[o]&&(n[o]||(n[o]=t.vc[o]),e&&delete n.vc[o]);const i=[...je(t.context),...je(t["@context"]),...je(t.vc?.["@context"])].filter(wi);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 Ec(t,e=!0){let n;try{n=Vi(t)}catch{throw new TypeError("unknown credential format")}return{..._u(n.payload,e),proof:{type:J0,jwt:t}}}function ju(t,e=!0){if(typeof t=="string"){if(K0.test(t))return Ec(t,e);{let n;try{n=JSON.parse(t)}catch{throw new TypeError("unknown credential format")}return ju(n,e)}}else return t.proof?.jwt?vr({...Ec(t.proof.jwt,e),proof:t.proof}):{proof:{},..._u(t,e)}}function Q0(t,e=!0){if(Array.isArray(t.credentialSubject))throw Error("credentialSubject of type array not supported");const n=vr({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=[...je(t.context),...je(t["@context"]),...je(t.vc?.["@context"])].filter(wi);n.vc["@context"]=[...new Set(i)],e&&(delete n.context,delete n["@context"]);const o=[...je(t.type),...je(t.vc?.type)].filter(wi);if(n.vc.type=[...new Set(o)],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 s=Date.parse(t.issuanceDate);isNaN(s)||(n.nbf=Math.floor(s/1e3),e&&delete n.issuanceDate)}if(t.expirationDate&&Object.getOwnPropertyNames(t).indexOf("exp")===-1){const s=Date.parse(t.expirationDate);isNaN(s)||(n.exp=Math.floor(s/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 s of Vu)t[s]&&(n.vc[s]||(n.vc[s]=t[s]),e&&delete n[s]);return n}const Er={SCHEMA_ERROR:"schema_error"};function X0(t){return t&&!isNaN(t)&&Object.prototype.toString.call(t)==="[object Date]"}function Dr(t){if(typeof t=="number"){if(!(Number.isInteger(t)&&t<1e11))throw new TypeError(`${Er.SCHEMA_ERROR}: "${t}" is not a unix timestamp in seconds`)}else if(typeof t=="string")Dr(Math.floor(new Date(t).valueOf()/1e3));else if(!X0(t))throw new TypeError(`${Er.SCHEMA_ERROR}: "${t}" is not a valid time`)}function Hu(t){const e=je(t);if(e.length<1||e.indexOf(jo)===-1)throw new TypeError(`${Er.SCHEMA_ERROR}: @context is missing default context "${jo}"`)}function zu(t){const e=je(t);if(e.length<1||e.indexOf(Ho)===-1)throw new TypeError(`${Er.SCHEMA_ERROR}: type is missing default "${Ho}"`)}function Ku(t){if(Object.keys(t).length===0)throw new TypeError(`${Er.SCHEMA_ERROR}: credentialSubject must not be empty`)}const eg=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(Es(t,{resolver:e,...n})).then(function(o){return o.verifiableCredential=ju(o.jwt,n?.removeOriginalFields),n?.policies?.format!==!1&&rg(o.verifiableCredential),o})}catch(r){return Promise.reject(r)}},tg=function(t,e,n={}){try{const r={iat:void 0,...Q0(t,n.removeOriginalFields)};if(ng(r),Array.isArray(e)){const i=e[0].did,o=[];for(const s of e){if(s.did!==i)throw new Error("All issuers must be the same did to comply with the Verifiable Conditions spec");o.push({issuer:s.did||r.iss||"",signer:s.signer,alg:s.alg||n.header?.alg||vc})}return Promise.resolve(Qb(r,{...n},o))}else return Promise.resolve(Iu(r,{...n,issuer:e.did||r.iss||"",signer:e.signer},{...n.header,alg:e.alg||n.header?.alg||vc}))}catch(r){return Promise.reject(r)}};function ng(t){Hu(t.vc["@context"]),zu(t.vc.type),Ku(t.vc.credentialSubject),t.nbf&&Dr(t.nbf),t.exp&&Dr(t.exp)}function rg(t){Hu(t["@context"]),zu(t.type),Ku(t.credentialSubject),t.issuanceDate&&Dr(t.issuanceDate),t.expirationDate&&Dr(t.expirationDate)}function ig(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 o=Number(r);if(isNaN(o))throw new Error(`Invalid chain id: ${r}`);return{chainId:o,networkId:n,address:i}}async function og(t){try{const e=parseInt(String(Date.now()/1e3)),n=await eg(t,sg(),{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 Ju(t,e,n,r,i){const o={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 tg(o,r,{expiresIn:i?.expiresIn})}const sg=()=>{const t=z0();if(!t)throw new Error("Failed to get key resolver");return new yb(t)};class Ze{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(Ze.#e);r.onupgradeneeded=this.#c,r.onsuccess=()=>this.#o(r.result,e,n),r.onerror=()=>n(r.error)})}#c=e=>{const n=e.target.result;this.#s(n)};#o=(e,n,r)=>{if(e.objectStoreNames.contains(Ze.#t))n(e);else{const i=e.version;e.close();const o=indexedDB.open(Ze.#e,i+1);o.onupgradeneeded=this.#c,o.onsuccess=()=>n(o.result),o.onerror=()=>r(o.error)}};#s(e){e.objectStoreNames.contains(Ze.#t)||e.createObjectStore(Ze.#t)}async#a(e="readwrite"){return(await this.#r).transaction(Ze.#t,e).objectStore(Ze.#t)}async saveKeyPair(e){const r=(await this.#a()).put(e,Ze.#n);return new Promise((i,o)=>{r.onsuccess=()=>{i()},r.onerror=()=>{o(new Error("Failed to save key pair"))}})}async loadKeyPair(){const n=(await this.#a("readonly")).get(Ze.#n);return new Promise((r,i)=>{n.onsuccess=()=>{const o=n.result;r(o)},n.onerror=()=>{i(new Error("Failed to load key pair"))}})}}const ag="eip155",cg=1;function dg(t){return Array.prototype.map.call(new Uint8Array(t),e=>("00"+e.toString(16)).slice(-2)).join("")}class kn{#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.#s(),await this.#n.saveKeyPair(await this.#a())),await this.#o()}async getBearerToken(e,n,r=!1,i){const o=await this.getIssuer();if((r||!this.#i)&&(this.#i=await Ju(Number(cg),ag,n||await this.#r,o,i)),!this.#i)throw new Error("Could not create bearer token");return this.#i}did(){return this.#r}async regenerateDid(){this.#t=await this.#s(),await this.#n.saveKeyPair(await this.#a())}async#o(){if(!this.#t)throw new Error("No key pair available");const e=await this.#e.exportKey("raw",this.#t.publicKey),n="p256-pub",r=Cy(dg(e)),i=Sy(r);return Ay(n,i)}async#s(){return await this.#e.generateKey(kn.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,kn.algorithm,!0,["verify"]),privateKey:await this.#e.importKey("jwk",e.privateKey,kn.algorithm,!0,["sign"])}}#u=async(...e)=>await this.#e.sign(...e);#p=async(...e)=>await this.#e.verify(...e);#h(e){return S0(e,"utf-8")}async sign(e){if(this.#t?.privateKey){const n=typeof e=="string"?this.#h(e):e,r=await this.#e.sign(kn.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 Ns(n)},alg:"ES256"}}}const ug="https://www.renown.id";class lg{#e;#t;#n;#r;constructor(e,n,r,i=ug){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=ig(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),o=await fetch(i,{method:"GET"});if(o.ok)return(await o.json()).credential;throw new Error("Failed to get credential")}async verifyBearerToken(e){return og(e)}async createBearerToken(e,n,r,i){if(!this.user)throw new Error("User not found");return Ju(n,this.#n,e,r,i)}}class Dc extends CustomEvent{constructor(e,n){super(e,{detail:n})}}class hg{#e=new EventTarget;on(e,n){const r=i=>{i instanceof Dc&&n(i.detail)};return this.#e.addEventListener(e.toString(),r),()=>{this.#e.removeEventListener(e.toString(),r)}}emit(e,n){const r=new Dc(e.toString(),n);this.#e.dispatchEvent(r)}}class fg{namespace;constructor(e){this.namespace=e}}class pg extends fg{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 q1(t,e,n){return new lg(new pg("renown",e),new hg,t,n)}const Ss=I("drives"),Gu=Ss.useValue,Zu=Ss.setValue,mg=Ss.addEventHandler;function wg(t){return t.reduce((e,n)=>(n.status==="fulfilled"?e.push(n.value):console.warn(n.reason),e),[])}function F1(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 V1(t){if(!t)return!1;const e="readContext"in t,{availableOffline:n}=e?{availableOffline:!1}:t.state.local;return n??!1}async function bg(t){if(!t)return[];const e=await t.getDrives(),n=await Promise.allSettled(e.map(r=>t.getDrive(r)));return wg(n)}function _1(t,e){if(e==="LOCAL")return;if(Mi()){const r=window.ph?.legacyReactor;if(!r)return;try{const i=r.getSyncStatus(t);return i instanceof vh?"INITIAL_SYNC":i}catch(i){return console.error(i),"ERROR"}}else return}function yg(t){return t?.state.local.triggers.find(e=>e.type==="PullResponder")}function Yu(t){return yg(t)?.data?.url}function Qu(t){if(!t)return;const e=Yu(t);if("remoteUrl"in t.state.global){const n=t.state.global.remoteUrl;if(typeof n=="string")return n}return e}function gg(t){const e=Qu(t),n=Yu(t);return e!==void 0||n!==void 0}const j1=(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"}}}},Xu=200,el=1e3;async function kc(t){if(!t)return;const e=await bg(t);Zu(e)}async function Sc(t){if(!t)return;const e=await t.find({type:"powerhouse/document-drive"});Zu(e.results)}function Ng(t=Xu,e=el){let n=null,r=0;return(i,o=!1)=>{const s=Date.now(),a=s-r;return n!==null&&clearTimeout(n),o||a>=e?(r=s,kc(i)):new Promise(c=>{n=setTimeout(()=>{r=Date.now(),kc(i).then(c)},t)})}}function xg(t=Xu,e=el){let n=null,r=0;return(i,o=!1)=>{const s=Date.now(),a=s-r;return n!==null&&clearTimeout(n),o||a>=e?(r=s,Sc(i)):new Promise(c=>{n=setTimeout(()=>{r=Date.now(),Sc(i).then(c)},t)})}}const H1=Ng(),z1=xg();async function K1(t,e,n){await vg(t,e,n);const i=(await t.initialize())?.at(0);if(i)throw i}async function vg(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 J1(){const t=new kn(new Ze);return await t.did(),t}function tl(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}),tl(t)}}function G1(t){const e=new Map;return t.on("documentDeleted",n=>{e.delete(n)}),{get(n,r){const i=e.get(n);if(i&&(tl(i).status==="pending"||!r))return i;const o=t.getDocument(n);return e.set(n,o),o},subscribe(n,r){const i=Array.isArray(n)?n:[n];return t.on("operationsAdded",o=>{i.includes(o)&&this.get(o,!0).then(()=>r()).catch(()=>{console.warn("Failed to refetch document",o)})})}}}const Cs=I("documentCache"),Eg=Cs.useValue,Z1=Cs.setValue,Dg=Cs.addEventHandler;function kg(t){const e=Eg(),n=Ht.useSyncExternalStore(r=>t&&e?e.subscribe(t,r):()=>{},()=>t?e?.get(t):void 0);return n?Ht.use(n):void 0}function nl(t){const e=kg(t),[,n]=os(e);return[e,n]}let ii;typeof window<"u"?window.btoa?ii=function(t){return btoa(unescape(encodeURIComponent(t)))}:ii=function(t){const e=unescape(encodeURIComponent(t+""));let n="";for(let r,i,o=0,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";e.charAt(o|0)||(s="=",o%1);n+=s.charAt(63&r>>8-o%1*8)){if(i=e.charCodeAt(o+=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}:ii=function(t){return Buffer.from(t).toString("base64")};function Z(t,e){let n=Cc(t,e);return(e&&e.fallback!==void 0?e.fallback:Z.defaults.fallback)===!0&&n===""&&(n=Cc(ii(t),e)),n}const rl={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 As={};function Cc(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=rl[e.locale]||As;let o=[];for(const c in e.multicharmap){if(!Object.prototype.hasOwnProperty.call(e.multicharmap,c))continue;const u=c.length;o.indexOf(u)===-1&&o.push(u)}o=o.sort(function(c,u){return u-c});const s=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<o.length;l++){const m=o[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(s,"")),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 il={फ़:"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"},ol={À:"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({},ol);Z.multicharmap=Object.assign({},il);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({},ol),Z.defaults.modes.rfc3986.multicharmap=Z.defaults.modes.pretty.multicharmap=Z.multicharmap=Z.defaults.multicharmap=Object.assign({},il),As=""};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){As=rl[t]||{}};function bi(t){return new URL(t.replace(/^\/+/,""),window.location.origin+(window.ph?.basePath??"/")).pathname}function sl(t){const e=window.ph?.basePath??"/";return t.replace(e,e.endsWith("/")?"/":"")}function Sg(t){if(!t)return"";const e=t.name;return Z(e?`${e}-${t.id}`:t.id)}function Cg(t){const e=sl(t);return/^\/d\/[^/]+\/([^/]+)$/.exec(e)?.[1]}function al(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 Ag(t){return al(t)}function cl(t){const e=sl(t);return/^\/d\/([^/]+)/.exec(e)?.[1]??""}function Og(t){return al(t)}function Tg(t){const e=cl(t);return Og(e)}const Os=I("selectedDriveId"),dl=Os.useValue,Rg=Os.setValue,Ig=Os.addEventHandler;function Wg(){const t=Ts();if(!t[0])throw new Error("There is no drive selected. Did you mean to call 'useSelectedDriveSafe'?");return t}function Ts(){const t=dl(),n=Gu()?.find(o=>o.header.id===t),[r,i]=os(n);return n?[r,i]:[void 0,void 0]}function Mg(t){const e=typeof t=="string"?t:t?.header.slug,r=window.ph?.drives?.find(o=>o.header.slug===e)?.header.id;if(Rg(r),!r){const o=bi("/");if(o===window.location.pathname)return;window.history.pushState(null,"",o);return}const i=bi(`/d/${e}`);i!==window.location.pathname&&window.history.pushState(null,"",i)}function Lg(){window.addEventListener("popstate",()=>{const t=window.location.pathname,e=Tg(t),n=window.ph?.selectedDriveId;e!==n&&Mg(e)})}function Mr(){const[t]=Ts();return t?.state.global.nodes}function Pg(){return Mr()?.filter(e=>ad(e))}const Rs=I("selectedNodeId"),$g=Rs.useValue,ul=Rs.setValue,Bg=Rs.addEventHandler;function Lr(){const t=$g();return Mr()?.find(n=>n.id===t)}function ll(t){const e=typeof t=="string"?t:Sg(t),n=Ag(e);ul(n);const r=cl(window.location.pathname);if(!r)return;if(!e){const o=bi(`/d/${r}`);if(o===window.location.pathname)return;window.history.pushState(null,"",o);return}const i=bi(`/d/${r}/${e}`);i!==window.location.pathname&&window.history.pushState(null,"",i)}function Ug(){window.addEventListener("ph:selectedDriveIdUpdated",()=>{ul(void 0)})}function qg(){window.addEventListener("popstate",()=>{const t=window.location.pathname,e=Cg(t),n=window.ph?.selectedNodeId;e!==n&&ll(e)})}function Is(){const t=Lr();if(ad(t))return t}function Y1(){const t=Mr(),n=Is()?.id;return t?la(n?t.filter(r=>r.parentFolder===n):t.filter(r=>!r.parentFolder)):[]}const{setValue:Fg,addEventHandler:Vg}=I("routerBasename"),{setValue:_g,addEventHandler:jg}=I("version"),{setValue:Hg,addEventHandler:zg}=I("requiresHardRefresh"),{setValue:Kg,addEventHandler:Jg}=I("warnOutdatedApp"),{setValue:Gg,addEventHandler:Zg}=I("studioMode"),{setValue:Yg,addEventHandler:Qg}=I("basePath"),{setValue:Xg,addEventHandler:eN}=I("versionCheckInterval"),{setValue:tN,addEventHandler:nN}=I("cliVersion"),{setValue:rN,addEventHandler:iN}=I("fileUploadOperationsChunkSize"),{setValue:oN,addEventHandler:sN}=I("isDocumentModelSelectionSettingsEnabled"),{setValue:aN,addEventHandler:cN}=I("gaTrackingId"),{setValue:dN,addEventHandler:uN}=I("defaultDrivesUrl"),{setValue:lN,addEventHandler:hN}=I("drivesPreserveStrategy"),{setValue:fN,addEventHandler:pN}=I("isLocalDrivesEnabled"),{setValue:mN,addEventHandler:wN}=I("isAddDriveEnabled"),{setValue:bN,addEventHandler:yN}=I("isPublicDrivesEnabled"),{setValue:gN,addEventHandler:NN}=I("isAddPublicDrivesEnabled"),{setValue:xN,addEventHandler:vN}=I("isDeletePublicDrivesEnabled"),{setValue:EN,addEventHandler:DN}=I("isCloudDrivesEnabled"),{setValue:kN,addEventHandler:SN}=I("isAddCloudDrivesEnabled"),{setValue:CN,addEventHandler:AN}=I("isDeleteCloudDrivesEnabled");I("isLocalDrivesEnabled");const{setValue:ON,addEventHandler:TN}=I("isAddLocalDrivesEnabled"),{setValue:RN,addEventHandler:IN}=I("isDeleteLocalDrivesEnabled"),{setValue:WN,addEventHandler:MN}=I("isEditorDebugModeEnabled"),{setValue:LN,addEventHandler:PN}=I("isEditorReadModeEnabled"),{setValue:$N,addEventHandler:BN}=I("isAnalyticsDatabaseWorkerEnabled"),{setValue:UN,addEventHandler:qN}=I("isDiffAnalyticsEnabled"),{setValue:FN,addEventHandler:VN}=I("isDriveAnalyticsEnabled"),{setValue:_N,addEventHandler:jN}=I("renownUrl"),{setValue:HN,addEventHandler:zN}=I("renownNetworkId"),{setValue:KN,addEventHandler:JN}=I("renownChainId"),{setValue:GN,addEventHandler:ZN}=I("sentryRelease"),{setValue:YN,addEventHandler:QN}=I("sentryDsn"),{setValue:XN,addEventHandler:e2}=I("sentryEnv"),{setValue:t2,addEventHandler:n2}=I("isSentryTracingEnabled"),{setValue:r2,addEventHandler:i2}=I("isExternalProcessorsEnabled"),{setValue:o2,addEventHandler:s2}=I("isExternalPackagesEnabled"),hl=I("enabledEditors"),a2=hl.setValue,c2=hl.addEventHandler,fl=I("disabledEditors"),d2=fl.setValue,u2=fl.addEventHandler,pl=I("isRelationalProcessorsEnabled"),l2=pl.setValue,h2=pl.addEventHandler,ml=I("isExternalRelationalProcessorsEnabled"),f2=ml.setValue,p2=ml.addEventHandler,wl=I("isAnalyticsEnabled"),m2=wl.setValue,w2=wl.addEventHandler,bl=I("isAnalyticsExternalProcessorsEnabled"),b2=bl.setValue,y2=bl.addEventHandler,yl=I("analyticsDatabaseName"),g2=yl.setValue,N2=yl.addEventHandler,gl=I("logLevel"),x2=gl.setValue,v2=gl.addEventHandler,Ws=I("allowList"),E2=Ws.setValue,D2=Ws.useValue,k2=Ws.addEventHandler,S2={routerBasename:Fg,version:_g,requiresHardRefresh:Hg,warnOutdatedApp:Kg,studioMode:Gg,basePath:Yg,versionCheckInterval:Xg,cliVersion:tN,fileUploadOperationsChunkSize:rN,isDocumentModelSelectionSettingsEnabled:oN,gaTrackingId:aN,defaultDrivesUrl:dN,drivesPreserveStrategy:lN,isLocalDrivesEnabled:fN,isAddDriveEnabled:mN,isPublicDrivesEnabled:bN,isAddPublicDrivesEnabled:gN,isDeletePublicDrivesEnabled:xN,isCloudDrivesEnabled:EN,isAddCloudDrivesEnabled:kN,isDeleteCloudDrivesEnabled:CN,isAddLocalDrivesEnabled:ON,isDeleteLocalDrivesEnabled:RN,isEditorDebugModeEnabled:WN,isEditorReadModeEnabled:LN,isRelationalProcessorsEnabled:l2,isExternalRelationalProcessorsEnabled:f2,isAnalyticsEnabled:m2,analyticsDatabaseName:g2,isAnalyticsExternalProcessorsEnabled:b2,isAnalyticsDatabaseWorkerEnabled:$N,isDiffAnalyticsEnabled:UN,isDriveAnalyticsEnabled:FN,renownUrl:_N,renownNetworkId:HN,renownChainId:KN,sentryRelease:GN,sentryDsn:YN,sentryEnv:XN,isSentryTracingEnabled:t2,isExternalProcessorsEnabled:r2,isExternalPackagesEnabled:o2,allowList:E2,logLevel:x2,disabledEditors:d2,enabledEditors:a2},C2={...ff,...pf,...S2};function Ms(t,e){const n=C2[t];n(e)}function Q1(t){for(const e of Object.keys(t))Ms(e,t[e])}function A2(t){for(const e of Object.keys(t))Ms(e,t[e])}function O2(t){for(const e of Object.keys(t))Ms(e,t[e])}function X1(t){const[e,n]=Ht.useState(!1);Ht.useEffect(()=>{e||(A2(t),n(!0))},[t,e])}function eE(t){const[e,n]=Ht.useState(!1);Ht.useEffect(()=>{e||(O2(t),n(!0))},[t,e])}function T2(t,e){const[n,r]=nl(t),i=wf(e);if(!t||!e)return[];if(!n)throw new Eh(t);if(!i)throw new Dh(e);if(n.header.documentType!==e)throw new jh(t,e,n.header.documentType);return[n,r]}function R2(){return sd()?.map(e=>e.documentModel.global.id)}function I2(){const t=lf(),e=R2();return t??e}function tE(t){const n=Gu()?.find(o=>o.header.id===t),[r,i]=os(n);if(!n)throw new Error(`Drive with id ${t} not found`);return[r,i]}function Nl(){return is()?.flatMap(e=>e.modules.editorModules||[]).filter(e=>!e.documentTypes.includes("powerhouse/document-drive"))}function W2(){return is()?.flatMap(e=>e.modules.editorModules||[]).filter(e=>e.documentTypes.includes("powerhouse/document-drive"))}function nE(t){const e=Nl();return!t||e?.length===0?void 0:e?.filter(r=>r.documentTypes.includes(t))?.[0]}function M2(t){return W2()?.find(n=>n.id===t)}function rE(){return M2(of)}function iE(t){return Nl()?.find(n=>n.id===t)}function xl(t){return Pg()?.find(n=>n.id===t)}const Ls=I("modal"),oE=Ls.useValue,ji=Ls.setValue,L2=Ls.addEventHandler;function P2(t){ji(t)}function sE(){ji(void 0)}function aE(t){ji({type:"createDocument",documentType:t})}function cE(t){const e=typeof t=="string"?t:t.id;ji({type:"deleteItem",id:e})}function nt(t,e){return e?.id!==t?e:void 0}function dE(){const[t]=Ts(),e=Is(),n=Lr(),r=xl(n?.parentFolder),i=t?.header.id;async function o(l,m){if(!i)return;const p=l.name.replace(/\..+/gim,"");return Yh(l,i,p,nt(i,m)?.id)}async function s(l,m){if(i)return Xh(i,l,nt(i,m)?.id)}async function a(l,m){if(!i)return;if(!nt(i,m)){console.error(`Node ${m.id} not found`);return}return await tf(i,m.id,l)}async function c(l,m){if(!i)return;const p=nt(i,l);if(!p){console.error(`Node ${l.id} not found`);return}const w=nt(i,m);await ua(i,p,w)}async function u(l,m){if(!i)return;const p=nt(i,l);if(!p){console.error(`Node ${l.id} not found`);return}const w=nt(i,m);!w?.id&&!l.parentFolder||w?.id===l.parentFolder||await nf(i,p,w)}async function h(l){if(!i)return;const m=nt(i,l);if(!m){console.error(`Node ${l.id} not found`);return}const p=nt(i,e??r);await ua(i,m,p)}async function f(l){if(!l||!i)return;const m=nt(i,e??r);if(!m)return;const p=await s(l,m);p&&ll(p)}return{onAddFile:o,onAddFolder:s,onRenameNode:a,onCopyNode:c,onMoveNode:u,onDuplicateNode:h,onAddAndSelectNewFolder:f}}function $2(t){return Mr()?.find(n=>n.id===t)}function B2(t){const e=Mr();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 uE(){const t=Lr();return B2(t?.id)}function U2(t){const e=$2(t);return xl(e?.parentFolder)}function lE(){const t=Lr();return U2(t?.id)}const Ps=I("revisionHistoryVisible"),hE=Ps.useValue,q2=Ps.setValue,F2=Ps.addEventHandler;function fE(){q2(!0)}function vl(){const t=Lr();return t&&lr(t)?t.id:void 0}function pE(){const t=vl();return nl(t)}function mE(t){const e=vl();if(!e)throw new Hh;return T2(e,t)}const $s=I("selectedTimelineItem"),wE=$s.useValue,bE=$s.setValue,V2=$s.addEventHandler,_2=I("selectedTimelineRevision"),j2=_2.addEventHandler,H2=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,...Ih(r.state[u].initialValue,u!=="global").map(h=>({...h,message:`${h.message}. Scope: ${u}`,details:{...h.details,scope:u}}))]},[]),o=Object.keys(r.state).reduce((a,c)=>{const u=c,h=u==="global";return[...a,...Wh(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}}))]},[]),s=Mh(r.modules);return[...i,...o,...s]},yE=t=>{if(!t)return;if(H2(t).length)P2({type:"exportDocumentWithErrors",documentId:t.header.id});else return Zh(t)},gE=(t,e,n=[])=>{if(!t||!e)return 0;const r=n.find(i=>{const o=new Date(i.timestampUtcMs);return o>=t&&o<=e});return r?r.index:0};var Ao={exports:{}},Ac;function z2(){return Ac||(Ac=1,(function(t){var e=(function(){var n=String.fromCharCode,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",o={};function s(c,u){if(!o[c]){o[c]={};for(var h=0;h<c.length;h++)o[c][c.charAt(h)]=h}return o[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 s(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 s(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={},w="",v="",b="",g=2,y=3,k=2,x=[],N=0,C=0,S;for(S=0;S<c.length;S+=1)if(w=c.charAt(S),Object.prototype.hasOwnProperty.call(m,w)||(m[w]=y++,p[w]=!0),v=b+w,Object.prototype.hasOwnProperty.call(m,v))b=v;else{if(Object.prototype.hasOwnProperty.call(p,b)){if(b.charCodeAt(0)<256){for(f=0;f<k;f++)N=N<<1,C==u-1?(C=0,x.push(h(N)),N=0):C++;for(l=b.charCodeAt(0),f=0;f<8;f++)N=N<<1|l&1,C==u-1?(C=0,x.push(h(N)),N=0):C++,l=l>>1}else{for(l=1,f=0;f<k;f++)N=N<<1|l,C==u-1?(C=0,x.push(h(N)),N=0):C++,l=0;for(l=b.charCodeAt(0),f=0;f<16;f++)N=N<<1|l&1,C==u-1?(C=0,x.push(h(N)),N=0):C++,l=l>>1}g--,g==0&&(g=Math.pow(2,k),k++),delete p[b]}else for(l=m[b],f=0;f<k;f++)N=N<<1|l&1,C==u-1?(C=0,x.push(h(N)),N=0):C++,l=l>>1;g--,g==0&&(g=Math.pow(2,k),k++),m[v]=y++,b=String(w)}if(b!==""){if(Object.prototype.hasOwnProperty.call(p,b)){if(b.charCodeAt(0)<256){for(f=0;f<k;f++)N=N<<1,C==u-1?(C=0,x.push(h(N)),N=0):C++;for(l=b.charCodeAt(0),f=0;f<8;f++)N=N<<1|l&1,C==u-1?(C=0,x.push(h(N)),N=0):C++,l=l>>1}else{for(l=1,f=0;f<k;f++)N=N<<1|l,C==u-1?(C=0,x.push(h(N)),N=0):C++,l=0;for(l=b.charCodeAt(0),f=0;f<16;f++)N=N<<1|l&1,C==u-1?(C=0,x.push(h(N)),N=0):C++,l=l>>1}g--,g==0&&(g=Math.pow(2,k),k++),delete p[b]}else for(l=m[b],f=0;f<k;f++)N=N<<1|l&1,C==u-1?(C=0,x.push(h(N)),N=0):C++,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,C==u-1?(C=0,x.push(h(N)),N=0):C++,l=l>>1;for(;;)if(N=N<<1,C==u-1){x.push(h(N));break}else C++;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,w="",v=[],b,g,y,k,x,N,C,S={val:h(0),position:u,index:1};for(b=0;b<3;b+=1)f[b]=b;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;C=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;C=n(y);break;case 2:return""}for(f[3]=C,g=C,v.push(C);;){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(C=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),C=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),C=m-1,l--;break;case 2:return v.join("")}if(l==0&&(l=Math.pow(2,p),p++),f[C])w=f[C];else if(C===m)w=g+g.charAt(0);else return null;v.push(w),f[m++]=g+w.charAt(0),l--,g=w,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})})(Ao)),Ao.exports}var K2=z2();function J2(t){return t.split("/").pop()}function G2(){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 Z2(t,e,n){const r=J2(t),i=G2(),o={documentId:e,driveId:r},s=n?{Authorization:`Bearer ${n}`}:void 0,a={document:i.trim(),variables:JSON.stringify(o,null,2)};return s&&(a.headers=JSON.stringify(s)),K2.compressToEncodedURIComponent(JSON.stringify(a))}function Y2(t,e,n){const r=Z2(t,e,n);return`${t}?explorerURLState=${r}`}function NE(t){return{id:et(),name:t.manifest.name,description:t.manifest.description,category:t.manifest.category,author:{name:"Powerhouse",website:"https://powerhousedao.com"},modules:{documentModelModules:t.documentModels.map(Q2),editorModules:t.editors.map(r=>X2(r,t.manifest))}}}function Q2(t){const e=t.documentModel.global,n=e.name,r=e.id,i=r,o=e.extension,s=e.specifications,a=t.reducer,c=t.actions,u=t.utils;return{id:i,name:n,documentType:r,extension:o,documentModel:Lh(Ph(),e),specifications:s,reducer:a,actions:c,utils:u}}function X2(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(" "),o=n||t.config.name||i,s=t.documentTypes,a=t.Component;return{id:r,name:o,documentTypes:s,Component:a}}function xE(t){const{id:e,name:n,description:r,category:i,author:o,modules:s}=t;return{id:e,name:n,description:r,category:i,author:o,modules:ex(s)}}function ex(t){return Object.entries(t).reduce((e,[n,r])=>(e[n]=r.map(i=>({id:i.id,name:i.name})),e),{})}const Bs=I("connectCrypto"),tx=Bs.useValue,vE=Bs.setValue,nx=Bs.addEventHandler,{setValue:EE,addEventHandler:rx}=I("did"),{addEventHandler:ix}=I("loading"),{setValue:vn,addEventHandler:ox}=I("loginStatus"),El=I("processorManager"),DE=El.setValue,sx=El.addEventHandler,Us=I("legacyReactor"),Dl=I("reactorClient"),kl=I("sync"),kE=Us.useValue,SE=Us.setValue,ax=Us.addEventHandler,CE=Dl.setValue,cx=Dl.addEventHandler,AE=kl.setValue,dx=kl.addEventHandler,Sl=I("renown"),OE=Sl.setValue,ux=Sl.addEventHandler,qs=I("user"),Cl=qs.useValue,Oc=qs.setValue,lx=qs.addEventHandler,hx={loading:ix,legacyReactor:ax,reactorClient:cx,sync:dx,features:$h,modal:L2,connectCrypto:nx,did:rx,renown:ux,loginStatus:ox,user:lx,processorManager:sx,drives:mg,documentCache:Dg,selectedDriveId:()=>{Ig(),Lg(),Ug()},selectedNodeId:()=>{Bg(),qg()},vetraPackages:mf,selectedTimelineRevision:j2,revisionHistoryVisible:F2,selectedTimelineItem:V2,routerBasename:Vg,version:jg,logLevel:v2,requiresHardRefresh:zg,warnOutdatedApp:Jg,studioMode:Zg,basePath:Qg,versionCheckInterval:eN,cliVersion:nN,fileUploadOperationsChunkSize:iN,isDocumentModelSelectionSettingsEnabled:sN,gaTrackingId:cN,allowList:k2,defaultDrivesUrl:uN,drivesPreserveStrategy:hN,allowedDocumentTypes:hf,enabledEditors:c2,disabledEditors:u2,isAddDriveEnabled:wN,isLocalDrivesEnabled:pN,isPublicDrivesEnabled:yN,isAddPublicDrivesEnabled:NN,isDeletePublicDrivesEnabled:vN,isCloudDrivesEnabled:DN,isAddCloudDrivesEnabled:SN,isDeleteCloudDrivesEnabled:AN,isAddLocalDrivesEnabled:TN,isDeleteLocalDrivesEnabled:IN,isDragAndDropEnabled:df,isExternalControlsEnabled:af,isEditorDebugModeEnabled:MN,isEditorReadModeEnabled:PN,isRelationalProcessorsEnabled:h2,isExternalRelationalProcessorsEnabled:p2,isAnalyticsEnabled:w2,isAnalyticsExternalProcessorsEnabled:y2,analyticsDatabaseName:N2,isAnalyticsDatabaseWorkerEnabled:BN,isDiffAnalyticsEnabled:qN,isDriveAnalyticsEnabled:VN,renownUrl:jN,renownNetworkId:zN,renownChainId:JN,sentryRelease:ZN,sentryDsn:QN,sentryEnv:e2,isSentryTracingEnabled:n2,isExternalProcessorsEnabled:i2,isExternalPackagesEnabled:s2};function TE(){for(const t of Object.values(hx))t()}function RE(t){const[e]=Wg(),n=gg(e),r=Qu(e),i=tx(),o=Cl();return Ht.useMemo(()=>!n||!t?.header.id||!r?null:async()=>{const s=o?.address?await i?.getBearerToken(r,o.address,!1,{expiresIn:600}):void 0;return Y2(r,t.header.id,s)},[n,r,t,o,i])}const IE=t=>{const e=dl(),n=Is(),r=I2();return async(o,s,a)=>{if(!e){console.warn("No selected drive - upload skipped");return}const c=o.name.replace(/\..+/gim,""),u=n?.id;return await Qh(o,e,c,u,s,r,a)}};function WE(){const t=Cl(),e=D2();return e?{isAllowedToCreateDocuments:e.includes(t?.address??""),isAllowedToEditDocuments:e.includes(t?.address??"")}:{isAllowedToCreateDocuments:!0,isAllowedToEditDocuments:!0}}function jt(t){return typeof t>"u"||t===void 0}function Ce(t){return typeof t=="string"}function Hi(t){return typeof t=="number"}function yi(t){return typeof t=="boolean"}function Fs(t){return t===null}function fx(t){return t instanceof Date}function Vs(t){return typeof t=="bigint"}function Ve(t){return typeof t=="function"}function He(t){return typeof t=="object"&&t!==null}function px(t){return t[t.length-1]}function d(t){return Object.freeze(t)}function Yr(t){return Dt(t)?t:[t]}function Dt(t){return Array.isArray(t)}function Be(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})}}),pt=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]})}}),Al=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})}}),mx=["preserve rows","delete rows","drop"],Me=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})}}),kt=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)})}}),Qn=d({is(t){return t.kind==="DropIndexNode"},create(t,e){return d({kind:"DropIndexNode",name:kt.create(t),...e})},cloneWith(t,e){return d({...t,...e})}}),zo=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})}}),Ko=d({is(t){return t.kind==="DropTableNode"},create(t,e){return d({kind:"DropTableNode",table:t,...e})},cloneWith(t,e){return d({...t,...e})}}),Ct=d({is(t){return t.kind==="AliasNode"},create(t,e){return d({kind:"AliasNode",node:t,alias:e})}}),xt=d({is(t){return t.kind==="TableNode"},create(t){return d({kind:"TableNode",table:kt.create(t)})},createWithSchema(t,e){return d({kind:"TableNode",table:kt.createWithSchema(t,e)})}});function Ae(t){return He(t)&&Ve(t.toOperationNode)}function Ol(t){return He(t)&&"expressionType"in t&&Ae(t)}function wx(t){return He(t)&&"expression"in t&&Ce(t.alias)&&Ae(t)}const ft=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})}}),zt=d({is(t){return t.kind==="AndNode"},create(t,e){return d({kind:"AndNode",left:t,right:e})}}),Un=d({is(t){return t.kind==="OrNode"},create(t,e){return d({kind:"OrNode",left:t,right:e})}}),Oo=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"?zt.create(t.on,n):Un.create(t.on,n)})}}),cn=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:Oo.create(n)})},cloneWithOn(t,e){return d({...t,on:t.on?Oo.cloneWithOperation(t.on,"And",e):Oo.create(e)})}}),$n=d({is(t){return t.kind==="BinaryOperationNode"},create(t,e,n){return d({kind:"BinaryOperationNode",leftOperand:t,operator:e,rightOperand:n})}}),bx=["=","==","!=","<>",">",">=","<","<=","in","not in","is","is not","like","not like","match","ilike","not ilike","@>","<@","^@","&&","?","?&","?|","!<","!>","<=>","!~","~","~*","!~*","@@","@@@","!!","<->","regexp","is distinct from","is not distinct from"],yx=["+","-","*","/","%","^","&","|","#","<<",">>"],Tl=["->","->>"],gx=[...bx,...yx,"&&","||"],Nx=["exists","not exists"],xx=["not","-",...Nx],vx=[...gx,...Tl,...xx,"between","between symmetric"],Kt=d({is(t){return t.kind==="OperatorNode"},create(t){return d({kind:"OperatorNode",operator:t})}});function Tc(t){return Ce(t)&&Tl.includes(t)}const ue=d({is(t){return t.kind==="ColumnNode"},create(t){return d({kind:"ColumnNode",column:G.create(t)})}}),_s=d({is(t){return t.kind==="SelectAllNode"},create(){return d({kind:"SelectAllNode"})}}),zi=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:_s.create()})}});class Ex{#e;get dynamicReference(){return this.#e}get refType(){}constructor(e){this.#e=e}toOperationNode(){return Ll(this.#e)}}function Rl(t){return He(t)&&Ae(t)&&Ce(t.dynamicReference)}const gt=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})}}),ce=d({is(t){return t.kind==="RawNode"},create(t,e){return d({kind:"RawNode",sqlFragments:d(t),parameters:d(e)})},createWithSql(t){return ce.create([t],[])},createWithChild(t){return ce.create(["",""],[t])},createWithChildren(t){return ce.create(new Array(t.length+1).fill(""),t)}}),Dx={is(t){return t.kind==="CollateNode"},create(t){return d({kind:"CollateNode",collation:G.create(t)})}};class Jt{#e;constructor(e){this.#e=d(e)}desc(){return new Jt({node:gt.cloneWith(this.#e.node,{direction:ce.createWithSql("desc")})})}asc(){return new Jt({node:gt.cloneWith(this.#e.node,{direction:ce.createWithSql("asc")})})}nullsLast(){return new Jt({node:gt.cloneWith(this.#e.node,{nulls:"last"})})}nullsFirst(){return new Jt({node:gt.cloneWith(this.#e.node,{nulls:"first"})})}collate(e){return new Jt({node:gt.cloneWith(this.#e.node,{collation:Dx.create(e)})})}toOperationNode(){return this.#e.node}}const Rc=new Set;function qn(t){Rc.has(t)||(Rc.add(t),console.log(t))}function Il(t){return t==="asc"||t==="desc"}function un(t){if(t.length===2)return[To(t[0],t[1])];if(t.length===1){const[e]=t;return Array.isArray(e)?(qn("orderBy(array) is deprecated, use multiple orderBy calls instead."),e.map(n=>To(n))):[To(e)]}throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${t.length}`)}function To(t,e){const n=kx(t);if(gt.is(n)){if(e)throw new Error("Cannot specify direction twice!");return n}return Wl(n,e)}function kx(t){if(Br(t))return mn(t);if(Rl(t))return t.toOperationNode();const[e,n]=t.split(" ");return n?(qn("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),Wl(St(e),n)):St(t)}function Wl(t,e){if(typeof e=="string"){if(!Il(e))throw new Error(`Invalid order by direction: ${e}`);return gt.create(t,ce.createWithSql(e))}if(Ol(e))return qn("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),gt.create(t,e.toOperationNode());const n=gt.create(t);return e?e(new Jt({node:n})).toOperationNode():n}const gi=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})}}),Ml=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])})}}),Xn=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 Ll(t){return Ce(t)?St(t):t.toOperationNode()}function kr(t){return Dt(t)?t.map(e=>Ue(e)):[Ue(t)]}function Ue(t){return Br(t)?mn(t):Ll(t)}function Sx(t,e){const n=St(t);if(Tc(e))return gi.create(n,Ml.create(Kt.create(e)));const r=e.slice(0,-1);if(Tc(r))return gi.create(n,Xn.create(Kt.create(r)));throw new Error(`Invalid JSON operator: ${e}`)}function St(t){if(!t.includes("."))return zi.create(ue.create(t));const n=t.split(".").map(js);if(n.length===3)return Ax(n);if(n.length===2)return Ox(n);throw new Error(`invalid column reference ${t}`)}function Cx(t){const e=" as ";if(t.includes(e)){const[n,r]=t.split(e).map(js);return Ct.create(St(n),G.create(r))}else return St(t)}function Pl(t){return ue.create(t)}function Ni(t){if(t.includes(" ")){const[n,r]=t.split(" ").map(js);if(!Il(r))throw new Error(`invalid order direction "${r}" next to "${n}"`);return un([n,r])[0]}else return Pl(t)}function Ax(t){const[e,n,r]=t;return zi.create(ue.create(r),xt.createWithSchema(e,n))}function Ox(t){const[e,n]=t;return zi.create(ue.create(n),xt.create(e))}function js(t){return t.trim()}const $l=d({is(t){return t.kind==="PrimitiveValueListNode"},create(t){return d({kind:"PrimitiveValueListNode",values:d([...t])})}}),Ki=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 Tx(t){return Dt(t)?Rx(t):he(t)}function he(t){return Br(t)?mn(t):Ke.create(t)}function Hs(t){return Hi(t)||yi(t)||Fs(t)}function zs(t){if(!Hs(t))throw new Error(`unsafe immediate value ${JSON.stringify(t)}`);return Ke.createImmediate(t)}function Rx(t){return t.some(Br)?Ki.create(t.map(e=>he(e))):$l.create(t)}const vt=d({is(t){return t.kind==="ParensNode"},create(t){return d({kind:"ParensNode",node:t})}});function ye(t){if(t.length===3)return Ks(t[0],t[1],t[2]);if(t.length===1)return he(t[0]);throw new Error(`invalid arguments: ${JSON.stringify(t)}`)}function Ks(t,e,n){return Ix(e)&&Bl(n)?$n.create(Ue(t),Jo(e),Ke.createImmediate(n)):$n.create(Ue(t),Jo(e),Tx(n))}function dt(t,e,n){return $n.create(Ue(t),Jo(e),Ue(n))}function Ic(t,e){return xi(Object.entries(t).filter(([,n])=>!jt(n)).map(([n,r])=>Ks(n,Bl(r)?"is":"=",r)),e)}function xi(t,e,n=!0){const r=e==="and"?zt.create:Un.create;if(t.length===0)return $n.create(Ke.createImmediate(1),Kt.create("="),Ke.createImmediate(e==="and"?1:0));let i=Wc(t[0]);for(let o=1;o<t.length;++o)i=r(i,Wc(t[o]));return t.length>1&&n?vt.create(i):i}function Ix(t){return t==="is"||t==="is not"}function Bl(t){return Fs(t)||yi(t)}function Jo(t){if(Ce(t)&&vx.includes(t))return Kt.create(t);if(Ae(t))return t.toOperationNode();throw new Error(`invalid operator ${JSON.stringify(t)}`)}function Wc(t){return Ae(t)?t.toOperationNode():t}const Bn=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])})}}),Mc=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])})}}),Go=d({is(t){return t.kind==="OverNode"},create(){return d({kind:"OverNode"})},cloneWithOrderByItems(t,e){return d({...t,orderBy:t.orderBy?Bn.cloneWithItems(t.orderBy,e):Bn.create(e)})},cloneWithPartitionByItems(t,e){return d({...t,partitionBy:t.partitionBy?Mc.cloneWithItems(t.partitionBy,e):Mc.create(e)})}}),vi=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])})}}),Lc=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])})}}),Pc=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"?zt.create(t.having,n):Un.create(t.having,n)})}}),we=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})}}),Ul=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]:Ul.create(t),...e&&{with:e}})},createWithoutTable(){return d({kind:"UpdateQueryNode"})},cloneWithFromItems(t,e){return d({...t,from:t.from?vi.cloneWithFroms(t.from,e):vi.create(e)})},cloneWithUpdates(t,e){return d({...t,updates:t.updates?d([...t.updates,...e]):e})},cloneWithLimit(t,e){return d({...t,limit:e})}}),$c=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])})}}),er=d({is(t){return t.kind==="DeleteQueryNode"},create(t,e){return d({kind:"DeleteQueryNode",from:vi.create(t),...e&&{with:e}})},cloneWithOrderByItems:(t,e)=>R.cloneWithOrderByItems(t,e),cloneWithoutOrderBy:t=>R.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?$c.cloneWithTables(t.using,e):$c.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"?zt.create(t.where,n):Un.create(t.where,n)})}}),Bc=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)})}}),Wx=d({is(t){return t.kind==="ExplainNode"},create(t,e){return d({kind:"ExplainNode",format:t,options:e})}}),ln=d({is(t){return t.kind==="WhenNode"},create(t){return d({kind:"WhenNode",condition:t})},cloneWithResult(t,e){return d({...t,result:e})}}),st=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),ln.cloneWithResult(t.whens[t.whens.length-1],e)]):void 0})}}),Uc=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)})}}),R=d({is(t){return Q.is(t)||we.is(t)||On.is(t)||er.is(t)||st.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?Bc.cloneWithSelections(t.returning,e):Bc.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:Wx.create(e,n?.toOperationNode())})},cloneWithTop(t,e){return d({...t,top:e})},cloneWithOutput(t,e){return d({...t,output:t.output?Uc.cloneWithSelections(t.output,e):Uc.create(e)})},cloneWithOrderByItems(t,e){return d({...t,orderBy:t.orderBy?Bn.cloneWithItems(t.orderBy,e):Bn.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:vi.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)=>R.cloneWithOrderByItems(t,e),cloneWithGroupByItems(t,e){return d({...t,groupBy:t.groupBy?Lc.cloneWithItems(t.groupBy,e):Lc.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?Pc.cloneWithOperation(t.having,"And",e):Pc.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=>R.cloneWithoutOrderBy(t),cloneWithoutGroupBy(t){return d({...t,groupBy:void 0})}});class tr{#e;constructor(e){this.#e=d(e)}on(...e){return new tr({...this.#e,joinNode:cn.cloneWithOn(this.#e.joinNode,ye(e))})}onRef(e,n,r){return new tr({...this.#e,joinNode:cn.cloneWithOn(this.#e.joinNode,dt(e,n,r))})}onTrue(){return new tr({...this.#e,joinNode:cn.cloneWithOn(this.#e.joinNode,ce.createWithSql("true"))})}$call(e){return e(this)}toOperationNode(){return this.#e.joinNode}}const Mx=d({is(t){return t.kind==="PartitionByItemNode"},create(t){return d({kind:"PartitionByItemNode",partitionBy:t})}});function Lx(t){return kr(t).map(Mx.create)}class nr{#e;constructor(e){this.#e=d(e)}orderBy(...e){return new nr({overNode:Go.cloneWithOrderByItems(this.#e.overNode,un(e))})}clearOrderBy(){return new nr({overNode:R.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(e){return new nr({overNode:Go.cloneWithPartitionByItems(this.#e.overNode,Lx(e))})}$call(e){return e(this)}toOperationNode(){return this.#e.overNode}}const rr=d({is(t){return t.kind==="SelectionNode"},create(t){return d({kind:"SelectionNode",selection:t})},createSelectAll(){return d({kind:"SelectionNode",selection:_s.create()})},createSelectAllFromTable(t){return d({kind:"SelectionNode",selection:zi.createSelectAll(t)})}});function qe(t){return Ve(t)?qe(t(Vn())):Dt(t)?t.map(e=>qc(e)):[qc(t)]}function qc(t){return Ce(t)?rr.create(Cx(t)):Rl(t)?rr.create(t.toOperationNode()):rr.create(Zl(t))}function Je(t){return t?Array.isArray(t)?t.map(Fc):[Fc(t)]:[rr.createSelectAll()]}function Fc(t){if(Ce(t))return rr.createSelectAllFromTable(de(t));throw new Error(`invalid value selectAll expression: ${JSON.stringify(t)}`)}const Px=d({is(t){return t.kind==="ValuesNode"},create(t){return d({kind:"ValuesNode",values:d(t)})}}),$x=d({is(t){return t.kind==="DefaultInsertValueNode"},create(){return d({kind:"DefaultInsertValueNode"})}});function ql(t){const e=Ve(t)?t(Vn()):t,n=Dt(e)?e:d([e]);return Bx(n)}function Bx(t){const e=Ux(t);return[d([...e.keys()].map(ue.create)),Px.create(t.map(n=>qx(n,e)))]}function Ux(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 qx(t,e){const n=Object.keys(t),r=Array.from({length:e.size});let i=!1,o=n.length;for(const a of n){const c=e.get(a);if(jt(c)){o--;continue}const u=t[a];(jt(u)||Br(u))&&(i=!0),r[c]=u}if(o<e.size||i){const a=$x.create();return Ki.create(r.map(c=>jt(c)?a:he(c)))}return $l.create(r)}const Fl=d({is(t){return t.kind==="ColumnUpdateNode"},create(t,e){return d({kind:"ColumnUpdateNode",column:t,value:e})}});function Fx(...t){return t.length===2?[Fl.create(Ue(t[0]),he(t[1]))]:Js(t[0])}function Js(t){const e=Ve(t)?t(Vn()):t;return Object.entries(e).filter(([n,r])=>r!==void 0).map(([n,r])=>Fl.create(ue.create(n),he(r)))}const Vx=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 Pr extends Error{node;constructor(e){super("no result"),this.node=e}}function $r(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 mt{#e;constructor(e){this.#e=d(e)}column(e){const n=ue.create(e);return new mt({...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(ue.create);return new mt({...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 mt({...this.#e,onConflictNode:Pe.cloneWith(this.#e.onConflictNode,{constraint:G.create(e)})})}expression(e){return new mt({...this.#e,onConflictNode:Pe.cloneWith(this.#e.onConflictNode,{indexExpression:e.toOperationNode()})})}where(...e){return new mt({...this.#e,onConflictNode:Pe.cloneWithIndexWhere(this.#e.onConflictNode,ye(e))})}whereRef(e,n,r){return new mt({...this.#e,onConflictNode:Pe.cloneWithIndexWhere(this.#e.onConflictNode,dt(e,n,r))})}clearWhere(){return new mt({...this.#e,onConflictNode:Pe.cloneWithoutIndexWhere(this.#e.onConflictNode)})}doNothing(){return new jx({...this.#e,onConflictNode:Pe.cloneWith(this.#e.onConflictNode,{doNothing:!0})})}doUpdateSet(e){return new ir({...this.#e,onConflictNode:Pe.cloneWith(this.#e.onConflictNode,{updates:Js(e)})})}$call(e){return e(this)}}class jx{#e;constructor(e){this.#e=d(e)}toOperationNode(){return this.#e.onConflictNode}}class ir{#e;constructor(e){this.#e=d(e)}where(...e){return new ir({...this.#e,onConflictNode:Pe.cloneWithUpdateWhere(this.#e.onConflictNode,ye(e))})}whereRef(e,n,r){return new ir({...this.#e,onConflictNode:Pe.cloneWithUpdateWhere(this.#e.onConflictNode,dt(e,n,r))})}clearWhere(){return new ir({...this.#e,onConflictNode:Pe.cloneWithoutUpdateWhere(this.#e.onConflictNode)})}$call(e){return e(this)}toOperationNode(){return this.#e.onConflictNode}}const Hx=d({is(t){return t.kind==="TopNode"},create(t,e){return d({kind:"TopNode",expression:t,modifiers:e})}});function Fn(t,e){if(!Hi(t)&&!Vs(t))throw new Error(`Invalid top expression: ${t}`);if(!jt(e)&&!zx(e))throw new Error(`Invalid top modifiers: ${e}`);return Hx.create(t,e)}function zx(t){return t==="percent"||t==="with ties"||t==="percent with ties"}const gn=d({is(t){return t.kind==="OrActionNode"},create(t){return d({kind:"OrActionNode",action:t})}});class z{#e;constructor(e){this.#e=d(e)}values(e){const[n,r]=ql(e);return new z({...this.#e,queryNode:we.cloneWith(this.#e.queryNode,{columns:n,values:r})})}columns(e){return new z({...this.#e,queryNode:we.cloneWith(this.#e.queryNode,{columns:d(e.map(ue.create))})})}expression(e){return new z({...this.#e,queryNode:we.cloneWith(this.#e.queryNode,{values:mn(e)})})}defaultValues(){return new z({...this.#e,queryNode:we.cloneWith(this.#e.queryNode,{defaultValues:!0})})}modifyEnd(e){return new z({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}ignore(){return new z({...this.#e,queryNode:we.cloneWith(this.#e.queryNode,{orAction:gn.create("ignore")})})}orIgnore(){return new z({...this.#e,queryNode:we.cloneWith(this.#e.queryNode,{orAction:gn.create("ignore")})})}orAbort(){return new z({...this.#e,queryNode:we.cloneWith(this.#e.queryNode,{orAction:gn.create("abort")})})}orFail(){return new z({...this.#e,queryNode:we.cloneWith(this.#e.queryNode,{orAction:gn.create("fail")})})}orReplace(){return new z({...this.#e,queryNode:we.cloneWith(this.#e.queryNode,{orAction:gn.create("replace")})})}orRollback(){return new z({...this.#e,queryNode:we.cloneWith(this.#e.queryNode,{orAction:gn.create("rollback")})})}top(e,n){return new z({...this.#e,queryNode:R.cloneWithTop(this.#e.queryNode,Fn(e,n))})}onConflict(e){return new z({...this.#e,queryNode:we.cloneWith(this.#e.queryNode,{onConflict:e(new mt({onConflictNode:Pe.create()})).toOperationNode()})})}onDuplicateKeyUpdate(e){return new z({...this.#e,queryNode:we.cloneWith(this.#e.queryNode,{onDuplicateKey:Vx.create(Js(e))})})}returning(e){return new z({...this.#e,queryNode:R.cloneWithReturning(this.#e.queryNode,qe(e))})}returningAll(){return new z({...this.#e,queryNode:R.cloneWithReturning(this.#e.queryNode,Je())})}output(e){return new z({...this.#e,queryNode:R.cloneWithOutput(this.#e.queryNode,qe(e))})}outputAll(e){return new z({...this.#e,queryNode:R.cloneWithOutput(this.#e.queryNode,Je(e))})}clearReturning(){return new z({...this.#e,queryNode:R.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(e,n){return e?n(this):new z({...this.#e})}$castTo(){return new z(this.#e)}$narrowType(){return new z(this.#e)}$assertType(){return new z(this.#e)}withPlugin(e){return new z({...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=Pr){const n=await this.executeTakeFirst();if(n===void 0)throw $r(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 z({...this.#e,queryNode:R.cloneWithExplain(this.#e.queryNode,e,n)}).execute()}}class Kx{numDeletedRows;constructor(e){this.numDeletedRows=e}}const Gs=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:R.cloneWithWhere(this.#e.queryNode,ye(e))})}whereRef(e,n,r){return new te({...this.#e,queryNode:R.cloneWithWhere(this.#e.queryNode,dt(e,n,r))})}clearWhere(){return new te({...this.#e,queryNode:R.cloneWithoutWhere(this.#e.queryNode)})}top(e,n){return new te({...this.#e,queryNode:R.cloneWithTop(this.#e.queryNode,Fn(e,n))})}using(e){return new te({...this.#e,queryNode:er.cloneWithUsing(this.#e.queryNode,Tn(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:R.cloneWithJoin(this.#e.queryNode,Gi(e,n))})}returning(e){return new te({...this.#e,queryNode:R.cloneWithReturning(this.#e.queryNode,qe(e))})}returningAll(e){return new te({...this.#e,queryNode:R.cloneWithReturning(this.#e.queryNode,Je(e))})}output(e){return new te({...this.#e,queryNode:R.cloneWithOutput(this.#e.queryNode,qe(e))})}outputAll(e){return new te({...this.#e,queryNode:R.cloneWithOutput(this.#e.queryNode,Je(e))})}clearReturning(){return new te({...this.#e,queryNode:R.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new te({...this.#e,queryNode:er.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...e){return new te({...this.#e,queryNode:R.cloneWithOrderByItems(this.#e.queryNode,un(e))})}clearOrderBy(){return new te({...this.#e,queryNode:R.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new te({...this.#e,queryNode:er.cloneWithLimit(this.#e.queryNode,Gs.create(he(e)))})}modifyEnd(e){return new te({...this.#e,queryNode:R.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 Kx(n.numAffectedRows??BigInt(0))]}async executeTakeFirst(){const[e]=await this.execute();return e}async executeTakeFirstOrThrow(e=Pr){const n=await this.executeTakeFirst();if(n===void 0)throw $r(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:R.cloneWithExplain(this.#e.queryNode,e,n)}).execute()}}class Jx{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:R.cloneWithWhere(this.#e.queryNode,ye(e))})}whereRef(e,n,r){return new X({...this.#e,queryNode:R.cloneWithWhere(this.#e.queryNode,dt(e,n,r))})}clearWhere(){return new X({...this.#e,queryNode:R.cloneWithoutWhere(this.#e.queryNode)})}top(e,n){return new X({...this.#e,queryNode:R.cloneWithTop(this.#e.queryNode,Fn(e,n))})}from(e){return new X({...this.#e,queryNode:On.cloneWithFromItems(this.#e.queryNode,Tn(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:R.cloneWithJoin(this.#e.queryNode,Gi(e,n))})}orderBy(...e){return new X({...this.#e,queryNode:R.cloneWithOrderByItems(this.#e.queryNode,un(e))})}clearOrderBy(){return new X({...this.#e,queryNode:R.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new X({...this.#e,queryNode:On.cloneWithLimit(this.#e.queryNode,Gs.create(he(e)))})}set(...e){return new X({...this.#e,queryNode:On.cloneWithUpdates(this.#e.queryNode,Fx(...e))})}returning(e){return new X({...this.#e,queryNode:R.cloneWithReturning(this.#e.queryNode,qe(e))})}returningAll(e){return new X({...this.#e,queryNode:R.cloneWithReturning(this.#e.queryNode,Je(e))})}output(e){return new X({...this.#e,queryNode:R.cloneWithOutput(this.#e.queryNode,qe(e))})}outputAll(e){return new X({...this.#e,queryNode:R.cloneWithOutput(this.#e.queryNode,Je(e))})}modifyEnd(e){return new X({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}clearReturning(){return new X({...this.#e,queryNode:R.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 Jx(n.numAffectedRows??BigInt(0),n.numChangedRows)]}async executeTakeFirst(){const[e]=await this.execute();return e}async executeTakeFirstOrThrow(e=Pr){const n=await this.executeTakeFirst();if(n===void 0)throw $r(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:R.cloneWithExplain(this.#e.queryNode,e,n)}).execute()}}const Vc=d({is(t){return t.kind==="CommonTableExpressionNameNode"},create(t,e){return d({kind:"CommonTableExpressionNameNode",table:xt.create(t),columns:e?d(e.map(ue.create)):void 0})}}),Ei=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 Di{#e;constructor(e){this.#e=d(e)}materialized(){return new Di({...this.#e,node:Ei.cloneWith(this.#e.node,{materialized:!0})})}notMaterialized(){return new Di({...this.#e,node:Ei.cloneWith(this.#e.node,{materialized:!1})})}toOperationNode(){return this.#e.node}}function _c(t,e){const n=e(sv()).toOperationNode();return Ve(t)?t(Gx(n)).toOperationNode():Ei.create(Vl(t),n)}function Gx(t){return e=>new Di({node:Ei.create(Vl(e),t)})}function Vl(t){if(t.includes("(")){const e=t.split(/[\(\)]/),n=e[0],r=e[1].split(",").map(i=>i.trim());return Vc.create(n,r)}else return Vc.create(t)}const Qr=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])})}}),jc=["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 Zx(t){let e="";for(let n=0;n<t;++n)e+=Yx();return e}function Yx(){return jc[~~(Math.random()*jc.length)]}function j(){return new Qx}class Qx{#e;get queryId(){return this.#e===void 0&&(this.#e=Zx(8)),this.#e}}class _l{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 Xx=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}),ev={json_agg:!0,to_json:!0};class tv extends _l{#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.#o(e);for(const s of r)this.#n.add(s);const i=this.#c(e);for(const s of i)this.#t.add(s);const o=super.transformNodeImpl(e,n);for(const s of i)this.#t.delete(s);for(const s of r)this.#n.delete(s);return o}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:xt.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 ev[e.func]?e[r].map(i=>!xt.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 Xx}#c(e){const n=new Set;if("name"in e&&e.name&&kt.is(e.name)&&this.#a(e.name,n),"from"in e&&e.from)for(const r of e.from.froms)this.#s(r,n);if("into"in e&&e.into&&this.#s(e.into,n),"table"in e&&e.table&&this.#s(e.table,n),"joins"in e&&e.joins)for(const r of e.joins)this.#s(r.table,n);return"using"in e&&e.using&&(cn.is(e.using)?this.#s(e.using.table,n):this.#s(e.using,n)),n}#o(e){const n=new Set;return"with"in e&&e.with&&this.#d(e.with,n),n}#s(e,n){if(xt.is(e))this.#a(e.table,n);else if(Ct.is(e)&&xt.is(e.node))this.#a(e.node.table,n);else if(Ul.is(e))for(const r of e.items)this.#s(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 pn{#e;constructor(e){this.#e=new tv(e)}transformQuery(e){return this.#e.transformNode(e.node,e.queryId)}async transformResult(e){return e.result}}const nv=d({is(t){return t.kind==="MatchedNode"},create(t,e=!1){return d({kind:"MatchedNode",not:t,bySource:e})}});function Hc(t,e,n){return ln.create(xi([nv.create(!t.isMatched,t.bySource),...e&&e.length>0?[e.length===3&&n?dt(e[0],e[1],e[2]):ye(e)]:[]],"and",!1))}function or(t){return Ce(t)?ce.create([t],[]):Ae(t)?t.toOperationNode():t}class zc{#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 jl(t){const e=new zc,n=new zc;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 rv=d([]);class Hl{#e;constructor(e=rv){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&&qn("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 jl(this);try{for await(const o of r.streamQuery(e,n))yield await this.#t(o,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 Sn extends Hl{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 Sn([...this.plugins,e])}withPlugins(e){return new Sn([...this.plugins,...e])}withPluginAtFront(e){return new Sn([e,...this.plugins])}withoutPlugins(){return new Sn([])}}const Ji=new Sn;class iv{numChangedRows;constructor(e){this.numChangedRows=e}}class Mt{#e;constructor(e){this.#e=d(e)}modifyEnd(e){return new Mt({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,n){return new Mt({...this.#e,queryNode:R.cloneWithTop(this.#e.queryNode,Fn(e,n))})}using(...e){return new Re({...this.#e,queryNode:st.cloneWithUsing(this.#e.queryNode,Gi("Using",e))})}returning(e){return new Mt({...this.#e,queryNode:R.cloneWithReturning(this.#e.queryNode,qe(e))})}returningAll(e){return new Mt({...this.#e,queryNode:R.cloneWithReturning(this.#e.queryNode,Je(e))})}output(e){return new Mt({...this.#e,queryNode:R.cloneWithOutput(this.#e.queryNode,qe(e))})}outputAll(e){return new Mt({...this.#e,queryNode:R.cloneWithOutput(this.#e.queryNode,Je(e))})}}class Re{#e;constructor(e){this.#e=d(e)}modifyEnd(e){return new Re({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,n){return new Re({...this.#e,queryNode:R.cloneWithTop(this.#e.queryNode,Fn(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 Kc({...this.#e,queryNode:st.cloneWithWhen(this.#e.queryNode,Hc({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 Re({...this.#e,queryNode:R.cloneWithReturning(this.#e.queryNode,qe(e))})}returningAll(e){return new Re({...this.#e,queryNode:R.cloneWithReturning(this.#e.queryNode,Je(e))})}output(e){return new Re({...this.#e,queryNode:R.cloneWithOutput(this.#e.queryNode,qe(e))})}outputAll(e){return new Re({...this.#e,queryNode:R.cloneWithOutput(this.#e.queryNode,Je(e))})}#n(e,n=!1,r=!1){const i={...this.#e,queryNode:st.cloneWithWhen(this.#e.queryNode,Hc({isMatched:!1,bySource:r},e,n))},o=r?Kc:ov;return new o(i)}$call(e){return e(this)}$if(e,n){return e?n(this):new Re({...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 iv(n.numAffectedRows)]}async executeTakeFirst(){const[e]=await this.execute();return e}async executeTakeFirstOrThrow(e=Pr){const n=await this.executeTakeFirst();if(n===void 0)throw $r(e)?new e(this.toOperationNode()):e(this.toOperationNode());return n}}class Kc{#e;constructor(e){this.#e=d(e)}thenDelete(){return new Re({...this.#e,queryNode:st.cloneWithThen(this.#e.queryNode,or("delete"))})}thenDoNothing(){return new Re({...this.#e,queryNode:st.cloneWithThen(this.#e.queryNode,or("do nothing"))})}thenUpdate(e){return new Re({...this.#e,queryNode:st.cloneWithThen(this.#e.queryNode,or(e(new X({queryId:this.#e.queryId,executor:Ji,queryNode:On.createWithoutTable()}))))})}thenUpdateSet(...e){return this.thenUpdate(n=>n.set(...e))}}class ov{#e;constructor(e){this.#e=d(e)}thenDoNothing(){return new Re({...this.#e,queryNode:st.cloneWithThen(this.#e.queryNode,or("do nothing"))})}thenInsertValues(e){const[n,r]=ql(e);return new Re({...this.#e,queryNode:st.cloneWithThen(this.#e.queryNode,or(we.cloneWith(we.createWithoutInto(),{columns:n,values:r})))})}}class qt{#e;constructor(e){this.#e=d(e)}selectFrom(e){return Zo({queryId:j(),executor:this.#e.executor,queryNode:Q.createFrom(Tn(e),this.#e.withNode)})}selectNoFrom(e){return Zo({queryId:j(),executor:this.#e.executor,queryNode:Q.cloneWithSelections(Q.create(this.#e.withNode),qe(e))})}insertInto(e){return new z({queryId:j(),executor:this.#e.executor,queryNode:we.create(de(e),this.#e.withNode)})}replaceInto(e){return new z({queryId:j(),executor:this.#e.executor,queryNode:we.create(de(e),this.#e.withNode,!0)})}deleteFrom(e){return new te({queryId:j(),executor:this.#e.executor,queryNode:er.create(Tn(e),this.#e.withNode)})}updateTable(e){return new X({queryId:j(),executor:this.#e.executor,queryNode:On.create(Tn(e),this.#e.withNode)})}mergeInto(e){return new Mt({queryId:j(),executor:this.#e.executor,queryNode:st.create(Yl(e),this.#e.withNode)})}with(e,n){const r=_c(e,n);return new qt({...this.#e,withNode:this.#e.withNode?Qr.cloneWithExpression(this.#e.withNode,r):Qr.create(r)})}withRecursive(e,n){const r=_c(e,n);return new qt({...this.#e,withNode:this.#e.withNode?Qr.cloneWithExpression(this.#e.withNode,r):Qr.create(r,{recursive:!0})})}withPlugin(e){return new qt({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new qt({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new qt({...this.#e,executor:this.#e.executor.withPluginAtFront(new pn(e))})}}function sv(){return new qt({executor:Ji})}function av(t,e){return new tr({joinNode:cn.create(t,Cr(e))})}function cv(){return new nr({overNode:Go.create()})}function Gi(t,e){if(e.length===3)return uv(t,e[0],e[1],e[2]);if(e.length===2)return dv(t,e[0],e[1]);if(e.length===1)return lv(t,e[0]);throw new Error("not implemented")}function dv(t,e,n){return n(av(t,e)).toOperationNode()}function uv(t,e,n,r){return cn.createWithOn(t,Cr(e),dt(n,"=",r))}function lv(t,e){return cn.create(t,Cr(e))}const hv=d({is(t){return t.kind==="OffsetNode"},create(t){return d({kind:"OffsetNode",offset:t})}}),fv=d({is(t){return t.kind==="GroupByItemNode"},create(t){return d({kind:"GroupByItemNode",groupBy:t})}});function pv(t){return t=Ve(t)?t(Vn()):t,kr(t).map(fv.create)}const zl=d({is(t){return t.kind==="SetOperationNode"},create(t,e,n){return d({kind:"SetOperationNode",operator:t,expression:e,all:n})}});function Nn(t,e,n){return Ve(e)&&(e=e(Ys())),Dt(e)||(e=[e]),e.map(r=>zl.create(t,mn(r),n))}class K{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new Zs(this,e)}or(...e){return new ki(Un.create(this.#e,ye(e)))}and(...e){return new Si(zt.create(this.#e,ye(e)))}$castTo(){return new K(this.#e)}$notNull(){return new K(this.#e)}toOperationNode(){return this.#e}}class Zs{#e;#t;constructor(e,n){this.#e=e,this.#t=n}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return Ct.create(this.#e.toOperationNode(),Ae(this.#t)?this.#t.toOperationNode():G.create(this.#t))}}class ki{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new Zs(this,e)}or(...e){return new ki(Un.create(this.#e,ye(e)))}$castTo(){return new ki(this.#e)}toOperationNode(){return vt.create(this.#e)}}class Si{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new Zs(this,e)}and(...e){return new Si(zt.create(this.#e,ye(e)))}$castTo(){return new Si(this.#e)}toOperationNode(){return vt.create(this.#e)}}const mv={is(t){return t.kind==="FetchNode"},create(t,e){return{kind:"FetchNode",rowCount:Ke.create(t),modifier:e}}};function wv(t,e){if(!Hi(t)&&!Vs(t))throw new Error(`Invalid fetch row count: ${t}`);if(!bv(e))throw new Error(`Invalid fetch modifier: ${e}`);return mv.create(t,e)}function bv(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:R.cloneWithWhere(this.#e.queryNode,ye(e))})}whereRef(e,n,r){return new F({...this.#e,queryNode:R.cloneWithWhere(this.#e.queryNode,dt(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,dt(e,n,r))})}select(e){return new F({...this.#e,queryNode:Q.cloneWithSelections(this.#e.queryNode,qe(e))})}distinctOn(e){return new F({...this.#e,queryNode:Q.cloneWithDistinctOn(this.#e.queryNode,kr(e))})}modifyFront(e){return new F({...this.#e,queryNode:Q.cloneWithFrontModifier(this.#e.queryNode,ft.createWithExpression(e.toOperationNode()))})}modifyEnd(e){return new F({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,ft.createWithExpression(e.toOperationNode()))})}distinct(){return new F({...this.#e,queryNode:Q.cloneWithFrontModifier(this.#e.queryNode,ft.create("Distinct"))})}forUpdate(e){return new F({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,ft.create("ForUpdate",e?Yr(e).map(de):void 0))})}forShare(e){return new F({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,ft.create("ForShare",e?Yr(e).map(de):void 0))})}forKeyShare(e){return new F({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,ft.create("ForKeyShare",e?Yr(e).map(de):void 0))})}forNoKeyUpdate(e){return new F({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,ft.create("ForNoKeyUpdate",e?Yr(e).map(de):void 0))})}skipLocked(){return new F({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,ft.create("SkipLocked"))})}noWait(){return new F({...this.#e,queryNode:R.cloneWithEndModifier(this.#e.queryNode,ft.create("NoWait"))})}selectAll(e){return new F({...this.#e,queryNode:Q.cloneWithSelections(this.#e.queryNode,Je(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:R.cloneWithJoin(this.#e.queryNode,Gi(e,n))})}orderBy(...e){return new F({...this.#e,queryNode:R.cloneWithOrderByItems(this.#e.queryNode,un(e))})}groupBy(e){return new F({...this.#e,queryNode:Q.cloneWithGroupByItems(this.#e.queryNode,pv(e))})}limit(e){return new F({...this.#e,queryNode:Q.cloneWithLimit(this.#e.queryNode,Gs.create(he(e)))})}offset(e){return new F({...this.#e,queryNode:Q.cloneWithOffset(this.#e.queryNode,hv.create(he(e)))})}fetch(e,n="only"){return new F({...this.#e,queryNode:Q.cloneWithFetch(this.#e.queryNode,wv(e,n))})}top(e,n){return new F({...this.#e,queryNode:R.cloneWithTop(this.#e.queryNode,Fn(e,n))})}union(e){return new F({...this.#e,queryNode:Q.cloneWithSetOperations(this.#e.queryNode,Nn("union",e,!1))})}unionAll(e){return new F({...this.#e,queryNode:Q.cloneWithSetOperations(this.#e.queryNode,Nn("union",e,!0))})}intersect(e){return new F({...this.#e,queryNode:Q.cloneWithSetOperations(this.#e.queryNode,Nn("intersect",e,!1))})}intersectAll(e){return new F({...this.#e,queryNode:Q.cloneWithSetOperations(this.#e.queryNode,Nn("intersect",e,!0))})}except(e){return new F({...this.#e,queryNode:Q.cloneWithSetOperations(this.#e.queryNode,Nn("except",e,!1))})}exceptAll(e){return new F({...this.#e,queryNode:Q.cloneWithSetOperations(this.#e.queryNode,Nn("except",e,!0))})}as(e){return new yv(this,e)}clearSelect(){return new F({...this.#e,queryNode:Q.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new F({...this.#e,queryNode:R.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:R.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 K(this.toOperationNode())}$asScalar(){return new K(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=Pr){const n=await this.executeTakeFirst();if(n===void 0)throw $r(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:R.cloneWithExplain(this.#e.queryNode,e,n)}).execute()}}function Zo(t){return new F(t)}class yv{#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 Ct.create(this.#e.toOperationNode(),G.create(this.#t))}}const Ft=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]?Bn.cloneWithItems(t[r],e):Bn.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})}}),Jc=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 gv(this,e)}distinct(){return new $e({...this.#e,aggregateFunctionNode:Ft.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...e){return new $e({...this.#e,aggregateFunctionNode:R.cloneWithOrderByItems(this.#e.aggregateFunctionNode,un(e))})}clearOrderBy(){return new $e({...this.#e,aggregateFunctionNode:R.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...e){return new $e({...this.#e,aggregateFunctionNode:Ft.cloneWithOrderBy(this.#e.aggregateFunctionNode,un(e),!0)})}filterWhere(...e){return new $e({...this.#e,aggregateFunctionNode:Ft.cloneWithFilter(this.#e.aggregateFunctionNode,ye(e))})}filterWhereRef(e,n,r){return new $e({...this.#e,aggregateFunctionNode:Ft.cloneWithFilter(this.#e.aggregateFunctionNode,dt(e,n,r))})}over(e){const n=cv();return new $e({...this.#e,aggregateFunctionNode:Ft.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 gv{#e;#t;constructor(e,n){this.#e=e,this.#t=n}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return Ct.create(this.#e.toOperationNode(),G.create(this.#t))}}function Kl(){const t=(n,r)=>new K(Jc.create(n,kr(r??[]))),e=(n,r)=>new $e({aggregateFunctionNode:Ft.create(n,r?kr(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:Ft.create("count",Je(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:Ft.create("json_agg",[Ce(n)?de(n):n.toOperationNode()])})},toJson(n){return new K(Jc.create("to_json",[Ce(n)?de(n):n.toOperationNode()]))}})}const Nv=d({is(t){return t.kind==="UnaryOperationNode"},create(t,e){return d({kind:"UnaryOperationNode",operator:t,operand:e})}});function xv(t,e){return Nv.create(Kt.create(t),Ue(e))}const ot=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),ln.cloneWithResult(t.when[t.when.length-1],e)]):void 0})},cloneWith(t,e){return d({...t,...e})}});class Jl{#e;constructor(e){this.#e=d(e)}when(...e){return new Gl({...this.#e,node:ot.cloneWithWhen(this.#e.node,ln.create(ye(e)))})}}class Gl{#e;constructor(e){this.#e=d(e)}then(e){return new vv({...this.#e,node:ot.cloneWithThen(this.#e.node,Hs(e)?zs(e):he(e))})}}class vv{#e;constructor(e){this.#e=d(e)}when(...e){return new Gl({...this.#e,node:ot.cloneWithWhen(this.#e.node,ln.create(ye(e)))})}else(e){return new Ev({...this.#e,node:ot.cloneWith(this.#e.node,{else:Hs(e)?zs(e):he(e)})})}end(){return new K(ot.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new K(ot.cloneWith(this.#e.node,{isStatement:!0}))}}class Ev{#e;constructor(e){this.#e=d(e)}end(){return new K(ot.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new K(ot.cloneWith(this.#e.node,{isStatement:!0}))}}const Gc=d({is(t){return t.kind==="JSONPathLegNode"},create(t,e){return d({kind:"JSONPathLegNode",type:t,value:e})}});class Yo{#e;constructor(e){this.#e=e}at(e){return this.#t("ArrayLocation",e)}key(e){return this.#t("Member",e)}#t(e,n){return gi.is(this.#e)?new Sr(gi.cloneWithTraversal(this.#e,Xn.is(this.#e.traversal)?Xn.cloneWithLeg(this.#e.traversal,Gc.create(e,n)):Ml.cloneWithValue(this.#e.traversal,Ke.createImmediate(n)))):new Sr(Xn.cloneWithLeg(this.#e,Gc.create(e,n)))}}class Sr extends Yo{#e;constructor(e){super(e),this.#e=e}get expressionType(){}as(e){return new Dv(this,e)}$castTo(){return new Sr(this.#e)}$notNull(){return new Sr(this.#e)}toOperationNode(){return this.#e}}class Dv{#e;#t;constructor(e,n){this.#e=e,this.#t=n}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return Ct.create(this.#e.toOperationNode(),Ae(this.#t)?this.#t.toOperationNode():G.create(this.#t))}}const Zc=d({is(t){return t.kind==="TupleNode"},create(t){return d({kind:"TupleNode",values:d(t)})}}),kv=["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"],Sv=[/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^varbinary\(\d+\)$/],Cv=d({is(t){return t.kind==="DataTypeNode"},create(t){return d({kind:"DataTypeNode",dataType:t})}});function Av(t){return!!(kv.includes(t)||Sv.some(e=>e.test(t)))}function hn(t){if(Ae(t))return t.toOperationNode();if(Av(t))return Cv.create(t);throw new Error(`invalid column data type ${JSON.stringify(t)}`)}const Ov=d({is(t){return t.kind==="CastNode"},create(t,e){return d({kind:"CastNode",expression:t,dataType:e})}});function Ys(t=Ji){function e(i,o,s){return new K(Ks(i,o,s))}function n(i,o){return new K(xv(i,o))}const r=Object.assign(e,{fn:void 0,eb:void 0,selectFrom(i){return Zo({queryId:j(),executor:t,queryNode:Q.createFrom(Tn(i))})},case(i){return new Jl({node:ot.create(jt(i)?void 0:Ue(i))})},ref(i,o){return jt(o)?new K(St(i)):new Yo(Sx(i,o))},jsonPath(){return new Yo(Xn.create())},table(i){return new K(de(i))},val(i){return new K(he(i))},refTuple(...i){return new K(Zc.create(i.map(Ue)))},tuple(...i){return new K(Zc.create(i.map(he)))},lit(i){return new K(zs(i))},unary:n,not(i){return n("not",i)},exists(i){return n("exists",i)},neg(i){return n("-",i)},between(i,o,s){return new K($n.create(Ue(i),Kt.create("between"),zt.create(he(o),he(s))))},betweenSymmetric(i,o,s){return new K($n.create(Ue(i),Kt.create("between symmetric"),zt.create(he(o),he(s))))},and(i){return Dt(i)?new K(xi(i,"and")):new K(Ic(i,"and"))},or(i){return Dt(i)?new K(xi(i,"or")):new K(Ic(i,"or"))},parens(...i){const o=ye(i);return vt.is(o)?new K(o):new K(vt.create(o))},cast(i,o){return new K(Ov.create(Ue(i),hn(o)))},withSchema(i){return Ys(t.withPluginAtFront(new pn(i)))}});return r.fn=Kl(),r.eb=r,r}function Vn(t){return Ys()}function mn(t){if(Ae(t))return t.toOperationNode();if(Ve(t))return t(Vn()).toOperationNode();throw new Error(`invalid expression: ${JSON.stringify(t)}`)}function Zl(t){if(Ae(t))return t.toOperationNode();if(Ve(t))return t(Vn()).toOperationNode();throw new Error(`invalid aliased expression: ${JSON.stringify(t)}`)}function Br(t){return Ol(t)||wx(t)||Ve(t)}class Tv{#e;get table(){return this.#e}constructor(e){this.#e=e}as(e){return new Rv(this.#e,e)}}class Rv{#e;#t;get table(){return this.#e}get alias(){return this.#t}constructor(e,n){this.#e=e,this.#t=n}toOperationNode(){return Ct.create(de(this.#e),G.create(this.#t))}}function Iv(t){return He(t)&&Ae(t)&&Ce(t.table)&&Ce(t.alias)}function Tn(t){return Dt(t)?t.map(e=>Cr(e)):[Cr(t)]}function Cr(t){return Ce(t)?Yl(t):Iv(t)?t.toOperationNode():Zl(t)}function Yl(t){const e=" as ";if(t.includes(e)){const[n,r]=t.split(e).map(Ql);return Ct.create(de(n),G.create(r))}else return de(t)}function de(t){if(t.includes(".")){const[n,r]=t.split(".").map(Ql);return xt.createWithSchema(n,r)}else return xt.create(t)}function Ql(t){return t.trim()}const Xl=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:ue.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})}}),eh=d({is(t){return t.kind==="DropColumnNode"},create(t){return d({kind:"DropColumnNode",column:ue.create(t)})}}),th=d({is(t){return t.kind==="RenameColumnNode"},create(t,e){return d({kind:"RenameColumnNode",column:ue.create(t),renameTo:ue.create(e)})}}),Qs=d({is(t){return t.kind==="CheckConstraintNode"},create(t,e){return d({kind:"CheckConstraintNode",expression:t,name:e?G.create(e):void 0})}}),Wv=["no action","restrict","cascade","set null","set default"],oi=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 nh(t){return Ae(t)?t.toOperationNode():Ke.createImmediate(t)}const Xr=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})}}),Mv=d({is(t){return t.kind==="DefaultValueNode"},create(t){return d({kind:"DefaultValueNode",defaultValue:t})}});function Ci(t){if(Wv.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=St(e);if(!n.table||_s.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:oi.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:oi.cloneWithOnDelete(this.#e.references,Ci(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:oi.cloneWithOnUpdate(this.#e.references,Ci(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:Mv.create(nh(e))}))}check(e){return new ee(ne.cloneWith(this.#e,{check:Qs.create(e.toOperationNode())}))}generatedAlwaysAs(e){return new ee(ne.cloneWith(this.#e,{generated:Xr.createWithExpression(e.toOperationNode())}))}generatedAlwaysAsIdentity(){return new ee(ne.cloneWith(this.#e,{generated:Xr.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new ee(ne.cloneWith(this.#e,{generated:Xr.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:Xr.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 rh=d({is(t){return t.kind==="ModifyColumnNode"},create(t){return d({kind:"ModifyColumnNode",column:t})}}),Lt=d({is(t){return t.kind==="ForeignKeyConstraintNode"},create(t,e,n,r){return d({kind:"ForeignKeyConstraintNode",columns:t,references:oi.create(e,n),name:r?G.create(r):void 0})},cloneWith(t,e){return d({...t,...e})}});class yt{#e;constructor(e){this.#e=e}onDelete(e){return new yt(Lt.cloneWith(this.#e,{onDelete:Ci(e)}))}onUpdate(e){return new yt(Lt.cloneWith(this.#e,{onUpdate:Ci(e)}))}deferrable(){return new yt(Lt.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new yt(Lt.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new yt(Lt.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new yt(Lt.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}}const si=d({is(t){return t.kind==="AddConstraintNode"},create(t){return d({kind:"AddConstraintNode",constraint:t})}}),Gt=d({is(t){return t.kind==="UniqueConstraintNode"},create(t,e,n){return d({kind:"UniqueConstraintNode",columns:d(t.map(ue.create)),name:e?G.create(e):void 0,nullsNotDistinct:n})},cloneWith(t,e){return d({...t,...e})}}),ai=d({is(t){return t.kind==="DropConstraintNode"},create(t){return d({kind:"DropConstraintNode",constraintName:G.create(t)})},cloneWith(t,e){return d({...t,...e})}}),zn=d({is(t){return t.kind==="AlterColumnNode"},create(t,e,n){return d({kind:"AlterColumnNode",column:ue.create(t),[e]:n})}});class ih{#e;constructor(e){this.#e=e}setDataType(e){return new Kn(zn.create(this.#e,"dataType",hn(e)))}setDefault(e){return new Kn(zn.create(this.#e,"setDefault",nh(e)))}dropDefault(){return new Kn(zn.create(this.#e,"dropDefault",!0))}setNotNull(){return new Kn(zn.create(this.#e,"setNotNull",!0))}dropNotNull(){return new Kn(zn.create(this.#e,"dropNotNull",!0))}$call(e){return e(this)}}class Kn{#e;constructor(e){this.#e=e}toOperationNode(){return this.#e}}class xn{#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:si.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 Rn{#e;constructor(e){this.#e=d(e)}ifExists(){return new Rn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{dropConstraint:ai.cloneWith(this.#e.node.dropConstraint,{ifExists:!0})})})}cascade(){return new Rn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{dropConstraint:ai.cloneWith(this.#e.node.dropConstraint,{modifier:"cascade"})})})}restrict(){return new Rn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{dropConstraint:ai.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 Cn=d({is(t){return t.kind==="PrimaryKeyConstraintNode"},create(t,e){return d({kind:"PrimaryKeyConstraintNode",columns:d(t.map(ue.create)),name:e?G.create(e):void 0})},cloneWith(t,e){return d({...t,...e})}}),En=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 Zt{#e;constructor(e){this.#e=d(e)}unique(){return new Zt({...this.#e,node:H.cloneWithTableProps(this.#e.node,{addIndex:En.cloneWith(this.#e.node.addIndex,{unique:!0})})})}column(e){return new Zt({...this.#e,node:H.cloneWithTableProps(this.#e.node,{addIndex:En.cloneWithColumns(this.#e.node.addIndex,[Ni(e)])})})}columns(e){return new Zt({...this.#e,node:H.cloneWithTableProps(this.#e.node,{addIndex:En.cloneWithColumns(this.#e.node.addIndex,e.map(Ni))})})}expression(e){return new Zt({...this.#e,node:H.cloneWithTableProps(this.#e.node,{addIndex:En.cloneWithColumns(this.#e.node.addIndex,[e.toOperationNode()])})})}using(e){return new Zt({...this.#e,node:H.cloneWithTableProps(this.#e.node,{addIndex:En.cloneWith(this.#e.node.addIndex,{using:ce.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 Vt{#e;constructor(e){this.#e=e}nullsNotDistinct(){return new Vt(Gt.cloneWith(this.#e,{nullsNotDistinct:!0}))}deferrable(){return new Vt(Gt.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new Vt(Gt.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new Vt(Gt.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new Vt(Gt.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}}class nn{#e;constructor(e){this.#e=e}deferrable(){return new nn(Cn.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new nn(Cn.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new nn(Cn.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new nn(Cn.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}}class oh{#e;constructor(e){this.#e=e}$call(e){return e(this)}toOperationNode(){return this.#e}}const Lv=d({is(t){return t.kind==="RenameConstraintNode"},create(t,e){return d({kind:"RenameConstraintNode",oldName:G.create(t),newName:G.create(e)})}});class Pv{#e;constructor(e){this.#e=d(e)}renameTo(e){return new xn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{renameTo:de(e)})})}setSchema(e){return new xn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{setSchema:G.create(e)})})}alterColumn(e,n){const r=n(new ih(e));return new Qe({...this.#e,node:H.cloneWithColumnAlteration(this.#e.node,r.toOperationNode())})}dropColumn(e){return new Qe({...this.#e,node:H.cloneWithColumnAlteration(this.#e.node,eh.create(e))})}renameColumn(e,n){return new Qe({...this.#e,node:H.cloneWithColumnAlteration(this.#e.node,th.create(e,n))})}addColumn(e,n,r=Be){const i=r(new ee(ne.create(e,hn(n))));return new Qe({...this.#e,node:H.cloneWithColumnAlteration(this.#e.node,Xl.create(i.toOperationNode()))})}modifyColumn(e,n,r=Be){const i=r(new ee(ne.create(e,hn(n))));return new Qe({...this.#e,node:H.cloneWithColumnAlteration(this.#e.node,rh.create(i.toOperationNode()))})}addUniqueConstraint(e,n,r=Be){const i=r(new Vt(Gt.create(n,e)));return new xn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{addConstraint:si.create(i.toOperationNode())})})}addCheckConstraint(e,n,r=Be){const i=r(new oh(Qs.create(n.toOperationNode(),e)));return new xn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{addConstraint:si.create(i.toOperationNode())})})}addForeignKeyConstraint(e,n,r,i,o=Be){const s=o(new yt(Lt.create(n.map(ue.create),de(r),i.map(ue.create),e)));return new Pt({...this.#e,constraintBuilder:s})}addPrimaryKeyConstraint(e,n,r=Be){const i=r(new nn(Cn.create(n,e)));return new xn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{addConstraint:si.create(i.toOperationNode())})})}dropConstraint(e){return new Rn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{dropConstraint:ai.create(e)})})}renameConstraint(e,n){return new Rn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{renameConstraint:Lv.create(e,n)})})}addIndex(e){return new Zt({...this.#e,node:H.cloneWithTableProps(this.#e.node,{addIndex:En.create(e)})})}dropIndex(e){return new xn({...this.#e,node:H.cloneWithTableProps(this.#e.node,{dropIndex:Qn.create(e)})})}$call(e){return e(this)}}class Qe{#e;constructor(e){this.#e=d(e)}alterColumn(e,n){const r=n(new ih(e));return new Qe({...this.#e,node:H.cloneWithColumnAlteration(this.#e.node,r.toOperationNode())})}dropColumn(e){return new Qe({...this.#e,node:H.cloneWithColumnAlteration(this.#e.node,eh.create(e))})}renameColumn(e,n){return new Qe({...this.#e,node:H.cloneWithColumnAlteration(this.#e.node,th.create(e,n))})}addColumn(e,n,r=Be){const i=r(new ee(ne.create(e,hn(n))));return new Qe({...this.#e,node:H.cloneWithColumnAlteration(this.#e.node,Xl.create(i.toOperationNode()))})}modifyColumn(e,n,r=Be){const i=r(new ee(ne.create(e,hn(n))));return new Qe({...this.#e,node:H.cloneWithColumnAlteration(this.#e.node,rh.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 sh extends _l{transformPrimitiveValueList(e){return Ki.create(e.values.map(Ke.createImmediate))}transformValue(e){return Ke.createImmediate(e.value)}}class Ye{#e;constructor(e){this.#e=d(e)}ifNotExists(){return new Ye({...this.#e,node:pt.cloneWith(this.#e.node,{ifNotExists:!0})})}unique(){return new Ye({...this.#e,node:pt.cloneWith(this.#e.node,{unique:!0})})}nullsNotDistinct(){return new Ye({...this.#e,node:pt.cloneWith(this.#e.node,{nullsNotDistinct:!0})})}on(e){return new Ye({...this.#e,node:pt.cloneWith(this.#e.node,{table:de(e)})})}column(e){return new Ye({...this.#e,node:pt.cloneWithColumns(this.#e.node,[Ni(e)])})}columns(e){return new Ye({...this.#e,node:pt.cloneWithColumns(this.#e.node,e.map(Ni))})}expression(e){return new Ye({...this.#e,node:pt.cloneWithColumns(this.#e.node,[e.toOperationNode()])})}using(e){return new Ye({...this.#e,node:pt.cloneWith(this.#e.node,{using:ce.createWithSql(e)})})}where(...e){const n=new sh;return new Ye({...this.#e,node:R.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 Xs{#e;constructor(e){this.#e=d(e)}ifNotExists(){return new Xs({...this.#e,node:Al.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 $v(t){if(mx.includes(t))return t;throw new Error(`invalid OnCommitAction ${t}`)}class Le{#e;constructor(e){this.#e=d(e)}temporary(){return new Le({...this.#e,node:Me.cloneWith(this.#e.node,{temporary:!0})})}onCommit(e){return new Le({...this.#e,node:Me.cloneWith(this.#e.node,{onCommit:$v(e)})})}ifNotExists(){return new Le({...this.#e,node:Me.cloneWith(this.#e.node,{ifNotExists:!0})})}addColumn(e,n,r=Be){const i=r(new ee(ne.create(e,hn(n))));return new Le({...this.#e,node:Me.cloneWithColumn(this.#e.node,i.toOperationNode())})}addPrimaryKeyConstraint(e,n,r=Be){const i=r(new nn(Cn.create(n,e)));return new Le({...this.#e,node:Me.cloneWithConstraint(this.#e.node,i.toOperationNode())})}addUniqueConstraint(e,n,r=Be){const i=r(new Vt(Gt.create(n,e)));return new Le({...this.#e,node:Me.cloneWithConstraint(this.#e.node,i.toOperationNode())})}addCheckConstraint(e,n,r=Be){const i=r(new oh(Qs.create(n.toOperationNode(),e)));return new Le({...this.#e,node:Me.cloneWithConstraint(this.#e.node,i.toOperationNode())})}addForeignKeyConstraint(e,n,r,i,o=Be){const s=o(new yt(Lt.create(n.map(ue.create),de(r),i.map(ue.create),e)));return new Le({...this.#e,node:Me.cloneWithConstraint(this.#e.node,s.toOperationNode())})}modifyFront(e){return new Le({...this.#e,node:Me.cloneWithFrontModifier(this.#e.node,e.toOperationNode())})}modifyEnd(e){return new Le({...this.#e,node:Me.cloneWithEndModifier(this.#e.node,e.toOperationNode())})}as(e){return new Le({...this.#e,node:Me.cloneWith(this.#e.node,{selectQuery:mn(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:Qn.cloneWith(this.#e.node,{table:de(e)})})}ifExists(){return new sr({...this.#e,node:Qn.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new sr({...this.#e,node:Qn.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:zo.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new Ai({...this.#e,node:zo.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 Oi{#e;constructor(e){this.#e=d(e)}ifExists(){return new Oi({...this.#e,node:Ko.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new Oi({...this.#e,node:Ko.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:kt.create(t)})},cloneWith(t,e){return d({...t,...e})}});class Bv{#e=new sh;transformQuery(e){return this.#e.transformNode(e.node,e.queryId)}transformResult(e){return Promise.resolve(e.result)}}class Bt{#e;constructor(e){this.#e=d(e)}temporary(){return new Bt({...this.#e,node:$t.cloneWith(this.#e.node,{temporary:!0})})}materialized(){return new Bt({...this.#e,node:$t.cloneWith(this.#e.node,{materialized:!0})})}ifNotExists(){return new Bt({...this.#e,node:$t.cloneWith(this.#e.node,{ifNotExists:!0})})}orReplace(){return new Bt({...this.#e,node:$t.cloneWith(this.#e.node,{orReplace:!0})})}columns(e){return new Bt({...this.#e,node:$t.cloneWith(this.#e.node,{columns:e.map(Pl)})})}as(e){const n=e.withPlugin(new Bv).toOperationNode();return new Bt({...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 ci=d({is(t){return t.kind==="DropViewNode"},create(t){return d({kind:"DropViewNode",name:kt.create(t)})},cloneWith(t,e){return d({...t,...e})}});class ar{#e;constructor(e){this.#e=d(e)}materialized(){return new ar({...this.#e,node:ci.cloneWith(this.#e.node,{materialized:!0})})}ifExists(){return new ar({...this.#e,node:ci.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new ar({...this.#e,node:ci.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 ah=d({is(t){return t.kind==="CreateTypeNode"},create(t){return d({kind:"CreateTypeNode",name:t})},cloneWithEnum(t,e){return d({...t,enum:Ki.create(e.map(Ke.createImmediate))})}});class ea{#e;constructor(e){this.#e=d(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}asEnum(e){return new ea({...this.#e,node:ah.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 ch=d({is(t){return t.kind==="DropTypeNode"},create(t){return d({kind:"DropTypeNode",name:t})},cloneWith(t,e){return d({...t,...e})}});class ta{#e;constructor(e){this.#e=d(e)}ifExists(){return new ta({...this.#e,node:ch.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 Yc(t){if(t.includes(".")){const n=t.split(".").map(Uv);if(n.length===2)return kt.createWithSchema(n[0],n[1]);throw new Error(`invalid schemable identifier ${t}`)}else return kt.create(t)}function Uv(t){return t.trim()}const di=d({is(t){return t.kind==="RefreshMaterializedViewNode"},create(t){return d({kind:"RefreshMaterializedViewNode",name:kt.create(t)})},cloneWith(t,e){return d({...t,...e})}});class cr{#e;constructor(e){this.#e=d(e)}concurrently(){return new cr({...this.#e,node:di.cloneWith(this.#e.node,{concurrently:!0,withNoData:!1})})}withData(){return new cr({...this.#e,node:di.cloneWith(this.#e.node,{withNoData:!1})})}withNoData(){return new cr({...this.#e,node:di.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 dr{#e;constructor(e){this.#e=e}createTable(e){return new Le({queryId:j(),executor:this.#e,node:Me.create(de(e))})}dropTable(e){return new Oi({queryId:j(),executor:this.#e,node:Ko.create(de(e))})}createIndex(e){return new Ye({queryId:j(),executor:this.#e,node:pt.create(e)})}dropIndex(e){return new sr({queryId:j(),executor:this.#e,node:Qn.create(e)})}createSchema(e){return new Xs({queryId:j(),executor:this.#e,node:Al.create(e)})}dropSchema(e){return new Ai({queryId:j(),executor:this.#e,node:zo.create(e)})}alterTable(e){return new Pv({queryId:j(),executor:this.#e,node:H.create(de(e))})}createView(e){return new Bt({queryId:j(),executor:this.#e,node:$t.create(e)})}refreshMaterializedView(e){return new cr({queryId:j(),executor:this.#e,node:di.create(e)})}dropView(e){return new ar({queryId:j(),executor:this.#e,node:ci.create(e)})}createType(e){return new ea({queryId:j(),executor:this.#e,node:ah.create(Yc(e))})}dropType(e){return new ta({queryId:j(),executor:this.#e,node:ch.create(Yc(e))})}withPlugin(e){return new dr(this.#e.withPlugin(e))}withoutPlugins(){return new dr(this.#e.withoutPlugins())}withSchema(e){return new dr(this.#e.withPluginAtFront(new pn(e)))}}class qv{ref(e){return new Ex(e)}table(e){return new Tv(e)}}class Fv{#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 Yt extends Hl{#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 Yt(this.#e,this.#t,this.#n,[...this.plugins,...e])}withPlugin(e){return new Yt(this.#e,this.#t,this.#n,[...this.plugins,e])}withPluginAtFront(e){return new Yt(this.#e,this.#t,this.#n,[e,...this.plugins])}withConnectionProvider(e){return new Yt(this.#e,this.#t,e,[...this.plugins])}withoutPlugins(){return new Yt(this.#e,this.#t,this.#n,[])}}function Ro(){return typeof performance<"u"&&Ve(performance.now)?performance.now():Date.now()}class Vv{#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.#o()&&this.#s(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)}#o(){return this.#t.isLevelEnabled("query")||this.#t.isLevelEnabled("error")}#s(e){const n=e.executeQuery,r=e.streamQuery,i=this;e.executeQuery=async o=>{let s;const a=Ro();try{return await n.call(e,o)}catch(c){throw s=c,await i.#a(c,o,a),c}finally{s||await i.#d(o,a)}},e.streamQuery=async function*(o,s){let a;const c=Ro();try{for await(const u of r.call(e,o,s))yield u}catch(u){throw a=u,await i.#a(u,o,c),u}finally{a||await i.#d(o,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 Ro()-e}}const _v=()=>{};class na{#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 jv=["read only","read write"],Hv=["read uncommitted","read committed","repeatable read","serializable","snapshot"];function dh(t){if(t.accessMode&&!jv.includes(t.accessMode))throw new Error(`invalid transaction access mode ${t.accessMode}`);if(t.isolationLevel&&!Hv.includes(t.isolationLevel))throw new Error(`invalid transaction isolation level ${t.isolationLevel}`)}d(["query","error"]);class zv{#e;#t;constructor(e){Ve(e)?(this.#t=e,this.#e=d({query:!0,error:!0})):(this.#t=Kv,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 Kv(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 Jv(t){return He(t)&&Ve(t.compile)}Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");class rn extends qt{#e;constructor(e){let n,r;if(Gv(e))n={executor:e.executor},r={...e};else{const i=e.dialect,o=i.createDriver(),s=i.createQueryCompiler(),a=i.createAdapter(),c=new zv(e.log??[]),u=new Vv(o,c),h=new Fv(u),f=new Yt(s,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 dr(this.#e.executor)}get dynamic(){return new qv}get introspection(){return this.#e.dialect.createIntrospector(this.withoutPlugins())}case(e){return new Jl({node:ot.create(jt(e)?void 0:mn(e))})}get fn(){return Kl()}transaction(){return new Ti({...this.#e})}startTransaction(){return new Ri({...this.#e})}connection(){return new Zv({...this.#e})}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 pn(e))})}withTables(){return new rn({...this.#e})}async destroy(){await this.#e.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#e.executor}executeQuery(e,n){n!==void 0&&qn("Passing `queryId` in `db.executeQuery` is deprecated and will result in a compile-time error in the future.");const r=Jv(e)?e.compile():e;return this.getExecutor().executeQuery(r)}async[Symbol.asyncDispose](){await this.destroy()}}class on extends rn{#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 on({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new on({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new on({...this.#e,executor:this.#e.executor.withPluginAtFront(new pn(e))})}withTables(){return new on({...this.#e})}}function Gv(t){return He(t)&&He(t.config)&&He(t.driver)&&He(t.executor)&&He(t.dialect)}class Zv{#e;constructor(e){this.#e=d(e)}async execute(e){return this.#e.executor.provideConnection(async n=>{const r=this.#e.executor.withConnectionProvider(new na(n)),i=new rn({...this.#e,executor:r});return await e(i)})}}class Ti{#e;constructor(e){this.#e=d(e)}setAccessMode(e){return new Ti({...this.#e,accessMode:e})}setIsolationLevel(e){return new Ti({...this.#e,isolationLevel:e})}async execute(e){const{isolationLevel:n,accessMode:r,...i}=this.#e,o={isolationLevel:n,accessMode:r};return dh(o),this.#e.executor.provideConnection(async s=>{const a=this.#e.executor.withConnectionProvider(new na(s)),c=new on({...i,executor:a});let u=!1;try{await this.#e.driver.beginTransaction(s,o),u=!0;const h=await e(c);return await this.#e.driver.commitTransaction(s),h}catch(h){throw u&&await this.#e.driver.rollbackTransaction(s),h}})}}class Ri{#e;constructor(e){this.#e=d(e)}setAccessMode(e){return new Ri({...this.#e,accessMode:e})}setIsolationLevel(e){return new Ri({...this.#e,isolationLevel:e})}async execute(){const{isolationLevel:e,accessMode:n,...r}=this.#e,i={isolationLevel:e,accessMode:n};dh(i);const o=await jl(this.#e.executor);return await this.#e.driver.beginTransaction(o.connection,i),new wt({...r,connection:o,executor:this.#e.executor.withConnectionProvider(new na(o.connection))})}}class wt extends on{#e;#t;#n;constructor(e){const n={isCommitted:!1,isRolledBack:!1};e={...e,executor:new Ut(e.executor,n)};const{connection:r,...i}=e;super(i),this.#e=d(e),this.#n=n;const o=j();this.#t=s=>e.executor.compileQuery(s,o)}get isCommitted(){return this.#n.isCommitted}get isRolledBack(){return this.#n.isRolledBack}commit(){return Qt(this.#n),new Jn(async()=>{await this.#e.driver.commitTransaction(this.#e.connection.connection),this.#n.isCommitted=!0,this.#e.connection.release()})}rollback(){return Qt(this.#n),new Jn(async()=>{await this.#e.driver.rollbackTransaction(this.#e.connection.connection),this.#n.isRolledBack=!0,this.#e.connection.release()})}savepoint(e){return Qt(this.#n),new Jn(async()=>(await this.#e.driver.savepoint?.(this.#e.connection.connection,e,this.#t),new wt({...this.#e})))}rollbackToSavepoint(e){return Qt(this.#n),new Jn(async()=>(await this.#e.driver.rollbackToSavepoint?.(this.#e.connection.connection,e,this.#t),new wt({...this.#e})))}releaseSavepoint(e){return Qt(this.#n),new Jn(async()=>(await this.#e.driver.releaseSavepoint?.(this.#e.connection.connection,e,this.#t),new wt({...this.#e})))}withPlugin(e){return new wt({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new wt({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new wt({...this.#e,executor:this.#e.executor.withPluginAtFront(new pn(e))})}withTables(){return new wt({...this.#e})}}class Jn{#e;constructor(e){this.#e=e}async execute(){return await this.#e()}}function Qt(t){if(t.isCommitted)throw new Error("Transaction is already committed");if(t.isRolledBack)throw new Error("Transaction is already rolled back")}class Ut{#e;#t;constructor(e,n){e instanceof Ut?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 Qt(this.#t),this.#e.executeQuery(e)}stream(e,n){return Qt(this.#t),this.#e.stream(e,n)}withConnectionProvider(e){return new Ut(this.#e.withConnectionProvider(e),this.#t)}withPlugin(e){return new Ut(this.#e.withPlugin(e),this.#t)}withPlugins(e){return new Ut(this.#e.withPlugins(e),this.#t)}withPluginAtFront(e){return new Ut(this.#e.withPluginAtFront(e),this.#t)}withoutPlugins(){return new Ut(this.#e.withoutPlugins(),this.#t)}}class ur{#e;constructor(e){this.#e=d(e)}get expressionType(){}get isRawBuilder(){return!0}as(e){return new Yv(this,e)}$castTo(){return new ur({...this.#e})}$notNull(){return new ur(this.#e)}withPlugin(e){return new ur({...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():Ji;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 Wt(t){return new ur(t)}class Yv{#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 Ct.create(this.#e.toOperationNode(),Ae(this.#t)?this.#t.toOperationNode():G.create(this.#t))}}const In=Object.assign((t,...e)=>Wt({queryId:j(),rawNode:ce.create(t,e?.map(Qc)??[])}),{ref(t){return Wt({queryId:j(),rawNode:ce.createWithChild(St(t))})},val(t){return Wt({queryId:j(),rawNode:ce.createWithChild(he(t))})},value(t){return this.val(t)},table(t){return Wt({queryId:j(),rawNode:ce.createWithChild(de(t))})},id(...t){const e=new Array(t.length+1).fill(".");return e[0]="",e[e.length-1]="",Wt({queryId:j(),rawNode:ce.create(e,t.map(G.create))})},lit(t){return Wt({queryId:j(),rawNode:ce.createWithChild(Ke.createImmediate(t))})},literal(t){return this.lit(t)},raw(t){return Wt({queryId:j(),rawNode:ce.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]=Qc(t[i]),i!==t.length-1&&(n[2*i+1]=r);return Wt({queryId:j(),rawNode:ce.createWithChildren(n)})}});function Qc(t){return Ae(t)?t.toOperationNode():he(t)}class Qv{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 Xv=/'/g;class e1 extends Qv{#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&&!vt.is(this.parentNode)&&!we.is(this.parentNode)&&!Me.is(this.parentNode)&&!$t.is(this.parentNode)&&!zl.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&&!vt.is(this.parentNode)&&!ce.is(this.parentNode)&&!ln.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&&(qn("`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&&!vt.is(this.parentNode)&&!ce.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(!Ce(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(n1[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&&!vt.is(this.parentNode)&&!ce.is(this.parentNode)&&!ln.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 "),yi(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(t1[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 o of e)i+=o,o===n?i+=n:o===r&&(i+=r);return i}sanitizeStringLiteral(e){return e.replace(Xv,"''")}addParameter(e){this.#t.push(e)}appendImmediateValue(e){if(Ce(e))this.appendStringLiteral(e);else if(Hi(e)||yi(e)||Vs(e))this.append(e.toString());else if(Fs(e))this.append("null");else if(fx(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?Xc[n.modifier]-Xc[r.modifier]:1),d(e)}compileColumnAlterations(e){this.compileList(e)}announcesNewColumnDataType(){return!0}}const t1=d({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),Xc=d({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),n1=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"}),ei=d({raw(t,e=[]){return d({sql:t,query:ce.createWithSql(t),parameters:d(e),queryId:j()})}});class r1{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}}class i1{transformQuery(e){return e.node}async transformResult(e){return e.result}}const uh="kysely_migration",Qo="kysely_migration_lock",o1=!1,Io="migration_lock";d({__noMigrations__:!0});class ME{#e;constructor(e){this.#e=d(e)}async getMigrations(){const e=await this.#l(this.#r)?await this.#e.db.withPlugin(this.#o).selectFrom(this.#r).select(["name","timestamp"]).$narrowType().execute():[];return(await this.#w()).map(({name:r,...i})=>{const o=e.find(s=>s.name===r);return{name:r,migration:i,executedAt:o?new Date(o.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(He(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 o=r.indexOf(e),s=i.findIndex(a=>a.name===e);if(o!==-1)return{direction:"Down",step:r.length-o-1};if(s!==-1)return{direction:"Up",step:s+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.#s(),await this.#b(e)}catch(n){return n instanceof Wo?n.resultSet:{error:n}}}get#n(){return this.#e.migrationTableSchema}get#r(){return this.#e.migrationTableName??uh}get#i(){return this.#e.migrationLockTableName??Qo}get#c(){return this.#e.allowUnorderedMigrations??o1}get#o(){return this.#n?new pn(this.#n):new i1}async#s(){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.#o).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.#o).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.#o).insertInto(this.#i).values({id:Io,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.#o).selectFrom(this.#i).where("id","=",Io).select("id").executeTakeFirst()}async#b(e){const n=this.#e.db.getExecutor().adapter,r=d({lockTable:this.#e.migrationLockTableName??Qo,lockRowId:Io,lockTableSchema:this.#e.migrationTableSchema}),i=async o=>{try{await n.acquireMigrationLock(o,r);const s=await this.#y(o);if(s.migrations.length===0)return{results:[]};const{direction:a,step:c}=e(s);return c<=0?{results:[]}:a==="Down"?await this.#E(o,s,c):a==="Up"?await this.#D(o,s,c):{results:[]}}finally{await n.releaseMigrationLock(o,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.#w(),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:px(r),pendingMigrations:i})}#g(e,n){return e.filter(r=>!n.includes(r.name))}async#w(){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.#o).selectFrom(this.#r).select(["name","timestamp"]).$narrowType().execute(),r=this.#e.nameComparator||((i,o)=>i.localeCompare(o));return n.sort((i,o)=>i.timestamp===o.timestamp?r(i.name,o.name):new Date(i.timestamp).getTime()-new Date(o.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(s=>n.migrations.find(a=>a.name===s)),o=i.map(s=>({migrationName:s.name,direction:"Down",status:"NotExecuted"}));for(let s=0;s<o.length;++s){const a=i[s];try{a.down&&(await a.down(e),await e.withPlugin(this.#o).deleteFrom(this.#r).where("name","=",a.name).execute(),o[s]={migrationName:a.name,direction:"Down",status:"Success"})}catch(c){throw o[s]={migrationName:a.name,direction:"Down",status:"Error"},new Wo({error:c,results:o})}}return{results:o}}async#D(e,n,r){const o=n.pendingMigrations.slice(0,r).map(s=>({migrationName:s.name,direction:"Up",status:"NotExecuted"}));for(let s=0;s<o.length;s++){const a=n.pendingMigrations[s];try{await a.up(e),await e.withPlugin(this.#o).insertInto(this.#r).values({name:a.name,timestamp:new Date().toISOString()}).execute(),o[s]={migrationName:a.name,direction:"Up",status:"Success"}}catch(c){throw o[s]={migrationName:a.name,direction:"Up",status:"Error"},new Wo({error:c,results:o})}}return{results:o}}async#f(e){this.#e.db.getExecutor().adapter.supportsCreateIfNotExists&&(e=e.ifNotExists()),await e.execute()}}class Wo extends Error{#e;constructor(e){super(),this.#e=e}get resultSet(){return this.#e}}const s1=/"/g;class a1 extends e1{sanitizeIdentifier(e){return e.replace(s1,'""')}}class c1{#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","!=",uh).where("c.relname","!=",Qo));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(o=>o.name===r.table&&o.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 d1=BigInt("3853314791062309107");class u1 extends r1{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(e,n){await In`select pg_advisory_xact_lock(${In.lit(d1)})`.execute(e)}async releaseMigrationLock(e,n){}}var l1=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)}}},LE=class{constructor(t){this.pgLite=t}createAdapter(){return new u1}createDriver(){return new h1(this.pgLite)}createQueryCompiler(){return new a1}createIntrospector(t){return new c1(t)}},h1=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 l1(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(ei.raw(`start transaction isolation level ${e.isolationLevel}`)):await t.executeQuery(ei.raw("begin"))}async commitTransaction(t){await t.executeQuery(ei.raw("commit"))}async rollbackTransaction(t){await t.executeQuery(ei.raw("rollback"))}async destroy(){this.client=void 0}};const f1="https://www.renown.id",p1="eip155",m1="1";function PE(){const t=new URL(f1);t.searchParams.set("connect",window.ph?.did??""),t.searchParams.set("network",p1),t.searchParams.set("chain",m1);const e=new URL(window.location.pathname,window.location.origin);t.searchParams.set("returnUrl",e.toJSON()),window.open(t,"_self")?.focus()}async function $E(t,e,n,r){if(!(!n||!r||!e))try{vn("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 vn("authorized"),Oc(i),e.setGenerateJwtHandler(async s=>r.getBearerToken(s,i.address,!0,{expiresIn:10})),i;if(!t)return;const o=await n.login(t??"");o?(vn("authorized"),Oc(o),e.setGenerateJwtHandler(async s=>r.getBearerToken(s,o.address,!0,{expiresIn:10}))):vn("not-authorized")}catch(i){vn("not-authorized"),pe.error(i)}}async function BE(){const t=window.ph?.renown,e=window.ph?.legacyReactor;vn("initial"),await t?.logout(),e?.removeJwtHandler()}export{ad as $,Wg as A,gg as B,Qu as C,tx as D,Cl as E,Y2 as F,H2 as G,Zh as H,M2 as I,rE as J,rn as K,F1 as L,ME as M,wE as N,hE as O,LE as P,wf as Q,iE as R,nE as S,q2 as T,gE as U,oE as V,sd as W,aE as X,Y1 as Y,M1 as Z,Is as _,eE as a,X1 as a0,of as a1,R1 as a2,TE as a3,J1 as a4,q1 as a5,j1 as a6,K1 as a7,G1 as a8,bg as a9,lE as aA,id as aB,A1 as aC,O1 as aD,T1 as aE,tE as aF,D1 as aG,$2 as aH,ef as aI,V1 as aJ,C1 as aK,S1 as aL,k1 as aM,is as aN,xE as aO,U1 as aP,cl as aa,Cg as ab,$E as ac,Q1 as ad,SE as ae,CE as af,AE as ag,Z1 as ah,vE as ai,EE as aj,OE as ak,DE as al,Zu as am,x1 as an,H1 as ao,z1 as ap,O2 as aq,A2 as ar,Gu as as,kE as at,E1 as au,BE as av,PE as aw,W2 as ax,sE as ay,v1 as az,WE as b,Ts as c,dl as d,uE as e,ll as f,Xh as g,nl as h,pE as i,U2 as j,RE as k,fE as l,bE as m,yE as n,dE as o,I1 as p,IE as q,tb as r,Mg as s,_1 as t,mE as u,cE as v,P2 as w,In as x,NE as y,W1 as z};